import { D as ChannelOutboundTargetMode, r as ChannelAccountSnapshot } from "./types.core-CQ2qSVEW.js"; import { E as ThinkingLevel, f as Model$1, l as ImageContent$2, r as AssistantMessage } from "./types-CFIUY_La.js"; import { T as StreamFn, f as AgentToolResult, l as AgentTool, s as AgentMessage } from "./types-D0CdrmU4.js"; import { t as ChatType } from "./chat-type-B6XXSSnm.js"; import { M as SessionScope, f as ContextVisibilityMode, k as SessionMaintenanceMode, y as HumanDelayConfig } from "./types.base-BDLtjuuz.js"; import { a as SourceReplyDeliveryMode, l as ReplyPayload, n as GetReplyOptions, o as PromptImageOrderEntry, r as PartialReplyPayload, t as BlockReplyContext } from "./types-Bo6laTsg.js"; import { a as SupplementalContextFacts, g as InboundEventKind, i as MsgContext, m as PluginHookChannelContext, n as InboundSourceModality, o as CommandTurnContext, r as MentionSource, s as CommandTurnKind, t as FinalizedMsgContext } from "./templating-DOk3rz_v.js"; import { Vn as SilentReplyConversationType, fn as CliBackendConfig, i as OpenClawConfig, t as ConfigFileSnapshot, vt as TalkProviderConfig } from "./types.openclaw-DH5a2ppk.js"; import { t as FastMode } from "./string-coerce-DJnd-JG-.js"; import { d as SecretInput } from "./types.secrets-C15Z_eLX.js"; import { o as AgentModelConfig } from "./types.provider-request-D8-dJlQu.js"; import { n as SafeBinProfileFixture } from "./exec-safe-bin-policy-profiles-BDyHRwUP.js"; import { M as MemoryCitationsMode, S as ToolLoopDetectionConfig } from "./types.tools-CdgAbSYx.js"; import { G as TtsAutoMode, K as TtsConfig, Q as TtsProvider, W as ResolvedTtsPersona, q as TtsMode } from "./types.slack-LdGC1N63.js"; import { d as ModelProviderAuthMode, f as ModelProviderConfig, l as ModelMediaInputConfig, o as ModelCompatConfig } from "./types.models-KkyWTGkd.js"; import { a as AuthProfileFailureReason, c as OAuthCredential, i as AuthProfileCredential, o as AuthProfileIdRepairResult, r as AuthProfileBlockedSource, s as AuthProfileStore, t as ApiKeyCredential } from "./types-C021KvTL.js"; import { f as MediaUnderstandingProvider } from "./types-DOyvl3t7.js"; import { n as UserTurnTranscriptRecorder, r as InputProvenance, t as UserTurnInput } from "./user-turn-transcript.types-DPSAsexh.js"; import { n as HistoryMediaEntry, t as HistoryEntry } from "./history.types-Bc8mCALh.js"; import { t as ChannelId$1 } from "./channel-id.types-DjYEl-_2.js"; import { C as ExecTarget, S as ExecSecurity, c as ExecApprovalDecision, u as ExecApprovalRequestPayload$1, x as ExecMode, y as ExecAsk } from "./exec-approvals-bouecjdj.js"; import { c as PluginApprovalRequestPayload } from "./plugin-approvals-Du2wBIIa.js"; import { n as RuntimeEnv } from "./runtime-Bxifh4bY.js"; import { _ as PluginFormat, d as UnifiedModelCatalogEntry, f as UnifiedModelCatalogKind, g as PluginDiagnostic, h as PluginConfigUiHint, i as PluginDependencyStatus, m as PluginBundleFormat, o as PluginManifestContracts, u as PluginKind } from "./manifest-registry-BCD6e2rb.js"; import { t as JsonSchemaObject } from "./json-schema.types-z_ZXZBRr.js"; import { t as PluginOrigin$1 } from "./plugin-origin.types-DOQEvsWL.js"; import { P as MessageReceipt } from "./types-qFgVZoFh.js"; import { _ as chunkTextWithMode, g as chunkText, h as chunkMarkdownTextWithMode, m as chunkMarkdownText, n as ChannelOutboundAdapter, p as chunkByNewline, v as resolveChunkMode, y as resolveTextChunkLimit } from "./outbound.types-CeQt-xHY.js"; import { i as WizardPrompter } from "./prompts-QQvLKZMo.js"; import { t as OperatorScope } from "./operator-scopes-Phea7r7e.js"; import { t as ChannelPlugin$2 } from "./types.plugin-BdPYAFYc.js"; import { n as PluginMetadataSnapshot, r as PluginCompatCode, t as PluginMetadataRegistryView } from "./plugin-metadata-snapshot.types-DSa-TOrz.js"; import { t as ConfigWriteAfterWrite } from "./runtime-snapshot-B6Klun10.js"; import { n as ConfigReplaceResult, t as ConfigMutationBase } from "./config-CIiZlLSv.js"; import { i as resolveStateDir } from "./paths-BeM5WEAC.js"; import { c as SessionBindingRecord } from "./session-binding.types-BbT2v6Ty.js"; import { o as SsrFPolicy$1 } from "./ssrf-skjEI_i5.js"; import { t as ModelProviderRequestTransportOverrides$1 } from "./provider-request-config-BuzYUp9w.js"; import { n as requestHeartbeat, t as HeartbeatRunResult } from "./heartbeat-wake-B5gXOqCt.js"; import { a as SessionContextBudgetStatus, c as SessionSystemPromptReport, n as CliSessionBinding, o as SessionEntry, r as GroupKeyResolution } from "./types-Dv0vM7Zp.js"; import { o as ChannelRouteRef } from "./channel-route-DUbOqcPC.js"; import { t as DeliveryContext } from "./delivery-context.types-DyNhFIjW.js"; import { g as updateSessionStore, m as onSessionTranscriptUpdate, v as loadSessionStore, x as ResolvedSessionMaintenanceConfigInput } from "./transcript-I3NBVHw4.js"; import { i as VerboseLevel, n as ThinkLevel, r as ThinkingCatalogEntry, t as ReasoningLevel } from "./thinking.shared-Dn7xz8fk.js"; import { r as AnyAgentTool } from "./common-CZ-od2BP.js"; import { Dt as PluginHookToolKind, Et as PluginHookToolInputKind, Gt as PluginNextTurnInjectionEnqueueResult, J as PluginHookHandlerMap, N as PluginHookBeforeToolCallEvent, Tt as PluginHookToolContext, Wt as PluginNextTurnInjection, _n as ReplyDispatchKind, an as PluginHookBeforeToolCallResult, bn as ReplyFollowupAdmissionBarrierTimeoutPolicy, gn as ReplyDispatchBeforeDeliver, ln as PluginHookBeforeAgentStartResult, nt as PluginHookRegistration$1, qt as PluginJsonValue, rn as PluginApprovalResolution, tt as PluginHookName, vn as ReplyDispatchRuntimeInfo, yn as ReplyDispatcher } from "./hook-types-DQlV8eed.js"; import { t as DiagnosticTraceContext } from "./diagnostic-trace-context-c5mRZYEt.js"; import { a as PluginConversationBindingResolvedEvent$1, n as PluginConversationBindingRequestParams, r as PluginConversationBindingRequestResult, t as PluginConversationBinding } from "./conversation-binding.types-CR-Dv6HW.js"; import { a as SkillUsagePath, i as SkillTelemetrySource, r as SkillSnapshot } from "./types-DKGs3QG0.js"; import { i as ExecAutoReviewer } from "./exec-auto-review-CYFxs7ho.js"; import { G as SandboxBackendWorkdirValidation, K as SandboxBackendWorkdirValidator, L as SandboxToolPolicy, V as SandboxBackendExecSpec, q as SandboxFsBridge } from "./sandbox-DfdtONMQ.js"; import { n as FailoverReason, t as EmbeddedContextFile } from "./types-CF0DHR3y.js"; import { t as FallbackAttempt } from "./model-fallback.types-BQxBBoz4.js"; import { n as NormalizedUsage, t as ContextUsage } from "./usage-DjdNXvuF.js"; import { n as completeSimple } from "./stream-C62LZX2q.js"; import { o as ProviderUsageSnapshot } from "./provider-usage.types-wjE6UjsI.js"; import { B as HookEntry, H as ensureAgentWorkspace, I as ConnectParams, L as ErrorShape, M as InternalHookHandler, N as CliDeps, V as WorkspaceBootstrapFile, z as RequestFrame } from "./internal-hooks-DYYCvcTJ.js"; import { i as ModelCatalogEntry, n as DEFAULT_MODEL, r as DEFAULT_PROVIDER } from "./defaults-CuM4TSj3.js"; import { Ai as AuthStorage, Ci as ModelRegistry$1 } from "./index-BDr9c_3B.js"; import { n as createSubsystemLogger, s as LogLevel } from "./subsystem-Boo2DQIV.js"; import { t as OpenClawAgentDatabase } from "./openclaw-agent-db-B-F-AnOy.js"; import { t as ProviderAuthEvidence } from "./provider-env-vars-HCSAoecz.js"; import { o as resolveStorePath, r as resolveSessionFilePath } from "./sessions-CO5rEtes.js"; import { a as CronJobCreate, c as CronRunStatus, i as CronJob, l as EmbeddedAgentExecutionPhase, o as CronJobPatch, s as CronPayload } from "./store-C6oU5Db4.js"; import { N as resolveAgentDir, P as resolveAgentWorkspaceDir } from "./agent-scope-BvKO6GFB.js"; import { a as createAckReactionHandle, c as shouldAckReaction, d as resolveAgentIdentity, f as resolveEffectiveMessagesConfig, o as removeAckReactionAfterReply, p as resolveHumanDelayConfig, s as removeAckReactionHandleAfterReply } from "./ack-reactions-BP5Ijb9Z.js"; import { o as enqueueSystemEvent } from "./system-events-BLt5iC5_.js"; import { a as runCommandWithTimeout } from "./exec-2Em92hsX.js"; import { s as mediaKindFromMime } from "./constants-DUpDbaN0.js"; import { h as resizeToJpeg, u as getImageMetadata } from "./media-services-BqLZh0ST.js"; import { n as loadWebMedia } from "./web-media-D1aVPCGn.js"; import { n as detectMime } from "./mime-B6baDqNM.js"; import { d as readRemoteMediaBuffer, f as saveRemoteMedia, g as isVoiceCompatibleAudio, p as saveResponseMedia, u as fetchRemoteMedia } from "./fetch-DXPnCJql.js"; import { _ as ImageGenerationSourceImage, c as ImageGenerationOutputFormat, f as ImageGenerationProviderOptions, h as ImageGenerationResolution, i as ImageGenerationNormalization, l as ImageGenerationProvider, n as ImageGenerationBackground, p as ImageGenerationQuality, r as ImageGenerationIgnoredOverride, t as GeneratedImageAsset } from "./types-BbLdsWl3.js"; import { d as VideoGenerationResolution, n as VideoGenerationIgnoredOverride, o as VideoGenerationNormalization, p as VideoGenerationSourceAsset, s as VideoGenerationProvider, t as GeneratedVideoAsset } from "./types-Ban9I_vo.js"; import { c as MusicGenerationProvider, f as MusicGenerationSourceImage, o as MusicGenerationNormalization, r as MusicGenerationIgnoredOverride, s as MusicGenerationOutputFormat, t as GeneratedMusicAsset } from "./types-C7aMRLEr.js"; import { n as RuntimeWebFetchMetadata, r as RuntimeWebSearchMetadata } from "./command-secret-gateway-Vw5Qodty.js"; import { a as shouldLogVerbose } from "./globals-BL1_NohW.js"; import { i as PluginStateSyncKeyedStore, r as PluginStateKeyedStore, t as OpenKeyedStoreOptions } from "./plugin-state-store.types-xAF7b0j2.js"; import { a as MediaUnderstandingRuntime } from "./runtime-types-C_f0_qUM.js"; import { r as EmbeddingProviderAdapter } from "./embedding-providers-BCBMINLP.js"; import { d as MemoryPromptSectionBuilder, o as MemoryFlushPlanResolver, r as MemoryCorpusSupplement, s as MemoryPluginCapability, u as MemoryPluginRuntime } from "./memory-state-1EG1Ro8c.js"; import { n as TimeFormatPreference } from "./date-time-C_aF3jiN.js"; import { n as MemoryMultimodalSettings, t as MemoryMultimodalModality } from "./multimodal-B2zGqeG7.js"; import { a as fetchWithSsrFGuard } from "./fetch-guard-BKvfwdRa.js"; import { l as shouldUseEnvHttpProxyForUrl } from "./proxy-env-CRHrWZla.js"; import { St as DiagnosticToolTerminalReason, a as DiagnosticEventPayload, i as DiagnosticEventMetadata, o as DiagnosticEventPrivateData, r as DiagnosticEventInput, rn as TalkTransport } from "./diagnostic-events-Bp9g9h2c.js"; import { r as PluginActivationSource } from "./config-state-CSLnEDsJ.js"; import { a as ResponsePrefixContext, s as TypingCallbacks } from "./reply-prefix-Cl7iPAre.js"; import { n as ReadChannelAllowFromStoreForAccount$1, r as UpsertChannelPairingRequestForAccount$1 } from "./pairing-store.types-z_X8e_Xx.js"; import { s as CommandNormalizeOptions, u as ShouldHandleTextCommandsParams } from "./commands-registry.types-BPwmKh6u.js"; import { a as MatchesMentionWithExplicit$1, i as MatchesMentionPatterns$1, t as BuildMentionRegexes$1 } from "./mentions.types-DDEnLRxm.js"; import { n as RecordInboundSession$1, t as InboundLastRouteUpdate } from "./session.types-Dt8nrcqx.js"; import { t as hasControlCommand } from "./command-detection-DY6wa56v.js"; import { t as ResolveMarkdownTableMode } from "./markdown-tables.types-DbxWzy38.js"; import { t as convertMarkdownTables } from "./tables-BBMGs0qO.js"; import { i as buildAgentSessionKey, o as resolveAgentRoute } from "./resolve-route-Dn_RNdFq.js"; import { t as buildPairingReply } from "./pairing-messages-CkTVypel.js"; import { p as saveMediaBuffer } from "./store-D6pQmvkB.js"; import { n as getChannelActivity, r as recordChannelActivity } from "./channel-activity-B4WQX84y.js"; import { f as implicitMentionKindWhen, p as resolveInboundMentionDecision } from "./mention-gating-D6dFDlTf.js"; import { n as resolveChannelGroupPolicy, r as resolveChannelGroupRequireMention } from "./group-policy-DcunSfaK.js"; import { n as createInboundDebouncer, r as resolveInboundDebounceMs } from "./inbound-debounce-Cg7vawdc.js"; import { r as resolveCommandAuthorizedFromAuthorizers } from "./command-gating-pUtyEXB1.js"; import { a as OutboundDeliveryQueuePolicy, n as DurableFinalDeliveryRequirement, r as DurableFinalDeliveryRequirements, t as DeliverOutboundPayloadsParams } from "./deliver-Dct7lo7t.js"; import { i as createChannelReplyPipeline, n as CreateChannelReplyPipelineParams } from "./reply-pipeline-D_IJab92.js"; import { a as PairLoopGuardResult, i as PairLoopGuardConfig } from "./pair-loop-guard-runtime-D5O3zwX9.js"; import { n as createChannelHistoryWindow, t as ChannelHistoryWindow } from "./history-window-BSd8jX-m.js"; import { t as HeartbeatSummary } from "./heartbeat-summary-DmiATCZ9.js"; import { o as TranscriptSourceProvider$2 } from "./provider-types-DcHVFapN.js"; import { ZodTypeAny } from "zod"; import { statRegularFile } from "@openclaw/fs-safe/advanced"; import { TSchema, Type } from "typebox"; import { isPathInside } from "@openclaw/fs-safe/path"; import { monitorEventLoopDelay, performance } from "node:perf_hooks"; import { WebSocket } from "ws"; import { Duplex } from "node:stream"; import { Model } from "openclaw/plugin-sdk/llm"; import { IncomingMessage, ServerResponse } from "node:http"; import { Command } from "commander"; //#region src/crestodian/setup-apply.d.ts /** * The whole first-run setup as one approved operation: the user says "yes" in * the conversation and this applies model + workspace + quickstart gateway * defaults, seeds workspace bootstrap files, and (on the CLI surface) installs * and starts the gateway service. No interactive prompts may occur here — * everything uses quickstart defaults, so the conversation stays the only UI. */ type CrestodianSetupApplyParams = { workspace: string; model?: string; surface: "cli" | "gateway"; runtime: RuntimeEnv; }; type CrestodianSetupApplyResult = { configPath: string; lines: string[]; }; declare function applyCrestodianSetup(params: CrestodianSetupApplyParams): Promise; //#endregion //#region src/cli/config-set-input.d.ts type ConfigSetOptions = { strictJson?: boolean; /** @deprecated Use strictJson. */ json?: boolean; dryRun?: boolean; allowExec?: boolean; merge?: boolean; replace?: boolean; refProvider?: string; refSource?: string; refId?: string; providerSource?: string; providerAllowlist?: string[]; providerPath?: string; providerMode?: string; providerTimeoutMs?: string; providerMaxBytes?: string; providerCommand?: string; providerArg?: string[]; providerNoOutputTimeoutMs?: string; providerMaxOutputBytes?: string; providerJsonOnly?: boolean; providerEnv?: string[]; providerPassEnv?: string[]; providerTrustedDir?: string[]; providerAllowInsecurePath?: boolean; providerAllowSymlinkCommand?: boolean; batchJson?: string; batchFile?: string; }; //#endregion //#region src/commands/doctor.types.d.ts /** CLI option shape shared by doctor command entrypoints and prompt helpers. */ type DoctorOptions = { workspaceSuggestions?: boolean; yes?: boolean; nonInteractive?: boolean; deep?: boolean; repair?: boolean; force?: boolean; generateGatewayToken?: boolean; allowExec?: boolean; postUpgrade?: boolean; json?: boolean; }; //#endregion //#region src/crestodian/probes.d.ts /** * Local environment probes used by Crestodian overview loading. * * Probes are bounded by output and timeout limits so setup/status commands do * not hang or retain unbounded child output. */ /** Result from probing a local command binary. */ type LocalCommandProbe = { command: string; found: boolean; version?: string; error?: string; }; /** Probe a command by running a small version command with bounded output and timeout. */ declare function probeLocalCommand(command: string, args?: string[], opts?: { outputLimit?: number; timeoutKillGraceMs?: number; timeoutMs?: number; }): Promise; //#endregion //#region src/commands/onboard-inference.d.ts type InferenceBackendKind = "existing-model" | "openai-api-key" | "anthropic-api-key" | "claude-cli" | "codex-cli" | "gemini-cli"; type InferenceBackendCandidate = { kind: InferenceBackendKind; modelRef: string; /** Short human label, e.g. "Claude Code CLI". */ label: string; /** One-line provenance, e.g. "logged in", "ANTHROPIC_API_KEY set". */ detail: string; /** * true: credentials verified; false: definitively logged out; undefined: * unknown (e.g. macOS keychain-backed logins we must not prompt for here). */ credentials?: boolean; }; type DetectInferenceBackendsDeps = { probeLocalCommand?: typeof probeLocalCommand; readClaudeCliCredentials?: () => { type: string; } | null; readCodexCliCredentials?: () => { type: string; } | null; readGeminiCliCredentials?: () => { type: string; } | null; }; type DetectInferenceBackendsOptions = { config?: OpenClawConfig; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; deps?: DetectInferenceBackendsDeps; }; /** * Detect usable inference backends in ladder order. Returns candidates only * for backends that exist on this machine; the first entry is the bootstrap * default. Backends that are definitively logged out sink below logged-in and * unknown ones so a stale install never outranks a working login. */ declare function detectInferenceBackends(options?: DetectInferenceBackendsOptions): Promise; //#endregion //#region src/tui/tui-types.d.ts type TuiExitReason = "exit" | "return-to-crestodian"; type TuiResult = { exitReason: TuiExitReason; crestodianMessage?: string; }; //#endregion //#region src/crestodian/overview.d.ts type CrestodianAgentSummary = { id: string; name?: string; isDefault: boolean; model?: string; workspace?: string; }; type CrestodianOverview = { config: { path: string; exists: boolean; valid: boolean; issues: string[]; hash: string | null; }; agents: CrestodianAgentSummary[]; defaultAgentId: string; defaultModel?: string; tools: { codex: LocalCommandProbe; claude: LocalCommandProbe; gemini: LocalCommandProbe; apiKeys: { openai: boolean; anthropic: boolean; }; }; gateway: { url: string; source: string; reachable: boolean; error?: string; }; references: { docsPath?: string; docsUrl: string; sourcePath?: string; sourceUrl: string; }; }; //#endregion //#region src/crestodian/operations.d.ts type CrestodianOverviewLoader = () => Promise; type CrestodianOverviewFormatter = (overview: CrestodianOverview) => string; /** Parsed Crestodian operation before approval/execution. */ type CrestodianOperation = { kind: "none"; message: string; } | { kind: "overview"; } | { kind: "doctor"; } | { kind: "doctor-fix"; } | { kind: "status"; } | { kind: "health"; } | { kind: "config-validate"; } | { kind: "config-get"; path: string; } | { kind: "config-schema"; path?: string; } | { kind: "config-set"; path: string; value: string; } | { kind: "config-set-ref"; path: string; source: "env" | "file" | "exec"; id: string; provider?: string; } | { kind: "setup"; workspace?: string; model?: string; } | { kind: "model-setup"; workspace?: string; } | { kind: "channel-list"; } | { kind: "channel-setup"; channel: string; } | { kind: "gateway-status"; } | { kind: "gateway-start"; } | { kind: "gateway-stop"; } | { kind: "gateway-restart"; } | { kind: "agents"; } | { kind: "models"; } | { kind: "plugin-list"; } | { kind: "plugin-search"; query: string; } | { kind: "plugin-install"; spec: string; } | { kind: "plugin-uninstall"; pluginId: string; } | { kind: "audit"; } | { kind: "create-agent"; agentId: string; workspace?: string; model?: string; } | { kind: "open-tui"; agentId?: string; workspace?: string; } | { kind: "set-default-model"; model: string; }; /** Injectable command dependencies used by tests and alternate runners. */ type CrestodianCommandDeps = { formatOverview?: CrestodianOverviewFormatter; loadOverview?: CrestodianOverviewLoader; runAgentsAdd?: (opts: { name?: string; workspace?: string; model?: string; nonInteractive?: boolean; json?: boolean; }, runtime: RuntimeEnv, params?: { hasFlags?: boolean; }) => Promise; runConfigSet?: (opts: { path?: string; value?: string; cliOptions: ConfigSetOptions; }) => Promise; runDoctor?: (runtime: RuntimeEnv, options: DoctorOptions) => Promise; runGatewayRestart?: () => Promise; runGatewayStart?: () => Promise; runGatewayStop?: () => Promise; runPluginInstall?: (spec: string, runtime: RuntimeEnv) => Promise; runPluginUninstall?: (pluginId: string, runtime: RuntimeEnv) => Promise; runPluginsList?: (runtime: RuntimeEnv) => Promise; runPluginsSearch?: (query: string, runtime: RuntimeEnv) => Promise; runTui?: (opts: { local: boolean; session?: string; deliver?: boolean; historyLimit?: number; }) => Promise; detectInferenceBackends?: typeof detectInferenceBackends; /** Where setup side effects run; the gateway surface never manages its own daemon. */ setupSurface?: "cli" | "gateway"; applySetup?: typeof applyCrestodianSetup; }; //#endregion //#region src/agents/tools/crestodian-tool.d.ts type CrestodianToolOptions = { /** Where setup side effects run; the gateway surface never manages its own daemon. */surface: "cli" | "gateway"; /** * Host-verified consent for THIS turn: true only when the host judged the * user's actual message to be an explicit approval. The model-supplied * `approved` argument alone must never authorize a mutation (prompt * injection, model error). */ approvalArmed?: boolean; /** * Approval is scoped to one exact operation: a denied mutating call records * its canonical hash here (host-owned, survives turns), and an armed turn * may execute only a call matching that hash. Cleared after use. */ proposalRef?: { current?: string; }; /** * Host handoff channel for actions the tool cannot perform itself * (interactive channel-setup wizard, opening the agent TUI). The engine * reads it after the turn; CLI MCP hosts mirror it from tool events. */ directiveRef?: { current?: CrestodianToolDirective; }; }; /** Interactive handoffs the hosting chat engine executes after the turn. */ type CrestodianToolDirective = { kind: "channel-setup"; channel: string; } | { kind: "model-setup"; workspace?: string; } | { kind: "open-tui"; agentId?: string; workspace?: string; }; //#endregion //#region src/auto-reply/reply/reply-run-registry.d.ts type ReplyRunKey = string; type ReplyBackendKind = "embedded" | "cli"; type ReplyBackendCancelReason = "user_abort" | "restart" | "superseded"; type ReplyBackendQueueMessageOptions = { steeringMode?: "all"; debounceMs?: number; deliveryTimeoutMs?: number; waitForTranscriptCommit?: boolean; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; /** Prepared channel turn to merge only at transcript persistence. */ userTurnTranscriptRecorder?: UserTurnTranscriptRecorder; }; type ReplyBackendHandle = { readonly kind: ReplyBackendKind; cancel(reason?: ReplyBackendCancelReason): void; isStreaming(): boolean; isStopped?: () => boolean; isAbortable?: () => boolean; queueMessage?: (text: string, options?: ReplyBackendQueueMessageOptions) => Promise; /** * Compatibility-only hook so legacy "abort compacting runs" paths can still * find embedded runs that are compacting during the main run phase. */ isCompacting?: () => boolean; }; type ReplyOperationPhase = "queued" | "preflight_compacting" | "memory_flushing" | "running" | "completed" | "failed" | "aborted"; type ReplyOperationFailureCode = "gateway_draining" | "command_lane_cleared" | "aborted_by_user" | "session_corruption_reset" | "run_failed"; type ReplyOperationAbortCode = "aborted_by_user" | "aborted_for_restart"; type ReplyOperationResult = { kind: "completed"; } | { kind: "failed"; code: ReplyOperationFailureCode; cause?: unknown; } | { kind: "aborted"; code: ReplyOperationAbortCode; }; type ReplyOperation = { readonly key: ReplyRunKey; readonly sessionId: string; readonly routeThreadId?: string | number; readonly abortSignal: AbortSignal; readonly resetTriggered: boolean; /** * True when this operation was admitted to recover a terminal session (a * leftover failed/timeout/killed run). Concurrent visible turns reading the * same terminal store snapshot must NOT force-clear such an operation: it is a * sibling recovery already in flight, not the proven stale leftover. */ readonly terminalRecovery: boolean; /** * Sticky fact for audio accepted into this operation after its originating turn. * Final delivery reads it because the original dispatch context cannot change. */ readonly acceptedSteeredInboundAudio: boolean; readonly phase: ReplyOperationPhase; readonly result: ReplyOperationResult | null; /** True when this operation has owned the supplied session ID. */ hasOwnedSessionId(sessionId: string): boolean; setPhase(next: "queued" | "preflight_compacting" | "memory_flushing" | "running"): void; /** Mark this operation as an in-flight terminal-session recovery. */ markTerminalRecovery(): void; markAcceptedSteeredInboundAudio(): void; updateSessionId(nextSessionId: string): void; attachBackend(handle: ReplyBackendHandle): void; detachBackend(handle: ReplyBackendHandle): void; /** Reject later aborts after the backend has committed its terminal outcome. */ freezeAbort(): void; /** * Keep a failed operation active until complete() releases the session lane. * Dispatch uses this while a user-visible failure payload still needs delivery. */ retainFailureUntilComplete(): void; complete(): void; /** * Complete the operation, clear active-run state, then run follow-up work. * Use when the follow-up can create another ReplyOperation for this session. */ completeThen(afterClear: () => void): void; /** * Clear active-run state immediately, but delay registered after-clear work * until delivery or another external barrier settles. */ completeWithAfterClearBarrier(barrier: PromiseLike, timeout?: number | ReplyFollowupAdmissionBarrierTimeoutPolicy): void; fail(code: Exclude, cause?: unknown): void; abortByUser(): boolean; abortForRestart(): boolean; }; //#endregion //#region src/process/command-queue.types.d.ts /** * Public enqueue knobs shared by command-lane callers and narrower injection * points that should not import the full queue implementation. */ type CommandQueueEnqueueOptions = { warnAfterMs?: number; onWait?: (waitMs: number, queuedAhead: number) => void; taskTimeoutMs?: number; taskTimeoutProgressAtMs?: () => number | undefined; taskTimeoutAbortSignal?: AbortSignal; taskTimeoutAbortGraceMs?: number; /** Ends the task after a caller-owned timeout cleanup grace has already elapsed. */ taskTimeoutReleaseSignal?: AbortSignal; priority?: "foreground" | "normal" | "background"; }; /** Minimal queue function contract used by code that only needs to schedule work. */ type CommandQueueEnqueueFn = (task: () => Promise, opts?: CommandQueueEnqueueOptions) => Promise; //#endregion //#region src/infra/event-session-routing.d.ts /** Routing policy derived from config and the source session for an event. */ type EventSessionRoutingPolicy = { mainKey?: string; sessionScope?: SessionScope; dmScope?: string | null; allowFrom?: ReadonlyArray | null; channel?: string | null; accountId?: string | null; preserveSessionKey?: boolean; }; //#endregion //#region src/agents/bash-tools.shared.d.ts /** Sandbox metadata needed to map host workspaces into container exec calls. */ type BashSandboxConfig = { containerName: string; workspaceDir: string; containerWorkdir: string; workdirValidation?: SandboxBackendWorkdirValidation; validateWorkdir?: SandboxBackendWorkdirValidator; discardPreparedWorkdir?: (workdir: string) => void; workdirRoots?: readonly string[]; env?: Record; buildExecSpec?: (params: { command: string; workdir?: string; env: Record; usePty: boolean; }) => Promise; finalizeExec?: (params: { status: "completed" | "failed"; exitCode: number | null; timedOut: boolean; token?: unknown; }) => Promise; }; //#endregion //#region src/auto-reply/heartbeat-tool-response.d.ts /** Tool name used by heartbeat runs to report visible or silent progress. */ declare const HEARTBEAT_RESPONSE_TOOL_NAME = "heartbeat_respond"; /** Allowed heartbeat response outcomes. */ declare const HEARTBEAT_TOOL_OUTCOMES: readonly ["no_change", "progress", "done", "blocked", "needs_attention"]; type HeartbeatToolOutcome = (typeof HEARTBEAT_TOOL_OUTCOMES)[number]; /** Allowed heartbeat notification priorities. */ declare const HEARTBEAT_TOOL_PRIORITIES: readonly ["low", "normal", "high"]; type HeartbeatToolPriority = (typeof HEARTBEAT_TOOL_PRIORITIES)[number]; /** Normalized response emitted by the heartbeat response tool. */ type HeartbeatToolResponse = { outcome: HeartbeatToolOutcome; notify: boolean; summary: string; notificationText?: string; reason?: string; priority?: HeartbeatToolPriority; nextCheck?: string; }; /** Validate and normalize unknown heartbeat tool output. */ declare function normalizeHeartbeatToolResponse(value: unknown): HeartbeatToolResponse | undefined; //#endregion //#region src/agents/accepted-session-spawn.d.ts type AcceptedSessionSpawn = { runId: string; childSessionKey: string; }; //#endregion //#region src/agents/embedded-agent-messaging.types.d.ts type MessagingToolSend = { tool: string; provider: string; accountId?: string; to?: string; threadId?: string; threadImplicit?: boolean; threadSuppressed?: boolean; text?: string; mediaUrls?: string[]; hasRichContent?: true; }; type MessagingToolSourceReplyPayload = Pick & { idempotencyKey?: string; }; //#endregion //#region src/agents/run-timeout-attribution.d.ts /** Agent run phases used when attributing timeout/cancellation sources. */ declare const AGENT_RUN_TIMEOUT_PHASES: readonly ["queue", "preflight", "provider", "post_turn", "gateway_draining"]; /** Timeout attribution phase for agent run lifecycle spans. */ type AgentRunTimeoutPhase = (typeof AGENT_RUN_TIMEOUT_PHASES)[number]; //#endregion //#region src/agents/embedded-agent-runner/types.d.ts type BlockReplyFlushContext = { /** Boundary that requested the flush. */reason: "message_end" | "terminal"; } | { /** Tool boundary separating pre-tool narration from the eventual answer. */reason: "tool_start"; assistantMessageIndex: number; } | { /** Pre-compaction delivery is safe only for a completed assistant attempt. */reason: "pre_compaction"; attemptAccepted: boolean; }; type EmbeddedAgentMeta = { sessionId: string; sessionFile?: string; provider: string; model: string; contextTokens?: number; agentHarnessId?: string; fallbackAttempts?: FallbackAttempt[]; cliSessionBinding?: CliSessionBinding; clearCliSessionBinding?: boolean; compactionCount?: number; /** * Token count estimate after the most recent successful auto-compaction. * Used as the freshest context snapshot when the follow-up model call omits * usage metadata. */ compactionTokensAfter?: number; /** * Prompt/context snapshot from the latest model request. Prefer this for * context-window utilization because provider usage totals can include cached * and completion tokens that are useful for billing but noisy as live context. */ promptTokens?: number; usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; reasoningTokens?: number; total?: number; }; /** * Usage from the last individual API call (not accumulated across tool-use * loops or compaction retries). Used for context-window utilization display * (`totalTokens` in sessions.json) because the accumulated `usage.input` * sums input tokens from every API call in the run, which overstates the * actual context size. */ lastCallUsage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; contextUsage?: ContextUsage; reasoningTokens?: number; total?: number; }; contextBudgetStatus?: SessionContextBudgetStatus; }; type TraceAttempt = { provider: string; model: string; result: "success" | "timeout" | "surface_error" | "candidate_failed" | "rotate_profile" | "same_model_rate_limit" | "fallback_model" | "aborted" | "error"; reason?: string; stage?: "prompt" | "assistant"; elapsedMs?: number; status?: number; }; type ExecutionTrace = { winnerProvider?: string; winnerModel?: string; attempts?: TraceAttempt[]; fallbackUsed?: boolean; runner?: "embedded" | "cli"; }; type RequestShapingTrace = { authMode?: string; thinking?: string; reasoning?: string; verbose?: string; trace?: string; fallbackEligible?: boolean; blockStreaming?: string; }; type PromptSegmentTrace = { key: string; chars: number; }; type ToolSummaryTrace = { calls: number; tools: string[]; failures?: number; totalToolTimeMs?: number; }; type CompletionTrace = { finishReason?: string; stopReason?: string; refusal?: boolean; }; type ContextManagementTrace = { sessionCompactions?: number; lastTurnCompactions?: number; preflightCompactionApplied?: boolean; postCompactionContextInjected?: boolean; }; type EmbeddedRunLivenessState = "working" | "paused" | "blocked" | "abandoned"; type EmbeddedRunFailureSignal = { kind: "execution_denied"; source: "tool"; toolName?: string; code: "SYSTEM_RUN_DENIED" | "INVALID_REQUEST"; message: string; fatalForCron: true; }; type EmbeddedAgentRunMeta = { durationMs: number; agentMeta?: EmbeddedAgentMeta; aborted?: boolean; systemPromptReport?: SessionSystemPromptReport; finalPromptText?: string; finalAssistantVisibleText?: string; finalAssistantRawText?: string; replayInvalid?: boolean; livenessState?: EmbeddedRunLivenessState; timeoutPhase?: AgentRunTimeoutPhase; providerStarted?: boolean; agentHarnessResultClassification?: "empty" | "reasoning-only" | "planning-only"; terminalReplyKind?: "silent-empty"; yielded?: boolean; error?: { kind: "context_overflow" | "compaction_failure" | "role_ordering" | "image_size" | "retry_limit" | "incomplete_turn" | "hook_block"; message: string; /** True only when model fallback can retry this terminal error without repeating side effects. */ fallbackSafe?: boolean; /** True when the payload includes a trusted structured terminal tool summary. */ terminalPresentation?: boolean; }; failureSignal?: EmbeddedRunFailureSignal; /** Stop reason for the agent run (e.g., "completed", "tool_calls"). */ stopReason?: string; /** Pending tool calls when stopReason is "tool_calls". */ pendingToolCalls?: Array<{ id: string; name: string; arguments: string; }>; executionTrace?: ExecutionTrace; requestShaping?: RequestShapingTrace; promptSegments?: PromptSegmentTrace[]; toolSummary?: ToolSummaryTrace; completion?: CompletionTrace; contextManagement?: ContextManagementTrace; }; type EmbeddedAgentRunResult = { payloads?: Array<{ text?: string; mediaUrl?: string; mediaUrls?: string[]; replyToId?: string; isError?: boolean; isReasoning?: boolean; /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */ isCommentary?: boolean; audioAsVoice?: boolean; trustedLocalMedia?: boolean; channelData?: Record; }>; meta: EmbeddedAgentRunMeta; diagnosticTrace?: DiagnosticTraceContext; didSendViaMessagingTool?: boolean; didDeliverSourceReplyViaMessageTool?: boolean; didSendDeterministicApprovalPrompt?: boolean; messagingToolSentTexts?: string[]; messagingToolSentMediaUrls?: string[]; messagingToolSentTargets?: MessagingToolSend[]; messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[]; acceptedSessionSpawns?: AcceptedSessionSpawn[]; heartbeatToolResponse?: HeartbeatToolResponse; successfulCronAdds?: number; }; type EmbeddedAgentCompactResult = { ok: boolean; compacted: boolean; reason?: string; /** Structured failure metadata used by model fallback classification. */ failure?: { reason?: string; status?: number; code?: string; rawError?: string; }; result?: { summary: string; firstKeptEntryId: string; tokensBefore: number; tokensAfter?: number; details?: unknown; sessionId?: string; sessionFile?: string; }; }; type EmbeddedFullAccessBlockedReason = "sandbox" | "host-policy" | "channel" | "runtime"; //#endregion //#region src/llm/model-registry.d.ts /** Registry abstraction used by model pickers and provider availability checks. */ type ModelRegistry = { getAll(): Model$1[]; getAvailable(): Model$1[]; find(provider: string, modelId: string): Model$1 | undefined; hasConfiguredAuth(model: Model$1): boolean; }; //#endregion //#region src/plugins/provider-external-auth.types.d.ts /** Context for resolving synthetic provider credentials from config. */ type ProviderResolveSyntheticAuthContext = { config?: OpenClawConfig; provider: string; providerConfig?: ModelProviderConfig; }; /** Synthetic provider credential returned by plugin auth helpers. */ type ProviderSyntheticAuthResult = { apiKey: string; source: string; mode: Exclude; expiresAt?: number; }; /** Context for resolving external provider auth profiles. */ type ProviderResolveExternalAuthProfilesContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; store: AuthProfileStore; }; /** OAuth-specific external auth profile resolution context. */ type ProviderResolveExternalOAuthProfilesContext = ProviderResolveExternalAuthProfilesContext; /** External auth profile credential resolved for a provider. */ type ProviderExternalAuthProfile = { profileId: string; credential: OAuthCredential; persistence?: "runtime-only" | "persisted"; }; /** OAuth-specific provider external auth profile alias. */ type ProviderExternalOAuthProfile = ProviderExternalAuthProfile; //#endregion //#region src/agents/system-prompt-contribution.d.ts /** * Provider-owned system prompt contribution types. * Separates cache-stable prefixes, dynamic suffixes, and section overrides for * runtime prompt assembly. */ /** Core system-prompt sections that providers may replace. */ type ProviderSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; /** Provider guidance merged into the assembled agent system prompt. */ type ProviderSystemPromptContribution = { /** * Cache-stable provider guidance inserted above the system-prompt cache boundary. * * Use this for static provider/model-family instructions that should preserve * KV cache reuse across turns. */ stablePrefix?: string; /** * Provider guidance inserted below the cache boundary. * * Use this only for genuinely dynamic text that is expected to vary across * runs or sessions. */ dynamicSuffix?: string; /** * Whole-section replacements for selected core prompt sections. * * Values should contain the complete rendered section, including any desired * heading such as `## Tool Call Style`. */ sectionOverrides?: Partial>; }; //#endregion //#region src/plugins/provider-hook-runtime.d.ts type ProviderRuntimePluginLookupParams = { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; applyAutoEnable?: boolean; bundledProviderVitestCompat?: boolean; pluginMetadataSnapshot?: PluginMetadataRegistryView; }; type ProviderRuntimePluginHandle = ProviderRuntimePluginLookupParams & { plugin?: ProviderPlugin; }; //#endregion //#region src/plugins/provider-runtime-model.types.d.ts /** * Fully-resolved runtime model shape used after provider/plugin-owned * discovery, overrides, and compat normalization. */ type ProviderRuntimeModel = Omit & { compat?: ModelCompatConfig; contextTokens?: number; params?: Record; requestTimeoutMs?: number; mediaInput?: ModelMediaInputConfig; }; //#endregion //#region src/plugins/provider-thinking.types.d.ts /** * Provider-owned thinking policy input. * * Used by shared `/think`, ACP controls, and directive parsing to ask a * provider whether a model supports special reasoning UX such as adaptive, * xhigh, max, or a binary on/off toggle. */ type ProviderThinkingPolicyContext = { provider: string; modelId: string; }; type ProviderThinkingModelCompat = { thinkingFormat?: string; supportedReasoningEfforts?: readonly string[] | null; }; /** * Provider-owned default thinking policy input. * * `reasoning` is the merged catalog hint for the selected model when one is * available. Providers can use it to keep "reasoning model => low" behavior * without re-reading the catalog themselves. * * `compat` carries model-level request contract facts for the selected model * when available. Providers can use it to expose model-specific thinking * profiles only when the configured payload style supports them. */ type ProviderDefaultThinkingPolicyContext = ProviderThinkingPolicyContext & { /** Effective agent runtime selected for this model, when known. */agentRuntime?: string | null; reasoning?: boolean; params?: Record; compat?: ProviderThinkingModelCompat | null; }; type ProviderThinkingLevelId = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max" | "ultra"; type ProviderThinkingLevel = { id: ProviderThinkingLevelId; /** * Optional display label. Use this when the stored value differs from the * provider-facing UX, for example binary providers storing `low` but showing * `on`. */ label?: string; /** * Relative strength used when downgrading a stored level that the selected * model no longer supports. */ rank?: number; }; type ProviderThinkingProfile = { levels: ProviderThinkingLevel[] | ReadonlyArray; defaultLevel?: ProviderThinkingLevelId | null; /** * Some bundled providers have model-specific thinking contracts that are more * current than cached generic catalog metadata. Keep this opt-in so * `reasoning: false` remains authoritative for ordinary catalog entries. */ preserveWhenCatalogReasoningFalse?: boolean; }; //#endregion //#region src/plugins/provider-runtime.d.ts declare function runProviderDynamicModel(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderResolveDynamicModelContext; }): ProviderRuntimeModel | undefined; declare function prepareProviderDynamicModel(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderPrepareDynamicModelContext; }): Promise; declare function shouldPreferProviderRuntimeResolvedModel(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderPreferRuntimeResolvedModelContext; }): boolean; declare function normalizeProviderResolvedModelWithPlugin(params: { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; pluginMetadataSnapshot?: PluginMetadataRegistryView; context: { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; model: ProviderRuntimeModel; }; }): ProviderRuntimeModel | undefined; declare function applyProviderResolvedTransportWithPlugin(params: { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderNormalizeResolvedModelContext; }): ProviderRuntimeModel | undefined; declare function normalizeProviderTransportWithPlugin(params: { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderNormalizeTransportContext; }): { api?: string | null; baseUrl?: string; } | undefined; declare function buildProviderUnknownModelHintWithPlugin(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderBuildUnknownModelHintContext; }): string | undefined; declare function augmentModelCatalogWithProviderPlugins(params: { config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderAugmentModelCatalogContext; }): Promise; //#endregion //#region src/agents/embedded-agent-runner/model.d.ts type ProviderRuntimeHooks = { applyProviderResolvedTransportWithPlugin?: (params: Parameters[0]) => unknown; buildProviderUnknownModelHintWithPlugin: (params: Parameters[0]) => string | undefined; prepareProviderDynamicModel: (params: Parameters[0]) => Promise; runProviderDynamicModel: (params: Parameters[0]) => unknown; shouldPreferProviderRuntimeResolvedModel?: (params: Parameters[0]) => boolean; normalizeProviderResolvedModelWithPlugin: (params: Parameters[0]) => unknown; normalizeProviderTransportWithPlugin: typeof normalizeProviderTransportWithPlugin; }; declare function resolveModelAsync(provider: string, modelId: string, agentDir?: string, cfg?: OpenClawConfig, options?: { authStorage?: AuthStorage; modelRegistry?: ModelRegistry$1; allowBundledStaticCatalogFallback?: boolean; preferBundledStaticCatalogTransport?: boolean; retryTransientProviderRuntimeMiss?: boolean; runtimeHooks?: ProviderRuntimeHooks; skipProviderRuntimeHooks?: boolean; skipAgentDiscovery?: boolean; workspaceDir?: string; authProfileId?: string; preferredProfile?: string; }): Promise<{ model?: Model$1; error?: string; authStorage: AuthStorage; modelRegistry: ModelRegistry$1; }>; //#endregion //#region src/agents/auth-profiles/constants.d.ts /** @deprecated Anthropic provider-owned CLI profile id; do not use from third-party plugins. */ declare const CLAUDE_CLI_PROFILE_ID = "anthropic:claude-cli"; /** @deprecated OpenAI provider-owned CLI profile id; do not use from third-party plugins. */ declare const CODEX_CLI_PROFILE_ID = "openai:codex-cli"; //#endregion //#region src/agents/auth-profiles/credential-state.d.ts /** Reason code for why a stored auth credential can or cannot be used. */ type AuthCredentialReasonCode = "ok" | "missing_credential" | "invalid_expires" | "expired" | "unresolved_ref" | "malformed_api_key"; /** Default OAuth access-token refresh margin before expiry. */ declare const DEFAULT_OAUTH_REFRESH_MARGIN_MS: number; /** Normalized expiry state for token-style credentials. */ type TokenExpiryState = "missing" | "valid" | "expiring" | "expired" | "invalid_expires"; /** Returns true when an OAuth credential has a non-expiring access token. */ declare function hasUsableOAuthCredential(credential: OAuthCredential | undefined, opts?: { now?: number; refreshMarginMs?: number; }): boolean; //#endregion //#region src/agents/provider-auth-aliases.d.ts /** Inputs that control plugin metadata and trust scope for auth alias lookup. */ type ProviderAuthAliasLookupParams = { config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; includeUntrustedWorkspacePlugins?: boolean; metadataSnapshot?: Pick; }; /** Clear provider auth alias cache for tests that mutate plugin metadata. */ declare function resetProviderAuthAliasMapCacheForTest(): void; /** Resolve canonical auth provider aliases from plugin metadata. */ declare function resolveProviderAuthAliasMap(params?: ProviderAuthAliasLookupParams): Record; /** Resolve the provider ID that should be used for credential lookup. */ declare function resolveProviderIdForAuth(provider: string, params?: ProviderAuthAliasLookupParams): string; //#endregion //#region src/agents/auth-profiles/order.d.ts /** Reason a profile is or is not eligible for provider auth. */ type AuthProfileEligibilityReasonCode = AuthCredentialReasonCode | "profile_missing" | "provider_mismatch" | "mode_mismatch"; /** Eligibility decision for one auth profile candidate. */ type AuthProfileEligibility = { eligible: boolean; reasonCode: AuthProfileEligibilityReasonCode; }; /** Returns true when a stored credential can authenticate the requested provider. */ /** Resolves whether a profile can be used for a provider right now. */ declare function resolveAuthProfileEligibility(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId: string; now?: number; }): AuthProfileEligibility; /** Resolves ordered auth profile candidates for a provider. */ /** Resolve ordered usable auth profile ids for a provider. */ declare function resolveAuthProfileOrder(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; preferredProfile?: string; }): string[]; //#endregion //#region src/agents/auth-profiles/display.d.ts /** Builds the human-readable profile label used in status and auth listings. */ declare function resolveAuthProfileDisplayLabel(params: { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; }): string; //#endregion //#region src/agents/auth-profiles/doctor.d.ts type FormatAuthDoctorHintParams = { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId?: string; }; /** Formats provider-specific auth doctor guidance for a profile/store. */ declare function formatAuthDoctorHint(params: FormatAuthDoctorHintParams): Promise; //#endregion //#region src/agents/auth-profiles/external-cli-discovery.d.ts /** External CLI auth discovery mode used while loading auth profile stores. */ type ExternalCliAuthDiscovery = { mode: "none"; allowKeychainPrompt?: false; config?: OpenClawConfig; } | { mode: "existing"; allowKeychainPrompt?: boolean; config?: OpenClawConfig; } | { mode: "scoped"; allowKeychainPrompt?: boolean; config?: OpenClawConfig; providerIds?: Iterable; profileIds?: Iterable; }; //#endregion //#region src/agents/auth-profiles/oauth.d.ts type ResolveApiKeyForProfileResult = { apiKey: string; provider: string; email?: string; profileId: string; profileType: AuthProfileCredential["type"]; credential?: AuthProfileCredential; }; /** Detect provider errors caused by single-use OAuth refresh token races. */ type ResolveApiKeyForProfileParams = { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; agentDir?: string; forceRefresh?: boolean; }; /** Refresh one OAuth credential and merge provider-returned token fields. */ declare function refreshOAuthCredentialForRuntime(params: { credential: OAuthCredential; }): Promise; /** Resolve a selected auth profile into the provider API key string. */ declare function resolveApiKeyForProfile(params: ResolveApiKeyForProfileParams): Promise; //#endregion //#region src/agents/auth-profiles/profile-list.d.ts /** Deduplicates profile ids while preserving first-seen order. */ declare function dedupeProfileIds(profileIds: string[]): string[]; /** Lists auth profile ids whose credential provider matches the requested provider. */ declare function listProfilesForProvider(store: AuthProfileStore, provider: string): string[]; //#endregion //#region src/agents/auth-profiles/profiles.d.ts /** Sets or clears explicit auth profile order for a provider. */ declare function setAuthProfileOrder(params: { agentDir?: string; provider: string; order?: string[] | null; }): Promise; /** Upserts an auth profile immediately into the local store. */ declare function upsertAuthProfile(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): void; /** Upserts an auth profile under the auth store lock. */ declare function upsertAuthProfileWithLock(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): Promise; /** Removes all auth profiles and related state for a provider. */ declare function removeProviderAuthProfilesWithLock(params: { provider: string; agentDir?: string; }): Promise; /** Mark a profile as successfully used and update ordering/usage metadata. */ declare function markAuthProfileSuccess(params: { store: AuthProfileStore; provider: string; profileId: string; agentDir?: string; }): Promise; //#endregion //#region src/agents/auth-profiles/repair.d.ts /** Suggests a modern OAuth profile id for a legacy provider:default profile. */ declare function suggestOAuthProfileIdForLegacyDefault(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; legacyProfileId: string; }): string | null; /** Migrates config auth profile references away from a legacy OAuth default id. */ declare function repairOAuthProfileIdMismatch(params: { cfg: OpenClawConfig; store: AuthProfileStore; provider: string; legacyProfileId?: string; }): AuthProfileIdRepairResult; //#endregion //#region src/agents/auth-profiles/store.d.ts type LoadAuthProfileStoreOptions = { allowKeychainPrompt?: boolean; config?: OpenClawConfig; database?: OpenClawAgentDatabase; externalCli?: ExternalCliAuthDiscovery; readOnly?: boolean; syncExternalCli?: boolean; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; }; type SaveAuthProfileStoreOptions = { filterExternalAuthProfiles?: boolean; preserveOrderProfileIds?: Iterable; preserveStateProfileIds?: Iterable; pruneOrderProfileIds?: Iterable; syncExternalCli?: boolean; }; /** Apply an auth store update inside the SQLite write lock. */ declare function updateAuthProfileStoreWithLock(params: { agentDir?: string; saveOptions?: SaveAuthProfileStoreOptions; updater: (store: AuthProfileStore) => boolean; }): Promise; /** Load the main auth profile store with runtime external profiles overlaid. */ declare function loadAuthProfileStore(): AuthProfileStore; /** Loads the effective runtime store for an agent, including inherited main profiles. */ declare function loadAuthProfileStoreForRuntime(agentDir?: string, options?: LoadAuthProfileStoreOptions): AuthProfileStore; /** Load auth profiles for secret resolution without keychain prompts or writes. */ declare function loadAuthProfileStoreForSecretsRuntime(agentDir?: string, options?: Pick): AuthProfileStore; /** Load auth profiles with runtime external profiles removed from the result. */ declare function loadAuthProfileStoreWithoutExternalProfiles(agentDir?: string, loadOptions?: Pick): AuthProfileStore; /** Ensure an auth store is available, including runtime/external profile overlays. */ declare function ensureAuthProfileStore(agentDir?: string, options?: { allowKeychainPrompt?: boolean; config?: OpenClawConfig; externalCli?: ExternalCliAuthDiscovery; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; readOnly?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; /** Ensure an auth store is available without external profile overlays. */ declare function ensureAuthProfileStoreWithoutExternalProfiles(agentDir?: string, options?: { allowKeychainPrompt?: boolean; readOnly?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; /** Find a persisted credential in the scoped store, falling back to the main store. */ declare function findPersistedAuthProfileCredential(params: { agentDir?: string; profileId: string; }): AuthProfileStore["profiles"][string] | undefined; /** Resolve which agent dir owns a persisted profile, accounting for inherited OAuth. */ declare function resolvePersistedAuthProfileOwnerAgentDir(params: { agentDir?: string; profileId: string; }): string | undefined; /** Load the store shape used when applying local-only auth updates. */ declare function ensureAuthProfileStoreForLocalUpdate(agentDir?: string): AuthProfileStore; /** Replace runtime auth-profile snapshots, used by tests and prepared runtimes. */ declare function replaceRuntimeAuthProfileStoreSnapshots(entries: Array<{ agentDir?: string; store: AuthProfileStore; }>): void; /** Clear all runtime auth-profile snapshots. */ declare function clearRuntimeAuthProfileStoreSnapshots(): void; /** Save the auth profile store plus sidecar state, preserving runtime overlay metadata. */ declare function saveAuthProfileStore(store: AuthProfileStore, agentDir?: string, options?: SaveAuthProfileStoreOptions, database?: OpenClawAgentDatabase): void; //#endregion //#region src/agents/auth-profiles/usage-state.d.ts /** * Check if a profile is currently in cooldown (due to rate limits, overload, or other transient failures). */ declare function isProfileInCooldown(store: AuthProfileStore, profileId: string, now?: number, forModel?: string): boolean; /** * Return the soonest `unusableUntil` timestamp (ms epoch) among the given * profiles, or `null` when no profile has a recorded cooldown. Note: the * returned timestamp may be in the past if the cooldown has already expired. */ declare function getSoonestCooldownExpiry(store: AuthProfileStore, profileIds: string[], options?: { now?: number; forModel?: string; }): number | null; /** * Clear expired cooldowns from all profiles in the store. * * When `cooldownUntil` or `disabledUntil` has passed, the corresponding fields * are removed and error counters are reset so the profile gets a fresh start * (circuit-breaker half-open -> closed). Without this, a stale `errorCount` * causes the *next* transient failure to immediately escalate to a much longer * cooldown -- the root cause of profiles appearing "stuck" after rate limits. * * `cooldownUntil` and `disabledUntil` are handled independently: if a profile * has both and only one has expired, only that field is cleared. * * Mutates the in-memory store; disk persistence happens lazily on the next * store write (e.g. `markAuthProfileSuccess` / `markAuthProfileFailure`), which * matches the existing save pattern throughout the auth-profiles module. * * @returns `true` if any profile was modified. */ declare function clearExpiredCooldowns(store: AuthProfileStore, now?: number): boolean; //#endregion //#region src/agents/auth-profiles/usage.d.ts /** * Infer the most likely reason all candidate profiles are currently unavailable. * * We prefer explicit active `disabledReason` values (for example billing/auth) * over generic cooldown buckets, then fall back to failure-count signals. */ declare function resolveProfilesUnavailableReason(params: { store: AuthProfileStore; profileIds: string[]; now?: number; }): AuthProfileFailureReason | null; /** Returns the regular transient-failure cooldown duration for an error count. */ declare function calculateAuthProfileCooldownMs(errorCount: number): number; /** Resolves the display-facing unusable timestamp, honoring provider bypasses. */ declare function resolveProfileUnusableUntilForDisplay(store: AuthProfileStore, profileId: string): number | null; /** * Mark a profile as failed for a specific reason. Billing and permanent-auth * failures are treated as "disabled" (longer backoff) vs the regular cooldown * window. */ declare function markAuthProfileFailure(params: { store: AuthProfileStore; profileId: string; reason: AuthProfileFailureReason; cfg?: OpenClawConfig; agentDir?: string; runId?: string; modelId?: string; }): Promise; /** Marks a profile blocked until a provider-reported reset timestamp. */ declare function markAuthProfileBlockedUntil(params: { store: AuthProfileStore; profileId: string; blockedUntil: number; source: AuthProfileBlockedSource; agentDir?: string; runId?: string; modelId?: string; }): Promise; /** * Mark a profile as transiently failed. Applies stepped backoff cooldown. * Cooldown times: 30s, 1min, 5min (capped). * Uses store lock to avoid overwriting concurrent usage updates. */ declare function markAuthProfileCooldown(params: { store: AuthProfileStore; profileId: string; agentDir?: string; runId?: string; }): Promise; /** * Clear cooldown for a profile (e.g., manual reset). * Uses store lock to avoid overwriting concurrent usage updates. */ declare function clearAuthProfileCooldown(params: { store: AuthProfileStore; profileId: string; agentDir?: string; }): Promise; //#endregion //#region src/agents/model-auth-env.d.ts type EnvApiKeyResult = { apiKey: string; source: string; }; type EnvApiKeyLookupOptions = { config?: OpenClawConfig; workspaceDir?: string; aliasMap?: Readonly>; candidateMap?: Readonly>; authEvidenceMap?: Readonly>; skipSetupProviderFallback?: boolean; }; /** Resolve an API key or auth-evidence marker for a provider from environment state. */ declare function resolveEnvApiKey(provider: string, env?: NodeJS.ProcessEnv, options?: EnvApiKeyLookupOptions): EnvApiKeyResult | null; //#endregion //#region src/agents/model-auth-runtime-shared.d.ts /** Resolved credential material and provenance for one provider request. */ type ResolvedProviderAuth = { apiKey?: string; profileId?: string; source: string; mode: "api-key" | "oauth" | "token" | "aws-sdk"; }; /** Stable provider auth error code used by fallback/retry paths. */ type ProviderAuthErrorCode = "missing-api-key" | "missing-provider-auth"; /** Base provider auth error with a stable code for retry/fallback logic. */ declare class ProviderAuthError extends Error { readonly code: ProviderAuthErrorCode; readonly provider: string; constructor(code: ProviderAuthErrorCode, provider: string, message: string); } /** Auth error raised when a resolved provider auth source lacks usable material. */ declare class MissingProviderAuthError extends ProviderAuthError { readonly mode: ResolvedProviderAuth["mode"]; readonly source: string; constructor(provider: string, auth: ResolvedProviderAuth); } /** Narrow unknown errors to provider auth errors, optionally by code. */ declare function isProviderAuthError(err: unknown, code?: ProviderAuthErrorCode): err is ProviderAuthError; /** Narrow unknown errors to missing-provider-auth failures. */ declare function isMissingProviderAuthError(err: unknown): err is MissingProviderAuthError; /** Return the AWS credential env var that proves SDK auth is configured. */ declare function resolveAwsSdkEnvVarName(env?: NodeJS.ProcessEnv): string | undefined; /** Format the user-facing missing-auth error from auth provenance. */ declare function formatMissingAuthError(auth: ResolvedProviderAuth, provider: string): string; /** Require a normalized API key or throw a provider-auth error. */ declare function requireApiKey(auth: ResolvedProviderAuth, provider: string): string; //#endregion //#region src/agents/model-auth.d.ts type ProviderCredentialPrecedence = "profile-first" | "env-first"; /** Precomputed provider-auth lookup tables reused during one runtime turn. */ type RuntimeProviderAuthLookup = { envApiKey: Pick; setupProviderFallbackRefs?: readonly string[]; syntheticAuthProviderRefs?: readonly string[]; syntheticAuthProviderRefsComplete?: boolean; }; /** Builds stable env/synthetic auth lookup data for repeated provider checks. */ declare function createRuntimeProviderAuthLookup(params: { cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; includePluginSyntheticAuth?: boolean; }): RuntimeProviderAuthLookup; /** Reads a literal or env-secret marker for a custom provider entry. */ declare function getCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string): string | undefined; type ResolvedCustomProviderApiKey = { apiKey: string; source: string; }; /** Resolves custom provider API keys that are usable without mutating secret stores. */ declare function resolveUsableCustomProviderApiKey(params: { cfg: OpenClawConfig | undefined; provider: string; env?: NodeJS.ProcessEnv; secretSentinels?: boolean; }): ResolvedCustomProviderApiKey | null; /** True when a custom provider has a literal/env/local key available now. */ declare function hasUsableCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string, env?: NodeJS.ProcessEnv): boolean; /** True when explicit provider config should outrank profile/environment auth. */ declare function shouldPreferExplicitConfigApiKeyAuth(cfg: OpenClawConfig | undefined, provider: string): boolean; type ProviderEntryApiKeyProfileReference = { kind: "none"; } | { kind: "literal"; apiKey: string; source: string; } | { kind: "profile"; profileId: string; credential: AuthProfileCredential; mode: ResolvedProviderAuth["mode"]; } | { kind: "profile-incompatible"; profileId: string; credentialProvider: string; credentialType: AuthProfileCredential["type"]; reason: "credential-class" | "provider-binding"; } | { kind: "marker"; }; type ProviderEntryApiKeyBindingResolution = { kind: "none"; } | { kind: "literal"; apiKey: string; source: string; } | { kind: "profile-resolved"; auth: ResolvedProviderAuth; } | { kind: "profile-incompatible"; profileId: string; credentialProvider: string; credentialType: AuthProfileCredential["type"]; reason: "credential-class" | "provider-binding"; } | { kind: "profile-unresolved"; profileId: string; error?: unknown; }; /** True when a bearer auth profile can safely satisfy a provider-entry apiKey reference. */ declare function canUseProfileAsProviderEntryApiKey(params: { cfg?: OpenClawConfig; provider: string; credential: AuthProfileCredential; }): boolean; /** Classifies a provider entry apiKey as literal/profile/marker before resolving secrets. */ declare function resolveProviderEntryApiKeyProfileReference(params: { cfg?: OpenClawConfig; provider: string; store: AuthProfileStore; }): ProviderEntryApiKeyProfileReference; /** Resolves a provider-entry apiKey profile reference into runtime auth when possible. */ declare function resolveProviderEntryApiKeyBinding(params: { cfg?: OpenClawConfig; provider: string; store: AuthProfileStore; agentDir?: string; secretSentinels?: boolean; }): Promise; /** True when a custom local provider can use a synthetic no-auth placeholder. */ declare function hasSyntheticLocalProviderAuthConfig(params: { cfg: OpenClawConfig | undefined; provider: string; }): boolean; /** Fast auth-availability check for runtime provider/model selection. */ declare function hasRuntimeAvailableProviderAuth(params: { provider: string; cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; allowPluginSyntheticAuth?: boolean; runtimeLookup?: RuntimeProviderAuthLookup; modelApi?: string; }): boolean; /** Resolves the credential that should be used for one provider request. */ declare function resolveApiKeyForProvider(params: { provider: string; cfg?: OpenClawConfig; profileId?: string; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; /** When true, treat profileId as a user-locked selection that must not be * silently overridden by env/config credentials. */ lockedProfile?: boolean; forceRefresh?: boolean; credentialPrecedence?: ProviderCredentialPrecedence; modelApi?: string; /** Keep SecretRef-backed model credentials opaque until a sentinel-aware transport boundary. */ secretSentinels?: boolean; }): Promise; type ModelAuthMode = "api-key" | "oauth" | "token" | "mixed" | "aws-sdk" | "unknown"; /** Reports the strongest configured auth mode for provider-list UI and diagnostics. */ declare function resolveModelAuthMode(provider?: string, cfg?: OpenClawConfig, store?: AuthProfileStore, options?: { workspaceDir?: string; }): ModelAuthMode | undefined; /** Checks provider auth availability, including profile fallback order. */ declare function hasAvailableAuthForProvider(params: { provider: string; cfg?: OpenClawConfig; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; modelApi?: string; }): Promise; /** Resolves request credentials from the provider attached to a model descriptor. */ declare function getApiKeyForModel(params: { model: Model$1; cfg?: OpenClawConfig; profileId?: string; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; lockedProfile?: boolean; credentialPrecedence?: ProviderCredentialPrecedence; secretSentinels?: boolean; }): Promise; /** Clears auth for local OpenAI-compatible servers that explicitly use no auth. */ declare function applyLocalNoAuthHeaderOverride(model: T, auth: ResolvedProviderAuth | null | undefined): T; declare function applySecretRefHeaderSentinels(model: T, cfg: OpenClawConfig | undefined): T; /** * When the provider config sets `authHeader: true`, inject an explicit * `Authorization: Bearer ` header into the model so downstream SDKs * (e.g. `@google/genai`) send credentials via the standard HTTP Authorization * header instead of vendor-specific headers like `x-goog-api-key`. * * This is a no-op when `authHeader` is not `true`, when no API key is * available, or when the API key is a synthetic marker (e.g. local-server * placeholders) rather than a real credential. */ declare function applyAuthHeaderOverride(model: T, auth: ResolvedProviderAuth | null | undefined, cfg: OpenClawConfig | undefined): T; //#endregion //#region src/agents/simple-completion-runtime.d.ts type AllowedMissingApiKeyMode = ResolvedProviderAuth["mode"]; type SimpleCompletionModelOptions = { maxTokens?: number; temperature?: number; reasoning?: ThinkLevel | ThinkingLevel; signal?: AbortSignal; }; type PreparedSimpleCompletionModel = { model: Model$1; auth: ResolvedProviderAuth; } | { error: string; auth?: ResolvedProviderAuth; }; type AgentSimpleCompletionSelection = { provider: string; modelId: string; /** Provider used for auth/transport when runtime policy redirects the logical model ref. */ runtimeProvider?: string; profileId?: string; agentDir: string; }; type PreparedSimpleCompletionModelForAgent = { selection: AgentSimpleCompletionSelection; model: Model$1; auth: ResolvedProviderAuth; } | { error: string; selection?: AgentSimpleCompletionSelection; auth?: ResolvedProviderAuth; }; declare function resolveSimpleCompletionSelectionForAgent(params: { cfg: OpenClawConfig; agentId: string; agentDir?: string; modelRef?: string; useUtilityModel?: boolean; }): AgentSimpleCompletionSelection | null; declare function prepareSimpleCompletionModel(params: { cfg: OpenClawConfig | undefined; provider: string; modelId: string; agentDir?: string; profileId?: string; preferredProfile?: string; allowMissingApiKeyModes?: ReadonlyArray; allowBundledStaticCatalogFallback?: boolean; useAsyncModelResolution?: boolean; skipAgentDiscovery?: boolean; modelResolver?: typeof resolveModelAsync; }): Promise; declare function prepareSimpleCompletionModelForAgent(params: { cfg: OpenClawConfig; agentId: string; agentDir?: string; modelRef?: string; useUtilityModel?: boolean; preferredProfile?: string; allowMissingApiKeyModes?: ReadonlyArray; allowBundledStaticCatalogFallback?: boolean; useAsyncModelResolution?: boolean; skipAgentDiscovery?: boolean; modelResolver?: typeof resolveModelAsync; }): Promise; declare function completeWithPreparedSimpleCompletionModel(params: { model: Model$1; auth: ResolvedProviderAuth; context: Parameters[1]; cfg?: OpenClawConfig; options?: SimpleCompletionModelOptions; }): Promise; //#endregion //#region src/agents/exec-auto-reviewer.d.ts /** Config for the optional model-backed exec reviewer. */ type ExecReviewerConfig = { model?: AgentModelConfig; timeoutMs?: number; }; //#endregion //#region src/agents/bash-tools.exec-types.d.ts /** Runtime defaults passed into exec/process tool factories. */ type ExecToolDefaults = { hasCronTool?: boolean; host?: ExecTarget; mode?: ExecMode; security?: ExecSecurity; ask?: ExecAsk; trigger?: string; node?: string; pathPrepend?: string[]; safeBins?: string[]; strictInlineEval?: boolean; commandHighlighting?: boolean; safeBinTrustedDirs?: string[]; safeBinProfiles?: Record; reviewer?: ExecReviewerConfig; config?: OpenClawConfig; autoReviewer?: ExecAutoReviewer; agentId?: string; backgroundMs?: number; timeoutSec?: number; approvalWarningText?: string; approvalFollowupText?: string; approvalFollowup?: ExecApprovalFollowupFactory; approvalFollowupMode?: "agent" | "direct"; approvalRunningNoticeMs?: number; sandbox?: BashSandboxConfig; elevated?: ExecElevatedDefaults; allowBackground?: boolean; scopeKey?: string; sessionKey?: string; /** Ephemeral session UUID active when this exec tool was built. Regenerated * on `/new` and `/reset`, so it pins exec-approval followups to the original * session instance and lets stale followups drop after a session rebind. */ sessionId?: string; /** `session.store` template from the runtime config. Lets the direct/denied * exec approval followup path resolve the session key's current sessionId and * drop the followup when the key was rebound by `/new` or `/reset`. */ sessionStore?: string; /** `session.mainKey` from the runtime config; passed through into * runExecProcess so background-exit notifications can remap cron-run * session keys to the agent's main queue without an ambient config load. */ mainKey?: string; /** `session.scope` from the runtime config; passed alongside `mainKey` * so the cron-run remap can route global-scope agents to the "global" * queue instead of agent-main. */ sessionScope?: "per-sender" | "global"; /** Start-time routing policy for detached exec system events. */ eventRouting?: EventSessionRoutingPolicy; messageProvider?: string; currentChannelId?: string; currentThreadTs?: string; /** Channel-owned sender/chat metadata. Exec subprocesses receive only sender/chat IDs. */ channelContext?: PluginHookChannelContext; accountId?: string; approvalReviewerDeviceId?: string; notifyOnExit?: boolean; notifyOnExitEmptySuccess?: boolean; cwd?: string; }; /** Outcome passed to approval follow-up factories after approved async exec. */ type ExecApprovalFollowupOutcome = { status: "completed" | "failed"; exitCode: number | null; timedOut: boolean; aggregated: string; reason?: string; }; type ExecApprovalFollowupContext = { approvalId: string; sessionId: string; trigger?: string; outcome: ExecApprovalFollowupOutcome; }; /** Hook that can append domain-specific text to approval follow-up messages. */ type ExecApprovalFollowupFactory = (context: ExecApprovalFollowupContext) => string | undefined | Promise; /** Effective elevated-exec defaults derived from config/runtime policy. */ type ExecElevatedDefaults = { enabled: boolean; allowed: boolean; defaultLevel: "on" | "off" | "ask" | "full"; fullAccessAvailable?: boolean; fullAccessBlockedReason?: EmbeddedFullAccessBlockedReason; }; //#endregion //#region src/agents/bootstrap-mode.d.ts type BootstrapContextRunKind = "default" | "heartbeat" | "cron" | "commitment-only"; //#endregion //#region src/agents/command/shared-types.d.ts /** * Shared command types that are imported by both public and runtime modules. */ /** Best-effort provider stream parameter overrides for an agent command. */ type AgentStreamParams = { /** Provider stream params override (best-effort). */temperature?: number; topP?: number; maxTokens?: number; /** Stop sequences forwarded to the provider (best-effort). */ stop?: string[]; /** Provider fast-mode override (best-effort). */ fastMode?: boolean; responseFormat?: Record; frequencyPenalty?: number; presencePenalty?: number; seed?: number; }; /** Simplified tool definition for client-provided OpenResponses hosted tools. */ type ClientToolDefinition = { type: "function"; function: { name: string; description?: string; parameters?: Record; /** Strict argument enforcement (Responses API). Propagated from the request. */ strict?: boolean; }; }; //#endregion //#region src/agents/embedded-agent-payloads.d.ts /** * Channel-facing reply payload emitted by embedded agents. Keep this type * small: channel adapters decide how to render text, media, and reply targets. */ type BlockReplyPayload = { text?: string; mediaUrls?: string[]; audioAsVoice?: boolean; trustedLocalMedia?: boolean; sensitiveMedia?: boolean; isReasoning?: boolean; /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */ isCommentary?: boolean; replyToId?: string; replyToTag?: boolean; replyToCurrent?: boolean; }; //#endregion //#region src/agents/embedded-agent-block-chunker.d.ts /** * Splits streamed embedded-agent replies into Markdown-safe message chunks. */ type BlockReplyChunking = { minChars: number; maxChars: number; breakPreference?: "paragraph" | "newline" | "sentence"; /** When true, prefer \n\n paragraph boundaries once minChars has been satisfied. */ flushOnParagraph?: boolean; }; declare class EmbeddedBlockChunker { #private; constructor(chunking: BlockReplyChunking); /** Add streamed text to the pending chunk buffer. */ append(text: string): void; /** Clear any buffered reply text without emitting it. */ reset(): void; /** Return the currently buffered text for tests and flush logic. */ get bufferedText(): string; /** Return true when there is pending text to drain. */ hasBuffered(): boolean; /** Emit safe chunks according to size and Markdown fence constraints. */ drain(params: { force: boolean; emit: (chunk: string) => void; }): void; } //#endregion //#region src/agents/embedded-agent-subscribe.shared-types.d.ts /** Rendering mode for completed tool results in subscribed replies. */ type ToolResultFormat = "markdown" | "plain"; /** Detail level for in-flight tool progress messages. */ type ToolProgressDetailMode = "explain" | "raw"; //#endregion //#region src/shared/fast-mode.d.ts type FastModeSource = "session" | "agent" | "config" | "default"; type FastModeAutoProgressState = { offAnnounced: boolean; resetAnnounced: boolean; }; declare function resolveFastModeForElapsed(params: { mode?: FastMode; startedAtMs: number; fastAutoOnSeconds?: number; nowMs?: number; }): { mode: FastMode | undefined; enabled: boolean; elapsedSeconds: number; fastAutoOnSeconds: number; }; declare function formatFastModeAutoProgressText(params: { enabled: boolean; elapsedSeconds: number; fastAutoOnSeconds?: number; }): string; declare function formatFastModeStatusValue(params: { mode: FastMode | undefined; fastAutoOnSeconds?: number; }): string; declare function formatFastModeCommandOptions(params?: { fastAutoOnSeconds?: number; }): string; declare function formatFastModeSourceSuffix(source: FastModeSource | undefined): string; declare function formatFastModeCurrentStatus(params: { mode: FastMode | undefined; source?: FastModeSource; fastAutoOnSeconds?: number; label?: string; }): string; //#endregion //#region src/agents/fast-mode.d.ts type FastModeState = { mode: FastMode; enabled: boolean; source: FastModeSource; fastAutoOnSeconds: number; }; /** Resolve the effective fast-mode setting and its source. */ declare function resolveFastModeState(params: { cfg: OpenClawConfig | undefined; provider: string; model: string; agentId?: string; sessionEntry?: Pick | undefined; }): FastModeState; //#endregion //#region src/agents/generated-attachments.d.ts type AgentGeneratedAttachment = { type?: "image" | "audio" | "video" | "file"; path?: string; url?: string; mediaUrl?: string; filePath?: string; mimeType?: string; name?: string; }; //#endregion //#region src/agents/internal-event-contract.d.ts declare const AGENT_INTERNAL_EVENT_TYPE_TASK_COMPLETION: "task_completion"; declare const AGENT_INTERNAL_EVENT_SOURCES: readonly ["subagent", "cron", "image_generation", "video_generation", "music_generation"]; declare const AGENT_INTERNAL_EVENT_STATUSES: readonly ["ok", "timeout", "error", "unknown"]; type AgentInternalEventSource = (typeof AGENT_INTERNAL_EVENT_SOURCES)[number]; type AgentInternalEventStatus = (typeof AGENT_INTERNAL_EVENT_STATUSES)[number]; //#endregion //#region src/agents/internal-events.d.ts type AgentTaskCompletionInternalEvent = { type: typeof AGENT_INTERNAL_EVENT_TYPE_TASK_COMPLETION; source: AgentInternalEventSource; childSessionKey: string; childSessionId?: string; announceType: string; taskLabel: string; status: AgentInternalEventStatus; statusLabel: string; result: string; attachments?: AgentGeneratedAttachment[]; mediaUrls?: string[]; statsLine?: string; replyInstruction: string; }; /** Internal event variants that can be rendered into agent prompt context. */ type AgentInternalEvent = AgentTaskCompletionInternalEvent; //#endregion //#region src/agents/run-session-target.d.ts /** Identifies a run transcript target without naming the current storage artifact. */ type AgentRunSessionTarget = { agentId?: string; sessionId?: string; sessionKey?: string; storePath?: string; threadId?: string | number; }; //#endregion //#region src/agents/system-prompt.types.d.ts type PromptMode = "full" | "minimal" | "none"; type SilentReplyPromptMode = "generic" | "none"; //#endregion //#region src/agents/embedded-agent-runner/run/auth-profile-failure-policy.types.d.ts /** * Scope used when classifying auth-profile failures for retry/fallback decisions. */ type AuthProfileFailurePolicy = "shared" | "local" | "local_transient"; //#endregion //#region src/agents/embedded-agent-runner/run/params.d.ts type EmbeddedRunTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; type ReasoningStreamPayload = Pick & { requiresReasoningProgressOptIn?: boolean; }; type CurrentInboundPromptContext = { text: string; resumableText?: string; promptJoiner?: "\n\n" | "\n" | " "; /** Generated goal blocks owned by inbound-context assembly, never user text. */ injectedGoalContexts?: string[]; }; type RunEmbeddedAgentParams = { sessionId: string; sessionKey?: string; /** Storage-neutral transcript/session target. Defaults to sessionId/sessionKey/agentId. */ sessionTarget?: AgentRunSessionTarget; /** Immutable gateway lifecycle ownership captured when this execution was admitted. */ lifecycleGeneration?: string; /** Provider prompt-cache affinity key; distinct from transcript/session identity. */ promptCacheKey?: string; /** Session-like key for sandbox and tool-policy resolution. Defaults to sessionKey. */ sandboxSessionKey?: string; agentId?: string; messageChannel?: string; messageProvider?: string; chatType?: ChatType; agentAccountId?: string; /** What initiated this agent run: "user", "heartbeat", "cron", "memory", "overflow", or "manual". */ trigger?: EmbeddedRunTrigger; /** Stable cron job identifier populated for cron-triggered runs. */ jobId?: string; /** Relative workspace path that memory-triggered writes are allowed to append to. */ memoryFlushWritePath?: string; /** Delivery target for topic/thread routing. */ messageTo?: string; /** Thread/topic identifier for routing replies to the originating thread. */ messageThreadId?: string | number; /** Group id for channel-level tool policy resolution. */ groupId?: string | null; /** Group channel label (e.g. #general) for channel-level tool policy resolution. */ groupChannel?: string | null; /** Group space label (e.g. guild/team id) for channel-level tool policy resolution. */ groupSpace?: string | null; /** Trusted provider role ids for the requester in this group turn. */ memberRoleIds?: string[]; /** Parent session key for subagent policy inheritance. */ spawnedBy?: string | null; /** Whether workspaceDir points at the canonical agent workspace for bootstrap purposes. */ isCanonicalWorkspace?: boolean; senderId?: string | null; senderName?: string | null; senderUsername?: string | null; senderE164?: string | null; /** Trusted sender identity bit for command/channel-action auth. */ senderIsOwner?: boolean; /** Device-scoped operator session allowed to review approvals initiated by this run. */ approvalReviewerDeviceId?: string; /** Current channel ID for auto-threading (Slack). */ currentChannelId?: string; /** Transport-native chat/conversation ID for hook identity context. */ chatId?: string; /** Channel-specific identity metadata surfaced to plugin hooks. */ channelContext?: PluginHookChannelContext; /** Routable target for the current conversation when it differs from the native channel ID. */ currentMessagingTarget?: string; /** Current thread timestamp for auto-threading (Slack). */ currentThreadTs?: string; /** Current inbound message id for action fallbacks (e.g. Telegram react). */ currentMessageId?: string | number; /** True when the current inbound turn carried audio media. */ currentInboundAudio?: boolean; /** Reply-to mode for Slack auto-threading. */ replyToMode?: "off" | "first" | "all" | "batched"; /** Mutable ref to track if a reply was sent (for "first" mode). */ hasRepliedRef?: { value: boolean; }; /** Require explicit message tool targets (no implicit last-route sends). */ requireExplicitMessageTarget?: boolean; /** If true, omit the message tool from the tool list. */ disableMessageTool?: boolean; /** Internal one-shot model probe mode: no tools, no workspace/chat prompt policy. */ modelRun?: boolean; /** Explicit system prompt mode override for trusted callers. */ promptMode?: PromptMode; /** Keep the message tool available even when a narrow profile would omit it. */ forceMessageTool?: boolean; /** Include the heartbeat response tool for structured heartbeat outcomes. */ enableHeartbeatTool?: boolean; /** Keep the heartbeat response tool available even when a narrow profile would omit it. */ forceHeartbeatTool?: boolean; /** Allow runtime plugins for this run to late-bind the gateway subagent. */ allowGatewaySubagentBinding?: boolean; /** @deprecated Use sessionTarget plus sessionId/sessionKey/agentId for runtime identity. */ sessionFile?: string; workspaceDir: string; /** Task working directory for tool/runtime execution. Defaults to workspaceDir. */ cwd?: string; agentDir?: string; /** * Run config consumed by core paths (model selection, tools, plugin * activation). Plugin harnesses resolve `plugins.entries..config` from * the live global config, NOT from this object — per-run plugin-config * overrides are unsupported; use an explicit run param instead. */ config?: OpenClawConfig; skillsSnapshot?: SkillSnapshot; prompt: string; /** User-visible prompt body to submit and persist; runtime context travels separately. */ transcriptPrompt?: string; currentInboundEventKind?: InboundEventKind; currentInboundContext?: CurrentInboundPromptContext; images?: ImageContent$2[]; imageOrder?: PromptImageOrderEntry[]; /** Optional client-provided tools (OpenResponses hosted tools). */ clientTools?: ClientToolDefinition[]; /** Disable built-in tools for this run (LLM-only mode). */ disableTools?: boolean; provider?: string; model?: string; /** Effective model fallback chain for this session attempt. Undefined uses config defaults. */ modelFallbacksOverride?: string[]; /** Session-pinned embedded harness id. Prevents runtime hot-switching. */ agentHarnessId?: string; /** Explicit runtime override selected for this turn. Unlike agentHarnessId, this may force OpenClaw. */ agentHarnessRuntimeOverride?: string; authProfileId?: string; authProfileIdSource?: "auto" | "user"; thinkLevel?: ThinkLevel; fastMode?: FastMode; /** Stable outer-run start time for auto fast-mode cutoff across retries/fallbacks. */ fastModeStartedAtMs?: number; /** Effective auto fast-mode cutoff for this run, in seconds. */ fastModeAutoOnSeconds?: number; /** Shared notification state for nested harnesses that can observe the same tool boundary. */ fastModeAutoProgressState?: FastModeAutoProgressState; /** True when the outer model fallback loop has reached its final candidate. */ isFinalFallbackAttempt?: boolean; verboseLevel?: VerboseLevel; reasoningLevel?: ReasoningLevel; toolResultFormat?: ToolResultFormat; toolProgressDetail?: ToolProgressDetailMode; /** If true, suppress tool error warning payloads for this run (including mutating tools). */ suppressToolErrorWarnings?: boolean | (() => boolean | undefined); /** Bootstrap context mode for workspace file injection. */ bootstrapContextMode?: "full" | "lightweight"; /** Run kind hint for context mode behavior. */ bootstrapContextRunKind?: BootstrapContextRunKind; /** Optional tool allow-list; when set, only these tools are sent to the model. */ toolsAllow?: string[]; /** Ring-zero Crestodian tool; set only by the Crestodian agent runner. */ crestodianTool?: CrestodianToolOptions; /** Seen bootstrap truncation warning signatures for this session (once mode dedupe). */ bootstrapPromptWarningSignaturesSeen?: string[]; /** Last shown bootstrap truncation warning signature for this session. */ bootstrapPromptWarningSignature?: string; execOverrides?: Pick; bashElevated?: ExecElevatedDefaults; timeoutMs: number; /** * Explicit per-run timeout override, in milliseconds, when the caller knows * the run was launched with a deliberate per-run value (e.g. a cron payload's * `timeoutSeconds`) rather than inheriting `agents.defaults.timeoutSeconds`. * When set, the LLM idle watchdog honors this value directly instead of * inferring "explicitness" from `timeoutMs !== agents.defaults.timeoutSeconds`, * which fails when the explicit value happens to numerically equal the agent * default. */ runTimeoutOverrideMs?: number; runId: string; abortSignal?: AbortSignal; onExecutionStarted?: (info?: { lifecycleGeneration?: string; }) => void; onExecutionPhase?: (info: { phase: EmbeddedAgentExecutionPhase; provider?: string; model?: string; backend?: string; source?: string; tool?: string; toolCallId?: string; itemId?: string; firstModelCallStarted?: boolean; }) => void; onLaneWait?: (info: { waitMs: number; queuedAhead: number; waiting?: boolean; }) => void; onRunProgress?: (info: { reason: string; provider?: string; model?: string; backend?: string; }) => void; onSessionIdChanged?: (sessionId: string) => void; replyOperation?: ReplyOperation; shouldEmitToolResult?: () => boolean; shouldEmitToolOutput?: () => boolean; onPartialReply?: (payload: PartialReplyPayload) => void | Promise; onAssistantMessageStart?: () => void | Promise; onBlockReply?: (payload: BlockReplyPayload, context?: BlockReplyContext) => void | Promise; onBlockReplyFlush?: (context: BlockReplyFlushContext) => void | Promise; blockReplyBreak?: "text_end" | "message_end"; blockReplyChunking?: BlockReplyChunking; onReasoningStream?: (payload: ReasoningStreamPayload) => void | Promise; streamReasoningInNonStreamModes?: boolean; onReasoningEnd?: () => void | Promise; onToolResult?: (payload: ReplyPayload) => void | Promise; /** Synchronous private observer for the sanitized per-tool result. */ onAgentToolResult?: (event: { toolName: string; result: unknown; isError: boolean; }) => void; onAgentEvent?: (evt: { stream: string; data: Record; sessionKey?: string; }) => void | Promise; onToolStreamBoundary?: () => void | Promise; /** * Emit lifecycle "finishing" when the attempt ends; the caller owns the * final lifecycle "end" or "error" after fallback and post-turn work settle. */ deferTerminalLifecycle?: boolean; /** @deprecated Use deferTerminalLifecycle. */ deferTerminalLifecycleEnd?: boolean; lane?: string; enqueue?: CommandQueueEnqueueFn; extraSystemPrompt?: string; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; silentReplyPromptMode?: SilentReplyPromptMode; internalEvents?: AgentInternalEvent[]; inputProvenance?: InputProvenance; streamParams?: AgentStreamParams; ownerNumbers?: string[]; enforceFinalTag?: boolean; silentExpected?: boolean; /** Skip per-chunk live visible-text parsing when no live stream consumer exists (e.g. subagents). */ suppressLiveStreamOutput?: boolean; /** * Treat a clean empty assistant stop as an intentional silent reply. * Only set when the caller's prompt policy already allows an exact NO_REPLY * final answer for silence. */ allowEmptyAssistantReplyAsSilent?: boolean; authProfileFailurePolicy?: AuthProfileFailurePolicy; /** * Allow a single run attempt even when all auth profiles are in cooldown, * but only for inferred transient cooldowns like `rate_limit` or `overloaded`. * * This is used by model fallback when trying sibling models on providers * where transient service pressure is often model-scoped. */ allowTransientCooldownProbe?: boolean; suppressNextUserMessagePersistence?: boolean; suppressTranscriptOnlyAssistantPersistence?: boolean; suppressAssistantErrorPersistence?: boolean; userTurnTranscriptRecorder?: UserTurnTranscriptRecorder; onUserMessagePersisted?: (message: Extract) => void; onAssistantErrorMessagePersisted?: (message: Extract) => void; /** * Dispose bundled MCP runtimes when the overall run ends instead of preserving * the session-scoped cache. Intended for one-shot local CLI runs that must * exit promptly after emitting the final JSON result. */ cleanupBundleMcpOnRunEnd?: boolean; /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */ oneShotCliRun?: boolean; }; //#endregion //#region src/agents/timeout.d.ts declare function resolveAgentTimeoutMs(opts: { cfg?: OpenClawConfig; overrideMs?: number | null; overrideSeconds?: number | null; minMs?: number; }): number; //#endregion //#region src/config/sessions/runtime-types.d.ts /** Runtime hook for reading a session store entry timestamp. */ type ReadSessionUpdatedAt$1 = (params: { storePath: string; sessionKey: string; }) => number | undefined; type SessionMaintenanceWarningRuntime = { activeSessionKey: string; activeUpdatedAt?: number; totalEntries: number; pruneAfterMs: number; maxEntries: number; wouldPrune: boolean; wouldCap: boolean; }; type ResolvedSessionMaintenanceConfigRuntime = { mode: SessionMaintenanceMode; pruneAfterMs: number; maxEntries: number; modelRunPruneAfterMs: number; resetArchiveRetentionMs: number | null; maxDiskBytes: number | null; highWaterBytes: number | null; }; type SessionMaintenanceApplyReportRuntime = { mode: SessionMaintenanceMode; beforeCount: number; afterCount: number; modelRunPruned: number; pruned: number; capped: number; diskBudget: Record | null; }; type SaveSessionStoreOptions = { skipMaintenance?: boolean; activeSessionKey?: string; onWarn?: (warning: SessionMaintenanceWarningRuntime) => void | Promise; onMaintenanceApplied?: (report: SessionMaintenanceApplyReportRuntime) => void | Promise; maintenanceOverride?: Partial; }; type SaveSessionStore = (storePath: string, store: Record, opts?: SaveSessionStoreOptions) => Promise; type RecordSessionMetaFromInbound$1 = (params: { storePath: string; sessionKey: string; ctx: MsgContext; groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; }) => Promise; type UpdateLastRoute$1 = (params: { storePath: string; sessionKey: string; channel?: SessionEntry["lastChannel"]; to?: string; accountId?: string; threadId?: string | number; route?: ChannelRouteRef; deliveryContext?: DeliveryContext; ctx?: MsgContext; groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; }) => Promise; //#endregion //#region src/plugins/runtime/native-deps.d.ts /** Inputs used to format native dependency install/rebuild guidance. */ type NativeDependencyHintParams = { packageName: string; manager?: "pnpm" | "npm" | "yarn"; rebuildCommand?: string; approveBuildsCommand?: string; downloadCommand?: string; }; /** Formats concise guidance for installing and rebuilding a native dependency. */ declare function formatNativeDependencyHint(params: NativeDependencyHintParams): string; //#endregion //#region src/image-generation/runtime-types.d.ts type GenerateImageParams = { cfg: OpenClawConfig; prompt: string; agentDir?: string; authStore?: AuthProfileStore; modelOverride?: string; count?: number; size?: string; aspectRatio?: string; resolution?: ImageGenerationResolution; /** Resolution inferred from reference images; omitted for incompatible fallback models. */ inferredResolution?: ImageGenerationResolution; quality?: ImageGenerationQuality; outputFormat?: ImageGenerationOutputFormat; background?: ImageGenerationBackground; inputImages?: ImageGenerationSourceImage[]; autoProviderFallback?: boolean; /** Optional per-request provider timeout in milliseconds. */ timeoutMs?: number; providerOptions?: ImageGenerationProviderOptions; /** SSRF policy to propagate into image-generation provider HTTP calls. */ ssrfPolicy?: SsrFPolicy$1; }; type GenerateImageRuntimeResult = { images: GeneratedImageAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; appliedResolution?: ImageGenerationResolution; normalization?: ImageGenerationNormalization; metadata?: Record; ignoredOverrides: ImageGenerationIgnoredOverride[]; }; type ListRuntimeImageGenerationProvidersParams = { config?: OpenClawConfig; }; type RuntimeImageGenerationProvider = ImageGenerationProvider; //#endregion //#region src/video-generation/runtime-types.d.ts type GenerateVideoParams = { cfg: OpenClawConfig; prompt: string; agentDir?: string; authStore?: AuthProfileStore; modelOverride?: string; size?: string; aspectRatio?: string; resolution?: VideoGenerationResolution; durationSeconds?: number; audio?: boolean; watermark?: boolean; inputImages?: VideoGenerationSourceAsset[]; inputVideos?: VideoGenerationSourceAsset[]; inputAudios?: VideoGenerationSourceAsset[]; autoProviderFallback?: boolean; /** Arbitrary provider-specific options forwarded as-is to provider.generateVideo. */ providerOptions?: Record; /** Optional per-request provider timeout in milliseconds. */ timeoutMs?: number; }; type GenerateVideoRuntimeResult = { videos: GeneratedVideoAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; normalization?: VideoGenerationNormalization; metadata?: Record; ignoredOverrides: VideoGenerationIgnoredOverride[]; }; type ListRuntimeVideoGenerationProvidersParams = { config?: OpenClawConfig; }; type RuntimeVideoGenerationProvider = VideoGenerationProvider; //#endregion //#region src/music-generation/runtime-types.d.ts /** * Runtime input/output contracts for music generation. * * These are separate from provider contracts because runtime results include * fallback attempts, normalized metadata, and selected provider/model identity. */ /** Parameters accepted by the core music generation runtime. */ type GenerateMusicParams = { cfg: OpenClawConfig; prompt: string; agentDir?: string; authStore?: AuthProfileStore; modelOverride?: string; lyrics?: string; instrumental?: boolean; durationSeconds?: number; format?: MusicGenerationOutputFormat; inputImages?: MusicGenerationSourceImage[]; autoProviderFallback?: boolean; /** Optional per-request provider timeout in milliseconds. */ timeoutMs?: number; }; /** Result returned after a successful runtime provider attempt. */ type GenerateMusicRuntimeResult = { tracks: GeneratedMusicAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; lyrics?: string[]; normalization?: MusicGenerationNormalization; metadata?: Record; ignoredOverrides: MusicGenerationIgnoredOverride[]; }; /** Parameters for listing music generation providers visible to runtime code. */ type ListRuntimeMusicGenerationProvidersParams = { config?: OpenClawConfig; }; /** Provider shape exposed by runtime listing APIs. */ type RuntimeMusicGenerationProvider = MusicGenerationProvider; //#endregion //#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/plugins/web-provider-types.d.ts type WebSearchProviderId = string; type WebFetchProviderId = string; type WebSearchProviderToolDefinition = { description: string; parameters: TSchema; execute: (args: Record, context?: WebSearchProviderToolExecutionContext) => Promise>; }; type WebFetchProviderToolDefinition = { description: string; parameters: TSchema; execute: (args: Record) => Promise>; }; type WebSearchProviderContext = { config?: OpenClawConfig; searchConfig?: Record; runtimeMetadata?: RuntimeWebSearchMetadata; agentDir?: string; }; type WebSearchProviderToolExecutionContext = { signal?: AbortSignal; }; type WebFetchProviderContext = { config?: OpenClawConfig; fetchConfig?: Record; runtimeMetadata?: RuntimeWebFetchMetadata; }; type WebSearchCredentialResolutionSource = "config" | "secretRef" | "env" | "missing"; type WebSearchProviderConfiguredCredentialFallback = { path: string; value: unknown; }; type WebFetchProviderConfiguredCredentialFallback = { path: string; value: unknown; }; type WebSearchRuntimeMetadataContext = { config?: OpenClawConfig; searchConfig?: Record; runtimeMetadata?: RuntimeWebSearchMetadata; resolvedCredential?: { value?: string; source: WebSearchCredentialResolutionSource; fallbackEnvVar?: string; }; }; type WebSearchProviderSetupContext = { config: OpenClawConfig; runtime: RuntimeEnv; prompter: WizardPrompter; quickstartDefaults?: boolean; secretInputMode?: SecretInputMode; }; type WebFetchCredentialResolutionSource = "config" | "secretRef" | "env" | "missing"; type WebFetchRuntimeMetadataContext = { config?: OpenClawConfig; fetchConfig?: Record; runtimeMetadata?: RuntimeWebFetchMetadata; resolvedCredential?: { value?: string; source: WebFetchCredentialResolutionSource; fallbackEnvVar?: string; }; }; type WebSearchProviderPlugin$1 = { id: WebSearchProviderId; label: string; hint: string; onboardingScopes?: readonly "text-inference"[]; requiresCredential?: boolean; credentialLabel?: string; envVars: string[]; /** Optional model-provider auth profile id that can satisfy this web provider without a tool-specific API key. */ authProviderId?: string; placeholder: string; signupUrl: string; docsUrl?: string; /** Optional note shown before credential collection for provider-specific prerequisites. */ credentialNote?: string; autoDetectOrder?: number; credentialPath: string; inactiveSecretPaths?: string[]; getCredentialValue: (searchConfig?: Record) => unknown; setCredentialValue: (searchConfigTarget: Record, value: unknown) => void; getConfiguredCredentialValue?: (config?: OpenClawConfig) => unknown; setConfiguredCredentialValue?: (configTarget: OpenClawConfig, value: unknown) => void; getConfiguredCredentialFallback?: (config?: OpenClawConfig) => WebSearchProviderConfiguredCredentialFallback | undefined; applySelectionConfig?: (config: OpenClawConfig) => OpenClawConfig; runSetup?: (ctx: WebSearchProviderSetupContext) => OpenClawConfig | Promise; resolveRuntimeMetadata?: (ctx: WebSearchRuntimeMetadataContext) => Partial | Promise>; createTool: (ctx: WebSearchProviderContext) => WebSearchProviderToolDefinition | null; }; type PluginWebSearchProviderEntry = WebSearchProviderPlugin$1 & { pluginId: string; }; type WebFetchProviderPlugin$1 = { id: WebFetchProviderId; label: string; hint: string; requiresCredential?: boolean; credentialLabel?: string; envVars: string[]; placeholder: string; signupUrl: string; docsUrl?: string; autoDetectOrder?: number; credentialPath: string; inactiveSecretPaths?: string[]; getCredentialValue: (fetchConfig?: Record) => unknown; setCredentialValue: (fetchConfigTarget: Record, value: unknown) => void; getConfiguredCredentialValue?: (config?: OpenClawConfig) => unknown; setConfiguredCredentialValue?: (configTarget: OpenClawConfig, value: unknown) => void; getConfiguredCredentialFallback?: (config?: OpenClawConfig) => WebFetchProviderConfiguredCredentialFallback | undefined; applySelectionConfig?: (config: OpenClawConfig) => OpenClawConfig; resolveRuntimeMetadata?: (ctx: WebFetchRuntimeMetadataContext) => Partial | Promise>; createTool: (ctx: WebFetchProviderContext) => WebFetchProviderToolDefinition | null; }; type PluginWebFetchProviderEntry = WebFetchProviderPlugin$1 & { pluginId: string; }; //#endregion //#region src/web-search/runtime-types.d.ts /** Provider/tool resolution inputs for web_search. */ type ResolveWebSearchDefinitionParams = { config?: OpenClawConfig; agentDir?: string; sandboxed?: boolean; runtimeWebSearch?: RuntimeWebSearchMetadata; providerId?: string; preferRuntimeProviders?: boolean; preferInputConfig?: boolean; }; /** Inputs for executing a web_search request through the selected provider. */ type RunWebSearchParams = ResolveWebSearchDefinitionParams & { args: Record; signal?: AbortSignal; }; /** Normalized execution result that records which provider answered. */ type RunWebSearchResult = { provider: string; result: Record; }; /** List-provider query parameters. */ type ListWebSearchProvidersParams = { config?: OpenClawConfig; }; type RuntimeWebSearchProviderEntry = PluginWebSearchProviderEntry; //#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; /** Internal, non-enumerable gateway lifecycle generation that owns this run. */ lifecycleGeneration?: string; 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/channels/message/ingress-queue.d.ts /** Pending or retryable inbound channel event stored in the durable ingress queue. */ type ChannelIngressQueueRecord = { id: string; channelId: string; accountId: string; queueName: string; payload: TPayload; metadata?: TMetadata; receivedAt: number; updatedAt: number; laneKey?: string; attempts: number; lastAttemptAt?: number; lastError?: string; }; /** Pending ingress event currently claimed by a worker. */ type ChannelIngressQueueClaim = ChannelIngressQueueRecord & { claim: { token: string; ownerId: string; claimedAt: number; }; }; /** Minimal claim reference used to guard completion/release/failure with a claim token. */ type ChannelIngressQueueClaimRef = { id: string; claim: { token: string; }; }; /** Completed ingress event tombstone retained for duplicate detection. */ type ChannelIngressQueueCompletedRecord = { id: string; channelId: string; accountId: string; queueName: string; completedAt: number; metadata?: TCompletedMetadata; }; /** Failed ingress event tombstone retained for duplicate detection and diagnostics. */ type ChannelIngressQueueFailedRecord = { id: string; channelId: string; accountId: string; queueName: string; failedAt: number; reason: string; message?: string; }; /** Retention options for pending, completed, and failed ingress queue rows. */ type ChannelIngressQueuePruneOptions = { pendingTtlMs?: number; completedTtlMs?: number; failedTtlMs?: number; pendingMaxEntries?: number; completedMaxEntries?: number; failedMaxEntries?: number; protectIds?: Iterable; now?: number; }; /** Result of enqueueing a possibly duplicate ingress event id. */ type ChannelIngressQueueEnqueueResult = { kind: "accepted"; duplicate: false; record: ChannelIngressQueueRecord; } | { kind: "pending"; duplicate: true; record: ChannelIngressQueueRecord; } | { kind: "claimed"; duplicate: true; record: ChannelIngressQueueClaim; } | { kind: "completed"; duplicate: true; record: ChannelIngressQueueCompletedRecord; } | { kind: "failed"; duplicate: true; record: ChannelIngressQueueFailedRecord; }; /** Durable FIFO-ish ingress queue with claims, duplicate detection, and retention pruning. */ type ChannelIngressQueue = { enqueue(id: string, payload: TPayload, options?: { metadata?: TMetadata; receivedAt?: number; laneKey?: string; }): Promise>; listPending(options?: { limit?: number | "all"; orderBy?: "received" | "id"; }): Promise>>; listClaims(): Promise>>; claimNext(options?: { ownerId?: string; blockedLaneKeys?: Iterable; staleMs?: number; orderBy?: "received" | "id"; scanLimit?: number; candidateIds?: Iterable; deriveLaneKey?: (record: ChannelIngressQueueRecord) => string | undefined; }): Promise | null>; claim(id: string, options?: { ownerId?: string; }): Promise | null>; refreshClaim?(claim: ChannelIngressQueueClaimRef, options?: { refreshedAt?: number; }): Promise; complete(idOrClaim: string | ChannelIngressQueueClaimRef, options?: { metadata?: TCompletedMetadata; completedAt?: number; }): Promise; release(idOrClaim: string | ChannelIngressQueueClaimRef, options?: { lastError?: string; releasedAt?: number; }): Promise; fail(idOrClaim: string | ChannelIngressQueueClaimRef, options: { reason: string; message?: string; failedAt?: number; }): Promise; delete(idOrClaim: string | ChannelIngressQueueRecord | ChannelIngressQueueClaimRef): Promise; recoverStaleClaims(options?: { staleMs?: number; now?: number; shouldRecover?: (claim: ChannelIngressQueueClaim) => boolean | Promise; }): Promise; prune(options?: ChannelIngressQueuePruneOptions): Promise; }; /** Construction options for a channel/account-scoped ingress queue. */ type CreateChannelIngressQueueOptions = { channelId: string; accountId?: string; stateDir?: string; now?: () => number; }; //#endregion //#region src/tasks/task-registry.types.d.ts /** Runtime family that owns a task run lifecycle. */ type TaskRuntime = "subagent" | "acp" | "cli" | "cron"; type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "timed_out" | "cancelled" | "lost"; type TaskDeliveryStatus = "pending" | "delivered" | "session_queued" | "failed" | "parent_missing" | "not_applicable"; type TaskNotifyPolicy = "done_only" | "state_changes" | "silent"; /** Semantic success detail for required-completion task outcomes. */ type TaskTerminalOutcome = "succeeded" | "blocked"; type TaskScopeKind = "session" | "system"; type TaskStatusCounts = Record; type TaskRuntimeCounts = Record; type TaskRegistrySummary = { total: number; active: number; terminal: number; failures: number; byStatus: TaskStatusCounts; byRuntime: TaskRuntimeCounts; }; type TaskDeliveryState = { taskId: string; requesterOrigin?: DeliveryContext; lastNotifiedEventAt?: number; }; type TaskRecord = { taskId: string; runtime: TaskRuntime; taskKind?: string; sourceId?: string; requesterSessionKey: string; ownerKey: string; scopeKind: TaskScopeKind; childSessionKey?: string; parentFlowId?: string; parentTaskId?: string; agentId?: string; /** Agent store for requester transcripts whose session key is unscoped, such as `global`. * Task authorization remains keyed by ownerKey. */ requesterAgentId?: string; runId?: string; label?: string; task: string; status: TaskStatus; deliveryStatus: TaskDeliveryStatus; notifyPolicy: TaskNotifyPolicy; createdAt: number; startedAt?: number; endedAt?: number; lastEventAt?: number; cleanupAfter?: number; error?: string; progressSummary?: string; terminalSummary?: string; terminalOutcome?: TaskTerminalOutcome; }; //#endregion //#region src/tasks/task-flow-registry.types.d.ts /** JSON value shape persisted with task-flow state and wait metadata. */ type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue; }; type TaskFlowSyncMode = "task_mirrored" | "managed"; /** Lifecycle status for multi-step task flows. */ type TaskFlowStatus = "queued" | "running" | "waiting" | "blocked" | "succeeded" | "failed" | "cancelled" | "lost"; type TaskFlowRecord = { flowId: string; syncMode: TaskFlowSyncMode; ownerKey: string; requesterOrigin?: DeliveryContext; controllerId?: string; revision: number; status: TaskFlowStatus; notifyPolicy: TaskNotifyPolicy; goal: string; currentStep?: string; blockedTaskId?: string; blockedSummary?: string; stateJson?: JsonValue; waitJson?: JsonValue; cancelRequestedAt?: number; createdAt: number; updatedAt: number; endedAt?: number; }; //#endregion //#region src/agents/tool-fs-policy.types.d.ts /** Filesystem policy for agent tools that can touch local paths. */ type ToolFsPolicy = { workspaceOnly: boolean; }; //#endregion //#region src/plugins/tool-types.d.ts type OpenClawPluginActiveModelContext = { provider?: string; modelId?: string; modelRef?: string; }; /** Trusted execution context passed to plugin-owned agent tool factories. */ type OpenClawPluginToolContext = { config?: OpenClawConfig; /** Active runtime-resolved config snapshot when one is available. */ runtimeConfig?: OpenClawConfig; /** Returns the latest runtime-resolved config snapshot for long-lived tool definitions. */ getRuntimeConfig?: () => OpenClawConfig | undefined; /** Effective filesystem policy for the active tool run. */ fsPolicy?: ToolFsPolicy; workspaceDir?: string; agentDir?: string; agentId?: string; sessionKey?: string; /** Ephemeral session UUID - regenerated on /new and /reset. Use for per-conversation isolation. */ sessionId?: string; /** * Runtime-supplied active model metadata for informational use, diagnostics, * and plugin-owned policy decisions. This is not a security boundary against * the local operator, installed plugin code, or a modified OpenClaw runtime. */ activeModel?: OpenClawPluginActiveModelContext; browser?: { sandboxBridgeUrl?: string; allowHostControl?: boolean; }; messageChannel?: string; agentAccountId?: string; /** Trusted provider auth availability from the active auth profile store. */ hasAuthForProvider?: (providerId: string) => boolean; /** Resolves an API key from the active auth profile store when available. */ resolveApiKeyForProvider?: (providerId: string) => Promise; /** Trusted ambient delivery route for the active agent/session. */ deliveryContext?: DeliveryContext; /** Trusted sender id from inbound context (runtime-provided, not tool args). */ requesterSenderId?: string; /** Trusted owner bit from inbound context (runtime-provided, not tool args). */ senderIsOwner?: boolean; sandboxed?: boolean; /** * True for explicit one-shot local CLI runs that must release plugin-owned * process resources before the command exits. */ oneShotCliRun?: boolean; }; type OpenClawPluginToolFactory$1 = (ctx: OpenClawPluginToolContext) => AnyAgentTool | AnyAgentTool[] | null | undefined; type OpenClawPluginToolOptions = { name?: string; names?: string[]; optional?: boolean; }; type OpenClawPluginHookOptions = { entry?: HookEntry; name?: string; description?: string; register?: boolean; }; //#endregion //#region src/plugins/runtime/runtime-taskflow.types.d.ts type ManagedTaskFlowRecord = TaskFlowRecord & { syncMode: "managed"; controllerId: string; }; type ManagedTaskFlowMutationErrorCode = "not_found" | "not_managed" | "revision_conflict" | "persist_failed"; type ManagedTaskFlowMutationResult = { applied: true; flow: ManagedTaskFlowRecord; } | { applied: false; code: ManagedTaskFlowMutationErrorCode; current?: TaskFlowRecord; }; type ManagedTaskFlowCreateParams = { controllerId: string; goal: string; status?: ManagedTaskFlowRecord["status"]; notifyPolicy?: TaskNotifyPolicy; currentStep?: string | null; stateJson?: JsonValue | null; waitJson?: JsonValue | null; cancelRequestedAt?: number | null; createdAt?: number; updatedAt?: number; endedAt?: number | null; }; type BoundTaskFlowTaskRunResult = { created: true; flow: ManagedTaskFlowRecord; task: TaskRecord; } | { created: false; reason: string; found: boolean; flow?: TaskFlowRecord; }; type BoundTaskFlowCancelResult = { found: boolean; cancelled: boolean; reason?: string; flow?: TaskFlowRecord; tasks?: TaskRecord[]; }; type BoundTaskFlowRuntime = { readonly sessionKey: string; readonly requesterOrigin?: TaskDeliveryState["requesterOrigin"]; createManaged: (params: ManagedTaskFlowCreateParams) => ManagedTaskFlowRecord; tryCreateManaged: (params: ManagedTaskFlowCreateParams) => ManagedTaskFlowRecord | null; get: (flowId: string) => TaskFlowRecord | undefined; list: () => TaskFlowRecord[]; findLatest: () => TaskFlowRecord | undefined; resolve: (token: string) => TaskFlowRecord | undefined; getTaskSummary: (flowId: string) => TaskRegistrySummary | undefined; setWaiting: (params: { flowId: string; expectedRevision: number; currentStep?: string | null; stateJson?: JsonValue | null; waitJson?: JsonValue | null; blockedTaskId?: string | null; blockedSummary?: string | null; updatedAt?: number; }) => ManagedTaskFlowMutationResult; resume: (params: { flowId: string; expectedRevision: number; status?: Extract; currentStep?: string | null; stateJson?: JsonValue | null; updatedAt?: number; }) => ManagedTaskFlowMutationResult; finish: (params: { flowId: string; expectedRevision: number; stateJson?: JsonValue | null; updatedAt?: number; endedAt?: number; }) => ManagedTaskFlowMutationResult; fail: (params: { flowId: string; expectedRevision: number; stateJson?: JsonValue | null; blockedTaskId?: string | null; blockedSummary?: string | null; updatedAt?: number; endedAt?: number; }) => ManagedTaskFlowMutationResult; requestCancel: (params: { flowId: string; expectedRevision: number; cancelRequestedAt?: number; }) => ManagedTaskFlowMutationResult; cancel: (params: { flowId: string; cfg: OpenClawConfig; }) => Promise; runTask: (params: { flowId: string; runtime: TaskRuntime; sourceId?: string; childSessionKey?: string; parentTaskId?: string; agentId?: string; runId?: string; label?: string; task: string; preferMetadata?: boolean; notifyPolicy?: TaskNotifyPolicy; deliveryStatus?: TaskDeliveryStatus; status?: "queued" | "running"; startedAt?: number; lastEventAt?: number; progressSummary?: string | null; }) => BoundTaskFlowTaskRunResult; }; type PluginRuntimeTaskFlow = { bindSession: (params: { sessionKey: string; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; }) => BoundTaskFlowRuntime; fromToolContext: (ctx: Pick) => BoundTaskFlowRuntime; }; //#endregion //#region src/plugins/runtime/model-auth-types.d.ts /** * Runtime-ready auth result exposed to native plugins and context engines. * * `source`, `mode`, and `profileId` describe how the original credential was * resolved. `apiKey` is the request-ready credential after any provider-owned * runtime exchange, so it may differ from the stored/raw credential. */ type ResolvedProviderRuntimeAuth = Omit & { apiKey?: string; baseUrl?: string; request?: ModelProviderRequestTransportOverrides$1; expiresAt?: number; }; //#endregion //#region src/tts/provider-types.d.ts /** Canonical speech provider identifier after provider registry normalization. */ type SpeechProviderId = string; /** Output context requested from a speech provider. */ type SpeechSynthesisTarget = "audio-file" | "voice-note" | "telephony"; /** Provider-owned normalized config map. */ type SpeechProviderConfig = Record; /** Provider-owned per-request directive/persona overrides. */ type SpeechProviderOverrides = Record; /** Policy controlling which [[tts:*]] directive fields can affect synthesis. */ type SpeechModelOverridePolicy = { enabled: boolean; allowText: boolean; allowProvider: boolean; allowVoice: boolean; allowModelId: boolean; allowVoiceSettings: boolean; allowNormalization: boolean; allowSeed: boolean; }; /** Parsed directive overrides grouped by provider. */ type TtsDirectiveOverrides = { ttsText?: string; provider?: SpeechProviderId; providerOverrides?: Record; }; /** Result of parsing TTS directives from message text. */ type TtsDirectiveParseResult = { cleanedText: string; ttsText?: string; hasDirective: boolean; overrides: TtsDirectiveOverrides; warnings: string[]; }; /** Context for checking whether a provider has enough config to synthesize. */ type SpeechProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: SpeechProviderConfig; timeoutMs: number; }; /** Request for buffered speech synthesis. */ type SpeechSynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; target: SpeechSynthesisTarget; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; /** Buffered speech synthesis result plus file/voice-note compatibility metadata. */ type SpeechSynthesisResult = { audioBuffer: Buffer; outputFormat: string; fileExtension: string; voiceCompatible: boolean; }; type SpeechSynthesisStreamRequest = SpeechSynthesisRequest; /** Streaming speech synthesis result; release frees provider transport resources. */ type SpeechSynthesisStreamResult = { audioStream: ReadableStream; outputFormat: string; fileExtension: string; voiceCompatible: boolean; release?: () => Promise; }; /** Telephony synthesis request for provider output that needs a fixed sample rate. */ type SpeechTelephonySynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; /** Telephony synthesis result with sample-rate metadata for call transports. */ type SpeechTelephonySynthesisResult = { audioBuffer: Buffer; outputFormat: string; sampleRate: number; }; /** Provider hook input for applying persona/config before synthesis. */ type SpeechProviderPrepareSynthesisContext = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; persona?: ResolvedTtsPersona; personaProviderConfig?: SpeechProviderConfig; target: SpeechSynthesisTarget; timeoutMs: number; }; /** Optional provider-prepared synthesis overrides. */ type SpeechProviderPreparedSynthesis = { text?: string; providerConfig?: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; }; /** Voice metadata returned by provider list-voices hooks. */ type SpeechVoiceOption = { id: string; name?: string; category?: string; description?: string; locale?: string; gender?: string; personalities?: string[]; }; /** Provider voice-listing request with optional direct auth/URL overrides. */ type SpeechListVoicesRequest = { cfg?: OpenClawConfig; providerConfig?: SpeechProviderConfig; apiKey?: string; baseUrl?: string; }; /** Provider hook input for resolving normalized config from raw OpenClaw config. */ type SpeechProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: Record; timeoutMs: number; }; /** One parsed directive key/value plus current provider override state. */ type SpeechDirectiveTokenParseContext = { key: string; value: string; policy: SpeechModelOverridePolicy; selectedProvider?: SpeechProviderId; providerConfig?: SpeechProviderConfig; currentOverrides?: SpeechProviderOverrides; }; /** Provider directive parser result. */ type SpeechDirectiveTokenParseResult = { handled: boolean; overrides?: SpeechProviderOverrides; warnings?: string[]; }; /** Provider hook input for resolving talk-command speech config. */ type SpeechProviderResolveTalkConfigContext = { cfg: OpenClawConfig; baseTtsConfig: Record; talkProviderConfig: TalkProviderConfig; timeoutMs: number; }; /** Provider hook input for per-call talk-command overrides. */ type SpeechProviderResolveTalkOverridesContext = { talkProviderConfig: TalkProviderConfig; params: Record; }; //#endregion //#region src/tts/tts-auto-mode.d.ts /** Accepted TTS auto modes from config, prefs, and session-level overrides. */ declare const TTS_AUTO_MODES: Set; /** Normalize an unknown value into a supported TTS auto mode. */ declare function normalizeTtsAutoMode(value: unknown): TtsAutoMode | undefined; //#endregion //#region src/tts/tts-config.d.ts /** Routing context used to layer global, agent, channel, and account TTS config. */ type TtsConfigResolutionContext = { agentId?: string; channelId?: string; accountId?: string; }; /** Resolve effective TTS config after applying global, agent, channel, and account layers. */ declare function resolveEffectiveTtsConfig(cfg: OpenClawConfig, contextOrAgentId?: string | TtsConfigResolutionContext): TtsConfig; //#endregion //#region src/tts/tts-types.d.ts /** Resolved directive override policy after config defaults are applied. */ type ResolvedTtsModelOverrides = SpeechModelOverridePolicy; /** Fully resolved TTS runtime config consumed by synthesis and status paths. */ type ResolvedTtsConfig = { auto: TtsAutoMode; mode: TtsMode; provider: TtsProvider; providerSource: "config" | "default"; persona?: string; personas: Record; summaryModel?: string; modelOverrides: ResolvedTtsModelOverrides; providerConfigs: Record; prefsPath?: string; maxTextLength: number; timeoutMs: number; timeoutMsSource?: "config" | "default"; rawConfig?: TtsConfig; sourceConfig?: OpenClawConfig; }; //#endregion //#region src/plugin-sdk/tts-runtime.types.d.ts /** Stable reason codes for one provider attempt in a TTS fallback chain. */ type TtsAttemptReasonCode = "success" | "no_provider_registered" | "not_configured" | "unsupported_for_streaming" | "unsupported_for_telephony" | "timeout" | "provider_error"; /** Per-provider attempt record used in TTS status, logs, and result metadata. */ type TtsProviderAttempt = { provider: string; outcome: "success" | "skipped" | "failed"; reasonCode: TtsAttemptReasonCode; persona?: string; personaBinding?: "applied" | "missing" | "none"; latencyMs?: number; error?: string; }; /** Delivery target requested for synthesized speech output. */ type TtsSpeechTarget = "audio-file" | "voice-note"; /** Standard text-to-speech request for file or stream synthesis. */ type TtsRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; channel?: string; overrides?: TtsDirectiveOverrides; disableFallback?: boolean; timeoutMs?: number; agentId?: string; accountId?: string; }; /** Telephony-specific synthesis request where output format is constrained by the caller. */ type TtsTelephonyRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; overrides?: TtsDirectiveOverrides; }; /** Inputs for listing voices from a speech provider with optional resolved config. */ type ListSpeechVoicesParams = { provider: string; cfg?: OpenClawConfig; config?: ResolvedTtsConfig; apiKey?: string; baseUrl?: string; }; /** File-backed text-to-speech result returned by high-level runtime helpers. */ type TtsResult = { success: boolean; audioPath?: string; error?: string; latencyMs?: number; provider?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; voiceCompatible?: boolean; audioAsVoice?: boolean; target?: TtsSpeechTarget; }; /** Stream-backed synthesis result with optional release hook for provider resources. */ type TtsStreamResult = { success: boolean; audioStream?: ReadableStream; error?: string; latencyMs?: number; provider?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; voiceCompatible?: boolean; fileExtension?: string; target?: TtsSpeechTarget; release?: () => Promise; }; /** Telephony synthesis result with provider voice/model and sample-rate metadata. */ type TtsTelephonyResult = { success: boolean; audioBuffer?: Buffer; error?: string; latencyMs?: number; provider?: string; providerModel?: string; providerVoice?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; sampleRate?: number; }; /** High-level function contract for file-backed text-to-speech synthesis. */ type TextToSpeech = (params: TtsRequestParams) => Promise; /** High-level function contract for streaming text-to-speech synthesis. */ type TextToSpeechStream = (params: TtsRequestParams) => Promise; /** High-level function contract for telephony-safe text-to-speech synthesis. */ type TextToSpeechTelephony = (params: TtsTelephonyRequestParams) => Promise; /** Function contract for provider voice discovery. */ type ListSpeechVoices = (params: ListSpeechVoicesParams) => Promise; //#endregion //#region src/plugins/runtime/task-domain-types.d.ts /** Aggregate task-run counts exposed to plugin task views. */ type TaskRunAggregateSummary = { total: number; active: number; terminal: number; failures: number; byStatus: TaskStatusCounts; byRuntime: TaskRuntimeCounts; }; /** Public task run summary exposed through plugin runtime task APIs. */ type TaskRunView = { id: string; runtime: TaskRuntime; sourceId?: string; sessionKey: string; ownerKey: string; scope: TaskScopeKind; childSessionKey?: string; flowId?: string; parentTaskId?: string; agentId?: string; runId?: string; label?: string; title: string; status: TaskStatus; deliveryStatus: TaskDeliveryStatus; notifyPolicy: TaskNotifyPolicy; createdAt: number; startedAt?: number; endedAt?: number; lastEventAt?: number; cleanupAfter?: number; error?: string; progressSummary?: string; terminalSummary?: string; terminalOutcome?: TaskTerminalOutcome; }; /** Detailed task run view; currently equal to the summary view. */ type TaskRunDetail = TaskRunView; /** Result returned when cancelling a task run. */ type TaskRunCancelResult = { found: boolean; cancelled: boolean; reason?: string; task?: TaskRunDetail; }; /** Public task flow summary exposed through plugin runtime task APIs. */ type TaskFlowView = { id: string; ownerKey: string; requesterOrigin?: DeliveryContext; status: TaskFlowStatus; notifyPolicy: TaskNotifyPolicy; goal: string; currentStep?: string; cancelRequestedAt?: number; createdAt: number; updatedAt: number; endedAt?: number; }; /** Detailed task flow view with state, wait, blocked, and task summary data. */ type TaskFlowDetail = TaskFlowView & { state?: JsonValue; wait?: JsonValue; blocked?: { taskId?: string; summary?: string; }; tasks: TaskRunView[]; taskSummary: TaskRunAggregateSummary; }; //#endregion //#region src/tasks/detached-task-runtime-contract.d.ts type DetachedTaskCreateParams = { runtime: TaskRuntime; taskKind?: string; sourceId?: string; requesterSessionKey?: string; ownerKey?: string; scopeKind?: TaskScopeKind; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; parentFlowId?: string; childSessionKey?: string; parentTaskId?: string; agentId?: string; requesterAgentId?: string; runId?: string; label?: string; task: string; preferMetadata?: boolean; notifyPolicy?: TaskNotifyPolicy; deliveryStatus?: TaskDeliveryStatus; }; type DetachedRunningTaskCreateParams = DetachedTaskCreateParams & { startedAt?: number; lastEventAt?: number; progressSummary?: string | null; }; type DetachedTaskStartParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; startedAt?: number; lastEventAt?: number; progressSummary?: string | null; eventSummary?: string | null; }; type DetachedTaskProgressParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; lastEventAt?: number; progressSummary?: string | null; eventSummary?: string | null; }; type DetachedTaskCompleteParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; endedAt: number; lastEventAt?: number; progressSummary?: string | null; terminalSummary?: string | null; terminalOutcome?: TaskTerminalOutcome | null; suppressDelivery?: boolean; }; type DetachedTaskFailParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; status?: Extract; endedAt: number; lastEventAt?: number; error?: string; progressSummary?: string | null; terminalSummary?: string | null; suppressDelivery?: boolean; }; type DetachedTaskFinalizeParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; status: Extract; endedAt: number; lastEventAt?: number; error?: string; progressSummary?: string | null; terminalSummary?: string | null; terminalOutcome?: TaskTerminalOutcome | null; suppressDelivery?: boolean; }; type DetachedTaskDeliveryStatusParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; deliveryStatus: TaskDeliveryStatus; error?: string; }; type DetachedTaskCancelParams = { cfg: OpenClawConfig; taskId: string; reason?: string; }; type DetachedTaskCancelResult = { found: boolean; cancelled: boolean; reason?: string; task?: TaskRecord; }; type DetachedTaskRecoveryAttemptParams = { taskId: string; runtime: TaskRuntime; task: TaskRecord; now: number; }; type DetachedTaskRecoveryAttemptResult = { recovered: boolean; }; type DetachedTaskFindParams = { runId: string; runtime: TaskRuntime; sessionKey: string; createdAtOrAfter: number; createdBefore?: number; allowSessionFallback?: boolean; }; type DetachedTaskLifecycleRuntime = { createQueuedTaskRun: (params: DetachedTaskCreateParams) => TaskRecord | null; createRunningTaskRun: (params: DetachedRunningTaskCreateParams) => TaskRecord | null; startTaskRunByRunId: (params: DetachedTaskStartParams) => TaskRecord[]; recordTaskRunProgressByRunId: (params: DetachedTaskProgressParams) => TaskRecord[]; finalizeTaskRunByRunId?: (params: DetachedTaskFinalizeParams) => TaskRecord[]; completeTaskRunByRunId: (params: DetachedTaskCompleteParams) => TaskRecord[]; failTaskRunByRunId: (params: DetachedTaskFailParams) => TaskRecord[]; setDetachedTaskDeliveryStatusByRunId: (params: DetachedTaskDeliveryStatusParams) => TaskRecord[]; /** * Resolve the task owned by one run generation. Custom runtimes should * implement this when their records are not mirrored into core task state. */ findTaskRun?: (params: DetachedTaskFindParams) => TaskRecord | undefined; /** * Return `found: false` when this runtime does not own the task so core can * fall back to the legacy detached-task cancel path. */ cancelDetachedTaskRunById: (params: DetachedTaskCancelParams) => Promise; /** * Give a registered detached runtime one last chance to recover a stale task * before core marks it lost during maintenance. */ tryRecoverTaskBeforeMarkLost?: (params: DetachedTaskRecoveryAttemptParams) => DetachedTaskRecoveryAttemptResult | Promise; }; //#endregion //#region src/plugins/runtime/runtime-tasks.types.d.ts type BoundTaskRunsRuntime = { readonly sessionKey: string; readonly requesterOrigin?: TaskDeliveryState["requesterOrigin"]; get: (taskId: string) => TaskRunDetail | undefined; list: () => TaskRunView[]; findLatest: () => TaskRunDetail | undefined; resolve: (token: string) => TaskRunDetail | undefined; cancel: (params: { taskId: string; cfg: OpenClawConfig; }) => Promise; }; type PluginRuntimeTaskRuns = { bindSession: (params: { sessionKey: string; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; }) => BoundTaskRunsRuntime; fromToolContext: (ctx: Pick) => BoundTaskRunsRuntime; }; type BoundTaskFlowsRuntime = { readonly sessionKey: string; readonly requesterOrigin?: TaskDeliveryState["requesterOrigin"]; get: (flowId: string) => TaskFlowDetail | undefined; list: () => TaskFlowView[]; findLatest: () => TaskFlowDetail | undefined; resolve: (token: string) => TaskFlowDetail | undefined; getTaskSummary: (flowId: string) => TaskRunAggregateSummary | undefined; }; type PluginRuntimeTaskFlows = { bindSession: (params: { sessionKey: string; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; }) => BoundTaskFlowsRuntime; fromToolContext: (ctx: Pick) => BoundTaskFlowsRuntime; }; type PluginRuntimeTasks = { runs: PluginRuntimeTaskRuns; flows: PluginRuntimeTaskFlows; managedFlows: PluginRuntimeTaskFlow; /** @deprecated Use runtime.tasks.flows for DTO-based TaskFlow access. */ flow: PluginRuntimeTaskFlow; }; //#endregion //#region src/plugins/runtime/types-core.d.ts type RuntimeRequestHeartbeatOptions = Parameters[0]; type RuntimeRequestHeartbeatNowOptions = Omit & Partial>; type RuntimeWriteConfigOptions = { envSnapshotForRestore?: Record; expectedConfigPath?: string; unsetPaths?: string[][]; }; type DeepReadonly = T extends ((...args: never[]) => unknown) ? T : T extends readonly (infer U)[] ? ReadonlyArray> : T extends object ? { readonly [K in keyof T]: DeepReadonly } : T; type RuntimeConfigAfterWrite = ConfigWriteAfterWrite; type RuntimeConfigReplaceResult = ConfigReplaceResult; type RuntimeConfigMutationBase = ConfigMutationBase; type RuntimeConfigMutationContext = { snapshot: ConfigFileSnapshot; previousHash: string | null; }; type RuntimeMutateConfigFileParams = { base?: RuntimeConfigMutationBase; baseHash?: string; afterWrite: RuntimeConfigAfterWrite; writeOptions?: RuntimeWriteConfigOptions; mutate: (draft: OpenClawConfig, context: RuntimeConfigMutationContext) => Promise | T | void; }; type RuntimeReplaceConfigFileParams = { nextConfig: OpenClawConfig; baseHash?: string; afterWrite: RuntimeConfigAfterWrite; writeOptions?: RuntimeWriteConfigOptions; }; type RuntimeSessionEntry = SessionEntry; type RuntimeSessionStoreReadParams = { agentId?: string; env?: NodeJS.ProcessEnv; hydrateSkillPromptRefs?: boolean; sessionKey: string; readConsistency?: "latest"; storePath?: string; }; type RuntimeSessionStoreListParams = Partial>; type RuntimeSessionStoreEntrySummary = { sessionKey: string; entry: RuntimeSessionEntry; }; type RuntimeSessionStoreEntryPatchParams = RuntimeSessionStoreReadParams & { fallbackEntry?: RuntimeSessionEntry; maintenanceConfig?: ResolvedSessionMaintenanceConfigInput; preserveActivity?: boolean; replaceEntry?: boolean; update: (entry: RuntimeSessionEntry, context: { existingEntry?: RuntimeSessionEntry; }) => Promise | null> | Partial | null; }; type RuntimeUpsertSessionEntryParams = RuntimeSessionStoreReadParams & { entry: RuntimeSessionEntry; }; type RuntimeSessionWorkAdmissionParams = { storePath: string; sessionKey: string; signal?: AbortSignal; }; type RuntimeSessionStoreEntryUpdateParams = { storePath: string; sessionKey: string; update: (entry: RuntimeSessionEntry) => Promise | null> | Partial | null; skipMaintenance?: boolean; takeCacheOwnership?: boolean; requireWriteSuccess?: boolean; }; type PluginRuntimeThinkingPolicyRequest = { provider?: string | null; model?: string | null; catalog?: ThinkingCatalogEntry[]; agentRuntime?: string | null; }; type PluginRuntimeThinkingPolicyLevel = { id: ThinkLevel; label: string; }; type PluginRuntimeThinkingPolicy = { levels: PluginRuntimeThinkingPolicyLevel[]; defaultLevel?: ThinkLevel | null; }; /** Structured logger surface injected into runtime-backed plugin helpers. */ type RuntimeLogger = { debug?: (message: string, meta?: Record) => void; info: (message: string, meta?: Record) => void; warn: (message: string, meta?: Record) => void; error: (message: string, meta?: Record) => void; }; type RunHeartbeatOnceOptions = { reason?: string; agentId?: string; sessionKey?: string; /** Override heartbeat config (e.g. `{ target: "last" }` to deliver to the last active channel). */ heartbeat?: { target?: string; }; }; type LlmCompleteMessage = { role: "system" | "user" | "assistant"; content: string; }; type LlmCompleteCaller = { kind: "plugin" | "context-engine" | "host" | "unknown"; id?: string; name?: string; }; type LlmCompleteUsage = { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; totalTokens?: number; costUsd?: number; }; type LlmCompleteParams = { messages: LlmCompleteMessage[]; /** Model ref (e.g. "anthropic/claude-sonnet-4-6"); defaults to the target agent's configured model. */ model?: string; maxTokens?: number; temperature?: number; systemPrompt?: string; signal?: AbortSignal; /** Human-readable reason for audit/debug output. */ purpose?: string; /** Agent whose model/credentials to use. Session-bound capabilities may disallow overrides. */ agentId?: string; }; type LlmCompleteResult = { text: string; provider: string; model: string; agentId: string; usage: LlmCompleteUsage; audit: { caller: LlmCompleteCaller; purpose?: string; sessionKey?: string; }; }; type RuntimeRunEmbeddedAgent = (params: RunEmbeddedAgentParams) => Promise; /** Core runtime helpers exposed to trusted native plugins. */ type PluginRuntimeCore = { version: string; config: { /** Current process runtime config snapshot. Prefer config passed into the active call path. */current: () => DeepReadonly; /** * Persist a focused config mutation. Callers must choose the post-write * behavior explicitly so the gateway can hot-reload, restart, or defer. */ mutateConfigFile: (params: RuntimeMutateConfigFileParams) => Promise; /** * Persist a full config replacement. Callers must choose the post-write * behavior explicitly so the gateway can hot-reload, restart, or defer. */ replaceConfigFile: (params: RuntimeReplaceConfigFileParams) => Promise; /** * @deprecated Use current(), or pass the already loaded config through the * call path. Runtime code must not reload config on demand. Bundled * plugins and repo code are blocked from using this by the * deprecated-internal-config-api architecture guard. */ loadConfig: () => OpenClawConfig; /** * @deprecated Use mutateConfigFile() or replaceConfigFile() with an * explicit afterWrite intent so restart behavior stays under host control. * Bundled plugins and repo code are blocked from using this by the * deprecated-internal-config-api architecture guard. */ writeConfigFile: (cfg: OpenClawConfig, options?: RuntimeWriteConfigOptions & { afterWrite?: RuntimeConfigAfterWrite; }) => Promise; }; agent: { defaults: { model: typeof DEFAULT_MODEL; provider: typeof DEFAULT_PROVIDER; }; resolveAgentDir: typeof resolveAgentDir; resolveAgentWorkspaceDir: typeof resolveAgentWorkspaceDir; resolveAgentIdentity: typeof resolveAgentIdentity; resolveThinkingDefault: (params: { cfg: OpenClawConfig; provider: string; model: string; catalog?: ModelCatalogEntry[]; }) => ThinkLevel; normalizeThinkingLevel: (raw?: string | null) => ThinkLevel | undefined; resolveThinkingPolicy: (params: PluginRuntimeThinkingPolicyRequest) => PluginRuntimeThinkingPolicy; runEmbeddedAgent: RuntimeRunEmbeddedAgent; /** @deprecated Use runEmbeddedAgent. */ runEmbeddedPiAgent: RuntimeRunEmbeddedAgent; resolveAgentTimeoutMs: typeof resolveAgentTimeoutMs; ensureAgentWorkspace: typeof ensureAgentWorkspace; session: { resolveStorePath: typeof resolveStorePath; getSessionEntry: (params: RuntimeSessionStoreReadParams) => RuntimeSessionEntry | undefined; listSessionEntries: (params?: RuntimeSessionStoreListParams) => RuntimeSessionStoreEntrySummary[]; patchSessionEntry: (params: RuntimeSessionStoreEntryPatchParams) => Promise; upsertSessionEntry: (params: RuntimeUpsertSessionEntryParams) => Promise; runWithWorkAdmission: (params: RuntimeSessionWorkAdmissionParams, run: (signal: AbortSignal) => Promise) => Promise; /** * @deprecated Use getSessionEntry/listSessionEntries for reads and * patchSessionEntry/upsertSessionEntry for writes. This whole-store * helper is kept only during the transition before SQLite migration. * Callers must migrate away from reading sessions.json directly. */ loadSessionStore: typeof loadSessionStore; /** * @deprecated Use patchSessionEntry/upsertSessionEntry for writes. This * whole-store helper is kept only during the transition before SQLite * migration. Callers must migrate away from writing sessions.json * directly. */ saveSessionStore: SaveSessionStore; /** * @deprecated Use patchSessionEntry/upsertSessionEntry for writes. This * whole-store helper is kept only during the transition before SQLite * migration. Callers must migrate away from updating sessions.json * directly. */ updateSessionStore: typeof updateSessionStore; updateSessionStoreEntry: (params: RuntimeSessionStoreEntryUpdateParams) => Promise; /** * @deprecated Use getSessionEntry to read session metadata by * agent/session identity. This file-path helper is kept only during the * transition before SQLite migration. Callers must migrate away from * resolving transcript file paths directly. */ resolveSessionFilePath: typeof resolveSessionFilePath; }; }; system: { enqueueSystemEvent: typeof enqueueSystemEvent; requestHeartbeat: typeof requestHeartbeat; /** * @deprecated Use `requestHeartbeat({ source, intent, reason })` so wake producers declare * scheduler intent explicitly. */ requestHeartbeatNow: (opts?: RuntimeRequestHeartbeatNowOptions) => void; /** * Run a single heartbeat cycle immediately (bypassing the coalesce timer). * Accepts an optional `heartbeat` config override so callers can force * delivery to the last active channel — the same pattern the cron service * uses to avoid the default `target: "none"` suppression. */ runHeartbeatOnce: (opts?: RunHeartbeatOnceOptions) => Promise; runCommandWithTimeout: typeof runCommandWithTimeout; formatNativeDependencyHint: typeof formatNativeDependencyHint; }; media: { loadWebMedia: typeof loadWebMedia; detectMime: typeof detectMime; mediaKindFromMime: typeof mediaKindFromMime; isVoiceCompatibleAudio: typeof isVoiceCompatibleAudio; getImageMetadata: typeof getImageMetadata; resizeToJpeg: typeof resizeToJpeg; }; tts: { textToSpeech: TextToSpeech; textToSpeechStream: TextToSpeechStream; textToSpeechTelephony: TextToSpeechTelephony; listVoices: ListSpeechVoices; }; mediaUnderstanding: { runFile: MediaUnderstandingRuntime["runMediaUnderstandingFile"]; describeImageFile: MediaUnderstandingRuntime["describeImageFile"]; describeImageFileWithModel: MediaUnderstandingRuntime["describeImageFileWithModel"]; extractStructuredWithModel: MediaUnderstandingRuntime["extractStructuredWithModel"]; describeVideoFile: MediaUnderstandingRuntime["describeVideoFile"]; transcribeAudioFile: MediaUnderstandingRuntime["transcribeAudioFile"]; }; imageGeneration: { generate: (params: GenerateImageParams) => Promise; listProviders: (params?: ListRuntimeImageGenerationProvidersParams) => RuntimeImageGenerationProvider[]; }; videoGeneration: { generate: (params: GenerateVideoParams) => Promise; listProviders: (params?: ListRuntimeVideoGenerationProvidersParams) => RuntimeVideoGenerationProvider[]; }; musicGeneration: { generate: (params: GenerateMusicParams) => Promise; listProviders: (params?: ListRuntimeMusicGenerationProvidersParams) => RuntimeMusicGenerationProvider[]; }; webSearch: { listProviders: (params?: ListWebSearchProvidersParams) => RuntimeWebSearchProviderEntry[]; search: (params: RunWebSearchParams) => Promise; }; stt: { transcribeAudioFile: MediaUnderstandingRuntime["transcribeAudioFile"]; }; events: { onAgentEvent: typeof onAgentEvent; onSessionTranscriptUpdate: typeof onSessionTranscriptUpdate; }; logging: { shouldLogVerbose: typeof shouldLogVerbose; getChildLogger: (bindings?: Record, opts?: { level?: LogLevel; }) => RuntimeLogger; }; state: { resolveStateDir: typeof resolveStateDir; openKeyedStore: (options: OpenKeyedStoreOptions) => PluginStateKeyedStore; openSyncKeyedStore: (options: OpenKeyedStoreOptions) => PluginStateSyncKeyedStore; openChannelIngressQueue: (options?: Omit) => ChannelIngressQueue; }; tasks: { runs: PluginRuntimeTaskRuns; flows: PluginRuntimeTaskFlows; managedFlows: PluginRuntimeTaskFlow; /** @deprecated Use runtime.tasks.flows for DTO-based TaskFlow access. */ flow: PluginRuntimeTaskFlow; }; /** @deprecated Use runtime.tasks.flows for DTO-based TaskFlow access. */ taskFlow: PluginRuntimeTaskFlow; llm: { complete: (params: LlmCompleteParams) => Promise; }; modelAuth: { /** Resolve auth for a model. Only provider/model, optional cfg, and workspaceDir are used. */getApiKeyForModel: (params: { model: import("openclaw/plugin-sdk/llm").Model; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; /** Resolve request-ready auth for a model, including provider runtime exchanges. */ getRuntimeAuthForModel: (params: { model: import("openclaw/plugin-sdk/llm").Model; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; /** Resolve auth for a provider by name. Only provider, optional cfg, and workspaceDir are used. */ resolveApiKeyForProvider: (params: { provider: string; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; }; }; //#endregion //#region src/context-engine/types.d.ts type AssembleResult = { /** Ordered messages to use as model context */messages: AgentMessage[]; /** Estimated total tokens in assembled context */ estimatedTokens: number; /** * Controls which token estimate the runner treats as authoritative for * preemptive overflow prechecks. The returned `messages` are always the * prompt sent to the model; this only affects the precheck's token comparison. * * - "assembled": the generic precheck uses only the assembled prompt's estimate * unless the engine owns compaction; owning engines manage prompt admission. * - "preassembly_may_overflow": the precheck takes the maximum of the * assembled estimate and the pre-assembly (unwindowed) session-history * estimate. Engines opt into this when their assembled view can hide an * overflow that would still affect the underlying transcript. This opt-in * keeps the generic precheck active even for engines that own compaction. * * Defaults to "assembled". */ promptAuthority?: "assembled" | "preassembly_may_overflow"; /** Optional context-engine-provided instructions prepended to the runtime system prompt */ systemPromptAddition?: string; /** * Optional projection lifecycle for hosts with persistent backend threads. * * Context engines that return `thread_bootstrap` ask the host to inject the * assembled context once for the supplied epoch, then reuse the backend * thread until the epoch changes. Engines that omit this field retain the * legacy per-turn projection behavior. */ contextProjection?: ContextEngineProjection; }; type ContextEngineProjection = { /** How the assembled context should be projected into the backend runtime. */mode: "per_turn" | "thread_bootstrap"; /** Stable context epoch. Changing this tells persistent backends to rotate. */ epoch?: string; /** Optional diagnostic fingerprint for the projected context payload. */ fingerprint?: string; }; type ContextEngineOperation = "agent-run" | "manual-compact" | "subagent-spawn"; type ContextEngineRuntimeMode = "normal" | "fallback" | "degraded"; type ContextEngineSelectionSource = "configured" | "default" | "unknown"; type ContextEngineRuntimeReasonCode = "provider_timeout" | "provider_unavailable" | "rate_limited" | "context_overflow" | "runtime_unavailable" | "unknown"; type ContextEngineHostCapability = "bootstrap" | "assemble-before-prompt" | "after-turn" | "maintain" | "compact" | "runtime-llm-complete" | "thread-bootstrap-projection"; type ContextEngineHostRequirements = { /** Host capabilities required before the engine can safely serve this operation. */requiredCapabilities: ContextEngineHostCapability[]; /** Optional engine-authored guidance appended to the host compatibility error. */ unsupportedMessage?: string; }; type ContextEngineRuntimeSettings = { schemaVersion: 1; runtime: { host: "openclaw"; mode: ContextEngineRuntimeMode; harnessId: string | null; runtimeId: string | null; }; model: { requested: string | null; resolved: string | null; provider: string | null; family: string | null; }; contextEngineSelection: { selectedId: string | null; source: ContextEngineSelectionSource; }; executionHost: { id: string | null; label: string | null; }; limits: { promptTokenBudget: number | null; maxOutputTokens: number | null; }; diagnostics: { fallbackReason: ContextEngineRuntimeReasonCode | null; degradedReason: ContextEngineRuntimeReasonCode | null; }; }; declare class ContextEngineRuntimeSettingsUnavailableError extends Error { readonly code = "context_engine_runtime_settings_unavailable"; constructor(message?: string); } declare class ContextEngineRuntimeSettingsUnsupportedError extends Error { readonly code = "context_engine_runtime_settings_unsupported"; constructor(message?: string); } /** * Typed session target for compaction results. * * Makes the storage mode explicit and carries precise session identity * instead of a raw file path string. File-backed is the only storage mode * today; new storage modes extend this union when they ship. */ type ContextEngineSessionTarget = { kind: "file"; /** Agent that owns the session, when the caller resolved it. */ agentId?: string; /** Runtime session id for the post-compaction live session. */ sessionId: string; /** Stable session key used for aliases, policy, and store resolution. */ sessionKey?: string; /** Live transcript artifact path for the file-backed session. */ sessionFile: string; }; type CompactResult = { ok: boolean; compacted: boolean; reason?: string; result?: { summary?: string; firstKeptEntryId?: string; tokensBefore: number; tokensAfter?: number; details?: unknown; /** Session id after compaction, when the runtime rotated transcripts. */ sessionId?: string; /** Typed post-compaction live session target; successor when the runtime rotated transcripts. */ sessionTarget?: ContextEngineSessionTarget; /** * Raw session file path after compaction. * * @deprecated Use `sessionTarget`. Shipped plugin-sdk contract: released * third-party context engines (v2026.6.x and earlier) report rotated * transcripts through this field. Remove once typed session targets are * the only successor contract. */ sessionFile?: string; }; }; type IngestResult = { /** Whether the message was ingested (false if duplicate or no-op) */ingested: boolean; }; type IngestBatchResult = { /** Number of messages ingested from the supplied batch */ingestedCount: number; }; type BootstrapResult = { /** Whether bootstrap ran and initialized the engine's store */bootstrapped: boolean; /** Number of historical messages imported (if applicable) */ importedMessages?: number; /** Optional reason when bootstrap was skipped */ reason?: string; }; type ContextEngineInfo = { id: string; name: string; version?: string; /** True when the engine manages its own compaction lifecycle. */ ownsCompaction?: boolean; /** * Controls how turn-triggered maintenance should be executed. * * Engines remain compatible by default unless the host explicitly opts into * background turn maintenance. */ turnMaintenanceMode?: "foreground" | "background"; /** * Host capability requirements for operations where using an unsupported * runtime would silently degrade or corrupt the engine's behavior. */ hostRequirements?: Partial>; }; type SubagentSpawnPreparation = { /** Roll back pre-spawn setup when subagent launch fails. */rollback: () => void | Promise; }; type SubagentEndReason = "deleted" | "completed" | "swept" | "released"; type TranscriptRewriteReplacement = { /** Existing transcript entry id to replace on the active branch. */entryId: string; /** Replacement message content for that entry. */ message: AgentMessage; }; type TranscriptRewriteRequest = { /** Message entry replacements to apply in one branch-and-reappend pass. */replacements: TranscriptRewriteReplacement[]; /** Optional entry-id set that must cover every active-branch entry from the first replacement onward. */ allowedRewriteSuffixEntryIds?: string[]; }; type TranscriptRewriteResult = { /** Whether the active branch changed. */changed: boolean; /** Estimated bytes removed from the active branch message payloads. */ bytesFreed: number; /** Number of transcript message entries rewritten. */ rewrittenEntries: number; /** Optional reason when no rewrite occurred. */ reason?: string; }; type ContextEngineMaintenanceResult = TranscriptRewriteResult; type ContextEnginePromptCacheRetention = "none" | "short" | "long" | "in_memory" | "24h"; type ContextEnginePromptCacheUsage = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; contextUsage?: { state: "available"; promptTokens: number; totalTokens: number; } | { state: "unavailable"; }; total?: number; }; type ContextEnginePromptCacheObservationChangeCode = "cacheRetention" | "model" | "streamStrategy" | "systemPrompt" | "tools" | "transport"; type ContextEnginePromptCacheObservationChange = { code: ContextEnginePromptCacheObservationChangeCode; detail: string; }; type ContextEnginePromptCacheObservation = { broke: boolean; previousCacheRead?: number; cacheRead?: number; changes?: ContextEnginePromptCacheObservationChange[]; }; type ContextEnginePromptCacheInfo = { /** Runtime-resolved retention for the actual provider/model/request path. */retention?: ContextEnginePromptCacheRetention; /** Usage from the most recent API call, not accumulated retry/tool-loop totals. */ lastCallUsage?: ContextEnginePromptCacheUsage; /** Result from the runtime's prompt-cache observability heuristic. */ observation?: ContextEnginePromptCacheObservation; /** Last known cache-touch timestamp from runtime-managed cache-TTL bookkeeping. */ lastCacheTouchAt?: number; /** Known cache expiry time when the runtime can source it confidently. */ expiresAt?: number; }; type ContextEngineRuntimeContext = Record & { /** Runtime task working directory; workspaceDir remains the agent bootstrap workspace. */cwd?: string; /** * True when the host has explicitly opted this maintenance run into * consuming deferred compaction debt. */ allowDeferredCompactionExecution?: boolean; /** Runtime-resolved context window budget for the active model call. */ tokenBudget?: number; /** Selected agent harness id when compaction delegates back to the runtime. */ agentHarnessId?: string; /** Best-effort current prompt/context token estimate for this turn. */ currentTokenCount?: number; /** Optional prompt-cache telemetry for cache-aware engines. */ promptCache?: ContextEnginePromptCacheInfo; /** * Safe transcript rewrite helper implemented by the runtime. * * Engines decide what is safe to rewrite; the runtime owns how the session * DAG is updated on disk. */ rewriteTranscriptEntries?: (request: TranscriptRewriteRequest) => Promise; /** LLM completion capability for engines that need model inference. */ llm?: { complete: (params: LlmCompleteParams) => Promise; }; }; /** * ContextEngine defines the pluggable contract for context management. * * Required methods define a generic lifecycle; optional methods allow engines * to provide additional capabilities (retrieval, lineage, etc.). */ interface ContextEngine { /** Engine identifier and metadata */ readonly info: ContextEngineInfo; /** * Initialize engine state for a session, optionally importing historical context. */ bootstrap?(params: { sessionId: string; sessionKey?: string; sessionFile: string; runtimeSettings?: ContextEngineRuntimeSettings; }): Promise; /** * Run transcript maintenance after bootstrap, successful turns, or compaction. * * Engines can use runtimeContext.rewriteTranscriptEntries() to request safe * branch-and-reappend transcript rewrites without depending on runner internals. */ maintain?(params: { sessionId: string; sessionKey?: string; sessionFile: string; runtimeSettings?: ContextEngineRuntimeSettings; runtimeContext?: ContextEngineRuntimeContext; }): Promise; /** * Ingest a single message into the engine's store. */ ingest(params: { sessionId: string; sessionKey?: string; message: AgentMessage; /** True when the message belongs to a heartbeat run. */ isHeartbeat?: boolean; }): Promise; /** * Ingest a completed turn batch as a single unit. */ ingestBatch?(params: { sessionId: string; sessionKey?: string; messages: AgentMessage[]; /** True when the batch belongs to a heartbeat run. */ isHeartbeat?: boolean; }): Promise; /** * Execute optional post-turn lifecycle work after a run attempt completes. * Engines can use this to persist canonical context and trigger background * compaction decisions. */ afterTurn?(params: { sessionId: string; sessionKey?: string; sessionFile: string; messages: AgentMessage[]; /** Number of messages that existed before the prompt was sent. */ prePromptMessageCount: number; /** Optional auto-compaction summary emitted by the runtime. */ autoCompactionSummary?: string; /** True when this turn belongs to a heartbeat run. */ isHeartbeat?: boolean; /** Optional model context token budget for proactive compaction. */ tokenBudget?: number; /** Optional runtime-owned context for engines that need caller state. */ runtimeSettings?: ContextEngineRuntimeSettings; runtimeContext?: ContextEngineRuntimeContext; }): Promise; /** * Assemble model context under a token budget. * Returns an ordered set of messages ready for the model. */ assemble(params: { sessionId: string; sessionKey?: string; messages: AgentMessage[]; tokenBudget?: number; /** Tool names available for this run so engines can align prompt guidance with runtime tool access. */ availableTools?: Set; /** Active memory citation mode when engines want to mirror memory prompt guidance. */ citationsMode?: MemoryCitationsMode; /** Current model identifier (e.g. "claude-opus-4", "gpt-4o", "qwen2.5-7b"). * Allows context engine plugins to adapt formatting per model. */ model?: string; /** The incoming user prompt for this turn (useful for retrieval-oriented engines). */ prompt?: string; runtimeSettings?: ContextEngineRuntimeSettings; }): Promise; /** * Compact context to reduce token usage. * May create summaries, prune old turns, etc. * * The host always bounds this call with a finite safety timeout (the same * one that protects native runtime compaction). Engines that run long * operations SHOULD additionally honor `abortSignal` so an in-flight * compaction can be canceled promptly on run abort or host timeout instead * of running to completion in the background. */ compact(params: { sessionId: string; sessionKey?: string; sessionFile: string; tokenBudget?: number; /** Force compaction even below the default trigger threshold. */ force?: boolean; /** Optional live token estimate from the caller's active context. */ currentTokenCount?: number; /** Controls convergence target; defaults to budget. */ compactionTarget?: "budget" | "threshold"; customInstructions?: string; /** Optional runtime-owned context for engines that need caller state. */ runtimeSettings?: ContextEngineRuntimeSettings; runtimeContext?: ContextEngineRuntimeContext; /** * Optional abort signal honored before and during compaction. The host * aborts it on run-level abort or when its compaction safety timeout * fires; engines should stop work and reject promptly when it aborts. */ abortSignal?: AbortSignal; }): Promise; /** * Prepare context-engine-managed subagent state before the child run starts. * * Implementations can return a rollback handle that is invoked when spawn * fails after preparation succeeds. */ prepareSubagentSpawn?(params: { parentSessionKey: string; childSessionKey: string; contextMode?: "isolated" | "fork"; parentSessionId?: string; parentSessionFile?: string; childSessionId?: string; childSessionFile?: string; ttlMs?: number; }): Promise; /** * Notify the context engine that a subagent lifecycle ended. */ onSubagentEnded?(params: { childSessionKey: string; reason: SubagentEndReason; }): Promise; /** * Dispose of any resources held by the engine. */ dispose?(): Promise; } //#endregion //#region src/context-engine/registry.d.ts /** * Runtime context passed to context engine factories during resolution. * Provides config and path information so plugins can initialize engines * without fragile workarounds. */ type ContextEngineFactoryContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; }; /** * A factory that creates a ContextEngine instance. * Supports async creation for engines that need DB connections etc. * * The factory receives a {@link ContextEngineFactoryContext} with runtime * environment context (config, paths). Existing no-arg factories remain * backward compatible because TypeScript permits assigning functions with * fewer parameters to wider signatures. */ type ContextEngineFactory = (ctx: ContextEngineFactoryContext) => ContextEngine | Promise; type ContextEngineRegistrationResult = { ok: true; } | { ok: false; existingOwner: string; }; /** * Public SDK entry point for third-party registrations. * * This path is intentionally unprivileged: it cannot claim core-owned ids and * it cannot safely refresh an existing registration because the caller's * identity is not authenticated. */ declare function registerContextEngine(id: string, factory: ContextEngineFactory): ContextEngineRegistrationResult; /** * Return the trusted plugin id that registered a resolved context engine. */ declare function resolveContextEngineOwnerPluginId(engine: ContextEngine | undefined | null): string | undefined; //#endregion //#region src/plugins/compaction-provider.d.ts /** * Compaction provider registry — process-global singleton. * * Plugins implement the CompactionProvider interface and register via * `registerCompactionProvider()`. The compaction safeguard checks this * registry before falling back to the built-in `summarizeInStages()`. */ /** * A pluggable compaction provider that can replace the built-in * summarizeInStages pipeline. */ type CompactionProviderSummarizationInstructions = { identifierPolicy?: "strict" | "off" | "custom"; identifierInstructions?: string; }; interface CompactionProvider { id: string; label: string; summarize(params: { messages: unknown[]; signal?: AbortSignal; compressionRatio?: number; customInstructions?: string; summarizationInstructions?: CompactionProviderSummarizationInstructions; /** Summary from a prior compaction round, if re-compacting. */ previousSummary?: string; }): Promise; } //#endregion //#region src/agents/current-time.d.ts type CronStyleNow = { userTimezone: string; formattedTime: string; timeLine: string; }; type TimeConfigLike = { agents?: { defaults?: { userTimezone?: string; timeFormat?: TimeFormatPreference; }; }; }; /** Resolve localized and UTC current-time text for agent prompts. */ declare function resolveCronStyleNow(cfg: TimeConfigLike, nowMs: number): CronStyleNow; declare function appendCronStyleCurrentTimeLine(text: string, cfg: TimeConfigLike, nowMs: number): string; //#endregion //#region src/agents/agent-settings.d.ts declare const DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR = 20000; //#endregion //#region src/agents/memory-search.d.ts type ResolvedMemorySearchConfig = { enabled: boolean; sources: Array<"memory" | "sessions">; extraPaths: string[]; multimodal: MemoryMultimodalSettings; provider: string; remote?: { baseUrl?: string; apiKey?: SecretInput; headers?: Record; nonBatchConcurrency?: number; batch?: { enabled: boolean; wait: boolean; concurrency: number; pollIntervalMs: number; timeoutMinutes: number; }; }; experimental: { sessionMemory: boolean; }; fallback: string; model: string; inputType?: string; queryInputType?: string; documentInputType?: string; outputDimensionality?: number; local: { modelPath?: string; modelCacheDir?: string; contextSize?: number | "auto"; }; store: { driver: "sqlite"; databasePath: string; fts: { tokenizer: "unicode61" | "trigram"; }; vector: { enabled: boolean; extensionPath?: string; }; }; chunking: { tokens: number; overlap: number; }; sync: { onSessionStart: boolean; onSearch: boolean; watch: boolean; watchDebounceMs: number; intervalMinutes: number; embeddingBatchTimeoutSeconds: number | undefined; sessions: { deltaBytes: number; deltaMessages: number; postCompactionForce: boolean; }; }; query: { maxResults: number; minScore: number; hybrid: { enabled: boolean; vectorWeight: number; textWeight: number; candidateMultiplier: number; mmr: { enabled: boolean; lambda: number; }; temporalDecay: { enabled: boolean; halfLifeDays: number; }; }; }; cache: { enabled: boolean; maxEntries?: number; }; }; type ResolvedMemorySearchSyncConfig = ResolvedMemorySearchConfig["sync"]; declare function resolveMemorySearchConfig(cfg: OpenClawConfig, agentId: string): ResolvedMemorySearchConfig | null; declare function resolveMemorySearchSyncConfig(cfg: OpenClawConfig, agentId: string): ResolvedMemorySearchSyncConfig | null; //#endregion //#region src/auto-reply/heartbeat.d.ts /** Default prompt for heartbeat turns when config does not override it. */ declare const HEARTBEAT_PROMPT = "Read HEARTBEAT.md if it exists (workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK."; declare const DEFAULT_HEARTBEAT_ACK_MAX_CHARS = 300; /** Resolves configured heartbeat prompt text with the built-in default fallback. */ declare function resolveHeartbeatPrompt(raw?: string): string; type StripHeartbeatMode = "heartbeat" | "message"; /** Strips HEARTBEAT_OK acknowledgements and decides whether visible notification is needed. */ declare function stripHeartbeatToken(raw?: string, opts?: { mode?: StripHeartbeatMode; maxAckChars?: number; }): { shouldSkip: boolean; text: string; didStrip: boolean; }; //#endregion //#region src/cli/progress.d.ts type ProgressOptions = { label: string; indeterminate?: boolean; total?: number; enabled?: boolean; delayMs?: number; stream?: NodeJS.WriteStream; fallback?: "spinner" | "line" | "log" | "none"; }; /** Minimal progress API exposed to CLI work callbacks. */ type ProgressReporter = { setLabel: (label: string) => void; setPercent: (percent: number) => void; tick: (delta?: number) => void; done: () => void; }; /** Completed/total progress update shape used by totals-based commands. */ type ProgressTotalsUpdate = { completed: number; total: number; label?: string; }; /** Run async work with a progress reporter that is always stopped in finally. */ declare function withProgress(options: ProgressOptions, work: (progress: ProgressReporter) => Promise): Promise; /** Run async work with a progress reporter plus a completed/total update adapter. */ declare function withProgressTotals(options: ProgressOptions, work: (update: (update: ProgressTotalsUpdate) => void, progress: ProgressReporter) => Promise): Promise; //#endregion //#region src/config/byte-size.d.ts /** * Parse an optional byte-size value from config. * Accepts non-negative numbers or strings like "2mb". */ declare function parseNonNegativeByteSize(value: unknown): number | null; //#endregion //#region src/plugins/memory-embedding-provider-runtime.d.ts /** Lists registered memory embedding provider adapters without registry metadata. */ declare function listRegisteredMemoryEmbeddingProviderAdapters(): MemoryEmbeddingProviderAdapter[]; /** Lists memory embedding providers from runtime config and registered adapters. */ declare function listMemoryEmbeddingProviders(cfg?: OpenClawConfig): MemoryEmbeddingProviderAdapter[]; /** Resolves one memory embedding provider by id, alias, or configured API owner. */ declare function getMemoryEmbeddingProvider(id: string, cfg?: OpenClawConfig): MemoryEmbeddingProviderAdapter | undefined; //#endregion //#region src/plugins/config-schema.d.ts type BuildPluginConfigSchemaOptions = { uiHints?: Record; safeParse?: OpenClawPluginConfigSchema["safeParse"]; }; type BuildJsonPluginConfigSchemaOptions = { cacheKey?: string; uiHints?: Record; safeParse?: OpenClawPluginConfigSchema["safeParse"]; }; /** Build a plugin config schema from JSON Schema with runtime validation/default support. */ declare function buildJsonPluginConfigSchema(schema: JsonSchemaObject, options?: BuildJsonPluginConfigSchemaOptions): OpenClawPluginConfigSchema; /** Build a plugin config schema from Zod, exporting JSON Schema when the Zod runtime supports it. */ declare function buildPluginConfigSchema(schema: ZodTypeAny, options?: BuildPluginConfigSchemaOptions): OpenClawPluginConfigSchema; /** Return a schema for plugins that intentionally accept no config keys. */ declare function emptyPluginConfigSchema(): OpenClawPluginConfigSchema; //#endregion //#region src/utils/shell-argv.d.ts /** Splits a shell-like argv string into tokens, returning null for unterminated quotes or escapes. */ declare function splitShellArgs(raw: string): string[] | null; //#endregion //#region packages/memory-host-sdk/src/host/fs-utils.d.ts /** True for missing-file errors emitted by Node or fs-safe. */ declare function isFileMissingError(err: unknown): err is NodeJS.ErrnoException & { code: "ENOENT" | "ENOTDIR" | "not-found"; }; //#endregion //#region packages/memory-host-sdk/src/host/embedding-inputs.d.ts /** Text part passed through embedding providers that support structured input. */ type EmbeddingInputTextPart = { type: "text"; text: string; }; /** Inline binary payload encoded for providers with multimodal embedding support. */ type EmbeddingInputInlineDataPart = { type: "inline-data"; mimeType: string; data: string; }; /** Single structured embedding input part. */ type EmbeddingInputPart = EmbeddingInputTextPart | EmbeddingInputInlineDataPart; /** Provider-facing input while preserving the plain text fallback. */ type EmbeddingInput = { text: string; parts?: EmbeddingInputPart[]; }; /** Return true when a chunk needs structured provider handling, not text splitting. */ declare function hasNonTextEmbeddingParts(input: EmbeddingInput | undefined): boolean; //#endregion //#region packages/memory-host-sdk/src/host/embeddings.types.d.ts type EmbeddingProvider = { id: string; model: string; maxInputTokens?: number; embedQuery: (text: string, options?: EmbeddingProviderCallOptions) => Promise; embedBatch: (texts: string[], options?: EmbeddingProviderCallOptions) => Promise; embedBatchInputs?: (inputs: EmbeddingInput[], options?: EmbeddingProviderCallOptions) => Promise; close?: () => Promise | void; }; type EmbeddingProviderCallOptions = { signal?: AbortSignal; }; type EmbeddingProviderRequest = string; type EmbeddingProviderFallback = string; type GeminiTaskType = "RETRIEVAL_QUERY" | "RETRIEVAL_DOCUMENT" | "SEMANTIC_SIMILARITY" | "CLASSIFICATION" | "CLUSTERING" | "QUESTION_ANSWERING" | "FACT_VERIFICATION"; type EmbeddingProviderOptions = { config: OpenClawConfig; agentDir?: string; provider?: EmbeddingProviderRequest; remote?: { baseUrl?: string; apiKey?: SecretInput; headers?: Record; }; model: string; inputType?: string; queryInputType?: string; documentInputType?: string; fallback?: EmbeddingProviderFallback; local?: { modelPath?: string; modelCacheDir?: string; /** * Context size passed to node-llama-cpp `createEmbeddingContext`. * Default: 4096, chosen to cover typical memory-search chunks (128–512 tokens) * while keeping non-weight VRAM bounded. * Set `"auto"` to let node-llama-cpp use the model's trained maximum — not * recommended for 8B+ models (e.g. Qwen3-Embedding-8B: up to 40 960 tokens → ~32 GB VRAM). */ contextSize?: number | "auto"; }; /** Provider-specific output vector dimensions for supported embedding families. */ outputDimensionality?: number; /** Gemini: override the default task type sent with embedding requests. */ taskType?: GeminiTaskType; }; //#endregion //#region packages/memory-host-sdk/src/host/embedding-defaults.d.ts /** Default local embedding model used when config omits an explicit model. */ declare const DEFAULT_LOCAL_MODEL = "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf"; //#endregion //#region packages/memory-host-sdk/src/host/embeddings.d.ts type LocalEmbeddingProviderRuntimeOptions = { workerScriptPath?: string; nodeLlamaCppImportUrl?: string; }; declare function createLocalEmbeddingProvider(options: EmbeddingProviderOptions, runtimeOptions?: LocalEmbeddingProviderRuntimeOptions): Promise; //#endregion //#region packages/memory-host-sdk/src/host/batch-error-utils.d.ts /** Minimal batch output line shape that can carry provider error messages. */ type BatchOutputErrorLike = { error?: { message?: string; }; response?: { body?: string | { error?: { message?: string; }; }; }; }; /** Return the first useful error message from batch output lines. */ declare function extractBatchErrorMessage(lines: BatchOutputErrorLike[]): string | undefined; /** Format a failed error-file read without hiding the underlying read problem. */ declare function formatUnavailableBatchError(err: unknown): string | undefined; //#endregion //#region packages/memory-host-sdk/src/host/retry-utils.d.ts /** Retry timing configuration with optional jitter. */ type RetryConfig = { attempts?: number; minDelayMs?: number; maxDelayMs?: number; jitter?: number; }; /** Retry callback payload. */ type RetryInfo = { attempt: number; maxAttempts: number; delayMs: number; err: unknown; label?: string; }; /** Retry options for retryAsync. */ type RetryOptions = RetryConfig & { label?: string; shouldRetry?: (err: unknown, attempt: number) => boolean; retryAfterMs?: (err: unknown) => number | undefined; onRetry?: (info: RetryInfo) => void; }; /** Run an async operation with exponential backoff retry handling. */ declare function retryAsync(fn: () => Promise, attemptsOrOptions?: number | RetryOptions, initialDelayMs?: number): Promise; //#endregion //#region packages/memory-host-sdk/src/host/ssrf-policy.d.ts /** Host/network allowlist policy forwarded to the runtime SSRF guard. */ type SsrFPolicy = { allowPrivateNetwork?: boolean; dangerouslyAllowPrivateNetwork?: boolean; allowRfc2544BenchmarkRange?: boolean; allowIpv6UniqueLocalRange?: boolean; allowedHostnames?: string[]; hostnameAllowlist?: string[]; }; //#endregion //#region packages/memory-host-sdk/src/host/batch-http.d.ts /** POST JSON and retry provider 429/5xx failures with bounded backoff. */ declare function postJsonWithRetry(params: { url: string; headers: Record; ssrfPolicy?: SsrFPolicy; fetchImpl?: typeof fetch; retryImpl?: typeof retryAsync; body: unknown; errorPrefix: string; }): Promise; //#endregion //#region packages/memory-host-sdk/src/host/batch-output.d.ts /** Minimal OpenAI-compatible embedding batch output line. */ type EmbeddingBatchOutputLine = { custom_id?: string; error?: { message?: string; }; response?: { status_code?: number; body?: { data?: Array<{ embedding?: number[]; }>; error?: { message?: string; }; } | string; }; }; /** Apply one output line, collecting errors and successful embeddings by custom id. */ declare function applyEmbeddingBatchOutputLine(params: { line: EmbeddingBatchOutputLine; remaining: Set; errors: string[]; byCustomId: Map; }): void; //#endregion //#region packages/memory-host-sdk/src/host/batch-provider-common.d.ts /** Provider output line after an embedding batch file is read. */ type ProviderBatchOutputLine = EmbeddingBatchOutputLine; /** OpenAI-compatible endpoint used inside embedding batch request lines. */ declare const EMBEDDING_BATCH_ENDPOINT = "/v1/embeddings"; //#endregion //#region packages/memory-host-sdk/src/host/batch-runner.d.ts /** Execution controls for provider embedding batch submissions and polling. */ type EmbeddingBatchExecutionParams = { wait: boolean; pollIntervalMs: number; timeoutMs: number; concurrency: number; debug?: (message: string, data?: Record) => void; }; type EmbeddingBatchGroupRunArgs = { group: TRequest[]; groupIndex: number; groups: number; byCustomId: Map; pollIntervalMs: number; timeoutMs: number; }; type EmbeddingBatchSplitArgs = { error: unknown; group: TRequest[]; parts: TRequest[][]; groupIndex: number; groups: number; depth: number; }; /** Run request groups with bounded concurrency and return embeddings by custom id. */ declare function runEmbeddingBatchGroups(params: { requests: TRequest[]; maxRequests: number; maxJsonlBytes?: number; wait: EmbeddingBatchExecutionParams["wait"]; pollIntervalMs: EmbeddingBatchExecutionParams["pollIntervalMs"]; timeoutMs: EmbeddingBatchExecutionParams["timeoutMs"]; concurrency: EmbeddingBatchExecutionParams["concurrency"]; debugLabel: string; debug?: EmbeddingBatchExecutionParams["debug"]; shouldSplitGroupOnError?: (error: unknown, group: TRequest[]) => boolean; onSplitGroup?: (args: EmbeddingBatchSplitArgs) => void; runGroup: (args: EmbeddingBatchGroupRunArgs) => Promise; }): Promise>; /** Build normalized batch-group options for provider-specific runners. */ declare function buildEmbeddingBatchGroupOptions(params: { requests: TRequest[]; } & EmbeddingBatchExecutionParams, options: { maxRequests: number; maxJsonlBytes?: number; debugLabel: string; }): { requests: TRequest[]; maxRequests: number; maxJsonlBytes: number | undefined; wait: boolean; pollIntervalMs: number; timeoutMs: number; concurrency: number; debug: ((message: string, data?: Record) => void) | undefined; debugLabel: string; }; //#endregion //#region packages/memory-host-sdk/src/host/batch-status.d.ts /** Minimal provider batch status used for completion and terminal-failure checks. */ type BatchStatusLike = { id?: string; status?: string; output_file_id?: string | null; error_file_id?: string | null; }; /** File ids returned once a batch has completed. */ type BatchCompletionResult = { outputFileId: string; errorFileId?: string; }; /** Convert a completed provider status payload into output/error file ids. */ declare function resolveBatchCompletionFromStatus(params: { provider: string; batchId: string; status: BatchStatusLike; }): BatchCompletionResult; /** Throw when a provider reports a terminal failure, including error-file detail if available. */ declare function throwIfBatchTerminalFailure(params: { provider: string; status: BatchStatusLike; readError: (errorFileId: string) => Promise; }): Promise; /** Resolve the completed batch files, optionally waiting according to caller policy. */ declare function resolveCompletedBatchResult(params: { provider: string; status: BatchStatusLike; wait: boolean; waitForBatch: () => Promise; }): Promise; //#endregion //#region packages/memory-host-sdk/src/host/batch-utils.d.ts /** Minimal HTTP client config needed by batch providers. */ type BatchHttpClientConfig = { baseUrl?: string; headers?: Record; ssrfPolicy?: SsrFPolicy; fetchImpl?: typeof fetch; }; /** Normalize batch API base URLs by removing one trailing slash. */ declare function normalizeBatchBaseUrl(client: BatchHttpClientConfig): string; /** Build request headers, preserving caller auth and controlling JSON/form content type. */ declare function buildBatchHeaders(client: Pick, params: { json: boolean; }): Record; //#endregion //#region packages/memory-host-sdk/src/host/batch-upload.d.ts /** Upload embedding batch requests and return the provider file id. */ declare function uploadBatchJsonlFile(params: { client: BatchHttpClientConfig; requests: unknown[]; errorPrefix: string; maxResponseBytes?: number; signal?: AbortSignal; }): Promise; //#endregion //#region packages/memory-host-sdk/src/host/hash.d.ts /** SHA-256 hash helper for stable cache/content keys. */ declare function hashText(value: string): string; //#endregion //#region packages/memory-host-sdk/src/host/internal.d.ts type MemoryFileEntry = { path: string; absPath: string; mtimeMs: number; size: number; hash: string; dataHash?: string; kind?: "markdown" | "multimodal"; contentText?: string; modality?: MemoryMultimodalModality; mimeType?: string; }; type MemoryChunk = { startLine: number; endLine: number; text: string; hash: string; embeddingInput?: EmbeddingInput; }; type MultimodalMemoryChunk = { chunk: MemoryChunk; structuredInputBytes: number; }; declare function ensureDir(dir: string): string; declare function normalizeExtraMemoryPaths(workspaceDir: string, extraPaths?: string[]): string[]; declare function listMemoryFiles(workspaceDir: string, extraPaths?: string[], multimodal?: MemoryMultimodalSettings): Promise; declare function buildFileEntry(absPath: string, workspaceDir: string, multimodal?: MemoryMultimodalSettings): Promise; declare function buildMultimodalChunkForIndexing(entry: Pick): Promise; declare function chunkMarkdown(content: string, chunking: { tokens: number; overlap: number; }): MemoryChunk[]; /** * Remap chunk startLine/endLine from content-relative positions to original * source file positions using a lineMap. Each entry in lineMap gives the * 1-indexed source line for the corresponding 0-indexed content line. * * This is used for session JSONL files where buildSessionEntry() flattens * messages into a plain-text string before chunking. Without remapping the * stored line numbers would reference positions in the flattened text rather * than the original JSONL file. */ declare function remapChunkLines(chunks: MemoryChunk[], lineMap: number[] | undefined): void; declare function parseEmbedding(raw: string): number[]; declare function cosineSimilarity(a: number[], b: number[]): number; declare function runWithConcurrency(tasks: Array<() => Promise>, limit: number): Promise; //#endregion //#region packages/memory-host-sdk/src/host/embedding-chunk-limits.d.ts /** * Split text-only chunks to the provider's effective input limit. * * Structured multimodal chunks are preserved because only the provider can decide how to count * non-text parts. */ declare function enforceEmbeddingMaxInputTokens(provider: EmbeddingProvider, chunks: MemoryChunk[], hardMaxInputTokens?: number): MemoryChunk[]; //#endregion //#region packages/memory-host-sdk/src/host/embedding-provider-adapter-utils.d.ts /** Detect missing API key errors from provider auth resolution. */ declare function isMissingEmbeddingApiKeyError(err: unknown): boolean; /** Return stable cache headers after removing provider-specific secret headers. */ declare function sanitizeEmbeddingCacheHeaders(headers: Record, excludedHeaderNames: string[]): Array<[string, string]>; /** Convert custom-id keyed batch embeddings back to request-index order. */ declare function mapBatchEmbeddingsByIndex(byCustomId: Map, count: number): number[][]; //#endregion //#region packages/memory-host-sdk/src/host/embedding-vectors.d.ts /** Replace invalid coordinates and L2-normalize non-empty vectors. */ declare function sanitizeAndNormalizeEmbedding(vec: number[]): number[]; //#endregion //#region packages/memory-host-sdk/src/host/embeddings-debug.d.ts /** Write embedding debug metadata when OPENCLAW_DEBUG_MEMORY_EMBEDDINGS is enabled. */ declare function debugEmbeddingsLog(message: string, meta?: Record): void; //#endregion //#region packages/memory-host-sdk/src/host/embeddings-model-normalize.d.ts /** Trim a configured model id, fall back when empty, and strip known prefixes. */ declare function normalizeEmbeddingModelWithPrefixes(params: { model: string; defaultModel: string; prefixes: string[]; }): string; //#endregion //#region packages/memory-host-sdk/src/host/embeddings-remote-client.d.ts /** Provider id used for remote embedding auth and config lookup. */ type RemoteEmbeddingProviderId = string; /** Resolve base URL, bearer headers, header overrides, and SSRF policy for remote embeddings. */ declare function resolveRemoteEmbeddingBearerClient(params: { provider: RemoteEmbeddingProviderId; options: EmbeddingProviderOptions; defaultBaseUrl: string; }): Promise<{ baseUrl: string; headers: Record; ssrfPolicy?: SsrFPolicy; }>; //#endregion //#region packages/memory-host-sdk/src/host/embeddings-remote-provider.d.ts /** HTTP client details required by a remote embedding provider. */ type RemoteEmbeddingClient = { baseUrl: string; headers: Record; ssrfPolicy?: SsrFPolicy; fetchImpl?: typeof fetch; model: string; }; /** Create an EmbeddingProvider backed by a remote embeddings endpoint. */ declare function createRemoteEmbeddingProvider(params: { id: string; client: RemoteEmbeddingClient; errorPrefix: string; maxInputTokens?: number; }): EmbeddingProvider; /** Resolve a normalized remote embedding client from provider config and model options. */ declare function resolveRemoteEmbeddingClient(params: { provider: RemoteEmbeddingProviderId; options: EmbeddingProviderOptions; defaultBaseUrl: string; normalizeModel: (model: string) => string; }): Promise; //#endregion //#region packages/memory-host-sdk/src/host/embeddings-remote-fetch.d.ts /** POST an embedding request and return validated vectors in provider response order. */ declare function fetchRemoteEmbeddingVectors(params: { url: string; headers: Record; ssrfPolicy?: SsrFPolicy; fetchImpl?: typeof fetch; signal?: AbortSignal; body: unknown; errorPrefix: string; }): Promise; //#endregion //#region packages/memory-host-sdk/src/host/embedding-input-limits.d.ts declare function estimateUtf8Bytes(text: string): number; declare function estimateStructuredEmbeddingInputBytes(input: EmbeddingInput): number; //#endregion //#region packages/memory-host-sdk/src/host/remote-http.d.ts /** Build an SSRF allow policy from a configured remote base URL. */ declare const buildRemoteBaseUrlPolicy: (baseUrl: string) => SsrFPolicy | undefined; /** Execute a remote HTTP request under SSRF guard and always release the response handle. */ declare function withRemoteHttpResponse(params: { url: string; init?: RequestInit; signal?: AbortSignal; ssrfPolicy?: SsrFPolicy; fetchImpl?: typeof fetch; fetchWithSsrFGuardImpl?: typeof fetchWithSsrFGuard; shouldUseEnvHttpProxyForUrlImpl?: typeof shouldUseEnvHttpProxyForUrl; auditContext?: string; onResponse: (response: Response) => Promise; }): Promise; //#endregion //#region src/plugins/memory-embedding-providers.d.ts /** Chunk submitted to memory embedding batch processing. */ type MemoryEmbeddingBatchChunk = { text: string; embeddingInput?: EmbeddingInput; }; /** Options for batch memory embedding work. */ type MemoryEmbeddingBatchOptions = { agentId: string; chunks: MemoryEmbeddingBatchChunk[]; wait: boolean; concurrency: number; pollIntervalMs: number; timeoutMs: number; debug: (message: string, data?: Record) => void; }; /** Per-call options for memory embedding providers. */ type MemoryEmbeddingProviderCallOptions = { signal?: AbortSignal; }; /** Runtime metadata returned with memory embedding providers. */ type MemoryEmbeddingProviderRuntime = { id: string; cacheKeyData?: Record; /** Prior persisted model/cache identities that are equivalent to the current identity. */ indexIdentityAliases?: Array<{ model: string; cacheKeyData: Record; }>; inlineQueryTimeoutMs?: number; inlineBatchTimeoutMs?: number; sourceWideBatchEmbed?: boolean; batchEmbed?: (options: MemoryEmbeddingBatchOptions) => Promise; }; /** Provider-owned canonical identity and exact aliases for persisted indexes. */ type MemoryEmbeddingProviderIndexIdentity = { model: string; cacheKeyData: Record; aliases?: Array<{ model: string; cacheKeyData: Record; }>; }; /** Created memory embedding provider instance. */ type MemoryEmbeddingProvider = { id: string; model: string; maxInputTokens?: number; embedQuery: (text: string, options?: MemoryEmbeddingProviderCallOptions) => Promise; embedBatch: (texts: string[], options?: MemoryEmbeddingProviderCallOptions) => Promise; embedBatchInputs?: (inputs: EmbeddingInput[], options?: MemoryEmbeddingProviderCallOptions) => Promise; close?: () => Promise | void; }; /** Options passed to memory embedding provider adapters. */ type MemoryEmbeddingProviderCreateOptions = { config: OpenClawConfig; agentDir?: string; provider?: string; fallback?: string; remote?: { baseUrl?: string; apiKey?: SecretInput; headers?: Record; }; model: string; inputType?: string; queryInputType?: string; documentInputType?: string; local?: { modelPath?: string; modelCacheDir?: string; contextSize?: number | "auto"; }; outputDimensionality?: number; taskType?: "RETRIEVAL_QUERY" | "RETRIEVAL_DOCUMENT" | "SEMANTIC_SIMILARITY" | "CLASSIFICATION" | "CLUSTERING" | "QUESTION_ANSWERING" | "FACT_VERIFICATION"; }; /** Result returned by a memory embedding provider adapter. */ type MemoryEmbeddingProviderCreateResult = { provider: MemoryEmbeddingProvider | null; runtime?: MemoryEmbeddingProviderRuntime; }; /** Adapter contract for registered memory embedding providers. */ type MemoryEmbeddingProviderAdapter = { id: string; defaultModel?: string; transport?: "local" | "remote"; authProviderId?: string; autoSelectPriority?: number; allowExplicitWhenConfiguredAuto?: boolean; supportsMultimodalEmbeddings?: (params: { model: string; }) => boolean; resolveIndexIdentity?: (options: MemoryEmbeddingProviderCreateOptions) => MemoryEmbeddingProviderIndexIdentity; create: (options: MemoryEmbeddingProviderCreateOptions) => Promise; formatSetupError?: (err: unknown) => string; shouldContinueAutoSelection?: (err: unknown) => boolean; }; /** Registered memory embedding provider with optional owning plugin metadata. */ type RegisteredMemoryEmbeddingProvider = { adapter: MemoryEmbeddingProviderAdapter; ownerPluginId?: string; }; /** Registers a memory embedding provider adapter for the current process. */ declare function registerMemoryEmbeddingProvider(adapter: MemoryEmbeddingProviderAdapter, options?: { ownerPluginId?: string; }): void; /** Lists registered memory embedding provider entries. */ declare function listRegisteredMemoryEmbeddingProviders(): RegisteredMemoryEmbeddingProvider[]; /** Clears registered memory embedding providers. */ declare function clearMemoryEmbeddingProviders(): void; //#endregion //#region src/agents/agent-runtime-id.d.ts /** Agent runtime id normalization and retired runtime-selection compatibility helpers. */ type EmbeddedAgentRuntime = "openclaw" | "auto" | (string & {}); /** * @deprecated Whole-agent runtime environment selection is retired. Use * provider/model runtime policy or a registered agent harness instead. */ declare function resolveEmbeddedAgentRuntime(_env?: NodeJS.ProcessEnv): EmbeddedAgentRuntime; //#endregion //#region src/tasks/agent-harness-task-runtime-scope.d.ts type AgentHarnessTaskRuntimeScope = { readonly requesterSessionKey: string; readonly requesterOrigin?: DeliveryContext; }; //#endregion //#region src/agents/agent-tools.before-tool-call.state.d.ts /** Consume and remove hook-adjusted params for a completed tool call. */ declare function consumeAdjustedParamsForToolCall(toolCallId: string, runId?: string): unknown; /** Consume whether policy prevented the target tool from starting. */ declare function consumePreExecutionBlockedToolCall(toolCallId: string, runId?: string): boolean; //#endregion //#region src/agents/before-tool-call-metadata.d.ts /** Return true when a tool already carries the before_tool_call wrapper marker. */ declare function isToolWrappedWithBeforeToolCallHook(tool: AnyAgentTool): boolean; /** Toggle diagnostic event emission on an existing before_tool_call wrapper. */ declare function setBeforeToolCallDiagnosticsEnabled(tool: AnyAgentTool, enabled: boolean): void; //#endregion //#region src/agents/agent-tools.before-tool-call.d.ts type ToolOutcomeObservation = { toolName: string; argsHash: string; resultHash: string; /** Monotonic model-call order within the owning embedded run. */ toolCallOrdinal?: number; terminalPresentation?: string; presentationOnly?: boolean; }; type ToolOutcomeObserver = (observation: ToolOutcomeObservation) => void; type HookContext = { agentId?: string; config?: OpenClawConfig; /** Tool execution cwd for host-derived path facts. */ cwd?: string; /** Host workspace used to resolve relative tool params for diagnostics only. */ workspaceDir?: string; sessionKey?: string; /** Ephemeral session UUID — regenerated on /new and /reset. */ sessionId?: string; runId?: string; /** Device-scoped operator session allowed to review approvals initiated by this run. */ approvalReviewerDeviceId?: string; trace?: DiagnosticTraceContext; channelId?: string; /** Originating channel for approval delivery routing; mirrors exec approval turn-source fields. */ turnSourceChannel?: string; turnSourceTo?: string; turnSourceAccountId?: string; turnSourceThreadId?: string | number; loopDetection?: ToolLoopDetectionConfig; onToolOutcome?: ToolOutcomeObserver; allocateToolOutcomeOrdinal?: (toolCallId?: string) => number; skillsSnapshot?: SkillSnapshot; skillUsagePaths?: SkillUsagePath[]; skillCommand?: { commandName: string; skillFile?: string; skillName: string; skillSource?: SkillTelemetrySource; toolName?: string; }; sandbox?: { root: string; bridge: SandboxFsBridge; }; }; type HookBlockedReason = "plugin-before-tool-call" | "plugin-approval" | "tool-loop"; type BeforeToolCallFailureDisposition = "blocked" | DiagnosticToolTerminalReason; type HookBlockedOutcome = { blocked: true; deniedReason?: HookBlockedReason; reason: string; params?: unknown; }; type HookOutcome = (HookBlockedOutcome & { kind: "veto"; }) | (HookBlockedOutcome & { kind: "failure"; disposition: BeforeToolCallFailureDisposition; }) | { blocked: false; params: unknown; approvalResolution?: PluginApprovalResolution; deferredApproval?: DeferredPluginToolApproval; }; type PluginApprovalRequest = NonNullable; type DeferredPluginToolApproval = { approval: PluginApprovalRequest; toolName: string; toolCallId?: string; ctx?: HookContext; baseParams: unknown; overrideParams?: unknown; }; type BeforeToolCallPolicyDiagnosticState = { hasBeforeToolCallHook: boolean; trustedToolPolicies: Array<{ id: string; pluginId: string; pluginName?: string; }>; }; /** Return whether before_tool_call hooks or trusted policies are active. */ declare function getBeforeToolCallPolicyDiagnosticState(): BeforeToolCallPolicyDiagnosticState; /** Return true when any before_tool_call policy could affect tool execution. */ declare function hasBeforeToolCallPolicy(): boolean; /** Finalizes a trusted terminal summary after harness result middleware. */ declare function finalizeToolTerminalPresentation(params: { toolCallId: string; runId?: string; result: Awaited>; isError: boolean; observer?: ToolOutcomeObserver; toolName?: string; toolCallOrdinal?: number; }): void; /** Return the closed terminal disposition carried by a before-tool failure. */ declare function getBeforeToolCallFailureDisposition(error: unknown): BeforeToolCallFailureDisposition | undefined; /** Resolve a deferred plugin approval request at the later execution boundary. */ declare function requestDeferredPluginToolApproval(params: { deferredApproval: DeferredPluginToolApproval; signal?: AbortSignal; }): Promise; /** Run the full before_tool_call policy chain for a pending tool call. */ declare function runBeforeToolCallHook(args: { toolName: string; params: unknown; toolKind?: PluginHookToolKind; toolInputKind?: PluginHookToolInputKind; toolCallId?: string; ctx?: HookContext; signal?: AbortSignal; approvalMode?: "request" | "report" | "defer"; }): Promise; /** Wrap a tool execute function with before_tool_call hooks and diagnostics. */ declare function wrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext, options?: { approvalMode?: "request" | "report"; emitDiagnostics?: boolean; }): AnyAgentTool; //#endregion //#region src/agents/runtime-plan/types.d.ts /** Runtime transport selected for one model attempt. */ type AgentRuntimeTransport = "sse" | "websocket" | "auto"; /** Thinking levels accepted by runtime-plan extra-param preparation. */ type AgentRuntimeThinkLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; /** System prompt rendering mode selected for one attempt. */ type AgentRuntimePromptMode = "full" | "minimal" | "none"; /** Trigger source that can alter provider system prompt contributions. */ type AgentRuntimePromptTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; /** Normalized failure reason used by model fallback classification. */ type AgentRuntimeFailoverReason = "auth" | "auth_permanent" | "format" | "rate_limit" | "overloaded" | "billing" | "server_error" | "timeout" | "context_overflow" | "model_not_found" | "session_expired" | "empty_response" | "no_error_details" | "unclassified" | "unknown"; /** Provider/runtime config object passed through plugin boundaries. */ type AgentRuntimeConfig = unknown; /** Provider model descriptor consumed by runtime-plan hooks. */ type AgentRuntimeModel = { id?: string; name?: string; api?: string; provider?: string; baseUrl?: string; reasoning?: boolean; input?: readonly string[]; cost?: { input: number; output: number; cacheRead: number; cacheWrite: number; }; contextWindow?: number; maxTokens?: number; contextTokens?: number; compat?: unknown; }; /** Text replacement rule used by provider input/output transforms. */ type AgentRuntimeTextReplacement = { from: string | RegExp; to: string; }; /** Provider text transforms applied around model calls. */ type AgentRuntimeTextTransforms = { input?: AgentRuntimeTextReplacement[]; output?: AgentRuntimeTextReplacement[]; }; /** Resolved provider runtime handle forwarded to plugin-owned hooks. */ type AgentRuntimeProviderHandle = { provider: string; config?: AgentRuntimeConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; applyAutoEnable?: boolean; bundledProviderVitestCompat?: boolean; }; type AgentRuntimeInteractiveButtonStyle = "primary" | "secondary" | "success" | "danger"; type AgentRuntimeMessagePresentationAction = { type: "command"; command: string; } | { type: "callback"; value: string; }; /** Portable action control exposed to agent runtime reply payloads. */ type AgentRuntimeMessagePresentationButton = { /** User-visible button label. */label: string; /** Typed action sent when pressed. */ action?: AgentRuntimeMessagePresentationAction; /** Legacy opaque callback value sent when pressed. */ value?: string; /** External URL opened by the button. */ url?: string; /** Channel-native web app URL for renderers that support embedded web apps. */ webApp?: { url: string; }; /** Higher values are kept first when channel action limits require dropping controls. */ priority?: number; /** Disabled action hint; channels without disabled-state support render fallback text. */ disabled?: boolean; /** Optional visual style hint for renderers that support styled actions. */ style?: AgentRuntimeInteractiveButtonStyle; }; /** Portable select/menu option exposed to agent runtime reply payloads. */ type AgentRuntimeMessagePresentationOption = { /** User-visible option label. */label: string; /** Typed action sent when selected. */ action?: AgentRuntimeMessagePresentationAction; /** Legacy opaque callback value sent when selected. */ value?: string; }; /** * @deprecated Use AgentRuntimeMessagePresentationButton. */ type AgentRuntimeInteractiveReplyButton = AgentRuntimeMessagePresentationButton; /** * @deprecated Use AgentRuntimeMessagePresentationOption. */ type AgentRuntimeInteractiveReplyOption = AgentRuntimeMessagePresentationOption; /** * @deprecated Use AgentRuntimeMessagePresentationBlock. */ type AgentRuntimeInteractiveReplyBlock = { type: "text"; text: string; } | { type: "buttons"; buttons: AgentRuntimeInteractiveReplyButton[]; } | { type: "select"; placeholder?: string; options: AgentRuntimeInteractiveReplyOption[]; }; /** * @deprecated Use AgentRuntimeMessagePresentation. */ type AgentRuntimeInteractiveReply = { blocks: AgentRuntimeInteractiveReplyBlock[]; }; /** Portable reply presentation severity/style hint. */ type AgentRuntimeMessagePresentationTone = "info" | "success" | "warning" | "danger" | "neutral"; /** Portable structured reply block rendered or downgraded by channels. */ type AgentRuntimeMessagePresentationBlock = { type: "text"; text: string; } | { type: "context"; text: string; } | { type: "divider"; } | { type: "buttons"; buttons: AgentRuntimeMessagePresentationButton[]; } | { type: "select"; placeholder?: string; options: AgentRuntimeMessagePresentationOption[]; }; /** Portable structured reply presentation for channel adapters. */ type AgentRuntimeMessagePresentation = { /** Optional short heading rendered before blocks when supported. */title?: string; /** Optional severity/status tone for renderers that support toned presentations. */ tone?: AgentRuntimeMessagePresentationTone; /** Ordered portable blocks rendered or downgraded by channel adapters. */ blocks: AgentRuntimeMessagePresentationBlock[]; }; /** Delivery pin options attached to runtime reply payloads. */ type AgentRuntimeReplyPayloadDeliveryPin = { enabled: boolean; notify?: boolean; required?: boolean; }; /** Delivery instructions attached to runtime reply payloads. */ type AgentRuntimeReplyPayloadDelivery = { pin?: boolean | AgentRuntimeReplyPayloadDeliveryPin; }; /** Portable reply payload emitted by agent runtimes before channel rendering. */ type AgentRuntimeReplyPayload = { text?: string; mediaUrl?: string; mediaUrls?: string[]; trustedLocalMedia?: boolean; sensitiveMedia?: boolean; presentation?: AgentRuntimeMessagePresentation; delivery?: AgentRuntimeReplyPayloadDelivery; /** * @deprecated Use presentation. */ interactive?: AgentRuntimeInteractiveReply; btw?: { question: string; }; replyToId?: string; replyToTag?: boolean; replyToCurrent?: boolean; audioAsVoice?: boolean; spokenText?: string; ttsSupplement?: { spokenText: string; visibleTextAlreadyDelivered?: boolean; }; isError?: boolean; isReasoning?: boolean; /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */ isCommentary?: boolean; isReasoningSnapshot?: boolean; isCompactionNotice?: boolean; isFallbackNotice?: boolean; isStatusNotice?: boolean; channelData?: Record; }; /** Stable section IDs for provider system prompt overrides. */ type AgentRuntimeSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; /** Provider-owned system prompt contribution and section overrides. */ type AgentRuntimeSystemPromptContribution = { stablePrefix?: string; dynamicSuffix?: string; sectionOverrides?: Partial>; }; /** Context passed when resolving provider system prompt contributions. */ type AgentRuntimeSystemPromptContributionContext = { config?: AgentRuntimeConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; promptMode: AgentRuntimePromptMode; runtimeChannel?: string; runtimeCapabilities?: string[]; agentId?: string; trigger?: AgentRuntimePromptTrigger; }; /** Provider fallback route decision for follow-up delivery. */ type AgentRuntimeFollowupFallbackRouteResult = { route?: "origin" | "dispatcher" | "drop"; reason?: string; }; /** Tool-call id sanitizer mode for provider transcript policy. */ type AgentRuntimeToolCallIdMode = "strict" | "strict9"; /** Provider transcript sanitation, repair, and validation policy. */ type AgentRuntimeTranscriptPolicy = { sanitizeMode: "full" | "images-only"; sanitizeToolCallIds: boolean; toolCallIdMode?: AgentRuntimeToolCallIdMode; duplicateToolCallIdStyle?: "openai"; preserveNativeAnthropicToolUseIds: boolean; repairToolUseResultPairing: boolean; preserveSignatures: boolean; sanitizeThoughtSignatures?: { allowBase64Only?: boolean; includeCamelCase?: boolean; }; sanitizeThinkingSignatures: boolean; dropThinkingBlocks: boolean; dropReasoningFromHistory?: boolean; applyGoogleTurnOrdering: boolean; validateGeminiTurns: boolean; validateAnthropicTurns: boolean; allowSyntheticToolResults: boolean; }; /** Classified model-call failure or success observation for fallback. */ type AgentRuntimeOutcomeClassification = { message: string; reason?: AgentRuntimeFailoverReason; status?: number; code?: string; rawError?: string; } | { error: unknown; } | null | undefined; /** Runtime hook that classifies run results for model fallback. */ type AgentRuntimeOutcomeClassifier = (params: { provider: string; model: string; result: unknown; hasDirectlySentBlockReply?: boolean; hasBlockReplyPipelineOutput?: boolean; }) => AgentRuntimeOutcomeClassification; /** Resolved provider/model/harness/transport reference for an attempt. */ type AgentRuntimeResolvedRef = { provider: string; modelId: string; modelApi?: string; harnessId?: string; transport?: AgentRuntimeTransport; }; /** Auth forwarding decision for one runtime attempt. */ type AgentRuntimeAuthPlan = { providerForAuth: string; authProfileProviderForAuth: string; harnessAuthProvider?: string; forwardedAuthProfileId?: string; forwardedAuthProfileCandidateIds?: string[]; }; /** Prompt transforms and provider contribution hooks for one runtime attempt. */ type AgentRuntimePromptPlan = { provider: string; modelId: string; textTransforms?: AgentRuntimeTextTransforms; resolveSystemPromptContribution(context: AgentRuntimeSystemPromptContributionContext): AgentRuntimeSystemPromptContribution | undefined; transformSystemPrompt(context: AgentRuntimeSystemPromptContributionContext & { systemPrompt: string; }): string; }; /** Prepared plugin metadata snapshot kept opaque to runtime-plan consumers. */ type AgentRuntimePreparedMetadataSnapshot = object; /** Prepared metadata loader used by tool planning without eager manifest reads. */ type PreparedOpenClawToolPlanning = { metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot; loadMetadataSnapshot?: () => AgentRuntimePreparedMetadataSnapshot; }; /** Tool normalization and diagnostics hooks for one runtime attempt. */ type AgentRuntimeToolPlan = { preparedPlanning?: PreparedOpenClawToolPlanning; normalize(tools: AgentTool[], params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): AgentTool[]; logDiagnostics(tools: AgentTool[], params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): void; }; /** Delivery behavior hooks for one runtime attempt. */ type AgentRuntimeDeliveryPlan = { isSilentPayload(payload: Pick): boolean; resolveFollowupRoute(params: { payload: AgentRuntimeReplyPayload; originatingChannel?: string; originatingTo?: string; originRoutable: boolean; dispatcherAvailable: boolean; }): AgentRuntimeFollowupFallbackRouteResult | undefined; }; /** Outcome classification hooks for one runtime attempt. */ type AgentRuntimeOutcomePlan = { classifyRunResult: AgentRuntimeOutcomeClassifier; }; /** Extra transport parameter plan for one runtime attempt. */ type AgentRuntimeTransportPlan = { extraParams: Record; resolveExtraParams(params?: { extraParamsOverride?: Record; thinkingLevel?: AgentRuntimeThinkLevel; agentId?: string; workspaceDir?: string; model?: AgentRuntimeModel; resolvedTransport?: AgentRuntimeTransport; }): Record; }; /** Complete prepared runtime plan consumed by embedded-agent attempts. */ type AgentRuntimePlan = { resolvedRef: AgentRuntimeResolvedRef; providerRuntimeHandle?: AgentRuntimeProviderHandle; auth: AgentRuntimeAuthPlan; prompt: AgentRuntimePromptPlan; tools: AgentRuntimeToolPlan; transcript: { policy: AgentRuntimeTranscriptPolicy; resolvePolicy(params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): AgentRuntimeTranscriptPolicy; }; delivery: AgentRuntimeDeliveryPlan; outcome: AgentRuntimeOutcomePlan; transport: AgentRuntimeTransportPlan; observability: { resolvedRef: string; provider: string; modelId: string; modelApi?: string; harnessId?: string; authProfileId?: string; transport?: AgentRuntimeTransport; }; }; /** Inputs needed to build the full prepared runtime plan. */ type BuildAgentRuntimePlanParams = { config?: AgentRuntimeConfig; workspaceDir?: string; agentDir?: string; provider: string; modelId: string; model?: AgentRuntimeModel; modelApi?: string | null; harnessId?: string; harnessRuntime?: string; allowHarnessAuthProfileForwarding?: boolean; authProfileProvider?: string; authProfileMode?: string; sessionAuthProfileId?: string; sessionAuthProfileCandidateIds?: string[]; agentId?: string; thinkingLevel?: AgentRuntimeThinkLevel; extraParamsOverride?: Record; resolvedTransport?: AgentRuntimeTransport; providerRuntimeHandle?: AgentRuntimeProviderHandle; }; //#endregion //#region src/agents/tool-mutation.d.ts type FileTarget = { path?: string; oldpath?: string; }; /** Return true only for tool calls whose structured contract proves replay safety. */ declare function isReplaySafeToolCall(toolName: string, args: unknown): boolean; //#endregion //#region src/agents/tool-error-summary.d.ts type ToolErrorSummary = { toolName: string; meta?: string; errorCode?: string; error?: string; validationErrorSummary?: string; timedOut?: boolean; middlewareError?: boolean; mutatingAction?: boolean; actionFingerprint?: string; fileTarget?: FileTarget; }; //#endregion //#region src/agents/embedded-agent-runner/replay-state.d.ts /** * Tracks whether an embedded run can be replayed after compaction or retry. */ type EmbeddedRunReplayState = { replayInvalid: boolean; hadPotentialSideEffects: boolean; }; /** Serializable replay metadata stored with run results. */ type EmbeddedRunReplayMetadata = { hadPotentialSideEffects: boolean; replaySafe: boolean; }; //#endregion //#region src/agents/embedded-agent-runner/run/preemptive-compaction.types.d.ts /** * Route chosen before a model call when context pressure may require compaction or truncation. */ type PreemptiveCompactionRoute = "fits" | "compact_only" | "truncate_tool_results_only" | "compact_then_truncate"; //#endregion //#region src/agents/embedded-agent-runner/run/types.d.ts type EmbeddedRunAttemptBase = Omit; type EmbeddedRunContextWindowInfo = { tokens: number; referenceTokens?: number; source: "model" | "modelsConfig" | "agentContextTokens" | "default"; }; type EmbeddedRunFastModeParam = boolean | (() => boolean | undefined); type EmbeddedRunAttemptParams = EmbeddedRunAttemptBase & { /** Active file-backed artifact target resolved by the run/session target seam. */sessionFile: string; initialReplayState?: EmbeddedRunReplayState; /** Pluggable context engine for ingest/assemble/compact lifecycle. */ contextEngine?: ContextEngine; /** Resolved model context window in tokens for assemble/compact budgeting. */ contextTokenBudget?: number; /** Source metadata for the resolved model context budget. */ contextWindowInfo?: EmbeddedRunContextWindowInfo; /** Resolved API key for this run when runtime auth did not replace it. */ resolvedApiKey?: string; /** Auth profile resolved for this attempt's provider/model call. */ authProfileId?: string; /** Source for the resolved auth profile (user-locked or automatic). */ authProfileIdSource?: "auto" | "user"; provider: string; modelId: string; /** Operator-requested or initial model id before any fallback resolution. */ requestedModelId?: string | null; /** True when this attempt is running after a model fallback decision. */ fallbackActive?: boolean; /** Concrete fallback reason that selected this attempt, when known. */ fallbackReason?: string | null; /** Concrete degraded-runtime reason for this attempt, when known. */ degradedReason?: string | null; /** Session-pinned embedded harness id. Prevents runtime hot-switching. */ agentHarnessId?: string; /** OpenClaw-owned runtime policy prepared by the orchestrator for this attempt. */ runtimePlan?: AgentRuntimePlan; /** Host-issued scope for harnesses that mirror native child runs into task state. */ agentHarnessTaskRuntimeScope?: AgentHarnessTaskRuntimeScope; /** Live observer called after wrapped tool outcomes are recorded. */ onToolOutcome?: ToolOutcomeObserver; /** Signals that the attempt's own run-timeout watchdog is active. */ onAttemptTimeoutArmed?: () => void; /** Signals that this attempt's timeout has fired and must unwind promptly. */ onAttemptTimeout?: (reason: Error) => void; /** Signals an explicit cancellation through the active native run handle. */ onAttemptAbort?: () => void; /** Supplies run-global model-call ordering for parallel tool outcomes. */ allocateToolOutcomeOrdinal?: (toolCallId?: string) => number; model: Model$1; authStorage: AuthStorage; /** Auth profile store already resolved during startup for this attempt. */ authProfileStore: AuthProfileStore; /** * Full auth profile store for OpenClaw tool availability. * Plugin-owned harnesses may scope `authProfileStore` to model transport credentials. */ toolAuthProfileStore?: AuthProfileStore; modelRegistry: ModelRegistry$1; thinkLevel: ThinkLevel; fastMode?: EmbeddedRunFastModeParam; /** True when this attempt is running the auto fast-mode policy. */ fastModeAuto?: boolean; beforeAgentStartResult?: PluginHookBeforeAgentStartResult; beforeAgentFinalizeRevisionAttempts?: number; maxBeforeAgentFinalizeRevisions?: number; }; type EmbeddedRunAttemptResult = { aborted: boolean; /** True when the runtime made the authoritative final-assistant transcript decision. */ assistantTranscriptOwned?: boolean; /** True when the abort originated from the caller-provided abortSignal. */ externalAbort: boolean; timedOut: boolean; /** True when the no-response LLM idle watchdog caused the timeout. */ idleTimedOut: boolean; /** True if the timeout occurred while compaction was in progress or pending. */ timedOutDuringCompaction: boolean; /** Optional because this type is re-exported as `AgentHarnessAttemptResult`. */ timedOutDuringToolExecution?: boolean; timedOutByRunBudget?: boolean; promptError: unknown; /** * Identifies which phase produced the promptError. * - "prompt": the LLM call itself failed and may be eligible for retry/fallback. * - "compaction": the prompt succeeded, but waiting for compaction/retry teardown was aborted; * this must not be retried as a fresh prompt or the same tool turn can replay. * - "precheck": pre-prompt overflow recovery intentionally short-circuited the prompt so the * outer run loop can recover via compaction/truncation before any model call is made. * - "hook:before_agent_run": a lifecycle hook blocked the run before the prompt was sent. * - null: no promptError. */ promptErrorSource: "prompt" | "compaction" | "precheck" | "hook:before_agent_run" | null; preflightRecovery?: { route: Exclude; source?: "mid-turn"; estimatedPromptTokens?: number; promptBudgetBeforeReserve?: number; overflowTokens?: number; handled: true; truncatedCount?: number; } | { route: Exclude; source?: "mid-turn"; estimatedPromptTokens?: number; promptBudgetBeforeReserve?: number; overflowTokens?: number; handled?: false; }; sessionIdUsed: string; sessionFileUsed?: string; diagnosticTrace?: DiagnosticTraceContext; agentHarnessId?: string; agentHarnessResultClassification?: "empty" | "reasoning-only" | "planning-only"; promptTimeoutOutcome?: { message?: string; replayInvalid?: boolean; livenessState?: EmbeddedRunLivenessState; timeoutPhase?: AgentRunTimeoutPhase; providerStarted?: boolean; }; codexAppServerFailure?: { kind: "client_closed_before_turn_completed" | "turn_completion_idle_timeout"; turnWatchTimeoutKind?: "progress" | "completion" | "terminal"; transport: "stdio" | "websocket"; threadId?: string; turnId?: string; replaySafe: boolean; replayBlockedReason?: "assistant_output" | "tool_activity" | "potential_side_effect" | "active_item"; diagnostics?: { idleMs?: number; timeoutMs?: number; lastActivityReason?: string; lastNotificationMethod?: string; lastNotificationItemId?: string; lastNotificationItemType?: string; lastNotificationItemRole?: string; lastAssistantTextPreview?: string; activeAppServerTurnRequests?: number; activeTurnItemCount?: number; terminalTurnNotificationQueued?: boolean; completionIdleWatchArmed?: boolean; assistantCompletionIdleWatchArmed?: boolean; terminalIdleWatchArmed?: boolean; }; }; bootstrapPromptWarningSignaturesSeen?: string[]; bootstrapPromptWarningSignature?: string; systemPromptReport?: SessionSystemPromptReport; finalPromptText?: string; messagesSnapshot: AgentMessage[]; beforeAgentFinalizeRevisionReason?: string; assistantTexts: string[]; lastAssistantTextMessageIndex?: number; toolMetas: Array<{ toolName: string; meta?: string; replaySafe?: boolean; asyncStarted?: boolean; asyncTaskRunId?: string; asyncTaskId?: string; }>; acceptedSessionSpawns?: AcceptedSessionSpawn[]; lastAssistant: AssistantMessage | undefined; currentAttemptAssistant?: AssistantMessage | undefined; lastToolError?: ToolErrorSummary; didSendViaMessagingTool: boolean; didDeliverSourceReplyViaMessageTool?: boolean; didSendDeterministicApprovalPrompt?: boolean; messagingToolSentTexts: string[]; messagingToolSentMediaUrls: string[]; messagingToolSentTargets: MessagingToolSend[]; messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[]; heartbeatToolResponse?: HeartbeatToolResponse; toolMediaUrls?: string[]; toolAudioAsVoice?: boolean; toolTrustedLocalMedia?: boolean; hasToolMediaBlockReply?: boolean; successfulCronAdds?: number; cloudCodeAssistFormatError: boolean; attemptUsage?: NormalizedUsage; promptCache?: ContextEnginePromptCacheInfo; contextBudgetStatus?: SessionContextBudgetStatus; compactionCount?: number; compactionTokensAfter?: number; /** * Client tool calls detected during this attempt (OpenResponses hosted * tools), in the order the underlying LLM emitted them. Field is * `undefined` when no client tools were called so existing truthiness * checks across the runner pipeline (`attempt.clientToolCalls ? ...`) * keep their meaning. When set, the array always has at least one entry. */ clientToolCalls?: Array<{ name: string; params: Record; }>; /** True when sessions_yield tool was called during this attempt. */ yieldDetected?: boolean; replayMetadata: EmbeddedRunReplayMetadata; itemLifecycle: { startedCount: number; completedCount: number; activeCount: number; }; setTerminalLifecycleMeta?: (meta: { replayInvalid?: boolean; livenessState?: EmbeddedRunLivenessState; stopReason?: string; yielded?: boolean; timeoutPhase?: AgentRunTimeoutPhase; providerStarted?: boolean; aborted?: boolean; }) => void; }; //#endregion //#region src/agents/embedded-agent-runner/compact.types.d.ts type CompactEmbeddedAgentSessionParams = { sessionId: string; runId?: string; sessionKey?: string; /** Storage-neutral transcript/session target. Defaults to sessionId/sessionKey/agentId. */ sessionTarget?: AgentRunSessionTarget; /** Caller-resolved owner agent for global session aliases. */ agentId?: string; /** Session key used only for runtime policy/sandbox resolution. Defaults to sessionKey. */ sandboxSessionKey?: string; messageChannel?: string; messageProvider?: string; chatType?: ChatType; agentAccountId?: string; currentChannelId?: string; currentThreadTs?: string; currentMessageId?: string | number; /** Trusted sender id from inbound context for scoped message-tool discovery. */ senderId?: string; senderName?: string; senderUsername?: string; senderE164?: string; authProfileId?: string; /** Host-resolved provider credential for native harness compaction. */ resolvedApiKey?: string; /** Group id for channel-level tool policy resolution. */ groupId?: string | null; /** Group channel label (e.g. #general) for channel-level tool policy resolution. */ groupChannel?: string | null; /** Group space label (e.g. guild/team id) for channel-level tool policy resolution. */ groupSpace?: string | null; /** Parent session key for subagent policy inheritance. */ spawnedBy?: string | null; sessionFile: string; /** Optional caller-observed live prompt tokens used for compaction diagnostics. */ currentTokenCount?: number; workspaceDir: string; /** Optional task working directory; workspaceDir remains the agent bootstrap workspace. */ cwd?: string; agentDir?: string; config?: OpenClawConfig; skillsSnapshot?: SkillSnapshot; senderIsOwner?: boolean; provider?: string; model?: string; /** Caller-resolved model/provider shape used by native harness compactors. */ runtimeModel?: Model; /** Effective model fallback chain for this session attempt. Undefined uses config defaults. */ modelFallbacksOverride?: string[]; /** Optional caller-resolved context engine for harness-owned compaction. */ contextEngine?: ContextEngine; /** Optional caller-resolved token budget for harness-owned compaction. */ contextTokenBudget?: number; /** Optional caller-resolved runtime context for harness-owned context-engine compaction. */ contextEngineRuntimeContext?: ContextEngineRuntimeContext; /** Session-pinned embedded harness id. Prevents compaction hot-switching. */ agentHarnessId?: string; /** OpenClaw-owned runtime policy prepared for this compaction path. */ runtimePlan?: AgentRuntimePlan; thinkLevel?: ThinkLevel; reasoningLevel?: ReasoningLevel; execOverrides?: Pick; bashElevated?: ExecElevatedDefaults; customInstructions?: string; tokenBudget?: number; force?: boolean; /** Force compaction because the caller already determined this turn must compact before prompt submission. */ forcePreflight?: boolean; /** Alias for forcePreflight used by preflight budget gates. */ preflightRequired?: boolean; /** Diagnostic trigger that made preflight compaction mandatory. */ preflightCompactionTrigger?: "tokens" | "transcript_bytes"; trigger?: "budget" | "overflow" | "manual"; /** * Preflight callers can allow native/current-session harness compaction but * move plugin-owned budget compaction onto background turn maintenance. */ deferOwningContextEngineCompaction?: boolean; diagId?: string; attempt?: number; maxAttempts?: number; lane?: string; enqueue?: CommandQueueEnqueueFn; extraSystemPrompt?: string; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; ownerNumbers?: string[]; abortSignal?: AbortSignal; onCompactionHookMessages?: (payload: { phase: "before" | "after"; messages: string[]; sessionId: string; sessionKey: string; }) => void | Promise; /** Allow runtime plugins for this compaction to late-bind the gateway subagent. */ allowGatewaySubagentBinding?: boolean; /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */ oneShotCliRun?: boolean; }; //#endregion //#region src/agents/harness/types.d.ts /** * Public native agent harness contracts and capability shapes. */ type AgentHarnessSupportContext = { provider: string; modelId?: string; modelProvider?: { api?: string; baseUrl?: string; azureApiVersion?: string; request?: { auth?: { mode?: unknown; }; proxy?: unknown; tls?: unknown; allowPrivateNetwork?: unknown; }; }; requestedRuntime: EmbeddedAgentRuntime; providerOwnerStatus?: "unowned" | "owned" | "ambiguous"; providerOwnerPluginIds?: readonly string[]; }; type AgentHarnessSupport = { supported: true; priority?: number; reason?: string; } | { supported: false; reason?: string; }; type AgentHarnessAttemptParams = EmbeddedRunAttemptParams; type AgentHarnessAttemptResult = EmbeddedRunAttemptResult; type AgentHarnessSideQuestionParams = { cfg: OpenClawConfig; agentDir: string; provider: string; model: string; runtimeModel?: import("openclaw/plugin-sdk/llm").Model; question: string; sessionEntry: SessionEntry; sessionStore?: Record; sessionKey?: string; storePath?: string; resolvedThinkLevel?: ThinkLevel; resolvedReasoningLevel: ReasoningLevel; blockReplyChunking?: BlockReplyChunking; resolvedBlockStreamingBreak?: "text_end" | "message_end"; opts?: GetReplyOptions; isNewSession: boolean; sessionId: string; sessionFile: string; sandboxSessionKey?: string; agentId?: string; workspaceDir?: string; messageChannel?: string; messageProvider?: string; agentAccountId?: string; messageTo?: string; messageThreadId?: string | number; groupId?: string | null; groupChannel?: string | null; groupSpace?: string | null; memberRoleIds?: string[]; spawnedBy?: string | null; senderId?: string | null; senderName?: string | null; senderUsername?: string | null; senderE164?: string | null; senderIsOwner?: boolean; currentChannelId?: string; toolsAllow?: string[]; authProfileId?: string; authProfileIdSource?: "auto" | "user"; }; type AgentHarnessSideQuestionResult = { text: string; }; type AgentHarnessCompactParams = CompactEmbeddedAgentSessionParams; type AgentHarnessCompactResult = EmbeddedAgentCompactResult; type AgentHarnessResetParams = { agentId?: string; sessionId?: string; sessionKey?: string; sessionFile?: string; reason?: "new" | "reset" | "idle" | "daily" | "compaction" | "deleted" | "unknown"; }; type AgentHarnessResultClassification = "ok" | NonNullable; type AgentHarnessDeliveryDefaults = { /** * @deprecated Prefer `messages.visibleReplies` / `messages.groupChat.visibleReplies` * config. Kept for existing harness plugins. */ sourceVisibleReplies?: "automatic" | "message_tool"; }; type AgentHarnessRunCapability = { id: string; label: string; pluginId?: string; /** * Context-engine host capabilities provided by this harness during agent * runs. Harnesses that omit this are unsupported for engines that declare * host requirements. */ contextEngineHostCapabilities?: readonly ContextEngineHostCapability[]; deliveryDefaults?: AgentHarnessDeliveryDefaults; supports(ctx: AgentHarnessSupportContext): AgentHarnessSupport; runAttempt(params: AgentHarnessAttemptParams): Promise; }; type AgentHarnessSideQuestionCapability = { runSideQuestion?(params: AgentHarnessSideQuestionParams): Promise; }; type AgentHarnessClassificationCapability = { classify?(result: AgentHarnessAttemptResult, ctx: AgentHarnessAttemptParams): AgentHarnessResultClassification | undefined; }; type AgentHarnessCompactionCapability = { compact?(params: AgentHarnessCompactParams): Promise; }; type AgentHarnessSessionLifecycleCapability = { reset?(params: AgentHarnessResetParams): Promise | void; dispose?(): Promise | void; }; type AgentHarness = AgentHarnessRunCapability & AgentHarnessSideQuestionCapability & AgentHarnessClassificationCapability & AgentHarnessCompactionCapability & AgentHarnessSessionLifecycleCapability; //#endregion //#region src/gateway/chat-queued-turns.d.ts type QueuedChatTurnEntry = { controller: AbortController; sessionId: string; sessionKey: string; /** False once collect-mode transfers cancellation to the aggregate owner. */ abortable?: boolean; agentId?: string; ownerConnId?: string; ownerDeviceId?: string; }; //#endregion //#region src/agents/web-search-tool-policy.d.ts type WebSearchToolPolicyParams = { config?: OpenClawConfig; modelProvider?: string; modelId?: string; agentId?: string; sessionKey?: string; sandboxToolPolicy?: SandboxToolPolicy; messageProvider?: string; agentAccountId?: string | null; groupId?: string | null; groupChannel?: string | null; groupSpace?: string | null; spawnedBy?: string | null; senderId?: string | null; senderName?: string | null; senderUsername?: string | null; senderE164?: string | null; }; type WebSearchToolPolicyResolution = { allowed: boolean; persistentAllowed: boolean; }; /** Resolves current and sender-independent policy for the managed web_search tool. */ declare function resolveWebSearchToolPolicy(params: WebSearchToolPolicyParams): WebSearchToolPolicyResolution; //#endregion //#region src/agents/embedded-agent-runner/run-state.d.ts /** * Shared process state for embedded-agent runs, queues, and snapshots. * * The maps are global-singleton backed so reloads and lazy imports inside the same gateway process * do not split active-run bookkeeping. */ type EmbeddedAgentQueueHandle = { kind?: "embedded"; runId?: string; queueMessage: (text: string, options?: EmbeddedAgentQueueMessageOptions) => Promise; isStreaming: () => boolean; isStopped?: () => boolean; isAbortable?: () => boolean; isCompacting: () => boolean; supportsTranscriptCommitWait?: boolean; cancel?: (reason?: "user_abort" | "restart" | "superseded") => void; abort: (reason?: "restart") => void; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; }; type EmbeddedAgentQueueMessageOptions = ReplyBackendQueueMessageOptions; /** Resolves the current session id for an active run after resets or compaction. */ declare function resolveActiveEmbeddedRunSessionId(sessionKey: string): string | undefined; //#endregion //#region src/agents/embedded-agent-runner/runs.d.ts type EmbeddedAgentQueueFailureReason = "no_active_run" | "not_streaming" | "compacting" | "source_reply_delivery_mode_mismatch" | "transcript_commit_wait_unsupported" | "runtime_rejected"; type EmbeddedAgentQueueMessageOutcome = { queued: true; sessionId: string; target: "embedded_run" | "reply_run"; gatewayHealth: "live"; deliveredAtMs?: number; enqueuedAtMs?: number; } | { queued: false; sessionId: string; reason: EmbeddedAgentQueueFailureReason; gatewayHealth: "live"; errorMessage?: string; }; /** * Abort embedded OpenClaw runs. * * - With a sessionId, aborts that single run. * - With no sessionId, supports targeted abort modes (for example, compacting runs only). */ declare function abortEmbeddedAgentRun(sessionId: string): boolean; declare function abortEmbeddedAgentRun(sessionId: undefined, opts: { mode: "all" | "compacting"; reason?: "restart"; }): boolean; type AbortAndDrainEmbeddedAgentRunResult = { aborted: boolean; drained: boolean; forceCleared: boolean; }; declare function abortAndDrainEmbeddedAgentRun(params: { sessionId: string; sessionKey?: string; settleMs?: number; forceClear?: boolean; reason?: string; }): Promise; declare function setActiveEmbeddedRun(sessionId: string, handle: EmbeddedAgentQueueHandle, sessionKey?: string, sessionFile?: string): void; declare function clearActiveEmbeddedRun(sessionId: string, handle: EmbeddedAgentQueueHandle, sessionKey?: string, sessionFile?: string, reason?: string): void; //#endregion //#region src/agents/bash-tools.process.d.ts /** Defaults injected by tests, agent scopes, and scoped process registries. */ type ProcessToolDefaults = { cleanupMs?: number; hasCronTool?: boolean; inputWaitIdleMs?: number; scopeKey?: string; }; //#endregion //#region src/agents/spawned-context.d.ts type SpawnedRunMetadata = { spawnedBy?: string | null; groupId?: string | null; groupChannel?: string | null; groupSpace?: string | null; workspaceDir?: string | null; }; //#endregion //#region src/agents/command/types.d.ts /** Image content block for Claude API multimodal messages. */ type ImageContent$1 = { type: "image"; data: string; mimeType: string; }; /** Metadata overrides for trusted internal agent command callers. */ type AgentCommandResultMetaOverrides = { transport?: "embedded"; fallbackFrom?: "gateway"; fallbackReason?: "gateway_timeout"; fallbackSessionId?: string; fallbackSessionKey?: string; }; /** ACP turn source markers accepted by trusted command callsites. */ type AcpTurnSource = "manual_spawn"; /** Channel/account/thread context carried into an agent run. */ type AgentRunContext = { messageChannel?: string; accountId?: string; groupId?: string | null; groupChannel?: string | null; groupSpace?: string | null; currentChannelId?: string; /** Transport-native chat/conversation ID for plugin hook identity context. */ chatId?: string; /** Channel-specific sender/chat metadata for plugin hook identity context. */ channelContext?: PluginHookChannelContext; currentThreadTs?: string; currentInboundAudio?: boolean; senderId?: string | null; replyToMode?: "off" | "first" | "all" | "batched"; hasRepliedRef?: { value: boolean; }; }; /** Full trusted option surface for running an agent command. */ type AgentCommandOpts = { message: string; /** User-visible transcript body; defaults to message and excludes runtime-only context. */ transcriptMessage?: string; /** Durable media metadata for the user-visible transcript turn. */ transcriptMedia?: UserTurnInput["media"]; /** Optional image attachments for multimodal messages. */ images?: ImageContent$1[]; /** Original inline/offloaded attachment order for inbound images. */ imageOrder?: PromptImageOrderEntry[]; /** Optional client-provided tools (OpenResponses hosted tools). */ clientTools?: ClientToolDefinition[]; /** Agent id override (must exist in config). */ agentId?: string; /** Per-run provider override. */ provider?: string; /** Per-run model override. */ model?: string; to?: string; sessionId?: string; sessionKey?: string; thinking?: string; thinkingOnce?: string; verbose?: string; json?: boolean; timeout?: string; deliver?: boolean; /** Override delivery target (separate from session routing). */ replyTo?: string; /** Override delivery channel (separate from session routing). */ replyChannel?: string; /** Override delivery account id (separate from session routing). */ replyAccountId?: string; /** Override delivery thread/topic id (separate from session routing). */ threadId?: string | number; /** Message channel context. */ messageChannel?: string; /** Tool-policy/output surface context. Defaults to messageChannel. */ messageProvider?: string; /** Delivery channel. */ channel?: string; /** Account ID for multi-account channel routing. */ accountId?: string; /** Context for embedded run routing (channel/account/thread). */ runContext?: AgentRunContext; /** Device-scoped operator session allowed to review approvals initiated by this run. */ approvalReviewerDeviceId?: string; /** Internal trusted exec approval follow-up elevated defaults. */ bashElevated?: ExecElevatedDefaults; /** Trusted sender identity bit for command/channel-action auth; defaults true for local CLI calls. */ senderIsOwner?: boolean; /** Whether this caller is authorized to use provider/model per-run overrides. */ allowModelOverride?: boolean; /** Optional runtime tool allow-list; when set, only these tools are exposed for this run. */ toolsAllow?: string[]; /** Group/spawn metadata for subagent policy inheritance and routing context. */ groupId?: SpawnedRunMetadata["groupId"]; groupChannel?: SpawnedRunMetadata["groupChannel"]; groupSpace?: SpawnedRunMetadata["groupSpace"]; spawnedBy?: SpawnedRunMetadata["spawnedBy"]; deliveryTargetMode?: ChannelOutboundTargetMode; bestEffortDeliver?: boolean; abortSignal?: AbortSignal; lane?: string; runId?: string; /** Immutable gateway lifecycle ownership captured when this run was admitted. */ lifecycleGeneration?: string; extraSystemPrompt?: string; /** Bootstrap workspace context injection mode for this run. */ bootstrapContextMode?: "full" | "lightweight"; /** Run kind hint for bootstrap context behavior. */ bootstrapContextRunKind?: BootstrapContextRunKind; internalEvents?: AgentInternalEvent[]; inputProvenance?: InputProvenance; /** Internal runs can execute against a session without updating visible status/model/usage. */ sessionEffects?: "visible" | "internal"; /** Internal handoffs can write transcript turns without changing user-facing model/usage state. */ preserveUserFacingSessionModelState?: boolean; /** Visible source replies must be sent through the message tool when set. */ sourceReplyDeliveryMode?: SourceReplyDeliveryMode; /** Internal runs can omit the channel message tool entirely. */ disableMessageTool?: boolean; /** Gateway ingress that already persisted visible activity can skip the duplicate pre-run touch. */ skipInitialSessionTouch?: boolean; /** Per-call stream param overrides (best-effort). */ streamParams?: AgentStreamParams; /** Resolved per-run fast mode from channel/directive handling. */ fastMode?: FastMode; /** Resolved per-run auto cutoff seconds for fast mode. */ fastModeAutoOnSeconds?: number; /** Explicit workspace directory override (for subagents to inherit parent workspace). */ workspaceDir?: SpawnedRunMetadata["workspaceDir"]; /** Explicit task working directory for this run. Bootstrap still uses workspaceDir. */ cwd?: string; /** Force bundled MCP teardown when a one-shot local run completes. */ cleanupBundleMcpOnRunEnd?: boolean; /** Force long-lived CLI live session teardown when a one-shot local run completes. */ cleanupCliLiveSessionOnRunEnd?: boolean; /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */ oneShotCliRun?: boolean; /** Gateway-owned runs can late-bind plugin subagent and node runtime helpers. */ allowGatewaySubagentBinding?: boolean; /** Internal local CLI callers can annotate result metadata before JSON/text output. */ resultMetaOverrides?: AgentCommandResultMetaOverrides; /** Called when the actual run model is selected, including fallback retries. */ onActiveModelSelected?: (ctx: { provider: string; model: string; }) => void; /** Called when compaction rotates the active run onto a successor session. */ onSessionIdChanged?: (sessionId: string) => void; /** Internal one-shot model probe mode: no tools, no workspace/chat prompt policy. */ modelRun?: boolean; /** Internal prompt-mode override for trusted local/gateway callsites. */ promptMode?: PromptMode; /** Internal ACP-ready session turn source. Manual spawn turns bypass only the dispatch gate. */ acpTurnSource?: AcpTurnSource; /** Internal handoffs can feed the model without writing the synthetic prompt to transcript. */ suppressPromptPersistence?: boolean; }; /** Restricted option surface for external ingress callsites. */ type AgentCommandIngressOpts = Omit & { /** Trusted sender identity bit for command/channel-action auth; defaults false for ingress. */senderIsOwner?: boolean; /** Ingress callsites must always pass explicit model-override authorization state. */ allowModelOverride: boolean; }; //#endregion //#region src/plugins/cli-backend.types.d.ts type PluginTextReplacement = { from: string | RegExp; to: string; }; type PluginTextTransforms = { /** Rewrites applied to outbound prompt text before provider/CLI transport. */input?: PluginTextReplacement[]; /** Rewrites applied to inbound assistant text before OpenClaw consumes it. */ output?: PluginTextReplacement[]; }; type CliBundleMcpMode = "claude-config-file" | "codex-config-overrides" | "gemini-system-settings"; type CliBackendPrepareExecutionContext = { config?: OpenClawConfig; workspaceDir: string; agentDir?: string; provider: string; modelId: string; authProfileId?: string; executionMode?: CliBackendExecutionMode; }; type CliBackendPreparedExecution = { env?: Record; clearEnv?: string[]; /** * Backend-owned staging that must run after the core CLI queue admits the turn. * Use this for mutable per-profile CLI homes that the launched process also owns. */ beforeExecution?: () => Promise; cleanup?: () => Promise; }; type CliBackendThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; type CliBackendExecutionMode = "agent" | "side-question"; type CliBackendResolveExecutionArgsContext = { config?: OpenClawConfig; workspaceDir: string; provider: string; modelId: string; authProfileId?: string; thinkingLevel?: CliBackendThinkingLevel; executionMode?: CliBackendExecutionMode; useResume: boolean; baseArgs: readonly string[]; }; type CliBackendResolveExecutionArgs = (ctx: CliBackendResolveExecutionArgsContext) => readonly string[] | null | undefined; type CliBackendAuthEpochMode = "combined" | "profile-only"; type CliBackendNativeToolMode = "none" | "always-on"; type CliBackendSideQuestionToolMode = "disabled"; type CliBackendNormalizeConfigContext = { config?: OpenClawConfig; backendId: string; agentId?: string; }; /** Plugin-owned CLI backend defaults used by the text-only CLI runner. */ type CliBackendPlugin$1 = { /** Provider id used in model refs, for example `claude-cli/opus`. */id: string; /** Canonical model provider whose models this CLI backend can execute. */ modelProvider?: string; /** Default backend config before user overrides from `agents.defaults.cliBackends`. */ config: CliBackendConfig; /** * Context-engine host capabilities provided by this backend when it is * driven through the generic CLI runner. */ contextEngineHostCapabilities?: readonly ContextEngineHostCapability[]; /** * Backend-owned compaction for non-harness CLI sessions. * Set only when the backend bounds its own transcript and persists resumable state. */ ownsNativeCompaction?: boolean; /** * Optional live-smoke metadata owned by the backend plugin. * * Keep provider-specific test wiring here instead of scattering it across * Docker wrappers, docs, and gateway live tests. */ liveTest?: { defaultModelRef?: string; defaultImageProbe?: boolean; defaultMcpProbe?: boolean; docker?: { npmPackage?: string; binaryName?: string; }; }; /** * Whether OpenClaw should inject bundle MCP config for this backend. * * Keep this opt-in. Only backends that explicitly consume OpenClaw's bundle * MCP bridge should enable it. */ bundleMcp?: boolean; /** * Provider-owned bundle MCP integration strategy. * * Different CLIs wire MCP through different surfaces: * - Claude: `--strict-mcp-config --mcp-config` * - Codex: `-c mcp_servers=...` * - Gemini: system-level `settings.json` */ bundleMcpMode?: CliBundleMcpMode; /** * Optional config normalizer applied after user overrides merge. * * Use this for backend-specific compatibility rewrites when old config * shapes need to stay working. */ normalizeConfig?: (config: CliBackendConfig, context?: CliBackendNormalizeConfigContext) => CliBackendConfig; /** * Backend-owned final system-prompt transform. * * Use this for tiny CLI-specific compatibility rewrites without replacing * the generic CLI runner or prompt builder. */ transformSystemPrompt?: (ctx: { config?: OpenClawConfig; workspaceDir?: string; provider: string; modelId: string; modelDisplay: string; agentId?: string; systemPrompt: string; }) => string | null | undefined; /** * Backend-owned bidirectional text replacements. * * `input` applies to the system prompt and user prompt passed to the CLI. * `output` applies to parsed/streamed assistant text from the CLI. */ textTransforms?: PluginTextTransforms; /** * Preferred auth-profile id when the caller did not explicitly lock one. * * Use this when the backend should consume a canonical OpenClaw auth profile * rather than ambient host auth by default. */ defaultAuthProfileId?: string; /** * Session/auth epoch source policy. * * `combined` keeps the legacy "host credential + auth profile" fingerprint. * `profile-only` treats the selected OpenClaw auth profile as the sole auth * owner for session invalidation when one is present. */ authEpochMode?: CliBackendAuthEpochMode; /** * Backend-owned execution bridge. * * Use this on async run paths when the backend needs a generated auth/config * bridge (for example a private CLI home directory) without teaching the core * runner about provider-specific file formats. */ prepareExecution?: (ctx: CliBackendPrepareExecutionContext) => Promise | CliBackendPreparedExecution | null | undefined; /** * Backend-owned per-run argv rewrite. * * Use this for request-scoped CLI dialect flags that should not be modeled * as static config, such as mapping OpenClaw thinking levels to a backend's * native effort flag. */ resolveExecutionArgs?: CliBackendResolveExecutionArgs; /** * Whether this CLI backend can expose native tools outside OpenClaw's tool * catalog. Backends that cannot provide a true no-tools mode must mark * themselves as `always-on` so callers that require disabled tools fail * closed instead of launching a native harness. */ nativeToolMode?: CliBackendNativeToolMode; /** * Side-question native tool behavior. * * Set to `disabled` only when `executionMode: "side-question"` reliably * launches the CLI without native tools, even if normal agent turns expose * backend-owned tools. */ sideQuestionToolMode?: CliBackendSideQuestionToolMode; }; //#endregion //#region src/agents/bootstrap-files.d.ts type BootstrapContextMode = "full" | "lightweight"; /** Resolves hook-adjusted, session-filtered bootstrap files for a run. */ declare function resolveBootstrapFilesForRun(params: { workspaceDir: string; config?: OpenClawConfig; sessionKey?: string; sessionId?: string; agentId?: string; warn?: (message: string) => void; contextMode?: BootstrapContextMode; runKind?: BootstrapContextRunKind; }): Promise; /** Resolves both raw bootstrap metadata and bounded context files for a run. */ declare function resolveBootstrapContextForRun(params: { workspaceDir: string; config?: OpenClawConfig; sessionKey?: string; sessionId?: string; agentId?: string; warn?: (message: string) => void; contextMode?: BootstrapContextMode; runKind?: BootstrapContextRunKind; }): Promise<{ bootstrapFiles: WorkspaceBootstrapFile[]; contextFiles: EmbeddedContextFile[]; }>; /** Builds bounded context files from already-resolved bootstrap file metadata. */ declare function buildBootstrapContextForFiles(bootstrapFiles: WorkspaceBootstrapFile[], params: { config?: OpenClawConfig; agentId?: string | null; warn?: (message: string) => void; }): EmbeddedContextFile[]; //#endregion //#region src/crestodian/agent-turn.d.ts type CrestodianAgentTurnDirective = CrestodianToolDirective; type CrestodianAgentTurnReply = { text: string; modelLabel?: string; /** Interactive handoff the tool requested; the host chat executes it. */ directive?: CrestodianAgentTurnDirective; }; type CrestodianAgentTurnRunner = (params: { input: string; overview: CrestodianOverview; surface: "cli" | "gateway"; /** Host-verified: the user's current message is an explicit approval. */ approvalArmed: boolean; session: CrestodianAgentSession; }) => Promise; type CrestodianAgentSession = { sessionId: string; /** Host-owned pending-proposal fingerprint; see crestodian-tool.ts. */ proposalRef: { current?: string; }; /** Native CLI session id captured after CLI-harness turns for --resume reuse. */ cliSessionId?: string; }; //#endregion //#region src/crestodian/approval-intent.d.ts /** * Approval detection for pending mutations. The host — not the conversation * model — decides whether a turn is armed, so the agent loop can never * self-approve (see crestodian-tool.ts). Users approve in their own words: * unambiguous replies resolve instantly from a closed list, everything else is * judged by a separate single-shot model call that sees only the user's * message and the proposal description, never tool output. When no completion * model is usable the closed list is the whole decision — "other" (the safe * default) keeps the proposal pending and the conversation re-asks. */ type CrestodianApprovalIntent = "approve" | "decline" | "other"; type CrestodianApprovalClassifier = (params: { message: string; /** Human-readable proposal description when the host knows it. */ proposal?: string; }) => Promise; //#endregion //#region src/crestodian/assistant-prompts.d.ts /** One prior conversation turn supplied to the assistant. */ type CrestodianAssistantTurn = { role: "user" | "assistant"; text: string; }; /** Parsed assistant plan before its command is re-validated as an operation. */ type CrestodianAssistantPlan = { command?: string; reply?: string; modelLabel?: string; }; //#endregion //#region src/crestodian/assistant.d.ts type CrestodianAssistantPlanner = (params: { input: string; overview: CrestodianOverview; history?: CrestodianAssistantTurn[]; pendingOperation?: string; }) => Promise; //#endregion //#region src/crestodian/chat-engine.d.ts /** * One conversation with Crestodian, independent of transport. The TUI backend * and the gateway `crestodian.chat` RPC both drive this engine, so onboarding * behaves the same in a terminal and in the macOS app. * * The conversation is AI-only: every message is an AI turn (agent loop first, * single-turn planner as fallback), and approval of pending mutations is * judged from the user's own words by a host-run classifier — never by the * conversation model itself, which cannot self-approve (see * crestodian-tool.ts). The anchored typed-command grammar is not a chat * feature: it only takes over when no model is usable at all (fresh machine, * logged-out CLIs, broken config), so repair keeps working configless. * Hosted wizards resolve deterministically because they are structured forms, * not conversation. */ type CrestodianChatEngineOptions = { yes?: boolean; deps?: CrestodianCommandDeps; planWithAssistant?: CrestodianAssistantPlanner; /** Test seam for the embedded agent-loop turn runner. */ runAgentTurn?: CrestodianAgentTurnRunner; /** Test seam for the approval-intent classifier. */ classifyApproval?: CrestodianApprovalClassifier; /** Where side effects run; the gateway surface never manages its own daemon. */ surface?: "cli" | "gateway"; /** Test seam for the channel-setup wizard hosted by the chat bridge. */ runChannelSetupWizard?: (channel: string, prompter: WizardPrompterLike) => Promise; /** Test seam for model-provider setup hosted by gateway chat. */ runModelSetupWizard?: (workspace: string | undefined, prompter: WizardPrompterLike) => Promise; }; type CrestodianChatReplyAction = "none" | "exit" | "open-tui"; type CrestodianChatReply = { text: string; action: CrestodianChatReplyAction; /** The next hosted-wizard reply contains a secret and must be masked/redacted by hosts. */ sensitive?: boolean; /** Present when the host must leave chat for an interactive handoff. */ handoff?: CrestodianOperation; }; type WizardPrompterLike = WizardPrompter; declare class CrestodianChatEngine { private readonly opts; private pending; private wizardBridge; private readonly history; private readonly agentSession; /** Turns run strictly one at a time; interleaved handles corrupt wizard/pending state. */ private turnQueue; constructor(opts?: CrestodianChatEngineOptions); /** * Seed a proposed operation that the user's next approval will apply. Used * by first-run onboarding: the welcome message states the plan, the user * just agrees. */ propose(operation: CrestodianOperation): string; hasPendingProposal(): boolean; /** Record a host-rendered assistant message (welcome) so AI turns see it. */ noteAssistantMessage(text: string): void; dispose(): Promise; handle(text: string): Promise; private handleSerialized; private resolveTurn; private classifyApprovalIntent; private applyPendingProposal; /** * AI turn: the custodian persona answers and acts through the ring-zero * tool. Falls back to the single-turn planner, then to the anchored typed * grammar when no model backend is usable at all. */ private resolveAssistantTurn; private applyAgentTurnReply; /** * Last resort with zero usable models: the anchored typed grammar keeps * setup/repair working on a fresh or broken machine (docs/cli/crestodian.md, * configless contract). This is never reached while any model answers. */ private resolveDeterministicTurn; private runOperation; loadOverview(): Promise; /** * Post-write hook: re-validate openclaw.json after every applied operation. * On failure the exact schema issues go straight back into the conversation * (and to the AI, which proposes one corrective command) so a bad write is * caught and fixed in the same chat instead of surfacing at gateway start. */ private verifyConfigAfterWrite; private commandDeps; private clearPendingProposals; private armFollowUp; private startChannelSetupWizard; private startModelSetup; /** * "connect telegram" already names the channel; answer the wizard's channel * selection step automatically instead of echoing the full channel wall. */ private tryAutoSelectChannel; /** Advance the hosted wizard to the next interactive step (or completion). */ private pumpWizardBridge; private resolveWizardBridgeReply; } //#endregion //#region src/gateway/server-methods/crestodian.d.ts /** * `crestodian.chat` lets clients (macOS app onboarding, future UIs) run the * same conversational setup as `openclaw crestodian`. It is configless-safe: * the engine answers deterministically before any model is configured, so the * app can onboard a fresh machine entirely through this one method. * * Sessions are process-local by design — Crestodian state is an in-flight * conversation, not persisted data. The map is bounded; the oldest session is * evicted first, and `reset: true` starts a session over explicitly. */ type CrestodianChatSession = { engine: CrestodianChatEngine; welcome: string; lastUsedAt: number; }; //#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" | "on-exit"; /** 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; /** @deprecated Legacy partition key; actual storage is SQLite. Use `sqlitePath`. */ storePath: string; /** Storage backend identifier. */ storage: "sqlite"; /** Resolved path to the shared state SQLite database. */ sqlitePath: 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: true; ran: false; reason: "restart-recovery-pending"; } | { ok: true; ran: false; reason: "invalid-spec"; } | { ok: true; ran: false; reason: "stopped"; } | { 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 CronDeclarativeAddResult = CronJob & { created: boolean; updated?: boolean; job: CronJob; }; type CronAddResult = CronJob | CronDeclarativeAddResult; /** 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; /** Caller-specific declaration-key visibility and explicit enablement metadata. */ type CronAddOptions = { matchesExisting?: (job: CronJob) => boolean; enabledExplicit?: boolean; }; /** Normalized patch input accepted by cron service updates. */ type CronUpdateInput = CronJobPatch; /** Cron-store-locked guard evaluated against the current job before an update applies. */ type CronUpdatePrecondition = (job: CronJob, nowMs: number) => void | Promise; //#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. */ type CronServiceRunResult = CronRunResult; type CronServiceRunOptions = { payload?: CronPayload; }; /** 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, opts?: CronAddOptions): Promise; update(id: string, patch: CronUpdateInput): Promise; updateWithPrecondition(id: string, patch: CronUpdateInput, precondition: CronUpdatePrecondition): Promise; remove(id: string): Promise; run(id: string, mode?: CronRunMode, opts?: CronServiceRunOptions): 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; agentId?: string; }): CronWakeResult; } //#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/plugins/agent-tool-result-middleware-types.d.ts type OpenClawAgentToolResult = AgentToolResult; type AgentToolResultMiddlewareRuntime = "openclaw" | "codex"; /** @deprecated Use AgentToolResultMiddlewareRuntime. */ type AgentToolResultMiddlewareHarness = AgentToolResultMiddlewareRuntime | "codex-app-server"; type AgentToolResultMiddlewareEvent = { threadId?: string; turnId?: string; toolCallId: string; toolName: string; args: Record; cwd?: string; isError?: boolean; result: OpenClawAgentToolResult; }; type AgentToolResultMiddlewareContext = { runtime: AgentToolResultMiddlewareRuntime; /** @deprecated Use runtime. */ harness?: AgentToolResultMiddlewareRuntime; agentId?: string; sessionId?: string; sessionKey?: string; runId?: string; }; type AgentToolResultMiddlewareResult = { result: OpenClawAgentToolResult; }; type AgentToolResultMiddleware = (event: AgentToolResultMiddlewareEvent, ctx: AgentToolResultMiddlewareContext) => Promise | AgentToolResultMiddlewareResult | void; type AgentToolResultMiddlewareOptions = { runtimes?: AgentToolResultMiddlewareRuntime[]; /** @deprecated Use runtimes. */ harnesses?: AgentToolResultMiddlewareHarness[]; }; //#endregion //#region src/plugins/codex-app-server-extension-types.d.ts /** Tool-result event emitted to Codex app-server plugin extensions. */ type CodexAppServerToolResultEvent = { threadId: string; turnId: string; toolCallId: string; toolName: string; args: Record; result: AgentToolResult; }; /** Session context passed with Codex app-server extension events. */ type CodexAppServerExtensionContext = { agentId?: string; sessionId?: string; sessionKey?: string; runId?: string; }; /** Optional replacement result returned by a Codex app-server extension handler. */ type CodexAppServerToolResultHandlerResult = { result: AgentToolResult; }; /** Runtime event surface exposed to Codex app-server extension factories. */ type CodexAppServerExtensionRuntime = { on: (event: "tool_result", handler: (event: CodexAppServerToolResultEvent, ctx: CodexAppServerExtensionContext) => Promise | CodexAppServerToolResultHandlerResult | void) => void; }; /** Factory signature for Codex app-server plugin extensions. */ type CodexAppServerExtensionFactory = (runtime: CodexAppServerExtensionRuntime) => Promise | void; //#endregion //#region src/plugins/host-hooks.d.ts /** Reason passed to plugin cleanup callbacks when host-owned state changes. */ type PluginHostCleanupReason = "disable" | "reset" | "delete" | "restart"; type PluginSessionExtensionProjectionContext = { sessionKey: string; sessionId?: string; state: PluginJsonValue | undefined; }; /** Session extension registration owned by a plugin namespace. */ type PluginSessionExtensionRegistration = { namespace: string; description: string; project?: (ctx: PluginSessionExtensionProjectionContext) => PluginJsonValue | undefined; cleanup?: (ctx: { reason: PluginHostCleanupReason; sessionKey?: string; }) => void | Promise; /** * When set, after every successful `patchSessionExtension` the projected * value is mirrored to `SessionEntry[]` so non-plugin readers * can consume the typed slot without reaching into * `pluginExtensions[pluginId][namespace]`. * * The slot is a read-only mirror: writes always go through * `patchSessionExtension`; the host overwrites the slot value on every * subsequent patch. */ sessionEntrySlotKey?: string; /** * Optional JSON-compatible schema describing the projected slot value. * Purely informational at this layer; clients may use it to validate the * mirrored slot against a contract. */ sessionEntrySlotSchema?: PluginJsonValue; }; type PluginSessionExtensionProjection = { pluginId: string; namespace: string; value: PluginJsonValue; }; type PluginToolPolicyDecision = PluginHookBeforeToolCallResult | { allow?: boolean; reason?: string; }; type PluginTrustedToolPolicyRegistration = { id: string; description: string; evaluate: (event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext) => PluginToolPolicyDecision | void | Promise; }; type PluginToolMetadataRegistration = { toolName: string; displayName?: string; description?: string; risk?: "low" | "medium" | "high"; tags?: string[]; }; type PluginControlUiTabGroup = "control" | "agent"; type PluginControlUiDescriptor = { id: string; /** "tab" adds a Control UI sidebar tab; other surfaces attach to existing views. */ surface: "session" | "tool" | "run" | "settings" | "tab"; label: string; description?: string; placement?: string; schema?: PluginJsonValue; requiredScopes?: OperatorScope[]; /** Icon name hint for tab descriptors; unknown names fall back to a generic icon. */ icon?: string; /** * Gateway HTTP path (e.g. /plugins//panel) rendered in a sandboxed frame * when the Control UI has no bundled view for this tab. */ path?: string; /** Sidebar group for tab descriptors; defaults to "control". */ group?: PluginControlUiTabGroup; /** Sort order among plugin tabs; lower renders first. */ order?: number; }; type PluginSessionActionContext = { pluginId: string; actionId: string; sessionKey?: string; payload?: PluginJsonValue; client?: { connId?: string; scopes: string[]; }; }; type PluginSessionActionResult = { ok?: true; result?: PluginJsonValue; reply?: PluginJsonValue; continueAgent?: boolean; } | { ok: false; error: string; code?: string; details?: PluginJsonValue; }; type PluginSessionActionRegistration = { id: string; description?: string; schema?: PluginJsonValue; requiredScopes?: OperatorScope[]; handler: (ctx: PluginSessionActionContext) => PluginSessionActionResult | void | Promise; }; type PluginRuntimeLifecycleRegistration = { id: string; description?: string; cleanup?: (ctx: { reason: PluginHostCleanupReason; sessionKey?: string; runId?: string; }) => void | Promise; }; type PluginAgentEventSubscriptionRegistration = { id: string; description?: string; streams?: AgentEventStream[]; handle: (event: AgentEventPayload, ctx: { getRunContext: (namespace: string) => T | undefined; setRunContext: (namespace: string, value: PluginJsonValue) => void; clearRunContext: (namespace?: string) => void; }) => void | Promise; }; type PluginAgentEventEmitParams = { runId: string; stream: AgentEventStream; data: PluginJsonValue; sessionKey?: string; }; type PluginAgentEventEmitResult = { emitted: true; stream: AgentEventStream; } | { emitted: false; reason: string; }; type PluginRunContextPatch = { runId: string; namespace: string; value?: PluginJsonValue; unset?: boolean; }; type PluginRunContextGetParams = { runId: string; namespace: string; }; type PluginSessionSchedulerJobRegistration = { id: string; sessionKey: string; kind: string; description?: string; cleanup?: (ctx: { reason: PluginHostCleanupReason; sessionKey: string; jobId: string; }) => void | Promise; }; type PluginSessionSchedulerJobHandle = { id: string; pluginId: string; sessionKey: string; kind: string; }; type PluginSessionAttachmentFile = { path: string; }; type PluginAttachmentChannelHints = { telegram?: { parseMode?: "HTML"; disableNotification?: boolean; /** * Require host-side detection to match this MIME before forcing document delivery. * Mismatched files are rejected before the outbound adapter is called. */ forceDocumentMime?: string; }; slack?: { threadTs?: string; }; }; type PluginSessionAttachmentCaptionFormat = "plain" | "html" | "markdown"; type PluginSessionAttachmentParams = { sessionKey: string; files: PluginSessionAttachmentFile[]; text?: string; threadId?: string | number; forceDocument?: boolean; maxBytes?: number; captionFormat?: PluginSessionAttachmentCaptionFormat; channelHints?: PluginAttachmentChannelHints; }; type PluginSessionAttachmentResult = { ok: true; channel: string; deliveredTo: string; count: number; } | { ok: false; error: string; }; type PluginSessionTurnScheduleCommonParams = { sessionKey: string; message: string; agentId?: string; deliveryMode?: "none" | "announce"; name?: string; /** Optional cleanup tag. Reserved cron-name delimiters like `:` are rejected. */ tag?: string; }; type PluginSessionTurnScheduleParams = ({ at: string | number | Date; deleteAfterRun?: boolean; } & PluginSessionTurnScheduleCommonParams) | ({ delayMs: number; deleteAfterRun?: boolean; } & PluginSessionTurnScheduleCommonParams) | ({ cron: string; tz?: string; deleteAfterRun?: false; } & PluginSessionTurnScheduleCommonParams); type PluginSessionTurnUnscheduleByTagParams = { sessionKey: string; tag: string; }; type PluginSessionTurnUnscheduleByTagResult = { removed: number; failed: number; }; //#endregion //#region src/auto-reply/reply/abort.runtime-types.d.ts /** Result from the fast abort path before normal reply dispatch starts. */ type FastAbortResult = { handled: boolean; aborted: boolean; rejectionReason?: "finalizing"; stoppedSubagents?: number; }; /** Runtime hook that may convert a message into an immediate abort action. */ type TryFastAbortFromMessage = (params: { ctx: FinalizedMsgContext; cfg: OpenClawConfig; }) => Promise; /** Formats the user-visible abort acknowledgement text. */ type FormatAbortReplyText = (stoppedSubagents?: number, rejectionReason?: FastAbortResult["rejectionReason"]) => string; //#endregion //#region src/auto-reply/reply/command-session-metadata.d.ts type CommandSessionMetadataChange = { sessionKey: string; agentId?: string; reason: "command-metadata"; }; //#endregion //#region src/infra/heartbeat-run-scope.d.ts type HeartbeatRunScope = "global" | "commitment-only"; declare const HEARTBEAT_RUN_SCOPE: unique symbol; type ReplyOptionsWithHeartbeatRunScope = { [HEARTBEAT_RUN_SCOPE]?: HeartbeatRunScope; }; //#endregion //#region src/auto-reply/reply/get-reply.types.d.ts type InternalReplySessionOptions = { requestedSessionId?: string; resumeRequestedSession?: boolean; sessionPromptSourceReplyDeliveryMode?: GetReplyOptions["sourceReplyDeliveryMode"]; /** Marks queued follow-up admission waits on an older owner's delivery barrier. */ onFollowupAdmissionWaitChange?: (waiting: boolean) => void; }; type InternalGetReplyOptions = GetReplyOptions & InternalReplySessionOptions & ReplyOptionsWithHeartbeatRunScope; /** Reply resolver signature used by dispatchers and tests for dependency injection. */ type GetReplyFromConfig = (ctx: MsgContext, opts?: GetReplyOptions, configOverride?: OpenClawConfig) => Promise; type InternalGetReplyFromConfig = (ctx: MsgContext, opts?: InternalGetReplyOptions, configOverride?: OpenClawConfig) => Promise; //#endregion //#region src/auto-reply/reply/dispatch-from-config.types.d.ts type DispatchFromConfigResult = { queuedFinal: boolean; counts: Record; failedCounts?: Partial>; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; sendPolicyDenied?: boolean; observedReplyDelivery?: boolean; noVisibleReplyFallbackEligible?: boolean; beforeAgentRunBlocked?: boolean; sessionMetadataChanges?: CommandSessionMetadataChange[]; }; type DispatchFromConfigParams = { ctx: FinalizedMsgContext; cfg: OpenClawConfig; dispatcher: ReplyDispatcher; replyOptions?: Omit; replyResolver?: InternalGetReplyFromConfig; onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void; fastAbortResolver?: TryFastAbortFromMessage; formatAbortReplyTextResolver?: FormatAbortReplyText; /** Optional patch applied to the already loaded config before reply resolution. */ configOverride?: OpenClawConfig; }; type DispatchReplyFromConfig = (params: DispatchFromConfigParams) => Promise; //#endregion //#region src/auto-reply/reply/normalize-reply.d.ts type NormalizeReplySkipReason = "empty" | "silent" | "heartbeat"; //#endregion //#region src/auto-reply/reply/reply-dispatcher.d.ts type ReplyDispatchErrorHandler = (err: unknown, info: ReplyDispatchRuntimeInfo) => Promise | void; type ReplyDispatchSkipHandler = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo & { reason: NormalizeReplySkipReason; }) => void; type ReplyDispatchCancelHandler = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo) => Promise | void; type ReplyDispatchDeliverer = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo) => Promise; type ReplyDispatcherOptions = { deliver: ReplyDispatchDeliverer; silentReplyContext?: { cfg?: OpenClawConfig; sessionKey?: string; surface?: string; conversationType?: SilentReplyConversationType; }; responsePrefix?: string; transformReplyPayload?: (payload: ReplyPayload) => ReplyPayload | null; /** Static context for response prefix template interpolation. */ responsePrefixContext?: ResponsePrefixContext; /** Dynamic context provider for response prefix template interpolation. * Called at normalization time, after model selection is complete. */ responsePrefixContextProvider?: () => ResponsePrefixContext; onHeartbeatStrip?: () => void; onIdle?: () => Promise | void; onError?: ReplyDispatchErrorHandler; onSkip?: ReplyDispatchSkipHandler; /** Human-like delay between block replies for natural rhythm. */ humanDelay?: HumanDelayConfig; beforeDeliver?: ReplyDispatchBeforeDeliver; onBeforeDeliverCancelled?: ReplyDispatchCancelHandler; /** Observe each queued payload settling, including cancellation and delivery failure. */ onDeliverySettled?: (info: ReplyDispatchRuntimeInfo) => void; /** Resolve an owner activity policy for holding queued follow-ups behind delivery. */ resolveFollowupAdmissionBarrierTimeoutPolicy?: (context: { queuedCounts: Readonly>; humanDelayBudgetMs: number; }) => ReplyFollowupAdmissionBarrierTimeoutPolicy | undefined; }; type ReplyDispatcherWithTypingOptions = Omit & { typingCallbacks?: TypingCallbacks; onReplyStart?: () => Promise | void; onIdle?: () => Promise | void; onSettled?: () => unknown; onFreshSettledDelivery?: () => unknown; /** Called when the typing controller is cleaned up (e.g., on NO_REPLY). */ onCleanup?: () => void; }; type ReplyDispatcherWithTypingResult = { dispatcher: ReplyDispatcher; replyOptions: Pick; markDispatchIdle: () => void; /** Signal that the model run is complete so the typing controller can stop. */ markRunComplete: () => void; }; declare function createReplyDispatcher(options: ReplyDispatcherOptions): ReplyDispatcher; declare function createReplyDispatcherWithTyping(options: ReplyDispatcherWithTypingOptions): ReplyDispatcherWithTypingResult; //#endregion //#region src/auto-reply/reply/provider-dispatcher.types.d.ts type DispatchReplyContext = MsgContext | FinalizedMsgContext; type DispatchReplyOptions = Omit; /** Buffered block dispatcher entry point used by provider reply flows. */ type DispatchReplyWithBufferedBlockDispatcher$1 = (params: { ctx: DispatchReplyContext; cfg: OpenClawConfig; dispatcherOptions: ReplyDispatcherWithTypingOptions; toolsAllow?: string[]; replyOptions?: DispatchReplyOptions; replyResolver?: GetReplyFromConfig; }) => Promise; /** Plain dispatcher entry point used when block buffering is not needed. */ type DispatchReplyWithDispatcher = (params: { ctx: DispatchReplyContext; cfg: OpenClawConfig; dispatcherOptions: ReplyDispatcherOptions; toolsAllow?: string[]; replyOptions?: DispatchReplyOptions; replyResolver?: GetReplyFromConfig; }) => Promise; //#endregion //#region src/auto-reply/reply/reply-dispatcher.runtime-types.d.ts /** Type of the lazy reply dispatcher factory used by runtime dispatch paths. */ type CreateReplyDispatcherWithTyping$1 = typeof createReplyDispatcherWithTyping; //#endregion //#region src/auto-reply/commands-registry.runtime-types.d.ts /** Runtime-injected policy hook for whether text slash commands should be honored. */ type ShouldHandleTextCommands$1 = (params: ShouldHandleTextCommandsParams) => boolean; //#endregion //#region src/auto-reply/command-detection.runtime-types.d.ts /** Runtime-injected predicate for deciding whether visible text is an OpenClaw command. */ type IsControlCommandMessage$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; /** Runtime-injected predicate for deciding whether command authorization must be computed. */ type ShouldComputeCommandAuthorized$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; //#endregion //#region src/auto-reply/dispatch-dispatcher.d.ts /** Mark a dispatcher complete, wait for pending work, then run optional cleanup. */ declare function settleReplyDispatcher(params: { dispatcher: ReplyDispatcher; onSettled?: () => void | Promise; }): Promise; /** Run work with a dispatcher and always drain it before returning or throwing. */ declare function withReplyDispatcher(params: { dispatcher: ReplyDispatcher; run: () => Promise; onSettled?: () => void | Promise; }): Promise; //#endregion //#region src/auto-reply/reply/inbound-context.d.ts type FinalizeInboundContextOptions = { forceBodyForAgent?: boolean; forceBodyForCommands?: boolean; forceChatType?: boolean; forceConversationLabel?: boolean; }; declare function finalizeInboundContext>(ctx: T, opts?: FinalizeInboundContextOptions): T & FinalizedMsgContext; //#endregion //#region src/channels/sender-label.d.ts type SenderLabelParams = { name?: string; username?: string; tag?: string; e164?: string; id?: string; }; //#endregion //#region src/auto-reply/envelope.d.ts type AgentEnvelopeParams = { channel: string; from?: string; timestamp?: number | Date; host?: string; ip?: string; body: string; previousTimestamp?: number | Date; envelope?: EnvelopeFormatOptions; }; /** User/config-facing controls for timestamp rendering in prompt envelopes. */ type EnvelopeFormatOptions = { /** * "local" (default), "utc", "user", or an explicit IANA timezone string. */ timezone?: string; /** * Include absolute timestamps in the envelope (default: true). */ includeTimestamp?: boolean; /** * Include elapsed time suffix when previousTimestamp is provided (default: true). */ includeElapsed?: boolean; /** * Optional user timezone used when timezone="user". */ userTimezone?: string; }; /** Resolves envelope formatting defaults from agent config. */ declare function resolveEnvelopeFormatOptions(cfg?: OpenClawConfig): EnvelopeFormatOptions; /** Formats the generic bracketed envelope prepended to agent-visible messages. */ declare function formatAgentEnvelope(params: AgentEnvelopeParams): string; /** Formats an inbound message body with sender attribution appropriate for direct/group chats. */ declare function formatInboundEnvelope(params: { channel: string; from: string; body: string; timestamp?: number | Date; chatType?: string; senderLabel?: string; sender?: SenderLabelParams; previousTimestamp?: number | Date; envelope?: EnvelopeFormatOptions; fromMe?: boolean; }): string; /** Builds the compact `from` label used in inbound envelope headers. */ declare function formatInboundFromLabel(params: { isGroup: boolean; groupLabel?: string; groupId?: string; directLabel: string; directId?: string; groupFallback?: string; }): string; //#endregion //#region src/channels/plugins/outbound/load.types.d.ts /** * Lazy loader contract for channel outbound adapters. */ type LoadChannelOutboundAdapter = (id: ChannelId$1) => Promise; //#endregion //#region src/channels/turn/bot-loop-protection.d.ts /** Facts used to detect repeated bot-to-bot channel reply loops. */ type ChannelBotLoopProtectionFacts = { scopeId: string; conversationId: string; senderId: string; receiverId: string; config?: PairLoopGuardConfig; defaultsConfig?: PairLoopGuardConfig; defaultEnabled: boolean; nowMs?: number; }; /** Records a bot pair interaction and returns whether the loop guard should suppress it. */ declare function recordChannelBotPairLoopAndCheckSuppression(params: ChannelBotLoopProtectionFacts): PairLoopGuardResult; /** Clears channel bot-loop state for isolated tests. */ declare function clearChannelBotPairLoopGuardForTests(): void; //#endregion //#region src/channels/turn/types.d.ts /** Admission decision for an inbound channel event before agent dispatch. */ type ChannelTurnAdmission = { kind: "dispatch"; reason?: string; } | { kind: "observeOnly"; reason: string; } | { kind: "handled"; reason: string; } | { kind: "drop"; reason: string; recordHistory?: boolean; }; /** Coarse event classification used to decide whether an event can start an agent turn. */ type ChannelEventClass = { kind: "message" | "command" | "interaction" | "reaction" | "lifecycle" | "unknown"; canStartAgentTurn: boolean; requiresImmediateAck?: boolean; }; /** Normalized inbound event text and raw payload after channel-specific ingestion. */ type NormalizedTurnInput = { id: string; timestamp?: number; rawText: string; textForAgent?: string; textForCommands?: string; raw?: unknown; }; /** Sender identity facts projected into channel access, routing, and prompt context. */ type SenderFacts = { id?: string; name?: string; username?: string; tag?: string; roles?: string[]; isBot?: boolean; isSelf?: boolean; displayLabel?: string; }; /** Conversation identity and threading facts for a channel turn. */ type ConversationFacts = { kind: "direct" | "group" | "channel"; id: string; label?: string; spaceId?: string; parentId?: string; threadId?: string; nativeChannelId?: string; routePeer?: { kind: "direct" | "group" | "channel"; id: string; }; }; /** Session routing facts derived before dispatch. */ type RouteFacts = { agentId: string; accountId?: string; routeSessionKey: string; dispatchSessionKey?: string; persistedSessionKey?: string; parentSessionKey?: string; modelParentSessionKey?: string; mainSessionKey?: string; createIfMissing?: boolean; }; /** Reply target and source-delivery facts for a channel turn. */ type ReplyPlanFacts = { to: string; originatingTo?: string; nativeChannelId?: string; replyTarget?: string; deliveryTarget?: string; replyToId?: string; replyToIdFull?: string; messageThreadId?: string | number; threadParentId?: string; sourceReplyDeliveryMode?: "thread" | "reply" | "channel" | "direct" | "none"; }; /** Allowlist projection used by access checks without exposing raw configured entries. */ type ProjectedAllowlistAccessFacts = { configured: boolean; matched: boolean; reasonCode?: string; matchedEntryIds: string[]; invalidEntryCount: number; disabledEntryCount: number; accessGroups: { referenced: string[]; matched: string[]; missing: string[]; unsupported: string[]; failed: string[]; }; }; /** Event-level access projection for commands, reactions, buttons, and native events. */ type ProjectedEventAccessFacts = { kind: "message" | "reaction" | "button" | "postback" | "native-command" | "slash-command" | "system"; authMode: "inbound" | "command" | "origin-subject" | "route-only" | "none"; mayPair: boolean; authorized: boolean; reasonCode?: string; hasOriginSubject: boolean; originSubjectMatched: boolean; }; /** Access decisions for DMs, groups, commands, events, and mention gating. */ type AccessFacts = { dm?: { decision: "allow" | "pairing" | "deny"; reason?: string; /** * @deprecated Shared ingress projections redact allowlist entries and return an empty compat list. * Use allowlist diagnostics instead. */ allowFrom: string[]; allowlist?: ProjectedAllowlistAccessFacts; }; group?: { policy: "open" | "allowlist" | "disabled"; routeAllowed: boolean; senderAllowed: boolean; /** * @deprecated Shared ingress projections redact allowlist entries and return an empty compat list. * Use allowlist diagnostics instead. */ allowFrom: string[]; requireMention: boolean; allowlist?: ProjectedAllowlistAccessFacts; }; commands?: { authorized?: boolean; shouldBlockControlCommand?: boolean; reasonCode?: string; useAccessGroups: boolean; allowTextCommands: boolean; modeWhenAccessGroupsOff?: "allow" | "deny" | "configured"; /** * @deprecated Shared ingress projections do not expose raw authorizer lists. * Use authorized and reasonCode instead. */ authorizers: Array<{ configured: boolean; allowed: boolean; }>; }; event?: ProjectedEventAccessFacts; mentions?: { canDetectMention: boolean; wasMentioned: boolean; hasAnyMention?: boolean; explicitlyMentionedBot?: boolean; mentionedUserIds?: string[]; mentionedSubteamIds?: string[]; mentionSource?: MentionSource; implicitMentionKinds?: Array<"reply_to_bot" | "quoted_bot" | "bot_thread_participant" | "native">; requireMention?: boolean; effectiveWasMentioned?: boolean; shouldSkip?: boolean; }; }; /** Message text/history facts passed into templating and dispatch. */ type MessageFacts = { inboundEventKind?: InboundEventKind; body?: string; rawBody: string; bodyForAgent?: string; commandBody?: string; envelopeFrom?: string; senderLabel?: string; preview?: string; inboundHistory?: HistoryEntry[]; sourceModality?: InboundSourceModality; }; /** Parsed command facts for command-like channel turns. */ type CommandFacts = { kind: CommandTurnKind; body?: string; name?: string; authorized?: boolean; }; /** Inbound media facts supplied to the agent context. */ type InboundMediaFacts = { path?: string; url?: string; contentType?: string; kind?: "image" | "video" | "audio" | "document" | "unknown"; transcribed?: boolean; messageId?: string; }; type MaybePromise$1 = T | Promise; /** Adapter preflight output assembled before turn resolution. */ type PreflightFacts = { admission?: ChannelTurnAdmission; command?: CommandFacts; message?: Partial; media?: readonly InboundMediaFacts[] | (() => MaybePromise$1); supplemental?: SupplementalContextFacts; history?: ChannelTurnDroppedHistoryOptions; }; /** Delivery metadata for one reply payload dispatch. */ type ChannelDeliveryInfo = { kind: ReplyDispatchKind; }; /** Durable delivery queue intent recorded when a reply is deferred. */ type ChannelDeliveryIntent = { id: string; kind: "outbound_queue"; queuePolicy: OutboundDeliveryQueuePolicy; }; /** Result returned after delivering one channel reply payload. */ type ChannelDeliveryResult = { messageIds?: string[]; receipt?: MessageReceipt; threadId?: string; replyToId?: string; visibleReplySent?: boolean; deliveryIntent?: ChannelDeliveryIntent; }; /** Durable outbound delivery options available to channel turn delivery adapters. */ type ChannelTurnDurableDeliveryOptions = Pick & { to?: string | null; replyToId?: string | null; requiredCapabilities?: DurableFinalDeliveryRequirements; }; /** Delivery adapter used by channel turns to send reply payloads. */ type ChannelEventDeliveryAdapter = { preparePayload?: (payload: ReplyPayload, info: ChannelDeliveryInfo) => Promise | ReplyPayload; deliver: (payload: ReplyPayload, info: ChannelDeliveryInfo) => Promise; durable?: false | ChannelTurnDurableDeliveryOptions | ((payload: ReplyPayload, info: ChannelDeliveryInfo) => false | ChannelTurnDurableDeliveryOptions | Promise); onDelivered?: (payload: ReplyPayload, info: ChannelDeliveryInfo, result: ChannelDeliveryResult | void) => Promise | void; onError?: (err: unknown, info: { kind: string; }) => void; }; /** Options for recording inbound session route state around a turn. */ type ChannelTurnRecordOptions = { groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; updateLastRoute?: InboundLastRouteUpdate; onRecordError?: (err: unknown) => void; trackSessionMetaTask?: (task: Promise) => void; }; /** Options for finalizing visible conversation history after dispatch. */ type ChannelTurnHistoryFinalizeOptions = { isGroup?: boolean; historyKey?: string; historyMap?: Map; limit?: number; }; /** Options for recording history when an inbound event is dropped before dispatch. */ type ChannelTurnDroppedHistoryOptions = { key: string; limit: number; historyMap: Map; recordOnDrop?: boolean; mediaLimit?: number; shouldRecord?: () => boolean; }; /** Dispatcher options excluding delivery hooks owned by the channel turn adapter. */ type ChannelTurnDispatcherOptions = Omit; /** Reply pipeline options excluding cfg/agent/channel identity supplied by the turn. */ type ChannelTurnReplyPipelineOptions = Omit; /** Fully assembled channel turn ready to build the dispatch runner. */ type AssembledChannelTurn = { cfg: OpenClawConfig; channel: string; accountId?: string; agentId: string; routeSessionKey: string; storePath: string; ctxPayload: FinalizedMsgContext; recordInboundSession: RecordInboundSession$1; afterRecord?: () => void | Promise; dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher$1; delivery: ChannelEventDeliveryAdapter; replyPipeline?: ChannelTurnReplyPipelineOptions; dispatcherOptions?: ChannelTurnDispatcherOptions; toolsAllow?: string[]; replyOptions?: Omit; replyResolver?: GetReplyFromConfig; record?: ChannelTurnRecordOptions; history?: ChannelTurnHistoryFinalizeOptions; admission?: Extract; botLoopProtection?: ChannelBotLoopProtectionFacts; log?: (event: ChannelTurnLogEvent) => void; messageId?: string; /** * Observes turn adoption without waiting for settle. Threaded into * replyOptions for the agent runner (after recovery persist attempt). */ onTurnAdopted?: () => void | Promise; }; /** Channel turn with dispatch runner already prepared. */ type PreparedChannelTurn = { channel: string; accountId?: string; routeSessionKey: string; storePath: string; ctxPayload: FinalizedMsgContext; recordInboundSession: RecordInboundSession$1; afterRecord?: () => void | Promise; record?: ChannelTurnRecordOptions; history?: ChannelTurnHistoryFinalizeOptions; onPreDispatchFailure?: (err: unknown) => void | Promise; runDispatch: () => Promise; observeOnlyDispatchResult?: TDispatchResult; admission?: Extract; botLoopProtection?: ChannelBotLoopProtectionFacts; log?: (event: ChannelTurnLogEvent) => void; messageId?: string; }; /** Resolved turn shape returned by adapters before final run/dispatch handling. */ type ChannelTurnResolved = (AssembledChannelTurn & { admission?: Extract; }) | (PreparedChannelTurn & { admission?: Extract; }); /** Ordered lifecycle stage names emitted to channel turn log hooks. */ type ChannelTurnStage = "ingest" | "classify" | "preflight" | "resolve" | "authorize" | "assemble" | "record" | "dispatch" | "finalize"; /** Structured channel turn log event. */ type ChannelTurnLogEvent = { stage: ChannelTurnStage; event: "start" | "done" | "drop" | "handled" | "error" | "warning"; channel: string; accountId?: string; messageId?: string; sessionKey?: string; admission?: ChannelTurnAdmission["kind"]; reason?: string; error?: unknown; }; /** Final result for a channel turn, dispatched or admitted without dispatch. */ type ChannelTurnResult = DispatchedChannelTurnResult | { admission: ChannelTurnAdmission; dispatched: false; ctxPayload?: MsgContext; routeSessionKey?: string; }; /** Successful dispatch result for a channel turn. */ type DispatchedChannelTurnResult = { admission: Extract; dispatched: true; ctxPayload: MsgContext; routeSessionKey: string; dispatchResult: TDispatchResult; }; /** Adapter contract for ingesting, classifying, resolving, and finalizing raw channel events. */ type ChannelTurnAdapter = { ingest: (raw: TRaw) => Promise | NormalizedTurnInput | null; classify?: (input: NormalizedTurnInput) => Promise | ChannelEventClass; preflight?: (input: NormalizedTurnInput, eventClass: ChannelEventClass) => Promise | PreflightFacts | ChannelTurnAdmission | null | undefined; resolveTurn: (input: NormalizedTurnInput, eventClass: ChannelEventClass, preflight: PreflightFacts) => Promise> | ChannelTurnResolved; onFinalize?: (result: ChannelTurnResult) => Promise | void; }; /** Parameters for running one raw channel event through the turn kernel. */ type RunChannelTurnParams = { channel: string; accountId?: string; raw: TRaw; adapter: ChannelTurnAdapter; log?: (event: ChannelTurnLogEvent) => void; /** * Observes turn adoption without waiting for settle. Fired after the * recovery-context persist attempt (context may be absent when source * delivery is suppressed). Default callers still await full settle. */ onTurnAdopted?: () => void | Promise; }; //#endregion //#region src/channels/inbound-event/context.d.ts type MaybePromise = T | Promise; type ChannelInboundSupplementalMediaResolver = () => MaybePromise; type ChannelInboundSupplementalQuoteFacts = NonNullable & { isSelf?: boolean; media?: readonly InboundMediaFacts[] | ChannelInboundSupplementalMediaResolver; }; type ChannelInboundSupplementalFacts = Omit & { quote?: ChannelInboundSupplementalQuoteFacts; }; /** * @deprecated Prefer passing `resolveSupplementalMedia: true` directly to * `buildChannelInboundEventContext` without naming this compatibility type. */ type ChannelInboundSupplementalResolutionOptions = { resolveSupplementalMedia: true; suppressSelfQuoteBody?: boolean; suppressSelfQuoteMedia?: boolean; }; type BuildAccessFacts = Omit & { commands?: Partial>; }; type BuildChannelInboundEventContextParams = { channel: string; accountId?: string; provider?: string; surface?: string; messageId?: string; messageIdFull?: string; timestamp?: number; from: string; sender: SenderFacts; conversation: ConversationFacts; route: RouteFacts; reply: ReplyPlanFacts; message: MessageFacts; access?: BuildAccessFacts; command?: CommandFacts; commandTurn?: CommandTurnContext; media?: InboundMediaFacts[]; supplemental?: ChannelInboundSupplementalFacts; channelContext?: PluginHookChannelContext; contextVisibility?: ContextVisibilityMode; finalize?: FinalizeInboundContextFn; finalizeOptions?: FinalizeInboundContextOptions; extra?: Record; }; /** * @deprecated Prefer `BuildChannelInboundEventContextParams` with * `resolveSupplementalMedia: true` at call sites that need lazy quote media. */ type BuildChannelInboundEventContextAsyncParams = BuildChannelInboundEventContextParams & ChannelInboundSupplementalResolutionOptions; type BuiltChannelInboundEventContext = FinalizedMsgContext & { Body: string; BodyForAgent: string; BodyForCommands: string; ChatType: ConversationFacts["kind"]; CommandAuthorized: boolean; CommandBody: string; From: string; RawBody: string; SessionKey: string; To: string; InboundEventKind: InboundEventKind; }; type FinalizeInboundContextFn = (ctx: Record, opts?: FinalizeInboundContextOptions) => unknown; /** * @deprecated Used by deprecated `finalizeChannelInboundContext`; new channel * code should pass facts to `buildChannelInboundEventContext`. */ type FinalizeChannelInboundContextParams> = { context: T; supplemental?: SupplementalContextFacts | ChannelInboundSupplementalFacts; contextVisibility?: ContextVisibilityMode; media?: readonly InboundMediaFacts[]; finalize?: FinalizeInboundContextFn; finalizeOptions?: FinalizeInboundContextOptions; }; /** * @deprecated Prefer `FinalizeChannelInboundContextParams` with * `resolveSupplementalMedia: true` when lazy quote media must be resolved. */ type FinalizeChannelInboundContextAsyncParams> = FinalizeChannelInboundContextParams & { resolveSupplementalMedia: true; } & Pick; /** * @deprecated Result type for deprecated `finalizeChannelInboundContext`. */ type FinalizeChannelInboundContextResult> = { context: T & FinalizedMsgContext; supplemental?: SupplementalContextFacts; quoteHidden: boolean; forwardedHidden: boolean; threadHidden: boolean; }; declare function filterChannelInboundSupplementalContext(params: { supplemental?: SupplementalContextFacts; contextVisibility?: ContextVisibilityMode; }): SupplementalContextFacts | undefined; declare function filterChannelInboundQuoteContext(contextVisibility: ContextVisibilityMode | undefined, quote: SupplementalContextFacts["quote"] | undefined): SupplementalContextFacts["quote"] | undefined; /** * @deprecated Prefer `buildChannelInboundEventContext({ resolveSupplementalMedia: true })` * for channel inbound payloads. */ declare function resolveChannelInboundSupplementalContext(params: { supplemental?: ChannelInboundSupplementalFacts; contextVisibility?: ContextVisibilityMode; media?: readonly InboundMediaFacts[]; suppressSelfQuoteBody?: boolean; suppressSelfQuoteMedia?: boolean; }): Promise<{ supplemental?: SupplementalContextFacts; media: InboundMediaFacts[]; quoteHidden: boolean; }>; /** * @deprecated Public compatibility for callers that already prepared legacy * prompt fields. New channel code should use `buildChannelInboundEventContext`. */ declare function finalizeChannelInboundContext>(params: FinalizeChannelInboundContextAsyncParams): Promise>; declare function finalizeChannelInboundContext>(params: FinalizeChannelInboundContextParams): FinalizeChannelInboundContextResult; declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextAsyncParams): Promise; declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextParams): BuiltChannelInboundEventContext; //#endregion //#region src/channels/turn/durable-delivery.d.ts /** Options controlling durable final delivery for inbound channel replies. */ type DurableInboundReplyDeliveryOptions = Pick & { to?: string | null; replyToId?: string | null; requiredCapabilities?: DurableFinalDeliveryRequirements; }; /** Full context required to deliver one inbound final reply through durable message sending. */ type DurableInboundReplyDeliveryParams = DurableInboundReplyDeliveryOptions & { cfg: OpenClawConfig; channel: string; accountId?: string; agentId: string; ctxPayload: FinalizedMsgContext; payload: ReplyPayload; info: ChannelDeliveryInfo; }; /** Outcome of attempting durable final delivery for an inbound reply payload. */ type DurableInboundReplyDeliveryResult = { status: "not_applicable"; reason: "non_final"; } | { status: "unsupported"; reason: "missing_channel" | "missing_target" | "missing_outbound_handler" | "capability_mismatch"; capability?: DurableFinalDeliveryRequirement; } | { status: "handled_visible"; delivery: ChannelDeliveryResult; } | { status: "handled_no_send"; reason: "no_visible_result"; delivery: ChannelDeliveryResult; } | { status: "failed"; error: unknown; sentBeforeError?: true; }; /** Narrows durable delivery results that handled the payload without caller fallback. */ declare function isDurableInboundReplyDeliveryHandled(result: DurableInboundReplyDeliveryResult): result is Extract; /** Throws failed durable delivery results, preserving visible-send metadata when applicable. */ declare function throwIfDurableInboundReplyDeliveryFailed(result: DurableInboundReplyDeliveryResult): void; /** Delivers final inbound replies through the durable message-send context when supported. */ declare function deliverInboundReplyWithMessageSendContext(params: DurableInboundReplyDeliveryParams): Promise; /** @deprecated Use `deliverInboundReplyWithMessageSendContext`. */ declare const deliverDurableInboundReplyPayload: typeof deliverInboundReplyWithMessageSendContext; //#endregion //#region src/channels/turn/delivery-result.d.ts /** Converts a normalized message receipt into the delivery result shape used by channel turns. */ declare function createChannelDeliveryResultFromReceipt(params: { receipt: MessageReceipt; threadId?: string; replyToId?: string; visibleReplySent?: boolean; deliveryIntent?: ChannelDeliveryIntent; }): ChannelDeliveryResult; //#endregion //#region src/channels/turn/dispatch-result.d.ts /** Minimal dispatch result shape needed to count visible channel deliveries. */ type ChannelTurnDispatchResultLike = { queuedFinal?: boolean; counts?: Partial>; observedReplyDelivery?: boolean; } | null | undefined; /** Extra delivery signals observed outside the normal dispatch count payload. */ type ChannelTurnVisibleDeliverySignals = { observedReplyDelivery?: boolean; fallbackDelivered?: boolean; deliverySummaryDelivered?: boolean; }; /** Zero-filled reply dispatch count map used before merging optional provider counts. */ declare const EMPTY_CHANNEL_TURN_DISPATCH_COUNTS: Record; /** Resolves dispatch counts with missing reply kinds filled as zero. */ declare function resolveChannelTurnDispatchCounts(result: ChannelTurnDispatchResultLike): Record; /** Returns whether a turn produced any visible reply delivery signal. */ declare function hasVisibleChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: ChannelTurnVisibleDeliverySignals): boolean; /** Returns whether a turn produced a final reply, fallback, summary, or queued final payload. */ declare function hasFinalChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: Pick): boolean; declare namespace kernel_d_exports { export { AccessFacts, AssembledChannelTurn, BuildChannelInboundEventContextParams, ChannelBotLoopProtectionFacts, ChannelDeliveryInfo, ChannelDeliveryResult, ChannelEventClass, ChannelEventDeliveryAdapter, ChannelHistoryWindow, ChannelTurnAdapter, ChannelTurnAdmission, ChannelTurnDispatchResultLike, ChannelTurnDispatcherOptions, ChannelTurnDroppedHistoryOptions, ChannelTurnHistoryFinalizeOptions, ChannelTurnLogEvent, ChannelTurnRecordOptions, ChannelTurnReplyPipelineOptions, ChannelTurnResolved, ChannelTurnResult, ChannelTurnVisibleDeliverySignals, ConversationFacts, DispatchedChannelTurnResult, DurableInboundReplyDeliveryOptions, DurableInboundReplyDeliveryParams, DurableInboundReplyDeliveryResult, EMPTY_CHANNEL_TURN_DISPATCH_COUNTS, InboundMediaFacts, MessageFacts, NormalizedTurnInput, PreflightFacts, PreparedChannelTurn, ReplyPlanFacts, RouteFacts, RunChannelTurnParams, SenderFacts, SupplementalContextFacts, buildChannelInboundEventContext, clearChannelBotPairLoopGuardForTests, createChannelDeliveryResultFromReceipt, createChannelHistoryWindow, createChannelTurnReplyPipeline, createNoopChannelEventDeliveryAdapter, deliverDurableInboundReplyPayload, deliverInboundReplyWithMessageSendContext, dispatchAssembledChannelTurn, dispatchChannelInboundReply, filterChannelInboundSupplementalContext, hasFinalChannelTurnDispatch, hasVisibleChannelTurnDispatch, isDurableInboundReplyDeliveryHandled, recordChannelBotPairLoopAndCheckSuppression, recordDroppedChannelInboundHistory, recordDroppedChannelTurnHistory, resolveChannelTurnDispatchCounts, runChannelInboundEvent, runChannelTurn, runPreparedChannelTurn, runPreparedInboundReply, throwIfDurableInboundReplyDeliveryFailed }; } /** * @deprecated Compatibility assembly for legacy buffered reply dispatchers. * New channel plugins should expose `defineChannelMessageAdapter(...)` from * `openclaw/plugin-sdk/channel-outbound` and route send/receive behavior through * the message lifecycle helpers. */ declare function createChannelTurnReplyPipeline(params: CreateChannelReplyPipelineParams): ReturnType; declare function createNoopChannelEventDeliveryAdapter(): ChannelEventDeliveryAdapter; declare function recordDroppedChannelTurnHistory(params: { input: NormalizedTurnInput; preflight: PreflightFacts; admission?: ChannelTurnAdmission; }): Promise; declare const recordDroppedChannelInboundHistory: typeof recordDroppedChannelTurnHistory; type AssembledChannelTurnWithBotLoopProtection = AssembledChannelTurn & { botLoopProtection: NonNullable; }; type AssembledChannelTurnWithoutBotLoopProtection = Omit & { botLoopProtection?: undefined; }; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurnWithBotLoopProtection): Promise; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurnWithoutBotLoopProtection): Promise; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurn): Promise; declare const dispatchChannelInboundReply: typeof dispatchAssembledChannelTurn; type PreparedChannelTurnWithBotLoopProtection = PreparedChannelTurn & { botLoopProtection: NonNullable["botLoopProtection"]>; }; type PreparedChannelTurnWithoutBotLoopProtection = Omit, "botLoopProtection"> & { botLoopProtection?: undefined; }; declare function runPreparedChannelTurn(params: PreparedChannelTurnWithBotLoopProtection): Promise>; declare function runPreparedChannelTurn(params: PreparedChannelTurnWithoutBotLoopProtection): Promise>; declare function runPreparedChannelTurn(params: PreparedChannelTurn): Promise>; declare const runPreparedInboundReply: typeof runPreparedChannelTurn; declare function runChannelTurn(params: RunChannelTurnParams): Promise>; declare const runChannelInboundEvent: typeof runChannelTurn; //#endregion //#region src/plugins/runtime/types-channel.d.ts /** * Runtime helpers for native channel plugins. * * This surface exposes generic core helpers only. Plugin-owned behavior stays * inside the owning plugin package instead of hanging off core runtime slots * keyed by plugin id. */ type DispatchReplyWithBufferedBlockDispatcher = DispatchReplyWithBufferedBlockDispatcher$1; type CreateReplyDispatcherWithTyping = CreateReplyDispatcherWithTyping$1; type ReadChannelAllowFromStoreForAccount = ReadChannelAllowFromStoreForAccount$1; type UpsertChannelPairingRequestForAccount = UpsertChannelPairingRequestForAccount$1; type ShouldHandleTextCommands = ShouldHandleTextCommands$1; type IsControlCommandMessage = IsControlCommandMessage$1; type ShouldComputeCommandAuthorized = ShouldComputeCommandAuthorized$1; type BuildMentionRegexes = BuildMentionRegexes$1; type MatchesMentionPatterns = MatchesMentionPatterns$1; type MatchesMentionWithExplicit = MatchesMentionWithExplicit$1; type ReadSessionUpdatedAt = ReadSessionUpdatedAt$1; type RecordSessionMetaFromInbound = RecordSessionMetaFromInbound$1; type UpdateLastRoute = UpdateLastRoute$1; type RecordInboundSession = RecordInboundSession$1; type RuntimeThreadBindingLifecycleRecord = SessionBindingRecord | { boundAt: number; lastActivityAt: number; idleTimeoutMs?: number; maxAgeMs?: number; }; type PluginRuntimeChannelContextKey = { channelId: string; accountId?: string | null; capability: string; }; type PluginRuntimeChannelContextEvent = { type: "registered" | "unregistered"; key: { channelId: string; accountId?: string; capability: string; }; context?: unknown; }; type PluginRuntimeChannelContextRegistry = { register: (params: PluginRuntimeChannelContextKey & { context: unknown; abortSignal?: AbortSignal; }) => { dispose: () => void; }; get: (params: PluginRuntimeChannelContextKey) => T | undefined; watch: (params: { channelId?: string; accountId?: string | null; capability?: string; onEvent: (event: PluginRuntimeChannelContextEvent) => void; }) => () => void; }; type PluginRuntimeChannel$1 = { text: { chunkByNewline: typeof chunkByNewline; chunkMarkdownText: typeof chunkMarkdownText; chunkMarkdownTextWithMode: typeof chunkMarkdownTextWithMode; chunkText: typeof chunkText; chunkTextWithMode: typeof chunkTextWithMode; resolveChunkMode: typeof resolveChunkMode; resolveTextChunkLimit: typeof resolveTextChunkLimit; hasControlCommand: typeof hasControlCommand; resolveMarkdownTableMode: ResolveMarkdownTableMode; convertMarkdownTables: typeof convertMarkdownTables; }; reply: { dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher; /** * @deprecated Prefer `openclaw/plugin-sdk/channel-outbound` adapters plus * `dispatchReplyWithBufferedBlockDispatcher` or channel turn helpers. * This is a low-level legacy dispatcher escape hatch. */ createReplyDispatcherWithTyping: CreateReplyDispatcherWithTyping; resolveEffectiveMessagesConfig: typeof resolveEffectiveMessagesConfig; /** * @deprecated Prefer the channel-message reply pipeline helpers. This is * tied to the low-level legacy dispatcher path. */ resolveHumanDelayConfig: typeof resolveHumanDelayConfig; /** * @deprecated Prefer `dispatchReplyWithBufferedBlockDispatcher` with a * channel-message adapter or the channel turn helpers. Direct use must * manually preserve source reply delivery metadata such as * `sourceReplyDeliveryMode`. */ dispatchReplyFromConfig: DispatchReplyFromConfig; withReplyDispatcher: typeof withReplyDispatcher; settleReplyDispatcher: typeof settleReplyDispatcher; /** * @deprecated Prefer `buildChannelInboundEventContext` from * `openclaw/plugin-sdk/channel-inbound` so inbound event metadata is * carried into reply dispatch. */ finalizeInboundContext: typeof finalizeInboundContext; formatAgentEnvelope: typeof formatAgentEnvelope; /** @deprecated Prefer `BodyForAgent` + structured user-context blocks (do not build plaintext envelopes for prompts). */ formatInboundEnvelope: typeof formatInboundEnvelope; resolveEnvelopeFormatOptions: typeof resolveEnvelopeFormatOptions; }; routing: { buildAgentSessionKey: typeof buildAgentSessionKey; resolveAgentRoute: typeof resolveAgentRoute; }; pairing: { buildPairingReply: typeof buildPairingReply; readAllowFromStore: ReadChannelAllowFromStoreForAccount; upsertPairingRequest: UpsertChannelPairingRequestForAccount; }; media: { readRemoteMediaBuffer: typeof readRemoteMediaBuffer; /** @deprecated Use `readRemoteMediaBuffer`. */ fetchRemoteMedia: typeof fetchRemoteMedia; saveRemoteMedia: typeof saveRemoteMedia; saveResponseMedia: typeof saveResponseMedia; saveMediaBuffer: typeof saveMediaBuffer; }; activity: { record: typeof recordChannelActivity; get: typeof getChannelActivity; }; session: { /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */resolveStorePath: typeof resolveStorePath; readSessionUpdatedAt: ReadSessionUpdatedAt; recordSessionMetaFromInbound: RecordSessionMetaFromInbound; /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */ recordInboundSession: RecordInboundSession; updateLastRoute: UpdateLastRoute; }; mentions: { buildMentionRegexes: BuildMentionRegexes; matchesMentionPatterns: MatchesMentionPatterns; matchesMentionWithExplicit: MatchesMentionWithExplicit; implicitMentionKindWhen: typeof implicitMentionKindWhen; resolveInboundMentionDecision: typeof resolveInboundMentionDecision; }; reactions: { createAckReactionHandle: typeof createAckReactionHandle; shouldAckReaction: typeof shouldAckReaction; removeAckReactionAfterReply: typeof removeAckReactionAfterReply; removeAckReactionHandleAfterReply: typeof removeAckReactionHandleAfterReply; }; groups: { resolveGroupPolicy: typeof resolveChannelGroupPolicy; resolveRequireMention: typeof resolveChannelGroupRequireMention; }; debounce: { createInboundDebouncer: typeof createInboundDebouncer; resolveInboundDebounceMs: typeof resolveInboundDebounceMs; }; commands: { resolveCommandAuthorizedFromAuthorizers: typeof resolveCommandAuthorizedFromAuthorizers; isControlCommandMessage: IsControlCommandMessage; shouldComputeCommandAuthorized: ShouldComputeCommandAuthorized; shouldHandleTextCommands: ShouldHandleTextCommands; }; outbound: { loadAdapter: LoadChannelOutboundAdapter; }; inbound: { buildContext: typeof buildChannelInboundEventContext; run: typeof runChannelInboundEvent; /** @deprecated Prefer `run` for raw inbound events or `dispatchReply` for assembled contexts. */ runPreparedReply: typeof runPreparedInboundReply; dispatchReply: typeof dispatchChannelInboundReply; }; threadBindings: { setIdleTimeoutBySessionKey: (params: { channelId: string; targetSessionKey: string; accountId?: string; idleTimeoutMs: number; }) => RuntimeThreadBindingLifecycleRecord[]; setMaxAgeBySessionKey: (params: { channelId: string; targetSessionKey: string; accountId?: string; maxAgeMs: number; }) => RuntimeThreadBindingLifecycleRecord[]; }; runtimeContexts: PluginRuntimeChannelContextRegistry; }; //#endregion //#region src/plugins/runtime/types.d.ts type PluginRuntimeChannel = PluginRuntimeChannel$1; type SubagentRunParams = { sessionKey: string; message: string; provider?: string; model?: string; extraSystemPrompt?: string; lane?: string; lightContext?: boolean; deliver?: boolean; idempotencyKey?: string; cwd?: string; }; type PluginManagedWorktree = { id: string; path: string; branch: string; }; type SubagentRunResult = { runId: string; }; type SubagentWaitParams = { runId: string; timeoutMs?: number; }; type SubagentWaitResult = { status: "ok" | "error" | "timeout"; error?: string; }; type SubagentGetSessionMessagesParams = { sessionKey: string; limit?: number; }; type SubagentGetSessionMessagesResult = { messages: unknown[]; }; /** @deprecated Use SubagentGetSessionMessagesParams. */ type SubagentGetSessionParams = SubagentGetSessionMessagesParams; /** @deprecated Use SubagentGetSessionMessagesResult. */ type SubagentGetSessionResult = SubagentGetSessionMessagesResult; type SubagentDeleteSessionParams = { sessionKey: string; deleteTranscript?: boolean; }; type RuntimeNodeListParams = { connected?: boolean; }; type RuntimeNodeListResult = { nodes: Array<{ nodeId: string; displayName?: string; remoteIp?: string; connected?: boolean; caps?: string[]; commands?: string[]; }>; }; type RuntimeNodeInvokeParams = { nodeId: string; command: string; params?: unknown; timeoutMs?: number; idempotencyKey?: string; /** Requested Gateway scopes. Honored only for bundled or trusted official plugins. */ scopes?: OperatorScope[]; }; type RuntimeGatewayRequestOptions = { timeoutMs?: number; }; /** Trusted in-process runtime surface injected into native plugins. */ type PluginRuntime = PluginRuntimeCore & { gateway: { /** Whether this process owns an active Gateway request context. */isAvailable: () => Promise; /** Dispatch a Gateway method as the current trusted plugin. */ request: (method: string, params?: Record, options?: RuntimeGatewayRequestOptions) => Promise; }; subagent: { run: (params: SubagentRunParams) => Promise; waitForRun: (params: SubagentWaitParams) => Promise; getSessionMessages: (params: SubagentGetSessionMessagesParams) => Promise; /** @deprecated Use getSessionMessages. */ getSession: (params: SubagentGetSessionParams) => Promise; deleteSession: (params: SubagentDeleteSessionParams) => Promise; }; nodes: { list: (params?: RuntimeNodeListParams) => Promise; invoke: (params: RuntimeNodeInvokeParams) => Promise; }; worktrees: { create: (params: { repoRoot: string; name: string; baseRef?: string; ownerKind: "workboard"; ownerId: string; }) => Promise; release: (params: { path: string; }) => Promise; removeIfLossless: (params: { path: string; }) => Promise; }; channel: PluginRuntimeChannel; }; type CreatePluginRuntimeOptions = { subagent?: PluginRuntime["subagent"]; nodes?: PluginRuntime["nodes"]; allowGatewaySubagentBinding?: boolean; }; //#endregion //#region src/plugins/registry-types.d.ts type ChannelPlugin$1 = ChannelPlugin$2; type CliBackendPlugin = CliBackendPlugin$1; type ImageGenerationProviderPlugin$1 = ImageGenerationProviderPlugin; type MediaUnderstandingProviderPlugin$1 = MediaUnderstandingProviderPlugin; type TranscriptSourceProvider$1 = TranscriptSourceProvider; type MusicGenerationProviderPlugin$1 = MusicGenerationProviderPlugin; type OpenClawPluginCliCommandDescriptor$1 = OpenClawPluginCliCommandDescriptor; type OpenClawPluginCliRegistrar$1 = OpenClawPluginCliRegistrar; type OpenClawPluginCommandDefinition$1 = OpenClawPluginCommandDefinition; type PluginInteractiveHandlerRegistration$1 = PluginInteractiveHandlerRegistration; type OpenClawPluginGatewayRuntimeScopeSurface$1 = OpenClawPluginGatewayRuntimeScopeSurface; type OpenClawGatewayDiscoveryService$1 = OpenClawGatewayDiscoveryService; type OpenClawPluginHttpRouteAuth$1 = OpenClawPluginHttpRouteAuth; type OpenClawPluginHttpRouteHandler$1 = OpenClawPluginHttpRouteHandler; type OpenClawPluginHttpRouteUpgradeHandler$1 = OpenClawPluginHttpRouteUpgradeHandler; type OpenClawPluginHttpRouteMatch$1 = OpenClawPluginHttpRouteMatch; type OpenClawPluginHostedMediaResolver$1 = OpenClawPluginHostedMediaResolver; type OpenClawPluginReloadRegistration$1 = OpenClawPluginReloadRegistration; type OpenClawPluginSecurityAuditCollector$1 = OpenClawPluginSecurityAuditCollector; type OpenClawPluginService$1 = OpenClawPluginService; type OpenClawPluginToolFactory = OpenClawPluginToolFactory$1; type PluginConversationBindingResolvedEvent = PluginConversationBindingResolvedEvent$1; type TypedPluginHookRegistration = PluginHookRegistration$1; type PluginLogger$1 = PluginLogger; type PluginOrigin = PluginOrigin$1; type PluginTextTransformRegistration$1 = PluginTextTransformRegistration; type MigrationProviderPlugin$1 = MigrationProviderPlugin; type ProviderPlugin$1 = ProviderPlugin; type RealtimeTranscriptionProviderPlugin$1 = RealtimeTranscriptionProviderPlugin; type RealtimeVoiceProviderPlugin$1 = RealtimeVoiceProviderPlugin; type SpeechProviderPlugin$1 = SpeechProviderPlugin; type VideoGenerationProviderPlugin$1 = VideoGenerationProviderPlugin; type WebFetchProviderPlugin = WebFetchProviderPlugin$1; type WebSearchProviderPlugin = WebSearchProviderPlugin$1; type UnifiedModelCatalogProviderPlugin$1 = UnifiedModelCatalogProviderPlugin; /** Agent tool factory registered by one plugin runtime. */ type PluginToolRegistration = { pluginId: string; pluginName?: string; factory: OpenClawPluginToolFactory; names: string[]; declaredNames?: string[]; optional: boolean; source: string; rootDir?: string; }; type PluginCliRegistration = { pluginId: string; pluginName?: string; register: OpenClawPluginCliRegistrar$1; parentPath: string[]; commands: string[]; descriptors: OpenClawPluginCliCommandDescriptor$1[]; source: string; rootDir?: string; }; /** Gateway HTTP route registered by a plugin runtime. */ type PluginHttpRouteRegistration$1 = { pluginId?: string; path: string; handler: OpenClawPluginHttpRouteHandler$1; handleUpgrade?: OpenClawPluginHttpRouteUpgradeHandler$1; auth: OpenClawPluginHttpRouteAuth$1; match: OpenClawPluginHttpRouteMatch$1; gatewayRuntimeScopeSurface?: OpenClawPluginGatewayRuntimeScopeSurface$1; gatewayMethodDispatchAllowed?: boolean; nodeCapability?: { surface: string; ttlMs?: number; }; source?: string; }; type PluginHostedMediaResolverRegistration = { pluginId: string; pluginName?: string; resolver: OpenClawPluginHostedMediaResolver$1; source: string; rootDir?: string; }; type PluginChannelRegistration = { pluginId: string; pluginName?: string; plugin: ChannelPlugin$1; source: string; rootDir?: string; }; type PluginChannelSetupRegistration = { pluginId: string; pluginName?: string; plugin: ChannelPlugin$1; source: string; enabled: boolean; rootDir?: string; }; type PluginProviderRegistration = { pluginId: string; pluginName?: string; provider: ProviderPlugin$1; source: string; rootDir?: string; }; type PluginModelCatalogProviderRegistration = { pluginId: string; pluginName?: string; provider: UnifiedModelCatalogProviderPlugin$1; source: string; rootDir?: string; }; type PluginCliBackendRegistration = { pluginId: string; pluginName?: string; backend: CliBackendPlugin; source: string; rootDir?: string; }; type PluginTextTransformsRegistration = { pluginId: string; pluginName?: string; transforms: PluginTextTransformRegistration$1; source: string; rootDir?: string; }; type PluginOwnedProviderRegistration = { pluginId: string; pluginName?: string; provider: T; source: string; rootDir?: string; }; type PluginSpeechProviderRegistration = PluginOwnedProviderRegistration; type PluginEmbeddingProviderRegistration = PluginOwnedProviderRegistration; type PluginRealtimeTranscriptionProviderRegistration = PluginOwnedProviderRegistration; type PluginRealtimeVoiceProviderRegistration = PluginOwnedProviderRegistration; type PluginMediaUnderstandingProviderRegistration = PluginOwnedProviderRegistration; type PluginTranscriptsSourceProviderRegistration = PluginOwnedProviderRegistration; type PluginImageGenerationProviderRegistration = PluginOwnedProviderRegistration; type PluginVideoGenerationProviderRegistration = PluginOwnedProviderRegistration; type PluginMusicGenerationProviderRegistration = PluginOwnedProviderRegistration; type PluginWebFetchProviderRegistration = PluginOwnedProviderRegistration; type PluginWebSearchProviderRegistration = PluginOwnedProviderRegistration; type PluginMigrationProviderRegistration = PluginOwnedProviderRegistration; type PluginMemoryEmbeddingProviderRegistration = PluginOwnedProviderRegistration; type PluginCodexAppServerExtensionFactoryRegistration = { pluginId: string; pluginName?: string; rawFactory: CodexAppServerExtensionFactory; factory: CodexAppServerExtensionFactory; source: string; rootDir?: string; }; type PluginAgentToolResultMiddlewareRegistration = { pluginId: string; pluginName?: string; rawHandler: AgentToolResultMiddleware; handler: AgentToolResultMiddleware; runtimes: AgentToolResultMiddlewareRuntime[]; source: string; rootDir?: string; }; type PluginAgentHarnessRegistration = { pluginId: string; pluginName?: string; harness: AgentHarness; source: string; rootDir?: string; }; type PluginHookRegistration = { pluginId: string; entry: HookEntry; events: string[]; source: string; rootDir?: string; }; type PluginServiceRegistration = { pluginId: string; pluginName?: string; service: OpenClawPluginService$1; source: string; origin: PluginOrigin; trustedOfficialInstall?: boolean; rootDir?: string; }; type PluginGatewayDiscoveryServiceRegistration = { pluginId: string; pluginName?: string; service: OpenClawGatewayDiscoveryService$1; source: string; rootDir?: string; }; type PluginReloadRegistration = { pluginId: string; pluginName?: string; registration: OpenClawPluginReloadRegistration$1; source: string; rootDir?: string; }; type PluginNodeHostCommandRegistration = { pluginId: string; pluginName?: string; command: OpenClawPluginNodeHostCommand; source: string; rootDir?: string; }; type PluginNodeInvokePolicyRegistration = { pluginId: string; pluginName?: string; policy: OpenClawPluginNodeInvokePolicy; pluginConfig?: Record; source: string; rootDir?: string; }; type PluginSecurityAuditCollectorRegistration = { pluginId: string; pluginName?: string; collector: OpenClawPluginSecurityAuditCollector$1; source: string; rootDir?: string; }; type PluginCommandRegistration = { pluginId: string; pluginName?: string; command: OpenClawPluginCommandDefinition$1; source: string; rootDir?: string; }; type PluginInteractiveHandlerRegistryRegistration = PluginInteractiveHandlerRegistration$1 & { pluginId: string; pluginName?: string; pluginRoot?: string; }; type PluginSessionExtensionRegistryRegistration = { pluginId: string; pluginName?: string; extension: PluginSessionExtensionRegistration; source: string; rootDir?: string; }; type PluginTrustedToolPolicyRegistryRegistration = { pluginId: string; pluginName?: string; policy: PluginTrustedToolPolicyRegistration; origin?: PluginRecord["origin"]; source: string; rootDir?: string; }; type PluginToolMetadataRegistryRegistration = { pluginId: string; pluginName?: string; metadata: PluginToolMetadataRegistration; source: string; rootDir?: string; }; type PluginControlUiDescriptorRegistryRegistration = { pluginId: string; pluginName?: string; descriptor: PluginControlUiDescriptor; source: string; rootDir?: string; }; type PluginRuntimeLifecycleRegistryRegistration = { pluginId: string; pluginName?: string; lifecycle: PluginRuntimeLifecycleRegistration; source: string; rootDir?: string; }; type PluginAgentEventSubscriptionRegistryRegistration = { pluginId: string; pluginName?: string; subscription: PluginAgentEventSubscriptionRegistration; source: string; rootDir?: string; }; type PluginSessionSchedulerJobRegistryRegistration = { pluginId: string; pluginName?: string; job: PluginSessionSchedulerJobRegistration; generation?: number; source: string; rootDir?: string; }; type PluginSessionActionRegistryRegistration = { pluginId: string; pluginName?: string; action: PluginSessionActionRegistration; source: string; rootDir?: string; }; type PluginConversationBindingResolvedHandlerRegistration = { pluginId: string; pluginName?: string; pluginRoot?: string; handler: (event: PluginConversationBindingResolvedEvent) => void | Promise; source: string; rootDir?: string; }; type PluginRecord = { id: string; name: string; version?: string; packageName?: string; description?: string; format?: PluginFormat; bundleFormat?: PluginBundleFormat; bundleCapabilities?: string[]; kind?: PluginKind | PluginKind[]; source: string; rootDir?: string; origin: PluginOrigin; workspaceDir?: string; trustedOfficialInstall?: boolean; enabled: boolean; explicitlyEnabled?: boolean; activated?: boolean; imported?: boolean; compat?: readonly PluginCompatCode[]; activationSource?: PluginActivationSource; activationReason?: string; status: "loaded" | "disabled" | "error"; error?: string; failedAt?: Date; failurePhase?: "validation" | "load" | "register"; toolNames: string[]; hookNames: string[]; channelIds: string[]; cliBackendIds: string[]; providerIds: string[]; syntheticAuthRefs?: string[]; embeddingProviderIds: string[]; speechProviderIds: string[]; realtimeTranscriptionProviderIds: string[]; realtimeVoiceProviderIds: string[]; mediaUnderstandingProviderIds: string[]; transcriptSourceProviderIds: string[]; imageGenerationProviderIds: string[]; videoGenerationProviderIds: string[]; musicGenerationProviderIds: string[]; webFetchProviderIds: string[]; webSearchProviderIds: string[]; migrationProviderIds: string[]; contextEngineIds?: string[]; memoryEmbeddingProviderIds: string[]; agentHarnessIds: string[]; cliCommands: string[]; services: string[]; gatewayDiscoveryServiceIds: string[]; commands: string[]; httpRoutes: number; hookCount: number; configSchema: boolean; configUiHints?: Record; configJsonSchema?: JsonSchemaObject; contracts?: PluginManifestContracts; memorySlotSelected?: boolean; dependencyStatus?: PluginDependencyStatus; }; type PluginRegistry = { plugins: PluginRecord[]; tools: PluginToolRegistration[]; hooks: PluginHookRegistration[]; typedHooks: TypedPluginHookRegistration[]; channels: PluginChannelRegistration[]; channelSetups: PluginChannelSetupRegistration[]; providers: PluginProviderRegistration[]; modelCatalogProviders: PluginModelCatalogProviderRegistration[]; cliBackends: PluginCliBackendRegistration[]; textTransforms: PluginTextTransformsRegistration[]; embeddingProviders: PluginEmbeddingProviderRegistration[]; speechProviders: PluginSpeechProviderRegistration[]; realtimeTranscriptionProviders: PluginRealtimeTranscriptionProviderRegistration[]; realtimeVoiceProviders: PluginRealtimeVoiceProviderRegistration[]; mediaUnderstandingProviders: PluginMediaUnderstandingProviderRegistration[]; transcriptSourceProviders: PluginTranscriptsSourceProviderRegistration[]; imageGenerationProviders: PluginImageGenerationProviderRegistration[]; videoGenerationProviders: PluginVideoGenerationProviderRegistration[]; musicGenerationProviders: PluginMusicGenerationProviderRegistration[]; webFetchProviders: PluginWebFetchProviderRegistration[]; webSearchProviders: PluginWebSearchProviderRegistration[]; migrationProviders: PluginMigrationProviderRegistration[]; codexAppServerExtensionFactories: PluginCodexAppServerExtensionFactoryRegistration[]; agentToolResultMiddlewares: PluginAgentToolResultMiddlewareRegistration[]; memoryEmbeddingProviders: PluginMemoryEmbeddingProviderRegistration[]; agentHarnesses: PluginAgentHarnessRegistration[]; gatewayHandlers: GatewayRequestHandlers; gatewayMethodDescriptors: GatewayMethodDescriptor[]; coreGatewayMethodNames: string[]; httpRoutes: PluginHttpRouteRegistration$1[]; hostedMediaResolvers: PluginHostedMediaResolverRegistration[]; cliRegistrars: PluginCliRegistration[]; reloads: PluginReloadRegistration[]; nodeHostCommands: PluginNodeHostCommandRegistration[]; nodeInvokePolicies: PluginNodeInvokePolicyRegistration[]; securityAuditCollectors: PluginSecurityAuditCollectorRegistration[]; services: PluginServiceRegistration[]; gatewayDiscoveryServices: PluginGatewayDiscoveryServiceRegistration[]; commands: PluginCommandRegistration[]; interactiveHandlers: PluginInteractiveHandlerRegistryRegistration[]; sessionExtensions: PluginSessionExtensionRegistryRegistration[]; trustedToolPolicies: PluginTrustedToolPolicyRegistryRegistration[]; toolMetadata: PluginToolMetadataRegistryRegistration[]; controlUiDescriptors: PluginControlUiDescriptorRegistryRegistration[]; runtimeLifecycles: PluginRuntimeLifecycleRegistryRegistration[]; agentEventSubscriptions: PluginAgentEventSubscriptionRegistryRegistration[]; sessionSchedulerJobs: PluginSessionSchedulerJobRegistryRegistration[]; sessionActions: PluginSessionActionRegistryRegistration[]; conversationBindingResolvedHandlers: PluginConversationBindingResolvedHandlerRegistration[]; diagnostics: PluginDiagnostic[]; }; type PluginRegistryParams = { logger: PluginLogger$1; coreGatewayHandlers?: GatewayRequestHandlers; coreGatewayMethodNames?: readonly string[]; runtime: PluginRuntime; hostServices?: { /** May be a live accessor; plugin APIs must read it at call time. */cron?: CronServiceContract; }; activateGlobalSideEffects?: boolean; }; //#endregion //#region src/plugins/registry.d.ts type PluginHttpRouteRegistration = PluginHttpRouteRegistration$1 & { gatewayRuntimeScopeSurface?: OpenClawPluginGatewayRuntimeScopeSurface; }; //#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-channels.d.ts type StartChannelOptions = { preserveRestartAttempts?: boolean; preserveManualStop?: boolean; deferAccountStartUntil?: Promise; manual?: boolean; }; //#endregion //#region src/commands/daemon-runtime.d.ts type GatewayDaemonRuntime = "node"; //#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"; /** Force the classic multi-step interactive wizard instead of the bootstrap flow. */ classic?: boolean; 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/config-reload-status.types.d.ts type GatewayHotReloadStatus = "active" | "disabled"; //#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[]; }; /** Dead-lettered delivery queue entries surfaced in health output. */ type DeliveryQueueHealthSummary = { failed: Array<{ queueName: string; count: number; oldestFailedAt?: number; }>; }; /** Optional model pricing cache health reported by the gateway. */ type ModelPricingHealthSummary = GatewayModelPricingHealth; /** Config hot-reload watcher status, present only when a reloader is running. */ type ConfigReloadHealthSummary = { hotReloadStatus: GatewayHotReloadStatus; }; /** Full gateway health payload consumed by `openclaw health`. */ type HealthSummary = { ok: true; ts: number; durationMs: number; eventLoop?: GatewayEventLoopHealth; plugins?: PluginHealthSummary; contextEngines?: ContextEngineHealthSummary; deliveryQueues?: DeliveryQueueHealthSummary; modelPricing?: ModelPricingHealthSummary; configReload?: ConfigReloadHealthSummary; 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/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, validate?: (value: string) => string | undefined): Promise; private resolveStep; getStatus(): WizardSessionStatus; getError(): string | undefined; } //#endregion //#region src/gateway/agent-runtime-identity-token.d.ts type AgentRuntimeIdentity = { kind: "agentRuntime"; agentId: string; sessionKey: string; }; //#endregion //#region src/gateway/server-chat-state.d.ts type ChatRunTiming = { ackedAtMs: number; connId: string; dispatchStartedAtMs?: number; firstAssistantEventSent?: boolean; receivedAtMs: number; }; type ChatRunRegistration = { sessionKey: string; agentId?: string; clientRunId: string; chatSendTiming?: ChatRunTiming; }; type ChatRunEntry = ChatRunRegistration & { registeredAtMs: number; registeredSequence: number; }; type ChatAbortMarker = number | { abortedAtMs: number; sequence: number; }; type BufferedAgentEvent = { sessionKey?: string; agentId?: string; payload: AgentEventPayload & { spawnedBy?: string; }; }; //#endregion //#region src/gateway/chat-abort.d.ts type ChatAbortControllerEntry = { controller: AbortController; sessionId: string; sessionKey: string; lifecycleGeneration?: string; agentId?: string; startedAtMs: number; expiresAtMs: number; ownerConnId?: string; ownerDeviceId?: string; providerId?: string; authProviderId?: string; abortStopReason?: string; /** Latest argument-free validation diagnostic for operator-initiated aborts. */ toolErrorSummary?: 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; /** True after the terminal session-store update has completed. */ projectSessionTerminalPersisted?: boolean; /** A terminal lifecycle event was observed and is awaiting persistence. */ projectSessionTerminalPending?: boolean; /** Store timestamp expected from the observed terminal lifecycle event. */ projectSessionTerminalObservedAt?: number; /** In-flight terminal session-store update used by restart shutdown. */ projectSessionTerminalPersistence?: Promise; /** Caller completion requested cleanup before terminal lifecycle persistence settled. */ registrationCleanupRequested?: boolean; /** False after the owning reply run commits a terminal outcome. */ isAbortable?: (entry: ChatAbortControllerEntry) => boolean; /** Runs once when this registration is actually removed. */ onRemoved?: () => void; /** * 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"; /** Side questions stay independent from main-turn TUI session stops. */ turnKind?: "main" | "btw"; }; //#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; approvalReviewerDeviceIds?: string[]; 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; 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/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; connect: ConnectParams; connId: string; isDeviceTokenAuth?: boolean; usesSharedGatewayAuth: boolean; sharedGatewaySessionGeneration?: string; presenceKey?: string; clientIp?: string; internal?: { approvalRuntime?: boolean; agentRuntimeIdentity?: AgentRuntimeIdentity; }; 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[]; sessionCapsCeiling?: string[]; caps: string[]; declaredCommands: string[]; sessionCommandsCeiling?: 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; 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-shared.d.ts type DedupeEntry = { ts: number; ok: boolean; payload?: unknown; error?: ErrorShape; }; //#endregion //#region src/gateway/terminal/launch.d.ts /** Why a terminal cannot open, or `null` when it can. */ type TerminalLaunchBlock = { kind: "disabled"; } | { kind: "unknown-agent"; agentId: string; } | { kind: "sandboxed"; agentId: string; mode: "all"; }; /** Resolved plan for a host terminal session. */ type TerminalLaunchPlan = { agentId: string; cwd: string; shell: string; args: string[]; }; /** Terminal launch resolution result: either a runnable plan or a block reason. */ type TerminalLaunchResolution = { ok: true; plan: TerminalLaunchPlan; } | { ok: false; block: TerminalLaunchBlock; }; //#endregion //#region src/gateway/terminal/pty.d.ts /** Live PTY handle used by one operator terminal session. */ type TerminalPtyHandle = { pid: number; write: (data: string) => void; resize: (cols: number, rows: number) => void; onData: (listener: (chunk: string) => void) => void; onExit: (listener: (event: { exitCode: number; signal?: number; }) => void) => void; kill: (signal?: string) => void; }; /** Spawns a PTY process and adapts it to the terminal session handle. */ declare function spawnTerminalPty(params: { file: string; args: string[]; cwd?: string; env: Record; cols: number; rows: number; }): Promise; //#endregion //#region src/gateway/terminal/session-manager.d.ts /** Emits one terminal event frame to the single owning connection. */ type TerminalEventSink = (connId: string, event: string, payload: unknown) => void; /** Injectable PTY spawner so tests can drive sessions without a real shell. */ type TerminalSpawner = typeof spawnTerminalPty; /** One session's facts as reported by terminal.list. */ type TerminalSessionSummary = { sessionId: string; agentId: string; shell: string; cwd: string; attached: boolean; createdAtMs: number; }; /** Default grace period before a detached session is killed (seconds). */ type TerminalSessionManagerOptions = { emit: TerminalEventSink; spawn?: TerminalSpawner; maxSessions?: number; env?: NodeJS.ProcessEnv; /** * How long a session may stay detached after its connection drops before it * is killed. 0 (default) preserves kill-on-disconnect; the config-facing * default lives in DEFAULT_TERMINAL_DETACH_SECONDS and is applied by the * gateway wiring. */ detachGraceMs?: number; maxDetachedSessions?: number; scrollbackChars?: number; }; /** Parameters for a resolved host terminal launch (isolation already checked). */ type TerminalOpenRequest = { connId: string; agentId: string; cwd: string; shell: string; args: string[]; cols: number; rows: number; env: Record; }; type TerminalOpenOutcome = { ok: true; sessionId: string; agentId: string; cwd: string; shell: string; } | { ok: false; code: "limit" | "spawn_failed" | "closed"; message: string; }; /** * Tracks live PTY sessions keyed by session id, with a reverse index by * connection so a disconnect can tear down every shell it owned. */ declare class TerminalSessionManager { private readonly sessions; private readonly byConn; private readonly pendingOpens; private readonly emit; private readonly spawn; private readonly maxSessions; private readonly detachGraceMs; private readonly maxDetachedSessions; private readonly scrollbackChars; private opening; constructor(options: TerminalSessionManagerOptions); /** Number of live sessions; used by tests and health surfaces. */ get size(): number; /** Spawns a shell and wires its output/exit to the owning connection. */ open(request: TerminalOpenRequest): Promise; /** Writes client input to a session; returns false when the session is gone. */ write(connId: string, sessionId: string, data: string): boolean; /** Applies a new PTY grid size; returns false when the session is gone. */ resize(connId: string, sessionId: string, cols: number, rows: number): boolean; /** Closes one session on operator request. */ close(connId: string, sessionId: string): boolean; /** * Rebinds a live-or-detached session to `connId` and returns the replay * buffer. Take-over is deliberate: the surface is operator.admin (full host * access already), so any admin connection may adopt any session; a previous * live owner is notified with reason "detached". Snapshot and rebind happen * in one synchronous step, so no PTY chunk can land in both the returned * buffer and the new owner's event stream. */ attach(connId: string, sessionId: string): { sessionId: string; agentId: string; cwd: string; shell: string; buffer: string; } | undefined; /** Every live session, oldest first; all admin connections see the same list. */ list(): TerminalSessionSummary[]; /** Raw buffered output for one session, or undefined when it is gone. */ snapshot(sessionId: string): string | undefined; private trackPendingOpen; private untrackPendingOpen; /** * Handles a dropped connection: detaches its sessions for later reattach * when a grace period is configured, otherwise kills them (legacy behavior, * still selected by detachedSessionTimeoutSeconds: 0). */ handleDisconnect(connId: string): void; /** Closes live and pending sessions whose agent no longer permits a host shell. */ closeDisallowedAgents(isAllowed: (agentId: string) => boolean): void; /** Parks a session ownerless with a reaper; PTY output keeps buffering. */ private detach; private enforceDetachedCap; /** * Tears down every session — detached ones included — on gateway * shutdown/stop. Silent because the sockets are going away anyway (disabling * the terminal is a `gateway` restart, so that path also runs through here, * not a live notification). */ disposeAll(): void; private indexByConn; private ownedSession; private finalize; } //#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; agentRuntimeIdentity?: AgentRuntimeIdentity; 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; resolveTerminalLaunchPolicy: (agentId?: string) => TerminalLaunchResolution; isTerminalEnabled: () => boolean; 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; terminalSessions?: TerminalSessionManager; agentRunSeq: Map; chatAbortControllers: Map; /** Cancel identities for turns waiting in the followup/collect queue. */ chatQueuedTurns: Map; chatAbortedRuns: Map; chatRunBuffers: Map; chatDeltaSentAt: Map; chatDeltaLastBroadcastLen: Map; chatDeltaLastBroadcastText: Map; agentDeltaSentAt: Map; bufferedAgentEvents: Map; clearChatRunState: (runId: string) => void; addChatRun: (sessionId: string, entry: ChatRunRegistration) => void; removeChatRun: (sessionId: string, clientRunId: string, sessionKey?: string) => ChatRunEntry | 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; crestodianSessions: Map; findRunningWizard: () => string | null; purgeWizardSession: (id: string) => void; getRuntimeSnapshot: () => ChannelRuntimeSnapshot; getEventLoopHealth?: () => GatewayEventLoopHealth | undefined; getConfigReloaderHotReloadStatus?: () => GatewayHotReloadStatus | undefined; startChannel: (channel: ChannelId$1, accountId?: string, opts?: StartChannelOptions) => Promise; stopChannel: (channel: ChannelId$1, accountId?: string) => Promise; markChannelLoggedOut: (channelId: ChannelId$1, 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 //#region src/realtime-transcription/provider-types.d.ts type RealtimeTranscriptionProviderId = string; type RealtimeTranscriptionProviderConfig = Record; type RealtimeTranscriptionProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: RealtimeTranscriptionProviderConfig; }; type RealtimeTranscriptionProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: RealtimeTranscriptionProviderConfig; }; /** Callback hooks emitted by realtime transcription sessions. */ type RealtimeTranscriptionSessionCallbacks = { onPartial?: (partial: string) => void; onTranscript?: (transcript: string) => void; onSpeechStart?: () => void; onError?: (error: Error) => void; }; /** Inputs passed to a provider when creating a transcription session. */ type RealtimeTranscriptionSessionCreateRequest = RealtimeTranscriptionSessionCallbacks & { cfg?: OpenClawConfig; providerConfig: RealtimeTranscriptionProviderConfig; }; /** Runtime control surface for a realtime transcription session. */ type RealtimeTranscriptionSession = { connect(): Promise; sendAudio(audio: Buffer): void; close(): void; isConnected(): boolean; }; //#endregion //#region src/security/audit.types.d.ts /** Severity levels emitted by security audit checks. */ type SecurityAuditSeverity = "info" | "warn" | "critical"; /** One actionable or informational security audit finding. */ type SecurityAuditFinding = { checkId: string; severity: SecurityAuditSeverity; title: string; detail: string; remediation?: string; }; //#endregion //#region src/talk/provider-types.d.ts type RealtimeVoiceProviderId = string; type RealtimeVoiceRole = "user" | "assistant"; type RealtimeVoiceCloseReason = "completed" | "error"; type RealtimeVoiceAudioFormat = { encoding: "g711_ulaw"; sampleRateHz: 8000; channels: 1; } | { encoding: "pcm16"; sampleRateHz: 24000; channels: 1; }; declare const REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ: RealtimeVoiceAudioFormat; declare const REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ: RealtimeVoiceAudioFormat; type RealtimeVoiceTool = { type: "function"; name: string; description: string; parameters: { type: "object"; properties: Record; required?: string[]; }; }; type RealtimeVoiceToolCallEvent = { itemId: string; callId: string; name: string; args: unknown; }; type RealtimeVoiceToolResultOptions = { /** * Submit the tool result without prompting the realtime provider to generate a new assistant * response. Use when another channel has already delivered the user-visible answer. */ suppressResponse?: boolean; willContinue?: boolean; }; type RealtimeVoiceBridgeEvent = { direction: "client" | "server"; type: string; detail?: string; itemId?: string; responseId?: string; }; type RealtimeVoiceAudioClearReason = "barge-in"; type RealtimeVoiceBridgeCallbacks = { onAudio: (audio: Buffer) => void; onClearAudio: (reason?: RealtimeVoiceAudioClearReason) => void; onMark?: (markName: string) => void; onTranscript?: (role: RealtimeVoiceRole, text: string, isFinal: boolean) => void; onEvent?: (event: RealtimeVoiceBridgeEvent) => void; onToolCall?: (event: RealtimeVoiceToolCallEvent) => void; onReady?: () => void; onError?: (error: Error) => void; onClose?: (reason: RealtimeVoiceCloseReason) => void; }; type RealtimeVoiceProviderConfig = Record; type RealtimeVoiceProviderCapabilities = { transports: TalkTransport[]; inputAudioFormats: RealtimeVoiceAudioFormat[]; outputAudioFormats: RealtimeVoiceAudioFormat[]; supportsBrowserSession?: boolean; supportsBargeIn?: boolean; /** True when provider VAD reports confirmed interruptions through onClearAudio("barge-in"). */ handlesInputAudioBargeIn?: boolean; supportsToolCalls?: boolean; supportsVideoFrames?: boolean; supportsSessionResumption?: boolean; }; type RealtimeVoiceProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: RealtimeVoiceProviderConfig; }; type RealtimeVoiceProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: RealtimeVoiceProviderConfig; }; type RealtimeVoiceBridgeCreateRequest = RealtimeVoiceBridgeCallbacks & { cfg?: OpenClawConfig; providerConfig: RealtimeVoiceProviderConfig; audioFormat?: RealtimeVoiceAudioFormat; instructions?: string; autoRespondToAudio?: boolean; interruptResponseOnInputAudio?: boolean; tools?: RealtimeVoiceTool[]; }; type RealtimeVoiceBrowserSessionCreateRequest = { cfg?: OpenClawConfig; providerConfig: RealtimeVoiceProviderConfig; instructions?: string; tools?: RealtimeVoiceTool[]; model?: string; voice?: string; vadThreshold?: number; silenceDurationMs?: number; prefixPaddingMs?: number; reasoningEffort?: string; }; type RealtimeVoiceBrowserAudioContract = { inputEncoding: "pcm16" | "g711_ulaw"; inputSampleRateHz: number; outputEncoding: "pcm16" | "g711_ulaw"; outputSampleRateHz: number; }; type RealtimeVoiceBrowserWebRtcSdpSession = { provider: RealtimeVoiceProviderId; transport: "webrtc"; clientSecret: string; offerUrl?: string; offerHeaders?: Record; model?: string; voice?: string; expiresAt?: number; }; type RealtimeVoiceBrowserJsonPcmWebSocketSession = { provider: RealtimeVoiceProviderId; transport: "provider-websocket"; protocol: string; clientSecret: string; websocketUrl: string; audio: RealtimeVoiceBrowserAudioContract; initialMessage?: unknown; model?: string; voice?: string; expiresAt?: number; }; type RealtimeVoiceBrowserGatewayRelaySession = { provider: RealtimeVoiceProviderId; transport: "gateway-relay"; relaySessionId: string; audio: RealtimeVoiceBrowserAudioContract; model?: string; voice?: string; expiresAt?: number; }; type RealtimeVoiceBrowserManagedRoomSession = { provider: RealtimeVoiceProviderId; transport: "managed-room"; roomUrl: string; token?: string; model?: string; voice?: string; expiresAt?: number; }; type RealtimeVoiceBrowserSession = RealtimeVoiceBrowserWebRtcSdpSession | RealtimeVoiceBrowserJsonPcmWebSocketSession | RealtimeVoiceBrowserGatewayRelaySession | RealtimeVoiceBrowserManagedRoomSession; type RealtimeVoiceBridge = { supportsToolResultContinuation?: boolean; connect(): Promise; sendAudio(audio: Buffer): void; setMediaTimestamp(ts: number): void; sendUserMessage?(text: string): void; triggerGreeting?(instructions?: string): void; handleBargeIn?(options?: RealtimeVoiceBargeInOptions): void; submitToolResult(callId: string, result: unknown, options?: RealtimeVoiceToolResultOptions): void; acknowledgeMark(): void; close(): void; isConnected(): boolean; }; type RealtimeVoiceBargeInOptions = { /** * The caller has already confirmed assistant audio is still playing in its output sink. * This lets providers interrupt output even when the sink cannot provide real playback marks. */ audioPlaybackActive?: boolean; /** Interrupt even when normal barge-in audio-duration guards would treat the event as echo. */ force?: boolean; }; //#endregion //#region src/plugins/provider-config-context.types.d.ts /** * Provider-owned config normalization for `models.providers.` entries. * * Use this for provider-specific config cleanup that should stay with the * plugin rather than in core config-policy tables. */ type ProviderNormalizeConfigContext = { provider: string; providerConfig: ModelProviderConfig; }; /** * Provider-owned env/config auth marker resolution for `models.providers`. * * Use this when a provider resolves auth from env vars that do not follow the * generic API-key conventions. */ type ProviderResolveConfigApiKeyContext = { provider: string; env: NodeJS.ProcessEnv; }; /** * Provider-owned config-default application input. * * Use this when a provider needs to add global config defaults that depend on * provider auth mode or provider-specific model families. */ type ProviderApplyConfigDefaultsContext = { provider: string; config: OpenClawConfig; env: NodeJS.ProcessEnv; }; //#endregion //#region src/plugins/provider-oauth-flow.d.ts /** Prompt payload used when OAuth flow code entry needs user input. */ type OAuthPrompt = { message: string; placeholder?: string; }; /** Creates OAuth callbacks that use local browser auth locally and manual code entry on VPS hosts. */ declare function createVpsAwareOAuthHandlers(params: { isRemote: boolean; prompter: WizardPrompter; runtime: RuntimeEnv; spin: ReturnType; openUrl: (url: string) => Promise; localBrowserMessage: string; manualPromptMessage?: string; }): { onAuth: (event: { url: string; }) => Promise; onPrompt: (prompt: OAuthPrompt) => Promise; }; //#endregion //#region src/plugins/types.d.ts type ModelProviderRequestTransportOverrides = ModelProviderRequestTransportOverrides$1; type ChannelId = ChannelId$1; type ChannelPlugin = ChannelPlugin$2; type ProviderAuthOptionBag = { token?: string; tokenProvider?: string; secretInputMode?: SecretInputMode; [key: string]: unknown; }; /** Logger passed into plugin registration, services, and CLI surfaces. */ type PluginLogger = { debug?: (message: string) => void; info: (message: string) => void; warn: (message: string) => void; error: (message: string) => void; }; type PluginConfigValidation = { ok: true; value?: unknown; } | { ok: false; errors: string[]; }; /** * Config schema contract accepted by plugin manifests and runtime registration. * * Plugins can provide a Zod-like parser, a lightweight `validate(...)` * function, or both. `uiHints` and `jsonSchema` are optional extras for docs, * forms, and config UIs. */ type OpenClawPluginConfigSchema = { safeParse?: (value: unknown) => { success: boolean; data?: unknown; error?: { issues?: Array<{ path: Array; message: string; }>; }; }; parse?: (value: unknown) => unknown; validate?: (value: unknown) => PluginConfigValidation; uiHints?: Record; jsonSchema?: JsonSchemaObject; }; type ProviderAuthKind = "oauth" | "api_key" | "token" | "device_code" | "custom"; /** Standard result payload returned by provider auth methods. */ type ProviderAuthResult = { profiles: Array<{ profileId: string; credential: AuthProfileCredential; }>; /** * Optional config patch to merge after credentials are written. * * Use this for provider-owned onboarding defaults such as * `models.providers.` entries, default aliases, or agent model helpers. * The caller still persists auth-profile bindings separately. */ configPatch?: Partial; defaultModel?: string; notes?: string[]; /** * Opt in to replace `agents.defaults.models` wholesale with the patch map. * Default behavior merges the map so other providers' entries survive. * Set only from migrations that intentionally rename/remove model keys. */ replaceDefaultModels?: boolean; }; /** Interactive auth context passed to provider login/setup methods. */ type ProviderAuthContext = { config: OpenClawConfig; env?: NodeJS.ProcessEnv; agentDir?: string; workspaceDir?: string; prompter: WizardPrompter; runtime: RuntimeEnv; /** * Optional onboarding CLI options that triggered this auth flow. * * Present for setup/configure/auth-choice flows so provider methods can * honor preseeded flags like `--openai-api-key` or generic * `--token/--token-provider` pairs. Direct `models auth login` usually * leaves this undefined. */ opts?: ProviderAuthOptionBag; /** * Onboarding secret persistence preference. * * Interactive wizard flows set this when the caller explicitly requested * plaintext or env/file/exec ref storage. Ad-hoc `models auth login` flows * usually leave it undefined. */ secretInputMode?: SecretInputMode; /** * Whether the provider auth flow should offer the onboarding secret-storage * mode picker when `secretInputMode` is unset. * * This is true for onboarding/configure flows and false for direct * `models auth` commands, which should keep a tighter, provider-owned prompt * surface. */ allowSecretRefPrompt?: boolean; isRemote: boolean; openUrl: (url: string) => Promise; oauth: { createVpsAwareHandlers: typeof createVpsAwareOAuthHandlers; }; }; type ProviderNonInteractiveApiKeyResult = { key: string; source: "profile" | "env" | "flag"; envVarName?: string; }; type ProviderResolveNonInteractiveApiKeyParams = { provider: string; flagValue?: string; flagName: `--${string}`; envVar: string; envVarName?: string; allowProfile?: boolean; required?: boolean; }; type ProviderNonInteractiveApiKeyCredentialParams = { provider: string; resolved: ProviderNonInteractiveApiKeyResult; email?: string; metadata?: Record; }; type ProviderAuthMethodNonInteractiveContext = { authChoice: string; config: OpenClawConfig; baseConfig: OpenClawConfig; opts: ProviderAuthOptionBag; runtime: RuntimeEnv; agentDir?: string; workspaceDir?: string; resolveApiKey: (params: ProviderResolveNonInteractiveApiKeyParams) => Promise; toApiKeyCredential: (params: ProviderNonInteractiveApiKeyCredentialParams) => ApiKeyCredential | null; }; type ProviderAuthMethod = { id: string; label: string; hint?: string; kind: ProviderAuthKind; /** Provider-owned model used to validate app-guided secret setup. */ starterModel?: string; /** * Optional wizard/onboarding metadata for this specific auth method. * * Use this when one provider exposes multiple setup entries (for example API * key + OAuth, or region-specific login flows). OpenClaw uses this to expose * method-specific auth choices while keeping the provider id stable. */ wizard?: ProviderPluginWizardSetup; run: (ctx: ProviderAuthContext) => Promise; runNonInteractive?: (ctx: ProviderAuthMethodNonInteractiveContext) => Promise; }; type ProviderCatalogOrder = "simple" | "profile" | "paired" | "late"; type ProviderCatalogContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; resolveProviderApiKey: (providerId?: string) => { apiKey: string | undefined; discoveryApiKey?: string; }; resolveProviderAuth: (providerId?: string, options?: { oauthMarker?: string; }) => { apiKey: string | undefined; discoveryApiKey?: string; mode: "api_key" | "aws-sdk" | "oauth" | "token" | "none"; source: "env" | "profile" | "none"; profileId?: string; }; }; type ProviderCatalogResult = { provider: ModelProviderConfig; } | { providers: Record; } | null | undefined; type ProviderPluginCatalog = { order?: ProviderCatalogOrder; run: (ctx: ProviderCatalogContext) => Promise; }; type UnifiedModelCatalogProviderContext = ProviderCatalogContext & { signal?: AbortSignal; includeLive?: boolean; timeoutMs?: number; }; type UnifiedModelCatalogProviderPlugin = { provider: string; kinds: readonly UnifiedModelCatalogKind[]; staticCatalog?: (ctx: UnifiedModelCatalogProviderContext) => readonly UnifiedModelCatalogEntry[] | Promise | null | undefined; liveCatalog?: (ctx: UnifiedModelCatalogProviderContext) => readonly UnifiedModelCatalogEntry[] | Promise | null | undefined; }; type ProviderRuntimeProviderConfig = { baseUrl?: string; api?: ModelProviderConfig["api"]; auth?: ModelProviderConfig["auth"]; models?: ModelProviderConfig["models"]; headers?: unknown; }; /** * Sync hook for provider-owned model ids that are not present in the local * registry/catalog yet. * * Use this for pass-through providers or provider-specific forward-compat * behavior. The hook should be cheap and side-effect free; async refreshes * belong in `prepareDynamicModel`. */ type ProviderResolveDynamicModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; agentRuntimeId?: string; provider: string; modelId: string; modelRegistry: ModelRegistry; providerConfig?: ProviderRuntimeProviderConfig; authProfileId?: string; authProfileMode?: AuthProfileCredential["type"] | "aws-sdk"; }; /** * Optional async warm-up for dynamic model resolution. * * Called only from async model resolution paths, before retrying * `resolveDynamicModel`. This is the place to refresh caches or fetch provider * metadata over the network. */ type ProviderPrepareDynamicModelContext = ProviderResolveDynamicModelContext; type ProviderPreferRuntimeResolvedModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; }; /** * Last-chance rewrite hook for provider-owned transport normalization. * * Runs after OpenClaw resolves an explicit/discovered/dynamic model and before * the embedded runner uses it. Typical uses: swap API ids, fix base URLs, or * patch provider-specific compat bits. */ type ProviderNormalizeResolvedModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; model: ProviderRuntimeModel; }; /** * Provider-owned model-id normalization before config/runtime lookup. * * Use this for provider-specific alias cleanup that should stay with the * plugin rather than in core string tables. */ type ProviderNormalizeModelIdContext = { provider: string; modelId: string; }; /** * Provider-owned transport normalization for arbitrary provider/model config. * * Use this when transport cleanup depends on API/baseUrl rather than the * owning provider id, for example custom providers that still target a * plugin-owned transport family. */ type ProviderNormalizeTransportContext = { config?: OpenClawConfig; workspaceDir?: string; provider: string; modelId?: string; api?: string | null; baseUrl?: string; }; /** * Runtime auth input for providers that need an extra exchange step before * inference. The incoming `apiKey` is the raw credential resolved from auth * profiles/env/config. The returned value should be the actual token/key to use * for the request. */ type ProviderPrepareRuntimeAuthContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; model: ProviderRuntimeModel; apiKey: string; authMode: string; profileId?: string; }; /** * Result of `prepareRuntimeAuth`. * * `apiKey` is required and becomes the runtime credential stored in auth * storage. `baseUrl` is optional and lets providers like GitHub Copilot swap to * an entitlement-specific endpoint at request time. `expiresAt` enables generic * background refresh in long-running turns. */ type ProviderPreparedRuntimeAuth = { apiKey: string; baseUrl?: string; request?: ModelProviderRequestTransportOverrides; expiresAt?: number; }; /** * Usage/billing auth input for providers that expose quota/usage endpoints. * * This hook is intentionally separate from `prepareRuntimeAuth`: usage * snapshots often need a different credential source than live inference * requests, and they run outside the embedded runner. * * The helper methods cover the common OpenClaw auth resolution paths: * * - `resolveApiKeyFromConfigAndStore`: env/config/plain token/api_key profiles * - `resolveOAuthToken`: oauth/token profiles resolved through the auth store, * optionally for an explicit provider override * * Plugins can still do extra provider-specific work on top (for example parse a * token blob, read a legacy credential file, or pick between aliases). */ type ProviderResolveUsageAuthContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; resolveApiKeyFromConfigAndStore: (params?: { providerIds?: string[]; envDirect?: Array; }) => string | undefined; /** Ordered API-key/token candidates, including resolved SecretRefs, for credential classification. */ resolveApiKeyCandidatesFromConfigAndStore?: (params?: { providerIds?: string[]; envDirect?: Array; }) => Promise; resolveOAuthToken: (params?: { provider?: string; }) => Promise; }; type ProviderUsageAuthToken = { token: string; accountId?: string; }; /** * Result of `resolveUsageAuth`. * * Two shapes are supported: * - `{ token: string; accountId?: string }` — use this token for provider usage endpoints. * - `{ handled: true }` — this provider handled the request but has no usable * usage token; core must skip further fallback (generic API-key/OAuth fallback * must not run). * * Returning `null` or `undefined` means "not handled by this provider"; core * proceeds to generic fallback resolution. */ type ProviderResolvedUsageAuth = ProviderUsageAuthToken | { handled: true; }; /** * Usage/quota snapshot input for providers that own their usage endpoint * fetch/parsing behavior. * * This hook runs after `resolveUsageAuth` succeeds. Core still owns summary * fan-out, timeout wrapping, filtering, and formatting; the provider plugin * owns the provider-specific HTTP request + response normalization. */ type ProviderFetchUsageSnapshotContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; token: string; accountId?: string; authProfileId?: string; timeoutMs: number; fetchFn: typeof fetch; }; /** * Provider-owned auth-doctor hint input. * * Called when OAuth refresh fails and OpenClaw wants a provider-specific repair * hint to append to the generic re-auth message. Use this for legacy profile-id * migrations or other provider-owned auth-store cleanup guidance. */ type ProviderAuthDoctorHintContext = { config?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId?: string; }; /** * Provider-owned extra-param normalization before OpenClaw builds its generic * stream option wrapper. * * Use this to set provider defaults or rewrite provider-specific config keys * into the merged `extraParams` object. Return the full next extraParams object. */ /** Provider-facing effort after OpenClaw lowers orchestration-only modes. */ type ProviderTransportThinkingLevel = Exclude; type ProviderPrepareExtraParamsContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; agentId?: string; nativeWebSearchAllowedByToolPolicy?: boolean; provider: string; modelId: string; model?: ProviderRuntimeModel; extraParams?: Record; thinkingLevel?: ProviderTransportThinkingLevel; }; type ProviderExtraParamsForTransportContext = Omit & { model?: ProviderRuntimeModel; transport?: "sse" | "websocket" | "auto"; extraParams: Record; }; type ProviderExtraParamsForTransportResult = { patch?: Record | null; }; type ProviderResolvePromptOverlayContext = ProviderSystemPromptContributionContext & { baseOverlay?: ProviderSystemPromptContribution; }; type ProviderFollowupFallbackRouteContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; payload: ReplyPayload; originatingChannel?: string; originatingTo?: string; originRoutable: boolean; dispatcherAvailable: boolean; }; type ProviderFollowupFallbackRouteResult = { route?: "origin" | "dispatcher" | "drop"; reason?: string; }; type ProviderResolveAuthProfileIdContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; preferredProfileId?: string; lockedProfileId?: string; profileOrder: string[]; authStore: AuthProfileStore; }; type ProviderReplaySanitizeMode = "full" | "images-only"; type ProviderReplayToolCallIdMode = "strict" | "strict9"; type ProviderReasoningOutputMode = "native" | "tagged"; /** * @deprecated Legacy static provider capability bag. * * Core replay/runtime ownership now lives on explicit provider hooks such as * `buildReplayPolicy`, `normalizeToolSchemas`, and `wrapStreamFn`. OpenClaw no * longer reads this bag at runtime, but the field remains typed so existing * third-party plugins do not fail to compile immediately. */ type ProviderCapabilities = Record; /** * Provider-owned replay/compaction transcript policy. * * These values are consumed by shared history replay and compaction logic. * Return only the fields the provider wants to override; core fills the rest * with its default policy. */ type ProviderReplayPolicy = { sanitizeMode?: ProviderReplaySanitizeMode; sanitizeToolCallIds?: boolean; toolCallIdMode?: ProviderReplayToolCallIdMode; duplicateToolCallIdStyle?: "openai"; preserveNativeAnthropicToolUseIds?: boolean; preserveSignatures?: boolean; sanitizeThoughtSignatures?: { allowBase64Only?: boolean; includeCamelCase?: boolean; }; dropThinkingBlocks?: boolean; dropReasoningFromHistory?: boolean; repairToolUseResultPairing?: boolean; applyAssistantFirstOrderingFix?: boolean; validateGeminiTurns?: boolean; validateAnthropicTurns?: boolean; allowSyntheticToolResults?: boolean; }; /** * Provider-owned replay/compaction policy input. * * Use this when transcript replay rules depend on provider/model transport * behavior and should stay with the provider plugin instead of core tables. */ type ProviderReplayPolicyContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env?: NodeJS.ProcessEnv; provider: string; modelId?: string; modelApi?: string | null; model?: ProviderRuntimeModel; }; type ProviderReplaySessionEntry = { customType: string; data?: unknown; }; type ProviderReplaySessionState = { getCustomEntries(): ProviderReplaySessionEntry[]; appendCustomEntry(customType: string, data: unknown): void; }; /** * Provider-owned replay-history sanitization input. * * Runs after core applies generic transcript cleanup so plugins can make * provider-specific replay rewrites without owning the whole compaction flow. */ type ProviderSanitizeReplayHistoryContext = ProviderReplayPolicyContext & { sessionId: string; messages: AgentMessage[]; allowedToolNames?: Iterable; sessionState?: ProviderReplaySessionState; }; /** * Provider-owned final replay-turn validation input. * * Use this for providers that require strict turn ordering or additional * replay-time transcript validation beyond generic sanitation. */ type ProviderValidateReplayTurnsContext = ProviderReplayPolicyContext & { sessionId?: string; messages: AgentMessage[]; sessionState?: ProviderReplaySessionState; }; /** * Provider-owned tool-schema normalization input. * * Runs before tool registration for replay/compaction/inference so providers * can rewrite schema keywords that their transport family does not support. */ type ProviderNormalizeToolSchemasContext = ProviderReplayPolicyContext & { tools: AnyAgentTool[]; }; type ProviderToolSchemaDiagnostic = { toolName: string; toolIndex?: number; violations: string[]; }; /** * Provider-owned reasoning output mode input. * * Use this when a provider requires a specific reasoning-output contract, such * as text tags instead of native structured reasoning fields. */ type ProviderReasoningOutputModeContext = ProviderReplayPolicyContext; /** * Provider-owned transport creation. * * Use this when the provider needs to replace shared model runtime's default transport with a * custom StreamFn (for example a native API transport that cannot be expressed * as a wrapper around `streamSimple`). */ type ProviderCreateStreamFnContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; model: ProviderRuntimeModel; }; /** * Provider-owned stream wrapper hook after OpenClaw applies its generic * transport-independent wrappers. * * Use this for provider-specific payload/header/model mutations that still run * through the normal `shared model runtime` stream path. */ type ProviderWrapStreamFnContext = ProviderPrepareExtraParamsContext & { model?: ProviderRuntimeModel; streamFn?: StreamFn; }; /** * Provider-owned transport turn state. * * Use this for provider-native request headers or metadata that should stay * stable across retries while still being attached by generic core transports. */ type ProviderTransportTurnState = { headers?: Record; metadata?: Record; }; /** * Provider-owned request identity for transport turns. * * Use this when the provider exposes native request/session metadata that must * be attached by both HTTP and WebSocket transports. */ type ProviderResolveTransportTurnStateContext = { provider: string; modelId: string; model?: ProviderRuntimeModel; sessionId?: string; turnId: string; attempt: number; transport: "stream" | "websocket"; }; /** * Provider-owned WebSocket session policy. * * Use this for session-scoped headers or cool-down behavior that should apply * before a generic WebSocket transport decides to retry or fall back. */ type ProviderWebSocketSessionPolicy = { headers?: Record; degradeCooldownMs?: number; }; /** * Provider-owned WebSocket session policy input. * * Use this when the provider wants to control native session handshake headers * or the post-failure cool-down window for a generic WebSocket transport. */ type ProviderResolveWebSocketSessionPolicyContext = { provider: string; modelId: string; model?: ProviderRuntimeModel; sessionId?: string; }; /** * Provider-owned failover error classification input. * * Use this when provider-specific transport or API errors need classification * hints that generic string matching cannot express safely. */ type ProviderFailoverErrorContext = { provider?: string; modelId?: string; errorMessage: string; status?: number; code?: string; errorType?: string; }; /** * Generic embedding provider shape returned by provider plugins. * * Keep this aligned with the memory embedding contract without forcing the * plugin system to import memory internals directly. */ type PluginEmbeddingProvider = { id: string; model: string; maxInputTokens?: number; embedQuery: (text: string, options?: { signal?: AbortSignal; }) => Promise; embedBatch: (texts: string[], options?: { signal?: AbortSignal; }) => Promise; embedBatchInputs?: (inputs: unknown[], options?: { signal?: AbortSignal; }) => Promise; client?: unknown; }; /** * Provider-owned embedding transport creation. * * Use this when a provider wants memory embeddings to live with the provider * plugin instead of the core memory switchboard. */ type ProviderCreateEmbeddingProviderContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; model: string; remote?: { baseUrl?: string; apiKey?: unknown; headers?: Record; }; providerApiKey?: string; inputType?: string; queryInputType?: string; documentInputType?: string; outputDimensionality?: number; taskType?: string; }; /** * Provider-owned prompt-cache eligibility. * * Return `true` or `false` to override OpenClaw's built-in provider cache TTL * detection for this provider. Return `undefined` to fall back to core rules. */ type ProviderCacheTtlEligibilityContext = { provider: string; modelId: string; modelApi?: string; }; /** * Provider-owned missing-auth message override. * * Runs only after OpenClaw exhausts normal env/profile/config auth resolution * for the requested provider. Return a custom message to replace the generic * "No API key found" error. */ type ProviderBuildMissingAuthMessageContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; listProfileIds: (providerId: string) => string[]; }; /** * Provider-owned unknown-model hint override. * * Runs after catalog/runtime lookup misses for the requested provider. Return a * hint suffix that OpenClaw should append to the generic `Unknown model` * error. */ type ProviderBuildUnknownModelHintContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; baseUrl?: string; }; /** * Built-in model suppression hook context. * * @deprecated Use manifest `modelCatalog.suppressions`. Runtime suppression * hooks are no longer called by model resolution. */ type ProviderBuiltInModelSuppressionContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; baseUrl?: string; }; type ProviderBuiltInModelSuppressionResult = { suppress: boolean; errorMessage?: string; }; /** * Provider-owned "modern model" policy input. * * Live smoke/model-profile selection uses this to keep provider-specific * inclusion/exclusion rules out of core. */ type ProviderModernModelPolicyContext = { provider: string; modelId: string; }; /** * Final catalog augmentation hook. * * Runs after OpenClaw loads the discovered model catalog and merges configured * opt-in providers. Use this for forward-compat rows or vendor-owned synthetic * entries that should appear in `models list` and model pickers even when the * upstream registry has not caught up yet. */ type ProviderAugmentModelCatalogContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; resolveProviderApiKey?: ProviderCatalogContext["resolveProviderApiKey"]; entries: ModelCatalogEntry[]; }; /** * @deprecated Use ProviderCatalogOrder. */ type ProviderDiscoveryOrder = ProviderCatalogOrder; /** * @deprecated Use ProviderCatalogContext. */ type ProviderDiscoveryContext = ProviderCatalogContext; /** * @deprecated Use ProviderCatalogResult. */ type ProviderDiscoveryResult = ProviderCatalogResult; /** * @deprecated Use ProviderPluginCatalog. */ type ProviderPluginDiscovery = ProviderPluginCatalog; type ProviderPluginWizardSetup = { choiceId?: string; choiceLabel?: string; choiceHint?: string; assistantPriority?: number; assistantVisibility?: "visible" | "manual-only"; onboardingFeatured?: boolean; groupId?: string; groupLabel?: string; groupHint?: string; methodId?: string; /** * Interactive onboarding surfaces where this auth choice should appear. * Defaults to `["text-inference"]` when omitted. */ onboardingScopes?: Array<"text-inference" | "image-generation" | "music-generation">; /** * Optional model-allowlist prompt policy applied after this auth choice is * selected in configure/onboarding flows. * * Keep this UI-facing and static. Provider logic that needs runtime state * should stay in `run`/`runNonInteractive`. */ modelAllowlist?: { allowedKeys?: string[]; initialSelections?: string[]; loadCatalog?: boolean; message?: string; }; /** * Optional default-model prompt policy for this auth/setup choice. * * Use this when selecting the auth choice should still force a model picker * even if the choice was preseeded via CLI/configure, or when "keep current" * would skip required provider-owned post-selection work. */ modelSelection?: { promptWhenAuthChoiceProvided?: boolean; allowKeepCurrent?: boolean; }; }; /** Optional model-picker metadata shown in interactive provider selection flows. */ type ProviderPluginWizardModelPicker = { label?: string; hint?: string; methodId?: string; }; /** UI metadata that lets provider plugins appear in onboarding and configure flows. */ type ProviderPluginWizard = { setup?: ProviderPluginWizardSetup; modelPicker?: ProviderPluginWizardModelPicker; }; type ProviderOAuthProfileIdRepair = { /** * Legacy OAuth profile id to migrate away from. * * When omitted, OpenClaw falls back to `:default`. */ legacyProfileId?: string; /** * Optional custom doctor prompt label. * * Defaults to the provider label when omitted. */ promptLabel?: string; }; type ProviderModelSelectedContext = { config: OpenClawConfig; model: string; prompter: WizardPrompter; agentDir?: string; workspaceDir?: string; }; type ProviderDeferSyntheticProfileAuthContext = { config?: OpenClawConfig; provider: string; providerConfig?: ModelProviderConfig; resolvedApiKey?: string; }; type ProviderSystemPromptContributionContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; promptMode: PromptMode; runtimeChannel?: string; runtimeCapabilities?: string[]; agentId?: string; trigger?: "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; }; type ProviderTransformSystemPromptContext = ProviderSystemPromptContributionContext & { systemPrompt: string; }; type PluginTextTransformRegistration = PluginTextTransforms; /** Text-inference provider capability registered by a plugin. */ type ProviderPlugin = { id: string; pluginId?: string; label: string; docsPath?: string; aliases?: string[]; /** * Internal-only aliases used for runtime/config hook lookup. * * Unlike `aliases`, these values are not treated as user-facing provider ids * for auth/setup surfaces. Use them for legacy config keys or compat-only * hook routing. */ hookAliases?: string[]; /** * Provider-related env vars shown in setup/search/help surfaces. * * Keep entries in preferred display order. This can include direct auth env * vars or setup inputs such as OAuth client id/secret vars. */ envVars?: string[]; auth: ProviderAuthMethod[]; /** * Legacy text-provider catalog hook. * * @deprecated New catalog/control-plane surfaces should use * `api.registerModelCatalogProvider`. This hook remains the text runtime * source until the unified loader fully replaces it. * Returns provider config/model definitions that merge into models.providers. */ catalog?: ProviderPluginCatalog; /** * Legacy offline text-provider catalog hook for display-only surfaces. * * @deprecated New static rows should be registered with * `api.registerModelCatalogProvider`. * * Unlike `catalog`, this hook must not perform network I/O or require real * credentials. Use it for bundled/static rows that can be shown before auth is * configured. */ staticCatalog?: ProviderPluginCatalog; /** * Show catalog row labels as the literal `/` * composition instead of the canonical (deduped) key. * * `modelKey` strips a duplicate `/` prefix so storage and * lookups stay stable. This flag only changes the picker label — the * option value and persisted config remain canonical. * * Set when the leading `/` segment in the native model id is * a meaningful vendor namespace (e.g. NVIDIA's `nvidia/nemotron-...` * alongside `moonshotai/kimi-k2.5`). */ preserveLiteralProviderPrefix?: boolean; /** * @deprecated Use catalog. * * Legacy alias for catalog. * Kept for compatibility with existing provider plugins. */ discovery?: ProviderPluginDiscovery; /** * Sync runtime fallback for model ids not present in the local catalog. * * Hook order: * 1. discovered/static model lookup * 2. plugin `resolveDynamicModel` * 3. core fallback heuristics * 4. generic provider-config fallback * * Keep this hook cheap and deterministic. If you need network I/O first, use * `prepareDynamicModel` to prime state for the async retry path. */ resolveDynamicModel?: (ctx: ProviderResolveDynamicModelContext) => ProviderRuntimeModel | null | undefined; /** * Optional async prefetch for dynamic model resolution. * * OpenClaw calls this only from async model resolution paths. After it * completes, `resolveDynamicModel` is called again. */ prepareDynamicModel?: (ctx: ProviderPrepareDynamicModelContext) => Promise; /** * Lets a provider plugin opt exact configured models into a runtime * metadata comparison pass before the embedded runner returns the explicit * entry unchanged. */ preferRuntimeResolvedModel?: (ctx: ProviderPreferRuntimeResolvedModelContext) => boolean; /** * Provider-owned transport normalization. * * Use this to rewrite a resolved model without forking the generic runner: * swap API ids, update base URLs, or adjust compat flags for a provider's * transport quirks. */ normalizeResolvedModel?: (ctx: ProviderNormalizeResolvedModelContext) => ProviderRuntimeModel | null | undefined; /** * Provider-owned model-id normalization. * * Runs before model lookup/canonicalization. Use this for alias cleanup such * as provider-owned preview/legacy model ids. */ normalizeModelId?: (ctx: ProviderNormalizeModelIdContext) => string | null | undefined; /** * Provider-owned transport-family normalization before generic model * assembly. * * Use this for API/baseUrl cleanup that may apply to custom provider ids * which still target the provider's transport family. */ normalizeTransport?: (ctx: ProviderNormalizeTransportContext) => { api?: string | null; baseUrl?: string; } | null | undefined; /** * Provider-owned config normalization for `models.providers.`. * * Use this for provider-specific baseUrl/model-id cleanup that should stay * with the plugin rather than in core config-policy tables. */ normalizeConfig?: (ctx: ProviderNormalizeConfigContext) => ModelProviderConfig | null | undefined; /** * Provider-owned final native-streaming compat pass for config providers. * * Use this when a provider opts specific native base URLs into * `supportsUsageInStreaming` or similar transport compatibility flags. */ applyNativeStreamingUsageCompat?: (ctx: ProviderNormalizeConfigContext) => ModelProviderConfig | null | undefined; /** * Provider-owned config apiKey/env marker resolution. * * Use this when a provider resolves auth from env vars such as AWS/GCP * markers rather than a normal API-key env var. */ resolveConfigApiKey?: (ctx: ProviderResolveConfigApiKeyContext) => string | null | undefined; /** * @deprecated Legacy static capability bag kept only for compatibility. * * New provider behavior should use explicit hooks instead. Core replay and * stream/runtime logic no longer consumes this field. */ capabilities?: ProviderCapabilities; /** * Provider-owned replay/compaction policy override. * * Use this when transcript replay or compaction should follow provider-owned * rules that are more expressive than the static `capabilities` bag. */ buildReplayPolicy?: (ctx: ProviderReplayPolicyContext) => ProviderReplayPolicy | null | undefined; /** * Provider-owned replay-history sanitization. * * Runs after OpenClaw performs generic transcript cleanup. Use this for * provider-specific replay rewrites that should stay with the provider * plugin rather than in shared core compaction helpers. */ sanitizeReplayHistory?: (ctx: ProviderSanitizeReplayHistoryContext) => Promise | AgentMessage[] | null | undefined; /** * Provider-owned final replay-turn validation. * * Use this when provider transports need stricter replay-time validation or * turn reshaping after generic sanitation. Returning a non-null value * replaces the built-in replay validators rather than composing with them. */ validateReplayTurns?: (ctx: ProviderValidateReplayTurnsContext) => Promise | AgentMessage[] | null | undefined; /** * Provider-owned tool-schema normalization. * * Use this for transport-family schema cleanup before OpenClaw registers * tools with the embedded runner. */ normalizeToolSchemas?: (ctx: ProviderNormalizeToolSchemasContext) => AnyAgentTool[] | null | undefined; /** * Provider-owned tool-schema diagnostics after normalization. * * Use this when a provider wants to surface transport-specific schema * warnings without teaching core about provider-specific keyword rules. */ inspectToolSchemas?: (ctx: ProviderNormalizeToolSchemasContext) => ProviderToolSchemaDiagnostic[] | null | undefined; /** * Provider-owned reasoning output mode. * * Use this when a provider requires tagged reasoning/final output instead of * native structured reasoning fields. */ resolveReasoningOutputMode?: (ctx: ProviderReasoningOutputModeContext) => ProviderReasoningOutputMode | null | undefined; /** * Provider-owned extra-param normalization before generic stream option * wrapping. * * Typical uses: set provider-default `transport`, map provider-specific * config aliases, or inject extra request metadata sourced from * `agents.defaults.models./.params`. */ prepareExtraParams?: (ctx: ProviderPrepareExtraParamsContext) => Record | null | undefined; /** * Provider-owned request params after transport/model resolution. * * Use this for transport-family request knobs that should be keyed by the * resolved model API/transport rather than a hardcoded core allowlist. */ extraParamsForTransport?: (ctx: ProviderExtraParamsForTransportContext) => ProviderExtraParamsForTransportResult | null | undefined; /** * Provider-owned transport factory. * * Use this when the provider needs a fully custom StreamFn instead of a * wrapper around the normal `streamSimple` path. */ createStreamFn?: (ctx: ProviderCreateStreamFnContext) => StreamFn | null | undefined; /** * Provider-owned stream wrapper applied after generic OpenClaw wrappers. * * Typical uses: provider attribution headers, request-body rewrites, or * provider-specific compat payload patches that do not justify a separate * transport implementation. */ wrapStreamFn?: (ctx: ProviderWrapStreamFnContext) => StreamFn | null | undefined; /** * Provider-owned wrapper for direct `completeSimple` callers. * * Opt in only when the provider must enforce the same wire contract outside * the embedded agent runtime. */ wrapSimpleCompletionStreamFn?: (ctx: ProviderWrapStreamFnContext) => StreamFn | null | undefined; /** * Provider-owned native transport turn identity. * * Use this when a provider wants generic transports to attach provider-native * request headers or metadata on each turn without hardcoding vendor logic in * core. */ resolveTransportTurnState?: (ctx: ProviderResolveTransportTurnStateContext) => ProviderTransportTurnState | null | undefined; /** * Provider-owned WebSocket session policy. * * Use this when a provider wants generic WebSocket transports to attach * native session headers or tune the session-scoped cool-down before HTTP * fallback. */ resolveWebSocketSessionPolicy?: (ctx: ProviderResolveWebSocketSessionPolicyContext) => ProviderWebSocketSessionPolicy | null | undefined; /** * Provider-owned embedding provider factory. * * Use this when memory embedding behavior belongs with the provider plugin * rather than the core embedding switchboard. */ createEmbeddingProvider?: (ctx: ProviderCreateEmbeddingProviderContext) => Promise | PluginEmbeddingProvider | null | undefined; /** * Runtime auth exchange hook. * * Called after OpenClaw resolves the raw configured credential but before the * runner stores it in runtime auth storage. This lets plugins exchange a * source credential (for example a GitHub token) into a short-lived runtime * token plus optional base URL override. */ prepareRuntimeAuth?: (ctx: ProviderPrepareRuntimeAuthContext) => Promise; /** * Usage/billing auth resolution hook. * * Called by provider-usage surfaces (`/usage`, status snapshots, reporting). * Use this when a provider's usage endpoint needs provider-owned token * extraction, blob parsing, or alias handling. */ resolveUsageAuth?: (ctx: ProviderResolveUsageAuthContext) => Promise | ProviderResolvedUsageAuth | null | undefined; /** * Usage/quota snapshot fetch hook. * * Called after `resolveUsageAuth` by `/usage` and related reporting surfaces. * Use this when the provider's usage endpoint or payload shape is * provider-specific and you want that logic to live with the provider plugin * instead of the core switchboard. */ fetchUsageSnapshot?: (ctx: ProviderFetchUsageSnapshotContext) => Promise | ProviderUsageSnapshot | null | undefined; /** * Provider-owned failover context-overflow matcher. * * Return true when the provider recognizes the raw error as a context-window * overflow shape that generic heuristics would miss. */ matchesContextOverflowError?: (ctx: ProviderFailoverErrorContext) => boolean | undefined; /** * Provider-owned failover error classification. * * Return a failover reason when the provider recognizes a provider-specific * raw error shape. Return undefined to fall back to generic classification. */ classifyFailoverReason?: (ctx: ProviderFailoverErrorContext) => FailoverReason | null | undefined; /** * Provider-owned cache TTL eligibility. * * Use this when a proxy provider supports Anthropic-style prompt caching for * only a subset of upstream models. */ isCacheTtlEligible?: (ctx: ProviderCacheTtlEligibilityContext) => boolean | undefined; /** * Provider-owned missing-auth message override. * * Return a custom message when the provider wants a more specific recovery * hint than OpenClaw's generic auth-store guidance. */ buildMissingAuthMessage?: (ctx: ProviderBuildMissingAuthMessageContext) => string | null | undefined; /** * Provider-owned unknown-model hint override. * * Return a suffix when the provider wants a more specific recovery hint than * OpenClaw's generic `Unknown model` error after catalog/runtime lookup * fails. */ buildUnknownModelHint?: (ctx: ProviderBuildUnknownModelHintContext) => string | null | undefined; /** * Provider-owned built-in model suppression. * * Return `{ suppress: true }` to hide a stale upstream row. Include * `errorMessage` when OpenClaw should surface a provider-specific hint for * direct model resolution failures. * * @deprecated Use manifest `modelCatalog.suppressions`. Runtime suppression * hooks are no longer called by model resolution. */ suppressBuiltInModel?: (ctx: ProviderBuiltInModelSuppressionContext) => ProviderBuiltInModelSuppressionResult | null | undefined; /** * Provider-owned final catalog augmentation. * * @deprecated Use `api.registerModelCatalogProvider` for supplemental catalog * rows. This hook is kept only for existing text-provider runtime * compatibility during the migration window. * * Return extra rows to append to the final catalog after discovery/config * merging. OpenClaw deduplicates by `provider/id`, so plugins only need to * describe the desired supplemental rows. */ augmentModelCatalog?: (ctx: ProviderAugmentModelCatalogContext) => Array | ReadonlyArray | Promise | ReadonlyArray | null | undefined> | null | undefined; /** * Provider-owned binary thinking toggle. * * Return true when the provider exposes a coarse on/off reasoning control * instead of the normal multi-level ladder shown by `/think`. * * @deprecated Prefer `resolveThinkingProfile`. */ isBinaryThinking?: (ctx: ProviderThinkingPolicyContext) => boolean | undefined; /** * Provider-owned xhigh reasoning support. * * Return true only for models that should expose the `xhigh` thinking level. * * @deprecated Prefer `resolveThinkingProfile`. */ supportsXHighThinking?: (ctx: ProviderThinkingPolicyContext) => boolean | undefined; /** * Provider-owned thinking level profile. * * Prefer this over the individual thinking capability hooks when a provider * or model exposes a custom set of thinking levels. OpenClaw stores the * canonical `id`, shows `label` when provided, and downgrades stale stored * values by profile rank. */ resolveThinkingProfile?: (ctx: ProviderDefaultThinkingPolicyContext) => ProviderThinkingProfile | null | undefined; /** * Provider-owned default thinking level. * * Use this to keep model-family defaults (for example Claude 4.6 => * adaptive) out of core command logic. * * @deprecated Prefer `resolveThinkingProfile`. */ resolveDefaultThinkingLevel?: (ctx: ProviderDefaultThinkingPolicyContext) => "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | null | undefined; /** * Provider-owned system-prompt contribution. * * Use this when a provider/model family needs cache-aware prompt tuning * without replacing the full OpenClaw-owned system prompt. */ resolveSystemPromptContribution?: (ctx: ProviderSystemPromptContributionContext) => ProviderSystemPromptContribution | null | undefined; /** * Provider-owned GPT/model prompt overlay seam. * * Runs after OpenClaw's built-in overlay is resolved and before the * provider's regular system-prompt contribution is merged. */ resolvePromptOverlay?: (ctx: ProviderResolvePromptOverlayContext) => ProviderSystemPromptContribution | null | undefined; /** * Provider-owned fallback route override for model/profile failure handling. * * Return undefined/null to keep OpenClaw's default fallback policy. */ followupFallbackRoute?: (ctx: ProviderFollowupFallbackRouteContext) => ProviderFollowupFallbackRouteResult | null | undefined; /** * Provider-owned auth profile resolver. * * Return a profile id from the supplied order to prefer it for this attempt; * invalid or missing ids are ignored by core. */ resolveAuthProfileId?: (ctx: ProviderResolveAuthProfileIdContext) => string | null | undefined; /** * Provider-owned final system-prompt transform. * * Use this sparingly when a provider transport needs small compatibility * rewrites after OpenClaw has assembled the complete prompt. Return * `undefined`/`null` to leave the prompt unchanged. */ transformSystemPrompt?: (ctx: ProviderTransformSystemPromptContext) => string | null | undefined; /** * Provider-owned bidirectional text replacements. * * `input` applies to system prompts and text message content before transport. * `output` applies to assistant text deltas/final text before OpenClaw handles * its own control markers or channel delivery. */ textTransforms?: PluginTextTransforms; /** * Provider-owned global config defaults. * * Use this when config materialization needs provider-specific defaults that * depend on auth mode, env, or provider model-family semantics. */ applyConfigDefaults?: (ctx: ProviderApplyConfigDefaultsContext) => OpenClawConfig | null | undefined; /** * Provider-owned "modern model" matcher used by live profile/smoke filters. * * Return true when the given provider/model ref should be treated as a * preferred modern model candidate. */ isModernModelRef?: (ctx: ProviderModernModelPolicyContext) => boolean | undefined; wizard?: ProviderPluginWizard; /** * Provider-owned auth-profile API-key formatter. * * OpenClaw uses this when a stored auth profile is already valid and needs to * be converted into the runtime `apiKey` string expected by the provider. Use * this for providers whose auth profile stores extra metadata alongside the * bearer token (for example Gemini CLI's `{ token, projectId }` payload). */ formatApiKey?: (cred: AuthProfileCredential) => string; /** * Legacy auth-profile ids that should be retired by `openclaw doctor`. * * Use this when a provider plugin replaces an older core-managed profile id * and wants cleanup/migration messaging to live with the provider instead of * in hardcoded doctor tables. */ deprecatedProfileIds?: string[]; /** * Legacy OAuth profile-id migrations that `openclaw doctor` should offer. * * Use this when a provider moved from a legacy default OAuth profile id to a * newer identity-based id and wants doctor to own the config rewrite without * another core-specific migration branch. */ oauthProfileIdRepairs?: ProviderOAuthProfileIdRepair[]; /** * Provider-owned OAuth refresh. * * OpenClaw calls this before falling back to the shared `shared model runtime` OAuth * refreshers. Use it when the provider has a custom refresh endpoint, or when * the provider needs custom refresh-failure behavior that should stay out of * core auth-profile code. */ refreshOAuth?: (cred: OAuthCredential) => Promise; /** * Provider-owned auth-doctor hint. * * Return a multiline repair hint when OAuth refresh fails and the provider * wants to steer users toward a specific auth-profile migration or recovery * path. Return nothing to keep OpenClaw's generic error text. */ buildAuthDoctorHint?: (ctx: ProviderAuthDoctorHintContext) => string | Promise | null | undefined; /** * Provider-owned config-backed auth resolution. * * Providers own any provider-specific fallback secret rules here so core * auth/discovery code can stay generic and avoid parsing provider-private * config layouts. * * The returned `apiKey` may be: * - a real credential from the active runtime snapshot, suitable for runtime use * - a non-secret marker (for example a managed SecretRef marker), suitable only * for discovery/bootstrap callers * * Runtime callers must not treat non-secret markers as runnable credentials; * they should retry against the active runtime snapshot when available. * * This hook is the canonical seam for provider-specific fallback auth * derived from plugin/private config. It may return: * - a runnable literal credential for runtime callers * - a non-secret marker for managed-secret source config, which is still useful * for discovery/bootstrap callers * * Runtime callers must not treat non-secret markers as runnable credentials; * they should retry against the active runtime snapshot when available. * * Use this when the provider can operate without a real secret for certain * configured local/self-hosted cases and wants auth resolution to treat that * config as available. */ resolveSyntheticAuth?: (ctx: ProviderResolveSyntheticAuthContext) => ProviderSyntheticAuthResult | null | undefined; /** * Provider-owned external auth profile discovery. * * Use this when credentials are managed by an external tool and should be visible * to runtime auth resolution without being written back into `auth-profiles.json` * by core. */ resolveExternalAuthProfiles?: (ctx: ProviderResolveExternalAuthProfilesContext) => Array | ReadonlyArray | null | undefined; /** * @deprecated Declare `contracts.externalAuthProviders` in the plugin manifest * and implement `resolveExternalAuthProfiles` instead. Kept at the public * plugin boundary until the SDK removal window closes. */ resolveExternalOAuthProfiles?: (ctx: ProviderResolveExternalOAuthProfilesContext) => Array | ReadonlyArray | null | undefined; /** * Provider-owned precedence rule for stored synthetic auth profiles. * * Return true when a stored profile API key is only a provider-owned * synthetic placeholder and should yield to env/config-backed auth before * OpenClaw falls back to that stored profile. */ shouldDeferSyntheticProfileAuth?: (ctx: ProviderDeferSyntheticProfileAuthContext) => boolean | undefined; onModelSelected?: (ctx: ProviderModelSelectedContext) => Promise; }; /** Speech capability registered by a plugin. */ type SpeechProviderPlugin = { id: SpeechProviderId; label: string; aliases?: string[]; autoSelectOrder?: number; /** Default provider operation timeout in milliseconds when caller/config omit timeoutMs. */ defaultTimeoutMs?: number; defaultModel?: string; models?: readonly string[]; voices?: readonly string[]; resolveConfig?: (ctx: SpeechProviderResolveConfigContext) => SpeechProviderConfig; parseDirectiveToken?: (ctx: SpeechDirectiveTokenParseContext) => SpeechDirectiveTokenParseResult; resolveTalkConfig?: (ctx: SpeechProviderResolveTalkConfigContext) => SpeechProviderConfig; resolveTalkOverrides?: (ctx: SpeechProviderResolveTalkOverridesContext) => SpeechProviderConfig | undefined; prepareSynthesis?: (ctx: SpeechProviderPrepareSynthesisContext) => SpeechProviderPreparedSynthesis | undefined | Promise; isConfigured: (ctx: SpeechProviderConfiguredContext) => boolean; synthesize: (req: SpeechSynthesisRequest) => Promise; streamSynthesize?: (req: SpeechSynthesisStreamRequest) => Promise; synthesizeTelephony?: (req: SpeechTelephonySynthesisRequest) => Promise; listVoices?: (req: SpeechListVoicesRequest) => Promise; }; type PluginSpeechProviderEntry = SpeechProviderPlugin & { pluginId: string; }; /** Realtime transcription capability registered by a plugin. */ type RealtimeTranscriptionProviderPlugin = { id: RealtimeTranscriptionProviderId; label: string; aliases?: string[]; defaultModel?: string; models?: readonly string[]; autoSelectOrder?: number; resolveConfig?: (ctx: RealtimeTranscriptionProviderResolveConfigContext) => RealtimeTranscriptionProviderConfig; isConfigured: (ctx: RealtimeTranscriptionProviderConfiguredContext) => boolean; createSession: (req: RealtimeTranscriptionSessionCreateRequest) => RealtimeTranscriptionSession; }; type PluginRealtimeTranscriptionProviderEntry = RealtimeTranscriptionProviderPlugin & { pluginId: string; }; /** Transcript source capability registered by a channel or meeting plugin. */ type TranscriptSourceProvider = TranscriptSourceProvider$2; type PluginTranscriptsSourceProviderEntry = TranscriptSourceProvider & { pluginId: string; }; /** Realtime voice capability registered by a plugin. */ type RealtimeVoiceProviderPlugin = { id: RealtimeVoiceProviderId; label: string; aliases?: string[]; defaultModel?: string; models?: readonly string[]; autoSelectOrder?: number; capabilities?: RealtimeVoiceProviderCapabilities; resolveConfig?: (ctx: RealtimeVoiceProviderResolveConfigContext) => RealtimeVoiceProviderConfig; isConfigured: (ctx: RealtimeVoiceProviderConfiguredContext) => boolean; createBridge: (req: RealtimeVoiceBridgeCreateRequest) => RealtimeVoiceBridge; createBrowserSession?: (req: RealtimeVoiceBrowserSessionCreateRequest) => Promise; }; type PluginRealtimeVoiceProviderEntry = RealtimeVoiceProviderPlugin & { pluginId: string; }; type MediaUnderstandingProviderPlugin = MediaUnderstandingProvider; type ImageGenerationProviderPlugin = ImageGenerationProvider; type VideoGenerationProviderPlugin = VideoGenerationProvider; type MusicGenerationProviderPlugin = MusicGenerationProvider; type OpenClawPluginGatewayMethod = { method: string; handler: GatewayRequestHandler; }; type PluginCommandDiagnosticsSession = { /** Stable host session key when available. */sessionKey?: string; /** Ephemeral OpenClaw session id when available. */ sessionId?: string; /** Transcript file for this OpenClaw session when available. */ sessionFile?: string; /** Embedded agent harness selected for this session. */ agentHarnessId?: string; /** Channel/provider for this session when available. */ channel?: string; /** Provider channel id when available. */ channelId?: ChannelId; /** Account id for multi-account channels when available. */ accountId?: string; /** Thread/topic id when available. */ messageThreadId?: string | number; /** Parent conversation id for thread-capable channels when available. */ threadParentId?: string; }; /** * Context passed to plugin command handlers. */ type PluginCommandContext = { /** The sender's identifier (for example a channel-scoped user ID) */senderId?: string; /** The channel/surface (for example "chat" or "team-chat") */ channel: string; /** Provider channel id */ channelId?: ChannelId; /** Whether the sender is on the allowlist */ isAuthorizedSender: boolean; /** Whether the sender is an owner for owner-only command surfaces. */ senderIsOwner?: boolean; /** Gateway client scopes for internal control-plane callers */ gatewayClientScopes?: string[]; /** Host-resolved agent that owns the active session. */ agentId?: string; /** Stable host session key for the active conversation when available. */ sessionKey?: string; /** Ephemeral host session id for the active conversation when available. */ sessionId?: string; /** Transcript file for the active OpenClaw session when available. */ sessionFile?: string; /** Raw command arguments after the command name */ args?: string; /** The full normalized command body */ commandBody: string; /** Current OpenClaw configuration */ config: OpenClawConfig; /** Raw "From" value (channel-scoped id) */ from?: string; /** Raw "To" value (channel-scoped id) */ to?: string; /** Account id for multi-account channels */ accountId?: string; /** Thread/topic id if available */ messageThreadId?: string | number; /** Parent conversation id for thread-capable channels */ threadParentId?: string; /** Sensitive diagnostics-only session inventory for owner-gated commands. */ diagnosticsSessions?: PluginCommandDiagnosticsSession[]; /** Host-bound runtime capabilities scoped to this command invocation. */ runtimeContext?: { llm?: PluginRuntimeCore["llm"]; }; /** Internal diagnostics-only marker that exec approval already authorized upload. */ diagnosticsUploadApproved?: boolean; /** Internal diagnostics-only marker to preview upload effects without exposing ids. */ diagnosticsPreviewOnly?: boolean; /** Internal diagnostics-only marker for owner-private routed confirmations. */ diagnosticsPrivateRouted?: boolean; requestConversationBinding: (params?: PluginConversationBindingRequestParams) => Promise; detachConversationBinding: () => Promise<{ removed: boolean; }>; getCurrentConversationBinding: () => Promise; }; /** * Result returned by a plugin command handler. */ type PluginCommandResult = ReplyPayload & { /** Allows the agent session to continue processing after the command. */continueAgent?: boolean; /** Suppresses channel fallback replies when the handler already delivered a response. */ suppressReply?: boolean; }; /** * Handler function for plugin commands. */ type PluginCommandHandler = (ctx: PluginCommandContext) => PluginCommandResult | Promise; /** * Definition for a plugin-registered command. */ declare const AGENT_PROMPT_SURFACE_KINDS: readonly ["openclaw_main", "pi_main", "codex_app_server", "cli_backend", "acp_backend", "subagent"]; type AgentPromptSurfaceKind = (typeof AGENT_PROMPT_SURFACE_KINDS)[number]; type AgentPromptGuidanceEntry = { text: string; surfaces?: readonly AgentPromptSurfaceKind[]; }; type AgentPromptGuidance = string | AgentPromptGuidanceEntry; type OpenClawPluginCommandDefinition = { /** Command name without leading slash (e.g., "tts") */name: string; /** * Optional native-command aliases for slash/menu surfaces. * `default` applies to all native providers unless a provider-specific * override exists (for example `{ default: "talkvoice", teamChat: "voice2" }`). */ nativeNames?: Partial> & { default?: string; }; /** * Optional native progress placeholder text for native command surfaces. * `default` applies to all native providers unless a provider-specific * override exists. */ nativeProgressMessages?: Partial> & { default?: string; }; /** Description shown in /help and command menus */ description: string; /** Localized descriptions for native command surfaces that support them. */ descriptionLocalizations?: Record; /** * Optional channel ids this command belongs to. * Omit to keep the command available on every channel surface. */ channels?: readonly string[]; /** Optional system-prompt guidance for agents when this command is registered. */ agentPromptGuidance?: readonly AgentPromptGuidance[]; /** Whether this command accepts arguments */ acceptsArgs?: boolean; /** Whether only authorized senders can use this command (default: true) */ requireAuth?: boolean; /** Operator scopes required by gateway clients; command owners may satisfy this on chat surfaces. */ requiredScopes?: OperatorScope[]; /** Whether a trusted bundled handler needs owner status for subcommand-level authorization. */ exposeSenderIsOwner?: boolean; /** * Allows a bundled plugin to claim a command name that is otherwise reserved * by core. External plugins cannot use this field. */ ownership?: "plugin" | "reserved"; /** The handler function */ handler: PluginCommandHandler; }; type PluginInteractiveHandlerResult = { handled?: boolean; } | void; type PluginInteractiveRegistration = { channel: TChannel; namespace: string; handler: (ctx: TContext) => Promise | TResult; }; type PluginInteractiveHandlerRegistration = PluginInteractiveRegistration; type OpenClawPluginHttpRouteAuth = "gateway" | "plugin"; type OpenClawPluginHttpRouteMatch = "exact" | "prefix"; type OpenClawPluginGatewayRuntimeScopeSurface = "write-default" | "trusted-operator"; type OpenClawPluginHttpRouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise | boolean | void; type OpenClawPluginHttpRouteUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => Promise | boolean | void; type OpenClawPluginHttpRouteParams = { path: string; handler: OpenClawPluginHttpRouteHandler; handleUpgrade?: OpenClawPluginHttpRouteUpgradeHandler; auth: OpenClawPluginHttpRouteAuth; match?: OpenClawPluginHttpRouteMatch; gatewayRuntimeScopeSurface?: OpenClawPluginGatewayRuntimeScopeSurface; nodeCapability?: { surface: string; ttlMs?: number; }; replaceExisting?: boolean; }; type OpenClawPluginHostedMediaResolver = (mediaUrl: string) => string | null | undefined | Promise; type OpenClawPluginCliContext = { /** * Command object where this plugin should register its commands. * * For root CLI registrations this is the root `openclaw` program. For nested * registrations it is the resolved parent command from `parentPath`. */ program: Command; parentPath: readonly string[]; config: OpenClawConfig; workspaceDir?: string; logger: PluginLogger; }; type OpenClawPluginCliRegistrar = (ctx: OpenClawPluginCliContext) => void | Promise; /** * Top-level CLI metadata for plugin-owned commands. * * Descriptors are the parse-time contract for lazy plugin CLI registration. * If you want OpenClaw to keep a plugin command lazy-loaded while still * advertising it at the root CLI level, provide descriptors that cover every * top-level command root registered by that plugin CLI surface. */ type OpenClawPluginCliCommandDescriptor = { name: string; description: string; hasSubcommands: boolean; }; type OpenClawPluginNodeCliFeatureOptions = { /** Explicit node feature command names owned under `openclaw nodes`. */commands?: string[]; /** * Parse-time command descriptors for lazy node feature CLI registration. * * Descriptors are registered under `openclaw nodes`, so a descriptor named * `"camera"` exposes `openclaw nodes camera`. */ descriptors?: OpenClawPluginCliCommandDescriptor[]; }; type OpenClawPluginReloadRegistration = { restartPrefixes?: string[]; hotPrefixes?: string[]; noopPrefixes?: string[]; }; type OpenClawPluginNodeHostCommand = { command: string; cap?: string; dangerous?: boolean; handle: (paramsJSON?: string | null) => Promise; }; type OpenClawPluginNodeInvokeTransportResult = { ok: true; payload?: unknown; payloadJSON?: string | null; } | { ok: false; code?: string; message: string; details?: Record; }; type OpenClawPluginNodeInvokeApprovalDecision = "allow-once" | "allow-always" | "deny"; type OpenClawPluginNodeInvokePolicyApprovalRuntime = { request: (input: { title: string; description: string; severity?: "info" | "warning" | "critical"; toolName?: string; toolCallId?: string; agentId?: string; sessionKey?: string; timeoutMs?: number; }) => Promise<{ id?: string; decision?: OpenClawPluginNodeInvokeApprovalDecision | null; }>; }; type OpenClawPluginNodeInvokePolicyContext = { nodeId: string; command: string; params: unknown; timeoutMs?: number; idempotencyKey?: string; config: OpenClawConfig; pluginConfig?: Record; node?: { nodeId: string; displayName?: string; platform?: string; deviceFamily?: string; commands?: string[]; }; client?: { connId?: string; scopes?: string[]; } | null; approvals?: OpenClawPluginNodeInvokePolicyApprovalRuntime; invokeNode: (input?: { params?: unknown; timeoutMs?: number; idempotencyKey?: string; }) => Promise; }; type OpenClawPluginNodeInvokePolicyResult = { ok: true; payload?: unknown; payloadJSON?: string | null; } | { ok: false; message: string; code?: string; details?: Record; unavailable?: boolean; }; type OpenClawPluginNodeInvokePolicy = { commands: string[]; /** * Platforms where these node-handled commands should be allowlisted by default. * Omit for commands that require explicit `gateway.nodes.allowCommands`. */ defaultPlatforms?: Array<"ios" | "android" | "macos" | "windows" | "linux" | "unknown">; /** * Dangerous policy commands are filtered out of default allowlists unless * explicitly allowed by config. */ dangerous?: boolean; /** * iOS foreground-restricted commands should be queued for foreground delivery * when an iOS node reports BACKGROUND_UNAVAILABLE. */ foregroundRestrictedOnIos?: boolean; handle: (ctx: OpenClawPluginNodeInvokePolicyContext) => Promise | OpenClawPluginNodeInvokePolicyResult; }; type OpenClawPluginSecurityAuditContext = { config: OpenClawConfig; sourceConfig: OpenClawConfig; env: NodeJS.ProcessEnv; stateDir: string; configPath: string; }; type OpenClawPluginSecurityAuditCollector = (ctx: OpenClawPluginSecurityAuditContext) => SecurityAuditFinding[] | Promise; type OpenClawGatewayDiscoveryAdvertiseContext = { machineDisplayName: string; gatewayPort: number; gatewayTlsEnabled: boolean; gatewayTlsFingerprintSha256?: string; gatewayDirectReachable: boolean; canvasPort?: number; tailnetDns?: string; sshPort?: number; cliPath?: string; minimal: boolean; }; type OpenClawGatewayDiscoveryService = { id: string; advertise: (ctx: OpenClawGatewayDiscoveryAdvertiseContext) => void | Promise void | Promise; }>; }; /** Context passed to long-lived plugin services. */ type OpenClawPluginServiceContext = { config: OpenClawConfig; workspaceDir?: string; stateDir: string; logger: PluginLogger; startupTrace?: { detail?: (name: string, metrics: ReadonlyArray) => void; measure: (name: string, run: () => T | Promise) => Promise; }; internalDiagnostics?: { emit: (event: DiagnosticEventInput, privateData?: DiagnosticEventPrivateData) => void; onEvent: (listener: (event: DiagnosticEventPayload, metadata: DiagnosticEventMetadata, privateData: DiagnosticEventPrivateData) => void) => () => void; }; }; /** Background service registered by a plugin during `register(api)`. */ type OpenClawPluginService = { id: string; start: (ctx: OpenClawPluginServiceContext) => void | Promise; stop?: (ctx: OpenClawPluginServiceContext) => void | Promise; }; type OpenClawPluginChannelRegistration = { plugin: ChannelPlugin; }; /** Module-level plugin definition loaded from a native plugin entry file. */ type OpenClawPluginDefinition = { id?: string; name?: string; description?: string; version?: string; /** * @deprecated Declare exclusive plugin kind in `openclaw.plugin.json` via * manifest `kind`. Runtime-exported `kind` is kept as a compatibility * fallback for older plugins and may require loading plugin runtime on * metadata-only command paths. */ kind?: PluginKind | PluginKind[]; configSchema?: OpenClawPluginConfigSchema; reload?: OpenClawPluginReloadRegistration; nodeHostCommands?: OpenClawPluginNodeHostCommand[]; securityAuditCollectors?: OpenClawPluginSecurityAuditCollector[]; register?: (api: OpenClawPluginApi) => void; activate?: (api: OpenClawPluginApi) => void; }; type OpenClawPluginModule = OpenClawPluginDefinition | ((api: OpenClawPluginApi) => void); /** * Public label exposed to plugin `register(api)` calls. * * Keep this as a compatibility signal for plugin authors. Loader internals * should derive explicit capability booleans from the mode instead of branching * on raw strings throughout the code path. * * - `full`: live runtime activation; long-lived side effects may start. * - `discovery`: read-only capability discovery; skip sockets/workers/clients. * - `tool-discovery`: capability discovery for executable tools; skip channel runtime hydration. * - `setup-only`: lightweight channel setup entry only. * - `setup-runtime`: setup flow that also needs the runtime channel entry. * - `cli-metadata`: CLI command metadata collection. */ type PluginRegistrationMode = "full" | "discovery" | "tool-discovery" | "setup-only" | "setup-runtime" | "cli-metadata"; type PluginConfigMigration = (config: OpenClawConfig) => { config: OpenClawConfig; changes: string[]; } | null | undefined; type MigrationItemStatus = "planned" | "migrated" | "skipped" | "warning" | "conflict" | "error"; type MigrationItemKind = "auth" | "config" | "secret" | "memory" | "skill" | "workspace" | "session" | "file" | "archive" | "manual"; type MigrationItemAction = "copy" | "create" | "update" | "merge" | "append" | "archive" | "skip" | "manual"; type MigrationItem = { id: string; kind: MigrationItemKind | (string & {}); action: MigrationItemAction | (string & {}); status: MigrationItemStatus; source?: string; target?: string; message?: string; reason?: string; sensitive?: boolean; details?: Record; }; type MigrationSummary = { total: number; planned: number; migrated: number; skipped: number; conflicts: number; errors: number; sensitive: number; }; type MigrationDetection = { found: boolean; source?: string; label?: string; confidence?: "low" | "medium" | "high"; message?: string; }; type MigrationPlan = { providerId: string; source: string; target?: string; summary: MigrationSummary; items: MigrationItem[]; warnings?: string[]; nextSteps?: string[]; metadata?: Record; }; type MigrationApplyResult = MigrationPlan & { backupPath?: string; reportDir?: string; }; type MigrationProviderPreparation = { dispose?: () => void | Promise; }; type MigrationProviderContext = { config: OpenClawConfig; runtime?: PluginRuntime; logger: PluginLogger; stateDir: string; source?: string; includeSecrets?: boolean; overwrite?: boolean; providerOptions?: Record; backupPath?: string; reportDir?: string; signal?: AbortSignal; }; /** Migration source implemented by a plugin and orchestrated by `openclaw migrate`. */ type MigrationProviderPlugin = { id: string; label: string; description?: string; detect?: (ctx: MigrationProviderContext) => MigrationDetection | Promise; prepareApply?: (ctx: MigrationProviderContext) => MigrationProviderPreparation | Promise | undefined; plan: (ctx: MigrationProviderContext) => MigrationPlan | Promise; apply: (ctx: MigrationProviderContext, plan?: MigrationPlan) => MigrationApplyResult | Promise; }; type PluginSetupAutoEnableContext = { config: OpenClawConfig; env: NodeJS.ProcessEnv; }; type PluginSetupAutoEnableProbe = (ctx: PluginSetupAutoEnableContext) => string | string[] | null | undefined; type OpenClawPluginSessionStateApi = { /** Register plugin-owned session state projected into Gateway session rows. */registerSessionExtension: (extension: PluginSessionExtensionRegistration) => void; }; type OpenClawPluginSessionWorkflowApi = { /** Queue one plugin-owned context injection for the next agent turn in a session. */enqueueNextTurnInjection: (injection: PluginNextTurnInjection) => Promise; /** * Register cleanup metadata for a plugin-owned session scheduler job. * This does not schedule work or create task records; it only lets the host * clean external scheduler state during reset/delete/disable. */ registerSessionSchedulerJob: (job: PluginSessionSchedulerJobRegistration) => PluginSessionSchedulerJobHandle | undefined; /** Send host-validated files to the active direct-outbound route for a session. */ sendSessionAttachment: (params: PluginSessionAttachmentParams) => Promise; /** * Schedule a future agent turn in a session through Cron. * Cron owns timing and creates the task ledger entry when the turn runs. */ scheduleSessionTurn: (params: PluginSessionTurnScheduleParams) => Promise; /** Remove Cron-backed scheduled session turns that share a plugin-owned tag. */ unscheduleSessionTurnsByTag: (params: PluginSessionTurnUnscheduleByTagParams) => Promise; }; type OpenClawPluginSessionControlsApi = { /** Register a typed session action that clients can dispatch through the Gateway. */registerSessionAction: (action: PluginSessionActionRegistration) => void; /** Register a generic Control UI contribution descriptor. */ registerControlUiDescriptor: (descriptor: PluginControlUiDescriptor) => void; }; type OpenClawPluginSessionApi = { state: OpenClawPluginSessionStateApi; workflow: OpenClawPluginSessionWorkflowApi; controls: OpenClawPluginSessionControlsApi; }; type OpenClawPluginAgentEventsApi = { /** Subscribe to sanitized agent events through the host-owned plugin lifecycle. */registerAgentEventSubscription: (subscription: PluginAgentEventSubscriptionRegistration) => void; /** Emit a host-routed, plugin-attributed event for workflow/UI subscribers. */ emitAgentEvent: (params: PluginAgentEventEmitParams) => PluginAgentEventEmitResult; }; type OpenClawPluginAgentApi = { events: OpenClawPluginAgentEventsApi; }; type OpenClawPluginRunContextApi = { /** Store namespaced, JSON-compatible data for the active run. Cleared on run end/error. */setRunContext: (patch: PluginRunContextPatch) => boolean; /** Read namespaced plugin data for a run. */ getRunContext: (params: PluginRunContextGetParams) => PluginJsonValue | undefined; /** Clear one namespace or all namespaces this plugin owns for a run. */ clearRunContext: (params: { runId: string; namespace?: string; }) => void; }; type OpenClawPluginLifecycleApi = { /** Register cleanup hooks for plugin-owned host state and background work. */registerRuntimeLifecycle: (lifecycle: PluginRuntimeLifecycleRegistration) => void; }; /** Main registration API injected into native plugin entry files. */ type OpenClawPluginApi = { id: string; name: string; version?: string; description?: string; source: string; rootDir?: string; registrationMode: PluginRegistrationMode; config: OpenClawConfig; pluginConfig?: Record; /** * In-process runtime helpers for trusted native plugins. * * This surface is broader than hooks. Prefer hooks for third-party * automation/integration unless you need native registry integration. */ runtime: PluginRuntime; logger: PluginLogger; /** * Grouped facade over the existing flat session-related plugin API. * Flat methods remain supported for compatibility. */ session: OpenClawPluginSessionApi; /** Grouped facade for agent-event workflow seams. */ agent: OpenClawPluginAgentApi; /** Grouped facade for run-scoped plugin scratch state. */ runContext: OpenClawPluginRunContextApi; /** Grouped facade for plugin-owned lifecycle cleanup hooks. */ lifecycle: OpenClawPluginLifecycleApi; registerTool: (tool: AnyAgentTool | OpenClawPluginToolFactory$1, opts?: OpenClawPluginToolOptions) => void; registerHook: (events: string | string[], handler: InternalHookHandler, opts?: OpenClawPluginHookOptions) => void; registerHttpRoute: (params: OpenClawPluginHttpRouteParams) => void; /** Register a plugin-owned resolver for browser-style hosted media URLs. */ registerHostedMediaResolver: (resolver: OpenClawPluginHostedMediaResolver) => void; /** Register a native messaging channel plugin (channel capability). */ registerChannel: (registration: OpenClawPluginChannelRegistration | ChannelPlugin) => void; /** * Register a gateway RPC method for this plugin. * * Reserved core admin namespaces (`config.*`, `exec.approvals.*`, * `wizard.*`, `update.*`) always normalize to `operator.admin` even if a * narrower scope is requested. */ registerGatewayMethod: (method: string, handler: GatewayRequestHandler, opts?: { scope?: OperatorScope; }) => void; registerCli: (registrar: OpenClawPluginCliRegistrar, opts?: { /** Parent command path for nested command groups, for example `["nodes"]`. */parentPath?: string[]; /** Explicit command names owned by this registrar at `parentPath`. */ commands?: string[]; /** * Parse-time command descriptors for lazy CLI registration. * * When descriptors cover every command exposed at `parentPath`, OpenClaw * can keep the plugin registrar lazy. Command-only registrations stay on * the eager compatibility path. */ descriptors?: OpenClawPluginCliCommandDescriptor[]; }) => void; /** * Register a plugin-owned node feature command group under `openclaw nodes`. * * This is equivalent to `registerCli(registrar, { parentPath: ["nodes"], ... })` * and is intended for paired-node capabilities such as camera, screen, or Canvas. */ registerNodeCliFeature: (registrar: OpenClawPluginCliRegistrar, opts?: OpenClawPluginNodeCliFeatureOptions) => void; registerReload: (registration: OpenClawPluginReloadRegistration) => void; registerNodeHostCommand: (command: OpenClawPluginNodeHostCommand) => void; registerNodeInvokePolicy: (policy: OpenClawPluginNodeInvokePolicy) => void; registerSecurityAuditCollector: (collector: OpenClawPluginSecurityAuditCollector) => void; registerService: (service: OpenClawPluginService) => void; /** Register a local gateway discovery advertiser such as mDNS/Bonjour. */ registerGatewayDiscoveryService: (service: OpenClawGatewayDiscoveryService) => void; /** Register a text-only CLI backend used by the local CLI runner. */ registerCliBackend: (backend: CliBackendPlugin$1) => void; /** Register plugin-owned prompt/message compatibility text transforms. */ registerTextTransforms: (transforms: PluginTextTransformRegistration) => void; /** Register a lightweight config migration that can run before plugin runtime loads. */ registerConfigMigration: (migrate: PluginConfigMigration) => void; /** Register an importer for `openclaw migrate` (migration capability). */ registerMigrationProvider: (provider: MigrationProviderPlugin) => void; /** Register a lightweight config probe that can auto-enable this plugin generically. */ registerAutoEnableProbe: (probe: PluginSetupAutoEnableProbe) => void; /** Register a native model/provider plugin (text inference capability). */ registerProvider: (provider: ProviderPlugin) => void; /** Register provider-owned model catalog rows for text and media generation. */ registerModelCatalogProvider: (provider: UnifiedModelCatalogProviderPlugin) => void; /** Register a general embedding provider (embedding capability). */ registerEmbeddingProvider: (adapter: EmbeddingProviderAdapter) => void; /** Register a speech synthesis provider (speech capability). */ registerSpeechProvider: (provider: SpeechProviderPlugin) => void; /** Register a realtime transcription provider (streaming STT capability). */ registerRealtimeTranscriptionProvider: (provider: RealtimeTranscriptionProviderPlugin) => void; /** Register a realtime voice provider (duplex voice capability). */ registerRealtimeVoiceProvider: (provider: RealtimeVoiceProviderPlugin) => void; /** Register a media understanding provider (media understanding capability). */ registerMediaUnderstandingProvider: (provider: MediaUnderstandingProviderPlugin) => void; /** Register a transcripts source provider (live or imported meeting transcript capability). */ registerTranscriptSourceProvider: (provider: TranscriptSourceProvider) => void; /** Register an image generation provider (image generation capability). */ registerImageGenerationProvider: (provider: ImageGenerationProviderPlugin) => void; /** Register a video generation provider (video generation capability). */ registerVideoGenerationProvider: (provider: VideoGenerationProviderPlugin) => void; /** Register a music generation provider (music generation capability). */ registerMusicGenerationProvider: (provider: MusicGenerationProviderPlugin) => void; /** Register a web fetch provider (web fetch capability). */ registerWebFetchProvider: (provider: WebFetchProviderPlugin$1) => void; /** Register a web search provider (web search capability). */ registerWebSearchProvider: (provider: WebSearchProviderPlugin$1) => void; registerInteractiveHandler: (registration: PluginInteractiveHandlerRegistration) => void; onConversationBindingResolved: (handler: (event: PluginConversationBindingResolvedEvent$1) => void | Promise) => void; /** * Register a custom command that bypasses the LLM agent. * Plugin commands are processed before built-in commands and before agent invocation. * Use this for simple state-toggling or status commands that don't need AI reasoning. */ registerCommand: (command: OpenClawPluginCommandDefinition) => void; /** Register a context engine implementation (exclusive slot - only one active at a time). */ registerContextEngine: (id: string, factory: ContextEngineFactory) => void; /** Register a compaction provider (pluggable summarization backend). */ registerCompactionProvider: (provider: CompactionProvider) => void; /** Register an agent harness implementation. */ registerAgentHarness: (harness: AgentHarness) => void; /** * Register a Codex app-server extension factory for Codex harness tool-result * middleware. Only bundled plugins may use this seam, and * `contracts.embeddedExtensionFactories` must include `"codex-app-server"`. */ registerCodexAppServerExtensionFactory: (factory: CodexAppServerExtensionFactory) => void; /** * Register runtime-neutral tool-result middleware. Declare * `contracts.agentToolResultMiddleware` for every targeted runtime. */ registerAgentToolResultMiddleware: (handler: AgentToolResultMiddleware, options?: AgentToolResultMiddlewareOptions) => void; /** * Register plugin-owned session state that can be projected into Gateway session rows. * @deprecated Use `api.session.state.registerSessionExtension(...)`. */ registerSessionExtension: (extension: PluginSessionExtensionRegistration) => void; /** * Queue one plugin-owned context injection for the next agent turn in a session. * @deprecated Use `api.session.workflow.enqueueNextTurnInjection(...)`. */ enqueueNextTurnInjection: (injection: PluginNextTurnInjection) => Promise; /** * Register a trusted pre-tool policy. Installed plugins must declare the * policy id in `contracts.trustedToolPolicies`. */ registerTrustedToolPolicy: (policy: PluginTrustedToolPolicyRegistration) => void; /** * Register display/policy metadata for a plugin-owned tool. Metadata is * scoped to the (pluginId, toolName) pair at projection time, so plugins * cannot decorate other plugins' tools or core tools through this surface. */ registerToolMetadata: (metadata: PluginToolMetadataRegistration) => void; /** * Register a generic Control UI contribution descriptor. * @deprecated Use `api.session.controls.registerControlUiDescriptor(...)`. */ registerControlUiDescriptor: (descriptor: PluginControlUiDescriptor) => void; /** * Register cleanup hooks for plugin-owned host state and background work. * @deprecated Use `api.lifecycle.registerRuntimeLifecycle(...)`. */ registerRuntimeLifecycle: (lifecycle: PluginRuntimeLifecycleRegistration) => void; /** * Subscribe to sanitized agent events through the host-owned plugin lifecycle. * @deprecated Use `api.agent.events.registerAgentEventSubscription(...)`. */ registerAgentEventSubscription: (subscription: PluginAgentEventSubscriptionRegistration) => void; /** * Emit a host-routed, plugin-attributed agent event for workflow/UI subscribers. * @deprecated Use `api.agent.events.emitAgentEvent(...)`. */ emitAgentEvent: (params: PluginAgentEventEmitParams) => PluginAgentEventEmitResult; /** * Store namespaced, JSON-compatible data for the active run. Cleared on run end/error. * @deprecated Use `api.runContext.setRunContext(...)`. */ setRunContext: (patch: PluginRunContextPatch) => boolean; /** * Read namespaced plugin data for a run. * @deprecated Use `api.runContext.getRunContext(...)`. */ getRunContext: (params: PluginRunContextGetParams) => PluginJsonValue | undefined; /** * Clear one namespace or all namespaces this plugin owns for a run. * @deprecated Use `api.runContext.clearRunContext(...)`. */ clearRunContext: (params: { runId: string; namespace?: string; }) => void; /** * Register cleanup metadata for a plugin-owned session scheduler job. * This does not schedule work or create task records; it only lets the host * clean external scheduler state during reset/delete/disable. * * @deprecated Use `api.session.workflow.registerSessionSchedulerJob(...)`. */ registerSessionSchedulerJob: (job: PluginSessionSchedulerJobRegistration) => PluginSessionSchedulerJobHandle | undefined; /** * Register a typed session action that clients can dispatch through the Gateway. * @deprecated Use `api.session.controls.registerSessionAction(...)`. */ registerSessionAction: (action: PluginSessionActionRegistration) => void; /** * Send one or more host-validated files to the active direct-outbound channel for a session. * * This API is intended for bundled plugins running with the host channel/session * integration available. Calls may resolve to `{ ok: false }` instead of attaching * files when global side effects are disabled or when the required plugin/channel * runtime is not loaded, so callers must handle rejection via the returned result. * * @deprecated Use `api.session.workflow.sendSessionAttachment(...)`. */ sendSessionAttachment: (params: PluginSessionAttachmentParams) => Promise; /** * Schedule a future agent turn in a session through Cron. * Cron owns timing and creates the task ledger entry when the turn runs. * Bundled plugins only; workspace plugins receive undefined. * * @deprecated Use `api.session.workflow.scheduleSessionTurn(...)`. */ scheduleSessionTurn: (params: PluginSessionTurnScheduleParams) => Promise; /** * Remove Cron-backed scheduled session turns that share the same plugin-owned tag. * Bundled plugins only; workspace plugins receive a zero-count result. * * @deprecated Use `api.session.workflow.unscheduleSessionTurnsByTag(...)`. */ unscheduleSessionTurnsByTag: (params: PluginSessionTurnUnscheduleByTagParams) => Promise; /** Register the active detached task runtime for this plugin (exclusive slot). */ registerDetachedTaskRuntime: (runtime: DetachedTaskLifecycleRuntime) => void; /** Register the active memory capability for this memory plugin (exclusive slot). */ registerMemoryCapability: (capability: MemoryPluginCapability) => void; /** * Register the system prompt section builder for this memory plugin (exclusive slot). * @deprecated Use registerMemoryCapability({ promptBuilder }) instead. */ registerMemoryPromptSection: (builder: MemoryPromptSectionBuilder) => void; /** Register an additive memory-adjacent prompt section (non-exclusive). */ registerMemoryPromptSupplement: (builder: MemoryPromptSectionBuilder) => void; /** Register an additive memory-adjacent search/read corpus supplement (non-exclusive). */ registerMemoryCorpusSupplement: (supplement: MemoryCorpusSupplement) => void; /** * Register the pre-compaction flush plan resolver for this memory plugin (exclusive slot). * @deprecated Use registerMemoryCapability({ flushPlanResolver }) instead. */ registerMemoryFlushPlan: (resolver: MemoryFlushPlanResolver) => void; /** * Register the active memory runtime adapter for this memory plugin (exclusive slot). * @deprecated Use registerMemoryCapability({ runtime }) instead. */ registerMemoryRuntime: (runtime: MemoryPluginRuntime) => void; /** * Register a memory embedding provider adapter. Multiple adapters may coexist. * @deprecated New embedding providers should use `registerEmbeddingProvider` * and `contracts.embeddingProviders`. This memory-specific seam is retained * while existing memory providers migrate. */ registerMemoryEmbeddingProvider: (adapter: MemoryEmbeddingProviderAdapter) => void; resolvePath: (input: string) => string; /** Register a lifecycle hook handler */ on: (hookName: K, handler: PluginHookHandlerMap[K], opts?: { priority?: number; timeoutMs?: number; }) => void; }; //#endregion export { OpenClawPluginService as $, abortEmbeddedAgentRun as $a, LlmCompleteMessage as $c, resolvePersistedAuthProfileOwnerAgentDir as $d, PluginRunContextGetParams as $i, ChannelIngressQueueClaim as $l, ProviderApplyConfigDefaultsContext as $n, registerMemoryEmbeddingProvider as $o, hasFinalChannelTurnDispatch as $r, statRegularFile as $s, ProviderModelSelectedContext as $t, prepareSimpleCompletionModel as $u, OpenClawPluginDefinition as A, resolveBootstrapContextForRun as Aa, ContextEngineHostCapability as Ac, resolveAwsSdkEnvVarName as Ad, ProviderDefaultThinkingPolicyContext as Af, ChannelBotLoopProtectionFacts as Ai, SpeechProviderId as Al, ProviderResolvePromptOverlayContext as An, getBeforeToolCallFailureDisposition as Ao, GatewayRequestContext as Ar, uploadBatchJsonlFile as As, ProviderAuthOptionBag as At, GenerateImageParams as Au, OpenClawPluginModule as B, CliBackendResolveExecutionArgsContext as Ba, ContextEngineRuntimeSettings as Bc, clearExpiredCooldowns as Bd, ProviderResolveSyntheticAuthContext as Bf, DispatchReplyWithDispatcher as Bi, SpeechSynthesisTarget as Bl, ProviderTransportThinkingLevel as Bn, AgentHarnessTaskRuntimeScope as Bo, PluginNodeCapabilitySurface as Br, runEmbeddingBatchGroups as Bs, ProviderCatalogResult as Bt, formatFastModeCurrentStatus as Bu, OpenClawPluginApi as C, AgentToolResultMiddlewareEvent as Ca, ContextEngineFactoryContext as Cc, MissingProviderAuthError as Cd, AuthCredentialReasonCode as Cf, ChannelTurnResult as Ci, normalizeTtsAutoMode as Cl, ProviderReplaySanitizeMode as Cn, BuildAgentRuntimePlanParams as Co, RealtimeTranscriptionProviderConfig as Cr, ensureDir as Cs, PluginTranscriptsSourceProviderEntry as Ct, WebSearchProviderSetupContext as Cu, OpenClawPluginCliRegistrar as D, AgentToolResultMiddlewareRuntime as Da, BootstrapResult as Dc, isMissingProviderAuthError as Dd, CLAUDE_CLI_PROFILE_ID as Df, InboundMediaFacts as Di, SpeechModelOverridePolicy as Dl, ProviderResolveAuthProfileIdContext as Dn, HookContext as Do, RealtimeTranscriptionSession as Dr, remapChunkLines as Ds, ProviderAuthKind as Dt, SecretInputMode as Du, OpenClawPluginCliContext as E, AgentToolResultMiddlewareResult as Ea, AssembleResult as Ec, formatMissingAuthError as Ed, hasUsableOAuthCredential as Ef, DispatchedChannelTurnResult as Ei, SpeechListVoicesRequest as El, ProviderReplayToolCallIdMode as En, DeferredPluginToolApproval as Eo, RealtimeTranscriptionProviderResolveConfigContext as Er, parseEmbedding as Es, ProviderAuthDoctorHintContext as Et, WebSearchRuntimeMetadataContext as Eu, OpenClawPluginHttpRouteHandler as F, CliBackendNormalizeConfigContext as Fa, ContextEngineProjection as Fc, markAuthProfileBlockedUntil as Fd, ProviderSystemPromptContribution as Ff, formatInboundFromLabel as Fi, SpeechProviderResolveTalkConfigContext as Fl, ProviderRuntimeProviderConfig as Fn, wrapToolWithBeforeToolCallHook as Fo, RespondFn as Fr, resolveBatchCompletionFromStatus as Fs, ProviderBuiltInModelSuppressionResult as Ft, AgentInternalEvent as Fu, OpenClawPluginNodeInvokePolicyApprovalRuntime as G, PluginTextTransforms as Ga, IngestBatchResult as Gc, ensureAuthProfileStoreForLocalUpdate as Gd, MessagingToolSourceReplyPayload as Gf, DispatchFromConfigResult as Gi, ResolvedProviderRuntimeAuth as Gl, ProviderWrapStreamFnContext as Gn, MemoryEmbeddingProviderAdapter as Go, PluginRegistry as Gr, extractBatchErrorMessage as Gs, ProviderDiscoveryOrder as Gt, EmbeddedBlockChunker as Gu, OpenClawPluginNodeHostCommand as H, CliBackendThinkingLevel as Ha, ContextEngineRuntimeSettingsUnsupportedError as Hc, isProfileInCooldown as Hd, EmbeddedAgentCompactResult as Hf, ReplyDispatcherWithTypingOptions as Hi, SpeechVoiceOption as Hl, ProviderUsageAuthToken as Hn, MemoryEmbeddingBatchChunk as Ho, mintPluginNodeCapabilityToken as Hr, ProviderBatchOutputLine as Hs, ProviderCreateStreamFnContext as Ht, formatFastModeStatusValue as Hu, OpenClawPluginHttpRouteMatch as I, CliBackendPlugin$1 as Ia, ContextEnginePromptCacheInfo as Ic, markAuthProfileCooldown as Id, ProviderExternalAuthProfile as If, resolveEnvelopeFormatOptions as Ii, SpeechProviderResolveTalkOverridesContext as Il, ProviderSanitizeReplayHistoryContext as In, isToolWrappedWithBeforeToolCallHook as Io, NodeSession as Ir, resolveCompletedBatchResult as Is, ProviderCacheTtlEligibilityContext as It, resolveFastModeState as Iu, OpenClawPluginNodeInvokeTransportResult as J, AgentCommandResultMetaOverrides as Ja, SubagentSpawnPreparation as Jc, loadAuthProfileStore as Jd, normalizeHeartbeatToolResponse as Jf, CommandSessionMetadataChange as Ji, OpenClawPluginToolContext as Jl, SpeechProviderPlugin as Jn, MemoryEmbeddingProviderCreateResult as Jo, PluginRuntime as Jr, DEFAULT_LOCAL_MODEL as Js, ProviderExtraParamsForTransportResult as Jt, AgentSimpleCompletionSelection as Ju, OpenClawPluginNodeInvokePolicyContext as K, AgentCommandIngressOpts as Ka, IngestResult as Kc, ensureAuthProfileStoreWithoutExternalProfiles as Kd, HEARTBEAT_RESPONSE_TOOL_NAME as Kf, InternalGetReplyFromConfig as Ki, OpenClawPluginActiveModelContext as Kl, RealtimeTranscriptionProviderPlugin as Kn, MemoryEmbeddingProviderCallOptions as Ko, PluginRegistryParams as Kr, formatUnavailableBatchError as Ks, ProviderDiscoveryResult as Kt, BootstrapContextRunKind as Ku, OpenClawPluginHttpRouteParams as L, CliBackendPrepareExecutionContext as La, ContextEngineRuntimeContext as Lc, markAuthProfileFailure as Ld, ProviderExternalOAuthProfile as Lf, finalizeInboundContext as Li, SpeechSynthesisRequest as Ll, ProviderSystemPromptContributionContext as Ln, setBeforeToolCallDiagnosticsEnabled as Lo, DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS as Lr, throwIfBatchTerminalFailure as Ls, ProviderCapabilities as Lt, FastModeAutoProgressState as Lu, OpenClawPluginGatewayRuntimeScopeSurface as M, CliBackendAuthEpochMode as Ma, ContextEngineInfo as Mc, resolveEnvApiKey as Md, ProviderThinkingProfile as Mf, EnvelopeFormatOptions as Mi, SpeechProviderPrepareSynthesisContext as Ml, ProviderResolveUsageAuthContext as Mn, hasBeforeToolCallPolicy as Mo, GatewayRequestHandlerOptions as Mr, buildBatchHeaders as Ms, ProviderBuildMissingAuthMessageContext as Mt, EmbeddedRunTrigger as Mu, OpenClawPluginHostedMediaResolver as N, CliBackendExecutionMode as Na, ContextEngineMaintenanceResult as Nc, calculateAuthProfileCooldownMs as Nd, ProviderRuntimeModel as Nf, formatAgentEnvelope as Ni, SpeechProviderPreparedSynthesis as Nl, ProviderResolveWebSocketSessionPolicyContext as Nn, requestDeferredPluginToolApproval as No, GatewayRequestHandlers as Nr, normalizeBatchBaseUrl as Ns, ProviderBuildUnknownModelHintContext as Nt, RunEmbeddedAgentParams as Nu, OpenClawPluginCommandDefinition as O, OpenClawAgentToolResult as Oa, CompactResult as Oc, isProviderAuthError as Od, CODEX_CLI_PROFILE_ID as Of, PreparedChannelTurn as Oi, SpeechProviderConfig as Ol, ProviderResolveDynamicModelContext as On, ToolOutcomeObserver as Oo, RealtimeTranscriptionSessionCallbacks as Or, runWithConcurrency as Os, ProviderAuthMethod as Ot, GenerateVideoParams as Ou, OpenClawPluginHttpRouteAuth as P, CliBackendNativeToolMode as Pa, ContextEngineOperation as Pc, clearAuthProfileCooldown as Pd, ProviderRuntimePluginHandle as Pf, formatInboundEnvelope as Pi, SpeechProviderResolveConfigContext as Pl, ProviderResolvedUsageAuth as Pn, runBeforeToolCallHook as Po, GatewayRequestOptions as Pr, BatchCompletionResult as Ps, ProviderBuiltInModelSuppressionContext as Pt, PromptMode as Pu, OpenClawPluginSecurityAuditContext as Q, abortAndDrainEmbeddedAgentRun as Qa, LlmCompleteCaller as Qc, replaceRuntimeAuthProfileStoreSnapshots as Qd, PluginControlUiDescriptor as Qi, ChannelIngressQueue as Ql, VideoGenerationProviderPlugin as Qn, listRegisteredMemoryEmbeddingProviders as Qo, recordDroppedChannelInboundHistory as Qr, isPathInside as Qs, ProviderFollowupFallbackRouteResult as Qt, completeWithPreparedSimpleCompletionModel as Qu, OpenClawPluginHttpRouteUpgradeHandler as R, CliBackendPreparedExecution as Ra, ContextEngineRuntimeMode as Rc, resolveProfileUnusableUntilForDisplay as Rd, ProviderResolveExternalAuthProfilesContext as Rf, settleReplyDispatcher as Ri, SpeechSynthesisStreamRequest as Rl, ProviderToolSchemaDiagnostic as Rn, consumeAdjustedParamsForToolCall as Ro, NormalizedPluginNodeCapabilityUrl as Rr, EmbeddingBatchExecutionParams as Rs, ProviderCatalogContext as Rt, formatFastModeAutoProgressText as Ru, OpenClawPluginAgentEventsApi as S, AgentToolResultMiddlewareContext as Sa, ContextEngineFactory as Sc, shouldPreferExplicitConfigApiKeyAuth as Sd, resolveProviderIdForAuth as Sf, ChannelTurnRecordOptions as Si, TTS_AUTO_MODES as Sl, ProviderReplayPolicyContext as Sn, AgentRuntimePlan as So, RealtimeVoiceToolResultOptions as Sr, cosineSimilarity as Ss, PluginTextTransformRegistration as St, WebSearchProviderPlugin$1 as Su, OpenClawPluginCliCommandDescriptor as T, AgentToolResultMiddlewareOptions as Ta, resolveContextEngineOwnerPluginId as Tc, ResolvedProviderAuth as Td, TokenExpiryState as Tf, ConversationFacts as Ti, SpeechDirectiveTokenParseResult as Tl, ProviderReplaySessionState as Tn, BeforeToolCallPolicyDiagnosticState as To, RealtimeTranscriptionProviderId as Tr, normalizeExtraMemoryPaths as Ts, ProviderAuthContext as Tt, WebSearchProviderToolExecutionContext as Tu, OpenClawPluginNodeInvokeApprovalDecision as U, CliBundleMcpMode as Ua, ContextEngineSelectionSource as Uc, clearRuntimeAuthProfileStoreSnapshots as Ud, EmbeddedAgentRunMeta as Uf, createReplyDispatcher as Ui, TtsDirectiveOverrides as Ul, ProviderValidateReplayTurnsContext as Un, MemoryEmbeddingBatchOptions as Uo, normalizePluginNodeCapabilityScopedUrl as Ur, applyEmbeddingBatchOutputLine as Us, ProviderDeferSyntheticProfileAuthContext as Ut, resolveFastModeForElapsed as Uu, OpenClawPluginNodeCliFeatureOptions as V, CliBackendSideQuestionToolMode as Va, ContextEngineRuntimeSettingsUnavailableError as Vc, getSoonestCooldownExpiry as Vd, ProviderSyntheticAuthResult as Vf, ReplyDispatcherOptions as Vi, SpeechTelephonySynthesisRequest as Vl, ProviderTransportTurnState as Vn, resolveEmbeddedAgentRuntime as Vo, buildPluginNodeCapabilityScopedHostUrl as Vr, EMBEDDING_BATCH_ENDPOINT as Vs, ProviderCreateEmbeddingProviderContext as Vt, formatFastModeSourceSuffix as Vu, OpenClawPluginNodeInvokePolicy as W, PluginTextReplacement as Wa, ContextEngineSessionTarget as Wc, ensureAuthProfileStore as Wd, MessagingToolSend as Wf, createReplyDispatcherWithTyping as Wi, TtsDirectiveParseResult as Wl, ProviderWebSocketSessionPolicy as Wn, MemoryEmbeddingProvider as Wo, PluginHttpRouteRegistration as Wr, postJsonWithRetry as Ws, ProviderDiscoveryContext as Wt, BlockReplyChunking as Wu, OpenClawPluginRunContextApi as X, AbortAndDrainEmbeddedAgentRunResult as Xa, TranscriptRewriteRequest as Xc, loadAuthProfileStoreForSecretsRuntime as Xd, PluginAgentEventEmitResult as Xi, OpenClawPluginToolOptions as Xl, UnifiedModelCatalogProviderContext as Xn, MemoryEmbeddingProviderRuntime as Xo, SubagentRunResult as Xr, hasNonTextEmbeddingParts as Xs, ProviderFetchUsageSnapshotContext as Xt, PreparedSimpleCompletionModelForAgent as Xu, OpenClawPluginReloadRegistration as Y, ProcessToolDefaults as Ya, TranscriptRewriteReplacement as Yc, loadAuthProfileStoreForRuntime as Yd, CrestodianToolOptions as Yf, PluginAgentEventEmitParams as Yi, OpenClawPluginToolFactory$1 as Yl, TranscriptSourceProvider as Yn, MemoryEmbeddingProviderIndexIdentity as Yo, SubagentRunParams as Yr, EmbeddingInput as Ys, ProviderFailoverErrorContext as Yt, PreparedSimpleCompletionModel as Yu, OpenClawPluginSecurityAuditCollector as Z, EmbeddedAgentQueueMessageOutcome as Za, TranscriptRewriteResult as Zc, loadAuthProfileStoreWithoutExternalProfiles as Zd, PluginAgentEventSubscriptionRegistration as Zi, TaskRecord as Zl, UnifiedModelCatalogProviderPlugin as Zn, clearMemoryEmbeddingProviders as Zo, kernel_d_exports as Zr, isFileMissingError as Zs, ProviderFollowupFallbackRouteContext as Zt, SimpleCompletionModelOptions as Zu, MigrationSummary as _, CodexAppServerExtensionFactory as _a, resolveMemorySearchSyncConfig as _c, resolveApiKeyForProvider as _d, resolveAuthProfileEligibility as _f, resolveChannelInboundSupplementalContext as _i, TaskRunView as _l, ProviderPrepareRuntimeAuthContext as _n, CompactEmbeddedAgentSessionParams as _o, RealtimeVoiceProviderId as _r, MemoryChunk as _s, PluginRealtimeVoiceProviderEntry as _t, WebFetchProviderToolDefinition as _u, ImageGenerationProviderPlugin as a, PluginSessionAttachmentParams as aa, listMemoryEmbeddingProviders as ac, RuntimeProviderAuthLookup as ad, removeProviderAuthProfilesWithLock as af, deliverInboundReplyWithMessageSendContext as ai, BoundTaskFlowsRuntime as al, ProviderNormalizeToolSchemasContext as an, AgentHarness as ao, RealtimeVoiceAudioFormat as ar, RemoteEmbeddingClient as as, PluginCommandContext as at, ChannelIngressQueueRecord as au, OpenClawGatewayDiscoveryService as b, CodexAppServerToolResultHandlerResult as ba, appendCronStyleCurrentTimeLine as bc, resolveProviderEntryApiKeyProfileReference as bd, resetProviderAuthAliasMapCacheForTest as bf, ChannelTurnAdmission as bi, TtsConfigResolutionContext as bl, ProviderReasoningOutputModeContext as bn, PreemptiveCompactionRoute as bo, RealtimeVoiceTool as br, buildMultimodalChunkForIndexing as bs, PluginSetupAutoEnableProbe as bt, WebSearchProviderContext as bu, MigrationDetection as c, PluginSessionExtensionRegistration as ca, withProgress as cc, applySecretRefHeaderSentinels as cd, upsertAuthProfileWithLock as cf, BuiltChannelInboundEventContext as ci, PluginRuntimeTaskRuns as cl, ProviderPlugin as cn, AgentHarnessCompactParams as co, RealtimeVoiceBridgeCallbacks as cr, RemoteEmbeddingProviderId as cs, PluginCommandResult as ct, emitAgentEvent as cu, MigrationItemKind as d, PluginSessionTurnScheduleParams as da, HEARTBEAT_PROMPT as dc, getApiKeyForModel as dd, refreshOAuthCredentialForRuntime as df, FinalizeChannelInboundContextParams as di, DetachedTaskLifecycleRuntime as dl, ProviderPluginWizard as dn, AgentHarnessResetParams as do, RealtimeVoiceBrowserSession as dr, debugEmbeddingsLog as ds, PluginEmbeddingProvider as dt, PluginWebFetchProviderEntry as du, PluginRunContextPatch as ea, splitShellArgs as ec, prepareSimpleCompletionModelForAgent as ed, saveAuthProfileStore as ef, hasVisibleChannelTurnDispatch as ei, LlmCompleteParams as el, ProviderModernModelPolicyContext as en, clearActiveEmbeddedRun as eo, ProviderNormalizeConfigContext as er, buildRemoteBaseUrlPolicy as es, OpenClawPluginServiceContext as et, ChannelIngressQueueClaimRef as eu, MigrationItemStatus as f, PluginSessionTurnUnscheduleByTagParams as fa, resolveHeartbeatPrompt as fc, getCustomProviderApiKey as fd, resolveApiKeyForProfile as ff, FinalizeChannelInboundContextResult as fi, TaskFlowDetail as fl, ProviderPluginWizardModelPicker as fn, AgentHarnessResultClassification as fo, RealtimeVoiceBrowserSessionCreateRequest as fr, sanitizeAndNormalizeEmbedding as fs, PluginInteractiveHandlerRegistration as ft, PluginWebSearchProviderEntry as fu, MigrationProviderPreparation as g, CodexAppServerExtensionContext as ga, resolveMemorySearchConfig as gc, hasUsableCustomProviderApiKey as gd, AuthProfileEligibilityReasonCode as gf, finalizeChannelInboundContext as gi, TaskRunDetail as gl, ProviderPrepareExtraParamsContext as gn, AgentHarnessSupportContext as go, RealtimeVoiceProviderConfiguredContext as gr, enforceEmbeddingMaxInputTokens as gs, PluginRealtimeTranscriptionProviderEntry as gt, WebFetchProviderPlugin$1 as gu, MigrationProviderPlugin as h, PluginTrustedToolPolicyRegistration as ha, ResolvedMemorySearchSyncConfig as hc, hasSyntheticLocalProviderAuthConfig as hd, resolveAuthProfileDisplayLabel as hf, filterChannelInboundSupplementalContext as hi, TaskRunCancelResult as hl, ProviderPrepareDynamicModelContext as hn, AgentHarnessSupport as ho, RealtimeVoiceProviderConfig as hr, sanitizeEmbeddingCacheHeaders as hs, PluginLogger as ht, WebFetchProviderId as hu, AgentPromptSurfaceKind as i, PluginSessionActionResult as ia, getMemoryEmbeddingProvider as ic, ProviderEntryApiKeyBindingResolution as id, markAuthProfileSuccess as if, DurableInboundReplyDeliveryResult as ii, RuntimeLogger as il, ProviderNormalizeResolvedModelContext as in, resolveWebSearchToolPolicy as io, RealtimeVoiceAudioClearReason as ir, fetchRemoteEmbeddingVectors as is, OpenClawPluginSessionWorkflowApi as it, ChannelIngressQueuePruneOptions as iu, OpenClawPluginGatewayMethod as j, resolveBootstrapFilesForRun as ja, ContextEngineHostRequirements as jc, EnvApiKeyResult as jd, ProviderThinkingPolicyContext as jf, recordChannelBotPairLoopAndCheckSuppression as ji, SpeechProviderOverrides as jl, ProviderResolveTransportTurnStateContext as jn, getBeforeToolCallPolicyDiagnosticState as jo, GatewayRequestHandler as jr, BatchHttpClientConfig as js, ProviderAuthResult as jt, GenerateImageRuntimeResult as ju, OpenClawPluginConfigSchema as k, buildBootstrapContextForFiles as ka, ContextEngine as kc, requireApiKey as kd, augmentModelCatalogWithProviderPlugins as kf, RunChannelTurnParams as ki, SpeechProviderConfiguredContext as kl, ProviderResolveNonInteractiveApiKeyParams as kn, finalizeToolTerminalPresentation as ko, RealtimeTranscriptionSessionCreateRequest as kr, hashText as ks, ProviderAuthMethodNonInteractiveContext as kt, GenerateVideoRuntimeResult as ku, MigrationItem as l, PluginSessionSchedulerJobHandle as la, withProgressTotals as lc, canUseProfileAsProviderEntryApiKey as ld, dedupeProfileIds as lf, ChannelInboundSupplementalResolutionOptions as li, PluginRuntimeTasks as ll, ProviderPluginCatalog as ln, AgentHarnessCompactResult as lo, RealtimeVoiceBridgeCreateRequest as lr, resolveRemoteEmbeddingBearerClient as ls, PluginConfigMigration as lt, onAgentEvent as lu, MigrationProviderContext as m, PluginToolMetadataRegistration as ma, ResolvedMemorySearchConfig as mc, hasRuntimeAvailableProviderAuth as md, formatAuthDoctorHint as mf, filterChannelInboundQuoteContext as mi, TaskRunAggregateSummary as ml, ProviderPreferRuntimeResolvedModelContext as mn, AgentHarnessSideQuestionResult as mo, RealtimeVoiceProviderCapabilities as mr, mapBatchEmbeddingsByIndex as ms, PluginInteractiveRegistration as mt, WebFetchProviderContext as mu, AgentPromptGuidance as n, PluginSessionActionContext as na, buildPluginConfigSchema as nc, ModelAuthMode as nd, repairOAuthProfileIdMismatch as nf, DurableInboundReplyDeliveryOptions as ni, LlmCompleteUsage as nl, ProviderNonInteractiveApiKeyResult as nn, EmbeddedAgentQueueMessageOptions as no, REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ as nr, estimateStructuredEmbeddingInputBytes as ns, OpenClawPluginSessionControlsApi as nt, ChannelIngressQueueEnqueueResult as nu, MediaUnderstandingProviderPlugin as o, PluginSessionAttachmentResult as oa, listRegisteredMemoryEmbeddingProviderAdapters as oc, applyAuthHeaderOverride as od, setAuthProfileOrder as of, BuildChannelInboundEventContextAsyncParams as oi, BoundTaskRunsRuntime as ol, ProviderNormalizeTransportContext as on, AgentHarnessAttemptParams as oo, RealtimeVoiceBargeInOptions as or, createRemoteEmbeddingProvider as os, PluginCommandDiagnosticsSession as ot, AgentApprovalEventData as ou, MigrationPlan as p, PluginSessionTurnUnscheduleByTagResult as pa, stripHeartbeatToken as pc, hasAvailableAuthForProvider as pd, ExternalCliAuthDiscovery as pf, buildChannelInboundEventContext as pi, TaskFlowView as pl, ProviderPluginWizardSetup as pn, AgentHarnessSideQuestionParams as po, RealtimeVoiceCloseReason as pr, isMissingEmbeddingApiKeyError as ps, PluginInteractiveHandlerResult as pt, WebFetchCredentialResolutionSource as pu, OpenClawPluginNodeInvokePolicyResult as q, AgentCommandOpts as qa, SubagentEndReason as qc, findPersistedAuthProfileCredential as qd, HeartbeatToolResponse as qf, InternalGetReplyOptions as qi, OpenClawPluginHookOptions as ql, RealtimeVoiceProviderPlugin as qn, MemoryEmbeddingProviderCreateOptions as qo, CreatePluginRuntimeOptions as qr, createLocalEmbeddingProvider as qs, ProviderExtraParamsForTransportContext as qt, ExecToolDefaults as qu, AgentPromptGuidanceEntry as r, PluginSessionActionRegistration as ra, emptyPluginConfigSchema as rc, ProviderCredentialPrecedence as rd, suggestOAuthProfileIdForLegacyDefault as rf, DurableInboundReplyDeliveryParams as ri, PluginRuntimeCore as rl, ProviderNormalizeModelIdContext as rn, resolveActiveEmbeddedRunSessionId as ro, REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ as rr, estimateUtf8Bytes as rs, OpenClawPluginSessionStateApi as rt, ChannelIngressQueueFailedRecord as ru, MigrationApplyResult as s, PluginSessionExtensionProjection as sa, parseNonNegativeByteSize as sc, applyLocalNoAuthHeaderOverride as sd, upsertAuthProfile as sf, BuildChannelInboundEventContextParams as si, PluginRuntimeTaskFlows as sl, ProviderOAuthProfileIdRepair as sn, AgentHarnessAttemptResult as so, RealtimeVoiceBridge as sr, resolveRemoteEmbeddingClient as ss, PluginCommandHandler as st, AgentEventPayload as su, AGENT_PROMPT_SURFACE_KINDS as t, PluginRuntimeLifecycleRegistration as ta, buildJsonPluginConfigSchema as tc, resolveSimpleCompletionSelectionForAgent as td, updateAuthProfileStoreWithLock as tf, resolveChannelTurnDispatchCounts as ti, LlmCompleteResult as tl, ProviderNonInteractiveApiKeyCredentialParams as tn, setActiveEmbeddedRun as to, ProviderResolveConfigApiKeyContext as tr, withRemoteHttpResponse as ts, OpenClawPluginSessionApi as tt, ChannelIngressQueueCompletedRecord as tu, MigrationItemAction as u, PluginSessionSchedulerJobRegistration as ua, DEFAULT_HEARTBEAT_ACK_MAX_CHARS as uc, createRuntimeProviderAuthLookup as ud, listProfilesForProvider as uf, FinalizeChannelInboundContextAsyncParams as ui, DetachedTaskFinalizeParams as ul, ProviderPluginDiscovery as un, AgentHarnessDeliveryDefaults as uo, RealtimeVoiceBridgeEvent as ur, normalizeEmbeddingModelWithPrefixes as us, PluginConfigValidation as ut, resetAgentEventsForTest as uu, MusicGenerationProviderPlugin as v, CodexAppServerExtensionRuntime as va, DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR as vc, resolveModelAuthMode as vd, resolveAuthProfileOrder as vf, AccessFacts as vi, ResolvedTtsConfig as vl, ProviderPreparedRuntimeAuth as vn, EmbeddedRunAttemptParams as vo, RealtimeVoiceProviderResolveConfigContext as vr, MemoryFileEntry as vs, PluginRegistrationMode as vt, WebFetchRuntimeMetadataContext as vu, OpenClawPluginChannelRegistration as w, AgentToolResultMiddlewareHarness as wa, registerContextEngine as wc, ProviderAuthError as wd, DEFAULT_OAUTH_REFRESH_MARGIN_MS as wf, CommandFacts as wi, SpeechDirectiveTokenParseContext as wl, ProviderReplaySessionEntry as wn, BeforeToolCallFailureDisposition as wo, RealtimeTranscriptionProviderConfiguredContext as wr, listMemoryFiles as ws, ProviderAugmentModelCatalogContext as wt, WebSearchProviderToolDefinition as wu, OpenClawPluginAgentApi as x, AgentToolResultMiddleware as xa, resolveCronStyleNow as xc, resolveUsableCustomProviderApiKey as xd, resolveProviderAuthAliasMap as xf, ChannelTurnDroppedHistoryOptions as xi, resolveEffectiveTtsConfig as xl, ProviderReplayPolicy as xn, isReplaySafeToolCall as xo, RealtimeVoiceToolCallEvent as xr, chunkMarkdown as xs, PluginSpeechProviderEntry as xt, WebSearchProviderId as xu, OpenClawGatewayDiscoveryAdvertiseContext as y, CodexAppServerToolResultEvent as ya, CronStyleNow as yc, resolveProviderEntryApiKeyBinding as yd, ProviderAuthAliasLookupParams as yf, AssembledChannelTurn as yi, ResolvedTtsModelOverrides as yl, ProviderReasoningOutputMode as yn, EmbeddedRunAttemptResult as yo, RealtimeVoiceRole as yr, buildFileEntry as ys, PluginSetupAutoEnableContext as yt, WebSearchCredentialResolutionSource as yu, OpenClawPluginLifecycleApi as z, CliBackendResolveExecutionArgs as za, ContextEngineRuntimeReasonCode as zc, resolveProfilesUnavailableReason as zd, ProviderResolveExternalOAuthProfilesContext as zf, DispatchReplyWithBufferedBlockDispatcher$1 as zi, SpeechSynthesisStreamResult as zl, ProviderTransformSystemPromptContext as zn, consumePreExecutionBlockedToolCall as zo, PLUGIN_NODE_CAPABILITY_PATH_PREFIX as zr, buildEmbeddingBatchGroupOptions as zs, ProviderCatalogOrder as zt, formatFastModeCommandOptions as zu };