cavi-ai/
GitHub ↗

@cavi-ai/api-client

Package subpath: .

AgentRun#

Kind: type

ts
export type AgentRun = {
    key: string;
    title: string;
    agentId: string;
    channel: string;
    updatedAt: number | null;
    status: AgentRunStatus;
    totalTokens: number;
    errors: number;
    /** Model used for this run (e.g. claude-sonnet-4, gpt-4). From backend when available. */
    model?: string;
    /** Cost in USD for this run. From backend when available. */
    totalCostUsd?: number;
    /** Optional manifest-derived binding for source/channel/team routing diagnostics. */
    binding?: GatewayResolvedRouteBinding | null;
};

AgentRunDetailSnapshot#

Kind: type

ts
export type AgentRunDetailSnapshot = {
    run: AgentRun | null;
    preview: {
        status: string;
        items: AgentRunPreviewItem[];
    };
    usage: {
        totalTokens: number;
        totalCostUsd: number;
        messages: number;
        toolCalls: number;
        errors: number;
    };
};

ApiClientError#

Kind: class

ts
export declare class ApiClientError extends Error {
    readonly type: ApiClientErrorType | string;
    readonly code: ApiClientErrorCode | string;
    readonly runtime?: RuntimeErrorMetadata;
    constructor(message: string, options?: ApiClientErrorOptions);
}

ApiClientErrorCode#

Kind: enum

ts
export declare enum ApiClientErrorCode {
    Unknown = "unknown",
    ValidationFailed = "validation_failed",
    InvalidConfig = "invalid_config",
    InvalidJson = "invalid_json",
    HttpRequestFailed = "http_request_failed",
    GatewayError = "gateway_error",
    RequestFailed = "request_failed",
    Timeout = "timeout",
    Aborted = "aborted",
    SocketError = "socket_error",
    SocketClosed = "socket_closed",
    SocketUnavailable = "socket_unavailable",
    ConnectFailed = "connect_failed",
    BackendUnavailable = "backend_unavailable",
    EndpointNotFound = "endpoint_not_found",
    ProtocolMismatch = "protocol_mismatch",
    AuthRequired = "auth_required",
    AuthForbidden = "auth_forbidden",
    CapabilityUnavailable = "capability_unavailable",
    PermissionDenied = "permission_denied",
    InvalidRequest = "invalid_request",
    Conflict = "conflict",
    RateLimited = "rate_limited",
    TransportUnavailable = "transport_unavailable",
    TransportProtocolError = "transport_protocol_error",
    ServerOverloaded = "server_overloaded"
}

ApiClientErrorOptions#

Kind: type

ts
export type ApiClientErrorOptions = {
    type?: ApiClientErrorType | string;
    code?: ApiClientErrorCode | string;
    cause?: unknown;
    runtime?: RuntimeErrorMetadata;
};

ApiClientErrorType#

Kind: enum

ts
export declare enum ApiClientErrorType {
    Unknown = "unknown",
    Validation = "validation",
    Configuration = "configuration",
    Http = "http",
    GatewayHttp = "gateway_http",
    GatewayRpc = "gateway_rpc",
    Transport = "transport",
    Timeout = "timeout",
    Abort = "abort",
    BackendUnavailable = "backend_unavailable",
    Auth = "auth"
}

ApiKeyCredentialOptions#

Kind: type

ts
export type ApiKeyCredentialOptions = {
    /** Header name for the key. Defaults to "Authorization". */
    header?: string;
    /** Extra static headers (e.g. { "anthropic-version": "2023-06-01" }). */
    extra?: Record<string, string>;
};

apiKeyCredentials#

Kind: function

ts
/** API-key scheme (e.g. Anthropic: header "x-api-key" + "anthropic-version"). */
export declare function apiKeyCredentials(key: string, options?: ApiKeyCredentialOptions): CredentialResolver;

appendHttpQuery#

Kind: function

ts
export declare function appendHttpQuery(path: string, query?: Record<string, string | number | boolean | undefined>): string;

assertProtocolVersion#

Kind: function

ts
/** Throw a typed ProtocolMismatch error when the reported version is not `expected`. */
export declare function assertProtocolVersion(carrier: ProtocolVersionCarrier, expected: string): void;

assertSafeRelativePath#

Kind: function

ts
/**
 * Validate and normalize a caller-supplied **relative** path, returning the
 * cleaned `a/b/c` form or throwing on anything unsafe.
 *
 * This is the **opt-in** companion to the manifest workspace whitelist
 * (`resolveTeamWorkspacePath`). The whitelist is the primary, recommended guard:
 * a path the consumer never declared can never be resolved. Reach for this only
 * when a downstream surface must accept a *free-form* relative path — e.g. a raw
 * `?path=` value a consumer wants to hand to a workspace/wiki file endpoint
 * (`GATEWAY_WIKI_API_ENDPOINTS.read`, a manifest action `query`).
 *
 * `appendHttpQuery` does **not** sanitize values — it only URL-encodes them, so
 * `?path=../secret` becomes `?path=..%2Fsecret` and the backend decodes it back.
 * Run untrusted path values through this first, then pass the result as a query
 * value via `appendHttpQuery` (which encodes it).
 *
 * Rejects: empty/whitespace, absolute (`/…`), protocol-relative (`//…`), URL
 * schemes (`file:`, `http:`…), backslashes, and any `.`/`..` segment — including
 * percent-encoded forms such as `%2e%2e`. Interior `./` and duplicate slashes
 * are collapsed. The return value is **not** URL-encoded.
 *
 * This intentionally mirrors the relative-path rules the team manifest enforces
 * internally for workspace whitelist entries (`src/contracts/team-manifest.ts`).
 * Both are guarded by `safe-relative-path.test.ts`; keep them in lockstep.
 */
export declare function assertSafeRelativePath(value: string): string;

AuthStatusClient#

Kind: interface

ts
export interface AuthStatusClient {
    listAuthStatus(): Promise<readonly RuntimeAuthStatus[]>;
}

bearerCredentials#

Kind: function

ts
/** Standard bearer scheme. Emits nothing when the token is empty. */
export declare function bearerCredentials(token: string | null | undefined): CredentialResolver;

buildDryRunStatus#

Kind: function

ts
/**
 * Build the canonical `dry_run` RuntimeRunStatus every provider's dryRun
 * short-circuit returns (A3). Single-source shape — same pattern as
 * normalizeRuntimeUsage: `dryRun: true` always builds + validates the
 * provider request first, then returns this WITHOUT any network call.
 */
export declare function buildDryRunStatus(model?: string): RuntimeRunStatus;

buildDryRunStreamEvent#

Kind: function

ts
/** Build the single terminal stream event a dryRun streamRun() emits (A3). */
export declare function buildDryRunStreamEvent(model?: string): RunStreamRunCompletedEvent;

buildGatewayHttpError#

Kind: function

ts
export declare function buildGatewayHttpError(params: {
    label: string;
    status: number;
    statusText: string;
    message?: string | null;
    code?: string | null;
}): GatewayHttpError;

CachedTeamManifestSource#

Kind: interface

ts
export interface CachedTeamManifestSource extends TeamManifestSource {
    /** Re-run the loader and replace the cached manifest. */
    refresh(): Promise<TeamManifest>;
}

CAPABILITY_GROUPS#

Kind: variable

ts
/** Grouping is presentation/ergonomics only; it partitions the taxonomy exactly. */
export declare const CAPABILITY_GROUPS: {
    readonly execution: readonly [
        "runs",
        "streaming",
        "batch"
    ];
    readonly lifecycle: readonly [
        "sessions",
        "tasks",
        "events"
    ];
    readonly introspection: readonly [
        "models",
        "usage",
        "authStatus"
    ];
    readonly domain: readonly [
        "kanban",
        "teams",
        "workspace",
        "operator",
        "discourse",
        "media",
        "wiki",
        "agentConfig"
    ];
};

CAPABILITY_TAXONOMY#

Kind: variable

ts
/**
 * The unified capability taxonomy — the single, provider-agnostic list of
 * everything a provider may expose through the one client contract.
 *
 * It is the union of the two legacy axes: runtime SURFACES (`RUNTIME_SURFACES`)
 * and control-plane MODULES, de-duplicated (`workspace` appeared in both).
 * Every provider declares support for each key in ONE place; an unsupported
 * capability's call still exists on the client and throws a uniform, notated
 * `CapabilityUnavailable`.
 *
 * This module is purely additive: it introduces the taxonomy alongside the two
 * legacy axes it will replace. The `satisfies` bridges below are a compile-time
 * proof that the taxonomy is a strict superset of both — miss a surface or a
 * module and the build fails.
 */
export declare const CAPABILITY_TAXONOMY: readonly [
    "runs",
    "streaming",
    "batch",
    "sessions",
    "tasks",
    "events",
    "models",
    "usage",
    "authStatus",
    "kanban",
    "teams",
    "workspace",
    "operator",
    "discourse",
    "media",
    "wiki",
    "agentConfig"
];

CapabilityCallRejected#

Kind: class

ts
/**
 * Thrown by internal plumbing (e.g. the gateway streamRun bridges) for a
 * caller mistake the transport can name before any request is made. The
 * facade classifies it into a `request-invalid` gap — consumers never see it.
 */
export declare class CapabilityCallRejected extends Error {
    readonly httpStatus?: number | undefined;
    readonly name = "CapabilityCallRejected";
    constructor(message: string, httpStatus?: number | undefined);
}

CapabilityClient#

Kind: interface

ts
/**
 * The single client surface (the redesign's core invariant): every capability
 * accessor exists on every provider. Gated surfaces never throw and never go
 * missing — an unsupported or failed call resolves `ok: false` with a
 * structured `ContractGap` (the same notation the throwing gate once carried),
 * while a supported call resolves `ok: true` with a live result. The only
 * throws left on a gated call are the envelope contract's carve-outs: auth
 * errors (401/403) and unknown-classified errors. Feature-detect via
 * `getCapabilityMap()`, or just call and branch on `result.ok`. Support is
 * decided by the runtime-resolved capabilities merged over the static fallback
 * (design decision M1).
 */
export interface CapabilityClient {
    readonly providerKind: string;
    /** Merged (runtime over static) capability profile. */
    getCapabilityMap(): Promise<CapabilityMap>;
    /** Runtime-resolved manifest, when the provider publishes one. */
    getManifest(): Promise<TeamManifest | null>;
    /** Drop the memoized runtime resolution and resolve again. */
    refreshCapabilities(): Promise<CapabilityMap>;
    /**
     * Tear down the client: dispose the control plane and run provider teardown.
     * In-flight gateway `streamRun` bridges are settled as part of teardown
     * (their in-flight calls are aborted, so pending `streamRun` promises resolve
     * rather than hang), then any transport (SSE/WebSocket) is closed.
     */
    dispose(): Promise<void>;
    startRun(body: RuntimeRunStartBody): Promise<CapabilityResult<RuntimeRunStatus>>;
    getRun(runId: string): Promise<CapabilityResult<RuntimeRunStatus>>;
    cancelRun(runId: string): Promise<CapabilityResult<{
        status: string;
    }>>;
    /**
     * Stream a run, unified across providers. The resolved `ok` reflects the
     * STREAMING CALL, not the run: a clean stream (or one whose run merely failed
     * as an event) resolves `ok: true` with a {@link RunStreamOutcome} carrying
     * the captured `runId` and the terminal `outcome` seen. A stream that a
     * transport error tore down resolves `ok: false` with a classified gap. A
     * caller-initiated abort (via `options.signal`), or a provider-internal
     * AbortError, resolves `ok: false` with a `request-aborted` gap — never a
     * silent `ok: true` — and, when a `runId` is known and the runtime exposes
     * `cancelRun`, issues a best-effort `cancelRun(runId)` so no gateway run is
     * orphaned (the gap note records whether a cancel was requested). Auth
     * (401/403) and unknown-classified errors still throw.
     */
    streamRun(body: StreamRunBody, handlers: RunEventStreamHandlers, options?: {
        signal?: AbortSignal;
    }): Promise<CapabilityResult<RunStreamOutcome>>;
    submitBatch(requests: RuntimeBatchRequest[]): Promise<CapabilityResult<RuntimeBatchStatus>>;
    getBatch(batchId: string): Promise<CapabilityResult<RuntimeBatchStatus>>;
    cancelBatch(batchId: string): Promise<CapabilityResult<RuntimeBatchStatus>>;
    getBatchResults(batchId: string): Promise<CapabilityResult<RuntimeBatchResult[]>>;
    readonly sessions: CapabilityGated<SessionClient>;
    readonly tasks: CapabilityGated<TaskClient>;
    readonly events: CapabilityGated<RuntimeEventClient>;
    readonly models: CapabilityGated<ModelCatalogClient>;
    readonly usage: CapabilityGated<UsageClient>;
    readonly authStatus: CapabilityGated<AuthStatusClient>;
    readonly workspace: CapabilityGated<WorkspaceClient>;
    readonly kanban: CapabilityGated<KanbanClient>;
    readonly teams: CapabilityGated<TeamDirectory>;
    readonly media: CapabilityGated<GatewayMediaClient>;
    readonly wiki: CapabilityGated<GatewayWikiClient>;
    readonly agentConfig: CapabilityGated<GatewayAgentConfigClient>;
}

CapabilityClientBackends#

Kind: type

ts
export type CapabilityClientBackends = {
    /** Control-plane backing for sessions/tasks/events/models/usage/authStatus/workspace. */
    controlPlane?: LazyAsync<RuntimeControlClient>;
    kanban?: LazyAsync<KanbanClient>;
    media?: LazyAsync<GatewayMediaClient>;
    wiki?: LazyAsync<GatewayWikiClient>;
    agentConfig?: LazyAsync<GatewayAgentConfigClient>;
    /** Supply the directory or a sync factory. */
    teams?: TeamDirectory | (() => TeamDirectory);
};

CapabilityGated#

Kind: type

ts
export type CapabilityGated<T> = {
    readonly [K in keyof T]-?: CapabilityGatedMethod<NonNullable<T[K]>>;
};

CapabilityGatedMethod#

Kind: type

ts
/** A backend surface re-typed to the non-throwing facade contract. */
export type CapabilityGatedMethod<F> = F extends (...args: infer A) => Promise<infer R> ? (...args: A) => Promise<CapabilityResult<R>> : F extends (...args: infer A) => infer R ? (...args: A) => Promise<CapabilityResult<R>> : F extends object ? CapabilityGated<F> : never;

CapabilityGroup#

Kind: type

ts
export type CapabilityGroup = keyof typeof CAPABILITY_GROUPS;

CapabilityKey#

Kind: type

ts
export type CapabilityKey = (typeof CAPABILITY_TAXONOMY)[number];

CapabilityMap#

Kind: interface

ts
/**
 * A provider's capability profile over the unified taxonomy. Every provider
 * publishes exactly one of these (Phase 2 makes it the single declaration
 * site); the client exposes the full surface and gates each call on it.
 */
export interface CapabilityMap {
    providerKind: string;
    supports: CapabilitySupport;
}

CapabilityResult#

Kind: type

ts
/**
 * The non-throwing capability contract (design decision 2026-07-21): every
 * facade method resolves one of these. `ok: false` states honestly that
 * nothing happened and why — there is no mock data and no fabricated success.
 * The only throws left on the facade are auth errors (401/403) and
 * unknown-classified errors, the same carve-outs as `withFallback`.
 */
export type CapabilityResult<T> = {
    ok: true;
    data: T;
    source: "live";
} | {
    ok: false;
    data: null;
    gap: ContractGap;
};

CapabilitySupport#

Kind: type

ts
/** A provider's declared support for each capability. Absent key ⇒ unsupported. */
export type CapabilitySupport = Partial<Record<CapabilityKey, boolean>>;

CapabilityUnavailable#

Kind: class

ts
export declare class CapabilityUnavailable extends Error {
    readonly providerId: string;
    readonly capability: string;
    readonly name = "CapabilityUnavailable";
    constructor(providerId: string, capability: string);
}

checkProtocolVersion#

Kind: function

ts
/** Compare a provider's reported protocol version against the expected one. */
export declare function checkProtocolVersion(carrier: ProtocolVersionCarrier, expected: string): ProtocolVersionCheck;

classifyCapabilityFailure#

Kind: function

ts
/**
 * Classify a failed capability call into a gap, preserving the envelope
 * contract's carve-outs: auth errors and unknown-classified errors rethrow.
 * HTTP 4xx caller errors (except 401/403/404) become `request-invalid`.
 *
 * 404 and 5xx are classified explicitly here rather than left to
 * `classifyFallbackError`: that classifier only recognizes `GatewayHttpError`
 * instances via `instanceof`, so a bare `{ status }` error (as thrown by
 * non-gateway transports) would otherwise fall through as `unknown`.
 * This deliberately diverges from `classifyFallbackError` for the 4xx band
 * (e.g. it reports `GatewayHttpError` 429 as `request-invalid`, not
 * `backend-unavailable`) because 4xx other than 401/403/404 is a caller
 * error, not backend degradation.
 */
export declare function classifyCapabilityFailure(params: {
    error: unknown;
    area: string;
    expectedContract: string;
    call: string;
}): ContractGap;

classifyFallbackError#

Kind: function

ts
export declare function classifyFallbackError(error: unknown): {
    message: string;
    reason: ContractGapReason;
    httpStatus?: number;
};

composeRunEventProviders#

Kind: function

ts
/**
 * Fan a single subscription out to multiple providers. Events from each
 * provider are forwarded to the shared handler in arrival order; disposing the
 * composite disposes every child subscription. Errors from any child are
 * surfaced via {@link RunEventStreamHandlers.onError}; the others keep running
 * unless the consumer disposes.
 */
export declare function composeRunEventProviders(...providers: RunEventStreamProvider[]): RunEventStreamProvider;

ConnectivityDomain#

Kind: type

ts
export type ConnectivityDomain = {
    domain: string;
    label: string;
    transport: "ws" | "http" | "mixed";
    source: DataSourceMode | "not-loaded";
    status: ConnectivityStatus;
    contractGaps: readonly ContractGap[];
    fetchedAt: number | null;
};

ConnectivityStatus#

Kind: type

ts
export type ConnectivityStatus = "live" | "empty-but-valid" | "mock-fallback" | "conditional-unavailable" | "not-loaded";

ContractGap#

Kind: type

ts
export type ContractGap = {
    area: string;
    expectedContract: string;
    note: string;
    reason?: ContractGapReason;
    httpStatus?: number;
};

ContractGapReason#

Kind: type

ts
export type ContractGapReason = "backend-unavailable" | "backend-not-configured" | "endpoint-not-found" | "auth-insufficient" | "transport-disconnected" | "capability-unsupported" | "request-invalid" | "request-aborted" | "unknown";

createApiClient#

Kind: function

ts
export declare function createApiClient(provider: string, options?: CreateApiClientOptions): CapabilityClient;

CreateApiClientOptions#

Kind: type

ts
export type CreateApiClientOptions = {
    /** Provider registry; defaults to the built-in gateway modules. */
    registry?: RuntimeProviderRegistry;
    baseUrl?: string;
    /** Gateway WebSocket URL; derived from `baseUrl` when omitted. */
    webSocketUrl?: string;
    token?: string;
    fetchImpl?: typeof fetch;
    /** Advertised WS client id for gateways that validate it. */
    clientId?: string;
    /**
     * `Origin` header for the gateway WebSocket handshake. Origin-gated gateways
     * reject connections whose origin is absent/not allowlisted; Node clients
     * send no Origin by default. Defaults to the gateway's own base origin (which
     * is typically allowlisted). Set explicitly to override.
     */
    clientOrigin?: string;
    /**
     * Advertised WS client mode (e.g. `"cli"`, `"webchat"`). Gateways bind the
     * scope-preservation and device-identity policy to the mode: a headless
     * operator client on loopback uses `"cli"` so shared-secret auth keeps its
     * operator scopes instead of being downgraded to read-only.
     */
    clientMode?: string;
    /**
     * Operator scopes to request on the WS connect handshake. Omit for the
     * gateway default (read-only). Request `operator.write` to start runs.
     */
    requestedScopes?: readonly string[];
    /** Manifest team id for this gateway instance. */
    teamId?: string;
    /** Override the auto-wired runtime capability resolver. */
    resolver?: ProviderCapabilityResolver;
    /** Extend/override the auto-wired backends. */
    backends?: CapabilityClientBackends;
    /** Override the static fallback declaration. */
    fallbackSupports?: CapabilitySupport;
};

createCachedManifestSource#

Kind: function

ts
/**
 * A manifest fetched via a loader (e.g. from a gateway). Cached after first
 * load; call refresh() to revalidate.
 */
export declare function createCachedManifestSource(loader: TeamManifestLoader): CachedTeamManifestSource;

createCapabilityClient#

Kind: function

ts
export declare function createCapabilityClient(options: CreateCapabilityClientOptions): CapabilityClient;

CreateCapabilityClientOptions#

Kind: type

ts
export type CreateCapabilityClientOptions = {
    providerKind: string;
    runtime: RuntimeClient;
    /** Static declaration used until (or when) runtime resolution is available. */
    fallbackSupports?: CapabilitySupport;
    /** Runtime-authoritative source; transport failures degrade to the fallback. */
    resolver?: ProviderCapabilityResolver;
    backends?: CapabilityClientBackends;
    /** Which providers serve a capability — enriches the notated gap. */
    availableOn?: (key: CapabilityKey) => readonly string[];
    /**
     * Gateway streaming transport: start the run and pump canonical run-stream
     * events into the handlers. Used when the runtime client itself has no
     * `streamRun` (gateways). Wired by `createApiClient`.
     */
    streamRunBridge?: (body: StreamRunBody, handlers: RunEventStreamHandlers, options?: {
        signal?: AbortSignal;
        /** Invoked with the run id as soon as the run starts (before events). */
        onRunId?: (runId: string) => void;
    }) => Promise<void>;
    /** Extra teardown run by dispose() after the control plane is disposed. */
    onDispose?: () => Promise<void> | void;
};

createDefaultTeamManifest#

Kind: function

ts
export declare function createDefaultTeamManifest(options?: CreateDefaultTeamManifestOptions): TeamManifest;

CreateDefaultTeamManifestOptions#

Kind: type

ts
export type CreateDefaultTeamManifestOptions = {
    teamId?: string;
    memberId?: string;
    workspaceRootPath?: string | null;
    workspacePaths?: readonly TeamWorkspacePathEntry[] | null;
};

createGatewayAgentConfigClient#

Kind: function

ts
export declare function createGatewayAgentConfigClient(clientOptions: HttpApiClientOptions, providerOptions?: ResolveGatewayProviderOptions): GatewayAgentConfigApiClient;

createGatewayApiClient#

Kind: function

ts
export declare function createGatewayApiClient(clientOptions: HttpApiClientOptions, providerOptions?: ResolveGatewayProviderOptions): GatewayApiClient;

createGatewayMediaClient#

Kind: function

ts
export declare function createGatewayMediaClient(clientOptions: HttpApiClientOptions, providerOptions?: ResolveGatewayProviderOptions): GatewayMediaApiClient;

createGatewayProviderRegistry#

Kind: function

ts
export declare function createGatewayProviderRegistry(options?: CreateGatewayProviderRegistryOptions): GatewayProviderRegistry;

CreateGatewayProviderRegistryOptions#

Kind: type

ts
export type CreateGatewayProviderRegistryOptions = CreateProviderRegistryOptions<GatewayProviderModule>;

createGatewayRpcClient#

Kind: variable

ts
export declare const createGatewayRpcClient: typeof createGatewayWebSocketClient;

createGatewaySseRunEventProvider#

Kind: function

ts
export declare function createGatewaySseRunEventProvider(options: CreateGatewaySseRunEventProviderOptions, providerOptions?: ResolveGatewayProviderOptions): GatewaySseRunEventProvider;

CreateGatewaySseRunEventProviderOptions#

Kind: type

ts
export type CreateGatewaySseRunEventProviderOptions = GatewaySseRunEventProviderOptions & {
    sessionKey?: string;
};

createGatewayWebSocketClient#

Kind: function

ts
export declare function createGatewayWebSocketClient(wsUrl: string, authToken: string | null, clientOptions?: GatewayWebSocketClientOptions, providerOptions?: ResolveGatewayProviderOptions): GatewayWebSocketClient;

createGatewayWikiClient#

Kind: function

ts
export declare function createGatewayWikiClient(clientOptions: HttpApiClientOptions, providerOptions?: ResolveGatewayProviderOptions): GatewayWikiApiClient;

createProviderRegistry#

Kind: function

ts
export declare function createProviderRegistry<M extends RuntimeProviderModule>(options?: CreateProviderRegistryOptions<M>): ProviderRegistry<M>;

CreateProviderRegistryOptions#

Kind: type

ts
export type CreateProviderRegistryOptions<M extends RuntimeProviderModule = GatewayProviderModule> = CreateRuntimeProviderRegistryOptions<M>;

createRunStreamWithToolFallback#

Kind: function

ts
/**
 * Wraps a primary {@link RunEventStreamProvider} with a tool-event fallback
 * that fires only when the primary's run completes without ever emitting tool
 * events. Used to bridge the gap while the Hermes SSE protocol does not yet
 * surface `tool.call.*` events natively: the
 * {@link RunPreviewPollProvider}-backed fallback stitches tool events in from
 * the post-hoc run preview. When the primary starts emitting tool events
 * natively, the fallback becomes a no-op automatically.
 */
export declare function createRunStreamWithToolFallback(options: CreateRunStreamWithToolFallbackOptions): RunEventStreamProvider;

CreateRunStreamWithToolFallbackOptions#

Kind: type

ts
export type CreateRunStreamWithToolFallbackOptions = {
    /** Authoritative source for lifecycle + (eventually) tool events. */
    primary: RunEventStreamProvider;
    /**
     * One-shot fallback that fires only after the primary emits `run.completed`
     * AND the primary did not emit any tool events during the run. Typically a
     * {@link RunPreviewPollProvider}. Optional — when omitted the composer
     * behaves like `primary` alone.
     */
    toolEventFallback?: RunEventStreamProvider;
};

createRuntimeClient#

Kind: function

ts
export declare function createRuntimeClient(provider: string, options: CreateRuntimeClientOptions): RuntimeClient;

CreateRuntimeClientOptions#

Kind: type

ts
export type CreateRuntimeClientOptions = {
    registry: RuntimeProviderRegistry;
    clientOptions: RuntimeClientOptions;
};

createRuntimeControlClient#

Kind: function

ts
export declare function createRuntimeControlClient(provider: string, options?: RuntimeControlClientOptions): Promise<RuntimeControlClient>;

createRuntimeControlExtensionRegistry#

Kind: function

ts
export declare function createRuntimeControlExtensionRegistry(entries?: Iterable<RuntimeControlExtensionEntry>): RuntimeControlExtensionRegistry;

createRuntimeProviderRegistry#

Kind: function

ts
export declare function createRuntimeProviderRegistry(options?: CreateProviderRegistryOptions<RuntimeProviderModule>): ProviderRegistry<RuntimeProviderModule>;

createStaticManifestSource#

Kind: function

ts
/** A fixed, host-provided manifest. Normalized once. */
export declare function createStaticManifestSource(manifest: TeamManifestInput): TeamManifestSource;

createSurfacePathResolver#

Kind: function

ts
export declare function createSurfacePathResolver(extensionContracts?: SurfaceContractMap, baseResolver?: SurfacePathResolver): SurfacePathResolver;

createTeamRouteResolver#

Kind: function

ts
export declare function createTeamRouteResolver(): TeamRouteResolver;

CredentialHeaders#

Kind: type

ts
/** Auth headers a credential resolver contributes to a request. */
export type CredentialHeaders = Record<string, string>;

CredentialResolver#

Kind: type

ts
/**
 * Provider-supplied auth scheme. Returns the headers to merge onto a request.
 * Closes over whatever secret the provider needs (token, api key, cookie).
 */
export type CredentialResolver = () => CredentialHeaders;

DataEnvelope#

Kind: type

ts
export type DataEnvelope<TData> = {
    data: TData;
    source: DataSourceMode;
    fetchedAt: number;
    contractGaps: ContractGap[];
};

DataSourceMode#

Kind: type

ts
export type DataSourceMode = "gateway" | "mock";

declaredCapabilities#

Kind: function

ts
/** The set of capability keys a provider declares supported. */
export declare function declaredCapabilities(provider: DeclaredProviderKey): CapabilityKey[];

DEFAULT_TEAM_ID#

Kind: variable

ts
export declare const DEFAULT_TEAM_ID: "default";

DEFAULT_TEAM_MEMBER_ID#

Kind: variable

ts
export declare const DEFAULT_TEAM_MEMBER_ID: "default-agent";

DEFAULT_TEAM_ROUTE_KEYS#

Kind: variable

ts
export declare const DEFAULT_TEAM_ROUTE_KEYS: readonly [
    "kanban",
    "runs",
    "config",
    "workspace"
];

DefaultTeamRouteKey#

Kind: type

ts
export type DefaultTeamRouteKey = (typeof DEFAULT_TEAM_ROUTE_KEYS)[number];

defineRuntimeControlExtension#

Kind: function

ts
export declare function defineRuntimeControlExtension<T>(id: string): RuntimeControlExtensionDescriptor<T>;

estimateUsageCost#

Kind: function

ts
/**
 * Estimate run cost from normalized usage + consumer-supplied prices. The
 * package ships NO price table — prices are always the caller's. Any missing
 * token count or price contributes 0.
 */
export declare function estimateUsageCost(usage: RuntimeUsage, prices: TokenPrices): number;

fallbackGap#

Kind: function

ts
export declare function fallbackGap(area: string, expectedContract: string, note: string, reason?: ContractGapReason, httpStatus?: number): ContractGap;

FallbackResolveInfo#

Kind: type

ts
export type FallbackResolveInfo = {
    source: "gateway" | "mock";
    fellBack: boolean;
    area: string;
};

findTeamActionContract#

Kind: function

ts
export declare function findTeamActionContract(actions: readonly TeamActionContract[] | null | undefined, actionId: string | null | undefined): TeamActionContract | null;

findTeamManifestMember#

Kind: function

ts
export declare function findTeamManifestMember(team: ManifestTeam, memberId: string | null | undefined): ManifestMember | null;

findTeamManifestTeam#

Kind: function

ts
export declare function findTeamManifestTeam(manifest: TeamManifest, teamId: string | null | undefined): ManifestTeam | null;

gapResult#

Kind: function

ts
export declare function gapResult<T>(gap: ContractGap): CapabilityResult<T>;

GATEWAY_API_ENDPOINT_TEMPLATES#

Kind: variable

ts
export declare const GATEWAY_API_ENDPOINT_TEMPLATES: {
    readonly ecgSharedFiles: "/api/v1/files?agent={agent}&folder={folder}";
    readonly runApproval: "/v1/runs/{run_id}/approval";
};

GATEWAY_API_ENDPOINTS#

Kind: variable

ts
export declare const GATEWAY_API_ENDPOINTS: {
    readonly health: "/health";
    readonly healthDetailed: "/health/detailed";
    readonly models: "/v1/models";
    readonly capabilities: "/v1/capabilities";
    readonly chatCompletions: "/v1/chat/completions";
    readonly responses: "/v1/responses";
    readonly response: (responseId: string) => string;
    readonly runs: "/v1/runs";
    readonly run: (runId: string) => string;
    readonly runEvents: (runId: string) => string;
    readonly runApproval: (runId: string) => string;
    readonly runStop: (runId: string) => string;
    readonly jobs: "/api/jobs";
    readonly job: (jobId: string) => string;
};

GATEWAY_MEDIA_API_BASE_PATH#

Kind: variable

ts
export declare const GATEWAY_MEDIA_API_BASE_PATH: "/v1/media";

GATEWAY_MEDIA_API_ENDPOINTS#

Kind: variable

ts
export declare const GATEWAY_MEDIA_API_ENDPOINTS: {
    readonly root: "/v1/media";
    readonly providers: (kind?: string | null) => string;
    readonly generate: (kind: string) => string;
    readonly job: (kind: string, jobId: string) => string;
    readonly assets: (query?: {
        kind?: string | null;
        cursor?: string | null;
        limit?: number | null;
    } | null) => string;
    readonly asset: (assetId: string) => string;
};

GATEWAY_PROBE_ENDPOINTS#

Kind: variable

ts
export declare const GATEWAY_PROBE_ENDPOINTS: {
    readonly health: "/health";
    readonly healthz: "/healthz";
    readonly readyz: "/readyz";
};

GATEWAY_PROVIDER_ENV_KEYS#

Kind: variable

ts
export declare const GATEWAY_PROVIDER_ENV_KEYS: readonly [
    "CAVI_GATEWAY_PROVIDER",
    "GATEWAY_PROVIDER"
];

GATEWAY_RAW_EXTENSION#

Kind: variable

ts
export declare const GATEWAY_RAW_EXTENSION: RuntimeControlExtensionDescriptor<RawGatewayChannel>;

GATEWAY_SYSTEM_RPC_METHODS#

Kind: variable

ts
export declare const GATEWAY_SYSTEM_RPC_METHODS: {
    readonly healthSnapshot: "health.snapshot";
    readonly health: "health";
    readonly logsTail: "logs.tail";
};

GATEWAY_WIKI_API_BASE_PATH#

Kind: variable

ts
export declare const GATEWAY_WIKI_API_BASE_PATH: "/v1/wiki";

GATEWAY_WIKI_API_ENDPOINTS#

Kind: variable

ts
export declare const GATEWAY_WIKI_API_ENDPOINTS: {
    readonly root: "/v1/wiki";
    readonly vaults: "/v1/wiki/vaults";
    readonly vault: (vaultId: string) => string;
    readonly tree: (vaultId: string) => string;
    readonly read: (vaultId: string, path: string) => string;
    readonly ingest: (vaultId: string) => string;
    readonly compile: (vaultId: string) => string;
    readonly promote: (vaultId: string) => string;
    readonly job: (vaultId: string, jobId: string) => string;
    readonly artifact: (vaultId: string, artifactId: string) => string;
};

GatewayApiClient#

Kind: class

ts
export declare class GatewayApiClient extends BaseHttpApiClient implements RuntimeClient {
    readonly endpoints: {
        readonly health: "/health";
        readonly healthDetailed: "/health/detailed";
        readonly models: "/v1/models";
        readonly capabilities: "/v1/capabilities";
        readonly chatCompletions: "/v1/chat/completions";
        readonly responses: "/v1/responses";
        readonly response: (responseId: string) => string;
        readonly runs: "/v1/runs";
        readonly run: (runId: string) => string;
        readonly runEvents: (runId: string) => string;
        readonly runApproval: (runId: string) => string;
        readonly runStop: (runId: string) => string;
        readonly jobs: "/api/jobs";
        readonly job: (jobId: string) => string;
    };
    readonly request: HttpApiTransport;
    constructor(options: HttpApiClientOptions, surface?: string);
    getCapabilities(): Promise<GatewayCapabilities>;
    getFeatureCapabilities(options?: Omit<NormalizeGatewayFeatureCapabilitiesOptions, "capabilities">): Promise<NormalizedGatewayFeatureCapabilities>;
    getRuntimeCapabilities(): Promise<RuntimeCapabilities>;
    cancelRun(runId: string): Promise<{
        status: string;
    }>;
    startRun(body: GatewayRunStartBody): Promise<GatewayRunStatus>;
    getRun(runId: string): Promise<GatewayRunStatus>;
    private withNormalizedUsage;
    stopRun(runId: string): Promise<{
        status: string;
    }>;
    resolveRunApproval<T = unknown>(runId: string, body: {
        approved: boolean;
        reason?: string;
    }, idempotencyKey?: string): Promise<T>;
}

GatewayCapabilities#

Kind: type

ts
export type GatewayCapabilities = GatewayCommandCapabilities & {
    object?: string;
    platform?: string;
    model?: string;
    auth?: {
        type?: string;
        required?: boolean;
    };
    features: Record<string, unknown>;
    endpoints?: Record<string, {
        method: string;
        path: string;
    }>;
    runtime?: Record<string, unknown>;
};

GatewayHttpError#

Kind: class

ts
export declare class GatewayHttpError extends Error {
    readonly type = ApiClientErrorType.GatewayHttp;
    readonly status: number;
    readonly code: string | null;
    constructor(message: string, status: number, code?: string | null);
}

GatewayProviderEnv#

Kind: type

ts
export type GatewayProviderEnv = Record<string, string | undefined>;

GatewayProviderFactories#

Kind: interface

ts
export interface GatewayProviderFactories {
    createApiClient?: (clientOptions: HttpApiClientOptions) => GatewayApiClient;
    createWebSocketClient?: (wsUrl: string, authToken: string | null, clientOptions: GatewayWebSocketClientOptions) => GatewayWebSocketClient;
    createSseRunEventProvider?: (options: CreateGatewaySseRunEventProviderOptions) => GatewaySseRunEventProvider;
    createMediaClient?: (clientOptions: HttpApiClientOptions) => GatewayMediaApiClient;
    createWikiClient?: (clientOptions: HttpApiClientOptions) => GatewayWikiApiClient;
    createAgentConfigClient?: (clientOptions: HttpApiClientOptions) => GatewayAgentConfigApiClient;
}

GatewayProviderKind#

Kind: type

ts
export type GatewayProviderKind = "hermes" | "openclaw" | (string & {});

GatewayProviderModule#

Kind: interface

ts
export interface GatewayProviderModule extends RuntimeProviderModule, GatewayProviderFactories {
    /** Gateway providers return the gateway-capable client. */
    createApiClient?: (clientOptions: HttpApiClientOptions) => GatewayApiClient;
}

GatewayProviderRegistry#

Kind: type

ts
export type GatewayProviderRegistry = ProviderRegistry<GatewayProviderModule>;

GatewayResolvedRouteBinding#

Kind: type

ts
export type GatewayResolvedRouteBinding = {
    id: string;
    teamId: string;
    memberId: string | null;
    source: string | null;
    channel: string | null;
    actionId: string | null;
    routeKey: TeamRouteKey;
    path: string;
    metadata?: Record<string, unknown> | null;
};

GatewayRouteBinding#

Kind: type

ts
export type GatewayRouteBinding = {
    id: string;
    teamId: string;
    memberId?: string | null;
    source?: string | null;
    channel?: string | null;
    actionId?: string | null;
    routeKey?: TeamRouteKey | null;
    sessionKeyPattern?: string | null;
    metadata?: Record<string, unknown> | null;
};

GatewayRunAttachment#

Kind: type

ts
export type GatewayRunAttachment = {
    name: string;
    mimeType?: string;
    mime_type?: string;
    size?: number;
    dataBase64?: string;
    data_base64?: string;
    [key: string]: unknown;
};

GatewayRunMessage#

Kind: type

ts
export type GatewayRunMessage = RuntimeRunMessage;

GatewayRunStartBody#

Kind: type

ts
export type GatewayRunStartBody = RuntimeRunStartBody & {
    session_id?: string;
    sessionKey?: string;
    session_key?: string;
    previous_response_id?: string;
    conversation_history?: GatewayRunMessage[];
    targetProfile?: string;
    target_profile?: string;
    targetAgent?: string;
    target_agent?: string;
    agentId?: string;
    agent_id?: string;
    action?: string;
    source?: Record<string, unknown>;
    attachments?: GatewayRunAttachment[];
    dry_run?: boolean;
};

GatewayRunStatus#

Kind: type

ts
export type GatewayRunStatus = RuntimeRunStatus & {
    object?: string;
    session_id?: string;
    targetProfile?: string;
    task_id?: string;
    routing?: {
        kind?: string;
        targetProfile?: string | null;
        taskId?: string | null;
        workerEventStream?: boolean;
        decision?: Record<string, unknown>;
    };
    events?: Record<string, unknown>[];
    tool_call_count?: number;
};

getBrowserWindowOrigin#

Kind: function

ts
export declare function getBrowserWindowOrigin(): string | null;

getErrorCode#

Kind: function

ts
export declare function getErrorCode(error: unknown): string | undefined;

getErrorMessage#

Kind: function

ts
export declare function getErrorMessage(error: unknown, fallbackMessage?: string): string;

getErrorStatus#

Kind: function

ts
/**
 * HTTP status carried by a typed transport error (`HttpApiError`,
 * `GatewayHttpError`, or any error exposing a numeric `status`). `undefined`
 * for non-HTTP failures (transport, abort, RPC) so callers branch on the value,
 * never on the message string.
 */
export declare function getErrorStatus(error: unknown): number | undefined;

getErrorType#

Kind: function

ts
export declare function getErrorType(error: unknown): string | undefined;

getRuntimeErrorMetadata#

Kind: function

ts
export declare function getRuntimeErrorMetadata(error: unknown): RuntimeErrorMetadata | undefined;

getRuntimeProviderCapabilityRow#

Kind: function

ts
export declare function getRuntimeProviderCapabilityRow(provider: string): RuntimeProviderCapabilityRow | undefined;

getTransportErrorMetadata#

Kind: function

ts
export declare function getTransportErrorMetadata(error: unknown): TransportErrorMetadata | undefined;

GLOBAL_REPO_ROOT_KEY#

Kind: variable

ts
export declare const GLOBAL_REPO_ROOT_KEY: "__CAVI_REPO_ROOT__";

HERMES_API_ENDPOINT_TEMPLATES#

Kind: variable

ts
export declare const HERMES_API_ENDPOINT_TEMPLATES: {
    readonly ecgSharedFiles: "/api/v1/files?agent={agent}&folder={folder}";
    readonly runApproval: "/v1/runs/{run_id}/approval";
};

HERMES_API_ENDPOINTS#

Kind: variable

ts
export declare const HERMES_API_ENDPOINTS: {
    readonly health: "/health";
    readonly healthDetailed: "/health/detailed";
    readonly models: "/v1/models";
    readonly capabilities: "/v1/capabilities";
    readonly chatCompletions: "/v1/chat/completions";
    readonly responses: "/v1/responses";
    readonly response: (responseId: string) => string;
    readonly runs: "/v1/runs";
    readonly run: (runId: string) => string;
    readonly runEvents: (runId: string) => string;
    readonly runApproval: (runId: string) => string;
    readonly runStop: (runId: string) => string;
    readonly jobs: "/api/jobs";
    readonly job: (jobId: string) => string;
};

HERMES_MEDIA_API_ENDPOINTS#

Kind: variable

ts
export declare const HERMES_MEDIA_API_ENDPOINTS: {
    readonly root: "/v1/media";
    readonly providers: (kind?: string | null) => string;
    readonly generate: (kind: string) => string;
    readonly job: (kind: string, jobId: string) => string;
    readonly assets: (query?: {
        kind?: string | null;
        cursor?: string | null;
        limit?: number | null;
    } | null) => string;
    readonly asset: (assetId: string) => string;
};

HERMES_WIKI_API_ENDPOINTS#

Kind: variable

ts
export declare const HERMES_WIKI_API_ENDPOINTS: {
    readonly root: "/v1/wiki";
    readonly vaults: "/v1/wiki/vaults";
    readonly vault: (vaultId: string) => string;
    readonly tree: (vaultId: string) => string;
    readonly read: (vaultId: string, path: string) => string;
    readonly ingest: (vaultId: string) => string;
    readonly compile: (vaultId: string) => string;
    readonly promote: (vaultId: string) => string;
    readonly job: (vaultId: string, jobId: string) => string;
    readonly artifact: (vaultId: string, artifactId: string) => string;
};

HttpApiClientAuth#

Kind: type

ts
export type HttpApiClientAuth = {
    bearerToken?: string | null;
    clientId?: string | null;
    /**
     * Provider-supplied auth scheme. When present, its headers replace the
     * default bearer Authorization header. See core/http/credentials.ts.
     */
    resolveHeaders?: CredentialResolver;
};

HttpApiClientOptions#

Kind: type

ts
export type HttpApiClientOptions = {
    baseUrl: string;
    basePath?: string;
    allowRelativeBaseUrl?: boolean;
    defaultHeaders?: Record<string, string>;
    /** Send the X-Portal-Client-Id header. Default true; set false for non-gateway backends. */
    includePortalClientIdHeader?: boolean;
    auth?: HttpApiClientAuth;
    defaultTimeoutMs?: number;
    fetchImpl?: typeof fetch;
    cache?: RequestCache;
    credentials?: RequestCredentials;
    onTrace?: (trace: HttpApiTrace) => void;
};

HttpApiClientSurface#

Kind: type

ts
export type HttpApiClientSurface = string;

HttpApiError#

Kind: class

ts
export declare class HttpApiError extends Error {
    readonly type = ApiClientErrorType.Http;
    readonly code = ApiClientErrorCode.HttpRequestFailed;
    readonly path: string;
    readonly url: string;
    readonly method: HttpApiHttpMethod;
    readonly status: number;
    readonly body: string;
    constructor(params: {
        message: string;
        path: string;
        url: string;
        method: HttpApiHttpMethod;
        status: number;
        body: string;
    });
}

HttpApiHttpMethod#

Kind: type

ts
export type HttpApiHttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

HttpApiRequestInit#

Kind: type

ts
export type HttpApiRequestInit = {
    method?: HttpApiHttpMethod;
    body?: unknown;
    rawBody?: BodyInit;
    headers?: Record<string, string>;
    signal?: AbortSignal;
    timeoutMs?: number;
    idempotencyKey?: string;
    cache?: RequestCache;
    credentials?: RequestCredentials;
};

HttpApiTrace#

Kind: type

ts
export type HttpApiTrace = {
    at: number;
    surface: HttpApiClientSurface;
    method: HttpApiHttpMethod;
    path: string;
    url: string;
    ok: boolean;
    status?: number;
    durationMs: number;
    error?: string;
};

HttpApiTransport#

Kind: type

ts
export type HttpApiTransport = <TResponse>(path: string, init?: HttpApiRequestInit) => Promise<TResponse>;

IDEMPOTENCY_KEY_HEADER#

Kind: variable

ts
export declare const IDEMPOTENCY_KEY_HEADER: "Idempotency-Key";

inspectRuntimeEventSequence#

Kind: function

ts
export declare function inspectRuntimeEventSequence(events: readonly RuntimeControlPlaneEvent[]): RuntimeEventSequenceInspection;

isAbortError#

Kind: function

ts
export declare function isAbortError(error: unknown): boolean;

isAuthError#

Kind: function

ts
/**
 * True when an error is an authentication/authorization failure (HTTP 401/403,
 * or a synthesized `Auth`-typed/`auth_required`/`auth_forbidden` error). Use
 * this to trigger token refresh or re-auth instead of inspecting `.status`
 * inline at every call site.
 */
export declare function isAuthError(error: unknown): boolean;

isCapabilityKey#

Kind: function

ts
/** Narrow an arbitrary string to a `CapabilityKey`. */
export declare function isCapabilityKey(value: string): value is CapabilityKey;

isEndpointNotFoundError#

Kind: function

ts
/**
 * True when an error is a synthesized `EndpointNotFound` failure — the
 * everyday cross-provider branch for a surface a provider declares
 * unsupported (Gemini `getRun`/`cancelRun`, OpenClaw wiki/media).
 */
export declare function isEndpointNotFoundError(error: unknown): boolean;

isGatewayHttpError#

Kind: function

ts
export declare function isGatewayHttpError(error: unknown): error is GatewayHttpError;

isHttpApiError#

Kind: function

ts
export declare function isHttpApiError(error: unknown): error is HttpApiError;

liveResult#

Kind: function

ts
export declare function liveResult<T>(data: T): CapabilityResult<T>;

ManifestIdentity#

Kind: type

ts
export type ManifestIdentity = {
    name?: string | null;
    displayName?: string | null;
    slug?: string | null;
    code?: string | null;
    aliases?: readonly string[] | null;
    /** Host/domain-specific identity hints (e.g. CAVI portalId/sector). Agnostic core never reads these. */
    metadata?: Record<string, unknown> | null;
};

ManifestMember#

Kind: type

ts
export type ManifestMember = {
    id: string;
    identity?: ManifestIdentity | null;
    workspace?: TeamWorkspaceConfig | null;
    actions?: readonly TeamActionContract[] | null;
    capabilities?: readonly string[] | null;
    metadata?: Record<string, unknown> | null;
};

ManifestRouteConfig#

Kind: type

ts
export type ManifestRouteConfig = {
    key: string;
    path?: string | null;
};

ManifestTeam#

Kind: type

ts
export type ManifestTeam = {
    id: string;
    identity?: ManifestIdentity | null;
    members?: readonly ManifestMember[] | null;
    workspace?: TeamWorkspaceConfig | null;
    actions?: readonly TeamActionContract[] | null;
    capabilities?: readonly string[] | null;
    routes?: readonly ManifestRouteConfig[] | null;
    metadata?: Record<string, unknown> | null;
};

manifestTeamToTeam#

Kind: function

ts
/** Project a manifest team onto the provider-agnostic core `Team`. */
export declare function manifestTeamToTeam(team: ManifestTeam): Team;

mergeCapabilitySupport#

Kind: function

ts
/**
 * Merge a runtime-resolved support map over the static fallback: runtime keys
 * win; the fallback fills whatever the runtime response did not mention. This
 * realizes "runtime authoritative, static fallback" for capability presence —
 * a static OpenClaw default that gates media/wiki off flips them on for an
 * instance whose capabilities endpoint reports them supported.
 */
export declare function mergeCapabilitySupport(fallback: CapabilitySupport, runtime: CapabilitySupport): CapabilitySupport;

ModelCatalogClient#

Kind: interface

ts
export interface ModelCatalogClient {
    listModels(query?: {
        cursor?: string;
        limit?: number;
    }): Promise<RuntimePage<RuntimeModelDescriptor>>;
}

MutationResult#

Kind: type

ts
export type MutationResult<TData> = {
    data: TData;
    source: DataSourceMode;
    appliedAt: number;
    contractGaps: ContractGap[];
};

normalizeGatewayProviderToken#

Kind: function

ts
export declare function normalizeGatewayProviderToken(value: string | null | undefined): string | null;

normalizeRuntimeBasePath#

Kind: function

ts
export declare function normalizeRuntimeBasePath(rawBasePath: string | null | undefined): string;

normalizeRuntimeProviderToken#

Kind: function

ts
export declare function normalizeRuntimeProviderToken(value: string | null | undefined): string | null;

normalizeRuntimeUsage#

Kind: function

ts
/**
 * Normalize a flat provider-native usage record into RuntimeUsage. Tolerant of
 * snake_case / camelCase across providers. Provider mappers are preferred where
 * the native (possibly nested) object is in hand; this covers callers holding
 * only the legacy flat `RuntimeRunStatus.usage`. `providerKind` is reserved for
 * future provider-specific disambiguation.
 */
export declare function normalizeRuntimeUsage(raw: Record<string, number> | undefined, providerKind: string): RuntimeUsage | undefined;

normalizeTeamManifest#

Kind: function

ts
export declare function normalizeTeamManifest(manifest: Partial<TeamManifest> | null | undefined): TeamManifest;

PORTAL_CLIENT_ID_HEADER#

Kind: variable

ts
export declare const PORTAL_CLIENT_ID_HEADER: "X-Portal-Client-Id";

ProtocolVersionCarrier#

Kind: type

ts
export type ProtocolVersionCarrier = {
    protocolVersion?: string | null;
};

ProtocolVersionCheck#

Kind: type

ts
export type ProtocolVersionCheck = {
    ok: boolean;
    expected: string;
    actual: string | null;
};

PROVIDER_CAPABILITIES#

Kind: variable

ts
export declare const PROVIDER_CAPABILITIES: {
    readonly claude: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly "claude-managed-agents": Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly codex: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly gemini: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly agy: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly hermes: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
    readonly openclaw: Partial<Record<"runs" | "streaming" | "media" | "wiki" | "agentConfig" | "teams" | "kanban" | "workspace" | "operator" | "discourse" | "batch" | "authStatus" | "sessions" | "models" | "usage" | "tasks" | "events", boolean>>;
};

ProviderCapabilityResolver#

Kind: type

ts
/**
 * A gateway provider supplies one of these: fetch its capabilities endpoint
 * and transform it into the unified shape. Runtime-only providers without a
 * capabilities endpoint omit it, and the static fallback is used unchanged.
 */
export type ProviderCapabilityResolver = (options?: {
    signal?: AbortSignal;
}) => Promise<ResolvedProviderCapabilities>;

ProviderRegistry#

Kind: type

ts
export type ProviderRegistry<M extends RuntimeProviderModule = GatewayProviderModule> = RuntimeProviderRegistry<M>;

RawGatewayChannel#

Kind: interface

ts
export interface RawGatewayChannel {
    request<TResult = unknown>(operationId: string, payload?: Readonly<Record<string, unknown>>, options?: RawGatewayRequestOptions): Promise<TResult>;
    subscribe(listener: (event: RawGatewayEvent) => void): () => void;
    getConnectionState(): RawGatewayConnectionState;
    onConnectionState(listener: (state: RawGatewayConnectionState) => void): () => void;
    connect(): Promise<void>;
    dispose(): Promise<void>;
}

RawGatewayConnectionState#

Kind: type

ts
export type RawGatewayConnectionState = "idle" | "connecting" | "reconnecting" | "connected" | "error";

RawGatewayEvent#

Kind: type

ts
export type RawGatewayEvent = Readonly<{
    event: string;
    payload: unknown;
}>;

RawGatewayRequestOptions#

Kind: type

ts
export type RawGatewayRequestOptions = Readonly<{
    signal?: AbortSignal;
}>;

REPO_ROOT_ENV_KEY#

Kind: variable

ts
export declare const REPO_ROOT_ENV_KEY: "REPO_ROOT";

RepoRootEnv#

Kind: type

ts
export type RepoRootEnv = Record<string, string | undefined>;

requireRepoRoot#

Kind: function

ts
export declare function requireRepoRoot(options?: ResolveRepoRootOptions): string;

ResolvedProviderCapabilities#

Kind: interface

ts
/**
 * The runtime-resolved capability + path picture for a live provider instance,
 * produced by fetching the provider's capabilities endpoint and transforming
 * the response. This is the AUTHORITATIVE source (design decision M1):
 *
 * - `supports` overrides the static `PROVIDER_CAPABILITIES` fallback, because
 *   capability presence is plugin/runtime dependent (e.g. OpenClaw media/wiki
 *   are gated off pre-plugin but live once the plugin is installed).
 * - `manifest` drives dynamic path resolution — members are agents, actions
 *   carry their real `route.path` — so no agent name (`machine`, `martina`,
 *   `deb`, …) or endpoint literal is ever hardcoded in the package.
 */
export interface ResolvedProviderCapabilities {
    providerKind: string;
    supports: CapabilitySupport;
    manifest: TeamManifest;
}

resolvedSupports#

Kind: function

ts
/** True iff, after merging runtime over fallback, the provider supports `key`. */
export declare function resolvedSupports(fallback: CapabilitySupport, runtime: CapabilitySupport | undefined, key: CapabilityKey): boolean;

resolveGatewayProviderKind#

Kind: function

ts
export declare function resolveGatewayProviderKind(options?: ResolveGatewayProviderOptions): GatewayProviderKind;

resolveGatewayProviderModule#

Kind: function

ts
export declare function resolveGatewayProviderModule(options?: ResolveGatewayProviderOptions): GatewayProviderModule | null;

ResolveGatewayProviderOptions#

Kind: type

ts
export type ResolveGatewayProviderOptions = {
    provider?: GatewayProviderKind | string | null;
    env?: GatewayProviderEnv;
    defaultProvider?: GatewayProviderKind | string | null;
    registry?: GatewayProviderRegistry | null;
    providerModules?: readonly GatewayProviderModule[] | null;
    allowProviderOverrides?: boolean;
};

resolveGatewayRouteBinding#

Kind: function

ts
export declare function resolveGatewayRouteBinding(manifest: TeamManifest, options: ResolveGatewayRouteBindingOptions): GatewayResolvedRouteBinding | null;

ResolveGatewayRouteBindingOptions#

Kind: type

ts
export type ResolveGatewayRouteBindingOptions = {
    bindingId?: string | null;
    source?: string | null;
    channel?: string | null;
    sessionKey?: string | null;
    key?: string | null;
    agentId?: string | null;
    actionId?: string | null;
};

resolvePath#

Kind: function

ts
export declare function resolvePath(key: string, params?: Record<string, string>): string;

resolvePublicRuntimeAsset#

Kind: function

ts
export declare function resolvePublicRuntimeAsset(pathname: string, rawBasePath: string | null | undefined): string;

resolveRepoRoot#

Kind: function

ts
export declare function resolveRepoRoot(options?: ResolveRepoRootOptions): string | null;

ResolveRepoRootOptions#

Kind: type

ts
export type ResolveRepoRootOptions = {
    repoRoot?: string | null;
    env?: RepoRootEnv;
    globalRepoRoot?: string | null;
};

resolveSurfaceContractPath#

Kind: function

ts
export declare function resolveSurfaceContractPath(contract: SurfaceContract, params?: Record<string, string>): string;

resolveTeamActionApiPath#

Kind: function

ts
export declare function resolveTeamActionApiPath(manifest: TeamManifest, teamId: string | null | undefined, actionId: string | null | undefined, options?: ResolveTeamActionContractOptions): string;

resolveTeamActionContract#

Kind: function

ts
export declare function resolveTeamActionContract(manifest: TeamManifest, teamId: string | null | undefined, actionId: string | null | undefined, options?: ResolveTeamActionContractOptions): TeamActionContract;

ResolveTeamActionContractOptions#

Kind: type

ts
export type ResolveTeamActionContractOptions = {
    memberId?: string | null;
    /** Values substituted into `{token}` placeholders in the action's route path. */
    params?: Record<string, string | number | boolean> | null;
    /** Query parameters appended to the resolved path (via `appendHttpQuery`). */
    query?: Record<string, string | number | boolean | undefined> | null;
};

resolveTeamRoutePath#

Kind: function

ts
export declare function resolveTeamRoutePath(routeKey: TeamRouteKey, options: ResolveTeamRoutePathOptions): string;

ResolveTeamRoutePathOptions#

Kind: type

ts
export type ResolveTeamRoutePathOptions = {
    teamId: string;
    actionId?: string | null;
    agentId?: string | null;
    workspacePath?: string | null;
};

resolveTeamWorkspaceApiPath#

Kind: function

ts
export declare function resolveTeamWorkspaceApiPath(team: ManifestTeam, keyOrPath: string, options?: ResolveTeamWorkspacePathOptions): string;

resolveTeamWorkspacePath#

Kind: function

ts
export declare function resolveTeamWorkspacePath(team: ManifestTeam, keyOrPath: string, options?: ResolveTeamWorkspacePathOptions): string;

ResolveTeamWorkspacePathOptions#

Kind: type

ts
export type ResolveTeamWorkspacePathOptions = {
    memberId?: string | null;
};

RUN_STREAM_EVENT_NAMES#

Kind: variable

ts
export declare const RUN_STREAM_EVENT_NAMES: {
    readonly MESSAGE_DELTA: "message.delta";
    readonly RUN_COMPLETED: "run.completed";
    readonly RUN_FAILED: "run.failed";
    readonly RUN_CANCELLED: "run.cancelled";
    readonly APPROVAL_REQUEST: "approval.request";
    readonly TOOL_CALL_STARTED: "tool.call.started";
    readonly TOOL_CALL_COMPLETED: "tool.call.completed";
    readonly TOOL_CALL_FAILED: "tool.call.failed";
};

RunEventStreamHandlers#

Kind: type

ts
export type RunEventStreamHandlers = {
    onEvent: (event: RunStreamEvent) => void;
    /**
     * Transport / parse errors. Lifecycle "run.failed" is delivered via onEvent,
     * not here.
     *
     * TERMINALITY: by default an `onError` is TERMINAL — it ends the stream and
     * (through the gateway bridge) rejects/settles the run. A provider that
     * surfaces a *per-frame*, NON-terminal error (e.g. a single malformed frame
     * on a still-live subscription) MUST mark it with
     * {@link markNonTerminalStreamError} so the bridge forwards it for
     * observability without tearing the stream down. Connection loss is terminal
     * and stays unmarked.
     */
    onError?: (error: unknown) => void;
    /** Fired once after the stream has emitted its last event of the run. */
    onComplete?: () => void;
};

RunEventStreamProvider#

Kind: interface

ts
/**
 * Harness-agnostic source of live run events. Implementations bind to a
 * transport and translate native messages into the canonical RunStreamEvent
 * union; every emitted event's `event` field MUST be one of
 * RUN_STREAM_EVENT_NAMES.
 */
export interface RunEventStreamProvider {
    subscribe(params: RunEventStreamSubscribeParams, handlers: RunEventStreamHandlers): Promise<RunEventStreamSubscription>;
}

RunEventStreamSubscribeParams#

Kind: type

ts
export type RunEventStreamSubscribeParams = {
    runId: string;
    /** Optional caller-supplied abort signal. Implementations MUST honor abort and dispose. */
    signal?: AbortSignal;
};

RunEventStreamSubscription#

Kind: type

ts
/** Disposes an active subscription. Idempotent. */
export type RunEventStreamSubscription = {
    dispose(): void | Promise<void>;
};

RunPreviewPollProvider#

Kind: class

ts
/**
 * Synthesizes tool events from {@link AgentRunPreviewItem}s by polling the
 * run-detail snapshot. Used as a stopgap until the Hermes SSE protocol emits
 * `tool.call.*` events natively.
 *
 * Default mode is one-shot: subscribe → fetch snapshot once → emit a
 * `tool.call.completed` event for each tool item → fire `onComplete` → dispose.
 *
 * For in-progress polling (multi-shot), pass `maxPolls > 1` and a
 * `pollIntervalMs`. The provider dedupes by `(toolName, at)` so the same tool
 * call is never emitted twice.
 *
 * This provider DOES NOT emit lifecycle events (`message.delta`,
 * `run.completed`, etc.). Compose it alongside a Hermes/gateway provider that
 * handles the lifecycle.
 */
export declare class RunPreviewPollProvider implements RunEventStreamProvider {
    private readonly fetchSnapshot;
    private readonly maxPolls;
    private readonly pollIntervalMs;
    constructor(options: RunPreviewPollProviderOptions);
    subscribe(params: RunEventStreamSubscribeParams, handlers: RunEventStreamHandlers): Promise<RunEventStreamSubscription>;
}

RunPreviewPollProviderOptions#

Kind: type

ts
export type RunPreviewPollProviderOptions = {
    /** Caller-supplied fetcher for the run-detail snapshot (mobile uses gateway loaders; web hits HTTP directly). */
    fetchSnapshot: RunPreviewSnapshotFetcher;
    /**
     * Cap on how many snapshots to poll before giving up. Each poll synthesizes
     * tool events for items newer than the previous snapshot.
     *
     * Set to 1 for one-shot "stitch tool events after run completed" usage.
     * Set higher to track in-progress tool calls before backend SSE catches up.
     */
    maxPolls?: number;
    /** Delay between polls when {@link maxPolls} > 1. */
    pollIntervalMs?: number;
};

RunPreviewSnapshotFetcher#

Kind: type

ts
export type RunPreviewSnapshotFetcher = (runId: string, signal?: AbortSignal) => Promise<AgentRunDetailSnapshot | null>;

RunStreamEvent#

Kind: type

ts
export type RunStreamEvent = RunStreamMessageDeltaEvent | RunStreamRunCompletedEvent | RunStreamRunFailedEvent | RunStreamRunCancelledEvent | RunStreamApprovalRequestEvent | RunStreamToolEvent;

RunStreamEventName#

Kind: type

ts
export type RunStreamEventName = (typeof RUN_STREAM_EVENT_NAMES)[keyof typeof RUN_STREAM_EVENT_NAMES];

RunStreamOutcome#

Kind: type

ts
/**
 * What a facade `streamRun` reports once its streaming CALL settles. `ok`
 * reflects the streaming call (did the stream run without a caller/transport
 * failure); this payload carries the RUN's own terminal state as data, so
 * `ok: true` with `outcome: "failed"` is coherent — the stream worked, the run
 * failed (run.failed is an event, already the contract).
 *
 * - `runId` — the run id: reported by a gateway bridge as soon as the run
 *   starts, otherwise captured from the first stream event carrying one; `null`
 *   only when no run was started and no event carried an id.
 * - `outcome` — the terminal lifecycle event seen (`run.completed`→"completed",
 *   `run.failed`→"failed", `run.cancelled`→"cancelled"); `null` when the stream
 *   ended without a terminal event.
 *
 * Note the abort asymmetry: a CALLER abort (via `options.signal`) resolves
 * `ok: false` with a `request-aborted` gap, but `dispose()`-driven teardown of
 * an in-flight stream aborts an INTERNAL composed signal invisible to the
 * facade, so the bridge settles cleanly and this resolves
 * `ok: true` with `outcome: null` (the run id may be present if the run had
 * already started) — teardown is not a caller abort.
 */
export type RunStreamOutcome = {
    runId: string | null;
    outcome: "completed" | "failed" | "cancelled" | null;
};

RUNTIME_CONTROL_PLANE_EVENT_NAMES#

Kind: variable

ts
export declare const RUNTIME_CONTROL_PLANE_EVENT_NAMES: readonly [
    "operation.started",
    "operation.updated",
    "message.delta",
    "reasoning.delta",
    "tool.started",
    "tool.progress",
    "tool.completed",
    "approval.requested",
    "approval.resolved",
    "usage.updated",
    "stream.reconnected",
    "stream.gap",
    "operation.completed",
    "operation.failed",
    "operation.cancelled",
    "operation.interrupted"
];

RUNTIME_PROVIDER_CAPABILITY_MATRIX#

Kind: variable

ts
export declare const RUNTIME_PROVIDER_CAPABILITY_MATRIX: Readonly<{
    claude: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    "claude-managed-agents": Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    codex: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    gemini: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    agy: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    hermes: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
    openclaw: Readonly<{
        runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
        transports: Readonly<RuntimeTransportCapabilities>;
        controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
    }>;
}>;

RUNTIME_SURFACES#

Kind: variable

ts
/** Every surface a provider may declare support for. */
export declare const RUNTIME_SURFACES: readonly [
    "runs",
    "streaming",
    "media",
    "wiki",
    "agentConfig",
    "teams",
    "kanban",
    "workspace",
    "operator",
    "discourse",
    "batch"
];

RUNTIME_TRANSPORT_KINDS#

Kind: variable

ts
export declare const RUNTIME_TRANSPORT_KINDS: readonly [
    "http",
    "sse",
    "websocket",
    "json-rpc",
    "stdio",
    "unix-socket"
];

RuntimeAuthStatus#

Kind: interface

ts
export interface RuntimeAuthStatus {
    providerId: string;
    profileId?: string;
    status: "authenticated" | "unauthenticated" | "expired" | "unknown";
    expiresAt?: string;
    sourceCategory?: string;
    reasonCode?: string;
    metadata: RuntimeControlPlaneMetadata;
}

RuntimeBatchCounts#

Kind: type

ts
export type RuntimeBatchCounts = {
    total?: number;
    processing?: number;
    succeeded?: number;
    errored?: number;
    canceled?: number;
    expired?: number;
};

RuntimeBatchOutcome#

Kind: type

ts
export type RuntimeBatchOutcome = "succeeded" | "errored" | "canceled" | "expired" | (string & {});

RuntimeBatchRequest#

Kind: type

ts
/** One entry in a batch submission — a run body plus a caller correlation id. */
export type RuntimeBatchRequest = {
    /** Caller-chosen id, echoed on the matching result. */
    customId: string;
    body: RuntimeRunStartBody;
};

RuntimeBatchResult#

Kind: type

ts
export type RuntimeBatchResult = {
    customId: string;
    outcome: RuntimeBatchOutcome;
    /** Present when outcome === "succeeded": the normalized run status (incl. tokens). */
    run?: RuntimeRunStatus;
    error?: string;
};

RuntimeBatchState#

Kind: type

ts
export type RuntimeBatchState = "in_progress" | "canceling" | "completed" | "cancelled" | "failed" | (string & {});

RuntimeBatchStatus#

Kind: type

ts
export type RuntimeBatchStatus = {
    batch_id: string;
    status: RuntimeBatchState;
    counts?: RuntimeBatchCounts;
    createdAt?: number | string;
    endedAt?: number | string;
    /** True once results are retrievable (the provider batch has ended). */
    resultsAvailable?: boolean;
};

RuntimeCapabilities#

Kind: type

ts
/** Provider-declared capability profile. Returned by RuntimeClient. */
export type RuntimeCapabilities = {
    providerKind: string;
    protocolVersion?: string | null;
    auth?: {
        type?: string;
        required?: boolean;
    };
    supports: Partial<Record<RuntimeSurface, boolean>>;
};

RuntimeClient#

Kind: interface

ts
/**
 * The UNIVERSAL agent-runtime contract every provider implements.
 * Gateway backends implement this via `GatewayApiClient` (teams/kanban/
 * workspace/operator live there). React’s `GatewayClient*` names are the
 * WebSocket RPC context only — there is no exported `GatewayClient` interface.
 */
export interface RuntimeClient {
    getRuntimeCapabilities(): Promise<RuntimeCapabilities>;
    startRun(body: RuntimeRunStartBody): Promise<RuntimeRunStatus>;
    /**
     * Optional run lifecycle. Three real behaviors exist in this package:
     *
     * - **omit** — method absent; consumers null-check (`client.getRun?.(id)`).
     * - **server** — real backend retrieval/cancel (Codex background responses,
     *   Claude Managed Agents sessions, `GatewayApiClient` HTTP runs).
     * - **sync-store** — synchronous providers (Claude Messages, Gemini) keep a
     *   local `SynchronousRunStore` of terminal statuses from `startRun`;
     *   `getRun` returns the remembered status or an honest `unknown` status for
     *   foreign ids and **does not throw**. `cancelRun` is a no-op success on
     *   an already-terminal run.
     *
     * Providers that expose the method but cannot serve it any other way should
     * throw `ApiClientError(EndpointNotFound)` (`unsupported-throw` semantics).
     */
    getRun?(runId: string): Promise<RuntimeRunStatus>;
    cancelRun?(runId: string): Promise<{
        status: string;
    }>;
    /**
     * Start a run and stream it as canonical RunStreamEvents. Optional.
     *
     * **Streaming duality (intentional):** runtime-only providers implement
     * `streamRun(body, handlers)`. Gateway providers typically omit this and
     * expose subscribe-by-`runId` via `createSseRunEventProvider` /
     * `RunEventStreamProvider` on the gateway provider module instead.
     */
    streamRun?(body: RuntimeRunStartBody, handlers: RunEventStreamHandlers, options?: {
        signal?: AbortSignal;
    }): Promise<void>;
    /**
     * Batch surface (optional). Providers that support async batch processing
     * declare `supports.batch` and implement these; others omit them. Consumers
     * null-check (`client.submitBatch?.(…)`) or gate on `RuntimeCapabilities`.
     */
    submitBatch?(requests: RuntimeBatchRequest[]): Promise<RuntimeBatchStatus>;
    getBatch?(batchId: string): Promise<RuntimeBatchStatus>;
    cancelBatch?(batchId: string): Promise<RuntimeBatchStatus>;
    /**
     * Retrieve batch results. Throws an `EndpointNotFound`-class error if the
     * batch has not ended yet — poll `getBatch` until `resultsAvailable` is true.
     */
    getBatchResults?(batchId: string): Promise<RuntimeBatchResult[]>;
}

RuntimeClientOptions#

Kind: type

ts
export type RuntimeClientOptions = Pick<HttpApiClientOptions, "baseUrl" | "fetchImpl" | "onTrace">;

RuntimeControlClient#

Kind: interface

ts
export interface RuntimeControlClient {
    readonly authStatus: AuthStatusClient;
    readonly sessions: SessionClient;
    readonly models: ModelCatalogClient;
    readonly usage: UsageClient;
    readonly tasks: TaskClient;
    readonly workspace: WorkspaceClient;
    readonly events: RuntimeEventClient;
    readonly extensions: RuntimeControlExtensionRegistry;
    dispose(): Promise<void>;
}

RuntimeControlClientFactory#

Kind: type

ts
export type RuntimeControlClientFactory = (options: RuntimeControlClientOptions) => Promise<RuntimeControlClient>;

RuntimeControlClientOptions#

Kind: type

ts
export type RuntimeControlClientOptions = {
    baseUrl?: string;
    webSocketUrl?: string;
    token?: string;
    resolveAuth?: TransportAuthResolver;
    signal?: AbortSignal;
    trace?: (event: TransportLifecycleEvent) => void;
    /** Provider-neutral gateway handshake and request settings for an owned connection. */
    gatewayConnection?: GatewayRpcClientOptions;
    /** Opt-in bounded retry policy for reconnecting an owned gateway after a retryable drop. */
    gatewayReconnect?: TransportRetryPolicy;
    transport?: GatewayTransport;
    registry?: RuntimeProviderRegistry;
};

RuntimeControlExtensionDescriptor#

Kind: type

ts
export type RuntimeControlExtensionDescriptor<T> = Readonly<{
    id: string;
    [extensionType]?: T;
}>;

RuntimeControlExtensionRegistry#

Kind: interface

ts
export interface RuntimeControlExtensionRegistry {
    has<T>(descriptor: RuntimeControlExtensionDescriptor<T>): boolean;
    get<T>(descriptor: RuntimeControlExtensionDescriptor<T>): T | undefined;
    list(): readonly string[];
}

RuntimeControlPlaneDeclaration#

Kind: type

ts
export type RuntimeControlPlaneDeclaration = {
    transports?: RuntimeTransportCapabilities;
    modules?: Partial<Record<"sessions" | "models" | "usage" | "tasks" | "workspace" | "authStatus" | "events", true>>;
};

RuntimeControlPlaneEvent#

Kind: type

ts
export type RuntimeControlPlaneEvent = (RuntimeControlPlaneEventBase & {
    event: "operation.started";
}) | (RuntimeControlPlaneEventBase & {
    event: "operation.updated";
    update: unknown;
}) | (RuntimeControlPlaneEventBase & {
    event: "message.delta";
    delta: string;
}) | (RuntimeControlPlaneEventBase & {
    event: "reasoning.delta";
    delta: string;
}) | (RuntimeControlPlaneEventBase & {
    event: "tool.started";
    toolCallId: string;
    toolName: string;
}) | (RuntimeControlPlaneEventBase & {
    event: "tool.progress";
    toolCallId: string;
    progress: unknown;
}) | (RuntimeControlPlaneEventBase & {
    event: "tool.completed";
    toolCallId: string;
    result?: unknown;
}) | (RuntimeControlPlaneEventBase & {
    event: "approval.requested";
    approvalId: string;
    request?: unknown;
}) | (RuntimeControlPlaneEventBase & {
    event: "approval.resolved";
    approvalId: string;
    approved: boolean;
}) | (RuntimeControlPlaneEventBase & {
    event: "usage.updated";
    usage: RuntimeUsage;
}) | (RuntimeControlPlaneEventBase & {
    event: "stream.reconnected";
    cursor?: string;
}) | (RuntimeControlPlaneEventBase & {
    event: "stream.gap";
    reason: string;
}) | (RuntimeControlPlaneEventBase & {
    event: "operation.completed";
}) | (RuntimeControlPlaneEventBase & {
    event: "operation.failed";
    error: unknown;
}) | (RuntimeControlPlaneEventBase & {
    event: "operation.cancelled";
}) | (RuntimeControlPlaneEventBase & {
    event: "operation.interrupted";
    reason?: string;
});

RuntimeControlPlaneEventName#

Kind: type

ts
export type RuntimeControlPlaneEventName = (typeof RUNTIME_CONTROL_PLANE_EVENT_NAMES)[number];

RuntimeControlPlaneMetadata#

Kind: type

ts
export type RuntimeControlPlaneMetadata = {
    provider: string;
    stability: RuntimeProviderStability;
    source: RuntimeControlPlaneSource;
    providerData?: unknown;
};

RuntimeControlPlaneSource#

Kind: type

ts
export type RuntimeControlPlaneSource = {
    transport: "http" | "sse" | "websocket" | "json-rpc" | "stdio" | "unix-socket";
    method: string;
};

RuntimeErrorMetadata#

Kind: type

ts
export type RuntimeErrorMetadata = {
    provider: string;
    transport: string;
    operation: string;
    retryable: boolean;
    retryAfterMs?: number;
    status?: number;
    providerCode?: string;
};

RuntimeEventClient#

Kind: interface

ts
export interface RuntimeEventClient {
    subscribe(params: {
        operationId: string;
        cursor?: string;
        signal?: AbortSignal;
    }, handlers: {
        onEvent(event: RuntimeControlPlaneEvent): void;
        onError?(error: unknown): void;
    }): Promise<RuntimeEventSubscription>;
}

RuntimeEventSequenceInspection#

Kind: interface

ts
export interface RuntimeEventSequenceInspection {
    valid: boolean;
    terminalCount: number;
    gaps: number;
}

RuntimeEventSubscription#

Kind: interface

ts
export interface RuntimeEventSubscription {
    dispose(): void | Promise<void>;
}

RuntimeModelDescriptor#

Kind: interface

ts
export interface RuntimeModelDescriptor {
    providerId: string;
    id: string;
    displayName?: string;
    availability: "available" | "unavailable" | "unknown";
    capabilities?: Readonly<Record<string, boolean>>;
    authenticated?: boolean;
    metadata: RuntimeControlPlaneMetadata;
}

RuntimePage#

Kind: type

ts
export type RuntimePage<T> = {
    data: readonly T[];
    nextCursor?: string;
};

RuntimeProviderCapabilityMatrixKey#

Kind: type

ts
export type RuntimeProviderCapabilityMatrixKey = keyof typeof RUNTIME_PROVIDER_CAPABILITY_MATRIX;

RuntimeProviderCapabilityRow#

Kind: type

ts
export type RuntimeProviderCapabilityRow = Readonly<{
    runtime: Readonly<Partial<Record<RuntimeSurface, boolean>>>;
    transports: Readonly<RuntimeTransportCapabilities>;
    controlPlane: Readonly<RuntimeControlPlaneDeclaration>;
}>;

RuntimeProviderModule#

Kind: interface

ts
/** @deprecated Import RuntimeProviderModule from core/runtime. */
export interface RuntimeProviderModule extends RuntimeProviderModuleBase {
}

RuntimeProviderRegistry#

Kind: interface

ts
export interface RuntimeProviderRegistry<M extends RuntimeProviderModule = RuntimeProviderModule> {
    resolveProvider(provider: string | null | undefined): M | null;
    listProviders(): readonly M[];
}

RuntimeProviderStability#

Kind: type

ts
export type RuntimeProviderStability = "stable" | "experimental";

RuntimeRunInput#

Kind: type

ts
export type RuntimeRunInput = string | RuntimeRunMessage[];

RuntimeRunMessage#

Kind: type

ts
/** A single conversation message. Structurally shared by every provider. */
export type RuntimeRunMessage = {
    role: string;
    content: string | Record<string, unknown>[];
    [key: string]: unknown;
};

RuntimeRunStartBody#

Kind: type

ts
/**
 * The UNIVERSAL run-start body. Carries only fields every agent runtime
 * understands. Provider/gateway-only concepts (sessions, routing, target
 * profiles, tasks) are NOT here — they live on `GatewayRunStartBody`.
 */
export type RuntimeRunStartBody = {
    input: RuntimeRunInput;
    /** System / developer instructions (Anthropic `system`). */
    instructions?: string;
    model?: string;
    tools?: Record<string, unknown>[];
    metadata?: Record<string, unknown>;
    dryRun?: boolean;
};

RuntimeRunState#

Kind: type

ts
export type RuntimeRunState = "started" | "running" | "completed" | "failed" | "cancelled" | "stopping" | "dry_run" | (string & {});

RuntimeRunStatus#

Kind: type

ts
/** The UNIVERSAL run status. Gateway-only fields live on `GatewayRunStatus`. */
export type RuntimeRunStatus = {
    run_id: string;
    status: RuntimeRunState;
    model?: string;
    output?: string;
    response?: string;
    error?: string;
    /**
     * @deprecated Raw provider-native token counts. Use `tokens` for portable,
     * normalized usage. Still populated for backward compatibility.
     */
    usage?: Record<string, number>;
    /** Provider-agnostic normalized token usage. */
    tokens?: RuntimeUsage;
};

RuntimeSessionState#

Kind: type

ts
export type RuntimeSessionState = "pending" | "active" | "completed" | "cancelled" | "failed" | "unknown";

RuntimeSessionSummary#

Kind: interface

ts
export interface RuntimeSessionSummary {
    id: string;
    providerId: string;
    title?: string;
    state: RuntimeSessionState;
    createdAt?: string;
    updatedAt?: string;
    providerKind: string;
    model?: string;
    workspaceId?: string;
    metadata: RuntimeControlPlaneMetadata;
}

runtimeSupports#

Kind: function

ts
export declare function runtimeSupports(capabilities: RuntimeCapabilities, surface: RuntimeSurface): boolean;

RuntimeSurface#

Kind: type

ts
export type RuntimeSurface = (typeof RUNTIME_SURFACES)[number];

RuntimeTaskState#

Kind: type

ts
export type RuntimeTaskState = "pending" | "running" | "completed" | "cancelled" | "failed" | "unknown";

RuntimeTaskSummary#

Kind: interface

ts
export interface RuntimeTaskSummary {
    id: string;
    state: RuntimeTaskState;
    createdAt?: string;
    updatedAt?: string;
    runId?: string;
    sessionId?: string;
    threadId?: string;
    cancellable?: boolean;
    metadata: RuntimeControlPlaneMetadata;
}

RuntimeTransportCapabilities#

Kind: type

ts
export type RuntimeTransportCapabilities = Partial<Record<RuntimeTransportKind, RuntimeTransportCapability>>;

RuntimeTransportCapability#

Kind: type

ts
export type RuntimeTransportCapability = {
    kind: RuntimeTransportKind;
    stability: RuntimeProviderStability;
    authenticated: boolean;
    reconnect?: boolean;
    replay?: boolean;
    cancellation?: boolean;
};

RuntimeTransportKind#

Kind: type

ts
export type RuntimeTransportKind = (typeof RUNTIME_TRANSPORT_KINDS)[number];

runtimeTransportSupports#

Kind: function

ts
export declare function runtimeTransportSupports(capabilities: RuntimeTransportCapabilities, kind: RuntimeTransportKind): boolean;

RuntimeUsage#

Kind: type

ts
/** Canonical, provider-agnostic token usage for a single run. */
export type RuntimeUsage = {
    inputTokens?: number;
    outputTokens?: number;
    totalTokens?: number;
    /** Tokens served from prompt cache. */
    cacheReadTokens?: number;
    /** Tokens written to prompt cache (Anthropic "cache_creation"). */
    cacheWriteTokens?: number;
    /** Lossless provider-native numeric fields, flattened. */
    raw?: Record<string, number>;
};

RuntimeUsageCost#

Kind: interface

ts
export interface RuntimeUsageCost {
    availability: "available" | "estimated" | "unavailable";
    amount?: number;
    currency?: string;
    calculationSource?: string;
}

RuntimeUsageQuery#

Kind: interface

ts
export interface RuntimeUsageQuery {
    startTime?: string;
    endTime?: string;
    providerId?: string;
    model?: string;
    sessionId?: string;
    agentId?: string;
}

RuntimeUsageSummary#

Kind: interface

ts
export interface RuntimeUsageSummary {
    tokens: RuntimeUsage;
    cost: RuntimeUsageCost;
    aggregation?: string;
    metadata: RuntimeControlPlaneMetadata;
}

RuntimeWorkspaceDescriptor#

Kind: interface

ts
export interface RuntimeWorkspaceDescriptor {
    id: string;
    providerId: string;
    displayName?: string;
    root?: string;
    accessMode: "read-only" | "read-write" | "unknown";
    metadata: RuntimeControlPlaneMetadata;
}

SerializedApiClientError#

Kind: type

ts
export type SerializedApiClientError = {
    name: string;
    message: string;
    type?: string;
    code?: string;
};

serializeError#

Kind: function

ts
export declare function serializeError(error: unknown, fallbackMessage?: string): SerializedApiClientError;

SessionClient#

Kind: interface

ts
export interface SessionClient {
    listSessions(query?: ListSessionsOptions): Promise<RuntimePage<RuntimeSessionSummary>>;
    getSession(id: string, options?: SessionRequestOptions): Promise<RuntimeSessionSummary>;
    cancelSession?(id: string, options?: SessionRequestOptions): Promise<RuntimeSessionSummary>;
}

StreamRunBody#

Kind: type

ts
/**
 * The body accepted by the facade's `streamRun`: the universal
 * {@link RuntimeRunStartBody} plus the OPTIONAL gateway session-selection
 * fields. Gateway providers (Hermes) bind the stream to a session via one of
 * these; runtime-only providers ignore them. Exposing them here is what lets
 * `client.streamRun({ input, sessionKey })` typecheck at the call site instead
 * of failing `TS2353` on an excess property.
 */
export type StreamRunBody = RuntimeRunStartBody & {
    sessionKey?: string;
    session_key?: string;
    session_id?: string;
};

stringifyUnknownError#

Kind: function

ts
export declare function stringifyUnknownError(error: unknown): string;

supportsCapability#

Kind: function

ts
/** True iff `map` declares `key` supported. The only place `=== true` lives. */
export declare function supportsCapability(map: CapabilityMap, key: CapabilityKey): boolean;

SURFACE_CONTRACTS#

Kind: variable

ts
export declare const SURFACE_CONTRACTS: Record<string, SurfaceContract>;

SurfaceContract#

Kind: type

ts
export type SurfaceContract = {
    key: string;
    method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
    path: (params?: Record<string, string>) => string;
    degradation: "hard" | "gap" | "silent";
    owner: string;
    note: string;
};

SurfaceContractMap#

Kind: type

ts
export type SurfaceContractMap = Record<string, SurfaceContract>;

SurfacePathResolver#

Kind: type

ts
export type SurfacePathResolver = (key: string, params?: Record<string, string>) => string;

TaskClient#

Kind: interface

ts
export interface TaskClient {
    listTasks(query?: {
        cursor?: string;
        limit?: number;
    }): Promise<RuntimePage<RuntimeTaskSummary>>;
    getTask(id: string): Promise<RuntimeTaskSummary>;
    cancelTask?(id: string): Promise<RuntimeTaskSummary>;
}

TEAM_ACTION_INPUT_MODES#

Kind: variable

ts
export declare const TEAM_ACTION_INPUT_MODES: readonly [
    "command",
    "json",
    "text"
];

TEAM_ACTION_OUTPUT_MODES#

Kind: variable

ts
export declare const TEAM_ACTION_OUTPUT_MODES: readonly [
    "artifact",
    "json",
    "markdown",
    "text"
];

TEAM_MANIFEST_VERSION#

Kind: variable

ts
export declare const TEAM_MANIFEST_VERSION: 1;

TeamActionArtifact#

Kind: type

ts
export type TeamActionArtifact = {
    key: string;
    contentType?: string | null;
    path?: string | null;
    url?: string | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionArtifactContract#

Kind: type

ts
export type TeamActionArtifactContract = {
    key: string;
    contentType?: string | null;
    path?: string | null;
    description?: string | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionContract#

Kind: type

ts
export type TeamActionContract = {
    id: string;
    title?: string | null;
    description?: string | null;
    enabled?: boolean | null;
    route?: TeamActionRouteContract | null;
    input?: TeamActionInputContract | null;
    output?: TeamActionOutputContract | null;
    defaults?: Record<string, TeamActionJsonValue> | null;
    capabilities?: readonly string[] | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionHttpMethod#

Kind: type

ts
export type TeamActionHttpMethod = "DELETE" | "GET" | "PATCH" | "POST" | "PUT";

TeamActionInputContract#

Kind: type

ts
export type TeamActionInputContract = {
    mode?: TeamActionInputMode | null;
    command?: string | null;
    params?: readonly TeamActionParamContract[] | null;
    schema?: Record<string, unknown> | null;
    examples?: readonly string[] | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionInputMode#

Kind: type

ts
export type TeamActionInputMode = (typeof TEAM_ACTION_INPUT_MODES)[number];

TeamActionJsonValue#

Kind: type

ts
export type TeamActionJsonValue = string | number | boolean | null | readonly TeamActionJsonValue[] | {
    readonly [key: string]: TeamActionJsonValue;
};

TeamActionOutputContract#

Kind: type

ts
export type TeamActionOutputContract = {
    mode?: TeamActionOutputMode | null;
    contentType?: string | null;
    schema?: Record<string, unknown> | null;
    artifacts?: readonly TeamActionArtifactContract[] | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionOutputMode#

Kind: type

ts
export type TeamActionOutputMode = (typeof TEAM_ACTION_OUTPUT_MODES)[number];

TeamActionParamContract#

Kind: type

ts
export type TeamActionParamContract = {
    key: string;
    type?: TeamActionParamType | null;
    required?: boolean | null;
    default?: TeamActionJsonValue;
    values?: readonly string[] | null;
    aliases?: readonly string[] | null;
    description?: string | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionParamType#

Kind: type

ts
export type TeamActionParamType = "boolean" | "enum" | "file" | "json" | "number" | "string";

TeamActionResponse#

Kind: type

ts
export type TeamActionResponse = (TeamActionResponseBase & {
    kind: "artifact";
    artifacts: readonly TeamActionArtifact[];
    data?: TeamActionJsonValue;
}) | (TeamActionResponseBase & {
    kind: "json";
    data: TeamActionJsonValue;
}) | (TeamActionResponseBase & {
    kind: "markdown";
    markdown: string;
}) | (TeamActionResponseBase & {
    kind: "text";
    text: string;
});

TeamActionResponseBase#

Kind: type

ts
export type TeamActionResponseBase = {
    actionId?: string | null;
    teamId?: string | null;
    memberId?: string | null;
    metadata?: Record<string, unknown> | null;
};

TeamActionRouteContract#

Kind: type

ts
export type TeamActionRouteContract = {
    method?: TeamActionHttpMethod | null;
    surfaceKey?: string | null;
    path?: string | null;
    metadata?: Record<string, unknown> | null;
};

teamDirectoryFromManifest#

Kind: function

ts
/** Build a resolution-only `TeamDirectory` from a resolved team manifest. */
export declare function teamDirectoryFromManifest(manifest: TeamManifest): TeamDirectory;

TeamManifest#

Kind: type

ts
export type TeamManifest = {
    version: TeamManifestVersion;
    actions?: readonly TeamActionContract[] | null;
    bindings?: readonly GatewayRouteBinding[] | null;
    teams: readonly ManifestTeam[];
};

TeamManifestInput#

Kind: type

ts
export type TeamManifestInput = Partial<TeamManifest> | null | undefined;

TeamManifestLoader#

Kind: type

ts
export type TeamManifestLoader = () => TeamManifestInput | Promise<TeamManifestInput>;

TeamManifestSource#

Kind: interface

ts
/** The seam through which a host supplies its manifest to the package. */
export interface TeamManifestSource {
    getManifest(): Promise<TeamManifest>;
}

TeamManifestVersion#

Kind: type

ts
export type TeamManifestVersion = typeof TEAM_MANIFEST_VERSION;

TeamRouteKey#

Kind: type

ts
export type TeamRouteKey = DefaultTeamRouteKey | "action" | "agent.action" | "agent.config" | "agent.workspace" | (string & {});

TeamRouteResolver#

Kind: interface

ts
/**
 * Generic, host-overridable route resolution over a TeamManifest. The default
 * implementation delegates to the standard REST path builders.
 */
export interface TeamRouteResolver {
    resolveRoutePath(routeKey: TeamRouteKey, options: ResolveTeamRoutePathOptions): string;
    resolveActionApiPath(manifest: TeamManifest, teamId: string, actionId: string, options?: ResolveTeamActionContractOptions): string;
    resolveWorkspaceApiPath(manifest: TeamManifest, teamId: string, keyOrPath: string, options?: ResolveTeamWorkspacePathOptions): string;
    resolveBinding(manifest: TeamManifest, options: ResolveGatewayRouteBindingOptions): GatewayResolvedRouteBinding | null;
}

TeamWorkspaceConfig#

Kind: type

ts
export type TeamWorkspaceConfig = {
    rootPath: string;
    paths?: readonly TeamWorkspacePathEntry[] | null;
};

TeamWorkspacePathEntry#

Kind: type

ts
export type TeamWorkspacePathEntry = string | {
    key: string;
    path?: string | null;
};

toError#

Kind: function

ts
export declare function toError(error: unknown, fallbackMessage?: string): Error;

TokenPrices#

Kind: type

ts
/** Per-million-token prices supplied by the consumer. No defaults ship. */
export type TokenPrices = {
    inputPerMTok?: number;
    outputPerMTok?: number;
    cacheReadPerMTok?: number;
    cacheWritePerMTok?: number;
};

TransportError#

Kind: class

ts
export declare class TransportError extends ApiClientError {
    readonly transport: TransportErrorMetadata;
    constructor(message: string, options: {
        metadata: TransportErrorMetadata;
        cause?: unknown;
    });
}

TransportErrorMetadata#

Kind: type

ts
export type TransportErrorMetadata = Readonly<{
    kind: TransportKind;
    phase: TransportPhase;
    operation: string;
    retryable: boolean;
    attempt: number;
    status?: number;
    code?: string | number;
    retryAfterMs?: number;
}>;

TransportKind#

Kind: type

ts
export type TransportKind = "http" | "sse" | "websocket" | "json-rpc" | "stdio" | "unix";

TransportLifecycleEvent#

Kind: type

ts
export type TransportLifecycleEvent = Readonly<{
    state: "connecting" | "connected" | "retrying" | "reconnected" | "closed";
    kind: TransportKind;
    operation: string;
    attempt: number;
    delayMs?: number;
}>;

unsupportedRuntimeSurface#

Kind: function

ts
/** Throw a typed EndpointNotFound for a surface this provider does not serve. */
export declare function unsupportedRuntimeSurface(providerKind: string, surface: RuntimeSurface): never;

UsageClient#

Kind: interface

ts
export interface UsageClient {
    getUsage(query?: RuntimeUsageQuery): Promise<RuntimeUsageSummary>;
}

withFallback#

Kind: function

ts
export declare function withFallback<TData>(params: {
    run: () => Promise<TData>;
    fallback: TData;
    area: string;
    expectedContract: string;
    note: string;
    /** Optional observability hook: fired when the envelope resolves live or mock (C2). */
    onResolve?: (info: FallbackResolveInfo) => void;
}): Promise<DataEnvelope<TData>>;

withMutationResult#

Kind: function

ts
export declare function withMutationResult<TData>(params: {
    run: () => Promise<TData>;
    fallback: () => TData;
    area: string;
    expectedContract: string;
    note: string;
}): Promise<MutationResult<TData>>;

withRuntimeBasePath#

Kind: function

ts
export declare function withRuntimeBasePath(pathname: string, rawBasePath: string | null | undefined): string;

withRuntimeControlExtensions#

Kind: function

ts
export declare function withRuntimeControlExtensions(client: RuntimeControlClient, entries: Iterable<RuntimeControlExtensionEntry>): RuntimeControlClient;

WorkspaceClient#

Kind: interface

ts
export interface WorkspaceClient {
    listWorkspaces(): Promise<readonly RuntimeWorkspaceDescriptor[]>;
    getWorkspace(id: string): Promise<RuntimeWorkspaceDescriptor>;
}