///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
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