import { E as ThinkingLevel, f as Model$1, l as ImageContent$1, r as AssistantMessage } from "./types-CZAevFX5.js"; import { Dr as AgentMessage, Mr as AgentToolResult, Wr as StreamFn, kr as AgentTool } from "./proxy-B6W6GCLx.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-CQee7pkj.js"; import { i as CommandTurnKind, n as MsgContext, r as CommandTurnContext, t as FinalizedMsgContext, u as InboundEventKind } from "./templating-Cqqe1hGs.js"; import { In as SilentReplyConversationType, i as OpenClawConfig, pt as TalkProviderConfig, sn as CliBackendConfig, t as ConfigFileSnapshot } from "./types.openclaw-CpnoYlBx.js"; import { o as AgentModelConfig } from "./types.provider-request-B-0pnpMf.js"; import { O as SessionMaintenanceMode, d as ContextVisibilityMode, j as SessionScope, v as HumanDelayConfig } from "./types.base-CrXPFJf5.js"; import { n as SafeBinProfileFixture } from "./exec-safe-bin-policy-profiles-BDyHRwUP.js"; import { M as MemoryCitationsMode, S as ToolLoopDetectionConfig } from "./types.tools-Cv1qRb8B.js"; import { G as TtsConfig, K as TtsMode, U as ResolvedTtsPersona, W as TtsAutoMode, Z as TtsProvider } from "./types.slack-D0KGm8xO.js"; import { d as ModelProviderAuthMode, f as ModelProviderConfig, l as ModelMediaInputConfig, o as ModelCompatConfig } from "./types.models-Aj4YxL2N.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-DNDRLfm4.js"; import { f as MediaUnderstandingProvider } from "./types-KM9j04hJ.js"; import { n as HistoryMediaEntry, t as HistoryEntry } from "./history.types-Bc8mCALh.js"; import { t as ChannelId } from "./channel-id.types-DjYEl-_2.js"; import { b as ExecTarget, g as ExecAsk, v as ExecMode, y as ExecSecurity } from "./exec-approvals-BMVAZXjT.js"; import { n as RuntimeEnv } from "./runtime-Bxifh4bY.js"; import { d as UnifiedModelCatalogEntry, f as UnifiedModelCatalogKind, h as PluginConfigUiHint, u as PluginKind } from "./manifest-registry-BtEkkVE2.js"; import { t as JsonSchemaObject } from "./json-schema.types-z_ZXZBRr.js"; import { P as MessageReceipt } from "./types-D77zZaVv.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-CfSE45o1.js"; import { i as WizardPrompter } from "./prompts-DgKIGa-v.js"; import { t as OperatorScope } from "./operator-scopes-Phea7r7e.js"; import { t as ChannelPlugin } from "./types.plugin-oQrs9-Gb.js"; import { n as PluginMetadataSnapshot, t as PluginMetadataRegistryView } from "./plugin-metadata-snapshot.types-c1gNlttf.js"; import { t as ConfigWriteAfterWrite } from "./runtime-snapshot-B86eJRWU.js"; import { n as ConfigReplaceResult, t as ConfigMutationBase } from "./config-DjIVH3y7.js"; import { i as resolveStateDir } from "./paths-BUqnpqoG.js"; import { c as SessionBindingRecord } from "./session-binding.types-BbT2v6Ty.js"; import { o as SsrFPolicy } from "./ssrf-skjEI_i5.js"; import { t as ModelProviderRequestTransportOverrides$1 } from "./provider-request-config-C-hN37EM.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-CqlsKSD9.js"; import { i as SkillTelemetrySource, r as SkillSnapshot } from "./types-DMkIhnzE.js"; import { r as SandboxBackendExecSpec, s as SandboxFsBridge } from "./backend-handle.types-CSIpH53U.js"; import { a as SessionEntry, i as SessionContextBudgetStatus, n as GroupKeyResolution, s as SessionSystemPromptReport, t as CliSessionBinding } from "./types-CCX1gTNG.js"; import { o as ChannelRouteRef } from "./channel-route-DUbOqcPC.js"; import { t as DeliveryContext } from "./delivery-context.types-DyNhFIjW.js"; import { t as DiagnosticTraceContext } from "./diagnostic-trace-context-c5mRZYEt.js"; import { n as FailoverReason } from "./types-CMKgUJ7Q.js"; import { t as FallbackAttempt } from "./model-fallback.types-BQfVfFgq.js"; import { r as completeSimple } from "./stream-DRio68UP.js"; import { t as ProviderUsageSnapshot } from "./provider-usage.types-BxukMSHd.js"; import { i as HookEntry, o as ensureAgentWorkspace, r as InternalHookHandler } from "./internal-hook-types-CKIMi9vm.js"; import { r as AnyAgentTool } from "./common-BQld_MGZ.js"; import { t as ModelCatalogEntry } from "./model-catalog.types-CJ6dM2vF.js"; import { Ai as AuthStorage, Ci as ModelRegistry$1 } from "./index-BorGBMsC.js"; import { s as LogLevel } from "./subsystem-n4Y4vCcQ.js"; import { t as ProviderAuthEvidence } from "./provider-env-vars-DOL95o8u.js"; import { c as EmbeddedAgentExecutionPhase } from "./store-D9Y8B7Gz.js"; import { n as DEFAULT_MODEL, r as DEFAULT_PROVIDER } from "./defaults-6FEupg54.js"; import { N as resolveAgentDir, P as resolveAgentWorkspaceDir } from "./agent-scope-DZ3FuVdu.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-B29HUA45.js"; import { S as resolveSessionFilePath, T as resolveStorePath, _ as updateSessionStoreEntry, b as loadSessionStore, d as patchSessionEntry, g as updateSessionStore, l as getSessionEntry, u as listSessionEntries, v as upsertSessionEntry } from "./sessions-Byk1S2qd.js"; import { o as enqueueSystemEvent } from "./system-events-BPINBuYn.js"; import { a as runCommandWithTimeout } from "./exec-zRR_8-LK.js"; import { s as mediaKindFromMime } from "./constants-DUpDbaN0.js"; import { h as resizeToJpeg, u as getImageMetadata } from "./media-services-C_llATX1.js"; import { n as loadWebMedia } from "./web-media-D1aVPCGn.js"; import { n as detectMime } from "./mime-B6baDqNM.js"; import { d as readRemoteMediaBuffer, f as saveRemoteMedia, g as isVoiceCompatibleAudio, p as saveResponseMedia, u as fetchRemoteMedia } from "./fetch-BMJMSs8r.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-BhltwqXu.js"; import { d as VideoGenerationResolution, n as VideoGenerationIgnoredOverride, o as VideoGenerationNormalization, p as VideoGenerationSourceAsset, s as VideoGenerationProvider, t as GeneratedVideoAsset } from "./types-B9vKuuFx.js"; import { c as MusicGenerationProvider, f as MusicGenerationSourceImage, o as MusicGenerationNormalization, r as MusicGenerationIgnoredOverride, s as MusicGenerationOutputFormat, t as GeneratedMusicAsset } from "./types-loo8-oKo.js"; import { n as RuntimeWebSearchMetadata, t as RuntimeWebFetchMetadata } from "./runtime-web-tools.types-BgJBzqWL.js"; import { C as SecretInputMode, n as GatewayRequestHandler, v as AgentEventPayload, x as onAgentEvent, y as AgentEventStream } from "./types-DxShel1i.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-Bm0_upwK.js"; import { a as MediaUnderstandingRuntime } from "./runtime-types-CSMEOpgy.js"; import { r as EmbeddingProviderAdapter } from "./embedding-providers-BoC8F7nZ.js"; import { d as MemoryPromptSectionBuilder, o as MemoryFlushPlanResolver, r as MemoryCorpusSupplement, s as MemoryPluginCapability, u as MemoryPluginRuntime } from "./memory-state-h-9q2ZAo.js"; import { i as MemoryEmbeddingProviderAdapter } from "./memory-embedding-providers-BnuRkvUl.js"; import { Et as PluginHookToolKind, J as PluginHookHandlerMap, Kt as PluginJsonValue, N as PluginHookBeforeToolCallEvent, Tt as PluginHookToolInputKind, Ut as PluginNextTurnInjection, Wt as PluginNextTurnInjectionEnqueueResult, an as ReplyDispatchBeforeDeliver, dn as PluginHookBeforeAgentStartResult, in as PluginHookBeforeToolCallResult, nn as PluginApprovalResolution, on as ReplyDispatchKind, sn as ReplyDispatcher, tt as PluginHookName, wt as PluginHookToolContext } from "./hook-types-DgRt3F-m.js"; import { Ht as TalkTransport, a as DiagnosticEventPayload, i as DiagnosticEventMetadata, o as DiagnosticEventPrivateData, r as DiagnosticEventInput } from "./diagnostic-events-D1iQK7Zc.js"; import { o as TranscriptSourceProvider$1 } from "./provider-types-DBEXTQwu.js"; import { a as PluginConversationBindingResolvedEvent, n as PluginConversationBindingRequestParams, r as PluginConversationBindingRequestResult, t as PluginConversationBinding } from "./conversation-binding.types-BFfJqmvK.js"; import { a as ResponsePrefixContext, s as TypingCallbacks } from "./reply-prefix-Cv9CAwjQ.js"; import { n as ReadChannelAllowFromStoreForAccount$1, r as UpsertChannelPairingRequestForAccount$1 } from "./pairing-store.types-BTVzEeHr.js"; import { a as MatchesMentionWithExplicit$1, i as MatchesMentionPatterns$1, t as BuildMentionRegexes$1 } from "./mentions.types-C6xoiMSb.js"; import { n as RecordInboundSession$1, t as InboundLastRouteUpdate } from "./session.types-CtfTyAZg.js"; import { t as hasControlCommand } from "./command-detection-CUA14GsW.js"; import { t as ResolveMarkdownTableMode } from "./markdown-tables.types-CRc4TNox.js"; import { t as convertMarkdownTables } from "./tables-BBMGs0qO.js"; import { i as buildAgentSessionKey, o as resolveAgentRoute } from "./resolve-route-CkavOH8l.js"; import { t as buildPairingReply } from "./pairing-messages-2zRdr-XS.js"; import { p as saveMediaBuffer } from "./store-D6pQmvkB.js"; import { n as getChannelActivity, r as recordChannelActivity } from "./channel-activity-B4WQX84y.js"; import { f as implicitMentionKindWhen, p as resolveInboundMentionDecision } from "./mention-gating-D6dFDlTf.js"; import { n as resolveChannelGroupPolicy, r as resolveChannelGroupRequireMention } from "./group-policy-Cbahc9Nd.js"; import { n as createInboundDebouncer, r as resolveInboundDebounceMs } from "./inbound-debounce-C62DU-b9.js"; import { r as resolveCommandAuthorizedFromAuthorizers } from "./command-gating-pUtyEXB1.js"; import { a as OutboundDeliveryQueuePolicy, n as DurableFinalDeliveryRequirement, r as DurableFinalDeliveryRequirements, t as DeliverOutboundPayloadsParams } from "./deliver-CiIAxhtB.js"; import { i as createChannelReplyPipeline, n as CreateChannelReplyPipelineParams } from "./reply-pipeline-DEbSlP5y.js"; import { a as PairLoopGuardResult, i as PairLoopGuardConfig, s as PairLoopGuardSnapshotEntry } from "./pair-loop-guard-runtime-D5O3zwX9.js"; import { n as createChannelHistoryWindow, t as ChannelHistoryWindow } from "./history-window-BSd8jX-m.js"; import { TSchema, Type } from "typebox"; import { Duplex } from "node:stream"; import { Model } from "openclaw/plugin-sdk/llm"; import { IncomingMessage, ServerResponse } from "node:http"; import { Command } from "commander"; import { DatabaseSync } from "node:sqlite"; //#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 routeThreadId?: string | number; 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 /** * Public enqueue knobs shared by command-lane callers and narrower injection * points that should not import the full queue implementation. */ type CommandQueueEnqueueOptions = { warnAfterMs?: number; onWait?: (waitMs: number, queuedAhead: number) => void; taskTimeoutMs?: number; taskTimeoutProgressAtMs?: () => number | undefined; priority?: "foreground" | "normal" | "background"; }; /** Minimal queue function contract used by code that only needs to schedule work. */ type CommandQueueEnqueueFn = (task: () => Promise, opts?: CommandQueueEnqueueOptions) => Promise; //#endregion //#region src/infra/event-session-routing.d.ts /** Routing policy derived from config and the source session for an event. */ type EventSessionRoutingPolicy = { mainKey?: string; sessionScope?: SessionScope; dmScope?: string | null; allowFrom?: ReadonlyArray | null; channel?: string | null; accountId?: string | null; preserveSessionKey?: boolean; }; //#endregion //#region src/infra/exec-auto-review.d.ts /** Risk level returned by exec auto-reviewers for approval routing decisions. */ type ExecAutoReviewRisk = "unknown" | "low" | "medium" | "high"; /** Auto-review outcome: either approve once or send the command to normal approval. */ type ExecAutoReviewDecision = { decision: "allow-once"; rationale: string; risk: "low" | "medium" | "high"; } | { decision: "ask"; rationale: string; risk: ExecAutoReviewRisk; }; /** Execution host whose command policy context is being reviewed. */ type ExecAutoReviewHost = "gateway" | "node"; /** Command and policy facts supplied to an exec auto-reviewer. */ 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; }; }; /** Reviewer function used by gateway/node exec paths before human approval fallback. */ type ExecAutoReviewer = (input: ExecAutoReviewInput) => Promise | ExecAutoReviewDecision; //#endregion //#region src/agents/bash-tools.shared.d.ts /** Sandbox metadata needed to map host workspaces into container exec calls. */ type BashSandboxConfig = { containerName: string; workspaceDir: string; containerWorkdir: string; env?: Record; buildExecSpec?: (params: { command: string; workdir?: string; env: Record; usePty: boolean; }) => Promise; finalizeExec?: (params: { status: "completed" | "failed"; exitCode: number | null; timedOut: boolean; token?: unknown; }) => Promise; }; //#endregion //#region src/auto-reply/heartbeat-tool-response.d.ts /** Tool name used by heartbeat runs to report visible or silent progress. */ declare const HEARTBEAT_RESPONSE_TOOL_NAME = "heartbeat_respond"; /** Allowed heartbeat response outcomes. */ declare const HEARTBEAT_TOOL_OUTCOMES: readonly ["no_change", "progress", "done", "blocked", "needs_attention"]; type HeartbeatToolOutcome = (typeof HEARTBEAT_TOOL_OUTCOMES)[number]; /** Allowed heartbeat notification priorities. */ declare const HEARTBEAT_TOOL_PRIORITIES: readonly ["low", "normal", "high"]; type HeartbeatToolPriority = (typeof HEARTBEAT_TOOL_PRIORITIES)[number]; /** Normalized response emitted by the heartbeat response tool. */ type HeartbeatToolResponse = { outcome: HeartbeatToolOutcome; notify: boolean; summary: string; notificationText?: string; reason?: string; priority?: HeartbeatToolPriority; nextCheck?: string; }; /** Validate and normalize unknown heartbeat tool output. */ declare function normalizeHeartbeatToolResponse(value: unknown): HeartbeatToolResponse | undefined; //#endregion //#region src/agents/accepted-session-spawn.d.ts type AcceptedSessionSpawn = { runId: string; childSessionKey: string; }; //#endregion //#region src/agents/embedded-agent-messaging.types.d.ts type MessagingToolSend = { tool: string; provider: string; accountId?: string; to?: string; threadId?: string; threadImplicit?: boolean; threadSuppressed?: boolean; text?: string; mediaUrls?: string[]; }; type MessagingToolSourceReplyPayload = Pick & { idempotencyKey?: string; }; //#endregion //#region src/agents/run-timeout-attribution.d.ts /** Agent run phases used when attributing timeout/cancellation sources. */ declare const AGENT_RUN_TIMEOUT_PHASES: readonly ["queue", "preflight", "provider", "post_turn", "gateway_draining"]; /** Timeout attribution phase for agent run lifecycle spans. */ type AgentRunTimeoutPhase = (typeof AGENT_RUN_TIMEOUT_PHASES)[number]; //#endregion //#region src/agents/embedded-agent-runner/types.d.ts type EmbeddedAgentMeta = { sessionId: string; sessionFile?: string; provider: string; model: string; contextTokens?: number; agentHarnessId?: string; fallbackAttempts?: FallbackAttempt[]; cliSessionBinding?: CliSessionBinding; clearCliSessionBinding?: boolean; compactionCount?: number; /** * Token count estimate after the most recent successful auto-compaction. * Used as the freshest context snapshot when the follow-up model call omits * usage metadata. */ compactionTokensAfter?: number; /** * Prompt/context snapshot from the latest model request. Prefer this for * context-window utilization because provider usage totals can include cached * and completion tokens that are useful for billing but noisy as live context. */ promptTokens?: number; usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; reasoningTokens?: number; total?: number; }; /** * Usage from the last individual API call (not accumulated across tool-use * loops or compaction retries). Used for context-window utilization display * (`totalTokens` in sessions.json) because the accumulated `usage.input` * sums input tokens from every API call in the run, which overstates the * actual context size. */ lastCallUsage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; 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; didDeliverSourceReplyViaMessageTool?: boolean; didSendDeterministicApprovalPrompt?: boolean; messagingToolSentTexts?: string[]; messagingToolSentMediaUrls?: string[]; messagingToolSentTargets?: MessagingToolSend[]; messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[]; acceptedSessionSpawns?: AcceptedSessionSpawn[]; heartbeatToolResponse?: HeartbeatToolResponse; successfulCronAdds?: number; }; type EmbeddedAgentCompactResult = { ok: boolean; compacted: boolean; reason?: string; /** Structured failure metadata used by model fallback classification. */ failure?: { reason?: string; status?: number; code?: string; rawError?: string; }; result?: { summary: string; firstKeptEntryId: string; tokensBefore: number; tokensAfter?: number; details?: unknown; sessionId?: string; sessionFile?: string; }; }; type EmbeddedFullAccessBlockedReason = "sandbox" | "host-policy" | "channel" | "runtime"; //#endregion //#region src/llm/model-registry.d.ts /** Registry abstraction used by model pickers and provider availability checks. */ type ModelRegistry = { getAll(): Model$1[]; getAvailable(): Model$1[]; find(provider: string, modelId: string): Model$1 | undefined; hasConfiguredAuth(model: Model$1): boolean; }; //#endregion //#region src/plugins/provider-external-auth.types.d.ts /** Context for resolving synthetic provider credentials from config. */ type ProviderResolveSyntheticAuthContext = { config?: OpenClawConfig; provider: string; providerConfig?: ModelProviderConfig; }; /** Synthetic provider credential returned by plugin auth helpers. */ type ProviderSyntheticAuthResult = { apiKey: string; source: string; mode: Exclude; expiresAt?: number; }; /** Context for resolving external provider auth profiles. */ type ProviderResolveExternalAuthProfilesContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; store: AuthProfileStore; }; /** OAuth-specific external auth profile resolution context. */ type ProviderResolveExternalOAuthProfilesContext = ProviderResolveExternalAuthProfilesContext; /** External auth profile credential resolved for a provider. */ type ProviderExternalAuthProfile = { profileId: string; credential: OAuthCredential; persistence?: "runtime-only" | "persisted"; }; /** OAuth-specific provider external auth profile alias. */ type ProviderExternalOAuthProfile = ProviderExternalAuthProfile; //#endregion //#region src/agents/system-prompt-contribution.d.ts /** * Provider-owned system prompt contribution types. * Separates cache-stable prefixes, dynamic suffixes, and section overrides for * runtime prompt assembly. */ /** Core system-prompt sections that providers may replace. */ type ProviderSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; /** Provider guidance merged into the assembled agent system prompt. */ type ProviderSystemPromptContribution = { /** * Cache-stable provider guidance inserted above the system-prompt cache boundary. * * Use this for static provider/model-family instructions that should preserve * KV cache reuse across turns. */ stablePrefix?: string; /** * Provider guidance inserted below the cache boundary. * * Use this only for genuinely dynamic text that is expected to vary across * runs or sessions. */ dynamicSuffix?: string; /** * Whole-section replacements for selected core prompt sections. * * Values should contain the complete rendered section, including any desired * heading such as `## Tool Call Style`. */ sectionOverrides?: Partial>; }; //#endregion //#region src/plugins/provider-hook-runtime.d.ts type ProviderRuntimePluginLookupParams = { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; applyAutoEnable?: boolean; bundledProviderVitestCompat?: boolean; pluginMetadataSnapshot?: PluginMetadataRegistryView; }; type ProviderRuntimePluginHandle = ProviderRuntimePluginLookupParams & { plugin?: ProviderPlugin; }; //#endregion //#region src/plugins/provider-runtime-model.types.d.ts /** * Fully-resolved runtime model shape used after provider/plugin-owned * discovery, overrides, and compat normalization. */ type ProviderRuntimeModel = Omit & { compat?: ModelCompatConfig; contextTokens?: number; params?: Record; requestTimeoutMs?: number; mediaInput?: ModelMediaInputConfig; }; //#endregion //#region src/plugins/provider-thinking.types.d.ts /** * Provider-owned thinking policy input. * * Used by shared `/think`, ACP controls, and directive parsing to ask a * provider whether a model supports special reasoning UX such as adaptive, * xhigh, max, or a binary on/off toggle. */ type ProviderThinkingPolicyContext = { provider: string; modelId: string; }; type ProviderThinkingModelCompat = { thinkingFormat?: string; supportedReasoningEfforts?: readonly string[] | null; }; /** * Provider-owned default thinking policy input. * * `reasoning` is the merged catalog hint for the selected model when one is * available. Providers can use it to keep "reasoning model => low" behavior * without re-reading the catalog themselves. * * `compat` carries model-level request contract facts for the selected model * when available. Providers can use it to expose model-specific thinking * profiles only when the configured payload style supports them. */ type ProviderDefaultThinkingPolicyContext = ProviderThinkingPolicyContext & { 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; modelId?: string | null; 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; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderNormalizeResolvedModelContext; }): ProviderRuntimeModel | undefined; declare function normalizeProviderTransportWithPlugin(params: { provider: string; modelId?: string | null; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderNormalizeTransportContext; }): { api?: string | null; baseUrl?: string; } | undefined; declare function buildProviderUnknownModelHintWithPlugin(params: { provider: string; config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderBuildUnknownModelHintContext; }): string | undefined; declare function augmentModelCatalogWithProviderPlugins(params: { config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; context: ProviderAugmentModelCatalogContext; }): Promise; //#endregion //#region src/agents/embedded-agent-runner/model.d.ts type ProviderRuntimeHooks = { applyProviderResolvedTransportWithPlugin?: (params: Parameters[0]) => unknown; buildProviderUnknownModelHintWithPlugin: (params: Parameters[0]) => string | undefined; prepareProviderDynamicModel: (params: Parameters[0]) => Promise; runProviderDynamicModel: (params: Parameters[0]) => unknown; shouldPreferProviderRuntimeResolvedModel?: (params: Parameters[0]) => boolean; normalizeProviderResolvedModelWithPlugin: (params: Parameters[0]) => unknown; normalizeProviderTransportWithPlugin: typeof normalizeProviderTransportWithPlugin; }; declare function resolveModelAsync(provider: string, modelId: string, agentDir?: string, cfg?: OpenClawConfig, options?: { authStorage?: AuthStorage; modelRegistry?: ModelRegistry$1; allowBundledStaticCatalogFallback?: boolean; preferBundledStaticCatalogTransport?: boolean; retryTransientProviderRuntimeMiss?: boolean; runtimeHooks?: ProviderRuntimeHooks; skipProviderRuntimeHooks?: boolean; skipAgentDiscovery?: boolean; workspaceDir?: string; authProfileId?: string; preferredProfile?: string; }): Promise<{ model?: Model$1; error?: string; authStorage: AuthStorage; modelRegistry: ModelRegistry$1; }>; //#endregion //#region src/agents/auth-profiles/constants.d.ts /** @deprecated Anthropic provider-owned CLI profile id; do not use from third-party plugins. */ declare const CLAUDE_CLI_PROFILE_ID = "anthropic:claude-cli"; /** @deprecated OpenAI provider-owned CLI profile id; do not use from third-party plugins. */ declare const CODEX_CLI_PROFILE_ID = "openai:codex-cli"; //#endregion //#region src/agents/auth-profiles/credential-state.d.ts /** Reason code for why a stored auth credential can or cannot be used. */ type AuthCredentialReasonCode = "ok" | "missing_credential" | "invalid_expires" | "expired" | "unresolved_ref"; /** Default OAuth access-token refresh margin before expiry. */ declare const DEFAULT_OAUTH_REFRESH_MARGIN_MS: number; /** Normalized expiry state for token-style credentials. */ type TokenExpiryState = "missing" | "valid" | "expiring" | "expired" | "invalid_expires"; /** Returns true when an OAuth credential has a non-expiring access token. */ declare function hasUsableOAuthCredential(credential: OAuthCredential | undefined, opts?: { now?: number; refreshMarginMs?: number; }): boolean; //#endregion //#region src/agents/provider-auth-aliases.d.ts /** Inputs that control plugin metadata and trust scope for auth alias lookup. */ type ProviderAuthAliasLookupParams = { config?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; includeUntrustedWorkspacePlugins?: boolean; metadataSnapshot?: Pick; }; /** Clear provider auth alias cache for tests that mutate plugin metadata. */ declare function resetProviderAuthAliasMapCacheForTest(): void; /** Resolve canonical auth provider aliases from plugin metadata. */ declare function resolveProviderAuthAliasMap(params?: ProviderAuthAliasLookupParams): Record; /** Resolve the provider ID that should be used for credential lookup. */ declare function resolveProviderIdForAuth(provider: string, params?: ProviderAuthAliasLookupParams): string; //#endregion //#region src/agents/auth-profiles/order.d.ts /** Reason a profile is or is not eligible for provider auth. */ type AuthProfileEligibilityReasonCode = AuthCredentialReasonCode | "profile_missing" | "provider_mismatch" | "mode_mismatch"; /** Eligibility decision for one auth profile candidate. */ type AuthProfileEligibility = { eligible: boolean; reasonCode: AuthProfileEligibilityReasonCode; }; /** Resolves whether a profile can be used for a provider right now. */ declare function resolveAuthProfileEligibility(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId: string; now?: number; }): AuthProfileEligibility; /** Resolves ordered auth profile candidates for a provider. */ /** Resolve ordered usable auth profile ids for a provider. */ declare function resolveAuthProfileOrder(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; preferredProfile?: string; }): string[]; //#endregion //#region src/agents/auth-profiles/display.d.ts /** Builds the human-readable profile label used in status and auth listings. */ declare function resolveAuthProfileDisplayLabel(params: { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; }): string; //#endregion //#region src/agents/auth-profiles/doctor.d.ts /** Formats provider-specific auth doctor guidance for a profile/store. */ declare function formatAuthDoctorHint(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; profileId?: string; }): Promise; //#endregion //#region src/agents/auth-profiles/external-cli-discovery.d.ts /** External CLI auth discovery mode used while loading auth profile stores. */ type ExternalCliAuthDiscovery = { mode: "none"; allowKeychainPrompt?: false; config?: OpenClawConfig; } | { mode: "existing"; allowKeychainPrompt?: boolean; config?: OpenClawConfig; } | { mode: "scoped"; allowKeychainPrompt?: boolean; config?: OpenClawConfig; providerIds?: Iterable; profileIds?: Iterable; }; //#endregion //#region src/agents/auth-profiles/oauth.d.ts type ResolveApiKeyForProfileResult = { apiKey: string; provider: string; email?: string; profileId: string; profileType: AuthProfileCredential["type"]; }; /** Detect provider errors caused by single-use OAuth refresh token races. */ type ResolveApiKeyForProfileParams = { cfg?: OpenClawConfig; store: AuthProfileStore; profileId: string; agentDir?: string; forceRefresh?: boolean; }; /** Refresh one OAuth credential and merge provider-returned token fields. */ declare function refreshOAuthCredentialForRuntime(params: { credential: OAuthCredential; }): Promise; /** Resolve a selected auth profile into the provider API key string. */ declare function resolveApiKeyForProfile(params: ResolveApiKeyForProfileParams): Promise; //#endregion //#region src/agents/auth-profiles/profile-list.d.ts /** Deduplicates profile ids while preserving first-seen order. */ declare function dedupeProfileIds(profileIds: string[]): string[]; /** Lists auth profile ids whose credential provider matches the requested provider. */ declare function listProfilesForProvider(store: AuthProfileStore, provider: string): string[]; //#endregion //#region src/agents/auth-profiles/profiles.d.ts /** Sets or clears explicit auth profile order for a provider. */ declare function setAuthProfileOrder(params: { agentDir?: string; provider: string; order?: string[] | null; }): Promise; /** Upserts an auth profile immediately into the local store. */ declare function upsertAuthProfile(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): void; /** Upserts an auth profile under the auth store lock. */ declare function upsertAuthProfileWithLock(params: { profileId: string; credential: AuthProfileCredential; agentDir?: string; }): Promise; /** Removes all auth profiles and related state for a provider. */ declare function removeProviderAuthProfilesWithLock(params: { provider: string; agentDir?: string; }): Promise; /** Mark a profile as successfully used and update ordering/usage metadata. */ declare function markAuthProfileSuccess(params: { store: AuthProfileStore; provider: string; profileId: string; agentDir?: string; }): Promise; //#endregion //#region src/agents/auth-profiles/repair.d.ts /** Suggests a modern OAuth profile id for a legacy provider:default profile. */ declare function suggestOAuthProfileIdForLegacyDefault(params: { cfg?: OpenClawConfig; store: AuthProfileStore; provider: string; legacyProfileId: string; }): string | null; /** Migrates config auth profile references away from a legacy OAuth default id. */ declare function repairOAuthProfileIdMismatch(params: { cfg: OpenClawConfig; store: AuthProfileStore; provider: string; legacyProfileId?: string; }): AuthProfileIdRepairResult; //#endregion //#region src/infra/sqlite-wal.d.ts type SqliteWalCheckpointMode = "PASSIVE" | "FULL" | "RESTART" | "TRUNCATE"; type SqliteWalMaintenance = { checkpoint: () => boolean; close: () => boolean; }; /** Options controlling WAL autocheckpoint and periodic checkpoint behavior. */ type SqliteWalMaintenanceOptions = { autoCheckpointPages?: number; checkpointIntervalMs?: number; checkpointMode?: SqliteWalCheckpointMode; databaseLabel?: string; databasePath?: string; onCheckpointError?: (error: unknown) => void; }; //#endregion //#region src/state/openclaw-agent-db.d.ts /** Open per-agent SQLite database handle plus lifecycle maintenance. */ type OpenClawAgentDatabase = { agentId: string; db: DatabaseSync; path: string; walMaintenance: SqliteWalMaintenance; }; //#endregion //#region src/agents/auth-profiles/store.d.ts type LoadAuthProfileStoreOptions = { allowKeychainPrompt?: boolean; config?: OpenClawConfig; database?: OpenClawAgentDatabase; externalCli?: ExternalCliAuthDiscovery; readOnly?: boolean; syncExternalCli?: boolean; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; }; type SaveAuthProfileStoreOptions = { filterExternalAuthProfiles?: boolean; preserveOrderProfileIds?: Iterable; preserveStateProfileIds?: Iterable; pruneOrderProfileIds?: Iterable; syncExternalCli?: boolean; }; /** Apply an auth store update inside the SQLite write lock. */ declare function updateAuthProfileStoreWithLock(params: { agentDir?: string; saveOptions?: SaveAuthProfileStoreOptions; updater: (store: AuthProfileStore) => boolean; }): Promise; /** Load the main auth profile store with runtime external profiles overlaid. */ declare function loadAuthProfileStore(): AuthProfileStore; /** Loads the effective runtime store for an agent, including inherited main profiles. */ declare function loadAuthProfileStoreForRuntime(agentDir?: string, options?: LoadAuthProfileStoreOptions): AuthProfileStore; /** Load auth profiles for secret resolution without keychain prompts or writes. */ declare function loadAuthProfileStoreForSecretsRuntime(agentDir?: string, options?: Pick): AuthProfileStore; /** Load auth profiles with runtime external profiles removed from the result. */ declare function loadAuthProfileStoreWithoutExternalProfiles(agentDir?: string, loadOptions?: Pick): AuthProfileStore; /** Ensure an auth store is available, including runtime/external profile overlays. */ declare function ensureAuthProfileStore(agentDir?: string, options?: { allowKeychainPrompt?: boolean; config?: OpenClawConfig; externalCli?: ExternalCliAuthDiscovery; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; readOnly?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; /** Ensure an auth store is available without external profile overlays. */ declare function ensureAuthProfileStoreWithoutExternalProfiles(agentDir?: string, options?: { allowKeychainPrompt?: boolean; readOnly?: boolean; syncExternalCli?: boolean; }): AuthProfileStore; /** Find a persisted credential in the scoped store, falling back to the main store. */ declare function findPersistedAuthProfileCredential(params: { agentDir?: string; profileId: string; }): AuthProfileStore["profiles"][string] | undefined; /** Resolve which agent dir owns a persisted profile, accounting for inherited OAuth. */ declare function resolvePersistedAuthProfileOwnerAgentDir(params: { agentDir?: string; profileId: string; }): string | undefined; /** Load the store shape used when applying local-only auth updates. */ declare function ensureAuthProfileStoreForLocalUpdate(agentDir?: string): AuthProfileStore; /** Replace runtime auth-profile snapshots, used by tests and prepared runtimes. */ declare function replaceRuntimeAuthProfileStoreSnapshots(entries: Array<{ agentDir?: string; store: AuthProfileStore; }>): void; /** Clear all runtime auth-profile snapshots. */ declare function clearRuntimeAuthProfileStoreSnapshots(): void; /** Save the auth profile store plus sidecar state, preserving runtime overlay metadata. */ declare function saveAuthProfileStore(store: AuthProfileStore, agentDir?: string, options?: SaveAuthProfileStoreOptions, database?: OpenClawAgentDatabase): void; //#endregion //#region src/agents/auth-profiles/usage-state.d.ts /** * Check if a profile is currently in cooldown (due to rate limits, overload, or other transient failures). */ declare function isProfileInCooldown(store: AuthProfileStore, profileId: string, now?: number, forModel?: string): boolean; /** * Return the soonest `unusableUntil` timestamp (ms epoch) among the given * profiles, or `null` when no profile has a recorded cooldown. Note: the * returned timestamp may be in the past if the cooldown has already expired. */ declare function getSoonestCooldownExpiry(store: AuthProfileStore, profileIds: string[], options?: { now?: number; forModel?: string; }): number | null; /** * Clear expired cooldowns from all profiles in the store. * * When `cooldownUntil` or `disabledUntil` has passed, the corresponding fields * are removed and error counters are reset so the profile gets a fresh start * (circuit-breaker half-open -> closed). Without this, a stale `errorCount` * causes the *next* transient failure to immediately escalate to a much longer * cooldown -- the root cause of profiles appearing "stuck" after rate limits. * * `cooldownUntil` and `disabledUntil` are handled independently: if a profile * has both and only one has expired, only that field is cleared. * * Mutates the in-memory store; disk persistence happens lazily on the next * store write (e.g. `markAuthProfileSuccess` / `markAuthProfileFailure`), which * matches the existing save pattern throughout the auth-profiles module. * * @returns `true` if any profile was modified. */ declare function clearExpiredCooldowns(store: AuthProfileStore, now?: number): boolean; //#endregion //#region src/agents/auth-profiles/usage.d.ts /** * Infer the most likely reason all candidate profiles are currently unavailable. * * We prefer explicit active `disabledReason` values (for example billing/auth) * over generic cooldown buckets, then fall back to failure-count signals. */ declare function resolveProfilesUnavailableReason(params: { store: AuthProfileStore; profileIds: string[]; now?: number; }): AuthProfileFailureReason | null; /** Returns the regular transient-failure cooldown duration for an error count. */ declare function calculateAuthProfileCooldownMs(errorCount: number): number; /** Resolves the display-facing unusable timestamp, honoring provider bypasses. */ declare function resolveProfileUnusableUntilForDisplay(store: AuthProfileStore, profileId: string): number | null; /** * Mark a profile as failed for a specific reason. Billing and permanent-auth * failures are treated as "disabled" (longer backoff) vs the regular cooldown * window. */ declare function markAuthProfileFailure(params: { store: AuthProfileStore; profileId: string; reason: AuthProfileFailureReason; cfg?: OpenClawConfig; agentDir?: string; runId?: string; modelId?: string; }): Promise; /** Marks a profile blocked until a provider-reported reset timestamp. */ declare function markAuthProfileBlockedUntil(params: { store: AuthProfileStore; profileId: string; blockedUntil: number; source: AuthProfileBlockedSource; agentDir?: string; runId?: string; modelId?: string; }): Promise; /** * Mark a profile as transiently failed. Applies stepped backoff cooldown. * Cooldown times: 30s, 1min, 5min (capped). * Uses store lock to avoid overwriting concurrent usage updates. */ declare function markAuthProfileCooldown(params: { store: AuthProfileStore; profileId: string; agentDir?: string; runId?: string; }): Promise; /** * Clear cooldown for a profile (e.g., manual reset). * Uses store lock to avoid overwriting concurrent usage updates. */ declare function clearAuthProfileCooldown(params: { store: AuthProfileStore; profileId: string; agentDir?: string; }): Promise; //#endregion //#region src/agents/model-auth-env.d.ts type EnvApiKeyResult = { apiKey: string; source: string; }; type EnvApiKeyLookupOptions = { config?: OpenClawConfig; workspaceDir?: string; aliasMap?: Readonly>; candidateMap?: Readonly>; authEvidenceMap?: Readonly>; skipSetupProviderFallback?: boolean; }; /** Resolve an API key or auth-evidence marker for a provider from environment state. */ declare function resolveEnvApiKey(provider: string, env?: NodeJS.ProcessEnv, options?: EnvApiKeyLookupOptions): EnvApiKeyResult | null; //#endregion //#region src/agents/model-auth-runtime-shared.d.ts /** Resolved credential material and provenance for one provider request. */ type ResolvedProviderAuth = { apiKey?: string; profileId?: string; source: string; mode: "api-key" | "oauth" | "token" | "aws-sdk"; }; /** Stable provider auth error code used by fallback/retry paths. */ type ProviderAuthErrorCode = "missing-api-key" | "missing-provider-auth"; /** Base provider auth error with a stable code for retry/fallback logic. */ declare class ProviderAuthError extends Error { readonly code: ProviderAuthErrorCode; readonly provider: string; constructor(code: ProviderAuthErrorCode, provider: string, message: string); } /** Auth error raised when a resolved provider auth source lacks usable material. */ declare class MissingProviderAuthError extends ProviderAuthError { readonly mode: ResolvedProviderAuth["mode"]; readonly source: string; constructor(provider: string, auth: ResolvedProviderAuth); } /** Narrow unknown errors to provider auth errors, optionally by code. */ declare function isProviderAuthError(err: unknown, code?: ProviderAuthErrorCode): err is ProviderAuthError; /** Narrow unknown errors to missing-provider-auth failures. */ declare function isMissingProviderAuthError(err: unknown): err is MissingProviderAuthError; /** Return the AWS credential env var that proves SDK auth is configured. */ declare function resolveAwsSdkEnvVarName(env?: NodeJS.ProcessEnv): string | undefined; /** Format the user-facing missing-auth error from auth provenance. */ declare function formatMissingAuthError(auth: ResolvedProviderAuth, provider: string): string; /** Require a normalized API key or throw a provider-auth error. */ declare function requireApiKey(auth: ResolvedProviderAuth, provider: string): string; //#endregion //#region src/agents/model-auth.d.ts type ProviderCredentialPrecedence = "profile-first" | "env-first"; /** Precomputed provider-auth lookup tables reused during one runtime turn. */ type RuntimeProviderAuthLookup = { envApiKey: Pick; setupProviderFallbackRefs?: readonly string[]; syntheticAuthProviderRefs?: readonly string[]; syntheticAuthProviderRefsComplete?: boolean; }; /** Builds stable env/synthetic auth lookup data for repeated provider checks. */ declare function createRuntimeProviderAuthLookup(params: { cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; includePluginSyntheticAuth?: boolean; }): RuntimeProviderAuthLookup; /** Reads a literal or env-secret marker for a custom provider entry. */ declare function getCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string): string | undefined; type ResolvedCustomProviderApiKey = { apiKey: string; source: string; }; /** Resolves custom provider API keys that are usable without mutating secret stores. */ declare function resolveUsableCustomProviderApiKey(params: { cfg: OpenClawConfig | undefined; provider: string; env?: NodeJS.ProcessEnv; }): ResolvedCustomProviderApiKey | null; /** True when a custom provider has a literal/env/local key available now. */ declare function hasUsableCustomProviderApiKey(cfg: OpenClawConfig | undefined, provider: string, env?: NodeJS.ProcessEnv): boolean; /** True when explicit provider config should outrank profile/environment auth. */ declare function shouldPreferExplicitConfigApiKeyAuth(cfg: OpenClawConfig | undefined, provider: string): boolean; type ProviderEntryApiKeyProfileReference = { kind: "none"; } | { kind: "literal"; apiKey: string; source: string; } | { kind: "profile"; profileId: string; credential: AuthProfileCredential; mode: ResolvedProviderAuth["mode"]; } | { kind: "profile-incompatible"; profileId: string; credentialProvider: string; credentialType: AuthProfileCredential["type"]; reason: "credential-class" | "provider-binding"; } | { kind: "marker"; }; type ProviderEntryApiKeyBindingResolution = { kind: "none"; } | { kind: "literal"; apiKey: string; source: string; } | { kind: "profile-resolved"; auth: ResolvedProviderAuth; } | { kind: "profile-incompatible"; profileId: string; credentialProvider: string; credentialType: AuthProfileCredential["type"]; reason: "credential-class" | "provider-binding"; } | { kind: "profile-unresolved"; profileId: string; error?: unknown; }; /** True when a bearer auth profile can safely satisfy a provider-entry apiKey reference. */ declare function canUseProfileAsProviderEntryApiKey(params: { cfg?: OpenClawConfig; provider: string; credential: AuthProfileCredential; }): boolean; /** Classifies a provider entry apiKey as literal/profile/marker before resolving secrets. */ declare function resolveProviderEntryApiKeyProfileReference(params: { cfg?: OpenClawConfig; provider: string; store: AuthProfileStore; }): ProviderEntryApiKeyProfileReference; /** Resolves a provider-entry apiKey profile reference into runtime auth when possible. */ declare function resolveProviderEntryApiKeyBinding(params: { cfg?: OpenClawConfig; provider: string; store: AuthProfileStore; agentDir?: string; }): Promise; /** True when a custom local provider can use a synthetic no-auth placeholder. */ declare function hasSyntheticLocalProviderAuthConfig(params: { cfg: OpenClawConfig | undefined; provider: string; }): boolean; /** Fast auth-availability check for runtime provider/model selection. */ declare function hasRuntimeAvailableProviderAuth(params: { provider: string; cfg?: OpenClawConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; allowPluginSyntheticAuth?: boolean; runtimeLookup?: RuntimeProviderAuthLookup; modelApi?: string; }): boolean; /** Resolves the credential that should be used for one provider request. */ declare function resolveApiKeyForProvider(params: { provider: string; cfg?: OpenClawConfig; profileId?: string; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; /** When true, treat profileId as a user-locked selection that must not be * silently overridden by env/config credentials. */ lockedProfile?: boolean; forceRefresh?: boolean; credentialPrecedence?: ProviderCredentialPrecedence; modelApi?: string; }): Promise; type ModelAuthMode = "api-key" | "oauth" | "token" | "mixed" | "aws-sdk" | "unknown"; /** Reports the strongest configured auth mode for provider-list UI and diagnostics. */ declare function resolveModelAuthMode(provider?: string, cfg?: OpenClawConfig, store?: AuthProfileStore, options?: { workspaceDir?: string; }): ModelAuthMode | undefined; /** Checks provider auth availability, including profile fallback order. */ declare function hasAvailableAuthForProvider(params: { provider: string; cfg?: OpenClawConfig; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; modelApi?: string; }): Promise; /** Resolves request credentials from the provider attached to a model descriptor. */ declare function getApiKeyForModel(params: { model: Model$1; cfg?: OpenClawConfig; profileId?: string; preferredProfile?: string; store?: AuthProfileStore; agentDir?: string; workspaceDir?: string; lockedProfile?: boolean; credentialPrecedence?: ProviderCredentialPrecedence; }): Promise; /** Clears auth for local OpenAI-compatible servers that explicitly use no auth. */ 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 /** Config for the optional model-backed exec reviewer. */ type ExecReviewerConfig = { model?: AgentModelConfig; timeoutMs?: number; }; //#endregion //#region src/agents/bash-tools.exec-types.d.ts /** Runtime defaults passed into exec/process tool factories. */ type ExecToolDefaults = { hasCronTool?: boolean; host?: ExecTarget; mode?: ExecMode; security?: ExecSecurity; ask?: ExecAsk; trigger?: string; node?: string; pathPrepend?: string[]; safeBins?: string[]; strictInlineEval?: boolean; commandHighlighting?: boolean; safeBinTrustedDirs?: string[]; safeBinProfiles?: Record; reviewer?: ExecReviewerConfig; config?: OpenClawConfig; autoReviewer?: ExecAutoReviewer; agentId?: string; backgroundMs?: number; timeoutSec?: number; approvalWarningText?: string; approvalFollowupText?: string; approvalFollowup?: ExecApprovalFollowupFactory; approvalFollowupMode?: "agent" | "direct"; approvalRunningNoticeMs?: number; sandbox?: BashSandboxConfig; elevated?: ExecElevatedDefaults; allowBackground?: boolean; scopeKey?: string; sessionKey?: string; /** `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; }; /** Outcome passed to approval follow-up factories after approved async exec. */ type ExecApprovalFollowupOutcome = { status: "completed" | "failed"; exitCode: number | null; timedOut: boolean; aggregated: string; reason?: string; }; type ExecApprovalFollowupContext = { approvalId: string; sessionId: string; trigger?: string; outcome: ExecApprovalFollowupOutcome; }; /** Hook that can append domain-specific text to approval follow-up messages. */ type ExecApprovalFollowupFactory = (context: ExecApprovalFollowupContext) => string | undefined | Promise; /** Effective elevated-exec defaults derived from config/runtime policy. */ type ExecElevatedDefaults = { enabled: boolean; allowed: boolean; defaultLevel: "on" | "off" | "ask" | "full"; fullAccessAvailable?: boolean; fullAccessBlockedReason?: EmbeddedFullAccessBlockedReason; }; //#endregion //#region src/agents/command/shared-types.d.ts /** * Shared command types that are imported by both public and runtime modules. */ /** Best-effort provider stream parameter overrides for an agent command. */ type AgentStreamParams = { /** Provider stream params override (best-effort). */temperature?: number; topP?: number; maxTokens?: number; /** Stop sequences forwarded to the provider (best-effort). */ stop?: string[]; /** Provider fast-mode override (best-effort). */ fastMode?: boolean; responseFormat?: Record; frequencyPenalty?: number; presencePenalty?: number; seed?: number; }; /** Simplified tool definition for client-provided OpenResponses hosted tools. */ type ClientToolDefinition = { type: "function"; function: { name: string; description?: string; parameters?: Record; /** Strict argument enforcement (Responses API). Propagated from the request. */ strict?: boolean; }; }; //#endregion //#region src/agents/embedded-agent-payloads.d.ts /** * Channel-facing reply payload emitted by embedded agents. Keep this type * small: channel adapters decide how to render text, media, and reply targets. */ type BlockReplyPayload = { text?: string; mediaUrls?: string[]; audioAsVoice?: boolean; trustedLocalMedia?: boolean; sensitiveMedia?: boolean; isReasoning?: boolean; 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); /** Add streamed text to the pending chunk buffer. */ append(text: string): void; /** Clear any buffered reply text without emitting it. */ reset(): void; /** Return the currently buffered text for tests and flush logic. */ get bufferedText(): string; /** Return true when there is pending text to drain. */ hasBuffered(): boolean; /** Emit safe chunks according to size and Markdown fence constraints. */ drain(params: { force: boolean; emit: (chunk: string) => void; }): void; } //#endregion //#region src/agents/embedded-agent-subscribe.shared-types.d.ts /** Rendering mode for completed tool results in subscribed replies. */ type ToolResultFormat = "markdown" | "plain"; /** Detail level for in-flight tool progress messages. */ type ToolProgressDetailMode = "explain" | "raw"; //#endregion //#region src/agents/generated-attachments.d.ts type AgentGeneratedAttachment = { type?: "image" | "audio" | "video" | "file"; path?: string; url?: string; mediaUrl?: string; filePath?: string; mimeType?: string; name?: string; }; //#endregion //#region src/agents/internal-event-contract.d.ts declare const AGENT_INTERNAL_EVENT_TYPE_TASK_COMPLETION: "task_completion"; declare const AGENT_INTERNAL_EVENT_SOURCES: readonly ["subagent", "cron", "image_generation", "video_generation", "music_generation"]; declare const AGENT_INTERNAL_EVENT_STATUSES: readonly ["ok", "timeout", "error", "unknown"]; type AgentInternalEventSource = (typeof AGENT_INTERNAL_EVENT_SOURCES)[number]; type AgentInternalEventStatus = (typeof AGENT_INTERNAL_EVENT_STATUSES)[number]; //#endregion //#region src/agents/internal-events.d.ts type AgentTaskCompletionInternalEvent = { type: typeof AGENT_INTERNAL_EVENT_TYPE_TASK_COMPLETION; source: AgentInternalEventSource; childSessionKey: string; childSessionId?: string; announceType: string; taskLabel: string; status: AgentInternalEventStatus; statusLabel: string; result: string; attachments?: AgentGeneratedAttachment[]; mediaUrls?: string[]; statsLine?: string; replyInstruction: string; }; /** Internal event variants that can be rendered into agent prompt context. */ type AgentInternalEvent = AgentTaskCompletionInternalEvent; //#endregion //#region src/agents/system-prompt.types.d.ts type PromptMode = "full" | "minimal" | "none"; type SilentReplyPromptMode = "generic" | "none"; //#endregion //#region src/agents/embedded-agent-runner/run/auth-profile-failure-policy.types.d.ts /** * Scope used when classifying auth-profile failures for retry/fallback decisions. */ type AuthProfileFailurePolicy = "shared" | "local"; //#endregion //#region src/agents/embedded-agent-runner/run/params.d.ts type EmbeddedRunTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; type CurrentInboundPromptContext = { text: string; resumableText?: 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; /** True when the current inbound turn carried audio media. */ currentInboundAudio?: boolean; /** Reply-to mode for Slack auto-threading. */ replyToMode?: "off" | "first" | "all" | "batched"; /** Mutable ref to track if a reply was sent (for "first" mode). */ hasRepliedRef?: { value: boolean; }; /** Require explicit message tool targets (no implicit last-route sends). */ requireExplicitMessageTarget?: boolean; /** If true, omit the message tool from the tool list. */ disableMessageTool?: boolean; /** Internal one-shot model probe mode: no tools, no workspace/chat prompt policy. */ modelRun?: boolean; /** Explicit system prompt mode override for trusted callers. */ promptMode?: PromptMode; /** Keep the message tool available even when a narrow profile would omit it. */ forceMessageTool?: boolean; /** Include the heartbeat response tool for structured heartbeat outcomes. */ enableHeartbeatTool?: boolean; /** Keep the heartbeat response tool available even when a narrow profile would omit it. */ forceHeartbeatTool?: boolean; /** Allow runtime plugins for this run to late-bind the gateway subagent. */ allowGatewaySubagentBinding?: boolean; 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; 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 /** Runtime hook for reading a session store entry timestamp. */ type ReadSessionUpdatedAt$1 = (params: { storePath: string; sessionKey: string; }) => number | undefined; type SessionMaintenanceWarningRuntime = { activeSessionKey: string; activeUpdatedAt?: number; totalEntries: number; pruneAfterMs: number; maxEntries: number; wouldPrune: boolean; wouldCap: boolean; }; type ResolvedSessionMaintenanceConfigRuntime = { mode: SessionMaintenanceMode; pruneAfterMs: number; maxEntries: number; 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; onWarn?: (warning: SessionMaintenanceWarningRuntime) => void | Promise; onMaintenanceApplied?: (report: SessionMaintenanceApplyReportRuntime) => void | Promise; maintenanceOverride?: Partial; }; type SaveSessionStore = (storePath: string, store: Record, opts?: SaveSessionStoreOptions) => Promise; type RecordSessionMetaFromInbound$1 = (params: { storePath: string; sessionKey: string; ctx: MsgContext; groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; }) => Promise; type UpdateLastRoute$1 = (params: { storePath: string; sessionKey: string; channel?: SessionEntry["lastChannel"]; to?: string; accountId?: string; threadId?: string | number; route?: ChannelRouteRef; deliveryContext?: DeliveryContext; ctx?: MsgContext; groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; }) => Promise; //#endregion //#region src/plugins/runtime/native-deps.d.ts /** Inputs used to format native dependency install/rebuild guidance. */ type NativeDependencyHintParams = { packageName: string; manager?: "pnpm" | "npm" | "yarn"; rebuildCommand?: string; approveBuildsCommand?: string; downloadCommand?: string; }; /** Formats concise guidance for installing and rebuilding a native dependency. */ declare function formatNativeDependencyHint(params: NativeDependencyHintParams): string; //#endregion //#region src/image-generation/runtime-types.d.ts type GenerateImageParams = { cfg: OpenClawConfig; prompt: string; agentDir?: string; authStore?: AuthProfileStore; modelOverride?: string; count?: number; size?: string; aspectRatio?: string; resolution?: ImageGenerationResolution; 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 /** * Runtime input/output contracts for music generation. * * These are separate from provider contracts because runtime results include * fallback attempts, normalized metadata, and selected provider/model identity. */ /** Parameters accepted by the core music generation runtime. */ type GenerateMusicParams = { cfg: OpenClawConfig; prompt: string; agentDir?: string; authStore?: AuthProfileStore; modelOverride?: string; lyrics?: string; instrumental?: boolean; durationSeconds?: number; format?: MusicGenerationOutputFormat; inputImages?: MusicGenerationSourceImage[]; autoProviderFallback?: boolean; /** Optional per-request provider timeout in milliseconds. */ timeoutMs?: number; }; /** Result returned after a successful runtime provider attempt. */ type GenerateMusicRuntimeResult = { tracks: GeneratedMusicAsset[]; provider: string; model: string; attempts: FallbackAttempt[]; lyrics?: string[]; normalization?: MusicGenerationNormalization; metadata?: Record; ignoredOverrides: MusicGenerationIgnoredOverride[]; }; /** Parameters for listing music generation providers visible to runtime code. */ type ListRuntimeMusicGenerationProvidersParams = { config?: OpenClawConfig; }; /** Provider shape exposed by runtime listing APIs. */ type RuntimeMusicGenerationProvider = MusicGenerationProvider; //#endregion //#region src/plugins/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 /** Provider/tool resolution inputs for web_search. */ type ResolveWebSearchDefinitionParams = { config?: OpenClawConfig; agentDir?: string; sandboxed?: boolean; runtimeWebSearch?: RuntimeWebSearchMetadata; providerId?: string; preferRuntimeProviders?: boolean; preferInputConfig?: boolean; }; /** Inputs for executing a web_search request through the selected provider. */ type RunWebSearchParams = ResolveWebSearchDefinitionParams & { args: Record; signal?: AbortSignal; }; /** Normalized execution result that records which provider answered. */ type RunWebSearchResult = { provider: string; result: Record; }; /** List-provider query parameters. */ type ListWebSearchProvidersParams = { config?: OpenClawConfig; }; type RuntimeWebSearchProviderEntry = PluginWebSearchProviderEntry; //#endregion //#region src/sessions/transcript-events.d.ts /** Normalized transcript update emitted after a session transcript changes. */ type SessionTranscriptUpdate = { sessionFile: string; sessionKey?: string; agentId?: string; message?: unknown; messageId?: string; messageSeq?: number; }; type SessionTranscriptListener = (update: SessionTranscriptUpdate) => void; /** Registers a listener for normalized session transcript updates. */ declare function onSessionTranscriptUpdate(listener: SessionTranscriptListener): () => void; /** Emits a normalized transcript update to all registered listeners. */ declare function emitSessionTranscriptUpdate(update: string | SessionTranscriptUpdate): void; //#endregion //#region src/channels/message/ingress-queue.d.ts /** Pending or retryable inbound channel event stored in the durable ingress queue. */ type ChannelIngressQueueRecord = { id: string; channelId: string; accountId: string; queueName: string; payload: TPayload; metadata?: TMetadata; receivedAt: number; updatedAt: number; laneKey?: string; attempts: number; lastAttemptAt?: number; lastError?: string; }; /** Pending ingress event currently claimed by a worker. */ type ChannelIngressQueueClaim = ChannelIngressQueueRecord & { claim: { token: string; ownerId: string; claimedAt: number; }; }; /** Minimal claim reference used to guard completion/release/failure with a claim token. */ type ChannelIngressQueueClaimRef = { id: string; claim: { token: string; }; }; /** Completed ingress event tombstone retained for duplicate detection. */ type ChannelIngressQueueCompletedRecord = { id: string; channelId: string; accountId: string; queueName: string; completedAt: number; metadata?: TCompletedMetadata; }; /** Failed ingress event tombstone retained for duplicate detection and diagnostics. */ type ChannelIngressQueueFailedRecord = { id: string; channelId: string; accountId: string; queueName: string; failedAt: number; reason: string; message?: string; }; /** Retention options for pending, completed, and failed ingress queue rows. */ type ChannelIngressQueuePruneOptions = { pendingTtlMs?: number; completedTtlMs?: number; failedTtlMs?: number; pendingMaxEntries?: number; completedMaxEntries?: number; failedMaxEntries?: number; protectIds?: Iterable; now?: number; }; /** Result of enqueueing a possibly duplicate ingress event id. */ type ChannelIngressQueueEnqueueResult = { kind: "accepted"; duplicate: false; record: ChannelIngressQueueRecord; } | { kind: "pending"; duplicate: true; record: ChannelIngressQueueRecord; } | { kind: "claimed"; duplicate: true; record: ChannelIngressQueueClaim; } | { kind: "completed"; duplicate: true; record: ChannelIngressQueueCompletedRecord; } | { kind: "failed"; duplicate: true; record: ChannelIngressQueueFailedRecord; }; /** Durable FIFO-ish ingress queue with claims, duplicate detection, and retention pruning. */ type ChannelIngressQueue = { enqueue(id: string, payload: TPayload, options?: { metadata?: TMetadata; receivedAt?: number; laneKey?: string; }): Promise>; listPending(options?: { limit?: number | "all"; orderBy?: "received" | "id"; }): Promise>>; listClaims(): Promise>>; claimNext(options?: { ownerId?: string; blockedLaneKeys?: Iterable; staleMs?: number; }): Promise | null>; claim(id: string, options?: { ownerId?: string; }): Promise | null>; complete(idOrClaim: string | ChannelIngressQueueClaimRef, options?: { metadata?: TCompletedMetadata; completedAt?: number; }): Promise; release(idOrClaim: string | ChannelIngressQueueClaimRef, options?: { lastError?: string; releasedAt?: number; }): Promise; fail(idOrClaim: string | ChannelIngressQueueClaimRef, options: { reason: string; message?: string; failedAt?: number; }): Promise; delete(idOrClaim: string | ChannelIngressQueueRecord | ChannelIngressQueueClaimRef): Promise; recoverStaleClaims(options?: { staleMs?: number; now?: number; shouldRecover?: (claim: ChannelIngressQueueClaim) => boolean | Promise; }): Promise; prune(options?: ChannelIngressQueuePruneOptions): Promise; }; /** Construction options for a channel/account-scoped ingress queue. */ type CreateChannelIngressQueueOptions = { channelId: string; accountId?: string; stateDir?: string; now?: () => number; }; //#endregion //#region src/tasks/task-registry.types.d.ts /** Runtime family that owns a task run lifecycle. */ type TaskRuntime = "subagent" | "acp" | "cli" | "cron"; type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "timed_out" | "cancelled" | "lost"; type TaskDeliveryStatus = "pending" | "delivered" | "session_queued" | "failed" | "parent_missing" | "not_applicable"; type TaskNotifyPolicy = "done_only" | "state_changes" | "silent"; /** Semantic success detail for required-completion task outcomes. */ type TaskTerminalOutcome = "succeeded" | "blocked"; type TaskScopeKind = "session" | "system"; type TaskStatusCounts = Record; type TaskRuntimeCounts = Record; type TaskRegistrySummary = { total: number; active: number; terminal: number; failures: number; byStatus: TaskStatusCounts; byRuntime: TaskRuntimeCounts; }; type TaskDeliveryState = { taskId: string; requesterOrigin?: DeliveryContext; lastNotifiedEventAt?: number; }; type TaskRecord = { taskId: string; runtime: TaskRuntime; taskKind?: string; sourceId?: string; requesterSessionKey: string; ownerKey: string; scopeKind: TaskScopeKind; childSessionKey?: string; parentFlowId?: string; parentTaskId?: string; agentId?: string; runId?: string; label?: string; task: string; status: TaskStatus; deliveryStatus: TaskDeliveryStatus; notifyPolicy: TaskNotifyPolicy; createdAt: number; startedAt?: number; endedAt?: number; lastEventAt?: number; cleanupAfter?: number; error?: string; progressSummary?: string; terminalSummary?: string; terminalOutcome?: TaskTerminalOutcome; }; //#endregion //#region src/tasks/task-flow-registry.types.d.ts /** JSON value shape persisted with task-flow state and wait metadata. */ type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue; }; type TaskFlowSyncMode = "task_mirrored" | "managed"; /** Lifecycle status for multi-step task flows. */ type TaskFlowStatus = "queued" | "running" | "waiting" | "blocked" | "succeeded" | "failed" | "cancelled" | "lost"; type TaskFlowRecord = { flowId: string; syncMode: TaskFlowSyncMode; ownerKey: string; requesterOrigin?: DeliveryContext; controllerId?: string; revision: number; status: TaskFlowStatus; notifyPolicy: TaskNotifyPolicy; goal: string; currentStep?: string; blockedTaskId?: string; blockedSummary?: string; stateJson?: JsonValue; waitJson?: JsonValue; cancelRequestedAt?: number; createdAt: number; updatedAt: number; endedAt?: number; }; //#endregion //#region src/agents/tool-fs-policy.types.d.ts /** Filesystem policy for agent tools that can touch local paths. */ type ToolFsPolicy = { workspaceOnly: boolean; }; //#endregion //#region src/plugins/tool-types.d.ts type OpenClawPluginActiveModelContext = { provider?: string; modelId?: string; modelRef?: string; }; /** Trusted execution context passed to plugin-owned agent tool factories. */ type OpenClawPluginToolContext = { config?: OpenClawConfig; /** Active runtime-resolved config snapshot when one is available. */ runtimeConfig?: OpenClawConfig; /** Returns the latest runtime-resolved config snapshot for long-lived tool definitions. */ getRuntimeConfig?: () => OpenClawConfig | undefined; /** Effective filesystem policy for the active tool run. */ fsPolicy?: ToolFsPolicy; workspaceDir?: string; agentDir?: string; agentId?: string; sessionKey?: string; /** Ephemeral session UUID - regenerated on /new and /reset. Use for per-conversation isolation. */ sessionId?: string; /** * Runtime-supplied active model metadata for informational use, diagnostics, * and plugin-owned policy decisions. This is not a security boundary against * the local operator, installed plugin code, or a modified OpenClaw runtime. */ activeModel?: OpenClawPluginActiveModelContext; browser?: { sandboxBridgeUrl?: string; allowHostControl?: boolean; }; messageChannel?: string; agentAccountId?: string; /** Trusted provider auth availability from the active auth profile store. */ hasAuthForProvider?: (providerId: string) => boolean; /** Resolves an API key from the active auth profile store when available. */ resolveApiKeyForProvider?: (providerId: string) => Promise; /** Trusted ambient delivery route for the active agent/session. */ deliveryContext?: DeliveryContext; /** Trusted sender id from inbound context (runtime-provided, not tool args). */ requesterSenderId?: string; 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" | "persist_failed"; type ManagedTaskFlowMutationResult = { applied: true; flow: ManagedTaskFlowRecord; } | { applied: false; code: ManagedTaskFlowMutationErrorCode; current?: TaskFlowRecord; }; type ManagedTaskFlowCreateParams = { controllerId: string; goal: string; status?: ManagedTaskFlowRecord["status"]; notifyPolicy?: TaskNotifyPolicy; currentStep?: string | null; stateJson?: JsonValue | null; waitJson?: JsonValue | null; cancelRequestedAt?: number | null; createdAt?: number; updatedAt?: number; endedAt?: number | null; }; type BoundTaskFlowTaskRunResult = { created: true; flow: ManagedTaskFlowRecord; task: TaskRecord; } | { created: false; reason: string; found: boolean; flow?: TaskFlowRecord; }; type BoundTaskFlowCancelResult = { found: boolean; cancelled: boolean; reason?: string; flow?: TaskFlowRecord; tasks?: TaskRecord[]; }; type BoundTaskFlowRuntime = { readonly sessionKey: string; readonly requesterOrigin?: TaskDeliveryState["requesterOrigin"]; createManaged: (params: ManagedTaskFlowCreateParams) => ManagedTaskFlowRecord; tryCreateManaged: (params: ManagedTaskFlowCreateParams) => ManagedTaskFlowRecord | null; get: (flowId: string) => TaskFlowRecord | undefined; list: () => TaskFlowRecord[]; findLatest: () => TaskFlowRecord | undefined; resolve: (token: string) => TaskFlowRecord | undefined; getTaskSummary: (flowId: string) => TaskRegistrySummary | undefined; setWaiting: (params: { flowId: string; expectedRevision: number; currentStep?: string | null; stateJson?: JsonValue | null; waitJson?: JsonValue | null; blockedTaskId?: string | null; blockedSummary?: string | null; updatedAt?: number; }) => ManagedTaskFlowMutationResult; resume: (params: { flowId: string; expectedRevision: number; status?: Extract; currentStep?: string | null; stateJson?: JsonValue | null; updatedAt?: number; }) => ManagedTaskFlowMutationResult; finish: (params: { flowId: string; expectedRevision: number; stateJson?: JsonValue | null; updatedAt?: number; endedAt?: number; }) => ManagedTaskFlowMutationResult; fail: (params: { flowId: string; expectedRevision: number; stateJson?: JsonValue | null; blockedTaskId?: string | null; blockedSummary?: string | null; updatedAt?: number; endedAt?: number; }) => ManagedTaskFlowMutationResult; requestCancel: (params: { flowId: string; expectedRevision: number; cancelRequestedAt?: number; }) => ManagedTaskFlowMutationResult; cancel: (params: { flowId: string; cfg: OpenClawConfig; }) => Promise; runTask: (params: { flowId: string; runtime: TaskRuntime; sourceId?: string; childSessionKey?: string; parentTaskId?: string; agentId?: string; runId?: string; label?: string; task: string; preferMetadata?: boolean; notifyPolicy?: TaskNotifyPolicy; deliveryStatus?: TaskDeliveryStatus; status?: "queued" | "running"; startedAt?: number; lastEventAt?: number; progressSummary?: string | null; }) => BoundTaskFlowTaskRunResult; }; type PluginRuntimeTaskFlow = { bindSession: (params: { sessionKey: string; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; }) => BoundTaskFlowRuntime; fromToolContext: (ctx: Pick) => BoundTaskFlowRuntime; }; //#endregion //#region src/plugins/runtime/model-auth-types.d.ts /** * Runtime-ready auth result exposed to native plugins and context engines. * * `source`, `mode`, and `profileId` describe how the original credential was * resolved. `apiKey` is the request-ready credential after any provider-owned * runtime exchange, so it may differ from the stored/raw credential. */ type ResolvedProviderRuntimeAuth = Omit & { apiKey?: string; baseUrl?: string; request?: ModelProviderRequestTransportOverrides$1; expiresAt?: number; }; //#endregion //#region src/tts/provider-types.d.ts /** Canonical speech provider identifier after provider registry normalization. */ type SpeechProviderId = string; /** Output context requested from a speech provider. */ type SpeechSynthesisTarget = "audio-file" | "voice-note" | "telephony"; /** Provider-owned normalized config map. */ type SpeechProviderConfig = Record; /** Provider-owned per-request directive/persona overrides. */ type SpeechProviderOverrides = Record; /** Policy controlling which [[tts:*]] directive fields can affect synthesis. */ type SpeechModelOverridePolicy = { enabled: boolean; allowText: boolean; allowProvider: boolean; allowVoice: boolean; allowModelId: boolean; allowVoiceSettings: boolean; allowNormalization: boolean; allowSeed: boolean; }; /** Parsed directive overrides grouped by provider. */ type TtsDirectiveOverrides = { ttsText?: string; provider?: SpeechProviderId; providerOverrides?: Record; }; /** Result of parsing TTS directives from message text. */ type TtsDirectiveParseResult = { cleanedText: string; ttsText?: string; hasDirective: boolean; overrides: TtsDirectiveOverrides; warnings: string[]; }; /** Context for checking whether a provider has enough config to synthesize. */ type SpeechProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: SpeechProviderConfig; timeoutMs: number; }; /** Request for buffered speech synthesis. */ type SpeechSynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; target: SpeechSynthesisTarget; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; /** Buffered speech synthesis result plus file/voice-note compatibility metadata. */ type SpeechSynthesisResult = { audioBuffer: Buffer; outputFormat: string; fileExtension: string; voiceCompatible: boolean; }; type SpeechSynthesisStreamRequest = SpeechSynthesisRequest; /** Streaming speech synthesis result; release frees provider transport resources. */ type SpeechSynthesisStreamResult = { audioStream: ReadableStream; outputFormat: string; fileExtension: string; voiceCompatible: boolean; release?: () => Promise; }; /** Telephony synthesis request for provider output that needs a fixed sample rate. */ type SpeechTelephonySynthesisRequest = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; timeoutMs: number; }; /** Telephony synthesis result with sample-rate metadata for call transports. */ type SpeechTelephonySynthesisResult = { audioBuffer: Buffer; outputFormat: string; sampleRate: number; }; /** Provider hook input for applying persona/config before synthesis. */ type SpeechProviderPrepareSynthesisContext = { text: string; cfg: OpenClawConfig; providerConfig: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; persona?: ResolvedTtsPersona; personaProviderConfig?: SpeechProviderConfig; target: SpeechSynthesisTarget; timeoutMs: number; }; /** Optional provider-prepared synthesis overrides. */ type SpeechProviderPreparedSynthesis = { text?: string; providerConfig?: SpeechProviderConfig; providerOverrides?: SpeechProviderOverrides; }; /** Voice metadata returned by provider list-voices hooks. */ type SpeechVoiceOption = { id: string; name?: string; category?: string; description?: string; locale?: string; gender?: string; personalities?: string[]; }; /** Provider voice-listing request with optional direct auth/URL overrides. */ type SpeechListVoicesRequest = { cfg?: OpenClawConfig; providerConfig?: SpeechProviderConfig; apiKey?: string; baseUrl?: string; }; /** Provider hook input for resolving normalized config from raw OpenClaw config. */ type SpeechProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: Record; timeoutMs: number; }; /** One parsed directive key/value plus current provider override state. */ type SpeechDirectiveTokenParseContext = { key: string; value: string; policy: SpeechModelOverridePolicy; selectedProvider?: SpeechProviderId; providerConfig?: SpeechProviderConfig; currentOverrides?: SpeechProviderOverrides; }; /** Provider directive parser result. */ type SpeechDirectiveTokenParseResult = { handled: boolean; overrides?: SpeechProviderOverrides; warnings?: string[]; }; /** Provider hook input for resolving talk-command speech config. */ type SpeechProviderResolveTalkConfigContext = { cfg: OpenClawConfig; baseTtsConfig: Record; talkProviderConfig: TalkProviderConfig; timeoutMs: number; }; /** Provider hook input for per-call talk-command overrides. */ type SpeechProviderResolveTalkOverridesContext = { talkProviderConfig: TalkProviderConfig; params: Record; }; //#endregion //#region src/tts/tts-auto-mode.d.ts /** Accepted TTS auto modes from config, prefs, and session-level overrides. */ declare const TTS_AUTO_MODES: Set; /** Normalize an unknown value into a supported TTS auto mode. */ declare function normalizeTtsAutoMode(value: unknown): TtsAutoMode | undefined; //#endregion //#region src/tts/tts-config.d.ts /** Routing context used to layer global, agent, channel, and account TTS config. */ type TtsConfigResolutionContext = { agentId?: string; channelId?: string; accountId?: string; }; /** Resolve effective TTS config after applying global, agent, channel, and account layers. */ declare function resolveEffectiveTtsConfig(cfg: OpenClawConfig, contextOrAgentId?: string | TtsConfigResolutionContext): TtsConfig; //#endregion //#region src/tts/tts-types.d.ts /** Resolved directive override policy after config defaults are applied. */ type ResolvedTtsModelOverrides = SpeechModelOverridePolicy; /** Fully resolved TTS runtime config consumed by synthesis and status paths. */ type ResolvedTtsConfig = { auto: TtsAutoMode; mode: TtsMode; provider: TtsProvider; providerSource: "config" | "default"; persona?: string; personas: Record; summaryModel?: string; modelOverrides: ResolvedTtsModelOverrides; providerConfigs: Record; prefsPath?: string; maxTextLength: number; timeoutMs: number; timeoutMsSource?: "config" | "default"; rawConfig?: TtsConfig; sourceConfig?: OpenClawConfig; }; //#endregion //#region src/plugin-sdk/tts-runtime.types.d.ts /** Stable reason codes for one provider attempt in a TTS fallback chain. */ type TtsAttemptReasonCode = "success" | "no_provider_registered" | "not_configured" | "unsupported_for_streaming" | "unsupported_for_telephony" | "timeout" | "provider_error"; /** Per-provider attempt record used in TTS status, logs, and result metadata. */ type TtsProviderAttempt = { provider: string; outcome: "success" | "skipped" | "failed"; reasonCode: TtsAttemptReasonCode; persona?: string; personaBinding?: "applied" | "missing" | "none"; latencyMs?: number; error?: string; }; /** Delivery target requested for synthesized speech output. */ type TtsSpeechTarget = "audio-file" | "voice-note"; /** Standard text-to-speech request for file or stream synthesis. */ type TtsRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; channel?: string; overrides?: TtsDirectiveOverrides; disableFallback?: boolean; timeoutMs?: number; agentId?: string; accountId?: string; }; /** Telephony-specific synthesis request where output format is constrained by the caller. */ type TtsTelephonyRequestParams = { text: string; cfg: OpenClawConfig; prefsPath?: string; overrides?: TtsDirectiveOverrides; }; /** Inputs for listing voices from a speech provider with optional resolved config. */ type ListSpeechVoicesParams = { provider: string; cfg?: OpenClawConfig; config?: ResolvedTtsConfig; apiKey?: string; baseUrl?: string; }; /** File-backed text-to-speech result returned by high-level runtime helpers. */ type TtsResult = { success: boolean; audioPath?: string; error?: string; latencyMs?: number; provider?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; voiceCompatible?: boolean; audioAsVoice?: boolean; target?: TtsSpeechTarget; }; /** Stream-backed synthesis result with optional release hook for provider resources. */ type TtsStreamResult = { success: boolean; audioStream?: ReadableStream; error?: string; latencyMs?: number; provider?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; voiceCompatible?: boolean; fileExtension?: string; target?: TtsSpeechTarget; release?: () => Promise; }; /** Telephony synthesis result with provider voice/model and sample-rate metadata. */ type TtsTelephonyResult = { success: boolean; audioBuffer?: Buffer; error?: string; latencyMs?: number; provider?: string; providerModel?: string; providerVoice?: string; persona?: string; fallbackFrom?: string; attemptedProviders?: string[]; attempts?: TtsProviderAttempt[]; outputFormat?: string; sampleRate?: number; }; /** High-level function contract for file-backed text-to-speech synthesis. */ type TextToSpeech = (params: TtsRequestParams) => Promise; /** High-level function contract for streaming text-to-speech synthesis. */ type TextToSpeechStream = (params: TtsRequestParams) => Promise; /** High-level function contract for telephony-safe text-to-speech synthesis. */ type TextToSpeechTelephony = (params: TtsTelephonyRequestParams) => Promise; /** Function contract for provider voice discovery. */ type ListSpeechVoices = (params: ListSpeechVoicesParams) => Promise; //#endregion //#region src/plugins/runtime/task-domain-types.d.ts /** Aggregate task-run counts exposed to plugin task views. */ type TaskRunAggregateSummary = { total: number; active: number; terminal: number; failures: number; byStatus: TaskStatusCounts; byRuntime: TaskRuntimeCounts; }; /** Public task run summary exposed through plugin runtime task APIs. */ type TaskRunView = { id: string; runtime: TaskRuntime; sourceId?: string; sessionKey: string; ownerKey: string; scope: TaskScopeKind; childSessionKey?: string; flowId?: string; parentTaskId?: string; agentId?: string; runId?: string; label?: string; title: string; status: TaskStatus; deliveryStatus: TaskDeliveryStatus; notifyPolicy: TaskNotifyPolicy; createdAt: number; startedAt?: number; endedAt?: number; lastEventAt?: number; cleanupAfter?: number; error?: string; progressSummary?: string; terminalSummary?: string; terminalOutcome?: TaskTerminalOutcome; }; /** Detailed task run view; currently equal to the summary view. */ type TaskRunDetail = TaskRunView; /** Result returned when cancelling a task run. */ type TaskRunCancelResult = { found: boolean; cancelled: boolean; reason?: string; task?: TaskRunDetail; }; /** Public task flow summary exposed through plugin runtime task APIs. */ type TaskFlowView = { id: string; ownerKey: string; requesterOrigin?: DeliveryContext; status: TaskFlowStatus; notifyPolicy: TaskNotifyPolicy; goal: string; currentStep?: string; cancelRequestedAt?: number; createdAt: number; updatedAt: number; endedAt?: number; }; /** Detailed task flow view with state, wait, blocked, and task summary data. */ type TaskFlowDetail = TaskFlowView & { state?: JsonValue; wait?: JsonValue; blocked?: { taskId?: string; summary?: string; }; tasks: TaskRunView[]; taskSummary: TaskRunAggregateSummary; }; //#endregion //#region src/tasks/detached-task-runtime-contract.d.ts type DetachedTaskCreateParams = { runtime: TaskRuntime; taskKind?: string; sourceId?: string; requesterSessionKey?: string; ownerKey?: string; scopeKind?: TaskScopeKind; requesterOrigin?: TaskDeliveryState["requesterOrigin"]; parentFlowId?: string; childSessionKey?: string; parentTaskId?: string; agentId?: string; 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 | null; createRunningTaskRun: (params: DetachedRunningTaskCreateParams) => TaskRecord | null; startTaskRunByRunId: (params: DetachedTaskStartParams) => TaskRecord[]; recordTaskRunProgressByRunId: (params: DetachedTaskProgressParams) => TaskRecord[]; finalizeTaskRunByRunId?: (params: DetachedTaskFinalizeParams) => TaskRecord[]; completeTaskRunByRunId: (params: DetachedTaskCompleteParams) => TaskRecord[]; failTaskRunByRunId: (params: DetachedTaskFailParams) => TaskRecord[]; setDetachedTaskDeliveryStatusByRunId: (params: DetachedTaskDeliveryStatusParams) => TaskRecord[]; /** * 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; openChannelIngressQueue: (options?: Omit) => ChannelIngressQueue; }; tasks: { runs: PluginRuntimeTaskRuns; flows: PluginRuntimeTaskFlows; managedFlows: PluginRuntimeTaskFlow; /** @deprecated Use runtime.tasks.flows for DTO-based TaskFlow access. */ flow: PluginRuntimeTaskFlow; }; /** @deprecated Use runtime.tasks.flows for DTO-based TaskFlow access. */ taskFlow: PluginRuntimeTaskFlow; llm: { complete: (params: LlmCompleteParams) => Promise; }; modelAuth: { /** Resolve auth for a model. Only provider/model, optional cfg, and workspaceDir are used. */getApiKeyForModel: (params: { model: import("openclaw/plugin-sdk/llm").Model; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; /** Resolve request-ready auth for a model, including provider runtime exchanges. */ getRuntimeAuthForModel: (params: { model: import("openclaw/plugin-sdk/llm").Model; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; /** Resolve auth for a provider by name. Only provider, optional cfg, and workspaceDir are used. */ resolveApiKeyForProvider: (params: { provider: string; cfg?: OpenClawConfig; workspaceDir?: string; }) => Promise; }; }; //#endregion //#region src/context-engine/types.d.ts type AssembleResult = { /** Ordered messages to use as model context */messages: AgentMessage[]; /** Estimated total tokens in assembled context */ estimatedTokens: number; /** * Controls which token estimate the runner treats as authoritative for * preemptive overflow prechecks. The returned `messages` are always the * prompt sent to the model; this only affects the precheck's token comparison. * * - "assembled": the 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; /** Selected agent harness id when compaction delegates back to the runtime. */ agentHarnessId?: string; /** Best-effort current prompt/context token estimate for this turn. */ currentTokenCount?: number; /** Optional prompt-cache telemetry for cache-aware engines. */ promptCache?: ContextEnginePromptCacheInfo; /** * Safe transcript rewrite helper implemented by the runtime. * * Engines decide what is safe to rewrite; the runtime owns how the session * DAG is updated on disk. */ rewriteTranscriptEntries?: (request: TranscriptRewriteRequest) => Promise; /** LLM completion capability for engines that need model inference. */ llm?: { complete: (params: LlmCompleteParams) => Promise; }; }; /** * ContextEngine defines the pluggable contract for context management. * * Required methods define a generic lifecycle; optional methods allow engines * to provide additional capabilities (retrieval, lineage, etc.). */ interface ContextEngine { /** Engine identifier and metadata */ readonly info: ContextEngineInfo; /** * Initialize engine state for a session, optionally importing historical context. */ bootstrap?(params: { sessionId: string; sessionKey?: string; sessionFile: string; }): 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/agents/agent-runtime-id.d.ts /** Agent runtime id normalization and retired runtime-selection compatibility helpers. */ type EmbeddedAgentRuntime = "openclaw" | "auto" | (string & {}); /** * @deprecated Whole-agent runtime environment selection is retired. Use * provider/model runtime policy or a registered agent harness instead. */ declare function resolveEmbeddedAgentRuntime(_env?: NodeJS.ProcessEnv): EmbeddedAgentRuntime; //#endregion //#region src/tasks/agent-harness-task-runtime-scope.d.ts type AgentHarnessTaskRuntimeScope = { readonly requesterSessionKey: string; readonly requesterOrigin?: DeliveryContext; }; //#endregion //#region src/agents/agent-tools.before-tool-call.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; }>; }; /** Return whether before_tool_call hooks or trusted policies are active. */ declare function getBeforeToolCallPolicyDiagnosticState(): BeforeToolCallPolicyDiagnosticState; /** Return true when any before_tool_call policy could affect tool execution. */ declare function hasBeforeToolCallPolicy(): boolean; /** Resolve a deferred plugin approval request at the later execution boundary. */ declare function requestDeferredPluginToolApproval(params: { deferredApproval: DeferredPluginToolApproval; signal?: AbortSignal; }): Promise; /** Run the full before_tool_call policy chain for a pending tool call. */ declare function runBeforeToolCallHook(args: { toolName: string; params: unknown; toolKind?: PluginHookToolKind; toolInputKind?: PluginHookToolInputKind; toolCallId?: string; ctx?: HookContext; signal?: AbortSignal; approvalMode?: "request" | "report" | "defer"; }): Promise; /** Wrap a tool execute function with before_tool_call hooks and diagnostics. */ declare function wrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext, options?: { approvalMode?: "request" | "report"; emitDiagnostics?: boolean; }): AnyAgentTool; /** Return true when a tool already carries the before_tool_call wrapper marker. */ declare function isToolWrappedWithBeforeToolCallHook(tool: AnyAgentTool): boolean; /** Toggle diagnostic event emission on an existing before_tool_call wrapper. */ declare function setBeforeToolCallDiagnosticsEnabled(tool: AnyAgentTool, enabled: boolean): void; //#endregion //#region src/agents/runtime-plan/types.d.ts /** Runtime transport selected for one model attempt. */ type AgentRuntimeTransport = "sse" | "websocket" | "auto"; /** Thinking levels accepted by runtime-plan extra-param preparation. */ type AgentRuntimeThinkLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max"; /** System prompt rendering mode selected for one attempt. */ type AgentRuntimePromptMode = "full" | "minimal" | "none"; /** Trigger source that can alter provider system prompt contributions. */ type AgentRuntimePromptTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; /** Normalized failure reason used by model fallback classification. */ type AgentRuntimeFailoverReason = "auth" | "auth_permanent" | "format" | "rate_limit" | "overloaded" | "billing" | "server_error" | "timeout" | "model_not_found" | "session_expired" | "empty_response" | "no_error_details" | "unclassified" | "unknown"; /** Provider/runtime config object passed through plugin boundaries. */ type AgentRuntimeConfig = unknown; /** Provider model descriptor consumed by runtime-plan hooks. */ type AgentRuntimeModel = { id?: string; name?: string; api?: string; provider?: string; baseUrl?: string; reasoning?: boolean; input?: readonly string[]; cost?: { input: number; output: number; cacheRead: number; cacheWrite: number; }; contextWindow?: number; maxTokens?: number; contextTokens?: number; compat?: unknown; }; /** Text replacement rule used by provider input/output transforms. */ type AgentRuntimeTextReplacement = { from: string | RegExp; to: string; }; /** Provider text transforms applied around model calls. */ type AgentRuntimeTextTransforms = { input?: AgentRuntimeTextReplacement[]; output?: AgentRuntimeTextReplacement[]; }; /** Resolved provider runtime handle forwarded to plugin-owned hooks. */ type AgentRuntimeProviderHandle = { provider: string; config?: AgentRuntimeConfig; workspaceDir?: string; env?: NodeJS.ProcessEnv; applyAutoEnable?: boolean; bundledProviderVitestCompat?: boolean; }; type AgentRuntimeInteractiveButtonStyle = "primary" | "secondary" | "success" | "danger"; type AgentRuntimeMessagePresentationAction = { type: "command"; command: string; } | { type: "callback"; value: string; }; /** Portable action control exposed to agent runtime reply payloads. */ type AgentRuntimeMessagePresentationButton = { /** User-visible button label. */label: string; /** Typed action sent when pressed. */ action?: AgentRuntimeMessagePresentationAction; /** Legacy opaque callback value sent when pressed. */ value?: string; /** External URL opened by the button. */ url?: string; /** Channel-native web app URL for renderers that support embedded web apps. */ webApp?: { url: string; }; /** Higher values are kept first when channel action limits require dropping controls. */ priority?: number; /** Disabled action hint; channels without disabled-state support render fallback text. */ disabled?: boolean; /** Optional visual style hint for renderers that support styled actions. */ style?: AgentRuntimeInteractiveButtonStyle; }; /** Portable select/menu option exposed to agent runtime reply payloads. */ type AgentRuntimeMessagePresentationOption = { /** User-visible option label. */label: string; /** Typed action sent when selected. */ action?: AgentRuntimeMessagePresentationAction; /** Legacy opaque callback value sent when selected. */ value?: string; }; /** * @deprecated Use AgentRuntimeMessagePresentationButton. */ type AgentRuntimeInteractiveReplyButton = AgentRuntimeMessagePresentationButton; /** * @deprecated Use AgentRuntimeMessagePresentationOption. */ type AgentRuntimeInteractiveReplyOption = AgentRuntimeMessagePresentationOption; /** * @deprecated Use AgentRuntimeMessagePresentationBlock. */ type AgentRuntimeInteractiveReplyBlock = { type: "text"; text: string; } | { type: "buttons"; buttons: AgentRuntimeInteractiveReplyButton[]; } | { type: "select"; placeholder?: string; options: AgentRuntimeInteractiveReplyOption[]; }; /** * @deprecated Use AgentRuntimeMessagePresentation. */ type AgentRuntimeInteractiveReply = { blocks: AgentRuntimeInteractiveReplyBlock[]; }; /** Portable reply presentation severity/style hint. */ type AgentRuntimeMessagePresentationTone = "info" | "success" | "warning" | "danger" | "neutral"; /** Portable structured reply block rendered or downgraded by channels. */ type AgentRuntimeMessagePresentationBlock = { type: "text"; text: string; } | { type: "context"; text: string; } | { type: "divider"; } | { type: "buttons"; buttons: AgentRuntimeMessagePresentationButton[]; } | { type: "select"; placeholder?: string; options: AgentRuntimeMessagePresentationOption[]; }; /** Portable structured reply presentation for channel adapters. */ type AgentRuntimeMessagePresentation = { /** Optional short heading rendered before blocks when supported. */title?: string; /** Optional severity/status tone for renderers that support toned presentations. */ tone?: AgentRuntimeMessagePresentationTone; /** Ordered portable blocks rendered or downgraded by channel adapters. */ blocks: AgentRuntimeMessagePresentationBlock[]; }; /** Delivery pin options attached to runtime reply payloads. */ type AgentRuntimeReplyPayloadDeliveryPin = { enabled: boolean; notify?: boolean; required?: boolean; }; /** Delivery instructions attached to runtime reply payloads. */ type AgentRuntimeReplyPayloadDelivery = { pin?: boolean | AgentRuntimeReplyPayloadDeliveryPin; }; /** Portable reply payload emitted by agent runtimes before channel rendering. */ type AgentRuntimeReplyPayload = { text?: string; mediaUrl?: string; mediaUrls?: string[]; trustedLocalMedia?: boolean; sensitiveMedia?: boolean; presentation?: AgentRuntimeMessagePresentation; delivery?: AgentRuntimeReplyPayloadDelivery; /** * @deprecated Use presentation. */ interactive?: AgentRuntimeInteractiveReply; btw?: { question: string; }; replyToId?: string; replyToTag?: boolean; replyToCurrent?: boolean; audioAsVoice?: boolean; spokenText?: string; ttsSupplement?: { spokenText: string; visibleTextAlreadyDelivered?: boolean; }; isError?: boolean; isReasoning?: boolean; isReasoningSnapshot?: boolean; isCompactionNotice?: boolean; isFallbackNotice?: boolean; isStatusNotice?: boolean; channelData?: Record; }; /** Stable section IDs for provider system prompt overrides. */ type AgentRuntimeSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias"; /** Provider-owned system prompt contribution and section overrides. */ type AgentRuntimeSystemPromptContribution = { stablePrefix?: string; dynamicSuffix?: string; sectionOverrides?: Partial>; }; /** Context passed when resolving provider system prompt contributions. */ type AgentRuntimeSystemPromptContributionContext = { config?: AgentRuntimeConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; promptMode: AgentRuntimePromptMode; runtimeChannel?: string; runtimeCapabilities?: string[]; agentId?: string; trigger?: AgentRuntimePromptTrigger; }; /** Provider fallback route decision for follow-up delivery. */ type AgentRuntimeFollowupFallbackRouteResult = { route?: "origin" | "dispatcher" | "drop"; reason?: string; }; /** Tool-call id sanitizer mode for provider transcript policy. */ type AgentRuntimeToolCallIdMode = "strict" | "strict9"; /** Provider transcript sanitation, repair, and validation policy. */ type AgentRuntimeTranscriptPolicy = { sanitizeMode: "full" | "images-only"; sanitizeToolCallIds: boolean; toolCallIdMode?: AgentRuntimeToolCallIdMode; preserveNativeAnthropicToolUseIds: boolean; repairToolUseResultPairing: boolean; preserveSignatures: boolean; sanitizeThoughtSignatures?: { allowBase64Only?: boolean; includeCamelCase?: boolean; }; sanitizeThinkingSignatures: boolean; dropThinkingBlocks: boolean; dropReasoningFromHistory?: boolean; applyGoogleTurnOrdering: boolean; validateGeminiTurns: boolean; validateAnthropicTurns: boolean; allowSyntheticToolResults: boolean; }; /** Classified model-call failure or success observation for fallback. */ type AgentRuntimeOutcomeClassification = { message: string; reason?: AgentRuntimeFailoverReason; status?: number; code?: string; rawError?: string; } | { error: unknown; } | null | undefined; /** Runtime hook that classifies run results for model fallback. */ type AgentRuntimeOutcomeClassifier = (params: { provider: string; model: string; result: unknown; hasDirectlySentBlockReply?: boolean; hasBlockReplyPipelineOutput?: boolean; }) => AgentRuntimeOutcomeClassification; /** Resolved provider/model/harness/transport reference for an attempt. */ type AgentRuntimeResolvedRef = { provider: string; modelId: string; modelApi?: string; harnessId?: string; transport?: AgentRuntimeTransport; }; /** Auth forwarding decision for one runtime attempt. */ type AgentRuntimeAuthPlan = { providerForAuth: string; authProfileProviderForAuth: string; harnessAuthProvider?: string; forwardedAuthProfileId?: string; forwardedAuthProfileCandidateIds?: string[]; }; /** Prompt transforms and provider contribution hooks for one runtime attempt. */ type AgentRuntimePromptPlan = { provider: string; modelId: string; textTransforms?: AgentRuntimeTextTransforms; resolveSystemPromptContribution(context: AgentRuntimeSystemPromptContributionContext): AgentRuntimeSystemPromptContribution | undefined; transformSystemPrompt(context: AgentRuntimeSystemPromptContributionContext & { systemPrompt: string; }): string; }; /** Prepared plugin metadata snapshot kept opaque to runtime-plan consumers. */ type AgentRuntimePreparedMetadataSnapshot = object; /** Prepared metadata loader used by tool planning without eager manifest reads. */ type PreparedOpenClawToolPlanning = { metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot; loadMetadataSnapshot?: () => AgentRuntimePreparedMetadataSnapshot; }; /** Tool normalization and diagnostics hooks for one runtime attempt. */ type AgentRuntimeToolPlan = { preparedPlanning?: PreparedOpenClawToolPlanning; normalize(tools: AgentTool[], params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): AgentTool[]; logDiagnostics(tools: AgentTool[], params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): void; }; /** Delivery behavior hooks for one runtime attempt. */ type AgentRuntimeDeliveryPlan = { isSilentPayload(payload: Pick): boolean; resolveFollowupRoute(params: { payload: AgentRuntimeReplyPayload; originatingChannel?: string; originatingTo?: string; originRoutable: boolean; dispatcherAvailable: boolean; }): AgentRuntimeFollowupFallbackRouteResult | undefined; }; /** Outcome classification hooks for one runtime attempt. */ type AgentRuntimeOutcomePlan = { classifyRunResult: AgentRuntimeOutcomeClassifier; }; /** Extra transport parameter plan for one runtime attempt. */ type AgentRuntimeTransportPlan = { extraParams: Record; resolveExtraParams(params?: { extraParamsOverride?: Record; thinkingLevel?: AgentRuntimeThinkLevel; agentId?: string; workspaceDir?: string; model?: AgentRuntimeModel; resolvedTransport?: AgentRuntimeTransport; }): Record; }; /** Complete prepared runtime plan consumed by embedded-agent attempts. */ type AgentRuntimePlan = { resolvedRef: AgentRuntimeResolvedRef; providerRuntimeHandle?: AgentRuntimeProviderHandle; auth: AgentRuntimeAuthPlan; prompt: AgentRuntimePromptPlan; tools: AgentRuntimeToolPlan; transcript: { policy: AgentRuntimeTranscriptPolicy; resolvePolicy(params?: { workspaceDir?: string; modelApi?: string; model?: AgentRuntimeModel; }): AgentRuntimeTranscriptPolicy; }; delivery: AgentRuntimeDeliveryPlan; outcome: AgentRuntimeOutcomePlan; transport: AgentRuntimeTransportPlan; observability: { resolvedRef: string; provider: string; modelId: string; modelApi?: string; harnessId?: string; authProfileId?: string; transport?: AgentRuntimeTransport; }; }; /** Inputs needed to build the full prepared runtime plan. */ type BuildAgentRuntimePlanParams = { config?: AgentRuntimeConfig; workspaceDir?: string; agentDir?: string; provider: string; modelId: string; model?: AgentRuntimeModel; modelApi?: string | null; harnessId?: string; harnessRuntime?: string; allowHarnessAuthProfileForwarding?: boolean; authProfileProvider?: string; authProfileMode?: string; sessionAuthProfileId?: string; sessionAuthProfileCandidateIds?: string[]; agentId?: string; thinkingLevel?: AgentRuntimeThinkLevel; extraParamsOverride?: Record; resolvedTransport?: AgentRuntimeTransport; providerRuntimeHandle?: AgentRuntimeProviderHandle; }; //#endregion //#region src/agents/tool-mutation.d.ts type FileTarget = { path?: string; oldpath?: string; }; //#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 /** Provider/SDK usage payload variants accepted by usage normalization. */ 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; }; }; /** Normalized token counts used by runtime accounting. */ type NormalizedUsage = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; reasoningTokens?: number; total?: number; }; /** Normalize provider-specific token usage fields into OpenClaw usage buckets. */ declare function normalizeUsage(raw?: UsageLike | null): NormalizedUsage | undefined; //#endregion //#region src/agents/embedded-agent-runner/replay-state.d.ts /** * Tracks whether an embedded run can be replayed after compaction or retry. */ type EmbeddedRunReplayState = { replayInvalid: boolean; hadPotentialSideEffects: boolean; }; /** Serializable replay metadata stored with run results. */ type EmbeddedRunReplayMetadata = { hadPotentialSideEffects: boolean; replaySafe: boolean; }; //#endregion //#region src/agents/embedded-agent-runner/run/preemptive-compaction.types.d.ts /** * Route chosen before a model call when context pressure may require compaction or truncation. */ type PreemptiveCompactionRoute = "fits" | "compact_only" | "truncate_tool_results_only" | "compact_then_truncate"; //#endregion //#region src/agents/embedded-agent-runner/run/types.d.ts type EmbeddedRunAttemptBase = Omit; type EmbeddedRunContextWindowInfo = { tokens: number; referenceTokens?: number; source: "model" | "modelsConfig" | "agentContextTokens" | "default"; }; type 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; beforeAgentFinalizeRevisionAttempts?: number; maxBeforeAgentFinalizeRevisions?: number; }; 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"; turnWatchTimeoutKind?: "progress" | "completion" | "terminal"; transport: "stdio" | "websocket"; threadId?: string; turnId?: string; replaySafe: boolean; replayBlockedReason?: "assistant_output" | "tool_activity" | "potential_side_effect" | "active_item"; diagnostics?: { idleMs?: number; timeoutMs?: number; lastActivityReason?: string; lastNotificationMethod?: string; lastNotificationItemId?: string; lastNotificationItemType?: string; lastNotificationItemRole?: string; lastAssistantTextPreview?: string; activeAppServerTurnRequests?: number; activeTurnItemCount?: number; terminalTurnNotificationQueued?: boolean; completionIdleWatchArmed?: boolean; assistantCompletionIdleWatchArmed?: boolean; terminalIdleWatchArmed?: boolean; }; }; bootstrapPromptWarningSignaturesSeen?: string[]; bootstrapPromptWarningSignature?: string; systemPromptReport?: SessionSystemPromptReport; finalPromptText?: string; messagesSnapshot: AgentMessage[]; beforeAgentFinalizeRevisionReason?: string; assistantTexts: string[]; toolMetas: Array<{ toolName: string; meta?: string; asyncStarted?: boolean; asyncTaskRunId?: string; asyncTaskId?: string; }>; acceptedSessionSpawns?: AcceptedSessionSpawn[]; lastAssistant: AssistantMessage | undefined; currentAttemptAssistant?: AssistantMessage | undefined; lastToolError?: ToolErrorSummary; didSendViaMessagingTool: boolean; didDeliverSourceReplyViaMessageTool?: boolean; didSendDeterministicApprovalPrompt?: boolean; messagingToolSentTexts: string[]; messagingToolSentMediaUrls: string[]; messagingToolSentTargets: MessagingToolSend[]; messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[]; heartbeatToolResponse?: HeartbeatToolResponse; toolMediaUrls?: string[]; toolAudioAsVoice?: boolean; toolTrustedLocalMedia?: boolean; successfulCronAdds?: number; cloudCodeAssistFormatError: boolean; attemptUsage?: NormalizedUsage; promptCache?: ContextEnginePromptCacheInfo; contextBudgetStatus?: SessionContextBudgetStatus; compactionCount?: number; compactionTokensAfter?: number; /** * Client tool calls detected during this attempt (OpenResponses hosted * tools), in the order the underlying LLM emitted them. Field is * `undefined` when no client tools were called so existing truthiness * checks across the runner pipeline (`attempt.clientToolCalls ? ...`) * keep their meaning. When set, the array always has at least one entry. */ clientToolCalls?: Array<{ name: string; params: Record; }>; /** True when sessions_yield tool was called during this attempt. */ yieldDetected?: boolean; replayMetadata: EmbeddedRunReplayMetadata; itemLifecycle: { startedCount: number; completedCount: number; activeCount: number; }; setTerminalLifecycleMeta?: (meta: { replayInvalid?: boolean; livenessState?: EmbeddedRunLivenessState; stopReason?: string; yielded?: boolean; timeoutPhase?: AgentRunTimeoutPhase; providerStarted?: boolean; aborted?: boolean; }) => void; }; //#endregion //#region src/agents/embedded-agent-runner/compact.types.d.ts type CompactEmbeddedAgentSessionParams = { sessionId: string; runId?: string; sessionKey?: string; /** Caller-resolved owner agent for global session aliases. */ agentId?: string; /** Session key used only for runtime policy/sandbox resolution. Defaults to sessionKey. */ sandboxSessionKey?: string; messageChannel?: string; messageProvider?: string; agentAccountId?: string; currentChannelId?: string; currentThreadTs?: string; currentMessageId?: string | number; /** Trusted sender id from inbound context for scoped message-tool discovery. */ senderId?: string; senderName?: string; senderUsername?: string; senderE164?: string; authProfileId?: string; /** Host-resolved provider credential for native harness compaction. */ resolvedApiKey?: string; /** Group id for channel-level tool policy resolution. */ groupId?: string | null; /** Group channel label (e.g. #general) for channel-level tool policy resolution. */ groupChannel?: string | null; /** Group space label (e.g. guild/team id) for channel-level tool policy resolution. */ groupSpace?: string | null; /** Parent session key for subagent policy inheritance. */ spawnedBy?: string | null; sessionFile: string; /** Optional caller-observed live prompt tokens used for compaction diagnostics. */ currentTokenCount?: number; workspaceDir: string; /** Optional task working directory; workspaceDir remains the agent bootstrap workspace. */ cwd?: string; agentDir?: string; config?: OpenClawConfig; skillsSnapshot?: SkillSnapshot; senderIsOwner?: boolean; provider?: string; model?: string; /** Effective model fallback chain for this session attempt. Undefined uses config defaults. */ modelFallbacksOverride?: string[]; /** Optional caller-resolved context engine for harness-owned compaction. */ contextEngine?: ContextEngine; /** Optional caller-resolved token budget for harness-owned compaction. */ contextTokenBudget?: number; /** Optional caller-resolved runtime context for harness-owned context-engine compaction. */ contextEngineRuntimeContext?: ContextEngineRuntimeContext; /** Session-pinned embedded harness id. Prevents compaction hot-switching. */ agentHarnessId?: string; /** OpenClaw-owned runtime policy prepared for this compaction path. */ runtimePlan?: AgentRuntimePlan; thinkLevel?: ThinkLevel; reasoningLevel?: ReasoningLevel; execOverrides?: Pick; bashElevated?: ExecElevatedDefaults; customInstructions?: string; tokenBudget?: number; force?: boolean; /** Force compaction because the caller already determined this turn must compact before prompt submission. */ forcePreflight?: boolean; /** Alias for forcePreflight used by preflight budget gates. */ preflightRequired?: boolean; /** Diagnostic trigger that made preflight compaction mandatory. */ preflightCompactionTrigger?: "tokens" | "transcript_bytes"; trigger?: "budget" | "overflow" | "manual"; /** * Preflight callers can allow native/current-session harness compaction but * move plugin-owned budget compaction onto background turn maintenance. */ deferOwningContextEngineCompaction?: boolean; diagId?: string; attempt?: number; maxAttempts?: number; lane?: string; enqueue?: CommandQueueEnqueueFn; extraSystemPrompt?: string; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; ownerNumbers?: string[]; abortSignal?: AbortSignal; onCompactionHookMessages?: (payload: { phase: "before" | "after"; messages: string[]; sessionId: string; sessionKey: string; }) => void | Promise; /** Allow runtime plugins for this compaction to late-bind the gateway subagent. */ allowGatewaySubagentBinding?: boolean; }; //#endregion //#region src/agents/harness/types.d.ts /** * Public native agent harness contracts and capability shapes. */ 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 AgentHarnessRunCapability = { id: string; label: string; pluginId?: string; /** * Context-engine host capabilities provided by this harness during agent * runs. Harnesses that omit this are unsupported for engines that declare * host requirements. */ contextEngineHostCapabilities?: readonly ContextEngineHostCapability[]; deliveryDefaults?: AgentHarnessDeliveryDefaults; supports(ctx: AgentHarnessSupportContext): AgentHarnessSupport; runAttempt(params: AgentHarnessAttemptParams): Promise; }; type AgentHarnessSideQuestionCapability = { runSideQuestion?(params: AgentHarnessSideQuestionParams): Promise; }; type AgentHarnessClassificationCapability = { classify?(result: AgentHarnessAttemptResult, ctx: AgentHarnessAttemptParams): AgentHarnessResultClassification | undefined; }; type AgentHarnessCompactionCapability = { compact?(params: AgentHarnessCompactParams): Promise; }; type AgentHarnessSessionLifecycleCapability = { reset?(params: AgentHarnessResetParams): Promise | void; dispose?(): Promise | void; }; type AgentHarness = AgentHarnessRunCapability & AgentHarnessSideQuestionCapability & AgentHarnessClassificationCapability & AgentHarnessCompactionCapability & AgentHarnessSessionLifecycleCapability; //#endregion //#region src/realtime-transcription/provider-types.d.ts type RealtimeTranscriptionProviderId = string; type RealtimeTranscriptionProviderConfig = Record; type RealtimeTranscriptionProviderResolveConfigContext = { cfg: OpenClawConfig; rawConfig: RealtimeTranscriptionProviderConfig; }; type RealtimeTranscriptionProviderConfiguredContext = { cfg?: OpenClawConfig; providerConfig: RealtimeTranscriptionProviderConfig; }; /** Callback hooks emitted by realtime transcription sessions. */ type RealtimeTranscriptionSessionCallbacks = { onPartial?: (partial: string) => void; onTranscript?: (transcript: string) => void; onSpeechStart?: () => void; onError?: (error: Error) => void; }; /** Inputs passed to a provider when creating a transcription session. */ type RealtimeTranscriptionSessionCreateRequest = RealtimeTranscriptionSessionCallbacks & { cfg?: OpenClawConfig; providerConfig: RealtimeTranscriptionProviderConfig; }; /** Runtime control surface for a realtime transcription session. */ type RealtimeTranscriptionSession = { connect(): Promise; sendAudio(audio: Buffer): void; close(): void; isConnected(): boolean; }; //#endregion //#region src/security/audit.types.d.ts /** Severity levels emitted by security audit checks. */ type SecurityAuditSeverity = "info" | "warn" | "critical"; /** One actionable or informational security audit finding. */ type SecurityAuditFinding = { checkId: string; severity: SecurityAuditSeverity; title: string; detail: string; remediation?: string; }; //#endregion //#region src/talk/provider-types.d.ts type RealtimeVoiceProviderId = string; type RealtimeVoiceRole = "user" | "assistant"; type RealtimeVoiceCloseReason = "completed" | "error"; type RealtimeVoiceAudioFormat = { encoding: "g711_ulaw"; sampleRateHz: 8000; channels: 1; } | { encoding: "pcm16"; sampleRateHz: 24000; channels: 1; }; declare const REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ: RealtimeVoiceAudioFormat; declare const REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ: RealtimeVoiceAudioFormat; type RealtimeVoiceTool = { type: "function"; name: string; description: string; parameters: { type: "object"; properties: Record; required?: string[]; }; }; type RealtimeVoiceToolCallEvent = { itemId: string; callId: string; name: string; args: unknown; }; type RealtimeVoiceToolResultOptions = { /** * Submit the tool result without prompting the realtime provider to generate a new assistant * response. Use when another channel has already delivered the user-visible answer. */ suppressResponse?: boolean; willContinue?: boolean; }; type RealtimeVoiceBridgeEvent = { direction: "client" | "server"; type: string; detail?: string; itemId?: string; responseId?: string; }; type 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[]; /** * Backend-owned compaction for non-harness CLI sessions. * Set only when the backend bounds its own transcript and persists resumable state. */ ownsNativeCompaction?: boolean; /** * Optional live-smoke metadata owned by the backend plugin. * * Keep provider-specific test wiring here instead of scattering it across * Docker wrappers, docs, and gateway live tests. */ liveTest?: { defaultModelRef?: string; defaultImageProbe?: boolean; defaultMcpProbe?: boolean; docker?: { npmPackage?: string; binaryName?: string; }; }; /** * Whether OpenClaw should inject bundle MCP config for this backend. * * Keep this opt-in. Only backends that explicitly consume OpenClaw's bundle * MCP bridge should enable it. */ bundleMcp?: boolean; /** * Provider-owned bundle MCP integration strategy. * * Different CLIs wire MCP through different surfaces: * - Claude: `--strict-mcp-config --mcp-config` * - Codex: `-c mcp_servers=...` * - Gemini: system-level `settings.json` */ bundleMcpMode?: CliBundleMcpMode; /** * Optional config normalizer applied after user overrides merge. * * Use this for backend-specific compatibility rewrites when old config * shapes need to stay working. */ normalizeConfig?: (config: CliBackendConfig, context?: CliBackendNormalizeConfigContext) => CliBackendConfig; /** * Backend-owned final system-prompt transform. * * Use this for tiny CLI-specific compatibility rewrites without replacing * the generic CLI runner or prompt builder. */ transformSystemPrompt?: (ctx: { config?: OpenClawConfig; workspaceDir?: string; provider: string; modelId: string; modelDisplay: string; agentId?: string; systemPrompt: string; }) => string | null | undefined; /** * Backend-owned bidirectional text replacements. * * `input` applies to the system prompt and user prompt passed to the CLI. * `output` applies to parsed/streamed assistant text from the CLI. */ textTransforms?: PluginTextTransforms; /** * Preferred auth-profile id when the caller did not explicitly lock one. * * Use this when the backend should consume a canonical OpenClaw auth profile * rather than ambient host auth by default. */ defaultAuthProfileId?: string; /** * Session/auth epoch source policy. * * `combined` keeps the legacy "host credential + auth profile" fingerprint. * `profile-only` treats the selected OpenClaw auth profile as the sole auth * owner for session invalidation when one is present. */ authEpochMode?: CliBackendAuthEpochMode; /** * Backend-owned execution bridge. * * Use this on async run paths when the backend needs a generated auth/config * bridge (for example a private CLI home directory) without teaching the core * runner about provider-specific file formats. */ prepareExecution?: (ctx: CliBackendPrepareExecutionContext) => Promise | CliBackendPreparedExecution | null | undefined; /** * Backend-owned per-run argv rewrite. * * Use this for request-scoped CLI dialect flags that should not be modeled * as static config, such as mapping OpenClaw thinking levels to a backend's * native effort flag. */ resolveExecutionArgs?: CliBackendResolveExecutionArgs; /** * Whether this CLI backend can expose native tools outside OpenClaw's tool * catalog. Backends that cannot provide a true no-tools mode must mark * themselves as `always-on` so callers that require disabled tools fail * closed instead of launching a native harness. */ nativeToolMode?: CliBackendNativeToolMode; }; //#endregion //#region src/plugins/codex-app-server-extension-types.d.ts /** Tool-result event emitted to Codex app-server plugin extensions. */ type CodexAppServerToolResultEvent = { threadId: string; turnId: string; toolCallId: string; toolName: string; args: Record; result: AgentToolResult; }; /** Session context passed with Codex app-server extension events. */ type CodexAppServerExtensionContext = { agentId?: string; sessionId?: string; sessionKey?: string; runId?: string; }; /** Optional replacement result returned by a Codex app-server extension handler. */ type CodexAppServerToolResultHandlerResult = { result: AgentToolResult; }; /** Runtime event surface exposed to Codex app-server extension factories. */ type CodexAppServerExtensionRuntime = { on: (event: "tool_result", handler: (event: CodexAppServerToolResultEvent, ctx: CodexAppServerExtensionContext) => Promise | CodexAppServerToolResultHandlerResult | void) => void; }; /** Factory signature for Codex app-server plugin extensions. */ type CodexAppServerExtensionFactory = (runtime: CodexAppServerExtensionRuntime) => Promise | void; //#endregion //#region src/plugins/host-hooks.d.ts /** Reason passed to plugin cleanup callbacks when host-owned state changes. */ type PluginHostCleanupReason = "disable" | "reset" | "delete" | "restart"; type PluginSessionExtensionProjectionContext = { sessionKey: string; sessionId?: string; state: PluginJsonValue | undefined; }; /** Session extension registration owned by a plugin namespace. */ type PluginSessionExtensionRegistration = { namespace: string; description: string; project?: (ctx: PluginSessionExtensionProjectionContext) => PluginJsonValue | undefined; cleanup?: (ctx: { reason: PluginHostCleanupReason; sessionKey?: string; }) => void | Promise; /** * When set, after every successful `patchSessionExtension` the projected * value is mirrored to `SessionEntry[]` so non-plugin readers * can consume the typed slot without reaching into * `pluginExtensions[pluginId][namespace]`. * * The slot is a read-only mirror: writes always go through * `patchSessionExtension`; the host overwrites the slot value on every * subsequent patch. */ sessionEntrySlotKey?: string; /** * Optional JSON-compatible schema describing the projected slot value. * Purely informational at this layer; clients may use it to validate the * mirrored slot against a contract. */ sessionEntrySlotSchema?: PluginJsonValue; }; type PluginSessionExtensionProjection = { pluginId: string; namespace: string; value: PluginJsonValue; }; type PluginToolPolicyDecision = PluginHookBeforeToolCallResult | { allow?: boolean; reason?: string; }; type PluginTrustedToolPolicyRegistration = { id: string; description: string; evaluate: (event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext) => PluginToolPolicyDecision | void | Promise; }; type PluginToolMetadataRegistration = { toolName: string; displayName?: string; description?: string; risk?: "low" | "medium" | "high"; tags?: string[]; }; type 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 /** Prompt payload used when OAuth flow code entry needs user input. */ type OAuthPrompt = { message: string; placeholder?: string; }; /** Creates OAuth callbacks that use local browser auth locally and manual code entry on VPS hosts. */ declare function createVpsAwareOAuthHandlers(params: { isRemote: boolean; prompter: WizardPrompter; runtime: RuntimeEnv; spin: ReturnType; openUrl: (url: string) => Promise; localBrowserMessage: string; manualPromptMessage?: string; }): { onAuth: (event: { url: string; }) => Promise; onPrompt: (prompt: OAuthPrompt) => Promise; }; //#endregion //#region src/auto-reply/reply/abort.runtime-types.d.ts /** Result from the fast abort path before normal reply dispatch starts. */ type FastAbortResult = { handled: boolean; aborted: boolean; stoppedSubagents?: number; }; /** Runtime hook that may convert a message into an immediate abort action. */ type TryFastAbortFromMessage = (params: { ctx: FinalizedMsgContext; cfg: OpenClawConfig; }) => Promise; /** Formats the user-visible abort acknowledgement text. */ type FormatAbortReplyText = (stoppedSubagents?: number) => string; //#endregion //#region src/agents/bash-tools.process.d.ts /** Defaults injected by tests, agent scopes, and scoped process registries. */ type ProcessToolDefaults = { cleanupMs?: number; hasCronTool?: boolean; inputWaitIdleMs?: number; scopeKey?: string; }; //#endregion //#region src/auto-reply/reply/command-session-metadata.d.ts type CommandSessionMetadataChange = { sessionKey: string; agentId?: string; reason: "command-metadata"; }; //#endregion //#region src/auto-reply/reply/get-reply.types.d.ts /** Reply resolver signature used by dispatchers and tests for dependency injection. */ type GetReplyFromConfig = (ctx: MsgContext, opts?: GetReplyOptions, configOverride?: OpenClawConfig) => Promise; //#endregion //#region src/auto-reply/reply/dispatch-from-config.types.d.ts type DispatchFromConfigResult = { queuedFinal: boolean; counts: Record; failedCounts?: Partial>; sourceReplyDeliveryMode?: SourceReplyDeliveryMode; sendPolicyDenied?: boolean; observedReplyDelivery?: boolean; noVisibleReplyFallbackEligible?: boolean; beforeAgentRunBlocked?: boolean; sessionMetadataChanges?: CommandSessionMetadataChange[]; }; type DispatchFromConfigParams = { ctx: FinalizedMsgContext; cfg: OpenClawConfig; dispatcher: ReplyDispatcher; replyOptions?: Omit; replyResolver?: GetReplyFromConfig; onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void; fastAbortResolver?: TryFastAbortFromMessage; formatAbortReplyTextResolver?: FormatAbortReplyText; /** Optional patch applied to the already loaded config before reply resolution. */ configOverride?: OpenClawConfig; }; type DispatchReplyFromConfig = (params: DispatchFromConfigParams) => Promise; //#endregion //#region src/auto-reply/reply/normalize-reply.d.ts type NormalizeReplySkipReason = "empty" | "silent" | "heartbeat"; //#endregion //#region src/auto-reply/reply/reply-dispatcher.d.ts type ReplyDispatchErrorHandler = (err: unknown, info: { kind: ReplyDispatchKind; }) => Promise | void; type ReplyDispatchSkipHandler = (payload: ReplyPayload, info: { kind: ReplyDispatchKind; reason: NormalizeReplySkipReason; }) => void; type ReplyDispatchDeliverer = (payload: ReplyPayload, info: { kind: ReplyDispatchKind; }) => Promise; type ReplyDispatcherOptions = { deliver: ReplyDispatchDeliverer; silentReplyContext?: { cfg?: OpenClawConfig; sessionKey?: string; surface?: string; conversationType?: SilentReplyConversationType; }; responsePrefix?: string; transformReplyPayload?: (payload: ReplyPayload) => ReplyPayload | null; /** Static context for response prefix template interpolation. */ responsePrefixContext?: ResponsePrefixContext; /** Dynamic context provider for response prefix template interpolation. * Called at normalization time, after model selection is complete. */ responsePrefixContextProvider?: () => ResponsePrefixContext; onHeartbeatStrip?: () => void; onIdle?: () => Promise | void; onError?: ReplyDispatchErrorHandler; onSkip?: ReplyDispatchSkipHandler; /** Human-like delay between block replies for natural rhythm. */ humanDelay?: HumanDelayConfig; beforeDeliver?: ReplyDispatchBeforeDeliver; }; type ReplyDispatcherWithTypingOptions = Omit & { typingCallbacks?: TypingCallbacks; onReplyStart?: () => Promise | void; onIdle?: () => Promise | void; onSettled?: () => unknown; onFreshSettledDelivery?: () => unknown; /** Called when the typing controller is cleaned up (e.g., on NO_REPLY). */ onCleanup?: () => void; }; type ReplyDispatcherWithTypingResult = { dispatcher: ReplyDispatcher; replyOptions: Pick; markDispatchIdle: () => void; /** Signal that the model run is complete so the typing controller can stop. */ markRunComplete: () => void; }; declare function createReplyDispatcher(options: ReplyDispatcherOptions): ReplyDispatcher; declare function createReplyDispatcherWithTyping(options: ReplyDispatcherWithTypingOptions): ReplyDispatcherWithTypingResult; //#endregion //#region src/auto-reply/reply/provider-dispatcher.types.d.ts type DispatchReplyContext = MsgContext | FinalizedMsgContext; type DispatchReplyOptions = Omit; /** Buffered block dispatcher entry point used by provider reply flows. */ type DispatchReplyWithBufferedBlockDispatcher$1 = (params: { ctx: DispatchReplyContext; cfg: OpenClawConfig; dispatcherOptions: ReplyDispatcherWithTypingOptions; toolsAllow?: string[]; replyOptions?: DispatchReplyOptions; replyResolver?: GetReplyFromConfig; }) => Promise; /** Plain dispatcher entry point used when block buffering is not needed. */ type DispatchReplyWithDispatcher = (params: { ctx: DispatchReplyContext; cfg: OpenClawConfig; dispatcherOptions: ReplyDispatcherOptions; toolsAllow?: string[]; replyOptions?: DispatchReplyOptions; replyResolver?: GetReplyFromConfig; }) => Promise; //#endregion //#region src/auto-reply/reply/reply-dispatcher.runtime-types.d.ts /** Type of the lazy reply dispatcher factory used by runtime dispatch paths. */ type CreateReplyDispatcherWithTyping$1 = typeof createReplyDispatcherWithTyping; //#endregion //#region src/auto-reply/commands-registry.runtime-types.d.ts /** Runtime-injected policy hook for whether text slash commands should be honored. */ type ShouldHandleTextCommands$1 = (params: ShouldHandleTextCommandsParams) => boolean; //#endregion //#region src/auto-reply/command-detection.runtime-types.d.ts /** Runtime-injected predicate for deciding whether visible text is an OpenClaw command. */ type IsControlCommandMessage$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; /** Runtime-injected predicate for deciding whether command authorization must be computed. */ type ShouldComputeCommandAuthorized$1 = (text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions) => boolean; //#endregion //#region src/auto-reply/dispatch-dispatcher.d.ts /** Mark a dispatcher complete, wait for pending work, then run optional cleanup. */ declare function settleReplyDispatcher(params: { dispatcher: ReplyDispatcher; onSettled?: () => void | Promise; }): Promise; /** Run work with a dispatcher and always drain it before returning or throwing. */ declare function withReplyDispatcher(params: { dispatcher: ReplyDispatcher; run: () => Promise; onSettled?: () => void | Promise; }): Promise; //#endregion //#region src/auto-reply/reply/inbound-context.d.ts type FinalizeInboundContextOptions = { forceBodyForAgent?: boolean; forceBodyForCommands?: boolean; forceChatType?: boolean; forceConversationLabel?: boolean; }; declare function finalizeInboundContext>(ctx: T, opts?: FinalizeInboundContextOptions): T & FinalizedMsgContext; //#endregion //#region src/channels/sender-label.d.ts type SenderLabelParams = { name?: string; username?: string; tag?: string; e164?: string; id?: string; }; //#endregion //#region src/auto-reply/envelope.d.ts type AgentEnvelopeParams = { channel: string; from?: string; timestamp?: number | Date; host?: string; ip?: string; body: string; previousTimestamp?: number | Date; envelope?: EnvelopeFormatOptions; }; /** User/config-facing controls for timestamp rendering in prompt envelopes. */ type EnvelopeFormatOptions = { /** * "local" (default), "utc", "user", or an explicit IANA timezone string. */ timezone?: string; /** * Include absolute timestamps in the envelope (default: true). */ includeTimestamp?: boolean; /** * Include elapsed time suffix when previousTimestamp is provided (default: true). */ includeElapsed?: boolean; /** * Optional user timezone used when timezone="user". */ userTimezone?: string; }; /** Resolves envelope formatting defaults from agent config. */ declare function resolveEnvelopeFormatOptions(cfg?: OpenClawConfig): EnvelopeFormatOptions; /** Formats the generic bracketed envelope prepended to agent-visible messages. */ declare function formatAgentEnvelope(params: AgentEnvelopeParams): string; /** Formats an inbound message body with sender attribution appropriate for direct/group chats. */ declare function formatInboundEnvelope(params: { channel: string; from: string; body: string; timestamp?: number | Date; chatType?: string; senderLabel?: string; sender?: SenderLabelParams; previousTimestamp?: number | Date; envelope?: EnvelopeFormatOptions; fromMe?: boolean; }): string; /** Builds the compact `from` label used in inbound envelope headers. */ declare function formatInboundFromLabel(params: { isGroup: boolean; groupLabel?: string; groupId?: string; directLabel: string; directId?: string; groupFallback?: string; }): string; //#endregion //#region src/channels/plugins/outbound/load.types.d.ts /** * Lazy loader contract for channel outbound adapters. */ type LoadChannelOutboundAdapter = (id: ChannelId) => Promise; //#endregion //#region src/channels/turn/bot-loop-protection.d.ts /** Facts used to detect repeated bot-to-bot channel reply loops. */ type ChannelBotLoopProtectionFacts = { scopeId: string; conversationId: string; senderId: string; receiverId: string; config?: PairLoopGuardConfig; defaultsConfig?: PairLoopGuardConfig; defaultEnabled: boolean; nowMs?: number; }; /** Records a bot pair interaction and returns whether the loop guard should suppress it. */ declare function recordChannelBotPairLoopAndCheckSuppression(params: ChannelBotLoopProtectionFacts): PairLoopGuardResult; /** Clears channel bot-loop state for isolated tests. */ declare function clearChannelBotPairLoopGuardForTests(): void; /** Lists tracked bot-loop pairs for isolated tests. */ declare function listTrackedChannelBotPairsForTests(): PairLoopGuardSnapshotEntry[]; //#endregion //#region src/channels/turn/types.d.ts /** Admission decision for an inbound channel event before agent dispatch. */ type ChannelTurnAdmission = { kind: "dispatch"; reason?: string; } | { kind: "observeOnly"; reason: string; } | { kind: "handled"; reason: string; } | { kind: "drop"; reason: string; recordHistory?: boolean; }; /** Coarse event classification used to decide whether an event can start an agent turn. */ type ChannelEventClass = { kind: "message" | "command" | "interaction" | "reaction" | "lifecycle" | "unknown"; canStartAgentTurn: boolean; requiresImmediateAck?: boolean; }; /** Normalized inbound event text and raw payload after channel-specific ingestion. */ type NormalizedTurnInput = { id: string; timestamp?: number; rawText: string; textForAgent?: string; textForCommands?: string; raw?: unknown; }; /** Sender identity facts projected into channel access, routing, and prompt context. */ type SenderFacts = { id?: string; name?: string; username?: string; tag?: string; roles?: string[]; isBot?: boolean; isSelf?: boolean; displayLabel?: string; }; /** Conversation identity and threading facts for a channel turn. */ type ConversationFacts = { kind: "direct" | "group" | "channel"; id: string; label?: string; spaceId?: string; parentId?: string; threadId?: string; nativeChannelId?: string; routePeer?: { kind: "direct" | "group" | "channel"; id: string; }; }; /** Session routing facts derived before dispatch. */ type RouteFacts = { agentId: string; accountId?: string; routeSessionKey: string; dispatchSessionKey?: string; persistedSessionKey?: string; parentSessionKey?: string; modelParentSessionKey?: string; mainSessionKey?: string; createIfMissing?: boolean; }; /** Reply target and source-delivery facts for a channel turn. */ type ReplyPlanFacts = { to: string; originatingTo?: string; nativeChannelId?: string; replyTarget?: string; deliveryTarget?: string; replyToId?: string; replyToIdFull?: string; messageThreadId?: string | number; threadParentId?: string; sourceReplyDeliveryMode?: "thread" | "reply" | "channel" | "direct" | "none"; }; /** Allowlist projection used by access checks without exposing raw configured entries. */ type ProjectedAllowlistAccessFacts = { configured: boolean; matched: boolean; reasonCode?: string; matchedEntryIds: string[]; invalidEntryCount: number; disabledEntryCount: number; accessGroups: { referenced: string[]; matched: string[]; missing: string[]; unsupported: string[]; failed: string[]; }; }; /** Event-level access projection for commands, reactions, buttons, and native events. */ type ProjectedEventAccessFacts = { kind: "message" | "reaction" | "button" | "postback" | "native-command" | "slash-command" | "system"; authMode: "inbound" | "command" | "origin-subject" | "route-only" | "none"; mayPair: boolean; authorized: boolean; reasonCode?: string; hasOriginSubject: boolean; originSubjectMatched: boolean; }; /** Access decisions for DMs, groups, commands, events, and mention gating. */ type AccessFacts = { dm?: { decision: "allow" | "pairing" | "deny"; reason?: string; /** * @deprecated Shared ingress projections redact allowlist entries and return an empty compat list. * Use allowlist diagnostics instead. */ allowFrom: string[]; allowlist?: ProjectedAllowlistAccessFacts; }; group?: { policy: "open" | "allowlist" | "disabled"; routeAllowed: boolean; senderAllowed: boolean; /** * @deprecated Shared ingress projections redact allowlist entries and return an empty compat list. * Use allowlist diagnostics instead. */ allowFrom: string[]; requireMention: boolean; allowlist?: ProjectedAllowlistAccessFacts; }; commands?: { authorized?: boolean; shouldBlockControlCommand?: boolean; reasonCode?: string; useAccessGroups: boolean; allowTextCommands: boolean; modeWhenAccessGroupsOff?: "allow" | "deny" | "configured"; /** * @deprecated Shared ingress projections do not expose raw authorizer lists. * Use authorized and reasonCode instead. */ authorizers: Array<{ configured: boolean; allowed: boolean; }>; }; event?: ProjectedEventAccessFacts; mentions?: { canDetectMention: boolean; wasMentioned: boolean; hasAnyMention?: boolean; implicitMentionKinds?: Array<"reply_to_bot" | "quoted_bot" | "bot_thread_participant" | "native">; requireMention?: boolean; effectiveWasMentioned?: boolean; shouldSkip?: boolean; }; }; /** Message text/history facts passed into templating and dispatch. */ type MessageFacts = { inboundEventKind?: InboundEventKind; body?: string; rawBody: string; bodyForAgent?: string; commandBody?: string; envelopeFrom?: string; senderLabel?: string; preview?: string; inboundHistory?: HistoryEntry[]; }; /** Parsed command facts for command-like channel turns. */ type CommandFacts = { kind: CommandTurnKind; body?: string; name?: string; authorized?: boolean; }; /** Quoted, forwarded, thread, and untrusted context facts attached to an inbound turn. */ type SupplementalContextFacts = { quote?: { id?: string; fullId?: string; body?: string; sender?: string; senderAllowed?: boolean; isExternal?: boolean; isQuote?: boolean; }; forwarded?: { from?: string; fromType?: string; fromId?: string; date?: number; senderAllowed?: boolean; }; thread?: { id?: string; starterBody?: string; historyBody?: string; label?: string; parentSessionKey?: string; modelParentSessionKey?: string; senderAllowed?: boolean; }; untrustedContext?: Array<{ label: string; source?: string; type?: string; payload: unknown; }>; groupSystemPrompt?: string; /** Prompt-like group metadata from user-controlled sources; never enters the system prompt. */ untrustedGroupSystemPrompt?: string; }; /** Inbound media facts supplied to the agent context. */ type InboundMediaFacts = { path?: string; url?: string; contentType?: string; kind?: "image" | "video" | "audio" | "document" | "unknown"; transcribed?: boolean; messageId?: string; }; type MaybePromise$1 = T | Promise; /** Adapter preflight output assembled before turn resolution. */ type PreflightFacts = { admission?: ChannelTurnAdmission; command?: CommandFacts; message?: Partial; media?: readonly InboundMediaFacts[] | (() => MaybePromise$1); supplemental?: SupplementalContextFacts; history?: ChannelTurnDroppedHistoryOptions; }; /** Delivery metadata for one reply payload dispatch. */ type ChannelDeliveryInfo = { kind: ReplyDispatchKind; }; /** Durable delivery queue intent recorded when a reply is deferred. */ type ChannelDeliveryIntent = { id: string; kind: "outbound_queue"; queuePolicy: OutboundDeliveryQueuePolicy; }; /** Result returned after delivering one channel reply payload. */ type ChannelDeliveryResult = { messageIds?: string[]; receipt?: MessageReceipt; threadId?: string; replyToId?: string; visibleReplySent?: boolean; deliveryIntent?: ChannelDeliveryIntent; }; /** Durable outbound delivery options available to channel turn delivery adapters. */ type ChannelTurnDurableDeliveryOptions = Pick & { to?: string | null; replyToId?: string | null; requiredCapabilities?: DurableFinalDeliveryRequirements; }; /** Delivery adapter used by channel turns to send reply payloads. */ type ChannelEventDeliveryAdapter = { preparePayload?: (payload: ReplyPayload, info: ChannelDeliveryInfo) => Promise | ReplyPayload; deliver: (payload: ReplyPayload, info: ChannelDeliveryInfo) => Promise; durable?: false | ChannelTurnDurableDeliveryOptions | ((payload: ReplyPayload, info: ChannelDeliveryInfo) => false | ChannelTurnDurableDeliveryOptions | Promise); onDelivered?: (payload: ReplyPayload, info: ChannelDeliveryInfo, result: ChannelDeliveryResult | void) => Promise | void; onError?: (err: unknown, info: { kind: string; }) => void; }; /** Options for recording inbound session route state around a turn. */ type ChannelTurnRecordOptions = { groupResolution?: GroupKeyResolution | null; createIfMissing?: boolean; updateLastRoute?: InboundLastRouteUpdate; onRecordError?: (err: unknown) => void; trackSessionMetaTask?: (task: Promise) => void; }; /** Options for finalizing visible conversation history after dispatch. */ type ChannelTurnHistoryFinalizeOptions = { isGroup?: boolean; historyKey?: string; historyMap?: Map; limit?: number; }; /** Options for recording history when an inbound event is dropped before dispatch. */ type ChannelTurnDroppedHistoryOptions = { key: string; limit: number; historyMap: Map; recordOnDrop?: boolean; mediaLimit?: number; shouldRecord?: () => boolean; }; /** Dispatcher options excluding delivery hooks owned by the channel turn adapter. */ type ChannelTurnDispatcherOptions = Omit; /** Reply pipeline options excluding cfg/agent/channel identity supplied by the turn. */ type ChannelTurnReplyPipelineOptions = Omit; /** Fully assembled channel turn ready to build the dispatch runner. */ type AssembledChannelTurn = { cfg: OpenClawConfig; channel: string; accountId?: string; agentId: string; routeSessionKey: string; storePath: string; ctxPayload: FinalizedMsgContext; recordInboundSession: RecordInboundSession$1; dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher$1; delivery: ChannelEventDeliveryAdapter; replyPipeline?: ChannelTurnReplyPipelineOptions; dispatcherOptions?: ChannelTurnDispatcherOptions; toolsAllow?: string[]; replyOptions?: Omit; replyResolver?: GetReplyFromConfig; record?: ChannelTurnRecordOptions; history?: ChannelTurnHistoryFinalizeOptions; admission?: Extract; botLoopProtection?: ChannelBotLoopProtectionFacts; log?: (event: ChannelTurnLogEvent) => void; messageId?: string; }; /** Channel turn with dispatch runner already prepared. */ type PreparedChannelTurn = { channel: string; accountId?: string; routeSessionKey: string; storePath: string; ctxPayload: FinalizedMsgContext; recordInboundSession: RecordInboundSession$1; record?: ChannelTurnRecordOptions; history?: ChannelTurnHistoryFinalizeOptions; onPreDispatchFailure?: (err: unknown) => void | Promise; runDispatch: () => Promise; observeOnlyDispatchResult?: TDispatchResult; admission?: Extract; botLoopProtection?: ChannelBotLoopProtectionFacts; log?: (event: ChannelTurnLogEvent) => void; messageId?: string; }; /** Resolved turn shape returned by adapters before final run/dispatch handling. */ type ChannelTurnResolved = (AssembledChannelTurn & { admission?: Extract; }) | (PreparedChannelTurn & { admission?: Extract; }); /** Ordered lifecycle stage names emitted to channel turn log hooks. */ type ChannelTurnStage = "ingest" | "classify" | "preflight" | "resolve" | "authorize" | "assemble" | "record" | "dispatch" | "finalize"; /** Structured channel turn log event. */ type ChannelTurnLogEvent = { stage: ChannelTurnStage; event: "start" | "done" | "drop" | "handled" | "error"; channel: string; accountId?: string; messageId?: string; sessionKey?: string; admission?: ChannelTurnAdmission["kind"]; reason?: string; error?: unknown; }; /** Final result for a channel turn, dispatched or admitted without dispatch. */ type ChannelTurnResult = DispatchedChannelTurnResult | { admission: ChannelTurnAdmission; dispatched: false; ctxPayload?: MsgContext; routeSessionKey?: string; }; /** Successful dispatch result for a channel turn. */ type DispatchedChannelTurnResult = { admission: Extract; dispatched: true; ctxPayload: MsgContext; routeSessionKey: string; dispatchResult: TDispatchResult; }; /** Adapter contract for ingesting, classifying, resolving, and finalizing raw channel events. */ type ChannelTurnAdapter = { ingest: (raw: TRaw) => Promise | NormalizedTurnInput | null; classify?: (input: NormalizedTurnInput) => Promise | ChannelEventClass; preflight?: (input: NormalizedTurnInput, eventClass: ChannelEventClass) => Promise | PreflightFacts | ChannelTurnAdmission | null | undefined; resolveTurn: (input: NormalizedTurnInput, eventClass: ChannelEventClass, preflight: PreflightFacts) => Promise> | ChannelTurnResolved; onFinalize?: (result: ChannelTurnResult) => Promise | void; }; /** Parameters for running one raw channel event through the turn kernel. */ type RunChannelTurnParams = { channel: string; accountId?: string; raw: TRaw; adapter: ChannelTurnAdapter; log?: (event: ChannelTurnLogEvent) => void; }; //#endregion //#region src/channels/inbound-event/context.d.ts type MaybePromise = T | Promise; type ChannelInboundSupplementalMediaResolver = () => MaybePromise; type ChannelInboundSupplementalQuoteFacts = NonNullable & { isSelf?: boolean; media?: readonly InboundMediaFacts[] | ChannelInboundSupplementalMediaResolver; }; type ChannelInboundSupplementalFacts = Omit & { quote?: ChannelInboundSupplementalQuoteFacts; }; /** * @deprecated Prefer passing `resolveSupplementalMedia: true` directly to * `buildChannelInboundEventContext` without naming this compatibility type. */ type ChannelInboundSupplementalResolutionOptions = { resolveSupplementalMedia: true; suppressSelfQuoteBody?: boolean; suppressSelfQuoteMedia?: boolean; }; type BuildAccessFacts = Omit & { commands?: Partial>; }; type BuildChannelInboundEventContextParams = { channel: string; accountId?: string; provider?: string; surface?: string; messageId?: string; messageIdFull?: string; timestamp?: number; from: string; sender: SenderFacts; conversation: ConversationFacts; route: RouteFacts; reply: ReplyPlanFacts; message: MessageFacts; access?: BuildAccessFacts; command?: CommandFacts; commandTurn?: CommandTurnContext; media?: InboundMediaFacts[]; supplemental?: ChannelInboundSupplementalFacts; contextVisibility?: ContextVisibilityMode; finalize?: FinalizeInboundContextFn; finalizeOptions?: FinalizeInboundContextOptions; extra?: Record; }; /** * @deprecated Prefer `BuildChannelInboundEventContextParams` with * `resolveSupplementalMedia: true` at call sites that need lazy quote media. */ type BuildChannelInboundEventContextAsyncParams = BuildChannelInboundEventContextParams & ChannelInboundSupplementalResolutionOptions; type BuiltChannelInboundEventContext = FinalizedMsgContext & { Body: string; BodyForAgent: string; BodyForCommands: string; ChatType: ConversationFacts["kind"]; CommandAuthorized: boolean; CommandBody: string; From: string; RawBody: string; SessionKey: string; To: string; InboundEventKind: InboundEventKind; }; type FinalizeInboundContextFn = (ctx: Record, opts?: FinalizeInboundContextOptions) => unknown; /** * @deprecated Used by deprecated `finalizeChannelInboundContext`; new channel * code should pass facts to `buildChannelInboundEventContext`. */ type FinalizeChannelInboundContextParams> = { context: T; supplemental?: SupplementalContextFacts | ChannelInboundSupplementalFacts; contextVisibility?: ContextVisibilityMode; media?: readonly InboundMediaFacts[]; finalize?: FinalizeInboundContextFn; finalizeOptions?: FinalizeInboundContextOptions; }; /** * @deprecated Prefer `FinalizeChannelInboundContextParams` with * `resolveSupplementalMedia: true` when lazy quote media must be resolved. */ type FinalizeChannelInboundContextAsyncParams> = FinalizeChannelInboundContextParams & { resolveSupplementalMedia: true; } & Pick; /** * @deprecated Result type for deprecated `finalizeChannelInboundContext`. */ type FinalizeChannelInboundContextResult> = { context: T & FinalizedMsgContext; supplemental?: SupplementalContextFacts; quoteHidden: boolean; forwardedHidden: boolean; threadHidden: boolean; }; declare function filterChannelInboundSupplementalContext(params: { supplemental?: SupplementalContextFacts; contextVisibility?: ContextVisibilityMode; }): SupplementalContextFacts | undefined; declare function filterChannelInboundQuoteContext(contextVisibility: ContextVisibilityMode | undefined, quote: SupplementalContextFacts["quote"] | undefined): SupplementalContextFacts["quote"] | undefined; /** * @deprecated Prefer `buildChannelInboundEventContext({ resolveSupplementalMedia: true })` * for channel inbound payloads. */ declare function resolveChannelInboundSupplementalContext(params: { supplemental?: ChannelInboundSupplementalFacts; contextVisibility?: ContextVisibilityMode; media?: readonly InboundMediaFacts[]; suppressSelfQuoteBody?: boolean; suppressSelfQuoteMedia?: boolean; }): Promise<{ supplemental?: SupplementalContextFacts; media: InboundMediaFacts[]; quoteHidden: boolean; }>; /** * @deprecated Public compatibility for callers that already prepared legacy * prompt fields. New channel code should use `buildChannelInboundEventContext`. */ declare function finalizeChannelInboundContext>(params: FinalizeChannelInboundContextAsyncParams): Promise>; declare function finalizeChannelInboundContext>(params: FinalizeChannelInboundContextParams): FinalizeChannelInboundContextResult; declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextAsyncParams): Promise; declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextParams): BuiltChannelInboundEventContext; //#endregion //#region src/channels/turn/durable-delivery.d.ts /** Options controlling durable final delivery for inbound channel replies. */ type DurableInboundReplyDeliveryOptions = Pick & { to?: string | null; replyToId?: string | null; requiredCapabilities?: DurableFinalDeliveryRequirements; }; /** Full context required to deliver one inbound final reply through durable message sending. */ type DurableInboundReplyDeliveryParams = DurableInboundReplyDeliveryOptions & { cfg: OpenClawConfig; channel: string; accountId?: string; agentId: string; ctxPayload: FinalizedMsgContext; payload: ReplyPayload; info: ChannelDeliveryInfo; }; /** Outcome of attempting durable final delivery for an inbound reply payload. */ type DurableInboundReplyDeliveryResult = { status: "not_applicable"; reason: "non_final"; } | { status: "unsupported"; reason: "missing_channel" | "missing_target" | "missing_outbound_handler" | "capability_mismatch"; capability?: DurableFinalDeliveryRequirement; } | { status: "handled_visible"; delivery: ChannelDeliveryResult; } | { status: "handled_no_send"; reason: "no_visible_result"; delivery: ChannelDeliveryResult; } | { status: "failed"; error: unknown; sentBeforeError?: true; }; /** Narrows durable delivery results that handled the payload without caller fallback. */ declare function isDurableInboundReplyDeliveryHandled(result: DurableInboundReplyDeliveryResult): result is Extract; /** Throws failed durable delivery results, preserving visible-send metadata when applicable. */ declare function throwIfDurableInboundReplyDeliveryFailed(result: DurableInboundReplyDeliveryResult): void; /** Delivers final inbound replies through the durable message-send context when supported. */ declare function deliverInboundReplyWithMessageSendContext(params: DurableInboundReplyDeliveryParams): Promise; /** @deprecated Use `deliverInboundReplyWithMessageSendContext`. */ declare const deliverDurableInboundReplyPayload: typeof deliverInboundReplyWithMessageSendContext; //#endregion //#region src/channels/turn/delivery-result.d.ts /** Converts a normalized message receipt into the delivery result shape used by channel turns. */ declare function createChannelDeliveryResultFromReceipt(params: { receipt: MessageReceipt; threadId?: string; replyToId?: string; visibleReplySent?: boolean; deliveryIntent?: ChannelDeliveryIntent; }): ChannelDeliveryResult; //#endregion //#region src/channels/turn/dispatch-result.d.ts /** Minimal dispatch result shape needed to count visible channel deliveries. */ type ChannelTurnDispatchResultLike = { queuedFinal?: boolean; counts?: Partial>; observedReplyDelivery?: boolean; } | null | undefined; /** Extra delivery signals observed outside the normal dispatch count payload. */ type ChannelTurnVisibleDeliverySignals = { observedReplyDelivery?: boolean; fallbackDelivered?: boolean; deliverySummaryDelivered?: boolean; }; /** Zero-filled reply dispatch count map used before merging optional provider counts. */ declare const EMPTY_CHANNEL_TURN_DISPATCH_COUNTS: Record; /** Resolves dispatch counts with missing reply kinds filled as zero. */ declare function resolveChannelTurnDispatchCounts(result: ChannelTurnDispatchResultLike): Record; /** Returns whether a turn produced any visible reply delivery signal. */ declare function hasVisibleChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: ChannelTurnVisibleDeliverySignals): boolean; /** Returns whether a turn produced a final reply, fallback, summary, or queued final payload. */ declare function hasFinalChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: Pick): boolean; declare namespace kernel_d_exports { export { AccessFacts, AssembledChannelTurn, BuildChannelInboundEventContextParams, ChannelBotLoopProtectionFacts, ChannelDeliveryInfo, ChannelDeliveryResult, ChannelEventClass, ChannelEventDeliveryAdapter, ChannelHistoryWindow, ChannelTurnAdapter, ChannelTurnAdmission, ChannelTurnDispatchResultLike, ChannelTurnDispatcherOptions, ChannelTurnDroppedHistoryOptions, ChannelTurnHistoryFinalizeOptions, ChannelTurnLogEvent, ChannelTurnRecordOptions, ChannelTurnReplyPipelineOptions, ChannelTurnResolved, ChannelTurnResult, ChannelTurnVisibleDeliverySignals, ConversationFacts, DispatchedChannelTurnResult, DurableInboundReplyDeliveryOptions, DurableInboundReplyDeliveryParams, DurableInboundReplyDeliveryResult, EMPTY_CHANNEL_TURN_DISPATCH_COUNTS, InboundMediaFacts, MessageFacts, NormalizedTurnInput, PreflightFacts, PreparedChannelTurn, ReplyPlanFacts, RouteFacts, RunChannelTurnParams, SenderFacts, SupplementalContextFacts, buildChannelInboundEventContext, clearChannelBotPairLoopGuardForTests, createChannelDeliveryResultFromReceipt, createChannelHistoryWindow, createChannelTurnReplyPipeline, createNoopChannelEventDeliveryAdapter, deliverDurableInboundReplyPayload, deliverInboundReplyWithMessageSendContext, dispatchAssembledChannelTurn, dispatchChannelInboundReply, filterChannelInboundSupplementalContext, hasFinalChannelTurnDispatch, hasVisibleChannelTurnDispatch, isDurableInboundReplyDeliveryHandled, listTrackedChannelBotPairsForTests, recordChannelBotPairLoopAndCheckSuppression, recordDroppedChannelInboundHistory, recordDroppedChannelTurnHistory, resolveChannelTurnDispatchCounts, runChannelInboundEvent, runChannelTurn, runPreparedChannelTurn, runPreparedInboundReply, throwIfDurableInboundReplyDeliveryFailed }; } /** * @deprecated Compatibility assembly for legacy buffered reply dispatchers. * New channel plugins should expose `defineChannelMessageAdapter(...)` from * `openclaw/plugin-sdk/channel-outbound` and route send/receive behavior through * the message lifecycle helpers. */ declare function createChannelTurnReplyPipeline(params: CreateChannelReplyPipelineParams): ReturnType; declare function createNoopChannelEventDeliveryAdapter(): ChannelEventDeliveryAdapter; declare function recordDroppedChannelTurnHistory(params: { input: NormalizedTurnInput; preflight: PreflightFacts; admission?: ChannelTurnAdmission; }): Promise; declare const recordDroppedChannelInboundHistory: typeof recordDroppedChannelTurnHistory; type AssembledChannelTurnWithBotLoopProtection = AssembledChannelTurn & { botLoopProtection: NonNullable; }; type AssembledChannelTurnWithoutBotLoopProtection = Omit & { botLoopProtection?: undefined; }; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurnWithBotLoopProtection): Promise; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurnWithoutBotLoopProtection): Promise; declare function dispatchAssembledChannelTurn(params: AssembledChannelTurn): Promise; declare const dispatchChannelInboundReply: typeof dispatchAssembledChannelTurn; type PreparedChannelTurnWithBotLoopProtection = PreparedChannelTurn & { botLoopProtection: NonNullable["botLoopProtection"]>; }; type PreparedChannelTurnWithoutBotLoopProtection = Omit, "botLoopProtection"> & { botLoopProtection?: undefined; }; declare function runPreparedChannelTurn(params: PreparedChannelTurnWithBotLoopProtection): Promise>; declare function runPreparedChannelTurn(params: PreparedChannelTurnWithoutBotLoopProtection): Promise>; declare function runPreparedChannelTurn(params: PreparedChannelTurn): Promise>; declare const runPreparedInboundReply: typeof runPreparedChannelTurn; declare function runChannelTurn(params: RunChannelTurnParams): Promise>; declare const runChannelInboundEvent: typeof runChannelTurn; //#endregion //#region src/plugins/runtime/types-channel.d.ts /** * Runtime helpers for native channel plugins. * * This surface exposes generic core helpers only. Plugin-owned behavior stays * inside the owning plugin package instead of hanging off core runtime slots * keyed by plugin id. */ type DispatchReplyWithBufferedBlockDispatcher = DispatchReplyWithBufferedBlockDispatcher$1; type CreateReplyDispatcherWithTyping = CreateReplyDispatcherWithTyping$1; type ReadChannelAllowFromStoreForAccount = ReadChannelAllowFromStoreForAccount$1; type UpsertChannelPairingRequestForAccount = UpsertChannelPairingRequestForAccount$1; type ShouldHandleTextCommands = ShouldHandleTextCommands$1; type IsControlCommandMessage = IsControlCommandMessage$1; type ShouldComputeCommandAuthorized = ShouldComputeCommandAuthorized$1; type BuildMentionRegexes = BuildMentionRegexes$1; type MatchesMentionPatterns = MatchesMentionPatterns$1; type MatchesMentionWithExplicit = MatchesMentionWithExplicit$1; type ReadSessionUpdatedAt = ReadSessionUpdatedAt$1; type RecordSessionMetaFromInbound = RecordSessionMetaFromInbound$1; type UpdateLastRoute = UpdateLastRoute$1; type RecordInboundSession = RecordInboundSession$1; type RuntimeThreadBindingLifecycleRecord = SessionBindingRecord | { boundAt: number; lastActivityAt: number; idleTimeoutMs?: number; maxAgeMs?: number; }; type PluginRuntimeChannelContextKey = { channelId: string; accountId?: string | null; capability: string; }; type PluginRuntimeChannelContextEvent = { type: "registered" | "unregistered"; key: { channelId: string; accountId?: string; capability: string; }; context?: unknown; }; type PluginRuntimeChannelContextRegistry = { register: (params: PluginRuntimeChannelContextKey & { context: unknown; abortSignal?: AbortSignal; }) => { dispose: () => void; }; get: (params: PluginRuntimeChannelContextKey) => T | undefined; watch: (params: { channelId?: string; accountId?: string | null; capability?: string; onEvent: (event: PluginRuntimeChannelContextEvent) => void; }) => () => void; }; type PluginRuntimeChannel$1 = { text: { chunkByNewline: typeof chunkByNewline; chunkMarkdownText: typeof chunkMarkdownText; chunkMarkdownTextWithMode: typeof chunkMarkdownTextWithMode; chunkText: typeof chunkText; chunkTextWithMode: typeof chunkTextWithMode; resolveChunkMode: typeof resolveChunkMode; resolveTextChunkLimit: typeof resolveTextChunkLimit; hasControlCommand: typeof hasControlCommand; resolveMarkdownTableMode: ResolveMarkdownTableMode; convertMarkdownTables: typeof convertMarkdownTables; }; reply: { dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher; /** * @deprecated Prefer `openclaw/plugin-sdk/channel-outbound` adapters plus * `dispatchReplyWithBufferedBlockDispatcher` or channel turn helpers. * This is a low-level legacy dispatcher escape hatch. */ createReplyDispatcherWithTyping: CreateReplyDispatcherWithTyping; resolveEffectiveMessagesConfig: typeof resolveEffectiveMessagesConfig; /** * @deprecated Prefer the channel-message reply pipeline helpers. This is * tied to the low-level legacy dispatcher path. */ resolveHumanDelayConfig: typeof resolveHumanDelayConfig; /** * @deprecated Prefer `dispatchReplyWithBufferedBlockDispatcher` with a * channel-message adapter or the channel turn helpers. Direct use must * manually preserve source reply delivery metadata such as * `sourceReplyDeliveryMode`. */ dispatchReplyFromConfig: DispatchReplyFromConfig; withReplyDispatcher: typeof withReplyDispatcher; settleReplyDispatcher: typeof settleReplyDispatcher; /** * @deprecated Prefer `buildChannelInboundEventContext` from * `openclaw/plugin-sdk/channel-inbound` so inbound event metadata is * carried into reply dispatch. */ finalizeInboundContext: typeof finalizeInboundContext; formatAgentEnvelope: typeof formatAgentEnvelope; /** @deprecated Prefer `BodyForAgent` + structured user-context blocks (do not build plaintext envelopes for prompts). */ formatInboundEnvelope: typeof formatInboundEnvelope; resolveEnvelopeFormatOptions: typeof resolveEnvelopeFormatOptions; }; routing: { buildAgentSessionKey: typeof buildAgentSessionKey; resolveAgentRoute: typeof resolveAgentRoute; }; pairing: { buildPairingReply: typeof buildPairingReply; readAllowFromStore: ReadChannelAllowFromStoreForAccount; upsertPairingRequest: UpsertChannelPairingRequestForAccount; }; media: { readRemoteMediaBuffer: typeof readRemoteMediaBuffer; /** @deprecated Use `readRemoteMediaBuffer`. */ fetchRemoteMedia: typeof fetchRemoteMedia; saveRemoteMedia: typeof saveRemoteMedia; saveResponseMedia: typeof saveResponseMedia; saveMediaBuffer: typeof saveMediaBuffer; }; activity: { record: typeof recordChannelActivity; get: typeof getChannelActivity; }; session: { /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */resolveStorePath: typeof resolveStorePath; readSessionUpdatedAt: ReadSessionUpdatedAt; recordSessionMetaFromInbound: RecordSessionMetaFromInbound; /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */ recordInboundSession: RecordInboundSession; updateLastRoute: UpdateLastRoute; }; mentions: { buildMentionRegexes: BuildMentionRegexes; matchesMentionPatterns: MatchesMentionPatterns; matchesMentionWithExplicit: MatchesMentionWithExplicit; implicitMentionKindWhen: typeof implicitMentionKindWhen; resolveInboundMentionDecision: typeof resolveInboundMentionDecision; }; reactions: { createAckReactionHandle: typeof createAckReactionHandle; shouldAckReaction: typeof shouldAckReaction; removeAckReactionAfterReply: typeof removeAckReactionAfterReply; removeAckReactionHandleAfterReply: typeof removeAckReactionHandleAfterReply; }; groups: { resolveGroupPolicy: typeof resolveChannelGroupPolicy; resolveRequireMention: typeof resolveChannelGroupRequireMention; }; debounce: { createInboundDebouncer: typeof createInboundDebouncer; resolveInboundDebounceMs: typeof resolveInboundDebounceMs; }; commands: { resolveCommandAuthorizedFromAuthorizers: typeof resolveCommandAuthorizedFromAuthorizers; isControlCommandMessage: IsControlCommandMessage; shouldComputeCommandAuthorized: ShouldComputeCommandAuthorized; shouldHandleTextCommands: ShouldHandleTextCommands; }; outbound: { loadAdapter: LoadChannelOutboundAdapter; }; inbound: { buildContext: typeof buildChannelInboundEventContext; run: typeof runChannelInboundEvent; /** @deprecated Prefer `run` for raw inbound events or `dispatchReply` for assembled contexts. */ runPreparedReply: typeof runPreparedInboundReply; dispatchReply: typeof dispatchChannelInboundReply; }; threadBindings: { setIdleTimeoutBySessionKey: (params: { channelId: string; targetSessionKey: string; accountId?: string; idleTimeoutMs: number; }) => RuntimeThreadBindingLifecycleRecord[]; setMaxAgeBySessionKey: (params: { channelId: string; targetSessionKey: string; accountId?: string; maxAgeMs: number; }) => RuntimeThreadBindingLifecycleRecord[]; }; runtimeContexts: PluginRuntimeChannelContextRegistry; }; //#endregion //#region src/plugins/runtime/types.d.ts type PluginRuntimeChannel = PluginRuntimeChannel$1; type SubagentRunParams = { sessionKey: string; message: string; provider?: string; model?: string; extraSystemPrompt?: string; lane?: string; lightContext?: boolean; deliver?: boolean; idempotencyKey?: string; }; 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"]; auth?: ModelProviderConfig["auth"]; models?: ModelProviderConfig["models"]; headers?: unknown; }; /** * Sync hook for provider-owned model ids that are not present in the local * registry/catalog yet. * * Use this for pass-through providers or provider-specific forward-compat * behavior. The hook should be cheap and side-effect free; async refreshes * belong in `prepareDynamicModel`. */ type ProviderResolveDynamicModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; modelRegistry: ModelRegistry; providerConfig?: ProviderRuntimeProviderConfig; authProfileId?: string; authProfileMode?: AuthProfileCredential["type"] | "aws-sdk"; }; /** * Optional async warm-up for dynamic model resolution. * * Called only from async model resolution paths, before retrying * `resolveDynamicModel`. This is the place to refresh caches or fetch provider * metadata over the network. */ type ProviderPrepareDynamicModelContext = ProviderResolveDynamicModelContext; type ProviderPreferRuntimeResolvedModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; }; /** * Last-chance rewrite hook for provider-owned transport normalization. * * Runs after OpenClaw resolves an explicit/discovered/dynamic model and before * the embedded runner uses it. Typical uses: swap API ids, fix base URLs, or * patch provider-specific compat bits. */ type ProviderNormalizeResolvedModelContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; model: ProviderRuntimeModel; }; /** * Provider-owned model-id normalization before config/runtime lookup. * * Use this for provider-specific alias cleanup that should stay with the * plugin rather than in core string tables. */ type ProviderNormalizeModelIdContext = { provider: string; modelId: string; }; /** * Provider-owned transport normalization for arbitrary provider/model config. * * Use this when transport cleanup depends on API/baseUrl rather than the * owning provider id, for example custom providers that still target a * plugin-owned transport family. */ type ProviderNormalizeTransportContext = { config?: OpenClawConfig; workspaceDir?: string; provider: string; modelId?: string; api?: string | null; baseUrl?: string; }; /** * Runtime auth input for providers that need an extra exchange step before * inference. The incoming `apiKey` is the raw credential resolved from auth * profiles/env/config. The returned value should be the actual token/key to use * for the request. */ type ProviderPrepareRuntimeAuthContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; model: ProviderRuntimeModel; apiKey: string; authMode: string; profileId?: string; }; /** * Result of `prepareRuntimeAuth`. * * `apiKey` is required and becomes the runtime credential stored in auth * storage. `baseUrl` is optional and lets providers like GitHub Copilot swap to * an entitlement-specific endpoint at request time. `expiresAt` enables generic * background refresh in long-running turns. */ type ProviderPreparedRuntimeAuth = { apiKey: string; baseUrl?: string; request?: ModelProviderRequestTransportOverrides; expiresAt?: number; }; /** * Usage/billing auth input for providers that expose quota/usage endpoints. * * This hook is intentionally separate from `prepareRuntimeAuth`: usage * snapshots often need a different credential source than live inference * requests, and they run outside the embedded runner. * * The helper methods cover the common OpenClaw auth resolution paths: * * - `resolveApiKeyFromConfigAndStore`: env/config/plain token/api_key profiles * - `resolveOAuthToken`: oauth/token profiles resolved through the auth store, * optionally for an explicit provider override * * Plugins can still do extra provider-specific work on top (for example parse a * token blob, read a legacy credential file, or pick between aliases). */ type ProviderResolveUsageAuthContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; resolveApiKeyFromConfigAndStore: (params?: { providerIds?: string[]; envDirect?: Array; }) => string | undefined; resolveOAuthToken: (params?: { provider?: string; }) => Promise; }; type ProviderUsageAuthToken = { token: string; accountId?: string; }; /** * Result of `resolveUsageAuth`. * * Two shapes are supported: * - `{ token: string; accountId?: string }` — use this token for provider usage endpoints. * - `{ handled: true }` — this provider handled the request but has no usable * usage token; core must skip further fallback (generic API-key/OAuth fallback * must not run). * * Returning `null` or `undefined` means "not handled by this provider"; core * proceeds to generic fallback resolution. */ type ProviderResolvedUsageAuth = ProviderUsageAuthToken | { handled: true; }; /** * Usage/quota snapshot input for providers that own their usage endpoint * fetch/parsing behavior. * * This hook runs after `resolveUsageAuth` succeeds. Core still owns summary * fan-out, timeout wrapping, filtering, and formatting; the provider plugin * owns the provider-specific HTTP request + response normalization. */ type ProviderFetchUsageSnapshotContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; token: string; accountId?: string; 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; model?: ProviderRuntimeModel; 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; status?: number; code?: string; errorType?: string; }; /** * Generic embedding provider shape returned by provider plugins. * * Keep this aligned with the memory embedding contract without forcing the * plugin system to import memory internals directly. */ type PluginEmbeddingProvider = { id: string; model: string; maxInputTokens?: number; embedQuery: (text: string, options?: { signal?: AbortSignal; }) => Promise; embedBatch: (texts: string[], options?: { signal?: AbortSignal; }) => Promise; embedBatchInputs?: (inputs: unknown[], options?: { signal?: AbortSignal; }) => Promise; client?: unknown; }; /** * Provider-owned embedding transport creation. * * Use this when a provider wants memory embeddings to live with the provider * plugin instead of the core memory switchboard. */ type ProviderCreateEmbeddingProviderContext = { config: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; model: string; remote?: { baseUrl?: string; apiKey?: unknown; headers?: Record; }; providerApiKey?: string; inputType?: string; queryInputType?: string; documentInputType?: string; outputDimensionality?: number; taskType?: string; }; /** * Provider-owned prompt-cache eligibility. * * Return `true` or `false` to override OpenClaw's built-in provider cache TTL * detection for this provider. Return `undefined` to fall back to core rules. */ type ProviderCacheTtlEligibilityContext = { provider: string; modelId: string; modelApi?: string; }; /** * Provider-owned missing-auth message override. * * Runs only after OpenClaw exhausts normal env/profile/config auth resolution * for the requested provider. Return a custom message to replace the generic * "No API key found" error. */ type ProviderBuildMissingAuthMessageContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; listProfileIds: (providerId: string) => string[]; }; /** * Provider-owned unknown-model hint override. * * Runs after catalog/runtime lookup misses for the requested provider. Return a * hint suffix that OpenClaw should append to the generic `Unknown model` * error. */ type ProviderBuildUnknownModelHintContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; baseUrl?: string; }; /** * Built-in model suppression hook context. * * @deprecated Use manifest `modelCatalog.suppressions`. Runtime suppression * hooks are no longer called by model resolution. */ type ProviderBuiltInModelSuppressionContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; provider: string; modelId: string; baseUrl?: string; }; type ProviderBuiltInModelSuppressionResult = { suppress: boolean; errorMessage?: string; }; /** * Provider-owned "modern model" policy input. * * Live smoke/model-profile selection uses this to keep provider-specific * inclusion/exclusion rules out of core. */ type ProviderModernModelPolicyContext = { provider: string; modelId: string; }; /** * Final catalog augmentation hook. * * Runs after OpenClaw loads the discovered model catalog and merges configured * opt-in providers. Use this for forward-compat rows or vendor-owned synthetic * entries that should appear in `models list` and model pickers even when the * upstream registry has not caught up yet. */ type ProviderAugmentModelCatalogContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; env: NodeJS.ProcessEnv; resolveProviderApiKey?: ProviderCatalogContext["resolveProviderApiKey"]; entries: ModelCatalogEntry[]; }; /** * @deprecated Use ProviderCatalogOrder. */ type ProviderDiscoveryOrder = ProviderCatalogOrder; /** * @deprecated Use ProviderCatalogContext. */ type ProviderDiscoveryContext = ProviderCatalogContext; /** * @deprecated Use ProviderCatalogResult. */ type ProviderDiscoveryResult = ProviderCatalogResult; /** * @deprecated Use ProviderPluginCatalog. */ type ProviderPluginDiscovery = ProviderPluginCatalog; type ProviderPluginWizardSetup = { choiceId?: string; choiceLabel?: string; choiceHint?: string; assistantPriority?: number; assistantVisibility?: "visible" | "manual-only"; onboardingFeatured?: boolean; groupId?: string; groupLabel?: string; groupHint?: string; methodId?: string; /** * Interactive onboarding surfaces where this auth choice should appear. * Defaults to `["text-inference"]` when omitted. */ onboardingScopes?: Array<"text-inference" | "image-generation" | "music-generation">; /** * Optional model-allowlist prompt policy applied after this auth choice is * selected in configure/onboarding flows. * * Keep this UI-facing and static. Provider logic that needs runtime state * should stay in `run`/`runNonInteractive`. */ modelAllowlist?: { allowedKeys?: string[]; initialSelections?: string[]; loadCatalog?: boolean; message?: string; }; /** * Optional default-model prompt policy for this auth/setup choice. * * Use this when selecting the auth choice should still force a model picker * even if the choice was preseeded via CLI/configure, or when "keep current" * would skip required provider-owned post-selection work. */ modelSelection?: { promptWhenAuthChoiceProvided?: boolean; allowKeepCurrent?: boolean; }; }; /** Optional model-picker metadata shown in interactive provider selection flows. */ type ProviderPluginWizardModelPicker = { label?: string; hint?: string; methodId?: string; }; /** UI metadata that lets provider plugins appear in onboarding and configure flows. */ type ProviderPluginWizard = { setup?: ProviderPluginWizardSetup; modelPicker?: ProviderPluginWizardModelPicker; }; type ProviderOAuthProfileIdRepair = { /** * Legacy OAuth profile id to migrate away from. * * When omitted, OpenClaw falls back to `:default`. */ legacyProfileId?: string; /** * Optional custom doctor prompt label. * * Defaults to the provider label when omitted. */ promptLabel?: string; }; type ProviderModelSelectedContext = { config: OpenClawConfig; model: string; prompter: WizardPrompter; agentDir?: string; workspaceDir?: string; }; type ProviderDeferSyntheticProfileAuthContext = { config?: OpenClawConfig; provider: string; providerConfig?: ModelProviderConfig; resolvedApiKey?: string; }; type ProviderSystemPromptContributionContext = { config?: OpenClawConfig; agentDir?: string; workspaceDir?: string; provider: string; modelId: string; promptMode: PromptMode; runtimeChannel?: string; runtimeCapabilities?: string[]; agentId?: string; trigger?: "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user"; }; type ProviderTransformSystemPromptContext = ProviderSystemPromptContributionContext & { systemPrompt: string; }; type PluginTextTransformRegistration = PluginTextTransforms; /** Text-inference provider capability registered by a plugin. */ type ProviderPlugin = { id: string; pluginId?: string; label: string; docsPath?: string; aliases?: string[]; /** * Internal-only aliases used for runtime/config hook lookup. * * Unlike `aliases`, these values are not treated as user-facing provider ids * for auth/setup surfaces. Use them for legacy config keys or compat-only * hook routing. */ hookAliases?: string[]; /** * Provider-related env vars shown in setup/search/help surfaces. * * Keep entries in preferred display order. This can include direct auth env * vars or setup inputs such as OAuth client id/secret vars. */ envVars?: string[]; auth: ProviderAuthMethod[]; /** * Legacy text-provider catalog hook. * * @deprecated New catalog/control-plane surfaces should use * `api.registerModelCatalogProvider`. This hook remains the text runtime * source until the unified loader fully replaces it. * Returns provider config/model definitions that merge into models.providers. */ catalog?: ProviderPluginCatalog; /** * Legacy offline text-provider catalog hook for display-only surfaces. * * @deprecated New static rows should be registered with * `api.registerModelCatalogProvider`. * * Unlike `catalog`, this hook must not perform network I/O or require real * credentials. Use it for bundled/static rows that can be shown before auth is * configured. */ staticCatalog?: ProviderPluginCatalog; /** * Show catalog row labels as the literal `/` * composition instead of the canonical (deduped) key. * * `modelKey` strips a duplicate `/` prefix so storage and * lookups stay stable. This flag only changes the picker label — the * option value and persisted config remain canonical. * * Set when the leading `/` segment in the native model id is * a meaningful vendor namespace (e.g. NVIDIA's `nvidia/nemotron-...` * alongside `moonshotai/kimi-k2.5`). */ preserveLiteralProviderPrefix?: boolean; /** * @deprecated Use catalog. * * Legacy alias for catalog. * Kept for compatibility with existing provider plugins. */ discovery?: ProviderPluginDiscovery; /** * Sync runtime fallback for model ids not present in the local catalog. * * Hook order: * 1. discovered/static model lookup * 2. plugin `resolveDynamicModel` * 3. core fallback heuristics * 4. generic provider-config fallback * * Keep this hook cheap and deterministic. If you need network I/O first, use * `prepareDynamicModel` to prime state for the async retry path. */ resolveDynamicModel?: (ctx: ProviderResolveDynamicModelContext) => ProviderRuntimeModel | null | undefined; /** * Optional async prefetch for dynamic model resolution. * * OpenClaw calls this only from async model resolution paths. After it * completes, `resolveDynamicModel` is called again. */ prepareDynamicModel?: (ctx: ProviderPrepareDynamicModelContext) => Promise; /** * Lets a provider plugin opt exact configured models into a runtime * metadata comparison pass before the embedded runner returns the explicit * entry unchanged. */ preferRuntimeResolvedModel?: (ctx: ProviderPreferRuntimeResolvedModelContext) => boolean; /** * Provider-owned transport normalization. * * Use this to rewrite a resolved model without forking the generic runner: * swap API ids, update base URLs, or adjust compat flags for a provider's * transport quirks. */ normalizeResolvedModel?: (ctx: ProviderNormalizeResolvedModelContext) => ProviderRuntimeModel | null | undefined; /** * Provider-owned model-id normalization. * * Runs before model lookup/canonicalization. Use this for alias cleanup such * as provider-owned preview/legacy model ids. */ normalizeModelId?: (ctx: ProviderNormalizeModelIdContext) => string | null | undefined; /** * Provider-owned transport-family normalization before generic model * assembly. * * Use this for API/baseUrl cleanup that may apply to custom provider ids * which still target the provider's transport family. */ normalizeTransport?: (ctx: ProviderNormalizeTransportContext) => { api?: string | null; baseUrl?: string; } | null | undefined; /** * Provider-owned config normalization for `models.providers.`. * * Use this for provider-specific baseUrl/model-id cleanup that should stay * with the plugin rather than in core config-policy tables. */ normalizeConfig?: (ctx: ProviderNormalizeConfigContext) => ModelProviderConfig | null | undefined; /** * Provider-owned final native-streaming compat pass for config providers. * * Use this when a provider opts specific native base URLs into * `supportsUsageInStreaming` or similar transport compatibility flags. */ applyNativeStreamingUsageCompat?: (ctx: ProviderNormalizeConfigContext) => ModelProviderConfig | null | undefined; /** * Provider-owned config apiKey/env marker resolution. * * Use this when a provider resolves auth from env vars such as AWS/GCP * markers rather than a normal API-key env var. */ resolveConfigApiKey?: (ctx: ProviderResolveConfigApiKeyContext) => string | null | undefined; /** * @deprecated Legacy static capability bag kept only for compatibility. * * New provider behavior should use explicit hooks instead. Core replay and * stream/runtime logic no longer consumes this field. */ capabilities?: ProviderCapabilities; /** * Provider-owned replay/compaction policy override. * * Use this when transcript replay or compaction should follow provider-owned * rules that are more expressive than the static `capabilities` bag. */ buildReplayPolicy?: (ctx: ProviderReplayPolicyContext) => ProviderReplayPolicy | null | undefined; /** * Provider-owned replay-history sanitization. * * Runs after OpenClaw performs generic transcript cleanup. Use this for * provider-specific replay rewrites that should stay with the provider * plugin rather than in shared core compaction helpers. */ sanitizeReplayHistory?: (ctx: ProviderSanitizeReplayHistoryContext) => Promise | AgentMessage[] | null | undefined; /** * Provider-owned final replay-turn validation. * * Use this when provider transports need stricter replay-time validation or * turn reshaping after generic sanitation. Returning a non-null value * replaces the built-in replay validators rather than composing with them. */ validateReplayTurns?: (ctx: ProviderValidateReplayTurnsContext) => Promise | AgentMessage[] | null | undefined; /** * Provider-owned tool-schema normalization. * * Use this for transport-family schema cleanup before OpenClaw registers * tools with the embedded runner. */ normalizeToolSchemas?: (ctx: ProviderNormalizeToolSchemasContext) => AnyAgentTool[] | null | undefined; /** * Provider-owned tool-schema diagnostics after normalization. * * Use this when a provider wants to surface transport-specific schema * warnings without teaching core about provider-specific keyword rules. */ inspectToolSchemas?: (ctx: ProviderNormalizeToolSchemasContext) => ProviderToolSchemaDiagnostic[] | null | undefined; /** * Provider-owned reasoning output mode. * * Use this when a provider requires tagged reasoning/final output instead of * native structured reasoning fields. */ resolveReasoningOutputMode?: (ctx: ProviderReasoningOutputModeContext) => ProviderReasoningOutputMode | null | undefined; /** * Provider-owned extra-param normalization before generic stream option * wrapping. * * Typical uses: set provider-default `transport`, map provider-specific * config aliases, or inject extra request metadata sourced from * `agents.defaults.models./.params`. */ prepareExtraParams?: (ctx: ProviderPrepareExtraParamsContext) => Record | null | undefined; /** * Provider-owned request params after transport/model resolution. * * Use this for transport-family request knobs that should be keyed by the * resolved model API/transport rather than a hardcoded core allowlist. */ extraParamsForTransport?: (ctx: ProviderExtraParamsForTransportContext) => ProviderExtraParamsForTransportResult | null | undefined; /** * Provider-owned transport factory. * * Use this when the provider needs a fully custom StreamFn instead of a * wrapper around the normal `streamSimple` path. */ createStreamFn?: (ctx: ProviderCreateStreamFnContext) => StreamFn | null | undefined; /** * Provider-owned stream wrapper applied after generic OpenClaw wrappers. * * Typical uses: provider attribution headers, request-body rewrites, or * provider-specific compat payload patches that do not justify a separate * transport implementation. */ wrapStreamFn?: (ctx: ProviderWrapStreamFnContext) => StreamFn | null | undefined; /** * Provider-owned 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 $, AgentHarnessTaskRuntimeScope as $a, resolveProfileUnusableUntilForDisplay as $c, RealtimeVoiceBargeInOptions as $i, ProviderSystemPromptContribution as $l, PluginRuntime as $n, SpeechModelOverridePolicy as $o, CommandSessionMetadataChange as $r, GenerateImageRuntimeResult as $s, ProviderModelSelectedContext as $t, OpenClawPluginDefinition as A, AgentHarnessResultClassification as Aa, hasSyntheticLocalProviderAuthConfig as Ac, CliBackendAuthEpochMode as Ai, ExternalCliAuthDiscovery as Al, ProviderResolvePromptOverlayContext as An, RuntimeLogger as Ao, ConversationFacts as Ar, ChannelIngressQueuePruneOptions as As, ProviderAuthOptionBag as At, OpenClawPluginModule as B, normalizeUsage as Ba, ResolvedProviderAuth as Bc, PluginTextReplacement as Bi, AuthCredentialReasonCode as Bl, ProviderTransportTurnState as Bn, TaskRunAggregateSummary as Bo, formatInboundEnvelope as Br, WebFetchProviderToolDefinition as Bs, ProviderCatalogResult as Bt, OpenClawPluginApi as C, AgentHarness as Ca, applyLocalNoAuthHeaderOverride as Cc, PluginToolMetadataRegistration as Ci, setAuthProfileOrder as Cl, ProviderReplaySanitizeMode as Cn, TranscriptRewriteResult as Co, AccessFacts as Cr, TaskRecord as Cs, PluginTranscriptsSourceProviderEntry as Ct, OpenClawPluginCliRegistrar as D, AgentHarnessCompactResult as Da, getCustomProviderApiKey as Dc, CodexAppServerExtensionRuntime as Di, listProfilesForProvider as Dl, ProviderResolveAuthProfileIdContext as Dn, LlmCompleteResult as Do, ChannelTurnRecordOptions as Dr, ChannelIngressQueueCompletedRecord as Ds, ProviderAuthKind as Dt, OpenClawPluginCliContext as E, AgentHarnessCompactParams as Ea, getApiKeyForModel as Ec, CodexAppServerExtensionFactory as Ei, dedupeProfileIds as El, ProviderReplayToolCallIdMode as En, LlmCompleteParams as Eo, ChannelTurnDroppedHistoryOptions as Er, ChannelIngressQueueClaimRef as Es, ProviderAuthDoctorHintContext as Et, OpenClawPluginHttpRouteHandler as F, CompactEmbeddedAgentSessionParams as Fa, resolveProviderEntryApiKeyProfileReference as Fc, CliBackendPreparedExecution as Fi, resolveAuthProfileOrder as Fl, ProviderRuntimeProviderConfig as Fn, PluginRuntimeTasks as Fo, SupplementalContextFacts as Fr, PluginWebSearchProviderEntry as Fs, ProviderBuiltInModelSuppressionResult as Ft, OpenClawPluginNodeInvokePolicyApprovalRuntime as G, ToolOutcomeObserver as Ga, resolveAwsSdkEnvVarName as Gc, AgentToolResultMiddlewareHarness as Gi, CODEX_CLI_PROFILE_ID as Gl, RealtimeTranscriptionProviderPlugin as Gn, ResolvedTtsModelOverrides as Go, DispatchReplyWithBufferedBlockDispatcher$1 as Gr, WebSearchProviderPlugin as Gs, ProviderDiscoveryOrder as Gt, OpenClawPluginNodeHostCommand as H, BuildAgentRuntimePlanParams as Ha, isMissingProviderAuthError as Hc, AgentToolResultMiddleware as Hi, TokenExpiryState as Hl, ProviderValidateReplayTurnsContext as Hn, TaskRunDetail as Ho, resolveEnvelopeFormatOptions as Hr, WebSearchCredentialResolutionSource as Hs, ProviderCreateStreamFnContext as Ht, OpenClawPluginHttpRouteMatch as I, EmbeddedRunAttemptParams as Ia, resolveUsableCustomProviderApiKey as Ic, CliBackendResolveExecutionArgs as Ii, ProviderAuthAliasLookupParams as Il, ProviderSanitizeReplayHistoryContext as In, DetachedTaskFinalizeParams as Io, ChannelBotLoopProtectionFacts as Ir, WebFetchCredentialResolutionSource as Is, ProviderCacheTtlEligibilityContext as It, OpenClawPluginNodeInvokeTransportResult as J, isToolWrappedWithBeforeToolCallHook as Ja, calculateAuthProfileCooldownMs as Jc, AgentToolResultMiddlewareRuntime as Ji, ProviderDefaultThinkingPolicyContext as Jl, TranscriptSourceProvider as Jn, TTS_AUTO_MODES as Jo, ReplyDispatcherWithTypingOptions as Jr, WebSearchProviderToolExecutionContext as Js, ProviderExtraParamsForTransportResult as Jt, OpenClawPluginNodeInvokePolicyContext as K, getBeforeToolCallPolicyDiagnosticState as Ka, EnvApiKeyResult as Kc, AgentToolResultMiddlewareOptions as Ki, resolveModelAsync as Kl, RealtimeVoiceProviderPlugin as Kn, TtsConfigResolutionContext as Ko, DispatchReplyWithDispatcher as Kr, WebSearchProviderSetupContext as Ks, ProviderDiscoveryResult as Kt, OpenClawPluginHttpRouteParams as L, EmbeddedRunAttemptResult as La, shouldPreferExplicitConfigApiKeyAuth as Lc, CliBackendResolveExecutionArgsContext as Li, resetProviderAuthAliasMapCacheForTest as Ll, ProviderSystemPromptContributionContext as Ln, DetachedTaskLifecycleRuntime as Lo, recordChannelBotPairLoopAndCheckSuppression as Lr, WebFetchProviderContext as Ls, ProviderCapabilities as Lt, OpenClawPluginGatewayRuntimeScopeSurface as M, AgentHarnessSideQuestionResult as Ma, resolveApiKeyForProvider as Mc, CliBackendNormalizeConfigContext as Mi, resolveAuthProfileDisplayLabel as Ml, ProviderResolveUsageAuthContext as Mn, BoundTaskRunsRuntime as Mo, InboundMediaFacts as Mr, emitSessionTranscriptUpdate as Ms, ProviderBuildMissingAuthMessageContext as Mt, OpenClawPluginHostedMediaResolver as N, AgentHarnessSupport as Na, resolveModelAuthMode as Nc, CliBackendPlugin as Ni, AuthProfileEligibilityReasonCode as Nl, ProviderResolveWebSocketSessionPolicyContext as Nn, PluginRuntimeTaskFlows as No, PreparedChannelTurn as Nr, onSessionTranscriptUpdate as Ns, ProviderBuildUnknownModelHintContext as Nt, OpenClawPluginCommandDefinition as O, AgentHarnessDeliveryDefaults as Oa, hasAvailableAuthForProvider as Oc, CodexAppServerToolResultEvent as Oi, refreshOAuthCredentialForRuntime as Ol, ProviderResolveDynamicModelContext as On, LlmCompleteUsage as Oo, ChannelTurnResult as Or, ChannelIngressQueueEnqueueResult as Os, ProviderAuthMethod as Ot, OpenClawPluginHttpRouteAuth as P, AgentHarnessSupportContext as Pa, resolveProviderEntryApiKeyBinding as Pc, CliBackendPrepareExecutionContext as Pi, resolveAuthProfileEligibility as Pl, ProviderResolvedUsageAuth as Pn, PluginRuntimeTaskRuns as Po, RunChannelTurnParams as Pr, PluginWebFetchProviderEntry as Ps, ProviderBuiltInModelSuppressionContext as Pt, OpenClawPluginSecurityAuditContext as Q, wrapToolWithBeforeToolCallHook as Qa, markAuthProfileFailure as Qc, RealtimeVoiceAudioFormat as Qi, ProviderRuntimePluginHandle as Ql, CreatePluginRuntimeOptions as Qn, SpeechListVoicesRequest as Qo, GetReplyFromConfig as Qr, GenerateImageParams as Qs, ProviderFollowupFallbackRouteResult as Qt, OpenClawPluginHttpRouteUpgradeHandler as R, PreemptiveCompactionRoute as Ra, MissingProviderAuthError as Rc, CliBackendThinkingLevel as Ri, resolveProviderAuthAliasMap as Rl, ProviderToolSchemaDiagnostic as Rn, TaskFlowDetail as Ro, EnvelopeFormatOptions as Rr, WebFetchProviderId as Rs, ProviderCatalogContext as Rt, OpenClawPluginAgentEventsApi as S, RealtimeTranscriptionSessionCreateRequest as Sa, applyAuthHeaderOverride as Sc, PluginSessionTurnUnscheduleByTagResult as Si, removeProviderAuthProfilesWithLock as Sl, ProviderReplayPolicyContext as Sn, TranscriptRewriteRequest as So, resolveChannelInboundSupplementalContext as Sr, OpenClawPluginToolOptions as Ss, PluginTextTransformRegistration as St, OpenClawPluginCliCommandDescriptor as T, AgentHarnessAttemptResult as Ta, createRuntimeProviderAuthLookup as Tc, CodexAppServerExtensionContext as Ti, upsertAuthProfileWithLock as Tl, ProviderReplaySessionState as Tn, LlmCompleteMessage as To, ChannelTurnAdmission as Tr, ChannelIngressQueueClaim as Ts, ProviderAuthContext as Tt, OpenClawPluginNodeInvokeApprovalDecision as U, BeforeToolCallPolicyDiagnosticState as Ua, isProviderAuthError as Uc, AgentToolResultMiddlewareContext as Ui, hasUsableOAuthCredential as Ul, ProviderWebSocketSessionPolicy as Un, TaskRunView as Uo, finalizeInboundContext as Ur, WebSearchProviderContext as Us, ProviderDeferSyntheticProfileAuthContext as Ut, OpenClawPluginNodeCliFeatureOptions as V, AgentRuntimePlan as Va, formatMissingAuthError as Vc, PluginTextTransforms as Vi, DEFAULT_OAUTH_REFRESH_MARGIN_MS as Vl, ProviderUsageAuthToken as Vn, TaskRunCancelResult as Vo, formatInboundFromLabel as Vr, WebFetchRuntimeMetadataContext as Vs, ProviderCreateEmbeddingProviderContext as Vt, OpenClawPluginNodeInvokePolicy as W, DeferredPluginToolApproval as Wa, requireApiKey as Wc, AgentToolResultMiddlewareEvent as Wi, CLAUDE_CLI_PROFILE_ID as Wl, ProviderWrapStreamFnContext as Wn, ResolvedTtsConfig as Wo, settleReplyDispatcher as Wr, WebSearchProviderId as Ws, ProviderDiscoveryContext as Wt, OpenClawPluginRunContextApi as X, runBeforeToolCallHook as Xa, markAuthProfileBlockedUntil as Xc, REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ as Xi, ProviderThinkingProfile as Xl, UnifiedModelCatalogProviderPlugin as Xn, SpeechDirectiveTokenParseContext as Xo, createReplyDispatcherWithTyping as Xr, GenerateVideoParams as Xs, ProviderFetchUsageSnapshotContext as Xt, OpenClawPluginReloadRegistration as Y, requestDeferredPluginToolApproval as Ya, clearAuthProfileCooldown as Yc, OpenClawAgentToolResult as Yi, ProviderThinkingPolicyContext as Yl, UnifiedModelCatalogProviderContext as Yn, normalizeTtsAutoMode as Yo, createReplyDispatcher as Yr, WebSearchRuntimeMetadataContext as Ys, ProviderFailoverErrorContext as Yt, OpenClawPluginSecurityAuditCollector as Z, setBeforeToolCallDiagnosticsEnabled as Za, markAuthProfileCooldown as Zc, REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ as Zi, ProviderRuntimeModel as Zl, VideoGenerationProviderPlugin as Zn, SpeechDirectiveTokenParseResult as Zo, DispatchFromConfigResult as Zr, GenerateVideoRuntimeResult as Zs, ProviderFollowupFallbackRouteContext as Zt, MigrationSummary as _, RealtimeTranscriptionProviderConfiguredContext as _a, resolveSimpleCompletionSelectionForAgent as _c, PluginSessionExtensionRegistration as _i, SqliteWalMaintenance as _l, ProviderPrepareRuntimeAuthContext as _n, IngestBatchResult as _o, FinalizeChannelInboundContextResult as _r, ResolvedProviderRuntimeAuth as _s, PluginRealtimeVoiceProviderEntry as _t, ImageGenerationProviderPlugin as a, RealtimeVoiceBrowserSessionCreateRequest as aa, EmbeddedBlockChunker as ac, PluginAgentEventEmitResult as ai, ensureAuthProfileStore as al, ProviderNormalizeToolSchemasContext as an, AssembleResult as ao, hasVisibleChannelTurnDispatch as ar, SpeechProviderPreparedSynthesis as as, PluginCommandContext as at, ProviderSyntheticAuthResult as au, OpenClawGatewayDiscoveryService as b, RealtimeTranscriptionSession as ba, ProviderEntryApiKeyBindingResolution as bc, PluginSessionTurnScheduleParams as bi, suggestOAuthProfileIdForLegacyDefault as bl, ProviderReasoningOutputModeContext as bn, SubagentSpawnPreparation as bo, filterChannelInboundSupplementalContext as br, OpenClawPluginToolContext as bs, PluginSetupAutoEnableProbe as bt, MigrationDetection as c, RealtimeVoiceProviderConfig as ca, ExecElevatedDefaults as cc, PluginRunContextGetParams as ci, findPersistedAuthProfileCredential as cl, ProviderPlugin as cn, ContextEngine as co, DurableInboundReplyDeliveryParams as cr, SpeechProviderResolveTalkOverridesContext as cs, PluginCommandResult as ct, MessagingToolSend as cu, MigrationItemKind as d, RealtimeVoiceProviderResolveConfigContext as da, PreparedSimpleCompletionModel as dc, PluginSessionActionContext as di, loadAuthProfileStoreForSecretsRuntime as dl, ProviderPluginWizard as dn, ContextEngineInfo as do, BuildChannelInboundEventContextAsyncParams as dr, SpeechSynthesisStreamResult as ds, PluginEmbeddingProvider as dt, HeartbeatToolResponse as du, RealtimeVoiceBridge as ea, EmbeddedRunTrigger as ec, ProcessToolDefaults as ei, resolveProfilesUnavailableReason as el, ProviderModernModelPolicyContext as en, resolveEmbeddedAgentRuntime as eo, SubagentRunParams as er, SpeechProviderConfig as es, OpenClawPluginServiceContext as et, ProviderExternalAuthProfile as eu, MigrationItemStatus as f, RealtimeVoiceRole as fa, PreparedSimpleCompletionModelForAgent as fc, PluginSessionActionRegistration as fi, loadAuthProfileStoreWithoutExternalProfiles as fl, ProviderPluginWizardModelPicker as fn, ContextEngineMaintenanceResult as fo, BuildChannelInboundEventContextParams as fr, SpeechSynthesisTarget as fs, PluginInteractiveHandlerRegistration as ft, normalizeHeartbeatToolResponse as fu, MigrationProviderPreparation as g, RealtimeTranscriptionProviderConfig as ga, prepareSimpleCompletionModelForAgent as gc, PluginSessionExtensionProjection as gi, updateAuthProfileStoreWithLock as gl, ProviderPrepareExtraParamsContext as gn, ContextEngineRuntimeContext as go, FinalizeChannelInboundContextParams as gr, TtsDirectiveParseResult as gs, PluginRealtimeTranscriptionProviderEntry as gt, MigrationProviderPlugin as h, RealtimeVoiceToolResultOptions as ha, prepareSimpleCompletionModel as hc, PluginSessionAttachmentResult as hi, saveAuthProfileStore as hl, ProviderPrepareDynamicModelContext as hn, ContextEnginePromptCacheInfo as ho, FinalizeChannelInboundContextAsyncParams as hr, TtsDirectiveOverrides as hs, PluginLogger as ht, AgentPromptSurfaceKind as i, RealtimeVoiceBrowserSession as ia, BlockReplyChunking as ic, PluginAgentEventEmitParams as ii, clearRuntimeAuthProfileStoreSnapshots as il, ProviderNormalizeResolvedModelContext as in, resolveContextEngineOwnerPluginId as io, hasFinalChannelTurnDispatch as ir, SpeechProviderPrepareSynthesisContext as is, OpenClawPluginSessionWorkflowApi as it, ProviderResolveSyntheticAuthContext as iu, OpenClawPluginGatewayMethod as j, AgentHarnessSideQuestionParams as ja, hasUsableCustomProviderApiKey as jc, CliBackendNativeToolMode as ji, formatAuthDoctorHint as jl, ProviderResolveTransportTurnStateContext as jn, BoundTaskFlowsRuntime as jo, DispatchedChannelTurnResult as jr, ChannelIngressQueueRecord as js, ProviderAuthResult as jt, OpenClawPluginConfigSchema as k, AgentHarnessResetParams as ka, hasRuntimeAvailableProviderAuth as kc, CodexAppServerToolResultHandlerResult as ki, resolveApiKeyForProfile as kl, ProviderResolveNonInteractiveApiKeyParams as kn, PluginRuntimeCore as ko, CommandFacts as kr, ChannelIngressQueueFailedRecord as ks, ProviderAuthMethodNonInteractiveContext as kt, MigrationItem as l, RealtimeVoiceProviderConfiguredContext as la, ExecToolDefaults as lc, PluginRunContextPatch as li, loadAuthProfileStore as ll, ProviderPluginCatalog as ln, ContextEngineHostCapability as lo, DurableInboundReplyDeliveryResult as lr, SpeechSynthesisRequest as ls, PluginConfigMigration as lt, MessagingToolSourceReplyPayload as lu, MigrationProviderContext as m, RealtimeVoiceToolCallEvent as ma, completeWithPreparedSimpleCompletionModel as mc, PluginSessionAttachmentParams as mi, resolvePersistedAuthProfileOwnerAgentDir as ml, ProviderPreferRuntimeResolvedModelContext as mn, ContextEngineProjection as mo, ChannelInboundSupplementalResolutionOptions as mr, SpeechVoiceOption as ms, PluginInteractiveRegistration as mt, AgentPromptGuidance as n, RealtimeVoiceBridgeCreateRequest as na, PromptMode as nc, ProviderNormalizeConfigContext as ni, getSoonestCooldownExpiry as nl, ProviderNonInteractiveApiKeyResult as nn, ContextEngineFactoryContext as no, kernel_d_exports as nr, SpeechProviderId as ns, OpenClawPluginSessionControlsApi as nt, ProviderResolveExternalAuthProfilesContext as nu, MediaUnderstandingProviderPlugin as o, RealtimeVoiceCloseReason as oa, AgentStreamParams as oc, PluginAgentEventSubscriptionRegistration as oi, ensureAuthProfileStoreForLocalUpdate as ol, ProviderNormalizeTransportContext as on, BootstrapResult as oo, resolveChannelTurnDispatchCounts as or, SpeechProviderResolveConfigContext as os, PluginCommandDiagnosticsSession as ot, EmbeddedAgentCompactResult as ou, MigrationPlan as p, RealtimeVoiceTool as pa, SimpleCompletionModelOptions as pc, PluginSessionActionResult as pi, replaceRuntimeAuthProfileStoreSnapshots as pl, ProviderPluginWizardSetup as pn, ContextEngineOperation as po, BuiltChannelInboundEventContext as pr, SpeechTelephonySynthesisRequest as ps, PluginInteractiveHandlerResult as pt, OpenClawPluginNodeInvokePolicyResult as q, hasBeforeToolCallPolicy as qa, resolveEnvApiKey as qc, AgentToolResultMiddlewareResult as qi, augmentModelCatalogWithProviderPlugins as ql, SpeechProviderPlugin as qn, resolveEffectiveTtsConfig as qo, ReplyDispatcherOptions as qr, WebSearchProviderToolDefinition as qs, ProviderExtraParamsForTransportContext as qt, AgentPromptGuidanceEntry as r, RealtimeVoiceBridgeEvent as ra, AgentInternalEvent as rc, ProviderResolveConfigApiKeyContext as ri, isProfileInCooldown as rl, ProviderNormalizeModelIdContext as rn, registerContextEngine as ro, recordDroppedChannelInboundHistory as rr, SpeechProviderOverrides as rs, OpenClawPluginSessionStateApi as rt, ProviderResolveExternalOAuthProfilesContext as ru, MigrationApplyResult as s, RealtimeVoiceProviderCapabilities as sa, ClientToolDefinition as sc, PluginControlUiDescriptor as si, ensureAuthProfileStoreWithoutExternalProfiles as sl, ProviderOAuthProfileIdRepair as sn, CompactResult as so, DurableInboundReplyDeliveryOptions as sr, SpeechProviderResolveTalkConfigContext as ss, PluginCommandHandler as st, EmbeddedAgentRunMeta as su, AGENT_PROMPT_SURFACE_KINDS as t, RealtimeVoiceBridgeCallbacks as ta, RunEmbeddedAgentParams as tc, ProviderApplyConfigDefaultsContext as ti, clearExpiredCooldowns as tl, ProviderNonInteractiveApiKeyCredentialParams as tn, ContextEngineFactory as to, SubagentRunResult as tr, SpeechProviderConfiguredContext as ts, OpenClawPluginSessionApi as tt, ProviderExternalOAuthProfile as tu, MigrationItemAction as u, RealtimeVoiceProviderId as ua, AgentSimpleCompletionSelection as uc, PluginRuntimeLifecycleRegistration as ui, loadAuthProfileStoreForRuntime as ul, ProviderPluginDiscovery as un, ContextEngineHostRequirements as uo, deliverInboundReplyWithMessageSendContext as ur, SpeechSynthesisStreamRequest as us, PluginConfigValidation as ut, HEARTBEAT_RESPONSE_TOOL_NAME as uu, MusicGenerationProviderPlugin as v, RealtimeTranscriptionProviderId as va, ModelAuthMode as vc, PluginSessionSchedulerJobHandle as vi, SqliteWalMaintenanceOptions as vl, ProviderPreparedRuntimeAuth as vn, IngestResult as vo, buildChannelInboundEventContext as vr, OpenClawPluginActiveModelContext as vs, PluginRegistrationMode as vt, OpenClawPluginChannelRegistration as w, AgentHarnessAttemptParams as wa, canUseProfileAsProviderEntryApiKey as wc, PluginTrustedToolPolicyRegistration as wi, upsertAuthProfile as wl, ProviderReplaySessionEntry as wn, LlmCompleteCaller as wo, AssembledChannelTurn as wr, ChannelIngressQueue as ws, ProviderAugmentModelCatalogContext as wt, OpenClawPluginAgentApi as x, RealtimeTranscriptionSessionCallbacks as xa, RuntimeProviderAuthLookup as xc, PluginSessionTurnUnscheduleByTagParams as xi, markAuthProfileSuccess as xl, ProviderReplayPolicy as xn, TranscriptRewriteReplacement as xo, finalizeChannelInboundContext as xr, OpenClawPluginToolFactory as xs, PluginSpeechProviderEntry as xt, OpenClawGatewayDiscoveryAdvertiseContext as y, RealtimeTranscriptionProviderResolveConfigContext as ya, ProviderCredentialPrecedence as yc, PluginSessionSchedulerJobRegistration as yi, repairOAuthProfileIdMismatch as yl, ProviderReasoningOutputMode as yn, SubagentEndReason as yo, filterChannelInboundQuoteContext as yr, OpenClawPluginHookOptions as ys, PluginSetupAutoEnableContext as yt, OpenClawPluginLifecycleApi as z, NormalizedUsage as za, ProviderAuthError as zc, CliBundleMcpMode as zi, resolveProviderIdForAuth as zl, ProviderTransformSystemPromptContext as zn, TaskFlowView as zo, formatAgentEnvelope as zr, WebFetchProviderPlugin as zs, ProviderCatalogOrder as zt };