import { Hr as StreamFn, Pr as AgentToolResult, jr as AgentTool, kr as AgentMessage } from "./proxy-abAExyXW.js"; import { c as ImageContent$1, d as Model$1, r as AssistantMessage, w as ThinkingLevel } from "./types-CBQ0-JNc.js"; import { a as SourceReplyDeliveryMode, c as PromptImageOrderEntry, l as InputProvenance, n as GetReplyOptions, o as UserTurnTranscriptRecorder, r as PartialReplyPayload, u as ReplyPayload } from "./types-CgXdquv1.js"; import { n as MsgContext, u as InboundEventKind } from "./templating-BLkCZBKN.js"; import { i as OpenClawConfig, on as CliBackendConfig, pt as TalkProviderConfig, t as ConfigFileSnapshot } from "./types.openclaw-Dkap9jPv.js"; import { l as SecretInput } from "./types.secrets-tbFW-hY6.js"; import { o as AgentModelConfig } from "./types.provider-request-DjXDZnyb.js"; import { O as SessionMaintenanceMode, j as SessionScope } from "./types.base-bTa1ro6X.js"; import { n as SafeBinProfileFixture } from "./exec-safe-bin-policy-profiles-BDyHRwUP.js"; import { M as MemoryCitationsMode, S as ToolLoopDetectionConfig } from "./types.tools-Bn_OLwRV.js"; import { H as TtsAutoMode, U as TtsConfig, V as ResolvedTtsPersona, W as TtsMode, Y as TtsProvider } from "./types.slack-DAS-St0z.js"; import { d as ModelProviderAuthMode, f as ModelProviderConfig, l as ModelMediaInputConfig, o as ModelCompatConfig } from "./types.models-Vjh6XQd-.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-D6ePUYK_.js"; import { f as MediaUnderstandingProvider } from "./types-D-YmDPF-.js"; import { t as ChannelId } from "./channel-id.types-ClK6B_QE.js"; import { b as ExecTarget, g as ExecAsk, v as ExecMode, y as ExecSecurity } from "./exec-approvals-CPpcfY0H.js"; import { n as RuntimeEnv } from "./runtime-Bxifh4bY.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-ylohpEJA.js"; import { i as WizardPrompter } from "./prompts-DgKIGa-v.js"; import { t as JsonSchemaObject } from "./json-schema.types-fpZiub1R.js"; import { t as OperatorScope } from "./operator-scopes-ijAvkvEk.js"; import { n as ChannelPlugin } from "./types.public-B-Egru3s.js"; import { d as UnifiedModelCatalogKind, l as PluginKind, m as PluginConfigUiHint, u as UnifiedModelCatalogEntry } from "./manifest-registry-uVtImuYA.js"; import { t as ConfigWriteAfterWrite } from "./runtime-snapshot-CrZJffyc.js"; import { n as ConfigReplaceResult, t as ConfigMutationBase } from "./config-BTL146qD.js"; import { i as resolveStateDir } from "./paths-Lsj0j7L3.js"; import { c as SessionBindingRecord } from "./session-binding.types-cd2c9es6.js"; import { o as SsrFPolicy } from "./ssrf-skjEI_i5.js"; import { t as ModelProviderRequestTransportOverrides$1 } from "./provider-request-config-G2HAEQ9-.js"; import { n as requestHeartbeat, t as HeartbeatRunResult } from "./heartbeat-wake-B5gXOqCt.js"; import { d as ReasoningLevel, f as ThinkLevel, m as VerboseLevel, p as ThinkingCatalogEntry, s as CommandNormalizeOptions, u as ShouldHandleTextCommandsParams } from "./commands-registry.types-BA9TbajD.js"; import { n as SkillSnapshot, r as SkillTelemetrySource } from "./types-e2DzUtW5.js"; import { r as SandboxBackendExecSpec, s as SandboxFsBridge } from "./backend-handle.types-D7afWmft.js"; import { o as ChannelRouteRef } from "./channel-route-BlhIItCm.js"; import { t as DeliveryContext } from "./delivery-context.types-CMuLXJxD.js"; import { l as SessionSystemPromptReport, n as CliSessionBinding, o as SessionContextBudgetStatus, r as GroupKeyResolution, s as SessionEntry } from "./types-RtYh3aO7.js"; import { t as DiagnosticTraceContext } from "./diagnostic-trace-context-DKGBqNVx.js"; import { n as FailoverReason } from "./types-7Vl6d1IJ.js"; import { t as FallbackAttempt } from "./model-fallback.types-BLDHZH6C.js"; import { n as completeSimple } from "./stream-yzURun8K.js"; import { t as ProviderUsageSnapshot } from "./provider-usage.types-BGbkzahX.js"; import { i as HookEntry, o as ensureAgentWorkspace, r as InternalHookHandler } from "./internal-hook-types-CKIMi9vm.js"; import { r as AnyAgentTool } from "./common-BdhtzyVj.js"; import { t as ModelCatalogEntry } from "./model-catalog.types-D3mWWlzt.js"; import { Oi as AuthStorage, xi as ModelRegistry$1 } from "./index-CmNKdJTo.js"; import { s as LogLevel } from "./subsystem-n4Y4vCcQ.js"; import { t as ProviderAuthEvidence } from "./provider-env-vars-C1Ea_Kwi.js"; import { c as EmbeddedAgentExecutionPhase } from "./store-B_fjddgo.js"; import { n as DEFAULT_MODEL, r as DEFAULT_PROVIDER } from "./defaults-6FEupg54.js"; import { M as resolveAgentDir, N as resolveAgentWorkspaceDir } from "./agent-scope-B4Xy--jT.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-DTk3jkPH.js"; import { S as resolveStorePath, _ as loadSessionStore, c as patchSessionEntry, h as upsertSessionEntry, m as updateSessionStoreEntry, o as getSessionEntry, p as updateSessionStore, s as listSessionEntries, y as resolveSessionFilePath } from "./session-file-DeykXIII.js"; import { o as enqueueSystemEvent } from "./system-events-aSa8pIiL.js"; import { a as runCommandWithTimeout } from "./exec-BdCmhVG3.js"; import { s as mediaKindFromMime } from "./constants-Bjv4FoLj.js"; import { h as resizeToJpeg, u as getImageMetadata } from "./media-services-VQu0-ewV.js"; import { n as loadWebMedia } from "./web-media-DPbTJU4K.js"; import { n as detectMime } from "./mime-Ds6Fkh-A.js"; import { d as readRemoteMediaBuffer, f as saveRemoteMedia, g as isVoiceCompatibleAudio, p as saveResponseMedia, u as fetchRemoteMedia } from "./fetch-6raxI7fB.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-BKqMNpEZ.js"; import { d as VideoGenerationResolution, n as VideoGenerationIgnoredOverride, o as VideoGenerationNormalization, p as VideoGenerationSourceAsset, s as VideoGenerationProvider, t as GeneratedVideoAsset } from "./types-Dqdj3mwb.js"; import { c as MusicGenerationProvider, f as MusicGenerationSourceImage, o as MusicGenerationNormalization, r as MusicGenerationIgnoredOverride, s as MusicGenerationOutputFormat, t as GeneratedMusicAsset } from "./types-Dyl8pyjk.js"; import { n as RuntimeWebSearchMetadata, t as RuntimeWebFetchMetadata } from "./runtime-web-tools.types-Co2KBj4w.js"; import { C as SecretInputMode, n as GatewayRequestHandler, v as AgentEventPayload, x as onAgentEvent, y as AgentEventStream } from "./types-CllBlUKV.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-BaJtc5SJ.js"; import { a as MediaUnderstandingRuntime } from "./runtime-types-HXyc-25P.js"; import { r as EmbeddingProviderAdapter } from "./embedding-providers-hCaXr5gk.js"; import { d as MemoryPromptSectionBuilder, o as MemoryFlushPlanResolver, r as MemoryCorpusSupplement, s as MemoryPluginCapability, u as MemoryPluginRuntime } from "./memory-state-BJcIAV_c.js"; import { Bt as PluginNextTurnInjectionEnqueueResult, Ct as PluginHookToolKind, Ht as PluginJsonValue, M as PluginHookBeforeToolCallEvent, N as PluginHookBeforeToolCallResult, St as PluginHookToolInputKind, a as PluginApprovalResolution, et as PluginHookName, q as PluginHookHandlerMap, tn as PluginHookBeforeAgentStartResult, xt as PluginHookToolContext, zt as PluginNextTurnInjection } from "./hook-types-Ddb7SJ-d.js"; import { Vt as TalkTransport, a as DiagnosticEventPayload, i as DiagnosticEventMetadata, o as DiagnosticEventPrivateData, r as DiagnosticEventInput } from "./diagnostic-events-CUkKDQxn.js"; import { o as TranscriptSourceProvider$1 } from "./provider-types-Bj08Ja9R.js"; import { a as PluginConversationBindingResolvedEvent, n as PluginConversationBindingRequestParams, r as PluginConversationBindingRequestResult, t as PluginConversationBinding } from "./conversation-binding.types-CUczetNC.js"; import { r as ReplyDispatcher } from "./reply-dispatcher.types-D6zjGnXN.js"; import { i as MatchesMentionWithExplicit$1, r as MatchesMentionPatterns$1, t as BuildMentionRegexes$1 } from "./mentions.types-WSGqC1Fw.js"; import { n as RecordInboundSession$1 } from "./session.types-AZsGVEuw.js"; import { t as hasControlCommand } from "./command-detection-BspD3szp.js"; import { t as ResolveMarkdownTableMode } from "./markdown-tables.types-N76f_uWN.js"; import { t as convertMarkdownTables } from "./tables-DRznK8Pj.js"; import { c as DispatchReplyFromConfig, o as createReplyDispatcherWithTyping, t as DispatchReplyWithBufferedBlockDispatcher } from "./provider-dispatcher.types-CVKLrf_Z.js"; import { n as finalizeInboundContext } from "./inbound-context-BQ2UeuLA.js"; import { a as resolveEnvelopeFormatOptions, n as formatAgentEnvelope, r as formatInboundEnvelope } from "./envelope-wCDpPlzi.js"; import { i as buildAgentSessionKey, o as resolveAgentRoute } from "./resolve-route-DYzL8phf.js"; import { n as ReadChannelAllowFromStoreForAccount, r as UpsertChannelPairingRequestForAccount } from "./pairing-store.types-33uOZlgb.js"; import { t as buildPairingReply } from "./pairing-messages-B53CgWtS.js"; import { p as saveMediaBuffer } from "./store-B1k6BLfV.js"; import { n as getChannelActivity, r as recordChannelActivity } from "./channel-activity-BQcki2mv.js"; import { f as implicitMentionKindWhen, p as resolveInboundMentionDecision } from "./mention-gating-D6dFDlTf.js"; import { n as resolveChannelGroupPolicy, r as resolveChannelGroupRequireMention } from "./group-policy-B9F8vEyX.js"; import { n as createInboundDebouncer, r as resolveInboundDebounceMs } from "./inbound-debounce-DDr-SLUq.js"; import { r as resolveCommandAuthorizedFromAuthorizers } from "./command-gating-CqkwecYF.js"; import { a as runPreparedInboundReply, b as buildChannelInboundEventContext, i as runChannelInboundEvent, t as dispatchChannelInboundReply } from "./kernel-DXI6x5iz.js"; import { TSchema } from "typebox"; import { Duplex } from "node:stream"; import { Model } from "openclaw/plugin-sdk/llm"; import { IncomingMessage, ServerResponse } from "node:http"; import { Command } from "commander"; //#region src/auto-reply/reply/reply-run-registry.d.ts type ReplyRunKey = string; type ReplyBackendKind = "embedded" | "cli"; type ReplyBackendCancelReason = "user_abort" | "restart" | "superseded"; type ReplyBackendHandle = { readonly kind: ReplyBackendKind; cancel(reason?: ReplyBackendCancelReason): void; isStreaming(): boolean; queueMessage?: (text: string) => 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 abortSignal: AbortSignal; readonly resetTriggered: boolean; readonly phase: ReplyOperationPhase; readonly result: ReplyOperationResult | null; setPhase(next: "queued" | "preflight_compacting" | "memory_flushing" | "running"): void; updateSessionId(nextSessionId: string): void; attachBackend(handle: ReplyBackendHandle): void; detachBackend(handle: ReplyBackendHandle): 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; fail(code: Exclude, cause?: unknown): void; abortByUser(): void; abortForRestart(): void; }; //#endregion //#region src/process/command-queue.types.d.ts type CommandQueueEnqueueOptions = { warnAfterMs?: number; onWait?: (waitMs: number, queuedAhead: number) => void; taskTimeoutMs?: number; taskTimeoutProgressAtMs?: () => number | undefined; priority?: "foreground" | "normal" | "background"; }; type CommandQueueEnqueueFn = (task: () => Promise, opts?: CommandQueueEnqueueOptions) => Promise; //#endregion //#region src/infra/event-session-routing.d.ts type EventSessionRoutingPolicy = { mainKey?: string; sessionScope?: SessionScope; dmScope?: string | null; allowFrom?: ReadonlyArray | null; channel?: string | null; accountId?: string | null; preserveSessionKey?: boolean; }; //#endregion //#region src/infra/exec-auto-review.d.ts type ExecAutoReviewRisk = "unknown" | "low" | "medium" | "high"; type ExecAutoReviewDecision = { decision: "allow-once"; rationale: string; risk: "low" | "medium" | "high"; } | { decision: "ask"; rationale: string; risk: ExecAutoReviewRisk; }; type ExecAutoReviewHost = "gateway" | "node"; type ExecAutoReviewInput = { command: string; argv?: readonly string[]; cwd?: string | null; envKeys?: readonly string[]; host: ExecAutoReviewHost; reason: "approval-required" | "allowlist-miss" | "strict-inline-eval" | "heredoc" | "execution-plan-miss"; analysis: { parsed: boolean; allowlistMatched: boolean; safeBinMatched?: boolean; durableApprovalMatched?: boolean; inlineEval: boolean; heredoc?: boolean; shellWrapper?: boolean; }; agent?: { id?: string | null; sessionKey?: string | null; }; }; type ExecAutoReviewer = (input: ExecAutoReviewInput) => Promise | ExecAutoReviewDecision; //#endregion //#region src/agents/bash-tools.shared.d.ts type BashSandboxConfig = { containerName: string; workspaceDir: string; containerWorkdir: 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 declare const HEARTBEAT_RESPONSE_TOOL_NAME = "heartbeat_respond"; declare const HEARTBEAT_TOOL_OUTCOMES: readonly ["no_change", "progress", "done", "blocked", "needs_attention"]; type HeartbeatToolOutcome = (typeof HEARTBEAT_TOOL_OUTCOMES)[number]; declare const HEARTBEAT_TOOL_PRIORITIES: readonly ["low", "normal", "high"]; type HeartbeatToolPriority = (typeof HEARTBEAT_TOOL_PRIORITIES)[number]; type HeartbeatToolResponse = { outcome: HeartbeatToolOutcome; notify: boolean; summary: string; notificationText?: string; reason?: string; priority?: HeartbeatToolPriority; nextCheck?: string; }; 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[]; }; type MessagingToolSourceReplyPayload = Pick & { idempotencyKey?: string; }; //#endregion //#region src/agents/run-timeout-attribution.d.ts declare const AGENT_RUN_TIMEOUT_PHASES: readonly ["queue", "preflight", "provider", "post_turn", "gateway_draining"]; type AgentRunTimeoutPhase = (typeof AGENT_RUN_TIMEOUT_PHASES)[number]; //#endregion //#region src/agents/embedded-agent-runner/types.d.ts type EmbeddedAgentMeta = { sessionId: string; sessionFile?: string; provider: string; model: string; contextTokens?: number; agentHarnessId?: string; fallbackAttempts?: FallbackAttempt[]; cliSessionBinding?: CliSessionBinding; 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; reasoningTokens?: number; total?: number; }; contextBudgetStatus?: SessionContextBudgetStatus; }; type TraceAttempt = { provider: string; model: string; result: "success" | "timeout" | "surface_error" | "candidate_failed" | "rotate_profile" | "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" | "hook_block"; message: string; }; 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; audioAsVoice?: boolean; trustedLocalMedia?: boolean; channelData?: Record; }>; meta: EmbeddedAgentRunMeta; diagnosticTrace?: DiagnosticTraceContext; didSendViaMessagingTool?: 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 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 type ProviderResolveSyntheticAuthContext = { config?: OpenClawConfig; provider: string; providerConfig?: ModelProviderConfig; }; type ProviderSyntheticAuthResult = { apiKey: string; source: string; mode: Exclude; expiresAt?: number; }; type ProviderResolveExternalAuthProfilesContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; store: AuthProfileStore; }; type ProviderResolveExternalOAuthProfilesContext = ProviderResolveExternalAuthProfilesContext; type ProviderExternalAuthProfile = { profileId: string; credential: OAuthCredential; persistence?: "runtime-only" | "persisted"; }; type ProviderExternalOAuthProfile = ProviderExternalAuthProfile; //#endregion //#region src/agents/system-prompt-contribution.d.ts type ProviderSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; 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; }; 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 & { reasoning?: boolean; compat?: ProviderThinkingModelCompat | null; }; type ProviderThinkingLevelId = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; 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; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; model: ProviderRuntimeModel; }; }): ProviderRuntimeModel | undefined; declare function applyProviderResolvedTransportWithPlugin(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderNormalizeResolvedModelContext; }): ProviderRuntimeModel | undefined; declare function normalizeProviderTransportWithPlugin(params: { provider: string; 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; retryTransientProviderRuntimeMiss?: boolean; runtimeHooks?: ProviderRuntimeHooks; skipProviderRuntimeHooks?: boolean; skipAgentDiscovery?: boolean; workspaceDir?: 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 Codex provider-owned CLI profile id; do not use from third-party plugins. */ declare const CODEX_CLI_PROFILE_ID = "openai-codex:codex-cli"; //#endregion //#region src/agents/auth-profiles/credential-state.d.ts type AuthCredentialReasonCode = "ok" | "missing_credential" | "invalid_expires" | "expired" | "unresolved_ref"; declare const DEFAULT_OAUTH_REFRESH_MARGIN_MS: number; type TokenExpiryState = "missing" | "valid" | "expiring" | "expired" | "invalid_expires"; declare function hasUsableOAuthCredential(credential: OAuthCredential | undefined, opts?: { now?: number; refreshMarginMs?: number; }): boolean; //#endregion //#region src/agents/auth-profiles/order.d.ts type AuthProfileEligibilityReasonCode = AuthCredentialReasonCode | "profile_missing" | "provider_mismatch" | "mode_mismatch"; type AuthProfileEligibility = { eligible: boolean; reasonCode: AuthProfileEligibilityReasonCode; }; declare function resolveAuthProfileEligibility(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId: string; now?: number; }): AuthProfileEligibility; declare function resolveAuthProfileOrder(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; preferredProfile?: string; }): string[]; //#endregion //#region src/agents/auth-profiles/display.d.ts declare function resolveAuthProfileDisplayLabel(params: { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; }): string; //#endregion //#region src/agents/auth-profiles/doctor.d.ts declare function formatAuthDoctorHint(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId?: string; }): Promise; //#endregion //#region src/agents/auth-profiles/external-cli-discovery.d.ts 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"]; }; type ResolveApiKeyForProfileParams = { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; agentDir?: string; forceRefresh?: boolean; }; declare function refreshOAuthCredentialForRuntime(params: { credential: OAuthCredential; }): Promise; declare function resolveApiKeyForProfile(params: ResolveApiKeyForProfileParams): Promise; //#endregion //#region src/agents/auth-profiles/profile-list.d.ts declare function dedupeProfileIds(profileIds: string[]): string[]; declare function listProfilesForProvider(store: AuthProfileStore, provider: string): string[]; //#endregion //#region src/agents/auth-profiles/profiles.d.ts declare function setAuthProfileOrder(params: { agentDir?: string; provider: string; order?: string[] | null; }): Promise; declare function upsertAuthProfile(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): void; declare function upsertAuthProfileWithLock(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): Promise; declare function removeProviderAuthProfilesWithLock(params: { provider: string; agentDir?: string; }): Promise; declare function markAuthProfileSuccess(params: { store: AuthProfileStore; provider: string; profileId: string; agentDir?: string; }): Promise; //#endregion //#region src/agents/auth-profiles/repair.d.ts declare function suggestOAuthProfileIdForLegacyDefault(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; legacyProfileId: string; }): string | null; 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; externalCli?: ExternalCliAuthDiscovery; readOnly?: boolean; resolveLegacyOAuthSidecars?: boolean; syncExternalCli?: boolean; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; }; type SaveAuthProfileStoreOptions = { filterExternalAuthProfiles?: boolean; syncExternalCli?: boolean; }; declare function updateAuthProfileStoreWithLock(params: { agentDir?: string; saveOptions?: SaveAuthProfileStoreOptions; updater: (store: AuthProfileStore) => boolean; }): Promise; declare function loadAuthProfileStore(): AuthProfileStore; declare function loadAuthProfileStoreForRuntime(agentDir?: string, options?: LoadAuthProfileStoreOptions): AuthProfileStore; declare function loadAuthProfileStoreForSecretsRuntime(agentDir?: string, options?: Pick): AuthProfileStore; declare function loadAuthProfileStoreWithoutExternalProfiles(agentDir?: string, loadOptions?: Pick): AuthProfileStore; declare function ensureAuthProfileStore(agentDir?: string, options?: { allowKeychainPrompt?: boolean; config?: OpenClawConfig; externalCli?: ExternalCliAuthDiscovery; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; readOnly?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; declare function ensureAuthProfileStoreWithoutExternalProfiles(agentDir?: string, options?: { allowKeychainPrompt?: boolean; readOnly?: boolean; resolveLegacyOAuthSidecars?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; declare function findPersistedAuthProfileCredential(params: { agentDir?: string; profileId: string; }): AuthProfileStore["profiles"][string] | undefined; declare function resolvePersistedAuthProfileOwnerAgentDir(params: { agentDir?: string; profileId: string; }): string | undefined; declare function ensureAuthProfileStoreForLocalUpdate(agentDir?: string): AuthProfileStore; declare function replaceRuntimeAuthProfileStoreSnapshots(entries: Array<{ agentDir?: string; store: AuthProfileStore; }>): void; declare function clearRuntimeAuthProfileStoreSnapshots(): void; declare function saveAuthProfileStore(store: AuthProfileStore, agentDir?: string, options?: SaveAuthProfileStoreOptions): 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; declare function calculateAuthProfileCooldownMs(errorCount: number): number; 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; 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; }; declare function resolveEnvApiKey(provider: string, env?: NodeJS.ProcessEnv, options?: EnvApiKeyLookupOptions): EnvApiKeyResult | null; //#endregion //#region src/agents/model-auth-runtime-shared.d.ts type ResolvedProviderAuth = { apiKey?: string; profileId?: string; source: string; mode: "api-key" | "oauth" | "token" | "aws-sdk"; }; declare function resolveAwsSdkEnvVarName(env?: NodeJS.ProcessEnv): string | undefined; declare function formatMissingAuthError(auth: ResolvedProviderAuth, provider: string): string; declare function requireApiKey(auth: ResolvedProviderAuth, provider: string): string; //#endregion //#region src/agents/model-auth.d.ts type ProviderCredentialPrecedence = "profile-first" | "env-first"; type RuntimeProviderAuthLookup = { envApiKey: Pick; syntheticAuthProviderRefs?: readonly string[]; syntheticAuthProviderRefsComplete?: boolean; }; declare function createRuntimeProviderAuthLookup(params: { cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; includePluginSyntheticAuth?: boolean; }): RuntimeProviderAuthLookup; declare function getCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string): string | undefined; type ResolvedCustomProviderApiKey = { apiKey: string; source: string; }; declare function resolveUsableCustomProviderApiKey(params: { cfg: OpenClawConfig | undefined; provider: string; env?: NodeJS.ProcessEnv; }): ResolvedCustomProviderApiKey | null; declare function hasUsableCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string, env?: NodeJS.ProcessEnv): boolean; declare function shouldPreferExplicitConfigApiKeyAuth(cfg: OpenClawConfig | undefined, provider: string): boolean; declare function hasSyntheticLocalProviderAuthConfig(params: { cfg: OpenClawConfig | undefined; provider: string; }): boolean; declare function hasRuntimeAvailableProviderAuth(params: { provider: string; cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; allowPluginSyntheticAuth?: boolean; runtimeLookup?: RuntimeProviderAuthLookup; }): boolean; 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; }): Promise; type ModelAuthMode = "api-key" | "oauth" | "token" | "mixed" | "aws-sdk" | "unknown"; declare function resolveModelAuthMode(provider?: string, cfg?: OpenClawConfig, store?: AuthProfileStore, options?: { workspaceDir?: string; }): ModelAuthMode | undefined; declare function hasAvailableAuthForProvider(params: { provider: string; cfg?: OpenClawConfig; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; }): Promise; declare function getApiKeyForModel(params: { model: Model$1; cfg?: OpenClawConfig; profileId?: string; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; lockedProfile?: boolean; credentialPrecedence?: ProviderCredentialPrecedence; }): Promise; declare function applyLocalNoAuthHeaderOverride(model: T, auth: ResolvedProviderAuth | null | 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; modelRef?: string; }): AgentSimpleCompletionSelection | null; declare function prepareSimpleCompletionModel(params: { cfg: OpenClawConfig | undefined; provider: string; modelId: string; agentDir?: string; profileId?: string; preferredProfile?: string; allowMissingApiKeyModes?: ReadonlyArray; allowBundledStaticCatalogFallback?: boolean; skipAgentDiscovery?: boolean; modelResolver?: typeof resolveModelAsync; }): Promise; declare function prepareSimpleCompletionModelForAgent(params: { cfg: OpenClawConfig; agentId: string; modelRef?: string; preferredProfile?: string; allowMissingApiKeyModes?: ReadonlyArray; allowBundledStaticCatalogFallback?: 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 type ExecReviewerConfig = { model?: AgentModelConfig; timeoutMs?: number; }; //#endregion //#region src/agents/bash-tools.exec-types.d.ts 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; /** `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; accountId?: string; notifyOnExit?: boolean; notifyOnExitEmptySuccess?: boolean; cwd?: string; }; type ExecApprovalFollowupOutcome = { status: "completed" | "failed"; exitCode: number | null; timedOut: boolean; aggregated: string; reason?: string; }; type ExecApprovalFollowupContext = { approvalId: string; sessionId: string; trigger?: string; outcome: ExecApprovalFollowupOutcome; }; type ExecApprovalFollowupFactory = (context: ExecApprovalFollowupContext) => string | undefined | Promise; type ExecElevatedDefaults = { enabled: boolean; allowed: boolean; defaultLevel: "on" | "off" | "ask" | "full"; fullAccessAvailable?: boolean; fullAccessBlockedReason?: EmbeddedFullAccessBlockedReason; }; //#endregion //#region src/agents/command/shared-types.d.ts type AgentStreamParams = { /** Provider stream params override (best-effort). */temperature?: number; topP?: number; maxTokens?: number; /** Provider fast-mode override (best-effort). */ fastMode?: boolean; responseFormat?: Record; frequencyPenalty?: number; presencePenalty?: number; seed?: number; }; 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 type BlockReplyPayload = { text?: string; mediaUrls?: string[]; audioAsVoice?: boolean; trustedLocalMedia?: boolean; sensitiveMedia?: boolean; isReasoning?: boolean; replyToId?: string; replyToTag?: boolean; replyToCurrent?: boolean; }; //#endregion //#region src/agents/embedded-agent-block-chunker.d.ts 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); append(text: string): void; reset(): void; get bufferedText(): string; hasBuffered(): boolean; drain(params: { force: boolean; emit: (chunk: string) => void; }): void; } //#endregion //#region src/agents/embedded-agent-subscribe.shared-types.d.ts type ToolResultFormat = "markdown" | "plain"; type ToolProgressDetailMode = "explain" | "raw"; //#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; }; type AgentInternalEvent = AgentTaskCompletionInternalEvent; //#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 type AuthProfileFailurePolicy = "shared" | "local"; //#endregion //#region src/agents/embedded-agent-runner/run/params.d.ts type EmbeddedRunTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; type CurrentInboundPromptContext = { text: string; promptJoiner?: "\n\n" | "\n" | " "; }; type RunEmbeddedAgentParams = { sessionId: string; sessionKey?: 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; 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; /** Current channel ID for auto-threading (Slack). */ currentChannelId?: string; /** Current thread timestamp for auto-threading (Slack). */ currentThreadTs?: string; /** Current inbound message id for action fallbacks (e.g. Telegram react). */ currentMessageId?: string | number; /** 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; sessionFile: string; workspaceDir: string; /** Task working directory for tool/runtime execution. Defaults to workspaceDir. */ cwd?: string; agentDir?: string; 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$1[]; 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?: 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?: "default" | "heartbeat" | "cron"; /** Optional tool allow-list; when set, only these tools are sent to the model. */ toolsAllow?: string[]; /** 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?: () => void; onExecutionPhase?: (info: { phase: EmbeddedAgentExecutionPhase; provider?: string; model?: string; backend?: string; source?: string; tool?: string; toolCallId?: string; itemId?: string; firstModelCallStarted?: boolean; }) => void; onRunProgress?: (info: { reason: string; provider?: string; model?: string; backend?: string; }) => void; replyOperation?: ReplyOperation; shouldEmitToolResult?: () => boolean; shouldEmitToolOutput?: () => boolean; onPartialReply?: (payload: PartialReplyPayload) => void | Promise; onAssistantMessageStart?: () => void | Promise; onBlockReply?: (payload: BlockReplyPayload) => void | Promise; onBlockReplyFlush?: () => void | Promise; blockReplyBreak?: "text_end" | "message_end"; blockReplyChunking?: BlockReplyChunking; onReasoningStream?: (payload: { text?: string; mediaUrls?: string[]; isReasoningSnapshot?: boolean; }) => void | Promise; onReasoningEnd?: () => void | Promise; onToolResult?: (payload: ReplyPayload) => void | Promise; onAgentEvent?: (evt: { stream: string; data: Record; sessionKey?: string; }) => void | Promise; /** * Emit lifecycle "finishing" when the model turn ends; the caller owns the * final lifecycle "end" after durable post-turn maintenance completes. */ deferTerminalLifecycleEnd?: boolean; lane?: string; enqueue?: CommandQueueEnqueueFn; extraSystemPrompt?: string; customInstructions?: string; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; silentReplyPromptMode?: SilentReplyPromptMode; internalEvents?: AgentInternalEvent[]; inputProvenance?: InputProvenance; streamParams?: AgentStreamParams; ownerNumbers?: string[]; enforceFinalTag?: boolean; silentExpected?: 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; }; //#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 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; resetArchiveRetentionMs: number | null; maxDiskBytes: number | null; highWaterBytes: number | null; }; type SessionMaintenanceApplyReportRuntime = { mode: SessionMaintenanceMode; beforeCount: number; afterCount: number; pruned: number; capped: number; diskBudget: Record | null; }; type SaveSessionStoreOptions = { skipMaintenance?: boolean; activeSessionKey?: string; allowDropAcpMetaSessionKeys?: 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 type NativeDependencyHintParams = { packageName: string; manager?: "pnpm" | "npm" | "yarn"; rebuildCommand?: string; approveBuildsCommand?: string; downloadCommand?: string; }; 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; 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; }; type GenerateImageRuntimeResult = { images: GeneratedImageAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; 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 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; }; type GenerateMusicRuntimeResult = { tracks: GeneratedMusicAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; lyrics?: string[]; normalization?: MusicGenerationNormalization; metadata?: Record; ignoredOverrides: MusicGenerationIgnoredOverride[]; }; type ListRuntimeMusicGenerationProvidersParams = { config?: OpenClawConfig; }; type RuntimeMusicGenerationProvider = MusicGenerationProvider; //#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 = { 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 & { pluginId: string; }; type WebFetchProviderPlugin = { 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 & { pluginId: string; }; //#endregion //#region src/web-search/runtime-types.d.ts type ResolveWebSearchDefinitionParams = { config?: OpenClawConfig; agentDir?: string; sandboxed?: boolean; runtimeWebSearch?: RuntimeWebSearchMetadata; providerId?: string; preferRuntimeProviders?: boolean; preferInputConfig?: boolean; }; type RunWebSearchParams = ResolveWebSearchDefinitionParams & { args: Record; signal?: AbortSignal; }; type RunWebSearchResult = { provider: string; result: Record; }; type ListWebSearchProvidersParams = { config?: OpenClawConfig; }; type RuntimeWebSearchProviderEntry = PluginWebSearchProviderEntry; //#endregion //#region src/sessions/transcript-events.d.ts type SessionTranscriptUpdate = { sessionFile: string; sessionKey?: string; message?: unknown; messageId?: string; messageSeq?: number; }; type SessionTranscriptListener = (update: SessionTranscriptUpdate) => void; declare function onSessionTranscriptUpdate(listener: SessionTranscriptListener): () => void; declare function emitSessionTranscriptUpdate(update: string | SessionTranscriptUpdate): void; //#endregion //#region src/tasks/task-registry.types.d.ts 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"; 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; 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 type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue; }; type TaskFlowSyncMode = "task_mirrored" | "managed"; 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 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; sandboxed?: boolean; }; type OpenClawPluginToolFactory = (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"; type ManagedTaskFlowMutationResult = { applied: true; flow: ManagedTaskFlowRecord; } | { applied: false; code: ManagedTaskFlowMutationErrorCode; current?: TaskFlowRecord; }; 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: { 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; }) => ManagedTaskFlowRecord; 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 type SpeechProviderId = string; type SpeechSynthesisTarget = "audio-file" | "voice-note" | "telephony"; type SpeechProviderConfig = Record; type SpeechProviderOverrides = Record; type SpeechModelOverridePolicy = { enabled: boolean; allowText: boolean; allowProvider: boolean; allowVoice: boolean; allowModelId: boolean; allowVoiceSettings: boolean; allowNormalization: boolean; allowSeed: boolean; }; type TtsDirectiveOverrides = { ttsText?: string; provider?: SpeechProviderId; providerOverrides?: Record; }; type TtsDirectiveParseResult = { cleanedText: string; ttsText?: string; hasDirective: boolean; overrides: TtsDirectiveOverrides; warnings: string[]; }; type SpeechProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: SpeechProviderConfig; timeoutMs: number; }; type SpeechSynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; target: SpeechSynthesisTarget; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; type SpeechSynthesisResult = { audioBuffer: Buffer; outputFormat: string; fileExtension: string; voiceCompatible: boolean; }; type SpeechSynthesisStreamRequest = SpeechSynthesisRequest; type SpeechSynthesisStreamResult = { audioStream: ReadableStream; outputFormat: string; fileExtension: string; voiceCompatible: boolean; release?: () => Promise; }; type SpeechTelephonySynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; type SpeechTelephonySynthesisResult = { audioBuffer: Buffer; outputFormat: string; sampleRate: number; }; type SpeechProviderPrepareSynthesisContext = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; persona?: ResolvedTtsPersona; personaProviderConfig?: SpeechProviderConfig; target: SpeechSynthesisTarget; timeoutMs: number; }; type SpeechProviderPreparedSynthesis = { text?: string; providerConfig?: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; }; type SpeechVoiceOption = { id: string; name?: string; category?: string; description?: string; locale?: string; gender?: string; personalities?: string[]; }; type SpeechListVoicesRequest = { cfg?: OpenClawConfig; providerConfig?: SpeechProviderConfig; apiKey?: string; baseUrl?: string; }; type SpeechProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: Record; timeoutMs: number; }; type SpeechDirectiveTokenParseContext = { key: string; value: string; policy: SpeechModelOverridePolicy; selectedProvider?: SpeechProviderId; providerConfig?: SpeechProviderConfig; currentOverrides?: SpeechProviderOverrides; }; type SpeechDirectiveTokenParseResult = { handled: boolean; overrides?: SpeechProviderOverrides; warnings?: string[]; }; type SpeechProviderResolveTalkConfigContext = { cfg: OpenClawConfig; baseTtsConfig: Record; talkProviderConfig: TalkProviderConfig; timeoutMs: number; }; type SpeechProviderResolveTalkOverridesContext = { talkProviderConfig: TalkProviderConfig; params: Record; }; //#endregion //#region src/tts/tts-auto-mode.d.ts declare const TTS_AUTO_MODES: Set; declare function normalizeTtsAutoMode(value: unknown): TtsAutoMode | undefined; //#endregion //#region src/tts/tts-config.d.ts type TtsConfigResolutionContext = { agentId?: string; channelId?: string; accountId?: string; }; declare function resolveEffectiveTtsConfig(cfg: OpenClawConfig, contextOrAgentId?: string | TtsConfigResolutionContext): TtsConfig; //#endregion //#region src/tts/tts-types.d.ts type ResolvedTtsModelOverrides = SpeechModelOverridePolicy; 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 type TtsAttemptReasonCode = "success" | "no_provider_registered" | "not_configured" | "unsupported_for_streaming" | "unsupported_for_telephony" | "timeout" | "provider_error"; type TtsProviderAttempt = { provider: string; outcome: "success" | "skipped" | "failed"; reasonCode: TtsAttemptReasonCode; persona?: string; personaBinding?: "applied" | "missing" | "none"; latencyMs?: number; error?: string; }; type TtsSpeechTarget = "audio-file" | "voice-note"; type TtsRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; channel?: string; overrides?: TtsDirectiveOverrides; disableFallback?: boolean; timeoutMs?: number; agentId?: string; accountId?: string; }; type TtsTelephonyRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; overrides?: TtsDirectiveOverrides; }; type ListSpeechVoicesParams = { provider: string; cfg?: OpenClawConfig; config?: ResolvedTtsConfig; apiKey?: string; baseUrl?: string; }; 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; }; 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; }; 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; }; type TextToSpeech = (params: TtsRequestParams) => Promise; type TextToSpeechStream = (params: TtsRequestParams) => Promise; type TextToSpeechTelephony = (params: TtsTelephonyRequestParams) => Promise; type ListSpeechVoices = (params: ListSpeechVoicesParams) => Promise; //#endregion //#region src/plugins/runtime/task-domain-types.d.ts type TaskRunAggregateSummary = { total: number; active: number; terminal: number; failures: number; byStatus: TaskStatusCounts; byRuntime: TaskRuntimeCounts; }; 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; }; type TaskRunDetail = TaskRunView; type TaskRunCancelResult = { found: boolean; cancelled: boolean; reason?: string; task?: TaskRunDetail; }; type TaskFlowView = { id: string; ownerKey: string; requesterOrigin?: DeliveryContext; status: TaskFlowStatus; notifyPolicy: TaskNotifyPolicy; goal: string; currentStep?: string; cancelRequestedAt?: number; createdAt: number; updatedAt: number; endedAt?: number; }; 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; 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; }; type DetachedTaskFailParams = { runId: string; runtime?: TaskRuntime; sessionKey?: string; status?: Extract; endedAt: number; lastEventAt?: number; error?: string; progressSummary?: string | null; terminalSummary?: string | null; }; 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; }; 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 DetachedTaskLifecycleRuntime = { createQueuedTaskRun: (params: DetachedTaskCreateParams) => TaskRecord; createRunningTaskRun: (params: DetachedRunningTaskCreateParams) => TaskRecord; startTaskRunByRunId: (params: DetachedTaskStartParams) => TaskRecord[]; recordTaskRunProgressByRunId: (params: DetachedTaskProgressParams) => TaskRecord[]; finalizeTaskRunByRunId?: (params: DetachedTaskFinalizeParams) => TaskRecord[]; completeTaskRunByRunId: (params: DetachedTaskCompleteParams) => TaskRecord[]; failTaskRunByRunId: (params: DetachedTaskFailParams) => TaskRecord[]; setDetachedTaskDeliveryStatusByRunId: (params: DetachedTaskDeliveryStatusParams) => TaskRecord[]; /** * 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 PluginRuntimeThinkingPolicyRequest = { provider?: string | null; model?: string | null; catalog?: ThinkingCatalogEntry[]; }; 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: typeof getSessionEntry; listSessionEntries: typeof listSessionEntries; patchSessionEntry: typeof patchSessionEntry; upsertSessionEntry: typeof upsertSessionEntry; /** * @deprecated Use getSessionEntry/listSessionEntries for reads and * patchSessionEntry/upsertSessionEntry for writes. This keeps the legacy * mutable whole-store compatibility shape. */ loadSessionStore: typeof loadSessionStore; saveSessionStore: SaveSessionStore; updateSessionStore: typeof updateSessionStore; updateSessionStoreEntry: typeof updateSessionStoreEntry; 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; }; 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 precheck uses only the assembled prompt's estimate. * - "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. * * 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 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 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; /** Session file after compaction, when the runtime rotated transcripts. */ 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; 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; /** 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; }): 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; 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. */ 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; }): 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. */ 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/memory-host-sdk/host/embedding-inputs.d.ts type EmbeddingInputTextPart = { type: "text"; text: string; }; type EmbeddingInputInlineDataPart = { type: "inline-data"; mimeType: string; data: string; }; type EmbeddingInputPart = EmbeddingInputTextPart | EmbeddingInputInlineDataPart; type EmbeddingInput = { text: string; parts?: EmbeddingInputPart[]; }; //#endregion //#region src/plugins/memory-embedding-providers.d.ts type MemoryEmbeddingBatchChunk = { text: string; embeddingInput?: EmbeddingInput; }; type MemoryEmbeddingBatchOptions = { agentId: string; chunks: MemoryEmbeddingBatchChunk[]; wait: boolean; concurrency: number; pollIntervalMs: number; timeoutMs: number; debug: (message: string, data?: Record) => void; }; type MemoryEmbeddingProviderCallOptions = { signal?: AbortSignal; }; type MemoryEmbeddingProviderRuntime = { id: string; cacheKeyData?: Record; inlineQueryTimeoutMs?: number; inlineBatchTimeoutMs?: number; batchEmbed?: (options: MemoryEmbeddingBatchOptions) => Promise; }; 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; }; 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"; }; type MemoryEmbeddingProviderCreateResult = { provider: MemoryEmbeddingProvider | null; runtime?: MemoryEmbeddingProviderRuntime; }; type MemoryEmbeddingProviderAdapter = { id: string; defaultModel?: string; transport?: "local" | "remote"; authProviderId?: string; autoSelectPriority?: number; allowExplicitWhenConfiguredAuto?: boolean; supportsMultimodalEmbeddings?: (params: { model: string; }) => boolean; create: (options: MemoryEmbeddingProviderCreateOptions) => Promise; formatSetupError?: (err: unknown) => string; shouldContinueAutoSelection?: (err: unknown) => boolean; }; type RegisteredMemoryEmbeddingProvider = { adapter: MemoryEmbeddingProviderAdapter; ownerPluginId?: string; }; declare function registerMemoryEmbeddingProvider(adapter: MemoryEmbeddingProviderAdapter, options?: { ownerPluginId?: string; }): void; declare function listRegisteredMemoryEmbeddingProviders(): RegisteredMemoryEmbeddingProvider[]; declare function clearMemoryEmbeddingProviders(): void; //#endregion //#region src/agents/agent-runtime-id.d.ts 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.d.ts type ToolOutcomeObservation = { toolName: string; argsHash: string; resultHash: string; }; 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; trace?: DiagnosticTraceContext; channelId?: string; loopDetection?: ToolLoopDetectionConfig; onToolOutcome?: ToolOutcomeObserver; skillsSnapshot?: SkillSnapshot; skillCommand?: { commandName: string; skillName: string; skillSource?: SkillTelemetrySource; toolName?: string; }; sandbox?: { root: string; bridge: SandboxFsBridge; }; }; type HookBlockedKind = "veto" | "failure"; type HookBlockedReason = "plugin-before-tool-call" | "plugin-approval" | "tool-loop"; type HookOutcome = { blocked: true; kind?: HookBlockedKind; deniedReason?: HookBlockedReason; reason: string; params?: unknown; } | { 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; }>; }; declare function getBeforeToolCallPolicyDiagnosticState(): BeforeToolCallPolicyDiagnosticState; declare function hasBeforeToolCallPolicy(): boolean; declare function requestDeferredPluginToolApproval(params: { deferredApproval: DeferredPluginToolApproval; signal?: AbortSignal; }): Promise; declare function runBeforeToolCallHook(args: { toolName: string; params: unknown; toolKind?: PluginHookToolKind; toolInputKind?: PluginHookToolInputKind; toolCallId?: string; ctx?: HookContext; signal?: AbortSignal; approvalMode?: "request" | "report" | "defer"; }): Promise; declare function wrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext, options?: { approvalMode?: "request" | "report"; emitDiagnostics?: boolean; }): AnyAgentTool; declare function isToolWrappedWithBeforeToolCallHook(tool: AnyAgentTool): boolean; declare function setBeforeToolCallDiagnosticsEnabled(tool: AnyAgentTool, enabled: boolean): void; //#endregion //#region src/agents/runtime-plan/types.d.ts type AgentRuntimeTransport = "sse" | "websocket" | "auto"; type AgentRuntimeThinkLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; type AgentRuntimePromptMode = "full" | "minimal" | "none"; type AgentRuntimePromptTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; type AgentRuntimeFailoverReason = "auth" | "auth_permanent" | "format" | "rate_limit" | "overloaded" | "billing" | "server_error" | "timeout" | "model_not_found" | "session_expired" | "empty_response" | "no_error_details" | "unclassified" | "unknown"; type AgentRuntimeConfig = unknown; 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; }; type AgentRuntimeTextReplacement = { from: string | RegExp; to: string; }; type AgentRuntimeTextTransforms = { input?: AgentRuntimeTextReplacement[]; output?: AgentRuntimeTextReplacement[]; }; type AgentRuntimeProviderHandle = { provider: string; config?: AgentRuntimeConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; applyAutoEnable?: boolean; bundledProviderVitestCompat?: boolean; }; type AgentRuntimeInteractiveButtonStyle = "primary" | "secondary" | "success" | "danger"; /** Portable action control exposed to agent runtime reply payloads. */ type AgentRuntimeMessagePresentationButton = { /** User-visible button label. */label: string; /** Callback command or opaque 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; /** Callback command or opaque 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[]; }; type AgentRuntimeMessagePresentationTone = "info" | "success" | "warning" | "danger" | "neutral"; type AgentRuntimeMessagePresentationBlock = { type: "text"; text: string; } | { type: "context"; text: string; } | { type: "divider"; } | { type: "buttons"; buttons: AgentRuntimeMessagePresentationButton[]; } | { type: "select"; placeholder?: string; options: AgentRuntimeMessagePresentationOption[]; }; 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[]; }; type AgentRuntimeReplyPayloadDeliveryPin = { enabled: boolean; notify?: boolean; required?: boolean; }; type AgentRuntimeReplyPayloadDelivery = { pin?: boolean | AgentRuntimeReplyPayloadDeliveryPin; }; 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; isReasoningSnapshot?: boolean; isCompactionNotice?: boolean; isFallbackNotice?: boolean; isStatusNotice?: boolean; channelData?: Record; }; type AgentRuntimeSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; type AgentRuntimeSystemPromptContribution = { stablePrefix?: string; dynamicSuffix?: string; sectionOverrides?: Partial>; }; type AgentRuntimeSystemPromptContributionContext = { config?: AgentRuntimeConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; promptMode: AgentRuntimePromptMode; runtimeChannel?: string; runtimeCapabilities?: string[]; agentId?: string; trigger?: AgentRuntimePromptTrigger; }; type AgentRuntimeFollowupFallbackRouteResult = { route?: "origin" | "dispatcher" | "drop"; reason?: string; }; type AgentRuntimeToolCallIdMode = "strict" | "strict9"; type AgentRuntimeTranscriptPolicy = { sanitizeMode: "full" | "images-only"; sanitizeToolCallIds: boolean; toolCallIdMode?: AgentRuntimeToolCallIdMode; 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; }; type AgentRuntimeOutcomeClassification = { message: string; reason?: AgentRuntimeFailoverReason; status?: number; code?: string; rawError?: string; } | { error: unknown; } | null | undefined; type AgentRuntimeOutcomeClassifier = (params: { provider: string; model: string; result: unknown; hasDirectlySentBlockReply?: boolean; hasBlockReplyPipelineOutput?: boolean; }) => AgentRuntimeOutcomeClassification; type AgentRuntimeResolvedRef = { provider: string; modelId: string; modelApi?: string; harnessId?: string; transport?: AgentRuntimeTransport; }; type AgentRuntimeAuthPlan = { providerForAuth: string; authProfileProviderForAuth: string; harnessAuthProvider?: string; forwardedAuthProfileId?: string; forwardedAuthProfileCandidateIds?: string[]; }; type AgentRuntimePromptPlan = { provider: string; modelId: string; textTransforms?: AgentRuntimeTextTransforms; resolveSystemPromptContribution(context: AgentRuntimeSystemPromptContributionContext): AgentRuntimeSystemPromptContribution | undefined; transformSystemPrompt(context: AgentRuntimeSystemPromptContributionContext & { systemPrompt: string; }): string; }; type AgentRuntimePreparedMetadataSnapshot = object; type PreparedOpenClawToolPlanning = { metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot; loadMetadataSnapshot?: () => AgentRuntimePreparedMetadataSnapshot; }; 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; }; type AgentRuntimeDeliveryPlan = { isSilentPayload(payload: Pick): boolean; resolveFollowupRoute(params: { payload: AgentRuntimeReplyPayload; originatingChannel?: string; originatingTo?: string; originRoutable: boolean; dispatcherAvailable: boolean; }): AgentRuntimeFollowupFallbackRouteResult | undefined; }; type AgentRuntimeOutcomePlan = { classifyRunResult: AgentRuntimeOutcomeClassifier; }; type AgentRuntimeTransportPlan = { extraParams: Record; resolveExtraParams(params?: { extraParamsOverride?: Record; thinkingLevel?: AgentRuntimeThinkLevel; agentId?: string; workspaceDir?: string; model?: AgentRuntimeModel; resolvedTransport?: AgentRuntimeTransport; }): Record; }; 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; }; }; 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; }; //#endregion //#region src/agents/tool-error-summary.d.ts type ToolErrorSummary = { toolName: string; meta?: string; errorCode?: string; error?: string; timedOut?: boolean; middlewareError?: boolean; mutatingAction?: boolean; actionFingerprint?: string; fileTarget?: FileTarget; }; //#endregion //#region src/agents/usage.d.ts type UsageLike = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; total?: number; inputTokens?: number; outputTokens?: number; promptTokens?: number; completionTokens?: number; input_tokens?: number; output_tokens?: number; prompt_tokens?: number; completion_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; reasoningTokens?: number; reasoning_tokens?: number; completion_tokens_details?: { reasoning_tokens?: number; }; output_tokens_details?: { reasoning_tokens?: number; }; cached_tokens?: number; input_tokens_details?: { cached_tokens?: number; }; prompt_tokens_details?: { cached_tokens?: number; }; totalTokens?: number; total_tokens?: number; cache_read?: number; cache_write?: number; prompt_n?: number; predicted_n?: number; timings?: { prompt_n?: number; predicted_n?: number; }; }; type NormalizedUsage = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; reasoningTokens?: number; total?: number; }; declare function normalizeUsage(raw?: UsageLike | null): NormalizedUsage | undefined; //#endregion //#region src/agents/embedded-agent-runner/replay-state.d.ts type EmbeddedRunReplayState = { replayInvalid: boolean; hadPotentialSideEffects: boolean; }; type EmbeddedRunReplayMetadata = { hadPotentialSideEffects: boolean; replaySafe: boolean; }; //#endregion //#region src/agents/embedded-agent-runner/run/preemptive-compaction.types.d.ts 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 EmbeddedRunAttemptParams = EmbeddedRunAttemptBase & { 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; /** 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; 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; beforeAgentStartResult?: PluginHookBeforeAgentStartResult; }; type EmbeddedRunAttemptResult = { aborted: 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; 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"; handled: true; truncatedCount?: number; } | { route: Exclude; source?: "mid-turn"; 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"; transport: "stdio" | "websocket"; threadId?: string; turnId?: string; replaySafe: boolean; replayBlockedReason?: "assistant_output" | "tool_activity" | "potential_side_effect" | "active_item"; }; bootstrapPromptWarningSignaturesSeen?: string[]; bootstrapPromptWarningSignature?: string; systemPromptReport?: SessionSystemPromptReport; finalPromptText?: string; messagesSnapshot: AgentMessage[]; assistantTexts: string[]; toolMetas: Array<{ toolName: string; meta?: string; asyncStarted?: boolean; }>; acceptedSessionSpawns?: AcceptedSessionSpawn[]; lastAssistant: AssistantMessage | undefined; currentAttemptAssistant?: AssistantMessage | undefined; lastToolError?: ToolErrorSummary; didSendViaMessagingTool: boolean; didSendDeterministicApprovalPrompt?: boolean; messagingToolSentTexts: string[]; messagingToolSentMediaUrls: string[]; messagingToolSentTargets: MessagingToolSend[]; messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[]; heartbeatToolResponse?: HeartbeatToolResponse; toolMediaUrls?: string[]; toolAudioAsVoice?: boolean; toolTrustedLocalMedia?: 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; }) => void; }; //#endregion //#region src/agents/embedded-agent-runner/compact.types.d.ts type CompactEmbeddedAgentSessionParams = { sessionId: string; runId?: string; sessionKey?: string; /** Session key used only for runtime policy/sandbox resolution. Defaults to sessionKey. */ sandboxSessionKey?: string; messageChannel?: string; messageProvider?: string; 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; /** 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; /** 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; 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; }; //#endregion //#region src/agents/harness/types.d.ts type AgentHarnessSupportContext = { provider: string; modelId?: string; requestedRuntime: EmbeddedAgentRuntime; }; 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; agentId?: string; workspaceDir?: string; messageChannel?: string; messageProvider?: string; currentChannelId?: string; authProfileId?: string; authProfileIdSource?: "auto" | "user"; }; type AgentHarnessSideQuestionResult = { text: string; }; type AgentHarnessCompactParams = CompactEmbeddedAgentSessionParams; type AgentHarnessCompactResult = EmbeddedAgentCompactResult; type AgentHarnessResetParams = { 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 AgentHarness = { 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; runSideQuestion?(params: AgentHarnessSideQuestionParams): Promise; classify?(result: AgentHarnessAttemptResult, ctx: AgentHarnessAttemptParams): AgentHarnessResultClassification | undefined; compact?(params: AgentHarnessCompactParams): Promise; reset?(params: AgentHarnessResetParams): Promise | void; dispose?(): Promise | void; }; //#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; }; type RealtimeTranscriptionSessionCallbacks = { onPartial?: (partial: string) => void; onTranscript?: (transcript: string) => void; onSpeechStart?: () => void; onError?: (error: Error) => void; }; type RealtimeTranscriptionSessionCreateRequest = RealtimeTranscriptionSessionCallbacks & { cfg?: OpenClawConfig; providerConfig: RealtimeTranscriptionProviderConfig; }; type RealtimeTranscriptionSession = { connect(): Promise; sendAudio(audio: Buffer): void; close(): void; isConnected(): boolean; }; //#endregion //#region src/security/audit.types.d.ts type SecurityAuditSeverity = "info" | "warn" | "critical"; 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 RealtimeVoiceBridgeCallbacks = { onAudio: (audio: Buffer) => void; onClearAudio: () => 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; 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/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/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; }; type CliBackendPreparedExecution = { env?: Record; clearEnv?: string[]; cleanup?: () => Promise; }; type CliBackendThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; type CliBackendResolveExecutionArgsContext = { config?: OpenClawConfig; workspaceDir: string; provider: string; modelId: string; authProfileId?: string; thinkingLevel?: CliBackendThinkingLevel; useResume: boolean; baseArgs: readonly string[]; }; type CliBackendResolveExecutionArgs = (ctx: CliBackendResolveExecutionArgsContext) => readonly string[] | null | undefined; type CliBackendAuthEpochMode = "combined" | "profile-only"; type CliBackendNativeToolMode = "none" | "always-on"; type CliBackendNormalizeConfigContext = { config?: OpenClawConfig; backendId: string; agentId?: string; }; /** Plugin-owned CLI backend defaults used by the text-only CLI runner. */ type CliBackendPlugin = { /** 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[]; /** * 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; }; //#endregion //#region src/plugins/codex-app-server-extension-types.d.ts type CodexAppServerToolResultEvent = { threadId: string; turnId: string; toolCallId: string; toolName: string; args: Record; result: AgentToolResult; }; type CodexAppServerExtensionContext = { agentId?: string; sessionId?: string; sessionKey?: string; runId?: string; }; type CodexAppServerToolResultHandlerResult = { result: AgentToolResult; }; type CodexAppServerExtensionRuntime = { on: (event: "tool_result", handler: (event: CodexAppServerToolResultEvent, ctx: CodexAppServerExtensionContext) => Promise | CodexAppServerToolResultHandlerResult | void) => void; }; type CodexAppServerExtensionFactory = (runtime: CodexAppServerExtensionRuntime) => Promise | void; //#endregion //#region src/plugins/host-hooks.d.ts type PluginHostCleanupReason = "disable" | "reset" | "delete" | "restart"; type PluginSessionExtensionProjectionContext = { sessionKey: string; sessionId?: string; state: PluginJsonValue | undefined; }; 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 PluginControlUiDescriptor = { id: string; surface: "session" | "tool" | "run" | "settings"; label: string; description?: string; placement?: string; schema?: PluginJsonValue; requiredScopes?: OperatorScope[]; }; 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/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 type OAuthPrompt = { message: string; placeholder?: string; }; 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/auto-reply/commands-registry.runtime-types.d.ts type ShouldHandleTextCommands$1 = (params: ShouldHandleTextCommandsParams) => boolean; //#endregion //#region src/auto-reply/command-detection.runtime-types.d.ts type IsControlCommandMessage$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; type ShouldComputeCommandAuthorized$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; //#endregion //#region src/auto-reply/dispatch-dispatcher.d.ts declare function settleReplyDispatcher(params: { dispatcher: ReplyDispatcher; onSettled?: () => void | Promise; }): Promise; declare function withReplyDispatcher(params: { dispatcher: ReplyDispatcher; run: () => Promise; onSettled?: () => void | Promise; }): Promise; //#endregion //#region src/channels/plugins/outbound/load.types.d.ts type LoadChannelOutboundAdapter = (id: ChannelId) => Promise; //#endregion //#region src/auto-reply/reply/reply-dispatcher.runtime-types.d.ts type CreateReplyDispatcherWithTyping = typeof createReplyDispatcherWithTyping; //#endregion //#region src/plugins/runtime/types-channel.d.ts 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 = { 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 SubagentRunParams = { sessionKey: string; message: string; provider?: string; model?: string; extraSystemPrompt?: string; lane?: string; lightContext?: boolean; deliver?: boolean; idempotencyKey?: 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; }; /** Trusted in-process runtime surface injected into native plugins. */ type PluginRuntime = PluginRuntimeCore & { 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; }; channel: PluginRuntimeChannel; }; type CreatePluginRuntimeOptions = { subagent?: PluginRuntime["subagent"]; nodes?: PluginRuntime["nodes"]; allowGatewaySubagentBinding?: boolean; }; //#endregion //#region src/plugins/types.d.ts type ModelProviderRequestTransportOverrides = ModelProviderRequestTransportOverrides$1; 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; /** * 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"]; 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; provider: string; modelId: string; modelRegistry: ModelRegistry; providerConfig?: ProviderRuntimeProviderConfig; }; /** * 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; 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; resolveOAuthToken: (params?: { provider?: string; }) => Promise; }; /** * Result of `resolveUsageAuth`. * * `token` is the credential used for provider usage/billing endpoints. * `accountId` is optional provider-specific metadata used by some usage APIs. */ type ProviderResolvedUsageAuth = { token: string; accountId?: string; }; /** * 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; 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. */ type ProviderPrepareExtraParamsContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; extraParams?: Record; thinkingLevel?: ThinkLevel; }; 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; 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; }; /** * 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 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$1; 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[]; /** 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 & { continueAgent?: 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, 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) => 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) => void; /** Register a web search provider (web search capability). */ registerWebSearchProvider: (provider: WebSearchProviderPlugin) => void; registerInteractiveHandler: (registration: PluginInteractiveHandlerRegistration) => void; onConversationBindingResolved: (handler: (event: PluginConversationBindingResolvedEvent) => 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. Only bundled plugins may use this * before-tool-call policy tier. */ 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 $, TaskRunCancelResult as $a, MessagingToolSourceReplyPayload as $c, wrapToolWithBeforeToolCallHook as $i, SubagentRunParams as $n, WebSearchRuntimeMetadataContext as $o, RealtimeVoiceAudioFormat as $r, isProfileInCooldown as $s, ProviderModelSelectedContext as $t, OpenClawPluginDefinition as A, IngestResult as Aa, AuthCredentialReasonCode as Ac, AgentHarnessResetParams as Ai, ProviderResolvePromptOverlayContext as An, OpenClawPluginActiveModelContext as Ao, CodexAppServerToolResultHandlerResult as Ar, hasAvailableAuthForProvider as As, ProviderAuthOptionBag as At, OpenClawPluginModule as B, LlmCompleteUsage as Ba, ProviderThinkingProfile as Bc, NormalizedUsage as Bi, ProviderTransportTurnState as Bn, WebFetchCredentialResolutionSource as Bo, CliBundleMcpMode as Br, requireApiKey as Bs, ProviderCatalogResult as Bt, OpenClawPluginApi as C, ContextEngineInfo as Ca, resolveApiKeyForProfile as Cc, RealtimeTranscriptionSessionCreateRequest as Ci, ProviderReplaySanitizeMode as Cn, SpeechSynthesisStreamResult as Co, PluginSessionTurnUnscheduleByTagResult as Cr, ProviderCredentialPrecedence as Cs, PluginTranscriptsSourceProviderEntry as Ct, OpenClawPluginCliRegistrar as D, ContextEnginePromptCacheInfo as Da, AuthProfileEligibilityReasonCode as Dc, AgentHarnessCompactParams as Di, ProviderResolveAuthProfileIdContext as Dn, TtsDirectiveOverrides as Do, CodexAppServerExtensionFactory as Dr, createRuntimeProviderAuthLookup as Ds, ProviderAuthKind as Dt, OpenClawPluginCliContext as E, ContextEngineProjection as Ea, resolveAuthProfileDisplayLabel as Ec, AgentHarnessAttemptResult as Ei, ProviderReplayToolCallIdMode as En, SpeechVoiceOption as Eo, CodexAppServerExtensionContext as Er, applyLocalNoAuthHeaderOverride as Es, ProviderAuthDoctorHintContext as Et, OpenClawPluginHttpRouteHandler as F, TranscriptRewriteResult as Fa, CODEX_CLI_PROFILE_ID as Fc, AgentHarnessSupportContext as Fi, ProviderRuntimeProviderConfig as Fn, TaskRecord as Fo, CliBackendPrepareExecutionContext as Fr, resolveModelAuthMode as Fs, ProviderBuiltInModelSuppressionResult as Ft, OpenClawPluginNodeInvokePolicyApprovalRuntime as G, PluginRuntimeTaskFlows as Ga, ProviderExternalOAuthProfile as Gc, DeferredPluginToolApproval as Gi, RealtimeVoiceProviderPlugin as Gn, WebFetchRuntimeMetadataContext as Go, AgentToolResultMiddlewareEvent as Gr, clearAuthProfileCooldown as Gs, ProviderDiscoveryOrder as Gt, OpenClawPluginNodeHostCommand as H, RuntimeLogger as Ha, ProviderRuntimePluginHandle as Hc, AgentRuntimePlan as Hi, ProviderWebSocketSessionPolicy as Hn, WebFetchProviderId as Ho, PluginTextTransforms as Hr, EnvApiKeyResult as Hs, ProviderCreateStreamFnContext as Ht, OpenClawPluginHttpRouteMatch as I, LlmCompleteCaller as Ia, resolveModelAsync as Ic, CompactEmbeddedAgentSessionParams as Ii, ProviderSanitizeReplayHistoryContext as In, emitSessionTranscriptUpdate as Io, CliBackendPreparedExecution as Ir, resolveUsableCustomProviderApiKey as Is, ProviderCacheTtlEligibilityContext as It, OpenClawPluginNodeInvokeTransportResult as J, DetachedTaskFinalizeParams as Ja, ProviderResolveSyntheticAuthContext as Jc, hasBeforeToolCallPolicy as Ji, UnifiedModelCatalogProviderContext as Jn, WebSearchProviderId as Jo, AgentToolResultMiddlewareResult as Jr, markAuthProfileFailure as Js, ProviderExtraParamsForTransportResult as Jt, OpenClawPluginNodeInvokePolicyContext as K, PluginRuntimeTaskRuns as Ka, ProviderResolveExternalAuthProfilesContext as Kc, ToolOutcomeObserver as Ki, SpeechProviderPlugin as Kn, WebSearchCredentialResolutionSource as Ko, AgentToolResultMiddlewareHarness as Kr, markAuthProfileBlockedUntil as Ks, ProviderDiscoveryResult as Kt, OpenClawPluginHttpRouteParams as L, LlmCompleteMessage as La, augmentModelCatalogWithProviderPlugins as Lc, EmbeddedRunAttemptParams as Li, ProviderSystemPromptContributionContext as Ln, onSessionTranscriptUpdate as Lo, CliBackendResolveExecutionArgs as Lr, shouldPreferExplicitConfigApiKeyAuth as Ls, ProviderCapabilities as Lt, OpenClawPluginGatewayRuntimeScopeSurface as M, SubagentSpawnPreparation as Ma, TokenExpiryState as Mc, AgentHarnessSideQuestionParams as Mi, ProviderResolveUsageAuthContext as Mn, OpenClawPluginToolContext as Mo, CliBackendNativeToolMode as Mr, hasSyntheticLocalProviderAuthConfig as Ms, ProviderBuildMissingAuthMessageContext as Mt, OpenClawPluginHostedMediaResolver as N, TranscriptRewriteReplacement as Na, hasUsableOAuthCredential as Nc, AgentHarnessSideQuestionResult as Ni, ProviderResolveWebSocketSessionPolicyContext as Nn, OpenClawPluginToolFactory as No, CliBackendNormalizeConfigContext as Nr, hasUsableCustomProviderApiKey as Ns, ProviderBuildUnknownModelHintContext as Nt, OpenClawPluginCommandDefinition as O, ContextEngineRuntimeContext as Oa, resolveAuthProfileEligibility as Oc, AgentHarnessCompactResult as Oi, ProviderResolveDynamicModelContext as On, TtsDirectiveParseResult as Oo, CodexAppServerExtensionRuntime as Or, getApiKeyForModel as Os, ProviderAuthMethod as Ot, OpenClawPluginHttpRouteAuth as P, TranscriptRewriteRequest as Pa, CLAUDE_CLI_PROFILE_ID as Pc, AgentHarnessSupport as Pi, ProviderResolvedUsageAuth as Pn, OpenClawPluginToolOptions as Po, CliBackendPlugin as Pr, resolveApiKeyForProvider as Ps, ProviderBuiltInModelSuppressionContext as Pt, OpenClawPluginSecurityAuditContext as Q, TaskRunAggregateSummary as Qa, MessagingToolSend as Qc, setBeforeToolCallDiagnosticsEnabled as Qi, PluginRuntime as Qn, WebSearchProviderToolExecutionContext as Qo, REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ as Qr, getSoonestCooldownExpiry as Qs, ProviderFollowupFallbackRouteResult as Qt, OpenClawPluginHttpRouteUpgradeHandler as R, LlmCompleteParams as Ra, ProviderDefaultThinkingPolicyContext as Rc, EmbeddedRunAttemptResult as Ri, ProviderToolSchemaDiagnostic as Rn, PluginWebFetchProviderEntry as Ro, CliBackendResolveExecutionArgsContext as Rr, ResolvedProviderAuth as Rs, ProviderCatalogContext as Rt, OpenClawPluginAgentEventsApi as S, ContextEngineHostRequirements as Sa, refreshOAuthCredentialForRuntime as Sc, RealtimeTranscriptionSessionCallbacks as Si, ProviderReplayPolicyContext as Sn, SpeechSynthesisStreamRequest as So, PluginSessionTurnUnscheduleByTagParams as Sr, ModelAuthMode as Ss, PluginTextTransformRegistration as St, OpenClawPluginCliCommandDescriptor as T, ContextEngineOperation as Ta, formatAuthDoctorHint as Tc, AgentHarnessAttemptParams as Ti, ProviderReplaySessionState as Tn, SpeechTelephonySynthesisRequest as To, PluginTrustedToolPolicyRegistration as Tr, applyAuthHeaderOverride as Ts, ProviderAuthContext as Tt, OpenClawPluginNodeInvokeApprovalDecision as U, BoundTaskFlowsRuntime as Ua, ProviderSystemPromptContribution as Uc, BuildAgentRuntimePlanParams as Ui, ProviderWrapStreamFnContext as Un, WebFetchProviderPlugin as Uo, AgentToolResultMiddleware as Ur, resolveEnvApiKey as Us, ProviderDeferSyntheticProfileAuthContext as Ut, OpenClawPluginNodeCliFeatureOptions as V, PluginRuntimeCore as Va, ProviderRuntimeModel as Vc, normalizeUsage as Vi, ProviderValidateReplayTurnsContext as Vn, WebFetchProviderContext as Vo, PluginTextReplacement as Vr, resolveAwsSdkEnvVarName as Vs, ProviderCreateEmbeddingProviderContext as Vt, OpenClawPluginNodeInvokePolicy as W, BoundTaskRunsRuntime as Wa, ProviderExternalAuthProfile as Wc, BeforeToolCallPolicyDiagnosticState as Wi, RealtimeTranscriptionProviderPlugin as Wn, WebFetchProviderToolDefinition as Wo, AgentToolResultMiddlewareContext as Wr, calculateAuthProfileCooldownMs as Ws, ProviderDiscoveryContext as Wt, OpenClawPluginRunContextApi as X, TaskFlowDetail as Xa, EmbeddedAgentCompactResult as Xc, requestDeferredPluginToolApproval as Xi, VideoGenerationProviderPlugin as Xn, WebSearchProviderSetupContext as Xo, OpenClawAgentToolResult as Xr, resolveProfilesUnavailableReason as Xs, ProviderFetchUsageSnapshotContext as Xt, OpenClawPluginReloadRegistration as Y, DetachedTaskLifecycleRuntime as Ya, ProviderSyntheticAuthResult as Yc, isToolWrappedWithBeforeToolCallHook as Yi, UnifiedModelCatalogProviderPlugin as Yn, WebSearchProviderPlugin as Yo, AgentToolResultMiddlewareRuntime as Yr, resolveProfileUnusableUntilForDisplay as Ys, ProviderFailoverErrorContext as Yt, OpenClawPluginSecurityAuditCollector as Z, TaskFlowView as Za, EmbeddedAgentRunMeta as Zc, runBeforeToolCallHook as Zi, CreatePluginRuntimeOptions as Zn, WebSearchProviderToolDefinition as Zo, REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ as Zr, clearExpiredCooldowns as Zs, ProviderFollowupFallbackRouteContext as Zt, MigrationSummary as _, AssembleResult as _a, setAuthProfileOrder as _c, RealtimeTranscriptionProviderConfig as _i, ProviderPrepareRuntimeAuthContext as _n, SpeechProviderPreparedSynthesis as _o, PluginSessionExtensionProjection as _r, SimpleCompletionModelOptions as _s, PluginRealtimeVoiceProviderEntry as _t, ImageGenerationProviderPlugin as a, MemoryEmbeddingProviderAdapter as aa, loadAuthProfileStore as ac, RealtimeVoiceBrowserSession as ai, ProviderNormalizeToolSchemasContext as an, resolveEffectiveTtsConfig as ao, PluginAgentEventEmitParams as ar, RunEmbeddedAgentParams as as, PluginCommandContext as at, OpenClawGatewayDiscoveryService as b, ContextEngine as ba, dedupeProfileIds as bc, RealtimeTranscriptionProviderResolveConfigContext as bi, ProviderReasoningOutputModeContext as bn, SpeechProviderResolveTalkOverridesContext as bo, PluginSessionSchedulerJobRegistration as br, prepareSimpleCompletionModelForAgent as bs, PluginSetupAutoEnableProbe as bt, MigrationDetection as c, MemoryEmbeddingProviderCreateResult as ca, loadAuthProfileStoreWithoutExternalProfiles as cc, RealtimeVoiceProviderCapabilities as ci, ProviderPlugin as cn, SpeechDirectiveTokenParseContext as co, PluginControlUiDescriptor as cr, BlockReplyChunking as cs, PluginCommandResult as ct, MigrationItemKind as d, listRegisteredMemoryEmbeddingProviders as da, saveAuthProfileStore as dc, RealtimeVoiceProviderId as di, ProviderPluginWizard as dn, SpeechModelOverridePolicy as do, PluginRuntimeLifecycleRegistration as dr, ClientToolDefinition as ds, PluginEmbeddingProvider as dt, AgentHarnessTaskRuntimeScope as ea, clearRuntimeAuthProfileStoreSnapshots as ec, RealtimeVoiceBargeInOptions as ei, HEARTBEAT_RESPONSE_TOOL_NAME as el, ProviderModernModelPolicyContext as en, TaskRunDetail as eo, SubagentRunResult as er, GenerateVideoParams as es, OpenClawPluginServiceContext as et, MigrationItemStatus as f, registerMemoryEmbeddingProvider as fa, updateAuthProfileStoreWithLock as fc, RealtimeVoiceProviderResolveConfigContext as fi, ProviderPluginWizardModelPicker as fn, SpeechProviderConfig as fo, PluginSessionActionContext as fr, ExecElevatedDefaults as fs, PluginInteractiveHandlerRegistration as ft, MigrationProviderPreparation as g, resolveContextEngineOwnerPluginId as ga, removeProviderAuthProfilesWithLock as gc, RealtimeVoiceToolResultOptions as gi, ProviderPrepareExtraParamsContext as gn, SpeechProviderPrepareSynthesisContext as go, PluginSessionAttachmentResult as gr, PreparedSimpleCompletionModelForAgent as gs, PluginRealtimeTranscriptionProviderEntry as gt, MigrationProviderPlugin as h, registerContextEngine as ha, markAuthProfileSuccess as hc, RealtimeVoiceToolCallEvent as hi, ProviderPrepareDynamicModelContext as hn, SpeechProviderOverrides as ho, PluginSessionAttachmentParams as hr, PreparedSimpleCompletionModel as hs, PluginLogger as ht, AgentPromptSurfaceKind as i, MemoryEmbeddingProvider as ia, findPersistedAuthProfileCredential as ic, RealtimeVoiceBridgeEvent as ii, ProviderNormalizeResolvedModelContext as in, TtsConfigResolutionContext as io, ProviderResolveConfigApiKeyContext as ir, EmbeddedRunTrigger as is, OpenClawPluginSessionWorkflowApi as it, OpenClawPluginGatewayMethod as j, SubagentEndReason as ja, DEFAULT_OAUTH_REFRESH_MARGIN_MS as jc, AgentHarnessResultClassification as ji, ProviderResolveTransportTurnStateContext as jn, OpenClawPluginHookOptions as jo, CliBackendAuthEpochMode as jr, hasRuntimeAvailableProviderAuth as js, ProviderAuthResult as jt, OpenClawPluginConfigSchema as k, IngestBatchResult as ka, resolveAuthProfileOrder as kc, AgentHarnessDeliveryDefaults as ki, ProviderResolveNonInteractiveApiKeyParams as kn, ResolvedProviderRuntimeAuth as ko, CodexAppServerToolResultEvent as kr, getCustomProviderApiKey as ks, ProviderAuthMethodNonInteractiveContext as kt, MigrationItem as l, MemoryEmbeddingProviderRuntime as la, replaceRuntimeAuthProfileStoreSnapshots as lc, RealtimeVoiceProviderConfig as li, ProviderPluginCatalog as ln, SpeechDirectiveTokenParseResult as lo, PluginRunContextGetParams as lr, EmbeddedBlockChunker as ls, PluginConfigMigration as lt, MigrationProviderContext as m, ContextEngineFactoryContext as ma, suggestOAuthProfileIdForLegacyDefault as mc, RealtimeVoiceTool as mi, ProviderPreferRuntimeResolvedModelContext as mn, SpeechProviderId as mo, PluginSessionActionResult as mr, AgentSimpleCompletionSelection as ms, PluginInteractiveRegistration as mt, AgentPromptGuidance as n, MemoryEmbeddingBatchChunk as na, ensureAuthProfileStoreForLocalUpdate as nc, RealtimeVoiceBridgeCallbacks as ni, normalizeHeartbeatToolResponse as nl, ProviderNonInteractiveApiKeyResult as nn, ResolvedTtsConfig as no, ProviderApplyConfigDefaultsContext as nr, GenerateImageParams as ns, OpenClawPluginSessionControlsApi as nt, MediaUnderstandingProviderPlugin as o, MemoryEmbeddingProviderCallOptions as oa, loadAuthProfileStoreForRuntime as oc, RealtimeVoiceBrowserSessionCreateRequest as oi, ProviderNormalizeTransportContext as on, TTS_AUTO_MODES as oo, PluginAgentEventEmitResult as or, PromptMode as os, PluginCommandDiagnosticsSession as ot, MigrationPlan as p, ContextEngineFactory as pa, repairOAuthProfileIdMismatch as pc, RealtimeVoiceRole as pi, ProviderPluginWizardSetup as pn, SpeechProviderConfiguredContext as po, PluginSessionActionRegistration as pr, ExecToolDefaults as ps, PluginInteractiveHandlerResult as pt, OpenClawPluginNodeInvokePolicyResult as q, PluginRuntimeTasks as qa, ProviderResolveExternalOAuthProfilesContext as qc, getBeforeToolCallPolicyDiagnosticState as qi, TranscriptSourceProvider as qn, WebSearchProviderContext as qo, AgentToolResultMiddlewareOptions as qr, markAuthProfileCooldown as qs, ProviderExtraParamsForTransportContext as qt, AgentPromptGuidanceEntry as r, MemoryEmbeddingBatchOptions as ra, ensureAuthProfileStoreWithoutExternalProfiles as rc, RealtimeVoiceBridgeCreateRequest as ri, ProviderNormalizeModelIdContext as rn, ResolvedTtsModelOverrides as ro, ProviderNormalizeConfigContext as rr, GenerateImageRuntimeResult as rs, OpenClawPluginSessionStateApi as rt, MigrationApplyResult as s, MemoryEmbeddingProviderCreateOptions as sa, loadAuthProfileStoreForSecretsRuntime as sc, RealtimeVoiceCloseReason as si, ProviderOAuthProfileIdRepair as sn, normalizeTtsAutoMode as so, PluginAgentEventSubscriptionRegistration as sr, AgentInternalEvent as ss, PluginCommandHandler as st, AGENT_PROMPT_SURFACE_KINDS as t, resolveEmbeddedAgentRuntime as ta, ensureAuthProfileStore as tc, RealtimeVoiceBridge as ti, HeartbeatToolResponse as tl, ProviderNonInteractiveApiKeyCredentialParams as tn, TaskRunView as to, settleReplyDispatcher as tr, GenerateVideoRuntimeResult as ts, OpenClawPluginSessionApi as tt, MigrationItemAction as u, clearMemoryEmbeddingProviders as ua, resolvePersistedAuthProfileOwnerAgentDir as uc, RealtimeVoiceProviderConfiguredContext as ui, ProviderPluginDiscovery as un, SpeechListVoicesRequest as uo, PluginRunContextPatch as ur, AgentStreamParams as us, PluginConfigValidation as ut, MusicGenerationProviderPlugin as v, BootstrapResult as va, upsertAuthProfile as vc, RealtimeTranscriptionProviderConfiguredContext as vi, ProviderPreparedRuntimeAuth as vn, SpeechProviderResolveConfigContext as vo, PluginSessionExtensionRegistration as vr, completeWithPreparedSimpleCompletionModel as vs, PluginRegistrationMode as vt, OpenClawPluginChannelRegistration as w, ContextEngineMaintenanceResult as wa, ExternalCliAuthDiscovery as wc, AgentHarness as wi, ProviderReplaySessionEntry as wn, SpeechSynthesisTarget as wo, PluginToolMetadataRegistration as wr, RuntimeProviderAuthLookup as ws, ProviderAugmentModelCatalogContext as wt, OpenClawPluginAgentApi as x, ContextEngineHostCapability as xa, listProfilesForProvider as xc, RealtimeTranscriptionSession as xi, ProviderReplayPolicy as xn, SpeechSynthesisRequest as xo, PluginSessionTurnScheduleParams as xr, resolveSimpleCompletionSelectionForAgent as xs, PluginSpeechProviderEntry as xt, OpenClawGatewayDiscoveryAdvertiseContext as y, CompactResult as ya, upsertAuthProfileWithLock as yc, RealtimeTranscriptionProviderId as yi, ProviderReasoningOutputMode as yn, SpeechProviderResolveTalkConfigContext as yo, PluginSessionSchedulerJobHandle as yr, prepareSimpleCompletionModel as ys, PluginSetupAutoEnableContext as yt, OpenClawPluginLifecycleApi as z, LlmCompleteResult as za, ProviderThinkingPolicyContext as zc, PreemptiveCompactionRoute as zi, ProviderTransformSystemPromptContext as zn, PluginWebSearchProviderEntry as zo, CliBackendThinkingLevel as zr, formatMissingAuthError as zs, ProviderCatalogOrder as zt };