import { r as ChannelAccountSnapshot } from "./types.core-CuC3Nb15.js"; import { i as OpenClawConfig } from "./types.openclaw-CpnoYlBx.js"; import { t as ChannelId } from "./channel-id.types-DjYEl-_2.js"; import { c as ExecApprovalRequestPayload$1, o as ExecApprovalDecision } from "./exec-approvals-BMVAZXjT.js"; import { c as PluginApprovalRequestPayload } from "./plugin-approvals-B-1AuXnw.js"; import { i as ErrorShape, r as ConnectParams, s as RequestFrame } from "./schema-CKQIsrVB.js"; import { n as RuntimeEnv } from "./runtime-Bxifh4bY.js"; import { i as WizardPrompter } from "./prompts-DgKIGa-v.js"; import { t as OperatorScope } from "./operator-scopes-Phea7r7e.js"; import { t as ModelCatalogEntry } from "./model-catalog.types-CJ6dM2vF.js"; import { n as createSubsystemLogger } from "./subsystem-n4Y4vCcQ.js"; import { a as CronJobCreate, i as CronJob, o as CronJobPatch, s as CronRunStatus } from "./store-D9Y8B7Gz.js"; import { t as CliDeps } from "./deps.types-BdV6g6qp.js"; import { t as HeartbeatSummary } from "./heartbeat-summary-CAVLXl2a.js"; import { monitorEventLoopDelay, performance } from "node:perf_hooks"; import { WebSocket as WebSocket$1 } from "ws"; //#region src/plugins/provider-auth-types.d.ts /** Provider secret input modes: inline plaintext or external secret reference. */ type SecretInputMode = "plaintext" | "ref"; //#endregion //#region src/infra/agent-events.d.ts /** Stream name for agent events delivered to gateway listeners and plugin host hooks. */ type AgentEventStream = "lifecycle" | "tool" | "assistant" | "error" | "item" | "plan" | "approval" | "command_output" | "patch" | "compaction" | "thinking" | (string & {}); /** Approval event phase for request/resolution transitions. */ type AgentApprovalEventPhase = "requested" | "resolved"; /** Approval status after routing, user action, or delivery failure. */ type AgentApprovalEventStatus = "pending" | "unavailable" | "approved" | "denied" | "failed"; /** Approval family used by renderers and host hooks. */ type AgentApprovalEventKind = "exec" | "plugin" | "unknown"; /** Payload for approval requests and their later resolution events. */ type AgentApprovalEventData = { phase: AgentApprovalEventPhase; kind: AgentApprovalEventKind; status: AgentApprovalEventStatus; title: string; itemId?: string; toolCallId?: string; approvalId?: string; approvalSlug?: string; command?: string; host?: string; reason?: string; scope?: "turn" | "session"; message?: string; }; /** Enriched event delivered to subscribers after sequencing and context stamping. */ type AgentEventPayload = { runId: string; seq: number; stream: AgentEventStream; ts: number; data: Record; sessionKey?: string; /** * sessionId the run was bound to when it started. Lifecycle persistence uses * this to reject terminal events from a pre-`sessions.reset` run that would * otherwise clobber the rotated session row resolved by the shared sessionKey. */ sessionId?: string; agentId?: string; }; /** Emits an agent event after assigning per-run sequence, timestamp, and context metadata. */ declare function emitAgentEvent(event: Omit): void; /** Subscribes to sequenced agent events; returns an unsubscribe callback. */ declare function onAgentEvent(listener: (evt: AgentEventPayload) => void): () => void; /** Clears all agent event state, including listeners; test-only helper. */ declare function resetAgentEventsForTest(): void; //#endregion //#region src/commands/daemon-runtime.d.ts type GatewayDaemonRuntime = "node" | "bun"; //#endregion //#region src/commands/onboard-types.d.ts type OnboardMode = "local" | "remote"; /** * Auth choices are plugin-owned contract ids plus a few legacy aliases that * are normalized elsewhere (for example `oauth` -> `setup-token`). */ type BuiltInAuthChoice = /** @deprecated Use `setup-token`. */"oauth" | "setup-token" | "token" | "apiKey" | "custom-api-key" | "skip"; type AuthChoice = BuiltInAuthChoice | (string & {}); type GatewayAuthChoice = "token" | "password"; type ResetScope = "config" | "config+creds+sessions" | "full"; type GatewayBind = "loopback" | "lan" | "auto" | "custom" | "tailnet"; type TailscaleMode = "off" | "serve" | "funnel"; type NodeManagerChoice = "npm" | "pnpm" | "bun"; type OnboardDynamicProviderOptions = { /** * Provider-specific non-interactive auth flags are plugin-owned and keyed by * manifest `providerAuthChoices[].optionKey` values. */ [optionKey: string]: unknown; }; /** Parsed options accepted by `openclaw onboard`. */ type OnboardOptions = OnboardDynamicProviderOptions & { mode?: OnboardMode; /** "manual" is an alias for "advanced". */ flow?: "quickstart" | "advanced" | "manual" | "import"; workspace?: string; nonInteractive?: boolean; /** Required for non-interactive setup; skips the interactive risk prompt when true. */ acceptRisk?: boolean; reset?: boolean; resetScope?: ResetScope; authChoice?: AuthChoice; /** Used when `authChoice=token` in non-interactive mode. */ tokenProvider?: string; /** Used when `authChoice=token` in non-interactive mode. */ token?: string; /** Used when `authChoice=token` in non-interactive mode. */ tokenProfileId?: string; /** Used when `authChoice=token` in non-interactive mode. */ tokenExpiresIn?: string; /** API key persistence mode for setup flows (default: plaintext). */ secretInputMode?: SecretInputMode; arceeaiApiKey?: string; cloudflareAiGatewayAccountId?: string; cloudflareAiGatewayGatewayId?: string; customBaseUrl?: string; customApiKey?: string; lmstudioApiKey?: string; customModelId?: string; customProviderId?: string; customCompatibility?: "openai" | "openai-responses" | "anthropic"; customImageInput?: boolean; gatewayPort?: number; gatewayBind?: GatewayBind; gatewayAuth?: GatewayAuthChoice; gatewayToken?: string; gatewayTokenRefEnv?: string; gatewayPassword?: string; tailscale?: TailscaleMode; tailscaleResetOnExit?: boolean; installDaemon?: boolean; daemonRuntime?: GatewayDaemonRuntime; skipChannels?: boolean; /** @deprecated Legacy alias for `skipChannels`. */ skipProviders?: boolean; skipSkills?: boolean; skipBootstrap?: boolean; skipSearch?: boolean; skipHealth?: boolean; skipUi?: boolean; suppressGatewayTokenOutput?: boolean; skipHooks?: boolean; nodeManager?: NodeManagerChoice; remoteUrl?: string; remoteToken?: string; importFrom?: string; importSource?: string; importSecrets?: boolean; json?: boolean; }; //#endregion //#region src/infra/voicewake-routing.d.ts type VoiceWakeRouteTarget = { mode: "current"; agentId?: undefined; sessionKey?: undefined; } | { agentId: string; sessionKey?: undefined; mode?: undefined; } | { sessionKey: string; agentId?: undefined; mode?: undefined; }; type VoiceWakeRouteRule = { trigger: string; target: VoiceWakeRouteTarget; }; type VoiceWakeRoutingConfig = { version: 1; defaultTarget: VoiceWakeRouteTarget; routes: VoiceWakeRouteRule[]; updatedAtMs: number; }; //#endregion //#region src/gateway/model-pricing-cache-state.d.ts type GatewayModelPricingHealthSource = "openrouter" | "litellm" | "bootstrap" | "refresh"; type GatewayModelPricingHealth = { state: "ok" | "degraded" | "disabled"; sources: Array<{ source: GatewayModelPricingHealthSource; state: "ok" | "degraded"; lastFailureAt?: number; detail?: string; }>; lastFailureAt?: number; detail?: string; }; //#endregion //#region src/gateway/server/event-loop-health.d.ts type GatewayEventLoopHealthReason = "event_loop_delay" | "event_loop_utilization" | "cpu"; type GatewayEventLoopHealth = { degraded: boolean; reasons: GatewayEventLoopHealthReason[]; intervalMs: number; delayP99Ms: number; delayMaxMs: number; utilization: number; cpuCoreRatio: number; }; //#endregion //#region src/commands/health.types.d.ts /** Health snapshot for one configured channel account. */ type ChannelAccountHealthSummary = { accountId: string; configured?: boolean; linked?: boolean; authAgeMs?: number | null; probe?: unknown; lastProbeAt?: number | null; [key: string]: unknown; }; /** Channel-level health summary with optional per-account details. */ type ChannelHealthSummary = ChannelAccountHealthSummary & { accounts?: Record; }; /** Agent heartbeat and session-store health metadata. */ type AgentHealthSummary = { agentId: string; name?: string; isDefault: boolean; heartbeat: HeartbeatSummary; sessions: HealthSummary["sessions"]; }; /** Plugin load error details safe for the health payload. */ type PluginHealthErrorSummary = { id: string; origin: string; activated: boolean; activationSource?: string; activationReason?: string; failurePhase?: string; error: string; }; /** Plugin registry health summary. */ type PluginHealthSummary = { loaded: string[]; errors: PluginHealthErrorSummary[]; }; /** Context engine quarantine entry included in health output. */ type ContextEngineHealthQuarantineSummary = { engineId: string; owner?: string; operation: string; reason: string; failedAt: number; }; /** Context engine health summary. */ type ContextEngineHealthSummary = { quarantined: ContextEngineHealthQuarantineSummary[]; }; /** Optional model pricing cache health reported by the gateway. */ type ModelPricingHealthSummary = GatewayModelPricingHealth; /** Full gateway health payload consumed by `openclaw health`. */ type HealthSummary = { ok: true; ts: number; durationMs: number; eventLoop?: GatewayEventLoopHealth; plugins?: PluginHealthSummary; contextEngines?: ContextEngineHealthSummary; modelPricing?: ModelPricingHealthSummary; channels: Record; channelOrder: string[]; channelLabels: Record; heartbeatSeconds: number; defaultAgentId: string; agents: AgentHealthSummary[]; sessions: { path: string; count: number; recent: Array<{ key: string; updatedAt: number | null; age: number | null; }>; }; }; //#endregion //#region src/cron/service/list-page-types.d.ts /** Enabled-state filter accepted by paginated cron listing. */ type CronJobsEnabledFilter = "all" | "enabled" | "disabled"; /** Schedule-kind filter accepted by paginated cron listing. */ type CronJobsScheduleKindFilter = "all" | "at" | "every" | "cron"; /** Last-run status filter, including jobs that have not produced a status yet. */ type CronJobsLastRunStatusFilter = "all" | CronRunStatus | "unknown"; /** Stable sort keys supported by paginated cron listing. */ type CronJobsSortBy = "nextRunAtMs" | "updatedAtMs" | "name"; /** Sort direction for paginated cron listing. */ type CronSortDir = "asc" | "desc"; /** Input contract for filtered, sorted, offset-based cron job pages. */ type CronListPageOptions = { includeDisabled?: boolean; limit?: number; offset?: number; query?: string; enabled?: CronJobsEnabledFilter; scheduleKind?: CronJobsScheduleKindFilter; lastRunStatus?: CronJobsLastRunStatusFilter; sortBy?: CronJobsSortBy; sortDir?: CronSortDir; agentId?: string; }; /** Offset-page result returned by cron listPage callers. */ type CronListPageResult = { jobs: TJobs; total: number; offset: number; limit: number; hasMore: boolean; nextOffset: number | null; }; //#endregion //#region src/cron/service/state.d.ts /** Direct-run mode: respect due time or force execution. */ type CronRunMode = "due" | "force"; /** Main-session wake strategy used after enqueuing cron text. */ type CronWakeMode = "now" | "next-heartbeat"; /** Lightweight service status returned to gateway/control surfaces. */ type CronStatusSummary = { enabled: boolean; storePath: string; jobs: number; nextWakeAtMs: number | null; }; /** Result shape for immediate or queued cron run requests. */ type CronRunResult = { ok: true; ran: true; } | { ok: true; enqueued: true; runId: string; } | { ok: true; ran: false; reason: "not-due"; } | { ok: true; ran: false; reason: "already-running"; } | { ok: false; }; /** Remove result that distinguishes missing jobs from failed removal. */ type CronRemoveResult = { ok: true; removed: boolean; } | { ok: false; removed: false; }; /** Created cron job returned by service mutation calls. */ type CronAddResult = CronJob; /** Updated cron job returned by service mutation calls. */ type CronUpdateResult = CronJob; /** Chronological job list returned by service read calls. */ type CronListResult = CronJob[]; /** Normalized create input accepted by the cron service. */ type CronAddInput = CronJobCreate; /** Normalized patch input accepted by cron service updates. */ type CronUpdateInput = CronJobPatch; //#endregion //#region src/cron/service-contract.d.ts type CronWakeResult = { ok: true; } | { ok: false; reason?: "unwakeable-session-key"; }; /** Result shape for direct/queued cron runs, including invalid persisted specs. */ type CronServiceRunResult = CronRunResult | { ok: true; ran: false; reason: "invalid-spec"; }; /** Public cron service facade used by gateway, plugin SDK, and tests. */ interface CronServiceContract { start(): Promise; stop(): void; status(): Promise; list(opts?: { includeDisabled?: boolean; }): Promise; listPage(opts?: CronListPageOptions): Promise; add(input: CronAddInput): Promise; update(id: string, patch: CronUpdateInput): Promise; remove(id: string): Promise; run(id: string, mode?: CronRunMode): Promise; enqueueRun(id: string, mode?: CronRunMode): Promise; getJob(id: string): CronJob | undefined; readJob(id: string): Promise; getDefaultAgentId(): string | undefined; wake(opts: { mode: CronWakeMode; text: string; sessionKey?: string; }): CronWakeResult; } //#endregion //#region src/wizard/session.d.ts type WizardStepOption = { value: unknown; label: string; hint?: string; }; type WizardStep = { id: string; type: "note" | "select" | "text" | "confirm" | "multiselect" | "progress" | "action"; title?: string; message?: string; format?: "plain"; options?: WizardStepOption[]; initialValue?: unknown; placeholder?: string; sensitive?: boolean; executor?: "gateway" | "client"; }; type WizardSessionStatus = "running" | "done" | "cancelled" | "error"; type WizardNextResult = { done: boolean; step?: WizardStep; status: WizardSessionStatus; error?: string; }; declare class WizardSession { private runner; private currentStep; private stepDeferred; private pendingTerminalResolution; private answerDeferred; private status; private error; constructor(runner: (prompter: WizardPrompter) => Promise); next(): Promise; answer(stepId: string, value: unknown): Promise; cancel(): void; pushStep(step: WizardStep): void; private run; awaitAnswer(step: WizardStep): Promise; private resolveStep; getStatus(): WizardSessionStatus; getError(): string | undefined; } //#endregion //#region src/gateway/chat-abort.d.ts type ChatAbortControllerEntry = { controller: AbortController; sessionId: string; sessionKey: string; agentId?: string; startedAtMs: number; expiresAtMs: number; ownerConnId?: string; ownerDeviceId?: string; providerId?: string; authProviderId?: string; abortStopReason?: string; /** * False for backend/internal agent runs that may share a session key but must * not be projected into operator chat surfaces. */ controlUiVisible?: boolean; /** * Controls only the sessions.list active-run projection. Terminal lifecycle * clears this before chat.send settles, while the entry stays as the retry * idempotency guard until normal cleanup removes it. */ projectSessionActive?: boolean; /** * Which RPC owns this registration. Absent (undefined) is treated as * `"chat-send"` so pre-existing callers that constructed entries without * a kind keep their behavior. Consumers that need "chat.send specifically * is active" must check `kind !== "agent"`, not just `.has(runId)`. */ kind?: "chat-send" | "agent"; }; //#endregion //#region src/gateway/exec-approval-manager.d.ts type ExecApprovalRequestPayload = ExecApprovalRequestPayload$1; type ExecApprovalRecord = { id: string; request: TPayload; createdAtMs: number; expiresAtMs: number; requestedByConnId?: string | null; requestedByDeviceId?: string | null; requestedByClientId?: string | null; requestedByDeviceTokenAuth?: boolean; resolvedAtMs?: number; decision?: ExecApprovalDecision; consumedDecision?: ExecApprovalDecision; resolvedBy?: string | null; }; type ExecApprovalIdLookupResult = { kind: "exact" | "prefix"; id: string; } | { kind: "ambiguous"; ids: string[]; } | { kind: "none"; }; declare class ExecApprovalManager { private pending; create(request: TPayload, timeoutMs: number, id?: string | null): ExecApprovalRecord; /** * Register an approval record and return a promise that resolves when the decision is made. * This separates registration (synchronous) from waiting (async), allowing callers to * confirm registration before the decision is made. */ register(record: ExecApprovalRecord, timeoutMs: number): Promise; /** * @deprecated Use register() instead for explicit separation of registration and waiting. */ waitForDecision(record: ExecApprovalRecord, timeoutMs: number): Promise; resolve(recordId: string, decision: ExecApprovalDecision, resolvedBy?: string | null): boolean; expire(recordId: string, resolvedBy?: string | null): boolean; getSnapshot(recordId: string): ExecApprovalRecord | null; listPendingRecords(): ExecApprovalRecord[]; consumeAllowOnce(recordId: string): boolean; /** * Wait for decision on an already-registered approval. * Returns the decision promise if the ID is pending, null otherwise. */ awaitDecision(recordId: string): Promise | null; lookupApprovalId(input: string, opts?: { includeResolved?: boolean; filter?: (record: ExecApprovalRecord) => boolean; }): ExecApprovalIdLookupResult; lookupPendingId(input: string): ExecApprovalIdLookupResult; } //#endregion //#region src/gateway/methods/descriptor.d.ts /** Scope marker for methods that only authenticated node clients may call. */ declare const NODE_GATEWAY_METHOD_SCOPE: "node"; /** Scope marker for methods whose handler derives the required operator scope at runtime. */ declare const DYNAMIC_GATEWAY_METHOD_SCOPE: "dynamic"; /** Authorization scope attached to a gateway method descriptor. */ type GatewayMethodScope = OperatorScope | typeof NODE_GATEWAY_METHOD_SCOPE | typeof DYNAMIC_GATEWAY_METHOD_SCOPE; /** Owner metadata used to keep core, plugin, channel, and auxiliary methods distinguishable. */ type GatewayMethodOwner = { kind: "core"; area: string; } | { kind: "plugin"; pluginId: string; } | { kind: "channel"; channelId: string; } | { kind: "aux"; area: string; }; /** Startup availability flag exposed to clients as retryable startup-unavailable errors. */ type GatewayMethodStartupAvailability = "available" | "unavailable-until-sidecars"; type GatewayMethodHandler = (opts: never) => unknown; /** Complete metadata for one dispatchable gateway method. */ type GatewayMethodDescriptor = { name: string; handler: GatewayMethodHandler; scope: GatewayMethodScope; owner: GatewayMethodOwner; startup?: GatewayMethodStartupAvailability; controlPlaneWrite?: boolean; advertise?: boolean; description?: string; }; /** Read-only method registry view used by request dispatch and method listing. */ type GatewayMethodRegistryView = { getHandler: (name: string) => GatewayMethodHandler | undefined; listMethods: () => string[]; listAdvertisedMethods: () => string[]; getScope: (name: string) => GatewayMethodScope | undefined; isStartupUnavailable: (name: string) => boolean; isControlPlaneWrite: (name: string) => boolean; descriptors: () => readonly GatewayMethodDescriptor[]; }; //#endregion //#region src/gateway/plugin-node-capability.d.ts /** Path marker used to scope plugin-hosted node URLs with one-time capabilities. */ declare const PLUGIN_NODE_CAPABILITY_PATH_PREFIX = "/__openclaw__/cap"; /** Default lifetime for plugin-node capability tokens. */ declare const DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS: number; /** Declared plugin surface that may receive scoped node capabilities. */ type PluginNodeCapabilitySurface = { surface: string; ttlMs?: number; scopeKey?: string; }; /** Client-side storage for surface URLs and minted plugin-node capabilities. */ type PluginNodeCapabilityClient = { pluginSurfaceUrls?: Record; pluginNodeCapabilitySurfaces?: Record; pluginNodeCapabilities?: Record; }; /** Parsed URL details after extracting path/query capability tokens. */ type NormalizedPluginNodeCapabilityUrl = { pathname: string; capability?: string; rewrittenUrl?: string; scopedPath: boolean; malformedScopedPath: boolean; }; /** Mint an opaque capability token for plugin-node surface access. */ declare function mintPluginNodeCapabilityToken(): string; /** Append a capability path segment to a plugin host URL. */ declare function buildPluginNodeCapabilityScopedHostUrl(baseUrl: string, capability: string): string | undefined; /** Parse and rewrite scoped capability URLs into canonical paths plus query tokens. */ declare function normalizePluginNodeCapabilityScopedUrl(rawUrl: string): NormalizedPluginNodeCapabilityUrl; //#endregion //#region src/gateway/server/ws-types.d.ts /** * Runtime WebSocket client state tracked by the gateway server. */ type GatewayWsClient = PluginNodeCapabilityClient & { socket: WebSocket$1; connect: ConnectParams; connId: string; isDeviceTokenAuth?: boolean; usesSharedGatewayAuth: boolean; sharedGatewaySessionGeneration?: string; presenceKey?: string; clientIp?: string; internal?: { approvalRuntime?: boolean; }; canvasHostUrl?: string; canvasCapability?: string; canvasCapabilityExpiresAtMs?: number; invalidated?: boolean; invalidatedReason?: string; }; //#endregion //#region src/gateway/node-registry.d.ts /** Connected node session advertised over Gateway websocket. */ type NodeSession = { nodeId: string; connId: string; client: GatewayWsClient; clientId?: string; clientMode?: string; displayName?: string; platform?: string; version?: string; coreVersion?: string; uiVersion?: string; deviceFamily?: string; modelIdentifier?: string; remoteIp?: string; declaredCaps: string[]; caps: string[]; declaredCommands: string[]; commands: string[]; declaredPermissions?: Record; permissions?: Record; pathEnv?: string; connectedAtMs: number; }; /** Result payload returned from node.invoke. */ type NodeInvokeResult = { ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }; /** Connectivity probe result for a registered node. */ type NodeConnectivityResult = { ok: true; } | { ok: false; error: { code: string; message: string; }; }; declare const SERIALIZED_EVENT_PAYLOAD: unique symbol; type SerializedEventPayload = { readonly json: string; readonly [SERIALIZED_EVENT_PAYLOAD]: true; }; /** Registry of currently connected Gateway nodes. */ declare class NodeRegistry { private nodesById; private nodesByConn; private pendingInvokes; private authorizedSystemRunEvents; /** Register a websocket client as the current connection for its node id. */ register(client: GatewayWsClient, opts: { remoteIp?: string | undefined; }): NodeSession; /** Unregister one connection and reject invokes tied to that connection. */ unregister(connId: string): string | null; /** List connected node sessions. */ listConnected(): NodeSession[]; /** Return a connected node session by node id. */ get(nodeId: string): NodeSession | undefined; /** Probe websocket liveness with ping/pong when the socket supports it. */ checkConnectivity(nodeId: string, timeoutMs?: number): Promise; /** Update command list while keeping it within the node's declared command surface. */ updateCommands(nodeId: string, commands: readonly string[]): NodeSession | null; updateSurface(nodeId: string, surface: { caps?: readonly string[]; commands: readonly string[]; permissions?: Record | undefined; }): NodeSession | null; invoke(params: { nodeId: string; command: string; params?: unknown; timeoutMs?: number; idempotencyKey?: string; }): Promise; /** Authorize an inbound system.run event against a recently issued node invoke. */ authorizeSystemRunEvent(params: { nodeId: string; connId?: string; runId?: string; sessionKey: string; terminal: boolean; }): boolean; private rememberAuthorizedSystemRunEvent; private forgetAuthorizedSystemRunEvent; private authorizedSystemRunEventExpiresAt; private matchAuthorizedSystemRunEvent; private matchSingleAuthorizedSystemRunEvent; private authorizedSystemRunSessionMatches; private allowsLegacyMacRunIdFallback; private pruneAuthorizedSystemRunEvents; private authorizedSystemRunEventKey; handleInvokeResult(params: { id: string; nodeId: string; connId: string | undefined; ok: boolean; payload?: unknown; payloadJSON?: string | null; error?: { code?: string; message?: string; } | null; }): boolean; sendEvent(nodeId: string, event: string, payload?: unknown): boolean; sendEventRaw(nodeId: string, event: string, payloadJSON?: SerializedEventPayload | null): boolean; private sendEventInternal; private sendEventRawInternal; private sendEventToSession; private rejectSlowNodeSocket; } //#endregion //#region src/gateway/server-broadcast-types.d.ts type GatewayBroadcastStateVersion = { presence?: number; health?: number; }; /** Options for gateway websocket broadcasts. */ type GatewayBroadcastOpts = { dropIfSlow?: boolean; stateVersion?: GatewayBroadcastStateVersion; }; /** Broadcast function signature for all connected clients. */ type GatewayBroadcastFn = (event: string, payload: unknown, opts?: GatewayBroadcastOpts) => void; /** Broadcast function signature for targeted connection ids. */ type GatewayBroadcastToConnIdsFn = (event: string, payload: unknown, connIds: ReadonlySet, opts?: GatewayBroadcastOpts) => void; //#endregion //#region src/gateway/server-channel-runtime.types.d.ts /** Snapshot of channel runtime state keyed by channel and account id. */ type ChannelRuntimeSnapshot = { channels: Partial>; channelAccounts: Partial>>; }; //#endregion //#region src/gateway/server-chat-state.d.ts type BufferedAgentEvent = { sessionKey?: string; agentId?: string; payload: AgentEventPayload & { spawnedBy?: string; }; }; //#endregion //#region src/gateway/server-shared.d.ts type DedupeEntry = { ts: number; ok: boolean; payload?: unknown; error?: ErrorShape; }; //#endregion //#region src/gateway/server-methods/shared-types.d.ts /** * Shared gateway request types used by every server-method module. */ type SubsystemLogger = ReturnType; /** Per-connection client metadata captured after the gateway handshake. */ type GatewayClient = { connect: ConnectParams; connId?: string; clientIp?: string; pluginSurfaceUrls?: Record; pluginNodeCapabilitySurfaces?: Record; pluginNodeCapabilities?: Record; isDeviceTokenAuth?: boolean; internal?: { allowModelOverride?: boolean; approvalRuntime?: boolean; pluginRuntimeOwnerId?: string; agentRunTracking?: "plugin_subagent"; }; }; /** Callback used by method handlers to emit one protocol response frame. */ type RespondFn = (ok: boolean, payload?: unknown, error?: ErrorShape, meta?: Record) => void; /** Runtime services and mutable gateway state available to request handlers. */ type GatewayRequestContext = { deps: CliDeps; cron: CronServiceContract; cronStorePath: string; getRuntimeConfig: () => OpenClawConfig; execApprovalManager?: ExecApprovalManager; pluginApprovalManager?: ExecApprovalManager; loadGatewayModelCatalog: (params?: { readOnly?: boolean; }) => Promise; getHealthCache: () => HealthSummary | null; refreshHealthSnapshot: (opts?: { probe?: boolean; includeSensitive?: boolean; }) => Promise; logHealth: { error: (message: string) => void; }; logGateway: SubsystemLogger; incrementPresenceVersion: () => number; getHealthVersion: () => number; broadcast: GatewayBroadcastFn; broadcastToConnIds: GatewayBroadcastToConnIdsFn; nodeSendToSession: (sessionKey: string, event: string, payload: unknown) => void; nodeSendToAllSubscribed: (event: string, payload: unknown) => void; nodeSubscribe: (nodeId: string, sessionKey: string) => void; nodeUnsubscribe: (nodeId: string, sessionKey: string) => void; nodeUnsubscribeAll: (nodeId: string) => void; hasConnectedTalkNode: () => boolean; hasExecApprovalClients?: (excludeConnId?: string) => boolean; getApprovalClientConnIds?: (params?: { excludeConnId?: string; filter?: (client: GatewayClient, record?: ExecApprovalRecord) => boolean; record?: ExecApprovalRecord; }) => ReadonlySet; disconnectClientsForDevice?: (deviceId: string, opts?: { role?: string; }) => void; invalidateClientsForDevice?: (deviceId: string, opts?: { role?: string; reason?: string; }) => void; disconnectClientsUsingSharedGatewayAuth?: () => void; enforceSharedGatewayAuthGenerationForConfigWrite?: (nextConfig: OpenClawConfig) => void; nodeRegistry: NodeRegistry; agentRunSeq: Map; chatAbortControllers: Map; chatAbortedRuns: Map; chatRunBuffers: Map; chatDeltaSentAt: Map; chatDeltaLastBroadcastLen: Map; chatDeltaLastBroadcastText: Map; agentDeltaSentAt: Map; bufferedAgentEvents: Map; clearChatRunState: (runId: string) => void; addChatRun: (sessionId: string, entry: { sessionKey: string; agentId?: string; clientRunId: string; }) => void; removeChatRun: (sessionId: string, clientRunId: string, sessionKey?: string) => { sessionKey: string; agentId?: string; clientRunId: string; } | undefined; subscribeSessionEvents: (connId: string) => void; unsubscribeSessionEvents: (connId: string) => void; subscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeSessionMessageEvents: (connId: string, sessionKey: string) => void; unsubscribeAllSessionEvents: (connId: string) => void; getSessionEventSubscriberConnIds: () => ReadonlySet; registerToolEventRecipient: (runId: string, connId: string) => void; dedupe: Map; wizardSessions: Map; findRunningWizard: () => string | null; purgeWizardSession: (id: string) => void; getRuntimeSnapshot: () => ChannelRuntimeSnapshot; getEventLoopHealth?: () => GatewayEventLoopHealth | undefined; startChannel: (channel: ChannelId, accountId?: string) => Promise; stopChannel: (channel: ChannelId, accountId?: string) => Promise; markChannelLoggedOut: (channelId: ChannelId, cleared: boolean, accountId?: string) => void; wizardRunner: (opts: OnboardOptions, runtime: RuntimeEnv, prompter: WizardPrompter) => Promise; broadcastVoiceWakeChanged: (triggers: string[]) => void; broadcastVoiceWakeRoutingChanged: (config: VoiceWakeRoutingConfig) => void; unavailableGatewayMethods?: ReadonlySet; }; /** Full dispatch context for raw request frames before params are normalized. */ type GatewayRequestOptions = { req: RequestFrame; client: GatewayClient | null; isWebchatConnect: (params: ConnectParams | null | undefined) => boolean; respond: RespondFn; context: GatewayRequestContext; methodRegistry?: GatewayMethodRegistryView; }; /** Normalized method invocation options passed to registered handlers. */ type GatewayRequestHandlerOptions = { req: RequestFrame; params: Record; client: GatewayClient | null; isWebchatConnect: (params: ConnectParams | null | undefined) => boolean; respond: RespondFn; context: GatewayRequestContext; }; /** Single gateway method implementation. */ type GatewayRequestHandler = (opts: GatewayRequestHandlerOptions) => Promise | void; /** Registry fragment keyed by gateway protocol method name. */ type GatewayRequestHandlers = Record; //#endregion export { SecretInputMode as C, resetAgentEventsForTest as S, AgentApprovalEventData as _, GatewayRequestOptions as a, emitAgentEvent as b, DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS as c, PluginNodeCapabilitySurface as d, buildPluginNodeCapabilityScopedHostUrl as f, CronServiceContract as g, GatewayMethodDescriptor as h, GatewayRequestHandlers as i, NormalizedPluginNodeCapabilityUrl as l, normalizePluginNodeCapabilityScopedUrl as m, GatewayRequestHandler as n, RespondFn as o, mintPluginNodeCapabilityToken as p, GatewayRequestHandlerOptions as r, NodeSession as s, GatewayRequestContext as t, PLUGIN_NODE_CAPABILITY_PATH_PREFIX as u, AgentEventPayload as v, onAgentEvent as x, AgentEventStream as y };