/// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// import { OidcPrincipal as OidcPrincipal$1, AgentPrincipal as AgentPrincipal$1, GolemUserPrincipal as GolemUserPrincipal$1, AgentType as AgentType$1, PathSegment, HttpEndpointDetails, HttpMountDetails, AgentMethod as AgentMethod$1, Principal as Principal$1 } from 'golem:agent/common@2.0.0'; import * as golem_core_types_2_0_0 from 'golem:core/types@2.0.0'; import { Uuid as Uuid$1, AccountId as AccountId$1, ComponentId as ComponentId$1, EnvironmentId as EnvironmentId$1, Secret as Secret$1, QuotaToken as QuotaToken$1, SchemaValueStream, SchemaValueTree, PermissionCard as PermissionCard$1, TypeId, NumericRestrictions, MetadataEnvelope, TextRestrictions, BinaryRestrictions, PathSpec, UrlRestrictions, QuantitySpec, DiscriminatorRule, SecretSpec, QuotaTokenSpec, PermissionCardSpec, Datetime, QuantityValue, SchemaGraph as SchemaGraph$1, TypedSchemaValue as TypedSchemaValue$1, SchemaValueNode, PathDirection, PathKind, ToolRpcError as ToolRpcError$1, FieldDiscriminator, NumericBound, Role } from 'golem:core/types@2.0.0'; import { StringFilterComparator, FilterComparator, AgentStatus, AgentAnyFilter, OplogIndex, RevertAgentTarget, PromiseId, AgentId as AgentId$1, Snapshot as Snapshot$1 } from 'golem:api/host@1.5.0'; export { AgentAllFilter, AgentAnyFilter, AgentConfigVarsFilter, AgentCreatedAtFilter, AgentEnvFilter, AgentNameFilter, AgentPropertyFilter, AgentStatus, AgentStatusFilter, AgentVersionFilter, ComponentRevision, FilterComparator, GetPromiseResult, OplogIndex, PromiseId, RevertAgentTarget, StringFilterComparator, UpdateMode, completePromise, createPromise, forkAgent, getPromise, oplogCommit, revertAgent, trap, updateAgent } from 'golem:api/host@1.5.0'; import { Doc, Repetition, DuplicateKeyPolicy, FlagSpec, Quantifier, StreamSpec, Formatter, ErrorKind, CommandAnnotations, ToolError as ToolError$1, TypedSchemaValue as TypedSchemaValue$3, InvocationResult, Tool, Constraint, CommandNode, CommandBody } from 'golem:tool/common@0.1.0'; import { ByteStreamFailure, ByteStreamItem, ToolOutputWriter } from 'golem:tool/streams@0.1.0'; import { InvocationMetadata, Datetime as Datetime$1, ScheduledInvocationReceipt, CancellationToken, CancelableScheduledInvocationReceipt, PromiseId as PromiseId$1, RegisteredAgentType } from 'golem:agent/host@2.0.0'; export { CancellationToken } from 'golem:agent/host@2.0.0'; import { PermissionError as PermissionError$1 } from 'golem:permissions/types@0.1.0'; import { Duration as Duration$1, RetryPredicate, RetryPolicy, NamedRetryPolicy, PredicateValue } from 'golem:api/retry@1.5.0'; export { NamedRetryPolicy, PredicateValue, RetryPolicy, RetryPredicate, getRetryPolicies, getRetryPolicyByName, removeRetryPolicy, resolveRetryPolicy } from 'golem:api/retry@1.5.0'; import { DurableStreamErrorKind, DurableStreamAppendReceipt } from 'golem:agent/durable-streams@2.0.0'; export { DurableStreamAppendReceipt, DurableStreamErrorKind } from 'golem:agent/durable-streams@2.0.0'; import * as golem_api_oplog_1_5_0 from 'golem:api/oplog@1.5.0'; import { Datetime as Datetime$2, ComponentRevision, PluginInstallationDescription, LocalAgentConfigEntry, AgentId as AgentId$2, OplogIndex as OplogIndex$1, StartParameters, EndParameters, CancelledParameters, AgentInvocationStartedParameters, AgentInvocationFinishedParameters, Timestamp as Timestamp$1, ErrorParameters, JumpParameters, SetRetryPolicyParameters, PendingAgentInvocationParameters, PendingUpdateParameters, SuccessfulUpdateParameters, FailedUpdateParameters, GrowMemoryParameters, CreateResourceParameters, DropResourceParameters, LogParameters, ActivatePluginParameters, DeactivatePluginParameters, RevertParameters, CancelPendingInvocationParameters, BeginRemoteTransactionParameters, RemoteTransactionParameters, SnapshotParameters, SnapshotConfirmedParameters, EnvironmentId as EnvironmentId$2, AgentInitializationParameters, AgentInvocation, AgentInvocationOutputParameters, AgentInvocationResult, AgentMethodInvocationParameters, AgentResourceId, Attribute, AttributeValue, DurableStreamEventSummary, DurableStreamOutcome, ExternalSpanData, FallibleResultParameters, LoadSnapshotParameters, LocalSpanData, LogLevel, LogTraceContext, ManualUpdateParameters, OplogEntry, OplogErrorKind, OplogExternalPayload, OplogPayload, OplogRegion, ProcessOplogEntriesParameters, RawActivatePluginParameters, RawAgentInvocationFinishedParameters, RawAgentInvocationStartedParameters, RawBeginRemoteTransactionParameters, RawCancelledParameters, RawCompletionDeliveredParameters, RawCompletionDiscardedParameters, RawCreateParameters, RawCreateResourceParameters, RawDeactivatePluginParameters, RawDropResourceParameters, RawDurableStreamRecordParameters, RawEndParameters, RawErrorParameters, RawHostStreamFrameParameters, RawLocalAgentConfigEntry, RawOplogProcessorCheckpointParameters, RawPendingAgentInvocationParameters, RawPendingUpdateParameters, RawSnapshotBasedUpdate, RawSnapshotParameters, RawStartParameters, RawSuccessfulUpdateParameters, RawUpdateDescription, ResourceTypeId, SaveSnapshotResultParameters, SchemaValueTree as SchemaValueTree$1, SnapshotBasedUpdateParameters, SpanAttributes, SpanData, SpanFinished, SpanId, SpanKind, SpanLink, SpanOutcome, SpanStarted, TraceId, TypedSchemaValue as TypedSchemaValue$2, UpdateDescription, WorkerError, WrappedFunctionType } from 'golem:api/oplog@1.5.0'; import { Reservation as Reservation$1, FailedReservation } from 'golem:quota/types@1.5.0'; export { FailedReservation } from 'golem:quota/types@1.5.0'; import { DurableFunctionType } from 'golem:durability/durability@1.6.0'; import { toolMiddlewareGuest as toolMiddlewareGuest$1 } from 'agent-guest'; import * as WsClient from 'golem:websocket/client@1.5.0'; import { ByteStreamItem as ByteStreamItem$1, FutureInvokeResult, ToolRpc, RegisteredTool } from 'golem:tool/host@0.1.0'; /** * Rich UUID class that is structurally compatible with the WIT binding type * `{ highBits: bigint; lowBits: bigint }` from `golem:core/types@2.0.0`. */ declare class Uuid { readonly highBits: bigint; readonly lowBits: bigint; constructor(highBits: bigint, lowBits: bigint); /** * Formats the UUID as a standard hyphenated string. */ toString(): string; /** * Parses a UUID string. */ static parse(value: string): Uuid; /** * Generates a random UUID. */ static generate(): Uuid; /** * Wraps a raw WIT UUID object in a Uuid instance. * If the value is already a Uuid, it is returned directly. */ static from(value: Uuid$1): Uuid; } declare class ComponentId { readonly uuid: Uuid; constructor(uuid: Uuid); toString(): string; static from(value: ComponentId$1): ComponentId; } declare class AccountId { readonly uuid: Uuid; constructor(uuid: Uuid); toString(): string; static from(value: AccountId$1): AccountId; } declare class EnvironmentId { readonly uuid: Uuid; constructor(uuid: Uuid); toString(): string; static from(value: EnvironmentId$1): EnvironmentId; } declare const SECRET_INTERNAL: unique symbol; type SecretInternal = typeof SECRET_INTERNAL; declare class GuestSecretHandle { constructor(key: SecretInternal, raw: Secret$1, onTake?: () => void, tracked?: boolean); toJSON(): never; } declare const QUOTA_INTERNAL: unique symbol; /** The type of the {@link QUOTA_INTERNAL} capability key. */ type QuotaInternal = typeof QUOTA_INTERNAL; declare class GuestQuotaTokenHandle { constructor(key: QuotaInternal, raw: QuotaToken$1, tracked?: boolean); /** * Quota-token handles are unforgeable capabilities, not data: serializing one * (e.g. via `JSON.stringify`) is always an error. Transfer them only by * passing the owning `QuotaToken` through a WIT `schema-value-tree`. */ toJSON(): never; } type GuestSchemaValueStream = { kind: 'wrapped'; value: SchemaValueStream; } | { kind: 'native'; value: AsyncIterable; }; declare class GuestSchemaValueStreamHandle { #private; constructor(value: GuestSchemaValueStream); peek(): GuestSchemaValueStream | undefined; close(): Promise; take(): GuestSchemaValueStream | undefined; } declare const PERMISSION_CARD_INTERNAL: unique symbol; /** The type of the {@link PERMISSION_CARD_INTERNAL} capability key. */ type PermissionCardInternal = typeof PERMISSION_CARD_INTERNAL; /** Guest-side take-once carrier for an owned, opaque permission-card resource. */ declare class GuestPermissionCardHandle { constructor(key: PermissionCardInternal, raw: PermissionCard$1, tracked?: boolean, lifted?: boolean); toJSON(): never; } /** * Atomically build a schema value that may adopt owned capability handles. * Nested conversions share the outer journal, while a failed nested conversion * rolls back only the handles it adopted. */ declare function withCapabilityAdoptionTransaction(encode: () => T): T; /** A schema type node: a structural body plus its metadata envelope. */ interface SchemaType { readonly body: SchemaTypeBody; readonly metadata: MetadataEnvelope; } type SchemaTypeBody = { tag: 'ref'; id: TypeId; } | { tag: 'bool'; } | { tag: 's8'; restrictions?: NumericRestrictions; } | { tag: 's16'; restrictions?: NumericRestrictions; } | { tag: 's32'; restrictions?: NumericRestrictions; } | { tag: 's64'; restrictions?: NumericRestrictions; } | { tag: 'u8'; restrictions?: NumericRestrictions; } | { tag: 'u16'; restrictions?: NumericRestrictions; } | { tag: 'u32'; restrictions?: NumericRestrictions; } | { tag: 'u64'; restrictions?: NumericRestrictions; } | { tag: 'f32'; restrictions?: NumericRestrictions; } | { tag: 'f64'; restrictions?: NumericRestrictions; } | { tag: 'char'; } | { tag: 'string'; } | { tag: 'uuid'; } | { tag: 'record'; fields: NamedFieldType[]; } | { tag: 'variant'; cases: VariantCaseType[]; } | { tag: 'enum'; cases: string[]; } | { tag: 'flags'; names: string[]; } | { tag: 'tuple'; elements: SchemaType[]; } | { tag: 'list'; element: SchemaType; } | { tag: 'fixed-list'; element: SchemaType; length: number; } | { tag: 'map'; key: SchemaType; value: SchemaType; } | { tag: 'option'; element: SchemaType; } | { tag: 'result'; ok?: SchemaType; err?: SchemaType; } | { tag: 'text'; restrictions: TextRestrictions; } | { tag: 'binary'; restrictions: BinaryRestrictions; } | { tag: 'path'; spec: PathSpec; } | { tag: 'url'; restrictions: UrlRestrictions; } | { tag: 'datetime'; } | { tag: 'duration'; } | { tag: 'quantity'; spec: QuantitySpec; } | { tag: 'union'; branches: UnionBranch[]; } | { tag: 'secret'; spec: Omit; inner: SchemaType; } | { tag: 'quota-token'; spec: QuotaTokenSpec; } | { tag: 'permission-card'; spec: PermissionCardSpec; } | { tag: 'future'; element?: SchemaType; } | { tag: 'stream'; element?: SchemaType; }; interface NamedFieldType { name: string; body: SchemaType; metadata: MetadataEnvelope; } interface VariantCaseType { name: string; payload?: SchemaType; metadata: MetadataEnvelope; } interface UnionBranch { /** Logical branch name (carried in `union` values). */ tag: string; body: SchemaType; discriminator: DiscriminatorRule; metadata: MetadataEnvelope; } interface SchemaTypeDef { /** Optional human-readable qualified name (display only). */ readonly name?: string; readonly body: SchemaType; } /** * A self-contained schema graph: a registry of named definitions (keyed by * stable `type-id`) plus a root type. `ref` bodies reference entries in `defs`. */ interface SchemaGraph { readonly defs: ReadonlyMap; readonly root: SchemaType; } /** Compare canonical value shape while ignoring metadata and refinable restrictions. */ declare function schemaShapesMatch(left: SchemaGraph, right: SchemaGraph): boolean; /** Compare exact value semantics across graphs while ignoring refs, definition IDs, and metadata. */ declare function schemaGraphsEquivalent(left: SchemaGraph, right: SchemaGraph): boolean; declare function resolveShapeType(graph: SchemaGraph, type: SchemaType): SchemaTypeBody | undefined; type SchemaValue = { tag: 'bool'; value: boolean; } | { tag: 's8'; value: number; } | { tag: 's16'; value: number; } | { tag: 's32'; value: number; } | { tag: 's64'; value: bigint; } | { tag: 'u8'; value: number; } | { tag: 'u16'; value: number; } | { tag: 'u32'; value: number; } | { tag: 'u64'; value: bigint; } | { tag: 'f32'; value: number; } | { tag: 'f64'; value: number; } | { tag: 'char'; value: string; } | { tag: 'string'; value: string; } | { tag: 'uuid'; value: Uuid; } | { tag: 'record'; fields: SchemaValue[]; } | { tag: 'variant'; caseIndex: number; payload?: SchemaValue; } | { tag: 'enum'; caseIndex: number; } | { tag: 'flags'; flags: boolean[]; } | { tag: 'tuple'; elements: SchemaValue[]; } | { tag: 'list'; elements: SchemaValue[]; } | { tag: 'fixed-list'; elements: SchemaValue[]; } | { tag: 'map'; entries: SchemaMapEntry[]; } | { tag: 'option'; value?: SchemaValue; } | { tag: 'result'; result: SchemaResult; } | { tag: 'text'; text: string; language?: string; } | { tag: 'binary'; bytes: Uint8Array; mimeType?: string; } | { tag: 'path'; value: string; } | { tag: 'url'; value: string; } | { tag: 'datetime'; value: Datetime; } | { tag: 'duration'; nanoseconds: bigint; } | { tag: 'quantity'; value: QuantityValue; } | { tag: 'union'; unionTag: string; body: SchemaValue; } | { tag: 'secret'; handle: GuestSecretHandle; } | { tag: 'quota-token'; handle: GuestQuotaTokenHandle; } | { tag: 'stream'; handle: SchemaValueStreamHandle; } | { tag: 'permission-card'; handle: GuestPermissionCardHandle; }; interface SchemaMapEntry { key: SchemaValue; value: SchemaValue; } interface SchemaValueStreamHandle { peek(): GuestSchemaValueStream | undefined; take(): GuestSchemaValueStream | undefined; close(): Promise; } type SchemaResult = { tag: 'ok'; value?: SchemaValue; } | { tag: 'err'; value?: SchemaValue; }; interface TypedSchemaValue { graph: SchemaGraph; value: SchemaValue; } declare function emptyMetadata(): MetadataEnvelope; /** Wrap a body into a `SchemaType` node with empty metadata. */ declare function schemaType(body: SchemaTypeBody, metadata?: MetadataEnvelope): SchemaType; /** Compact constructors for schema types (anonymous unless wrapped in a def). */ declare const t: { ref: (id: TypeId) => SchemaType; bool: () => SchemaType; s8: (restrictions?: NumericRestrictions) => SchemaType; s16: (restrictions?: NumericRestrictions) => SchemaType; s32: (restrictions?: NumericRestrictions) => SchemaType; s64: (restrictions?: NumericRestrictions) => SchemaType; u8: (restrictions?: NumericRestrictions) => SchemaType; u16: (restrictions?: NumericRestrictions) => SchemaType; u32: (restrictions?: NumericRestrictions) => SchemaType; u64: (restrictions?: NumericRestrictions) => SchemaType; f32: (restrictions?: NumericRestrictions) => SchemaType; f64: (restrictions?: NumericRestrictions) => SchemaType; char: () => SchemaType; string: () => SchemaType; uuid: () => SchemaType; record: (fields: NamedFieldType[]) => SchemaType; variant: (cases: VariantCaseType[]) => SchemaType; enum: (cases: string[]) => SchemaType; flags: (names: string[]) => SchemaType; tuple: (elements: SchemaType[]) => SchemaType; list: (element: SchemaType) => SchemaType; fixedList: (element: SchemaType, length: number) => SchemaType; map: (key: SchemaType, value: SchemaType) => SchemaType; option: (element: SchemaType) => SchemaType; result: (ok?: SchemaType, err?: SchemaType) => SchemaType; path: (spec: PathSpec) => SchemaType; url: (restrictions: UrlRestrictions) => SchemaType; datetime: () => SchemaType; duration: () => SchemaType; quantity: (spec: QuantitySpec) => SchemaType; secret: (inner: SchemaType, spec?: Omit) => SchemaType; quotaToken: (spec: QuotaTokenSpec) => SchemaType; stream: (element?: SchemaType) => SchemaType; permissionCard: (spec: PermissionCardSpec) => SchemaType; }; /** Compact constructors for schema field/case helpers. */ declare function field(name: string, body: SchemaType, metadata?: MetadataEnvelope): NamedFieldType; declare function variantCase(name: string, payload?: SchemaType, metadata?: MetadataEnvelope): VariantCaseType; /** Compact constructors for schema values. */ declare const v: { bool: (value: boolean) => SchemaValue; s8: (value: number) => SchemaValue; s16: (value: number) => SchemaValue; s32: (value: number) => SchemaValue; s64: (value: bigint) => SchemaValue; u8: (value: number) => SchemaValue; u16: (value: number) => SchemaValue; u32: (value: number) => SchemaValue; u64: (value: bigint) => SchemaValue; f32: (value: number) => SchemaValue; f64: (value: number) => SchemaValue; char: (value: string) => SchemaValue; string: (value: string) => SchemaValue; uuid: (value: Uuid) => SchemaValue; record: (fields: SchemaValue[]) => SchemaValue; variant: (caseIndex: number, payload?: SchemaValue) => SchemaValue; enum: (caseIndex: number) => SchemaValue; flags: (flags: boolean[]) => SchemaValue; tuple: (elements: SchemaValue[]) => SchemaValue; list: (elements: SchemaValue[]) => SchemaValue; fixedList: (elements: SchemaValue[]) => SchemaValue; map: (entries: SchemaMapEntry[]) => SchemaValue; option: (value?: SchemaValue) => SchemaValue; ok: (value?: SchemaValue) => SchemaValue; err: (value?: SchemaValue) => SchemaValue; text: (text: string, language?: string) => SchemaValue; binary: (bytes: Uint8Array, mimeType?: string) => SchemaValue; path: (value: string) => SchemaValue; url: (value: string) => SchemaValue; datetime: (value: Datetime) => SchemaValue; duration: (nanoseconds: bigint) => SchemaValue; quantity: (value: QuantityValue) => SchemaValue; union: (unionTag: string, body: SchemaValue) => SchemaValue; secret: (handle: GuestSecretHandle) => SchemaValue; quotaToken: (handle: GuestQuotaTokenHandle) => SchemaValue; stream: (handle: SchemaValueStreamHandle) => SchemaValue; permissionCard: (handle: GuestPermissionCardHandle) => SchemaValue; }; /** Clone a schema value without duplicating affine capability handles. */ declare function cloneSchemaValue(value: SchemaValue): SchemaValue; /** * Deep structural equality that understands the value shapes used by the schema * model: bigint, Uint8Array, Map, arrays, and plain objects. Object keys whose * value is `undefined` are ignored, matching the WIT option lifting convention * (and Vitest's `toEqual`). */ declare function deepEqual(a: unknown, b: unknown, equivalent?: (a: unknown, b: unknown) => boolean): boolean; /** Structural equality for two schema types. */ declare function schemaTypeEquals(a: SchemaType, b: SchemaType): boolean; /** Structural equality for two schema values. */ declare function schemaValueEquals(a: SchemaValue, b: SchemaValue): boolean; declare function schemaGraphToWit(graph: SchemaGraph): SchemaGraph$1; /** Decode a Component Model carrier into the recursive SDK model. */ declare function schemaGraphFromWit(wit: SchemaGraph$1): SchemaGraph; declare function schemaValueToWit(value: SchemaValue): SchemaValueTree; declare function schemaValueFromWit(wit: SchemaValueTree): SchemaValue; declare function typedSchemaValueToWit(tv: TypedSchemaValue): TypedSchemaValue$1; declare function typedSchemaValueFromWit(wit: TypedSchemaValue$1): TypedSchemaValue; declare class SchemaFingerprintError extends Error { constructor(message: string); } /** Compute the BLAKE3-256 SchemaFingerprintV1 digest for a stream element schema closure. */ declare function schemaFingerprintV1(graph: SchemaGraph, element?: SchemaType): Uint8Array; /** * Represents a Golem agent, consisting of a component ID and the agent's string identifier. */ type AgentId = { componentId: ComponentId; agentId: string; }; /** * Metadata about an agent. */ type AgentMetadata = { agentId: AgentId; args: string[]; env: [string, string][]; config: [string, string][]; status: string; componentRevision: bigint; retryCount: bigint; environmentId: EnvironmentId; }; /** * Generates an idempotency key as a rich {@link Uuid}. */ declare function generateIdempotencyKey(): Uuid; /** * Get the component-id for a given component reference. * Returns undefined when no component with the specified reference exists. */ declare function resolveComponentId(componentReference: string): ComponentId | undefined; /** * Resolve an agent reference without checking that the concrete agent exists. * Returns `undefined` only when the component reference cannot be resolved. */ declare function resolveAgentId(componentReference: string, agentName: string): AgentId | undefined; /** * Resolve an agent reference and require the concrete agent to exist. * Returns `undefined` when either the component or the agent cannot be found. */ declare function resolveAgentIdStrict(componentReference: string, agentName: string): AgentId | undefined; /** * Get the current agent's metadata. * Requires view permission on the running agent. Stored env/config fields * are not filtered by the per-key permissions used for WASI reads. */ declare function getSelfMetadata(): AgentMetadata; /** * Get agent metadata. */ declare function getAgentMetadata(agentId: AgentId$1): AgentMetadata | undefined; /** * Agent enumeration with enriched metadata. */ declare class GetAgents { private readonly inner; constructor(componentId: ComponentId$1, filter: AgentAnyFilter | undefined, precise: boolean); getNext(): AgentMetadata[] | undefined; } /** * Immutable filter for {@link getAgents}. Build leaves with the static * constructors and compose them with `.and(...)` (intersection) / `.or(...)` * (union); {@link toRaw} compiles to the WIT `agent-any-filter`. * * @example * Filter.status('equal', 'idle').and(Filter.name('starts-with', 'worker-')) */ declare class Filter { private readonly node; private constructor(); /** Match by agent name. */ static name(comparator: StringFilterComparator, value: string): Filter; /** Match by agent status. */ static status(comparator: FilterComparator, value: AgentStatus): Filter; /** Match by component version. */ static version(comparator: FilterComparator, value: bigint): Filter; /** Match by creation time (epoch nanos). */ static createdAt(comparator: FilterComparator, value: bigint): Filter; /** Match by env-var key/value. */ static env(name: string, comparator: StringFilterComparator, value: string): Filter; /** Match by config-var key/value. */ static config(name: string, comparator: StringFilterComparator, value: string): Filter; private static leaf; /** Intersection — both must match. */ and(other: Filter): Filter; /** Union — either may match. */ or(other: Filter): Filter; /** Compile to the WIT `agent-any-filter` (disjunctive normal form: OR of ANDs). */ toRaw(): AgentAnyFilter; } /** * Enumerate a component's agents, optionally filtered. Lazily pages through the * host `get-agents` resource, yielding enriched {@link AgentMetadata}. Collect * with `[...getAgents(id, filter)]` or iterate directly. */ declare function getAgents(componentId: ComponentId, filter?: Filter | AgentAnyFilter, precise?: boolean): Generator; /** Builders for the `revert-agent` target (see {@link revertAgent}). */ declare const RevertTarget: { /** Revert to a specific oplog index (kept as the last retained entry). */ readonly toOplogIndex: (index: OplogIndex) => RevertAgentTarget; /** Revert the last N invocations. */ readonly lastInvocations: (n: number | bigint) => RevertAgentTarget; }; /** * Details about the fork result. */ type ForkDetails = { forkedPhantomId: Uuid; }; /** * Indicates which agent the code is running on after `fork`. */ type ForkResult = { tag: 'original'; val: ForkDetails; } | { tag: 'forked'; val: ForkDetails; }; /** * Forks the current agent. Returns enriched ForkResult with rich Uuid phantom IDs. */ declare function fork(): ForkResult; declare function awaitPromise(promiseId: PromiseId): Promise; /** * Awaits a Golem promise with abort support. When the signal is aborted, * the returned promise rejects, releasing the caller from waiting. * * **Note:** Aborting only cancels the local wait — the promise may still * be completed on the server side. */ declare function awaitAbortablePromise(promiseId: PromiseId, signal: AbortSignal): Promise; /** * Returns the raw string agent ID of the current agent. */ declare function getRawSelfAgentId(): ParsedAgentId; declare const DURATION_BRAND: unique symbol; declare const POLICY_BRAND: unique symbol; declare const NAMED_POLICY_BRAND: unique symbol; type PredicateNodeDef = { tag: 'pred-true'; } | { tag: 'pred-false'; } | { tag: 'prop-eq' | 'prop-neq' | 'prop-gt' | 'prop-gte' | 'prop-lt' | 'prop-lte'; property: string; value: PredicateValueInput; } | { tag: 'prop-exists'; property: string; } | { tag: 'prop-in'; property: string; values: readonly PredicateValueInput[]; } | { tag: 'prop-matches' | 'prop-starts-with' | 'prop-contains'; property: string; pattern: string; } | { tag: 'pred-and' | 'pred-or'; left: PredicateNodeDef; right: PredicateNodeDef; } | { tag: 'pred-not'; inner: PredicateNodeDef; }; type PredicateValueInput = string | boolean | bigint | number; type DurationInput = Duration | Duration$1 | bigint | number; type PolicyInput = Policy | RetryPolicy; type NamedPolicyInput = NamedPolicy | NamedRetryPolicy; /** * A validated retry duration helper backed by raw nanoseconds. */ declare class Duration { private readonly nanoseconds; readonly [DURATION_BRAND] = true; private constructor(); static nanoseconds(value: bigint | number): Duration; static microseconds(value: bigint | number): Duration; static milliseconds(value: bigint | number): Duration; static seconds(value: bigint | number): Duration; static minutes(value: bigint | number): Duration; static hours(value: bigint | number): Duration; static from(value: DurationInput): Duration; toRaw(): Duration$1; asNanoseconds(): bigint; } /** * Retry property keys and helpers that match the platform retry context vocabulary. */ declare class Props { static readonly verb = "verb"; static readonly nounUri = "noun-uri"; static readonly uriScheme = "uri-scheme"; static readonly uriHost = "uri-host"; static readonly uriPort = "uri-port"; static readonly uriPath = "uri-path"; static readonly statusCode = "status-code"; static readonly errorType = "error-type"; static readonly function = "function"; static readonly targetComponentId = "target-component-id"; static readonly targetAgentType = "target-agent-type"; static readonly dbType = "db-type"; static readonly trapType = "trap-type"; static entry(property: string, value: PredicateValueInput): [string, PredicateValue]; static entries(properties: Readonly>): [string, PredicateValue][]; } /** * Immutable predicate builder compiled to the flattened WIT retry-predicate format. */ declare class Predicate { private readonly node; private constructor(); static always(): Predicate; static never(): Predicate; static eq(property: string, value: PredicateValueInput): Predicate; static neq(property: string, value: PredicateValueInput): Predicate; static gt(property: string, value: PredicateValueInput): Predicate; static gte(property: string, value: PredicateValueInput): Predicate; static lt(property: string, value: PredicateValueInput): Predicate; static lte(property: string, value: PredicateValueInput): Predicate; static exists(property: string): Predicate; static oneOf(property: string, values: readonly PredicateValueInput[]): Predicate; static matchesGlob(property: string, pattern: string): Predicate; static startsWith(property: string, prefix: string): Predicate; static contains(property: string, substring: string): Predicate; and(other: Predicate): Predicate; or(other: Predicate): Predicate; not(): Predicate; toNode(): PredicateNodeDef; toRaw(): RetryPredicate; } /** * Immutable retry policy builder compiled to the flattened WIT retry-policy format. */ declare class Policy { private readonly node; readonly [POLICY_BRAND] = true; private constructor(); static immediate(): Policy; static never(): Policy; static periodic(delay: DurationInput): Policy; static exponential(baseDelay: DurationInput, factor: number): Policy; static fibonacci(first: DurationInput, second: DurationInput): Policy; maxRetries(maxRetries: number): Policy; within(limit: DurationInput): Policy; clamp(minDelay: DurationInput, maxDelay: DurationInput): Policy; addDelay(delay: DurationInput): Policy; withJitter(factor: number): Policy; onlyWhen(predicate: Predicate): Policy; andThen(other: Policy): Policy; union(other: Policy): Policy; intersect(other: Policy): Policy; toRaw(): RetryPolicy; } /** * Immutable named retry policy builder with sensible defaults for priority and predicate. */ declare class NamedPolicy { readonly name: string; private readonly policy; private readonly predicate; private readonly policyPriority; readonly [NAMED_POLICY_BRAND] = true; private constructor(); static named(name: string, policy: Policy): NamedPolicy; priority(priority: number): NamedPolicy; appliesWhen(predicate: Predicate): NamedPolicy; toRaw(): NamedRetryPolicy; } declare function toRawPredicateValue(value: PredicateValueInput, context?: string): PredicateValue; declare function toRawDuration(value: DurationInput, context?: string): Duration$1; declare function toRawPredicate(predicate: Predicate): RetryPredicate; declare function toRawPolicy(policy: PolicyInput): RetryPolicy; declare function toRawNamedPolicy(policy: NamedPolicyInput): NamedRetryPolicy; declare const prototype: { /** * Returns `true` if the result is successful, `false` otherwise * @example. * Result.ok(123).isOk() // true * @example * Result.err('error').isOk() // false */ readonly isOk: typeof isOk; /** * Returns `true` if the result is an error, `false` otherwise * @example * Result.err('error').isOk() // false * @example. * Result.ok(123).isOk() // true */ readonly isErr: typeof isErr; /** * Returns the successful value of the result or throws the error value. * This should be used when returning from a component function that expects to receive a result. * @example Returns the payload of a successful result. * Result.ok(123).unwrapForWit() // 123 * @example Throws the payload of a failed result. * Result.err('error').unwrapForWit() // throws 'error' */ readonly unwrapForWit: typeof unwrapForWit; /** * Returns `this.value` if `this` is a successful result, otherwise throws a TypeError. * @example Returns the payload of a successful result. * Result.ok(123).unwrap() // 123 * @example Throws a TypeError for a failed result. * Result.err('error').unwrap() // throws TypeError */ readonly unwrap: typeof unwrap; /** * * Returns `this.error` if `this` is a failed result, otherwise throws a TypeError. * @example Throw a TypeError for a successful result. * Result.ok(123).unwrapErr() // throws TypeError * @example Returns the payload of a failed result * Result.err('error').unwrap() // 'error' */ readonly unwrapErr: typeof unwrapErr; /** * Returns the payload of the result. * @example Returns the payload of a successful result. * Result.ok(123).toUnion() // 123 * @example Returns the payload of a failed result. * Result.err('error').toUnion() // 'error' */ readonly toUnion: typeof toUnion; /** * Return the result of applying one of the given functions to the payload. * @example * Result.ok(123).match((x) => x * 2, (x: string) => x + '!') // 246 * Result.err('error').match((x: number) => x * 2, (x) => x + '!') // 'error!' */ readonly match: typeof match; /** * Creates a Result value by modifying the payload of the successful result using the given function. * @example * Result.ok(123).map((x) => x * 2) // Result.ok(246) * Result.err('error').map((x: number) => x * 2) // Result.err('error') */ readonly map: typeof map; /** * Creates a Result value by modifying the payload of the failed result using the given function. * @example * Result.ok(123).mapError((x: string) => x + '!') // Result.ok(123) * Result.err('error').mapError((x) => x + '!') // Result.err('error!') */ readonly mapError: typeof mapError; /** * Calls the given function with the payload of the result and returns the result unchanged. */ readonly tap: typeof tap; /** * Maps the payload of the successful result and flattens the nested Result type. * @example * Result.ok(123).flatMap((x) => Result.ok(x * 2)) // Result.ok(246) * Result.ok(123).flatMap((x) => Result.err('error')) // Result.err('error') * Result.err('error').flatMap((x: number) => Result.ok(x * 2)) // Result.err('error') * Result.err('error').flatMap((x) => Result.err('failure')) // Result.err('error') */ readonly flatMap: typeof flatMap; /** * Flattens the nested Result type. * @example * Result.ok(Result.ok(123)).flatten() // Result.ok(123) * Result.ok(Result.err('error')).flatten() // Result.err('error') * Result.err('error').flatten() // Result.err('error') */ readonly flatten: typeof flatten; /** * Perform a safe cast of the error type to the given class. If the payload of the failed result is not instance of constructor, throws TypeError. * @example * const result: Result = Result.tryCatch(() => { * if (Math.random() >= 0) { * throw new Error('error') * } else { * return 123 * } * }).assertErrorInstanceOf(Error) */ readonly assertErrorInstanceOf: typeof assertErrorInstanceOf; }; /** Type representing success or failure. */ type Result = Result.Ok | Result.Err; declare namespace Result { /** * The type of a successful result. * @example * const success: Result.ok = Result.ok(123) */ type Ok = typeof prototype & { readonly tag: 'ok'; readonly val: T; }; /** * A failed result. * @example * const failure: Result.err = Result.err('error') */ type Err = typeof prototype & { readonly tag: 'err'; readonly val: E; }; /** * Create a successful result. */ function ok(value: T): Result.Ok; /** * Create an error result. */ function err(error: E): Err; /** * Create a result from a function that may throw an error. */ function tryCatch(f: () => T): Result; function fromNullish(value: null): Result.Err; function fromNullish(value: undefined): Result.Err; function fromNullish(value: null | undefined): Result.Err; function fromNullish(value: T): Result.Ok; function fromNullish(value: T | null): Result; function fromNullish(value: T | undefined): Result; function fromNullish(value: T | null | undefined): Result; function all(results: readonly Result.Ok[]): Result.Ok; function all(results: readonly Result[]): Result; } declare function isOk(this: Result): this is Result.Ok; declare function isErr(this: Result): this is Result.Err; declare function unwrapForWit(this: Result.Ok): T; declare function unwrapForWit(this: Result.Err): never; declare function unwrapForWit(this: Result): T; declare function unwrap(this: Result.Ok): T; declare function unwrap(this: Result.Err): never; declare function unwrap(this: Result): T; declare function unwrapErr(this: Result.Ok): never; declare function unwrapErr(this: Result.Err): E; declare function unwrapErr(this: Result): E; declare function toUnion(this: Result.Ok): T; declare function toUnion(this: Result.Err): E; declare function toUnion(this: Result): T | E; declare function match(this: Result.Ok, f: (value: T) => T2, g: (error: E) => E2): T2; declare function match(this: Result.Err, f: (value: T) => T2, g: (error: E) => E2): E2; declare function match(this: Result, f: (value: T) => T2, g: (error: E) => E2): T2 | E2; declare function map(this: Result.Ok, f: (value: T) => T2): Result.Ok; declare function map(this: Result.Err, f: (value: T) => T2): Result.Err; declare function map(this: Result, f: (value: T) => T2): Result; declare function mapError(this: Result.Ok, f: (error: E) => E2): Result.Ok; declare function mapError(this: Result.Err, f: (error: E) => E2): Result.Err; declare function mapError(this: Result, f: (error: E) => E2): Result; declare function tap(this: Result.Err, f: (error: E) => void): Result.Err; declare function tap(this: Result.Ok, f: (value: T) => void): Result.Ok; declare function tap(this: Result, f: (value: T) => void): Result; declare function flatMap(this: Result.Ok, f: (value: T) => Result.Ok): Result.Ok; declare function flatMap(this: Result.Ok, f: (value: T) => Result.Err): Result.Err; declare function flatMap(this: Result.Ok, f: (value: T) => Result): Result; declare function flatMap(this: Result.Err, f: (value: T) => Result<_T2, E2>): Result.Err; declare function flatMap(this: Result, f: (value: T) => Result.Ok): Result; declare function flatMap(this: Result, f: (value: T) => Result.Err): Result.Err; declare function flatMap(this: Result, f: (value: T) => Result): Result; declare function flatten(this: Result.Err): Result.Err; declare function flatten(this: Result.Ok>): Result.Err; declare function flatten(this: Result.Ok>): Result.Ok; declare function flatten(this: Result.Ok>): Result; declare function flatten(this: Result, E>): Result; declare function flatten(this: Result, E2>): Result.Err; declare function flatten(this: Result, E2>): Result; declare function assertErrorInstanceOf unknown>(this: Result.Ok, constructor: C): Result.Ok; declare function assertErrorInstanceOf unknown>(this: Result.Err, constructor: C): Result.Err>; declare function assertErrorInstanceOf unknown>(this: Result, constructor: C): Result>; /** * One grant pattern: `class(owner) @ recipient : verb : resource-id`. * * Plain data. A grant never carries authority by itself; derive inputs are * requests that the host validates against the parent card or the wallet. */ interface PatternGrant { readonly class: string; readonly owner: string; readonly recipient: string; readonly verb: string; readonly resourceId: string; } /** The four grant lists of a card's bound lattice. */ interface CardView { readonly lowerPositive: readonly PatternGrant[]; readonly lowerNegative: readonly PatternGrant[]; readonly upperPositive: readonly PatternGrant[]; readonly upperNegative: readonly PatternGrant[]; } /** * The four grant lists of a derive request. An omitted list is empty. * * For {@link PermissionCard.derive} the positive lists name the parent grants * to retain and the negative lists name the denials to add. For * {@link deriveFromWallet} and {@link deriveScope} they are the full requested * lists. */ interface Bounds { readonly lowerPositive?: readonly PatternGrant[]; readonly lowerNegative?: readonly PatternGrant[]; readonly upperPositive?: readonly PatternGrant[]; readonly upperNegative?: readonly PatternGrant[]; } /** An instant: seconds and nanoseconds since the Unix epoch (UTC). */ interface Timestamp { readonly seconds: bigint; readonly nanoseconds: number; } /** The caller's wallet version. It changes whenever the set of installed cards changes. */ interface WalletVersionToken { /** 32 bytes: BLAKE3 of (holder kind, holder id). */ readonly walletIdHash: Uint8Array; readonly generation: bigint; } /** A resource class registered in the permission kernel, with its verbs. */ interface KernelModule { readonly className: string; readonly verbs: readonly string[]; } /** * The lifespan of a derived card, as an ISO-8601 duration. * * The host accepts only the `PnDTnHnMnS` form (days, hours, minutes and * seconds; for example `"P1DT2H"` or `"PT30S"`) and rejects other values, * including year, month and week units, with `invalid-pattern`. */ declare class Lifespan { readonly iso8601: string; private constructor(); /** A lifespan from an ISO-8601 duration string such as `"PT1H"`. */ static iso8601(value: string): Lifespan; /** A lifespan from a positive SDK {@link Duration}. */ static of(duration: Duration): Lifespan; } declare const CARD_ID_INTERNAL: unique symbol; /** * An opaque permission-card identifier. * * Card IDs are host-private: a `CardId` has no public constructor and exposes * no UUID or string form. Printing or serializing one gives a redacted * placeholder. The SDK interns identifiers, so two `CardId` values for the same * card are the same object; compare them with `===` or {@link CardId.equals}, * and use them as `Map` / `Set` keys. */ declare class CardId { /** @internal */ constructor(key: typeof CARD_ID_INTERNAL, value: string); equals(other: CardId): boolean; toString(): string; toJSON(): string; } /** * The target of {@link PermissionCard.install}. * * The host currently installs cards only on agents; account and application * targets return `not-permitted`. */ declare class Holder { readonly tag: 'account' | 'app' | 'agent'; readonly val: Uuid | AgentId; private constructor(); static account(accountId: Uuid): Holder; static app(applicationId: Uuid): Holder; static agent(agentId: AgentId): Holder; } /** The case names of the WIT `permission-error` variant. */ type PermissionErrorKind = PermissionError$1['tag']; /** Every {@link PermissionErrorKind}, in WIT declaration order. */ declare const PERMISSION_ERROR_KINDS: readonly ["not-permitted", "lower-bound-too-broad", "upper-bound-too-broad", "wallet-multi-source-required", "card-revoked", "card-expired", "install-recipient-mismatch", "unknown-resource-class", "invalid-pattern", "invalid-verb", "invalid-owner", "invalid-recipient"]; /** An expected failure of a permission-card operation, reported by the host. */ declare class PermissionError extends Error { readonly kind: PermissionErrorKind; readonly details: string; readonly _tag = "PermissionError"; constructor(kind: PermissionErrorKind, details: string); } /** * The operations shared by {@link PermissionCard} and * {@link PolymorphicPermissionCard}. It is not part of the public API: use one * of the two card types. */ declare abstract class PersistentCard { /** @internal */ constructor(key: PermissionCardInternal, handle: GuestPermissionCardHandle); /** The card's identifier. */ id(): CardId; /** The identifiers of the card's parents in the derivation DAG. */ parents(): CardId[]; /** The card's expiry, or `undefined` when its lifespan is unbounded. */ expiresAt(): Timestamp | undefined; /** The card's grant lattice. Requires `card:inspect` authority over the card. */ inspect(): Result; /** * Derive a narrower child card. The positive lists of `bounds` name the * grants of this card to retain and the negative lists name the denials to * add. Requires `card:derive` authority over the card. The host labels the child * concrete or template. Child slots name the eventual holder and are universally * validated. A template parent must be in this agent's wallet, * where the host resolves it for this agent; otherwise the host returns * `not-permitted`. */ derive(bounds: Bounds, lifespan?: Lifespan): Result; /** * Revoke this card and every card derived from it, returning the number of * revoked cards. Moves the card, even when the host reports an error. */ revoke(): Result; /** * Install this card on `target`. Moves the card, even when the host reports * an error. Only agent targets are supported. */ install(target: Holder): Result; /** Drop this agent's handle to the card without revoking it. Moves the card. */ release(): void; /** `true` after the card was moved; every other operation then throws. */ isMoved(): boolean; toJSON(): never; } /** * An unforgeable concrete permission card held by this agent: every grant * names concrete owners and resources. * * Cards come only from the host: from {@link wallet}, a derive call, or an * agent method or RPC result. A card has no public constructor and cannot be * serialized. Sending a card to another agent, {@link PermissionCard.revoke}, * {@link PermissionCard.install} and {@link PermissionCard.release} move it; * every later use of a moved card throws. * * {@link PermissionCard.id}, {@link PermissionCard.parents} and * {@link PermissionCard.expiresAt} trap when the host no longer knows the card, * or when the card is revoked or expired. The other operations on such a card * return a `card-revoked` or `card-expired` {@link PermissionError}. * * In an agent or tool schema, declare it with * `s.permissionCard({ polymorphic: false })`. */ declare class PermissionCard extends PersistentCard { private readonly permissionCardBrand; } /** * An unforgeable template permission card held by this agent: its grants may * contain slot variables (`?agent`, `?env`, ...), which resolve for each * holder. * * It has the operations and the move rules of {@link PermissionCard}, and * {@link PolymorphicPermissionCard.derive} returns the host-labelled concrete or template child. A * template card is a `derive` or {@link deriveScope} parent only while it is in * this agent's wallet. The SDK has no conversion API between the two types * other than encoding and decoding through a schema: a decoded card takes the * type that the schema declares, and the host keeps the card's real kind. * * In an agent or tool schema, declare it with * `s.permissionCard({ polymorphic: true })`. */ declare class PolymorphicPermissionCard extends PersistentCard { private readonly polymorphicPermissionCardBrand; } /** * An invocation-local card from {@link deriveScope}, or the scope card lent to * the current invocation, listed by {@link wallet}. * * Attach a scope card to an awaited RPC call (the `scopeCard` call or client * option): the callee holds its authority until that invocation ends, and the * call borrows the card. A scope card is valid only during the invocation that * derived it; keeping it, or a client whose default is it, for a later * invocation makes awaited calls fail with `denied`. * * A scope card cannot be revoked, installed, used as the parent of a * persistent card, sent as an RPC argument or result, or serialized. It can be * a parent in another {@link deriveScope}. */ declare class ScopeCard { private readonly scopeCardBrand; /** @internal */ constructor(key: PermissionCardInternal, raw: PermissionCard$1); /** The scope card's identifier. */ id(): CardId; /** The identifiers of the scope card's root cards. */ parents(): CardId[]; /** * The earliest expiry of the root cards of this scope card, or `undefined` * when no root card expires. The scope card stops authorizing then. */ expiresAt(): Timestamp | undefined; /** The scope card's grant lattice. Requires `card:inspect` authority. */ inspect(): Result; /** Drop this agent's handle to the scope card. Every later use throws. */ release(): void; /** `true` after the scope card was released. */ isMoved(): boolean; toJSON(): never; } /** * A card in this agent's wallet, labelled with its kind. Switch on `tag`; the * card of each case has its own type. */ type WalletCard = /** A concrete card: every grant names concrete owners and resources. */ { readonly tag: 'concrete'; readonly card: PermissionCard; } /** A template card: its grants may contain slot variables, which resolve for each holder. */ | { readonly tag: 'template'; readonly card: PolymorphicPermissionCard; } /** The scope card lent to the current invocation. */ | { readonly tag: 'scope'; readonly card: ScopeCard; }; /** * The cards installed in this agent's wallet, each labelled with its kind. The * caller owns the returned cards; release the ones it does not keep. * * During an invocation that received a scope card, the host also lists that * scope card, as a `scope` entry, if the agent holds `card:inspect`. Like a * scope card from {@link deriveScope}, it is valid only during the current * invocation. */ declare function wallet(): WalletCard[]; /** This agent's wallet version. */ declare function walletVersion(): WalletVersionToken; /** * Derive a card from this agent's wallet. The lists of `bounds` are the full * requested lists. */ declare function deriveFromWallet(bounds: Bounds, lifespan?: Lifespan): Result; /** * Derive an invocation-local {@link ScopeCard} from one or more persistent or * scope parents. The parents are borrowed. The lists of `bounds` are the full * requested lists. Requested slots fail with `invalid-pattern`. */ declare function deriveScope(parents: readonly (PermissionCard | PolymorphicPermissionCard | ScopeCard)[], bounds: Bounds): Result; /** The resource classes and verbs registered in the permission kernel. */ declare function listModules(): KernelModule[]; /** Check that `grant` names a known class, owner, recipient, verb and resource-id pattern. */ declare function validateGrant(grant: PatternGrant): Result; type RemoteAgentError = { readonly tag: 'invalid-input'; readonly details: string; } | { readonly tag: 'invalid-method'; readonly details: string; } | { readonly tag: 'invalid-type'; readonly details: string; } | { readonly tag: 'invalid-agent-id'; readonly details: string; } | { readonly tag: 'custom-error'; readonly value: Value; }; type RemoteCallErrorCause = { readonly tag: 'protocol-error'; readonly details: string; } | { readonly tag: 'denied'; readonly details: string; } | { readonly tag: 'not-found'; readonly details: string; } | { readonly tag: 'remote-internal-error'; readonly details: string; } | { readonly tag: 'remote-agent-error'; readonly error: RemoteAgentError; }; declare class RemoteCallError extends Error { readonly _tag = "RemoteCallError"; readonly cause: RemoteCallErrorCause; constructor(context: string, cause: RemoteCallErrorCause); } declare function isRemoteCallError(error: unknown): error is RemoteCallError; declare class RemoteOutputError extends Error { readonly _tag = "RemoteOutputError"; constructor(message: string, options?: ErrorOptions); } interface RemoteInvocationResult { metadata: InvocationMetadata; value?: Value; } interface AgentConfigEntry { readonly path: readonly string[]; readonly value: TypedSchemaValue; } interface RemoteAgentHandle { readonly agentId: string; /** * Invoke `method` and await its result. A `scopeCard` is borrowed for the * call: the callee holds its authority until the invocation ends, and the * caller keeps the card. */ invokeAndAwait(method: string, params: Value, signal?: AbortSignal, scopeCard?: ScopeCard): Promise; invokeAndAwaitWithMetadata(method: string, params: Value, signal?: AbortSignal, scopeCard?: ScopeCard): Promise>; invoke(method: string, params: Value): void; invokeWithMetadata(method: string, params: Value): InvocationMetadata; schedule(at: Datetime$1, method: string, params: Value): void; scheduleWithMetadata(at: Datetime$1, method: string, params: Value): ScheduledInvocationReceipt; scheduleCancelable(at: Datetime$1, method: string, params: Value): CancellationToken; scheduleCancelableWithMetadata(at: Datetime$1, method: string, params: Value): CancelableScheduledInvocationReceipt; } /** Internal companion transport for prepared, capability-free invocation codecs. */ declare function wireRemoteAgent(remote: RemoteAgentHandle): RemoteAgentHandle | undefined; declare function resolveRemoteAgent(agentTypeName: string, constructorValue: SchemaValue, phantomId?: Uuid, configEntries?: readonly AgentConfigEntry[], mode?: 'durable' | 'ephemeral'): RemoteAgentHandle; declare function resolveRemoteAgentFallibly(agentTypeName: string, constructorValue: SchemaValue, phantomId?: Uuid, configEntries?: readonly AgentConfigEntry[], mode?: 'durable' | 'ephemeral'): RemoteAgentHandle; interface DynamicInvocation { readonly metadata: InvocationMetadata; readonly value?: T; } interface DynamicAgentClientSurface { readonly agentId: ParsedAgentId; method(name: string): DynamicAgentMethodSurface; } interface DynamicAgentMethodSurface { readonly name: string; /** Invoke and await. A `scopeCard` is borrowed for the call. */ invokeValue(input: SchemaValue, signal?: AbortSignal, scopeCard?: ScopeCard): Promise>; triggerValue(input: SchemaValue): InvocationMetadata; scheduleValue(at: Datetime$1, input: SchemaValue): CancelableScheduledInvocationReceipt; } declare class DynamicAgentClient implements DynamicAgentClientSurface { readonly agentId: ParsedAgentId; private readonly remote; constructor(agentId: ParsedAgentId); method(name: string): DynamicAgentMethod; } declare class DynamicAgentMethod implements DynamicAgentMethodSurface { readonly name: string; private readonly remote; constructor(name: string, remote: RemoteAgentHandle); invokeValue(input: SchemaValue, signal?: AbortSignal, scopeCard?: ScopeCard): Promise>; triggerValue(input: SchemaValue): InvocationMetadata; scheduleValue(at: Datetime$1, input: SchemaValue): CancelableScheduledInvocationReceipt; } /** @internal Protocol implemented by typed client definitions and reflected agent types. */ declare const bindAgentClient: "__golemBindAgentClient"; /** Options for a client bound to an existing agent identity. */ interface AgentClientBindOptions { /** The default scope card for every awaited call of the bound client. */ readonly scopeCard?: ScopeCard; } /** @internal A value that can bind itself to an existing agent identity. */ interface AgentClientBinding { [bindAgentClient](agentId: ParsedAgentId, config?: Config, options?: AgentClientBindOptions): Client; } /** Explicit parts used to construct a {@link ParsedAgentId}. */ interface ParsedAgentIdCreateOptions { readonly typeName: string; readonly constructorValue: SchemaValue; readonly phantomId?: Uuid; } /** Semantic parts of a {@link ParsedAgentId}. */ interface ParsedAgentIdParts { readonly typeName: string; readonly constructorValue: SchemaValue; readonly phantomId?: Uuid; } /** * Parsed environment-scoped agent identity string. * * A ParsedAgentId wraps the environment-scoped string representation of an agent ID and can parse it * into its constituent parts: agent type name, constructor parameters, and optional phantom ID. * * Constructor parameters are carried as the schema-native {@link SchemaValue} (the recursive * in-memory value); the embedded type graph the host returns is discarded because the SDK * re-derives parameter types from the agent's registered runtime metadata. */ declare class ParsedAgentId { readonly value: string; parsedCache: [string, SchemaValue, Uuid | undefined] | undefined; private wireCache; constructor(agentId: string); /** * Constructs a ParsedAgentId from an agent type name, constructor value, and optional phantom ID. * Prefer a definition's `agentId(...)` when a typed definition is available. */ static create(options: ParsedAgentIdCreateOptions): ParsedAgentId; /** * Returns the parsed agent ID. * @returns a tuple of the agent type name, parameters and an optional phantom ID */ parsed(): [string, SchemaValue, Uuid | undefined]; /** @internal Identity decoding for generated invocation and snapshot dispatch. */ parsedWire(): [string, SchemaValueTree, Uuid | undefined]; /** Return the semantic parts of this environment-scoped identity. */ parts(): ParsedAgentIdParts; /** * Bind a method-only, full, or reflected client to this identity. Config overrides apply only * if this creates the worker. `options.scopeCard` is the client's default scope card. */ client(binding: AgentClientBinding, config?: Config, options?: AgentClientBindOptions): Client; /** Invoke this identity with schema values and no discovery or typed client definition. */ dynamicClient(): DynamicAgentClientSurface; } declare class AgentClassName { readonly value: string; constructor(agentClassName: string); } type LanguageCode = string; /** * Represents unstructured text input, which can be either a URL or inline text. * * Example usage: * * ```ts * * function foo(input: UnstructuredText) {..} * * // With language codes * function bar(input: UnstructuredText<['en', 'de']>) {..} * * * foo(UnstructuredText.fromInline("hello")); * foo(UnstructuredText.fromUrl("http://.."')); * * bar(UnstructuredText.fromInline("hello", 'en')); // with language code * * ``` */ type UnstructuredText = { tag: 'url'; val: string; } | { tag: 'inline'; val: string; languageCode?: LC[number]; }; declare const UnstructuredText: { /** * Creates `UnstructuredText` from a URL. * * ```ts * function foo(input: UnstructuredText) {..} * * foo(UnstructuredText.fromUrl("hello")); * ``` * * @param urlValue A URL string * */ fromUrl(urlValue: string): UnstructuredText; /** * Creates `UnstructuredText` from inline text data. * * ```ts * function foo(input: UnstructuredText<['en', 'de']>) {..} * * foo(UnstructuredText.fromInline("hello", 'en')); * ``` * * If defining separately, please annotate the types to infer the types. * * ```ts * * const x: UnstructuredText<['en', 'de']> = UnstructuredText.fromInline("hello", 'en'); * * foo(x); * * ``` * * @param data * @param languageCode - The language code * @returns A `TextInput` object with `languageCode` set to `'en'`. */ fromInline(data: string, languageCode?: LC[number]): UnstructuredText; }; /** * Represents unstructured binary input, which can be either a URL or inline binary data. * * Example usage: * * ```ts * const inlineBinary: UnstructuredBinary<'application/json'> = * UnstructuredBinary.fromInline(Uint8Array([0x00, 0x01, 0x02]), "application/octet-stream"); * * const urlBinary: UnstructuredBinary = * UnstructuredBinary.fromUrl("https://example.com/file.bin"); *``` * * If no mime types are specified, any mime type is allowed. Note that * when using `inline` you always need to pass a mime-type as we don't allow * unstructured-binary without mime type. * * ```ts * function foo(input: UnstructuredBinary) {..} // any mime type allowed * function bar(input: UnstructuredBinary<['application/json', 'image/png']>) {..} // only application/json and image/png allowed * * const imageBinary: UnstructuredBinary = * UnstructuredBinary.fromInline(Uint8Array([0x00]), "image/jpeg"); * * const textBinary: UnstructuredBinary<'text/plain'> = * UnstructuredBinary.fromInline(Uint8Array([0x00]), "text/plain"); * * foo(imageBinary); // allowed * foo(textBinary); // allowed * * bar(imageBinary); // not allowed * * const appJsonBinary: UnstructuredBinary<'application/json'> = * UnstructuredBinary.fromInline(Uint8Array([0x00]), "application/json"); * * bar(appJsonBinary); // allowed * * ``` */ type MimeType = string; type UnstructuredBinary = { tag: 'url'; val: string; } | { tag: 'inline'; val: Uint8Array; mimeType: MT extends MimeType[] ? MT[number] : MimeType; }; declare const UnstructuredBinary: { /** * * Creates a `UnstructuredBinary` from a URL. * * Example usage: * * ```ts * * const urlBinary: UnstructuredBinary = * UnstructuredBinary.fromUrl("https://example.com/file.bin"); * * ``` * * @param urlValue */ fromUrl(urlValue: string): UnstructuredBinary; /** * Creates a `UnstructuredBinary` from inline binary data. * * Example usage: * * ```ts * * const inlineBinary: UnstructuredBinary<'application/json'> = * UnstructuredBinary.fromInline(Uint8Array([0x00, 0x01, 0x02]), "application/octet-stream"); * * ``` * * @param data * @param mimeType */ fromInline(data: Uint8Array, mimeType: MT extends MimeType[] ? MT[number] : MimeType): UnstructuredBinary; }; /** * Multimodal type represents a value that holds multiple types of inputs. * * Example: * * ```ts * * import { Multimodal } from '@golemcloud/golem-ts-sdk'; * * type Text = string; * type Image = Uint8Array; * * type Input = Multimodal; * * function processInput(input: Input) { } * * processInput(["text", new Uint8Array([137, 80, 78, 71])]); * * It is recommended to use tagged unions to distinguish between different types of inputs. * This will also ensure the internals of golem can name these inputs based on the value of the `tag` property. * * Example: * * ```ts * type TaggedInput = Multimodal<{ tag: 'text'; val: string } | { tag: 'image'; val: Uint8Array }>; * * processInput([{ tag: 'text', val: "hello" }, { tag: 'image', val: new Uint8Array([137, 80, 78, 71]) }]); * * ``` */ type MultimodalAdvanced = T[]; type Multimodal = MultimodalAdvanced; type MultimodalCustom = MultimodalAdvanced>; type BasicModality = { tag: 'text'; val: UnstructuredText; } | { tag: 'binary'; val: UnstructuredBinary; }; type CustomModality = { tag: 'text'; val: UnstructuredText; } | { tag: 'binary'; val: UnstructuredBinary; } | { tag: 'custom'; val: T; }; declare abstract class BasePrincipal { private readonly _brand; abstract readonly tag: 'oidc' | 'agent' | 'golem-user' | 'anonymous'; } declare class OidcPrincipal extends BasePrincipal { readonly inner: OidcPrincipal$1; readonly tag: "oidc"; readonly val: OidcPrincipal$1; constructor(inner: OidcPrincipal$1); get sub(): string; get issuer(): string; get email(): string | undefined; get name(): string | undefined; get emailVerified(): boolean | undefined; get givenName(): string | undefined; get familyName(): string | undefined; get picture(): string | undefined; get preferredUsername(): string | undefined; get claims(): string; } declare class AgentPrincipal extends BasePrincipal { readonly inner: AgentPrincipal$1; readonly tag: "agent"; readonly val: AgentPrincipal$1; constructor(inner: AgentPrincipal$1); get agentId(): golem_core_types_2_0_0.AgentId; } declare class GolemUserPrincipal extends BasePrincipal { readonly inner: GolemUserPrincipal$1; readonly tag: "golem-user"; readonly val: GolemUserPrincipal$1; constructor(inner: GolemUserPrincipal$1); get accountId(): golem_core_types_2_0_0.AccountId; } declare class AnonymousPrincipal extends BasePrincipal { readonly tag: "anonymous"; } type Principal = OidcPrincipal | AgentPrincipal | GolemUserPrincipal | AnonymousPrincipal; /** * Singleton registry for agent types. */ declare class AgentTypeRegistryImpl { private readonly registry; private readonly classNameCache; private readonly registrationErrors; private readonly registrationsInProgress; private cachedAgents; constructor(); register(agentClassName: AgentClassName, agentType: AgentType$1): void; beginRegistration(agentClassName: AgentClassName): void; completeRegistration(agentClassName: AgentClassName, agentType: AgentType$1): void; getRegisteredAgents(): AgentType$1[]; get(agentClassName: AgentClassName): AgentType$1 | undefined; exists(agentClassName: AgentClassName): boolean; recordRegistrationError(agentTypeName: string, message: string): void; getRegistrationError(agentTypeName: string): readonly string[] | undefined; getRegistrationErrors(): ReadonlyArray<{ agentTypeName: string; messages: readonly string[]; }>; } declare const AgentTypeRegistry: AgentTypeRegistryImpl; type SecretHandleProvider = (use: (handle: Secret$1) => R) => R; /** * A lazy, log-safe handle over a `secret` config field. Obtained from * `this.config.` (and `InitContext.config.`) for any field * declared with `s.secret(inner)`. * * - {@link get} performs the host read + reveal + decode fresh on every call, so * it always reflects the current value; cache the result yourself if you need * a stable snapshot within a single operation. * - {@link toJSON} throws, so `JSON.stringify(this.config)` (or a stray log of * the whole config object) can never leak the plaintext. */ declare class Secret { private readonly read; constructor(read: () => T, withHandle?: SecretHandleProvider); /** * Reveal and decode the current plaintext value. * * The host returns an opaque secret handle for a `secret` field; this * reveals it (capability-gated via `golem:secrets/reveal`) against the inner * type graph and decodes the resulting value tree with the inner codec. * * Only resolves inside the Golem guest (the host bindings are unavailable in * plain Node), so it is exercised at invocation time, never at import time. */ get(): T; /** Refuse serialization so secrets never leak through logs / JSON / snapshots. */ toJSON(): never; } interface StandardSchemaV1 { readonly '~standard': StandardSchemaV1.Props; } declare namespace StandardSchemaV1 { interface Props { readonly version: 1; readonly vendor: string; readonly validate: (value: unknown) => Result | Promise>; readonly types?: Types | undefined; } type Result = SuccessResult | FailureResult; interface SuccessResult { readonly value: Output; readonly issues?: undefined; } interface FailureResult { readonly issues: ReadonlyArray; } interface Issue { readonly message: string; readonly path?: ReadonlyArray | undefined; } interface PathSegment { readonly key: PropertyKey; } interface Types { readonly input: Input; readonly output: Output; } type InferInput = NonNullable['input']; type InferOutput = NonNullable['output']; } /** * A stable schema graph paired with deterministic value conversions. Codecs are * immutable once compiled: conversions must not mutate the codec, its graph, or * any codec reachable through structural child links. */ interface SchemaCodec { /** Immutable root SchemaType and the nominal definitions it references. */ readonly graph: SchemaGraph; readonly toValue: (value: unknown) => SchemaValue; readonly fromValue: (value: SchemaValue) => unknown; /** Direct flat-wire conversion. Absent when this codec can contain owned resources. */ readonly direct?: DirectSchemaCodec; /** Structural invocation conversion, with the ordinary leaf codec semantics. */ readonly invocationDirect?: DirectSchemaCodec; /** Source validator retained for metadata literals whose constraints are not representable in WIT. */ readonly sourceSchema?: StandardSchemaV1; /** * True for the unit/void type: the method's `returns` maps to WIT * `output-schema.unit`, so `graph` is a placeholder and is never encoded. */ readonly isUnit?: boolean; /** * For OBJECT codecs (a WIT `record` with named fields, e.g. `z.object({...})`): * the per-field child codecs, in declaration order. Set by the vendor object * walkers so the config surface can flatten nested config to leaf fields * (each fetched by its full multi-segment path). Absent for non-object codecs * (including `z.record(k, v)` maps, which are read whole). */ readonly fields?: ReadonlyArray<{ readonly name: string; readonly codec: SchemaCodec; }>; /** JavaScript absence convention for a codec whose root is a WIT `option`. */ readonly optionKind?: 'optional' | 'nullable' | 'nullish'; /** * For an OPTIONAL object group (`z.object({...}).optional()`): the codec's own * `graph` round-trips as `option`, but {@link fields} is ALSO exposed * (mirrored from the inner object) so the config surface can DESCEND the group * into per-leaf declarations. This flag tells the config surface that the * descended group is optional — its leaves are declared to the host as * `option` (so an unset leaf reads as option-none instead of trapping) * and its runtime presence is decided by its REQUIRED children. Absent for a * plain (non-optional) object group. */ readonly optionalGroup?: boolean; /** Inner codec for a WIT `option`, preserving the source-schema convention. */ readonly optionInner?: SchemaCodec; /** Item codec for a WIT `list` or `fixed-list`. */ readonly listItem?: SchemaCodec; /** Concrete typed-array constructor for a WIT list marker. */ readonly typedArrayConstructor?: { new (length: number): unknown; readonly name: string; }; /** Item codec for a typed schema-value stream. */ readonly streamItem?: SchemaCodec; /** Child codecs for a WIT `map`, when the source schema exposes them. */ readonly mapKey?: SchemaCodec; readonly mapValue?: SchemaCodec; readonly mapKind?: 'record' | 'map'; readonly tupleItems?: readonly SchemaCodec[]; /** Arms for a WIT result. */ readonly resultOk?: SchemaCodec; readonly resultErr?: SchemaCodec; /** * For SECRET markers (`s.secret(inner)`): the inner (revealed-value) codec — * the one that decodes the plaintext after `golem:secrets/reveal`. The * marker's own `graph` is `secret` and its own `fromValue` yields the * raw handle; the config surface uses this inner codec to decode a revealed * secret leaf. */ readonly secretInner?: SchemaCodec; /** * For the PRINCIPAL marker (`s.principal()`): the auto-injection kind. When a * method/constructor takes a bare `s.principal()` parameter, the caller does * NOT supply it — the host injects the caller's `Principal` (WIT * `field-source.auto-injected(principal)`). The runtime uses this to emit the * `auto-injected` source, decode the param from the separate invoke `principal` * arg (consuming no wire field), and exclude it from HTTP/RPC caller inputs. * A principal NESTED inside a record/return is ordinary user-supplied data and * is unaffected (only a top-level parameter codec is auto-injected). */ readonly autoInjected?: 'principal'; } /** Shared flat-value arena used while directly encoding child codecs. */ declare class SchemaValueWriter { readonly valueNodes: SchemaValueNode[]; readonly resources: Set; add(node: SchemaValueNode): number; /** Generated guest codecs retain ordinary scalar representability checks. */ scalar(tag: 'bool' | 's8' | 's16' | 's32' | 's64' | 'u8' | 'u16' | 'u32' | 'u64' | 'f32' | 'f64' | 'char' | 'string', value: unknown): number; } /** Shared flat-value arena used while directly decoding child codecs. */ declare class SchemaValueReader { readonly valueNodes: readonly SchemaValueNode[]; private readonly invocation; private readonly active; private readonly read; constructor(valueNodes: readonly SchemaValueNode[], invocation?: boolean); node(index: number | undefined, tag: SchemaValueNode['tag'], decode: (node: SchemaValueNode) => T): T; finish(): void; } interface DirectSchemaCodec { write(value: unknown, writer: SchemaValueWriter): number | undefined; read(reader: SchemaValueReader, index: number | undefined): unknown; } /** * A per-vendor schema walker. Given a schema (a Standard Schema value of a known * vendor) and a `recurse` callback for child schemas, it produces a `SchemaCodec`. * Only the walker is vendor-specific; `SchemaCodec` is vendor-neutral. */ type SchemaWalker = (schema: unknown, recurse: (child: unknown) => SchemaCodec) => SchemaCodec; /** * A demand-driven, single-reader stream for values nested anywhere in an agent method input or * output. * * Reading is lazy and non-concurrent: wait for each operation before starting another. Normal * completion returns `{ done: true, value: undefined }`. Encoding or forwarding an `AgentStream` * transfers its ownership; the original object cannot be used again. * * For a stream received through a connected P3 agent invocation, calling `return()`, including the * call made by an early exit from `for await`, closes its readable endpoint. Calling `throw()` also * closes it and rejects with the same local reason; the reason is not transmitted to the producer. * * When a stream created with {@link AgentStream.from} is sent through a connected P3 invocation, * each accepted downstream write gates the next source pull. If a subsequent write observes that * the remote reader was dropped, the runtime stops pulling and invokes and awaits the source * iterator's `return()` exactly once. P3 does not interrupt an arbitrary pending source `next()` or * guarantee cleanup before a later agent invocation. A source or cleanup rejection fails the * active producer, write, or invocation session rather than appearing as clean EOF. P3 streams do * not carry a recoverable terminal error; use an item type such as `Result` when errors must * be represented in the stream contract. */ declare class AgentStream implements AsyncIterable, AsyncIterator { private constructor(); /** * Create a stream from a synchronous or asynchronous iterable without pulling it eagerly. * * The source iterator's `return()` is used for cleanup when either the local stream is closed or * a connected remote reader is dropped. */ static from(source: Iterable | AsyncIterable): AgentStream; [Symbol.asyncIterator](): AsyncIterator; /** Read the next item, or `{ done: true, value: undefined }` after clean completion. */ next(): Promise>; /** * Close the stream and its underlying iterator. `for await` invokes this automatically on an * early `break` or `return`. */ return(value?: unknown): Promise>; /** * Fail local iteration and close a connected readable endpoint. * * Connected P3 streams reject with the same local reason, but do not transfer that reason to the * producer. Streams created with {@link AgentStream.from} delegate to the source iterator's * `throw()` when it provides one, but the `AgentStream` is consumed regardless of its result. */ throw(error?: unknown): Promise>; } /** @internal Move an AgentStream into a recursive schema value. */ declare function agentStreamToHandle(stream: AgentStream, itemCodec: SchemaCodec): GuestSchemaValueStreamHandle; /** @internal Lift a recursive schema-value-stream handle into an AgentStream. */ declare function agentStreamFromHandle(handle: Pick, itemCodec: SchemaCodec): AgentStream; /** A sanitized protocol failure. Native stream forwarding treats this as producer failure, not EOF. */ declare class DurableStreamError extends Error { readonly kind: DurableStreamErrorKind; readonly retryAfterMs?: bigint | undefined; readonly producerEpoch?: bigint | undefined; readonly expectedSequence?: bigint | undefined; readonly name = "DurableStreamError"; constructor(kind: DurableStreamErrorKind, message: string, retryAfterMs?: bigint | undefined, producerEpoch?: bigint | undefined, expectedSequence?: bigint | undefined); } interface DurableStreamOptions { readonly url: string; /** Borrowed capability; the SDK never reveals the bearer token. */ readonly auth?: Secret; /** Whole HTTP attempt deadline, 1–300000 ms. Default: 30000. */ readonly timeoutMs?: number; /** Automatic retries per batch operation, not counting the first attempt. Default: 8. */ readonly maxRetries?: number; /** Initial exponential retry delay. Default: 100 ms; capped at 30000 ms. */ readonly retryDelayMs?: number; } interface DurableStreamReadOptions extends DurableStreamOptions { /** Opaque server offset. Default: -1. `now` is resolved once via catch-up. */ readonly offset?: string; readonly cursor?: string; /** Live transport after catch-up. Default: long-poll. */ readonly live?: 'long-poll' | 'sse'; /** Durable delay after an empty live response. Default: 100 ms. */ readonly idleDelayMs?: number; } interface DurableStreamWriteOptions extends DurableStreamOptions { /** Generated once with the runtime's durable crypto.randomUUID() when omitted. */ readonly producerId?: string; /** Nonnegative protocol integer, at most 2^53-1. Default: 0. A new epoch starts at sequence 0. */ readonly epoch?: bigint; readonly contentType?: string; } /** * Optional exact application conversion. Each callback receives/returns one complete JSON value, * never the protocol's outer array. Callbacks must be synchronous and deterministic. The schema * still validates the resulting application value. Supply these for unquoted 64-bit integers; * the default canonical JSON codec rejects integers outside JavaScript's safe-number range. */ interface DurableStreamJsonCodec { readonly decode?: (json: string) => T; readonly encode?: (value: T) => string; } interface DurableStreamWriter { readonly producerId: string; readonly epoch: bigint; readonly nextSequence: bigint; /** Appends data, optionally closing atomically. Empty data requires close=true. */ append(data: T, options?: { readonly close?: boolean; }): Promise; /** Close-only also consumes a sequence. */ close(): Promise; /** Resolve the retained uncertain request without assigning another sequence. */ retryPending(): Promise; /** Resolve pending data, then release the local handle without closing the remote stream. */ dispose(): Promise; } /** Read JSON messages lazily as an ordinary affine AgentStream. */ declare function readDurableJsonStream(schema: StandardSchemaV1, options: DurableStreamReadOptions & Pick, 'decode'>): AgentStream; /** Read bytes, not append chunks: suitable for s.stream(s.u8()). */ declare function readDurableByteStream(options: DurableStreamReadOptions): AgentStream; /** Write a batch of logical JSON messages; an array-valued message remains one message. */ declare function createDurableJsonWriter(schema: StandardSchemaV1, options: DurableStreamWriteOptions & Pick, 'encode'>): DurableStreamWriter; /** Write exact bytes. Remote readers cannot recover these append boundaries. */ declare function createDurableByteWriter(options: DurableStreamWriteOptions): DurableStreamWriter; declare function createWebhook(): WebhookHandler; declare class WebhookHandler implements PromiseLike { private readonly url; private readonly promiseId; constructor(url: string, promiseId: PromiseId$1); getUrl(): string; private wait; then(onfulfilled?: ((value: WebhookRequestPayload) => TResult1 | PromiseLike) | null, onrejected?: ((_reason: unknown) => TResult2 | PromiseLike) | null): Promise; } declare class WebhookRequestPayload { private readonly payload; constructor(payload: Uint8Array); json(): T; bytes(): Uint8Array; } type EnvironmentPluginGrantId = { uuid: Uuid; }; type CreateParameters = { timestamp: Datetime$2; agentId: AgentId; componentRevision: ComponentRevision; env: [string, string][]; createdBy: AccountId; environmentId: EnvironmentId; parent?: AgentId; componentSize: bigint; initialTotalLinearMemorySize: bigint; initialActivePlugins: PluginInstallationDescription[]; localAgentConfig: LocalAgentConfigEntry[]; }; type OplogProcessorCheckpointParameters = { timestamp: Datetime$2; plugin: PluginInstallationDescription; targetAgentId: AgentId; confirmedUpTo: OplogIndex$1; sendingUpTo: OplogIndex$1; lastBatchStart: OplogIndex$1; }; type PublicOplogEntry = { tag: 'create'; val: CreateParameters; } | { tag: 'start'; val: StartParameters; } | { tag: 'end'; val: EndParameters; } | { tag: 'cancelled'; val: CancelledParameters; } | { tag: 'agent-invocation-started'; val: AgentInvocationStartedParameters; } | { tag: 'agent-invocation-finished'; val: AgentInvocationFinishedParameters; } | { tag: 'suspend'; val: Timestamp$1; } | { tag: 'error'; val: ErrorParameters; } | { tag: 'recovery-succeeded'; val: Timestamp$1; } | { tag: 'jump'; val: JumpParameters; } | { tag: 'interrupted'; val: Timestamp$1; } | { tag: 'exited'; val: Timestamp$1; } | { tag: 'set-retry-policy'; val: SetRetryPolicyParameters; } | { tag: 'pending-agent-invocation'; val: PendingAgentInvocationParameters; } | { tag: 'pending-update'; val: PendingUpdateParameters; } | { tag: 'successful-update'; val: SuccessfulUpdateParameters; } | { tag: 'failed-update'; val: FailedUpdateParameters; } | { tag: 'grow-memory'; val: GrowMemoryParameters; } | { tag: 'create-resource'; val: CreateResourceParameters; } | { tag: 'drop-resource'; val: DropResourceParameters; } | { tag: 'log'; val: LogParameters; } | { tag: 'restart'; val: Timestamp$1; } | { tag: 'activate-plugin'; val: ActivatePluginParameters; } | { tag: 'deactivate-plugin'; val: DeactivatePluginParameters; } | { tag: 'revert'; val: RevertParameters; } | { tag: 'cancel-pending-invocation'; val: CancelPendingInvocationParameters; } | { tag: 'begin-remote-transaction'; val: BeginRemoteTransactionParameters; } | { tag: 'pre-commit-remote-transaction'; val: RemoteTransactionParameters; } | { tag: 'pre-rollback-remote-transaction'; val: RemoteTransactionParameters; } | { tag: 'committed-remote-transaction'; val: RemoteTransactionParameters; } | { tag: 'rolled-back-remote-transaction'; val: RemoteTransactionParameters; } | { tag: 'snapshot'; val: SnapshotParameters; } | { tag: 'snapshot-confirmed'; val: SnapshotConfirmedParameters; } | { tag: 'oplog-processor-checkpoint'; val: OplogProcessorCheckpointParameters; }; declare class GetOplog { private readonly inner; constructor(agentId: AgentId$2, start: OplogIndex$1); getNext(): PublicOplogEntry[] | undefined; } declare class SearchOplog { private readonly inner; constructor(agentId: AgentId$2, text: string); getNext(): [OplogIndex$1, PublicOplogEntry][] | undefined; } declare function enrichOplogEntries(environmentId: EnvironmentId$2, agentId: AgentId$2, entries: [OplogIndex$1, golem_api_oplog_1_5_0.OplogEntry][], componentRevision: ComponentRevision): PublicOplogEntry[]; type oplog_AccountId = AccountId; declare const oplog_AccountId: typeof AccountId; declare const oplog_ActivatePluginParameters: typeof ActivatePluginParameters; type oplog_AgentId = AgentId; declare const oplog_AgentInitializationParameters: typeof AgentInitializationParameters; declare const oplog_AgentInvocation: typeof AgentInvocation; declare const oplog_AgentInvocationFinishedParameters: typeof AgentInvocationFinishedParameters; declare const oplog_AgentInvocationOutputParameters: typeof AgentInvocationOutputParameters; declare const oplog_AgentInvocationResult: typeof AgentInvocationResult; declare const oplog_AgentInvocationStartedParameters: typeof AgentInvocationStartedParameters; declare const oplog_AgentMethodInvocationParameters: typeof AgentMethodInvocationParameters; declare const oplog_AgentResourceId: typeof AgentResourceId; declare const oplog_Attribute: typeof Attribute; declare const oplog_AttributeValue: typeof AttributeValue; declare const oplog_BeginRemoteTransactionParameters: typeof BeginRemoteTransactionParameters; declare const oplog_CancelPendingInvocationParameters: typeof CancelPendingInvocationParameters; declare const oplog_CancelledParameters: typeof CancelledParameters; type oplog_ComponentId = ComponentId; declare const oplog_ComponentId: typeof ComponentId; declare const oplog_ComponentRevision: typeof ComponentRevision; type oplog_CreateParameters = CreateParameters; declare const oplog_CreateResourceParameters: typeof CreateResourceParameters; declare const oplog_DeactivatePluginParameters: typeof DeactivatePluginParameters; declare const oplog_DropResourceParameters: typeof DropResourceParameters; declare const oplog_DurableStreamEventSummary: typeof DurableStreamEventSummary; declare const oplog_DurableStreamOutcome: typeof DurableStreamOutcome; declare const oplog_EndParameters: typeof EndParameters; type oplog_EnvironmentId = EnvironmentId; declare const oplog_EnvironmentId: typeof EnvironmentId; type oplog_EnvironmentPluginGrantId = EnvironmentPluginGrantId; declare const oplog_ErrorParameters: typeof ErrorParameters; declare const oplog_ExternalSpanData: typeof ExternalSpanData; declare const oplog_FailedUpdateParameters: typeof FailedUpdateParameters; declare const oplog_FallibleResultParameters: typeof FallibleResultParameters; type oplog_GetOplog = GetOplog; declare const oplog_GetOplog: typeof GetOplog; declare const oplog_GrowMemoryParameters: typeof GrowMemoryParameters; declare const oplog_JumpParameters: typeof JumpParameters; declare const oplog_LoadSnapshotParameters: typeof LoadSnapshotParameters; declare const oplog_LocalAgentConfigEntry: typeof LocalAgentConfigEntry; declare const oplog_LocalSpanData: typeof LocalSpanData; declare const oplog_LogLevel: typeof LogLevel; declare const oplog_LogParameters: typeof LogParameters; declare const oplog_LogTraceContext: typeof LogTraceContext; declare const oplog_ManualUpdateParameters: typeof ManualUpdateParameters; declare const oplog_OplogEntry: typeof OplogEntry; declare const oplog_OplogErrorKind: typeof OplogErrorKind; declare const oplog_OplogExternalPayload: typeof OplogExternalPayload; declare const oplog_OplogPayload: typeof OplogPayload; type oplog_OplogProcessorCheckpointParameters = OplogProcessorCheckpointParameters; declare const oplog_OplogRegion: typeof OplogRegion; declare const oplog_PendingAgentInvocationParameters: typeof PendingAgentInvocationParameters; declare const oplog_PendingUpdateParameters: typeof PendingUpdateParameters; declare const oplog_PluginInstallationDescription: typeof PluginInstallationDescription; declare const oplog_ProcessOplogEntriesParameters: typeof ProcessOplogEntriesParameters; type oplog_PublicOplogEntry = PublicOplogEntry; declare const oplog_RawActivatePluginParameters: typeof RawActivatePluginParameters; declare const oplog_RawAgentInvocationFinishedParameters: typeof RawAgentInvocationFinishedParameters; declare const oplog_RawAgentInvocationStartedParameters: typeof RawAgentInvocationStartedParameters; declare const oplog_RawBeginRemoteTransactionParameters: typeof RawBeginRemoteTransactionParameters; declare const oplog_RawCancelledParameters: typeof RawCancelledParameters; declare const oplog_RawCompletionDeliveredParameters: typeof RawCompletionDeliveredParameters; declare const oplog_RawCompletionDiscardedParameters: typeof RawCompletionDiscardedParameters; declare const oplog_RawCreateParameters: typeof RawCreateParameters; declare const oplog_RawCreateResourceParameters: typeof RawCreateResourceParameters; declare const oplog_RawDeactivatePluginParameters: typeof RawDeactivatePluginParameters; declare const oplog_RawDropResourceParameters: typeof RawDropResourceParameters; declare const oplog_RawDurableStreamRecordParameters: typeof RawDurableStreamRecordParameters; declare const oplog_RawEndParameters: typeof RawEndParameters; declare const oplog_RawErrorParameters: typeof RawErrorParameters; declare const oplog_RawHostStreamFrameParameters: typeof RawHostStreamFrameParameters; declare const oplog_RawLocalAgentConfigEntry: typeof RawLocalAgentConfigEntry; declare const oplog_RawOplogProcessorCheckpointParameters: typeof RawOplogProcessorCheckpointParameters; declare const oplog_RawPendingAgentInvocationParameters: typeof RawPendingAgentInvocationParameters; declare const oplog_RawPendingUpdateParameters: typeof RawPendingUpdateParameters; declare const oplog_RawSnapshotBasedUpdate: typeof RawSnapshotBasedUpdate; declare const oplog_RawSnapshotParameters: typeof RawSnapshotParameters; declare const oplog_RawStartParameters: typeof RawStartParameters; declare const oplog_RawSuccessfulUpdateParameters: typeof RawSuccessfulUpdateParameters; declare const oplog_RawUpdateDescription: typeof RawUpdateDescription; declare const oplog_RemoteTransactionParameters: typeof RemoteTransactionParameters; declare const oplog_ResourceTypeId: typeof ResourceTypeId; declare const oplog_RevertParameters: typeof RevertParameters; declare const oplog_SaveSnapshotResultParameters: typeof SaveSnapshotResultParameters; type oplog_SearchOplog = SearchOplog; declare const oplog_SearchOplog: typeof SearchOplog; declare const oplog_SetRetryPolicyParameters: typeof SetRetryPolicyParameters; declare const oplog_SnapshotBasedUpdateParameters: typeof SnapshotBasedUpdateParameters; declare const oplog_SnapshotConfirmedParameters: typeof SnapshotConfirmedParameters; declare const oplog_SnapshotParameters: typeof SnapshotParameters; declare const oplog_SpanAttributes: typeof SpanAttributes; declare const oplog_SpanData: typeof SpanData; declare const oplog_SpanFinished: typeof SpanFinished; declare const oplog_SpanId: typeof SpanId; declare const oplog_SpanKind: typeof SpanKind; declare const oplog_SpanLink: typeof SpanLink; declare const oplog_SpanOutcome: typeof SpanOutcome; declare const oplog_SpanStarted: typeof SpanStarted; declare const oplog_StartParameters: typeof StartParameters; declare const oplog_SuccessfulUpdateParameters: typeof SuccessfulUpdateParameters; declare const oplog_TraceId: typeof TraceId; declare const oplog_UpdateDescription: typeof UpdateDescription; type oplog_Uuid = Uuid; declare const oplog_Uuid: typeof Uuid; declare const oplog_WorkerError: typeof WorkerError; declare const oplog_WrappedFunctionType: typeof WrappedFunctionType; declare const oplog_enrichOplogEntries: typeof enrichOplogEntries; declare namespace oplog { export { oplog_AccountId as AccountId, oplog_ActivatePluginParameters as ActivatePluginParameters, oplog_AgentInitializationParameters as AgentInitializationParameters, oplog_AgentInvocation as AgentInvocation, oplog_AgentInvocationFinishedParameters as AgentInvocationFinishedParameters, oplog_AgentInvocationOutputParameters as AgentInvocationOutputParameters, oplog_AgentInvocationResult as AgentInvocationResult, oplog_AgentInvocationStartedParameters as AgentInvocationStartedParameters, oplog_AgentMethodInvocationParameters as AgentMethodInvocationParameters, oplog_AgentResourceId as AgentResourceId, oplog_Attribute as Attribute, oplog_AttributeValue as AttributeValue, oplog_BeginRemoteTransactionParameters as BeginRemoteTransactionParameters, oplog_CancelPendingInvocationParameters as CancelPendingInvocationParameters, oplog_CancelledParameters as CancelledParameters, oplog_ComponentId as ComponentId, oplog_ComponentRevision as ComponentRevision, oplog_CreateResourceParameters as CreateResourceParameters, Datetime$2 as Datetime, oplog_DeactivatePluginParameters as DeactivatePluginParameters, oplog_DropResourceParameters as DropResourceParameters, oplog_DurableStreamEventSummary as DurableStreamEventSummary, oplog_DurableStreamOutcome as DurableStreamOutcome, oplog_EndParameters as EndParameters, oplog_EnvironmentId as EnvironmentId, oplog_ErrorParameters as ErrorParameters, oplog_ExternalSpanData as ExternalSpanData, oplog_FailedUpdateParameters as FailedUpdateParameters, oplog_FallibleResultParameters as FallibleResultParameters, oplog_GetOplog as GetOplog, oplog_GrowMemoryParameters as GrowMemoryParameters, oplog_JumpParameters as JumpParameters, oplog_LoadSnapshotParameters as LoadSnapshotParameters, oplog_LocalAgentConfigEntry as LocalAgentConfigEntry, oplog_LocalSpanData as LocalSpanData, oplog_LogLevel as LogLevel, oplog_LogParameters as LogParameters, oplog_LogTraceContext as LogTraceContext, oplog_ManualUpdateParameters as ManualUpdateParameters, oplog_OplogEntry as OplogEntry, oplog_OplogErrorKind as OplogErrorKind, oplog_OplogExternalPayload as OplogExternalPayload, OplogIndex$1 as OplogIndex, oplog_OplogPayload as OplogPayload, oplog_OplogRegion as OplogRegion, oplog_PendingAgentInvocationParameters as PendingAgentInvocationParameters, oplog_PendingUpdateParameters as PendingUpdateParameters, oplog_PluginInstallationDescription as PluginInstallationDescription, oplog_ProcessOplogEntriesParameters as ProcessOplogEntriesParameters, oplog_RawActivatePluginParameters as RawActivatePluginParameters, oplog_RawAgentInvocationFinishedParameters as RawAgentInvocationFinishedParameters, oplog_RawAgentInvocationStartedParameters as RawAgentInvocationStartedParameters, oplog_RawBeginRemoteTransactionParameters as RawBeginRemoteTransactionParameters, oplog_RawCancelledParameters as RawCancelledParameters, oplog_RawCompletionDeliveredParameters as RawCompletionDeliveredParameters, oplog_RawCompletionDiscardedParameters as RawCompletionDiscardedParameters, oplog_RawCreateParameters as RawCreateParameters, oplog_RawCreateResourceParameters as RawCreateResourceParameters, oplog_RawDeactivatePluginParameters as RawDeactivatePluginParameters, oplog_RawDropResourceParameters as RawDropResourceParameters, oplog_RawDurableStreamRecordParameters as RawDurableStreamRecordParameters, oplog_RawEndParameters as RawEndParameters, oplog_RawErrorParameters as RawErrorParameters, oplog_RawHostStreamFrameParameters as RawHostStreamFrameParameters, oplog_RawLocalAgentConfigEntry as RawLocalAgentConfigEntry, oplog_RawOplogProcessorCheckpointParameters as RawOplogProcessorCheckpointParameters, oplog_RawPendingAgentInvocationParameters as RawPendingAgentInvocationParameters, oplog_RawPendingUpdateParameters as RawPendingUpdateParameters, oplog_RawSnapshotBasedUpdate as RawSnapshotBasedUpdate, oplog_RawSnapshotParameters as RawSnapshotParameters, oplog_RawStartParameters as RawStartParameters, oplog_RawSuccessfulUpdateParameters as RawSuccessfulUpdateParameters, oplog_RawUpdateDescription as RawUpdateDescription, oplog_RemoteTransactionParameters as RemoteTransactionParameters, oplog_ResourceTypeId as ResourceTypeId, oplog_RevertParameters as RevertParameters, oplog_SaveSnapshotResultParameters as SaveSnapshotResultParameters, SchemaValueTree$1 as SchemaValueTree, oplog_SearchOplog as SearchOplog, oplog_SetRetryPolicyParameters as SetRetryPolicyParameters, oplog_SnapshotBasedUpdateParameters as SnapshotBasedUpdateParameters, oplog_SnapshotConfirmedParameters as SnapshotConfirmedParameters, oplog_SnapshotParameters as SnapshotParameters, oplog_SpanAttributes as SpanAttributes, oplog_SpanData as SpanData, oplog_SpanFinished as SpanFinished, oplog_SpanId as SpanId, oplog_SpanKind as SpanKind, oplog_SpanLink as SpanLink, oplog_SpanOutcome as SpanOutcome, oplog_SpanStarted as SpanStarted, oplog_StartParameters as StartParameters, oplog_SuccessfulUpdateParameters as SuccessfulUpdateParameters, Timestamp$1 as Timestamp, oplog_TraceId as TraceId, TypedSchemaValue$2 as TypedSchemaValue, oplog_UpdateDescription as UpdateDescription, oplog_Uuid as Uuid, oplog_WorkerError as WorkerError, oplog_WrappedFunctionType as WrappedFunctionType, oplog_enrichOplogEntries as enrichOplogEntries }; export type { oplog_AgentId as AgentId, oplog_CreateParameters as CreateParameters, oplog_EnvironmentPluginGrantId as EnvironmentPluginGrantId, oplog_OplogProcessorCheckpointParameters as OplogProcessorCheckpointParameters, oplog_PublicOplogEntry as PublicOplogEntry }; } declare function isPromiseLike(value: unknown): value is Promise; declare function executeWithDrop void; }, R>(resources: [Resource], fn: () => Promise): Promise; declare function executeWithDrop void; }, R>(resources: [Resource], fn: () => R): R; /** * Executes an async function and automatically drops the provided resources after execution. * @param resources - An array of resources to be dropped after execution. * @param fn - The async function to execute. * @returns A promise resolving to the result of the executed function. * @deprecated Use {@link executeWithDrop} instead, which handles both sync and async callbacks. */ declare function executeWithDropAsync void; }, R>(resources: [Resource], fn: () => Promise): Promise; /** * Drops all the provided resources and collects any errors that occur during the process. * @param resources - An array of resources to be dropped. * @throws DropError if any errors occur during the dropping process. */ declare function dropAll void; }>(throwOnError: boolean, resources: [Resource]): void; /** * A committed or in-flight resource-consumption handle. * * Dropping a `Reservation` without calling `commit` is equivalent to * committing zero usage — unused capacity is returned to the pool. */ declare class Reservation { private readonly raw; constructor(raw: Reservation$1); /** * Commit actual usage. * * - If `used` < reserved — unused capacity is returned to the pool. * - If `used` > reserved — the excess is deducted from the token's * remaining allocation as "debt". */ commit(used: bigint): void; } /** * An unforgeable capability granting the right to consume a named resource. * * Dropping the token releases the underlying lease back to the executor pool. * * Typical usage: * ```ts * const token = acquireQuotaToken('openai-tokens', 1000n); * const result = token.reserve(500n); * if (result.isOk()) { * // ... do work ... * result.unwrap().commit(actualUsed); * } * ``` * * Or use the RAII helper {@link withQuotaToken} to commit automatically. */ declare class QuotaToken { constructor(key: QuotaInternal, handle: GuestQuotaTokenHandle); /** * Reserve `amount` units from the local allocation. * * Returns `Result.ok(reservation)` when capacity is available, or * `Result.err(failedReservation)` when the resource's enforcement policy * is `reject`. For `throttle` / `terminate` policies the call suspends or * terminates the agent before returning. * * Traps if this token has already been transferred (for example, sent to * another agent through an RPC call or returned from a method). Split the * token first if you need to both keep and send a capability. */ reserve(amount: bigint): Result; /** * Split off a child token that receives `childExpectedUse` units of * expected-use from this token. * * - The parent's `expectedUse` is reduced by `childExpectedUse`. * - Credits are divided proportionally between parent and child. * * Traps if `childExpectedUse` exceeds the parent's current expected-use, or * if this token has already been transferred. */ split(childExpectedUse: bigint): QuotaToken; /** * Merge `other` back into this token, combining expected-use and credits. * * Both tokens must refer to the same resource (same resource-name and * environment). `other` is consumed by this call. * * Traps if the tokens refer to different resources, or if either token has * already been transferred. */ merge(other: QuotaToken): void; /** * Quota tokens are unforgeable capabilities, not data: serializing one (e.g. * via `JSON.stringify`) is always an error. Pass them directly to RPC / agent * boundaries instead, where they travel as an opaque owned handle. */ toJSON(): never; } /** * Construct a `QuotaToken` for the named resource. * * @param resourceName - The resource name as declared in the manifest. * @param expectedUse - Expected units per reservation; used to derive the * credit rate and max-credit for fair scheduling. */ declare function acquireQuotaToken(resourceName: string, expectedUse: bigint): QuotaToken; declare function withReservation(token: QuotaToken, amount: bigint, fn: (reservation: Reservation) => Promise<{ used: bigint; value: R; }>): Promise>; declare function withReservation(token: QuotaToken, amount: bigint, fn: (reservation: Reservation) => { used: bigint; value: R; }): Result; type permissions_Bounds = Bounds; type permissions_CardId = CardId; declare const permissions_CardId: typeof CardId; type permissions_CardView = CardView; type permissions_Holder = Holder; declare const permissions_Holder: typeof Holder; type permissions_KernelModule = KernelModule; type permissions_Lifespan = Lifespan; declare const permissions_Lifespan: typeof Lifespan; declare const permissions_PERMISSION_ERROR_KINDS: typeof PERMISSION_ERROR_KINDS; type permissions_PatternGrant = PatternGrant; type permissions_PermissionCard = PermissionCard; declare const permissions_PermissionCard: typeof PermissionCard; type permissions_PermissionError = PermissionError; declare const permissions_PermissionError: typeof PermissionError; type permissions_PermissionErrorKind = PermissionErrorKind; type permissions_PolymorphicPermissionCard = PolymorphicPermissionCard; declare const permissions_PolymorphicPermissionCard: typeof PolymorphicPermissionCard; type permissions_ScopeCard = ScopeCard; declare const permissions_ScopeCard: typeof ScopeCard; type permissions_Timestamp = Timestamp; type permissions_WalletCard = WalletCard; type permissions_WalletVersionToken = WalletVersionToken; declare const permissions_deriveFromWallet: typeof deriveFromWallet; declare const permissions_deriveScope: typeof deriveScope; declare const permissions_listModules: typeof listModules; declare const permissions_validateGrant: typeof validateGrant; declare const permissions_wallet: typeof wallet; declare const permissions_walletVersion: typeof walletVersion; declare namespace permissions { export { permissions_CardId as CardId, permissions_Holder as Holder, permissions_Lifespan as Lifespan, permissions_PERMISSION_ERROR_KINDS as PERMISSION_ERROR_KINDS, permissions_PermissionCard as PermissionCard, permissions_PermissionError as PermissionError, permissions_PolymorphicPermissionCard as PolymorphicPermissionCard, permissions_ScopeCard as ScopeCard, permissions_deriveFromWallet as deriveFromWallet, permissions_deriveScope as deriveScope, permissions_listModules as listModules, permissions_validateGrant as validateGrant, permissions_wallet as wallet, permissions_walletVersion as walletVersion }; export type { permissions_Bounds as Bounds, permissions_CardView as CardView, permissions_KernelModule as KernelModule, permissions_PatternGrant as PatternGrant, permissions_PermissionErrorKind as PermissionErrorKind, permissions_Timestamp as Timestamp, permissions_WalletCard as WalletCard, permissions_WalletVersionToken as WalletVersionToken }; } type RetryProperties = Readonly> | Iterable; interface RetryOptions { /** Projects semantic retry properties from each thrown or rejected value. */ properties?: (error: unknown, retryCount: number) => RetryProperties; /** Cancels an in-flight attempt or delay. The underlying user operation must observe it to stop. */ signal?: AbortSignal; } /** An invalid policy AST or a predicate that cannot be evaluated against projected properties. */ declare class RetryPolicyError extends Error { constructor(message: string); } /** * Runs arbitrary user code using a Golem semantic retry policy entirely in user space. * * The callback receives a zero-based physical attempt number. Its return value may be * synchronous or Promise-like; this function always returns a Promise. These retries * are ordinary user-space calls, not executor-managed retry attempts, and do not form * one durable retry sequence across suspension or recovery. * * Local `prop-matches` predicates translate `*` to JavaScript regex `.*` and `?` to `.`, * without flags. Use a host-driven retry policy when full platform glob semantics are required. */ declare function retry(policy: PolicyInput, operation: (attempt: number) => T | PromiseLike, options?: RetryOptions): Promise; declare function setRetryPolicy(policy: NamedPolicyInput): void; /** * RetryPolicyGuard is a guard type that restores the previous retry policy on drop. * If the policy existed before, it is restored; if it was newly added, it is removed. * You must call drop on the guard once you are finished using it. */ declare class RetryPolicyGuard { private previous; private name; constructor(previous: NamedRetryPolicy | undefined, name: string); drop(): void; } /** * Temporarily sets a named retry policy and returns a guard. * When the guard is dropped, the previous policy with the same name is restored * (or removed if it didn't exist). * @param policy - The named retry policy to set, either as a raw WIT shape or a high-level NamedPolicy. * @returns A RetryPolicyGuard instance. */ declare function useRetryPolicy(policy: NamedPolicyInput): RetryPolicyGuard; declare function withRetryPolicy(policy: NamedPolicyInput, f: () => Promise): Promise; declare function withRetryPolicy(policy: NamedPolicyInput, f: () => R): R; /** * A compensable step of a saga: an action with a matching rollback (compensation). * * Implement this interface and use it within a saga block (`fallibleSaga` / * `infallibleSaga`). Steps can also be constructed from closures via `compensable`. */ interface Compensable { /** * The action to execute. * @param input - The input to the step. * @returns A promise resolving to the result of the step. */ execute(input: In): Promise>; /** * Compensation to perform in case of failure. * Compensations should not throw errors. * @param input - The input to the step. * @param result - The result of the step. * @returns A promise resolving to the result of the compensation. */ compensate(input: In, result: Out): Promise>; } /** * Creates a {@link Compensable} step from the provided execute and compensate functions. * @param execute - The function to execute the step. * @param compensate - The function to compensate the step in case of failure. * @returns The created compensable step. */ declare function compensable(execute: (input: In) => Promise>, compensate: (input: In, result: Out) => Promise>): Compensable; /** A saga stopped after compensation, exhaustion, or an invalid retry policy. */ type SagaRetryFailureReason = { type: 'exhausted'; } | { type: 'compensation-failure'; compensationFailure: unknown; } | { type: 'policy-error'; policyError: unknown; }; declare class SagaRetryFailure extends Error { readonly error: unknown; readonly reason: SagaRetryFailureReason; constructor(error: unknown, reason: SagaRetryFailureReason); } declare class InfallibleSaga { private compensations; private terminal; checkActive(): void; failure(error: unknown): unknown; compensate(error: unknown): Promise; /** * Executes a compensable step within the infallible saga. * @param step - The step to execute. * @param input - The input to the step. * @returns A promise resolving to the result of the step. */ execute(step: Compensable, input: In): Promise; private retry; } declare class FallibleSaga { private compensations; /** * Executes a compensable step within the fallible saga. * @param step - The step to execute. * @param input - The input to the step. * @returns A promise resolving to the result of the step. */ execute(step: Compensable, input: In): Promise>; /** * Handles the failure of the fallible saga. * @param error - The error that caused the failure. * @returns A promise resolving to the saga failure result. */ onFailure(error: Err): Promise>; } type SagaResult = Result>; type SagaFailure = { type: 'FailedAndRolledBackCompletely'; error: Err; } | { type: 'FailedAndRolledBackPartially'; error: unknown; compensationFailure: unknown; }; /** * Executes an infallible saga. * * An infallible saga retries user-level failures after compensation. Each attempt appends * new durable calls without restoring JavaScript state. Compensate local state explicitly. * Do not reuse an external operation's idempotency key after compensating it. * * In addition, **user level failures** (represented by the `Result::Err` value of a step) * lead to performing the compensation actions of each already performed step in reverse order. * * Caught exceptions also run compensation before the host retry decision. * * @param f - The async function that defines the saga. * @returns A promise resolving to the result of the saga. */ declare function infallibleSaga(f: (saga: InfallibleSaga) => Promise): Promise>; /** * Executes a fallible saga. * * A fallible saga is a sequence of compensable steps. When the saga callback returns * `Result::Err`, compensation runs for successfully completed steps in reverse order. * If a compensation returns `Result::Err`, compensation stops and the saga reports * `FailedAndRolledBackPartially`. * * Caught exceptions run compensation and are rethrown unchanged when rollback completes. * * @param f - The async function that defines the saga. * @returns A promise resolving to the result of the saga. */ declare function fallibleSaga(f: (saga: FallibleSaga) => Promise>): Promise>; /** * Extracts the error types from an array of compensable steps. * * @template T - An array of `Compensable` steps. * @returns A union type representing the possible error types that can occur in the steps. * * @example * ```typescript * const stepOne: Compensable = compensable( * // ... * ); * * const stepTwo: Compensable = compensable( * // ... * ); * * type Errors = CompensableErrors<[typeof stepOne, typeof stepTwo]>; * // Errors = string | { code: string; message: string } * ``` * */ type CompensableErrors[]> = { [K in keyof T]: T[K] extends Compensable ? Err : never; }[number]; /** * The kind of wrapped function, mirroring the WIT `wrapped-function-type` (and * `golem-rust`'s `WrappedFunctionType`). Picks the executor's commit/replay * policy: * - `readLocal` — a local read-only side effect (PRNG, reading the clock/FS). * - `writeLocal` — a local mutating side effect (FS write, spawning a process). * - `readRemote` — an idempotent remote read (polling a job, fetching a page). * - `writeRemote` — a non-idempotent remote write (sending an LLM prompt, a DB insert). */ declare const FunctionType: { readonly readLocal: { readonly tag: "read-local"; }; readonly writeLocal: { readonly tag: "write-local"; }; readonly readRemote: { readonly tag: "read-remote"; }; readonly writeRemote: { readonly tag: "write-remote"; }; }; /** Static descriptor of a durable function: what it is + how its I/O is typed. */ interface DurableSpec { /** Interface name, e.g. `"host-features"`. Combined with `function` into the persisted name. */ readonly iface: string; /** Function name, e.g. `"fetchQuote"`. */ readonly function: string; /** The commit/replay policy — see {@link FunctionType}. */ readonly functionType: DurableFunctionType; /** Schema for the `request` value (persisted so oplogs are self-describing). */ readonly requestSchema: StandardSchemaV1; /** Schema for the body's success value. */ readonly success: StandardSchemaV1; /** Force an efficient oplog commit at the end of the region (default false). */ readonly forcedCommit?: boolean; } /** Fallible variant — carries an `error` schema; the body returns a {@link Result}. */ interface DurableFallibleSpec extends DurableSpec { /** Schema for the typed error; the persisted response is a WIT `result`. */ readonly error: StandardSchemaV1; } /** * Persists the body's result; a throw leaves the operation unfinished without triggering a retry. * * Sequential execution only, including properly nested calls. An async body may await host calls * only when no unrelated guest work runs during the wait. Do not overlap this operation with other * promises or callbacks, even those using ordinary host APIs: sibling effects can be attributed to * the wrong operation, causing incorrect replay or invocation failure. Misuse is not reliably detected. * Await each nested operation and do not detach work. Stop and join outstanding work before the * body exits, including on failure; Promise.all rejection does not join surviving siblings. */ declare function durable(spec: DurableSpec, request: Req, body: () => Promise): Promise; /** Synchronous form of {@link durable}; the same sequential-only and no-detached-work limits apply. */ declare function durable(spec: DurableSpec, request: Req, body: () => Ok): Ok; /** * Persists either Result variant; a throw is an uncaught defect. * The same sequential-only and no-detached-work limits as {@link durable} apply. */ declare function durable(spec: DurableFallibleSpec, request: Req, body: () => Promise>): Promise>; /** Synchronous Result form of {@link durable}; the same sequential-only and no-detached-work limits apply. */ declare function durable(spec: DurableFallibleSpec, request: Req, body: () => Result): Result; /** * Hidden brand key carried by every marker schema. The value is a * {@link MarkerDescriptor} the adapter uses to build the {@link SchemaCodec}. * A unique, unexported `Symbol` cannot be forged or guessed, so only this module * mints markers and only the adapter reads the brand. */ declare const WIT_MARKER: unique symbol; /** * Build a {@link SchemaCodec} from a marker. `recurse` compiles an inner * Standard Schema (the same `compileSchema` callback the vendor walkers use), so * capability wrappers (e.g. `s.secret(inner)`) can descend into their payload. */ type MarkerDescriptor = (recurse: (child: unknown) => SchemaCodec) => SchemaCodec; /** * Type-level classification of a marker. `'scalar'` covers everything that can * be bound from a string source (numeric pins, `char`, `datetime`, `url`, * `secret`, …); the other three tag the rich payload markers that can NOT be * bound from a path / query / header variable and therefore must be excluded * from HTTP variable binding (see {@link MarkerKindOf} / `BindableKeys`). */ type MarkerKind = 'scalar' | 'multimodal' | 'unstructured-text' | 'unstructured-binary' | 'secret' | 'result' | 'option' | 'typed-array' | 'principal' | 'stream'; /** Pure phantom key carrying a marker's {@link MarkerKind} at the type level. */ declare const MARKER_KIND: unique symbol; /** A Standard Schema that additionally carries a {@link WIT_MARKER} brand. */ interface MarkerSchema extends StandardSchemaV1 { readonly [WIT_MARKER]: MarkerDescriptor; /** * PURE PHANTOM: never assigned at runtime (no runtime object carries it), so * marker values are structurally unchanged. It exists only so the marker's * {@link MarkerKind} is recoverable at the type level via {@link MarkerKindOf}. */ readonly [MARKER_KIND]?: Kind; } /** * Recover a marker's {@link MarkerKind} at the type level. Resolves to * `undefined` for any value that is not a {@link MarkerSchema} (e.g. a plain * Zod / Valibot / ArkType schema). */ type MarkerKindOf = V extends MarkerSchema ? K : undefined; /** * Runtime brand key carried by every secret marker; its value is the marker's * INNER Standard Schema (describing the revealed plaintext). It doubles as the * type-level carrier of the inner type — {@link SecretInnerOf} recovers it — so * no separate phantom field is needed. Symbol-keyed, so it is invisible to * `JSON.stringify` / `Object.keys` and does not disturb the codec build. */ declare const SECRET_INNER: unique symbol; /** * A secret marker: a {@link MarkerSchema} of kind `'secret'` that additionally * carries its inner (revealed) schema under {@link SECRET_INNER}. The static * `Inner` type is recoverable via {@link SecretInnerOf}. */ interface SecretMarkerSchema extends MarkerSchema { readonly [SECRET_INNER]: StandardSchemaV1; } /** Recover the inner (revealed) type of a secret marker, else `never`. */ type SecretInnerOf = V extends SecretMarkerSchema ? I : never; /** Options for pinning a numeric with inline min/max/unit restrictions. */ interface NumericOpts { min?: number | bigint; max?: number | bigint; unit?: string; } interface PathOptions { direction?: PathDirection; kind?: PathKind; allowedMimeTypes?: string[]; allowedExtensions?: string[]; } interface QuantityOptions { baseUnit: string; allowedSuffixes?: string[]; min?: QuantityValue; max?: QuantityValue; } interface KeyValueOptions { keySchema?: StandardSchemaV1; } /** A filesystem path value backed by the rich WIT `path` schema node. */ declare function Path(options?: PathOptions): MarkerSchema; /** A fixed-point quantity backed by the rich WIT `quantity` schema node. */ declare function Quantity(options: QuantityOptions): MarkerSchema; /** A key-value collection backed by a real WIT `map` node. */ declare function KeyValue(valueSchema: StandardSchemaV1): MarkerSchema>; declare function KeyValue(valueSchema: StandardSchemaV1, options: KeyValueOptions & { keySchema: StandardSchemaV1; }): MarkerSchema>; /** Binary data backed by the rich WIT `binary` node, not `list`. */ declare function Bytes(options?: BinaryRestrictions): MarkerSchema; interface PermissionCardOptions { /** * `true` for a template card, whose grants may contain slot variables; * `false` for a concrete card. `s.permissionCard` needs a literal value. */ polymorphic: Polymorphic; } /** * A `permission-card` schema node. `polymorphic: false` declares a concrete * {@link PermissionCard}; `polymorphic: true` declares a template * {@link PolymorphicPermissionCard}. A received card is decoded into the * declared type; the host keeps the card's real kind. */ declare function permissionCardMarker(options: PermissionCardOptions): MarkerSchema; declare function permissionCardMarker(options: PermissionCardOptions): MarkerSchema; /** Domain value of an unstructured-text parameter: `url` or `inline` text. */ type TextReferenceValue = { tag: 'url'; val: string; } | { tag: 'inline'; val: string; languageCode?: string; }; /** Domain value of an unstructured-binary parameter: `url` or `inline` bytes. */ type BinaryReferenceValue = { tag: 'url'; val: string; } | { tag: 'inline'; val: Uint8Array; mimeType?: string; }; interface UnstructuredTextOpts { languages?: string[]; } interface UnstructuredBinaryOpts { mimeTypes?: string[]; } /** Domain value element of a multimodal payload: `{ tag, value }`. */ interface MultimodalElement { tag: string; value: unknown; } /** One named multimodal case: a name plus the marker / Standard Schema for it. */ interface MultimodalCase { name: string; schema: unknown; } interface ProcessExitStatus { exit_code: number; } /** The nominal process status contract shared by command tools. */ declare const processExitStatusSchema: StandardSchemaV1; /** * Vendor-neutral marker schemas for WIT kinds Standard Schema can't express on * its own: numeric pins, `char`, `datetime`, `duration`, `url`, `bytes`, plus * the capability / rich nodes (`secret`, `quota-token`, `permission-card`, `multimodal`, * `unstructured*`) and the `option` / `result` wrappers. Each returns a * {@link MarkerSchema} usable anywhere a Standard Schema is accepted; `stream` * is restricted to agent method inputs and outputs by the agent schema validator. */ declare const s: { u8: (opts?: NumericOpts) => MarkerSchema; u16: (opts?: NumericOpts) => MarkerSchema; u32: (opts?: NumericOpts) => MarkerSchema; u64: (opts?: NumericOpts) => MarkerSchema; s8: (opts?: NumericOpts) => MarkerSchema; s16: (opts?: NumericOpts) => MarkerSchema; s32: (opts?: NumericOpts) => MarkerSchema; s64: (opts?: NumericOpts) => MarkerSchema; f32: (opts?: NumericOpts) => MarkerSchema; char: () => MarkerSchema; uuid: () => MarkerSchema; datetime: () => MarkerSchema; duration: () => MarkerSchema; url: () => MarkerSchema; text: (opts?: TextRestrictions) => MarkerSchema; bytes: () => MarkerSchema, "typed-array">; binary: (opts?: BinaryRestrictions) => MarkerSchema, "scalar">; int8Array: () => MarkerSchema, "typed-array">; uint8Array: () => MarkerSchema, "typed-array">; int16Array: () => MarkerSchema, "typed-array">; uint16Array: () => MarkerSchema, "typed-array">; int32Array: () => MarkerSchema, "typed-array">; uint32Array: () => MarkerSchema, "typed-array">; float32Array: () => MarkerSchema, "typed-array">; float64Array: () => MarkerSchema, "typed-array">; bigInt64Array: () => MarkerSchema, "typed-array">; bigUint64Array: () => MarkerSchema, "typed-array">; secret: (inner: StandardSchemaV1) => SecretMarkerSchema; quotaToken: () => MarkerSchema; stream: (inner: StandardSchemaV1) => MarkerSchema, "stream">; permissionCard: typeof permissionCardMarker; principal: () => MarkerSchema; multimodal: (cases: MultimodalCase[]) => MarkerSchema; unstructuredText: (opts?: UnstructuredTextOpts) => MarkerSchema; unstructuredBinary: (opts?: UnstructuredBinaryOpts) => MarkerSchema; option: (innerSchema: StandardSchemaV1) => MarkerSchema; result: (okSchema: StandardSchemaV1, errSchema: StandardSchemaV1) => MarkerSchema, "result">; }; /** A canonical field occurrence. Values are bytes, not UTF-8 text. */ interface HttpHeader { readonly name: string; readonly value: Uint8Array; } /** The original public request; undefined query differs from an empty query. */ interface HttpRequest { readonly method: string; readonly scheme: string; readonly authority: string; readonly path: string; readonly query: string | undefined; readonly headers: readonly HttpHeader[]; readonly body: Body; } /** Canonical response. Body ownership is supplied by the language runtime. */ interface HttpResponse { readonly status: number; readonly headers: readonly HttpHeader[]; readonly body: Body; } interface FileExposure { readonly route: string; readonly path: string; } /** Response headers applied by the host when serving mounted files. */ type FileResponseHeaders = Readonly>; declare const InvalidBrand: unique symbol; /** * Branded "compile-time error" carrier. When a type-level check fails, the * helper resolves to a value that intersects with `Invalid<"…">`. Because * `[InvalidBrand]: Reason` is a non-optional unique-symbol property that no real * value carries, the failing assignment is rejected — and the `tsc` / IDE * message includes the literal `Reason` string verbatim, rendering as a readable * error rather than a bare `never`. */ interface Invalid { readonly [InvalidBrand]: Reason; } /** System-variable names the Golem host injects into routes. */ type SystemVariableName = 'agent-type' | 'agent-version'; type StartsWithSlash = S extends `/${string}` ? true : false; type HasTrailingSlash = S extends '/' ? false : S extends `${string}/` ? true : false; type HasDoubleSlash = S extends `${string}//${string}` ? true : false; type HasQuery = S extends `${string}?${string}` ? true : false; type CountQuery = []> = S extends `${string}?${infer Rest}` ? CountQuery : Acc['length']; type HasOpenBrace = S extends `${string}{${string}` ? true : false; type HasCloseBrace = S extends `${string}}${string}` ? true : false; type EndpointPathPart = S extends `${infer P}?${string}` ? P : S; type ValidateBracedSegment = Inner extends '' ? Invalid<`path '${S}' has an empty variable name in '${Seg}'`> : HasOpenBrace extends true ? Invalid<`path '${S}' has nested or malformed braces in '${Seg}'`> : HasCloseBrace extends true ? Invalid<`path '${S}' has nested or malformed braces in '${Seg}'`> : Inner extends `*${infer Name}` ? IsMount extends true ? Invalid<`mount path '${S}' may not include a catch-all segment '${Seg}'`> : Name extends '' ? Invalid<`endpoint path '${S}' has a catch-all variable with no name in '${Seg}'`> : IsLast extends true ? 'ok' : Invalid<`endpoint path '${S}' has catch-all segment '${Seg}' that is not the last path segment`> : 'ok'; type ValidateSegment = Seg extends '' ? 'ok' : Seg extends `{${infer Inner}}` ? ValidateBracedSegment : HasOpenBrace extends true ? Invalid<`path '${S}' segment '${Seg}' mixes literal text with '{...}' variables`> : HasCloseBrace extends true ? Invalid<`path '${S}' segment '${Seg}' mixes literal text with '{...}' variables`> : 'ok'; type ValidateSegmentsRec = Rest extends `${infer Head}/${infer Tail}` ? ValidateSegment extends infer R ? R extends Invalid ? R : ValidateSegmentsRec : never : ValidateSegment; type ValidateSegments = PathPart extends '/' ? 'ok' : PathPart extends `/${infer Rest}` ? ValidateSegmentsRec : 'ok'; type ValidateMountShape = StartsWithSlash extends false ? Invalid<`mount path '${S}' must start with '/'`> : HasTrailingSlash extends true ? Invalid<`mount path '${S}' must not end with '/' (except '/')`> : HasDoubleSlash extends true ? Invalid<`mount path '${S}' must not contain '//'`> : HasQuery extends true ? Invalid<`mount path '${S}' may not include a query string`> : ValidateSegments extends infer R ? R extends Invalid ? R : S : never; type ValidateEndpointShape = StartsWithSlash extends false ? Invalid<`endpoint path '${S}' must start with '/'`> : HasTrailingSlash extends true ? Invalid<`endpoint path '${S}' must not end with '/' (except '/')`> : HasDoubleSlash extends true ? Invalid<`endpoint path '${S}' must not contain '//'`> : CountQuery extends 0 | 1 ? ValidateSegments, false, S> extends infer R ? R extends Invalid ? R : ValidateEndpointQuery : never : Invalid<`endpoint path '${S}' contains more than one '?'`>; type ValidateEndpointQuery = S extends `${string}?${infer Q}` ? ValidateQueryString extends infer R ? R extends Invalid ? R : UniqueQueryKeys : never : S; type ValidateQueryString = Q extends '' ? S : Q extends `&${string}` ? Invalid<`endpoint path '${S}' has an empty '&' segment in its query string`> : Q extends `${string}&` ? Invalid<`endpoint path '${S}' has an empty '&' segment in its query string`> : Q extends `${string}&&${string}` ? Invalid<`endpoint path '${S}' has an empty '&' segment in its query string`> : ValidateQueryPairs; type ValidateQueryPairs = Q extends `${infer Pair}&${infer Rest}` ? CheckPair extends infer R ? R extends Invalid ? R : ValidateQueryPairs : never : CheckPair; type CheckPair

= P extends `=${string}` ? Invalid<`endpoint path '${S}' has an empty query parameter name`> : S; type ExtractQueryKey = Pair extends `${infer K}=${string}` ? K : Pair; type IncludesString, K extends string> = T extends readonly [ infer Head, ...infer Tail ] ? [Head, K] extends [K, Head] ? true : Tail extends ReadonlyArray ? IncludesString : false : false; type UniqueQueryPairsRec, S extends string> = Q extends `${infer Pair}&${infer Rest}` ? ExtractQueryKey extends infer K extends string ? IncludesString extends true ? Invalid<`endpoint path '${S}' has duplicate query key '${K}'`> : UniqueQueryPairsRec : never : ExtractQueryKey extends infer K extends string ? IncludesString extends true ? Invalid<`endpoint path '${S}' has duplicate query key '${K}'`> : S : never; /** * Compile-time gate for query-string key uniqueness. Walks `Q` (the portion of * an endpoint path *after* the first `?`) one pair at a time; collisions resolve * to `Invalid<"…duplicate query key '…'">`, otherwise resolves to `S` unchanged. */ type UniqueQueryKeys = UniqueQueryPairsRec; /** * Compile-time gate for mount paths: returns the literal `S` itself when the * template-literal rules hold (must start with `/`, no trailing `/`, no `//`, no * `?`, valid segment shapes, no catch-all), else an `Invalid<"…">` carrier. When * `S` widens to plain `string` (non-literal expression), the helper * short-circuits to `S` and the runtime parser is the only line of defence. */ type ValidMountPath = string extends S ? S : ValidateMountShape; /** * Compile-time gate for endpoint paths. Same rules as {@link ValidMountPath} * except `?` is permitted at most once and `{*rest}` is allowed as the last * segment; also enforces query-key uniqueness. */ type ValidEndpointPath = string extends S ? S : ValidateEndpointShape; type SplitPathQuery = S extends `${infer P}?${infer Q}` ? { path: P; query: Q; } : { path: S; query: ''; }; type CleanVarName = V extends `*${infer N}` ? N : V; type ExtractVarsFromPath = S extends `${string}{${infer V}}${infer Rest}` ? CleanVarName | ExtractVarsFromPath : never; type ExtractVarsFromQuery = S extends `${string}={${infer V}}${infer Rest}` ? V | ExtractVarsFromQuery : never; /** Extract all path-variable names from a literal path template (system vars included). */ type PathVarsOf = ExtractVarsFromPath['path']>; /** Extract all query-variable values from a literal path template's `?…` portion. */ type QueryVarsOf = ExtractVarsFromQuery['query']>; /** * Extract the union of values from a `Record` literal. Returns * `never` for empty records so `{}` does not widen the binding union to `string`. */ type ValuesOf = [keyof R] extends [never] ? never : R extends Readonly> ? V & string : never; type ExtractPathTupleRec = readonly []> = S extends `${string}{${infer V}}${infer Rest}` ? ExtractPathTupleRec]> : Acc; type ExtractQueryTupleRec = readonly []> = S extends `${string}={${infer V}}${infer Rest}` ? ExtractQueryTupleRec : Acc; type FilterSystemVarsRec, Acc extends ReadonlyArray = readonly []> = T extends readonly [infer Head extends string, ...infer Tail extends ReadonlyArray] ? Head extends SystemVariableName ? FilterSystemVarsRec : FilterSystemVarsRec : Acc; /** Tuple of path-variable names (system vars stripped, catch-all `*` removed). */ type PathTupleOf = FilterSystemVarsRec['path']>>; /** Tuple of query-variable names extracted from the inline `?…` portion. */ type QueryTupleOf = ExtractQueryTupleRec['query']>; type IsAny = 0 extends 1 & V ? true : false; type NonBindableKind = 'multimodal' | 'unstructured-text' | 'unstructured-binary' | 'result' | 'typed-array' | 'principal' | 'stream'; type IsBindable = IsAny extends true ? true : [MarkerKindOf] extends [NonBindableKind] ? false : true; /** * Subset of `keyof C & string` whose value is statically eligible for binding * from a string source (path / query / header) — i.e. NOT a multimodal or * unstructured marker (`s.multimodal(...)` / `s.unstructuredText(...)` / * `s.unstructuredBinary(...)`), which carry rich payloads. Full * string-bindability (rejecting struct-shaped schemas etc.) still depends on the * runtime AST inspection in `runtime.ts`. */ type BindableKeys = { [K in keyof C & string]: IsBindable extends true ? K : never; }[keyof C & string]; /** * Resolves to `HttpMountSpec` when every id field of `Id` is present in * `V` (the mount path's `{var}` names), else to `HttpMountSpec & * Invalid<"…">`. The intersection surfaces a readable `[InvalidBrand]: "mount * path missing var '…'"` requirement that no real spec value can satisfy, so the * `defineAgent` assignment fails with a clear message. * * Mirrors (defence-in-depth) the runtime "every mount var is an id field" loop * in `runtime.ts`. */ type MountSpecCovering = [ Exclude ] extends [never] ? HttpMountSpec : HttpMountSpec & Invalid<`mount path missing var '${Exclude & string}'`>; declare const WebhookVarsValidBrand: unique symbol; /** * Compile-time gate for webhook-suffix path variables. Returns `unknown` (a * no-op intersection at the assignment site) when every `{var}` in the webhook * suffix is an agent id field that is itself bindable (i.e. not a multimodal / * unstructured marker — see {@link BindableKeys}). On violation, resolves to a * carrier that no real value can satisfy, surfacing a readable error: * - when a suffix `{var}` IS an id field but that field is a non-bindable * marker, the message says it refers to a multimodal/unstructured id field; * - when a suffix `{var}` is not an id field at all, the message says it does * not match any agent id field. */ type WebhookVarsValid = [WebhookVars] extends [never] ? unknown : [Exclude>] extends [never] ? unknown : [Exclude] extends [never] ? { readonly [WebhookVarsValidBrand]: `webhook-suffix var '${Exclude> & string}' refers to a multimodal/unstructured id field and cannot be bound from a path variable`; } : { readonly [WebhookVarsValidBrand]: `webhook-suffix var '${Exclude & string}' does not match any agent id field`; }; /** * Structured shape of an endpoint's bound parameter names, broken down by * binding source. Carried as a phantom on {@link HttpEndpointSpec} so * {@link NoDuplicateBindings} can detect a parameter bound from more than one * source within the same endpoint. */ interface EndpointBound { readonly path: ReadonlyArray; readonly query: ReadonlyArray; readonly header: ReadonlyArray; } /** * Default ("unknown") `Bound` value used when no per-source tracking is * available (e.g. the wide `HttpEndpointSpec` used by the runtime validators). * Each slot is a non-tuple `ReadonlyArray`, so {@link NoDuplicateBindings} * short-circuits to `unknown` and the runtime check remains canonical. */ interface EndpointBoundAny extends EndpointBound { readonly path: ReadonlyArray; readonly query: ReadonlyArray; readonly header: ReadonlyArray; } type AllBoundNames = readonly [ ...B['path'], ...B['query'], ...B['header'] ]; type FindFirstDuplicate, Seen extends ReadonlyArray = readonly []> = T extends readonly [infer Head extends string, ...infer Tail extends ReadonlyArray] ? IncludesString extends true ? Head : FindFirstDuplicate : never; /** * Compile-time gate ensuring a single endpoint binds a given method parameter * from at most one of path / query / header. Resolves to `unknown` when every * name is unique or a slot is a non-tuple array (deferring to the runtime * check); to {@link Invalid} when a name appears in more than one slot. */ type NoDuplicateBindings = FindFirstDuplicate> extends infer D ? [D] extends [never] ? unknown : D extends string ? Invalid<`endpoint binds parameter '${D}' more than once across path/query/header`> : unknown : unknown; type _NoCaseFoldDup, Seen extends ReadonlyArray = readonly []> = Hs extends readonly [infer Head extends string, ...infer Tail extends ReadonlyArray] ? string extends Head ? unknown : IncludesString> extends true ? Invalid<`endpoint declares header '${Head}' more than once (case-insensitive)`> : _NoCaseFoldDup]> : unknown; /** * Compile-time gate ensuring a single endpoint does not declare the same header * twice when names are compared case-insensitively (HTTP header names are * case-insensitive on the wire). Resolves to `unknown` when unique or the tuple * widens to a non-tuple array; to {@link Invalid} on the first collision. */ type NoCaseFoldDuplicates> = _NoCaseFoldDup; type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; type LastOf = UnionToIntersection U : never> extends () => infer L ? L : never; /** * Convert a union of string literals to a readonly tuple. When `U` widens to * `string`, resolves to a non-tuple `ReadonlyArray` so downstream tuple * walkers short-circuit and defer to runtime checks. */ type UnionToTuple> = string extends U ? ReadonlyArray : [U] extends [never] ? readonly [] : Last extends string ? readonly [...UnionToTuple>, Last] : ReadonlyArray; /** * Tuple of header-name keys extracted from an endpoint's `headers` record. Empty * / widened records degrade to `ReadonlyArray` so the case-fold walker * short-circuits and defers to the runtime check. */ type HeaderKeysTuple = [H[keyof H]] extends [never] ? readonly [] : string extends keyof H ? ReadonlyArray : [keyof H & string] extends [never] ? readonly [] : UnionToTuple; /** * Header values extracted from `H`, used as the seed for the structured * `Bound["header"]` slot. Empty (`ValuesOf` = `never`) resolves to `readonly * []`; otherwise a non-tuple `ReadonlyArray<…>`. */ type HeaderValuesArray>> = [ValuesOf] extends [ never ] ? readonly [] : ReadonlyArray>; /** * Keys of `Params` that are auto-injected `s.principal()` parameters. These carry * no wire value (the host injects the caller principal), so they are NOT supplied * by an HTTP/RPC caller and are exempt from the bodyless "every param must be * bound" rule. */ type AutoInjectedKeys$1 = { [K in keyof C & string]: [MarkerKindOf] extends ['principal'] ? K : never; }[keyof C & string]; type ValidateEndpointStructure = B extends EndpointBound ? HN extends ReadonlyArray ? NoDuplicateBindings extends infer R1 ? [R1] extends [Invalid] ? R1 : NoCaseFoldDuplicates extends infer R2 ? [R2] extends [Invalid] ? R2 : E : E : E : E : E; /** * Positional validator for the `http` array of a `method({...})` call: for each * endpoint, enforce (in order) the bodyless-unbound-param check, then the * cross-source duplicate-binding check, then the case-fold header check. A * failing element is replaced with an {@link Invalid} carrier at that position. */ type ValidateEndpointsTuple>, Params> = { readonly [K in keyof Eps]: Eps[K] extends HttpEndpointSpec ? Kind extends 'bodyless' ? [Exclude>] extends [never] ? ValidateEndpointStructure : Invalid<`GET/HEAD endpoint cannot have unbound param '${Exclude> & string}' (only path / query / header bindings are allowed because there is no request body)`> : ValidateEndpointStructure : Eps[K]; }; /** * Single-endpoint variant of {@link ValidateEndpointsTuple} for the `method` * factory's non-array `http` form. Wraps the spec in a one-tuple, validates, and * unwraps. */ type ValidateSingleEndpoint, Params> = ValidateEndpointsTuple extends readonly [infer R] ? R : Ep; /** Build a literal path segment, e.g. `http.literal('counters')`. */ declare const literal: (value: string) => PathSegment; /** Build a path-variable segment, e.g. `http.pathVar('name')` → `{name}`. */ declare const pathVar: (variableName: string) => PathSegment; /** Build a catch-all (remaining-path) variable segment; only valid last. */ declare const restVar: (variableName: string) => PathSegment; /** `{agent-type}` — runtime-injected by the host. */ declare const agentType: () => PathSegment; /** `{agent-version}` — runtime-injected by the host. */ declare const agentVersion: () => PathSegment; /** A path: either a `{var}`-template string or an array of segment builders. */ type PathInput = string | readonly PathSegment[]; /** Explicit phantom UUID selection. Omission of an optional selector selects the original. */ type PhantomIdSpec = { readonly source: 'path'; readonly name: N; readonly optional: boolean; } | { readonly source: 'query'; readonly name: N; readonly optional: boolean; }; /** Select an exact phantom UUID scoped to this agent's constructor. */ declare const phantomId: { path: (name: N, options?: { readonly optional?: boolean; }) => { readonly source: "path"; readonly name: N; readonly optional: boolean; }; query: (name: N, options?: { readonly optional?: boolean; }) => { readonly source: "query"; readonly name: N; readonly optional: boolean; }; }; type PhantomPathName = S extends { readonly source: 'path'; readonly name: infer N; } ? N : never; /** A method input or output value exposed as a named durable stream. */ interface DurableStreamSlotOptions { readonly source: 'input' | 'output'; readonly slot: string; readonly name?: string; readonly contentType?: string; } /** Optional per-stream admission limits for a durable stream route. */ interface DurableStreamRouteLoadOptions { readonly maxConcurrentReadersPerStream?: number; readonly maxAppendRequestsPerSecondPerStream?: number; } /** Durable stream metadata attached to an HTTP endpoint. */ interface DurableStreamRouteOptions { readonly slots: readonly DurableStreamSlotOptions[]; readonly allowExternalWrites?: boolean; readonly allowStreamDelete?: boolean; readonly allowInvocationDelete?: boolean; readonly load?: DurableStreamRouteLoadOptions; } /** * The HTTP verbs supported by the Golem host. Standard verbs are the lowercase * literals; `{ custom: 'VERB' }` carries a non-standard verb verbatim through * to the WIT `http-method.custom(string)`. */ type HttpVerb = 'get' | 'head' | 'post' | 'put' | 'delete' | 'connect' | 'options' | 'trace' | 'patch' | { readonly custom: string; }; declare const mountVarsBrand: unique symbol; declare const mountWebhookVarsBrand: unique symbol; declare const endpointVarsBrand: unique symbol; declare const endpointKindBrand: unique symbol; declare const endpointBoundBrand: unique symbol; declare const endpointHeaderNamesBrand: unique symbol; /** * Whether an endpoint's HTTP verb permits a request body. `get` / `head` are * `"bodyless"`; every other verb (and `custom`) is `"bodyful"`. Used as a * phantom on {@link HttpEndpointSpec} so `method({...})` can statically reject a * bodyless endpoint whose bindings do not cover every method parameter. */ type EndpointKind = 'bodyless' | 'bodyful'; /** * Mount declaration carried by `defineAgent({ http })`. Compiled to the WIT * `agent-type.http-mount` (`http-mount-details`) at registration time via * {@link compileMount}. * * `MountVars` is the union of `{var}` names in the mount path (system vars * stripped); `WebhookVars` the union of `{var}` names in the optional * `webhookSuffix`. Both are phantom — see the block comment above. */ interface HttpMountSpec { readonly [mountVarsBrand]?: MountVars; readonly [mountWebhookVarsBrand]?: WebhookVars; /** Mount path prefix; a `{var}` template string or segment builders. */ readonly path: PathInput; /** When `true`, every endpoint requires authentication. Default `false`. */ readonly auth?: boolean; /** CORS allowed-origin patterns advertised at the mount level. */ readonly cors?: readonly string[]; /** Mark this agent as a phantom agent (fresh instance per request). */ readonly phantomAgent?: boolean; readonly phantomId?: PhantomIdSpec; /** Ordered live file mappings, only for durable non-phantom agents. */ readonly exposeFiles?: readonly FileExposure[]; /** Response headers applied by the host when serving exposed files. */ readonly fileResponseHeaders?: FileResponseHeaders; /** Optional custom webhook-suffix path (same rules as the mount path). */ readonly webhookSuffix?: PathInput; } /** * Endpoint declaration carried by `method({ http })`. Compiled to one entry of * `agent-method.http-endpoint` (`http-endpoint-details`) via * {@link compileEndpoint}. * * `EndpointVars` is the union of every name the endpoint binds (path + query + * header value); `Kind` tracks bodyless/bodyful; `Bound` is the structured * `{ path; query; header }` tuple view (for duplicate-binding detection); * `HeaderNames` is the tuple of declared header names (for case-fold * uniqueness). All four are phantom — see the block comment above. */ interface HttpEndpointSpec> { readonly [endpointVarsBrand]?: EndpointVars; readonly [endpointKindBrand]?: Kind; readonly [endpointBoundBrand]?: Bound; readonly [endpointHeaderNamesBrand]?: HeaderNames; /** HTTP verb; standard lowercase literal or `{ custom }`. */ readonly method: HttpVerb; /** * Endpoint path relative to the mount prefix. As a template string it may * include `{var}` / `{*rest}` segments and an inline `?key={var}&…` query. */ readonly path: PathInput; /** Map of HTTP header name → method-parameter (variable) name. */ readonly headers?: Readonly>; /** * Query-param bindings. Either via the inline `?…` of a template `path`, or * explicitly as a map of query-param name → method-parameter name. */ readonly query?: Readonly>; /** Override the mount-level auth requirement for this endpoint only. */ readonly auth?: boolean; /** Additional CORS allowed-origin patterns for this endpoint. */ readonly cors?: readonly string[]; /** Durable streams exposed by this endpoint. Omit to use platform defaults. */ readonly durableStreams?: DurableStreamRouteOptions; } /** * Default value for the `H` (headers) generic. An "empty record" sentinel that * signals "no header bindings"; using `{}` directly would widen `ValuesOf` to * `string`. */ type NoHeaderBindings = Readonly>; /** * Options accepted by the verb factories and `custom`. `H` is the header * name → method-parameter map; `Q` is the explicit query-param → method-parameter * map. Both maps' VALUES are the bound method-parameter names. */ interface EndpointOptsFor> = NoHeaderBindings, Q extends Readonly> = NoHeaderBindings> { /** Map of HTTP header name → method-parameter name. */ readonly headers?: H; /** * Explicit query-param name → method-parameter name map. Its VALUES are * threaded into the endpoint's `EndpointVars` (so binding to a non-parameter * errors) and into the structured `Bound.query` tuple (so it participates in * cross-source duplicate-binding detection), on par with the inline * `?k={var}` form. Use `as const` to preserve the literal values. */ readonly query?: Q; /** Override the mount-level auth requirement for this endpoint only. */ readonly auth?: boolean; /** Additional CORS allowed-origin patterns for this endpoint. */ readonly cors?: readonly string[]; /** Durable streams exposed by this endpoint. Omit to use platform defaults. */ readonly durableStreams?: DurableStreamRouteOptions; } /** Escape-hatch (segment-array) form options: maps un-parameterised. */ type EndpointSugarOpts = EndpointOptsFor>, Readonly>>; /** Tuple of method-parameter names bound by an explicit `query` map's VALUES. */ type QueryValuesTuple>> = UnionToTuple>; /** The branded endpoint spec produced for a literal path `P`, headers `H`, query `Q`. */ type EndpointSpecFor

>, Q extends Readonly>, Kind extends EndpointKind> = HttpEndpointSpec | QueryVarsOf

, SystemVariableName> | ValuesOf | ValuesOf, Kind, { readonly path: PathTupleOf

; readonly query: readonly [...QueryTupleOf

, ...QueryValuesTuple]; readonly header: HeaderValuesArray; }, HeaderKeysTuple>; /** Overloaded verb-factory shape, parameterised by {@link EndpointKind}. */ interface VerbFactory { > = NoHeaderBindings, Q extends Readonly> = NoHeaderBindings>(path: ValidEndpointPath

, opts?: EndpointOptsFor): EndpointSpecFor; (path: readonly PathSegment[], opts?: EndpointSugarOpts): HttpEndpointSpec; } /** Shorthand for `{ method: 'get', path, ...opts }`. Bodyless. */ declare const get: VerbFactory<"bodyless">; /** Shorthand for `{ method: 'head', path, ...opts }`. Bodyless. */ declare const head: VerbFactory<"bodyless">; /** Shorthand for `{ method: 'post', path, ...opts }`. Bodyful. */ declare const post: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'put', path, ...opts }`. Bodyful. */ declare const put: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'delete', path, ...opts }`. Bodyful. */ declare const del: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'patch', path, ...opts }`. Bodyful. */ declare const patch: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'options', path, ...opts }`. Bodyful. */ declare const options: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'connect', path, ...opts }`. Bodyful. */ declare const connect: VerbFactory<"bodyful">; /** Shorthand for `{ method: 'trace', path, ...opts }`. Bodyful. */ declare const trace: VerbFactory<"bodyful">; /** Overloaded factory shape for {@link custom} (always bodyful). */ interface CustomFactory { > = NoHeaderBindings, Q extends Readonly> = NoHeaderBindings>(verb: string, path: ValidEndpointPath

, opts?: EndpointOptsFor): EndpointSpecFor; (verb: string, path: readonly PathSegment[], opts?: EndpointSugarOpts): HttpEndpointSpec; } /** Shorthand for a custom (non-standard) verb. Always bodyful. */ declare const custom: CustomFactory; /** Options accepted by {@link mount}. */ interface MountOptionsFor { /** When `true`, the host treats every endpoint as authentication-required. */ readonly auth?: boolean; /** CORS allowed-origin patterns advertised at the mount level. */ readonly cors?: readonly string[]; /** Mark this agent as a phantom agent (one fresh instance per HTTP request). */ readonly phantomAgent?: boolean; readonly phantomId?: S; /** Ordered live file mappings, only for durable non-phantom agents. */ readonly exposeFiles?: readonly FileExposure[]; /** Response headers applied by the host when serving exposed files. */ readonly fileResponseHeaders?: FileResponseHeaders; /** * Optional custom webhook suffix path. Validated with the same * {@link ValidMountPath} rules as the mount path; a non-literal `string` * (default `W = string`) reduces the constraint to plain `string` and is * enforced by the runtime parser. */ readonly webhookSuffix?: string extends W ? string : ValidMountPath; } /** Escape-hatch (segment-array) form options for {@link mount}. */ type MountSugarOpts = MountOptionsFor & { readonly webhookSuffix?: PathInput; }; /** Overloaded factory shape for {@link mount}. */ interface MountFactory { (path: ValidMountPath

, opts?: MountOptionsFor & (string extends P ? unknown : Exclude, Exclude, SystemVariableName>> extends never ? unknown : Invalid<'phantom path selector must name a mount capture'>)): HttpMountSpec, SystemVariableName | PhantomPathName>, Exclude, SystemVariableName>>; (path: readonly PathSegment[], opts?: MountSugarOpts): HttpMountSpec; } /** * Declare an HTTP mount for an agent. Convenience constructor; equivalent to * writing the `HttpMountSpec` object literal directly. The template-string form * binds the path `{var}` names into the `MountVars` phantom (and any * `webhookSuffix` `{var}` names into `WebhookVars`) so `defineAgent` can check * coverage against the agent id. */ declare const mount: MountFactory; /** Return a copy of a mount/endpoint spec with `auth` set. */ declare function withAuth(spec: T, auth: boolean): T; /** Return a copy of a mount/endpoint spec with the CORS pattern list replaced. */ declare function withCors(spec: T, ...patterns: string[]): T; /** Return a copy of a mount spec with the webhook suffix set. */ declare function withWebhookSuffix(spec: HttpMountSpec, webhookSuffix: PathInput): HttpMountSpec; /** Compile an {@link HttpMountSpec} to the WIT `http-mount-details` record. */ declare function compileMount(spec: HttpMountSpec): HttpMountDetails; /** Compile a single {@link HttpEndpointSpec} to a WIT `http-endpoint-details`. */ declare function compileEndpoint(spec: HttpEndpointSpec): HttpEndpointDetails; /** Collect the `path-variable` names referenced by a list of path segments. */ declare function pathVariableNames(segments: readonly PathSegment[]): Set; type http_CustomFactory = CustomFactory; type http_DurableStreamRouteLoadOptions = DurableStreamRouteLoadOptions; type http_DurableStreamRouteOptions = DurableStreamRouteOptions; type http_DurableStreamSlotOptions = DurableStreamSlotOptions; type http_EndpointBound = EndpointBound; type http_EndpointBoundAny = EndpointBoundAny; type http_EndpointKind = EndpointKind; type http_EndpointOptsFor> = NoHeaderBindings, Q extends Readonly> = NoHeaderBindings> = EndpointOptsFor; type http_HeaderKeysTuple = HeaderKeysTuple; type http_HttpEndpointSpec> = HttpEndpointSpec; type http_HttpMountSpec = HttpMountSpec; type http_HttpVerb = HttpVerb; type http_MountFactory = MountFactory; type http_MountOptionsFor = MountOptionsFor; type http_NoCaseFoldDuplicates> = NoCaseFoldDuplicates; type http_NoDuplicateBindings = NoDuplicateBindings; type http_NoHeaderBindings = NoHeaderBindings; type http_PathInput = PathInput; declare const http_PathSegment: typeof PathSegment; type http_PhantomIdSpec = PhantomIdSpec; type http_UnionToTuple> = UnionToTuple; type http_ValidEndpointPath = ValidEndpointPath; type http_ValidMountPath = ValidMountPath; type http_VerbFactory = VerbFactory; declare const http_agentType: typeof agentType; declare const http_agentVersion: typeof agentVersion; declare const http_compileEndpoint: typeof compileEndpoint; declare const http_compileMount: typeof compileMount; declare const http_connect: typeof connect; declare const http_custom: typeof custom; declare const http_del: typeof del; declare const http_get: typeof get; declare const http_head: typeof head; declare const http_literal: typeof literal; declare const http_mount: typeof mount; declare const http_options: typeof options; declare const http_patch: typeof patch; declare const http_pathVar: typeof pathVar; declare const http_pathVariableNames: typeof pathVariableNames; declare const http_phantomId: typeof phantomId; declare const http_post: typeof post; declare const http_put: typeof put; declare const http_restVar: typeof restVar; declare const http_trace: typeof trace; declare const http_withAuth: typeof withAuth; declare const http_withCors: typeof withCors; declare const http_withWebhookSuffix: typeof withWebhookSuffix; declare namespace http { export { http_PathSegment as PathSegment, http_agentType as agentType, http_agentVersion as agentVersion, http_compileEndpoint as compileEndpoint, http_compileMount as compileMount, http_connect as connect, http_custom as custom, http_del as del, http_get as get, http_head as head, http_literal as literal, http_mount as mount, http_options as options, http_patch as patch, http_pathVar as pathVar, http_pathVariableNames as pathVariableNames, http_phantomId as phantomId, http_post as post, http_put as put, http_restVar as restVar, http_trace as trace, http_withAuth as withAuth, http_withCors as withCors, http_withWebhookSuffix as withWebhookSuffix }; export type { http_CustomFactory as CustomFactory, http_DurableStreamRouteLoadOptions as DurableStreamRouteLoadOptions, http_DurableStreamRouteOptions as DurableStreamRouteOptions, http_DurableStreamSlotOptions as DurableStreamSlotOptions, http_EndpointBound as EndpointBound, http_EndpointBoundAny as EndpointBoundAny, http_EndpointKind as EndpointKind, http_EndpointOptsFor as EndpointOptsFor, http_HeaderKeysTuple as HeaderKeysTuple, http_HttpEndpointSpec as HttpEndpointSpec, http_HttpMountSpec as HttpMountSpec, http_HttpVerb as HttpVerb, http_MountFactory as MountFactory, http_MountOptionsFor as MountOptionsFor, http_NoCaseFoldDuplicates as NoCaseFoldDuplicates, http_NoDuplicateBindings as NoDuplicateBindings, http_NoHeaderBindings as NoHeaderBindings, http_PathInput as PathInput, http_PhantomIdSpec as PhantomIdSpec, http_UnionToTuple as UnionToTuple, http_ValidEndpointPath as ValidEndpointPath, http_ValidMountPath as ValidMountPath, http_VerbFactory as VerbFactory }; } type InputRecord = Record; declare const MethodHasHttp: unique symbol; /** Whether a final method value definitely declares at least one HTTP endpoint. */ type MethodHasHttpOf = M extends { readonly http: readonly []; } ? false : M extends { readonly http: undefined; } ? false : M extends { readonly http: HttpEndpointSpec | ReadonlyArray; } ? true : typeof MethodHasHttp extends keyof M ? M extends MethodSpec ? HasHttp : false : false; /** * Fine-grained read-only configuration for a method (surfaced as the WIT * `agent-method.read-only` / `read-only-config`). * * - `cache`: the caching policy for the read-only result — * - `'no-cache'`: never cache; * - `'until-write'`: cache until a mutating (non-read-only) method runs — this * is the policy used when `readOnly` is set to the convenience boolean `true`; * - `{ ttlNanos }`: cache for the given time-to-live (nanoseconds). * The cache key includes the caller principal when the method declares a direct * `s.principal()` input parameter. */ type ReadOnlyOption = { cache?: 'no-cache' | 'until-write' | { ttlNanos: bigint; }; }; /** * The structural contract of one method: an input parameter record + a * success-value schema. `Output` is a phantom used only for handler inference. * * The optional metadata fields surface on the WIT `agent-method` record: * `description` → `description`, `promptHint` → `prompt-hint`, and `readOnly` * → `read-only`. A bare `true` selects `until-write` caching; a direct * `s.principal()` input enables per-principal caching. */ interface MethodSpec { readonly input: Input; readonly returns: StandardSchemaV1; /** Type-only marker used to require an agent-level HTTP mount. */ readonly [MethodHasHttp]?: HasHttp; /** Human-readable description, surfaced as `agent-method.description`. */ readonly description?: string; /** Optional `prompt-hint`, surfaced as `agent-method.prompt-hint`. */ readonly promptHint?: string; /** * Marks the method as read-only (surfaced as `agent-method.read-only`). * `true` uses the `until-write` cache policy; pass a {@link ReadOnlyOption} * for `no-cache` / `ttl` caching. A direct `s.principal()` input automatically * enables per-principal caching. */ readonly readOnly?: boolean | ReadOnlyOption; /** * HTTP endpoint(s) exposing this method. Each is compiled to one * `agent-method.http-endpoint` (`http-endpoint-details`) record. Requires the * agent to declare a `http` mount on `defineAgent`. */ readonly http?: HttpEndpointSpec | HttpEndpointSpec[]; } /** * Declare an agent method. `input` is a record of Standard Schema values (one * per parameter); `returns` is the success-value schema. Use `z.void()` (or the * equivalent) for methods with no return value. * * Optional `description` / `promptHint` / `readOnly` metadata is threaded into * the assembled WIT `agent-method`. * * **Compile-time guarantees on `http`** (literal `http.get('/…')` etc. call * shapes only): every path / query / header `{var}` must be a method input * parameter name ({@link BindableKeys}); a bodyless `get` / `head` endpoint may * not leave any input parameter unbound (there is no request body to carry it); * a parameter may be bound from at most one of path / query / header; and header * names must be unique case-insensitively. Non-literal / segment-array forms * widen and defer to the runtime checks in `runtime.ts`. * * ```ts * method({ input: { by: z.number() }, returns: z.number() }) * method({ input: {}, returns: z.number(), readOnly: true }) * ``` */ declare function method>>>(spec: { input: Input; returns: StandardSchemaV1; description?: string; promptHint?: string; readOnly?: boolean | ReadOnlyOption; http: ValidateEndpointsTuple; }): MethodSpec & { readonly http: ValidateEndpointsTuple; }; declare function method>>(spec: { input: Input; returns: StandardSchemaV1; description?: string; promptHint?: string; readOnly?: boolean | ReadOnlyOption; http: ValidateSingleEndpoint; }): MethodSpec & { readonly http: ValidateSingleEndpoint; }; declare function method>> = readonly []>(spec: { input: Input; returns: StandardSchemaV1; description?: string; promptHint?: string; readOnly?: boolean | ReadOnlyOption; http?: ValidateEndpointsTuple; }): MethodSpec; declare function method> = HttpEndpointSpec>>(spec: { input: Input; returns: StandardSchemaV1; description?: string; promptHint?: string; readOnly?: boolean | ReadOnlyOption; http?: ValidateSingleEndpoint; }): MethodSpec; type InferRecord$1> = { [K in keyof R]: StandardSchemaV1.InferOutput; }; /** The async remote signature for a durable method spec (no-arg when caller input is empty). */ type DurableRemoteMethodFor = M extends MethodSpec ? keyof CallerInput extends never ? { (options?: RemoteCallOptions): Promise; /** Fire-and-forget; no result is awaited. */ trigger(): void; /** Enqueue at `at`, returning a token to cancel it before it runs. */ schedule(at: Datetime$1): CancellationToken; } : { (input: InferRecord$1>, options?: RemoteCallOptions): Promise; trigger(input: InferRecord$1>): void; /** Enqueue at `at`, returning a token to cancel it before it runs. */ schedule(at: Datetime$1, input: InferRecord$1>): CancellationToken; } : never; /** Result of invoking an ephemeral agent, including its per-invocation identity. */ interface EphemeralInvocationResult { metadata: InvocationMetadata; value: T; } /** The async remote signature for an ephemeral method spec. */ type EphemeralRemoteMethodFor = M extends MethodSpec ? keyof CallerInput extends never ? { (options?: RemoteCallOptions): Promise>; trigger(): InvocationMetadata; schedule(at: Datetime$1): CancelableScheduledInvocationReceipt; } : { (input: InferRecord$1>, options?: RemoteCallOptions): Promise>; trigger(input: InferRecord$1>): InvocationMetadata; schedule(at: Datetime$1, input: InferRecord$1>): CancelableScheduledInvocationReceipt; } : never; /** Options for an awaited remote call. */ interface RemoteCallOptions { signal?: AbortSignal; /** * A scope card for this call. It replaces the client's default scope card; * `null` sends no scope card. The call borrows the card: the callee holds its * authority until the invocation ends, and the caller keeps the card. A scope * card is valid only during the invocation that derived it. */ scopeCard?: ScopeCard | null; } /** Options for a remote client. */ interface RemoteClientOptions { /** * The default scope card for every awaited call of the client. Each call * borrows the card; `trigger` and `schedule` never send a scope card. A scope * card is valid only during the invocation that derived it, so a client with * a default scope card is too: later awaited calls fail with `denied`. */ scopeCard?: ScopeCard; } /** A typed remote client: one async method per declared method on the def. */ type RemoteClient = { [K in keyof Methods]: Mode extends 'ephemeral' ? EphemeralRemoteMethodFor : DurableRemoteMethodFor; }; /** A newly generated phantom client together with its reusable phantom id. */ interface PhantomClientDetails { readonly client: RemoteClient; readonly agentId: ParsedAgentId; readonly phantomId: Uuid; } /** Address existing agents or create a fresh phantom agent client. */ type ConfigObjectShapeOf$1 = S extends { readonly shape: infer Shape; } ? Shape : S extends { readonly entries: infer Shape; } ? Shape : S extends { readonly fields: infer Shape; } ? Shape : never; type ConfigOverrideField = MarkerKindOf extends 'secret' ? never : [ConfigObjectShapeOf$1] extends [never] ? S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : never : ConfigOverrides, ConfigSpec>>; /** Typed, partial non-secret values used when an RPC caller creates a worker. Existing workers retain their initial configuration. */ type ConfigOverrides = { readonly [K in keyof Config]?: ConfigOverrideField; }; interface RemoteClientFactory { /** Address the durable agent with this constructor identity. */ get(id: InferRecord$1>, config?: ConfigOverrides, options?: RemoteClientOptions): RemoteClient; /** Address a known phantom instance. */ getPhantom(id: InferRecord$1>, phantomId: Uuid, config?: ConfigOverrides, options?: RemoteClientOptions): RemoteClient; /** Create a client with a newly generated phantom id. */ newPhantom(id: InferRecord$1>, config?: ConfigOverrides, options?: RemoteClientOptions): PhantomClientDetails; } /** Creates logical ephemeral clients whose final identity is allocated per invocation. */ interface EphemeralRemoteClientFactory { /** Address a known ephemeral phantom instance. */ getPhantom(id: InferRecord$1>, phantomId: Uuid, config?: ConfigOverrides, options?: RemoteClientOptions): RemoteClient; /** Create a logical client whose final identity is returned by each invocation. */ newPhantom(id: InferRecord$1>, config?: ConfigOverrides, options?: RemoteClientOptions): RemoteClient; } type FullAgentClientFactory = Mode extends 'ephemeral' ? EphemeralRemoteClientFactory : RemoteClientFactory; type FullAgentClientSpec = { readonly name: string; readonly id: Id; readonly methods: Methods; readonly config?: Config; } & (Mode extends 'ephemeral' ? { readonly mode: 'ephemeral'; } : { readonly mode?: 'durable'; }); interface MethodOnlyAgentClientSpec { readonly methods: Methods; readonly name?: never; readonly id?: never; readonly config?: never; readonly mode?: never; } /** * Build a typed client definition without registering or implementing an agent. * Its Standard Schema inputs may come from any schema library supported by the SDK. */ declare function defineAgentClient(spec: FullAgentClientSpec): FullAgentClientDefinition; declare function defineAgentClient(spec: FullAgentClientSpec): FullAgentClientDefinition; declare function defineAgentClient(spec: MethodOnlyAgentClientSpec): MethodOnlyAgentClientDefinition; /** * The agent's config spec: a single record of named fields, each a * Standard Schema (Zod / Valibot / ArkType / Effect Schema). Mark a field (at * any depth) with `s.secret(inner)` to make it a secret (declared to the host as * `secret`); any other leaf is a plain local field. */ type ConfigSpec = Record; /** An opaque application-owned part. Names are case-sensitive, not paths. */ interface SnapshotPart { readonly bytes: Uint8Array; readonly contentType: string; } /** Whole-buffer snapshot projection, independent of resource-bearing live state. */ interface MultipartSnapshot { readonly state: State; readonly parts: ReadonlyMap; } declare class SnapshotError extends Error { constructor(message: string); } /** Require a named part with a bare MIME type; returns its checked bytes. */ declare function requirePart(parts: ReadonlyMap, name: string, expectedContentType: string): Uint8Array; declare const Snapshot: { requirePart: typeof requirePart; }; type IdRecord = Record; type MethodsRecord = Record>; type MethodsHaveHttp = true extends { [K in keyof Methods]: MethodHasHttpOf; }[keyof Methods] ? true : false; /** * Recover the field-schema record of an OBJECT schema, or `never` for a * non-object. Vendor-agnostic structural detection: Zod exposes the field * schemas under `.shape`, Valibot under `.entries`, Effect Schema under * `.fields`. Non-object schemas (primitives, arrays, unions, maps, markers) * carry none of these, so they resolve to `never` and are typed by their * `InferOutput` (read whole), matching the runtime flattening scope. */ type ConfigObjectShapeOf = S extends { readonly shape: infer Sh; } ? Sh : S extends { readonly entries: infer Sh; } ? Sh : S extends { readonly fields: infer Sh; } ? Sh : never; /** * Deep view of a single config field's schema `S`: * - a secret marker (at any depth) → a lazy {@link Secret} handle over its inner * type (call `.get()` for the value); * - an object schema → recurse field-by-field (each field deeply transformed); * - anything else (primitive / union / array / map / scalar marker) → its * decoded `InferOutput` value, read whole. */ type ConfigFieldView = MarkerKindOf extends 'secret' ? Secret> : [ConfigObjectShapeOf] extends [never] ? OutputOf : { readonly [K in keyof ConfigObjectShapeOf]: ConfigFieldView[K]>; }; /** `InferOutput` guarded for the unconstrained recursion parameter. */ type OutputOf = S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : unknown; /** * The typed view of an agent's config on `this.config` / `InitContext.config`: * one property per declared field, deeply transformed by {@link ConfigFieldView} * (secrets → {@link Secret} handles at any depth; nested objects recursed). * Accessing an undeclared field is a compile error. Defaults to `{}` (no config). */ type ConfigView = { readonly [K in keyof C]: ConfigFieldView; }; type InferRecord> = { [K in keyof R]: StandardSchemaV1.InferOutput; }; /** Keys whose values are supplied by the host rather than an RPC caller. */ type AutoInjectedKeys> = { [K in keyof R & string]: [MarkerKindOf] extends ['principal'] ? K : never; }[keyof R & string]; /** The schema fields an RPC caller supplies after host-injected fields are removed. */ type CallerInput> = Omit>; /** The handler signature inferred for a method spec (no-arg when input is empty). */ type HandlerFor$1 = M extends MethodSpec ? keyof Input extends never ? () => Output | Promise : (input: InferRecord) => Output | Promise : never; /** SDK helpers available on a handler's `this` (alongside state). */ interface AgentContext { /** * Read identity through the durable host environment on every call. * Replay reproduces the historical observation; live reads after a fork * identify the child, including within the same invocation. Identity values * explicitly stored in application state are not rewritten. */ getId(): ParsedAgentId; /** Read the phantom ID from the current durable identity observation. */ getPhantomId(): Uuid | undefined; getPrincipal(): Principal; /** * The agent's config accessor: one fresh-reading getter per declared field. * Local fields read their decoded value directly; secret fields yield a lazy * {@link Secret} handle (call `.get()`). See {@link ConfigView}. */ readonly config: ConfigView; } interface InitContext { readonly id: InferRecord; readonly principal: Principal; readonly phantomId: Uuid | undefined; /** The agent's config accessor (see {@link AgentContext.config}). */ readonly config: ConfigView; } /** Context supplied when constructing an agent from a snapshot. */ interface SnapshotRestoreContext extends InitContext { readonly agentId: ParsedAgentId; } type AgentImplementation = { init: (ctx: InitContext) => State | Promise; /** One handler per declared method; `this` is bound to `State` + SDK helpers. */ methods: { [K in keyof Methods]: HandlerFor$1; } & ThisType>; } & (HasSnapshotState extends StandardSchemaV1 ? { /** Explicit projection and fresh-state restoration; ordinary init is skipped. */ snapshot: { save: (this: State & AgentContext) => MultipartSnapshot> | Promise>>; load: (this: void, saved: MultipartSnapshot>, ctx: SnapshotRestoreContext) => State | Promise; }; } : { /** Custom byte hooks, or a restoration factory for automatic typed saving. */ snapshot?: { load: (this: void, bytes: Uint8Array, ctx: SnapshotRestoreContext) => State | Promise; } & (HasSnapshotState extends true ? { save?: (this: State & AgentContext) => Uint8Array | Promise; } : { save: (this: State & AgentContext) => Uint8Array | Promise; }); }); interface AgentImpl { readonly name: string; } interface FullAgentClientShape { readonly name: string; readonly id: Id; readonly methods: Methods; readonly mode: Mode; /** The agent's config schema used to encode RPC config overrides. */ readonly config?: Config; } interface MethodOnlyAgentClientDefinition extends AgentClientBinding, readonly AgentConfigEntry[]> { readonly methods: Methods; } interface FullAgentClientDefinition extends FullAgentClientShape { /** Construct the environment-scoped identity for an agent addressed by this definition. */ readonly agentId: Mode extends 'ephemeral' ? (id: InferRecord>, phantomId: Uuid) => ParsedAgentId : (id: InferRecord>, phantomId?: Uuid) => ParsedAgentId; /** A client factory compiled from this definition's local schemas. */ readonly client: FullAgentClientFactory; [bindAgentClient](agentId: ParsedAgentId, config?: ConfigOverrides, options?: RemoteClientOptions): RemoteClient; } interface AgentDefinition extends FullAgentClientDefinition { /** Supply the runtime behaviour. Registers the agent at module-load time. */ implement)>(impl: AgentImplementation): AgentImpl; } /** * When the executor should snapshot, mapped to the WIT `snapshotting` variant: * - `'disabled'` → `disabled` * - `'default'` → `enabled(default)` * - `{ periodicSeconds }` → `enabled(periodic(duration))` * - `{ everyNInvocations }` → `enabled(every-n-invocation(u16))` */ type SnapshotPolicy = 'disabled' | 'default' | { periodicSeconds: number; } | { everyNInvocations: number; }; /** * Snapshotting configuration. Use `{ policy, state }` for automatic schema-driven * save and restoration. A bare {@link SnapshotPolicy} requires a custom * `snapshot: { save, load }` implementation when enabled. Explicit `{ multipart: * { state }, policy? }` always requires both hooks and keeps live state independent * of saved schema. Save returns schema input; load receives validated output. * Schema-backed snapshots preserve bigint values through lossless JSON encoding. * Hooks run unpersisted and must tolerate retries. Whole-buffer copies amplify * memory use; the host inline/blob threshold is not a snapshot size cap. */ type SnapshottingSpec = SnapshotPolicy | { policy?: SnapshotPolicy; state: StateSchema; multipart?: never; } | { policy?: SnapshotPolicy; multipart: { state: StateSchema; }; state?: never; }; interface AgentSpecBase { /** The wire-level agent type name. */ name: string; id: Id; methods: Methods; /** Human-readable description, surfaced as `agent-type.description`. */ description?: string; /** Optional `prompt-hint`, surfaced as `agent-constructor.prompt-hint`. */ promptHint?: string; /** * Other agent definitions this agent depends on. Each is emitted as an * `agent-dependency` record built from the dependency's already-registered * `AgentType`. The dependency MUST have been `defineAgent`-ed before this one. */ dependencies?: AgentDefinition[]; /** Snapshotting policy; defaults to `'disabled'`. Surfaced as `agent-type.snapshotting`. */ snapshotting?: SnapshottingSpec; /** * Named config fields, one Standard Schema value each. Mark a field with * `s.secret(inner)` to declare it to the host as `secret`; any other * field is a plain local field. Surfaced as `agent-type.config` and typed on * `this.config` / `InitContext.config` via {@link ConfigView}. */ config?: Config; } type AgentModeSpec = { mode?: Mode; } & (Mode extends 'ephemeral' ? { mode: 'ephemeral'; } : { mode?: 'durable'; }); /** * HTTP mount for the agent: required when any method declares HTTP endpoints, * and optional otherwise. Literal `http.mount('/…')` calls additionally verify * that mount variables cover the id record and webhook variables name valid id * fields. Plain object-literal / segment-array forms defer those checks to the * runtime validation in `runtime.ts`. */ type AgentHttpSpec = MethodsHaveHttp extends true ? { http: MountSpecCovering & WebhookVarsValid; } : { http?: MountSpecCovering & WebhookVarsValid; }; type AgentSpec = AgentSpecBase & AgentModeSpec & AgentHttpSpec; /** * Define an agent. Registers the agent's `AgentType` metadata immediately (so * the host can discover it); the returned def's `.implement(...)` registers the * runtime initiator. * * ```ts * export const counterDef = defineAgent({ * name: 'counter', * id: { name: z.string() }, * methods: { * increment: method({ input: { by: z.number() }, returns: z.number() }), * current: method({ input: {}, returns: z.number() }), * }, * }); * * export const counterImpl = counterDef.implement({ * init: () => ({ count: 0 }), * methods: { * increment({ by }) { this.count += by; return this.count; }, * current() { return this.count; }, * }, * }); * ``` */ declare function defineAgent(spec: AgentSpec & { snapshotting: { policy?: SnapshotPolicy; multipart: { state: StateSchema; }; state?: never; }; }): AgentDefinition; declare function defineAgent(spec: AgentSpec & { snapshotting: { policy?: SnapshotPolicy; state: StateSchema; }; }): AgentDefinition; declare function defineAgent(spec: AgentSpec): AgentDefinition; interface HttpRouterOptions { readonly config?: Config; readonly description?: string; } interface HttpRouterContext { readonly config: ConfigView; } /** Original head alongside the normalized Web Request; the body has one reader. */ interface WebHttpRouterContext extends HttpRouterContext { readonly rawRequest: Omit, 'body'>; } type HttpRouterHandler = (request: Request, context: WebHttpRouterContext) => Response | Promise; type RawHttpRouterHandler = (request: HttpRequest>, context: HttpRouterContext) => HttpResponse> | Promise>>; interface HttpRouterBuilder { mount(path: string, options?: { readonly auth?: boolean; readonly cors?: readonly string[]; readonly fileResponseHeaders?: FileResponseHeaders; }): HttpRouterBuilder; static(route: string, path: string): HttpRouterBuilder; openApi(provider: (context: HttpRouterContext) => unknown | Promise, options?: { readonly methodName?: string; }): HttpRouterBuilder; /** Finalize registration; omit the handler for static/provider-only or empty routers. */ implement(handler?: HttpRouterHandler, options?: { readonly methodName?: string; }): AgentImpl; /** Canonical streaming API, without Fetch method, URL, status, or header normalization. */ implementRaw(handler: RawHttpRouterHandler, options?: { readonly methodName?: string; }): AgentImpl; } /** Define a parameterless ephemeral HTTP router using the ordinary agent runtime. */ declare function defineHttpRouter(name: string, options?: HttpRouterOptions): HttpRouterBuilder; /** Replace the canonical header sequence; validation errors surface during owned conversion. */ declare function withRawHeaders(response: Response, headers: readonly HttpHeader[]): Response; declare function registerSchemaWalker(vendor: string, walker: SchemaWalker): void; /** Registered vendors (for diagnostics). */ declare function registeredVendors(): string[]; /** * Compile a Standard Schema value into a {@link SchemaCodec} via its vendor * walker. Seeds a fresh {@link RecursionRegistry} so self- and mutually-recursive * schemas (e.g. a `Tree`) close to a named `ref` def instead of infinite-looping; * the registry is threaded through the recursive walk (see {@link compileSchemaWith}). */ declare function compileSchema(schema: unknown): SchemaCodec; /** Values substituted for fields omitted from a record's canonical JSON object. */ type RecordFieldDefaults = ReadonlyMap; type JsonValue = null | boolean | number | string | JsonValue[] | { readonly [key: string]: JsonValue; }; interface SchemaIssue { readonly message: string; readonly path: readonly (string | number)[]; } type SchemaValidationResult = { readonly success: true; readonly value: T; } | { readonly success: false; readonly issues: readonly SchemaIssue[]; }; declare class SchemaRef { readonly graph: SchemaGraph; readonly root: SchemaType; private readonly fieldDefaults?; constructor(graph: SchemaGraph, root?: SchemaType); /** * @internal Build a view over definitions already owned and frozen by the SDK. * * `fieldDefaults` applies only to the JSON surface of an inline root record: canonical JSON * may omit those fields, and the rendered JSON Schema does not require them. Packed values * always contain every field of the record. */ static fromImmutableGraph(graph: SchemaGraph, root: SchemaType, fieldDefaults?: RecordFieldDefaults): SchemaRef; validateJson(value: JsonValue): SchemaValidationResult; validateValue(value: SchemaValue): SchemaValidationResult; /** Pack canonical JSON and validate it against the complete schema. */ packJson(value: JsonValue): SchemaValue; unpackJson(value: SchemaValue): JsonValue; toJsonSchema(options?: { includeDraftMarker?: boolean; }): JsonValue; } declare class SchemaRenderError extends TypeError { readonly path: readonly (string | number)[]; constructor(message: string, path?: readonly (string | number)[]); } type ToolInputStream = ReadableStream; declare class ToolStreamError extends Error { readonly failure: ByteStreamFailure; constructor(failure: ByteStreamFailure); } type SettledToolResult = { readonly status: 'fulfilled'; readonly value: Result; } | { readonly status: 'rejected'; readonly reason: unknown; }; interface CollectedToolInvocation { readonly result: SettledToolResult; readonly stdout: SettledToolResult; readonly stderr: SettledToolResult; } interface StartedToolInvocation { readonly stdout?: ReadableStream; readonly stderr?: ReadableStream; readonly result: Promise; cancel(): void; /** Stop result delivery without cancelling the invocation or either output. */ detachResult(): void; collect(): Promise>; } declare function settleToolResult(result: PromiseLike): Promise>; declare function mapSettledToolResult(settledResult: SettledToolResult | PromiseLike>, mapValue: (value: Input) => Result | PromiseLike, mapReason?: (reason: unknown) => unknown): Promise>; declare function resultFromSettledToolResult(settledResult: SettledToolResult | PromiseLike>): Promise; declare function startedToolInvocation(stdout: AsyncIterable | undefined, stderr: AsyncIterable | undefined, settledResult: Promise>, cancel: () => void): StartedToolInvocation; /** A metadata-time value kept with the codec that gives it its wire meaning. */ interface CodecValue { readonly codec: SchemaCodec; readonly value: T; } interface ExtendedCommandNode { readonly name: string; readonly aliases: readonly string[]; readonly doc: Doc; readonly globals: ExtendedGlobals; readonly subcommands: readonly ExtendedCommandNode[]; readonly body?: ExtendedCommandBody; /** Reconcile this independently built subtree root against strict ancestor globals. */ readonly reconcileInheritedGlobals?: true; } interface ExtendedGlobals { readonly options: readonly ExtendedOptionSpec[]; readonly flags: readonly FlagSpec[]; } interface ExtendedCommandBody { readonly positionals: ExtendedPositionals; readonly options: readonly ExtendedOptionSpec[]; readonly flags: readonly FlagSpec[]; readonly constraints: readonly ExtendedConstraint[]; readonly stdin?: StreamSpec; readonly stdout?: StreamSpec; readonly stderr?: StreamSpec; readonly result?: ExtendedResultSpec; readonly errors: readonly ExtendedErrorCase[]; readonly annotations?: CommandAnnotations; } interface ExtendedPositionals { readonly fixed: readonly ExtendedPositional[]; readonly tail?: ExtendedTailPositional; } interface ExtendedPositional { readonly name: string; readonly doc: Doc; readonly valueName?: string; readonly codec: SchemaCodec; readonly default?: CodecValue; readonly required: boolean; readonly acceptsStdio: boolean; } interface ExtendedTailPositional { readonly name: string; readonly doc: Doc; readonly valueName?: string; readonly itemCodec: SchemaCodec; readonly min: number; readonly max?: number; readonly separator?: string; readonly verbatim: boolean; readonly acceptsStdio: boolean; } interface ExtendedOptionSpec { readonly long: string; readonly short?: string; readonly aliases: readonly string[]; readonly doc: Doc; readonly valueName?: string; readonly shape: ExtendedOptionShape; readonly default?: CodecValue; readonly required: boolean; readonly envVar?: string; } type ExtendedOptionShape = { readonly tag: 'scalar'; readonly codec: SchemaCodec; } | { readonly tag: 'optional-scalar'; readonly codec: SchemaCodec; } | { readonly tag: 'repeatable-list'; readonly repetition: Repetition; readonly itemCodec: SchemaCodec; } | { readonly tag: 'repeatable-map'; readonly repetition: Repetition; readonly mapCodec: SchemaCodec; readonly valueCodec: SchemaCodec; readonly duplicateKeyPolicy: DuplicateKeyPolicy; }; interface ExtendedResultSpec { readonly codec: SchemaCodec; readonly doc: Doc; readonly formatters: readonly Formatter[]; readonly defaultFormatter: string; } interface ExtendedErrorCase { readonly name: string; readonly doc: Doc; readonly kind: ErrorKind; readonly exitCode: number; readonly payloadCodec?: SchemaCodec; } type ExtendedValueIsLiteral = { readonly tag: 'deferred'; readonly value: unknown; } | { readonly tag: 'resolved'; readonly codec: SchemaCodec; readonly value: unknown; readonly schemaValue: SchemaValue; }; type ExtendedRef = { readonly tag: 'present'; readonly name: string; } | { readonly tag: 'value-is'; readonly name: string; readonly value: ExtendedValueIsLiteral; }; type ExtendedConstraint = { readonly tag: 'requires-all'; readonly refs: readonly ExtendedRef[]; } | { readonly tag: 'all-or-none'; readonly refs: readonly ExtendedRef[]; } | { readonly tag: 'requires-any'; readonly refs: readonly ExtendedRef[]; } | { readonly tag: 'mutex-groups'; readonly groups: readonly (readonly ExtendedRef[])[]; } | { readonly tag: 'implies'; readonly lhsQuant: Quantifier; readonly lhs: readonly ExtendedRef[]; readonly rhsQuant: Quantifier; readonly rhs: readonly ExtendedRef[]; } | { readonly tag: 'forbids'; readonly lhsQuant: Quantifier; readonly lhs: readonly ExtendedRef[]; readonly rhs: readonly ExtendedRef[]; }; type EffectiveCommandField = { readonly tag: 'option'; readonly option: ExtendedOptionSpec; } | { readonly tag: 'flag'; readonly flag: FlagSpec; }; interface CanonicalInputField { readonly name: string; readonly aliases: readonly string[]; readonly codec: SchemaCodec; readonly optionalCarrier?: true; } interface CanonicalInputValue { readonly name: string; readonly aliases: readonly string[]; readonly codec: SchemaCodec; readonly optionalCarrier?: true; readonly value: unknown; readonly schemaValue: SchemaValue; } /** Ordered canonical record codec shared by invocation and typed clients. */ declare class CanonicalInputModel { readonly fields: readonly CanonicalInputField[]; readonly codec: SchemaCodec; constructor(fields: readonly CanonicalInputField[]); encode(input: Record): SchemaValue; encodeTyped(input: Record): TypedSchemaValue; /** Encode the ordinary invocation carrier without allocating the owned schema-value model. */ encodeWire(input: Record): { graph: golem_core_types_2_0_0.SchemaGraph; value: golem_core_types_2_0_0.SchemaValueTree; }; encodeWireForStartedInvocation(input: Record): { graph: golem_core_types_2_0_0.SchemaGraph; value: golem_core_types_2_0_0.SchemaValueTree; } | Promise; encodeWireAsync(input: Record): Promise<{ graph: golem_core_types_2_0_0.SchemaGraph; value: golem_core_types_2_0_0.SchemaValueTree; }>; decode(input: SchemaValue): Record; decodeValues(input: SchemaValue): CanonicalInputValue[]; /** * Project fields decoded by another canonical model into this model's field * identities. Schema values cross ownership boundaries and are decoded with * the target codec so each independently registered tool receives its native * value representation. */ projectValues(input: readonly CanonicalInputValue[]): CanonicalInputValue[]; /** Rebuild this model's positional record from fields decoded by another canonical model. */ forwardValues(input: readonly CanonicalInputValue[]): TypedSchemaValue; } type ToolHelpArgumentKind = 'global-option' | 'global-flag' | 'positional' | 'tail' | 'option' | 'flag'; interface ToolHelpArgument { readonly kind: ToolHelpArgumentKind; readonly name: string; readonly short?: string; readonly aliases: readonly string[]; readonly doc: Doc; readonly required?: boolean; readonly valueName?: string; readonly default?: CodecValue; readonly envVar?: string; readonly acceptsStdio?: boolean; readonly min?: number; readonly max?: number; readonly separator?: string; readonly verbatim?: boolean; readonly flagDefault?: boolean; readonly negatable?: boolean; readonly countMax?: number; } interface ToolHelpProjection { readonly command: ExtendedCommandNode; readonly commandPath: readonly string[]; readonly arguments: readonly ToolHelpArgument[]; readonly subcommands: readonly ExtendedCommandNode[]; } declare class ExtendedToolType { readonly version: string; readonly root: ExtendedCommandNode; readonly requiresFilesystem: boolean; constructor(version: string, root: ExtendedCommandNode, requiresFilesystem?: boolean); get toolName(): string; /** Resolve a root-excluded command path by canonical name or alias. */ commandByPath(commandPath: readonly string[], requireBody?: boolean): ExtendedCommandNode | undefined; /** Return the root-to-node object path, guarding against malformed cycles. */ pathTo(target: ExtendedCommandNode): readonly ExtendedCommandNode[] | undefined; commandPath(target: ExtendedCommandNode): readonly string[] | undefined; effectiveGlobals(target: ExtendedCommandNode): EffectiveCommandField[]; canonicalInputFields(target: ExtendedCommandNode): CanonicalInputField[]; canonicalInputModel(target: ExtendedCommandNode): CanonicalInputModel; projectHelp(commandPath: readonly string[]): ToolHelpProjection | undefined; } interface ToolClientOptions { readonly transport?: ToolClientTransport$1; /** Stable leaf registration name when the definition describes an adapted presented surface. */ readonly lookupName?: string; } /** A caller-owned typed command definition; its commands may be a subset of the deployed tool. */ interface ToolClientDefinition { readonly name?: string; readonly definition: Definition; client(targetName?: string, options?: Omit): ToolClient; } /** Bind a partial typed tool definition without discovery or compatibility preflight. */ declare function toolClientDefinition(definition: Definition, name?: string): ToolClientDefinition; type ToolCallErrorCause = { readonly tag: 'rpc'; readonly error: ToolRpcError$1; } | { readonly tag: 'tool'; readonly error: Errors; } | { readonly tag: 'unknown-error'; readonly name: string; readonly payload: Parameters[1]['payload']; }; /** A stable rejected-promise error for remote tool calls. */ declare class ToolCallError extends Error { readonly cause: ToolCallErrorCause; constructor(cause: ToolCallErrorCause); } /** Assemble a typed runtime client using the ambient tool host by default. */ declare function client(definition: Definition, options?: ToolClientOptions): ToolClient; type CamelCase = Name extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize>}` : Name; type Simplify = { [Key in keyof Value]: Value[Key]; } & {}; type SchemaOutput = StandardSchemaV1.InferOutput; type SuccessOutput = [SchemaOutput] extends [void] ? undefined : SchemaOutput; type StreamPresence = 'none' | 'optional' | 'required'; declare const TAIL_ARGUMENT: unique symbol; declare const GLOBAL_SURFACES: unique symbol; declare const BODY_SURFACES: unique symbol; type AddArgument = Args & (Required extends true ? { [Key in CamelCase]: Value; } : { [Key in CamelCase]?: Value; }); interface ArgumentSurface { readonly name: Name; readonly aliases: Aliases; } type GlobalEntries = Globals extends { readonly [GLOBAL_SURFACES]: infer Entries; } ? Entries : never; type GlobalArguments = Omit; type OptionAliases = Options extends { readonly aliases: readonly (infer Alias)[]; } ? Extract : never; type AddGlobalArgument = AddArgument, Name, Value, Required> & { readonly [GLOBAL_SURFACES]: GlobalEntries | ArgumentSurface>; }; type SurfaceIdentifiers = Entry extends ArgumentSurface ? Name | Aliases : never; type CapturedGlobalNames = GlobalEntries extends infer Entry ? Entry extends ArgumentSurface ? Extract, SurfaceIdentifiers>> extends never ? never : CamelCase : never : never; type UncapturedGlobalEntries = GlobalEntries extends infer Entry ? Entry extends ArgumentSurface ? Extract, SurfaceIdentifiers>> extends never ? Entry : never : never : never; type ReconcileGlobalArguments = Omit, CapturedGlobalNames> & { readonly [GLOBAL_SURFACES]: UncapturedGlobalEntries; }; type MergeGlobalArguments = GlobalArguments & GlobalArguments & { readonly [GLOBAL_SURFACES]: GlobalEntries | GlobalEntries; }; type BodySurfaceEntries = Args extends { readonly [BODY_SURFACES]: infer Entries; } ? Entries : never; type BodyArguments = Omit; type AddBodyArgument = AddArgument, Name, Value, Required> & { readonly [BODY_SURFACES]: BodySurfaceEntries | ArgumentSurface; }; type CapturedBodyNames = BodySurfaceEntries extends infer Entry ? Entry extends ArgumentSurface ? Extract, SurfaceIdentifiers>> extends never ? never : CamelCase : never : never; type UncapturedBodyEntries = BodySurfaceEntries extends infer Entry ? Entry extends ArgumentSurface ? Extract, SurfaceIdentifiers>> extends never ? Entry : never : never : never; type ReconcileBodyArguments = Omit | typeof BODY_SURFACES> & { readonly [BODY_SURFACES]: UncapturedBodyEntries; }; type TailArgumentKey = Args extends { readonly [TAIL_ARGUMENT]: infer Key; } ? Extract : never; type NonTailBodyEntries = BodySurfaceEntries extends infer Entry ? Entry extends ArgumentSurface ? CamelCase extends TailArgumentKey ? never : Entry : never : never; type ReplaceTailArgument = Omit | typeof TAIL_ARGUMENT | typeof BODY_SURFACES> & { [Key in CamelCase]: Value; } & { readonly [TAIL_ARGUMENT]: CamelCase; readonly [BODY_SURFACES]: NonTailBodyEntries | ArgumentSurface; }; type PublicArguments = Omit; type HasDefault = Options extends { readonly default: unknown; } ? true : false; type IsRequired = Options extends { readonly required: infer Required; } ? Required extends true ? true : Required extends false ? false : Default : Default; type IsRepeatable = Options extends { readonly repeatable: RepeatableMode; } ? true : false; type OptionIsRequired = IsRepeatable extends true ? true : HasDefault extends true ? true : IsRequired; type PositionalIsRequired = HasDefault extends true ? true : IsRequired; type FlagValue = Options extends { readonly kind: 'count-flag'; } ? number : boolean; type SchemaProducesMap = SchemaOutput extends ReadonlyMap ? true : Schema extends { readonly keyType: unknown; readonly valueType: unknown; } ? true : false; type OptionValue = IsRepeatable extends true ? SchemaProducesMap extends true ? SchemaOutput : SchemaOutput[] : Options extends { readonly optionalScalar: true; } ? HasDefault extends true ? SchemaOutput : SchemaOutput | undefined : SchemaOutput; type StreamState = Options extends { readonly required: true; } ? 'required' : 'optional'; interface ToolBodyModel { readonly args: Args; readonly success: Success; readonly errors: Errors; readonly stdin: Stdin; readonly stdout: Stdout; readonly stderr: Stderr; } type AnyToolBodyModel = ToolBodyModel; interface ToolCommandModel { readonly name: Name; readonly globals: Globals; readonly body: Body; readonly children: Children; } interface ToolSubtreeModel { readonly ownership: 'subtree'; readonly command: Command; } type BodyModelOf = Builder extends BodyBuilder ? ToolBodyModel : never; type ToolCommandModelOf = Builder extends CommandBuilder ? ToolCommandModel : never; type BodyArgs = Body extends ToolBodyModel ? PublicArguments : {}; type BodySuccess = Body extends ToolBodyModel ? Success : never; type BodyErrors = Body extends ToolBodyModel ? Errors : never; type BodyStdin = Body extends ToolBodyModel ? Stdin : 'none'; type BodyStdout = Body extends ToolBodyModel ? Stdout : 'none'; type BodyStderr = Body extends ToolBodyModel ? Stderr : 'none'; type ReconcileBodyModel = Body extends ToolBodyModel ? ToolBodyModel, Success, Errors, Stdin, Stdout, Stderr> : Body; type StreamContextField = Presence extends 'required' ? { readonly [Key in Name]: Stream; } : Presence extends 'optional' ? { readonly [Key in Name]?: Stream; } : {}; type ToolInvocationContext = Simplify<{ readonly principal: Principal; } & StreamContextField<'stdin', Stdin, ReadableStream> & StreamContextField<'stdout', Stdout, WritableStream> & StreamContextField<'stderr', Stderr, WritableStream>>; interface ToolOk { readonly tag: 'ok'; readonly value: Value; } type ToolErr = [Payload] extends [never] ? { readonly tag: 'err'; readonly name: Name; readonly hasPayload: false; readonly payload?: never; } : { readonly tag: 'err'; readonly name: Name; readonly hasPayload: true; readonly payload: Payload; }; type ToolResult = ToolOk | Errors; declare function ok(value: Value): ToolOk; declare function err(name: Name): ToolErr; declare function err(name: Name, payload: Payload): ToolErr; type ToolHandler = (args: Simplify, context: Context) => ToolResult | Promise>; declare const COMMAND_IMPLEMENTATION: unique symbol; type NestedCommandImplementation = Children & { readonly [COMMAND_IMPLEMENTATION]: { readonly body: Body; readonly receiver: Children; }; }; declare function command(children: Children): NestedCommandImplementation; declare function command(body: Body, children: Children): NestedCommandImplementation; type HandlerFor = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? ToolHandler> & BodyArgs, BodySuccess, BodyErrors, ToolInvocationContext, BodyStdout, BodyStderr>> : never : never; type ChildImplementations = { [Name in keyof Children as Children[Name] extends ToolSubtreeModel ? never : Name]: NodeImplementation; } & { [Name in keyof Children as Children[Name] extends ToolSubtreeModel ? Name : never]?: never; }; type NodeImplementation = Model extends ToolCommandModel ? keyof Children extends never ? Body extends AnyToolBodyModel ? HandlerFor : NestedCommandImplementation : Body extends AnyToolBodyModel ? NestedCommandImplementation, ChildImplementations>> : NestedCommandImplementation>> : never; type RootImplementation = Model extends ToolCommandModel ? Simplify<(Body extends AnyToolBodyModel ? { [Key in Name]: HandlerFor; } : {}) & ChildImplementations> : never; type ToolImplementation = RootImplementation>; declare const TOOL_CLIENT_ERRORS: unique symbol; interface ToolClientMethod { (args: Simplify): Result; readonly [TOOL_CLIENT_ERRORS]: Errors; } type ToolClientErrors = Method extends { readonly [TOOL_CLIENT_ERRORS]: infer Errors; } ? Errors : never; type ClientStdin = StreamContextField<'stdin', BodyStdin, ToolInputStream>; type ClientResult = BodyStdout extends 'required' | 'optional' ? StartedToolInvocation> : BodyStderr extends 'required' | 'optional' ? StartedToolInvocation> : [BodySuccess] extends [undefined] ? Promise : Promise>; type ClientMethodFor = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? ToolClientMethod> & BodyArgs & ClientStdin, ClientResult, BodyErrors> : never : never; type ChildClients = { [Name in keyof Children]: NodeClient; }; type NodeClient = Model extends ToolSubtreeModel ? NodeClient : Model extends ToolCommandModel ? NodeClientWithGlobals : Globals, Reconcile extends true ? ReconcileBodyModel : Body, Children> : never; type NodeClientWithGlobals = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? ClientMethodFor, Inherited> & ChildClients> : ChildClients> : never; type RootClient = Model extends ToolCommandModel ? (Body extends AnyToolBodyModel ? { [Key in Name]: ClientMethodFor; } : {}) & ChildClients : never; type ToolClient = Simplify>>; type UnderlyingStdin = StreamContextField<'stdin', BodyStdin, AsyncIterable>; type ToolUnderlyingInvocation = { readonly result: Promise; cancel(): void; }; type UnderlyingInvocation = ToolUnderlyingInvocation> & (BodyStdout extends 'required' ? { readonly stdout: AsyncIterable; } : BodyStdout extends 'optional' ? { readonly stdout?: AsyncIterable; } : { readonly stdout?: never; }) & (BodyStderr extends 'required' ? { readonly stderr: AsyncIterable; } : BodyStderr extends 'optional' ? { readonly stderr?: AsyncIterable; } : { readonly stderr?: never; }); type UnderlyingOutputField = Presence extends 'required' ? { readonly [Key in Name]: AsyncIterable; } : Presence extends 'optional' ? { readonly [Key in Name]?: AsyncIterable; } : {}; type UnderlyingResult = BodyStderr extends 'required' | 'optional' ? ([BodySuccess] extends [undefined] ? {} : { result: BodySuccess; }) & UnderlyingOutputField<'stdout', BodyStdout> & UnderlyingOutputField<'stderr', BodyStderr> : BodyStdout extends 'required' ? [BodySuccess] extends [undefined] ? AsyncIterable : { result: BodySuccess; stdout: AsyncIterable; } : BodyStdout extends 'optional' ? [BodySuccess] extends [undefined] ? AsyncIterable | undefined : { result: BodySuccess; stdout?: AsyncIterable; } : [BodySuccess] extends [undefined] ? void : BodySuccess; type ToolUnderlyingMethod = { start(args: Simplify): Promise>; readonly [TOOL_CLIENT_ERRORS]: Errors; } & (BodyStdout extends 'none' ? BodyStderr extends 'none' ? (args: Simplify) => Promise> : {} : {}); type UnderlyingMethodFor = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? ToolUnderlyingMethod> & BodyArgs & UnderlyingStdin, Body, BodyErrors> : never : never; type UnderlyingChildClients = { [Name in keyof Children]: UnderlyingNodeClient; }; type UnderlyingNodeClient = Model extends ToolSubtreeModel ? UnderlyingNodeClient : Model extends ToolCommandModel ? UnderlyingNodeClientWithGlobals : Globals, Reconcile extends true ? ReconcileBodyModel : Body, Children> : never; type UnderlyingNodeClientWithGlobals = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? UnderlyingMethodFor, Inherited> & UnderlyingChildClients> : UnderlyingChildClients> : never; type RootUnderlyingClient = Model extends ToolCommandModel ? (Body extends AnyToolBodyModel ? { [Key in Name]: UnderlyingMethodFor; } : {}) & UnderlyingChildClients : never; type ToolUnderlying = Simplify>>; type ToolUnderlyingErrors = ToolClientErrors; type ToolMiddlewareInvocationContext = Simplify<{ readonly principal: Principal; readonly underlying: ToolUnderlying; readonly parameters: Parameters; } & StreamContextField<'stdin', Stdin, AsyncIterable>>; type ToolMiddlewareHandler = (args: Simplify, context: Context) => Result | Promise; type MiddlewareHandlerFor = Model extends ToolCommandModel ? Body extends AnyToolBodyModel ? ToolMiddlewareHandler> & BodyArgs, UnderlyingResult, ToolMiddlewareInvocationContext, Params>> : never : never; type MiddlewareChildImplementations = { [Name in keyof Children]: MiddlewareNodeImplementation; }; type MiddlewareNodeImplementation = Model extends ToolSubtreeModel ? MiddlewareNodeImplementation : Model extends ToolCommandModel ? MiddlewareNodeImplementationWithGlobals : Globals, Reconcile extends true ? ReconcileBodyModel : Body, Children, Params> : never; type MiddlewareNodeImplementationWithGlobals = Model extends ToolCommandModel ? keyof Children extends never ? Body extends AnyToolBodyModel ? MiddlewareHandlerFor, Inherited, UnderlyingDefinition, Params> : NestedCommandImplementation : Body extends AnyToolBodyModel ? NestedCommandImplementation, Inherited, UnderlyingDefinition, Params>, MiddlewareChildImplementations, UnderlyingDefinition, Params>> : NestedCommandImplementation, UnderlyingDefinition, Params>> : never; type RootMiddlewareImplementation = Model extends ToolCommandModel ? Simplify<(Body extends AnyToolBodyModel ? { [Key in Name]: MiddlewareHandlerFor; } : {}) & MiddlewareChildImplementations> : never; type ToolMiddlewareImplementation = RootMiddlewareImplementation, ExpectedDefinition, Parameters>; interface ImplementedToolMiddleware { readonly name: Name; } interface ToolMiddlewareMetadataOptions { readonly name: Name; readonly version?: string; readonly aliases?: readonly string[]; readonly doc?: DocInput; readonly parameterSchema?: StandardSchemaV1; } type ToolMiddlewareOptions> = TransparentToolMiddlewareOptions | AdapterToolMiddlewareOptions; type TransparentToolMiddlewareOptions> = ToolMiddlewareMetadataOptions & { readonly parameterSchema?: ParameterSchema; readonly wraps?: undefined; readonly implementation: ToolMiddlewareImplementation>; }; type AdapterToolMiddlewareOptions> = ToolMiddlewareMetadataOptions & { readonly parameterSchema?: ParameterSchema; readonly wraps: ExpectedDefinition; readonly implementation: ToolMiddlewareImplementation>; }; interface UniversalToolUnderlying { readonly invoke: UniversalToolUnderlyingInvoke; invokeAndAwait(commandPath: readonly string[], input: TypedSchemaValue$3, stdin: AsyncIterable | undefined): Promise; } interface UniversalToolUnderlyingInvoke { (commandPath: readonly string[], input: TypedSchemaValue$3, stdin: AsyncIterable | undefined): Promise & { readonly stdout?: AsyncIterable; readonly stderr?: AsyncIterable; }>; readonly [TOOL_CLIENT_ERRORS]: TypedSchemaValue$3; } interface UniversalToolMiddlewareInvocation { readonly toolName: string; readonly toolMetadata: Tool; readonly commandPath: readonly string[]; readonly input: TypedSchemaValue$3; readonly stdin?: AsyncIterable; readonly stdout?: ToolOutputWriter; readonly stderr?: ToolOutputWriter; readonly principal: Principal; } interface UniversalToolMiddlewareContext { readonly underlying: UniversalToolUnderlying; readonly parameters: Parameters; } type UniversalToolMiddlewareInvoke = (invocation: UniversalToolMiddlewareInvocation, context: UniversalToolMiddlewareContext) => InvocationResult | Promise; interface UniversalToolMiddlewareOptions> { readonly name: Name; readonly version?: string; readonly aliases?: readonly string[]; readonly doc?: DocInput; readonly parameterSchema?: ParameterSchema; readonly invoke: UniversalToolMiddlewareInvoke>; } interface ToolClientInvocationResult { readonly stdout?: AsyncIterable; readonly stderr?: AsyncIterable; readonly settledResult: Promise>; cancel(): void; } /** Raw WIT invocation seam used by typed tool clients. */ interface ToolClientTransport$1 { start(commandPath: readonly string[], input: TypedSchemaValue$3, stdin: ToolInputStream | undefined, stdout: boolean, stderr: boolean): ToolClientInvocationResult; } type ToolInvokeErrorCause = Exclude | { readonly tag: 'protocol-error'; readonly val: string; } | { readonly tag: 'denied'; readonly val: string; } | { readonly tag: 'internal-error'; readonly val: string; } | { readonly tag: 'cancelled'; } | { readonly tag: 'resource-exhausted'; readonly val: string; } | { readonly tag: 'tool'; readonly error: Errors; } | { readonly tag: 'unknown-error'; readonly name: string; readonly payload: TypedSchemaValue$3; }; declare class ToolInvokeError extends Error { readonly cause: ToolInvokeErrorCause; constructor(cause: ToolInvokeErrorCause); static tool(error: Errors): ToolInvokeError; mapTool(map: (error: Errors) => Mapped): ToolInvokeError; } interface ImplementedTool { readonly name: Name; } type ToolHelpError = { readonly tag: 'invalid-command-path'; readonly commandPath: readonly string[]; } | { readonly tag: 'invalid-argument-name'; readonly commandPath: readonly string[]; readonly argumentName: string; }; type ToolHelpResult = { readonly tag: 'ok'; readonly value: string; } | { readonly tag: 'err'; readonly error: ToolHelpError; }; type DocInput = string | Partial; type RepeatableMode = 'repeated' | 'delimited' | 'either'; interface SurfaceOptions { readonly short?: string; readonly aliases?: readonly string[]; readonly doc?: DocInput; readonly env?: string; } interface ValueOptions extends SurfaceOptions { readonly valueName?: string; readonly required?: boolean; } type RepeatableDefault = MapLike extends true ? Value : Value[]; type OptionOptions ? true : false> = (ValueOptions & { readonly repeatable?: undefined; readonly delim?: never; readonly default?: Value; readonly optionalScalar?: boolean; readonly duplicateKeyPolicy?: never; }) | (ValueOptions & { readonly repeatable: 'repeated'; readonly delim?: never; readonly default?: RepeatableDefault; readonly optionalScalar?: never; readonly duplicateKeyPolicy?: DuplicateKeyPolicy; }) | (ValueOptions & { readonly repeatable: 'delimited' | 'either'; readonly delim: string; readonly default?: RepeatableDefault; readonly optionalScalar?: never; readonly duplicateKeyPolicy?: DuplicateKeyPolicy; }); interface PositionalOptions { readonly doc?: DocInput; readonly valueName?: string; readonly required?: boolean; readonly default?: Value; readonly acceptsStdio?: boolean; } interface TailOptions { readonly doc?: DocInput; readonly valueName?: string; readonly min?: number; readonly max?: number; readonly separator?: string; readonly verbatim?: boolean; readonly acceptsStdio?: boolean; } interface BooleanFlagOptions extends SurfaceOptions { readonly kind?: 'flag'; readonly default?: boolean; readonly negatable?: boolean; readonly max?: never; } interface CountFlagOptions extends SurfaceOptions { readonly kind: 'count-flag'; readonly max?: number; readonly default?: never; readonly negatable?: never; } type FlagOptions = BooleanFlagOptions | CountFlagOptions; type GlobalValueOptions = OptionOptions & { readonly kind?: 'option'; }; type GlobalFlagOptions = Omit & { readonly kind: 'flag'; }; type GlobalCountFlagOptions = CountFlagOptions; interface StreamOptions { readonly doc?: DocInput; readonly mime?: readonly string[]; readonly required?: boolean; } type FormatterInput = string | ({ readonly name: string; } & Partial>); interface ReturnsOptions { readonly doc?: DocInput; readonly formatters?: readonly FormatterInput[]; readonly defaultFormatter?: string; } interface ErrorOptionsBase { readonly kind: 'usage' | 'runtime'; readonly exitCode: number; readonly doc?: DocInput; } type ErrorOptions$1 = ErrorOptionsBase & { readonly payload?: Payload; }; type ConstraintRef = ExtendedRef; type ToolConstraint = ExtendedConstraint; type ConstraintSide = ConstraintRef | readonly ConstraintRef[]; declare const c: { readonly present: (name: string) => ConstraintRef; readonly valueIs: (name: string, value: unknown) => ConstraintRef; readonly requiresAll: (values: readonly ConstraintRef[]) => ToolConstraint; readonly allOrNone: (values: readonly ConstraintRef[]) => ToolConstraint; readonly requiresAny: (values: readonly ConstraintRef[]) => ToolConstraint; readonly mutexGroups: (groups: readonly (readonly ConstraintRef[])[]) => ToolConstraint; readonly implies: (options: { readonly lhs: ConstraintSide; readonly rhs: ConstraintSide; readonly lhsQuant?: Quantifier; readonly rhsQuant?: Quantifier; }) => ToolConstraint; readonly forbids: (options: { readonly lhs: ConstraintSide; readonly rhs: ConstraintSide; readonly lhsQuant?: Quantifier; }) => ToolConstraint; }; declare class BodyBuilder { private readonly value; private constructor(); static start(): BodyBuilder; positional> = {}>(name: Name, schema: Schema, options?: Options): BodyBuilder, PositionalIsRequired>, Success, Errors, Stdin, Stdout, Stderr>; tail(name: Name, schema: Schema, options?: TailOptions): BodyBuilder[]>, Success, Errors, Stdin, Stdout, Stderr>; option, SchemaProducesMap> = {}>(name: Name, schema: Schema, options?: Options): BodyBuilder, OptionIsRequired, OptionAliases>, Success, Errors, Stdin, Stdout, Stderr>; flag(name: Name, options?: Options): BodyBuilder, true, OptionAliases>, Success, Errors, Stdin, Stdout, Stderr>; constraint(constraint: ToolConstraint): BodyBuilder; stdin(options: Options): BodyBuilder, Stdout, Stderr>; stdout(options: Options): BodyBuilder, Stderr>; stderr(options: Options): BodyBuilder>; returns(schema: Schema, options?: ReturnsOptions): BodyBuilder, Errors, Stdin, Stdout, Stderr>; error(name: Name, options: ErrorOptions$1): BodyBuilder, Stdin, Stdout, Stderr>; error(name: Name, options: ErrorOptions$1 & { readonly payload: Payload; }): BodyBuilder>, Stdin, Stdout, Stderr>; private next; build(): ExtendedCommandBody; } declare const BUILD_TOOL: unique symbol; type AnyToolDefinition = CommandBuilder; declare class CommandBuilder { readonly name: Name; private readonly node; private readonly toolVersion; private readonly commandAnnotations?; private readonly subtreeForwards; private readonly requiresFilesystem; private implemented; private compiled?; private constructor(); static root(name: Name, requiresFilesystem?: boolean): CommandBuilder; /** Construct the exact typed client owned by this tool definition. */ client(this: CommandBuilder, options?: ToolClientOptions): ToolClient>; private static child; version(this: CommandBuilder, version: string): CommandBuilder; doc(doc: DocInput): CommandBuilder; aliases(...aliases: readonly string[]): CommandBuilder; annotations(annotations: Partial): CommandBuilder; global, SchemaProducesMap> = {}>(name: ArgumentName, schema: Schema, options?: Options): CommandBuilder, OptionIsRequired, Options>, Body, Children, Root>; global, const Options extends GlobalFlagOptions>(name: ArgumentName, schema: Schema, options: Options): CommandBuilder, Body, Children, Root>; global(name: ArgumentName, options: Options): CommandBuilder, Body, Children, Root>; body>(build: (body: BodyBuilder) => Built): CommandBuilder, Children, Root>; command(name: ChildName, subtree: ToolDefinition): CommandBuilder>; }, Root>; command>(name: ChildName, build: (command: CommandBuilder) => Built): CommandBuilder; }, Root>; middleware>(this: CommandBuilder, options: TransparentToolMiddlewareOptions, ParameterSchema>): ImplementedToolMiddleware; middleware>(this: CommandBuilder, options: AdapterToolMiddlewareOptions, ExpectedDefinition, ParameterSchema>): ImplementedToolMiddleware; implement(this: CommandBuilder, implementation: ToolImplementation>): ImplementedTool; private next; private finalizeNode; [BUILD_TOOL](this: CommandBuilder): ExtendedToolType; } type ToolDefinition = CommandBuilder; declare function toolDefinition(name: Name, options?: { requiresFilesystem?: boolean; }): ToolDefinition; declare function universalToolMiddleware>(options: UniversalToolMiddlewareOptions): ImplementedToolMiddleware; declare function decodeDeclaredToolError(body: ExtendedCommandBody, wireError: Extract['val'], callName: string): Promise | ToolErr | ToolErr | { readonly tag: 'unknown-error'; readonly name: string; readonly payload: TypedSchemaValue$3; }; /** Render descriptor-based help for the root or a nested command. */ declare function renderHelp(definition: AnyToolDefinition, commandPath?: readonly string[]): ToolHelpResult; /** Render descriptor-based help for one argument at the selected command. */ declare function renderArgumentHelp(definition: AnyToolDefinition, commandPath: readonly string[], argumentName: string): ToolHelpResult; declare const golemTool010ToolMiddlewareGuest: typeof toolMiddlewareGuest$1; declare const toolMiddlewareGuest: typeof toolMiddlewareGuest$1; /** * Raised when any host call into `wasi:keyvalue@0.1.0` traps. The `trace` * field carries the verbatim driver-supplied string from the host's * `error.trace()` (or, for non-Error host throws, the stringified cause). Per * the Golem source this is opaque / driver-specific and should not be parsed. */ declare class KeyValueError extends Error { readonly cause: unknown; readonly name = "KeyValueError"; readonly trace: string; readonly operation: string; constructor(cause: unknown, operation: string); } /** * Schema-typed view of a {@link Bucket}. Values are validated against the * Standard Schema and JSON-encoded (UTF-8) on writes; reads JSON-parse and * re-validate. Decoding failures throw {@link KeyValueError}. */ interface SchemaBucket { get(key: string): T | undefined; set(key: string, value: T): void; delete(key: string): void; exists(key: string): boolean; getMany(keys: readonly string[]): Array; setMany(entries: ReadonlyArray): void; deleteMany(keys: readonly string[]): void; keys(): string[]; } /** * Handle on an open keyvalue bucket. Acquired via {@link openBucket}. The * underlying WIT `bucket` resource has no explicit close method; dropping the * JS handle is enough (GC-managed lifetime). * * All host calls are synchronous, so these methods return plain values rather * than Promises. */ interface Bucket { readonly name: string; /** Get the bytes stored under `key`, or `undefined` if absent. */ get(key: string): Uint8Array | undefined; /** Overwrite `key` with `value`, or insert if absent. */ set(key: string, value: Uint8Array): void; /** Remove `key`. No-op if absent. */ delete(key: string): void; /** Test whether `key` is present. */ exists(key: string): boolean; /** * Batch-get. Returned array length === `keys.length`; missing keys surface * as `undefined`, positionally aligned with the request. All-or-nothing: a * storage-layer error fails the whole call. */ getMany(keys: readonly string[]): Array; /** Batch-set. Per-entry order is not guaranteed; failure is partial. */ setMany(entries: ReadonlyArray): void; /** Batch-delete. Per-entry order is not guaranteed; failure is partial. */ deleteMany(keys: readonly string[]): void; /** All keys currently present in the bucket. Order undefined. */ keys(): string[]; /** * Build a schema-typed view of this bucket. Values are JSON-encoded via the * supplied Standard Schema on writes and re-validated on reads. */ forSchema(schema: S): SchemaBucket>; } /** * Open a bucket by name. The WIT bucket resource has no explicit close; the * returned handle's lifetime is GC-managed. Failures from the host's * `bucket.open-bucket` surface as {@link KeyValueError}. * * `openBucket` is async for API ergonomics, although the host call is * synchronous. */ declare function openBucket(name: string): Promise; /** * Raised when any host call into `wasi:blobstore/*` traps. The blobstore WIT * error type is a plain `string`, so {@link trace} carries it verbatim. */ declare class BlobstoreError extends Error { readonly cause: unknown; readonly name = "BlobstoreError"; readonly trace: string; readonly operation: string; constructor(cause: unknown, operation: string); } /** Object identifier — `(containerName, objectName)` pair. */ interface ObjectId { readonly container: string; readonly object: string; } /** * Container metadata. The WIT `created-at` `u64` is populated by the Golem * host as Unix milliseconds (it is actually `last_modified_at`; object stores * have no separate creation time). Exposed as both a JS `Date` and the raw * bigint. */ interface ContainerMetadata { readonly name: string; readonly createdAt: Date; readonly createdAtMillis: bigint; } /** Object metadata. Same `created-at` caveat as {@link ContainerMetadata}. */ interface ObjectMetadata { readonly name: string; readonly container: string; readonly createdAt: Date; readonly createdAtMillis: bigint; readonly size: bigint; } /** * Schema-typed view of a {@link Container}. Object bodies are JSON-encoded via * the supplied Standard Schema. */ interface SchemaContainer { getData(name: string): Promise; writeData(name: string, value: T): Promise; has(name: string): Promise; info(name: string): Promise; delete(name: string): Promise; } /** * Handle on an open blob container. Acquired via {@link createContainer}, * {@link getContainer} or {@link getOrCreateContainer}. GC-managed lifetime. */ interface Container { readonly name: string; /** Container metadata. */ info(): Promise; /** Remove all objects, leaving the container empty. */ clear(): Promise; /** * Read an object's bytes. With no range, the whole object is read. With an * explicit `[start, end]` range, both offsets are inclusive, and the read * gives an error when a byte of the range is not in the object. */ getData(name: string, start?: bigint, end?: bigint): Promise; /** Create or replace `name` with `data` (chunked at 4096 bytes per write). */ writeData(name: string, data: Uint8Array): Promise; /** True if the named object exists in this container. */ has(name: string): Promise; /** Metadata for the named object. Gives an error if the object does not exist. */ objectInfo(name: string): Promise; /** Delete the named object. Does NOT fail if it does not exist. */ delete(name: string): Promise; /** Delete multiple objects. */ deleteMany(names: readonly string[]): Promise; /** * All object names in this container. The Golem host eagerly snapshots the * full name list when `list-objects` is called and pins it to the oplog; * this drains the whole snapshot (page size 256). Order is not guaranteed. */ listObjects(): Promise; /** Build a schema-typed view of this container. */ forSchema(schema: S): SchemaContainer>; } /** Create a container if it does not exist, or open the existing container. */ declare function createContainer(name: string): Promise; /** Open an existing container by name. Gives an error if it does not exist. */ declare function getContainer(name: string): Promise; /** True if a container with the given name exists. */ declare function containerExists(name: string): Promise; /** * Open the named container, creating it first if it does not exist. * Container creation is idempotent, so this is the same operation as * {@link createContainer}. */ declare function getOrCreateContainer(name: string): Promise; /** Delete a container and all of its objects. */ declare function deleteContainer(name: string): Promise; /** Copy an object to the same or a different container. Overwrites the destination. */ declare function copyObject(src: ObjectId, dest: ObjectId): Promise; /** Move (rename) an object. Overwrites the destination. */ declare function moveObject(src: ObjectId, dest: ObjectId): Promise; /** * Raised when any host call into `golem:websocket/client@1.5.0` traps. The * `tag` mirrors the WIT `error` variant (`connection-failure` / `send-failure` * / `receive-failure` / `protocol-error` / `session-lost` / `closed` / `other`) when it can be * recovered from the thrown value, otherwise `undefined`. For a `closed` * error, {@link closeInfo} carries the host's close code / reason if present. */ declare class WebsocketError extends Error { readonly cause: unknown; readonly name = "WebsocketError"; readonly tag: WsClient.Error['tag'] | undefined; readonly operation: string; readonly closeInfo: WsClient.CloseInfo | undefined; constructor(cause: unknown, operation: string); } /** * A received WebSocket message — text or binary, mirroring the host * `golem:websocket/client.message` variant. */ type WebSocketMessage = { readonly tag: 'text'; readonly val: string; } | { readonly tag: 'binary'; readonly val: Uint8Array; }; /** Options for {@link connectWebsocket}. */ interface ConnectOptions { /** * Reconstruction behavior after recovery. Absence uses the host default. * @since 1.6.0 * @category models */ readonly reconstructionPolicy?: WsClient.ReconstructionPolicy | undefined; /** * Headers forwarded verbatim to the host's `connect(url, headers)` — auth * tokens, `Sec-WebSocket-Protocol` subprotocols, etc. */ readonly headers?: ReadonlyArray | undefined; } /** * Handle on an open WebSocket connection. Thin imperative wrapper over the host * `WebsocketConnection` resource. Call {@link close} when done; the host frees * the resource on close. */ interface WebSocketHandle { /** Send a text (`string`) or binary (`Uint8Array`) message. */ send(data: string | Uint8Array): void; /** Receive the next message, blocking until one is available. */ receive(): Promise; /** * Receive the next message, waiting up to `timeoutMs` milliseconds. Returns * `undefined` if the timeout expires before a message arrives. */ receiveWithTimeout(timeoutMs: number): Promise; /** Send a close frame with an optional code and reason. */ close(code?: number, reason?: string): void; } /** * Connect to a WebSocket server at `url` (`ws://` or `wss://`). The host's * `connect` is synchronous — it returns only after the handshake completes (or * fails), so there is no separate "open" event to await. Handshake failure * surfaces as {@link WebsocketError} (tag `connection-failure`). * * `connectWebsocket` is async for API ergonomics, although the host call is * synchronous. */ declare function connectWebsocket(url: string, options?: ConnectOptions): Promise; /** * Coarse classification of an RDBMS failure, derived from the host's tagged * `Error` variant (or from a JS-side {@link ParamEncodingError}), collapsed onto * a plain string union so callers can branch on the failure reason. */ type RdbmsErrorReason = 'param-encoding' | 'connection-failure' | 'query-parameter-failure' | 'query-execution-failure' | 'query-response-failure' | 'resource-lost' | 'authentication' | 'other'; /** * Thrown by any RDBMS operation when a host call traps, or when a JS * parameter cannot be encoded to the host's `DbValue`. The {@link reason} * carries the coarse classification; {@link trace} is the verbatim * driver-supplied detail string (opaque / driver-specific — do not parse). * * Driver modules re-export thin subclasses (`PostgresError`, `MySqlError`, * `IgniteError`) so callers can `instanceof`-narrow by driver. */ declare class RdbmsError extends Error { readonly cause: unknown; readonly name: string; readonly reason: RdbmsErrorReason; readonly trace: string; readonly operation: string; constructor(cause: unknown, operation: string, driver: string); } /** * How temporal values (timestamp/timestamptz/date/time) are decoded from rows. * * - `"raw"` (default): keep the raw struct from the host as-is. No precision * loss, but consumers must pattern-match on the struct shape. * - `"date"`: decode `timestamp` / `timestamptz` / `date` to a JS `Date` * (UTC). `time` / `timetz` stay raw because `Date` cannot hold them. */ type TemporalDecodeMode = 'raw' | 'date'; declare const PARAM_TAG: unique symbol; /** Tagged-value envelope produced by every `Pg`/`MySql`/`Ignite` helper. */ interface DbParam { readonly [PARAM_TAG]: true; readonly driver: string; readonly kind: T; readonly value: V; } type PgBound = { readonly tag: 'included'; readonly val: T; } | { readonly tag: 'excluded'; readonly val: T; } | { readonly tag: 'unbounded'; }; interface PgRange { readonly start: PgBound; readonly end: PgBound; } interface PgSparseVec { readonly dim: number; readonly indices: ReadonlyArray; readonly values: ReadonlyArray; } type PgRangeElementHint = 'int4' | 'int8' | 'num' | 'ts' | 'tstz' | 'date'; /** Ignite uuid — 36-char string, `{hi,lo}` struct, or `[hi,lo]` tuple. */ type IgniteUuid = string | { readonly hi: bigint; readonly lo: bigint; } | [bigint, bigint]; /** Raised when any `golem:rdbms/postgres@1.5.0` host call traps or a parameter * cannot be encoded. See {@link RdbmsError} for `reason` / `trace`. */ declare class PostgresError extends RdbmsError { readonly name = "PostgresError"; constructor(cause: unknown, operation: string); } /** A decoded result set: column metadata + decoded rows (as records). */ interface PgResultSet { /** Column metadata, in result order. */ readonly columns: ReadonlyArray<{ readonly ordinal: bigint; readonly name: string; readonly dbTypeName: string; }>; /** Rows decoded to `{ columnName: value }` records. */ readonly rows: ReadonlyArray>; } /** An open postgres transaction. `commit()` / `rollback()` finalize it. */ interface PgTransaction { query(sql: string, params?: ReadonlyArray): PgResultSet; queryValues(sql: string, params?: ReadonlyArray): Array>; execute(sql: string, params?: ReadonlyArray): number; run(sql: string, params?: ReadonlyArray): PgResultSet | number; commit(): Promise; rollback(): Promise; } /** An open postgres connection. The underlying WIT `DbConnection` resource has * no explicit close; {@link PgConnection.close} drops the JS handle (GC-managed * lifetime) so callers have an explicit lifecycle hook. */ interface PgConnection { /** Run a row-returning statement (`SELECT`, `RETURNING`, …). */ query(sql: string, params?: ReadonlyArray): Promise; /** Like {@link query} but returns positional value arrays (no column names). */ queryValues(sql: string, params?: ReadonlyArray): Promise>>; /** Run a non-row statement and return the affected-row count. */ execute(sql: string, params?: ReadonlyArray): Promise; /** Begin a transaction; returns a handle you must `commit()`/`rollback()`. */ begin(): Promise; /** * Run `fn` inside a transaction: commits on success, rolls back if `fn` * throws (re-throwing the original error). */ transaction(fn: (tx: PgTransaction) => Promise | A): Promise; /** Drop the connection handle (GC-managed; provided for symmetry). */ close(): void; } /** Options for {@link Postgres.open}. */ interface PgOpenOptions { /** How temporal values decode from rows. Defaults to `"raw"`. */ readonly decodeTemporal?: TemporalDecodeMode; } /** * Postgres entry point. `open` acquires a connection via the host's * `DbConnection.open(address)`; the remaining rich-type param helpers live on * the {@link Pg} namespace. */ declare const Postgres: { /** * Open a connection to `url` (e.g. `postgres://user:pass@host:5432/db`). * Async for API ergonomics although the host call is synchronous. Failures * throw {@link PostgresError}. */ open(url: string, options?: PgOpenOptions): Promise; }; /** * Explicit parameter wrappers for rich Postgres types. Use to override the * conservative default JS mapping, e.g. `conn.query(sql, [Pg.uuid(id), * Pg.jsonb({ a: 1 })])`. */ declare const Pg: { json: (value: unknown) => DbParam<"json", unknown>; jsonb: (value: unknown) => DbParam<"jsonb", unknown>; jsonpath: (value: string) => DbParam<"jsonpath", string>; xml: (value: string) => DbParam<"xml", string>; uuid: (value: string | { highBits: bigint; lowBits: bigint; }) => DbParam<"uuid", string | { highBits: bigint; lowBits: bigint; }>; array: (value: ReadonlyArray) => DbParam<"array", readonly unknown[]>; range: (value: PgRange, hint: PgRangeElementHint) => DbParam<"range", { range: PgRange; hint: PgRangeElementHint; }>; composite: (name: string, values: ReadonlyArray) => DbParam<"composite", { name: string; values: readonly unknown[]; }>; domain: (name: string, value: unknown) => DbParam<"domain", { name: string; value: unknown; }>; enumeration: (name: string, value: string) => DbParam<"enumeration", { name: string; value: string; }>; vector: (value: ReadonlyArray) => DbParam<"vector", readonly number[]>; halfvec: (value: ReadonlyArray) => DbParam<"halfvec", readonly number[]>; sparsevec: (value: PgSparseVec) => DbParam<"sparsevec", PgSparseVec>; numeric: (value: string) => DbParam<"numeric", string>; interval: (value: { months: number; days: number; microseconds: bigint; }) => DbParam<"interval", { months: number; days: number; microseconds: bigint; }>; inet: (value: unknown) => DbParam<"inet", unknown>; cidr: (value: unknown) => DbParam<"cidr", unknown>; macaddr: (value: unknown) => DbParam<"macaddr", unknown>; bit: (value: ReadonlyArray) => DbParam<"bit", readonly boolean[]>; varbit: (value: ReadonlyArray) => DbParam<"varbit", readonly boolean[]>; int2: (value: number) => DbParam<"int2", number>; int4: (value: number) => DbParam<"int4", number>; int8: (value: number | bigint) => DbParam<"int8", number | bigint>; float4: (value: number) => DbParam<"float4", number>; float8: (value: number) => DbParam<"float8", number>; text: (value: string) => DbParam<"text", string>; varchar: (value: string) => DbParam<"varchar", string>; bpchar: (value: string) => DbParam<"bpchar", string>; character: (value: number) => DbParam<"character", number>; oid: (value: number) => DbParam<"oid", number>; money: (value: bigint) => DbParam<"money", bigint>; bytea: (value: Uint8Array) => DbParam<"bytea", Uint8Array>; timestamp: (value: unknown) => DbParam<"timestamp", unknown>; timestamptz: (value: unknown) => DbParam<"timestamptz", unknown>; }; /** Raised when any `golem:rdbms/mysql@1.5.0` host call traps or a parameter * cannot be encoded. See {@link RdbmsError} for `reason` / `trace`. */ declare class MySqlError extends RdbmsError { readonly name = "MySqlError"; constructor(cause: unknown, operation: string); } /** A decoded result set: column metadata + decoded rows (as records). */ interface MySqlResultSet { readonly columns: ReadonlyArray<{ readonly ordinal: bigint; readonly name: string; readonly dbTypeName: string; }>; readonly rows: ReadonlyArray>; } /** An open mysql transaction. */ interface MySqlTransaction { query(sql: string, params?: ReadonlyArray): MySqlResultSet; queryValues(sql: string, params?: ReadonlyArray): Array>; execute(sql: string, params?: ReadonlyArray): number; run(sql: string, params?: ReadonlyArray): MySqlResultSet | number; commit(): Promise; rollback(): Promise; } /** An open mysql connection. */ interface MySqlConnection { query(sql: string, params?: ReadonlyArray): Promise; queryValues(sql: string, params?: ReadonlyArray): Promise>>; execute(sql: string, params?: ReadonlyArray): Promise; begin(): Promise; transaction(fn: (tx: MySqlTransaction) => Promise | A): Promise; close(): void; } /** Options for {@link MySql.open}. */ interface MySqlOpenOptions { readonly decodeTemporal?: TemporalDecodeMode; } /** MySQL entry point + rich-type param helpers. */ declare const MySql: { /** * Open a connection to `url` (e.g. `mysql://user:pass@host:3306/db`). Async * for ergonomics although the host call is synchronous. Throws * {@link MySqlError}. */ open(url: string, options?: MySqlOpenOptions): Promise; json: (value: unknown) => DbParam<"json", unknown>; enumeration: (value: string) => DbParam<"enumeration", string>; set: (value: string) => DbParam<"set", string>; bit: (value: ReadonlyArray) => DbParam<"bit", readonly boolean[]>; decimal: (value: string) => DbParam<"decimal", string>; year: (value: number) => DbParam<"year", number>; tinyint: (value: number) => DbParam<"tinyint", number>; smallint: (value: number) => DbParam<"smallint", number>; mediumint: (value: number) => DbParam<"mediumint", number>; int: (value: number) => DbParam<"int", number>; bigint: (value: number | bigint) => DbParam<"bigint", number | bigint>; tinyintUnsigned: (value: number) => DbParam<"tinyint-unsigned", number>; smallintUnsigned: (value: number) => DbParam<"smallint-unsigned", number>; mediumintUnsigned: (value: number) => DbParam<"mediumint-unsigned", number>; intUnsigned: (value: number) => DbParam<"int-unsigned", number>; bigintUnsigned: (value: number | bigint) => DbParam<"bigint-unsigned", number | bigint>; float: (value: number) => DbParam<"float", number>; double: (value: number) => DbParam<"double", number>; fixchar: (value: string) => DbParam<"fixchar", string>; varchar: (value: string) => DbParam<"varchar", string>; tinytext: (value: string) => DbParam<"tinytext", string>; text: (value: string) => DbParam<"text", string>; mediumtext: (value: string) => DbParam<"mediumtext", string>; longtext: (value: string) => DbParam<"longtext", string>; binary: (value: Uint8Array) => DbParam<"binary", Uint8Array>; varbinary: (value: Uint8Array) => DbParam<"varbinary", Uint8Array>; tinyblob: (value: Uint8Array) => DbParam<"tinyblob", Uint8Array>; blob: (value: Uint8Array) => DbParam<"blob", Uint8Array>; mediumblob: (value: Uint8Array) => DbParam<"mediumblob", Uint8Array>; longblob: (value: Uint8Array) => DbParam<"longblob", Uint8Array>; date: (value: unknown) => DbParam<"date", unknown>; time: (value: unknown) => DbParam<"time", unknown>; datetime: (value: unknown) => DbParam<"datetime", unknown>; timestamp: (value: unknown) => DbParam<"timestamp", unknown>; }; /** Raised when any `golem:rdbms/ignite2@1.5.0` host call traps or a parameter * cannot be encoded. See {@link RdbmsError} for `reason` / `trace`. */ declare class IgniteError extends RdbmsError { readonly name = "IgniteError"; constructor(cause: unknown, operation: string); } /** A decoded result set. Ignite columns carry only `ordinal` + `name`. */ interface IgniteResultSet { readonly columns: ReadonlyArray<{ readonly ordinal: bigint; readonly name: string; }>; readonly rows: ReadonlyArray>; } /** An open ignite transaction. */ interface IgniteTransaction { query(sql: string, params?: ReadonlyArray): IgniteResultSet; queryValues(sql: string, params?: ReadonlyArray): Array>; execute(sql: string, params?: ReadonlyArray): number; run(sql: string, params?: ReadonlyArray): IgniteResultSet | number; commit(): Promise; rollback(): Promise; } /** An open ignite connection. */ interface IgniteConnection { query(sql: string, params?: ReadonlyArray): Promise; queryValues(sql: string, params?: ReadonlyArray): Promise>>; execute(sql: string, params?: ReadonlyArray): Promise; begin(): Promise; transaction(fn: (tx: IgniteTransaction) => Promise | A): Promise; close(): void; } /** Options for {@link Ignite.open}. */ interface IgniteOpenOptions { readonly decodeTemporal?: TemporalDecodeMode; } /** Apache Ignite 2.x entry point + rich-type param helpers. */ declare const Ignite: { /** * Open a connection to `url` * (`ignite://[user:pass@]host:port[?pool_size=N&tls=true]`, default port * 10800). Async for ergonomics although the host call is synchronous. Throws * {@link IgniteError}. */ open(url: string, options?: IgniteOpenOptions): Promise; uuid: (value: IgniteUuid) => DbParam<"uuid", IgniteUuid>; decimal: (value: string) => DbParam<"decimal", string>; date: (value: bigint | number | Date) => DbParam<"date", number | bigint | Date>; timestamp: (millis: bigint | number, subMilliNanos: number) => DbParam<"timestamp", { millis: number | bigint; subMilliNanos: number; }>; time: (nanos: bigint | number) => DbParam<"time", number | bigint>; char: (codeUnit: number) => DbParam<"char", number>; byteArray: (value: Uint8Array) => DbParam<"byte-array", Uint8Array>; byte: (value: number) => DbParam<"byte", number>; short: (value: number) => DbParam<"short", number>; int: (value: number) => DbParam<"int", number>; long: (value: number | bigint) => DbParam<"long", number | bigint>; float: (value: number) => DbParam<"float", number>; double: (value: number) => DbParam<"double", number>; string: (value: string) => DbParam<"string", string>; boolean: (value: boolean) => DbParam<"boolean", boolean>; }; type SecretHandle = Secret$1; declare function secretHandleToSchemaValue(value: SecretHandle): SchemaValue; declare function secretHandleFromSchemaValue(value: SchemaValue): SecretHandle; declare function quotaTokenToSchemaValue(value: QuotaToken): SchemaValue; declare function quotaTokenFromSchemaValue(value: SchemaValue): QuotaToken; declare function permissionCardToSchemaValue(value: PermissionCard): SchemaValue; declare function permissionCardFromSchemaValue(value: SchemaValue): PermissionCard; declare function polymorphicPermissionCardToSchemaValue(value: PolymorphicPermissionCard): SchemaValue; declare function polymorphicPermissionCardFromSchemaValue(value: SchemaValue): PolymorphicPermissionCard; declare function typedSchemaValueConforms(expectedGraph: SchemaGraph, typed: TypedSchemaValue): boolean; /** Convert an ISO-8601 instant to the nanosecond-precise schema datetime shape. */ declare function datetimeFromISOString(value: string): Datetime; /** Convert a schema datetime to its canonical ISO-8601 UTC representation. */ declare function datetimeToISOString(value: Datetime): string; type ToolError = golem_core_types_2_0_0.ToolError; type ToolRpcError = golem_core_types_2_0_0.ToolRpcError; interface ToolInvocationResult { readonly result?: TypedSchemaValue; } interface RawToolInvocation { readonly stdout?: AsyncIterable; readonly stderr?: AsyncIterable; readonly settledResult: Promise>>>; cancel(): void; } interface ToolClientTransport { start(commandPath: readonly string[], input: Parameters[1], stdin: ToolInputStream | undefined, stdout: boolean, stderr: boolean): RawToolInvocation; } declare function createToolClientTransport(toolName: string, reflected?: boolean): ToolClientTransport; interface ToolClientRuntime { start(commandPath: readonly string[], input: TypedSchemaValue, stdin: ToolInputStream | undefined, stdout: boolean, stderr: boolean): { stdout?: AsyncIterable; stderr?: AsyncIterable; settledResult: Promise>; cancel(): void; }; } declare function createToolClientRuntime(toolName: string, transport?: ToolClientTransport): ToolClientRuntime; type ToolRuntimeError = { readonly tag: 'rpc'; readonly error: ToolRpcError; } | { readonly tag: 'tool'; readonly error: Declared; }; declare function isRpcError(value: unknown): value is ToolRpcError; declare function splitToolRpcError(error: ToolRpcError, decodeCustomError: (name: string, payload: TypedSchemaValue) => Declared): ToolRuntimeError; /** * Native guest bridge conversion boundary. `convert` must be synchronous: stream * moves and lifts performed by it are retained until `handoff` succeeds. If either * fails, remaining owned endpoints are closed once, preserving the original error. * Successful results remain owned by the caller; this is not a stream pump. * * Keep awaits in `handoff`, not `convert`, so concurrent RPCs cannot acquire each * other's endpoints. Item callbacks use the same boundary lazily, when pulled. */ declare function withNativeStreamScope(convert: () => T, handoff?: (value: T) => R | Promise): Promise; /** * Call inside `withNativeStreamScope` before decoding an already lifted result. * This also owns unread siblings that a failing typed decoder never reaches. */ declare function ownSchemaValueStreams(value: SchemaValue | undefined): void; declare function throwIfAborted(signal?: AbortSignal): void; type UnstructuredTextType = UnstructuredText; type UnstructuredBinaryType = UnstructuredBinary; type index_AgentConfigEntry = AgentConfigEntry; type index_AgentStream = AgentStream; declare const index_AgentStream: typeof AgentStream; declare const index_BinaryRestrictions: typeof BinaryRestrictions; type index_CollectedToolInvocation = CollectedToolInvocation; declare const index_Datetime: typeof Datetime; declare const index_DiscriminatorRule: typeof DiscriminatorRule; declare const index_FieldDiscriminator: typeof FieldDiscriminator; declare const index_MetadataEnvelope: typeof MetadataEnvelope; type index_NamedFieldType = NamedFieldType; declare const index_NumericBound: typeof NumericBound; declare const index_NumericRestrictions: typeof NumericRestrictions; declare const index_PathDirection: typeof PathDirection; declare const index_PathKind: typeof PathKind; declare const index_PathSpec: typeof PathSpec; type index_PermissionCard = PermissionCard; declare const index_PermissionCard: typeof PermissionCard; declare const index_PermissionCardSpec: typeof PermissionCardSpec; type index_PolymorphicPermissionCard = PolymorphicPermissionCard; declare const index_PolymorphicPermissionCard: typeof PolymorphicPermissionCard; declare const index_QuantitySpec: typeof QuantitySpec; declare const index_QuantityValue: typeof QuantityValue; type index_QuotaToken = QuotaToken; declare const index_QuotaToken: typeof QuotaToken; declare const index_QuotaTokenSpec: typeof QuotaTokenSpec; type index_RawToolInvocation = RawToolInvocation; type index_RemoteAgentError = RemoteAgentError; type index_RemoteAgentHandle = RemoteAgentHandle; type index_RemoteCallError = RemoteCallError; declare const index_RemoteCallError: typeof RemoteCallError; type index_RemoteCallErrorCause = RemoteCallErrorCause; type index_RemoteInvocationResult = RemoteInvocationResult; type index_RemoteOutputError = RemoteOutputError; declare const index_RemoteOutputError: typeof RemoteOutputError; import index_Result = Result; declare const index_Role: typeof Role; type index_SchemaCodec = SchemaCodec; type index_SchemaGraph = SchemaGraph; type index_SchemaMapEntry = SchemaMapEntry; type index_SchemaResult = SchemaResult; type index_SchemaType = SchemaType; type index_SchemaTypeBody = SchemaTypeBody; type index_SchemaTypeDef = SchemaTypeDef; type index_SchemaValue = SchemaValue; declare const index_SchemaValueTree: typeof SchemaValueTree; type index_SchemaValueWriter = SchemaValueWriter; declare const index_SchemaValueWriter: typeof SchemaValueWriter; type index_ScopeCard = ScopeCard; declare const index_ScopeCard: typeof ScopeCard; type index_SecretHandle = SecretHandle; declare const index_SecretSpec: typeof SecretSpec; type index_SettledToolResult = SettledToolResult; type index_StartedToolInvocation = StartedToolInvocation; declare const index_TextRestrictions: typeof TextRestrictions; type index_ToolClientRuntime = ToolClientRuntime; type index_ToolClientTransport = ToolClientTransport; type index_ToolError = ToolError; type index_ToolInputStream = ToolInputStream; type index_ToolInvocationResult = ToolInvocationResult; type index_ToolRpcError = ToolRpcError; type index_ToolRuntimeError = ToolRuntimeError; type index_ToolStreamError = ToolStreamError; declare const index_ToolStreamError: typeof ToolStreamError; declare const index_TypeId: typeof TypeId; type index_TypedSchemaValue = TypedSchemaValue; type index_UnionBranch = UnionBranch; declare const index_UnstructuredBinary: typeof UnstructuredBinary; type index_UnstructuredBinaryType = UnstructuredBinaryType; declare const index_UnstructuredText: typeof UnstructuredText; type index_UnstructuredTextType = UnstructuredTextType; declare const index_UrlRestrictions: typeof UrlRestrictions; type index_Uuid = Uuid; declare const index_Uuid: typeof Uuid; type index_VariantCaseType = VariantCaseType; declare const index_agentStreamFromHandle: typeof agentStreamFromHandle; declare const index_agentStreamToHandle: typeof agentStreamToHandle; declare const index_cloneSchemaValue: typeof cloneSchemaValue; declare const index_createToolClientRuntime: typeof createToolClientRuntime; declare const index_createToolClientTransport: typeof createToolClientTransport; declare const index_datetimeFromISOString: typeof datetimeFromISOString; declare const index_datetimeToISOString: typeof datetimeToISOString; declare const index_deepEqual: typeof deepEqual; declare const index_emptyMetadata: typeof emptyMetadata; declare const index_field: typeof field; declare const index_isRemoteCallError: typeof isRemoteCallError; declare const index_isRpcError: typeof isRpcError; declare const index_mapSettledToolResult: typeof mapSettledToolResult; declare const index_ownSchemaValueStreams: typeof ownSchemaValueStreams; declare const index_permissionCardFromSchemaValue: typeof permissionCardFromSchemaValue; declare const index_permissionCardToSchemaValue: typeof permissionCardToSchemaValue; declare const index_polymorphicPermissionCardFromSchemaValue: typeof polymorphicPermissionCardFromSchemaValue; declare const index_polymorphicPermissionCardToSchemaValue: typeof polymorphicPermissionCardToSchemaValue; declare const index_quotaTokenFromSchemaValue: typeof quotaTokenFromSchemaValue; declare const index_quotaTokenToSchemaValue: typeof quotaTokenToSchemaValue; declare const index_resolveRemoteAgent: typeof resolveRemoteAgent; declare const index_resolveRemoteAgentFallibly: typeof resolveRemoteAgentFallibly; declare const index_resolveShapeType: typeof resolveShapeType; declare const index_resultFromSettledToolResult: typeof resultFromSettledToolResult; declare const index_schemaGraphFromWit: typeof schemaGraphFromWit; declare const index_schemaGraphToWit: typeof schemaGraphToWit; declare const index_schemaGraphsEquivalent: typeof schemaGraphsEquivalent; declare const index_schemaShapesMatch: typeof schemaShapesMatch; declare const index_schemaType: typeof schemaType; declare const index_schemaTypeEquals: typeof schemaTypeEquals; declare const index_schemaValueEquals: typeof schemaValueEquals; declare const index_schemaValueFromWit: typeof schemaValueFromWit; declare const index_schemaValueToWit: typeof schemaValueToWit; declare const index_secretHandleFromSchemaValue: typeof secretHandleFromSchemaValue; declare const index_secretHandleToSchemaValue: typeof secretHandleToSchemaValue; declare const index_settleToolResult: typeof settleToolResult; declare const index_splitToolRpcError: typeof splitToolRpcError; declare const index_startedToolInvocation: typeof startedToolInvocation; declare const index_t: typeof t; declare const index_throwIfAborted: typeof throwIfAborted; declare const index_typedSchemaValueConforms: typeof typedSchemaValueConforms; declare const index_typedSchemaValueFromWit: typeof typedSchemaValueFromWit; declare const index_typedSchemaValueToWit: typeof typedSchemaValueToWit; declare const index_v: typeof v; declare const index_variantCase: typeof variantCase; declare const index_wireRemoteAgent: typeof wireRemoteAgent; declare const index_withCapabilityAdoptionTransaction: typeof withCapabilityAdoptionTransaction; declare const index_withNativeStreamScope: typeof withNativeStreamScope; declare namespace index { export { index_AgentStream as AgentStream, index_BinaryRestrictions as BinaryRestrictions, index_Datetime as Datetime, index_DiscriminatorRule as DiscriminatorRule, EnvironmentId$1 as EnvironmentId, index_FieldDiscriminator as FieldDiscriminator, index_MetadataEnvelope as MetadataEnvelope, index_NumericBound as NumericBound, index_NumericRestrictions as NumericRestrictions, index_PathDirection as PathDirection, index_PathKind as PathKind, index_PathSpec as PathSpec, index_PermissionCard as PermissionCard, index_PermissionCardSpec as PermissionCardSpec, index_PolymorphicPermissionCard as PolymorphicPermissionCard, index_QuantitySpec as QuantitySpec, index_QuantityValue as QuantityValue, index_QuotaToken as QuotaToken, index_QuotaTokenSpec as QuotaTokenSpec, index_RemoteCallError as RemoteCallError, index_RemoteOutputError as RemoteOutputError, index_Result as Result, index_Role as Role, index_SchemaValueTree as SchemaValueTree, index_SchemaValueWriter as SchemaValueWriter, index_ScopeCard as ScopeCard, index_SecretSpec as SecretSpec, index_TextRestrictions as TextRestrictions, index_ToolStreamError as ToolStreamError, index_TypeId as TypeId, index_UnstructuredBinary as UnstructuredBinary, index_UnstructuredText as UnstructuredText, index_UrlRestrictions as UrlRestrictions, index_Uuid as Uuid, index_agentStreamFromHandle as agentStreamFromHandle, index_agentStreamToHandle as agentStreamToHandle, index_cloneSchemaValue as cloneSchemaValue, index_createToolClientRuntime as createToolClientRuntime, index_createToolClientTransport as createToolClientTransport, index_datetimeFromISOString as datetimeFromISOString, index_datetimeToISOString as datetimeToISOString, index_deepEqual as deepEqual, index_emptyMetadata as emptyMetadata, index_field as field, index_isRemoteCallError as isRemoteCallError, index_isRpcError as isRpcError, index_mapSettledToolResult as mapSettledToolResult, index_ownSchemaValueStreams as ownSchemaValueStreams, index_permissionCardFromSchemaValue as permissionCardFromSchemaValue, index_permissionCardToSchemaValue as permissionCardToSchemaValue, index_polymorphicPermissionCardFromSchemaValue as polymorphicPermissionCardFromSchemaValue, index_polymorphicPermissionCardToSchemaValue as polymorphicPermissionCardToSchemaValue, index_quotaTokenFromSchemaValue as quotaTokenFromSchemaValue, index_quotaTokenToSchemaValue as quotaTokenToSchemaValue, index_resolveRemoteAgent as resolveRemoteAgent, index_resolveRemoteAgentFallibly as resolveRemoteAgentFallibly, index_resolveShapeType as resolveShapeType, index_resultFromSettledToolResult as resultFromSettledToolResult, index_schemaGraphFromWit as schemaGraphFromWit, index_schemaGraphToWit as schemaGraphToWit, index_schemaGraphsEquivalent as schemaGraphsEquivalent, index_schemaShapesMatch as schemaShapesMatch, index_schemaType as schemaType, index_schemaTypeEquals as schemaTypeEquals, index_schemaValueEquals as schemaValueEquals, index_schemaValueFromWit as schemaValueFromWit, index_schemaValueToWit as schemaValueToWit, index_secretHandleFromSchemaValue as secretHandleFromSchemaValue, index_secretHandleToSchemaValue as secretHandleToSchemaValue, index_settleToolResult as settleToolResult, index_splitToolRpcError as splitToolRpcError, index_startedToolInvocation as startedToolInvocation, index_t as t, index_throwIfAborted as throwIfAborted, index_typedSchemaValueConforms as typedSchemaValueConforms, index_typedSchemaValueFromWit as typedSchemaValueFromWit, index_typedSchemaValueToWit as typedSchemaValueToWit, index_v as v, index_variantCase as variantCase, index_wireRemoteAgent as wireRemoteAgent, index_withCapabilityAdoptionTransaction as withCapabilityAdoptionTransaction, index_withNativeStreamScope as withNativeStreamScope }; export type { index_AgentConfigEntry as AgentConfigEntry, index_CollectedToolInvocation as CollectedToolInvocation, index_NamedFieldType as NamedFieldType, index_RawToolInvocation as RawToolInvocation, index_RemoteAgentError as RemoteAgentError, index_RemoteAgentHandle as RemoteAgentHandle, index_RemoteCallErrorCause as RemoteCallErrorCause, index_RemoteInvocationResult as RemoteInvocationResult, index_SchemaCodec as SchemaCodec, index_SchemaGraph as SchemaGraph, index_SchemaMapEntry as SchemaMapEntry, index_SchemaResult as SchemaResult, index_SchemaType as SchemaType, index_SchemaTypeBody as SchemaTypeBody, index_SchemaTypeDef as SchemaTypeDef, index_SchemaValue as SchemaValue, index_SecretHandle as SecretHandle, index_SettledToolResult as SettledToolResult, index_StartedToolInvocation as StartedToolInvocation, index_ToolClientRuntime as ToolClientRuntime, index_ToolClientTransport as ToolClientTransport, index_ToolError as ToolError, index_ToolInputStream as ToolInputStream, index_ToolInvocationResult as ToolInvocationResult, index_ToolRpcError as ToolRpcError, index_ToolRuntimeError as ToolRuntimeError, index_TypedSchemaValue as TypedSchemaValue, index_UnionBranch as UnionBranch, index_UnstructuredBinaryType as UnstructuredBinaryType, index_UnstructuredTextType as UnstructuredTextType, index_VariantCaseType as VariantCaseType }; } /** A declared tool argument with its selected value schema. */ interface ToolArgument { readonly kind: 'positional' | 'tail' | 'option' | 'flag'; readonly name: string; readonly aliases: readonly string[]; readonly short?: string; readonly required: boolean; readonly default?: SchemaValue; readonly optionalCarrier?: true; readonly schema: SchemaRef; } /** An invalid structured result returned by a remote tool. */ declare class ToolRemoteOutputError extends Error { constructor(message: string); } /** A declared custom tool error decoded using discovered metadata. */ interface ReflectedToolFailure { readonly name: string; readonly value?: JsonValue; } /** One callable command in an immutable discovered tool snapshot. */ declare class ToolCommand { readonly toolName: string; private readonly runtime; readonly path: readonly string[]; readonly name: string; readonly aliases: readonly string[]; readonly doc: Doc; readonly inputSchema?: SchemaRef; readonly arguments: readonly ToolArgument[]; readonly constraints: readonly Constraint[]; readonly stdin?: StreamSpec; readonly stdout?: StreamSpec; readonly stderr?: StreamSpec; readonly result?: SchemaRef; readonly errors: readonly { readonly name: string; readonly payload?: SchemaRef; }[]; readonly children: readonly ToolCommand[]; private readonly wireInputGraph?; private readonly omittedDefaults; constructor(toolName: string, node: CommandNode, body: CommandBody | undefined, path: readonly string[], inherited: readonly ToolArgument[], graph: SchemaGraph, typeAt: (index: number) => SchemaType, children: readonly ToolCommand[], runtime: ToolClientRuntime); /** * Validate and pack canonical JSON input before opening a tool RPC. Omitted scalar options, * positionals and flags take their declared defaults. */ packJson(input: JsonValue): SchemaValue; /** Validate canonical JSON and command constraints without dispatching. */ validateJson(input: JsonValue): ReturnType; private validateConstraints; private inputValue; private decodeResult; private unpackResult; /** Start a cancelable invocation with a schema-native input. */ startValue(input: SchemaValue, stdin?: ToolInputStream): StartedToolInvocation; /** Start a cancelable invocation with canonical JSON input. */ startJson(input: JsonValue, stdin?: ToolInputStream): StartedToolInvocation; /** Await a structured schema-native result. */ invokeValue(input: SchemaValue, stdin?: ToolInputStream): Promise; /** Await a structured canonical JSON result. */ invokeJson(input: JsonValue, stdin?: ToolInputStream): Promise; /** Admit a fire-and-forget invocation without output attachments. */ triggerValue(input: SchemaValue, stdin?: ToolInputStream): void; /** Admit a fire-and-forget invocation from canonical JSON. */ triggerJson(input: JsonValue, stdin?: ToolInputStream): void; private mapFailure; } /** An immutable snapshot of one accessible tool registration. */ declare class ToolType { readonly name: string; readonly lookupName: string; readonly version: string; readonly implementedBy: ComponentId; readonly commands: readonly ToolCommand[]; readonly client: ReflectedToolClient; constructor(registered: RegisteredTool, runtime?: ToolClientRuntime); /** Resolve names and aliases to a canonical command handle. */ command(path: readonly string[]): ToolCommand | undefined; } /** Strict callable lookup for a discovered tool. */ interface ReflectedToolClient { command(path: readonly string[]): ToolCommand; } /** List the current accessible tools. */ declare function getAllToolTypes(): ToolType[]; /** Look up one accessible tool; missing and inaccessible are indistinguishable. */ declare function getToolType(name: string): ToolType | undefined; /** A fully dynamic client that sends caller-owned packed values. */ declare class DynamicToolClient { readonly name: string; private readonly runtime; constructor(name: string, runtime?: ToolClientRuntime); start(path: readonly string[], input: TypedSchemaValue, stdin?: ToolInputStream, stdout?: boolean, stderr?: boolean): StartedToolInvocation; invoke(path: readonly string[], input: TypedSchemaValue, stdin?: ToolInputStream): Promise; trigger(path: readonly string[], input: TypedSchemaValue, stdin?: ToolInputStream): void; } interface ReflectedInvocation { readonly metadata: InvocationMetadata; readonly value?: T; } /** Canonical JSON values for declared local configuration paths. */ interface ReflectedConfigJsonEntry { readonly path: readonly string[]; readonly value: JsonValue; } declare class AgentMethod { readonly name: string; readonly description: string; readonly promptHint?: string; readonly input: SchemaRef; readonly output?: SchemaRef; constructor(raw: AgentMethod$1, graph: ReflectedGraph); } declare class AgentType { readonly name: string; readonly description: string; readonly sourceLanguage: string; readonly mode: 'durable' | 'ephemeral'; readonly implementedBy: ComponentId; readonly constructorInput: SchemaRef; readonly methods: readonly AgentMethod[]; readonly config: readonly { readonly path: readonly string[]; readonly source: 'local' | 'secret'; readonly schema: SchemaRef; }[]; readonly client: ReflectedAgentClientFactory; constructor(registered: RegisteredAgentType); method(name: string): AgentMethod | undefined; /** Construct an agent identity from canonical JSON constructor input. */ agentId(input: JsonValue, phantomId?: Uuid): ParsedAgentId; /** Construct an agent identity from an already packed constructor value. */ agentIdValue(input: SchemaValue, phantomId?: Uuid): ParsedAgentId; [bindAgentClient](agentId: ParsedAgentId, config?: readonly AgentConfigEntry[], options?: AgentClientBindOptions): ReflectedAgentClient; /** Pack canonical JSON overrides for declared local config fields. */ packConfigJson(entries: readonly ReflectedConfigJsonEntry[]): AgentConfigEntry[]; /** Validate schema-native overrides before opening an RPC. */ validateConfigValues(entries: readonly AgentConfigEntry[]): AgentConfigEntry[]; private configDeclaration; } interface ReflectedPhantomClient { readonly agentId: ParsedAgentId; readonly phantomId: Uuid; readonly client: ReflectedAgentClient; } declare class ReflectedAgentClientFactory { private readonly agentType; constructor(agentType: AgentType); get(input: JsonValue, config?: readonly ReflectedConfigJsonEntry[]): ReflectedAgentClient; getValue(input: SchemaValue, config?: readonly AgentConfigEntry[]): ReflectedAgentClient; getPhantom(input: JsonValue, phantomId: Uuid, config?: readonly ReflectedConfigJsonEntry[]): ReflectedAgentClient; getPhantomValue(input: SchemaValue, phantomId: Uuid, config?: readonly AgentConfigEntry[]): ReflectedAgentClient; newPhantom(input: JsonValue, config?: readonly ReflectedConfigJsonEntry[]): ReflectedPhantomClient | ReflectedAgentClient; newPhantomValue(input: SchemaValue, config?: readonly AgentConfigEntry[]): ReflectedPhantomClient | ReflectedAgentClient; private create; private requireMode; } declare class ReflectedAgentClient { private readonly agentType; private readonly remote; private readonly scopeCard?; constructor(agentType: AgentType, remote: RemoteAgentHandle, scopeCard?: ScopeCard | undefined); method(name: string): ReflectedAgentMethod; } /** * One method of a reflected agent. The awaited calls borrow `scopeCard` when it * is given, and otherwise the client's default scope card; `null` sends none. */ declare class ReflectedAgentMethod { readonly definition: AgentMethod; private readonly remote; private readonly defaultScopeCard?; constructor(definition: AgentMethod, remote: RemoteAgentHandle, defaultScopeCard?: ScopeCard | undefined); invoke(input: JsonValue, signal?: AbortSignal, scopeCard?: ScopeCard | null): Promise>; invokeJson(input: JsonValue, signal?: AbortSignal, scopeCard?: ScopeCard | null): Promise>; invokeValue(input: SchemaValue, signal?: AbortSignal, scopeCard?: ScopeCard | null): Promise>; trigger(input: JsonValue): InvocationMetadata; triggerValue(input: SchemaValue): InvocationMetadata; schedule(at: Datetime$1, input: JsonValue): CancelableScheduledInvocationReceipt; scheduleValue(at: Datetime$1, input: SchemaValue): CancelableScheduledInvocationReceipt; } declare function getAllAgentTypes(): readonly AgentType[]; /** * Look up a deployed agent type by name. * * This is an optional discovery operation: it returns `undefined` for routers or types not visible in * the current environment. Once returned, each schema operation is strict and throws for malformed * JSON or schema values. */ declare function getAgentType(name: string): AgentType | undefined; /** * Look up the current deployed schema for a full environment-scoped identity. * * Returns `undefined` for routers, or when the agent does not exist, its ID is malformed, its type is missing, or * the caller lacks `View` permission. Use {@link ParsedAgentId.parsed} when strict identity parsing is * required independently of discovery. */ declare function getAgentTypeByAgentId(agentId: ParsedAgentId): AgentType | undefined; interface ReflectedGraph { readonly graph: SchemaGraph; readonly types: readonly SchemaType[]; } type reflection_AgentMethod = AgentMethod; declare const reflection_AgentMethod: typeof AgentMethod; type reflection_AgentType = AgentType; declare const reflection_AgentType: typeof AgentType; type reflection_ComponentId = ComponentId; declare const reflection_ComponentId: typeof ComponentId; type reflection_DynamicAgentClient = DynamicAgentClient; declare const reflection_DynamicAgentClient: typeof DynamicAgentClient; type reflection_DynamicAgentClientSurface = DynamicAgentClientSurface; type reflection_DynamicAgentMethod = DynamicAgentMethod; declare const reflection_DynamicAgentMethod: typeof DynamicAgentMethod; type reflection_DynamicAgentMethodSurface = DynamicAgentMethodSurface; type reflection_DynamicInvocation = DynamicInvocation; type reflection_DynamicToolClient = DynamicToolClient; declare const reflection_DynamicToolClient: typeof DynamicToolClient; type reflection_ReflectedAgentClient = ReflectedAgentClient; declare const reflection_ReflectedAgentClient: typeof ReflectedAgentClient; type reflection_ReflectedAgentClientFactory = ReflectedAgentClientFactory; declare const reflection_ReflectedAgentClientFactory: typeof ReflectedAgentClientFactory; type reflection_ReflectedAgentMethod = ReflectedAgentMethod; declare const reflection_ReflectedAgentMethod: typeof ReflectedAgentMethod; type reflection_ReflectedConfigJsonEntry = ReflectedConfigJsonEntry; type reflection_ReflectedInvocation = ReflectedInvocation; type reflection_ReflectedPhantomClient = ReflectedPhantomClient; type reflection_ReflectedToolClient = ReflectedToolClient; type reflection_ReflectedToolFailure = ReflectedToolFailure; type reflection_RemoteAgentError = RemoteAgentError; type reflection_RemoteCallError = RemoteCallError; declare const reflection_RemoteCallError: typeof RemoteCallError; type reflection_RemoteCallErrorCause = RemoteCallErrorCause; type reflection_RemoteOutputError = RemoteOutputError; declare const reflection_RemoteOutputError: typeof RemoteOutputError; type reflection_ToolArgument = ToolArgument; type reflection_ToolCommand = ToolCommand; declare const reflection_ToolCommand: typeof ToolCommand; type reflection_ToolRemoteOutputError = ToolRemoteOutputError; declare const reflection_ToolRemoteOutputError: typeof ToolRemoteOutputError; type reflection_ToolType = ToolType; declare const reflection_ToolType: typeof ToolType; declare const reflection_getAgentType: typeof getAgentType; declare const reflection_getAgentTypeByAgentId: typeof getAgentTypeByAgentId; declare const reflection_getAllAgentTypes: typeof getAllAgentTypes; declare const reflection_getAllToolTypes: typeof getAllToolTypes; declare const reflection_getToolType: typeof getToolType; declare const reflection_isRemoteCallError: typeof isRemoteCallError; declare namespace reflection { export { reflection_AgentMethod as AgentMethod, reflection_AgentType as AgentType, reflection_ComponentId as ComponentId, reflection_DynamicAgentClient as DynamicAgentClient, reflection_DynamicAgentMethod as DynamicAgentMethod, reflection_DynamicToolClient as DynamicToolClient, reflection_ReflectedAgentClient as ReflectedAgentClient, reflection_ReflectedAgentClientFactory as ReflectedAgentClientFactory, reflection_ReflectedAgentMethod as ReflectedAgentMethod, reflection_RemoteCallError as RemoteCallError, reflection_RemoteOutputError as RemoteOutputError, reflection_ToolCommand as ToolCommand, reflection_ToolRemoteOutputError as ToolRemoteOutputError, reflection_ToolType as ToolType, reflection_getAgentType as getAgentType, reflection_getAgentTypeByAgentId as getAgentTypeByAgentId, reflection_getAllAgentTypes as getAllAgentTypes, reflection_getAllToolTypes as getAllToolTypes, reflection_getToolType as getToolType, reflection_isRemoteCallError as isRemoteCallError }; export type { reflection_DynamicAgentClientSurface as DynamicAgentClientSurface, reflection_DynamicAgentMethodSurface as DynamicAgentMethodSurface, reflection_DynamicInvocation as DynamicInvocation, reflection_ReflectedConfigJsonEntry as ReflectedConfigJsonEntry, reflection_ReflectedInvocation as ReflectedInvocation, reflection_ReflectedPhantomClient as ReflectedPhantomClient, reflection_ReflectedToolClient as ReflectedToolClient, reflection_ReflectedToolFailure as ReflectedToolFailure, reflection_RemoteAgentError as RemoteAgentError, reflection_RemoteCallErrorCause as RemoteCallErrorCause, reflection_ToolArgument as ToolArgument }; } interface GolemAgentGuest { initialize(agentTypeName: string, input: SchemaValueTree, principal: Principal$1): Promise; discoverAgentTypes(): AgentType$1[]; invoke(methodName: string, input: SchemaValueTree, principal: Principal$1): Promise; getDefinition(): AgentType$1; } interface GolemToolGuest { discoverTools(): Tool[]; getTool(name: string): Tool; invoke(toolName: string, commandPath: string[], input: TypedSchemaValue$3, stdin: AsyncIterable | undefined, stdout: ToolOutputWriter | undefined, stderr: ToolOutputWriter | undefined, principal: Principal$1): Promise; } interface SaveSnapshotGuest { save(): Promise; } interface LoadSnapshotGuest { load(snapshot: Snapshot$1): Promise; } declare const golemAgent200Guest: GolemAgentGuest; declare const guest: GolemAgentGuest; declare const golemTool010Guest: GolemToolGuest; declare const tool: GolemToolGuest; declare const saveSnapshot: SaveSnapshotGuest; declare const loadSnapshot: LoadSnapshotGuest; export { AccountId, AgentClassName, AgentStream, AgentTypeRegistry, BlobstoreError, Bytes, ComponentId, DurableStreamError, Duration, DynamicAgentClient, DynamicAgentMethod, EnvironmentId, Filter, FunctionType, GetAgents, Ignite, IgniteError, KeyValue, KeyValueError, MySql, MySqlError, NamedPolicy, ParsedAgentId, Path, PermissionCard, Pg, Policy, PolymorphicPermissionCard, Postgres, PostgresError, Predicate, Props, Quantity, QuotaToken, RdbmsError, ReflectedAgentClient, ReflectedAgentClientFactory, ReflectedAgentMethod, AgentMethod as ReflectedAgentMethodDefinition, AgentType as ReflectedAgentType, RemoteCallError, RemoteOutputError, Reservation, Result, RetryPolicyError, RetryPolicyGuard, RevertTarget, SagaRetryFailure, SchemaFingerprintError, SchemaRef, SchemaRenderError, ScopeCard, Secret, Snapshot, SnapshotError, StandardSchemaV1, ToolCallError, ToolInvokeError, ToolStreamError, UnstructuredBinary, UnstructuredText, Uuid, WebhookHandler, WebhookRequestPayload, WebsocketError, acquireQuotaToken, awaitAbortablePromise, awaitPromise, index as bridge, c, client, command, compensable, compileSchema, connectWebsocket, containerExists, copyObject, createContainer, createDurableByteWriter, createDurableJsonWriter, createWebhook, defineAgent, defineAgentClient, defineHttpRouter, deleteContainer, dropAll, durable, err, executeWithDrop, executeWithDropAsync, fallibleSaga, fork, generateIdempotencyKey, getAgentMetadata, getAgentTypeByAgentId, getAgents, getAllAgentTypes, getContainer, getOrCreateContainer, getRawSelfAgentId, getAgentType as getReflectedAgentType, getToolType as getReflectedToolType, getSelfMetadata, golemAgent200Guest, golemTool010Guest, golemTool010ToolMiddlewareGuest, guest, http, infallibleSaga, isPromiseLike, isRemoteCallError, loadSnapshot, method, moveObject, ok, openBucket, oplog, permissions, processExitStatusSchema, readDurableByteStream, readDurableJsonStream, reflection, registerSchemaWalker, registeredVendors, renderArgumentHelp, renderHelp, resolveAgentId, resolveAgentIdStrict, resolveComponentId, retry, s, saveSnapshot, schemaFingerprintV1, setRetryPolicy, toRawDuration, toRawNamedPolicy, toRawPolicy, toRawPredicate, toRawPredicateValue, tool, toolClientDefinition, toolDefinition, toolMiddlewareGuest, universalToolMiddleware, useRetryPolicy, withRawHeaders, withReservation, withRetryPolicy }; export type { AgentClientBindOptions, AgentConfigEntry, AgentContext, AgentDefinition, AgentId, AgentImpl, AgentImplementation, AgentMetadata, AgentSpec, BasicModality, Bucket, CamelCase, CollectedToolInvocation, Compensable, CompensableErrors, ConfigOverrides, ConfigSpec, ConfigView, ConnectOptions, ConstraintRef, Container, ContainerMetadata, CustomModality, DocInput, DurableStreamJsonCodec, DurableStreamOptions, DurableStreamReadOptions, DurableStreamWriteOptions, DurableStreamWriter, DurationInput, EphemeralInvocationResult, EphemeralRemoteClientFactory, ErrorOptions$1 as ErrorOptions, FileExposure, FileResponseHeaders, FlagOptions, ForkDetails, ForkResult, FormatterInput, FullAgentClientDefinition, FullAgentClientFactory, FullAgentClientSpec, GlobalCountFlagOptions, GlobalFlagOptions, GlobalValueOptions, HttpHeader, HttpRequest, HttpResponse, HttpRouterBuilder, HttpRouterContext, HttpRouterHandler, HttpRouterOptions, IdRecord, IgniteConnection, IgniteOpenOptions, IgniteResultSet, IgniteTransaction, IgniteUuid, ImplementedTool, ImplementedToolMiddleware, InitContext, InputRecord, JsonValue, KeyValueOptions, MethodOnlyAgentClientDefinition, MethodOnlyAgentClientSpec, MethodSpec, MethodsRecord, Multimodal, MultimodalAdvanced, MultimodalCustom, MultipartSnapshot, MySqlConnection, MySqlOpenOptions, MySqlResultSet, MySqlTransaction, NamedPolicyInput, NestedCommandImplementation, ObjectId, ObjectMetadata, OptionOptions, ParsedAgentIdCreateOptions, ParsedAgentIdParts, PathOptions, PermissionCardOptions, PgConnection, PgOpenOptions, PgResultSet, PgTransaction, PhantomClientDetails, PolicyInput, PositionalOptions, PredicateValueInput, Principal, ProcessExitStatus, QuantityOptions, RawHttpRouterHandler, RdbmsErrorReason, ReflectedInvocation, ReflectedPhantomClient, RemoteAgentError, RemoteCallErrorCause, RemoteCallOptions, RemoteClient, RemoteClientFactory, RemoteClientOptions, RepeatableMode, RetryOptions, RetryProperties, ReturnsOptions, SagaFailure, SagaResult, SagaRetryFailureReason, SchemaBucket, SchemaCodec, SchemaContainer, SchemaGraph, SchemaIssue, SchemaType, SchemaValidationResult, SchemaWalker, SnapshotPart, SnapshotRestoreContext, StartedToolInvocation, StreamOptions, TailOptions, TemporalDecodeMode, ToolBodyModel, ToolCallErrorCause, ToolClient, ToolClientDefinition, ToolClientErrors, ToolClientInvocationResult, ToolClientMethod, ToolClientOptions, ToolClientTransport$1 as ToolClientTransport, ToolCommandModel, ToolCommandModelOf, ToolConstraint, ToolDefinition, ToolErr, ToolHandler, ToolHelpError, ToolHelpResult, ToolImplementation, ToolInputStream, ToolInvocationContext, ToolInvokeErrorCause, ToolMiddlewareHandler, ToolMiddlewareImplementation, ToolMiddlewareInvocationContext, ToolMiddlewareOptions, ToolOk, ToolResult, ToolSubtreeModel, ToolUnderlying, ToolUnderlyingErrors, UniversalToolMiddlewareContext, UniversalToolMiddlewareInvocation, UniversalToolMiddlewareInvoke, UniversalToolMiddlewareOptions, UniversalToolUnderlying, UniversalToolUnderlyingInvoke, WebHttpRouterContext, WebSocketHandle, WebSocketMessage };