import { $ as PluginInstallRecord, B as ModelCompatConfig, Bn as PluginManifestControlUi, D as MemorySearchDeadlineControlOptions, Dt as TelegramDirectConfig, Et as TelegramActionConfig$1, G as ModelProviderConfigInput, H as ModelMediaInputConfig, Hn as PluginManifestDashboardActionVerb, J as ModelApi, Kn as PluginManifestNativeSessionCatalogSetup, Kt as ChannelImplicitMentionsConfig, M as ConfigFileSnapshot, Mn as PluginConfigUiHint, Mt as TelegramTopicConfig, Nn as PluginDiagnostic, On as ExecApprovalForwardTarget, P as OpenClawConfig, Pn as PluginFormat, Qn as ChannelAccountKeyPolicy, Rn as PluginManifestCliCommand, S as MemorySearchManager, T as MemorySessionKind, Tn as MentionPatternsPolicyConfig, Tt as TelegramAccountConfig$1, Un as PluginManifestDashboardDataBinding, V as ModelDefinitionConfig, Vn as PluginManifestDashboard, W as ModelProviderConfig, Wn as PluginManifestMcpServer, Y as McpCodexToolApprovalMode, Z as McpServerToolFilterConfig, Zn as PluginKind, _n as ToolProfileId, _r as AgentRuntimePolicyConfig, an as TtsAutoMode, c as AgentBinding, cn as TtsModelOverrideConfig, ct as TalkProviderConfig, d as MemoryCitationsMode, dn as TtsProvider, fn as CommonChannelGroupConfig, g as MemoryCliSearchResult, gn as ToolLoopDetectionConfig, gr as SubagentDelegationMode, h as MemoryCliSearchParams, hn as GroupToolPolicyConfig, i as CloudWorkerProfileConfig, in as ResolvedTtsPersona, ir as ModelCatalogProvider, it as GatewayPortalIngressConfig, jn as PluginBundleFormat, jt as TelegramNetworkConfig$1, kn as ExecApprovalForwardingMode, kt as TelegramGroupConfig, l as AgentConfig, lr as ModelDecisionCapabilities, m as LegacyMemoryReadResult, mn as GroupToolPolicyBySenderConfig, mr as AgentDefaultsConfig, n as QueueDropPolicy, nr as ModelCatalogContextWindowOption, o as AccessGroupConfig, on as TtsConfig, or as UnifiedModelCatalogEntry, pn as ExecToolConfig, pr as AgentContextLimitsConfig, qn as PluginManifestOnboardingScope, r as DesktopHostConfig, rr as ModelCatalogCost, rt as GatewayOperatorRoleDefinition, sn as TtsMode, sr as UnifiedModelCatalogKind, t as SandboxDockerSettings, tt as GatewayAuthRateLimitConfig, vn as ToolsConfig, vr as AgentSandboxConfig, w as MemorySearchResult, wn as MentionPatternsMode, x as MemoryReadResult, xn as BroadcastStrategy, y as MemoryOriginClass, yn as SafeBinProfileFixture, yt as AcpRuntimeSessionMode, zn as PluginManifestContracts } from "./types-D3g9JHH2.js";
import { h as JsonSchemaObject, m as ChannelConfigUiHint, p as ChannelConfigSchema } from "./zod-schema.implicit-mentions-CQ3UM0qf.js";
import { A as UserMessage, C as TextContent, D as ToolResultMessage, M as ProviderRefusalReview, O as Transport, S as StreamOptions, a as AssistantMessageEventStreamContract, b as StopReason, c as ImageContent$1, d as Model, f as ModelCostConfig, k as Usage, m as ModelThinkingLevel, n as AssistantHistoryMessage, o as CompleteSimpleFn, p as ModelRequestHeaders, r as AssistantMessage, s as Context, t as Api, u as Message$1, w as ThinkingBudgets, x as StreamFn, y as SimpleStreamOptions } from "./types-D_RlIixM.js";
import { t as SchemaContract } from "./schema-contract-v05QRSzC.js";
import { C as SessionScope, E as TextChunkMode, S as SessionResetConfig, T as StreamingMode, b as SessionConfig, d as DmPolicy, f as DmScope, h as HumanDelayConfig, l as ChannelStreamingProgressConfig, p as GroupPolicy, r as BlockStreamingCoalesceConfig, s as ChannelStreamingCommandTextMode, t as AgentElevatedAllowFromConfig, u as ContextVisibilityMode, v as MarkdownTableMode, x as SessionMaintenanceMode, y as ReplyToMode } from "./types.base-CRYAnFlG.js";
import { d as SecretRef, u as SecretInput } from "./types.secrets-DJ_rAo-B.js";
import { r as resolveStateDir } from "./home-dir-ek90rI1q.js";
import { a as PluginDependencyStatus, d as ChannelSetupAdapter, f as ChannelSetupInput, i as PluginDiscoveryResult, l as ChannelOwnedSetupContract, m as ChannelId$1, n as PluginManifestRegistry, p as ChannelMeta, r as PluginTrust, t as PluginManifestRecord } from "./manifest-registry-clB08cKE.js";
import { a as SkillsLibraryReadResult, i as SkillsLibraryListResult, n as SkillLibrarySelection, o as SkillsLibraryReceipt, r as SkillsLibraryActivateResult, t as SkillLibraryFile } from "./skill-library-DVzEZ7Hi.js";
import { $ as TalkClientCreateResult, $t as ModelChoice, A as SessionPlacementWorkerRuntimeInstall, An as SessionActivitySummary$1, B as HumanMention, Bt as AgentToolSurfacePresentation, Cn as SessionObserverDigest, D as SessionPlacementMachine, Dn as SessionsListParams, Dt as TranscriptUtterance$1, E as SessionPlacementDiskSpace, En as SessionsCompanionStateResult, Et as TranscriptSessionSummary, F as QuestionRecord, Ft as BoardWidgetMaterializedPutParams, G as ScopeUpgradeResult, Gt as WorkerInferenceCancelResult, H as UsersMentionableParams, Ht as WorkerGatewayToolInvokeParams, I as QuestionRequestQuestion, It as BoardWidgetPutResult, J as CronUpdateParams, Jt as WorkerInferenceEventParams, K as CronJob$1, Kt as WorkerInferenceErrorReason, L as QuestionResolveResult, Lt as ComputerInvokeParams, M as Question, Mn as SessionParticipant, Mt as BoardOp, N as QuestionAnswers, Nn as SessionParticipantIdentity, Nt as BoardSnapshot, O as SessionPlacementMove, On as SessionGoal, Ot as ProgressCard, P as QuestionOption, Pn as SessionPerson, Pt as BoardWidgetDeclared, Qt as WorkerInferenceTerminalOutcome, R as QuestionResolvedEvent, Rt as WorkerComputerParams, S as SessionDiscussionInfo, Sn as SessionCompanionExchange, St as SessionsCatalogReadResult, T as SessionPlacement, Tn as SessionsAssignOwnerParams, Tt as NativeSubagentsSnapshot, U as UsersMentionableResult, Ut as WorkerGatewayToolUpdateFrame, V as MentionsListResult, Vt as WorkerGatewayToolCancelParams, W as DevicePairRequestedEventSchema, Wt as WorkerInferenceCancelParams, X as SystemAgentWizardCancel, Xt as WorkerInferenceStartResult, Y as SystemAgentChatQuestion, Yt as WorkerInferenceStartParams, Z as ChannelsStatusResult, Zt as WorkerInferenceTerminalFrame, _ as TerminalUploadResult$1, _n as AgentActivityItem, _t as SessionsCatalogContinueParams, a as WorkerLiveEventParams, an as SessionGitHubStatusResult, at as ToolsGitHubAuthorizeStartResult, b as SessionsProcessesListResult, bn as SessionMember, c as WorkerTranscriptCommitErrorReason, cn as ConnectParams, d as WizardAnswer, dn as RequestFrame, en as ModelsListParams, f as WizardNextResult$1, fn as ResponseFrame, g as TerminalUploadPathStyle, gn as AgentWaitParams, h as TerminalSessionInfo, hn as AgentParamsSchema, ht as SessionsCatalogArchiveParams, i as WorkerLiveEventErrorDetails, in as SessionGitHubPublishParams, it as ToolsGitHubAuthorizePollResult, j as SessionsReclaimParams, jn as SessionCommunicationPolicy, jt as BoardMcpAppDescriptor, k as SessionPlacementRunner, kn as SessionsGoalMutationResult, kt as ProgressCardStep, l as WorkerTranscriptCommitParams, lt as SessionCatalogHost, m as TerminalOpenResult, mn as AgentEvent, n as WorkerAdmissionHandshake, nn as GitHubPublicationPublisher, o as WorkerLiveEventResult, p as WizardStep$1, pn as ErrorShape, pt as SessionCatalogShareRoute, q as CronRunLogEntry, qt as WorkerInferenceEventFrame, r as WorkerConnectParams, rn as SessionGitHubPublicationResult, rt as AgentSummary, s as WorkerProtocolCloseReason, t as WorkerAdmissionFailureReason, tn as ModelsListResult, tt as DecisionReceiptV1, u as WorkerTranscriptCommitResult, v as PresenceEntry, vn as ChatAttachmentSchema, w as SessionMoveTarget, wn as SessionObserverHealth, x as SessionsProcessesStopResult, xn as SessionBranch, xt as SessionsCatalogReadParams, y as Snapshot, yn as QueueMode, z as QuestionWaitAnswerResult, zt as WorkerComputerResult } from "./index-DLlUvLzK.js";
import { a as SessionRow, i as SessionPermissionMode, n as SessionCreatedActor$1, o as SessionRunStatus, r as SessionEntryArchiveReason, s as SessionToolOverrides$1, t as CyberAccessProgram } from "./sessions-row-56zOIHhu.js";
import { a as readSqliteDatabaseScopedWriteToken, c as DatabasePathIdentity, i as OpenClawDatabaseMaintenanceScope, n as OpenClawStateDatabaseReadAdmission, s as DatabaseFileIdentity } from "./gateway-state-owner-5vamWnqs.js";
import { t as EngineConnection } from "./sql-connection-DiMIHOpE.js";
import { a as SqliteWorkerCommand, c as SqliteWorkerStateContext, d as OpenBlobStoreOptions, f as PluginBlobStoreWithReceipts, i as SqliteWorkerAdmissionRequest, l as OpenClawStateWorkerErrorPayload, n as SqliteWorkerAdmissionFactory, o as SqliteWorkerOperations, p as PluginStateStoreError, r as RetainedWorkerTransactionAdmission, s as SqliteWorkerStore, u as TranscriptAppendRefusal } from "./sqlite-worker-broker.types-h2Z3zxBc.js";
import { c as GatewayWorkMetricsSnapshot, o as DiagnosticWorkerRequestFields, s as WorkerRequestKind } from "./diagnostic-process-types-DSi9Vq97.js";
import { a as DeclaredProviderOwnerIndex, c as OpenClawStateDatabaseOptions, d as SqliteWalPeriodicResult, f as SqliteWalReclamationResult, i as PluginMetadataSnapshotOwnerMaps, l as SqliteWalMaintenance, n as PluginMetadataRegistryView, o as PluginCompatCode, r as PluginMetadataSnapshot, s as OpenClawStateDatabase, u as SqliteWalPeriodicRequest } from "./plugin-metadata-snapshot-CWiro_gA.js";
import { t as Result$1 } from "./result-VHVNeWs6.js";
import { A as ProviderResolveSyntheticAuthContext, D as ProviderExternalAuthProfile, E as ProviderAuthOptionBag, F as MediaUnderstandingCapability, I as MediaUnderstandingOutput, M as SecretInputMode, N as ModelProviderRequestTransportOverrides$1, O as ProviderExternalAuthProfileResolver, P as ProviderRequestTransportOverrides, j as ProviderSyntheticAuthResult, k as ProviderResolveExternalAuthProfilesContext, m as MediaUnderstandingProvider, p as MediaUnderstandingDecision, u as ImagesDescriptionInput, x as StructuredExtractionRequest } from "./image-runtime-R5OAknTz.js";
import { a as AuthProfileFailureReason, c as OAuthCredential$1, d as RuntimeAuthProfileStore, i as AuthProfileCredentialSource, n as AuthProfileBlockedSource, o as AuthProfileStore$1, r as AuthProfileCredential, s as AuthProfileStoreOwner, t as ApiKeyCredential$1, u as PreparedAuthProfileStoreOwner } from "./types-jmhja8No.js";
import { a as mediaKindFromMime } from "./constants-BCpSHoXd.js";
import { i as MediaFactLegacyProjection, n as MediaFact, r as MediaFactInput, t as LegacyMediaContextKey } from "./media-facts-DFJC5G1o.js";
import "./index-Cj8vHfUP.js";
import { A as QueueMode$1, C as AgentTool, D as BashExecutionMessage, E as AgentToolUpdateCallback, M as ThinkingLevel, N as ToolExecutionMode, O as CustomMessage, P as ToolLoopWarning, S as AgentState, T as AgentToolResult, _ as AfterToolCallResult, b as AgentLoopTurnUpdate, g as ImageSanitizationLimits, j as StreamFn$1, k as PrepareNextTurnContext, n as AnyAgentTool, v as AgentEvent$1, w as AgentToolProgress, x as AgentMessage, y as AgentLoopConfig } from "./common-CQdhR1vx.js";
import { a as CommandNormalizeOptions, l as CommandArgs } from "./commands-registry.types-CCUXZxd2.js";
import { n as HistoryMediaEntry, t as HistoryEntry } from "./history.types-AP0C5aEq.js";
import { T as FastMode } from "./string-normalization-BJMJTTOA.js";
import { t as StreamingCompatEntry } from "./streaming-config-readers-C0jApFwj.js";
import { a as TraceLevel, i as ThinkingCatalogEntry, n as ReasoningLevel, o as VerboseLevel, r as ThinkLevel, t as ElevatedLevel } from "./thinking.shared-CFZJvgsr.js";
import { f as TerminalApprovalSnapshot, i as ApprovalPresentation, l as ApprovalTerminalReason, r as ApprovalDecision, u as SessionApprovalReplay } from "./exec-approvals-CQWW96Sr.js";
import { A as resolveExecModePolicy, C as ExecApprovalUnavailableDecision, D as ExecMode, E as ExecHost, O as ExecSecurity, S as ExecApprovalResolved, T as ExecAsk, _ as ApprovalScope, b as ExecApprovalRequest, c as SystemAgentApprovalResolved, d as PluginApprovalRequest$1, f as PluginApprovalRequestPayload, i as NormalizedApprovalRequest, j as AllowAlwaysPattern, k as ExecTarget, n as ApprovalResolved, o as SystemAgentApprovalRequest, p as PluginApprovalResolved, r as ChannelApprovalKind, s as SystemAgentApprovalRequestPayload, t as ApprovalRequestInput, w as ExecApprovalsFile, x as ExecApprovalRequestPayload, y as ExecApprovalDecision } from "./approval-types-DvHXW4T6.js";
import { A as ChannelApprovalNativeAdapterAsync, Ct as reduceLegacyInteractiveReply, D as ChannelNativeApprovalDeliveryCallbacks, E as ExecApprovalActionDescriptor, K as MessagePresentationButton, L as LegacyInteractiveReply, N as InteractiveReply, O as ChannelNativeApprovalTransportSpec, T as ResolvedApprovalView, U as MessagePresentation, ct as ReplyPayloadDelivery, k as ChannelApprovalNativeAdapter, l as ChannelApprovalNativeRuntimeAdapter, lt as ReplyPayloadDeliveryPin, u as ChannelApprovalNativeRuntimeAdapterAsync } from "./approval-handler-runtime-types-BYUybQpd.js";
import { _ as NodePluginToolDescriptor, a as WorkerDesktopLaunchParams, c as WorkerEnvironmentStartStatus, d as WorkerMachineOption$1, f as WorkerOperatingSystem$1, g as NodeInvokeProgressParams$1, h as NodeHostStatsPayload, l as WorkerEnvironmentState, m as WorkerTunnelStatus, n as EnvironmentsPrepareParams, o as WorkerDesktopLaunchResult, r as EnvironmentsPrepareResult, s as WorkerDesktopObserveResult$1, t as DesktopAvailability, u as WorkerExecutionMode, v as NodeSkillDescriptor } from "./environments-GFdlZ3hi.js";
import { a as UsersAuthConnectStatusResult, c as UsersLinkAuthProfileResult, d as UsersSelectModelAccountResult, f as UsersUnlinkAuthProfileResult, i as UsersAuthConnectStartResult, l as UsersListAuthLinksResult, o as UsersGitHubAuthorizePollResult, p as ChatAccountSelection, r as UsersAuthConnectCatalogResult, s as UsersGitHubAuthorizeStartResult, t as PersonalGitHubStatus, u as UsersListModelAccountsResult } from "./users-z8oBo6fW.js";
import { a as buildAgentSessionKey, l as ChatType, n as ResolvedAgentRoute, r as RoutePeer, s as resolveAgentRoute } from "./resolve-route-CyfWwioX.js";
import { a as GatewayClientMode, i as GatewayClientInfo, n as GatewayClientCap, o as GatewayClientName, t as GATEWAY_CLIENT_IDS } from "./client-info-BPGPL-OC.js";
import { i as ModelFallbackRouteResolution, n as ModelFallbackAttemptProvenance, o as ProviderModelRef, r as ModelFallbackAvailability, s as FailoverReason, t as FallbackAttempt } from "./model-fallback.types-DksCI2kd.js";
import { n as GithubPublicationRequests, r as GithubRepositoryPublicationRequests, t as DB$1 } from "./openclaw-state-db.generated-DeSaYzMz.js";
import { n as RuntimeEnv } from "./runtime-M_jncu14.js";
import { r as LogLevel, t as SubsystemLogger } from "./subsystem-RmDRaRJV.js";
import "./gateway-lock-payload-CHvO7eLi.js";
import { t as PluginJsonValue } from "./host-hook-json-C_dpw1uX.js";
import { a as SpawnResult, i as runCommandWithTimeout, r as CommandOptions, t as GatewayOwnerSupervisor } from "./gateway-owner-lease.types-9fXIFlAo.js";
import { a as ProviderResolveModelRoutesContext, i as ProviderModelRouteSource, n as ProviderModelRouteAuthRequirement, o as ProviderRouteOverridePresence, r as ProviderModelRouteRuntimePolicy, s as ProviderToolSearchPolicyContext, t as ProviderFastModePolicyContext } from "./provider-model-types-Cb04uFR6.js";
import { B as EmbeddedAgentExecutionPhase, C as DiagnosticEventMetadata, E as DiagnosticTraceContext, S as SessionEventRowsResetCause, T as InternalDiagnosticEventInterest, V as EmbeddedAgentExecutionPhaseInfo, b as GatewayWsPresenceMode, c as DiagnosticToolTerminalReason, l as TrustedToolExecutionEvent, n as DiagnosticEventPayload, r as DiagnosticEventPrivateData, t as DiagnosticEventInput, x as GatewayWsSessionEventAttribution, z as TalkTransport } from "./diagnostic-events-8AWE4yor.js";
import { c as ConversationRef, d as SessionBindingInspection, f as SessionBindingRecord, n as inspectSessionBindingByConversation } from "./session-binding-service-Du2yMZIY.js";
import { i as SsrFPolicy, n as PinnedDispatcherPolicy, t as LookupFn } from "./ssrf-C2_EXt4_.js";
import { f as resizeToJpeg, l as getImageMetadata, n as loadWebMedia, p as OutboundMediaAccess } from "./web-media-BOR_fUo8.js";
import { g as PollInput } from "./channel-actions-D-HbkrZm.js";
import { t as PluginServiceSchedulerV1 } from "./service-scheduler.types-BeqzszjJ.js";
import { t as PluginOrigin$1 } from "./plugin-origin.types-DOQEvsWL.js";
import { d as RuntimeWebFetchMetadata, f as RuntimeWebSearchMetadata, n as SecretDefaults, t as ResolverContext } from "./runtime-shared-bHq670Ua.js";
import { n as SecretTargetRegistryEntry } from "./target-registry-types-0AZ3Y_A_.js";
import { n as ChannelRuntimeContextRegistry, r as ChannelRuntimeSurface } from "./channel-runtime-surface.types-W_EoSebH.js";
import { f as OperatorScope, n as CallGatewayOptions, u as ResolvedGatewayAuth } from "./database-port-recovery-C5l9sEpd.js";
import { a as RemoteIngressPrincipalSnapshot, c as CachedGitHubIdentity, d as GatewayAccessGrantRef, f as PluginGatewayAccessPolicy, i as RemoteControlUiIngressContext, l as UserChannelAuthorizationReference, n as GatewayAuthenticatedUserProfile, o as GatewayOperatorRoleActor, r as GatewayWsBrowserOrigin, s as GatewayOperatorAccessAuthority, u as UserProfileIdentity } from "./origin-check-BdZY8ms1.js";
import { a as SkillInstallSpec, c as SkillTelemetrySource, d as Skill, f as PathMetadata, l as SkillUsagePath, n as SkillCommandSpec, p as SourceInfo, r as SkillEligibilityContext, s as SkillSnapshot, t as ExplicitSkillSelection } from "./types-CeA70ktN.js";
import { m as PostgresCatalogFact } from "./contract-BaQPdJAR.js";
import { g as resolveDebugProxySettings, h as createDebugProxyWebSocketAgent, i as captureWsEventAsync, r as captureWsEvent } from "./runtime-BMU6Oxl1.js";
import { _ as ImageGenerationProvider, c as VideoGenerationNormalization, d as VideoGenerationResult, f as MusicGenerationIgnoredOverride, g as MusicGenerationResult, h as MusicGenerationRequest, l as VideoGenerationProvider, m as MusicGenerationProvider, n as GenerateImageRuntimeResult, p as MusicGenerationNormalization, r as ProviderAuthEvidence, s as VideoGenerationIgnoredOverride, t as GenerateImageParams, u as VideoGenerationRequest } from "./runtime-types-BL44BFKE.js";
import "./websocket-DbnFnlN8.js";
import "./fs-safe-BPOkJ4aN.js";
import { c as ComputerUseCapabilityDescriptor, u as ComputerUseV2ActionName } from "./computer-use-contract-CCaN2ZvQ.js";
import { r as GatewayControlUiIngressFactoryV2 } from "./gateway-ingress.types-DxDLpuun.js";
import { f as resolveDefaultModelForAgent, g as ProviderDefaultThinkingPolicyContext, h as ProviderRuntimeModel, m as resolveThinkingProfile, n as DEFAULT_PROVIDER, p as listThinkingLevelOptions, s as resolveAllowedModelRefCore, t as DEFAULT_MODEL, v as ProviderThinkingProfile, y as ProviderThinkingRegistry } from "./defaults-CrnmaOmj.js";
import { t as ConfigReplaceResult, u as ConfigWriteAfterWrite, v as ConfigMutationBase } from "./config-CqQp4yQQ.js";
import { n as ModelCatalogSnapshot, r as ProviderCatalogOutcome, t as ModelCatalogEntry } from "./model-catalog.types-Bf7KSKw2.js";
import { u as ParsedAgentSessionKey } from "./session-key-CXlXkZeh.js";
import { i as ControlUiLinkReaderMetadata } from "./control-ui-link-reader-BiOt0FiZ.js";
import { i as NormalizePluginId, n as PluginActivationSource } from "./config-activation-shared-CGoAF7ye.js";
import { D as warn, T as shouldLogVerbose, v as RetryConfig, y as RetryOptions } from "./runtime-env-BGr10jK3.js";
import "./unhandled-rejections-wpUvkHsZ.js";
import "./utils-DhaCU8ER.js";
import { c as tryReadSecretFileSync } from "./secret-file-BjgdNcOT.js";
import { n as createInboundDebouncer, r as resolveInboundDebounceMs, t as InboundDebounceCreateParams } from "./inbound-debounce-D4STcP-n.js";
import { c as EnvelopeFormatOptions, f as resolveEnvelopeFormatOptions, l as formatAgentEnvelope } from "./envelope-5arWV_F8.js";
import { p as shouldHandleTextCommands } from "./commands-registry-5ugDBX7A.js";
import { C as shouldAckReaction, D as resolveHumanDelayConfig, E as resolveEffectiveMessagesConfig, S as removeAckReactionHandleAfterReply, T as resolveAgentIdentity, b as createAckReactionHandle, x as removeAckReactionAfterReply } from "./channel-feedback-iUi8ykpr.js";
import "./channel-config-schema-h9aIqGvP.js";
import { n as deleteMediaBuffer, s as saveMediaBuffer, t as SavedMedia } from "./store-uaGfvn-F.js";
import { t as detectMime } from "./mime-plQ6dJaD.js";
import "./local-roots-BOPSbeC9.js";
import "./agent-media-payload-THIeWgy5.js";
import { n as EmbeddingBatchOptions, r as EmbeddingProviderBatchRuntime, t as EmbeddingBatchChunk } from "./embedding-provider-runtime-types-DcOAns-d.js";
import { i as resolveOpenProviderRuntimeGroupPolicy } from "./runtime-group-policy-Cp-csLMc.js";
import { n as NodeWorkerBundleStatus, r as NodeHostStats, t as NodeListNode } from "./node-list-types-CrNM-VCL.js";
import { r as OpenClawPluginNodeWorkspace, t as OpenClawPluginNodeHostCommand } from "./types.node-host-d-nVUXWy.js";
import { n as createDeferredCore, t as Deferred } from "./deferred-C11zMw8s.js";
import { i as shouldComputeCommandAuthorized, r as isControlCommandMessage, t as hasControlCommand } from "./command-detection-BWIU2WBD.js";
import { t as convertMarkdownTables } from "./tables-BAppoNmX.js";
import { ZodTypeAny, z, z as z$1 } from "zod";
import { Static, TSchema, Type as Type$1 } from "typebox";
import { MessagePort, Transferable } from "node:worker_threads";
import { DatabaseSync } from "node:sqlite";
import { ColumnType, Expression, Insertable, Kysely, RawBuilder, Selectable, SqlBool } from "kysely";
import { Dispatcher } from "undici";
import "@openclaw/fs-safe/advanced";
import { Root } from "@openclaw/fs-safe/root";
import { Client } from "pg";
import { TlsOptions } from "node:tls";
import { WebSocket } from "ws";
import "@openclaw/fs-safe/path";
import { IncomingMessage, Server, ServerResponse } from "node:http";
import { AutocompleteItem, AutocompleteProvider, Component, EditorComponent, EditorTheme, KeyId, KeybindingsConfig, KeybindingsManager, OverlayHandle, OverlayOptions, TUI } from "@earendil-works/pi-tui";
import "@openclaw/ai";
import "@openclaw/ai/internal/runtime";
import "@openclaw/ai/internal/shared";
import "typebox/error";
import "@modelcontextprotocol/client";
import { Chat, ChatFullInfo, InputRichMessage, Message, User, UserFromGetMe } from "grammy/types";
import { Bot } from "grammy";
import { CallToolResult, GetPromptResult, ListResourceTemplatesResult, ListToolsResult } from "@modelcontextprotocol/sdk/types.js";
import { RuntimeToolInputSchemaJson, RuntimeToolInputSchemaProjection, projectRuntimeToolInputSchema } from "@openclaw/ai/internal/tool-schema";
import "minimatch";
import "@openclaw/ai/internal/openai";
import "@openclaw/ai/internal/model-request-body";
import { Duplex, Readable } from "node:stream";
import { Command } from "commander";
import "@agentclientprotocol/sdk";
//#endregion
//#region src/config/sessions/paths.d.ts
declare function resolveSessionTranscriptsDirForAgent(agentId: string, env?: NodeJS.ProcessEnv, homedir?: () => string): string;
declare class SessionStoreAgentIdRequiredError extends Error {
  constructor();
}
/** Resolves fixed literal paths without an owner; derived or templated paths require agentId. */
declare function resolveSessionStorePathCore(store?: string, opts?: {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
}): string;
//#endregion
//#region src/config/gateway-public-origin.d.ts
declare function resolveGatewayPublicOrigin(config: Pick<OpenClawConfig, "gateway"> | null | undefined): string | undefined;
//#endregion
//#region src/config/channel-groups.d.ts
type ChannelGroupConfig = Pick<CommonChannelGroupConfig, "requireMention" | "tools" | "toolsBySender"> & {
  requireMentionInBotThreads?: boolean;
  ingest?: boolean;
};
type ChannelGroups = Record<string, ChannelGroupConfig>;
declare function resolveChannelGroups(cfg: OpenClawConfig, channel: ChannelId$1, accountId?: string | null): ChannelGroups | undefined;
//#endregion
//#region src/config/tools-by-sender.d.ts
type GroupToolPolicySender = {
  /** Skip sender-specific overlays for trusted non-ingress executions. */
  senderPolicyMode?: "always" | "never";
  messageProvider?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
};
declare function resolveToolsBySender(params: {
  toolsBySender?: GroupToolPolicyBySenderConfig;
} & GroupToolPolicySender): GroupToolPolicyConfig | undefined;
//#endregion
//#region src/config/group-policy.d.ts
type ChannelGroupPolicy = {
  allowlistEnabled: boolean;
  allowed: boolean;
  groupConfig?: ChannelGroupConfig;
  defaultConfig?: ChannelGroupConfig;
};
/** Locate the authored map selected by the channel owner without changing its inheritance rules. */
declare function resolveChannelGroupsConfigPath(params: {
  cfg: OpenClawConfig;
  channel: ChannelId$1;
  accountId?: string | null;
  groups: Readonly<Record<string, unknown>> | undefined;
}): string;
declare function resolveChannelGroupPolicy(params: {
  cfg: OpenClawConfig;
  channel: ChannelId$1;
  groupId?: string | null;
  accountId?: string | null;
  groupIdCaseInsensitive?: boolean;
  /** When true, sender-level filtering (groupAllowFrom) is configured upstream. */
  hasGroupAllowFrom?: boolean;
}): ChannelGroupPolicy;
declare function resolveChannelGroupRequireMention(params: {
  cfg: OpenClawConfig;
  channel: ChannelId$1;
  groupId?: string | null;
  accountId?: string | null;
  groupIdCaseInsensitive?: boolean;
  requireMentionOverride?: boolean;
  configuredGroupDefaultsToNoMention?: boolean;
  overrideOrder?: "before-config" | "after-config";
}): boolean;
declare function resolveChannelGroupToolsPolicy(params: {
  cfg: OpenClawConfig;
  channel: ChannelId$1;
  groupId?: string | null;
  groupIdCandidates?: Array<string | null | undefined>;
  accountId?: string | null;
  groupIdCaseInsensitive?: boolean;
} & GroupToolPolicySender): GroupToolPolicyConfig | undefined;
//#endregion
//#region src/config/sessions/provider-review.types.d.ts
/** Runtime-authored precaution for one failed turn in this session generation. */
type SessionProviderReview = {
  id: string;
  sessionId: string;
  runId: string;
  provider: string;
  model: string;
  runtimeId: string;
  api?: string;
  review?: ProviderRefusalReview;
  nativeThreadId?: string;
  nativeTurnId?: string;
};
/** Serialized compare-and-set input shared by the store and its SQLite worker. */
type SessionProviderReviewComparison = {
  sessionKey: string;
  sessionId: string;
  lifecycleRevision?: string;
  expectedReview: Readonly<SessionProviderReview> | undefined;
  nextReview: SessionProviderReview | undefined;
};
//#endregion
//#region src/config/sessions/activity-summary.d.ts
declare const ActivitySummarySchema: z.ZodObject<{
  version: z.ZodLiteral<1>;
  formatRevision: z.ZodOptional<z.ZodNumber>;
  text: z.ZodString;
  updatedAt: z.ZodNumber;
  sessionId: z.ZodString;
  lifecycleRevision: z.ZodOptional<z.ZodString>;
  generation: z.ZodNullable<z.ZodString>;
  maxSeq: z.ZodNullable<z.ZodNumber>;
  leafEntryId: z.ZodNullable<z.ZodString>;
  coveredMessages: z.ZodNumber;
  totalMessages: z.ZodNumber;
  omittedContent: z.ZodBoolean;
}, z.core.$strip>;
type SessionActivitySummary = z.infer<typeof ActivitySummarySchema>;
//#endregion
//#region src/security/external-content-source.d.ts
/** Hook session sources that carry untrusted external content into agent prompts. */
type HookExternalContentSource = "email" | "gmail" | "webhook";
//#endregion
//#region src/config/sessions/session-entry-provenance.d.ts
/** Persisted identity excludes display-only actor projections. */
type SessionActor$1 = SchemaContract<Pick<SessionCreatedActor$1, "type" | "id" | "label">>;
/** Causal creator attribution; the enclosing actor stays the legacy isolation identity. */
type DelegatedSessionCreator = {
  type: "human";
  source: "profile";
  id: string;
} | {
  type: "agent";
  id?: string;
};
/** Only trusted creation owners may stamp Gateway profile namespaces. */
type SessionCreatedActor = SessionActor$1 & ({
  type: "human";
  source: "profile" | "channel" | "unknown";
} | {
  type: "agent" | "system";
}) & {
  delegatedBy?: DelegatedSessionCreator;
};
type SessionOwnerAssignment = {
  actor: SessionActor$1;
  assignedBy?: SessionActor$1;
  assignedAt?: number;
};
type SessionCreatedVia = NonNullable<SessionRow["createdVia"]>;
declare function buildSessionCreationStamp(params: {
  via: SessionCreatedVia;
  surface?: "plugin-dock";
  actor?: SessionCreatedActor;
  now?: number;
  sandbox?: "required";
  incognito?: boolean;
  skillLibrarySelections?: SkillLibrarySelection[];
  inheritedGitContributorProfileIds?: string[];
}): {
  createdVia: SessionCreatedVia;
  createdSurface?: "plugin-dock";
  createdActor?: SessionCreatedActor;
  createdAt: number;
  sandbox?: "required";
  skillLibrarySelections?: SkillLibrarySelection[];
  inheritedGitContributorProfileIds?: string[];
};
type SessionEntryProvenance = {
  /** Human contributor candidates captured once by trusted delegation; not participant activity. */
  inheritedGitContributorProfileIds?: string[];
  /** Plugin id that owns this session through a trusted runtime creation seam. */
  pluginOwnerId?: string;
  /** External hook source that has contributed content to this transcript. */
  hookExternalContentSource?: HookExternalContentSource;
};
//#endregion
//#region src/sessions/transcript-events.d.ts
/** Storage-neutral identity for the session transcript that changed. */
type SessionTranscriptUpdateTarget = {
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath?: string;
};
/** Internal transcript update that may identify a transcript without a file path. */
type InternalSessionTranscriptUpdate = {
  sessionFile?: string;
  target?: SessionTranscriptUpdateTarget;
  sessionKey?: string;
  agentId?: string;
  sessionId?: string;
  /** Committed lifecycle owner; internal delivery must not expose it publicly. */
  lifecycleRevision?: string;
  message?: unknown;
  messageId?: string;
  messageSeq?: number;
  runId?: string;
  /** Exact native display occurrences retired by this commit; never run authority. */
  assistantItemIds?: readonly string[];
};
type SessionTranscriptUpdate = Omit<InternalSessionTranscriptUpdate, "sessionFile" | "lifecycleRevision" | "target" | "assistantItemIds"> & {
  target: Omit<SessionTranscriptUpdateTarget, "storePath">;
};
type SessionTranscriptListener = (update: SessionTranscriptUpdate) => void;
type InternalSessionTranscriptListener = (update: InternalSessionTranscriptUpdate) => void;
declare function onSessionTranscriptUpdate(listener: SessionTranscriptListener): () => void;
declare function onInternalSessionTranscriptUpdate(listener: InternalSessionTranscriptListener): () => void;
//#endregion
//#region src/state/openclaw-agent-db-contract.d.ts
type OpenClawAgentDatabase = {
  agentId: string;
  db: EngineConnection;
  path: string;
  walMaintenance: SqliteWalMaintenance;
};
type OpenClawAgentDatabaseOptions = OpenClawStateDatabaseOptions & {
  agentId: string;
};
/** Internal Doctor custody; never part of the plugin-facing database options. */
type OpenClawAgentDatabaseRepairAdmission = {
  /** Doctor's requested SQLite coverage; ordinary runtime admission retains FULL. */
  integrityCheck?: "quick" | "full";
  /** Tables this repair callback mutates; pending schema migrations retain their own coverage. */
  integrityTables?: readonly string[];
  /** Bind repair admission to the physical database inspected and backed up by its owner. */
  expectedIdentity?: DatabaseFileIdentity;
  /** Live caller authority for native open and schema/registry admission mutations. */
  assertCurrent?: () => void;
};
/** Shared-state registry row describing an agent database seen by this process. */
type OpenClawRegisteredAgentDatabase = {
  agentId: string;
  path: string;
  schemaVersion: number;
  lastSeenAt: number;
  sizeBytes: number | null;
};
/** An in-process witness from the canonical invalidator, never serialized as authority. */
type AgentDatabaseRegistryChange = Readonly<{
  previous: symbol;
  current: symbol;
}>;
type OpenClawAgentDatabaseRegistrationCommit = Readonly<{
  agentId: string;
  agentPath: string;
  stateDatabasePath: string;
  stateDatabaseIdentity: string;
}>;
type OpenClawAgentDatabaseRegistrationObserver = {
  starting?: () => void;
  committed?: (receipt: OpenClawAgentDatabaseRegistrationCommit) => void;
};
//#endregion
//#region src/state/openclaw-agent-execution-admission-contract.d.ts
/** A borrowed native generation, never a file locator that can adopt a later open. */
type AgentDatabaseGenerationClaim = {
  readonly identity: string;
  readonly incarnation: string;
  assertCurrent(): void;
};
/** A request owner composes its retained admission with the native owner's validation. */
type AgentDatabaseRequestExecutionSource = {
  assertCurrent(): void;
  onRegistryChange?: (change: AgentDatabaseRegistryChange) => void;
  createAdmission(params: {
    attachment: {
      kind: "agent-execution";
      startupJournal: boolean;
    };
    nativeLocations: readonly string[];
    authorize(request: SqliteWorkerAdmissionRequest): void;
    assertCurrent(): void;
  }): SqliteWorkerAdmissionFactory;
};
type OpenClawAgentDatabaseAdmissionExecution = {
  readonly agentId: string;
  readonly path: string;
  assertCurrent(): void;
  captureGenerationClaim(): AgentDatabaseGenerationClaim;
  /** Reuse the native owner's published preparation and schema proof. */
  prepare(source: AgentDatabaseRequestExecutionSource, signal?: AbortSignal): Promise<void>;
};
//#endregion
//#region src/config/sessions/goals-operations.types.d.ts
type SessionGoalOperationIdentity = {
  operationId: string;
  issuedAtMs: number;
  /** Hash of the complete immutable request, including the requested session generation. */
  requestFingerprint: string;
};
type SessionGoalOperation = SessionGoalOperationIdentity & ({
  action: "start";
  objective: string;
  tokenBudget?: number;
} | {
  action: "edit";
  goalId: string;
  objective: string;
} |
/** Internal completed-interruption receipt; preserves the Goal unchanged. */
{
  action: "replace";
  goalId: string;
  expectedRunId: string;
} | {
  action: "resume";
  goalId: string;
  note?: string;
  preserveBudget?: true;
  /** Receipt-derived postimage, checked by the continuation writer before its own transition. */
  replacementSource?: {
    runId: string;
    goal: SessionGoal;
  };
} | {
  action: "pause" | "block" | "complete";
  goalId: string;
  note?: string;
} | {
  action: "clear";
  goalId: string;
});
type SessionGoalOperationResult = Omit<SessionsGoalMutationResult, "replayed">;
declare const SESSION_GOAL_OPERATION_ERROR_CODES: readonly ["expired", "operation-conflict", "session-rebound", "goal-rebound", "capacity", "receipt-invalid", "invalid"];
type SessionGoalOperationErrorCode = (typeof SESSION_GOAL_OPERATION_ERROR_CODES)[number];
type SessionGoalOperationLookup = {
  sessionKey: string;
  expectedSessionId: string;
  operation: SessionGoalOperation;
};
/** Closed session mutation admitted together with its transcript and lifecycle state. */
type SessionTranscriptTurnMutation = {
  kind: "goal";
  /** Private live authority; never serialized into operation fingerprints or receipts. */
  assertCurrent?: () => void;
  routingPredicate?: {
    config: OpenClawConfig;
    key: string;
    agentId: string;
    storePath: string;
    canonicalKey: string;
  };
  operation: SessionGoalOperation & {
    action: "start" | "resume";
  };
  runId: string;
};
type SessionTranscriptTurnMutationResult = {
  result: SessionGoalOperationResult;
  replayed: boolean;
};
type SessionGoalManagementInput = {
  sessionKey: string;
  expectedSessionId: string;
  operation: Exclude<SessionGoalOperation, {
    action: "start";
  }> & {
    action: "edit" | "replace" | "pause" | "block" | "complete" | "clear";
  };
};
type SessionGoalManagementCommit = SessionTranscriptTurnMutationResult & {
  sessionEntry?: SessionEntry;
  previous?: SessionEntry;
};
//#endregion
//#region src/state/openclaw-agent-db-identity.d.ts
type OpenClawAgentDatabaseIdentity = string;
//#endregion
//#region src/channels/inbound-event/kind.d.ts
type InboundEventKind = "user_request" | "room_event";
//#endregion
//#region src/gateway/ui-command-target.types.d.ts
/** Presentation destination captured from the requesting Control UI, never model arguments. */
type GatewayUiCommandTarget = Readonly<{
  connId: string;
  profileId?: string;
}>;
//#endregion
//#region src/media/prompt-image-order.d.ts
/** Tracks whether prompt images stayed inline or were offloaded while preserving model order. */
type PromptImageOrderEntry = "inline" | "offloaded";
//#endregion
//#region src/plugins/hook-channel-context.types.d.ts
interface PluginHookChannelSenderContext {
  /** Channel-scoped sender ID, matching `ctx.senderId` when both are present. */
  id?: string;
  [key: string]: unknown;
}
interface PluginHookChannelChatContext {
  /** Transport-native conversation ID, matching `ctx.chatId` when both are present. */
  id?: string;
  [key: string]: unknown;
}
interface PluginHookChannelContext {
  /** Sender metadata supplied by the originating channel. */
  sender?: PluginHookChannelSenderContext;
  /** Chat/conversation metadata supplied by the originating channel. */
  chat?: PluginHookChannelChatContext;
}
//#endregion
//#region src/sessions/input-provenance.d.ts
declare const INPUT_PROVENANCE_KIND_VALUES: readonly ["external_user", "inter_session", "internal_system"];
type InputProvenanceKind = (typeof INPUT_PROVENANCE_KIND_VALUES)[number];
type InputProvenance = {
  kind: InputProvenanceKind;
  originSessionId?: string;
  sourceSessionKey?: string;
  sourceChannel?: string;
  sourceTool?: string;
  sourceRole?: "subagent";
  sourcePromptPrefix?: string;
  jobId?: string;
  runId?: string;
};
//#endregion
//#region src/auto-reply/command-turn-context.d.ts
type CommandTurnKind = "native" | "text-slash" | "normal";
/** Transport-level source labels carried through auto-reply dispatch. */
type CommandTurnSource = "native" | "text" | "message";
type CommandTurnContext = {
  commandName?: string;
  body?: string;
} & ({
  kind: "native";
  source: "native";
  authorized: boolean;
} | {
  kind: "text-slash";
  source: "text";
  authorized: boolean;
} | {
  kind: "normal";
  source: "message";
  authorized: false;
});
/** Builds a normalized command-turn context and forces normal messages to unauthorized. */
declare function createCommandTurnContext(source: CommandTurnSource, input: {
  authorized: boolean;
  commandName?: string;
  body?: string;
}): CommandTurnContext;
/** Returns true for channel-native command turns. */
declare function isNativeCommandTurn(commandTurn: CommandTurnContext | undefined): boolean;
/** Returns true for text slash-command turns regardless of authorization. */
declare function isTextSlashCommandTurn(commandTurn: CommandTurnContext | undefined): boolean;
declare function isAuthorizedTextSlashCommandTurn(commandTurn: CommandTurnContext | undefined): boolean;
/** Returns true when a turn was explicitly invoked by a native or authorized text command. */
declare function isExplicitCommandTurn(commandTurn: CommandTurnContext | undefined): boolean;
//#endregion
//#region src/auto-reply/group-thread.types.d.ts
type ResolvedGroupThreadConfig = {
  agents: string[];
  unknownAgentIds: string[];
  qualified: boolean;
  configuredAgentCount: number;
  mentionGating: boolean;
  maxRounds: number;
  maxTurns: number;
  strategy: BroadcastStrategy;
};
type GroupThreadMentionFacts = {
  channel: string;
  peerId: string;
  group: ResolvedGroupThreadConfig;
  mentionedAgentIds: string[];
};
//#endregion
//#region src/sessions/provider-review.d.ts
type ProviderReviewTarget = {
  agentId: string;
  storePath: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision?: string;
};
declare const acknowledgmentBrand: unique symbol;
/** Host-issued capability; serialized request metadata cannot create one. */
interface ProviderReviewAcknowledgment {
  readonly [acknowledgmentBrand]: true;
  readonly read: () => Readonly<{
    review: Readonly<SessionProviderReview>;
    phase: "pending" | "accepted";
  }>;
  readonly assertRuntime: (runtime: {
    provider: string;
    model: string;
    runtimeId: string;
    api?: string;
    assertCurrent: () => void;
  }) => Promise<void>;
  readonly acceptNativeTurn: (accepted: {
    nativeThreadId: string;
    nativeTurnId: string;
    assertCurrent: () => void;
  }) => Promise<void>;
}
//#endregion
//#region packages/normalization-core/src/agent-run-terminal-outcome.d.ts
declare const AGENT_RUN_ABORTED_STOP_REASON: "aborted";
declare const AGENT_RUN_RESTART_ABORT_STOP_REASON: "restart";
declare const AGENT_RUN_SUPERSEDED_STOP_REASON: "superseded";
declare const AGENT_RUN_TIMEOUT_PHASES: readonly ["queue", "preflight", "provider", "tool_execution", "post_turn", "gateway_draining"];
type AgentRunTimeoutPhase = (typeof AGENT_RUN_TIMEOUT_PHASES)[number];
type AgentRunWaitStatus = "ok" | "error" | "timeout";
type AgentRunTerminalReason = "completed" | "hard_timeout" | "timed_out" | "superseded" | "cancelled" | "aborted" | "blocked" | "abandoned" | "failed";
type AgentRunTerminalFacts = {
  reason: AgentRunTerminalReason;
  status: AgentRunWaitStatus;
  stopReason?: string;
  livenessState?: string;
  timeoutPhase?: AgentRunTimeoutPhase;
  providerStarted?: boolean;
};
//#endregion
//#region src/agents/agent-run-terminal-outcome.types.d.ts
type AgentRunTerminalOutcome$1 = AgentRunTerminalFacts & {
  error?: string;
  startedAt?: number;
  endedAt?: number;
};
//#endregion
//#region src/agents/agent-run-terminal-outcome.d.ts
type AgentRunAttemptFailureSource = "prompt" | "compaction" | "precheck" | "hook:before_agent_run";
type AgentRunAttemptFailure = {
  source: AgentRunAttemptFailureSource;
  error: unknown;
};
type AgentRunAttemptTimeoutObservation = "compaction" | "tool_execution";
type AgentRunAttemptTimeoutSource = "runtime" | "run_budget" | "idle" | "external";
type AgentRunAttemptSettlementWarning = {
  pendingStage: string;
  elapsedMs: number;
  timeoutMs: number;
};
type AgentRunAttemptTerminal = {
  kind: "ok";
  settlementWarning?: AgentRunAttemptSettlementWarning;
} | {
  kind: "aborted";
  source: "runtime" | "external" | "yield_cleanup";
  failure?: AgentRunAttemptFailure;
  timeoutObservation?: AgentRunAttemptTimeoutObservation;
} | {
  kind: "timeout";
  /** Non-terminal observations preserve timeout detail without interrupting the attempt. */
  phase: AgentRunAttemptTimeoutObservation;
  source: "observation";
  failure?: AgentRunAttemptFailure;
} | {
  kind: "timeout";
  phase: "prompt" | AgentRunAttemptTimeoutObservation;
  source: AgentRunAttemptTimeoutSource;
  /** Present only when timeout handling also aborted the live harness run. */
  aborted?: true;
  failure?: AgentRunAttemptFailure;
} | {
  kind: "failed";
  source: AgentRunAttemptFailureSource;
  error: unknown;
  timeoutObservation?: AgentRunAttemptTimeoutObservation;
};
type LegacyAgentRunAttemptTerminalInput = {
  settlementWarning?: AgentRunAttemptSettlementWarning;
  aborted?: boolean;
  externalAbort?: boolean;
  idleTimedOut?: boolean;
  promptError?: unknown;
  promptErrorSource?: AgentRunAttemptFailureSource | null;
  timedOut?: boolean;
  timedOutByRunBudget?: boolean;
  timedOutDuringCompaction?: boolean;
  timedOutDuringToolExecution?: boolean;
};
/** Replaces attempt failure detail without changing a stronger interruption. */
declare function setAgentRunAttemptTerminalFailure(terminal: AgentRunAttemptTerminal, failure: AgentRunAttemptFailure | null): AgentRunAttemptTerminal;
/** Merges attempt observations while keeping terminal precedence in one owner. */
declare function mergeAgentRunAttemptTerminal(current: AgentRunAttemptTerminal, incoming: AgentRunAttemptTerminal): AgentRunAttemptTerminal;
/** Normalizes the shipped harness result shape at the Plugin SDK boundary. */
declare function normalizeAgentRunAttemptTerminal(input: LegacyAgentRunAttemptTerminalInput): AgentRunAttemptTerminal;
/** Projects the closed attempt terminal into legacy event/meta fields. */
declare function projectAgentRunAttemptTerminal(terminal: AgentRunAttemptTerminal): {
  settlementWarning?: AgentRunAttemptSettlementWarning | undefined;
  aborted: boolean;
  cleanupYieldAborted: boolean;
  externalAbort: boolean;
  failed: boolean;
  idleTimedOut: boolean;
  interrupted: boolean;
  promptError: unknown;
  promptErrorSource: AgentRunAttemptFailureSource | null;
  timedOut: boolean;
  timedOutByRunBudget: boolean;
  timedOutDuringCompaction: boolean;
  timedOutDuringToolExecution: boolean;
};
//#endregion
//#region src/audit/execution-identity-admission.d.ts
declare const ExecutionIdentityAdmissionEnvelopeSchema: Type$1.TObject<{
  envelopeVersion: Type$1.TLiteral<1>;
  contextId: Type$1.TString;
  executionId: Type$1.TString;
  runId: Type$1.TString;
  createdAt: Type$1.TInteger;
  runtimeInstanceId: Type$1.TString;
  agentId: Type$1.TString;
  ingress: Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"local-cli">, Type$1.TLiteral<"gateway-client">, Type$1.TLiteral<"channel">, Type$1.TLiteral<"api">, Type$1.TLiteral<"schedule">, Type$1.TLiteral<"webhook">, Type$1.TLiteral<"task">, Type$1.TLiteral<"subagent">, Type$1.TLiteral<"acp">, Type$1.TLiteral<"worker">, Type$1.TLiteral<"plugin">, Type$1.TLiteral<"recovery">, Type$1.TLiteral<"system">]>;
    boundary: Type$1.TString;
    state: Type$1.TUnion<[Type$1.TLiteral<"present">, Type$1.TLiteral<"absent">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"unsupported">]>;
    rawSourceRef: Type$1.TOptional<Type$1.TString>;
  }>;
  runtime: Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"gateway">, Type$1.TLiteral<"embedded">, Type$1.TLiteral<"worker">, Type$1.TLiteral<"plugin-harness">, Type$1.TLiteral<"acp">]>;
  }>;
  invoker: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    state: Type$1.TLiteral<"present">;
    kind: Type$1.TUnion<[Type$1.TLiteral<"person">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"service">, Type$1.TLiteral<"schedule">, Type$1.TLiteral<"webhook">, Type$1.TLiteral<"system">, Type$1.TLiteral<"local-account">, Type$1.TLiteral<"runtime">]>;
    rawPrincipalRef: Type$1.TString;
    displayLabel: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    state: Type$1.TLiteral<"unknown">;
  }>]>>;
  representedSubject: Type$1.TOptional<Type$1.TObject<{
    state: Type$1.TLiteral<"present">;
    kind: Type$1.TLiteral<"person">;
    rawPrincipalRef: Type$1.TString;
  }>>;
  applicableGrants: Type$1.TArray<Type$1.TObject<{
    rawGrantRef: Type$1.TString;
    state: Type$1.TUnion<[Type$1.TLiteral<"present">, Type$1.TLiteral<"absent">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"unsupported">]>;
  }>>;
  assurance: Type$1.TArray<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"durable-profile">, Type$1.TLiteral<"trusted-proxy">, Type$1.TLiteral<"tailscale-whois">, Type$1.TLiteral<"device-proof">, Type$1.TLiteral<"channel-admission">, Type$1.TLiteral<"local-process">, Type$1.TLiteral<"spawn-lineage">, Type$1.TLiteral<"worker-admission">, Type$1.TLiteral<"runtime-binding">, Type$1.TLiteral<"other">]>;
    rawEvidenceRef: Type$1.TString;
    strength: Type$1.TUnion<[Type$1.TLiteral<"self-asserted">, Type$1.TLiteral<"boundary-verified">, Type$1.TLiteral<"cryptographic">]>;
  }>>;
}>;
declare const ExecutionIdentityAdmissionTokenSchema: Type$1.TObject<{
  tokenVersion: Type$1.TLiteral<1>;
  contextId: Type$1.TString;
  executionId: Type$1.TString;
  runId: Type$1.TString;
  createdAt: Type$1.TInteger;
}>;
type ExecutionIdentityAdmissionEnvelope = Static<typeof ExecutionIdentityAdmissionEnvelopeSchema>;
type ExecutionIdentityAdmissionFacts = Omit<ExecutionIdentityAdmissionEnvelope, "envelopeVersion" | "contextId" | "executionId" | "createdAt" | "runtimeInstanceId" | "ingress" | "applicableGrants" | "assurance"> & {
  ingress: Omit<ExecutionIdentityAdmissionEnvelope["ingress"], "state"> & {
    state?: ExecutionIdentityAdmissionEnvelope["ingress"]["state"];
  };
  applicableGrants?: ExecutionIdentityAdmissionEnvelope["applicableGrants"];
  assurance?: ExecutionIdentityAdmissionEnvelope["assurance"];
};
type ExecutionIdentityAdmissionToken = Static<typeof ExecutionIdentityAdmissionTokenSchema>;
//#endregion
//#region src/channels/progress-draft-diffstat.d.ts
type ChannelProgressDraftDiffStat = Readonly<{
  files: number;
  added: number;
  removed: number;
}>;
declare function formatChannelProgressDraftDiffStat(diffStat: ChannelProgressDraftDiffStat | undefined): string | undefined;
//#endregion
//#region src/channels/progress-draft-lines.d.ts
type ChannelProgressDraftLine = {
  /** Stable line id used to update an existing progress line in place. */
  id?: string;
  kind: "tool" | "item" | "plan" | "approval" | "command-output" | "patch" | "operation-status" | "subagent-status";
  /** Rendered line text before final draft truncation/prefix formatting. */
  text: string;
  label: string;
  icon?: string;
  detail?: string;
  /** Optional lifecycle status, such as completed or exit code. */
  status?: string;
  /** Completion metadata for authored text; never rendered as a tool status. */
  complete?: boolean;
  /** Normalized tool name when the line represents tool work. */
  toolName?: string;
  /** Whether final formatting should add a bullet/line prefix. */
  prefix?: boolean;
};
/** Approvals and failures that can start a draft when their rows are visible. */
declare function isChannelProgressAttentionLine(line: string | ChannelProgressDraftLine): boolean;
//#endregion
//#region src/channels/streaming.d.ts
declare function isChannelProgressDraftWorkToolName(name: string | null | undefined): boolean;
type ChannelProgressLineOptions = {
  /** Whether generated tool details should use Markdown formatting. */
  markdown?: boolean;
  /** Detail shape for tool arguments shown in progress drafts. */
  detailMode?: "explain" | "raw";
  /** Whether command progress should show raw command text or status-only copy. */
  commandText?: ChannelStreamingCommandTextMode;
  /** Prefix tool rows with their text glyph; channels opt in, default plain. */
  toolIcons?: boolean;
};
type AgentPlanStepStatus = "pending" | "in_progress" | "completed";
type AgentPlanStep = {
  step: string;
  status: AgentPlanStepStatus;
};
type AgentPlanStepInput = AgentPlanStep | string;
/**
 * TODO(remove): normalizes the pre-2026.7.2 string plan-step wire shape to
 * pending typed steps. Bundled producers all emit typed steps, and
 * @openclaw/codex is force-updated with core, so this only covers a plugin
 * pinned against an update. Delete once that cannot happen.
 */
declare function normalizeAgentPlanSteps(value: unknown): AgentPlanStep[] | undefined;
type ChannelProgressDraftLineInput = {
  event: "tool";
  itemId?: string;
  toolCallId?: string;
  name?: string;
  phase?: string;
  args?: Record<string, unknown>;
} | {
  event: "item";
  itemId?: string;
  toolCallId?: string;
  itemKind?: string;
  hideFromChannelProgress?: boolean;
  suppressChannelProgress?: boolean;
  title?: string;
  name?: string;
  phase?: string;
  status?: string;
  summary?: string;
  progressText?: string;
  meta?: string;
  commandBearing?: boolean;
} | {
  event: "plan";
  phase?: string;
  title?: string;
  explanation?: string;
  steps?: readonly AgentPlanStepInput[];
} | {
  event: "approval";
  approvalId?: string;
  phase?: string;
  title?: string;
  command?: string;
  reason?: string;
  message?: string;
} | {
  event: "command-output";
  itemId?: string;
  toolCallId?: string;
  phase?: string;
  title?: string;
  name?: string;
  status?: string;
  exitCode?: number | null;
} | {
  event: "patch";
  itemId?: string;
  toolCallId?: string;
  phase?: string;
  title?: string;
  name?: string;
  added?: string[];
  modified?: string[];
  deleted?: string[];
  summary?: string;
};
declare function formatChannelProgressDraftLine(input: ChannelProgressDraftLineInput, options?: ChannelProgressLineOptions): string | undefined;
declare function buildChannelProgressDraftLineForEntry(entry: StreamingCompatEntry | null | undefined, input: ChannelProgressDraftLineInput, options?: ChannelProgressLineOptions): ChannelProgressDraftLine | undefined;
declare function formatChannelProgressDraftLineForEntry(entry: StreamingCompatEntry | null | undefined, input: ChannelProgressDraftLineInput, options?: ChannelProgressLineOptions): string | undefined;
declare function buildChannelProgressDraftLine(input: ChannelProgressDraftLineInput, options?: ChannelProgressLineOptions): ChannelProgressDraftLine | undefined;
declare function createChannelProgressDraftGate(params: {
  onStart: () => void | Promise<void>;
  /** Delay after the first work event before a draft starts. */
  initialDelayMs?: number;
  /** Reports timer-fired startup failures, which have no awaiting caller. */
  onStartError?: (error: unknown) => void;
  setTimeoutFn?: typeof setTimeout;
  clearTimeoutFn?: typeof clearTimeout;
}): {
  readonly hasStarted: boolean;
  readonly workEvents: number;
  noteWork(): Promise<boolean>;
  startNow(): Promise<void>;
  cancel(): void;
  reset(): void;
};
declare function resolveChannelStreamingChunkMode(entry: StreamingCompatEntry | null | undefined): TextChunkMode | undefined;
declare function resolveChannelStreamingBlockEnabled(entry: StreamingCompatEntry | null | undefined): boolean | undefined;
declare function resolveChannelStreamingBlockEnabled(entry: StreamingCompatEntry | null | undefined, previewPolicy: {
  previewAvailable: boolean;
  blockStreamingDefault?: "off" | "on";
}): boolean;
declare function resolveChannelStreamingBlockCoalesce(entry: StreamingCompatEntry | null | undefined): BlockStreamingCoalesceConfig | undefined;
/**
 * The shipped SDK default keeps tool rows visible. Bundled callers pass their
 * mode-specific default so progress drafts can stay quiet.
 */
declare function resolveChannelStreamingPreviewToolProgress(entry: StreamingCompatEntry | null | undefined, defaultValue?: boolean,
/**
 * The channel's resolved stream mode. Only the caller knows it: channels pick
 * their own default when `streaming.mode` is unset (Telegram uses "progress",
 * Discord uses "off", and Slack uses "progress"), and this helper has no
 * channel identity to guess with. Omitting it reads the configured mode and
 * treats unset as "partial".
 */
mode?: StreamingMode): boolean;
declare function resolveChannelStreamingProgressCommentary(entry: StreamingCompatEntry | null | undefined, defaultValue?: boolean,
/**
 * The channel's resolved stream mode, for the same reason
 * resolveChannelStreamingPreviewToolProgress takes one: only the caller knows
 * which default applies when `streaming.mode` is unset. Guessing "partial"
 * here made `progress.commentary: true` a silent no-op on the progress-draft
 * channels, such as Telegram, whose own default is "progress".
 */
mode?: StreamingMode): boolean;
declare function resolveChannelStreamingProgressNarration(entry: StreamingCompatEntry | null | undefined, defaultValue?: boolean): boolean;
declare function resolveChannelStreamingPreviewCommandText(entry: StreamingCompatEntry | null | undefined, defaultValue?: ChannelStreamingCommandTextMode): ChannelStreamingCommandTextMode;
declare function resolveChannelStreamingSuppressDefaultToolProgressMessages(entry: StreamingCompatEntry | null | undefined, options?: {
  draftStreamActive?: boolean;
  mode?: StreamingMode;
  previewToolProgressEnabled?: boolean;
  previewStreamingEnabled?: boolean;
}): boolean;
declare function resolveChannelPreviewStreamMode(entry: StreamingCompatEntry | null | undefined, defaultMode: StreamingMode): StreamingMode;
declare function resolveChannelProgressDraftConfig(entry: StreamingCompatEntry | null | undefined): ChannelStreamingProgressConfig;
declare function resolveChannelProgressDraftMaxLines(entry: StreamingCompatEntry | null | undefined, defaultValue?: number): number;
declare function resolveChannelProgressDraftMaxLineChars(entry: StreamingCompatEntry | null | undefined, defaultValue?: number): number;
declare function compactChannelProgressDraftLine(line: string, maxChars: number): string;
declare function selectPlanChecklistSteps(steps: readonly AgentPlanStep[], options: {
  maxLines: number;
}): {
  steps: AgentPlanStep[];
  summary?: string;
};
declare function formatPlanChecklistLines(steps: readonly AgentPlanStep[], options: {
  maxLines: number;
  maxLineChars: number;
  /** @deprecated v2026.9.1 SDK option; retain until a breaking SDK release. */
  plain?: boolean;
}): string[];
declare function normalizeChannelProgressDraftLineIdentity(line: string | ChannelProgressDraftLine | undefined): string;
declare function mergeChannelProgressDraftLine<TLine extends string | ChannelProgressDraftLine>(lines: TLine[], line: TLine, params: {
  maxLines: number;
}): TLine[];
type ChannelProgressDraftTextParams = {
  /** @deprecated v2026.9.1 SDK presentation; retain until a breaking SDK release. */
  presentation?: "summary";
  /** Channel streaming config source for progress label and bounds. */
  entry?: StreamingCompatEntry | null;
  /** Ordered progress lines to render. */
  lines: Array<string | ChannelProgressDraftLine>;
  /** Stable seed used when choosing automatic progress labels. */
  seed?: string;
  /** Random source used when choosing automatic progress labels. */
  random?: () => number;
  /** Optional formatter applied after line compaction. */
  formatLine?: (line: string) => string;
  /** Literal transport encoding, applied after compaction to prepared plain text. */
  formatPlainText?: (text: string) => string;
  /** Exposes the same ordered blocks to native renderers without parsing composed text. */
  onPreparedBlocks?: (blocks: Array<{
    text: string;
    format: "plain" | "markdown";
  }>) => void;
  /** Prefix used for plain progress lines that lack their own icon. */
  bullet?: string;
  /** Status headline rendered above the plan and activity rows. */
  narration?: string;
  narrationFormat?: "plain";
  /** Latest full plan snapshot, rendered independently from rolling tool lines. */
  plan?: readonly AgentPlanStep[];
  diffStat?: ChannelProgressDraftDiffStat;
};
declare function formatChannelProgressDraftText(params: ChannelProgressDraftTextParams): string;
//#endregion
//#region src/config/sessions/session-admission-transition.types.d.ts
type SessionAdmissionEntryIdentity = Readonly<Pick<InternalSessionEntry, "sessionId" | "lifecycleRevision">>;
/** Exact identity change committed by the host, independent of the admission executor. */
type SessionAdmissionTransition = Readonly<{
  previous?: SessionAdmissionEntryIdentity;
  current: SessionAdmissionEntryIdentity;
}>;
//#endregion
//#region src/config/sessions/session-entry-read-source.types.d.ts
/** Address of the physical store admitted by an entry read; never retains its handle. */
type SessionEntryReadSource = Readonly<{
  agentId: string;
  path: string;
}>;
type CapturedSessionEntryReadSource = SessionEntryReadSource & Readonly<{
  databaseIdentity: OpenClawAgentDatabaseIdentity;
  databaseBirthtime?: string;
}>;
//#endregion
//#region src/config/sessions/session-membership-facts.types.d.ts
type SessionParticipantProjection = Pick<SessionEntry, "participants" | "participantCount">;
/** No row JSON, prompts, or transcript payloads cross the membership publication boundary. */
type SessionMembershipFact = readonly [sessionKey: string, category: string | null, membership: readonly string[], participants: SessionParticipantProjection, sessionId: string | null];
type SessionParticipantRecord = {
  identity: SessionParticipantIdentity;
  contributionCount: number;
  firstPromptedAt: number | null;
  lastPromptedAt: number | null;
};
//#endregion
//#region src/config/sessions/session-pending-input-authority.d.ts
type SessionPendingInputAuthorityFacts = {
  agentId: string;
  storePath: string;
  sessionKey: string;
  entry: SessionEntry | undefined;
  readSource?: CapturedSessionEntryReadSource;
  members: readonly SessionMember[];
};
/** Host custody checks consume fresh worker facts without extending a snapshot across awaits. */
type SessionPendingInputAuthority = {
  assertLifetimeCurrent: () => void;
  /** Refresh policy facts for source preparation; this does not authorize disclosure or effects. */
  prepareForSourceScope?: () => Promise<void>;
  withCurrent: <T>(consume: (facts: SessionPendingInputAuthorityFacts, assertSourceCurrent: () => void) => T) => Promise<T>;
  withPreparedCurrent: <T>(facts: SessionPendingInputAuthorityFacts, consume: () => T, assertSourceCurrent: () => void) => T;
};
//#endregion
//#region src/config/sessions/session-transcript-context-version.types.d.ts
type SessionTranscriptWatermark = {
  generation: string | null;
  maxSeq: number | null;
};
type SessionTranscriptContextVersion = {
  generation: string | null;
  rawSeq: number | null;
  updatedAt: number | null;
};
//#endregion
//#region src/config/sessions/session-source-authority.d.ts
type SessionSourceConversationPredicate = {
  conversationRef: string;
  sessionKey: string | null;
};
/** Same-store facts are compared on the writer; published foreign sources may admit once. */
type SessionSourcePredicate = {
  source: CapturedSessionEntryReadSource;
  sessionKey: string;
  fields: (keyof InternalSessionEntry)[];
  expected: Partial<InternalSessionEntry> | undefined;
  members?: readonly string[];
  transcript?: {
    sessionId: string;
    version: SessionTranscriptContextVersion;
  };
  conversationAlternatives?: readonly (readonly SessionSourceConversationPredicate[])[];
};
type SessionSourcePredicateFacts = {
  entry: InternalSessionEntry | undefined;
  members?: readonly string[];
};
/** Current source facts supplied by the mutation's own transaction. */
type SessionSourceTransactionGrant = {
  source: CapturedSessionEntryReadSource;
  agentId: string;
  sessionKey: string;
  assertCurrent: (facts: SessionPendingInputAuthorityFacts) => void;
};
type SessionSourceValidation = {
  refusedSource?: {
    index: number;
    facts: SessionSourcePredicateFacts;
  };
  conversationMatches: Array<{
    index: number;
    alternatives: number[];
    acceptedAlternatives?: number[];
  }>;
};
type PreparedSessionSourceAuthority = {
  transaction?: SessionSourceTransactionGrant;
  /** Process-held sources require native atomicity when writing a durable target. */
  nativeSource?: boolean;
  /** Released SDK callbacks can perform arbitrary synchronous SQLite reads. */
  opaqueCommitGuard?: boolean;
  /** Wrapper checks need a native transaction unless the caller owns a prepared commit hook. */
  hasOpaqueCheck?: boolean;
  assertCurrent: () => void;
  /** Prepared components only; the owning commit boundary must also run opaque checks. */
  assertPreparedCurrent?: () => void;
  checks: {
    predicate: SessionSourcePredicate;
    refuse: (facts: SessionSourcePredicateFacts) => never;
    /** The returned array is filled by the next host assertion. */
    acceptConversationMatches?: (alternatives: readonly number[]) => number[];
  }[];
  release?: () => void | Promise<void>;
  scopedSources?: ReadonlyMap<SessionSourceAssertion, PreparedSessionSourceAuthority>;
};
type SessionSourceAssertion = (() => void) & {
  nativeSource?: boolean;
  opaqueCommitGuard?: boolean;
  /** Host commit notification only; never a substitute for the normal source checks. */
  onSessionCompactionCommitted?: (transition: SessionAdmissionTransition, entry: InternalSessionEntry) => void;
  /** Keep the source owner alive through accepted work that outlasts its request. */
  retain?: () => () => void;
  /** Checks the scope owner without invoking storage-dependent source predicates. */
  assertScopeCurrent?: () => void;
  prepareSessionSource?: () => Promise<PreparedSessionSourceAuthority>;
  prepareSessionSourceScope?: () => Promise<PreparedSessionSourceAuthority | undefined>;
};
/** Sources supplied to worker mutation APIs must own asynchronous predicate preparation. */
type PreparedSessionSourceAssertion = SessionSourceAssertion & {
  prepareSessionSource: () => Promise<PreparedSessionSourceAuthority>;
};
/** Public boolean callbacks stay callable; bundled owners also carry their prepared writer source. */
type SessionSourceCheck = (() => boolean) & {
  sessionSource?: SessionSourceAssertion;
};
/** Async effect checks also expose worker predicates and a storage-free host assertion. */
type AsyncSessionSourceCheck = (() => Promise<boolean>) & {
  sessionSource: PreparedSessionSourceAssertion & {
    assertScopeCurrent: () => void;
  };
};
//#endregion
//#region src/config/sessions/transcript-entry-anchor.d.ts
/** Immutable transcript identity issued by the SQLite append transaction. */
type TranscriptEntryAnchor = Readonly<{
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
  generation: string;
  entryId: string;
  rawSeq: number;
  effectiveParentId: string | null;
  activeMessagePosition: number;
  idempotencyKey?: string;
}>;
/** Current user row bound to one recorder-owned logical turn. */
type TranscriptTurnAdmission = TranscriptEntryAnchor & Readonly<{
  logicalTurnId: string;
  role: "user";
}>;
/** Exact accepted transcript range, inclusive of admission and terminal. */
type TranscriptTurnBoundary = Readonly<{
  admission: TranscriptTurnAdmission;
  terminal: TranscriptEntryAnchor;
}>;
//#endregion
//#region src/sessions/provider-review-terminal.d.ts
/** Carried only by the existing run owner; never serialized into event metadata. */
type ProviderReviewTerminalFact = Readonly<{
  target: Readonly<ProviderReviewTarget>;
  review: Readonly<SessionProviderReview>;
  expectedWriterRunId: string;
  lifecycleGeneration: string;
  lifecycleStartedAt?: number;
  capturedAtMs: number;
  assertCurrent: () => void;
}>;
//#endregion
//#region packages/gateway-protocol/src/schema/cron-automation-result.d.ts
/** A quiet check needs no prose; meaningful facts always carry a bounded summary. */
declare const AutomationResultSchema: Type$1.TUnion<[Type$1.TObject<{
  outcome: Type$1.TLiteral<"no_change">;
  summary: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  outcome: Type$1.TUnion<[Type$1.TLiteral<"progress">, Type$1.TLiteral<"done">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"needs_attention">]>;
  summary: Type$1.TString;
}>]>;
type AutomationResult = Static<typeof AutomationResultSchema>;
//#endregion
//#region src/infra/agent-run-authority.types.d.ts
/** Exact admitted-run claim shared by the registry and its subordinate approval leases. */
type AgentRunDelegatedAuthority = Readonly<{
  operationalRunInstance: Readonly<{
    instanceId: string;
    runId: string;
  }>;
  lifecycleGeneration: string;
  claimId: string;
}>;
//#endregion
//#region src/infra/agent-run-registry.types.d.ts
type AgentRunModel = {
  provider: string;
  model: string;
};
type ProjectedAgentRunState = "queued" | "running" | "capacity-wait";
type ProjectedAgentRunIndex = {
  modelsBySessionId: ReadonlyMap<string, AgentRunModel | null>;
  sessionKeys: ReadonlyMap<string, ProjectedAgentRunState>;
  sessionIds: ReadonlyMap<string, ProjectedAgentRunState>;
  ownerlessSessionKeys: ReadonlyMap<string, ProjectedAgentRunState>;
  ownerlessSessionIds: ReadonlyMap<string, ProjectedAgentRunState>;
};
//#endregion
//#region src/infra/agent-events.types.d.ts
/** Payload for approval requests and their later resolution events. */
type AgentApprovalEventData = {
  phase: "requested" | "resolved";
  kind: "exec" | "plugin" | "unknown";
  status: "pending" | "unavailable" | "approved" | "denied" | "failed";
  title: string;
  itemId?: string;
  toolCallId?: string;
  approvalId?: string;
  approvalSlug?: string;
  command?: string;
  host?: string;
  reason?: string;
  scope?: "turn" | "session";
  message?: string;
};
/** Stream name for agent events delivered to gateway listeners and plugin host hooks. */
type AgentEventStream = "lifecycle" | "tool" | "assistant" | "usage" | "error" | "item" | "plan" | "approval" | "command_output" | "patch" | "compaction" | "thinking" | (string & {});
/** Enriched event delivered to subscribers after sequencing and context stamping. */
type AgentEventPayload = {
  runId: string;
  seq: number;
  stream: AgentEventStream;
  ts: number;
  data: Record<string, unknown>;
  preamble?: AgentEvent["preamble"];
  /** Internal, non-enumerable gateway lifecycle generation that owns this run. */
  lifecycleGeneration?: string;
  sessionKey?: string;
  /**
   * sessionId the run was bound to when it started. Lifecycle persistence uses
   * this to reject terminal events from a pre-`sessions.reset` run that would
   * otherwise clobber the rotated session row resolved by the shared sessionKey.
   */
  sessionId?: string;
  agentId?: string;
};
type AgentAssistantSourceReceipt = {
  /** Stable occurrence identity for buffer scopes and worker forwarding. */
  itemId?: string;
  /** Undefined until commit; null is durable without an available transcript position. */
  committedMessageSeq?: number | null;
  /** Exact transcript occurrence assigned by the persistence owner after commit. */
  committedMessageId?: string;
};
//#endregion
//#region src/infra/agent-events.d.ts
/** Emits an agent event after assigning per-run sequence, timestamp, and context metadata. */
declare function emitAgentEvent(event: Omit<AgentEventPayload, "seq" | "ts">): void;
/** Subscribes to sequenced agent events; returns an unsubscribe callback. */
declare function onAgentEvent(listener: (evt: AgentEventPayload) => void): () => void;
/** Clears agent event state; test suites with a live Gateway can preserve its listeners. */
declare function resetAgentEventsForTest(options?: {
  preserveListeners?: boolean;
}): void;
//#endregion
//#region src/infra/agent-activity-events.d.ts
type AgentItemEventStatus = NonNullable<AgentActivityItem["status"]>;
/** Live producers retain a known status and may attach additional telemetry. */
type AgentItemEventData = AgentActivityItem & Record<string, unknown> & {
  status: AgentItemEventStatus;
};
/** Incremental command output payload associated with an item/tool call. */
type AgentCommandOutputEventFields = {
  itemId: string;
  phase: "delta" | "end";
  title: string;
  toolCallId: string;
  name?: string;
  output?: string;
  status?: AgentItemEventStatus | "running";
  exitCode?: number | null;
  durationMs?: number;
  cwd?: string;
};
type ToolActivityInput = {
  toolCallId: string;
  name: string;
  presentationName?: string;
  phase: "start" | "update" | "result";
  args?: unknown;
  result?: unknown;
  meta?: string;
  status?: AgentItemEventStatus | "unknown";
  isError?: boolean;
  hideFromChannelProgress?: boolean;
  nativeOperation?: "wait" | "process.poll";
};
declare function projectAgentToolActivity(tool: ToolActivityInput & ({
  phase: "start" | "update";
} | {
  status: AgentItemEventStatus;
})): AgentItemEventData;
declare function projectAgentToolActivity(tool: ToolActivityInput): AgentActivityItem;
//#endregion
//#region src/channels/location.d.ts
/** Normalized source kind for channel-provided geographic locations. */
type LocationSource = "pin" | "place" | "live";
/** Channel-neutral location payload passed from plugins into shared prompt rendering. */
type NormalizedLocation = {
  latitude: number;
  longitude: number;
  accuracy?: number;
  name?: string;
  address?: string;
  isLive?: boolean;
  source?: LocationSource;
  caption?: string;
};
/** Portable outbound location fields supported by channel send adapters. */
type OutboundLocation = Pick<NormalizedLocation, "latitude" | "longitude" | "accuracy" | "name" | "address">;
/** Normalize a portable location payload at an outbound/plugin boundary. */
declare function normalizeOutboundLocation(value: unknown, label?: string): OutboundLocation | undefined;
/**
 * Formats the safe inline location body shown to the model.
 *
 * Channel-provided labels, addresses, and captions are intentionally excluded
 * here; `toLocationContext` carries them into the untrusted metadata block.
 */
declare function formatLocationText(location: NormalizedLocation): string;
/** Converts a normalized location into template context fields for prompt metadata. */
declare function toLocationContext(location: NormalizedLocation): {
  LocationLat: number;
  LocationLon: number;
  LocationAccuracy?: number;
  LocationName?: string;
  LocationAddress?: string;
  LocationSource: LocationSource;
  LocationIsLive: boolean;
  LocationCaption?: string;
};
//#endregion
//#region src/shared/reply-payload.types.d.ts
type ReplyMediaAttachment = {
  type?: "image" | "audio" | "video" | "file";
  path?: string;
  url?: string;
  mediaUrl?: string;
  filePath?: string;
  mimeType?: string;
  name?: string;
  sizeBytes?: number;
  durationMs?: number;
  width?: number;
  height?: number;
  /** Internal per-URL trust carried until mixed media is split for history projection. */
  trustedLocalMedia?: boolean;
};
/** Metadata for audio-only media that supplements already-visible assistant text. */
type ReplyPayloadTtsSupplement = {
  spokenText: string;
  visibleTextAlreadyDelivered?: boolean;
};
/** Channel-agnostic assistant reply payload. */
type ReplyPayload$1 = {
  text?: string;
  /** For block previews only: append this text to the current answer. Omitted means replacement.
   * Durable sends and transcripts still consume this payload's text; finals always replace. */
  textMode?: "delta";
  /** Visible body a channel adapter may use when native structured content requires text. */
  fallbackText?: {
    text: string;
    /** Batch payload replaced when the adapter adopts this fallback body. */
    replacesPayloadIndex?: number;
  };
  mediaUrl?: string;
  mediaUrls?: string[];
  /** Prepared metadata aligned with mediaUrls for client-facing history projection. */
  attachments?: ReplyMediaAttachment[];
  /** Internal-only trust signal for gateway webchat local media embedding. */
  trustedLocalMedia?: boolean;
  /** Treat media as live-only content and avoid persisting the underlying media reference. */
  sensitiveMedia?: boolean;
  /** Channel-agnostic rich presentation. Core degrades or asks the channel renderer to map it. */
  presentation?: MessagePresentation;
  /** Runtime-authored text is the exact fallback, not additional native presentation content. */
  presentationTextMode?: "fallback";
  /** Channel-agnostic delivery preferences, e.g. pin the sent message when supported. */
  delivery?: ReplyPayloadDelivery;
  /**
   * @deprecated Use presentation.
   *
   * Internal legacy representation used by existing approval/reply helpers during migration.
   */
  interactive?: InteractiveReply;
  btw?: {
    question: string;
  };
  replyToId?: string;
  replyToTag?: boolean;
  /** True when [[reply_to_current]] was present but not yet mapped to a message id. */
  replyToCurrent?: boolean;
  /** Send audio as voice message (bubble) instead of audio file. Defaults to false. */
  audioAsVoice?: boolean;
  /** Send video media as a round video note when the channel supports it. */
  videoAsNote?: boolean;
  /** Channel-neutral geographic location or named place. */
  location?: OutboundLocation;
  /**
   * Text synthesized into an audio-only TTS payload. Exposed to hooks for
   * archival/search use when no visible channel text is sent.
   */
  spokenText?: string;
  /**
   * Marks a TTS media payload as supplemental audio for assistant text that is
   * already visible through streaming or transcript projection.
   */
  ttsSupplement?: ReplyPayloadTtsSupplement;
  isError?: boolean;
  /** Marks this payload as a reasoning/thinking block. Channels that do not
   *  have a dedicated reasoning lane (e.g. WhatsApp, web) should suppress it. */
  isReasoning?: boolean;
  /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
  isCommentary?: boolean;
  /** Reasoning stream text is a complete replacement snapshot, not a delta. */
  isReasoningSnapshot?: boolean;
  /** Marks this payload as a compaction status notice (start/end).
   *  Should be excluded from TTS transcript accumulation so compaction
   *  status lines are not synthesised into the spoken assistant reply. */
  isCompactionNotice?: boolean;
  /** Marks this payload as a model-fallback transition/recovery notice. */
  isFallbackNotice?: boolean;
  /** Marks this payload as transient status, not assistant answer content. */
  isStatusNotice?: boolean;
  /** Channel-specific payload data (per-channel envelope). */
  channelData?: Record<string, unknown>;
};
//#endregion
//#region src/infra/outbound/reply-payload-parts.d.ts
/** Derived sendability facts for text/media outbound payload delivery. */
type SendableOutboundReplyParts = ReturnType<typeof resolveSendableOutboundReplyParts>;
/** Prepared payload entry that keeps source indexing plus reusable projections. */
type OutboundPayloadPlan = {
  sourceIndex: number;
  payload: ReplyPayload$1;
  parts: SendableOutboundReplyParts;
  hasPresentation: boolean;
  hasInteractive: boolean;
  hasChannelData: boolean;
};
/** Prefer multi-attachment payloads, then fall back to the legacy single-media field. */
declare function resolveOutboundMediaUrls(payload: {
  mediaUrls?: string[];
  mediaUrl?: string;
}): string[];
declare function countOutboundMedia(payload: {
  mediaUrls?: string[];
  mediaUrl?: string;
}): number;
declare function hasOutboundMedia(payload: {
  mediaUrls?: string[];
  mediaUrl?: string;
}): boolean;
declare function hasOutboundText(payload: {
  text?: string;
}, options?: {
  trim?: boolean;
}): boolean;
/** Normalize reply payload text/media into a trimmed, sendable shape for delivery paths. */
declare function resolveSendableOutboundReplyParts(payload: {
  text?: string;
  mediaUrls?: string[];
  mediaUrl?: string;
}, options?: {
  text?: string;
}): {
  text: string;
  trimmedText: string;
  mediaUrls: string[];
  mediaCount: number;
  hasText: boolean;
  hasMedia: boolean;
  hasContent: boolean;
};
//#endregion
//#region src/gateway/operator-run-recovery-source.codec.d.ts
declare const operatorRunRecoverySnapshotSchema: z.ZodObject<{
  profileId: z.ZodString;
  scopes: z.ZodArray<z.ZodString>;
  assignedRole: z.ZodNullable<z.ZodString>;
  githubLogin: z.ZodNullable<z.ZodString>;
  rolePolicy: z.ZodOptional<z.ZodObject<{
    sessions: z.ZodObject<{
      others: z.ZodEnum<{
        none: "none";
        suggest: "suggest";
        view: "view";
        write: "write";
      }>;
    }, z.core.$strict>;
    sandbox: z.ZodOptional<z.ZodEnum<{
      inherit: "inherit";
      required: "required";
    }>>;
    agents: z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>]>;
    workerProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>>;
    accessPrograms: z.ZodOptional<z.ZodObject<{
      cyber: z.ZodPipe<z.ZodArray<z.ZodEnum<{
        daybreak_blue: "daybreak_blue";
        daybreak_red: "daybreak_red";
      }>>, z.ZodTransform<("daybreak_blue" | "daybreak_red")[], ("daybreak_blue" | "daybreak_red")[]>>;
    }, z.core.$strict>>;
    scopes: z.ZodPipe<z.ZodArray<z.ZodEnum<{
      "operator.admin": "operator.admin";
      "operator.approvals": "operator.approvals";
      "operator.pairing": "operator.pairing";
      "operator.questions": "operator.questions";
      "operator.read": "operator.read";
      "operator.sessions.read": "operator.sessions.read";
      "operator.sessions.write": "operator.sessions.write";
      "operator.talk": "operator.talk";
      "operator.talk.secrets": "operator.talk.secrets";
      "operator.write": "operator.write";
    }>>, z.ZodTransform<("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[], ("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[]>>;
    accessPolicyPlugin: z.ZodOptional<z.ZodString>;
  }, z.core.$strict>>;
  modelPolicy: z.ZodOptional<z.ZodObject<{
    models: z.ZodArray<z.ZodObject<{
      provider: z.ZodString;
      model: z.ZodString;
    }, z.core.$strict>>;
    allowed: z.ZodObject<{
      exact: z.ZodArray<z.ZodString>;
      wildcards: z.ZodArray<z.ZodString>;
    }, z.core.$strict>;
    denied: z.ZodObject<{
      exact: z.ZodArray<z.ZodString>;
      wildcards: z.ZodArray<z.ZodString>;
    }, z.core.$strict>;
  }, z.core.$strict>>;
  grant: z.ZodNullable<z.ZodObject<{
    pluginId: z.ZodString;
    grantId: z.ZodString;
  }, z.core.$strict>>;
  aliasBindingIds: z.ZodArray<z.ZodString>;
  authPolicy: z.ZodObject<{
    generation: z.ZodLiteral<"">;
    grantGeneration: z.ZodString;
    role: z.ZodLiteral<"operator">;
    authMethod: z.ZodEnum<{
      "device-token": "device-token";
      password: "password";
      tailscale: "tailscale";
      token: "token";
      "trusted-proxy": "trusted-proxy";
    }>;
    authModeOverride: z.ZodOptional<z.ZodEnum<{
      none: "none";
      password: "password";
      token: "token";
      "trusted-proxy": "trusted-proxy";
    }>>;
    verifiedIdentity: z.ZodOptional<z.ZodString>;
    browserOrigin: z.ZodOptional<z.ZodObject<{
      requestHost: z.ZodOptional<z.ZodString>;
      origin: z.ZodOptional<z.ZodString>;
      isLocalClient: z.ZodOptional<z.ZodBoolean>;
    }, z.core.$strict>>;
  }, z.core.$strict>;
  sharedGeneration: z.ZodOptional<z.ZodString>;
  device: z.ZodOptional<z.ZodObject<{
    deviceId: z.ZodString;
    key: z.ZodString;
  }, z.core.$strict>>;
  controlUiAdmin: z.ZodBoolean;
  localOperator: z.ZodBoolean;
  sourceIngress: z.ZodEnum<{
    "control-ui": "control-ui";
    internal: "internal";
  }>;
}, z.core.$strict>;
declare const sourceSchema: z.ZodObject<{
  version: z.ZodLiteral<1>;
  agentId: z.ZodString;
  sessionKey: z.ZodString;
  sessionId: z.ZodString;
  lifecycleRevision: z.ZodOptional<z.ZodString>;
  sourceRunId: z.ZodString;
  snapshot: z.ZodObject<{
    profileId: z.ZodString;
    scopes: z.ZodArray<z.ZodString>;
    assignedRole: z.ZodNullable<z.ZodString>;
    githubLogin: z.ZodNullable<z.ZodString>;
    rolePolicy: z.ZodOptional<z.ZodObject<{
      sessions: z.ZodObject<{
        others: z.ZodEnum<{
          none: "none";
          suggest: "suggest";
          view: "view";
          write: "write";
        }>;
      }, z.core.$strict>;
      sandbox: z.ZodOptional<z.ZodEnum<{
        inherit: "inherit";
        required: "required";
      }>>;
      agents: z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>]>;
      workerProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>>;
      accessPrograms: z.ZodOptional<z.ZodObject<{
        cyber: z.ZodPipe<z.ZodArray<z.ZodEnum<{
          daybreak_blue: "daybreak_blue";
          daybreak_red: "daybreak_red";
        }>>, z.ZodTransform<("daybreak_blue" | "daybreak_red")[], ("daybreak_blue" | "daybreak_red")[]>>;
      }, z.core.$strict>>;
      scopes: z.ZodPipe<z.ZodArray<z.ZodEnum<{
        "operator.admin": "operator.admin";
        "operator.approvals": "operator.approvals";
        "operator.pairing": "operator.pairing";
        "operator.questions": "operator.questions";
        "operator.read": "operator.read";
        "operator.sessions.read": "operator.sessions.read";
        "operator.sessions.write": "operator.sessions.write";
        "operator.talk": "operator.talk";
        "operator.talk.secrets": "operator.talk.secrets";
        "operator.write": "operator.write";
      }>>, z.ZodTransform<("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[], ("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[]>>;
      accessPolicyPlugin: z.ZodOptional<z.ZodString>;
    }, z.core.$strict>>;
    modelPolicy: z.ZodOptional<z.ZodObject<{
      models: z.ZodArray<z.ZodObject<{
        provider: z.ZodString;
        model: z.ZodString;
      }, z.core.$strict>>;
      allowed: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
      denied: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
    }, z.core.$strict>>;
    grant: z.ZodNullable<z.ZodObject<{
      pluginId: z.ZodString;
      grantId: z.ZodString;
    }, z.core.$strict>>;
    aliasBindingIds: z.ZodArray<z.ZodString>;
    authPolicy: z.ZodObject<{
      generation: z.ZodLiteral<"">;
      grantGeneration: z.ZodString;
      role: z.ZodLiteral<"operator">;
      authMethod: z.ZodEnum<{
        "device-token": "device-token";
        password: "password";
        tailscale: "tailscale";
        token: "token";
        "trusted-proxy": "trusted-proxy";
      }>;
      authModeOverride: z.ZodOptional<z.ZodEnum<{
        none: "none";
        password: "password";
        token: "token";
        "trusted-proxy": "trusted-proxy";
      }>>;
      verifiedIdentity: z.ZodOptional<z.ZodString>;
      browserOrigin: z.ZodOptional<z.ZodObject<{
        requestHost: z.ZodOptional<z.ZodString>;
        origin: z.ZodOptional<z.ZodString>;
        isLocalClient: z.ZodOptional<z.ZodBoolean>;
      }, z.core.$strict>>;
    }, z.core.$strict>;
    sharedGeneration: z.ZodOptional<z.ZodString>;
    device: z.ZodOptional<z.ZodObject<{
      deviceId: z.ZodString;
      key: z.ZodString;
    }, z.core.$strict>>;
    controlUiAdmin: z.ZodBoolean;
    localOperator: z.ZodBoolean;
    sourceIngress: z.ZodEnum<{
      "control-ui": "control-ui";
      internal: "internal";
    }>;
  }, z.core.$strict>;
}, z.core.$strict>;
declare const queuedSourceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
  kind: z.ZodLiteral<"gateway">;
  snapshot: z.ZodObject<{
    profileId: z.ZodString;
    scopes: z.ZodArray<z.ZodString>;
    assignedRole: z.ZodNullable<z.ZodString>;
    githubLogin: z.ZodNullable<z.ZodString>;
    rolePolicy: z.ZodOptional<z.ZodObject<{
      sessions: z.ZodObject<{
        others: z.ZodEnum<{
          none: "none";
          suggest: "suggest";
          view: "view";
          write: "write";
        }>;
      }, z.core.$strict>;
      sandbox: z.ZodOptional<z.ZodEnum<{
        inherit: "inherit";
        required: "required";
      }>>;
      agents: z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>]>;
      workerProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>>;
      accessPrograms: z.ZodOptional<z.ZodObject<{
        cyber: z.ZodPipe<z.ZodArray<z.ZodEnum<{
          daybreak_blue: "daybreak_blue";
          daybreak_red: "daybreak_red";
        }>>, z.ZodTransform<("daybreak_blue" | "daybreak_red")[], ("daybreak_blue" | "daybreak_red")[]>>;
      }, z.core.$strict>>;
      scopes: z.ZodPipe<z.ZodArray<z.ZodEnum<{
        "operator.admin": "operator.admin";
        "operator.approvals": "operator.approvals";
        "operator.pairing": "operator.pairing";
        "operator.questions": "operator.questions";
        "operator.read": "operator.read";
        "operator.sessions.read": "operator.sessions.read";
        "operator.sessions.write": "operator.sessions.write";
        "operator.talk": "operator.talk";
        "operator.talk.secrets": "operator.talk.secrets";
        "operator.write": "operator.write";
      }>>, z.ZodTransform<("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[], ("operator.admin" | "operator.approvals" | "operator.pairing" | "operator.questions" | "operator.read" | "operator.sessions.read" | "operator.sessions.write" | "operator.talk" | "operator.talk.secrets" | "operator.write")[]>>;
      accessPolicyPlugin: z.ZodOptional<z.ZodString>;
    }, z.core.$strict>>;
    modelPolicy: z.ZodOptional<z.ZodObject<{
      models: z.ZodArray<z.ZodObject<{
        provider: z.ZodString;
        model: z.ZodString;
      }, z.core.$strict>>;
      allowed: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
      denied: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
    }, z.core.$strict>>;
    grant: z.ZodNullable<z.ZodObject<{
      pluginId: z.ZodString;
      grantId: z.ZodString;
    }, z.core.$strict>>;
    aliasBindingIds: z.ZodArray<z.ZodString>;
    authPolicy: z.ZodObject<{
      generation: z.ZodLiteral<"">;
      grantGeneration: z.ZodString;
      role: z.ZodLiteral<"operator">;
      authMethod: z.ZodEnum<{
        "device-token": "device-token";
        password: "password";
        tailscale: "tailscale";
        token: "token";
        "trusted-proxy": "trusted-proxy";
      }>;
      authModeOverride: z.ZodOptional<z.ZodEnum<{
        none: "none";
        password: "password";
        token: "token";
        "trusted-proxy": "trusted-proxy";
      }>>;
      verifiedIdentity: z.ZodOptional<z.ZodString>;
      browserOrigin: z.ZodOptional<z.ZodObject<{
        requestHost: z.ZodOptional<z.ZodString>;
        origin: z.ZodOptional<z.ZodString>;
        isLocalClient: z.ZodOptional<z.ZodBoolean>;
      }, z.core.$strict>>;
    }, z.core.$strict>;
    sharedGeneration: z.ZodOptional<z.ZodString>;
    device: z.ZodOptional<z.ZodObject<{
      deviceId: z.ZodString;
      key: z.ZodString;
    }, z.core.$strict>>;
    controlUiAdmin: z.ZodBoolean;
    localOperator: z.ZodBoolean;
    sourceIngress: z.ZodEnum<{
      "control-ui": "control-ui";
      internal: "internal";
    }>;
  }, z.core.$strict>;
}, z.core.$strict>, z.ZodObject<{
  kind: z.ZodLiteral<"channel">;
  snapshot: z.ZodObject<{
    reference: z.ZodObject<{
      version: z.ZodLiteral<1>;
      id: z.ZodUUID;
    }, z.core.$strict>;
    profileId: z.ZodString;
    scopes: z.ZodArray<z.ZodString>;
    modelPolicy: z.ZodOptional<z.ZodObject<{
      models: z.ZodArray<z.ZodObject<{
        provider: z.ZodString;
        model: z.ZodString;
      }, z.core.$strict>>;
      allowed: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
      denied: z.ZodObject<{
        exact: z.ZodArray<z.ZodString>;
        wildcards: z.ZodArray<z.ZodString>;
      }, z.core.$strict>;
    }, z.core.$strict>>;
  }, z.core.$strict>;
}, z.core.$strict>, z.ZodObject<{
  kind: z.ZodLiteral<"unavailable">;
}, z.core.$strict>], "kind">;
/** Private accepted-input basis; only its current input owner may restore authority. */
type QueuedOperatorRecoverySource = z.infer<typeof queuedSourceSchema>;
/** Original authenticated basis, not an executable grant or a transport credential. */
type OperatorRunRecoverySnapshot = z.infer<typeof operatorRunRecoverySnapshotSchema>;
/** Private input custody; copied attribution or another session cannot authorize recovery. */
type RestartRecoveryOperatorSource = z.infer<typeof sourceSchema>;
//#endregion
//#region packages/gateway-protocol/src/session-agent-status.d.ts
declare const SESSION_AGENT_ATTENTION_ICON_IDS: readonly ["hand", "key", "alert", "flag", "lock", "hourglass"];
type SessionAgentAttentionIconId = (typeof SESSION_AGENT_ATTENTION_ICON_IDS)[number];
type SessionAgentStatus = {
  note: string;
  expiresAt: number;
  attention?: SessionAgentAttentionIconId;
};
//#endregion
//#region packages/gateway-protocol/src/session-row-deltas.d.ts
type SessionRowWireIdentity = {
  key: string;
  agentId?: string;
  version: number;
};
type SessionRowFull = SessionRowWireIdentity & {
  full: Record<string, unknown>;
  retain?: false;
};
type SessionRowPatch = SessionRowWireIdentity & {
  base: number;
  set: Record<string, unknown>;
  remove: string[];
};
type SessionRowWire = SessionRowFull | SessionRowPatch;
//#endregion
//#region packages/gateway-protocol/src/schema/session-placement-state.d.ts
declare const SESSION_PLACEMENT_STATES: readonly ["local", "requested", "provisioning", "syncing", "starting", "active", "draining", "reconciling", "reclaimed", "failed"];
type SessionPlacementState = (typeof SESSION_PLACEMENT_STATES)[number];
//#endregion
//#region src/agents/requester-origin.d.ts
/** Host-captured requester facts, independent of execution authority and agent grants. */
type RequesterOrigin = Readonly<{
  sessionKey: string;
  operatorProfileId?: string;
  /** Causal human retained across a selected-user delegation; null means no human origin. */
  delegatedCreatorProfileId?: string | null;
  messageProvider?: string | null;
  accountId?: string | null;
  chatType?: ChatType;
  conversationId?: string | null;
  messageThreadId?: string | number | null;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
}>;
//#endregion
//#region src/chat/message-client-source.d.ts
/** Reported transport facts, separate from authenticated sender identity. */
type MessageClientSource = Pick<GatewayClientInfo, "id" | "mode" | "displayName">;
//#endregion
//#region src/chat/sender-identity.d.ts
type TranscriptSenderIdentity = Extract<SessionParticipantIdentity, {
  type: "profile" | "remote" | "observation";
}>;
//#endregion
//#region packages/gateway-protocol/src/chat-work-context.d.ts
/** Bounded, untrusted send-time reference data; never routing or authorization. */
declare const CHAT_WORK_CONTEXT_LIMITS: {
  readonly page: 64;
  readonly title: 96;
  readonly sessionKey: 192;
  readonly sessionId: 64;
  readonly agentId: 64;
  readonly workspace: 224;
  readonly file: 224;
  readonly selection: 640;
};
type ChatWorkContext = {
  page: string;
  detail?: Readonly<Record<string, string>>;
} & Partial<Record<Exclude<keyof typeof CHAT_WORK_CONTEXT_LIMITS, "page">, string>>;
//#endregion
//#region src/chat/work-context.d.ts
type AttachedChatWorkContext = {
  snapshot: ChatWorkContext;
  text: string;
};
//#endregion
//#region src/config/sessions/session-transcript-turn-lifecycle.types.d.ts
/** `null` requires a revision-less row; omitting the field skips the revision fence. */
type SessionLifecycleRevisionExpectation = string | null;
/** Authoritative lifecycle snapshot required for an atomic transcript admission. */
type SessionTranscriptTurnExpectedState = {
  /** When supplied, fences exact pending-final custody; null requires its absence. */
  pendingFinalDelivery?: InternalSessionEntry["pendingFinalDelivery"] | null;
  /** Rejects a run-owned turn after another admitted run takes writer ownership. */
  expectedWriterRunId?: string;
  abortedLastRun: boolean | undefined;
  status: PersistedSessionRunStatus | undefined;
};
/** Lifecycle fields committed with an accepted transcript turn. */
type SessionTranscriptTurnLifecyclePatch = {
  activeWriterRunId?: InternalSessionEntry["activeWriterRunId"];
  abortedLastRun?: boolean;
  endedAt?: number;
  lifecycleRunId?: InternalSessionEntry["lifecycleRunId"];
  lastRunId?: InternalSessionEntry["lastRunId"];
  lastRunError?: InternalSessionEntry["lastRunError"];
  lastInteractionAt?: number;
  pendingFinalDelivery?: InternalSessionEntry["pendingFinalDelivery"];
  runtimeMs?: number;
  startedAt?: number;
  status?: PersistedSessionRunStatus;
  updatedAt?: number;
};
//#endregion
//#region src/config/sessions/session-input-lifecycle.d.ts
/** Lifecycle bookkeeping committed atomically with an ordinary accepted input. */
type SessionInputLifecycleAdmission = {
  expectedState: SessionTranscriptTurnExpectedState;
  lifecycle: SessionTranscriptTurnLifecyclePatch;
};
//#endregion
//#region src/config/sessions/session-message-rewrite.types.d.ts
type SessionMessageRewriteResult = {
  generation: string;
  messageId: string;
  message: unknown;
  unchanged?: true;
};
//#endregion
//#region src/sessions/user-turn-transcript.types.d.ts
type PersistedUserTurnMediaInput = Pick<MediaFactInput, "contentType" | "durationMs" | "fileName" | "origin" | "height" | "hydrationSuppressed" | "messageId" | "path" | "sizeBytes" | "transcribed" | "url" | "width"> & {
  kind?: string | null;
  workspaceDir?: string | null;
};
type PersistedUserTurnMessage = Extract<AgentMessage, {
  role: "user";
}> & {
  display?: false;
  excludeFromContext?: true;
  /** Private transcript correlation; never authorizes an execution. */
  idempotencyKey?: string;
  provenance?: InputProvenance;
  __openclaw?: Record<string, unknown> & {
    humanMentions?: readonly HumanMention[];
    /** Accepted delivery intent; readmission still checks the sender's current authority. */
    chatSendDelivery?: {
      deliver?: boolean;
      originatingChannel?: string;
      originatingTo?: string;
      originatingAccountId?: string;
      originatingThreadId?: string;
    };
    chatSendRuntime?: {
      thinking?: string;
      fastMode?: FastMode;
      fastAutoOnSeconds?: number;
      timeoutMs?: number;
    };
    requesterOrigin?: RequesterOrigin;
  };
};
type UserTurnInput = Pick<PersistedUserTurnMessage, "display" | "excludeFromContext"> & {
  text?: string | null;
  /** Authored text and its captured reference; model content stays unchanged. */
  workContext?: AttachedChatWorkContext;
  /** Explicit human selections bound to UTF-16 offsets in text. */
  mentions?: readonly HumanMention[];
  media?: readonly PersistedUserTurnMediaInput[] | null;
  /** Restart-safe native image placement; model-visible prompt bytes remain separate. */
  mediaImageLayout?: {
    slots: readonly {
      kind: "inline" | "offloaded";
      factIndex?: number;
    }[];
    suppressedFactIndexes?: readonly number[];
  } | null;
  timestamp?: number;
  idempotencyKey?: string;
  /** Durable transcript message reference used to render and hydrate replies. */
  replyToId?: string;
  /** Bounded display fallback for replies whose target is outside loaded history. */
  replyToPreview?: {
    text: string;
    senderLabel?: string | null;
  } | null;
  senderIsOwner?: boolean;
  /** Host-captured requester facts; recovery still requires exact accepted-input custody. */
  requesterOrigin?: RequesterOrigin;
  provenance?: InputProvenance;
  /** Identity is producer-owned attribution; labels remain editable display metadata. */
  sender?: {
    id?: string | null;
    name?: string | null;
    username?: string | null;
    identity?: TranscriptSenderIdentity;
  } | null;
  /** Durable transport correlation; stored privately and never rendered into model input. */
  transport?: {
    /** Reported client sources retained through collection; never sender authority. */
    clients?: readonly MessageClientSource[];
    channel?: string;
    conversationRef?: string;
    messageId?: string;
    replyToId?: string;
    threadId?: string;
  };
};
type UserTurnTranscriptUpdateMode = "inline" | "none";
type UserTurnBeforeMessageWrite = (params: {
  message: PersistedUserTurnMessage;
  agentId?: string;
  sessionKey?: string;
}) => AgentMessage | null;
type UserTurnTranscriptTarget = {
  sessionId: string;
  expectedSessionId?: string;
  initialSessionEntry?: SessionEntry;
  sessionKey: string;
  sessionEntry: SessionEntry | undefined;
  sessionStore?: Record<string, SessionEntry>;
  storePath?: string;
  agentId: string;
  threadId?: string | number;
  cwd?: string;
  config?: OpenClawConfig;
  beforeMessageWrite?: UserTurnBeforeMessageWrite;
};
type UserTurnTranscriptAdmissionReceipt = TranscriptTurnAdmission;
/** Native producer facts for the current host-admitted prompt; never a message replacement. */
type UserTurnTranscriptAnnotation = Readonly<{
  mirrorIdentity: string;
  upstreamUserText: string;
  mirrorOrigin: string;
  mirrorSourceFingerprint: string;
}>;
type UserTurnTranscriptPersistResult = {
  sessionTurnMutationResult?: SessionTranscriptTurnMutationResult;
  /** True only when this call inserted the transcript message. */
  appended?: boolean;
  sessionFile: string;
  sessionEntry: SessionEntry | undefined;
  messageId: string;
  message: PersistedUserTurnMessage;
  admission: UserTurnTranscriptAdmissionReceipt;
};
type UserTurnTranscriptTargetResolver = UserTurnTranscriptTarget | (() => UserTurnTranscriptTarget | undefined | Promise<UserTurnTranscriptTarget | undefined>);
type UserTurnPersistenceOptions = {
  target?: UserTurnTranscriptTargetResolver;
  sessionLifecyclePatch?: SessionTranscriptTurnLifecyclePatch;
  /** Pin admitted storage without replacing the recorder's target resolver or metadata. */
  storageTarget?: Readonly<Pick<UserTurnTranscriptTarget, "agentId" | "sessionKey" | "sessionId"> & {
    storePath: string;
  }>;
  updateMode?: UserTurnTranscriptUpdateMode;
  cwd?: string;
};
type PreparedModelPromptProjection = {
  intent: {
    anchor: TranscriptEntryAnchor;
    text: string;
  };
  onCommitted: (result: SessionMessageRewriteResult | null) => Promise<PersistedUserTurnMessage>;
};
type UserTurnTranscriptRecorder = {
  readonly message: PersistedUserTurnMessage | undefined;
  resolveMessage: () => Promise<PersistedUserTurnMessage | undefined>;
  /** Committed or delivered input, accepted pending custody, and blocked notices are exempt. */
  assertOriginalInputCommit?: SessionSourceAssertion;
  /** Durable input custody leaves the active transcript unchanged until execution owns it. */
  stageApproved?: (options: {
    runId: string;
    recoverySource?: QueuedOperatorRecoverySource;
    retryCancelled?: boolean;
    storageTarget?: UserTurnPersistenceOptions["storageTarget"];
    lifecycleAdmission?: SessionInputLifecycleAdmission;
    assertCurrent: () => void;
    assertAdmittedCurrent?: () => void;
    assertCompletionCurrent?: () => void;
    authority?: SessionPendingInputAuthority;
  }) => Promise<boolean>;
  getProcessingCompletion?: () => AgentRunTerminalOutcome$1 | undefined;
  /** @deprecated Await completeProcessingAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  completeProcessing?: (outcome: AgentRunTerminalOutcome$1) => AgentRunTerminalOutcome$1 | undefined;
  completeProcessingAsync?: (outcome: AgentRunTerminalOutcome$1) => Promise<AgentRunTerminalOutcome$1 | undefined>;
  getPendingInputMessage?: () => PersistedUserTurnMessage | undefined;
  isPendingInputConsumed?: () => boolean;
  validateCommittedReplay?: () => Promise<void>;
  withPendingInput?: <T>(run: () => T) => T;
  withPendingInputCurrent?: <T>(run: () => T) => Promise<Awaited<T>>;
  assertPendingInputLifetimeCurrent?: () => void;
  finishPendingInput?: (disposition: "cancelled" | "interrupted") => void;
  /** Join accepted completion and disposition writes before releasing the turn's admission. */
  waitForPendingInputSettlement?: () => Promise<void>;
  /** Replaces generated current-turn text before runtime persistence/provider submission. */
  replaceTextBeforePersistence?: (text: string) => void;
  /** Confirms exact-run steering provenance after transcript commitment is proven. */
  confirmSteerTargetRunIdForPersistence?: (targetRunId: string) => Promise<void>;
  getPersistedMessage?: () => PersistedUserTurnMessage | undefined;
  /** Freeze model-facing text on the canonical user record before its first provider dispatch. */
  captureModelPromptProjection?: (text: string, assertCurrent: () => void) => Promise<PersistedUserTurnMessage>;
  /** Prepare a projection for the carrier's actor commit without publishing it early. */
  prepareModelPromptProjection?: (text: string, assertCurrent: () => void) => Promise<PreparedModelPromptProjection | undefined>;
  getAdmissionReceipt: () => UserTurnTranscriptAdmissionReceipt | undefined;
  /** Persistence and `waitForRuntimePersistence` settle the handler's write and reject on its failure. */
  setAdmissionHandler?: (handler: (admission: UserTurnTranscriptAdmissionReceipt) => void | Promise<void>) => void;
  markSentToProvider?: () => void;
  markRuntimePersistencePending: (pending: Promise<void>) => void;
  markRuntimePersisted: (message?: PersistedUserTurnMessage, anchor?: TranscriptEntryAnchor | UserTurnTranscriptAdmissionReceipt, persistence?: {
    appended: boolean;
  }) => void;
  markBlocked: () => void;
  hasPersisted: () => boolean;
  isBlocked: () => boolean;
  hasRuntimePersistencePending: () => boolean;
  waitForRuntimePersistence: () => Promise<void>;
  persistApproved: (params?: UserTurnPersistenceOptions & {
    expectedSessionId?: string;
    expectedSessionState?: SessionTranscriptTurnExpectedState;
    beforeFreshMessageCommit?: SessionSourceAssertion;
    /** Allow a later explicit persistence attempt when this attempt appends nothing. */
    retryIfUnpersisted?: boolean;
  }) => Promise<UserTurnTranscriptPersistResult | undefined>;
  persistBlocked: (message: PersistedUserTurnMessage, params?: UserTurnPersistenceOptions) => Promise<UserTurnTranscriptPersistResult | undefined>;
  persistFallback: (params?: UserTurnPersistenceOptions) => Promise<UserTurnTranscriptPersistResult | undefined>;
};
//#endregion
//#region src/channels/progress-draft-events.d.ts
type ProgressPayload<TEvent extends ChannelProgressDraftLineInput["event"]> = Omit<Extract<ChannelProgressDraftLineInput, {
  event: TEvent;
}>, "event">;
type ItemProgressPayload = Omit<ProgressPayload<"item">, "itemKind"> & {
  kind?: string;
};
type ChannelProgressDraftEventLine = string | ChannelProgressDraftLine;
type ChannelProgressDraftEventLineBuilder = (input: ChannelProgressDraftLineInput, options?: ChannelProgressLineOptions) => ChannelProgressDraftEventLine | undefined;
//#endregion
//#region src/channels/progress-draft-compositor.types.d.ts
type ChannelProgressDraftCompositorLine = string | ChannelProgressDraftLine;
type ChannelProgressDraftCompositorSnapshot = Readonly<{
  lines: readonly ChannelProgressDraftCompositorLine[];
  label?: string;
  statusHeadline?: string;
  statusHeadlineFormat?: "plain";
  plan?: readonly AgentPlanStep[];
  planExplanation?: string;
  planExplanationFormat?: "plain";
  preparedBlocks?: readonly {
    text: string;
    format: "plain" | "markdown";
  }[];
  diffStat?: ChannelProgressDraftDiffStat;
}>;
type ChannelProgressDraftUpdateOptions = {
  flush?: boolean;
  lines: readonly ChannelProgressDraftCompositorLine[];
  snapshot: ChannelProgressDraftCompositorSnapshot;
};
type ChannelProgressDraftCompositorParams = {
  /** @deprecated v2026.9.1 SDK presentation; retain until a breaking SDK release. */
  presentation?: "summary";
  entry: StreamingCompatEntry | null | undefined;
  /** Prepared items own display; raw callbacks retain diagnostic bookkeeping only. */
  preparedItems?: boolean;
  /** Keep one public operation/task status when the rolling tool log is hidden. */
  showWorkStatus?: boolean;
  mode: StreamingMode;
  active: boolean;
  seed: string;
  /** Display data only; hydration neither starts publishing nor proves visibility. */
  initialSnapshot?: ChannelProgressDraftCompositorSnapshot;
  /** Omit to prepare display data without publication or timers. */
  update?: (text: string, options: ChannelProgressDraftUpdateOptions) => Promise<boolean | void> | boolean | void;
  deleteCurrent?: () => Promise<void> | void;
  tryNativeUpdate?: (text: string) => Promise<boolean> | boolean;
  /** Publish when structured lines change even if the rendered text does not. */
  updateOnLineChange?: boolean;
  /**
   * Set when the channel renders `update`'s structured `lines` itself, so the
   * composed text carries only the status block (label, headline, checklist).
   */
  rendersRollingLinesNatively?: boolean;
  formatLine?: (line: string) => string;
  formatPlainText?: (text: string) => string;
  isEmptyLine?: (line: ChannelProgressDraftCompositorLine | undefined) => boolean;
  shouldStartNow?: (line: ChannelProgressDraftCompositorLine | undefined) => boolean;
  reasoningLinePrefix?: string;
  commentaryLinePrefix?: string;
  /** Prefix tool rows with their text glyph (`🛠️ Exec`); default plain. */
  toolIcons?: boolean;
  /** Compact consecutive keyed, prepared tool invocations in status-only progress mode. */
  compactToolRuns?: boolean;
  reasoningGate?: boolean;
  commentaryItalics?: boolean;
  now?: () => number;
  setTimeoutFn?: typeof setTimeout;
  clearTimeoutFn?: typeof clearTimeout;
  /** Channel-specific formatter policy; event/lifecycle ownership remains in the compositor. */
  buildProgressEventLine?: ChannelProgressDraftEventLineBuilder;
};
//#endregion
//#region src/channels/progress-continuation.d.ts
/** The 2026.9.8 receipt handoff argument; the host no longer offers that capability. */
type ProgressContinuationReceipt = {
  channel: string;
  accountId?: string;
  to: string;
  threadId?: string | number;
  messageId: string;
  text: string;
  snapshot: ChannelProgressDraftCompositorSnapshot;
};
/**
 * A confirmed progress draft the channel keeps after its turn ends. The channel
 * owns rendering, throttling and deletion; the adopting owner only pushes
 * prepared items and retires the draft once.
 */
type ProgressContinuationDraft = {
  push: (item: ItemProgressPayload) => void;
  retire: () => void;
};
type ProgressContinuationCapability = {
  adopt: (this: void, draft: ProgressContinuationDraft) => boolean;
  close: () => void;
};
//#endregion
//#region src/config/sessions/group.d.ts
/**
 * Resolves channel/group chat context into the persisted group session key.
 *
 * Provider-prefixed ids use channel-owned normalization, while legacy plugin resolvers remain a
 * fallback for older channel surfaces that cannot yet express the generic route shape.
 */
declare function resolveGroupSessionKey(ctx: MsgContext): GroupKeyResolution | null;
//#endregion
//#region src/acp/runtime/session-meta-read.types.d.ts
type AcpSessionStoreEntry = {
  cfg: OpenClawConfig;
  agentId?: string;
  storePath: string;
  sessionKey: string;
  storeSessionKey: string;
  entry?: SessionEntry;
  acp?: SessionAcpMeta;
  storeReadFailed?: boolean;
};
type AcpSessionReadContextInput = {
  cfg?: OpenClawConfig;
  env?: NodeJS.ProcessEnv;
  databasePath?: string;
  assertCurrent?: () => void;
};
type AcpSessionEntryReadInput = AcpSessionReadContextInput & {
  sessionKey: string;
  agentId?: string;
  clone?: boolean;
};
type PreparedAcpSessionEntryRead = {
  session: AcpSessionStoreEntry | null;
  assertCurrent(this: void): void;
  release(): void;
};
type AcpSessionEntryPreparer = (params: AcpSessionEntryReadInput) => Promise<PreparedAcpSessionEntryRead> | undefined;
//#endregion
//#region src/acp/runtime/session-meta-control.types.d.ts
/** A cleanup target constraint; live task and actor authority remain separate. */
type AcpSessionControlBinding = Readonly<{
  sessionId: string;
  lifecycleRevision?: string;
  sessionStartedAt?: number;
  ownerKey: string;
}>;
//#endregion
//#region src/config/sessions/session-entry-current.types.d.ts
/** Identity is parser-validated; optional owner values retain their exact stored semantics. */
type SessionEntryCurrentFacts = {
  sessionId: string;
  clientCapabilities?: string[];
  createdVia?: unknown;
  createdActor?: SessionEntry["createdActor"];
  incognito?: SessionEntry["incognito"];
  modelSelectionLocked?: SessionEntry["modelSelectionLocked"];
  pluginOwnerId?: SessionEntry["pluginOwnerId"];
  agentHarnessId?: SessionEntry["agentHarnessId"];
  agentRuntimeOverride?: SessionEntry["agentRuntimeOverride"];
  initializationPending?: SessionEntry["initializationPending"];
  execHost?: SessionEntry["execHost"];
  execNode?: SessionEntry["execNode"];
  deviceFolder?: SessionEntry["deviceFolder"];
  sandbox?: SessionEntry["sandbox"];
  sandboxMode?: SessionEntry["sandboxMode"];
  permissionMode?: SessionEntry["permissionMode"];
  toolOverrides?: SessionEntry["toolOverrides"];
  sessionRoot?: SessionEntry["sessionRoot"];
  authProfileOverride?: SessionEntry["authProfileOverride"];
  authProfileOverrideSource?: SessionEntry["authProfileOverrideSource"];
  modelOverride?: SessionEntry["modelOverride"];
  providerOverride?: SessionEntry["providerOverride"];
  model?: SessionEntry["model"];
  modelProvider?: SessionEntry["modelProvider"];
  previousSessionId?: unknown;
  archivedAt?: unknown;
  repositoryWorkspaceId?: unknown;
  goal?: unknown;
  lifecycleRevision?: unknown;
  lifecycleRunId?: unknown;
  lastRunId?: unknown;
  activeWriterRunId?: unknown;
  spawnedBy?: unknown;
  spawnDepth?: unknown;
  completionOwnerSessionKey?: unknown;
  subagentRole?: unknown;
  subagentControlScope?: unknown;
  inheritedToolPolicyVersion?: unknown;
  inheritedToolPolicySource?: unknown;
  inheritedToolAllow?: unknown;
  inheritedToolDeny?: unknown;
  delegatedToolPolicy?: unknown;
  skillLibrarySelections?: unknown;
  executionPolicy?: unknown;
};
type SessionEntryCurrentSource = CapturedSessionEntryReadSource & Readonly<{
  databaseIdentity: string;
  sessionKey: string;
  sessionIdLookup?: string;
  projection?: "capability";
}>;
/** A current-row restriction; the caller's existing admission still supplies authority. */
type SessionEntryCurrentCheck = Readonly<{
  source: SessionEntryCurrentSource;
  assertCurrent(facts: SessionEntryCurrentFacts | undefined): void;
}>;
/** One predicate can depend on several source-bound rows, including absent exact-key probes. */
type SessionEntriesCurrentCheck = Readonly<{
  sources: readonly SessionEntryCurrentSource[];
  assertCurrent(entries: readonly (SessionEntryCurrentFacts | undefined)[]): void;
}>;
//#endregion
//#region src/infra/sqlite-transaction.d.ts
type SqliteTransactionOptions = {
  /** Already-started BEGIN budget, carried between workers in the same process. */
  beginDeadlineNs?: bigint;
  /** An outer owner handles nonblocking admission failures. */
  beginLockFailureReporting?: "suppress";
  busyTimeoutMs?: number;
  databaseLabel?: string;
  /** Prepared identifiers and counts only; never transcript or session payloads. */
  diagnosticContext?: Readonly<Record<string, string | number | boolean | null | undefined>>;
  logger?: Pick<SubsystemLogger, "warn">;
  operationLabel?: string;
  slowTransactionHoldMs?: number;
  /** Enclose the physical commit in an owner's synchronous authority guard. */
  withCommit?: (commit: () => void) => void;
};
//#endregion
//#region src/state/openclaw-state-worker-context.types.d.ts
type OpenClawStateWorkerContext = Omit<SqliteWorkerStateContext, "environment"> & {
  environment: {
    OPENCLAW_STATE_DIR: string;
    OPENCLAW_SUPERVISOR_MODE?: "external";
  };
  admission: OpenClawStateDatabaseReadAdmission;
  /** Committed facts outlive a caller's schema borrow, but never the captured database generation. */
  assertPublicationCurrent?: () => void;
  /** Host-only captured scope; reentry never extends the original admission lifetime. */
  runInCapturedSchemaScope?: <T>(operation: () => T) => T;
  /** Host-only ownership; workers request live schema grants through their job admission. */
  maintenanceScope?: OpenClawDatabaseMaintenanceScope;
};
//#endregion
//#region src/plugins/session-catalog-upstream.types.d.ts
type SessionUpstreamKind = "claude-cli" | "codex-app-server" | "opencode-cli" | "pi-cli";
//#endregion
//#region src/sessions/session-upstream-links.kernel.d.ts
type SessionUpstreamLink = {
  sessionKey: string;
  agentId: string;
  catalogId: string;
  hostId: string;
  threadId: string;
  upstreamKind: SessionUpstreamKind;
  upstreamRef: PluginJsonValue;
  marker: PluginJsonValue | null;
  lastScannedAt?: number;
  createdAt: number;
  updatedAt: number;
};
type SessionUpstreamLinkInput = Omit<SessionUpstreamLink, "lastScannedAt" | "createdAt" | "updatedAt">;
//#endregion
//#region src/infra/directory-entries.d.ts
type DirectoryEntry = {
  name: string;
  isDirectory: boolean;
  /** Optional no-follow metadata from the same directory listing. */
  isFile?: boolean;
  size?: number;
  mtimeMs?: number;
};
//#endregion
//#region src/agents/sandbox/fs-bridge.types.d.ts
type SandboxResolvedPath = {
  hostPath?: string;
  relativePath: string;
  containerPath: string;
};
type SandboxFsStat = {
  type: "file" | "directory" | "other";
  size: number;
  mtimeMs: number;
};
type SandboxFsBridge = {
  /**
   * Backend-owned runtime roots and their local policy projections, in mount
   * precedence order for equal roots. These do not grant access: bridge methods
   * still enforce visibility, read-only rules and physical path safety.
   * Omit only for pre-descriptor SDK implementations; an empty list admits nothing.
   */
  readonly pathMappings?: readonly {
    readonly hostRoot: string;
    readonly containerRoot: string;
  }[];
  resolvePath(params: {
    filePath: string;
    cwd?: string;
  }): SandboxResolvedPath;
  /**
   * Resolves a host-backed file into the caller-facing path policy namespace.
   * Implementations must bind matching expectedPolicyPath inputs to final I/O.
   */
  resolveReadPolicyPath?(params: {
    filePath: string;
    cwd?: string;
    signal?: AbortSignal;
  }): string | Promise<string>;
  /**
   * Resolves the canonical mutation destination before caller authorization.
   *
   * Returns two views of the same destination:
   * - `policyPath`: the destination in the caller's policy namespace. Path
   *   grants, read-only carveouts, and protected-path policies must be
   *   evaluated against this path.
   * - `pinnedPath`: the canonical mutation target in the bridge's runtime
   *   namespace. Pass it back as `pinnedPath` on the mutation so the pinned
   *   operation lands on exactly the authorized location.
   *
   * The two paths differ when the runtime resolves sandbox aliases onto
   * different host roots. Pinned mutations walk their path without following
   * symlinks, so any component swapped after resolution fails the mutation
   * instead of redirecting it.
   *
   * Directory semantics: for `mkdir` both paths describe the directory
   * itself (which an existing alias may rename); for file-backed actions
   * (`write`, `create`, `remove`, `copy-destination`) both paths describe the
   * canonical parent plus the requested basename, so the basename never
   * changes.
   */
  resolvePinnedMutationTarget?(params: {
    filePath: string;
    cwd?: string;
    action: "write" | "create" | "mkdir" | "remove" | "copy-destination";
    signal?: AbortSignal;
  }): Promise<{
    policyPath: string;
    pinnedPath: string;
  }>;
  /** Directory metadata only; callers paginate it without activating file contents. */
  readDirectory?(params: {
    filePath: string;
    cwd?: string;
    signal?: AbortSignal;
  }): Promise<DirectoryEntry[]>;
  /** Reads a safely opened regular file, rejecting growth beyond an optional byte limit. */
  readFile(params: {
    filePath: string;
    cwd?: string;
    signal?: AbortSignal;
    maxBytes?: number;
    /** Policy path authorized by the caller before this read. */
    expectedPolicyPath?: string;
  }): Promise<Buffer>;
  /**
   * Returns the canonical runtime path pinned by the successful read itself.
   * This identifies directory aliases, not inode equivalence across renames.
   * Consumers that filter protected sources must require this capability;
   * a separate path lookup cannot establish the source of the returned bytes.
   */
  readFileWithSource?(params: Parameters<SandboxFsBridge["readFile"]>[0]): Promise<{
    data: Buffer;
    canonicalPath: string;
    /** Canonical POSIX path within the workspace mount; absent for other mounts. */
    workspaceRelativePath?: string;
  }>;
  /** Streams a regular file within the sandbox when the backend supports native copying. */
  copyFile?(params: {
    sourcePath: string;
    destinationPath: string;
    cwd?: string;
    mkdir?: boolean;
    /** Pre-authorized canonical destination from resolvePinnedMutationTarget. */
    pinnedPath?: string;
    signal?: AbortSignal;
  }): Promise<void>;
  writeFile(params: {
    filePath: string;
    cwd?: string;
    data: Buffer | string;
    encoding?: BufferEncoding;
    mkdir?: boolean;
    /** Pre-authorized canonical mutation target from resolvePinnedMutationTarget. */
    pinnedPath?: string;
    signal?: AbortSignal;
  }): Promise<void>;
  /**
   * Atomically creates a file only when no entry already exists at the path.
   * Backends without this capability must omit it rather than emulate it with
   * a check followed by writeFile.
   */
  createFileExclusive?(params: Parameters<SandboxFsBridge["writeFile"]>[0]): Promise<"created" | "exists">;
  mkdirp(params: {
    filePath: string;
    cwd?: string;
    /** Pre-authorized canonical destination from resolvePinnedMutationTarget. */
    pinnedPath?: string;
    signal?: AbortSignal;
  }): Promise<void>;
  remove(params: {
    filePath: string;
    cwd?: string;
    recursive?: boolean;
    force?: boolean;
    /** Pre-authorized canonical destination from resolvePinnedMutationTarget. */
    pinnedPath?: string;
    signal?: AbortSignal;
  }): Promise<void>;
  rename(params: {
    from: string;
    to: string;
    cwd?: string;
    signal?: AbortSignal;
  }): Promise<void>;
  stat(params: {
    filePath: string;
    cwd?: string;
    /** Policy path authorized by the caller before this read. */
    expectedPolicyPath?: string;
    signal?: AbortSignal;
  }): Promise<SandboxFsStat | null>;
};
//#endregion
//#region src/agents/sandbox/backend-handle.types.d.ts
type SandboxBackendId = string;
type SandboxBackendExecSpec = {
  argv: string[];
  env: NodeJS.ProcessEnv;
  /** Local transport cwd, independent of the remote command's workdir. */
  cwd?: string;
  stdinMode: "pipe-open" | "pipe-closed";
  /** Synchronously revalidate runtime authority at deferred process admission. */
  assertCurrent?: () => void;
  finalizeToken?: unknown;
};
type SandboxBackendWorkdirValidation = "host" | "backend";
type SandboxBackendWorkdirValidator = (workdir: string) => Promise<string | null>;
type SandboxBackendPreparedWorkdirDiscarder = (workdir: string) => void;
type SandboxBackendCommandParams = {
  script: string;
  args?: string[];
  stdin?: Buffer | string;
  allowFailure?: boolean;
  signal?: AbortSignal;
};
type SandboxBackendCommandResult = {
  stdout: Buffer;
  stderr: Buffer;
  code: number;
};
type SandboxFsBridgeContext = {
  workspaceDir: string;
  agentWorkspaceDir: string;
  skillsWorkspaceDir?: string;
  readOnlyResourceMounts?: Array<{
    hostPath: string;
    containerPath: string;
  }>;
  workspaceAccess: "none" | "ro" | "rw";
  containerName: string;
  containerWorkdir: string;
  docker: {
    binds?: string[];
    tmpfs?: string[];
  };
  backend?: {
    runShellCommand(params: SandboxBackendCommandParams): Promise<SandboxBackendCommandResult>;
  };
};
type SandboxBackendHandle = {
  id: SandboxBackendId;
  runtimeId: string;
  runtimeLabel: string;
  workdir: string;
  env?: Record<string, string>;
  configLabel?: string;
  configLabelKind?: string;
  /**
   * Remote backends own cwd existence checks because valid runtime paths may
   * not exist in the local workspace mirror. Backend validation must be paired
   * with validateWorkdir so cwd is proved after before_tool_call adjustments
   * and before env resolution, approval, preflight, and launch.
   */
  workdirValidation?: SandboxBackendWorkdirValidation;
  validateWorkdir?: SandboxBackendWorkdirValidator;
  /** Discard one-shot state created while validating a backend-owned cwd. */
  discardPreparedWorkdir?: SandboxBackendPreparedWorkdirDiscarder;
  /** Remote cwd roots managed by backend validation. Defaults to workdir. */
  workdirRoots?: readonly string[];
  capabilities?: {
    browser?: boolean;
    readOnlyResourceMounts?: boolean;
  };
  buildExecSpec(params: {
    command: string;
    workdir?: string;
    env: Record<string, string>;
    usePty: boolean;
    /** Request piped input without a PTY; callers must honor the returned stdinMode. */
    stdin?: boolean;
  }): Promise<SandboxBackendExecSpec>;
  finalizeExec?: (params: {
    status: "completed" | "failed";
    exitCode: number | null;
    timedOut: boolean;
    token?: unknown;
  }) => Promise<void>;
  /** Mint termination-only custody while execution is admitted; retained cleanup cannot run arbitrary commands. */
  prepareProcessCleanup?: (env: Record<string, string>) => {
    env: Record<string, string>;
    terminate: () => Promise<void>;
    /** Interrupt may run guest signal handlers, so it retains ordinary live execution checks. */
    interrupt: (timeoutMs: number) => Promise<boolean>;
  };
  runShellCommand(params: SandboxBackendCommandParams): Promise<SandboxBackendCommandResult>;
  createFsBridge?: (params: {
    sandbox: SandboxFsBridgeContext;
  }) => SandboxFsBridge;
};
//#endregion
//#region src/state/worker-operation-registry.d.ts
type WorkerOperationContext = {
  open: () => OpenClawStateDatabase;
  stateOptions: () => {
    path: string;
    env: NodeJS.ProcessEnv;
  };
};
type WorkerOperationHandlers<Context = WorkerOperationContext> = Record<string, (input: never, context: Context) => unknown>;
type WorkerOperations<Handlers extends WorkerOperationHandlers<never>> = { [Key in keyof Handlers]: {
  input: Parameters<Handlers[Key]>[0];
  output: ReturnType<Handlers[Key]>;
}; };
type IntersectUnion<T> = (T extends unknown ? (value: T) => void : never) extends ((value: infer Intersection) => void) ? Intersection : never;
type WorkerOperationsFromLoaders<Loaders extends Record<string, () => Promise<WorkerOperationHandlers<never>>>> = IntersectUnion<{ [Key in keyof Loaders]: WorkerOperations<Awaited<ReturnType<Loaders[Key]>>>; }[keyof Loaders]>;
//#endregion
//#region src/cron/inference-binding.d.ts
/** Scheduler-owned identity, not a user model pin or a copy of credential material. */
type CronInferenceBinding = {
  version: 1;
  provider: string;
  profileId: string;
  authorizationId: string;
  authRequirement: ProviderModelRouteAuthRequirement;
  source: "auto" | "user";
  /**
   * The runtime the account was captured for. Runs execute on it instead of re-deriving one
   * from the cron session entry; bindings captured before it existed keep that derivation.
   */
  runtime?: string;
};
//#endregion
//#region src/agents/agent-run-terminal-reply.types.d.ts
type AgentRunTerminalReplySnapshot = {
  disposition: "visible";
  text: string;
  modelRouteChange?: string;
} | {
  disposition: "silent";
} | {
  disposition: "empty";
  code?: "message-tool-not-called";
};
//#endregion
//#region src/auto-reply/reply/normalize-reply-skip-reason.d.ts
type NormalizeReplySkipReason = "empty" | "silent" | "heartbeat" | "channel_transform";
type NormalizeReplyOutcome<T> = {
  kind: "deliver";
  payload: T;
} | {
  kind: "suppress";
  reason: NormalizeReplySkipReason;
};
//#endregion
//#region src/channels/plugins/message-action-names.d.ts
/**
 * Deliberately closed, core-owned vocabulary so every transport can render every action.
 * Plugins add names through a core PR; runtime registration is intentionally unsupported.
 */
declare const CHANNEL_MESSAGE_ACTION_DEFINITIONS: readonly [{
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly sendsContent: true;
  readonly crossContext: "marker";
  readonly name: "send";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "broadcast";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "marker";
  readonly name: "poll";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly name: "poll-vote";
  readonly crossContext: "guard";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly name: "react";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly targetMode: "to";
  readonly name: "reactions";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly targetMode: "to";
  readonly name: "read";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly scheduledWrite: "provider";
  readonly crossContext: "guard";
  readonly name: "edit";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly name: "unsend";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "marker";
  readonly name: "reply";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly sendsContent: true;
  readonly crossContext: "marker";
  readonly name: "sendWithEffect";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly name: "renameGroup";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly name: "setGroupIcon";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly name: "addParticipant";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly name: "removeParticipant";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly name: "leaveGroup";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly sendsContent: true;
  readonly crossContext: "marker";
  readonly name: "sendAttachment";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly scheduledWrite: "provider";
  readonly crossContext: "guard";
  readonly name: "delete";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly scheduledWrite: "provider";
  readonly crossContext: "guard";
  readonly name: "pin";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "to";
  readonly scheduledWrite: "provider";
  readonly crossContext: "guard";
  readonly name: "unpin";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly targetMode: "to";
  readonly name: "list-pins";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly targetMode: "to";
  readonly name: "permissions";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "guard";
  readonly name: "thread-create";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "thread-list";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly sendsContent: true;
  readonly crossContext: "marker";
  readonly name: "thread-reply";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "search";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "marker";
  readonly name: "sticker";
}, {
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "sticker-search";
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "bundled-current-context";
  };
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "member-info";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "role-info";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "emoji-list";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "emoji-upload";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "sticker-upload";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "role-add";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "role-remove";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "channel-info";
  readonly targetMode: "channelId";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "channel-list";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "channel-create";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "conversation-open";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "channelId";
  readonly name: "channel-edit";
  readonly scheduledWrite: "operator";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "channelId";
  readonly name: "channel-delete";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "channelId";
  readonly name: "channel-move";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "category-create";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "category-edit";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "category-delete";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "guard";
  readonly name: "topic-create";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly crossContext: "guard";
  readonly name: "topic-edit";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "voice-status";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "event-list";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "event-create";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "timeout";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "kick";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "ban";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "set-profile";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "none";
  readonly name: "set-presence";
}, {
  readonly readPolicy: {
    readonly kind: "conversation-read";
    readonly targetlessCache: "deny";
  };
  readonly targetMode: "none";
  readonly fencedRead: true;
  readonly readOnly: true;
  readonly name: "download-file";
}, {
  readonly readPolicy: {
    readonly kind: "none";
  };
  readonly targetMode: "to";
  readonly sendsContent: true;
  readonly crossContext: "marker";
  readonly name: "upload-file";
}];
type ActionNames<Definitions extends readonly {
  readonly name: string;
}[]> = { -readonly [Index in keyof Definitions]: Definitions[Index]["name"]; };
declare const CHANNEL_MESSAGE_ACTION_NAMES: Readonly<ActionNames<typeof CHANNEL_MESSAGE_ACTION_DEFINITIONS>>;
type ChannelMessageActionName = (typeof CHANNEL_MESSAGE_ACTION_NAMES)[number];
//#endregion
//#region src/channels/message-access/identifier-authentication.d.ts
/** Ordered strength of one identifier-authentication claim. */
type IdentifierAuthentication = "verified" | "asserted" | "unverified" | "mutable";
declare function meetsIdentifierAuthentication(actual: IdentifierAuthentication, minimum: IdentifierAuthentication): boolean;
//#endregion
//#region src/infra/outbound/send-deps.d.ts
/**
 * Dynamic bag of per-channel send functions, keyed by channel ID.
 * Each outbound adapter resolves its own function from this record and
 * falls back to a direct import when the key is absent.
 */
type OutboundSendDeps = {
  [channelId: string]: unknown;
};
/**
 * Extra historical keys to try after the normalized channel-derived keys.
 */
type ResolveOutboundSendDepOptions = {
  legacyKeys?: readonly string[];
};
/**
 * Resolves a channel send dependency from modern channel IDs or legacy helper keys.
 */
declare function resolveOutboundSendDep<T>(deps: OutboundSendDeps | null | undefined, channelId: string, options?: ResolveOutboundSendDepOptions): T | undefined;
//#endregion
//#region src/channels/message/types.d.ts
type MessageDurabilityPolicy = "required" | "best_effort" | "disabled";
type OutboundReplyFacts = Readonly<{
  source: "explicit";
  replyToId: string;
}> | Readonly<{
  source: "implicit";
  replyToId: string;
  mode: "first" | "all";
}>;
/** Capability names a channel must advertise before core can rely on durable final delivery. */
declare const durableFinalDeliveryCapabilities: readonly ["text", "media", "poll", "payload", "silent", "replyTo", "thread", "nativeQuote", "messageSendingHooks", "batch", "reconcileUnknownSend", "afterSendSuccess", "afterCommit"];
type DurableFinalDeliveryCapability = (typeof durableFinalDeliveryCapabilities)[number];
type DurableFinalDeliveryRequirementMap = Partial<Record<DurableFinalDeliveryCapability, boolean>>;
type DurableFinalDeliveryPayloadShape = {
  text?: string | null;
  replyToId?: string | null;
  mediaUrl?: string | null;
  mediaUrls?: readonly (string | null | undefined)[] | null;
};
type MessageReceiptSourceResult = {
  /** Provider-confirmed intentional omission before dispatch, never an ambiguous send. */
  outcome?: "not_sent";
  channel?: string;
  messageId?: string;
  target?: {
    kind: "chat" | "channel" | "room" | "conversation";
    id: string;
  };
  chatId?: string;
  channelId?: string;
  roomId?: string;
  conversationId?: string;
  toJid?: string;
  pollId?: string;
  timestamp?: number;
  meta?: Record<string, unknown>;
};
type MessageReceiptPartKind = "text" | "media" | "voice" | "poll" | "card" | "preview" | "unknown";
/** One platform message produced by a logical outbound send. */
type MessageReceiptPart = {
  platformMessageId: string;
  kind: MessageReceiptPartKind;
  index: number;
  threadId?: string;
  replyToId?: string;
  raw?: MessageReceiptSourceResult;
};
/** Normalized receipt for all platform messages that make up a logical send. */
type MessageReceipt = {
  primaryPlatformMessageId?: string;
  platformMessageIds: string[];
  parts: MessageReceiptPart[];
  threadId?: string;
  replyToId?: string;
  editToken?: string;
  deleteToken?: string;
  sentAt: number;
  raw?: readonly MessageReceiptSourceResult[];
  /** Normalized physical send evidence, retained even when a source has no platform ID. */
  sourceResults?: readonly MessageReceiptSourceResult[];
};
type RenderedMessageBatchPlanKind = "text" | "media" | "voice" | "presentation" | "interactive" | "channelData" | "empty";
type RenderedMessageBatchPlanItem = {
  index: number;
  kinds: readonly RenderedMessageBatchPlanKind[];
  text?: string;
  mediaUrls: readonly string[];
  audioAsVoice?: boolean;
  presentationBlockCount?: number;
  hasInteractive?: boolean;
  hasChannelData?: boolean;
};
type RenderedMessageBatchPlan = {
  payloadCount: number;
  textCount: number;
  mediaCount: number;
  voiceCount: number;
  presentationCount: number;
  interactiveCount: number;
  channelDataCount: number;
  items: readonly RenderedMessageBatchPlanItem[];
};
/** Rendered payload batch paired with the plan core uses for send routing and recovery. */
type RenderedMessageBatch<TPayload = unknown> = {
  payloads: TPayload[];
  plan: RenderedMessageBatchPlan;
};
type LiveMessagePhase = "idle" | "previewing" | "finalizing" | "finalized" | "cancelled";
type LiveMessageState<TPayload = unknown> = {
  phase: LiveMessagePhase;
  canFinalizeInPlace: boolean;
  receipt?: MessageReceipt;
  lastRendered?: RenderedMessageBatch<TPayload>;
};
type MessageSendContext<TPayload = unknown, TSendResult = unknown> = {
  id: string;
  channel: string;
  to: string;
  accountId?: string;
  durability: Exclude<MessageDurabilityPolicy, "disabled">;
  attempt: number;
  signal: AbortSignal;
  intent?: DurableMessageSendIntent;
  previousReceipt?: MessageReceipt;
  preview?: LiveMessageState<TPayload>;
  render(): Promise<RenderedMessageBatch<TPayload>>;
  previewUpdate(rendered: RenderedMessageBatch<TPayload>): Promise<LiveMessageState<TPayload>>;
  send(rendered: RenderedMessageBatch<TPayload>): Promise<TSendResult>;
  edit(receipt: MessageReceipt, rendered: RenderedMessageBatch<TPayload>): Promise<MessageReceipt>;
  delete(receipt: MessageReceipt): Promise<void>;
  commit(receipt: MessageReceipt): Promise<void>;
  fail(error: unknown): Promise<void>;
};
type ChannelMessageSendTextContext<TConfig = OpenClawConfig> = {
  cfg: TConfig;
  to: string;
  text: string;
  /** Host-resolved session that produced this send, distinct from the destination session. */
  sessionKey?: string;
  accountId?: string | null;
  deps?: OutboundSendDeps;
  replyToId?: string | null;
  replyToIdSource?: "explicit" | "implicit";
  replyToMode?: ReplyToMode;
  threadId?: string | number | null;
  silent?: boolean;
  /** Live cancellation signal; check before each physical send and after awaited preparation. */
  signal?: AbortSignal;
  gatewayClientScopes?: readonly string[];
  /** @internal Opaque durable intent id for exact provider-side send reconciliation. */
  deliveryQueueId?: string;
  /** @internal Stable platform-send index within one durable payload. */
  deliveryPartIndex?: number;
  /** @internal Exact platform-send count within one durable payload. */
  deliveryPartCount?: number;
  /** @internal Channel-valid id reserved before a correlated conversation turn is sent. */
  preparedMessageId?: string;
  /** @internal Refresh durable timing before recipient-visible or finalizing platform I/O. */
  onPlatformSendDispatch?: () => Promise<void>;
  /** @internal Synchronously fence custody after refresh and immediately before provider I/O. */
  assertDirectAdapterHandoff?: () => void;
  /** @internal Report each completed platform sub-send before another fallible step. */
  onDeliveryResult?: (result: ChannelMessageSendResult) => Promise<void> | void;
};
type ChannelMessageSendMediaContext<TConfig = OpenClawConfig> = ChannelMessageSendTextContext<TConfig> & {
  mediaUrl: string;
  mediaAccess?: OutboundMediaAccess;
  mediaLocalRoots?: readonly string[];
  mediaReadFile?: (filePath: string) => Promise<Buffer>;
  audioAsVoice?: boolean;
  gifPlayback?: boolean;
  /** Send image, GIF, or video as document to avoid channel compression. */
  forceDocument?: boolean;
};
type ChannelMessageSendPayloadContext<TConfig = OpenClawConfig> = Omit<ChannelMessageSendMediaContext<TConfig>, "mediaUrl"> & {
  payload: ReplyPayload$1;
  mediaUrl?: string;
};
/** Poll send context; thread ids stay string-like because poll APIs do not accept numeric ids. */
type ChannelMessageSendPollContext<TConfig = OpenClawConfig> = Omit<ChannelMessageSendTextContext<TConfig>, "text" | "threadId"> & {
  poll: PollInput;
  threadId?: string | null;
  isAnonymous?: boolean;
};
type ChannelMessageSendResult = {
  outcome?: MessageReceiptSourceResult["outcome"];
  receipt: MessageReceipt;
  messageId?: string;
  target?: MessageReceiptSourceResult["target"];
};
/** Concrete send shapes an adapter can reconcile after an unknown platform outcome. */
declare const unknownSendReconciliationKinds: readonly ["text", "media", "payload", "poll", "batch"];
type UnknownSendReconciliationKind = (typeof unknownSendReconciliationKinds)[number];
type ChannelMessageSendAttemptContext<TConfig = OpenClawConfig> = (ChannelMessageSendTextContext<TConfig> & {
  kind: "text";
}) | (ChannelMessageSendMediaContext<TConfig> & {
  kind: "media";
}) | (ChannelMessageSendPayloadContext<TConfig> & {
  kind: "payload";
}) | (ChannelMessageSendPollContext<TConfig> & {
  kind: "poll";
});
type ChannelMessageSendCommitContext<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = ChannelMessageSendAttemptContext<TConfig> & {
  result: TSendResult;
  attemptToken?: unknown;
};
type ChannelMessageSendFailureContext<TConfig = OpenClawConfig> = ChannelMessageSendAttemptContext<TConfig> & {
  error: unknown;
  attemptToken?: unknown;
};
type ChannelMessageUnknownSendContext<TConfig = OpenClawConfig> = {
  cfg: TConfig;
  queueId: string;
  channel: string;
  to: string;
  accountId?: string | null;
  enqueuedAt: number;
  retryCount: number;
  platformSendStartedAt?: number;
  /** Canonical reply target persisted after hooks and before platform I/O. */
  effectiveReplyToId?: string | null;
  payloads: readonly ReplyPayload$1[];
  renderedBatchPlan?: RenderedMessageBatchPlan;
  replyToId?: string | null;
  replyToMode?: ReplyToMode;
  threadId?: string | number | null;
  silent?: boolean;
};
type ChannelMessageUnknownSendReconciliationResult = {
  status: "sent";
  receipt: MessageReceipt;
  messageId?: string;
} | {
  status: "not_sent";
} | {
  status: "unresolved";
  error?: string;
  retryable?: boolean;
};
/** Provider decision made before core persists or replays a deferred delivery. */
type ChannelMessageDeferredDeliveryAdmissionResult = {
  status: "allowed";
} | {
  status: "permanent_rejection";
  reason: string;
};
type ChannelMessageDeferredDeliveryAdmissionContext<TConfig = OpenClawConfig> = {
  cfg: TConfig;
  channel: string;
  to: string;
  accountId?: string | null;
  phase: "live" | "recovery";
};
type ChannelMessageSendLifecycleAdapter<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = {
  beforeSendAttempt?: (ctx: ChannelMessageSendAttemptContext<TConfig>) => unknown;
  afterSendSuccess?: (ctx: ChannelMessageSendCommitContext<TConfig, TSendResult>) => Promise<void> | void;
  afterSendFailure?: (ctx: ChannelMessageSendFailureContext<TConfig>) => Promise<void> | void;
  afterCommit?: (ctx: ChannelMessageSendCommitContext<TConfig, TSendResult>) => Promise<void> | void;
};
type ChannelMessageSendAdapter<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = {
  text?: (ctx: ChannelMessageSendTextContext<TConfig>) => Promise<TSendResult>;
  media?: (ctx: ChannelMessageSendMediaContext<TConfig>) => Promise<TSendResult>;
  payload?: (ctx: ChannelMessageSendPayloadContext<TConfig>) => Promise<TSendResult>;
  poll?: (ctx: ChannelMessageSendPollContext<TConfig>) => Promise<TSendResult>;
  lifecycle?: ChannelMessageSendLifecycleAdapter<TConfig, TSendResult>;
};
type ChannelMessageDurableFinalAdapter = {
  capabilities?: DurableFinalDeliveryRequirementMap;
  /** Opt into provider reconciliation for ordinary single-payload queued sends. */
  automaticUnknownSendReconciliation?: boolean;
  /** Recognize inert channel metadata without admitting controls or side effects. */
  isTextOnlyChannelData?: (channelData: NonNullable<ReplyPayload$1["channelData"]>) => boolean;
  /**
   * Synchronous provider admission before a durable intent is created or replayed.
   * Providers must not perform I/O from this hook.
   */
  admitDeferredDelivery?: (ctx: ChannelMessageDeferredDeliveryAdmissionContext) => ChannelMessageDeferredDeliveryAdmissionResult;
  /** Send shapes for which reconciliation can prove the complete durable intent. */
  reconcileUnknownSendKinds?: Partial<Record<UnknownSendReconciliationKind, boolean>>;
  reconcileUnknownSend?: (ctx: ChannelMessageUnknownSendContext) => Promise<ChannelMessageUnknownSendReconciliationResult | null> | ChannelMessageUnknownSendReconciliationResult | null;
  /** Cleanup after core authoritatively retires an ambiguous send as failed. */
  afterUnknownSendTerminal?: (ctx: ChannelMessageUnknownSendContext) => Promise<void> | void;
};
type ChannelMessageLiveCapability = (typeof channelMessageLiveCapabilities)[number];
declare const channelMessageLiveCapabilities: readonly ["draftPreview", "previewFinalization", "progressUpdates", "nativeStreaming", "quietFinalization"];
declare const livePreviewFinalizerCapabilities: readonly ["finalEdit", "normalFallback", "discardPending", "previewReceipt", "retainOnAmbiguousFailure"];
type LivePreviewFinalizerCapability = (typeof livePreviewFinalizerCapabilities)[number];
type ChannelMessageLiveAdapterShape = {
  capabilities?: Partial<Record<ChannelMessageLiveCapability, boolean>>;
  finalizer?: {
    capabilities?: Partial<Record<LivePreviewFinalizerCapability, boolean>>;
  };
};
type ChannelMessageReceiveAckPolicy = (typeof channelMessageReceiveAckPolicies)[number];
declare const channelMessageReceiveAckPolicies: readonly ["after_receive_record", "after_agent_dispatch", "after_durable_send", "manual"];
type ChannelMessageReceiveAdapterShape = {
  defaultAckPolicy?: ChannelMessageReceiveAckPolicy;
  supportedAckPolicies?: readonly ChannelMessageReceiveAckPolicy[];
};
type ChannelMessageAdapterShape<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = {
  id?: string;
  durableFinal?: ChannelMessageDurableFinalAdapter;
  send?: ChannelMessageSendAdapter<TConfig, TSendResult>;
  live?: ChannelMessageLiveAdapterShape;
  receive?: ChannelMessageReceiveAdapterShape;
};
/** Concrete message adapter type, preserving channel-specific adapter refinements. */
type ChannelMessageAdapter<TAdapter extends ChannelMessageAdapterShape = ChannelMessageAdapterShape> = TAdapter;
type DeriveDurableFinalDeliveryRequirementsParams = {
  payload: DurableFinalDeliveryPayloadShape;
  replyToId?: string | null;
  threadId?: string | number | null;
  silent?: boolean;
  messageSendingHooks?: boolean;
  payloadTransport?: boolean;
  batch?: boolean;
  reconcileUnknownSend?: boolean;
  afterSendSuccess?: boolean;
  afterCommit?: boolean;
  extraCapabilities?: DurableFinalDeliveryRequirementMap;
};
type DurableMessageSendIntent<TPayload = unknown> = {
  id: string;
  channel: string;
  to: string;
  accountId?: string;
  durability: Exclude<MessageDurabilityPolicy, "disabled">;
  renderedBatch?: RenderedMessageBatch<TPayload>;
};
//#endregion
//#region src/channels/plugins/conversation-read-origin.d.ts
/**
 * Server-owned origin for one tool or message-action invocation.
 *
 * Missing and unknown values must remain delegated; callers must never derive
 * this from model arguments, provider parameters, config, or persisted state.
 */
type ConversationReadInvocationOrigin = "delegated" | "direct-operator";
//#endregion
//#region src/channels/plugins/message-capabilities.d.ts
type ChannelMessageCapability = "presentation" | "delivery-pin";
//#endregion
//#region src/channels/plugins/legacy-state-migration.types.d.ts
type ChannelLegacyStateMigrationPlan = {
  kind: "copy" | "move";
  label: string;
  sourcePath: string;
  targetPath: string;
} | {
  kind: "plugin-state-import";
  label: string;
  sourcePath: string;
  targetPath: string;
  pluginId: string;
  namespace: string;
  maxEntries: number;
  defaultTtlMs?: number;
  scopeKey: string;
  stateDir?: string;
  cleanupSource?: "rename" | "remove";
  cleanupWhenEmpty?: boolean;
  /** Only for unused artifacts whose retained bytes cannot affect runtime state. */
  cleanupWarningDisposition?: "recoverable";
  /** Deletes a non-file legacy source (e.g. plugin-state rows) once all entries are covered. */
  removeSource?: () => void | Promise<void>;
  preview?: string;
  shouldReplaceExistingEntry?: (params: {
    key: string;
    existingValue: unknown;
    incomingValue: unknown;
  }) => boolean | Promise<boolean>;
  /**
   * `timestamp` (epoch ms) and `ttlMs` order entries newest-first when capacity forces a
   * partial import; `timestamp` is also persisted as the migrated row's creation time so
   * cap eviction keeps treating imported rows as old as their legacy source.
   */
  readEntries: () => Array<{
    key: string;
    value: unknown;
    ttlMs?: number;
    timestamp?: number;
  }> | Promise<Array<{
    key: string;
    value: unknown;
    ttlMs?: number;
    timestamp?: number;
  }>>;
};
//#endregion
//#region src/channels/plugins/types.core.d.ts
type ChannelOutboundTargetMode = "explicit" | "implicit" | "heartbeat";
type ChannelAgentTool = AgentTool;
/** Lazy agent-tool factory used when tool availability depends on config. */
type ChannelAgentToolFactory = (params: {
  cfg?: OpenClawConfig;
}) => ChannelAgentTool[];
/**
 * Discovery-time inputs passed to channel action adapters when the core is
 * asking what an agent should be allowed to see. This is intentionally
 * smaller than execution context: it carries routing/account scope, but no
 * tool params or runtime handles.
 */
type ChannelMessageActionDiscoveryContext = {
  cfg: OpenClawConfig;
  chatType?: ChatType | null;
  currentChannelId?: string | null;
  currentChannelProvider?: string | null;
  currentThreadTs?: string | null;
  currentMessageId?: string | number | null;
  accountId?: string | null;
  sessionKey?: string | null;
  sessionId?: string | null;
  agentId?: string | null;
  requesterSenderId?: string | null;
  senderIsOwner?: boolean;
};
/**
 * Plugin-owned schema fragments for the shared `message` tool.
 * `current-channel` means expose the fields only when that provider is the
 * active runtime channel. `all-configured` keeps the fields visible even while
 * another configured channel is active, which is useful for cross-channel
 * sends from cron or isolated agents.
 */
type ChannelMessageToolSchemaContribution = {
  properties: Record<string, TSchema>;
  /**
   * Actions whose validation depends on this schema fragment. Cross-channel
   * discovery can hide only these actions when the fragment is current-channel
   * scoped. Omit to keep the legacy conservative behavior.
   */
  actions?: readonly ChannelMessageActionName[] | null;
  visibility?: "current-channel" | "all-configured";
};
type ChannelMessageToolDiscovery = {
  actions?: readonly ChannelMessageActionName[] | null;
  capabilities?: readonly ChannelMessageCapability[] | null;
  schema?: ChannelMessageToolSchemaContribution | ChannelMessageToolSchemaContribution[] | null;
  /**
   * Plugin-owned message-tool params that carry media sources.
   * Core uses this to derive sandbox path normalization and host media-access
   * hints without hardcoding plugin-specific param names. Prefer scoping keys
   * by action so unrelated actions do not inherit another action's media args.
   */
  mediaSourceParams?: readonly string[] | Partial<Record<ChannelMessageActionName, readonly string[]>> | null;
};
type ChannelStatusIssue = SchemaContract<Omit<NonNullable<ChannelsStatusResult["statusIssues"]>[number], "channel">> & {
  channel: ChannelId$1;
};
type ChannelAccountState = "linked" | "not linked" | "configured" | "not configured" | "enabled" | "disabled";
type ChannelHeartbeatDeps = {
  webAuthExists?: () => Promise<boolean>;
  hasActiveWebListener?: (accountId?: string) => boolean;
};
/** Snapshot row returned by channel status and lifecycle surfaces. */
type ChannelAccountSnapshot = SchemaContract<Omit<ChannelsStatusResult["channelAccounts"][string][number], "healthState" | "credentialSource" | "audienceType" | "audience" | "webhookPath" | "webhookUrl">> & {
  statusState?: string;
  restartPending?: boolean;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | null;
  lastMessageAt?: number | null;
  lastEventAt?: number | null;
  stateReason?: string;
  /**
   * Legacy channel-authored health label; channel plugins should publish `lifecycle` instead.
   * Core-derived policy writes remain supported. There is no removal date; removal awaits
   * external plugin adoption.
   */
  healthState?: string;
  /**
   * Recorded account lifecycle, independent of inferred transport health.
   * Optional so channels that never publish lifecycle remain unaffected.
   */
  lifecycle?: "starting" | "ready" | "recovering" | "blocked" | "stopped";
  /**
   * Inbound admission, which is a different failure domain from `connected`.
   * Optional-`true` on purpose: there is no `false` to mistake for "unknown",
   * so the 20+ channels that never report ingress at all stay unaffected.
   */
  ingressUnavailable?: true;
  terminalDisconnect?: boolean;
  userTokenSource?: string;
  signingSecretSource?: string;
  tokenStatus?: string;
  botTokenStatus?: string;
  appTokenStatus?: string;
  signingSecretStatus?: string;
  userTokenStatus?: string;
  apiCredentialStatus?: "available" | "configured_unavailable" | "missing";
  identity?: string;
  credentialSource?: string;
  secretSource?: string;
  audienceType?: string;
  audience?: string;
  webhookPath?: string;
  webhookUrl?: string;
  bot?: unknown;
  publicKey?: string | null;
  profile?: unknown;
  channelAccessToken?: string;
  channelSecret?: string;
};
type ChannelLogSink = {
  info: (msg: string) => void;
  warn: (msg: string) => void;
  error: (msg: string) => void;
  debug?: (msg: string) => void;
};
type ChannelGroupContext = {
  cfg: OpenClawConfig;
  groupId?: string | null;
  /** Human label for channel-like group conversations (e.g. #general). */
  groupChannel?: string | null;
  groupSpace?: string | null;
  accountId?: string | null;
  /** Trusted host instruction to ignore toolsBySender for non-ingress work. */
  senderPolicyMode?: "always" | "never";
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
};
/** Authenticated direct-conversation facts evaluated against an admitted config snapshot. */
type ChannelDirectToolPolicyContext = Omit<ChannelGroupContext, "groupId" | "groupChannel" | "groupSpace"> & {
  conversationId: string;
};
type ChannelTtsVoiceDeliveryCapabilities = {
  synthesisTarget: "audio-file" | "voice-note";
  transcodesAudio?: boolean;
  audioFileFormats?: readonly string[];
  /** Voice notes can carry the final reply text as a visible caption. */
  captionedFinalText?: boolean;
  /**
   * Preferred file-extension token, without a leading dot, for host pre-transcoding.
   * Conversion requires an available transcoder (e.g. `afconvert` on macOS).
   * iMessage uses CAF for native voice memos to avoid a downstream conversion/upload race.
   * New formats require a matching host transcoder recipe.
   */
  preferAudioFileFormat?: "caf";
};
type ChannelCapabilities = {
  chatTypes: Array<ChatType | "thread">;
  polls?: boolean;
  reactions?: boolean;
  /** Bot reactions per message; omitted means multiple independent emoji. */
  reactionSlots?: "single" | "multiple";
  edit?: boolean;
  unsend?: boolean;
  reply?: boolean;
  effects?: boolean;
  groupManagement?: boolean;
  threads?: boolean;
  media?: boolean;
  tts?: {
    voice?: ChannelTtsVoiceDeliveryCapabilities;
  };
  nativeCommands?: boolean;
  blockStreaming?: boolean;
};
type ChannelSecurityDmPolicy = {
  policy: string;
  allowFrom?: Array<string | number> | null;
  policyPath?: string;
  allowFromPath: string;
  approveHint: string;
  normalizeEntry?: (raw: string) => string;
  classifyEntryAuthentication?: (raw: string) => IdentifierAuthentication | undefined;
};
type ChannelSecurityContext<ResolvedAccount = unknown> = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  account: ResolvedAccount;
};
type ChannelMentionAdapter = {
  stripRegexes?: (params: {
    ctx: MsgContext;
    cfg: OpenClawConfig | undefined;
    agentId?: string;
  }) => RegExp[];
  stripPatterns?: (params: Parameters<NonNullable<ChannelMentionAdapter["stripRegexes"]>>[0]) => string[];
  stripMentions?: (params: Parameters<NonNullable<ChannelMentionAdapter["stripRegexes"]>>[0] & {
    text: string;
  }) => string;
};
type ChannelStreamingAdapter = {
  blockStreamingCoalesceDefaults?: {
    minChars: number;
    idleMs: number;
  };
};
type ChannelStructuredComponents = unknown[];
type ChannelOutboundSessionRoute = {
  sessionKey: string;
  baseSessionKey: string;
  /** Route authority for explicit recipient session selection. */
  recipientSessionExact?: boolean | "direct-alias" | "delivery-identity";
  peer: {
    kind: ChatType;
    id: string;
  };
  chatType: ChatType;
  from: string;
  to: string;
  threadId?: string | number;
};
type ChannelThreadingAdapter = {
  /**
   * Where the transport keeps thread identity.
   * "address" (default): the thread is part of the routing address (own channel id, topic id
   * in the target tuple), fully known before send.
   * "message": thread identity lives on a message (e.g. Slack thread_ts) — replying to a
   * message enters its thread, and routes can discover a session-scoping thread only after
   * target lookup.
   */
  threadAddressing?: "address" | "message";
  /** True only if omitting this thread id sends to the exact same transport destination. */
  isThreadAddressedByTarget?: (params: {
    to: string;
    threadId: string | number;
  }) => boolean;
  matchesToolContextTarget?: (params: {
    target: string;
    toolContext: ChannelThreadingToolContext;
  }) => boolean;
  resolveReplyToMode?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    chatType?: string | null;
  }) => ReplyToMode;
  /**
   * When replyToMode is "off", allow explicit reply tags/directives to keep replyToId.
   *
   * Default in shared reply flow: true for known providers; per-channel opt-out supported.
   */
  allowExplicitReplyTagsWhenOff?: boolean;
  /**
   * @deprecated Use allowExplicitReplyTagsWhenOff.
   *
   * Deprecated alias for allowExplicitReplyTagsWhenOff.
   * Kept for compatibility with older plugin surfaces.
   */
  allowTagsWhenOff?: boolean;
  buildToolContext?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    context: ChannelThreadingContext;
    hasRepliedRef?: {
      value: boolean;
    };
  }) => ChannelThreadingToolContext | undefined;
  resolveAutoThreadId?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    to: string;
    toolContext?: ChannelThreadingToolContext;
    replyToId?: string | null;
  }) => string | undefined;
  resolveCurrentChannelId?: (params: {
    to: string;
    threadId?: string | number | null;
  }) => string | undefined;
  resolveReplyTransport?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    /** Originating inbound message in this routed channel; not an explicit reply target. */
    currentMessageId?: string;
    threadId?: string | number | null;
    replyToId?: string | null;
    /** True when replyToId came from an explicit payload target or reply tag. */
    replyToIsExplicit?: boolean;
    /** Existing payload intent to reply to the current conversation, not an arbitrary target. */
    replyToCurrent?: boolean;
    replyDelivery?: ReplyDeliveryContext;
  }) => {
    replyToId?: string | null;
    /** Mark a channel-inferred target so outbound delivery can consume first-mode replies. */
    replyToIdSource?: "implicit";
    threadId?: string | number | null;
  } | null;
  resolveFocusedBinding?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    context: ChannelThreadingContext;
  }) => {
    conversationId: string;
    parentConversationId?: string;
    placement: "current" | "child";
    labelNoun: string;
  } | null;
};
type ChannelThreadingContext = {
  Channel?: string;
  From?: string;
  To?: string;
  ChatType?: string;
  CurrentMessageId?: string | number;
  /** Effective channel reply mode prepared for this turn. */
  ReplyToMode?: MsgContext["ReplyToMode"];
  ReplyToId?: string;
  ReplyToIdFull?: string;
  ThreadLabel?: string;
  MessageThreadId?: string | number;
  TransportThreadId?: string | number;
  /** Platform-native channel/conversation id (e.g. Slack DM channel "D…" id). */
  NativeChannelId?: string;
};
type ChannelThreadingToolContext = {
  currentChannelId?: string;
  /** Trusted normalized conversation kind for the active inbound turn. */
  currentChatType?: ChatType;
  /** Routable messaging target when it differs from the platform-native channel id. */
  currentMessagingTarget?: string;
  currentGraphChannelId?: string;
  currentChannelProvider?: ChannelId$1;
  currentThreadTs?: string;
  currentMessageId?: string | number;
  replyToMode?: ReplyToMode;
  hasRepliedRef?: {
    value: boolean;
  };
  /** True when posting at the parent conversation root would leak a thread-originated reply. */
  sameChannelThreadRequired?: boolean;
  /**
   * When true, skip cross-context decoration (e.g., "[from X]" prefix).
   * Use this for direct tool invocations where the agent is composing a new message,
   * not forwarding/relaying a message from another conversation.
   */
  skipCrossContextDecoration?: boolean;
};
/** Channel-owned messaging helpers for target parsing, routing, and payload shaping. */
type ChannelMessagingAdapter = {
  /**
   * Provider prefixes accepted in explicit targets, including aliases not used
   * as channel-selection aliases. Core uses these to reject cross-channel
   * targets before plugin-specific normalization.
   */
  targetPrefixes?: readonly string[];
  /** @deprecated Use prepareConversationRouteOwnersAsync for worker-backed route ownership. */
  resolveConversationRouteOwner?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    conversation: {
      kind: ChatType;
      peerId: string;
      /** Canonical delivery target when it differs from the routing peer. */
      target?: string;
      threadId?: string;
      nativeChannelId?: string;
      context?: {
        parentPeerId?: string;
        guildId?: string;
        teamId?: string;
        memberRoleIds?: string[];
      };
    };
  }) => {
    kind: "agent";
    agentId: string;
  } | {
    kind: "plugin";
    pluginId: string;
    fallbackAgentId: string;
  } | {
    kind: "unavailable";
  } | null | undefined;
  /** Prepare binding facts in workers; returned resolvers run under the current effect grant. */
  prepareConversationRouteOwnersAsync?: (params: readonly Parameters<NonNullable<ChannelMessagingAdapter["resolveConversationRouteOwner"]>>[0][], inspectBindings: (refs: readonly ConversationRef[]) => Promise<() => readonly SessionBindingInspection[]>) => Promise<readonly NonNullable<ChannelMessagingAdapter["resolveConversationRouteOwner"]>[]>;
  /** DM targets rebuilt from session keys require an explicit `user:` kind prefix. */
  directTargetStyle?: "user-prefixed";
  /** Equality rule for ids carried by prefixed outbound targets. */
  targetIdComparison?: "case-sensitive" | "lowercase";
  /** Bare numeric conversation/topic shorthand is valid for this channel. */
  numericTopicShorthand?: true;
  normalizeTarget?: (raw: string) => string | undefined;
  defaultMarkdownTableMode?: MarkdownTableMode;
  normalizeExplicitSessionKey?: (params: {
    sessionKey: string;
    ctx: MsgContext;
  }) => string | undefined;
  deriveLegacySessionChatType?: (sessionKey: string) => ChatType | undefined;
  isLegacyGroupSessionKey?: (key: string) => boolean;
  canonicalizeLegacySessionKey?: (params: {
    key: string;
    agentId: string;
  }) => string | null | undefined;
  resolveLegacyGroupSessionKey?: (ctx: MsgContext) => {
    key: string;
    channel: string;
    id: string;
    chatType: "group" | "channel";
  } | null;
  resolveInboundAttachmentRoots?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => string[];
  resolveRemoteInboundAttachmentRoots?: NonNullable<ChannelMessagingAdapter["resolveInboundAttachmentRoots"]>;
  /**
   * Bundled plugins that need inbound conversation resolution before runtime
   * bootstrap can mirror it through a top-level `thread-binding-api.ts` surface.
   */
  resolveInboundConversation?: (params: {
    from?: string;
    to?: string;
    conversationId?: string;
    threadId?: string | number;
    threadParentId?: string | number;
    isGroup: boolean;
  }) => {
    conversationId?: string;
    parentConversationId?: string;
  } | null;
  resolveDeliveryTarget?: (params: {
    conversationId: string;
    parentConversationId?: string;
  }) => {
    to?: string;
    threadId?: string;
  } | null;
  /**
   * Canonical plugin-owned session conversation grammar.
   * Use this when the provider encodes thread or scoped-conversation semantics
   * inside `rawId` (for example Telegram topics or Feishu sender scopes).
   * Return `baseConversationId` and `parentConversationCandidates` here when
   * you can so parsing and inheritance stay in one place.
   * `parentConversationCandidates`, when present, should be ordered from the
   * narrowest parent to the broadest/base conversation.
   * Bundled plugins that need the same grammar before runtime bootstrap can
   * mirror this contract through a top-level `session-key-api.ts` surface.
   */
  resolveSessionConversation?: (params: {
    kind: "group" | "channel";
    rawId: string;
  }) => {
    id: string;
    threadId?: string | null;
    baseConversationId?: string | null;
    parentConversationCandidates?: string[];
  } | null;
  /**
   * @deprecated Return parentConversationCandidates from resolveSessionConversation.
   *
   * Legacy compatibility hook for parent fallbacks when a plugin does not need
   * to customize `id` or `threadId`. Core only uses this when
   * `resolveSessionConversation(...)` does not return
   * `parentConversationCandidates`.
   */
  resolveParentConversationCandidates?: (params: Parameters<NonNullable<ChannelMessagingAdapter["resolveSessionConversation"]>>[0]) => string[] | null;
  resolveSessionTarget?: (params: {
    kind: "group" | "channel";
    id: string;
    threadId?: string | null;
  }) => string | undefined;
  /**
   * Lightweight chat-type inference used before directory lookup so plugins can
   * steer peer-vs-group resolution without reimplementing host search flow.
   */
  inferTargetChatType?: (params: {
    to: string;
  }) => ChatType | undefined;
  /**
   * Preserve the session thread/topic id for heartbeat replies when that thread
   * is part of the destination identity, not a transient reply thread.
   */
  preserveHeartbeatThreadIdForGroupRoute?: boolean;
  buildCrossContextPresentation?: (params: {
    originLabel: string;
    message: string;
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => MessagePresentation;
  transformReplyPayload?: (params: {
    payload: ReplyPayload$1;
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => ReplyPayload$1 | null;
  hasStructuredReplyPayload?: (params: {
    payload: ReplyPayload$1;
  }) => boolean;
  targetResolver?: {
    looksLikeId?: (raw: string, normalized?: string) => boolean;
    hint?: string;
    /** Bare words that are command/session references for this channel, not literal destinations. */
    reservedLiterals?: readonly string[];
    /**
     * Plugin-owned fallback for explicit/native targets or post-directory-miss
     * resolution. This should complement directory lookup, not duplicate it.
     */
    resolveTarget?: (params: {
      cfg: OpenClawConfig;
      accountId?: string | null;
      input: string;
      normalized: string;
      preferredKind?: ChannelDirectoryEntryKind | "channel";
    }) => Promise<{
      to: string;
      kind: ChannelDirectoryEntryKind | "channel";
      display?: string;
      source?: "normalized" | "directory";
    } | null>;
  };
  formatTargetDisplay?: (params: {
    target: string;
    display?: string;
    kind?: ChannelDirectoryEntryKind;
  }) => string;
  /**
   * Provider-specific session-route builder used after target resolution.
   * Keep session-key orchestration in core and channel-native routing rules here.
   * Set `recipientSessionExact` to true only when the target maps unambiguously
   * to the same canonical session that inbound delivery uses. `direct-alias`
   * may be used when only the direct chat kind is authoritative.
   * `delivery-identity` requires a stable outbound-only recipient identity and
   * a provider-keyed session that stays isolated from the agent main session.
   */
  resolveOutboundSessionRoute?: (params: {
    cfg: OpenClawConfig;
    agentId: string;
    accountId?: string | null;
    target: string;
    /** Identifies implicit operator delivery; other callers must supply their own destination. */
    deliveryPurpose?: "heartbeat-owner";
    currentSessionKey?: string;
    resolvedTarget?: {
      to: string;
      kind: ChannelDirectoryEntryKind | "channel";
      display?: string;
      source: "normalized" | "directory";
    };
    replyToId?: string | null;
    threadId?: string | number | null;
    /** Revalidates transport authority before new route-discovery network requests. */
    assertDirectAdapterHandoff?: () => void;
  }) => ChannelOutboundSessionRoute | Promise<ChannelOutboundSessionRoute | null> | null;
};
type ChannelAgentPromptAdapter = {
  /** Native controls that can present and resolve structured user questions. */
  questionInputMode?: "buttons";
  /** The channel supplies its own inline-button guidance through messageToolHints. */
  customInlineButtonHint?: boolean;
  messageToolHints?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => string[];
  messageToolCapabilities?: (params: Parameters<NonNullable<ChannelAgentPromptAdapter["messageToolHints"]>>[0]) => string[] | undefined;
  /** Per-account formatting contract for agent turns whose visible text reaches this channel. */
  inboundFormattingHints?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => {
    text_markup: string;
    rules: string[];
  } | undefined;
  reactionGuidance?: (params: Parameters<NonNullable<ChannelAgentPromptAdapter["messageToolHints"]>>[0]) => {
    level: "minimal" | "extensive";
    channelLabel?: string;
  } | undefined;
};
type ChannelDirectoryEntryKind = "user" | "group" | "channel";
type ChannelDirectoryEntry = {
  kind: ChannelDirectoryEntryKind;
  id: string;
  name?: string;
  handle?: string;
  avatarUrl?: string;
  rank?: number;
  raw?: unknown;
};
/** Execution context passed to channel-owned actions on the shared `message` tool. */
type ChannelMessageActionContext = {
  channel: ChannelId$1;
  action: ChannelMessageActionName;
  cfg: OpenClawConfig;
  params: Record<string, unknown>;
  /** Host-prepared progress display state; never sourced from model-controlled params. */
  progressSnapshot?: ChannelProgressDraftCompositorSnapshot;
  reply?: OutboundReplyFacts;
  mediaAccess?: OutboundMediaAccess;
  mediaLocalRoots?: readonly string[];
  mediaReadFile?: (filePath: string) => Promise<Buffer>;
  accountId?: string | null;
  /** Trusted originating account id paired with requesterSenderId. */
  requesterAccountId?: string | null;
  /**
   * Trusted sender id from inbound context. This is server-injected and must
   * never be sourced from tool/model-controlled params.
   */
  requesterSenderId?: string | null;
  /** Trusted owner identity bit from command/channel-action auth. */
  senderIsOwner?: boolean;
  /**
   * Server-owned origin for this operation. Missing values are delegated.
   * Plugins must use it only for conversation-read visibility policy.
   */
  conversationReadOrigin?: ConversationReadInvocationOrigin;
  sessionKey?: string | null;
  sessionId?: string | null;
  inboundEventKind?: InboundEventKind;
  agentId?: string | null;
  gateway?: {
    url?: string;
    token?: string;
    timeoutMs?: number;
    clientName: GatewayClientName;
    clientDisplayName?: string;
    mode: GatewayClientMode;
  };
  toolContext?: ChannelThreadingToolContext;
  dryRun?: boolean;
  gatewayClientScopes?: readonly string[];
  /**
   * Server-owned fact: this caller receives proven-not-sent failures and resends
   * them. Plugins forward it into durable sends so recovery does not replay too.
   */
  deliveryRetryOwner?: "caller";
  /** Host-owned live authority check; never read from model-controlled params. */
  onPlatformSendDispatch?: () => Promise<void>;
  /** Revalidate the same owner synchronously after waits and immediately before platform I/O. */
  assertDirectAdapterHandoff?: () => void;
  /**
   * Host-owned cancellation for the originating invocation. Plugins may drop
   * work that was never issued; platform I/O already dispatched settles normally.
   */
  abortSignal?: AbortSignal;
  /** Ephemeral-authority sends must not enter replayable recovery. */
  skipQueue?: boolean;
};
type ChannelToolSend = {
  to: string;
  accountId?: string | null;
  threadId?: string | null;
  /** True when the native provider send may inherit the active conversation thread. */
  threadImplicit?: boolean;
  threadSuppressed?: boolean;
};
/** Channel-owned action surface for the shared `message` tool. */
type ChannelMessageActionAdapter = {
  /**
   * Unified discovery surface for the shared `message` tool.
   * This returns the scoped actions,
   * capabilities, schema fragments, and any plugin-owned media-source params
   * together so they cannot drift.
   */
  describeMessageTool: (params: ChannelMessageActionDiscoveryContext) => ChannelMessageToolDiscovery | null | undefined;
  /** Runtime discovery that may read worker-owned account state. Preferred by the host. */
  describeMessageToolAsync?: (params: ChannelMessageActionDiscoveryContext) => Promise<ChannelMessageToolDiscovery | null | undefined>;
  /** Delegate conversation-read admission to the provider for registrations the host permits. */
  providerOwnedReadGates?: true | readonly ChannelMessageActionName[];
  /**
   * Opt into these host-fenced context actions for loader-verified official installs.
   * Every provider request must captureChannelReadAuthority() at submission and
   * invoke that check immediately before each I/O attempt, including queued retries.
   * Does not extend conversation-read mutation authority or bypass provider policy.
   */
  readAuthorityActions?: readonly ChannelMessageActionName[];
  /**
   * Declare write actions that preserve the host's live request authority.
   * Invoke assertDirectAdapterHandoff after asynchronous preparation and
   * immediately before every provider request, including queued retries.
   * Does not grant authority or bypass current requester/provider permissions.
   */
  writeAuthorityActions?: readonly ChannelMessageActionName[];
  supportsAction?: (params: {
    action: ChannelMessageActionName;
  }) => boolean;
  resolveExecutionMode?: (params: {
    action: ChannelMessageActionName;
  }) => "local" | "gateway";
  resolveCliActionRequest?: (params: {
    action: ChannelMessageActionName;
    args: Record<string, unknown>;
  }) => {
    action: ChannelMessageActionName;
    args: Record<string, unknown>;
  };
  messageActionTargetAliases?: Partial<Record<ChannelMessageActionName, {
    aliases: string[];
    /** Alias fields that identify the destination conversation, not an existing message. */
    deliveryTargetAliases?: string[];
    /** Convert typed owner fields such as chatId into the canonical shared target shape. */
    resolveDeliveryTarget?: (params: {
      args: Record<string, unknown>;
    }) => string | undefined;
    /**
     * Prove that provider-native aliases name the trusted current conversation.
     * Core consults this only for host-owned bundled registrations.
     * @deprecated Prefer matchesCurrentConversationAsync for storage-backed matching.
     * Keep this callback synchronous for hosts that predate the async companion.
     */
    matchesCurrentConversation?: (params: {
      args: Record<string, unknown>;
      accountId: string;
      toolContext: ChannelThreadingToolContext;
    }) => boolean;
    /**
     * Await provider-owned alias proof after host context and target checks.
     * Preferred over the synchronous callback when present; false or rejection
     * never falls back to the synchronous matcher.
     */
    matchesCurrentConversationAsync?: (params: {
      args: Record<string, unknown>;
      accountId: string;
      toolContext: ChannelThreadingToolContext;
    }) => Promise<boolean>;
  }>>;
  requiresTrustedRequesterSender?: (params: {
    action: ChannelMessageActionName;
    toolContext?: ChannelThreadingToolContext;
  }) => boolean;
  /** Return true when a provider-native tool invocation has a visible or destructive side effect. */
  isToolDeliveryAction?: (params: {
    args: Record<string, unknown>;
  }) => boolean;
  extractToolSend?: (params: {
    args: Record<string, unknown>;
  }) => ChannelToolSend | null;
  /** Recover the actual resolved send route from a successful action result. */
  extractToolSendResult?: (params: {
    result: unknown;
    send: ChannelToolSend;
  }) => ChannelToolSend | null;
  /**
   * Translate generic `message(action=send)` arguments into the payload core
   * should persist, retry, recover, and ack. Return null to keep the legacy
   * plugin-owned action path for sends that cannot be represented durably.
   */
  prepareSendPayload?: (params: {
    ctx: ChannelMessageActionContext;
    to: string;
    payload: ReplyPayload$1;
    replyToId?: string | null;
    /** Preserve caller intent when plugins translate reply ids into durable payloads. */
    replyToIdSource?: "explicit" | "implicit";
    threadId?: string | number | null;
  }) => ReplyPayload$1 | null | undefined | Promise<ReplyPayload$1 | null | undefined>;
  /**
   * Prefer this for channel-specific poll semantics or extra poll parameters.
   * Core only parses the shared poll model when falling back to `outbound.sendPoll`.
   */
  handleAction?: (ctx: ChannelMessageActionContext) => Promise<AgentToolResult<unknown>>;
};
type ChannelPollResult = Pick<MessageReceiptSourceResult, "messageId" | "toJid" | "channelId" | "conversationId" | "pollId"> & {
  messageId: string;
  receipt?: MessageReceipt;
};
/** Shared poll input after core has normalized the common poll model. */
type ChannelPollContext = Pick<ChannelMessageSendPollContext, "cfg" | "to" | "poll" | "accountId" | "threadId" | "silent" | "isAnonymous" | "gatewayClientScopes" | "signal" | "onPlatformSendDispatch" | "assertDirectAdapterHandoff"> & {
  content?: string;
  /** Trusted originating turn context for channel-owned delivery correlation. */
  sessionKey?: string;
  inboundEventKind?: InboundEventKind;
};
/** Minimal base for all channel probe results. Channel-specific probes extend this. */
type BaseProbeResult<TError = string | null> = {
  ok: boolean;
  error?: TError;
};
type BaseTokenResolution = {
  token: string;
  source: string;
};
//#endregion
//#region src/config/legacy.shared.d.ts
type LegacyConfigRule = {
  path: string[];
  message: string;
  match?: (value: unknown, root: Record<string, unknown>) => boolean;
  requireSourceLiteral?: boolean;
};
//#endregion
//#region src/security/audit.types.d.ts
type SecurityAuditSeverity = "info" | "warn" | "critical";
type SecurityAuditFinding = {
  checkId: string;
  severity: SecurityAuditSeverity;
  title: string;
  detail: string;
  remediation?: string;
};
//#endregion
//#region src/channels/plugins/config-write-policy-shared.d.ts
type ConfigWriteScopeLike<TChannelId extends string = string> = {
  channelId?: TChannelId | null;
  accountId?: string | null;
};
type ConfigWriteTargetLike<TChannelId extends string = string> = {
  kind: "global";
} | {
  kind: "channel";
  scope: {
    channelId: TChannelId;
  };
} | {
  kind: "account";
  scope: {
    channelId: TChannelId;
    accountId: string;
  };
} | {
  kind: "ambiguous";
  scopes: ConfigWriteScopeLike<TChannelId>[];
};
type ConfigWriteAuthorizationResultLike<TChannelId extends string = string> = {
  allowed: true;
} | {
  allowed: false;
  reason: "ambiguous-target" | "origin-disabled" | "target-disabled";
  blockedScope?: {
    kind: "origin" | "target";
    scope: ConfigWriteScopeLike<TChannelId>;
  };
};
//#endregion
//#region src/channels/plugins/config-writes.d.ts
type ConfigWriteTarget = ConfigWriteTargetLike;
declare const authorizeConfigWrite: (params: {
  cfg: OpenClawConfig;
  origin?: ConfigWriteScopeLike;
  target?: ConfigWriteTarget;
  allowBypass?: boolean;
}) => ConfigWriteAuthorizationResultLike;
declare const formatConfigWriteDeniedMessage: (params: {
  result: Exclude<ConfigWriteAuthorizationResultLike, {
    allowed: true;
  }>;
  fallbackChannelId?: string | null;
}) => string;
declare function canBypassConfigWritePolicy(params: {
  channel?: string | null;
  gatewayClientScopes?: string[] | null;
}): boolean;
//#endregion
//#region src/audit/audit-event-types.d.ts
type AuditMessageDeliveryKind = "text" | "media" | "other";
type AuditMessageFailureStage = "platform_send" | "queue" | "unknown";
declare const AUDIT_OUTBOUND_MESSAGE_SUPPRESSED_REASONS: readonly ["cancelled_by_message_sending_hook", "cancelled_by_reply_payload_sending_hook", "empty_after_message_sending_hook", "empty_after_reply_payload_sending_hook", "no_visible_payload"];
type AuditOutboundMessageSuppressedReasonCode = (typeof AUDIT_OUTBOUND_MESSAGE_SUPPRESSED_REASONS)[number];
//#endregion
//#region src/infra/outbound/delivery-placement-evidence.types.d.ts
/** Reported placement only: no payload, provider handles, or mutable receipt aliases. */
type DeliveryPlacementEvidence = Readonly<{
  channels: readonly string[];
  targets: readonly string[];
  threads: readonly string[];
  invalid: boolean;
}>;
//#endregion
//#region src/infra/outbound/deliver-types.d.ts
type OutboundDeliveryQueuePolicy = "required" | "best_effort";
type PlatformSendRoute = {
  replyToId?: string | null;
  threadId?: string | number | null;
};
/** Channel send result or explicit non-outcome normalized for delivery accounting. */
type OutboundDeliveryResult = {
  outcome?: MessageReceiptSourceResult["outcome"];
  channel: ChannelId$1;
  messageId: string;
  target?: NonNullable<MessageReceiptSourceResult["target"]>;
  timestamp?: number;
  toJid?: string;
  pollId?: string;
  receipt?: MessageReceipt;
  meta?: Record<string, unknown>;
};
type OutboundAuditTerminal = {
  outcome: "sent";
  results: readonly OutboundDeliveryResult[];
  deliveryKind?: AuditMessageDeliveryKind;
} | {
  outcome: "suppressed";
  reasonCode: AuditOutboundMessageSuppressedReasonCode;
  results?: readonly OutboundDeliveryResult[];
} | {
  outcome: "failed";
  failureStage: AuditMessageFailureStage;
  results?: readonly OutboundDeliveryResult[];
  sentBeforeError?: boolean;
  deliveryKind?: AuditMessageDeliveryKind;
} | {
  outcome: "unknown";
  failureStage: AuditMessageFailureStage;
  results?: readonly OutboundDeliveryResult[];
  sentBeforeError?: boolean;
};
type IndexedOutboundAuditTerminal = {
  payloadIndex: number;
  terminal: OutboundAuditTerminal;
};
/** Reason a payload was intentionally not sent after normalization or hooks. */
type OutboundPayloadDeliverySuppressionReason = "cancelled_by_message_sending_hook" | "cancelled_by_reply_payload_sending_hook" | "empty_after_message_sending_hook" | "empty_after_reply_payload_sending_hook" | "no_visible_payload" | "adapter_returned_no_send" | "adapter_returned_no_identity";
/** Delivery phase where a failure occurred. */
type OutboundDeliveryFailureStage = AuditMessageFailureStage;
type OutboundPayloadDeliveryKind = AuditMessageDeliveryKind;
/**
 * Provider assertion that no recipient-visible send began. Set retryable=false
 * for permanent payload/policy rejection; never use after an ambiguous send.
 */
declare class PlatformMessageNotDispatchedError extends Error {
  readonly code = "OPENCLAW_PLATFORM_MESSAGE_NOT_DISPATCHED";
  readonly retryable: boolean;
  constructor(message: string, options: {
    cause: unknown;
    retryable?: boolean;
  });
}
/** Per-payload delivery status emitted to callers and channel send summaries. */
type OutboundPayloadDeliveryOutcome = {
  index: number;
  status: "sent";
  results: OutboundDeliveryResult[];
  /** Identified progress exists, but at least one physical result was discarded. */
  incompleteReason?: "adapter_returned_no_send" | "adapter_returned_no_identity";
  /** Immutable union of reported placement before progress reconciliation/callback mutation. */
  reportedPlacement?: DeliveryPlacementEvidence;
  /** Effective post-hook, post-render payload kind. */
  deliveryKind?: OutboundPayloadDeliveryKind;
} | {
  index: number;
  status: "suppressed";
  reason: OutboundPayloadDeliverySuppressionReason;
  hookEffect?: {
    cancelReason?: string;
    metadata?: Record<string, unknown>;
  };
} | {
  index: number;
  status: "failed";
  error: unknown;
  sentBeforeError: boolean;
  stage: OutboundDeliveryFailureStage;
  /** Identified platform sends from this payload before its terminal failure. */
  results?: OutboundDeliveryResult[];
  /** Effective post-hook, post-render payload kind when platform delivery began. */
  deliveryKind?: OutboundPayloadDeliveryKind;
};
/** Error carrying partial delivery results when an outbound send fails mid-batch. */
declare class OutboundDeliveryError extends Error {
  readonly results: OutboundDeliveryResult[];
  readonly payloadOutcomes: OutboundPayloadDeliveryOutcome[];
  readonly sentBeforeError: boolean;
  readonly stage: OutboundDeliveryFailureStage;
  queueCustody?: "held" | "released";
  constructor(message: string, options: {
    cause: unknown;
    results?: readonly OutboundDeliveryResult[];
    payloadOutcomes?: readonly OutboundPayloadDeliveryOutcome[];
    /** Durable evidence from an earlier attempt of the same intent. */
    sentBeforeError?: boolean;
    stage?: OutboundDeliveryFailureStage;
  });
}
//#endregion
//#region src/auto-reply/chunk.d.ts
type TextChunkProvider = ChannelId$1;
/**
 * Chunking mode for outbound messages:
 * - "length": Split only when exceeding textChunkLimit (default)
 * - "newline": Prefer breaking on "soft" boundaries. Historically this split on every
 *   newline; now it only breaks on paragraph boundaries (blank lines) unless the text
 *   exceeds the length limit.
 */
type ChunkMode = "length" | "newline";
declare function resolveTextChunkLimit(cfg: OpenClawConfig | undefined, provider?: TextChunkProvider, accountId?: string | null, opts?: {
  fallbackLimit?: number;
}): number;
declare function resolveChunkMode(cfg: OpenClawConfig | undefined, provider?: TextChunkProvider, accountId?: string | null): ChunkMode;
/**
 * Split text on newlines, trimming line whitespace.
 * Blank lines are folded into the next non-empty line as leading "\n" prefixes.
 * Leading and trailing blank lines are capped to the available UTF-16 space.
 * Long lines can be split by length (default) or kept intact via splitLongLines:false.
 */
declare function chunkByNewline(text: string, maxLineLength: number, opts?: {
  splitLongLines?: boolean;
  trimLines?: boolean;
  isSafeBreak?: (index: number) => boolean;
}): string[];
/**
 * Split text into chunks on paragraph boundaries (blank lines), preserving lists and
 * single-newline line wraps inside paragraphs.
 *
 * - Only breaks at paragraph separators ("\n\n" or more, allowing whitespace on blank lines)
 * - Packs multiple paragraphs into a single chunk up to `limit`
 * - Falls back to length-based splitting when a single paragraph exceeds `limit`
 *   (unless `splitLongParagraphs` is disabled)
 */
declare function chunkByParagraph(text: string, limit: number, opts?: {
  splitLongParagraphs?: boolean;
}): string[];
declare function chunkTextWithMode(text: string, limit: number, mode: ChunkMode): string[];
declare function chunkMarkdownTextWithMode(text: string, limit: number, mode: ChunkMode): string[];
declare function chunkText(text: string, limit: number): string[];
declare function chunkMarkdownText(text: string, limit: number): string[];
//#endregion
//#region src/infra/outbound/formatting.d.ts
/**
 * Formatting and chunking hints carried through outbound delivery planning.
 */
type OutboundDeliveryFormattingOptions = {
  textLimit?: number;
  maxLinesPerMessage?: number;
  tableMode?: MarkdownTableMode;
  chunkMode?: ChunkMode;
  parseMode?: "HTML";
};
//#endregion
//#region src/infra/outbound/identity-types.d.ts
/** Agent identity metadata that outbound channels can render with a message. */
type OutboundIdentity = Partial<Record<"name" | "avatarUrl" | "emoji" | "theme", string>>;
//#endregion
//#region src/channels/plugins/outbound.types.d.ts
type ChannelOutboundContext = Omit<ChannelMessageSendMediaContext, "mediaUrl" | "onDeliveryResult"> & {
  mediaUrl?: string;
  formatting?: OutboundDeliveryFormattingOptions;
  identity?: OutboundIdentity;
  /** @internal Report each completed platform sub-send before starting another fallible step. */
  onDeliveryResult?: (result: OutboundDeliveryResult) => Promise<void> | void;
};
type ChannelOutboundPayloadContext = ChannelOutboundContext & {
  payload: ReplyPayload$1;
};
type ChannelPresentationCapabilities = {
  /** Whether the channel accepts structured presentation payloads at all. */
  supported?: boolean;
  /** Whether the channel can render button action blocks natively. */
  buttons?: boolean;
  /** Whether the channel can render select/menu blocks natively. */
  selects?: boolean;
  /** Whether the channel can render low-emphasis context blocks natively. */
  context?: boolean;
  /** Whether the channel can render divider blocks natively. */
  divider?: boolean;
  /** Whether the channel can render chart blocks natively. */
  charts?: boolean;
  /** Whether the channel can render table blocks natively. */
  tables?: boolean;
  /** Per-channel limits used to adapt portable presentation blocks before rendering. */
  limits?: {
    actions?: {
      /** Maximum total button/select actions in one message. */
      maxActions?: number;
      /** Maximum buttons per rendered action row. */
      maxActionsPerRow?: number;
      /** Maximum action rows in one message. */
      maxRows?: number;
      /** Maximum user-visible button label length. */
      maxLabelLength?: number;
      /** Maximum callback/action value size in UTF-8 bytes. */
      maxValueBytes?: number;
      /** Whether action styles such as primary or danger are preserved. */
      supportsStyles?: boolean;
      /** Whether disabled button state is preserved. */
      supportsDisabled?: boolean;
      /** Whether priority/layout hints affect native rendering. */
      supportsLayoutHints?: boolean;
    };
    selects?: {
      /** Maximum options in one select/menu block. */
      maxOptions?: number;
      /** Maximum user-visible option label length. */
      maxLabelLength?: number;
      /** Maximum option callback value size in UTF-8 bytes. */
      maxValueBytes?: number;
    };
    text?: {
      /** Maximum text length for title, text, and context blocks. */
      maxLength?: number;
      /** Unit used by maxLength. Defaults to Unicode code points. */
      encoding?: "characters" | "utf8-bytes" | "utf16-units";
      /** Markdown dialect understood by rendered text blocks. */
      markdownDialect?: "plain" | "markdown" | "html" | "slack-mrkdwn" | "discord-markdown";
      /** Whether the channel can edit presentation text in-place. */
      supportsEdit?: boolean;
    };
  };
};
type ChannelDeliveryCapabilities = {
  pin?: boolean;
  durableFinal?: DurableFinalDeliveryRequirementMap;
};
type ChannelOutboundPayloadHint = {
  kind: "approval-pending";
  approvalKind: ChannelApprovalKind;
  nativeRouteActive?: boolean;
} | {
  kind: "approval-resolved";
  approvalKind: ChannelApprovalKind;
};
type ChannelOutboundTargetRef = {
  channel: string;
  to: string;
  accountId?: string | null;
  threadId?: string | number | null;
};
type ChannelOutboundFormattedContext = ChannelOutboundContext & {
  abortSignal?: AbortSignal;
};
type ChannelOutboundChunkContext = Pick<ChannelOutboundContext, "formatting">;
type ChannelOutboundNormalizePayloadParams = {
  payload: ReplyPayload$1;
  cfg: OpenClawConfig;
  accountId?: string | null;
};
type ChannelOutboundNormalizePayloadBatchParams = Omit<ChannelOutboundNormalizePayloadParams, "payload"> & {
  payloads: readonly {
    index: number;
    payload: ReplyPayload$1;
  }[];
};
type ChannelOutboundAdapter = {
  deliveryMode: "direct" | "gateway" | "hybrid";
  chunker?: ((text: string, limit: number, ctx?: ChannelOutboundChunkContext) => string[]) | null;
  chunkerMode?: "text" | "markdown";
  chunkedTextFormatting?: OutboundDeliveryFormattingOptions;
  /** Lift remote Markdown image syntax in text into outbound media attachments. */
  extractMarkdownImages?: boolean;
  /** Preserve model-authored Markdown details blocks for a native channel renderer. */
  preserveMarkdownDetails?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  textChunkLimit?: number;
  /**
   * Reserve the exact provider id used by the next single-message send.
   * Presence opts the channel into conversations_turn reply correlation.
   */
  prepareConversationTurnMessageId?: (params: Pick<ChannelOutboundContext, "cfg" | "to" | "text" | "accountId" | "threadId">) => string;
  sanitizeText?: (params: {
    text: string;
    payload: ReplyPayload$1;
    cfg?: OpenClawConfig;
    accountId?: string;
  }) => string;
  pollMaxOptions?: number;
  supportsPollDurationSeconds?: boolean;
  supportsAnonymousPolls?: boolean;
  normalizePayload?: (params: ChannelOutboundNormalizePayloadParams) => ReplyPayload$1 | null;
  /** Normalize an ordered batch in place. Return one entry per input; null suppresses that send. */
  normalizePayloadBatch?: (params: ChannelOutboundNormalizePayloadBatchParams) => ReadonlyArray<ReplyPayload$1 | null>;
  sendTextOnlyErrorPayloads?: boolean;
  /**
   * Route ordinary multi-media payloads intact to sendPayload for native grouping.
   * The adapter must check cancellation and revalidate authority before every physical send.
   */
  sendPayloadGroupsMedia?: boolean;
  shouldSkipPlainTextSanitization?: (params: {
    payload: ReplyPayload$1;
  }) => boolean;
  resolveEffectiveTextChunkLimit?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    fallbackLimit?: number;
    formatting?: OutboundDeliveryFormattingOptions;
  }) => number | undefined;
  shouldSuppressLocalPayloadPrompt?: (params: ChannelOutboundNormalizePayloadParams & {
    hint?: ChannelOutboundPayloadHint;
  }) => boolean;
  shouldSuppressLocalPayloadPromptAsync?: (params: ChannelOutboundNormalizePayloadParams & {
    hint?: ChannelOutboundPayloadHint;
  }) => Promise<boolean>;
  beforeDeliverPayload?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    payload: ReplyPayload$1;
    hint?: ChannelOutboundPayloadHint;
  }) => Promise<void> | void;
  afterDeliverPayload?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    payload: ReplyPayload$1;
    results: readonly OutboundDeliveryResult[];
  }) => Promise<void> | void;
  /** Adopt a provider-created thread for later payloads in the same durable batch. */
  adoptTargetFromDelivery?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    result: OutboundDeliveryResult;
  }) => {
    threadId: string | number;
  } | null | undefined;
  /** Channel-advertised presentation features and limits used by core adaptation. */
  presentationCapabilities?: ChannelPresentationCapabilities;
  /**
   * Account- and formatting-aware capability resolution; takes precedence over
   * the static declaration. Formatting is the delivery's outbound formatting
   * options, so capabilities that only apply to one text funnel (for example
   * rich tables on the markdown path) can turn off for HTML-mode sends.
   */
  resolvePresentationCapabilities?: (params: Pick<ChannelOutboundContext, "cfg" | "accountId" | "formatting">) => ChannelPresentationCapabilities;
  deliveryCapabilities?: ChannelDeliveryCapabilities;
  /** Render an adapted portable presentation into channel-native payload data. */
  renderPresentation?: (params: {
    payload: ReplyPayload$1;
    presentation: MessagePresentation;
    /** Normalized original for readable fallbacks; native rendering uses presentation. */
    sourcePresentation?: MessagePresentation;
    ctx: ChannelOutboundPayloadContext;
  }) => Promise<ReplyPayload$1 | null> | ReplyPayload$1 | null;
  pinDeliveredMessage?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    messageId: string;
    pin: ReplyPayloadDeliveryPin;
    gatewayClientScopes?: readonly string[];
    /** @internal Revalidate the delivery owner after preparation and before each provider request. */
    assertDirectAdapterHandoff?: () => void;
  }) => Promise<void> | void;
  /**
   * @deprecated Use shouldTreatDeliveredTextAsVisible instead.
   */
  shouldTreatRoutedTextAsVisible?: NonNullable<ChannelOutboundAdapter["shouldTreatDeliveredTextAsVisible"]>;
  shouldTreatDeliveredTextAsVisible?: (params: {
    kind: "tool" | "block" | "final";
    text?: string;
  }) => boolean;
  preferFinalAssistantVisibleText?: boolean;
  targetsMatchForReplySuppression?: (params: {
    originTarget: string;
    targetKey: string;
    targetThreadId?: string;
  }) => boolean;
  resolveTarget?: (params: {
    cfg?: OpenClawConfig;
    to?: string;
    allowFrom?: string[];
    accountId?: string | null;
    mode?: ChannelOutboundTargetMode;
  }) => {
    ok: true;
    to: string;
  } | {
    ok: false;
    error: Error;
  };
  sendPayload?: (ctx: ChannelOutboundPayloadContext) => Promise<OutboundDeliveryResult>;
  sendFormattedText?: (ctx: ChannelOutboundFormattedContext) => Promise<OutboundDeliveryResult[]>;
  sendFormattedMedia?: (ctx: ChannelOutboundFormattedContext & {
    mediaUrl: string;
  }) => Promise<OutboundDeliveryResult>;
  sendText?: (ctx: ChannelOutboundContext) => Promise<OutboundDeliveryResult>;
  sendMedia?: (ctx: ChannelOutboundContext) => Promise<OutboundDeliveryResult>;
  sendPoll?: (ctx: ChannelPollContext) => Promise<ChannelPollResult>;
};
//#endregion
//#region src/channels/plugins/pairing.types.d.ts
/**
 * Channel pairing hooks used by setup and allowlist approval flows.
 */
type ChannelPairingAdapter = {
  idLabel: string;
  normalizeAllowEntry?: (entry: string) => string;
  /** Derive the persisted approval entry from the locally issued request. */
  resolveApprovalStoreEntry?: (request: {
    id: string;
    meta?: Record<string, string>;
  }) => string | null | undefined;
  notifyApproval?: (params: {
    cfg: OpenClawConfig;
    id: string;
    accountId?: string;
    meta?: Record<string, string>;
    runtime?: RuntimeEnv;
  }) => Promise<void>;
};
//#endregion
//#region src/channels/plugins/types.conversation-bindings.d.ts
type ChannelConversationBindingSupport = {
  supportsCurrentConversationBinding?: boolean;
  isCurrentConversationBindingSupported?: (params: {
    accountId: string;
  }) => boolean;
  /** Declares that live bindings come from a channel-registered adapter, never generic storage. */
  bindingStore?: "adapter";
  /**
   * Preferred placement when a command is started from a top-level conversation
   * without an existing native thread id.
   *
   * - `current`: bind/spawn in the current conversation
   * - `child`: create a child thread/conversation first
   */
  defaultTopLevelPlacement?: "current" | "child";
  resolveConversationRef?: (params: {
    accountId?: string | null;
    conversationId: string;
    parentConversationId?: string;
    threadId?: string | number | null;
  }) => {
    conversationId: string;
    parentConversationId?: string;
  } | null;
  buildBoundReplyPayload?: (params: {
    operation: "acp-spawn";
    placement: "current" | "child";
    conversation: {
      channel: string;
      accountId?: string | null;
      conversationId: string;
      parentConversationId?: string;
    };
  }) => Pick<ReplyPayload$1, "channelData" | "delivery" | "presentation"> | null | Promise<Pick<ReplyPayload$1, "channelData" | "delivery" | "presentation"> | null>;
  buildModelOverrideParentCandidates?: (params: {
    parentConversationId?: string | null;
  }) => string[] | null | undefined;
  shouldStripThreadFromAnnounceOrigin?: (params: {
    requester: {
      channel?: string;
      to?: string;
      threadId?: string | number;
    };
    entry: {
      channel?: string;
      to?: string;
      threadId?: string | number;
    };
  }) => boolean;
  /** @deprecated Use setIdleTimeoutBySessionKeyAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  setIdleTimeoutBySessionKey?: (params: {
    targetSessionKey: string;
    accountId?: string | null;
    idleTimeoutMs: number;
  }) => Array<{
    boundAt: number;
    lastActivityAt: number;
    idleTimeoutMs?: number;
    maxAgeMs?: number;
  }>;
  /** @deprecated Use setMaxAgeBySessionKeyAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  setMaxAgeBySessionKey?: (params: {
    targetSessionKey: string;
    accountId?: string | null;
    maxAgeMs: number;
  }) => ReturnType<NonNullable<ChannelConversationBindingSupport["setIdleTimeoutBySessionKey"]>>;
  setIdleTimeoutBySessionKeyAsync?: (params: Parameters<NonNullable<ChannelConversationBindingSupport["setIdleTimeoutBySessionKey"]>>[0]) => Promise<ReturnType<NonNullable<ChannelConversationBindingSupport["setIdleTimeoutBySessionKey"]>>>;
  setMaxAgeBySessionKeyAsync?: (params: Parameters<NonNullable<ChannelConversationBindingSupport["setMaxAgeBySessionKey"]>>[0]) => Promise<ReturnType<NonNullable<ChannelConversationBindingSupport["setMaxAgeBySessionKey"]>>>;
  createManager?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => {
    stop: () => void | Promise<void>;
  } | Promise<{
    stop: () => void | Promise<void>;
  }>;
};
//#endregion
//#region src/channels/plugins/types.adapters.d.ts
type ChannelActionAvailabilityState = {
  kind: "enabled";
} | {
  kind: "disabled";
} | {
  kind: "unsupported";
};
type ChannelApprovalForwardTarget$1 = {
  channel: string;
  to: string;
  accountId?: string | null;
  threadId?: string | number | null;
  source?: "session" | "target";
};
type ChannelCapabilitiesDisplayLine = {
  text: string;
  tone?: "default" | "muted" | "success" | "warn" | "error";
};
type ChannelCapabilitiesDiagnostics = {
  lines?: ChannelCapabilitiesDisplayLine[];
  details?: Record<string, unknown>;
};
type ChannelAccountLinkState = "linked" | "not-linked" | "unknown";
type ChannelConfigAdapter<ResolvedAccount> = {
  listAccountIds: (cfg: OpenClawConfig) => string[];
  resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) => ResolvedAccount;
  /** Operational account preparation; preferred over the synchronous compatibility hook. */
  resolveAccountAsync?: (cfg: OpenClawConfig, accountId?: string | null) => Promise<ResolvedAccount>;
  inspectAccount?: (cfg: OpenClawConfig, accountId?: string | null) => unknown;
  defaultAccountId?: (cfg: OpenClawConfig) => string;
  setAccountEnabled?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    enabled: boolean;
  }) => OpenClawConfig;
  deleteAccount?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
  }) => OpenClawConfig;
  isEnabled?: (account: ResolvedAccount, cfg: OpenClawConfig) => boolean;
  disabledReason?: (account: ResolvedAccount, cfg: OpenClawConfig) => string;
  isConfigured?: (account: ResolvedAccount, cfg: OpenClawConfig) => boolean | Promise<boolean>;
  isLinked?: (account: ResolvedAccount, cfg: OpenClawConfig) => ChannelAccountLinkState | Promise<ChannelAccountLinkState>;
  unconfiguredReason?: (account: ResolvedAccount, cfg: OpenClawConfig) => string;
  unlinkedReason?: (account: ResolvedAccount, cfg: OpenClawConfig) => string;
  describeAccount?: (account: ResolvedAccount, cfg: OpenClawConfig) => ChannelAccountSnapshot;
  describeAccountAsync?: (account: ResolvedAccount, cfg: OpenClawConfig) => Promise<ChannelAccountSnapshot>;
  resolveAllowFrom?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => Array<string | number> | undefined;
  resolveAllowFromAsync?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => Promise<Array<string | number> | undefined>;
  formatAllowFrom?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    allowFrom: Array<string | number>;
  }) => string[];
  hasConfiguredState?: (params: {
    cfg: OpenClawConfig;
    env?: NodeJS.ProcessEnv;
  }) => boolean;
  hasConfiguredStateAsync?: (params: {
    cfg: OpenClawConfig;
    env?: NodeJS.ProcessEnv;
  }) => Promise<boolean>;
  hasPersistedAuthState?: (params: {
    cfg: OpenClawConfig;
    env?: NodeJS.ProcessEnv;
  }) => boolean;
  resolveDefaultTo?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => string | undefined;
};
type ChannelSecretsAdapter = {
  /** Channel credentials may also live in this plugin's plugins.entries.<id>.config schema. */
  secretTargetRegistryEntries?: readonly SecretTargetRegistryEntry[];
  unsupportedSecretRefSurfacePatterns?: readonly string[];
  collectUnsupportedSecretRefConfigCandidates?: (raw: unknown) => Array<{
    path: string;
    value: unknown;
  }>;
  collectRuntimeConfigAssignments?: (params: {
    config: OpenClawConfig;
    defaults: SecretDefaults | undefined;
    context: ResolverContext;
  }) => void;
};
type ChannelGroupAdapter = {
  resolveRequireMention?: (params: ChannelGroupContext) => boolean | undefined;
  resolveToolPolicy?: (params: ChannelGroupContext) => GroupToolPolicyConfig | undefined;
};
type ChannelStatusAdapter<ResolvedAccount, Probe = unknown, Audit = unknown> = {
  defaultRuntime?: ChannelAccountSnapshot;
  buildChannelSummary?: (params: {
    account: ResolvedAccount;
    cfg: OpenClawConfig;
    defaultAccountId: string;
    snapshot: ChannelAccountSnapshot;
  }) => Record<string, unknown> | Promise<Record<string, unknown>>;
  probeAccount?: (params: {
    account: ResolvedAccount;
    timeoutMs: number;
    cfg: OpenClawConfig;
  }) => Promise<Probe>;
  formatCapabilitiesProbe?: (params: {
    probe: Probe;
  }) => ChannelCapabilitiesDisplayLine[];
  auditAccount?: (params: {
    account: ResolvedAccount;
    timeoutMs: number;
    cfg: OpenClawConfig;
    probe?: Probe;
  }) => Promise<Audit>;
  buildCapabilitiesDiagnostics?: (params: {
    account: ResolvedAccount;
    timeoutMs: number;
    cfg: OpenClawConfig;
    probe?: Probe;
    audit?: Audit;
    target?: string;
  }) => Promise<ChannelCapabilitiesDiagnostics | undefined>;
  buildAccountSnapshot?: (params: {
    account: ResolvedAccount;
    cfg: OpenClawConfig;
    runtime?: ChannelAccountSnapshot;
    probe?: Probe;
    audit?: Audit;
  }) => ChannelAccountSnapshot | Promise<ChannelAccountSnapshot>;
  logSelfId?: (params: {
    account: ResolvedAccount;
    cfg: OpenClawConfig;
    runtime: RuntimeEnv;
    includeChannelPrefix?: boolean;
  }) => void;
  resolveAccountState?: (params: {
    account: ResolvedAccount;
    cfg: OpenClawConfig;
    configured: boolean;
    enabled: boolean;
  }) => ChannelAccountState;
  collectStatusIssues?: (accounts: ChannelAccountSnapshot[]) => ChannelStatusIssue[];
};
type ChannelGatewayContext<ResolvedAccount = unknown> = {
  cfg: OpenClawConfig;
  accountId: string;
  account: ResolvedAccount;
  runtime: RuntimeEnv;
  abortSignal: AbortSignal;
  /** Account-owned timed work; required by the version 2 Gateway adapter. */
  scheduler?: PluginServiceSchedulerV1;
  log?: ChannelLogSink;
  getStatus: () => ChannelAccountSnapshot;
  setStatus: (next: ChannelAccountSnapshot) => void;
  /** Clear cached outbound directory lookups after the channel accepts newer directory data. */
  invalidateDirectoryCache?: () => void;
  /**
   * Host-provided channel helpers for dispatch, routing, sessions, text, media,
   * command authorization, groups, and pairing. Present when Gateway startup
   * has a runtime resolver; external plugins must handle its absence.
   * @since Plugin SDK 2026.2.19
   */
  channelRuntime?: ChannelRuntimeSurface;
};
type ChannelGatewayContextV2<ResolvedAccount = unknown> = ChannelGatewayContext<ResolvedAccount> & {
  scheduler: PluginServiceSchedulerV1;
};
type ChannelGatewayAdapter<ResolvedAccount = unknown> = {
  apiVersion?: 1;
  startAccount?: (ctx: ChannelGatewayContext<ResolvedAccount>) => Promise<unknown>;
  stopAccount?: (ctx: ChannelGatewayContext<ResolvedAccount>) => Promise<void>;
  /** Keep gateway auth bypass resolution mirrored through a lightweight top-level `gateway-auth-api.ts` artifact. */
  resolveGatewayAuthBypassPaths?: (params: {
    cfg: OpenClawConfig;
  }) => string[];
  loginWithQrStart?: (params: {
    accountId?: string;
    /** Revalidate the Gateway's account binding immediately before credential writes. */
    assertCredentialPersistenceCurrent?: () => void;
    force?: boolean;
    timeoutMs?: number;
    verbose?: boolean;
  }) => Promise<{
    qrDataUrl?: string;
    message: string;
    connected?: boolean;
    sessionKey?: string;
  }>;
  loginWithQrWait?: (params: {
    accountId?: string;
    sessionKey?: string;
    timeoutMs?: number;
    currentQrDataUrl?: string;
  }) => Promise<{
    connected: boolean;
    message: string;
    qrDataUrl?: string;
  }>;
  logoutAccount?: (ctx: {
    cfg: OpenClawConfig;
    accountId: string;
    account: ResolvedAccount;
    runtime: RuntimeEnv;
    log?: ChannelLogSink;
  }) => Promise<{
    cleared: boolean;
    loggedOut?: boolean;
    [key: string]: unknown;
  }>;
};
type ChannelGatewayAdapterV2<ResolvedAccount = unknown> = Omit<ChannelGatewayAdapter<ResolvedAccount>, "apiVersion" | "startAccount" | "stopAccount"> & {
  apiVersion: 2;
  startAccount?: (ctx: ChannelGatewayContextV2<ResolvedAccount>) => Promise<unknown>;
  stopAccount?: (ctx: ChannelGatewayContextV2<ResolvedAccount>) => Promise<void>;
};
type ChannelAuthAdapter = {
  login?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    runtime: RuntimeEnv;
    verbose?: boolean;
    channelInput?: string | null;
  }) => Promise<void>;
};
type ChannelHeartbeatAdapter = {
  checkReady?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    deps?: ChannelHeartbeatDeps;
  }) => Promise<{
    ok: boolean;
    reason: string;
  }>;
  sendTyping?: (params: {
    cfg: OpenClawConfig;
    to: string;
    accountId?: string | null;
    threadId?: string | number | null;
    deps?: ChannelHeartbeatDeps;
  }) => Promise<void> | void;
  /** Optional owned typing: recheck the guard after transport waits and honor cancellation. */
  sendTypingGuarded?: (params: {
    cfg: OpenClawConfig;
    to: string;
    accountId?: string | null;
    threadId?: string | number | null;
    signal: AbortSignal;
    assertPlatformSendAuthorized: () => void;
  }) => Promise<void> | void;
  clearTyping?: NonNullable<ChannelHeartbeatAdapter["sendTyping"]>;
};
type ChannelDirectoryListParams = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  query?: string | null;
  limit?: number | null;
  runtime: RuntimeEnv;
};
type ChannelDirectoryAdapter = {
  self?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    runtime: RuntimeEnv;
  }) => Promise<ChannelDirectoryEntry | null>;
  listPeers?: (params: ChannelDirectoryListParams) => Promise<ChannelDirectoryEntry[]>;
  listPeersLive?: (params: ChannelDirectoryListParams) => Promise<ChannelDirectoryEntry[]>;
  listGroups?: (params: ChannelDirectoryListParams) => Promise<ChannelDirectoryEntry[]>;
  listGroupsLive?: (params: ChannelDirectoryListParams) => Promise<ChannelDirectoryEntry[]>;
  listGroupMembers?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    groupId: string;
    limit?: number | null;
    runtime: RuntimeEnv;
  }) => Promise<ChannelDirectoryEntry[]>;
};
type ChannelResolveKind = "user" | "group";
type ChannelResolveResult = {
  input: string;
  resolved: boolean;
  id?: string;
  name?: string;
  note?: string;
};
type ChannelResolverAdapter = {
  resolveTargets: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    inputs: string[];
    kind: ChannelResolveKind;
    runtime: RuntimeEnv;
  }) => Promise<ChannelResolveResult[]>;
};
type ChannelElevatedAdapter = {
  allowFromFallback?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => Array<string | number> | undefined;
};
type ChannelCommandAdapter = {
  enforceOwnerForCommands?: boolean;
  skipWhenConfigEmpty?: boolean;
  nativeCommandsAutoEnabled?: boolean;
  nativeSkillsAutoEnabled?: boolean;
  preferSenderE164ForCommands?: boolean;
  resolveNativeCommandName?: (params: {
    commandKey: string;
    defaultName: string;
  }) => string | undefined;
  buildCommandsListChannelData?: (params: {
    currentPage: number;
    totalPages: number;
    agentId?: string;
  }) => ReplyPayload$1["channelData"] | null;
  buildModelsMenuChannelData?: (params: {
    providers: Array<{
      id: string;
      count: number;
    }>;
  }) => ReplyPayload$1["channelData"] | null;
  buildModelsProviderChannelData?: NonNullable<ChannelCommandAdapter["buildModelsMenuChannelData"]>;
  buildModelsAddProviderChannelData?: (params: {
    providers: Array<{
      id: string;
    }>;
  }) => ReplyPayload$1["channelData"] | null;
  buildModelsListChannelData?: (params: {
    provider: string;
    models: readonly string[];
    currentModel?: string;
    currentPage: number;
    totalPages: number;
    pageSize?: number;
    modelNames?: ReadonlyMap<string, string>;
  }) => ReplyPayload$1["channelData"] | null;
  buildModelBrowseChannelData?: () => ReplyPayload$1["channelData"] | null;
};
type ChannelDoctorConfigMutation = {
  config: OpenClawConfig;
  changes: string[];
  warnings?: string[];
  /** null defers environment-dependent eligibility; an undefined account ID selects the root. */
  historicalWebhookAccountIds?: readonly (string | undefined)[] | null;
};
type ChannelDoctorLegacyConfigRule = LegacyConfigRule;
type ChannelDoctorSequenceResult = {
  changeNotes: string[];
  infoNotes?: string[];
  warningNotes: string[];
};
type ChannelDoctorEmptyAllowlistAccountContext = {
  account: Record<string, unknown>;
  channelName: string;
  dmPolicy?: string;
  effectiveAllowFrom?: Array<string | number>;
  parent?: Record<string, unknown>;
  prefix: string;
};
type ChannelDoctorAdapter = {
  dmAllowFromMode?: "topOnly" | "topOrNested" | "nestedOnly";
  groupModel?: "sender" | "route" | "hybrid";
  groupAllowFromFallbackToAllowFrom?: boolean;
  warnOnEmptyGroupSenderAllowlist?: boolean;
  legacyConfigRules?: LegacyConfigRule[];
  normalizeCompatibilityConfig?: (params: {
    cfg: OpenClawConfig;
  }) => ChannelDoctorConfigMutation;
  collectPreviewWarnings?: (params: {
    cfg: OpenClawConfig;
    doctorFixCommand: string;
    env?: NodeJS.ProcessEnv;
  }) => string[] | Promise<string[]>;
  collectMutableAllowlistWarnings?: (params: {
    cfg: OpenClawConfig;
  }) => string[] | Promise<string[]>;
  repairConfig?: (params: {
    cfg: OpenClawConfig;
    doctorFixCommand: string;
    env?: NodeJS.ProcessEnv;
  }) => ChannelDoctorConfigMutation | Promise<ChannelDoctorConfigMutation>;
  runConfigSequence?: (params: {
    cfg: OpenClawConfig;
    env: NodeJS.ProcessEnv;
    shouldRepair: boolean;
  }) => ChannelDoctorSequenceResult | Promise<ChannelDoctorSequenceResult>;
  cleanStaleConfig?: (params: {
    cfg: OpenClawConfig;
  }) => ChannelDoctorConfigMutation | Promise<ChannelDoctorConfigMutation>;
  collectEmptyAllowlistExtraWarnings?: (params: ChannelDoctorEmptyAllowlistAccountContext) => string[];
  shouldSkipDefaultEmptyGroupAllowlistWarning?: (params: ChannelDoctorEmptyAllowlistAccountContext) => boolean;
};
type ChannelLifecycleAdapter = {
  onAccountConfigChanged?: (params: {
    prevCfg: OpenClawConfig;
    nextCfg: OpenClawConfig;
    accountId: string;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
  onAccountRemoved?: (params: {
    prevCfg: OpenClawConfig;
    accountId: string;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
  runStartupMaintenance?: (params: {
    cfg: OpenClawConfig;
    env?: NodeJS.ProcessEnv;
    log: {
      info?: (message: string) => void;
      warn?: (message: string) => void;
    };
    trigger?: string;
    logPrefix?: string;
  }) => Promise<void> | void;
  /**
   * @deprecated Export stateMigrations from the plugin doctor contract instead.
   * Removal plan: remove the lifecycle adapter after the 2027.1 external-plugin migration window.
   */
  detectLegacyStateMigrations?: (params: {
    cfg: OpenClawConfig;
    env: NodeJS.ProcessEnv;
    stateDir: string;
    oauthDir: string;
  }) => ChannelLegacyStateMigrationPlan[] | Promise<ChannelLegacyStateMigrationPlan[]>;
};
type ChannelApprovalForwardingFallbackParams = {
  cfg: OpenClawConfig;
  approvalKind: ChannelApprovalKind;
  target: ChannelApprovalForwardTarget$1;
  request: ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
};
type ChannelApprovalRenderHandlers<Request, Resolved> = {
  buildPendingPayload?: (params: {
    cfg: OpenClawConfig;
    request: Request;
    target: ChannelApprovalForwardTarget$1;
    nowMs: number;
  }) => ReplyPayload$1 | null;
  buildResolvedPayload?: (params: {
    cfg: OpenClawConfig;
    resolved: Resolved;
    target: ChannelApprovalForwardTarget$1;
  }) => ReplyPayload$1 | null;
};
type ChannelApprovalAdapter = {
  delivery?: {
    hasConfiguredDmRoute?: (params: {
      cfg: OpenClawConfig;
    }) => boolean;
    hasConfiguredDmRouteAsync?: (params: {
      cfg: OpenClawConfig;
    }) => Promise<boolean>;
    /** Deny a fallback that cannot satisfy this request's reviewer policy, even without a native handler. */
    shouldBlockForwardingFallback?: (params: ChannelApprovalForwardingFallbackParams) => boolean;
    shouldSuppressForwardingFallback?: (params: ChannelApprovalForwardingFallbackParams) => boolean;
    shouldSuppressForwardingFallbackAsync?: (params: ChannelApprovalForwardingFallbackParams) => Promise<boolean>;
  };
  nativeRuntime?: ChannelApprovalNativeRuntimeAdapter;
  nativeRuntimeAsync?: ChannelApprovalNativeRuntimeAdapterAsync;
  render?: {
    exec?: ChannelApprovalRenderHandlers<ExecApprovalRequest, ExecApprovalResolved>;
    plugin?: ChannelApprovalRenderHandlers<PluginApprovalRequest$1, PluginApprovalResolved>;
  };
  native?: ChannelApprovalNativeAdapter;
  nativeAsync?: ChannelApprovalNativeAdapterAsync;
  describeExecApprovalSetup?: (params: {
    channel: string;
    channelLabel: string;
    accountId?: string;
  }) => string | null | undefined;
  describePluginApprovalSetup?: NonNullable<ChannelApprovalAdapter["describeExecApprovalSetup"]>;
};
type ChannelApprovalCapability = ChannelApprovalAdapter & {
  /** Confirms that this channel enforces configured plugin reviewer lists for routing and decisions. */
  supportsScopedPluginApprovalApprovers?: true;
  /** @deprecated Prefer authorizeActorActionAsync for worker-owned approval routing. */
  authorizeActorAction?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    senderId?: string | null;
    action: "approve";
    approvalKind: ChannelApprovalKind;
    request?: ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
  }) => {
    authorized: boolean;
    reason?: string;
  };
  /** Prepare actor authorization without reading durable session state on the Gateway thread. */
  authorizeActorActionAsync?: (params: Parameters<NonNullable<ChannelApprovalCapability["authorizeActorAction"]>>[0] & {
    sessionDelivery?: Pick<SessionEntry, "sessionId" | "updatedAt" | "delivery"> | null;
  }) => Promise<ReturnType<NonNullable<ChannelApprovalCapability["authorizeActorAction"]>>>;
  resolveReviewerSenderId?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    senderId?: string | null;
    spaceId?: string | null;
  }) => string | undefined;
  getActionAvailabilityState?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    action: "approve";
    approvalKind?: ChannelApprovalKind;
    /** Exact pending plugin request when route availability depends on its selected tool. */
    request?: PluginApprovalRequest$1;
  }) => ChannelActionAvailabilityState;
  /** Prepare availability from worker-owned state before rendering an approval surface. */
  getActionAvailabilityStateAsync?: (params: Parameters<NonNullable<ChannelApprovalCapability["getActionAvailabilityState"]>>[0] & {
    sessionDelivery?: Pick<SessionEntry, "sessionId" | "updatedAt" | "delivery"> | null;
  }) => Promise<ChannelActionAvailabilityState>;
  /** Exec-native client availability for the initiating surface; distinct from same-chat auth. */
  getExecInitiatingSurfaceState?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    action: "approve";
  }) => ChannelActionAvailabilityState;
  /** Await worker-owned state before deciding initiating-surface availability. */
  getExecInitiatingSurfaceStateAsync?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    action: "approve";
  }) => Promise<ChannelActionAvailabilityState>;
  resolveApproveCommandBehavior?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    senderId?: string | null;
    approvalKind: ChannelApprovalKind;
  }) => {
    kind: "allow";
  } | {
    kind: "ignore";
  } | {
    kind: "reply";
    text: string;
  } | undefined;
};
type ChannelAllowlistConfigEditResult = {
  kind: "ok";
  changed: boolean;
  pathLabel: string;
  writeTarget: ConfigWriteTarget;
} | {
  kind: "invalid-entry";
};
type ChannelAllowlistConfig = {
  dmAllowFrom?: Array<string | number>;
  groupAllowFrom?: Array<string | number>;
  dmPolicy?: string;
  groupPolicy?: string;
  groupOverrides?: Array<{
    label: string;
    entries: Array<string | number>;
  }>;
};
type ChannelAllowlistAdapter = {
  applyConfigEdit?: (params: {
    cfg: OpenClawConfig;
    parsedConfig: Record<string, unknown>;
    accountId?: string | null;
    scope: "dm" | "group";
    action: "add" | "remove";
    entry: string;
  }) => ChannelAllowlistConfigEditResult | Promise<ChannelAllowlistConfigEditResult> | null;
  readConfig?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => ChannelAllowlistConfig | Promise<ChannelAllowlistConfig>;
  resolveNames?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    scope: "dm" | "group";
    entries: string[];
  }) => Array<{
    input: string;
    resolved: boolean;
    name?: string | null;
  }> | Promise<Array<{
    input: string;
    resolved: boolean;
    name?: string | null;
  }>>;
  supportsScope?: (params: {
    scope: "dm" | "group" | "all";
  }) => boolean;
};
type ChannelConfiguredBindingConversationRef = {
  conversationId: string;
  parentConversationId?: string;
};
type ChannelConfiguredBindingMatch = ChannelConfiguredBindingConversationRef & {
  matchPriority?: number;
};
type ChannelCommandConversationContext = {
  accountId: string;
  threadId?: string;
  threadParentId?: string;
  senderId?: string;
  sessionKey?: string;
  parentSessionKey?: string;
  from?: string;
  chatType?: string;
  originatingTo?: string;
  commandTo?: string;
  fallbackTo?: string;
};
type ChannelConfiguredBindingProvider = {
  selfParentConversationByDefault?: boolean;
  compileConfiguredBinding: (params: {
    binding: AgentBinding;
    conversationId: string;
  }) => ChannelConfiguredBindingConversationRef | null;
  matchInboundConversation: (params: {
    binding: AgentBinding;
    compiledBinding: ChannelConfiguredBindingConversationRef;
    conversationId: string;
    parentConversationId?: string;
  }) => ChannelConfiguredBindingMatch | null;
  resolveCommandConversation?: (params: ChannelCommandConversationContext) => ChannelConfiguredBindingConversationRef | null;
};
type ChannelSecurityDmRouteContext<ResolvedAccount> = ChannelSecurityContext<ResolvedAccount> & {
  accountId: string;
  principalId?: string;
};
type ChannelSecurityAdapter<ResolvedAccount = unknown> = {
  /** Resolve configured direct-conversation permissions once per new execution admission. */
  resolveDirectToolPolicy?: (ctx: ChannelDirectToolPolicyContext) => GroupToolPolicyConfig | undefined;
  applyConfigFixes?: (params: {
    cfg: OpenClawConfig;
    env: NodeJS.ProcessEnv;
  }) => ChannelDoctorConfigMutation | Promise<ChannelDoctorConfigMutation>;
  resolveDmPolicy?: (ctx: ChannelSecurityContext<ResolvedAccount>) => ChannelSecurityDmPolicy | null;
  resolveDmPolicyAsync?: (ctx: ChannelSecurityContext<ResolvedAccount>) => Promise<ChannelSecurityDmPolicy | null>;
  dmRouting?: {
    resolveDmScope?: (ctx: ChannelSecurityDmRouteContext<ResolvedAccount>) => DmScope | undefined;
    resolveDmRoute?: (ctx: ChannelSecurityDmRouteContext<ResolvedAccount> & {
      route: ResolvedAgentRoute;
    }) => {
      kind: "core" | "isolated";
    } | {
      sessionKey: string;
    } | undefined;
  };
  collectWarnings?: (ctx: ChannelSecurityContext<ResolvedAccount>) => Promise<Array<string | SecurityAuditFinding>> | Array<string | SecurityAuditFinding>;
  collectAuditFindings?: (ctx: ChannelSecurityContext<ResolvedAccount> & {
    sourceConfig: OpenClawConfig;
    orderedAccountIds: string[];
    hasExplicitAccountPath: boolean;
  }) => Promise<SecurityAuditFinding[]> | SecurityAuditFinding[];
};
//#endregion
//#region src/wizard/prompts.d.ts
type WizardSelectOption<T = string> = {
  value: T;
  label: string;
  hint?: string;
};
type WizardPromptNavigation = {
  canGoBack?: boolean;
  canGoForward?: boolean;
};
type WizardSelectParams<T = string> = {
  message: string;
  options: Array<WizardSelectOption<T>>;
  initialValue?: T;
  searchable?: boolean;
  navigation?: WizardPromptNavigation;
};
type WizardMultiSelectParams<T = string> = {
  message: string;
  options: Array<WizardSelectOption<T>>;
  initialValues?: T[];
  searchable?: boolean;
  navigation?: WizardPromptNavigation;
};
type WizardTextParams = {
  message: string;
  initialValue?: string;
  placeholder?: string;
  validate?: (value: string) => string | undefined;
  signal?: AbortSignal;
  sensitive?: boolean;
  navigation?: WizardPromptNavigation;
};
type WizardConfirmParams = {
  message: string;
  initialValue?: boolean;
  layout?: "inline" | "vertical";
  navigation?: WizardPromptNavigation;
};
type WizardProgress = {
  update: (message: string) => void;
  stop: (message?: string) => void;
};
type WizardDeviceCodeParams = {
  title: string;
  code: string;
  expiresInMinutes?: number;
  message?: string;
};
type WizardPrompter = {
  /** End a hosted flow after a required choice is declined. */
  cancel?: (message: string) => never;
  intro: (title: string) => Promise<void>;
  outro: (message: string) => Promise<void>;
  note: (message: string, title?: string) => Promise<void>;
  /** Present a browser device code as structured UI when the client supports it. */
  deviceCode?: (params: WizardDeviceCodeParams) => Promise<void>;
  plain?: (message: string) => Promise<void>;
  select: <T>(params: WizardSelectParams<T>) => Promise<T>;
  multiselect: <T>(params: WizardMultiSelectParams<T>) => Promise<T[]>;
  text: (params: WizardTextParams) => Promise<string>;
  confirm: (params: WizardConfirmParams) => Promise<boolean>;
  progress: (label: string) => WizardProgress;
  /** Queue an explicit browser destination for the next client step or browser-wait progress. */
  openUrl?: (url: string) => Promise<void>;
  disableBackNavigation?: () => void;
};
declare class WizardCancelledError extends Error {
  constructor(message?: string);
}
//#endregion
//#region src/channels/plugins/setup-group-access.d.ts
/**
 * Group access policy selected during channel setup.
 */
type ChannelAccessPolicy = "allowlist" | "open" | "disabled";
/** Prompts for group access and, when needed, its allowlist entries. */
declare function promptChannelAccessConfig(params: {
  prompter: WizardPrompter;
  label: string;
  currentPolicy?: ChannelAccessPolicy;
  currentEntries?: string[];
  placeholder?: string;
  allowOpen?: boolean;
  allowDisabled?: boolean;
  skipAllowlistEntries?: boolean;
  defaultPrompt?: boolean;
  updatePrompt?: boolean;
}): Promise<{
  policy: ChannelAccessPolicy;
  entries: string[];
} | null>;
//#endregion
//#region src/channels/plugins/setup-wizard-types.d.ts
type ChannelSetupPlugin = {
  id: ChannelId$1;
  meta: ChannelMeta;
  capabilities: ChannelCapabilities;
  config: ChannelConfigAdapter<unknown>;
  /** Channel-owned typed setup contract. Preferred over the legacy shared input adapter. */
  setupContract?: ChannelOwnedSetupContract;
  /** @deprecated Use setupContract for new plugins. */
  setup?: ChannelSetupAdapter;
  setupWizard?: ChannelSetupWizard | ChannelSetupWizardAdapter;
};
/** Status block shown before users select channels during setup. */
type ChannelSetupWizardStatus = {
  configuredLabel: string;
  unconfiguredLabel: string;
  configuredHint?: string;
  unconfiguredHint?: string;
  configuredScore?: number;
  unconfiguredScore?: number;
  resolveConfigured: (params: {
    cfg: OpenClawConfig;
    accountId?: string;
  }) => boolean | Promise<boolean>;
  resolveStatusLines?: (params: {
    cfg: OpenClawConfig;
    accountId?: string;
    configured: boolean;
  }) => string[] | Promise<string[]>;
  resolveSelectionHint?: (params: Parameters<NonNullable<ChannelSetupWizardStatus["resolveStatusLines"]>>[0]) => string | undefined | Promise<string | undefined>;
  resolveQuickstartScore?: (params: Parameters<NonNullable<ChannelSetupWizardStatus["resolveStatusLines"]>>[0]) => number | undefined | Promise<number | undefined>;
};
/** Snapshot of one credential before prompting or reusing existing config. */
type ChannelSetupWizardCredentialState = {
  accountConfigured: boolean;
  hasConfiguredValue: boolean;
  resolvedValue?: string;
  envValue?: string;
};
type ChannelSetupWizardCredentialValues = Partial<Record<string, string>>;
type ChannelSetupWizardAccountContext = {
  cfg: OpenClawConfig;
  accountId: string;
};
type ChannelSetupWizardStepContext = ChannelSetupWizardAccountContext & {
  credentialValues: ChannelSetupWizardCredentialValues;
};
type ChannelSetupWizardNote = {
  title: string;
  lines: string[];
  shouldShow?: (params: ChannelSetupWizardStepContext) => boolean | Promise<boolean>;
};
/** Lets a wizard configure an account entirely from existing environment. */
type ChannelSetupWizardEnvShortcut = {
  prompt: string;
  preferredEnvVar?: string;
  isAvailable: (params: ChannelSetupWizardAccountContext) => boolean;
  apply: (params: ChannelSetupWizardAccountContext) => OpenClawConfig | Promise<OpenClawConfig>;
};
type ChannelSetupWizardCredential = {
  /** Plugin-owned key written into the runtime setup input. */
  inputKey: string;
  providerHint: string;
  credentialLabel: string;
  preferredEnvVar?: string;
  helpTitle?: string;
  helpLines?: string[];
  envPrompt: string;
  keepPrompt: string;
  inputPrompt: string;
  allowEnv?: (params: ChannelSetupWizardAccountContext) => boolean;
  inspect: (params: ChannelSetupWizardAccountContext) => ChannelSetupWizardCredentialState;
  shouldPrompt?: (params: ChannelSetupWizardStepContext & {
    currentValue?: string;
    state: ChannelSetupWizardCredentialState;
  }) => boolean | Promise<boolean>;
  applyUseEnv?: ChannelSetupWizardEnvShortcut["apply"];
  applySet?: (params: ChannelSetupWizardStepContext & {
    value: unknown;
    resolvedValue: string;
  }) => OpenClawConfig | Promise<OpenClawConfig>;
};
type ChannelSetupWizardTextInput = {
  /** Plugin-owned key written into the runtime setup input. */
  inputKey: string;
  message: string;
  placeholder?: string;
  /** Mask input and keep any configured value server-side. */
  sensitive?: boolean;
  required?: boolean;
  applyEmptyValue?: boolean;
  helpTitle?: string;
  helpLines?: string[];
  confirmCurrentValue?: boolean;
  keepPrompt?: string | ((value: string) => string);
  currentValue?: (params: ChannelSetupWizardStepContext) => string | undefined | Promise<string | undefined>;
  initialValue?: NonNullable<ChannelSetupWizardTextInput["currentValue"]>;
  shouldPrompt?: (params: ChannelSetupWizardStepContext & {
    currentValue?: string;
  }) => boolean | Promise<boolean>;
  applyCurrentValue?: boolean;
  validate?: (params: ChannelSetupWizardStepContext & {
    value: string;
  }) => string | undefined;
  normalizeValue?: (params: ChannelSetupWizardStepContext & {
    value: string;
  }) => string;
  applySet?: (params: ChannelSetupWizardAccountContext & {
    value: string;
  }) => OpenClawConfig | Promise<OpenClawConfig>;
};
type ChannelSetupWizardAllowFromEntry = {
  input: string;
  resolved: boolean;
  id: string | null;
};
type ChannelSetupWizardHookContext = ChannelSetupWizardStepContext & {
  runtime: ChannelSetupConfigureContext["runtime"];
  prompter: WizardPrompter;
  options?: ChannelSetupConfigureContext["options"];
};
type ChannelSetupWizardHookResult = {
  cfg?: OpenClawConfig;
  credentialValues?: ChannelSetupWizardCredentialValues;
} | void;
type ChannelSetupWizard = {
  channel: string;
  status: ChannelSetupWizardStatus;
  introNote?: ChannelSetupWizardNote;
  envShortcut?: ChannelSetupWizardEnvShortcut;
  resolveAccountIdForConfigure?: (params: {
    cfg: OpenClawConfig;
    prompter: WizardPrompter;
    options?: ChannelSetupConfigureContext["options"];
    accountOverride?: string;
    shouldPromptAccountIds: boolean;
    listAccountIds: ChannelSetupPlugin["config"]["listAccountIds"];
    defaultAccountId: string;
  }) => string | Promise<string>;
  resolveShouldPromptAccountIds?: (params: {
    cfg: OpenClawConfig;
    options?: ChannelSetupConfigureContext["options"];
    shouldPromptAccountIds: boolean;
  }) => boolean;
  /** Optional pre-step hook for deriving helper config or credential values. */
  prepare?: (params: ChannelSetupWizardHookContext) => ChannelSetupWizardHookResult | Promise<ChannelSetupWizardHookResult>;
  stepOrder?: "credentials-first" | "text-first";
  credentials: ChannelSetupWizardCredential[];
  textInputs?: ChannelSetupWizardTextInput[];
  /** Optional post-step hook for final validation, writes, or post prompts. */
  finalize?: (params: ChannelSetupWizardHookContext & {
    forceAllowFrom: boolean;
  }) => ChannelSetupWizardHookResult | Promise<ChannelSetupWizardHookResult>;
  completionNote?: ChannelSetupWizardNote;
  dmPolicy?: ChannelSetupDmPolicy;
  allowFrom?: {
    helpTitle?: string;
    helpLines?: string[];
    credentialInputKey?: string;
    message: string;
    placeholder: string;
    invalidWithoutCredentialNote: string;
    parseInputs?: (raw: string) => string[];
    parseId: (raw: string) => string | null;
    resolveEntries: (params: ChannelSetupWizardStepContext & {
      entries: string[];
    }) => Promise<ChannelSetupWizardAllowFromEntry[]>;
    apply: (params: ChannelSetupWizardAccountContext & {
      allowFrom: string[];
    }) => OpenClawConfig | Promise<OpenClawConfig>;
  };
  groupAccess?: {
    label: string;
    placeholder: string;
    helpTitle?: string;
    helpLines?: string[];
    skipAllowlistEntries?: boolean;
    currentPolicy: (params: ChannelSetupWizardAccountContext) => ChannelAccessPolicy;
    currentEntries: (params: ChannelSetupWizardAccountContext) => string[];
    updatePrompt: (params: ChannelSetupWizardAccountContext) => boolean;
    setPolicy: (params: ChannelSetupWizardAccountContext & {
      policy: ChannelAccessPolicy;
    }) => OpenClawConfig;
    resolveAllowlist?: (params: ChannelSetupWizardStepContext & {
      entries: string[];
      prompter: Pick<WizardPrompter, "note">;
    }) => Promise<unknown>;
    applyAllowlist?: (params: ChannelSetupWizardAccountContext & {
      resolved: unknown;
    }) => OpenClawConfig;
  };
  disable?: (cfg: OpenClawConfig) => OpenClawConfig;
  onAccountRecorded?: ChannelSetupWizardAdapter["onAccountRecorded"];
};
type SetupChannelsOptions = {
  /** Workspace already selected by the caller, used for trusted plugin discovery. */
  workspaceDir?: string;
  allowDisable?: boolean;
  allowIMessageInstall?: boolean;
  allowSignalInstall?: boolean;
  /** Revalidate host authority immediately before an installer or other durable effect. */
  beforePersistentEffect?: () => Promise<void>;
  /** Pure live setup-owner check after asynchronous preparation and at the final write grant. */
  assertPersistentEffectCurrent?: () => void;
  onSelection?: (selection: ChannelId$1[]) => void;
  onPostWriteHook?: (hook: ChannelOnboardingPostWriteHook) => void;
  accountIds?: Partial<Record<ChannelId$1, string>>;
  onAccountId?: (channel: ChannelId$1, accountId: string) => void;
  onResolvedPlugin?: (channel: ChannelId$1, plugin: ChannelSetupPlugin) => void;
  promptAccountIds?: boolean;
  forceAllowFromChannels?: ChannelId$1[];
  deferStatusUntilSelection?: boolean;
  /**
   * The controlling client finishes device linking itself after config is
   * written (e.g. Control UI renders the WhatsApp QR via web.login.*), so
   * setup surfaces must skip terminal-interactive login/link prompts.
   */
  deferDeviceLinkToClient?: boolean;
  skipStatusNote?: boolean;
  skipDmPolicyPrompt?: boolean;
  skipConfirm?: boolean;
  quickstartDefaults?: boolean;
  initialSelection?: ChannelId$1[];
  /** Finish after the explicitly targeted channel is configured or paused. */
  finishAfterInitialSelection?: boolean;
  secretInputMode?: "plaintext" | "ref";
};
type PromptAccountIdParams = {
  cfg: OpenClawConfig;
  prompter: WizardPrompter;
  label: string;
  currentId?: string;
  listAccountIds: (cfg: OpenClawConfig) => string[];
  defaultAccountId: string;
};
type PromptAccountId = (params: PromptAccountIdParams) => Promise<string>;
type ChannelSetupStatus = {
  channel: ChannelId$1;
  configured: boolean;
  statusLines: string[];
  selectionHint?: string;
  quickstartScore?: number;
};
type ChannelSetupStatusContext = {
  cfg: OpenClawConfig;
  options?: SetupChannelsOptions;
  accountOverrides: Partial<Record<ChannelId$1, string>>;
};
type ChannelSetupConfigureContext = ChannelSetupStatusContext & {
  runtime: RuntimeEnv;
  prompter: WizardPrompter;
  shouldPromptAccountIds: boolean;
  forceAllowFrom: boolean;
};
/** Deferred hook for channel work that must run after config persistence. */
type ChannelOnboardingPostWriteHook = {
  channel: ChannelId$1;
  accountId: string;
  run: (ctx: {
    cfg: OpenClawConfig;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
};
type ChannelSetupResult = {
  cfg: OpenClawConfig;
  accountId?: string;
  completion?: "configured";
} | {
  cfg: OpenClawConfig;
  /** Paused setup is persisted without configured-account hooks or routing. */
  completion: "paused";
  accountId?: never;
};
type ChannelSetupConfiguredResult = ChannelSetupResult | "skip";
type ChannelSetupDmPolicy = {
  label: string;
  channel: ChannelId$1;
  policyKey: string;
  allowFromKey: string;
  resolveConfigKeys?: (cfg: OpenClawConfig, accountId?: string) => {
    policyKey: string;
    allowFromKey: string;
  };
  getCurrent: (cfg: OpenClawConfig, accountId?: string) => DmPolicy;
  setPolicy: (cfg: OpenClawConfig, policy: DmPolicy, accountId?: string) => OpenClawConfig;
  promptAllowFrom?: (params: {
    cfg: OpenClawConfig;
    prompter: WizardPrompter;
    accountId?: string;
  }) => Promise<OpenClawConfig>;
};
type ChannelSetupWizardAdapter = {
  channel: ChannelId$1;
  getStatus: (ctx: ChannelSetupStatusContext) => Promise<ChannelSetupStatus>;
  configure: (ctx: ChannelSetupConfigureContext) => Promise<ChannelSetupResult>;
  configureInteractive?: (ctx: ChannelSetupConfigureContext & {
    configured: boolean;
    label: string;
  }) => Promise<ChannelSetupConfiguredResult>;
  configureWhenConfigured?: NonNullable<ChannelSetupWizardAdapter["configureInteractive"]>;
  afterConfigWritten?: (ctx: ChannelSetupWizardAccountContext & {
    previousCfg: OpenClawConfig;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
  dmPolicy?: ChannelSetupDmPolicy;
  onAccountRecorded?: (accountId: string, options?: SetupChannelsOptions) => void;
  disable?: (cfg: OpenClawConfig) => OpenClawConfig;
};
//#endregion
//#region src/channels/plugins/types.plugin.d.ts
type ChannelGatewayMethodDescriptor = {
  name: string;
  scope?: OperatorScope;
  description?: string;
};
/** Full capability contract for a native channel plugin. */
type ChannelPlugin<ResolvedAccount = any, Probe = unknown, Audit = unknown, GatewayVersion extends 1 | 2 = 1> = Omit<ChannelSetupPlugin, "config"> & {
  defaults?: {
    queue?: {
      debounceMs?: number;
    };
  };
  reload?: {
    configPrefixes: string[];
    /** Published dynamic reads; `*` matches one nonempty dotted config key. */
    noopPrefixes?: string[];
    /**
     * Opt into restarting only the changed non-default named account.
     * Set only when sibling account resolution and lifecycle state are isolated and
     * account stop fully settles owned work. Shared, default, removed, or unresolved
     * account changes still restart the whole channel.
     */
    accountScopedRestart?: boolean;
  };
  config: ChannelConfigAdapter<ResolvedAccount>;
  configSchema?: ChannelConfigSchema;
  pairing?: ChannelPairingAdapter;
  security?: ChannelSecurityAdapter<ResolvedAccount>;
  groups?: ChannelGroupAdapter;
  mentions?: ChannelMentionAdapter;
  outbound?: ChannelOutboundAdapter;
  status?: ChannelStatusAdapter<ResolvedAccount, Probe, Audit>;
  gatewayMethods?: string[];
  gatewayMethodDescriptors?: ChannelGatewayMethodDescriptor[];
  gateway?: GatewayVersion extends 2 ? ChannelGatewayAdapterV2<ResolvedAccount> : ChannelGatewayAdapter<ResolvedAccount>;
  auth?: ChannelAuthAdapter;
  approvalCapability?: ChannelApprovalCapability;
  elevated?: ChannelElevatedAdapter;
  commands?: ChannelCommandAdapter;
  lifecycle?: ChannelLifecycleAdapter;
  secrets?: ChannelSecretsAdapter;
  allowlist?: ChannelAllowlistAdapter;
  doctor?: ChannelDoctorAdapter;
  bindings?: ChannelConfiguredBindingProvider;
  conversationBindings?: ChannelConversationBindingSupport;
  streaming?: ChannelStreamingAdapter;
  threading?: ChannelThreadingAdapter;
  message?: ChannelMessageAdapterShape;
  messaging?: ChannelMessagingAdapter;
  agentPrompt?: ChannelAgentPromptAdapter;
  directory?: ChannelDirectoryAdapter;
  resolver?: ChannelResolverAdapter;
  actions?: ChannelMessageActionAdapter;
  heartbeat?: ChannelHeartbeatAdapter;
  agentTools?: ChannelAgentToolFactory | ChannelAgentTool[];
};
/** Heterogeneous registries erase each plugin's account/probe/audit family, retaining its adapter version. */
type AnyChannelPlugin$2 = ChannelPlugin<any, any, any, 1 | 2>;
//#endregion
//#region src/gateway/cron-creator-authority-grant.types.d.ts
type CronCreatorAuthorityGrant = Readonly<{
  runId: string;
  token: string;
}>;
/** Private native sender fact shared by creator grants and the stored job envelope. */
type CronAuthenticatedChannelRequester = {
  version: 1;
  channel: string;
  accountId: string;
  senderId: string;
};
//#endregion
//#region src/cron/plugin-command-schedule.types.d.ts
/** Host-captured invocation facts, never a public cron payload or executable grant. */
type PluginCommandSchedule = {
  version: 1;
  pluginId: string;
  pluginIncarnation: string;
  hostProcessId: string;
  pluginSource: string;
  pluginRoot?: string;
  pluginVersion?: string;
  command: string;
  args?: string;
  channel: string;
  parent: {
    agentId: string;
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
  };
  sourceRunId: string;
  operatorSource: QueuedOperatorRecoverySource;
  toolsAllow: string[];
  deadlineAtMs: number;
  maxRuns: number;
};
/**
 * Store-private restart continuity, kept in job state so the envelope keeps its released shape.
 * Present only on schedules accepted by a host that re-arms them after a Gateway restart, from a
 * plugin whose loaded code has a code identity: its captured source digest or, for a core-bundled
 * plugin, its exact loaded OpenClaw build. It names the Gateway process and plugin
 * instance currently serving the schedule, and the code identity any later instance must match.
 * Older readers ignore it and keep ending the schedule with its original process.
 */
type PluginCommandScheduleBinding = {
  hostProcessId: string;
  pluginIncarnation: string;
  /**
   * Code identity fixed when the schedule is accepted: the captured source digest, or a
   * `bundled-build:` identity of a core-bundled plugin's exact build. The released field name
   * stays so stored rows keep one shape.
   */
  sourceDigest: string;
};
//#endregion
//#region src/cron/runtime-authority.d.ts
type CronRuntimeAuthority = Readonly<{
  version: 1;
  /** Concrete harness runtime that alone may consume this opaque authority. */
  runtimeId: string;
  /** Runtime-owned payload discriminator; core never interprets its value. */
  namespace: string;
  payload: Readonly<Record<string, unknown>>;
}>;
//#endregion
//#region src/cron/scheduled-tool-policy.d.ts
/** Closed, server-authored origin of an account-scoped scheduled tool cap. */
type CronScheduledToolCallerOrigin = {
  kind: "external";
  channel: string;
} | {
  kind: "local";
} | {
  kind: "unknown";
};
/**
 * Restrict-only execution target for a job's exec grant, captured from a
 * creator surface whose only exec capability was host-pinned. New pinned jobs
 * persist this as part of a grant-coupled envelope; unmarked legacy jobs keep
 * baseline exec behavior.
 */
type CronToolsAllowExecTarget = {
  version: 1;
  host: "gateway";
  /** Mandatory approval floor inherited from the captured creator surface. */
  ask?: "always";
};
/** Persisted proof that this job was created with an exact exec restriction. */
type CronToolsAllowExecTargetRequirement = {
  version: 1;
  target: CronToolsAllowExecTarget;
  grantIndex: number;
  recoveryRequired?: never;
} | {
  version: 1;
  target?: never;
  recoveryRequired: true;
};
/** Server-authored provenance for a persisted scheduled tool-cap authority envelope. */
type CronScheduledToolPolicy = {
  version: 1;
  mode: "trusted";
  ownerSessionKey?: never;
  ownerAccountId?: never;
} | {
  version: 1;
  mode: "account";
  ownerSessionKey: string;
  ownerAccountId: string;
};
//#endregion
//#region src/cron/stream-sandbox-target.d.ts
/** Creator-owned logical target; physical process custody belongs to the sandbox registry. */
type CronStreamSandboxTarget = {
  version: 1;
  backendId: "docker";
  agentId: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision?: string;
  scopeKey: string;
  workspaceDir: string;
  agentWorkspaceDir: string;
  workspaceAccess: "none" | "ro" | "rw";
  containerWorkdir: string;
  workspaceSource?: "managed-worktree";
  configLabel: string;
  operator?: {
    profileId: string;
    scopes: string[];
    assignedRole: string | null;
    githubLogin: string | null;
    gatewayAccessGrant: GatewayAccessGrantRef | null;
  };
};
//#endregion
//#region src/cron/types-shared.d.ts
/** Optional dynamic-cadence bounds for one cron job. */
type CronPacing = SchemaContract<NonNullable<CronJob$1["pacing"]>>;
/** Optional local-time execution window; the end is exclusive. */
type CronActiveHours = {
  start: string;
  end: string;
  timezone?: string;
};
/** Shared persisted cron job envelope used by runtime and external config shapes. */
type CronJobBase<TSchedule, TSessionTarget, TWakeMode, TPayload, TDelivery, TFailureAlert> = {
  id: string;
  agentId?: string;
  sessionKey?: string;
  name: string;
  description?: string;
  enabled: boolean;
  deleteAfterRun?: boolean;
  createdAtMs: number;
  updatedAtMs: number;
  schedule: TSchedule;
  pacing?: CronPacing;
  activeHours?: CronActiveHours;
  idleOnly?: boolean;
  sessionTarget: TSessionTarget;
  wakeMode: TWakeMode;
  payload: TPayload;
  delivery?: TDelivery;
  failureAlert?: TFailureAlert;
};
//#endregion
//#region src/cron/types.d.ts
/** Supported schedule forms persisted in cron job specs. */
type CronSchedule = CronJob$1["schedule"];
/** Runtime target that decides whether a job joins main, isolated, or a named session. */
type CronSessionTarget = "main" | "isolated" | "current" | `session:${string}`;
/** Wake policy for main-session jobs waiting on heartbeat/user activity. */
type CronWakeMode$1 = CronJob$1["wakeMode"];
/** Messaging channel id accepted by cron delivery settings. */
type CronMessageChannel = ChannelId$1;
/** Delivery mode for job completion output. */
type CronDeliveryMode = "none" | "announce" | "webhook";
/** Completion delivery configuration for cron job output. */
type CronDelivery = {
  mode: CronDeliveryMode;
  /** Resolve the owner's current direct-message route at execution time. */
  target?: "owner";
  directPolicy?: "allow" | "block";
  channel?: CronMessageChannel;
  to?: string;
  /** Explicit thread/topic id for channels that support threaded delivery. */
  threadId?: string | number;
  /** Explicit channel account id for multi-account setups (e.g. multiple Telegram bots). */
  accountId?: string;
  bestEffort?: boolean;
  /** Additional webhook destination used when a job must keep chat delivery. */
  completionDestination?: CronCompletionDestination;
  /** Separate destination for failure notifications. */
  failureDestination?: CronFailureDestination;
};
/** Webhook completion destination used alongside chat delivery. */
type CronCompletionDestination = {
  mode: "webhook";
  to?: string;
};
/** Destination override for failed-run notifications. */
type CronFailureDestination = {
  channel?: CronMessageChannel;
  to?: string;
  accountId?: string;
  mode?: "announce" | "webhook";
};
/** Partial failure-destination update shape; null clears individual override fields. */
type CronFailureDestinationPatch = { [K in keyof CronFailureDestination]?: CronFailureDestination[K] | null; };
/** Partial delivery update shape; null clears optional delivery destinations or fields. */
type CronDeliveryPatch = Partial<Pick<CronDelivery, "mode" | "bestEffort">> & {
  target?: "owner" | null;
  directPolicy?: "allow" | "block" | null;
  channel?: CronMessageChannel | null;
  to?: string | null;
  threadId?: string | number | null;
  accountId?: string | null;
  completionDestination?: CronCompletionDestination | null;
  failureDestination?: CronFailureDestinationPatch | null;
};
/** Execution outcome, separate from delivery outcome. */
type CronRunStatus = NonNullable<CronRunLogEntry["status"]>;
/** Model/provider/usage telemetry attached to cron run results and logs. */
type CronRunTelemetry = Pick<CronRunLogEntry, "model" | "provider" | "usage">;
/** Bounded diagnostic bundle stored on the run outcome. */
type CronRunDiagnostics = NonNullable<CronRunLogEntry["diagnostics"]>;
/** Explicit execution-error disposition used consistently by retry, history, and alerts. */
type CronRunErrorClassification = {
  kind: "reason";
  reason: FailoverReason;
} | {
  kind: "permanent";
} | {
  kind: "session-conflict";
} |
/** Operator cancellation or lifecycle retirement, never an execution timeout. */
{
  kind: "aborted";
};
/** Closed producer-authored facts allowed in operator-facing failure notifications. */
type CronFailureNotificationDetail = {
  kind: "invalid-target";
} | {
  kind: "command-exit";
  exitCode: number;
} | {
  kind: "command-timeout";
  mode: "wall-clock" | "no-output";
} | {
  kind: "script-failure";
  source: "payload" | "trigger";
  code: CronTriggerFailureCode;
};
/** Execution result used to author persisted state, run logs, and isolated turn results. */
type CronRunOutcome = {
  status: CronRunStatus;
  error?: string;
  /** True once agent execution begins; retries after this point can replay side effects. */
  executionStarted?: boolean;
  /** Admission deferral preserves the unstarted occurrence's scheduled slot. */
  admissionDeferred?: boolean;
  admissionDeferredReason?: "busy" | "active-hours";
  /** Lifecycle-owned restart fact; transient input to cron settlement, not a public event. */
  interruptedByRestart?: boolean;
  /** Optional classifier for execution errors to guide fallback behavior. */
  errorKind?: "delivery-target";
  errorClassification?: CronRunErrorClassification;
  /** Transient internal detail; never project into persisted or public cron events. */
  failureNotificationDetail?: CronFailureNotificationDetail;
  summary?: string;
  result?: AutomationResult;
  /** Producer-authored terminal reply fact without exposing reply text. */
  replyDisposition?: AgentRunTerminalReplySnapshot["disposition"];
  sessionId?: string;
  sessionKey?: string;
  diagnostics?: CronRunDiagnostics;
  /** Transient: the run was skipped because its parent conversation is gone; pause the job. */
  parentUnavailable?: CronParentUnavailable;
};
/** Why a parent-linked job pauses before any session is created. */
type CronParentUnavailable = {
  reason: "removed" | "archived" | "worktree-missing";
  parentSessionKey: string;
  worktreePath?: string;
};
/** Embedded-agent execution phase names surfaced to cron watchdog progress. */
type CronAgentExecutionPhase = EmbeddedAgentExecutionPhase;
/** Watchdog-visible execution metadata for an in-flight cron agent run. */
type CronAgentExecutionStarted = {
  jobId: string;
  agentId?: string;
  sessionId?: string;
  sessionKey?: string;
  /** Invocation run id; every attempt registers its embedded handle under it. */
  runId?: string;
  /** True when this runner belongs to a later candidate in the same fallback chain. */
  isFallback?: boolean;
  phase?: CronAgentExecutionPhase;
  provider?: string;
  model?: string;
  backend?: string;
  source?: string;
  tool?: string;
  toolCallId?: string;
  itemId?: string;
};
/** Watchdog update that requires the new execution phase. */
type CronAgentExecutionPhaseUpdate = CronAgentExecutionStarted & {
  phase: CronAgentExecutionPhase;
};
/** Failure alert policy persisted on a cron job. */
type CronFailureAlert = Exclude<NonNullable<CronJob$1["failureAlert"]>, false>;
/** Partial failure-alert update; null clears an inherited field override. */
type CronFailureAlertPatch = { [K in keyof CronFailureAlert]?: CronFailureAlert[K] | null; };
/** Payload variants cron can execute in main-session or detached modes. */
type CronPayload = Exclude<CronJob$1["payload"], {
  kind: "agentTurn";
}> | (Extract<CronJob$1["payload"], {
  kind: "agentTurn";
}> & CronExternalContent);
/** Partial payload update shape used by cron patch/edit flows. */
type CronPayloadPatch = Exclude<CronPayloadPatchWire, {
  kind: "agentTurn";
}> | (Extract<CronPayloadPatchWire, {
  kind: "agentTurn";
}> & CronExternalContent);
type CronPayloadPatchWire = NonNullable<CronUpdateParams["patch"]["payload"]>;
type CronExternalContent = {
  /** Immutable external hook provenance for async dispatch. */
  externalContentSource?: HookExternalContentSource;
};
/** Mutable runtime state persisted beside the immutable cron job spec. */
type CronJobState = Omit<CronJob$1["state"], "deliverySuppressionReason" | "lastStatus"> & {
  /** Exact startup catch-up slot protected from future-slot repair across restarts. */
  startupCatchupAtMs?: number;
  /** Exact paced completion slot protected from future-slot repair until consumed. */
  pacedNextRunAtMs?: number;
  /** Exact occurrence retained across a manual run; authored one-shots survive pause. */
  forcePreservedNextRunAtMs?: number;
  /** Store-private, monotonic launch attempts for a requester-admitted plugin command. */
  pluginCommandRuns?: number;
  /** Store-private restart continuity for a plugin command schedule; see its type. */
  pluginCommandBinding?: PluginCommandScheduleBinding;
  /** Durable pre-admission reservation. Cleared on restart without recording a run. */
  queuedAtMs?: number;
  /** Exact receipt awaiting scheduler reconciliation, even after execution authority closes. */
  runningReceiptId?: string;
  /** Nonce for a committed schedule edit during the pending run. */
  runningScheduleChangeId?: string;
  /**
   * Unresolved recovery scope and last notified signature, when an alert was requested.
   * `repair` records the owner-conversation repair request that replaced the streak's first
   * alert, and `alerted` that its fallback alert was sent. It lasts until the job succeeds,
   * so a streak is repaired at most once.
   */
  failureAlertIncident?: {
    signature?: string;
    scope: "run" | "trigger";
    repair?: {
      atMs: number;
      deadlineAtMs?: number;
      settledAtMs?: number;
      alerted?: true;
    };
  };
  /** Fences notification settlement when multiple cycles share a timestamp. */
  lastFailureNotificationId?: string;
  /** Number of consecutive schedule computation errors. Auto-disables job after threshold. */
  scheduleErrorCount?: number;
  /** @deprecated Use lastRunStatus. */
  lastStatus?: "ok" | "error" | "skipped";
  /** Intentional non-delivery reason for the last run, when recorded by the dispatcher. */
  deliverySuppressionReason?: NormalizeReplySkipReason;
};
type CronTrigger = SchemaContract<NonNullable<CronJob$1["trigger"]>>;
/**
 * Closed failure taxonomy for trigger-script evaluation. Mirrors the code-mode
 * failure codes plus the trigger tool budget; trigger-script.ts asserts the
 * union stays in sync at compile time. Lives here (leaf module) so the cron
 * service contract never imports the agents runtime.
 */
type CronTriggerFailureCode = "aborted" | "invalid_input" | "runtime_unavailable" | "timeout" | "output_limit_exceeded" | "snapshot_limit_exceeded" | "internal_error" | "plugin_reload_failed" | "tool_budget_exceeded";
/** Public cron job contract with spec fields and mutable run state. */
type CronJob = CronJobBase<CronSchedule, CronSessionTarget, CronWakeMode$1, CronPayload, CronDelivery, CronFailureAlert | false> & {
  declarationKey?: string;
  displayName?: string;
  /** Read-only execution placement derived from the stored stream target. */
  streamExecutionHost?: "gateway" | "sandbox";
  /**
   * Read-only stored payload kind when `payload` is a compatibility placeholder. A plugin command
   * schedule keeps its reserved agentTurn sentinel in `payload` for existing readers.
   */
  payloadSource?: {
    kind: "pluginCommand";
    pluginId: string;
    command: string;
  };
  owner?: {
    agentId?: string;
    sessionKey?: string;
    /** Authenticated account that created this scheduled authority envelope. */
    accountId?: string;
  };
  /** Server-authored provenance for requester-scoped scheduled tool authority. */
  scheduledToolPolicy?: CronScheduledToolPolicy;
  trigger?: CronTrigger;
  state: CronJobState;
};
/** Store-only proof omitted from public Gateway results and the CronJob wire/type contract. */
type CronToolsAllowProvenance = {
  version: 1;
  source: "final-executable-surface";
  /** Store-private creator origin; missing legacy facts normalize to unknown. */
  callerOrigin?: CronScheduledToolCallerOrigin;
  channelRequester?: CronAuthenticatedChannelRequester;
} | ({
  version: 1;
  source: "authenticated-requester";
} & ({
  /** Authenticated creator origin captured independently of the tool surface. */
  callerOrigin: CronScheduledToolCallerOrigin;
  channelRequester?: CronAuthenticatedChannelRequester;
} | {
  callerOrigin?: never;
  channelRequester: CronAuthenticatedChannelRequester;
}));
/** Persisted row shape; public Gateway and wire contracts use CronJob. */
type CronStoredJob = Omit<CronJob, "streamExecutionHost" | "payloadSource"> & {
  /** Immutable host-captured scheduled command invocation; never public create/patch input. */
  pluginCommand?: PluginCommandSchedule;
  /** Original authenticated source for a same-conversation continuation, never a public grant. */
  operatorSource?: {
    source: RestartRecoveryOperatorSource;
    executionRevision: string;
  };
  /** Captured inference owner; private and independent of scheduled tool authority. */
  inferenceBinding?: CronInferenceBinding;
  /** Creation-bound destination for isolated results when no external route exists. */
  sourceConversation?: {
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
  };
  /** Trusted logical sandbox and original access basis, never public create/patch input. */
  streamSandbox?: CronStreamSandboxTarget;
  /** Immutable revisions inherited from the authorized creator session, never human mutation authority. */
  skillLibrarySelections?: SessionEntry["skillLibrarySelections"];
  /** Immutable creator provenance stamped by the trusted cron creation seam. */
  createdActor?: SessionCreatedActor;
  toolsAllowProvenance?: CronToolsAllowProvenance;
  toolsAllowExecTarget?: CronToolsAllowExecTarget;
  /** Exact expected pin for jobs created from a verified host-owned exec projection. */
  toolsAllowExecTargetRequirement?: CronToolsAllowExecTargetRequirement;
  /** Runtime-private authority omitted from public Gateway and wire contracts. */
  runtimeAuthority?: CronRuntimeAuthority;
  /** Authority was explicitly cleared and must be reauthorized before app reuse. */
  runtimeAuthorityRecoveryRequired?: true;
};
type CronJobStateInput = Partial<Omit<CronJobState, "lastMeaningfulResult" | "autoDisabled" | "scheduleActivatedAtMs" | "streamSourceIdentity" | "sourceIdentity" | "runningReceiptId" | "runningScheduleChangeId" | "pluginCommandRuns" | "pluginCommandBinding">>;
/** Create input accepted by cron APIs before id/timestamps/state are assigned. */
type CronJobCreate = Omit<CronJob, "id" | "createdAtMs" | "updatedAtMs" | "state" | "scheduledToolPolicy" | "streamExecutionHost" | "payloadSource"> & {
  /** Internal callers can reserve a durable id before creation; public cron.add omits this. */
  id?: string;
  state?: CronJobStateInput;
};
/** Patch input accepted by cron APIs without allowing immutable identity fields. */
type CronJobPatch = Partial<Omit<CronJob, "id" | "createdAtMs" | "state" | "payload" | "delivery" | "failureAlert" | "declarationKey" | "displayName" | "owner" | "scheduledToolPolicy" | "streamExecutionHost" | "payloadSource" | "pacing" | "activeHours" | "idleOnly" | "trigger">> & {
  displayName?: string | null;
  pacing?: CronPacing | null;
  activeHours?: CronActiveHours | null;
  idleOnly?: boolean | null;
  trigger?: CronTrigger | null;
  payload?: CronPayloadPatch;
  delivery?: CronDeliveryPatch;
  failureAlert?: CronFailureAlertPatch | false | null;
  state?: CronJobStateInput;
};
//#endregion
//#region src/cron/event-source.d.ts
/** Immutable payload stored in the existing durable ingress queue. */
type CronEventInput = {
  jobId: string;
  sourceIdentity: string;
  eventId: string;
  receivedAtMs: number;
  payload: unknown;
};
/** The token must refer to a claim in the same admitted shared-state database. */
type CronEventClaim = {
  queueName: string;
  id: string;
  token: string;
};
type CronEventRunOptions = Omit<CronEventInput, "jobId"> & {
  claim: CronEventClaim;
  /** Captured plugin service/source authority, checked at transaction and commit. */
  commitGuard: () => void;
};
type CronEventRunResult = {
  kind: "transferred";
  receiptId: string;
  runId: string;
} | {
  kind: "pending";
  reason: "busy" | "paused" | "stopped";
} | {
  kind: "invalidated";
};
type CronEventSourceSnapshot = {
  jobId: string;
  sourceIdentity: string;
  enabled: boolean;
  options: Record<string, unknown>;
};
//#endregion
//#region src/gateway/operator-approval-store.types.d.ts
type OperatorApprovalKind = "exec" | "plugin" | "system-agent";
type OperatorApprovalStatus = "pending" | "allowed" | "denied" | "expired" | "cancelled";
type OperatorApprovalDecision = "allow-once" | "allow-always" | "deny";
type OperatorApprovalTerminalReason = ApprovalTerminalReason;
type OperatorApprovalResolverKind = NonNullable<TerminalApprovalSnapshot["resolver"]>["kind"];
type OperatorApprovalRequester = {
  deviceId: string | null;
  clientId: string | null;
  deviceTokenAuth: boolean;
};
type OperatorApprovalSource = {
  agentId: string | null;
  sessionKey: string | null;
  sessionId: string | null;
  runId: string | null;
  toolCallId: string | null;
  toolName: string | null;
};
type OperatorApprovalResolver = {
  kind: OperatorApprovalResolverKind;
  id: string | null;
};
type OperatorApprovalRecord = {
  id: string;
  resolutionRef: string;
  kind: OperatorApprovalKind;
  status: OperatorApprovalStatus;
  presentation: ApprovalPresentation;
  requester: OperatorApprovalRequester;
  reviewerDeviceIds: string[];
  source: OperatorApprovalSource;
  audienceSessionKeys: string[];
  runtimeEpoch: string;
  createdAtMs: number;
  expiresAtMs: number;
  updatedAtMs: number;
  decision: OperatorApprovalDecision | null;
  terminalReason: OperatorApprovalTerminalReason | null;
  resolvedAtMs: number | null;
  resolver: OperatorApprovalResolver | null;
  consumedAtMs: number | null;
  consumedBy: string | null;
};
/** A live waiter lends consumption to the effect's transaction and observes only its commit. */
type ExecApprovalPreparedConsumption = {
  input: Readonly<OperatorApprovalConsumptionInput>;
  databasePath: string;
  assertCurrent: () => void;
  markCommitted: (record: OperatorApprovalRecord) => void;
};
type ResolveOperatorApprovalResult = {
  outcome: "resolved";
  record: OperatorApprovalRecord;
} | {
  outcome: "expired";
  record: OperatorApprovalRecord;
} | {
  outcome: "already-resolved";
  retry: "same" | "conflict";
  record: OperatorApprovalRecord;
} | {
  outcome: "decision-not-allowed";
  record: OperatorApprovalRecord;
} | {
  outcome: "not-found";
} | {
  outcome: "corrupt";
};
type ForceDenyOperatorApprovalResult = {
  outcome: "denied";
  record: OperatorApprovalRecord;
} | {
  outcome: "expired";
  record: OperatorApprovalRecord;
} | {
  outcome: "not-due";
  record: OperatorApprovalRecord;
} | {
  outcome: "already-terminal";
  record: OperatorApprovalRecord;
} | {
  outcome: "not-found";
} | {
  outcome: "corrupt";
};
type OperatorApprovalConsumptionInput = {
  id: string;
  consumerId: string;
  expectedKind?: OperatorApprovalKind;
  runtimeEpoch?: string;
  redemptionWindowMs?: number;
  nowMs?: number;
};
/** Legacy callback guards share the worker precommit boundary with host-owned guards. */
type OperatorApprovalStoreGuard = {
  family: "worker" | "native-compatibility";
  assertCurrent: () => void;
};
//#endregion
//#region src/state/agent-deletion-journal.types.d.ts
type HeldAgentDatabase = {
  agentId: string;
  path: string;
};
//#endregion
//#region src/state/agent-deletion-journal-recovery.kernel.d.ts
type AgentDeletionRecoveryHoldPredicate = {
  agentId: string;
  held: readonly HeldAgentDatabase[];
  applies: boolean;
};
//#endregion
//#region src/cron/scratch-contract.d.ts
type CronJobScratch = {
  content: string;
  revision: number;
  sourceSha256?: string;
  updatedAtMs: number;
};
/** An unset retains its revision tombstone so stale writers cannot resurrect content. */
type CronJobScratchState = {
  currentRevision: number;
  scratch?: CronJobScratch;
};
type CronJobScratchWriteResult = {
  ok: true;
  currentRevision: number;
  scratch?: CronJobScratch;
} | {
  ok: false;
  reason: "revision-conflict";
  currentRevision: number;
};
//#endregion
//#region src/agents/sandbox/types.d.ts
type RequiredDockerConfigKeys = "image" | "containerPrefix" | "workdir" | "readOnlyRoot" | "tmpfs" | "network" | "capDrop";
type SandboxDockerConfig = Omit<SandboxDockerSettings, RequiredDockerConfigKeys> & Required<Pick<SandboxDockerSettings, RequiredDockerConfigKeys>>;
/** In-process provenance, bound to the original resolved allowlist; never serialized. */
declare const SANDBOX_DEFAULT_TOOL_ALLOW: unique symbol;
type SandboxToolPolicy = {
  [SANDBOX_DEFAULT_TOOL_ALLOW]?: readonly string[];
  allow?: string[];
  deny?: string[];
};
type SandboxToolPolicySource = {
  source: "agent" | "global" | "default";
  /**
   * Config key path hint for humans.
   * (Keyed agent entries use `agents.entries.*.…` form.)
   */
  key: string;
};
type SandboxToolPolicyResolved = SandboxToolPolicy & {
  allow: string[];
  deny: string[];
  sources: {
    allow: SandboxToolPolicySource;
    deny: SandboxToolPolicySource;
  };
};
type SandboxWorkspaceAccess = NonNullable<AgentSandboxConfig["workspaceAccess"]>;
/** Prepared resource ownership; only proven profiles retain cross-session workspaces. */
type SandboxIsolationSubject = {
  kind: "profile";
  profileId: string;
} | {
  kind: "session";
  sessionKey: string;
};
type SandboxBrowserSettings = SchemaContract<NonNullable<AgentSandboxConfig["browser"]>>;
type SandboxBrowserConfig = Required<Omit<SandboxBrowserSettings, "cdpSourceRange" | "binds">> & Pick<SandboxBrowserSettings, "cdpSourceRange" | "binds">;
type SandboxPruneConfig = Required<SchemaContract<NonNullable<AgentSandboxConfig["prune"]>>>;
type SandboxSshConfig = {
  target?: string;
  command: string;
  workspaceRoot: string;
  strictHostKeyChecking: boolean;
  updateHostKeys: boolean;
  identityFile?: string;
  certificateFile?: string;
  knownHostsFile?: string;
  identityData?: string;
  certificateData?: string;
  knownHostsData?: string;
};
type SandboxScope = NonNullable<AgentSandboxConfig["scope"]>;
type SandboxConfig = {
  mode: "off" | "non-main" | "all";
  backend: SandboxBackendId;
  scope: SandboxScope;
  workspaceAccess: SandboxWorkspaceAccess;
  workspaceRoot: string;
  dockerTmpfsSource: "default" | "configured";
  docker: SandboxDockerConfig;
  ssh: SandboxSshConfig;
  browser: SandboxBrowserConfig;
  tools: SandboxToolPolicy;
  prune: SandboxPruneConfig;
};
type SandboxBrowserContext = {
  bridgeUrl: string;
  noVncUrl?: string;
  containerName: string;
};
type SandboxContext = {
  /** Creators release retained authority after last use; supplied contexts remain caller-owned. */
  [Symbol.dispose]?: () => void;
  enabled: boolean;
  /** Immutable creator policy: this session may never escape to a host execution target. */
  required?: true;
  /** Core-prepared execution projection; ordinary rw sandboxes retain the requested workspace. */
  workspaceSource?: "managed-worktree";
  /** Selected repository subdirectory within the full private projection. */
  workspaceCwd?: string;
  backendId: SandboxBackendId;
  sessionKey: string;
  /** Agent admitted by sandbox policy resolution, which may differ from the requester. */
  agentId?: string;
  workspaceDir: string;
  agentWorkspaceDir: string;
  skillsWorkspaceDir?: string;
  skillsEligibility?: SkillEligibilityContext;
  skillUsagePaths?: SkillUsagePath[];
  readOnlyResourceMounts?: Array<{
    hostPath: string;
    containerPath: string;
  }>;
  workspaceAccess: SandboxWorkspaceAccess;
  runtimeId: string;
  runtimeLabel: string;
  containerName: string;
  containerWorkdir: string;
  docker: SandboxDockerConfig;
  tools: SandboxToolPolicy;
  browserAllowHostControl: boolean;
  browser?: SandboxBrowserContext;
  fsBridge?: SandboxFsBridge;
  backend?: SandboxBackendHandle;
};
//#endregion
//#region src/cron/stream-exec-authority.d.ts
type CronStreamExecApproval = {
  /** Retain creation identity, including derived authority revisions, across the approval wait. */
  createdAtMs: number;
  policyKey: string;
  binding: string;
  consumption: ExecApprovalPreparedConsumption;
};
/** Historical confirmation of the native approval consumed by this stream mutation. */
type CronStreamExecApprovalReceipt = {
  approvalId: string;
  decision: "allow-once";
  source: "operator";
};
/** Prepared run policy; only the host-floor branch reads approvals at the write boundary. */
type CronStreamExecPolicy = {
  sandboxContext?: SandboxContext;
  /** Rechecks cancellation and the creator’s captured policy at the mutation boundary. */
  assertCurrentSource?: () => void;
  /** Per-invocation result projection only; never grants execution authority. */
  onApprovalCommitted?: (receipt: CronStreamExecApprovalReceipt) => void;
} & ({
  kind: "resolved";
  assertCurrent: (approvedPolicyKey?: string) => void;
} | {
  kind: "needs-approvals";
  assertCurrent: (file: ExecApprovalsFile, approvedPolicyKey?: string) => void;
});
//#endregion
//#region src/cron/service/job-options.types.d.ts
/** Caller-specific declaration-key visibility and explicit enablement metadata. */
type CronAddOptions = {
  /** Validated host invocation facts; immutable after fresh command-job creation. */
  pluginCommand?: CronStoredJob["pluginCommand"];
  /** Captured source digest of the admitting plugin instance; enables restart continuity. */
  pluginCommandSourceDigest?: string;
  operatorSource?: NonNullable<CronStoredJob["operatorSource"]>["source"];
  operatorSourceExecutionRevision?: string;
  inferenceBinding?: CronStoredJob["inferenceBinding"];
  sourceConversation?: CronStoredJob["sourceConversation"];
  /** Logical sandbox target captured from the admitted creator, never public input. */
  streamSandbox?: CronStoredJob["streamSandbox"];
  /** Selected revisions captured from a validated caller session, never public input. */
  skillLibrarySelections?: CronStoredJob["skillLibrarySelections"];
  matchesExisting?: (job: CronJob) => boolean;
  enabledExplicit?: boolean;
  /** Reserved declaration namespaces require trusted ownership at creation. */
  systemOwned?: boolean;
  /** Trusted creator provenance persisted with new jobs; never accepted from public input. */
  createdActor?: SessionCreatedActor;
  /** Authenticated caller provenance stamped by the service, never public input. */
  scheduledToolPolicy?: CronScheduledToolPolicy;
  /** Private proof from an authenticated agent-runtime caller. */
  toolsAllowProvenance?: CronToolsAllowProvenance;
  /** Restrict-only exec pin from the signed creator-turn identity. */
  toolsAllowExecTarget?: CronToolsAllowExecTarget;
  /** Synchronous Gateway-owned liveness check repeated at mutation admission and commit. */
  commitGuard?: () => void;
  /** Prepared caller policy; host floors use the committing transaction's approvals. */
  execPolicy?: CronStreamExecPolicy;
  streamExecApproval?: CronStreamExecApproval;
  /** Creator-session facts refreshed by the worker at each native admission. */
  sessionEntryCurrent?: SessionEntryCurrentCheck;
  /** One-use fresh capture; callback presence means fresh even when it returns undefined. */
  captureRuntimeAuthority?: () => CronRuntimeAuthority | undefined;
};
//#endregion
//#region src/plugin-state/plugin-state-store.types.d.ts
type PluginStateEntry<T> = {
  key: string;
  value: T;
  createdAt: number;
  expiresAt?: number;
};
/** An opaque comparison of one store/key's live value and storage metadata, not ownership. */
type PluginStateObservation<T> = {
  value: T | undefined;
  comparison: string;
};
type PluginStateCompareIntent<T> = {
  operation: "update";
  action: "set";
  value: T;
  ttlMs?: number;
} | {
  operation: "update" | "delete";
  action: "keep";
} | {
  operation: "delete";
  action: "delete";
};
type PluginStateCompareResult<T> = {
  status: "applied" | "unchanged";
} | {
  status: "conflict";
  current: PluginStateObservation<T>;
};
/** Additional same-plugin rows checked atomically with a conditional mutation. */
type PluginStateComparisonCondition = {
  namespace: string;
  key: string;
  comparison: string;
};
type PluginStateActionAuthority = {
  assertCurrent: () => void;
  sessionEntryCurrent?: SessionEntryCurrentCheck | SessionEntriesCurrentCheck;
};
type PluginStateOperationDefinitions = Record<string, {
  input: unknown;
  output: unknown;
}>;
type PluginStateOperationReceipt<T> = {
  value: T;
  /** Refuses after watched state, the captured source, or live authority changes. */
  assertCurrent: () => void;
};
type PluginStateOperation<Operations extends PluginStateOperationDefinitions> = {
  execute<Type extends keyof Operations & string>(command: {
    type: Type;
    input: Operations[Type]["input"];
  }, options: {
    writeStores: readonly number[];
    watchStores?: readonly number[];
    /** Explicit noncreating result when a read-only source does not exist. */
    missingValue?: Operations[Type]["output"];
    /** Read-only shortcut: return this value when an autocommit namespace read is empty. */
    ifEmpty?: {
      store: number;
      value: Operations[Type]["output"];
    };
  }): Promise<PluginStateOperationReceipt<Operations[Type]["output"]>>;
};
type PluginStateKeyRange = {
  keyStartInclusive: string;
  keyEndExclusive: string;
  limit: number;
  order?: "asc" | "desc";
};
type PluginStateMoveEntries = {
  /** Bounded logical source namespace belonging to the same plugin. */
  namespace: string;
  entries: Array<{
    sourceKey: string;
    targetKey: string;
  }>;
};
type PluginStateKeyedStoreBase<T> = {
  /** Loads a plugin-owned static handler into the existing state worker. */
  createOperation?: <Operations extends PluginStateOperationDefinitions>(stores: readonly Pick<PluginStateKeyedStore<unknown>, "lookup" | "entries">[], handler: {
    moduleName: string;
    exportName: string;
  }, authority?: {
    assertCurrent(): void;
    sourceReceipt?: PluginStateOperationReceipt<unknown>;
  }) => PluginStateOperation<Operations>;
  /** Uses the admitted resident view when available; writable fallback may create state. */
  observe?: (key: string) => Promise<PluginStateObservation<T>>;
  /**
   * Compares the observed row and optional same-plugin conditions atomically before applying data.
   * On conflict, reread all preparation inputs; only explicit conflicts may retry.
   */
  compareAndApply?: (key: string, comparison: string, intent: PluginStateCompareIntent<T>, options?: {
    conditions: readonly PluginStateComparisonCondition[];
  }) => Promise<PluginStateCompareResult<T>>;
  register(key: string, value: T, opts?: {
    ttlMs?: number;
    assertCurrent?: () => void;
  }): Promise<void>;
  registerIfAbsent(key: string, value: T, opts?: {
    ttlMs?: number;
  }): Promise<boolean>;
  /**
   * The updater runs synchronously in the transaction; undefined leaves the entry unchanged.
   * @deprecated Use observe and compareAndApply to prepare data outside the worker transaction.
   * This synchronous callback will be removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
   */
  update?: (key: string, updateValue: (current: T | undefined) => T | undefined, opts?: {
    ttlMs?: number;
  }) => Promise<boolean>;
  /**
   * The synchronous predicate and conditional deletion run in one transaction.
   * @deprecated Use observe and compareAndApply, or deleteIfEqual for JSON scalars.
   * This synchronous callback will be removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
   */
  deleteIf?: (key: string, predicate: (current: T) => boolean) => Promise<boolean>;
  /** Atomically deletes a live entry equal to the supplied JSON scalar, without a callback. */
  deleteIfEqual?: (key: string, expected: string | number | boolean | null) => Promise<boolean>;
  lookup(key: string): Promise<T | undefined>;
  /** Positional outcomes for at most 10,000 keys; missing/expired values are undefined. */
  lookupMany?: (keys: readonly string[]) => Promise<Array<Result$1<T | undefined, PluginStateStoreError>>>;
  consume(key: string): Promise<T | undefined>;
  delete(key: string, opts?: {
    assertCurrent?: () => void;
    signal?: AbortSignal;
  }): Promise<boolean>;
  entries(): Promise<PluginStateEntry<T>[]>;
  /** Reads a lexical key range with ordering and limit applied by storage. */
  entriesInKeyRange?: (range: PluginStateKeyRange) => Promise<PluginStateEntry<T>[]>;
  /**
   * Atomically settles at most 10,000 bounded source rows into this retained store.
   * Existing targets win; live expiring sources reject the entire operation.
   */
  moveEntriesFrom?: (source: PluginStateMoveEntries) => Promise<number>;
  /** Counts live stored rows without decoding values; absent on older hosts and adapters. */
  count?: () => Promise<number>;
  clear(): Promise<void>;
};
/** Version 2 is an action-bound, data-only view; legacy stores remain source-compatible. */
type PluginStateKeyedStore<T, Version extends 1 | 2 = 1> = Version extends 2 ? Required<Omit<PluginStateKeyedStoreBase<T>, "update" | "deleteIf" | "createOperation">> & Pick<PluginStateKeyedStoreBase<T>, "createOperation"> : PluginStateKeyedStoreBase<T> & {
  /** Bind current action authority through read completion and final write admission. */
  withCurrent?: (authority: PluginStateActionAuthority) => PluginStateKeyedStore<T, 2>;
};
/**
 * Synchronous plugin-state compatibility contract.
 * @deprecated Use PluginStateKeyedStore<T, 2> from api.runtime.state.openKeyedStoreV2
 * and await its operations. This synchronous API will be removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
 */
type PluginStateSyncKeyedStore<T> = {
  /** @deprecated Await PluginStateKeyedStore.register; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  register(key: string, value: T, opts?: {
    ttlMs?: number;
  }): void;
  /** @deprecated Await PluginStateKeyedStore.registerIfAbsent; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  registerIfAbsent(key: string, value: T, opts?: {
    ttlMs?: number;
  }): boolean;
  /**
   * Expiry options are consumed after the synchronous updater returns.
   * @deprecated Use observe and compareAndApply; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
   */
  update?: (key: string, updateValue: (current: T | undefined) => T | undefined, opts?: {
    ttlMs?: number;
  }) => boolean;
  /** @deprecated Use observe and compareAndApply; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  deleteIf?: (key: string, predicate: (current: T) => boolean) => boolean;
  /** @deprecated Await PluginStateKeyedStore.lookup; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  lookup(key: string): T | undefined;
  /**
   * Positional outcomes for at most 10,000 keys; missing/expired values are undefined.
   * @deprecated Await PluginStateKeyedStore.lookupMany; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
   */
  lookupMany?: (keys: readonly string[]) => Array<Result$1<T | undefined, PluginStateStoreError>>;
  /** @deprecated Await PluginStateKeyedStore.consume; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  consume(key: string): T | undefined;
  /** @deprecated Await PluginStateKeyedStore.delete; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  delete(key: string): boolean;
  /** @deprecated Await PluginStateKeyedStore.entries; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  entries(): PluginStateEntry<T>[];
  /**
   * Counts live stored rows without decoding values; absent on older hosts and adapters.
   * @deprecated Await PluginStateKeyedStore.count; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31.
   */
  count?: () => number;
  /** @deprecated Await PluginStateKeyedStore.clear; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */
  clear(): void;
};
/** Options for opening a keyed plugin-state namespace. */
type PluginStateOverflowPolicy = "evict-oldest" | "reject-new";
/** Published bounded-store options; also used by sync stores, imports, and journals. */
type OpenKeyedStoreOptions = {
  namespace: string;
  maxEntries: number;
  retention?: "bounded";
  overflowPolicy?: PluginStateOverflowPolicy;
  defaultTtlMs?: number;
  env?: NodeJS.ProcessEnv;
};
/** Retained stores are available only through asynchronous keyed-store openers. */
type OpenRetainedKeyedStoreOptions = {
  namespace: string;
  retention: "retained";
  maxEntries?: never;
  overflowPolicy?: never;
  defaultTtlMs?: never;
  env?: NodeJS.ProcessEnv;
};
type OpenAsyncKeyedStoreOptions = OpenKeyedStoreOptions | OpenRetainedKeyedStoreOptions;
//#endregion
//#region src/state/session-repository-workspaces.types.d.ts
type SessionRepositoryWorkspaceRecord = {
  workspaceId: string;
  agentId: string;
  sessionKey: string;
  url: string;
  requestedRef: string | null;
  runSetupScript: boolean;
  baseCommit: string | null;
  baseManifestHash: string | null;
  branch: string;
  checkpointRef: string | null;
  manifestHash: string | null;
  revision: number;
  createdAtMs: number;
  updatedAtMs: number;
};
//#endregion
//#region src/state/github-publication-source.types.d.ts
type GitHubPublicationSourceSelector = {
  agentId: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision: string | null;
  profileId?: string;
  aliasBindingIds?: readonly string[];
  personalOwnerProfileId?: string;
  worktreeId?: string;
  repositoryWorkspaceId?: string;
  repositoryBranch?: string;
};
//#endregion
//#region src/infra/sqlite-maintenance-integrity.d.ts
type SqliteIntegrityCheckOptions = {
  check?: "quick" | "full";
  /** Tables rewritten or re-indexed by the migration; absent tables may be created by it. */
  tables?: readonly string[];
  /**
   * Owned FTS5 definitions whose inverted indexes are derived data. When these
   * are the only findings, the check passes: a SQLite tokenizer change makes a
   * healthy index report "malformed", and the runtime that next admits the
   * database rebuilds it.
   */
  ftsSchemas?: readonly string[];
};
//#endregion
//#region src/infra/sqlite-integrity.d.ts
type SqliteIntegrityCheckTiming = {
  syncElapsedMs?: number;
  workerCheckElapsedMs?: number;
  workerLifetimeElapsedMs?: number;
};
type SqliteIntegrityCheck = SqliteIntegrityCheckOptions & {
  database: DatabaseSync;
  databaseLabel: string;
  timing?: SqliteIntegrityCheckTiming;
};
//#endregion
//#region src/state/openclaw-agent-db-resources.d.ts
type OpenClawAgentDatabaseAsyncResource = {
  agentId: string;
  path: string;
  revoke: () => void;
  close: () => Promise<void>;
  /** A native executor retains its database lease until dependent readers and publications settle. */
  retireAfterResources?: true;
};
type OpenClawAgentDatabaseReadCandidateResource = Omit<OpenClawAgentDatabaseAsyncResource, "agentId"> & {
  scope?: "sibling-family";
};
//#endregion
//#region src/infra/database-engine/physical-facts-contract.d.ts
type PostgresCapabilities = {
  serverMajor: number;
  serverEncoding: "UTF8";
  clientEncoding: "UTF8";
};
type PostgresPhysicalFacts = {
  engine: "postgres";
  admissionId: string;
  store: string;
  namespace: string;
  storeId: string;
  version: number;
  capabilities: PostgresCapabilities;
  catalog: readonly PostgresCatalogFact[];
};
//#endregion
//#region src/infra/sqlite-native-observer.d.ts
declare module "node:sqlite" {
  interface StatementSync {
    /** Node 26.8+ supports finalization; older supported runtimes omit this method. */
    close?(): void;
    [Symbol.dispose]?(): void;
  }
}
//#endregion
//#region src/infra/sqlite-schema-scope.d.ts
type SqliteSchemaFacts = {
  readonly admissionId: string;
  readonly revision: number;
  readonly userVersion: number;
  readonly textEncoding: string;
  readonly schemaVersion: number;
  readonly tables: ReadonlySet<string>;
  readonly views: ReadonlySet<string>;
  readonly tableSql: ReadonlyMap<string, string | null>;
  readonly indexes: ReadonlySet<string>;
  readonly indexDefinitions: ReadonlyMap<string, {
    table: string;
    sql: string | null;
  }>;
  readonly triggers: ReadonlyMap<string, {
    table: string;
    sql: string | null;
  }>;
};
//#endregion
//#region src/state/openclaw-agent-db-validation-facts.d.ts
type OpenClawAgentDatabaseValidation = {
  agentId: string;
  identity: string;
  birthtime: string;
  /** Shared-buffer wrappers change across worker transfers; this identifies the proof instance. */
  receiptId: string;
  /** Preserve the full-check age when a worker borrows proof after host eviction. */
  integrityVerifiedAt?: number;
  /** Shared with admitted workers so owner invalidation revokes borrowed proof. */
  valid: SharedArrayBuffer;
  /** First full canonical proof; subsequent changes remain visible through the pending table. */
  canonicalReady: SharedArrayBuffer;
  /** Canonical admission, separately revoked by local DDL without discarding integrity proof. */
  schema?: ({
    facts: SqliteSchemaFacts;
    postgres?: never;
  } | {
    facts?: never;
    postgres: PostgresPhysicalFacts;
  }) & {
    valid: SharedArrayBuffer;
  };
};
//#endregion
//#region src/state/openclaw-agent-db-lease.d.ts
type OpenClawAgentIntegrityVerificationReceiver = (canReuseRuntimeIntegrity: boolean, invalidated: boolean, because?: string, liveOwnerProvenance?: string) => void;
type OpenClawAgentDatabaseWorkerLeaseReceipt = ReturnType<typeof readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim>;
/** Preparation grants no access; claim repeats admission on the captured shared owner. */
declare function prepareOpenClawAgentDatabaseWorkerLease(params: {
  agentId: string;
  path: string;
  env?: NodeJS.ProcessEnv;
}, sharedDatabase: OpenClawStateDatabase, leaseId: string): {
  receipt: OpenClawAgentDatabaseWorkerLeaseReceipt;
  provenance: string | null;
  validation?: OpenClawAgentDatabaseValidation;
  integrityRevoked?: boolean;
  startupRepair?: (check: SqliteIntegrityCheck, error: unknown, assertCurrent: () => void) => boolean;
  claim(onVerification?: OpenClawAgentIntegrityVerificationReceiver): string;
};
/** Capture the exact admitted claim so its parent can finish cleanup after native Worker exit. */
declare function readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim(leaseId: string, params: {
  agentId: string;
  path: string;
  env?: NodeJS.ProcessEnv;
}): {
  leaseId: string;
  agentId: string;
  path: string;
  ownerPid: number;
  ownerStartTime: number | null;
  sharedStatePath: string;
  sharedStateIdentity: string;
};
//#endregion
//#region src/agents/core-tool-facts.d.ts
type OpenClawCodingToolConstructionPlan = {
  includeBaseCodingTools: boolean;
  includeShellTools: boolean;
  includeChannelTools: boolean;
  includeOpenClawTools: boolean;
  includePluginTools: boolean;
};
//#endregion
//#region src/agents/tool-policy-shared.d.ts
declare function expandToolGroups(list?: string[]): string[];
//#endregion
//#region src/agents/workspace-state-store.worker-contract.d.ts
type WorkspaceStateGuard = {
  /** Host lifecycle and filesystem authority only; never reads SQLite. */
  assertHost?: () => void;
  recoveryHoldPredicate?: AgentDeletionRecoveryHoldPredicate;
  /** Released SDK compatibility: before worker dispatch or host file mutation, never a grant. */
  beforeLegacyApply?: () => void;
};
//#endregion
//#region src/plugins/plugin-command-dispatch-contract.d.ts
/** Lightweight reply-option contract for prepared plugin command ownership. */
declare const PLUGIN_COMMAND_DISPATCH: unique symbol;
type PluginCommandReplyOptions = Readonly<{
  [PLUGIN_COMMAND_DISPATCH]?: Readonly<{
    kind: "plugin" | "non-plugin";
  }>;
}>;
//#endregion
//#region src/gateway/worker-environments/placement-authorization.d.ts
type WorkerPlacementAuthorization = (() => void) & {
  assertWorkerGrant?: () => void;
  assertWorkerLifetime?: () => void;
};
//#endregion
//#region src/realtime-transcription/provider-types.d.ts
type RealtimeTranscriptionProviderId = string;
type RealtimeTranscriptionProviderConfig = Record<string, unknown>;
type RealtimeTranscriptionProviderResolveConfigContext = {
  cfg: OpenClawConfig;
  rawConfig: RealtimeTranscriptionProviderConfig;
};
type RealtimeTranscriptionProviderConfiguredContext = {
  cfg?: OpenClawConfig;
  providerConfig: RealtimeTranscriptionProviderConfig;
  /** Count fallback credentials only for an explicitly named provider, never automatic selection. */
  selectedExplicitly?: boolean;
};
/** 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<void>;
  sendAudio(audio: Buffer): void;
  close(): void;
  isConnected(): boolean;
};
//#endregion
//#region src/talk/audio-output-port.d.ts
/** A call-bound mono PCM16/24kHz sink. Transfer port; share state, never transfer it.
 * The first Int32 is a close fence: zero permits audio, one permanently revokes it.
 * The receiver checks it before playback and acknowledges each accepted audio message.
 */
type RealtimeVoiceAudioOutputPort = {
  port: MessagePort;
  state: SharedArrayBuffer;
};
//#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;
};
type RealtimeVoiceTool = {
  type: "function";
  name: string;
  description: string;
  parameters: {
    type: "object";
    properties: Record<string, unknown>;
    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 RealtimeVoiceCloseDisposition = "abort" | "detach";
type RealtimeVoiceCloseOptions = {
  /** Whether closing the transport also cancels work already accepted by the host. */
  disposition?: RealtimeVoiceCloseDisposition;
};
type RealtimeVoiceBridgeEvent = {
  direction: "client" | "server";
  type: string;
  detail?: string;
  itemId?: string;
  responseId?: string;
};
type RealtimeVoiceResponseError = {
  code?: string;
  message?: string;
  type?: string;
};
type RealtimeVoiceResponseOutcomeBase = {
  responseId?: string;
};
type RealtimeVoiceResponseOutcome = (RealtimeVoiceResponseOutcomeBase & {
  status: "completed";
}) | (RealtimeVoiceResponseOutcomeBase & {
  status: "cancelled";
  reason?: string;
}) | (RealtimeVoiceResponseOutcomeBase & {
  status: "failed" | "incomplete";
  reason?: string;
  error?: RealtimeVoiceResponseError;
  message: string;
});
type RealtimeVoiceAudioClearReason = "barge-in";
type RealtimeVoiceAudioChunkMetadata = {
  itemId: string;
};
type RealtimeVoicePlaybackItem = {
  itemId: string;
  audioEndMs: number;
};
type RealtimeVoiceBridgeCallbacks = {
  onAudio: (audio: Buffer, metadata?: RealtimeVoiceAudioChunkMetadata) => void;
  /** Retained native items in playback order; queued items have zero consumed duration.
   * An empty snapshot is authoritative. Omit when the transport cannot measure playback.
   */
  getPlaybackState?: () => readonly RealtimeVoicePlaybackItem[];
  onClearAudio: (reason?: RealtimeVoiceAudioClearReason) => void;
  /** Scoped acknowledgments are valid only for the provider connection that emitted the mark. */
  onMark?: (markName: string, acknowledge?: () => void) => void;
  /** Snapshot metadata replaces provisional text; omission retains incremental deltas. */
  onTranscript?: (role: RealtimeVoiceRole, text: string, isFinal: boolean, metadata?: {
    textMode: "snapshot";
  }) => void;
  /** Synchronously admits native control; only consult permits task fallthrough. Respond is call-bound. */
  handleDelegationInput?: (text: string, respond: (message: string) => void) => "control" | "consult";
  /** Diagnostic observation; returning from this callback cannot veto an event. */
  onEvent?: (event: RealtimeVoiceBridgeEvent) => void;
  onResponseDone?: (outcome: RealtimeVoiceResponseOutcome) => void;
  onToolCall?: (event: RealtimeVoiceToolCallEvent) => void;
  onReady?: () => void;
  onError?: (error: Error) => void;
  onClose?: (reason: RealtimeVoiceCloseReason) => void;
};
type RealtimeVoiceProviderConfig = Record<string, unknown>;
type RealtimeVoiceProviderCapabilities = {
  transports: TalkTransport[];
  inputAudioFormats: RealtimeVoiceAudioFormat[];
  outputAudioFormats: RealtimeVoiceAudioFormat[];
  supportsBrowserSession?: boolean;
  supportsBargeIn?: boolean;
  /** True when the provider owns interruption from incoming audio. */
  handlesInputAudioBargeIn?: boolean;
  supportsToolCalls?: boolean;
  /** True when user transcripts are reliable enough to gate responses on a leading wake name. */
  supportsActivationNameGating?: boolean;
  supportsVideoFrames?: boolean;
  supportsSessionResumption?: boolean;
};
type RealtimeVoiceProviderResolveConfigContext = {
  cfg: OpenClawConfig;
  rawConfig: RealtimeVoiceProviderConfig;
  /** Host-selected agent scope for account-aware defaults. */
  agentId?: string;
  /** Runtime surface whose defaults are being resolved; omission retains bridge behavior. */
  surface?: "browser-session" | "gateway-relay" | "bridge";
  /** False when the host needs to control when audio input receives a response. */
  autoRespondToAudio?: boolean;
  /** Session requirements used to choose a compatible default model. */
  requiredCapabilities?: Pick<RealtimeVoiceProviderCapabilities, "supportsVideoFrames">;
};
type RealtimeVoiceProviderConfiguredContext = {
  cfg?: OpenClawConfig;
  /** Host-selected agent scope for provider auth readiness. */
  agentId?: string;
  providerConfig: RealtimeVoiceProviderConfig;
};
type RealtimeVoiceAgentConsultRunner = (params: {
  prompt: string;
  signal?: AbortSignal;
}) => Promise<{
  text: string;
}>;
type RealtimeVoiceBridgeCreateRequest = RealtimeVoiceBridgeCallbacks & {
  cfg?: OpenClawConfig;
  /** Host-selected agent scope for provider auth and agent-owned bridge state. */
  agentId?: string;
  providerConfig: RealtimeVoiceProviderConfig;
  audioFormat?: RealtimeVoiceAudioFormat;
  instructions?: string;
  language?: string;
  autoRespondToAudio?: boolean;
  interruptResponseOnInputAudio?: boolean;
  tools?: RealtimeVoiceTool[];
  /** Host-injected agent delegation runner for provider-owned realtime control channels. */
  runAgentConsult?: RealtimeVoiceAgentConsultRunner;
};
type RealtimeVoiceBrowserSessionCreateRequest = {
  cfg?: OpenClawConfig;
  providerConfig: RealtimeVoiceProviderConfig;
  instructions?: string;
  tools?: RealtimeVoiceTool[];
  model?: string;
  voice?: string;
  vadThreshold?: number;
  silenceDurationMs?: number;
  prefixPaddingMs?: number;
  reasoningEffort?: string;
  /** Host-injected agent delegation runner for provider-owned realtime control channels. */
  runAgentConsult?: RealtimeVoiceAgentConsultRunner;
} & ({
  clientControl?: undefined;
  gatewayControl?: RealtimeVoiceGatewayControl;
} | {
  /** Explicit ownership requires command binding; lifecycle callbacks alone do not select it. */
  clientControl: {
    owner: "gateway";
  };
  gatewayControl: RealtimeVoiceGatewayControl & Required<Pick<RealtimeVoiceGatewayControl, "bindControl">>;
});
/** Narrow host/plugin seam for Gateway-owned control of a client-owned media session. */
type RealtimeVoiceGatewayControl = Omit<RealtimeVoiceBridgeCallbacks, "onAudio" | "onClearAudio" | "onMark" | "getPlaybackState"> & {
  /** Bind only supported sideband commands; client-owned media needs no audio bridge. */
  bindControl?: (control: Partial<Pick<RealtimeVoiceBridge, "submitToolResult" | "sendUserMessage">>) => void;
  /** @deprecated Stable 2026.8.1 SDK contract; remove only with a versioned SDK break. */
  bindBridge: (bridge: RealtimeVoiceBridge) => void;
};
/** Providers return transport details; the Gateway attaches client ownership fields. */
type RealtimeVoiceBrowserSession = SchemaContract<(Omit<Extract<TalkClientCreateResult, {
  transport: "webrtc";
}>, "voiceSessionId" | "clientControl"> & {
  offerResponseMaxBytes?: number;
}) | Omit<Extract<TalkClientCreateResult, {
  transport: "provider-websocket";
}>, "voiceSessionId"> | Omit<Extract<TalkClientCreateResult, {
  transport: "gateway-relay";
}>, "voiceSessionId"> | Omit<Extract<TalkClientCreateResult, {
  transport: "managed-room";
}>, "voiceSessionId">>;
type RealtimeVoiceBridge = {
  /** Bind before connect: continuous PCM and interruption go to this call-bound worker sink,
   * not onAudio/onClearAudio. Transcripts, delegation and lifecycle stay on the host. */
  setAudioOutputPort?(output: RealtimeVoiceAudioOutputPort): void;
  /** Continuous audio has no response boundaries; the provider owns interruption. */
  outputAudioMode?: "response" | "continuous";
  /** Buffers input at its sample rate and supplies silence between microphone writes. */
  pacesInputAudio?: boolean;
  supportsToolResultContinuation?: boolean;
  /** False when the provider cannot accept a tool result without starting a response. */
  supportsToolResultSuppression?: boolean;
  /** Per-session override for provider-confirmed input-audio barge-in handling. */
  handlesInputAudioBargeIn?: boolean;
  connect(): Promise<void>;
  sendAudio(audio: Buffer): void;
  setMediaTimestamp(ts: number): void;
  sendUserMessage?(text: string, options?: {
    toolChoice?: {
      type: "function";
      name: string;
    };
  }): void;
  triggerGreeting?(instructions?: string): void;
  handleBargeIn?(options?: RealtimeVoiceBargeInOptions): void;
  /**
   * Returns void when submission completes synchronously, or a Promise that resolves at the
   * asynchronous completion boundary exposed by the provider and rejects on submission failure.
   */
  submitToolResult(callId: string, result: unknown, options?: RealtimeVoiceToolResultOptions): void | Promise<void>;
  acknowledgeMark(markName?: string): void;
  /** Stops admission immediately; an optional promise completes after final transcripts and cleanup. */
  close(options?: RealtimeVoiceCloseOptions): void | Promise<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/transcripts/provider-types.d.ts
/** Supported source families for transcript providers. */
type TranscriptSourceKind = NonNullable<TranscriptSessionSummary["source"]["kind"]>;
/** Provider-specific locator for a live, recorded, or imported transcript source. */
type TranscriptSourceLocator = SchemaContract<TranscriptSessionSummary["source"]> & {
  [key: string]: string | undefined;
};
/** Speaker/participant identity attached to an utterance. */
type TranscriptParticipant = {
  id?: string;
  label: string;
};
/** One captured or imported transcript utterance. */
type TranscriptUtterance = SchemaContract<Omit<TranscriptUtterance$1, "sequence" | "speakerId" | "speakerLabel">> & {
  sessionId?: string;
  speaker?: TranscriptParticipant;
  metadata?: Record<string, unknown>;
};
/** Durable transcript session metadata. */
type TranscriptSessionDescriptor = SchemaContract<Pick<TranscriptSessionSummary, "sessionId" | "title" | "startedAt" | "stoppedAt">> & {
  source: TranscriptSourceLocator;
  metadata?: Record<string, unknown>;
};
/** Request passed to providers that can start live transcript capture. */
type TranscriptStartRequest = {
  cfg?: OpenClawConfig;
  session: TranscriptSessionDescriptor;
  abortSignal?: AbortSignal;
  startupWaitMs?: number;
  onUtterance: (utterance: TranscriptUtterance) => void | Promise<void>;
  /**
   * `active: false` permanently ends this exact capture subscription, including
   * replacement or detach; transient transport disconnects must not emit it.
   * Deliver final utterances first. Callback payload ids/source are descriptive;
   * consumers retain their admitted session identity and ownership metadata.
   */
  onStatus?: (status: TranscriptSourceStatus) => void | Promise<void>;
};
/** Request to watch whether a live source currently has human participants. */
type TranscriptOccupancyWatchRequest = {
  cfg?: OpenClawConfig;
  source: TranscriptSourceLocator;
  abortSignal?: AbortSignal;
  startupWaitMs?: number;
  /** Emitted on 0 -> >0 humans, and once on subscription if already occupied. */
  onOccupied: () => void;
  /** Emitted on >0 -> 0 humans. Bots never count; callbacks preserve observed order. */
  onEmpty: () => void;
};
type TranscriptOccupancyWatchHandle = {
  stop: () => void | Promise<void>;
};
/**
 * Result from starting a transcript source provider.
 *
 * Providers retain cleanup ownership until they return `ok: true`. A failed or
 * rejected start must release any partial capture before it settles.
 */
type TranscriptsStartResult = {
  ok: true;
  session: TranscriptSessionDescriptor;
} | {
  ok: false;
  error: string;
};
/** Request passed to providers that can stop live transcript capture. */
type TranscriptStopRequest = {
  cfg?: OpenClawConfig;
  sessionId: string;
  source: TranscriptSourceLocator;
  reason?: string;
};
/** Failure does not prove release; only success or a terminal onStatus ends cleanup custody. */
type TranscriptsStopResult = {
  ok: true;
  sessionId: string;
  stoppedAt?: string;
} | {
  ok: false;
  error: string;
};
/** Runtime status reported by transcript source providers. */
type TranscriptSourceStatus = {
  sessionId?: string;
  active: boolean;
  message?: string;
  source?: TranscriptSourceLocator;
};
/** Request passed to providers that import post-hoc transcript text. */
type TranscriptImportRequest = {
  cfg?: OpenClawConfig;
  session: TranscriptSessionDescriptor;
  text: string;
  speakerLabel?: string;
};
/** Trusted caller facts projected by core; never accepted from tool arguments. */
type TranscriptToolCaller = {
  kind: "operator";
  source: "channel-owner" | "local" | "scheduled";
} | {
  kind: "channel";
  channel: string;
  accountId?: string;
  senderId: string;
  groupId?: string;
  groupSpace?: string;
  roleIds: readonly string[];
};
type TranscriptToolAction = "import" | "start" | "status" | "stop" | "summarize" | "list" | "show";
type TranscriptSourceAccessControl = {
  /** Ingress channel whose trusted account owns this provider's account namespace. */
  channelId: string;
  /** Resolve and validate the canonical account before persistence. */
  resolveAccountId: (params: {
    cfg?: OpenClawConfig;
    source: TranscriptSourceLocator;
  }) => Result$1<string | undefined, string>;
  /** Apply the provider's native access policy to the resolved source. */
  authorize: (params: {
    action: TranscriptToolAction;
    caller: TranscriptToolCaller;
    cfg?: OpenClawConfig;
    source: TranscriptSourceLocator;
  }) => Promise<Result$1<void, string>>;
};
/** Provider contract for transcript capture/import integrations. */
type TranscriptSourceProvider$1 = {
  id: string;
  aliases?: readonly string[];
  /** Closed access contract for providers sharing one inbound channel namespace. */
  accessControl?: TranscriptSourceAccessControl;
  name: string;
  sourceKinds: readonly TranscriptSourceKind[];
  start?: (request: TranscriptStartRequest) => Promise<TranscriptsStartResult>;
  watchOccupancy?: (request: TranscriptOccupancyWatchRequest) => Promise<Result$1<TranscriptOccupancyWatchHandle, string>>;
  stop?: (request: TranscriptStopRequest) => Promise<TranscriptsStopResult>;
  status?: (source: TranscriptSourceLocator, cfg?: OpenClawConfig) => Promise<TranscriptSourceStatus[]>;
  importTranscript?: (request: TranscriptImportRequest) => Promise<TranscriptUtterance[]>;
};
//#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<string, unknown>;
/** Provider-owned per-request directive/persona overrides. */
type SpeechProviderOverrides = Record<string, unknown>;
/** Policy controlling which [[tts:*]] directive fields can affect synthesis. */
type SpeechModelOverridePolicy = { [Key in keyof TtsModelOverrideConfig]-?: Exclude<TtsModelOverrideConfig[Key], undefined>; };
/** Parsed directive overrides grouped by provider. */
type TtsDirectiveOverrides = {
  ttsText?: string;
  provider?: SpeechProviderId;
  providerOverrides?: Record<string, SpeechProviderOverrides>;
};
/** 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 = Omit<SpeechSynthesisResult, "audioBuffer"> & {
  audioStream: ReadableStream<Uint8Array>;
  release?: () => Promise<void>;
};
/** Telephony synthesis request for provider output that needs a fixed sample rate. */
type SpeechTelephonySynthesisRequest = Omit<SpeechSynthesisRequest, "target">;
/** 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 = SpeechSynthesisRequest & {
  persona?: ResolvedTtsPersona;
  personaProviderConfig?: SpeechProviderConfig;
};
/** 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;
  /** Core-resolved request timeout after config and provider defaults. */
  timeoutMs?: number;
};
/** Provider hook input for resolving normalized config from raw OpenClaw config. */
type SpeechProviderResolveConfigContext = {
  cfg: OpenClawConfig;
  rawConfig: Record<string, unknown>;
  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<string, unknown>;
  talkProviderConfig: TalkProviderConfig;
  timeoutMs: number;
};
/** Provider hook input for per-call talk-command overrides. */
type SpeechProviderResolveTalkOverridesContext = {
  talkProviderConfig: TalkProviderConfig;
  params: Record<string, unknown>;
};
//#endregion
//#region src/plugins/capability-provider.types.d.ts
type WorkerProfile = Readonly<Record<string, PluginJsonValue>>;
/** Provider-authored picker metadata for one machine class or exact machine type. */
type WorkerMachineOption = Readonly<SchemaContract<WorkerMachineOption$1>>;
/**
 * Provider-owned operating system choices for one configured worker profile.
 * disabledReason explains why a target cannot currently be selected, including a repair hint.
 */
type WorkerOperatingSystem = Readonly<SchemaContract<WorkerOperatingSystem$1>>;
/** SSH endpoint material returned by a worker provider after provisioning. */
type WorkerSshEndpoint = {
  host: string;
  port: number;
  /**
   * Up to 10 ordered unique integer ports (1..65535) after `port`; excludes the primary.
   * Core rotates only for idempotent probes, content-addressed transfers, receipt/lock-guarded
   * artifact installation, convergent managed-worktree mirroring, and tunnel reconnects.
   * Ambiguous unguarded stateful commands fail closed and are not replayed.
   */
  fallbackPorts?: readonly number[];
  user: string;
  /** OpenSSH public host-key line obtained from trusted provisioning output. */
  hostKey: string;
  /** Secret reference only; providers must never return plaintext key material. */
  keyRef: SecretRef;
};
/** Resolved SSH client identity. Providers may return a local path or ephemeral material. */
type WorkerSshIdentity = {
  kind: "path";
  path: string;
} | {
  kind: "material";
  contents: string;
};
/** Durable context supplied when a worker provider resolves the identity it minted. */
type WorkerSshIdentityRequest = {
  /** Optional live invocation guard; core supplies it for identity resolution. */
  assertCurrent?: () => void;
  leaseId: string;
  profile: WorkerProfile;
  keyRef: SecretRef;
};
/** Closed set of applications installed and launchable on a provisioned worker desktop. */
type WorkerDesktopApp = {
  id: "browser";
  executablePath: string;
  /** Fixed provider-owned arguments, passed directly without a shell. */
  args?: string[];
  cdpPort: number;
} | {
  id: "terminal";
  executablePath: string;
  args?: string[];
};
/** Optional interactive desktop endpoint provisioned with the lease (warm-time capability). */
type WorkerDesktopEndpoint = {
  /** Desktop service protocol on the worker loopback; "rfb" is the only phase-1 value. */
  protocol: "rfb";
  /** Loopback port on the worker (e.g. 5900). */
  port: number;
  /** Absolute on-box path to the per-lease password file; read by the owning transport, never persisted as plaintext. */
  passwordFilePath?: string;
  /** Managed desktop account for ARD authentication; its password stays in passwordFilePath. */
  username?: string;
  /** False restricts a native desktop from the provider-wide virtual display resize capability. */
  allowsResize?: boolean;
  /** Closed application metadata advertised by the provider for this desktop. */
  apps?: WorkerDesktopApp[];
};
/** Grant-free identity of the runtime bytes a provider may retain in a prepared image. */
type WorkerNodeRuntimeIdentity = {
  nodeBootstrapSha256: string;
  executionMode: WorkerExecutionMode;
  /** Present only when project preparation retains the independent worker archive. */
  workerBundleSha256?: string;
};
type WorkerNodeBootstrapAccess = {
  /** Core-owned command window for downloading and installing this grant's artifacts. */
  bootstrapTimeoutMs?: number;
  /** Immutable node distribution prepared by the Gateway for this provision operation. */
  nodeBootstrap: {
    url: string;
    token: string;
    sha256: string;
    bytes: number;
    openclawVersion: string;
    enabledPluginIds: readonly string[];
    tlsFingerprint?: string;
    /** Core-owned POSIX prerequisite script, applied only to Linux before invoking Node. */
    linuxToolchainSetup?: string;
    /** Optional npm project lock for this exact archive; failure must retain unlocked installation. */
    installLock?: {
      url: string;
      token: string;
      sha256: string;
      bytes: number;
      tlsFingerprint?: string;
    };
  };
  /** Runtime/enrollment closure, including shutdown; stop this work while preserving its allocation. */
  signal?: AbortSignal;
};
/** Operation-bound immutable artifacts without a node identity or enrollment credential. */
type WorkerNodeRuntimePreparation = WorkerNodeBootstrapAccess & {
  workerBundle: {
    url: string;
    token: string;
    sha256: string;
    bytes: number;
    tlsFingerprint?: string;
    /** Core-owned location within the installed node package, outside dist and enrollment state. */
    packageRelativePath: string;
  };
};
/** Replay-safe node enrollment prepared only after a provider has allocated its machine. */
type WorkerNodeEnrollment = WorkerNodeBootstrapAccess & {
  openclawVersion: string;
  displayName: string;
  waitForDeviceId: () => Promise<string>;
} & ({
  mode: "connect";
  setupCode: string;
  setupId: string;
} | {
  mode: "resume";
  deviceId: string;
});
/** Durable lease identity and endpoint returned by a successful provision operation. */
type WorkerLease = {
  leaseId: string;
  /** The SSH account also owns processes unrelated to this worker lease. */
  sharedHost?: boolean;
  desktop?: WorkerDesktopEndpoint;
} & ({
  ssh: WorkerSshEndpoint;
  node?: never;
} | {
  node: {
    deviceId: string;
  };
  ssh?: never;
});
/** Authoritative inspection result for an already-known worker lease. */
type WorkerLeaseStatus = {
  status: "active";
  /** Explicit provider fact used to reconcile leases persisted before this metadata existed. */
  sharedHost?: boolean;
} | {
  status: "dormant";
} | {
  status: "destroyed";
} | {
  status: "unknown";
};
/** Provision failed after allocation and the provider could not prove cleanup completed. */
declare class WorkerProvisionCleanupError extends AggregateError {
  readonly provisionError: unknown;
  readonly cleanupError: unknown;
  readonly code = "cleanup_indeterminate";
  readonly leaseId: string;
  constructor(leaseId: string, provisionError: unknown, cleanupError: unknown);
}
/** Provision failed after allocation and the provider confirmed cleanup completed. */
declare class WorkerProvisionCleanupCompleteError extends Error {
  readonly provisionError: unknown;
  readonly code = "cleanup_complete";
  readonly leaseId: string;
  constructor(leaseId: string, provisionError: unknown);
}
/** Permanent provider rejection recorded as a terminal worker failure. */
declare class WorkerProviderError extends Error {
  readonly code = "invalid_profile";
  constructor(message: string);
  static cleanupComplete(leaseId: string, provisionError: unknown): WorkerProvisionCleanupCompleteError;
  static isCleanupComplete(error: unknown): error is WorkerProvisionCleanupCompleteError;
  static cleanupIndeterminate(leaseId: string, provisionError: unknown, cleanupError: unknown): WorkerProvisionCleanupError;
  static isCleanupIndeterminate(error: unknown): error is WorkerProvisionCleanupError;
}
type WorkerRecipePreparation = {
  source: "devcontainer" | "script" | "detected" | "none";
  ignoredPropertiesNote?: string;
  note?: string;
  phaseDurationsMs?: {
    onCreate?: number;
    updateContent?: number;
    detectedInstall?: number;
  };
  failure?: {
    reason: string;
    outputTail?: string;
  };
};
/** Cloud-worker lifecycle capability shared by plugin and internal providers. */
type WorkerProvider = {
  id: string;
  /**
   * Nonsecret backend display ID, never a routing or allocation identity.
   * Synchronous local presentation only: no commands, network, or credential reads.
   * Return 1–64 lowercase ASCII letters/digits/hyphens, starting with a letter.
   * Omission, invalid values, and exceptions retain generic provider presentation.
   */
  resolveDisplayId?: (profile: WorkerProfile) => string | undefined;
  /** Safe to request virtual desktop resizing; the RFB server still negotiates support. */
  allowsDesktopResize?: boolean;
  /** Process-stable choices available for this profile; omit the hook to hide machine selection. */
  listMachineOptions?: (profile: WorkerProfile) => Promise<readonly WorkerMachineOption[]>;
  listOperatingSystems?: (profile: WorkerProfile) => Promise<readonly WorkerOperatingSystem[]>;
  /** Omission advertises no placement support; multiple modes use their canonical order. */
  supportedExecutionModes?: readonly [WorkerExecutionMode] | readonly ["worker-turn", "remote-exec"];
  /**
   * Provision before preparing an installation when the lease transport decides whether an
   * installation is needed. Defaults to false so SSH providers retain prepare-before-allocation.
   */
  provisionBeforeInstallation?: boolean;
  /** Provider allocates a node host through the environment-owned enrollment callback. */
  requiresNodeEnrollment?: boolean;
  /** Prepare a pristine project before enrollment so it can be included in a reusable image. */
  supportsProjectPreparation?: (profile: WorkerProfile, machineClass?: string, os?: string) => boolean;
  /** Immutable target resolved before project preparation or allocation. */
  resolvePreparationTarget?: (profile: WorkerProfile, machineClass?: string, os?: string) => {
    machineClass: string;
    platform: string;
    arch?: string;
    /** SHA-256 of provider-owned disk/boot settings, excluding runtime and lease policy. */
    profileKey?: string;
  } | undefined;
  /** Maximum unused ready-worker lifetime, measured from the original session demand. */
  resolvePreparedIdleTimeoutMs?: (profile: WorkerProfile) => number | undefined;
  /** Record successful demand in metadata only; must not allocate, capture, or renew reserves. */
  notePreparedDemand?: (lease: {
    leaseId: string;
    profile: WorkerProfile;
  }, demand: {
    preparationKey: string;
    demandAtMs: number;
  }) => Promise<void>;
  /**
   * Resolve the exact cleanup handle for this operation, even if no machine was created.
   * Must not provision, start, renew, run setup, enroll, or wait for transport readiness.
   * Identity is not existence/readiness proof; destroy still owns teardown confirmation.
   */
  resolveAllocation: (profile: WorkerProfile, operationId: string) => Promise<{
    leaseId: string;
    sharedHost: boolean;
  }>;
  /**
   * Provision or adopt the lease for this operation id.
   * Repeating the same operation id must be idempotent across gateway restarts.
   */
  provision: (profile: WorkerProfile, operationId: string, options?: {
    /** Configured profile id for display; settings and operation id own allocation identity. */
    profileId?: string;
    /** Attempt-scoped display facts; the host rejects reports after provisioning closes. */
    reportStartStatus?: (status: WorkerEnvironmentStartStatus) => void;
    /**
     * Stop this attempt, including on Gateway shutdown; settle active commands before rejecting.
     * Preserve allocations on abort. Explicit cancellation/destroy requests record destruction intent separately.
     */
    signal?: AbortSignal;
    /** Modern hosts supply authority; legacy optionality is source compatibility only. */
    assertCurrent?: () => void;
    executionMode?: WorkerExecutionMode;
    machineClass?: string;
    os?: string;
    nodeRuntimeIdentity?: WorkerNodeRuntimeIdentity;
    /** Upper bound per runtime preparation/enrollment phase, including the node connection wait. */
    nodeBootstrapTimeoutMs?: number;
    prepareNodeRuntime?: () => Promise<WorkerNodeRuntimePreparation>;
    beginNodeEnrollment?: () => Promise<WorkerNodeEnrollment>;
    project?: {
      key: string;
      baseCommit: string;
      label?: string;
      /** Gateway-local checkout root for display and explicit rebuild requests. */
      root?: string;
      preparation?: {
        key: string;
        cacheKey: string;
        purpose: "session" | "reserve";
        demandAtMs: number;
      };
      secretNames?: readonly string[];
      signal: AbortSignal;
      assertCurrent: () => void;
      /** Verify an already enrolled allocation without transferring, running setup, or capturing it. */
      inspectPreparedWorkspace?: (transport: {
        runScript: (script: string, signal: AbortSignal) => Promise<string>;
      }) => Promise<void>;
      /** Bound to this provision attempt; retained callbacks reject after it closes. */
      prepare: (transport: {
        runScript: (script: string, signal: AbortSignal) => Promise<string>;
        /** Render using this provider command's remaining budget before repository code runs. */
        runScriptWithBudget?: (createScript: (timeoutMs: number, setupEnv?: Record<string, string>) => string, signal: AbortSignal) => Promise<string>;
        upload: (localPath: string, remotePath: string, signal: AbortSignal) => Promise<void>;
        /** Persist diagnostics before a declared recipe rejects preparation. */
        recordRecipePreparation?: (value: WorkerRecipePreparation) => Promise<void>;
      }) => Promise<{
        seedKey: string;
        cacheHit: boolean;
        /** New completed setup must enter the reusable image before enrollment. */
        captureRequired?: true;
        /** Detected setup is best effort; this allocation must remain cold on failure. */
        captureSkipped?: string;
        recipePreparation?: WorkerRecipePreparation;
        preparedWorkspace?: {
          preparationKey: string;
          cacheKey: string;
          workspaceDir: string;
          homeDir: string;
          sourceManifestRef: string;
          preparedManifestRef: string;
        };
      }>;
    };
  }) => Promise<WorkerLease>;
  /** Provider-owned transport for repository lifecycle commands on an enrolled lease. */
  runSetupCommand?: (lease: {
    leaseId: string;
    profile: WorkerProfile;
  }, command: {
    createScript: (setupEnv?: Record<string, string>) => string;
    workspaceDir: string;
    homeDir: string;
    timeoutMs: number;
    assertCurrent: () => void;
    signal?: AbortSignal;
  }) => Promise<SpawnResult | undefined>;
  /**
   * Prepare without allocating, renewing, enrolling, or changing a provider resource. The
   * returned operation carries prepared facts; core records allocation intent before calling it.
   * Replay preparation cannot attest that an earlier operation allocated nothing.
   */
  prepareProvision?: (...args: Parameters<WorkerProvider["provision"]>) => Promise<() => Promise<WorkerLease>>;
  /** Maximum core wait for one provision attempt, including provider-owned setup and cleanup. */
  resolveProvisionTimeoutMs?: (profile: WorkerProfile, options?: {
    nodeBootstrapTimeoutMs?: number;
  }) => number;
  /**
   * Throws on transient/indeterminate observation failures. `unknown` means the provider no
   * longer recognizes a usable lease; core fences it and requests destroy. Only `destroyed`
   * proves teardown complete and lets core skip destroy.
   */
  inspect: (lease: {
    leaseId: string;
    profile: WorkerProfile;
    signal?: AbortSignal;
  }) => Promise<WorkerLeaseStatus>;
  /**
   * Resolves provider-owned dynamic identities. When absent, the gateway uses its generic
   * SecretRef resolver; when present, failures are authoritative and never fall back.
   */
  resolveSshIdentity?: (request: WorkerSshIdentityRequest) => Promise<WorkerSshIdentity>;
  renew?: (leaseId: string) => Promise<void>;
  /**
   * Bounded cleanup for configured profiles, including when no leases remain. Core schedules
   * one pass at a time without blocking allocation. Check authority before external effects
   * and after awaits before persistence; settle only after all owned commands have stopped.
   */
  maintain?: (context: {
    profiles: readonly WorkerProfile[];
    signal: AbortSignal;
    assertCurrent: () => void;
  }) => Promise<void>;
  /** Opt in to the cleanup-acceptance notification during session reclaim. */
  supportsCleanupAcceptance?: true;
  /** Idempotent; resolves only after the provider can prove teardown. */
  destroy: (lease: {
    leaseId: string;
    profile: WorkerProfile;
    /** Cancel commands, await their settlement, and reject while teardown remains unconfirmed. */
    signal?: AbortSignal;
    /**
     * Optional notification that cleanup is accepted and no longer needs the session.
     * The host may reclaim the session, but retains this operation until its promise settles.
     * Call only after durable provider acceptance (or a claimed, provider-owned capture).
     * Fulfillment must still prove physical teardown; rejection remains retryable.
     * Providers without this capability ignore the callback and keep blocking reclaim.
     */
    onCleanupAccepted?: () => void;
  }) => Promise<void>;
  /** Maximum core wait for teardown, including provider-owned checkpointing and cleanup. */
  resolveDestroyTimeoutMs?: (profile: WorkerProfile) => number;
};
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<SpeechProviderPreparedSynthesis | undefined>;
  /** @deprecated Use isConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  isConfigured: (ctx: SpeechProviderConfiguredContext) => boolean;
  isConfiguredAsync?: (ctx: SpeechProviderConfiguredContext) => Promise<boolean>;
  synthesize: (req: SpeechSynthesisRequest) => Promise<SpeechSynthesisResult>;
  streamSynthesize?: (req: SpeechSynthesisStreamRequest) => Promise<SpeechSynthesisStreamResult>;
  synthesizeTelephony?: (req: SpeechTelephonySynthesisRequest) => Promise<SpeechTelephonySynthesisResult>;
  listVoices?: (req: SpeechListVoicesRequest) => Promise<SpeechVoiceOption[]>;
};
type RealtimeTranscriptionProviderPlugin = {
  id: RealtimeTranscriptionProviderId;
  label: string;
  aliases?: string[];
  defaultModel?: string;
  models?: readonly string[];
  autoSelectOrder?: number;
  resolveConfig?: (ctx: RealtimeTranscriptionProviderResolveConfigContext) => RealtimeTranscriptionProviderConfig;
  /** @deprecated Use isConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  isConfigured: (ctx: RealtimeTranscriptionProviderConfiguredContext) => boolean;
  isConfiguredAsync?: (ctx: RealtimeTranscriptionProviderConfiguredContext) => Promise<boolean>;
  createSession: (req: RealtimeTranscriptionSessionCreateRequest) => RealtimeTranscriptionSession;
};
type TranscriptSourceProvider = TranscriptSourceProvider$1;
type RealtimeVoiceProviderPlugin = {
  id: RealtimeVoiceProviderId;
  label: string;
  aliases?: string[];
  defaultModel?: string;
  models?: readonly string[];
  /** Known speaker voices for pickers; providers still accept free-form values. */
  voices?: readonly string[];
  autoSelectOrder?: number;
  capabilities?: RealtimeVoiceProviderCapabilities;
  /** @deprecated Use resolveConfigAsync when config resolution needs credentials. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  resolveConfig?: (ctx: RealtimeVoiceProviderResolveConfigContext) => RealtimeVoiceProviderConfig;
  resolveConfigAsync?: (ctx: RealtimeVoiceProviderResolveConfigContext) => Promise<RealtimeVoiceProviderConfig>;
  /** @deprecated Use isConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  isConfigured: (ctx: RealtimeVoiceProviderConfiguredContext) => boolean;
  isConfiguredAsync?: (ctx: RealtimeVoiceProviderConfiguredContext) => Promise<boolean>;
  createBridge: (req: RealtimeVoiceBridgeCreateRequest) => RealtimeVoiceBridge;
  createBrowserSession?: (req: RealtimeVoiceBrowserSessionCreateRequest) => Promise<RealtimeVoiceBrowserSession>;
};
type MediaUnderstandingProviderPlugin = MediaUnderstandingProvider;
type ImageGenerationProviderPlugin = ImageGenerationProvider;
type VideoGenerationProviderPlugin = VideoGenerationProvider;
type MusicGenerationProviderPlugin = MusicGenerationProvider;
//#endregion
//#region src/gateway/worker-environments/workspace-conflicts.d.ts
type WorkerWorkspaceResultConflict = {
  paths: string[];
  stagedResultRef: string;
  totalCount?: number;
};
//#endregion
//#region src/gateway/worker-environments/placement-record.d.ts
type WorkerSessionPlacementIdentity = {
  sessionId: string;
  agentId: string;
  sessionKey: string;
};
type WorkerSessionPlacementChangeSnapshot = WorkerSessionPlacementIdentity & {
  state: SessionPlacementState;
  generation: number;
  updatedAtMs: number;
};
type WorkerPlacementExecutionMode = "worker-turn" | "remote-exec";
type WorkerSessionPlacementDispatchIdentity = WorkerSessionPlacementIdentity & {
  executionMode?: WorkerPlacementExecutionMode;
  expectedPlacement?: Pick<WorkerSessionPlacementRecord, "state" | "generation" | "environmentId" | "activeOwnerEpoch">;
};
type WorkerSessionTurnOwner = {
  kind: "local";
  environmentId?: string;
  ownerEpoch?: number;
} | {
  kind: "worker";
  environmentId: string;
  ownerEpoch: number;
};
type WorkerTurnClaimInput = WorkerSessionPlacementIdentity & {
  owner: WorkerSessionTurnOwner;
  claimId: string;
  runId: string;
};
type WorkerSessionTurnClaim = {
  sessionId: string;
  claimId: string;
  runId: string;
  placementGeneration: number;
  owner: WorkerSessionTurnOwner;
};
type PersistedTurnClaim = {
  claimId: string;
  runId: string;
  generation: number;
} & ({
  owner: "local";
  ownerEpoch: null;
} | {
  owner: "worker";
  ownerEpoch: number;
});
type PersistedLocalTurnClaim = Extract<PersistedTurnClaim, {
  owner: "local";
}>;
type PlacementRecordBase<TurnClaim extends PersistedTurnClaim | null> = WorkerSessionPlacementIdentity & {
  generation: number;
  executionMode: WorkerPlacementExecutionMode;
  turnClaim: TurnClaim;
  createdAtMs: number;
  updatedAtMs: number;
  stateChangedAtMs: number;
  /** Process-local UI projection; deliberately absent from SQLite. */
  workspaceResultConflict?: WorkerWorkspaceResultConflict;
};
type UnclaimedPlacementRecordBase = PlacementRecordBase<null>;
type LocalClaimablePlacementRecordBase = PlacementRecordBase<PersistedLocalTurnClaim | null>;
type EmptyWorkerPlacementMetadata = { [Field in keyof TerminalPlacementMetadata | "recoveryError"]: null; };
type ProvisioningPlacementMetadata = Omit<EmptyWorkerPlacementMetadata, "environmentId"> & {
  environmentId: string | null;
};
type SyncingPlacementMetadata = Omit<EmptyWorkerPlacementMetadata, "environmentId" | "workerBundleHash"> & {
  environmentId: string;
  workerBundleHash: string;
};
type StartingPlacementMetadata = Omit<SyncingPlacementMetadata, "workspaceBaseManifestRef" | "remoteWorkspaceDir"> & {
  workspaceBaseManifestRef: string;
  remoteWorkspaceDir: string;
};
type OwnedWorkerPlacementMetadata = Omit<StartingPlacementMetadata, "activeOwnerEpoch" | "lastTranscriptAckCursor" | "lastLiveEventAckCursor"> & {
  activeOwnerEpoch: number;
  lastTranscriptAckCursor: number | null;
  lastLiveEventAckCursor: number | null;
};
type TerminalPlacementMetadata = {
  environmentId: string | null;
  activeOwnerEpoch: number | null;
  workspaceBaseManifestRef: string | null;
  remoteWorkspaceDir: string | null;
  workerBundleHash: string | null;
  lastTranscriptAckCursor: number | null;
  lastLiveEventAckCursor: number | null;
  terminalReason: string | null;
  terminalAtMs: number | null;
};
type PlacementRecordsByState = {
  local: LocalClaimablePlacementRecordBase & EmptyWorkerPlacementMetadata;
  requested: LocalClaimablePlacementRecordBase & EmptyWorkerPlacementMetadata;
  provisioning: UnclaimedPlacementRecordBase & ProvisioningPlacementMetadata;
  syncing: UnclaimedPlacementRecordBase & SyncingPlacementMetadata;
  starting: UnclaimedPlacementRecordBase & StartingPlacementMetadata;
  active: PlacementRecordBase<PersistedTurnClaim | null> & OwnedWorkerPlacementMetadata;
  draining: PlacementRecordBase<PersistedTurnClaim | null> & OwnedWorkerPlacementMetadata;
  reconciling: UnclaimedPlacementRecordBase & OwnedWorkerPlacementMetadata;
  reclaimed: UnclaimedPlacementRecordBase & Omit<OwnedWorkerPlacementMetadata, "terminalReason" | "terminalAtMs"> & TerminalPlacementMetadata;
  failed: LocalClaimablePlacementRecordBase & TerminalPlacementMetadata & {
    recoveryError: string;
  };
};
type WorkerSessionPlacementRecord = { [State in SessionPlacementState]: PlacementRecordsByState[State] & {
  state: State;
}; }[SessionPlacementState];
type WorkerSessionPlacementTransitionPatch = Partial<Omit<TerminalPlacementMetadata, "terminalAtMs"> & {
  recoveryError: string | null;
}>;
//#endregion
//#region src/gateway/worker-environments/state.d.ts
type WorkerEnvironmentUnleasedState = "requested" | "provisioning" | "failed";
type WorkerEnvironmentLeasedState = Exclude<WorkerEnvironmentState, WorkerEnvironmentUnleasedState>;
//#endregion
//#region src/gateway/worker-environments/environment-record.d.ts
type WorkerEnvironmentBootstrapReceipt = WorkerAdmissionHandshake & {
  /** Provenance only; admission authority remains the exact stored build identity. */
  installKind?: "bundle" | "local";
};
type WorkerEnvironmentTeardownTerminalState = "destroyed" | "failed";
type WorkerEnvironmentPreparation = {
  purpose: "reserve" | "build";
  key: string;
  demandAtMs: number;
  expiresAtMs: number;
  consumedAtMs: number | null;
};
type WorkerEnvironmentPreparationIntent = Omit<WorkerEnvironmentPreparation, "consumedAtMs">;
type PreparedEnvironmentPlacementBinding = WorkerSessionPlacementDispatchIdentity & {
  generation: number;
  preparationKey: string;
  assertCurrent: () => void;
};
type PreparedEnvironmentSelection = WorkerSessionPlacementDispatchIdentity & {
  expectedGeneration: number;
  environmentId: string;
  ownerEpoch: number;
  providerId: string;
  profileId: string;
  preparationKey: string;
  nodeDeviceId: string;
  leaseId: string;
  bundleHash: string;
  assertCurrent: WorkerPlacementAuthorization;
};
type RecordIdentity = {
  environmentId: string;
  providerId: string;
  profileId: string;
};
type RecordBase = RecordIdentity & {
  profileSnapshot: WorkerProfile;
  preparation: WorkerEnvironmentPreparation | null;
  provisionOperationId: string;
  nodeSetupId: string | null;
  nodeDeviceId: string | null;
  sharedHost: boolean | null;
  desktop: WorkerDesktopEndpoint | null;
  bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
  ownerEpoch: number;
  teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
  attachedSessionIds: string[];
  lastError: string | null;
  createdAtMs: number;
  updatedAtMs: number;
  stateChangedAtMs: number;
  lastActivatedAtMs: number | null;
  idleSinceAtMs: number | null;
  destroyRequestedAtMs: number | null;
};
type UnleasedRecord = {
  state: WorkerEnvironmentUnleasedState;
  leaseId: null;
  sshEndpoint: null;
};
type LeasedRecord = {
  state: WorkerEnvironmentLeasedState;
  leaseId: string;
  sshEndpoint: WorkerSshEndpoint | null;
};
type WorkerEnvironmentRecord = RecordBase & (UnleasedRecord | LeasedRecord);
type WorkerEnvironmentIntentInput = RecordIdentity & {
  preparation?: WorkerEnvironmentPreparationIntent;
  profileSnapshot: WorkerProfile;
  provisionOperationId: string;
};
//#endregion
//#region src/gateway/worker-environments/placement-move-intent.types.d.ts
type WorkerPlacementMoveTarget = SessionMoveTarget;
type WorkerPlacementMoveSource = {
  generation: number;
  environmentId: string;
  ownerEpoch: number;
};
type WorkerPlacementMoveIntent = {
  operationId: string;
  sessionId: string;
  source: WorkerPlacementMoveSource;
  target: WorkerPlacementMoveTarget;
  abandonSource: boolean;
  lastError: string | null;
  createdAtMs: number;
  updatedAtMs: number;
};
//#endregion
//#region src/gateway/worker-environments/placement-workspace-result.types.d.ts
type WorkerWorkspacePendingResult = {
  sessionId: string;
  environmentId: string;
  ownerEpoch: number;
  placementGeneration: number;
  claimId: string;
  runId: string;
  gatewayInstanceId: string;
  recoveryRequestedAtMs: number | null;
  workspaceAcceptedAtMs: number | null;
  stagedResultRef: string | null;
  repositoryWorkspaceId?: string;
};
//#endregion
//#region src/gateway/worker-environments/placement-read-projection.types.d.ts
type WorkerEnvironmentPlacementFacts = Pick<WorkerEnvironmentRecord, "environmentId" | "providerId" | "profileId" | "profileSnapshot" | "state" | "leaseId" | "ownerEpoch" | "nodeDeviceId" | "attachedSessionIds"> & {
  inference?: "worker";
};
type WorkerSessionPlacementProjection = {
  readonly placements: ReadonlyMap<string, Readonly<WorkerSessionPlacementRecord>>;
  readonly moves: ReadonlyMap<string, WorkerPlacementMoveIntent>;
  readonly pendingResults: ReadonlyMap<string, WorkerWorkspacePendingResult>;
  readonly workspaceJournalOwnerSessionIds: ReadonlySet<string>;
  readonly workspaceResultReconcilingSessionIds: ReadonlySet<string>;
  readonly workspaceRecoveryPendingSessionIds: ReadonlySet<string>;
  readonly environments: ReadonlyMap<string, WorkerEnvironmentPlacementFacts>;
};
type WorkerPlacementRecoveryCandidate = {
  sessionId: string;
  environmentId: string | null;
  state?: SessionPlacementState;
  moveSourceEnvironmentId?: string;
};
//#endregion
//#region src/gateway/worker-environments/placement-session-tool-operations.receipt.d.ts
declare const OperationStartSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"execute">;
  operationSeed: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"completed">;
  resultJson: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"in-progress">;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"unknown">;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"capacity">;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"conflict">;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"unauthorized">;
}>]>;
type WorkerSessionToolOperationStart = Static<typeof OperationStartSchema>;
//#endregion
//#region src/gateway/worker-environments/placement-drain.d.ts
declare function drainWorkerSessionPlacement(db: EngineConnection, input: {
  sessionId: string;
  environmentId: string;
  ownerEpoch: number;
  expectedGeneration: number;
  expectedUpdatedAtMs?: number;
  workspaceBaseManifestRef?: string;
  allowPendingWorkspaceResult?: boolean;
  requireUnclaimed?: true;
  expectedTurnClaim?: WorkerSessionTurnClaim;
}, nowMs: number): WorkerSessionPlacementRecord;
//#endregion
//#region src/gateway/worker-environments/placement-turn-claims.types.d.ts
type PlacementTurnClaimCurrentCheck = {
  sessionEntry?: SessionEntryCurrentCheck;
  assertPlacementCurrent(placement: WorkerSessionPlacementRecord | undefined, move?: WorkerPlacementMoveIntent | null): void;
};
type PlacementAckCursorInput = {
  claim: WorkerSessionTurnClaim;
  transcript?: number;
  liveEvent?: number;
};
//#endregion
//#region src/gateway/worker-environments/workspace-manifest.d.ts
type WorkerWorkspaceManifestEntry = {
  path: string;
  type: "file";
  mode: number;
  size: number;
  sha256: string;
} | {
  path: string;
  type: "symlink";
  mode: number;
  target: string;
};
type WorkerWorkspaceManifest = {
  version: 1;
  baseCommit: string | null;
  entries: WorkerWorkspaceManifestEntry[];
  directories?: string[];
  /** Local guest build-cache policy and trusted inputs; never serialized into receipt bytes. */
  buildCacheInputs?: string[];
};
type WorkerWorkspaceReconciliationJournal = {
  version: 1;
  temporaryNonce: string;
  baseManifestRef: string;
  currentManifestRef: string;
  baseEntries: WorkerWorkspaceManifestEntry[];
  appliedEntries: WorkerWorkspaceManifestEntry[];
  baseDirectories?: string[];
  appliedDirectories?: string[];
  appliedManifestRef?: string;
  baseTree: string;
  basePackSha256: string;
  basePack: Uint8Array;
};
type WorkerWorkspaceReconciliationJournalAdapter = {
  load(): Promise<WorkerWorkspaceReconciliationJournal | undefined>;
  begin(journal: WorkerWorkspaceReconciliationJournal): Promise<void>;
  commit(manifestRef: string): Promise<void>;
  abort(): Promise<void>;
};
//#endregion
//#region src/gateway/worker-environments/placement-workspace-journal.types.d.ts
type WorkerWorkspaceJournalOwner = {
  sessionId: string;
  environmentId: string;
  ownerEpoch: number;
  placementGeneration: number;
};
//#endregion
//#region src/sessions/session-row-changes.d.ts
type SessionRowFacts = {
  kind: "unchanged";
} | {
  kind: "replacement";
  membership: SessionMembershipFact;
  /** Missing policy coverage must not preserve an already prepared send. */
  communicationBinding?: string;
  lifecycleChanged?: boolean;
} | {
  kind: "acp";
  sessionId: string | undefined;
  lifecycleRevision: string | null;
  sessionStartedAt?: number;
  acp: SessionAcpMeta | null;
} | {
  kind: "entry";
  previousSessionId: string | undefined;
  sessionId: string;
  category: string | null;
  clearMembers: boolean;
  /** Exact peer-policy/lifecycle projection; absent publications require a fresh read. */
  communicationBinding?: string;
  lifecycleChanged?: boolean;
} | {
  kind: "member";
  sessionId: string;
  identityId: string;
  present: boolean;
} | {
  kind: "owner";
  sessionId: string;
  lifecycleRevision: string | null;
  owner: SessionEntry["owner"];
} | {
  kind: "participants";
  /** Participant history belongs to the logical key, across transcript replacements. */
  projection?: Pick<SessionEntry, "participants" | "participantCount">;
  /** Count-only contributions leave display identity and ordering unchanged. */
  projectionChanged?: false;
  records?: readonly SessionParticipantRecord[];
  actorVersion?: {
    epoch: string;
    sequence: number;
  };
} | {
  kind: "category";
  sessionId: string;
  category: string | null;
} | {
  kind: "removed";
  transcriptInventoryUnchanged?: true;
};
type SessionRowChange = {
  sessionKey: string;
  agentId?: string;
  storePath?: string;
  scope?: "automation" | "runtime" | "session-entry" | "acp" | "transcript";
  /** Category uncertainty cannot change identity or lineage; other storage outcomes can. */
  factsInvalidated?: true | "category";
  /** Omission is a metadata notification; storage owners publish their changed facts. */
  facts?: SessionRowFacts;
} | {
  all: true;
  scope: string | {
    agentId?: string;
    storePath?: string;
    topology?: true;
  };
  /** Run owners without a logical key retain the identity for indexed row invalidation. */
  runtimeSession?: {
    sessionId: string;
    agentId?: string;
  };
  factsInvalidated?: true;
};
//#endregion
//#region src/gateway/worker-environments/placement-retirement.d.ts
declare const RETIRABLE_PLACEMENT_STATES: readonly ["local", "requested", "reclaimed", "failed"];
type WorkerSessionPlacementRetirement = {
  sessionId: string;
  expectedState: (typeof RETIRABLE_PLACEMENT_STATES)[number];
  expectedGeneration: number;
};
//#endregion
//#region src/gateway/worker-environments/placement-turn-authority.types.d.ts
type PlacementTurnClaimAuthority = {
  readonly claim: WorkerSessionTurnClaim;
  readonly identity: Readonly<{
    agentId: string;
    sessionKey: string;
  }>;
  isCurrent: () => boolean;
  onRevoked: (listener: () => void) => () => void;
  release: () => void;
};
//#endregion
//#region src/gateway/worker-environments/placement-store.d.ts
declare function createWorkerSessionPlacementStore(options?: {
  database?: OpenClawStateDatabase;
  now?: () => number;
}): {
  clearLocalTurnClaimsAfterRestartAsync(): Promise<number>;
  startDispatch(input: WorkerSessionPlacementDispatchIdentity, guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<WorkerSessionPlacementRecord>;
  beginPlacementMove(input: Parameters<(input: {
    sessionId: string;
    source: WorkerPlacementMoveSource;
    target: WorkerPlacementMoveTarget;
    abandonSource?: true;
  }, beforeBegin?: (placement: WorkerSessionPlacementRecord, joined: boolean) => void) => {
    intent: WorkerPlacementMoveIntent;
    placement: WorkerSessionPlacementRecord;
    joined: boolean;
  }>[0], guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  } & {
    assertNewSource?: (placement: WorkerSessionPlacementRecord) => void;
  }): Promise<{
    intent: WorkerPlacementMoveIntent;
    placement: WorkerSessionPlacementRecord;
    joined: boolean;
  }>;
  recordPlacementMoveError(input: Parameters<(input: {
    operationId: string;
    sessionId: string;
    error: string;
  }) => boolean>[0]): Promise<boolean>;
  cancelPlacementMove(input: Parameters<(input: {
    operationId: string;
    sessionId: string;
    expectedLocalGeneration?: number;
  }) => boolean>[0], guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<boolean>;
  completePlacementMoveSourceToLocal(input: Parameters<(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
  }) => {
    placement: WorkerSessionPlacementRecord;
    moveRemoved: boolean;
  }>[0], guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<WorkerSessionPlacementRecord>;
  completeAbandonedPlacementMoveSourceToLocal(input: Parameters<(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
  } & {
    expectedRecoveryError: string;
  }) => {
    placement: WorkerSessionPlacementRecord;
    moveRemoved: boolean;
  }>[0], guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<WorkerSessionPlacementRecord>;
  completePlacementMoveToWorker(input: Parameters<(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
    environmentId: string;
    ownerEpoch: number;
  }) => WorkerSessionPlacementRecord>[0], guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<WorkerSessionPlacementRecord>;
  bindPreparedEnvironment({ assertCurrent, ...input }: PreparedEnvironmentSelection): Promise<WorkerSessionPlacementRecord | undefined>;
  retireSessionPlacementAsync(input: WorkerSessionPlacementRetirement, guard?: {
    assertCurrent?: WorkerPlacementAuthorization;
  }): Promise<void>;
  getManyAsync: (sessionIds: readonly string[]) => Promise<ReadonlyMap<string, WorkerSessionPlacementRecord>>;
  getAsync(sessionId: string): Promise<WorkerSessionPlacementRecord | undefined>;
  getWithMoveAsync(sessionId: string): Promise<{
    placement: WorkerSessionPlacementRecord | undefined;
    move: WorkerPlacementMoveIntent | undefined;
  }>;
  listAsync: () => Promise<WorkerSessionPlacementRecord[]>;
  listSessionIdentitiesAsync(): Promise<WorkerSessionPlacementIdentity[]>;
  getPlacementMoveAsync(sessionId: string): Promise<WorkerPlacementMoveIntent | undefined>;
  listForReconcileAsync(sessionKey?: string): Promise<WorkerSessionPlacementRecord[]>;
  authorizeWorkerTurnTools(claim: WorkerSessionTurnClaim, names: readonly string[], assertCurrent?: () => void): Promise<void>;
  isWorkerTurnToolAuthorized(claim: WorkerSessionTurnClaim, name: string): boolean;
  closeWorkerTurnToolAdmission: (claim: WorkerSessionTurnClaim) => Promise<void>;
  closeWorkerTurnToolState(claim: WorkerSessionTurnClaim): Promise<void>;
  beginWorkerSessionToolOperation(params: Parameters<(params: {
    claim: WorkerSessionTurnClaim;
    toolName: "sessions_spawn" | "sessions_send";
    toolCallId: string;
    requestDigest: string;
  }) => WorkerSessionToolOperationStart>[0], assertCurrent?: () => void): Promise<{
    kind: "execute";
    operationSeed: string;
  } | {
    kind: "completed";
    resultJson: string;
  } | {
    kind: "in-progress";
  } | {
    kind: "unknown";
  } | {
    kind: "capacity";
  } | {
    kind: "conflict";
  } | {
    kind: "unauthorized";
  }>;
  bindWorkerSessionToolOperationChild(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  } & {
    childSessionKey: string;
  }): Promise<boolean>;
  completeWorkerSessionToolOperation(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  } & {
    resultJson: string;
    failed?: boolean;
  }): Promise<boolean>;
  abandonWorkerSessionToolOperation(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  }): Promise<boolean>;
  recoverWorkerSessionToolOperationsAfterRestart(): Promise<number>;
  transition: (input: {
    sessionId: string;
    from: SessionPlacementState;
    to: SessionPlacementState;
    expectedGeneration: number;
    patch?: WorkerSessionPlacementTransitionPatch;
    localIdentity?: WorkerSessionPlacementIdentity;
  }, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  startDrain: (input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration: number;
    expectedUpdatedAtMs?: number;
    workspaceBaseManifestRef?: string;
    requireUnclaimed?: true;
    expectedTurnClaim?: Parameters<typeof drainWorkerSessionPlacement>[1]["expectedTurnClaim"];
  }, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  startReconcile: (input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration: number;
    forceLocalClaim?: true;
    requireUnclaimed?: true;
    expectedTurnClaim?: WorkerSessionTurnClaim;
  }, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  fail: (input: {
    sessionId: string;
    recoveryError: string;
    expectedGeneration?: number;
    localIdentity?: WorkerSessionPlacementIdentity;
  }, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  failWorkspaceResultAndReleaseTurn(pending: WorkerWorkspacePendingResult, error: unknown, assertCurrent?: () => void): Promise<WorkerSessionPlacementRecord>;
  claimReclaimWorkspaceResult(input: Parameters<(input: WorkerTurnClaimInput) => WorkerSessionTurnClaim>[0], beforePublish?: (claim: WorkerSessionTurnClaim) => void, assertCurrent?: () => void): Promise<WorkerSessionTurnClaim>;
  claimWorkspaceMutationResult(input: Parameters<(input: Omit<WorkerTurnClaimInput, "runId">) => WorkerSessionTurnClaim>[0], assertCurrent?: () => void, current?: PlacementTurnClaimCurrentCheck): Promise<WorkerSessionTurnClaim>;
  markWorkspaceResultPending(claim: WorkerSessionTurnClaim, assertCurrent?: () => void): Promise<void>;
  acceptWorkspaceResult(claim: WorkerSessionTurnClaim, assertCurrent?: () => void, current?: PlacementTurnClaimCurrentCheck): Promise<void>;
  handoffWorkspaceResultRecovery(claim: WorkerSessionTurnClaim, assertCurrent?: () => void): Promise<void>;
  abandonWorkspaceResult(pending: WorkerWorkspacePendingResult, assertCurrent?: () => void): Promise<void>;
  startWorkspaceResultDrain: (input: WorkerSessionTurnClaim, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  completeWorkspaceResultAndReleaseTurn(claim: WorkerSessionTurnClaim, assertCurrent?: () => void, current?: PlacementTurnClaimCurrentCheck): Promise<WorkerSessionPlacementRecord>;
  cancelWorkspaceResultAndReleaseTurn(claim: WorkerSessionTurnClaim, options?: {
    reason: "node-disconnect";
  }, assertCurrent?: () => void): Promise<WorkerSessionPlacementRecord>;
  updateAckCursors(input: PlacementAckCursorInput, assertCurrent?: () => void): Promise<WorkerSessionPlacementRecord>;
  updateWorkspaceBaseManifest(input: Parameters<(input: {
    claim: WorkerSessionTurnClaim;
    manifestRef: string;
  }) => WorkerSessionPlacementRecord>[0], assertCurrent?: () => void, current?: PlacementTurnClaimCurrentCheck): Promise<WorkerSessionPlacementRecord>;
  recordStagedWorkspaceResult(claim: WorkerSessionTurnClaim, stagedResultRef: string, repositoryWorkspaceId?: string, assertCurrent?: () => void, current?: PlacementTurnClaimCurrentCheck): Promise<void>;
  retainInterruptedTurnWorkspace(claim: Parameters<(claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord>[0], assertCurrent: () => void): Promise<void>;
  handoffRuntimeRefreshResult: (input: {
    claim: WorkerSessionTurnClaim;
    sessionEntryCurrentSource?: SessionEntryCurrentSource;
    expectedGeneration: number;
    gatewayInstanceId: string;
  }, assertCurrent?: () => void) => Promise<WorkerSessionPlacementRecord>;
  claimTurn(input: Parameters<(input: WorkerTurnClaimInput) => {
    claim: WorkerSessionTurnClaim;
    placement: WorkerSessionPlacementRecord;
  }>[0], assertCurrent?: () => void): Promise<WorkerSessionTurnClaim>;
  releaseTurn(claim: WorkerSessionTurnClaim, assertCurrent?: () => void): Promise<{
    sessionId: string;
    agentId: string;
    sessionKey: string;
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    createdAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
    environmentId: string | null;
    state: "provisioning";
    turnClaim: null;
    updatedAtMs: number;
    activeOwnerEpoch: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  } | {
    sessionId: string;
    agentId: string;
    sessionKey: string;
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    createdAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
    environmentId: string;
    workerBundleHash: string;
    state: "syncing";
    turnClaim: null;
    updatedAtMs: number;
    activeOwnerEpoch: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workspaceBaseManifestRef: null;
  } | {
    sessionId: string;
    agentId: string;
    sessionKey: string;
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    createdAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
    environmentId: string;
    workerBundleHash: string;
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
    terminalReason: string | null;
    terminalAtMs: number | null;
    state: "reclaimed";
    turnClaim: null;
    updatedAtMs: number;
    recoveryError: null;
  } | {
    sessionId: string;
    agentId: string;
    sessionKey: string;
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    createdAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
    environmentId: string;
    workerBundleHash: string;
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
    state: "reconciling";
    turnClaim: null;
    updatedAtMs: number;
    recoveryError: null;
    terminalAtMs: null;
    terminalReason: null;
  } | {
    sessionId: string;
    agentId: string;
    sessionKey: string;
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    createdAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
    environmentId: string;
    workerBundleHash: string;
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
    state: "starting";
    turnClaim: null;
    updatedAtMs: number;
    activeOwnerEpoch: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    terminalAtMs: null;
    terminalReason: null;
  } | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: ({
      claimId: string;
      runId: string;
      generation: number;
    } & {
      owner: "local";
      ownerEpoch: null;
    }) | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & {
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  } & {
    state: "local";
  }) | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: ({
      claimId: string;
      runId: string;
      generation: number;
    } & {
      owner: "local";
      ownerEpoch: null;
    }) | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & {
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  } & {
    state: "requested";
  }) | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: PersistedTurnClaim | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & Omit<Omit<Omit<{
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  }, "environmentId" | "workerBundleHash"> & {
    environmentId: string;
    workerBundleHash: string;
  }, "remoteWorkspaceDir" | "workspaceBaseManifestRef"> & {
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
  }, "activeOwnerEpoch" | "lastLiveEventAckCursor" | "lastTranscriptAckCursor"> & {
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
  } & {
    state: "active";
  }) | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: PersistedTurnClaim | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & Omit<Omit<Omit<{
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  }, "environmentId" | "workerBundleHash"> & {
    environmentId: string;
    workerBundleHash: string;
  }, "remoteWorkspaceDir" | "workspaceBaseManifestRef"> & {
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
  }, "activeOwnerEpoch" | "lastLiveEventAckCursor" | "lastTranscriptAckCursor"> & {
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
  } & {
    state: "draining";
  }) | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: ({
      claimId: string;
      runId: string;
      generation: number;
    } & {
      owner: "local";
      ownerEpoch: null;
    }) | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & {
    environmentId: string | null;
    activeOwnerEpoch: number | null;
    workspaceBaseManifestRef: string | null;
    remoteWorkspaceDir: string | null;
    workerBundleHash: string | null;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
    terminalReason: string | null;
    terminalAtMs: number | null;
  } & {
    recoveryError: string;
  } & {
    state: "failed";
  })>;
  releaseTurnIfOwned(claim: Parameters<(claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord>[0]): Promise<void>;
  getWorkspaceReconciliationPlacement(owner: WorkerWorkspaceJournalOwner, assertCurrent?: () => void): Promise<(WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: PersistedTurnClaim | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & Omit<Omit<Omit<{
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  }, "environmentId" | "workerBundleHash"> & {
    environmentId: string;
    workerBundleHash: string;
  }, "remoteWorkspaceDir" | "workspaceBaseManifestRef"> & {
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
  }, "activeOwnerEpoch" | "lastLiveEventAckCursor" | "lastTranscriptAckCursor"> & {
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
  } & {
    state: "active";
  }) | (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: PersistedTurnClaim | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & Omit<Omit<Omit<{
    activeOwnerEpoch: null;
    environmentId: null;
    lastLiveEventAckCursor: null;
    lastTranscriptAckCursor: null;
    recoveryError: null;
    remoteWorkspaceDir: null;
    terminalAtMs: null;
    terminalReason: null;
    workerBundleHash: null;
    workspaceBaseManifestRef: null;
  }, "environmentId" | "workerBundleHash"> & {
    environmentId: string;
    workerBundleHash: string;
  }, "remoteWorkspaceDir" | "workspaceBaseManifestRef"> & {
    workspaceBaseManifestRef: string;
    remoteWorkspaceDir: string;
  }, "activeOwnerEpoch" | "lastLiveEventAckCursor" | "lastTranscriptAckCursor"> & {
    activeOwnerEpoch: number;
    lastTranscriptAckCursor: number | null;
    lastLiveEventAckCursor: number | null;
  } & {
    state: "draining";
  }) | undefined>;
  listWorkspaceReconciliationOwners(assertCurrent?: () => void): Promise<WorkerWorkspaceJournalOwner[]>;
  loadWorkspaceReconciliation(owner: WorkerWorkspaceJournalOwner, options?: {
    allowFailedOwner?: boolean;
  }, assertCurrent?: () => void): Promise<WorkerWorkspaceReconciliationJournal | undefined>;
  beginWorkspaceReconciliation(owner: WorkerWorkspaceJournalOwner, journal: WorkerWorkspaceReconciliationJournal, assertCurrent?: () => void): Promise<void>;
  abortWorkspaceReconciliation(owner: WorkerWorkspaceJournalOwner, options?: {
    force?: boolean;
  }, assertCurrent?: () => void): Promise<void>;
  pruneOrphanedWorkspaceReconciliations(assertCurrent?: () => void): Promise<WorkerWorkspaceJournalOwner[]>;
  withWorkspaceExclusion: <T>(sessionId: string, run: (assertOwned: () => void) => Promise<T>) => Promise<T>;
  withLocalWorkspaceReservation: <T>(identity: WorkerSessionPlacementIdentity, run: (assertCurrent: () => void) => Promise<T>) => Promise<T>;
  withRepositoryWorkspaceReservation: <T>(identity: WorkerSessionPlacementIdentity, run: (assertCurrent: () => void) => Promise<T>) => Promise<T>;
  workspaceResultInstanceId: () => string;
  prepareWorkspaceResultClaim(claim: WorkerSessionTurnClaim): Promise<void>;
  validateWorkspaceResultClaim: (claim: WorkerSessionTurnClaim) => boolean;
  preparedWorkspaceResult: (claim: WorkerSessionTurnClaim) => WorkerWorkspacePendingResult | undefined;
  preparedWorkspaceResultPlacement: (claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord | undefined;
  listPendingWorkspaceResults(sessionId?: string): WorkerWorkspacePendingResult[];
  getWorkspaceResultReconcilingSessionIds(sessionIds: readonly string[]): ReadonlySet<string>;
  getWorkspaceResultReconcilingSessionIdsAsync(sessionIds: readonly string[]): Promise<ReadonlySet<string>>;
  listPendingWorkspaceResultsAsync(sessionId?: string): Promise<WorkerWorkspacePendingResult[]>;
  subscribeChanges(listener: (placement: WorkerSessionPlacementIdentity) => void): () => void;
  /** @deprecated Await clearLocalTurnClaimsAfterRestartAsync; removed in the next Plugin SDK major. */
  clearLocalTurnClaimsAfterRestart(): number;
  waitForTurnClaimRelease: (sessionId: string, waitOptions: {
    timeoutMs?: number;
    signal?: AbortSignal;
  }) => Promise<void>;
  validateTurnClaim(claim: WorkerSessionTurnClaim): boolean;
  readWorkerTurnClaim(binding: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
  }): WorkerSessionTurnClaim | undefined;
  registerTurnClaimClosedHandler(handler: (claim: WorkerSessionTurnClaim) => void): () => void;
  /** @deprecated Await getAsync for cold reads; this method uses only prepared in-process facts. */
  get(sessionId: string): WorkerSessionPlacementRecord | undefined;
  prepareTurnClaimAuthority(claim: WorkerSessionTurnClaim): Promise<PlacementTurnClaimAuthority>;
  prepareRuntimeRefresh(sessionIdInput: string): Promise<{
    assertCurrent: () => void;
    release: () => void;
    placement: WorkerSessionPlacementRecord | undefined;
    move: WorkerPlacementMoveIntent | undefined;
    pendingResult: WorkerWorkspacePendingResult | undefined;
  }>;
  prepareSessionPlacement(sessionIdInput: string): Promise<{
    prepareRead(this: void): Promise<void> | undefined;
    current(this: void): WorkerSessionPlacementRecord | undefined;
    release: () => void;
  }>;
  prepareMaintenancePlacements(): Promise<{
    readonly placements: Iterable<WorkerSessionPlacementRecord>;
    assertCurrent: () => void;
    release: () => void;
  }>;
  readProjection(sessionIds: readonly string[], readOptions?: {
    current?: boolean;
  }): Promise<WorkerSessionPlacementProjection>;
  readPublishedProjection(change: SessionRowChange): WorkerSessionPlacementProjection | undefined;
  readEnvironmentOwner(environmentId: string, signal?: AbortSignal): Promise<WorkerSessionPlacementRecord | undefined>;
  readRecoveryCandidates(): Promise<WorkerPlacementRecoveryCandidate[]>;
  /** @deprecated Await getManyAsync; retained through the next Plugin SDK major. */
  getMany(sessionIds: readonly string[]): ReadonlyMap<string, WorkerSessionPlacementRecord>;
  /** @deprecated Await retireSessionPlacementAsync; removed in the next Plugin SDK major. */
  retireSessionPlacement(input: WorkerSessionPlacementRetirement): void;
  recordWorkspaceResultConflict(claim: WorkerSessionTurnClaim, conflict: WorkerWorkspaceResultConflict | undefined): void;
  adoptActive(input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration?: number;
  }): Promise<WorkerSessionPlacementRecord>;
  /** @deprecated Await listForReconcileAsync; retained through the next Plugin SDK major. */
  listForReconcile(sessionKey?: string): WorkerSessionPlacementRecord[];
  /** @deprecated Await listAsync; retained through the next Plugin SDK major. */
  list(): WorkerSessionPlacementRecord[];
  readChangeSnapshot(profileIds?: readonly string[]): Promise<WorkerSessionPlacementChangeSnapshot[]>;
};
type WorkerSessionPlacementStore = ReturnType<typeof createWorkerSessionPlacementStore>;
type WorkerSessionPlacementRetirementService = Pick<WorkerSessionPlacementStore, "retireSessionPlacement" | "retireSessionPlacementAsync">;
//#endregion
//#region src/worker/worker-process-observation.d.ts
declare const nodeRequest: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  environmentId: z.ZodCustom<string, string>;
  sessionId: z.ZodCustom<string, string>;
  ownerEpoch: z.ZodNumber;
  gatewayNamespace: z.ZodCustom<string, string>;
  placementGeneration: z.ZodNumber;
  expectedBundleHash: z.ZodString;
  operation: z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    action: z.ZodLiteral<"list">;
  }, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    action: z.ZodLiteral<"stop">;
    processId: z.ZodCustom<string, string>;
    instanceId: z.ZodCustom<string, string>;
  }, z.core.$strip>>]>;
}, z.core.$strip>>;
type NodeWorkerProcessInput = z.infer<typeof nodeRequest>;
//#endregion
//#region src/gateway/worker-environments/workspace-result-inventory.d.ts
declare const WorkerWorkspaceGitHistorySchema: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  baseCommit: z.ZodString;
  headCommit: z.ZodString;
  descendsFromBase: z.ZodBoolean;
  unavailableReason: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>;
type WorkerWorkspaceGitHistory = z.infer<typeof WorkerWorkspaceGitHistorySchema>;
//#endregion
//#region src/agents/internal-runtime-context.d.ts
/** Provenance assigned by the context producer, never inferred from its text. */
type RuntimeContextFragment = {
  kind: "runtime-instruction" | "conversation-data" | "heartbeat-outcome";
  text: string;
};
type CurrentInboundPromptContext = {
  text: string;
  /** Producer-owned fragments for model projection; text remains the legacy rendering. */
  fragments?: RuntimeContextFragment[];
  resumableText?: string;
  promptJoiner?: "\n\n" | "\n" | " ";
  /** Generated goal blocks owned by inbound-context assembly, never user text. */
  injectedGoalContexts?: string[];
};
/** Identifies hidden runtime context independently of its queue or transcript owner. */
declare function isOpenClawRuntimeContextCustomMessage(message: unknown): boolean;
//#endregion
//#region src/worker/launch-descriptor.d.ts
type WorkerLaunchPermissionContext = {
  permissionMode: SessionPermissionMode;
  workerContainmentRoot: string;
} | {
  permissionMode?: never;
  workerContainmentRoot?: never;
};
type WorkerComputerLaunchDescriptor = z.infer<typeof ComputerLaunchSchema>;
type WorkerLaunchAssignment = Omit<z.infer<typeof AssignmentSchema>, "permissionMode" | "workerContainmentRoot"> & WorkerLaunchPermissionContext;
type WorkerLaunchAdmission = Omit<WorkerConnectParams["admission"], "runId"> & {
  sessionId: string;
};
type WorkerLaunchPlan = {
  version: 4;
  admission: WorkerLaunchAdmission;
  assignment: WorkerLaunchAssignment;
};
declare const ComputerLaunchSchema: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  nodeId: z.ZodString;
  computerUse: z.ZodCustom<{
    contractVersion: 2;
    provider: {
      id: string;
      label: string;
      generation: string;
    };
    actions: ("bring_to_front" | "browser_click" | "browser_dialog" | "browser_download" | "browser_navigate" | "browser_pointer" | "browser_prepare" | "browser_set_input_files" | "browser_type" | "double_click" | "escalate_scope" | "get_accessibility_tree" | "get_browser_state" | "get_cursor_position" | "get_recording_state" | "get_window_state" | "hold_key" | "invoke_menu" | "key" | "kill_app" | "launch_app" | "left_click" | "left_click_drag" | "left_mouse_down" | "left_mouse_up" | "list_apps" | "list_windows" | "middle_click" | "mouse_move" | "replay_trajectory" | "right_click" | "screenshot" | "scroll" | "set_value" | "start_recording" | "stop_recording" | "triple_click" | "type" | "wait" | "zoom")[];
    targets: ("browser" | "element" | "screen" | "window")[];
    deliveryModes: ("background" | "foreground")[];
    observations: ("accessibility" | "browser" | "image")[];
    features: {
      recording: boolean;
      agentCursor: boolean;
      multiDisplay: boolean;
    };
  }, {
    contractVersion: 2;
    provider: {
      id: string;
      label: string;
      generation: string;
    };
    actions: ("bring_to_front" | "browser_click" | "browser_dialog" | "browser_download" | "browser_navigate" | "browser_pointer" | "browser_prepare" | "browser_set_input_files" | "browser_type" | "double_click" | "escalate_scope" | "get_accessibility_tree" | "get_browser_state" | "get_cursor_position" | "get_recording_state" | "get_window_state" | "hold_key" | "invoke_menu" | "key" | "kill_app" | "launch_app" | "left_click" | "left_click_drag" | "left_mouse_down" | "left_mouse_up" | "list_apps" | "list_windows" | "middle_click" | "mouse_move" | "replay_trajectory" | "right_click" | "screenshot" | "scroll" | "set_value" | "start_recording" | "stop_recording" | "triple_click" | "type" | "wait" | "zoom")[];
    targets: ("browser" | "element" | "screen" | "window")[];
    deliveryModes: ("background" | "foreground")[];
    observations: ("accessibility" | "browser" | "image")[];
    features: {
      recording: boolean;
      agentCursor: boolean;
      multiDisplay: boolean;
    };
  }>;
}, z.core.$strip>>;
declare const AssignmentSchema: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  skillAuthoring: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    multipleProfiles: z.ZodBoolean;
  }, z.core.$strip>>>;
  skillResources: z.ZodOptional<z.ZodCustom<{
    version: 1;
    skills: {
      sourcePath?: string | undefined;
      modelVisible?: boolean | undefined;
      name: string;
      displayName?: string | undefined;
      description: string;
      revision: string;
      files: {
        path: string;
        content: string;
        encoding?: "base64" | "utf8" | undefined;
        executable?: boolean | undefined;
      }[];
    }[];
  }, {
    version: 1;
    skills: {
      sourcePath?: string | undefined;
      modelVisible?: boolean | undefined;
      name: string;
      displayName?: string | undefined;
      description: string;
      revision: string;
      files: {
        path: string;
        content: string;
        encoding?: "base64" | "utf8" | undefined;
        executable?: boolean | undefined;
      }[];
    }[];
  }>>;
  agentId: z.ZodString;
  operationalRunInstance: z.ZodReadonly<z.ZodObject<{
    instanceId: z.ZodString;
    runId: z.ZodString;
  }, z.core.$strip>>;
  agentRuntimeIdentityToken: z.ZodString;
  runId: z.ZodString;
  turnId: z.ZodString;
  prompt: z.ZodCustom<string | ({
    type: "text";
    text: string;
    textSignature?: string | undefined;
  } | {
    type: "image";
    data: string;
    mimeType: string;
  })[], string | ({
    type: "text";
    text: string;
    textSignature?: string | undefined;
  } | {
    type: "image";
    data: string;
    mimeType: string;
  })[]>;
  suppressPromptTranscript: z.ZodBoolean;
  workspaceDir: z.ZodString;
  modelRef: z.ZodCustom<{
    provider: string;
    model: string;
  }, {
    provider: string;
    model: string;
  }>;
  inference: z.ZodOptional<z.ZodLiteral<"runtime-local">>;
  inferenceOptions: z.ZodCustom<{
    temperature?: number | undefined;
    maxTokens?: number | undefined;
    reasoning?: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh" | undefined;
    thinkingBudgets?: {
      minimal?: number | undefined;
      low?: number | undefined;
      medium?: number | undefined;
      high?: number | undefined;
      max?: number | undefined;
    } | undefined;
  }, {
    temperature?: number | undefined;
    maxTokens?: number | undefined;
    reasoning?: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh" | undefined;
    thinkingBudgets?: {
      minimal?: number | undefined;
      low?: number | undefined;
      medium?: number | undefined;
      high?: number | undefined;
      max?: number | undefined;
    } | undefined;
  }>;
  systemPrompt: z.ZodOptional<z.ZodString>;
  inHistorySystemUpdates: z.ZodOptional<z.ZodBoolean>;
  includeEmptySnapshots: z.ZodOptional<z.ZodBoolean>;
  runtimeContext: z.ZodOptional<z.ZodCustom<RuntimeContextFragment[], RuntimeContextFragment[]>>;
  initialMessages: z.ZodCustom<({
    role: "toolResult";
    toolCallId: string;
    toolName: string;
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    details?: unknown;
    isError: boolean;
    timestamp: number;
  } | {
    role: "user";
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    timestamp: number;
    operatorMessage?: {
      turnScoped: boolean;
    } | undefined;
  } | {
    role: "custom";
    content: string | ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    display: false;
    timestamp: number;
    customType: "openclaw.runtime-context";
    details: {
      source?: "openclaw-runtime-context" | undefined;
      runtimeContextCarrier?: true | undefined;
      fragments?: {
        kind: "conversation-data" | "heartbeat-outcome" | "runtime-instruction";
        text: string;
      }[] | undefined;
    };
  } | {
    role: "custom";
    content: string | ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    display: false;
    timestamp: number;
    customType: "openclaw.system-update";
    details: {
      kind: "prompt-update" | "runtime-context";
      turnScoped: boolean;
    };
  } | {
    role: "assistant";
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "thinking";
      thinking: string;
      thinkingSignature?: string | undefined;
      redacted?: boolean | undefined;
    } | {
      type: "toolCall";
      id: string;
      name: string;
      arguments: Record<string, unknown>;
      thoughtSignature?: string | undefined;
      executionMode?: "parallel" | "sequential" | undefined;
    })[];
    api: string;
    provider: string;
    model: string;
    responseModel?: string | undefined;
    responseId?: string | undefined;
    providerReplay?: {
      v: 1;
      type: string;
      id?: string | undefined;
      data: string;
      replayIndex?: number | undefined;
      provider: string;
      api: string;
      model: string;
      baseUrlHash?: string | undefined;
      sessionHash?: string | undefined;
      authProfileHash?: string | undefined;
    } | undefined;
    usage: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      usageReport?: {
        state: "available" | "unavailable";
      } | undefined;
      contextUsage?: {
        state: "available";
        promptTokens: number;
        totalTokens: number;
      } | {
        state: "unavailable";
      } | undefined;
      totalTokens: number;
      cost?: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        total: number;
        totalOrigin?: "provider-billed" | undefined;
      } | undefined;
    };
    timestamp: number;
    diagnostics?: {
      type: string;
      timestamp: number;
      error?: {
        name?: string | undefined;
        message: string;
        stack?: string | undefined;
        code?: string | number | undefined;
      } | undefined;
      details?: Record<string, unknown> | undefined;
    }[] | undefined;
    stopReason: "aborted" | "error" | "length" | "stop" | "toolUse";
    errorMessage?: string | undefined;
    errorCode?: string | undefined;
    errorType?: string | undefined;
    errorBody?: string | undefined;
    retryAfterMs?: number | null | undefined;
    itemId?: string | undefined;
  })[], ({
    role: "toolResult";
    toolCallId: string;
    toolName: string;
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    details?: unknown;
    isError: boolean;
    timestamp: number;
  } | {
    role: "user";
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    timestamp: number;
    operatorMessage?: {
      turnScoped: boolean;
    } | undefined;
  } | {
    role: "custom";
    content: string | ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    display: false;
    timestamp: number;
    customType: "openclaw.runtime-context";
    details: {
      source?: "openclaw-runtime-context" | undefined;
      runtimeContextCarrier?: true | undefined;
      fragments?: {
        kind: "conversation-data" | "heartbeat-outcome" | "runtime-instruction";
        text: string;
      }[] | undefined;
    };
  } | {
    role: "custom";
    content: string | ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    display: false;
    timestamp: number;
    customType: "openclaw.system-update";
    details: {
      kind: "prompt-update" | "runtime-context";
      turnScoped: boolean;
    };
  } | {
    role: "assistant";
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "thinking";
      thinking: string;
      thinkingSignature?: string | undefined;
      redacted?: boolean | undefined;
    } | {
      type: "toolCall";
      id: string;
      name: string;
      arguments: Record<string, unknown>;
      thoughtSignature?: string | undefined;
      executionMode?: "parallel" | "sequential" | undefined;
    })[];
    api: string;
    provider: string;
    model: string;
    responseModel?: string | undefined;
    responseId?: string | undefined;
    providerReplay?: {
      v: 1;
      type: string;
      id?: string | undefined;
      data: string;
      replayIndex?: number | undefined;
      provider: string;
      api: string;
      model: string;
      baseUrlHash?: string | undefined;
      sessionHash?: string | undefined;
      authProfileHash?: string | undefined;
    } | undefined;
    usage: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      usageReport?: {
        state: "available" | "unavailable";
      } | undefined;
      contextUsage?: {
        state: "available";
        promptTokens: number;
        totalTokens: number;
      } | {
        state: "unavailable";
      } | undefined;
      totalTokens: number;
      cost?: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        total: number;
        totalOrigin?: "provider-billed" | undefined;
      } | undefined;
    };
    timestamp: number;
    diagnostics?: {
      type: string;
      timestamp: number;
      error?: {
        name?: string | undefined;
        message: string;
        stack?: string | undefined;
        code?: string | number | undefined;
      } | undefined;
      details?: Record<string, unknown> | undefined;
    }[] | undefined;
    stopReason: "aborted" | "error" | "length" | "stop" | "toolUse";
    errorMessage?: string | undefined;
    errorCode?: string | undefined;
    errorType?: string | undefined;
    errorBody?: string | undefined;
    retryAfterMs?: number | null | undefined;
    itemId?: string | undefined;
  })[]>;
  transcript: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    baseLeafId: z.ZodNullable<z.ZodString>;
    nextSeq: z.ZodNumber;
  }, z.core.$strip>>;
  liveEvents: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    ackedSeq: z.ZodNumber;
    nextSeq: z.ZodNumber;
  }, z.core.$strip>>;
  toolAuthority: z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    allowedToolNames: z.ZodArray<z.ZodString>;
    exec: z.ZodOptional<z.ZodUnion<readonly [z.ZodPipe<z.ZodUnknown, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
      mode: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        ask: "ask";
        auto: "auto";
        deny: "deny";
        full: "full";
      }>>;
      strictInlineEval: z.ZodOptional<z.ZodBoolean>;
      security: z.ZodEnum<{
        allowlist: "allowlist";
        deny: "deny";
        full: "full";
      }>;
      ask: z.ZodEnum<{
        always: "always";
        off: "off";
        "on-miss": "on-miss";
      }>;
      safeBins: z.ZodOptional<z.ZodTuple<[], null>>;
      host: z.ZodEnum<{
        gateway: "gateway";
        sandbox: "sandbox";
      }>;
    }, z.core.$strip>>>, z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
      mode: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        ask: "ask";
        auto: "auto";
        deny: "deny";
        full: "full";
      }>>;
      strictInlineEval: z.ZodOptional<z.ZodBoolean>;
      security: z.ZodEnum<{
        allowlist: "allowlist";
        deny: "deny";
        full: "full";
      }>;
      ask: z.ZodEnum<{
        always: "always";
        off: "off";
        "on-miss": "on-miss";
      }>;
      safeBins: z.ZodOptional<z.ZodTuple<[], null>>;
      host: z.ZodLiteral<"node">;
      node: z.ZodOptional<z.ZodString>;
    }, z.core.$strip>>, z.ZodTransform<{
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node?: string | undefined;
    }, {
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node?: string | undefined;
    }>>]>>;
  }, z.core.$strip>>, z.ZodTransform<{
    allowedToolNames: string[];
    exec?: {
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "gateway" | "sandbox";
    } | {
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node?: string | undefined;
    } | undefined;
  }, {
    allowedToolNames: string[];
    exec?: {
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "gateway" | "sandbox";
    } | {
      mode?: "allowlist" | "ask" | "auto" | "deny" | "full" | undefined;
      strictInlineEval?: boolean | undefined;
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node?: string | undefined;
    } | undefined;
  }>>;
  browser: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    cdpUrl: z.ZodString;
    launcherPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
    launcherArgs: z.ZodOptional<z.ZodCustom<string[], string[]>>;
  }, z.core.$strip>>>;
  computer: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    nodeId: z.ZodString;
    computerUse: z.ZodCustom<{
      contractVersion: 2;
      provider: {
        id: string;
        label: string;
        generation: string;
      };
      actions: ("bring_to_front" | "browser_click" | "browser_dialog" | "browser_download" | "browser_navigate" | "browser_pointer" | "browser_prepare" | "browser_set_input_files" | "browser_type" | "double_click" | "escalate_scope" | "get_accessibility_tree" | "get_browser_state" | "get_cursor_position" | "get_recording_state" | "get_window_state" | "hold_key" | "invoke_menu" | "key" | "kill_app" | "launch_app" | "left_click" | "left_click_drag" | "left_mouse_down" | "left_mouse_up" | "list_apps" | "list_windows" | "middle_click" | "mouse_move" | "replay_trajectory" | "right_click" | "screenshot" | "scroll" | "set_value" | "start_recording" | "stop_recording" | "triple_click" | "type" | "wait" | "zoom")[];
      targets: ("browser" | "element" | "screen" | "window")[];
      deliveryModes: ("background" | "foreground")[];
      observations: ("accessibility" | "browser" | "image")[];
      features: {
        recording: boolean;
        agentCursor: boolean;
        multiDisplay: boolean;
      };
    }, {
      contractVersion: 2;
      provider: {
        id: string;
        label: string;
        generation: string;
      };
      actions: ("bring_to_front" | "browser_click" | "browser_dialog" | "browser_download" | "browser_navigate" | "browser_pointer" | "browser_prepare" | "browser_set_input_files" | "browser_type" | "double_click" | "escalate_scope" | "get_accessibility_tree" | "get_browser_state" | "get_cursor_position" | "get_recording_state" | "get_window_state" | "hold_key" | "invoke_menu" | "key" | "kill_app" | "launch_app" | "left_click" | "left_click_drag" | "left_mouse_down" | "left_mouse_up" | "list_apps" | "list_windows" | "middle_click" | "mouse_move" | "replay_trajectory" | "right_click" | "screenshot" | "scroll" | "set_value" | "start_recording" | "stop_recording" | "triple_click" | "type" | "wait" | "zoom")[];
      targets: ("browser" | "element" | "screen" | "window")[];
      deliveryModes: ("background" | "foreground")[];
      observations: ("accessibility" | "browser" | "image")[];
      features: {
        recording: boolean;
        agentCursor: boolean;
        multiDisplay: boolean;
      };
    }>;
  }, z.core.$strip>>>;
  github: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    token: z.ZodString;
    login: z.ZodString;
    branch: z.ZodString;
    remoteUrl: z.ZodOptional<z.ZodString>;
    gitAuthor: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
      name: z.ZodOptional<z.ZodString>;
      email: z.ZodOptional<z.ZodString>;
    }, z.core.$strip>>>;
  }, z.core.$strip>>>;
  permissionMode: z.ZodOptional<z.ZodCustom<"full" | "guarded" | "read-only" | "workspace", "full" | "guarded" | "read-only" | "workspace">>;
  workerContainmentRoot: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>;
//#endregion
//#region src/worker/node-workspace-protocol.d.ts
declare const WorkspaceQuiescence: z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodLiteral<"acquire">;
  nonce: z.ZodString;
  timeoutMs: z.ZodNumber;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodLiteral<"renew">;
  nonce: z.ZodString;
  timeoutMs: z.ZodNumber;
  validationMode: z.ZodEnum<{
    final: "final";
    heartbeat: "heartbeat";
  }>;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodLiteral<"release">;
  nonce: z.ZodString;
}, z.core.$strip>>]>;
type NodeWorkerWorkspaceQuiescenceInput = z.infer<typeof WorkspaceQuiescence>;
declare const WorkspaceProcess: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodEnum<{
    start: "start";
    status: "status";
    stop: "stop";
  }>;
  processId: z.ZodString;
}, z.core.$strip>>;
type NodeWorkerWorkspaceProcessInput = z.infer<typeof WorkspaceProcess>;
type NodeWorkerWorkspaceProcessResult = {
  processId: string;
  state: "running" | "exited";
};
declare const SeedInput: z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodLiteral<"apply">;
  key: z.ZodString;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  action: z.ZodLiteral<"store">;
  key: z.ZodString;
  maxAgeMs: z.ZodNumber;
}, z.core.$strip>>]>;
type NodeWorkerWorkspaceSeedInput = z.infer<typeof SeedInput>;
type NodeWorkerWorkspaceExecResult = SpawnResult & {
  workspaceDir: string;
  process?: NodeWorkerWorkspaceProcessResult;
};
//#endregion
//#region src/worker/node-workspace-transfer-protocol.d.ts
declare const NodeWorkerWorkspaceTransferInputSchema: z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  direction: z.ZodLiteral<"download">;
  token: z.ZodString;
  manifestRef: z.ZodString;
  seedKey: z.ZodOptional<z.ZodString>;
  attachments: z.ZodOptional<z.ZodLiteral<true>>;
  checkpointBaseManifestRef: z.ZodOptional<z.ZodString>;
  checkpointGitHistory: z.ZodOptional<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
    baseCommit: z.ZodString;
    headCommit: z.ZodString;
    descendsFromBase: z.ZodBoolean;
    unavailableReason: z.ZodOptional<z.ZodString>;
  }, z.core.$strip>>>;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  direction: z.ZodLiteral<"upload">;
  token: z.ZodString;
  baseManifestRef: z.ZodString;
  resultVersion: z.ZodOptional<z.ZodLiteral<2>>;
  referenceManifestRef: z.ZodString;
  publicationBaseCommit: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>]>;
type NodeWorkerWorkspaceTransferInput = z.infer<typeof NodeWorkerWorkspaceTransferInputSchema>;
//#endregion
//#region src/worker/worker-node-loss.d.ts
declare class WorkerNodeLostError extends Error {
  readonly code = "node-lost";
  canContinue: boolean;
  constructor(options?: ErrorOptions);
}
//#endregion
//#region src/infra/git-read-operations.d.ts
type GitCheckoutContext = {
  /** Omitted host is the public GitHub default. */
  host?: string;
  owner: string;
  repo: string;
  branch: string | null;
  root?: string;
  defaultBranch?: string;
  /**
   * Candidate head repositories from non-origin GitHub remotes tracking `branch`.
   * The PR response must identify the same head repository; remote names alone
   * do not establish fork membership. `owner`/`repo` stay the base identity.
   */
  forkHeadCandidates?: Array<{
    owner: string;
    repo: string;
  }>;
};
//#endregion
//#region src/infra/diff-read-timing.d.ts
declare const DIFF_READ_STAGES: readonly ["admission", "checkout-resolve", "cache-validate", "worker-queue", "git-wall", "encode"];
type DiffRevisionUnavailableReason = "oversized" | "no-revision-environment" | "no-revision-platform" | "no-revision-metadata" | "no-revision-git-installation" | "no-revision-config" | "no-revision-reftable" | "no-revision-alternates" | "no-revision-symlink" | "no-revision-status" | "no-revision-unmerged" | "no-revision-submodule" | "no-revision-permission" | "no-revision-missing" | "no-revision-io";
type DiffReadCacheMissReason = "cold" | "evicted" | "pending" | "no-revision" | DiffRevisionUnavailableReason | "revision-changed-head" | "revision-changed-index" | "revision-changed-untracked-set" | "revision-changed-worktree-mtime" | "revision-changed-metadata";
type DiffReadTiming = {
  durations: Partial<Record<(typeof DIFF_READ_STAGES)[number], number>>;
  outcome?: "cache-hit" | "cache-miss";
  missReason?: DiffReadCacheMissReason;
  revisionUnavailableReason?: DiffRevisionUnavailableReason;
};
//#endregion
//#region src/gateway/worker-environments/workspace-actual-manifest.d.ts
type ActualWorkspaceManifestOptions = {
  root: string;
  baseCommit: string | null;
  preserveDirectories?: ReadonlySet<string>;
  includePaths?: ReadonlySet<string>;
  buildCacheInputs?: ReadonlySet<string>;
  gitIgnore?: {
    paths: ReadonlySet<string>;
    retainedPaths: ReadonlySet<string>;
  };
  signal?: AbortSignal;
};
declare function readActualWorkspaceManifestImpl(params: ActualWorkspaceManifestOptions): Promise<{
  manifest: WorkerWorkspaceManifest;
  manifestRef: string;
  rawManifest: string;
}>;
//#endregion
//#region src/gateway/worker-environments/workspace-hash-memo.d.ts
declare const { workspaceCtimeIsReusable, workspaceStatIdentity, selectWorkerWorkspaceHashMemoEntries }: {
  workspaceCtimeIsReusable: (ctimeNs: bigint, startedAtMs: number) => boolean;
  workspaceStatIdentity: (owner: "gateway" | "worker", stats: {
    dev: bigint;
    ino: bigint;
    size: bigint;
    mtimeNs: bigint;
    ctimeNs: bigint;
  }) => string;
  selectWorkerWorkspaceHashMemoEntries: (memo: ReadonlyMap<string, string>, maxEntries: number, maxBytes: number) => Array<[string, string]>;
};
//#endregion
//#region src/gateway/worker-environments/workspace-manifest-worker.d.ts
type WorkspaceCaptureArguments = Parameters<typeof readActualWorkspaceManifestImpl>[0];
declare function captureWorkspaceSnapshot(params: WorkspaceCaptureArguments): Promise<{
  manifest: WorkerWorkspaceManifest;
  manifestRef: string;
  rawManifest: string;
}>;
//#endregion
//#region src/media/staged-inputs.d.ts
declare const { stagedInputPathDirectory, isStagedInputPath, stagedInputDirectoriesFromEntries }: {
  stagedInputPathDirectory: (relativePath: string) => string | undefined;
  isStagedInputPath: (relativePath: string, directories: ReadonlySet<string>) => boolean;
  stagedInputDirectoriesFromEntries: (entries: readonly {
    path: string;
    type: string;
    size?: number;
    sha256?: string;
  }[]) => Set<string>;
};
//#endregion
//#region src/gateway/worker-environments/workspace-reconcile-core.d.ts
type WorkerWorkspaceApplyResult = {
  manifestRef: string;
  manifest: WorkerWorkspaceManifest;
  conflictPaths: string[];
  verifyLocalStable(): Promise<void>;
};
//#endregion
//#region src/gateway/worker-environments/tunnel-contract.d.ts
type WorkerTunnelRequest = {
  environmentId: string;
  ownerEpoch: number;
  /** Initiating-operation authority; established tunnel custody is independent. */
  authorize?: () => void;
};
/** Provider teardown fences local work first; only its confirmed result releases physical ownership. */
type WorkerTunnelStopReason = "provider-destroying" | "provider-destroyed";
type WorkerWorkspaceCommand = {
  argv: readonly string[];
  transportRetry: "idempotent" | "never";
  /** Local owner guard revalidated after transport awaits, immediately before dispatch. */
  assertCurrent?: () => void;
  onDispatchReady?: () => void;
  input?: string;
  timeoutMs?: number;
  signal?: AbortSignal;
  transfer?: NodeWorkerWorkspaceTransferInput;
  seed?: NodeWorkerWorkspaceSeedInput;
  process?: NodeWorkerWorkspaceProcessInput;
  quiescence?: NodeWorkerWorkspaceQuiescenceInput;
  /** Legacy scripts own their detached lease helper, not the foreground command scope. */
  legacyQuiescence?: true;
};
type WorkerRepositoryCheckpointPayload = {
  stagingRoot: string;
  baseManifestRaw: string;
  currentManifestRaw: string;
  baseManifestRef: string;
  currentManifestRef: string;
  publicationStagingRoot?: string;
  publicationDigest?: string;
  gitHistory?: WorkerWorkspaceGitHistory;
  gitPackPath?: string;
  gitHistoryNote?: string;
};
type WorkerRepositoryCheckpointPreparation = {
  verify(): Promise<void>;
  publish(): Promise<unknown>;
  discard(): Promise<void>;
};
/** Attested by the dedicated node's one-use workspace binding. */
type PreparedRepositoryWorkspace = {
  baseCommit: string;
  workspaceDir: string;
  sourceManifestRef: string;
  preparedManifestRef: string;
};
type WorkerRepositoryWorkspaceSource = {
  kind: "repository";
  /** Owner-held result of binding this exact dedicated prepared workspace. */
  prepared?: PreparedRepositoryWorkspace;
  url: string;
  ref?: string;
  branch: string;
  baseCommit?: string;
  gitToken?: string;
  runSetupScript?: boolean;
  checkpoint?: Pick<WorkerRepositoryCheckpointPayload, "stagingRoot" | "baseManifestRaw" | "currentManifestRaw" | "publicationStagingRoot" | "publicationDigest" | "gitHistory" | "gitPackPath" | "gitHistoryNote">;
};
type WorkerWorkspaceSyncRequest = {
  /** Live initiating operation; retained workspace custody uses its independent owner. */
  authorize?: () => void;
  sessionId: string;
  sessionKey?: string;
  generation: number;
  gitAuthor?: {
    name?: string;
    email?: string;
  };
  source: {
    kind: "local";
    path: string;
    projectKey?: string;
  } | {
    kind: "device-folder";
    deviceId: string;
    path: string;
  } | WorkerRepositoryWorkspaceSource;
};
type WorkerWorkspaceSyncResult = {
  mode: "git" | "plain" | "device-folder";
  remoteWorkspaceDir: string;
  manifestRef: string;
} | {
  mode: "repository";
  remoteWorkspaceDir: string;
  manifestRef: string;
  baseCommit: string;
  baseManifestRef: string;
};
type WorkerLocalWorkspaceReconcileRequest = {
  localPath: string;
  remoteWorkspaceDir: string;
  baseManifestRef: string;
  journal: WorkerWorkspaceReconciliationJournalAdapter;
  assertCurrent?: () => void;
  stagedResult: {
    ref: string;
    record(ref: string): void | Promise<void>;
  };
};
type WorkerWorkspaceReconcileRequest = {
  remoteWorkspaceDir: string;
  baseManifestRef: string;
  source: {
    kind: "local";
    path: string;
    journal: WorkerWorkspaceReconciliationJournalAdapter;
    assertCurrent?: () => void;
    stagedResult: WorkerLocalWorkspaceReconcileRequest["stagedResult"];
  } | {
    kind: "repository";
    authorize?: () => void;
    markPhase?: (phase: string) => void;
    referenceManifestRef: string;
    prepareCheckpoint(payload: WorkerRepositoryCheckpointPayload): Promise<WorkerRepositoryCheckpointPreparation>;
  };
};
type WorkerWorkspaceReconcileResult = {
  manifestRef: string;
  changed: boolean;
  /** Re-read the remote workspace after local acceptance, immediately before teardown. */
  verifyStable(): Promise<void>;
  /** Re-read the accepted local result after the remote stability fence. */
  verifyLocalStable(): Promise<void>;
  /** Apply the prepared candidate locally without making it restart-authoritative. */
  applyPreparedStagedResult?(): Promise<void>;
  /** Reverify and accept an exact local/base match without mutating either workspace. */
  acceptUnchangedStagedResult?: () => Promise<void>;
  /** Return the accepted local manifest and any keep-local conflicts after apply. */
  getAppliedWorkspaceResult?(): WorkerWorkspaceApplyResult | undefined;
  /** Publish the verified candidate for restart recovery. */
  publishStagedResult(): Promise<void>;
  discardPreparedStagedResult(): Promise<void>;
};
type WorkerWorkspaceQuiescence = {
  /** Prove the watchdog lease still owns stopped processes and extend it through teardown. */
  assertActive(): Promise<void>;
  /** Resume only the remote processes stopped by this quiescence owner. */
  resume(): Promise<void>;
};
type WorkerTurnLaunchRequest = {
  assertCurrent?: SessionSourceAssertion;
  plan: WorkerLaunchPlan;
  turnClaim: WorkerSessionTurnClaim;
  timeoutMs?: number;
  credentialExpiresAtMs?: number;
  signal?: AbortSignal;
  onDispatchReady?: () => void;
};
type WorkerWorkspaceTunnelHandle = {
  environmentId: string;
  ownerEpoch: number;
  launchTurn?: never;
  measureLaunchTurn?: never;
  readLaunchToolNames?: never;
  runWorkspaceCommand(command: WorkerWorkspaceCommand): Promise<SpawnResult>;
  stageAttachments?(request: {
    localPath: string;
    isAuthorized: () => boolean;
    signal: AbortSignal;
  }): Promise<void>;
  quiesceWorkspace(remoteWorkspaceDir: string): Promise<WorkerWorkspaceQuiescence>;
  syncWorkspace(request: WorkerWorkspaceSyncRequest): Promise<WorkerWorkspaceSyncResult>;
  reconcileWorkspace(request: WorkerWorkspaceReconcileRequest): Promise<WorkerWorkspaceReconcileResult>;
  stop(): Promise<void>;
};
type WorkerTurnProcessResult = SpawnResult & {
  nodeLoss?: WorkerNodeLostError;
};
type WorkerTurnTunnelHandle = Omit<WorkerWorkspaceTunnelHandle, "launchTurn" | "measureLaunchTurn" | "readLaunchToolNames"> & {
  measureLaunchTurn(plan: WorkerLaunchPlan, claim: WorkerSessionTurnClaim): number;
  /** Placement tool implementations available in the destination's installed supervisor. */
  readLaunchToolNames(): Promise<readonly string[]>;
  launchTurn(request: WorkerTurnLaunchRequest): Promise<WorkerTurnProcessResult>;
};
type WorkerTunnelHandle = WorkerWorkspaceTunnelHandle | WorkerTurnTunnelHandle;
//#endregion
//#region src/gateway/agent-runtime-session-spawn-context.d.ts
/** Automatic intent bound to the complete request before creation resolves aliases. */
type AgentRuntimeSpawnModelAutoSelection = {
  model: string;
  /** Self-origin distinguishes configured selection from legacy fallback residue. */
  hasFallbackOrigin: boolean;
};
type AgentRuntimeSessionSpawnContext = {
  /** Host-verified human requester; inherited ownership still requires a matching parent owner. */
  requesterProfileId?: string;
  /** Attribution only; never used to grant operator authority or ownership. */
  gitContributorProfileId?: string;
  /** Trusted owner status of the spawning invocation, never synthetic child launch authority. */
  requesterSenderIsOwner?: boolean;
  completionOwnerSessionKey?: string;
  resolvedModel?: ProviderModelRef;
  inheritedPermissionMode?: SessionPermissionMode;
  inheritedToolPolicy: {
    version: 1;
    allow: string[];
    deny: string[];
    delegatedToolPolicy?: SessionEntry["delegatedToolPolicy"];
  };
  spawnModelAutoSelection?: AgentRuntimeSpawnModelAutoSelection;
};
//#endregion
//#region src/agents/scheduled-tool-policy.d.ts
/** Trusted runtime context for a scheduled run with a server-stamped tool cap. */
type ScheduledToolPolicyContext = (Extract<CronScheduledToolPolicy, {
  mode: "trusted";
}> | (Extract<CronScheduledToolPolicy, {
  mode: "account";
}> & {
  /** Missing legacy runtime contexts are treated as unknown and fail closed. */
  ownerOrigin?: CronScheduledToolCallerOrigin;
})) & {
  /** Restrict-only policy for the rebuilt exec tool; absence keeps baseline exec. */
  execTarget?: {
    host: "gateway";
    ask?: "always";
  };
};
//#endregion
//#region src/channels/threading-tool-context-internal.d.ts
/** Host-only turn correlation carried beside the plugin-facing threading contract. */
type InternalChannelThreadingToolContext = ChannelThreadingToolContext & {
  currentSourceTurnId?: string;
};
//#endregion
//#region src/config/sessions/session-reaction-store.types.d.ts
type StoredMessageReactionSummary = {
  emoji: string;
  count: number;
  identities: Array<{
    id: string;
    label?: string;
  }>;
};
type SetSessionReactionParams = {
  messageId: string;
  emoji: string;
  identityId: string;
  identityLabel?: string;
  remove?: boolean;
  expectedSessionId: string;
};
/** `changed` is false for an add that already exists or a remove with nothing to remove. */
type SessionReactionWrite = {
  reactions: StoredMessageReactionSummary[];
  /** Newest surviving row by created_at, independent of first-created summary order. */
  newestRemainingEmoji: string | undefined;
  changed: boolean;
};
//#endregion
//#region src/gateway/message-action-turn-capability.d.ts
/** Private handoff from authenticated dashboard admission to the exact reply run. */
type DashboardMessageReadAdmission = Readonly<{
  agentId: string;
  runId: string;
  sessionKey: string;
  sessionId?: string;
  prepare?: () => Promise<void>;
  assertCurrent: () => void;
}>;
type MessageActionRequesterIdentity = {
  requesterAccountId?: string;
  requesterSenderId?: string;
  requesterSenderName?: string;
  requesterSenderUsername?: string;
  requesterSenderE164?: string;
};
type AgentRuntimeMessageActionContextBase = MessageActionRequesterIdentity & {
  expiresAtMs: number;
  /** Process-local owner reference revalidated before privileged Gateway use. */
  turnCapability?: string;
  sessionId?: string;
  /** Durable session entry that owns restart-recovery receipt state. */
  sourceReplySessionKey?: string;
  toolContext?: InternalChannelThreadingToolContext;
};
type AgentRuntimeMessageActionContext = AgentRuntimeMessageActionContextBase & ({
  sourceReplyFinal: true;
  sourceReplyToolCallId: string;
} | {
  sourceReplyFinal?: false;
  sourceReplyToolCallId?: string;
});
//#endregion
//#region src/gateway/agent-runtime-identity-token.d.ts
type AgentRuntimeCronSelfManagementContext = {
  jobId: string;
  expiresAtMs: number;
};
type AgentRuntimeIdentity = {
  kind: "agentRuntime";
  agentId: string;
  sessionKey: string;
  operationalRunInstance: OperationalRunInstanceRef;
  delegatedAuthority: AgentRuntimeDelegatedAuthority;
  approvalOwnerPluginId?: string;
  executionIdentity?: ExecutionIdentityAdmissionToken;
  turnSourceChannel?: string;
  /** Explicit admission fact; omission is unknown, never inferred from session routing. */
  turnSourceLocal?: true;
  turnSourceTo?: string;
  turnSourceAccountId?: string;
  turnSourceThreadId?: string | number;
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  messageActionContext?: AgentRuntimeMessageActionContext;
  cronSelfManagementContext?: AgentRuntimeCronSelfManagementContext;
  cronToolsAllowCapture?: "final-executable-surface";
  cronExecToolTarget?: {
    host: "gateway";
    ask?: "always";
  };
  cronCreatorAuthorityGrant?: CronCreatorAuthorityGrant;
  cronManagementGrant?: CronCreatorAuthorityGrant;
  sessionSpawnContext?: AgentRuntimeSessionSpawnContext;
};
type AgentRuntimeDelegatedAuthority = AgentRunDelegatedAuthority & ({
  kind: "local";
} | {
  kind: "worker";
  turnClaim: WorkerSessionTurnClaim;
});
//#endregion
//#region src/state/openclaw-agent-db-admission.d.ts
/** Denial still invokes run under admission, with a throwing authority check, to permit cleanup. */
type OpenClawAgentDatabaseWriteAdmission = <T>(run: (assertCurrent: () => void, validation?: OpenClawAgentDatabaseValidation, integrityRevoked?: boolean) => T | Promise<T>) => Promise<T>;
//#endregion
//#region src/state/openclaw-agent-db.d.ts
declare const { openOpenClawAgentDatabase, openOpenClawAgentDatabaseInWorker, runOpenClawAgentWriteTransaction, withOpenClawAgentDatabaseAsync, withOpenClawAgentDatabaseRuntime, withOpenClawAgentDatabaseRuntimeFromExecution, withOpenClawAgentDatabaseAdmission }: {
  openOpenClawAgentDatabase: (options: OpenClawAgentDatabaseOptions, preparedLease?: ReturnType<typeof prepareOpenClawAgentDatabaseWorkerLease>, registrationObserver?: OpenClawAgentDatabaseRegistrationObserver) => OpenClawAgentDatabase;
  openOpenClawAgentDatabaseInWorker: (options: OpenClawAgentDatabaseOptions, preparedLease: ReturnType<typeof prepareOpenClawAgentDatabaseWorkerLease>, registrationObserver: OpenClawAgentDatabaseRegistrationObserver, signal: AbortSignal) => Promise<OpenClawAgentDatabase>;
  runOpenClawAgentWriteTransaction: <T>(operation: (database: OpenClawAgentDatabase) => T, options: OpenClawAgentDatabaseOptions, transactionOptions?: Pick<SqliteTransactionOptions, "busyTimeoutMs" | "operationLabel" | "slowTransactionHoldMs" | "diagnosticContext"> & {
    repairAdmission?: OpenClawAgentDatabaseRepairAdmission;
    singleStatement?: boolean;
  }) => T;
  withOpenClawAgentDatabaseAsync: <T>(inputOptions: OpenClawAgentDatabaseOptions, operation: (database: OpenClawAgentDatabase) => T | Promise<T>, assertCurrent?: () => void, signal?: AbortSignal) => Promise<T>;
  withOpenClawAgentDatabaseRuntime: <T>(inputOptions: OpenClawAgentDatabaseOptions, operation: (database: OpenClawAgentDatabase) => T | Promise<T>, assertCurrent?: () => void, signal?: AbortSignal) => Promise<T>;
  withOpenClawAgentDatabaseRuntimeFromExecution: <T>(inputOptions: OpenClawAgentDatabaseOptions, execution: OpenClawAgentDatabaseAdmissionExecution, operation: (database: OpenClawAgentDatabase) => T | Promise<T>, assertCurrent?: () => void, signal?: AbortSignal) => Promise<T>;
  withOpenClawAgentDatabaseAdmission: <T>(inputOptions: OpenClawAgentDatabaseOptions, withAdmission: OpenClawAgentDatabaseWriteAdmission, operation: (database: OpenClawAgentDatabase) => T | Promise<T>) => Promise<T>;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-creation-read.d.ts
type SessionCreationSnapshot = SessionEntryCreateWithTranscriptContext & {
  normalizedKey: string;
  legacyKeys: string[];
};
//#endregion
//#region src/config/sessions/session-accessor.transcript-target.d.ts
/** Resolve only a persisted window's key through the captured storage owner. */
declare function resolveSessionKeyBySessionIdAsync(scope: Pick<SessionTranscriptReadScope, "agentId" | "env" | "sessionId" | "storePath">): Promise<string | undefined>;
//#endregion
//#region src/config/sessions/lifecycle.types.d.ts
type SessionLifecycleTimestamps = {
  sessionStartedAt?: number;
  lastInteractionAt?: number;
};
//#endregion
//#region src/config/sessions/session-store-read-candidates.d.ts
type SessionStoreReadCandidate = Pick<OpenClawAgentDatabaseReadCandidateResource, "path" | "scope"> & {
  physicalPath: string;
  identity?: DatabasePathIdentity;
};
//#endregion
//#region src/config/sessions/session-transcript-anchor-read.types.d.ts
type SessionTranscriptAnchorEntry = Pick<InternalSessionEntry, "sessionId" | "updatedAt" | "lifecycleRevision" | "activeWriterRunId" | "cliHistoryBoundary" | "permissionMode">;
type SessionTranscriptAnchorFacts = {
  anchors: TranscriptEntryAnchor[];
  activePathRelation?: "exact" | "ancestor" | "off-path";
  session?: {
    sessionId: string;
    lifecycleRevision?: string;
  };
  header?: unknown;
  watermark?: SessionTranscriptWatermark;
  messagePresence?: boolean;
  metadata?: {
    present: boolean;
    observedAt: number | null;
    updatedAt: number | null;
  };
  contextValidated?: true;
  contextAuthority?: {
    entry?: SessionTranscriptAnchorEntry;
    watermark: SessionTranscriptWatermark;
  };
  replayValidated?: "current" | "initial";
  tail?: {
    lastSeq?: number;
    entries: {
      entryId: string;
      role: "user" | "assistant";
      runId?: string;
      anchor?: TranscriptEntryAnchor;
      message?: unknown;
    }[];
  };
};
//#endregion
//#region src/gateway/session-utils-store.types.d.ts
type GatewaySessionStoreTarget = {
  agentId: string;
  storePath: string;
  canonicalKey: string;
  storeKeys: string[];
};
type GatewaySessionStoreTargetWithStore = GatewaySessionStoreTarget & {
  canonicalValidationError?: Error;
  store: Record<string, InternalSessionEntry>;
  readSource?: SessionEntryReadSource;
  capturedReadSource?: CapturedSessionEntryReadSource;
  capturedReadSources?: CapturedSessionEntryReadSource[];
  lifecycleTimestamps?: SessionLifecycleTimestamps;
  transcript?: SessionTranscriptAnchorFacts;
};
//#endregion
//#region .artifacts/kysely/openclaw-agent-db.generated.d.ts
type Generated<T> = T extends ColumnType<infer S, infer I, infer U> ? ColumnType<S, I | undefined, U> : ColumnType<T, T | undefined, T>;
interface AcpParentStreamEvents {
  created_at: number;
  event_json: string;
  run_id: string;
  seq: number;
  session_id: string;
}
interface AuthProfileState {
  state_json: string;
  state_key: string;
  updated_at: number;
}
interface AuthProfileStore {
  store_json: string;
  store_key: string;
  updated_at: number;
}
interface BoardTabs {
  chat_dock: Generated<string>;
  created_by: string;
  position: number;
  revision: number;
  session_key: string;
  tab_id: string;
  title: string;
}
interface BoardWidgets {
  content_kind: string;
  created_at: number;
  created_by: string;
  descriptor_json: string | null;
  grant_state: Generated<string>;
  granted_sha: string | null;
  html: Uint8Array | null;
  manifest: Generated<string>;
  name: string;
  position: number;
  revision: number;
  session_key: string;
  sha256: string;
  size_h: number;
  size_w: number;
  tab_id: string;
  title: string | null;
  updated_at: number;
  view_generation: string | null;
}
interface CacheEntries {
  blob: Uint8Array | null;
  expires_at: number | null;
  key: string;
  scope: string;
  updated_at: number;
  value_json: string | null;
}
interface ContextEngineTurnOutbox {
  advancement_key: string;
  attempt_count: Generated<number>;
  created_at: number;
  engine_id: string;
  enqueue_sequence: Generated<number>;
  last_attempt_at: number | null;
  last_error: string | null;
  owner_plugin_id: string | null;
  payload_json: string;
  payload_state: string | null;
  session_id: string;
}
interface ConversationDeliveries {
  conversation_id: string;
  created_at: number;
  message_hash: string;
  operation_id: string;
  operation_kind: string;
  platform_message_id: string | null;
  prepared_message_id: string | null;
  queue_id: string | null;
  rejection_error: string | null;
  reply_message_id: string | null;
  reply_text: string | null;
  reply_thread_id: string | null;
  reply_timestamp: number | null;
  reply_to_id: string | null;
  source_session_key: string | null;
  status: string;
  updated_at: number;
}
interface Conversations {
  account_id: string;
  channel: string;
  conversation_id: string;
  created_at: number;
  delivery_target: string;
  kind: string;
  label: string | null;
  metadata_json: string | null;
  native_channel_id: string | null;
  native_direct_user_id: string | null;
  parent_conversation_id: string | null;
  peer_id: string;
  thread_id: string | null;
  updated_at: number;
}
interface HeartbeatOutcomes {
  context_claimed_at: number | null;
  context_run_id: string | null;
  next_check: string | null;
  occurred_at: number;
  outcome: string;
  priority: string | null;
  response_reason: string | null;
  run_session_key: string;
  session_key: string;
  summary: string;
  task_names_json: string | null;
  updated_at: number;
  wake_reason: string | null;
  wake_source: string | null;
}
interface MemoryEmbeddingCache {
  dims: number | null;
  embedding: Uint8Array;
  hash: string;
  model: string;
  provider: string;
  provider_key: string;
  updated_at: number;
}
interface MemoryEntryOrigins {
  agent_id: string;
  entry_key: string;
  observed_at: number;
  origin_class: string;
  session_id: string;
  session_key: string | null;
}
interface MemoryIndexChunkProvenance {
  chunk_id: string;
  observed_at: number;
  origin_class: string;
  session_kind: string;
  supersedes_key: string | null;
}
interface MemoryIndexChunkRecallMetadata {
  chunk_id: string;
  importance: number | null;
  project_key: string | null;
  triggers: string | null;
}
interface MemoryIndexChunks {
  chunk_rowid: Generated<number>;
  embedding: Uint8Array;
  end_line: number;
  hash: string;
  id: string;
  model: string;
  path: string;
  source: Generated<string>;
  start_line: number;
  text: string;
  updated_at: number;
}
interface MemoryIndexMeta {
  key: string;
  value: string;
}
interface MemoryIndexSources {
  hash: string;
  id: Generated<number>;
  mtime: number;
  path: string;
  size: number;
  source: Generated<string>;
}
interface MemoryIndexState {
  id: Generated<number>;
  revision: number;
}
interface MemorySessionTombstones {
  agent_id: string;
  created_at: number;
  reason: string;
  session_id: string;
}
interface MessageToolRunOutcomes {
  agent_id: string;
  id: Generated<number>;
  model: string;
  occurred_at: number;
  outcome: string;
  provider: string;
  run_id: string;
  run_status: string;
  session_key: string;
}
interface SchemaMeta {
  agent_id: string | null;
  app_version: string | null;
  created_at: number;
  meta_key: string;
  role: string;
  schema_version: number;
  updated_at: number;
}
interface SessionCanonicalValidationPending {
  session_key: string;
}
interface SessionConversations {
  conversation_id: string;
  first_seen_at: number;
  last_seen_at: number;
  role: Generated<string>;
  route_context_json: string | null;
  session_id: string;
}
interface SessionEntrySnapshots {
  field: string;
  session_key: string;
  value_json: string;
}
interface SessionGoalOperations {
  expires_at: number;
  operation_id: string;
  request_fingerprint: string;
  result_json: string;
  session_id: string;
  session_key: string;
}
interface SessionInputCompletions {
  completed_at: number;
  idempotency_key: string;
  outcome_json: string;
  request_hash: string;
  run_id: string;
  session_id: string;
  session_key: string;
  succeeded: number;
}
interface SessionKeyContract {
  canonical_ready: string | null;
  id: Generated<number>;
  main_key: string;
  updated_at: number;
}
interface SessionMembers {
  added_at: number;
  added_by: string;
  identity_id: string;
  session_key: string;
}
interface SessionNodes {
  archived_at: number | null;
  category: string | null;
  created_actor_id: string | null;
  created_actor_type: string | null;
  created_at: number | null;
  created_via: string | null;
  current_session_id: string;
  display_name: string | null;
  entry_json: string;
  entry_valid: Generated<number>;
  fork_source_entry_id: string | null;
  fork_source_session_id: string | null;
  fork_source_session_key: string | null;
  has_optional_references: Generated<number>;
  icon: string | null;
  label: string | null;
  last_activity_at: number | null;
  last_interaction_at: number | null;
  last_read_at: number | null;
  legacy_acp_migration_json: string | null;
  owner_actor_id: string | null;
  owner_actor_type: string | null;
  owner_assigned_at: number | null;
  owner_assigned_by_id: string | null;
  owner_assigned_by_type: string | null;
  parent_session_key: string | null;
  pinned_at: number | null;
  project_id: string | null;
  session_key: string;
  session_started_at: number | null;
  snapshot_revision: Generated<number>;
  spawned_by: string | null;
  status: string | null;
  updated_at: number;
}
interface SessionParticipants {
  actor_id: string;
  contribution_count: number;
  first_prompted_at: number | null;
  identity_namespace: string;
  last_prompted_at: number | null;
  session_key: string;
}
interface SessionPendingInputs {
  accepted_at: number;
  consumed_event_id: string | null;
  idempotency_key: string;
  input_id: string;
  lifecycle_generation: string;
  message_json: string;
  request_hash: string;
  run_id: string;
  seq: Generated<number>;
  session_id: string;
  session_key: string;
  state: string;
}
interface SessionProgressCards {
  created_at: number;
  markdown: string | null;
  revision: number;
  session_key: string;
  steps_json: string | null;
  updated_at: number;
}
interface SessionReactions {
  created_at: number;
  emoji: string;
  identity_id: string;
  identity_label: string | null;
  message_id: string;
  session_id: string;
  session_key: string;
}
interface SessionSuggestions {
  author_id: string;
  author_label: string | null;
  created_at: number;
  dispatch_resolution: string | null;
  dispatch_started_at: number | null;
  dispatch_token: string | null;
  id: string;
  session_key: string;
  state: string;
  text: string;
}
interface SessionTranscriptActiveEvents {
  active_position: number;
  context_eligible: number | null;
  event_seq: number;
  message_position: number | null;
  session_id: string;
}
interface SessionTranscriptArchives {
  archive_blob: Uint8Array;
  archive_name: string;
  archive_sha256: string;
  created_at: number;
  encoding: string;
  generation: string;
  last_publish_attempt_at: number | null;
  last_publish_error: string | null;
  publish_attempts: Generated<number>;
  published_at: number | null;
  reason: string;
  session_id: string;
  session_key: string;
}
interface SessionTranscriptColdArchiveChunks {
  archive_blob: Uint8Array | null;
  archive_bytes: number;
  archive_name: string;
  archive_sha256: string;
  chunk_index: number;
  event_count: number;
  first_seq: number;
  last_seq: number;
  raw_bytes: number;
  session_id: string;
}
interface SessionTranscriptColdArchives {
  archive_blob: Uint8Array | null;
  archive_bytes: number;
  archive_name: string;
  archive_sha256: string;
  archived_at: number;
  event_count: number;
  generation: string;
  last_seq: number;
  raw_bytes: number;
  session_id: string;
  storage: string;
}
interface SessionTranscriptFts {
  message_id: string | null;
  role: string | null;
  session_id: string | null;
  text: string | null;
  timestamp: string | null;
}
interface SessionTranscriptFtsConfig {
  k: string;
  v: string | null;
}
interface SessionTranscriptFtsContent {
  c0: string | null;
  c1: string | null;
  c2: string | null;
  c3: string | null;
  c4: string | null;
  id: Generated<number>;
}
interface SessionTranscriptFtsData {
  block: Uint8Array | null;
  id: Generated<number>;
}
interface SessionTranscriptFtsDocsize {
  id: Generated<number>;
  sz: Uint8Array | null;
}
interface SessionTranscriptFtsIdx {
  pgno: string | null;
  segid: string;
  term: string;
}
interface SessionTranscriptFtsRows {
  id: Generated<number>;
  message_id: string | null;
  session_id: string;
}
interface SessionTranscriptIndexState {
  active_event_count: Generated<number>;
  active_message_count: Generated<number>;
  indexed_seq: number;
  leaf_event_id: string | null;
  needs_rebuild: Generated<number>;
  session_id: string;
  updated_at: number;
}
interface SessionWindows {
  account_id: string | null;
  acp_owned: Generated<number>;
  agent_harness_id: string | null;
  channel: string | null;
  chat_type: string | null;
  created_at: number;
  display_name: string | null;
  ended_at: number | null;
  hook_external_content_source: string | null;
  model: string | null;
  model_provider: string | null;
  parent_session_key: string | null;
  plugin_owner_id: string | null;
  previous_session_id: string | null;
  primary_conversation_id: string | null;
  reason: string | null;
  row_transcript_json: string | null;
  row_transcript_updated_at: number | null;
  session_entry_provenance: Generated<number>;
  session_id: string;
  session_key: string;
  session_scope: Generated<string>;
  spawned_by: string | null;
  started_at: number | null;
  status: string | null;
  transcript_observed_at: Generated<number | null>;
  transcript_updated_at: Generated<number | null>;
  updated_at: number;
}
interface StandingIntents {
  channel_scope: string | null;
  cooldown_seconds: Generated<number>;
  created_at: number;
  creator_sender: string | null;
  description: string;
  expires_at: number;
  fire_count: Generated<number>;
  id: string;
  intent_key: Generated<number>;
  last_fired_at: number | null;
  max_fires: number;
  sender_scope: string | null;
  source_session_id: string | null;
  status: string;
  trigger_embedding: string | null;
  trigger_keywords: string;
}
interface StandingIntentsFts {
  trigger_keywords: string | null;
}
interface StandingIntentsFtsConfig {
  k: string;
  v: string | null;
}
interface StandingIntentsFtsData {
  block: Uint8Array | null;
  id: Generated<number>;
}
interface StandingIntentsFtsDocsize {
  id: Generated<number>;
  sz: Uint8Array | null;
}
interface StandingIntentsFtsIdx {
  pgno: string | null;
  segid: string;
  term: string;
}
interface TrajectoryRuntimeEvents {
  created_at: number;
  event_codec: string | null;
  event_json: string;
  event_payload: Uint8Array | null;
  event_utf8_bytes: number | null;
  run_id: string | null;
  seq: number;
  session_id: string;
}
interface TranscriptEventIdentities {
  created_at: number;
  event_id: string;
  event_type: string | null;
  message_idempotency_key: string | null;
  parent_id: string | null;
  seq: number;
  session_id: string;
}
interface TranscriptEvents {
  created_at: number;
  event_json: string | null;
  event_utf8_bytes: number | null;
  event_zstd: Uint8Array | null;
  message_role: string | null;
  navigation_custom_type: string | null;
  navigation_display: Generated<number>;
  navigation_json: string | null;
  navigation_last_custom_type: string | null;
  navigation_last_type: string | null;
  navigation_type: string | null;
  navigation_valid: Generated<number>;
  seq: number;
  session_id: string;
}
interface TranscriptRewriteWatermarks {
  generation: string;
  session_id: string;
  updated_at: number;
}
interface DB {
  acp_parent_stream_events: AcpParentStreamEvents;
  auth_profile_state: AuthProfileState;
  auth_profile_store: AuthProfileStore;
  board_tabs: BoardTabs;
  board_widgets: BoardWidgets;
  cache_entries: CacheEntries;
  context_engine_turn_outbox: ContextEngineTurnOutbox;
  conversation_deliveries: ConversationDeliveries;
  conversations: Conversations;
  heartbeat_outcomes: HeartbeatOutcomes;
  memory_embedding_cache: MemoryEmbeddingCache;
  memory_entry_origins: MemoryEntryOrigins;
  memory_index_chunk_provenance: MemoryIndexChunkProvenance;
  memory_index_chunk_recall_metadata: MemoryIndexChunkRecallMetadata;
  memory_index_chunks: MemoryIndexChunks;
  memory_index_meta: MemoryIndexMeta;
  memory_index_sources: MemoryIndexSources;
  memory_index_state: MemoryIndexState;
  memory_session_tombstones: MemorySessionTombstones;
  message_tool_run_outcomes: MessageToolRunOutcomes;
  schema_meta: SchemaMeta;
  session_canonical_validation_pending: SessionCanonicalValidationPending;
  session_conversations: SessionConversations;
  session_entry_snapshots: SessionEntrySnapshots;
  session_goal_operations: SessionGoalOperations;
  session_input_completions: SessionInputCompletions;
  session_key_contract: SessionKeyContract;
  session_members: SessionMembers;
  session_nodes: SessionNodes;
  session_participants: SessionParticipants;
  session_pending_inputs: SessionPendingInputs;
  session_progress_cards: SessionProgressCards;
  session_reactions: SessionReactions;
  session_suggestions: SessionSuggestions;
  session_transcript_active_events: SessionTranscriptActiveEvents;
  session_transcript_archives: SessionTranscriptArchives;
  session_transcript_cold_archive_chunks: SessionTranscriptColdArchiveChunks;
  session_transcript_cold_archives: SessionTranscriptColdArchives;
  session_transcript_fts: SessionTranscriptFts;
  session_transcript_fts_config: SessionTranscriptFtsConfig;
  session_transcript_fts_content: SessionTranscriptFtsContent;
  session_transcript_fts_data: SessionTranscriptFtsData;
  session_transcript_fts_docsize: SessionTranscriptFtsDocsize;
  session_transcript_fts_idx: SessionTranscriptFtsIdx;
  session_transcript_fts_rows: SessionTranscriptFtsRows;
  session_transcript_index_state: SessionTranscriptIndexState;
  session_windows: SessionWindows;
  standing_intents: StandingIntents;
  standing_intents_fts: StandingIntentsFts;
  standing_intents_fts_config: StandingIntentsFtsConfig;
  standing_intents_fts_data: StandingIntentsFtsData;
  standing_intents_fts_docsize: StandingIntentsFtsDocsize;
  standing_intents_fts_idx: StandingIntentsFtsIdx;
  trajectory_runtime_events: TrajectoryRuntimeEvents;
  transcript_event_identities: TranscriptEventIdentities;
  transcript_events: TranscriptEvents;
  transcript_rewrite_watermarks: TranscriptRewriteWatermarks;
}
//#endregion
//#region src/config/sessions/session-accessor.sqlite-delete-snapshot.types.d.ts
type SessionStateDeleteSnapshot = {
  acpParentStreamEventCount: number;
  generation: string | null;
  lastSeq: number | null;
  sessionKey: string | null;
  sessionUpdatedAt: number | null;
  trajectoryLastSeq: number | null;
  transcriptUpdatedAt: number | null;
};
//#endregion
//#region src/config/sessions/session-history-archive-pruning.types.d.ts
type PublishedSessionTranscriptArchive = {
  archive_name: string;
  archive_sha256: string;
  created_at: number;
  encoding: string;
  generation: string;
  published_at: number;
  reason: string;
  session_id: string;
  session_key: string;
};
type SessionLegacyArchiveRemovalResult = "removed" | "failed" | "preserved";
type SessionArchiveRetentionDelete = {
  candidates: readonly PublishedSessionTranscriptArchive[];
  archiveDirectory: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-archive-types.d.ts
type SessionColdArchive = Selectable<DB["session_transcript_cold_archives"]>;
type SessionStateDeletePlan = {
  agentId: string;
  archiveDirectory: string;
  archiveTranscript: boolean;
  databasePath: string;
  reason: "deleted" | "reset";
  sessionId: string;
  snapshot: SessionStateDeleteSnapshot;
};
type MaterializedSessionStateDeletePlan = SessionStateDeletePlan & {
  archive: MaterializedSessionTranscriptArchive | null;
  archivedTranscript: SessionLifecycleArchivedTranscript | null;
};
type MaterializedSessionTranscriptArchive = {
  archiveName: string;
  bytes: Uint8Array;
  createdAt: number;
  encoding: "identity" | "zstd";
  sha256: string;
};
type TranscriptArchivePublishPlan = {
  databaseIdentity?: string;
  agentId: string;
  archiveDirectory: string;
  databasePath: string;
  generation: string;
  sessionId: string;
};
type TranscriptArchivePublishResult = {
  archivedPath?: string;
  error?: string;
  generation: string;
  sessionId: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-contract.d.ts
type TranscriptWriteSnapshot<T> = {
  result: T;
  lifecycleRevision?: string;
  before: SessionTranscriptContextVersion;
  after: SessionTranscriptContextVersion;
};
type TranscriptMessageWriteSnapshot<TMessage> = TranscriptWriteSnapshot<TranscriptMessageAppendResult<TMessage> | undefined> & {
  visibleTail: {
    entryId: string | null;
    generation: string | null;
  };
};
type TranscriptEventAppendResult = {
  appended: false;
} | {
  appended: true;
  effectiveParentId?: string | null;
};
type CacheTtlProjectionPrefix = {
  anchorIds: string[];
  entries: Record<string, unknown>[];
};
type SessionTranscriptBoundedActiveContext = {
  activeLeafEntryId: string | null;
  version: SessionTranscriptContextVersion;
  opaqueParents: Map<string, string | null>;
  parents: Map<string, string | null>;
  firstKeptRanges: Map<string, {
    startIndex: number;
    endIndex: number;
  }>;
  persistedSuffixStartSeq: number;
  boundaryCount: number;
  events: TranscriptEvent[];
  cacheTtlProjectionPrefixes?: CacheTtlProjectionPrefix[];
  serializedBytes: number;
  totalEvents: number;
  transcriptMutationAt: number | null;
  truncated: boolean;
  /** Every indexed active entry is present, without a read fence or byte/event omission. */
  completeActivePath?: true;
};
type TranscriptEventAppendOptions = {
  appendIntent?: "active-branch";
  /** Synchronous authority check run inside the append transaction. */
  beforeCommitInTransaction?: () => void;
  /** Reject the append when the transcript changed since the caller loaded it. */
  expectedMutationAt?: number | null;
};
//#endregion
//#region src/config/sessions/session-entry-window.types.d.ts
declare const sessionEntryWindowColumns: readonly ["session_id", "session_key", "reason", "created_at", "updated_at", "session_entry_provenance", "acp_owned", "plugin_owner_id", "hook_external_content_source", "previous_session_id", "session_scope", "started_at", "ended_at", "status", "chat_type", "channel", "account_id", "model_provider", "model", "agent_harness_id", "parent_session_key", "spawned_by", "display_name", "primary_conversation_id", "transcript_observed_at", "transcript_updated_at"];
type SessionEntryWindowRow = Pick<Selectable<DB["session_windows"]>, (typeof sessionEntryWindowColumns)[number]>;
type SessionEntryWindowFacts = {
  sessionId: string;
  row: SessionEntryWindowRow | null;
};
//#endregion
//#region src/config/sessions/session-entry-storage.types.d.ts
type SessionEntryRow = Selectable<DB["session_nodes"]>;
type SqliteSessionOwnerRow = {
  owner_actor_type?: string | null;
  owner_actor_id?: string | null;
  owner_assigned_by_type?: string | null;
  owner_assigned_by_id?: string | null;
  owner_assigned_at?: number | null;
};
type SessionEntrySnapshotRow = {
  session_diff_baseline_json?: string | null;
  skills_snapshot_json?: string | null;
  system_prompt_report_json?: string | null;
};
type ResolvedSessionEntryRow = {
  entry: InternalSessionEntry;
  row: Pick<SessionEntryRow, "current_session_id" | "entry_json" | "session_key" | "updated_at"> & SqliteSessionOwnerRow & SessionEntrySnapshotRow & Partial<Pick<SessionEntryRow, "legacy_acp_migration_json">> & {
    board_present?: SqlBool;
    member_ids_json?: string;
    participant_identities_json?: string;
    row_transcript_window_id?: string | null;
    row_transcript_json?: string | null;
    row_transcript_updated_at?: number | null;
    row_transcript_source_updated_at?: number | null;
    row_transcript_indexed_seq?: number | null;
    window?: SessionEntryWindowRow | null;
    transcriptWatermark?: SessionTranscriptWatermark & {
      sessionId: string;
    };
  };
};
//#endregion
//#region src/config/sessions/session-entry-snapshot-values.d.ts
declare const sessionEntrySnapshotColumnsDefinition: readonly [readonly ["sessionDiffBaseline", "session_diff_baseline_json"], readonly ["skillsSnapshot", "skills_snapshot_json"], readonly ["systemPromptReport", "system_prompt_report_json"]];
type SessionEntrySnapshotField = (typeof sessionEntrySnapshotColumnsDefinition)[number][0];
type SessionEntryProjection = "full" | "list" | readonly SessionEntrySnapshotField[];
//#endregion
//#region src/config/sessions/session-accessor.sqlite-replacement-read.d.ts
type SessionEntryReplacementSelection = {
  sessionKeys?: readonly string[];
  includeSessionWindowOwner?: string;
  includeLabelOwners?: string;
};
type SessionEntryReplacementState = {
  entries: SessionEntryReplacementSnapshot[];
  expectedRows: Map<string, ResolvedSessionEntryRow>;
  labelOwnerKeys: string[];
  selectedSessionKeys?: string[];
};
//#endregion
//#region src/config/sessions/session-canonical-key.d.ts
type CanonicalSessionReaderContinuation = {
  agentId: string;
  identity: string;
  birthtime: string | undefined;
  mainKey: string;
  canonicalReady: boolean;
  validation: OpenClawAgentDatabaseValidation;
  live: SharedArrayBuffer;
};
//#endregion
//#region packages/agent-core/src/runtime-deps.d.ts
/** Runtime functions injected by host packages so agent-core stays provider-agnostic. */
interface AgentCoreRuntimeDeps {
  /** Streaming completion implementation used for normal agent turns. */
  streamSimple: StreamFn;
  /** Non-streaming completion implementation used by summarization helpers. */
  completeSimple: CompleteSimpleFn;
  /** Keep host stream ownership through iteration and decorated terminal work. */
  runStream?: <T>(stream: ReturnType<StreamFn>, consume: () => T) => T;
  /** Local host failures must propagate without synthesizing a provider response. */
  isLocalError?: (error: unknown) => boolean;
}
/** Runtime dependency subset required by streaming agent loops. */
type AgentCoreStreamRuntimeDeps = Pick<AgentCoreRuntimeDeps, "streamSimple" | "runStream" | "isLocalError">;
//#endregion
//#region packages/agent-core/src/agent.d.ts
/** Options for constructing an {@link Agent}. */
interface AgentOptions {
  /** Initial transcript, tools, model, and prompt state. */
  initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
  /** Convert agent-owned transcript messages into provider-facing messages. */
  convertToLlm?: AgentLoopConfig["convertToLlm"];
  /** Optionally rewrite context before each provider request. */
  transformContext?: NonNullable<AgentLoopConfig["transformContext"]>;
  /** Injected stream runtime used when streamFn is not supplied. */
  runtime?: AgentCoreStreamRuntimeDeps;
  /** Explicit stream implementation, preferred over runtime.streamSimple. */
  streamFn?: StreamFn$1;
  /** Resolve provider API keys at request time. */
  getApiKey?: NonNullable<AgentLoopConfig["getApiKey"]>;
  /** Inspect the provider payload before it is sent. */
  onPayload?: SimpleStreamOptions["onPayload"];
  /** Inspect the provider response after it returns. */
  onResponse?: SimpleStreamOptions["onResponse"];
  /** Hook that may short-circuit or alter a tool call before execution. */
  beforeToolCall?: NonNullable<AgentLoopConfig["beforeToolCall"]>;
  /** Hook that may hydrate a deferred authorized tool call into an executable tool. */
  resolveDeferredTool?: AgentLoopConfig["resolveDeferredTool"];
  /** Hook that may alter a tool result after execution. */
  afterToolCall?: NonNullable<AgentLoopConfig["afterToolCall"]>;
  /** Hook that may alter any finalized tool outcome, including pre-execution failures. */
  afterToolOutcome?: NonNullable<AgentLoopConfig["afterToolOutcome"]>;
  /** Hook that may update model, reasoning, or context after a turn. */
  prepareNextTurn?: (signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
  /** Context-aware turn hook. Takes precedence over `prepareNextTurn` when both are provided. */
  prepareNextTurnWithContext?: (context: PrepareNextTurnContext, signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
  /** Queue drain mode for steering messages applied at tool or model checkpoints. */
  steeringMode?: QueueMode$1;
  /** Queue drain mode for follow-up messages injected after the agent would otherwise stop. */
  followUpMode?: QueueMode$1;
  /** Session identifier forwarded to cache-aware providers. */
  sessionId?: string;
  /** Optional per-thinking-level token budgets forwarded to providers. */
  thinkingBudgets?: ThinkingBudgets;
  /** Preferred provider transport. */
  transport?: Transport;
  /** Optional cap for provider-requested retry delays. */
  maxRetryDelayMs?: number;
  /** Default strategy for executing multiple tool calls in one assistant message. */
  toolExecution?: ToolExecutionMode;
}
/**
 * Stateful wrapper around the low-level agent loop.
 *
 * `Agent` owns the current transcript, emits lifecycle events, executes tools,
 * and exposes queueing APIs for steering and follow-up messages.
 */
declare class Agent$2 {
  private mutableState;
  private preparedSystemPrompt?;
  private readonly listeners;
  private readonly steeringQueue;
  private readonly followUpQueue;
  private toolLoopRecoveryState;
  convertToLlm: NonNullable<AgentOptions["convertToLlm"]>;
  transformContext?: NonNullable<AgentOptions["transformContext"]>;
  runtime?: AgentCoreStreamRuntimeDeps;
  streamFn: StreamFn$1;
  getApiKey?: NonNullable<AgentOptions["getApiKey"]>;
  onPayload?: AgentOptions["onPayload"];
  onResponse?: AgentOptions["onResponse"];
  beforeToolCall?: NonNullable<AgentOptions["beforeToolCall"]>;
  resolveDeferredTool?: AgentOptions["resolveDeferredTool"];
  afterToolCall?: NonNullable<AgentOptions["afterToolCall"]>;
  afterToolOutcome?: NonNullable<AgentOptions["afterToolOutcome"]>;
  prepareNextTurn?: NonNullable<AgentOptions["prepareNextTurn"]>;
  prepareNextTurnWithContext?: NonNullable<AgentOptions["prepareNextTurnWithContext"]>;
  private activeRun?;
  /** Session identifier forwarded to providers for cache-aware backends. */
  sessionId?: string;
  /** Optional per-level thinking token budgets forwarded to the stream function. */
  thinkingBudgets?: ThinkingBudgets;
  /** Preferred transport forwarded to the stream function. */
  transport: Transport;
  /** Optional cap for provider-requested retry delays. */
  maxRetryDelayMs?: number;
  /** Tool execution strategy for assistant messages that contain multiple tool calls. */
  toolExecution: ToolExecutionMode;
  constructor(options?: AgentOptions);
  /**
   * Subscribe to agent lifecycle events.
   *
   * Listener promises are awaited in subscription order and are included in
   * the current run's settlement. Listeners also receive the active abort
   * signal for the current run.
   *
   * `agent_end` is the final emitted event for a run, but the agent does not
   * become idle until all awaited listeners for that event have settled.
   */
  subscribe(listener: (event: AgentEvent$1, signal: AbortSignal) => Promise<void> | void): () => void;
  /**
   * Current agent state.
   *
   * Assigning `state.tools` or `state.messages` copies the provided top-level array.
   */
  get state(): AgentState;
  /** Controls how queued steering messages are drained. */
  set steeringMode(mode: QueueMode$1);
  get steeringMode(): QueueMode$1;
  /** Controls how queued follow-up messages are drained. */
  set followUpMode(mode: QueueMode$1);
  get followUpMode(): QueueMode$1;
  /**
   * Queue a message for the active run. After its first tool starts, an assistant
   * message's unstarted sequential tail can be skipped. Parallel batches always run.
   */
  steer(message: AgentMessage): void;
  /** Install admitted input synchronously; notify listeners after admission custody ends. */
  admitSteeringMessage(message: AgentMessage): () => void;
  /** Cancel queued input unless a live provider response may already have admitted it. */
  cancelSteeringMessage(predicate: (message: AgentMessage) => boolean): AgentMessage | undefined;
  /** Queue a message to run only after the agent would otherwise stop. */
  followUp(message: AgentMessage): void;
  /** Remove queued steering messages that have not been submitted to a live response. */
  clearSteeringQueue(): void;
  /** Remove all queued follow-up messages. */
  clearFollowUpQueue(): void;
  /** Remove all queued steering and follow-up messages. */
  clearAllQueues(): void;
  /** Returns true when either queue contains pending input that can start a turn. */
  hasQueuedMessages(): boolean;
  /** Active abort signal for the current run, if any. */
  get signal(): AbortSignal | undefined;
  /** Abort the current run, if one is active. */
  abort(reason?: unknown): void;
  /**
   * Resolve when the current run and all awaited event listeners have finished.
   *
   * This resolves after `agent_end` listeners settle.
   */
  waitForIdle(): Promise<void>;
  /** Clear transcript state, runtime state, and queued messages. */
  reset(): void;
  /** Start a new prompt from text, a single message, or a batch of messages. */
  prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
  prompt(input: string, images?: ImageContent$1[]): Promise<void>;
  /** Continue from a user, tool result, or failed assistant without rewriting its history. */
  continue(): Promise<void>;
  private runPromptMessages;
  private createLoopConfig;
  /**
   * Reduce internal state for a loop event, then await listeners.
   *
   * `agent_end` only means no further loop events will be emitted. The run is
   * considered idle later, after all awaited listeners for `agent_end` finish
   * and run cleanup clears runtime-owned state.
   */
  private processEvents;
}
//#endregion
//#region packages/agent-core/src/errors.d.ts
/** A tool rejected model-authored arguments during prepareArguments, before execution. */
declare class ToolArgumentValidationError extends Error {
  constructor(message: string, options?: ErrorOptions);
}
//#endregion
//#region packages/agent-core/src/harness/types.d.ts
interface SessionTreeEntryBase {
  id: string;
  parentId: string | null;
  timestamp: string;
  appendMode?: "side";
}
type SessionTreeEntry = SessionTreeEntryBase & ({
  type: "message";
  message: AgentMessage;
} | {
  type: "thinking_level_change";
  thinkingLevel: string;
} | {
  type: "model_change";
  provider: string;
  modelId: string;
} | {
  type: "compaction";
  summary: string;
  firstKeptEntryId: string;
  tokensBefore: number;
  details?: unknown;
  fromHook?: boolean;
} | {
  type: "reset";
  reason: "new" | "reset" | "idle" | "daily" | "cron-stale";
  firstKeptEntryId?: string;
} | {
  type: "branch_summary";
  fromId: string;
  summary: string;
  details?: unknown;
  fromHook?: boolean;
} | {
  type: "custom";
  customType: string;
  data?: unknown;
} | {
  type: "custom_message";
  customType: string;
  content: string | (TextContent | ImageContent$1)[];
  details?: unknown;
  display: boolean;
  excludeFromContext?: boolean;
} | {
  type: "label";
  targetId: string;
  label: string | undefined;
} | {
  type: "session_info";
  name?: string;
} | {
  type: "leaf";
  targetId: string | null;
  appendParentId?: string | null;
});
interface SessionContext$1 {
  messages: AgentMessage[];
  thinkingLevel: string;
  model: {
    provider: string;
    modelId: string;
  } | null;
}
interface FileOperations {
  read: Set<string>;
  written: Set<string>;
  edited: Set<string>;
}
//#endregion
//#region packages/agent-core/src/harness/compaction/compaction-details.d.ts
/** File-operation details stored on generated compaction entries. */
interface CompactionDetails {
  /** Files read in the compacted history. */
  readFiles: string[];
  /** Files modified in the compacted history. */
  modifiedFiles: string[];
  /** Run-owned request that remains active across another compaction generation. */
  latestUnresolvedUserRequest?: string;
  /** The best available summary was committed without passing the safeguard audit. */
  qualityDegraded?: true;
}
//#endregion
//#region packages/agent-core/src/harness/compaction/compaction.d.ts
/** Generated compaction data ready to be persisted as a compaction entry. */
interface CompactionResult<T = unknown> {
  /** Summary text that replaces compacted history in future context. */
  summary: string;
  /** Entry id where retained history starts. */
  firstKeptEntryId: string;
  tokensBefore: number;
  /** Optional implementation-specific details stored with the compaction entry. */
  details?: T;
}
interface CompactionSettings$1 {
  /** Persisted summary character ceiling; omission preserves the 16,000-character default. */
  maxSummaryChars?: number;
  /** Enable automatic compaction decisions. */
  enabled: boolean;
  /** Tokens reserved for summary prompt and output. */
  reserveTokens: number;
  /** Approximate recent-context tokens to keep after compaction. */
  keepRecentTokens: number;
}
interface CompactionPreparation {
  /** Remaining foreground summary tokens, independent of the summarizer's context window. */
  summaryTokenBudget?: number;
  /** Entry id where retained history starts. */
  firstKeptEntryId: string;
  /** Messages summarized into the history summary. */
  messagesToSummarize: AgentMessage[];
  /** Prefix messages summarized separately when compaction splits a turn. */
  turnPrefixMessages: AgentMessage[];
  isSplitTurn: boolean;
  /** Run-owner selection; absent for legacy callers that infer from transcript history. */
  requestSelection?: {
    state: "unresolved";
    request: string;
  } | {
    state: "none";
  };
  /** Bounded unresolved request projected for existing extension consumers. */
  latestUnresolvedUserRequest?: string;
  tokensBefore: number;
  /** Previous compaction summary used for iterative updates. */
  previousSummary?: string;
  /** File metadata already appended to the previous compaction summary. */
  previousSummaryDetails?: CompactionDetails;
  /** File operations extracted from summarized history. */
  fileOps: FileOperations;
  settings: CompactionSettings$1;
}
//#endregion
//#region packages/agent-core/src/harness/utils/truncate.d.ts
/** Result metadata for content truncated by line count, byte count, or both. */
interface TruncationResult {
  /** The truncated content */
  content: string;
  /** Whether truncation occurred */
  truncated: boolean;
  /** Which limit was hit: "lines", "bytes", or null if not truncated */
  truncatedBy: "lines" | "bytes" | null;
  /** Total number of lines in the original content */
  totalLines: number;
  /** Total number of bytes in the original content */
  totalBytes: number;
  /** Number of complete lines in the truncated output */
  outputLines: number;
  /** Number of bytes in the truncated output */
  outputBytes: number;
  /** Whether the text-page owner retained a partial display line. */
  lastLinePartial: boolean;
  /** Whether the first line exceeded the byte limit (for head truncation) */
  firstLineExceedsLimit: boolean;
  /** The max lines limit that was applied */
  maxLines: number;
  /** The max bytes limit that was applied */
  maxBytes: number;
}
//#endregion
//#region src/config/sessions/session-accessor.sqlite-scope-helpers.d.ts
type ResolvedSqliteScope = {
  agentId: string;
  databaseAgentId?: string;
  env?: NodeJS.ProcessEnv;
  ownerStorePath?: string;
  path?: string;
  sessionKey: string;
};
type ResolvedSqliteReadScope = Omit<ResolvedSqliteScope, "sessionKey"> & {
  sessionKey?: string;
};
type ResolvedTranscriptScope = ResolvedSqliteScope & {
  sessionId: string;
};
type ResolvedTranscriptReadScope = ResolvedSqliteReadScope & {
  sessionId: string;
};
//#endregion
//#region src/config/sessions/session-sqlite-target.d.ts
/** SQLite database target resolved from a legacy session store path. */
type ResolvedSqliteStoreTarget = {
  agentId?: string;
  ownerSource?: "database-registry" | "database-path" | "registered-suffixed" | "occupied-unsuffixed" | "configured-default" | "ambiguous-registry";
  path: string;
  shared?: boolean;
  unsuffixedOwnerAgentId?: string;
};
type ResolveSqliteStoreTargetOptions = {
  agentId?: string;
  defaultAgentId?: string;
  env?: NodeJS.ProcessEnv;
  registeredDatabases?: SessionStoreRegistryRead;
  isSameDatabasePath?: (left: string, right: string) => boolean;
  readCandidates?: readonly SessionStoreReadCandidate[];
  /** Reports ordinary locator data failures, never candidate custody or native cleanup. */
  onReadError?: (error: unknown) => never;
};
type SessionStoreRegistryRead = readonly Pick<OpenClawRegisteredAgentDatabase, "agentId" | "path">[] | {
  status: "deferred" | "unavailable";
};
/** Resolves the SQLite database target that owns a legacy session store path. */
declare function resolveSqliteTargetFromSessionStorePath(storePath: string, options?: ResolveSqliteStoreTargetOptions): ResolvedSqliteStoreTarget;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-read-scope.d.ts
type SessionSqliteTargetResolutionCache = Map<NodeJS.ProcessEnv | undefined, Map<string, ReturnType<typeof resolveSqliteTargetFromSessionStorePath>>>;
declare function resolveSqliteTranscriptReadScope(scope: Pick<SessionTranscriptReadScope, "agentId" | "env" | "sessionId" | "sessionKey" | "storePath">, targetCache?: SessionSqliteTargetResolutionCache): ResolvedTranscriptReadScope;
//#endregion
//#region src/chat/transcript-display-position.d.ts
type TranscriptDisplayPosition = {
  source: string;
  rawSeq: number;
  activity?: {
    afterRawSeq: number | null;
    scopeId: string;
    startOrder: number;
  };
};
//#endregion
//#region src/sessions/transcript-read-window.d.ts
/** Internal continuity facts for history pages read in separate SQLite snapshots. */
type TranscriptReadWindow = {
  source: string | undefined;
  latestResetRawSeq: number | null;
  anchor?: {
    rawSeq: number;
    seq: number;
  };
};
type TranscriptReadWindowOptions = {
  captureReadWindow?: boolean;
  expectedReadWindow?: TranscriptReadWindow;
};
//#endregion
//#region src/config/sessions/session-transcript-projection-append.d.ts
type SessionTranscriptProjectionCursor = {
  activeEventCount: number;
  activeMessageCount: number;
  indexedSeq: number;
  leafEventId: string | null;
};
type SessionTranscriptProjectionState = SessionTranscriptProjectionCursor & {
  needsRebuild: boolean;
};
//#endregion
//#region src/config/sessions/session-transcript-projection-facts.types.d.ts
/** Complete eligible metadata for a bounded, boundary-free active path. No event bodies. */
type SessionTranscriptContextMetadata = {
  header: {
    seq: number;
    navigation_valid: number;
    serialized_bytes: number;
  } | undefined;
  rows: Array<{
    event_seq: number;
    active_position: number;
    serialized_bytes: number;
  }>;
  boundaryCount: 0;
  eventCount: number;
  sizeBytes: number;
};
/** Exact context totals; the actor updates these independently of its bounded row window. */
type SessionTranscriptContextStats = {
  eventCount: number;
  sizeBytes: number;
  boundaryActivePosition: number;
};
/** Small projection metadata; transcript bodies stay with the history reader. */
type SessionTranscriptProjectionFacts = {
  cold: boolean;
  generation: string | undefined;
  updatedAt: number | null;
  hasUnclassified: boolean;
  latestIndexedReset: {
    active_position: number;
    event_id: string;
    event_type: "reset";
    seq: number;
  } | null;
  hasUnindexedPrefix: boolean;
  latestSeq: number | null;
  state?: SessionTranscriptProjectionState;
  contextMetadata?: SessionTranscriptContextMetadata;
};
//#endregion
//#region src/config/sessions/transcript-predicate-fields.d.ts
type TranscriptPredicateFields = {
  navigation_type: string | null;
  navigation_custom_type: string | null;
  navigation_display: number;
  message_role: string | null;
  navigation_last_type: string | null;
  navigation_last_custom_type: string | null;
  navigation_valid: number;
};
//#endregion
//#region src/config/sessions/transcript-payload.d.ts
type TranscriptPayloadRecord = TranscriptPredicateFields & {
  event_json: string | null;
  event_zstd: Uint8Array | null;
  event_utf8_bytes: number | null;
  navigation_json: string | null;
};
type PreparedTranscriptPayload = {
  eventJson: string;
  storageEncoding: string;
  payload: TranscriptPayloadRecord;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-projection-read.d.ts
type SessionTranscriptMessageEvent = {
  event: TranscriptEvent;
  eventSeq: number;
  seq: number;
  displayPosition?: TranscriptDisplayPosition;
};
type SessionTranscriptMessageEventPage = {
  /** Source offset for the next older bounded page, independent of rendered message count. */
  olderOffset?: number;
  /** One source event exceeded a strict page byte limit and was skipped. */
  omittedOversized?: boolean;
  activeLeafEntryId?: string | null;
  deltaCursor?: string;
  displaySource?: string;
  readWindow?: TranscriptReadWindow;
  windowReset?: boolean;
  events: SessionTranscriptMessageEvent[];
  totalMessages: number;
};
type SessionTranscriptBoundedMessageTailPage = SessionTranscriptMessageEventPage & {
  /** Role-matched individual oversized messages in the requested check range. */
  hasOversizedMessages?: boolean;
  newestContiguousEventCount: number;
  scannedMessages: number;
  serializedBytes: number;
  snapshot: {
    boundarySeq?: number;
    generation?: string;
    indexedSeq: number;
  };
};
type SessionTranscriptBoundedMessageTailOptions = {
  maxBytes: number;
  maxMessages: number;
  offset: number;
  readOnly?: boolean;
  oversizedMessageCheck?: {
    roles: readonly string[];
    includeEarlier?: boolean;
  };
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-transcript-anchor.d.ts
type TranscriptSourceAuthority = Pick<InternalSessionEntry, "permissionMode" | "lifecycleRevision">;
//#endregion
//#region src/config/sessions/conversation-registry.types.d.ts
type ConversationRecord = {
  conversationRef: string;
  channel: string;
  accountId: string;
  kind: ChatType;
  peerId: string;
  target: string;
  parentConversationRef?: string;
  threadId?: string;
  nativeChannelId?: string;
  nativeDirectUserId?: string;
  label?: string;
  sessionId?: string;
  sessionKey?: string;
  role?: "participant" | "primary" | "related";
  /** True when this address has been linked to a session in this agent store. */
  observedFromSession?: true;
  /** Exact contextual facts from the authoritative inbound route. */
  routeContext?: ConversationRouteContext;
  /** True when authoritative ingress observed empty or populated route context. */
  routeContextObserved?: true;
  firstSeenAt: number;
  lastSeenAt: number;
};
type ConversationReadQuery = {
  channel?: string;
  deliveryAddress?: {
    accountId: string;
    target: string;
    threadId?: string;
  };
  conversationRef?: string;
  conversationRefs?: readonly string[];
  limit?: number;
  primarySession?: {
    sessionId: string;
    sessionKey: string;
  };
  currentBindingOnly?: boolean;
  currentSession?: {
    sessionKey: string;
    sessionId: string;
  };
};
//#endregion
//#region src/config/sessions/session-history-read.types.d.ts
type SessionTitleFields = {
  firstUserMessage: string | null;
  lastMessagePreview: string | null;
};
type SessionPreviewItem = {
  role: "user" | "assistant" | "tool" | "system" | "other";
  text: string;
};
type SessionBranchSummarySnapshot = SessionTranscriptWatermark & {
  branches: SessionBranchSummary[];
  appendSafe?: boolean;
  source?: {
    sessionId: string;
    databaseIdentity: string;
  };
};
type SessionBranchSummaryReadResult = ({
  status: "ok";
} & SessionBranchSummarySnapshot) | {
  status: "missing-session" | "failed";
};
type SessionModelContextLimits = {
  maxBytes: number;
  maxEvents: number;
  /** Model views may omit result bodies to retain earlier requests; evidence and forks stay strict. */
  toolResultOverflow?: "omit";
};
/** Compaction keeps the complete semantic window, independent of replay byte limits. */
type SessionTranscriptContextSelection = {
  maxBytes: number;
  maxEvents: number;
} | {
  compaction: true;
};
type SessionTranscriptModelContext = {
  events: TranscriptEvent[];
  version?: SessionTranscriptContextVersion;
};
type SessionTranscriptReadSnapshot = {
  events: TranscriptEvent[];
  eventJson?: string[];
  eventSeqs?: number[];
  version: SessionTranscriptContextVersion;
};
type SessionTranscriptContextSnapshot = {
  messages: AgentMessage[];
  header: unknown;
  version?: SessionTranscriptContextVersion;
  seed?: {
    omittedCount: number;
    omittedNonSummary: boolean;
    retainedInputTokens: number;
    admittedUser?: AgentMessage;
    summary?: AgentMessage;
  };
};
/** Internal native-seed view; full-fidelity context reads remain unbounded. */
type SessionContextSeedRequest = {
  maxBytes: number;
  tokenBudget: number;
  admittedKey?: string;
  beforeAdmittedUser: boolean;
};
type SessionCompactionPreparation = {
  sessionTarget: SessionTranscriptRuntimeTarget;
  /** Gateway lifecycle and accounting retain the originally selected key. */
  entry: InternalSessionEntry | undefined;
  runtimeEntry: InternalSessionEntry | undefined;
  primaryConversation: ConversationRecord | undefined;
};
type PreparedSessionTranscriptHydration = {
  kind: "full";
  snapshot: SessionTranscriptReadSnapshot;
} | {
  kind: "bounded";
  snapshot: SessionTranscriptBoundedActiveContext;
  transcript?: SessionTranscriptAnchorFacts;
  /** Byte and sequence facts for the actor's bounded context residency. */
  residentRows?: Array<{
    rawSeq: number;
    serializedBytes: number;
  }>;
  /** Compaction reads its session facts in the same snapshot as its bounded view. */
  compaction?: SessionCompactionPreparation;
};
type SessionPendingInputReceipt = {
  runId: string;
  state: "pending";
  cancelled?: true;
} | {
  runId: string;
  state: "consumed";
  consumedByEventId: string;
};
type SessionTranscriptEventMatch = {
  kind: "latest";
} | {
  kind: "canvas-widget";
  docId: string;
} | {
  kind: "visible-final";
  runId: string;
} | {
  kind: "idempotency";
  key: string;
  assistant?: boolean;
  runId?: string;
  deliveryMirror?: boolean;
} | {
  kind: "active-assistant";
  runId: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-model-context.d.ts
type TranscriptContextValidation = {
  version?: SessionTranscriptContextVersion;
  admission?: UserTurnTranscriptAdmissionReceipt;
  through?: TranscriptEntryAnchor;
  expectedAuthority?: TranscriptSourceAuthority;
};
/** Validate detached context using the final reader's transaction-local facts. */
declare function validateSessionTranscriptContextInDatabase(database: Pick<OpenClawAgentDatabase, "db" | "path">, resolved: ReturnType<typeof resolveSqliteTranscriptReadScope>, validation: TranscriptContextValidation, consistency?: "exact" | "prefix"): void;
//#endregion
//#region src/config/sessions/session-transcript-anchor-read.kernel.d.ts
type SessionTranscriptAnchorSelection = {
  entryIds: readonly string[];
  activePathEntryId?: string | null;
  afterSeq?: number;
  /** Payload selection stays in the history lane and shares the anchor snapshot. */
  includeMessagesForRunId?: string;
  includeSession?: boolean;
  includeHeader?: boolean;
  includeWatermark?: boolean;
  includeMessagePresence?: boolean;
  includeMetadata?: boolean;
  contextValidation?: Parameters<typeof validateSessionTranscriptContextInDatabase>[2];
  contextAuthority?: true | {
    permissionMode: InternalSessionEntry["permissionMode"];
  };
  replayValidation?: Pick<SessionTranscriptWriteScope, "expectedLifecycleRevision" | "expectedWriterRunId"> & {
    allowInitial: boolean;
    admission?: UserTurnTranscriptAdmissionReceipt;
  };
};
//#endregion
//#region src/state/openclaw-agent-db-readonly-open.d.ts
type OpenClawAgentReadOnlyDatabase = {
  agentId: string;
  db: EngineConnection;
  path: string;
};
type OpenClawAgentDatabaseReadOnlyResult<T> = {
  found: true;
  value: T;
} | {
  found: false;
  reason: "database-missing" | "schema-missing";
};
//#endregion
//#region src/config/sessions/session-transcript-projection-error.d.ts
declare class SessionTranscriptStorageUnavailableError extends Error {
  readonly reason?: Extract<OpenClawAgentDatabaseReadOnlyResult<never>, {
    found: false;
  }>["reason"] | undefined;
  constructor(reason?: Extract<OpenClawAgentDatabaseReadOnlyResult<never>, {
    found: false;
  }>["reason"] | undefined);
}
//#endregion
//#region src/config/sessions/session-transcript-worker-error.types.d.ts
type SessionTranscriptWorkerReadError = {
  kind: "read-error";
  message: string;
  payload: OpenClawStateWorkerErrorPayload;
} | {
  kind: "cold";
  sessionId: string;
} | {
  kind: "projection";
  sessionId: string;
  reason?: "window-changed";
} | {
  kind: "fence";
  message: string;
} | {
  kind: "syntax";
  message: string;
} | {
  kind: "jsonl-budget";
  message: string;
} | {
  kind: "storage";
  reason?: SessionTranscriptStorageUnavailableError["reason"];
};
//#endregion
//#region src/config/sessions/session-entry-read.types.d.ts
type SessionEntryReadWorkerInput = {
  kind: "session-entry-read";
  database: {
    agentId: string;
    path: string;
  };
  scope: SessionEntryReadScope & {
    databaseAgentId: string;
  };
  continuation?: CanonicalSessionReaderContinuation;
};
type SessionEntryReadWorkerResult = {
  kind: "session-entry-read";
  source?: CapturedSessionEntryReadSource & {
    databaseIdentity: string;
  };
} & ({
  entry: InternalSessionEntry | undefined;
  readError?: never;
  facts?: SessionExactEntriesWorkerResult;
} | {
  entry: undefined;
  readError: SessionTranscriptWorkerReadError;
  facts?: never;
});
type SessionEntryListWorkerInput = {
  kind: "session-entry-list";
  database: {
    agentId: string;
    path: string;
  };
  scope: SessionEntryListScope & {
    cleanupSession?: string;
  };
  expectedIdentity?: DatabasePathIdentity;
  continuation?: CanonicalSessionReaderContinuation;
  ifRevision?: string;
};
type SessionEntryListWorkerResult = {
  kind: "session-entry-list";
  entries: SessionEntrySummary[];
  source?: CapturedSessionEntryReadSource & {
    databaseIdentity: string;
  };
  revision?: string;
  unchanged?: true;
  /** Oldest cron run in the requested logical agent; null means no run rows. */
  nextCronRunUpdatedAt?: number | null;
  /** Last scanned cron key when another retention page may remain. */
  nextCronRunSessionKey?: string | null;
};
type SessionExactEntriesWorkerSelection = {
  sessionKeys: readonly string[];
  selection?: never;
  projection?: "full" | "sharing" | "replacement" | "creation" | "list" | "lifecycle" | "exact" | "worktree";
} | {
  sessionKeys?: never;
  selection: {
    kind: "session-id";
    sessionId: string;
    orderBy?: "updatedAt";
  };
  projection: "sharing" | "full";
} | {
  sessionKeys?: never;
  selection: {
    kind: "children";
    parentSessionKeys: readonly string[];
  };
  projection: "list" | "full";
} | {
  sessionKeys?: never;
  selection: {
    kind: "session-id-or-key";
    sessionIdOrKey: string;
  } | {
    kind: "label";
    label: string;
  };
  projection: "list";
};
type SessionExactEntriesWorkerRequest = (SessionExactEntriesWorkerSelection | {
  sessionKeys: readonly string[];
  selection: {
    kind: "transcript-aliases";
    sessionIds: readonly string[];
  };
  projection: "list";
}) & {
  /** Validate current entry and conversation predicates in one reader snapshot. */
  sourceChecks?: SessionSourcePredicate[];
  manualCompact?: {
    sessionId: string;
    sources: SessionSourcePredicate[];
  };
  expectedIdentity?: SessionEntryListWorkerInput["expectedIdentity"];
  /** Omitted retains the complete entry; an empty selection reads metadata only. */
  snapshotFields?: readonly SessionEntrySnapshotField[];
  env: NodeJS.ProcessEnv;
  lifecycleSessionKey?: string;
  /** Reply initialization reads the current row's model parent in this same snapshot. */
  replyInitializationSessionKey?: string;
  includeMembers?: boolean;
  includeParticipantRecords?: boolean;
  includeAuthorization?: boolean;
  /** Admission class only: the transport uses the reserved lane and never sends this field. */
  pointRead?: true;
  /** Inspect authority facts without opening the original SQLite family. */
  preserveSourceArtifacts?: true;
  inspectionSourcePath?: string;
  replacementSelection?: SessionEntryReplacementSelection;
  creationLabel?: string;
  continuation?: CanonicalSessionReaderContinuation;
  transcript?: Omit<SessionTranscriptAnchorSelection, "afterSeq" | "includeMessagesForRunId"> & {
    sessionKey: string;
    /** Captured logical owner; the executor still selects the physical database. */
    agentId?: string;
  };
};
/** Bounded foreground facts read through an already admitted session executor. */
type SessionEntryCohortRequest = Pick<SessionExactEntriesWorkerRequest, "snapshotFields" | "replyInitializationSessionKey" | "includeMembers" | "includeParticipantRecords" | "lifecycleSessionKey" | "transcript"> & {
  sessionKeys: readonly string[];
  includeAuthProfileSource?: boolean;
  runtimeTarget?: Pick<SessionTranscriptRuntimeTarget, "agentId" | "sessionId" | "sessionKey">;
  includeColdMetadata?: boolean;
  expected?: {
    /** Native incarnation returned by this cohort, independent of the host execution claim. */
    incarnation: string;
    sessions: readonly {
      sessionKey: string;
      sessionId: string;
      lifecycleRevision: string | undefined;
    }[];
  };
};
type SessionExactEntriesWorkerResult = {
  kind: "session-exact-entries";
  source?: SessionEntryListWorkerResult["source"];
  /** Original copy source, distinct from the private reader's native databaseIdentity. */
  snapshotSource?: NonNullable<SessionEntryListWorkerResult["source"]>;
  entries: SessionEntrySummary[];
  lifecycleTimestamps: SessionLifecycleTimestamps;
  sourceValidation?: SessionSourceValidation;
  manualCompact?: {
    archive?: Omit<SessionColdArchive, "archive_blob">;
    refusedSource?: {
      index: number;
      facts: SessionSourcePredicateFacts;
    };
  };
  pendingArchives?: boolean;
  databaseIdentity?: {
    identity: string;
    incarnation: string;
    filename: string;
    canonicalPath?: string;
    birthtime?: string;
  };
  members?: Record<string, SessionMember[]>;
  participantRecords?: Record<string, SessionParticipantRecord[]>;
  replacement?: SessionEntryReplacementState & {
    databaseIdentity: string;
  };
  creation?: SessionCreationSnapshot & {
    databaseIdentity: string;
    databasePath: string;
  };
  sharing?: {
    source: {
      agentId: string;
      path: string;
    };
    databaseIdentity: string;
    members: Array<{
      sessionKey: string;
      identityIds: string[];
    }>;
    placeholders: Array<{
      sessionKey: string;
      sessionId: string;
    }>;
  };
  transcript?: SessionTranscriptAnchorFacts;
};
type SessionEntryCohortResult = SessionExactEntriesWorkerResult & {
  runtimeTarget?: SessionTranscriptRuntimeTarget;
  coldArchives?: Array<Omit<SessionColdArchive, "archive_blob">>;
  source: NonNullable<SessionExactEntriesWorkerResult["source"]>;
  databaseIdentity: NonNullable<SessionExactEntriesWorkerResult["databaseIdentity"]>;
  authProfileSource?: boolean;
};
//#endregion
//#region src/config/sessions/session-entry-read-runtime.types.d.ts
type PreparedSessionEntryWorkerRead = {
  result: SessionExactEntriesWorkerResult;
  database: {
    agentId: string;
    path: string;
    env: NodeJS.ProcessEnv;
    readIdentity?: DatabasePathIdentity;
  };
  assertCurrent: () => void;
};
/** One admitted physical owner; each call prepares a fresh synchronous consumption phase. */
type SessionEntryCohortReader = {
  readonly database: PreparedSessionEntryWorkerRead["database"];
  readonly sessionKey: string;
  readonly logicalAgentId: string;
  readonly storePaths: readonly string[];
  assertCurrent(): void;
  /** Return committed data without retaining writer admission for a consumer effect. */
  readEntry(assertCallerCurrent: () => void, projection?: SessionEntryReadScope["projection"]): Promise<{
    entry: InternalSessionEntry;
    source: SessionEntryCohortResult["source"];
  }>;
  withRead<T>(request: Omit<SessionEntryCohortRequest, "expected">, assertCallerCurrent: () => void, consume: (read: SessionEntryCohortResult, assertCurrent: () => void) => T): Promise<T>;
};
//#endregion
//#region src/agents/embedded-agent-messaging.types.d.ts
type MessagingToolSend = {
  tool: string;
  provider: string;
  accountId?: string;
  to?: string;
  threadId?: string;
  threadImplicit?: boolean;
  threadSuppressed?: boolean;
  text?: string;
  mediaUrls?: string[];
  hasRichContent?: true;
  /** Current-source progress (`false`) or completed reply (`true`). */
  sourceReplyFinal?: boolean;
};
type MessagingToolSourceReplyPayload = Pick<ReplyPayload$1, "audioAsVoice" | "attachments" | "channelData" | "interactive" | "mediaUrl" | "mediaUrls" | "presentation" | "text" | "trustedLocalMedia"> & {
  idempotencyKey?: string;
  transcriptOwner?: true;
  /** Current-source progress (`false`) or completed reply (`true`). */
  sourceReplyFinal?: boolean;
  /** Authored by a `canDeliverSourceReply` tool: the host sends it, so the turn is complete. */
  toolAuthored?: true;
  /** Exact originating direct call; prevents suppression of another input's answer. */
  toolAuthoredForToolCallId?: string;
  /** Canonical assistant response/turn identity, or the native harness turn identity. */
  toolAuthoredForTurnId?: string;
};
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-llm-boundary.types.d.ts
type UserTranscriptContext = {
  runtimeMessage: AgentMessage;
  transcriptMessage: AgentMessage;
};
type CurrentUserTimestampMatch = {
  timestamp: number;
  text: string;
  alternateText?: string;
  runtimeTimestamp?: number;
};
type LlmBoundaryOptions = {
  sessionVersion?: number;
  appendOnlyRuntimeContext?: boolean;
  inHistorySystemUpdates?: boolean;
  timezone?: string;
  includeTimestamp?: boolean;
  projectPersistedSenderContext?: boolean;
  userTranscriptContexts?: readonly UserTranscriptContext[];
  currentUserIdempotencyKey?: string;
  currentUserTimestampOverride?: CurrentUserTimestampMatch;
  onRuntimeContextCarrierRemoved?: (removed: AgentMessage[]) => void;
};
//#endregion
//#region src/agents/reply-completion.types.d.ts
type ReplyExpectation = "required" | "optional" | "result-required";
type ReplyCompletionEvidence = "ready" | "delivered" | "pending" | "blocked" | "empty" | "silent";
type ReplyCompletion = {
  readonly expectation: ReplyExpectation;
  readonly outcome: ReplyCompletionEvidence | "missing";
};
//#endregion
//#region src/auto-reply/reply/agent-runner-execution-status.d.ts
/** Projects closed execution independently of later reply delivery. */
declare function resolveAgentTurnExecutionStatus(outcome?: {
  kind: "aborted" | "rejected";
} | {
  kind: "settled";
  status: "ok" | "failed";
}): "cancelled" | "failed" | "ok";
//#endregion
//#region src/auto-reply/reply/queue-policy.d.ts
type FollowupQueueDisposition$1 = "queue-cap" | "queue-cap-old" | "queue-cap-new";
//#endregion
//#region src/agents/agent-roster.d.ts
type AgentRosterConfig = {
  readonly agents?: {
    readonly ownership?: "explicit";
    readonly entries?: Readonly<Record<string, unknown>>;
    readonly list?: readonly unknown[];
  };
};
/** Lists unique configured agent ids. */
declare function listAgentIds(cfg: AgentRosterConfig): string[];
/** @deprecated Use tryResolveSoleAgentId; accepts raw shipped markers only for input compatibility. */
declare function tryResolveDefaultAgentId(cfg: AgentRosterConfig): string | undefined;
//#endregion
//#region src/agents/agent-scope-config.d.ts
type AgentEntry = AgentConfig;
type AgentSelectionContext = {
  surface: string;
  hint: string;
};
/** Per-agent config after applying agent defaults and normalizing scalar fields. */
type ResolvedAgentConfig = {
  name?: string;
  workspace?: string;
  agentDir?: string;
  model?: AgentEntry["model"];
  models?: AgentEntry["models"];
  params?: AgentEntry["params"];
  runtime?: AgentEntry["runtime"];
  modelPolicy?: AgentEntry["modelPolicy"];
  utilityModel?: AgentEntry["utilityModel"];
  decisionModel?: AgentEntry["decisionModel"];
  thinkingDefault?: AgentEntry["thinkingDefault"];
  verboseDefault?: AgentDefaultsConfig["verboseDefault"];
  toolProgressDetail?: AgentDefaultsConfig["toolProgressDetail"];
  reasoningDefault?: AgentEntry["reasoningDefault"];
  fastModeDefault?: AgentEntry["fastModeDefault"];
  contextInjection?: AgentEntry["contextInjection"];
  bootstrapMaxChars?: AgentEntry["bootstrapMaxChars"];
  bootstrapTotalMaxChars?: AgentEntry["bootstrapTotalMaxChars"];
  experimental?: AgentDefaultsConfig["experimental"];
  skills?: AgentEntry["skills"];
  memory?: AgentEntry["memory"];
  humanDelay?: AgentEntry["humanDelay"];
  typingMode?: AgentEntry["typingMode"];
  tts?: AgentEntry["tts"];
  compaction?: AgentEntry["compaction"];
  contextLimits?: AgentContextLimitsConfig;
  heartbeat?: AgentEntry["heartbeat"];
  identity?: AgentEntry["identity"];
  groupChat?: AgentEntry["groupChat"];
  subagents?: AgentEntry["subagents"];
  embeddedAgent?: AgentEntry["embeddedAgent"];
  sandbox?: AgentEntry["sandbox"];
  tools?: AgentEntry["tools"];
};
/**
 * @deprecated Ambient system work uses resolveAmbientOwnerAgentId so the configured
 * system agent is honored; explicit-selection surfaces use resolveSoleAgentId. This
 * accepts raw shipped markers only for input compatibility.
 */
declare function resolveDefaultAgentId(cfg: OpenClawConfig, context?: AgentSelectionContext): string;
type SessionAgentResolutionParams$1 = {
  sessionKey?: string;
  config?: OpenClawConfig;
  agentId?: string | undefined;
  fallbackAgentId?: string;
};
/** Strict session selection uses explicit context and legacy data ownership. */
declare function resolveSessionAgentIdsStrict(params: SessionAgentResolutionParams$1): {
  defaultAgentId: string;
  sessionAgentId: string;
};
declare function resolveSessionAgentIdStrict(params: SessionAgentResolutionParams$1): string;
/** Resolves merged config for one agent id. */
declare function resolveAgentConfig(cfg: OpenClawConfig, agentId: string): ResolvedAgentConfig | undefined;
declare function resolveAgentContextLimits(cfg: OpenClawConfig | undefined, agentId?: string | null): AgentContextLimitsConfig | undefined;
declare function resolveAgentWorkspaceDir(cfg: OpenClawConfig, agentId: string, env?: NodeJS.ProcessEnv): string;
declare function resolveAgentDir(cfg: OpenClawConfig, agentId: string, env?: NodeJS.ProcessEnv): string;
declare function resolveDefaultAgentDir(cfg: OpenClawConfig, env?: NodeJS.ProcessEnv): string;
//#endregion
//#region src/agents/agent-scope.d.ts
type AutoFallbackPrimaryProbe = {
  provider: string;
  model: string;
  fallbackProvider: string;
  fallbackModel: string;
  fallbackAuthProfileId?: string;
  fallbackAuthProfileIdSource?: "auto" | "user";
};
declare function resolveAgentEffectiveModelPrimary(cfg: OpenClawConfig, agentId: string): string | undefined;
type AgentModelPrimaryWriteTarget = "agent" | "defaults";
declare function setAgentEffectiveModelPrimary(cfg: OpenClawConfig, agentId: string, primary: string, options?: {
  target?: AgentModelPrimaryWriteTarget;
  forceAgent?: boolean;
}): AgentModelPrimaryWriteTarget;
//#endregion
//#region src/agents/bash-tools.exec-routing.types.d.ts
/** Execution routing and approval choices retained by a prepared turn. */
type ExecToolRoutingDefaults = {
  host?: ExecTarget;
  security?: ExecSecurity;
  ask?: ExecAsk;
  node?: string;
  /** Default working directory for node-host execution only. */
  nodeCwd?: string;
};
//#endregion
//#region src/auto-reply/source-reply-delivery-mode.types.d.ts
/** Per-turn authority for automatic replies versus explicit message-tool sends. */
type SourceReplyDeliveryMode = "automatic" | "message_tool_only";
//#endregion
//#region src/agents/cli-runner/session-binding.types.d.ts
type CliSessionBindingFacts = {
  extraSystemPromptStatic?: string;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  requireExplicitMessageTarget?: boolean;
};
//#endregion
//#region src/plugins/runtime/tool-grant.d.ts
/** Owner-scoped additive plugin tools for one trusted agent run. */
type RuntimePluginToolGrant = {
  pluginId: string;
  toolNames: readonly string[];
};
//#endregion
//#region src/skills/library/authoring.d.ts
type SkillLibraryAuthoringInput = {
  action: "list" | "read" | "create" | "update" | "share" | "unshare" | "transfer" | "activate" | "remove" | "rollback";
  skillId?: string;
  expectedRevision?: string;
  revision?: string;
  slug?: string;
  content?: string;
  files?: SkillLibraryFile[];
  deleteFiles?: string[];
};
/** Host-held namespace capability; never persisted or reconstructed from session attribution. */
type SkillLibraryAuthoringCapability = {
  target: "personal";
  defaultTarget: "workspace" | "personal";
  multipleProfiles: boolean;
  /** Gate for Workshop calls through the workspace-default wrapper, given the run's sandbox state. */
  assertWorkspaceCurrent?: (run?: {
    sandboxed?: boolean;
  }) => void;
  bind: (context: AdmittedRunContext) => void;
  invoke: (params: SkillLibraryAuthoringInput) => Promise<SkillsLibraryReceipt | SkillsLibraryReadResult | SkillsLibraryActivateResult | SkillsLibraryListResult>;
};
//#endregion
//#region src/agents/bootstrap-mode.d.ts
type BootstrapContextRunKind = "default" | "cron";
//#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/generated-attachments.d.ts
type AgentGeneratedAttachment = Omit<ReplyMediaAttachment, "trustedLocalMedia">;
//#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;
  /** True only when the producer substituted placeholder text for an absent result. */
  noVisibleResult?: boolean;
  modelRouteChange?: 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/tools/gateway-caller-receipt.types.d.ts
/** A storage predicate supplies worker facts without replacing its caller's lifetime fences. */
type GatewayToolCallerReceiptAdmission = {
  prepare(): Promise<{
    current: SessionEntriesCurrentCheck;
    isCurrent(): boolean;
  }>;
};
//#endregion
//#region src/agents/subagents/announce/subagent-announce-handoff.d.ts
type SubagentSettleToolPolicyBatch = {
  sourceSessionKeys: readonly string[];
  /** The settle owner retains batch, requester-incarnation, and revocation authority. */
  isCurrent: () => boolean;
  receiptAdmission?: GatewayToolCallerReceiptAdmission;
};
type TrustedSubagentCompletionHandoff = {
  kind: "subagent-completion";
  sourceSessionKey: string;
  sourceSessionId?: string;
  targetSessionKey: string;
  targetSessionId: string;
  provider: string;
  model: string;
  settleBatch?: SubagentSettleToolPolicyBatch;
};
type SubagentCompletionToolHandoffRegistration = {
  sourceSessionKey: string;
  sourceSessionId?: string;
  targetSessionKey: string;
  targetSessionId: string;
  idempotencyKey: string;
  settleBatch?: SubagentSettleToolPolicyBatch;
};
//#endregion
//#region src/agents/run-trigger.d.ts
type EmbeddedRunTrigger = "cron" | "event" | "manual" | "memory" | "overflow" | "user";
type ModelCallUrgency = "foreground" | "normal" | "background";
//#endregion
//#region src/agents/reply-completion.d.ts
type ReplyDeliveryState = "delivered" | "pending" | "missing";
type ReplyDeliveryObserver = (minimumAssistantMessageIndex?: number) => Promise<ReplyDeliveryState>;
type ReplyDeliveryFactsObserver = (minimumAssistantMessageIndex?: number) => Promise<{
  source: ReplyDeliveryState;
  terminal: ReplyDeliveryState;
}>;
//#endregion
//#region src/agents/system-prompt.types.d.ts
type PromptMode = "full" | "minimal" | "none";
type SilentReplyPromptMode = "generic" | "none";
//#endregion
//#region src/agents/command/queued-run-params.types.d.ts
/** Prepared execution inputs retained by queued turns, without live attempt ownership. */
type QueuedAgentRunParams = {
  requesterOrigin?: RequesterOrigin;
  operatorProfileId?: string;
  conversationId?: string | null;
  messageThreadId?: string | number;
  providerReviewAcknowledgment?: ProviderReviewAcknowledgment;
  sessionId: string;
  sessionKey?: string;
  messageProvider?: string;
  /** Capabilities declared by the gateway client that originated this run. */
  clientCaps?: string[];
  /** Profile selected from the session's assigned human owner or authenticated human creator, never its latest sender. */
  bootstrapUserProfileId?: string;
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  chatType?: ChatType;
  agentAccountId?: string;
  /** Channel-specific identity metadata surfaced to plugin hooks. */
  channelContext?: PluginHookChannelContext;
  /** Trusted sender identity bit for command/channel-action auth. */
  senderIsOwner?: boolean;
  /** Verified current requester for Git credit only; grants no tool authority. */
  gitContributorProfileId?: string;
  /** Device-scoped operator session allowed to review approvals initiated by this run. */
  approvalReviewerDeviceId?: string;
  workspaceDir: string;
  /** Task working directory for tool/runtime execution. Defaults to workspaceDir. */
  cwd?: string;
  toolOverrides?: SessionToolOverrides;
  skillsSnapshot?: SkillSnapshot;
  authProfileId?: string;
  thinkLevel?: ThinkLevel;
  /** Run-scoped selection intent for declared chat-template effort. */
  thinkingExplicit?: boolean;
  cyberAccessProgram?: SessionEntry["cyberAccessProgram"];
  fastMode?: FastMode;
  /** Effective auto fast-mode cutoff for this run, in seconds. */
  fastModeAutoOnSeconds?: number;
  timeoutMs: number;
  /** Explicit timeout override; equality with the configured default does not imply inheritance. */
  runTimeoutOverrideMs?: number;
  ownerNumbers?: string[];
  inputProvenance?: InputProvenance;
  /** Trusted server-stamped authority for an explicitly capped scheduled run. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
  extraSystemPrompt?: string;
  /** Exact producer-owned transient section; unannotated instructions remain persistent. */
  extraSystemPromptTurnContext?: {
    start: number;
    text: string;
  };
  /** Visible source replies must use the message tool when set to message_tool_only. */
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  /** Action sink available for model-proposed follow-up tasks. */
  taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  suppressNextUserMessagePersistence?: boolean;
  /** Out-of-band plugin bindings attached by the run initiator. */
  toolBindings?: Readonly<Record<string, unknown>>;
  /** Raw peer observed by the inbound routing owner, before identity linking. */
  conversationRoutePeerId?: string;
  /** Trusted channel-configured policy for the admitted conversation turn. */
  conversationToolPolicy?: GroupToolPolicyConfig;
  /** Trusted provider role ids for the requester in this group turn. */
  memberRoleIds?: string[];
  permissionMode?: SessionEntry["permissionMode"];
  sessionRoot?: string;
  /** Spawn-time blind child: the rendered prompt omits its model, identity and workspace path. */
  blindPrompt?: SessionEntry["blindPrompt"];
  /** Locks the selected model against hooks and fallbacks; does not imply native model ownership. */
  modelSelectionLocked?: boolean;
  authProfileIdSource?: "auto" | "user";
  verboseLevel?: VerboseLevel;
  reasoningLevel?: ReasoningLevel;
  /** Consumed in-process subagent-completion capability; never derived from public input. */
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  /** Owner-scoped plugin tool grant; normal policy and deny rules still apply. */
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  silentReplyPromptMode?: SilentReplyPromptMode;
  enforceFinalTag?: boolean;
  silentExpected?: boolean;
  /**
   * Host-owned reply requirement for this input, independent of model output.
   * Confirmed source delivery and pending custody prevent duplicate recovery.
   */
  terminalReplyExpectation?: ReplyExpectation;
  suppressTranscriptOnlyAssistantPersistence?: boolean;
  skillLibraryAuthoring?: SkillLibraryAuthoringCapability;
};
//#endregion
//#region src/channels/message-access/admission-evidence.types.d.ts
type ChannelAdmissionEvidence = Readonly<{
  kind: "channel-admission-evidence";
}>;
//#endregion
//#region src/config/sessions/transcript-assistant-delivery.d.ts
/** Turn-owned display preparation; source text precedes transcript-only hook rewrites. */
type PrepareAssistantTranscriptMessage = <T extends AssistantHistoryMessage>(message: T, sourceText: string | undefined) => T;
//#endregion
//#region src/gateway/cron-creator-authority-grant.d.ts
/** Admission fact, independent of a run lifetime so an authorized yield can transfer it. */
type CronManagementEntitlement = Readonly<{
  source: "control-ui-admin";
}> | Readonly<{
  source: "channel-owner";
  isCurrent: () => boolean;
}>;
type CronCreatorAuthorityRunScope = {
  readonly runId: string;
  readonly callerOrigin: CronScheduledToolCallerOrigin;
  readonly signal: AbortSignal;
  readonly grantTokens: Set<string>;
  readonly managementEntitlement?: CronManagementEntitlement;
  /** Separately admitted channel-owner identity, not implied by automation management rights. */
  readonly requesterOwner?: Readonly<{
    isCurrent: () => boolean;
    senderId?: string;
    channel?: string;
    accountId?: string;
  }>;
  /** Fresh admission only; never transferred with a management continuation. */
  readonly callerScopedCreation?: true;
  /** @deprecated Read managementEntitlement. Harness source compatibility lasts through 2026-10-12. */
  readonly controlUiAdmin?: true;
  readonly isCurrent?: () => boolean;
  active: boolean;
  abort: () => void;
};
//#endregion
//#region src/infra/gateway-scheduler.d.ts
type GatewaySchedulerClock = {
  now: () => number;
  monotonicNow: () => number;
  arm: (run: () => void | Promise<void>, delayMs: number) => () => void;
};
type GatewayScheduledJob = {
  readonly atMs: number;
  cancel: () => void;
  stop: () => Promise<void>;
};
type ScheduleParams = {
  id: string;
  everyMs?: number;
  /** Best-effort work may run up to 10s early to share a stable maintenance phase. */
  phase?: "maintenance";
  /** Keep both pending clock deadlines when a stale read would postpone the wake. */
  mode?: "replace" | "earliest";
  run: () => void | Promise<unknown>;
} & ({
  atMs: number;
} | {
  delayMs: number;
});
type GatewaySchedulerScope = Pick<GatewayScheduler, "signal" | "now" | "schedule" | "beginClose" | "stop"> & {
  /** Preserve synchronous retirement when this owner has no running work. */
  close: () => Promise<void> | undefined;
};
/** Owns Gateway wakeups; stores and execution owners retain their deadlines and authority. */
declare class GatewayScheduler {
  private readonly clock;
  private readonly jobs;
  private readonly pending;
  private cancelTimer?;
  private dispatching;
  private fenced;
  private readonly controller;
  constructor(options?: {
    clock?: GatewaySchedulerClock;
  });
  get signal(): AbortSignal;
  now(): number;
  get nextWakeAtMs(): number | null;
  /** Closes one owner's timers without retiring siblings or losing in-flight joins. */
  scope(): GatewaySchedulerScope;
  schedule(params: ScheduleParams): GatewayScheduledJob;
  private scheduleOwned;
  private cancel;
  /** Stop wakeups and admission without retiring authority held by accepted work. */
  fence(): void;
  beginClose(): void;
  stop(): Promise<void>;
  private remaining;
  private arm;
  private wake;
  private run;
}
//#endregion
//#region src/gateway/auth-rate-limit.d.ts
interface RateLimitConfig extends GatewayAuthRateLimitConfig {
  /** Background prune interval in milliseconds; set <= 0 to disable auto-prune.  @default 60_000 */
  pruneIntervalMs?: number;
  /** Maximum tracked client identities before old unlocked entries are evicted.  @default 10_000 */
  maxEntries?: number;
}
interface RateLimitCheckResult {
  allowed: boolean;
  /** Number of remaining attempts before the limit is reached. */
  remaining: number;
  /** Milliseconds until the lockout expires (0 when not locked). */
  retryAfterMs: number;
}
interface AuthRateLimiter {
  check(ip: string | undefined, scope?: string): RateLimitCheckResult;
  recordFailure(ip: string | undefined, scope?: string): void;
  /**
   * Record a failed attempt and await any loopback penalty delay.
   *
   * Deliberately post-verification: it prices repeated guessing from one loopback
   * source without ever gating a request before its credentials are checked.
   * Gating earlier would stop parallel fan-out, but would also let a bad local
   * peer stall the operator's own correct-credential CLI, which loopback must
   * never do. Fan-out from loopback is out of scope for this limiter by design.
   */
  recordFailureAndDelay(ip: string | undefined, scope?: string): Promise<void>;
  /** Reset the rate-limit state for `ip` (e.g. after a successful login). */
  reset(ip: string | undefined, scope?: string): void;
  size(): number;
  prune(): void;
  dispose(): void;
}
//#endregion
//#region src/gateway/ingress-attribution.d.ts
type VerifiedTailscaleIngressIdentity = {
  login: string;
  name: string;
  profilePic?: string;
};
//#endregion
//#region src/gateway/auth.d.ts
type GatewayAuthResult = {
  ok: boolean;
  method?: "none" | "token" | "password" | "tailscale" | "device-token" | "bootstrap-token" | "trusted-proxy" | "remote-ingress";
  user?: string;
  /** Full verified Tailscale identity; present only after header + WhoIs agreement. */
  tailscaleIdentity?: VerifiedTailscaleIngressIdentity;
  reason?: string;
  rateLimited?: boolean;
  /** Milliseconds the client should wait before retrying (when rate-limited). */
  retryAfterMs?: number;
};
//#endregion
//#region src/gateway/local-user-ingress.d.ts
type GatewayLocalUserIngressFacts = Readonly<Pick<ExecutionIdentityAdmissionFacts, "assurance" | "ingress" | "invoker" | "representedSubject">>;
type GatewayLocalUserIngress = Readonly<{
  facts: GatewayLocalUserIngressFacts;
}>;
//#endregion
//#region src/auto-reply/reply/goal-continuation.types.d.ts
type GoalContinuation = Pick<SessionEntry, "sessionId" | "lifecycleRevision"> & {
  goalId: string;
  workerGoal?: true;
  localCodexGoal?: true;
};
//#endregion
//#region src/agents/operational-run-instance.d.ts
/** Operational lifecycle correlation. This is never identity or authorization evidence. */
type OperationalRunInstanceRef = Readonly<{
  instanceId: string;
  runId: string;
}>;
//#endregion
//#region src/cron/execution-context.d.ts
type ScheduledIngress = "webhook" | "plugin-hook" | "channel-join";
/** A stored automation link names its parent conversation by key alone. */
type ScheduledParentLink = Readonly<{
  agentId: string;
  sessionKey: string;
}>;
/** The parent's current incarnation, read for this occurrence. */
type ScheduledParentRef = ScheduledParentLink & Readonly<{
  sessionId: string;
  lifecycleRevision?: string;
}>;
type ScheduledRequesterRef = Readonly<{
  kind: "operator-source";
  source: RestartRecoveryOperatorSource;
}> | Readonly<{
  kind: "channel";
  requester: CronAuthenticatedChannelRequester;
}> | Readonly<{
  kind: "profile";
  profileId: string;
}> | Readonly<{
  kind: "unknown";
}>;
type ParentlessScheduledPrincipal =
/** A parent key without a link. Every decision equals the legacy one until bound. */
Readonly<{
  kind: "unbound-parent";
  parentSessionKey: string;
}> | Readonly<{
  kind: "operator";
  basis: "trusted-policy" | "unlinked-legacy";
}> | Readonly<{
  kind: "ingress";
  ingress: ScheduledIngress;
}>;
type ScheduledPrincipal = Readonly<{
  kind: "parent";
  parent: ScheduledParentRef;
  requester: ScheduledRequesterRef;
}> | ParentlessScheduledPrincipal;
type ScheduledPlacement = "child" | "in-session" | "detached";
type ScheduledAuthority = Readonly<{
  owner: boolean;
  basis: "operator-source" | "channel-owner" | "profile-role" | "trusted-policy" | "legacy" | "none";
  /** Undefined for ingress turns, which are admitted without a schedule source. */
  admissionSource?: NonNullable<AdmittedRunContext["admissionSource"]>;
}>;
type ScheduledAutomationsScope = Readonly<{
  scope: "self";
  jobId: string;
}> | Readonly<{
  scope: "self-and-parent-wake";
  jobId: string;
  parentSessionKey: string;
}> | Readonly<{
  scope: "none";
}>;
type ScheduledToolPolicy = Readonly<{
  /** Resolved run cap; undefined means the agent's own policy applies uncapped. */
  allow?: readonly string[];
  policy?: CronScheduledToolPolicy;
  callerOrigin: CronScheduledToolCallerOrigin;
  execTarget?: CronToolsAllowExecTarget;
  automations: ScheduledAutomationsScope;
}>;
type ScheduledResourceScopes = Readonly<{
  /** Which session's memory audience the run reads; the builder holds no leases. */
  memory: Readonly<{
    source: "parent";
    parent: ScheduledParentRef;
    owner: boolean;
  }> | Readonly<{
    source: "run-session";
  }>;
  boardSessionKey: string;
  mediaSessionKey: string;
  eventTargetSessionKey: string;
  workspace: Readonly<{
    source: "parent-row";
    dir: string;
    cwd?: string;
    worktreePath?: string;
  }> | Readonly<{
    source: "run-session";
  }>;
  fileScope: "root" | "session";
  bootstrap: "cron-allowlist" | "default";
  sandbox: Readonly<{
    required: boolean;
    basis: readonly ("agent-config" | "creator-role" | "parent-row")[];
  }>;
  execHost?: CronToolsAllowExecTarget;
  messageAccounts: Readonly<{
    ownerAccountId?: string;
    channelRequester?: CronAuthenticatedChannelRequester;
  }>;
  delivery: Readonly<{
    sourceConversation?: CronStoredJob["sourceConversation"];
  }>;
}>;
type ScheduledInferenceAccount = Readonly<{
  kind: "bound";
  binding: CronInferenceBinding;
}> | Readonly<{
  kind: "runtime";
  authority: CronRuntimeAuthority;
}> | Readonly<{
  kind: "runtime-recovery-required";
}> | Readonly<{
  kind: "none";
}>;
/** The pure part of the context; admission adds the composed live assertion. */
type ScheduledExecutionFacts = Readonly<{
  version: 1;
  jobId: string;
  occurrence: Readonly<{
    runId: string;
    executionRevision: string;
  }>;
  principal: ScheduledPrincipal;
  placement: ScheduledPlacement;
  authority: ScheduledAuthority;
  toolPolicy: ScheduledToolPolicy;
  resources: ScheduledResourceScopes;
  inference: ScheduledInferenceAccount;
}>;
type ScheduledParentUnavailableReason = "removed" | "archived" | "worktree-missing";
type ScheduledExecutionContextResult = Readonly<{
  status: "ready";
  facts: ScheduledExecutionFacts;
}> | Readonly<{
  status: "pause";
  reason: ScheduledParentUnavailableReason;
  parentSessionKey: string;
  worktreePath?: string;
}> | Readonly<{
  status: "fail";
  error: string;
}>;
//#endregion
//#region src/cron/scheduled-occurrence.d.ts
type ScheduledExecutionContext = ScheduledExecutionFacts & Readonly<{
  /** Throws when the parent incarnation or the admitted run is no longer current. */
  assertCurrent: () => void;
  /**
   * Set when a requester holds owner authority for this run. Throws once the
   * requester stops passing its owner check, so owner-only tools refuse mid-run.
   */
  assertOwnerCurrent?: () => void;
}>;
/** Run-specific facts an executor supplies when its run is admitted. */
type ScheduledOccurrenceRun = {
  cfg: OpenClawConfig;
  agentId: string;
  runId: string;
  runSessionKey: string;
  toolsAllow?: readonly string[];
  /** Restored operator source authority, when the occurrence carries one. */
  operatorAuthority?: AdmittedRunOperatorAuthority;
};
type MintedScheduledExecution = Readonly<{
  result: ScheduledExecutionContextResult;
  /** Binds the context to the admitted run; the admission owner reads it through `current`. */
  bind: (run: OperationalRunInstanceRef, assertAdmitted: () => void) => void;
  current: () => ScheduledExecutionContext | undefined;
  release: () => void;
}>;
/** One admitted occurrence. Every scheduled agent run mints its context from it. */
type ScheduledOccurrence = Readonly<{
  /** Set when the exact parent is removed or archived, or its bound worktree is gone. */
  pause?: CronParentUnavailable;
  /** A child run's parent row, read once by the admission. */
  childParent?: Readonly<{
    /** Set when the parent row persists a workspace binding; it selects the child's workspace. */
    binding?: Readonly<{
      sessionKey: string;
      entry: SessionEntry;
    }>;
    /** Set when the parent row requires a sandbox. */
    sandbox?: "required";
    /** Fails once the parent is reset or removed, or the occurrence settles. */
    assertCurrent: () => void;
    /** Set with `binding`; aborts once the parent is reset or removed. */
    signal?: AbortSignal;
  }>;
  mint: (run: ScheduledOccurrenceRun) => MintedScheduledExecution;
  /** Releases the parent generation; the occurrence owner calls it once the occurrence settles. */
  release: () => void;
}>;
//#endregion
//#region src/config/sessions/session-worktree-intent.d.ts
/** Private source selection accepted under the session creation lifecycle lock. */
type PendingSessionWorktree = {
  workspace?: string;
  /** Source custody accepted by the locked creation owner, not public request input. */
  source?: {
    kind: "project" | "worktree";
    id: string;
  };
  name?: string;
  baseRef?: string;
  /** Verified commit used for checkout while baseRef remains user-facing metadata. */
  baseCommit?: string;
  titleSource: string;
};
//#endregion
//#region src/infra/sqlite-commit-receipt.d.ts
/** A committed postimage describes one domain/key, never all writers of a database. */
type SqliteCommittedFact<T> = {
  kind: "postimage";
  value: T;
} | {
  kind: "absent";
} | {
  kind: "unchanged";
} | {
  kind: "unknown";
};
type SqliteCommitSource = {
  identity: string | symbol;
  incarnation: string;
};
/**
 * Private, process-lifetime evidence. The existing domain owner still supplies
 * currentness, supersession, foreign freshness, policy, and reconciliation.
 * Operation identity is not a durable idempotency key or permission to replay.
 */
type SqliteCommitReceipt<T, Source extends SqliteCommitSource = SqliteCommitSource> = {
  version: 1;
  operationId: string;
  source: Source;
  domain: string;
  facts: ReadonlyMap<string, SqliteCommittedFact<T>>;
};
//#endregion
//#region src/config/sessions/conversation-binding-facts.types.d.ts
type ConversationBindingNode = Pick<Selectable<DB["session_nodes"]>, "session_key" | "current_session_id" | "entry_valid" | "updated_at"> & {
  entry_session_id: string | null;
};
type ConversationBindingWindow = Pick<Selectable<DB["session_windows"]>, "session_id" | "session_key" | "primary_conversation_id">;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-conversation-publication.d.ts
type ConversationCatalogRow = Selectable<DB["conversations"]>;
type ConversationAssociationRow = Selectable<DB["session_conversations"]>;
type ConversationFact = {
  kind: "catalogue";
  row: Pick<ConversationCatalogRow, "conversation_id" | "kind">;
} | {
  kind: "association";
  row: Pick<ConversationAssociationRow, "session_id" | "conversation_id" | "role" | "last_seen_at">;
} | {
  kind: "node";
  row: ConversationBindingNode;
} | {
  kind: "window";
  row: ConversationBindingWindow;
} | {
  kind: "rehome";
  sessionKey: string;
  sessionId?: string;
  previousKeys?: readonly string[];
};
type ConversationPublicationSource = SqliteCommitSource & {
  canonicalPath: string;
};
type ConversationPublication = SqliteCommitReceipt<ConversationFact, ConversationPublicationSource>;
//#endregion
//#region src/sessions/transcript-terminal-model.d.ts
type SessionTranscriptTerminalModel = {
  runId: string;
  modelProvider: string;
  model: string;
};
//#endregion
//#region src/gateway/session-row-transcript-preview.d.ts
type SessionRowAssistantMessage = NonNullable<SessionRow["lastAssistantMessage"]>;
/** Null is known empty; unknown needs a bounded transcript backfill. */
type SessionRowAssistantMessageFact = SessionRowAssistantMessage | null | "unknown";
/** An append can preserve the resident owner's fact without reading the transcript. */
type SessionRowAssistantMessageUpdate = SessionRowAssistantMessageFact | "unchanged";
type SessionRowTranscriptProjection = {
  lastMessagePreview: string | null;
  lastAssistantMessage: SessionRowAssistantMessageUpdate;
  terminalModel: SessionTranscriptTerminalModel | null;
  indexedSeq: number | null;
};
//#endregion
//#region src/state/openclaw-agent-execution-identity.types.d.ts
/** Recorded by the native owner; a descriptor never grants access to that owner. */
type AgentDatabaseFileExecutionIdentity = {
  kind: "file";
  physicalIdentity: string;
  birthtime?: string;
  incarnation: string;
  nativeLocation: string;
};
type AgentDatabaseExecutionFileIdentity = Pick<AgentDatabaseFileExecutionIdentity, "kind" | "physicalIdentity" | "birthtime" | "nativeLocation">;
//#endregion
//#region src/config/sessions/session-pending-input.types.d.ts
type SessionPendingInputRow = Selectable<SessionPendingInputs>;
/** Transported facts do not grant custody; the host retains and checks the exact live owner. */
type SessionPendingInputWorkerFacts = {
  agentId?: string;
  databaseAgentId?: string;
  inputId: string;
  transcriptInputId: string;
  sessionId: string;
  sessionKey: string;
  /** Native cache locator; may be the process-held incognito sentinel. */
  databasePath: string;
  idempotencyKey: string;
  lifecycleGeneration: string;
  messageJson: string;
  preparedAuthority?: true;
  sources?: readonly SessionPendingInputWorkerFacts[];
};
type SessionPendingInputWorkerReceipt = {
  transcriptInputId: string;
  consumedInputIds: string[];
};
type SessionInputCompletion = Selectable<SessionInputCompletions> & {
  outcome: AgentRunTerminalOutcome$1;
};
//#endregion
//#region src/config/sessions/session-actor-state.types.d.ts
type SessionActorTarget = Readonly<{
  database: AgentDatabaseExecutionFileIdentity | {
    kind: "memory";
    handle: string;
    incarnation: string;
  };
  sessionKey: string;
}>;
/** Sequences are comparable only within one owner epoch. Rehydration creates a new epoch. */
type SessionActorVersion = Readonly<{
  epoch: string;
  sequence: number;
}>;
type SessionActorLifetime = {
  /** Refuse new work without revoking already accepted settlement. */
  assertAdmission?(): void;
  assertCurrent(): void;
  /** Accepted work may still settle after new disclosure has been revoked. */
  assertReadable(): void;
};
/** Entry policy and physical/session identity; replica revisions are not authority. */
type SessionActorAuthorityFacts = Pick<SessionActorHotState, "target" | "entry">;
/** Host-owned live authority, rechecked at both synchronous admission boundaries. Facts are read-only. */
type SessionActorAuthority = {
  assertCurrent(): void;
  authorize(stage: "transaction" | "commit", facts: SessionActorAuthorityFacts,
  /** Existing kernel source/custody evidence remains subject to its owner's checks. */
  publication?: unknown): void;
};
/** Actor facts; durable history indexes and payloads stay with the bounded history reader. */
type SessionActorHotState = {
  target: SessionActorTarget;
  version: SessionActorVersion;
  /** In-process writer receipt revision, not a SQLite foreign-commit observation. */
  writeToken: string;
  /** Shared windows retained by the selected row and its lookup aliases. */
  dependencySessionIds: string[];
  /** Includes the canonical turn, lifecycle, recovery, and pendingFinalDelivery fields. */
  entry: InternalSessionEntry | undefined;
  hasBoard: boolean;
  participants: SessionParticipantRecord[];
  members: SessionMember[];
  /** Durable actors expose unconsumed custody only, not retained source history. */
  pendingInputs: Array<Omit<SessionPendingInputRow, "message_json">>;
  /** Retry-key membership is complete only with resident modelContext. */
  completionKeys: string[];
  transcript: {
    /** Durable projection postimage; omitted by adapters without SQLite projections. */
    projection?: SessionTranscriptProjectionFacts;
    contextStats?: SessionTranscriptContextStats;
    watermark: SessionTranscriptWatermark;
    version: SessionTranscriptContextVersion;
    /** Empty anchors prove absence only when this exact projection is resident. */
    anchorsState: "resident" | "unavailable";
    anchors: TranscriptEntryAnchor[];
    /** Durable postimages omit this index and mark modelContext unavailable. */
    idempotency: Array<{
      key: string;
      eventId: string;
      rawSeq: number;
    }>;
    /** Exact ordered active context membership, including an explicitly empty context. */
    modelContext: {
      kind: "resident";
      entries: Array<{
        rawSeq: number;
        eventId: string | null;
      }>;
    } | {
      kind: "unavailable";
      reason: "cold" | "projection";
      generation: string | null;
    };
  };
};
//#endregion
//#region src/config/sessions/session-actor-bounded-history.d.ts
type SessionActorTranscriptRow = {
  rawSeq: number;
  event: unknown;
  serializedBytes: number;
};
//#endregion
//#region src/config/sessions/session-transcript-authority.types.d.ts
/** Committed context facts, optionally carrying a resident actor's exact metadata rewrite. */
type SessionTranscriptAuthority = SessionTranscriptContextVersion & {
  sessionId: string;
  sessionKey: string;
  leafEventId: string | null;
  indexedSeq: number | null;
  activeMessageCount: number | null;
  needsRebuild: number | null;
  /** The projection writer established all rows, including context eligibility. */
  projectionReady?: true;
  /** Absent needs a tail lookup; null is a known empty bounded preview. */
  lastMessagePreview?: string | null;
  lastAssistantMessage?: SessionRowAssistantMessageUpdate;
  terminalModel?: SessionTranscriptTerminalModel | null;
  actorRewrite?: {
    before: SessionTranscriptContextVersion;
    postimage: SessionActorHotState;
    rows: SessionActorTranscriptRow[];
  };
};
type SessionTranscriptAuthorityReceipt = SqliteCommitReceipt<SessionTranscriptAuthority, SessionEntryPublicationSource>;
//#endregion
//#region src/config/sessions/store-maintenance.d.ts
type ResolvedSessionMaintenanceConfig = {
  mode: SessionMaintenanceMode;
  pruneAfterMs: number;
  archiveDashboardAfterMs: number | null;
  maxEntries: number;
  modelRunPruneAfterMs: number;
  preserveRecentMs?: number | null;
  resetArchiveRetentionMs: number | null;
  maxDiskBytes: number | null;
  highWaterBytes: number | null;
};
type ResolvedSessionMaintenanceConfigInput = Omit<ResolvedSessionMaintenanceConfig, "archiveDashboardAfterMs" | "modelRunPruneAfterMs"> & Partial<Pick<ResolvedSessionMaintenanceConfig, "archiveDashboardAfterMs" | "modelRunPruneAfterMs">>;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-maintenance-age.d.ts
type SessionMaintenanceAgeContinuation = {
  at: number;
  after?: {
    updatedAt: number;
    sessionKey: string;
  };
  modelRunPrune: boolean;
};
type SessionEntryMaintenanceAgeFact = {
  maintenance: ResolvedSessionMaintenanceConfig;
  entryCount?: number;
  next: {
    at: number;
  };
  recheckAt: number;
};
type MaintenanceActivity = Pick<SessionEntry, "updatedAt" | "lastActivityAt" | "lastInteractionAt" | "sessionStartedAt" | "archivedAt" | "sessionId" | "parentSessionKey"> & {
  preserved?: boolean;
};
type SessionEntryMaintenanceAgeChange = {
  sessionKey: string;
  entry: MaintenanceActivity;
  previousEntry?: MaintenanceActivity;
};
//#endregion
//#region src/config/sessions/store-maintenance-preserve-snapshot.types.d.ts
type SessionMaintenancePreservationSnapshot = {
  providerKeys: string[];
  workIdentities: string[];
  lifecycleIdentities: string[];
  /** A provider has not loaded its protection yet; automatic archiving waits for it. */
  archivingDeferred?: true;
};
/** Candidate identities needed by the final live-protection check. */
type SessionMaintenancePreservationPlan = {
  archivedEntries: readonly {
    sessionKey: string;
    sessionId?: string;
  }[];
  entryRemovals: readonly {
    sessionKey: string;
    expectedEntry?: {
      sessionId: string;
    };
  }[];
  stateDeletePlans: readonly {
    sessionId: string;
  }[];
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-entry-cache.types.d.ts
type SessionEntryPlaceholder = Readonly<{
  sessionId: string;
}>;
type SessionTranscriptInitializationPublication = {
  kind: "session-transcript-initialized";
  conversationPublication?: readonly ConversationPublication[];
  transcriptPublication?: readonly SessionTranscriptAuthorityReceipt[];
  sessionKey: string;
  placeholder?: SessionEntryPlaceholder;
};
declare const creationBrand: unique symbol;
type SessionEntryCreationOperation = Readonly<{
  [creationBrand]: true;
}>;
type SessionEntryPublicationSource = {
  /** The anchor routes receipts; null marks PostgreSQL capture without an admitted store. */
  admission?: Pick<PostgresPhysicalFacts, "engine" | "namespace" | "storeId" | "admissionId"> | null;
  identity: string | symbol;
  birthtime: string | undefined;
  incarnation: string;
  filename: string;
  canonicalPath?: string;
  revision?: number;
  /** Complete postimages may be reused only at this committing writer's physical revision. */
  writeToken?: string;
};
type SessionEntryProjectionFacts = {
  membership: SessionMembershipFact;
  hasBoard: boolean;
  activitySummaryWatermark: SessionTranscriptWatermark | undefined;
};
type SessionEntryReplacementPublication = {
  conversationPublication?: readonly ConversationPublication[];
  /** Removed aliases preserved transcript contents, visibility, and logical-agent attribution. */
  transcriptInventoryUnchanged?: true;
  maintenancePlans?: readonly SessionMaintenancePreservationPlan[];
  kind: "session-entry-replacements";
  transcriptPublication?: readonly SessionTranscriptAuthorityReceipt[];
  pendingArchiveRecovery: boolean;
  previous: Map<string, Pick<SessionEntry, "sessionId" | "lifecycleRevision">>;
  current: Map<string, SessionEntry>;
  /** Full snapshots belong to bounded entry readers, not resident display rows. */
  fullEntries?: ReadonlyMap<string, SessionEntry>;
  /** Closed entry patches preserve the resident actor's unchanged custody and transcript facts. */
  actorPostimages?: ReadonlyMap<string, SessionActorHotState>;
  /** Canonical metadata is committed, but these entries lack a valid display projection. */
  unavailableParticipantKeys?: readonly string[];
  ageChanges: SessionEntryMaintenanceAgeChange[];
  source?: SessionEntryPublicationSource;
  projection?: ReadonlyMap<string, SessionEntryProjectionFacts>;
  changedKeys: string[];
  membershipInvalidatedKeys: string[];
  sharingUnchangedKeys: string[];
  generationUnchangedKeys: string[];
};
//#endregion
//#region src/plugin-sdk/channel-route.d.ts
/** Coarse chat shape used when a channel can distinguish direct, group, and broadcast targets. */
type ChannelRouteChatType = "direct" | "group" | "channel";
/** Provider-specific thread kind carried with normalized channel routes. */
type ChannelRouteThreadKind = "topic" | "thread" | "reply";
/** Describes which runtime surface supplied a channel route thread id. */
type ChannelRouteThreadSource = "explicit" | "target" | "session" | "turn";
/** Normalized channel route used for comparison, binding, and dedupe helpers. */
type ChannelRouteRef = {
  /** Lowercase channel id such as `slack`, `telegram`, or `discord`. */
  channel?: string;
  /** Normalized account/profile id when a channel supports multiple accounts. */
  accountId?: string;
  target?: {
    /** Canonical destination id used for route equality and delivery. */
    to: string;
    /** Original destination text when provider target grammar differs from the canonical id. */
    rawTo?: string;
    /** Coarse destination shape used by channels with different direct/group/broadcast rules. */
    chatType?: ChannelRouteChatType;
  };
  thread?: {
    /** Provider thread/topic/root id; strings are preserved when providers use opaque ids. */
    id: string | number;
    /** Provider-specific thread family for channels that distinguish topics, replies, and threads. */
    kind?: ChannelRouteThreadKind;
    /** Runtime source that supplied the thread id, used when callers need route provenance. */
    source?: ChannelRouteThreadSource;
  };
};
/** Loose route input accepted at SDK boundaries before normalization. */
type ChannelRouteRefInput = {
  /** Raw channel id; normalized to lowercase. */
  channel?: unknown;
  /** Raw account/profile id; normalized with account-id rules when string. */
  accountId?: unknown;
  /** Raw destination id before trimming and route-key normalization. */
  to?: unknown;
  /** Provider-specific target text retained when different from `to`. */
  rawTo?: unknown;
  /** Coarse destination shape supplied by channels that distinguish target kinds. */
  chatType?: ChannelRouteChatType;
  /** Raw provider thread/topic/root id before route-key normalization. */
  threadId?: unknown;
  /** Provider-specific thread family carried with the normalized thread id. */
  threadKind?: ChannelRouteThreadKind;
  /** Runtime surface that supplied the thread id. */
  threadSource?: ChannelRouteThreadSource;
};
/** Raw outbound target input shape used by helpers that do not need thread metadata source. */
type ChannelRouteTargetInput = Pick<ChannelRouteRefInput, "channel" | "accountId" | "to" | "rawTo" | "chatType" | "threadId">;
//#endregion
//#region src/utils/delivery-context.types.d.ts
/** Canonical channel delivery target shared by sessions, cron, tasks, and plugins. */
type DeliveryContext = Pick<ChannelRouteTargetInput, "accountId" | "channel" | "threadId" | "to"> & {
  /** Channel/plugin id that owns the delivery target. */
  channel?: string;
  /** Channel-local destination id, preserved with channel-specific casing. */
  to?: string;
  /** Optional channel account/workspace id. */
  accountId?: string;
  /** Optional thread/topic id nested under `to`. */
  threadId?: string | number;
  /** Optional queued-delivery intent associated with this context. */
  deliveryIntent?: {
    /** Stable queue/work item id. */
    id: string;
    /** Intent family; currently scoped to outbound queue delivery. */
    kind: "outbound_queue";
    /** Whether queueing is mandatory or best-effort for this delivery. */
    queuePolicy?: "required" | "best_effort";
  };
};
//#endregion
//#region src/infra/exec-request-context.d.ts
type ExecRequestIdentity = {
  runId?: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  ownerConnId?: string;
  ownerDeviceId?: string;
  /** Original host-issued person follows request custody after its foreground source retires. */
  initiatingPersonalOperator?: AdmittedRunOperatorAuthority;
  controlUiVisible?: boolean;
  turnKind?: "main" | "btw";
};
/** Process-local ownership of ordinary commands, independent of a disposable tool call. */
type ExecRequestOwner = {
  identity: Readonly<ExecRequestIdentity>;
  readonly turnRunIds: Set<string>;
  readonly controller: AbortController;
  readonly signal: AbortSignal;
  readonly pendingProcesses: Set<Promise<void>>;
  cleanupUncertain: boolean;
};
declare const EVENT_OWNERS: unique symbol;
type OwnedEvent = {
  [EVENT_OWNERS]?: readonly ExecRequestOwner[];
};
/** Opaque request ancestry retained by work admitted through a host capability. */
type ExecRequestCustody = Readonly<OwnedEvent>;
//#endregion
//#region src/infra/system-events.d.ts
type SystemEvent = {
  /**
   * OpenClaw-assigned opaque identity for one queued occurrence. Preserve it when returning a
   * snapshot to consume. It changes on replacement or re-enqueue; optional only for legacy
   * ID-less compatibility.
   */
  id?: string;
  text: string;
  ts: number;
  contextKey?: string | null;
  deliveryContext?: DeliveryContext;
  /** An unresolved exec attempt must not be regenerated by an unrelated model turn. */
  deliveryHeld?: boolean;
  sessionStorePath?: string | null;
};
type SystemEventOptions = {
  sessionKey: string;
  sessionStorePath?: string | null;
  contextKey?: string | null;
  deliveryContext?: DeliveryContext;
  /** Replace the pending event for this context and delivery route. Requires contextKey. */
  replace?: boolean;
};
declare function isSystemEventContextChanged(sessionKey: string, contextKey?: string | null): boolean;
declare function enqueueSystemEventEntry(text: string, options: SystemEventOptions): SystemEvent | null;
declare function enqueueSystemEvent(text: string, options: SystemEventOptions): boolean;
declare function drainSystemEventEntries(sessionKey: string): SystemEvent[];
declare function consumeSelectedSystemEventEntries(sessionKey: string, consumedEntries: readonly SystemEvent[], options?: {
  deferredEventIds?: readonly string[];
}): SystemEvent[];
declare function drainSystemEvents(sessionKey: string): string[];
declare function peekSystemEvents(sessionKey: string): string[];
declare function hasSystemEvents(sessionKey: string): boolean;
declare function resolveSystemEventDeliveryContext(events: readonly SystemEvent[]): DeliveryContext | undefined;
//#endregion
//#region src/sessions/reply-operation-state.d.ts
/** Synchronous turn lifecycle state; attempts, authority and settlement belong to its operation. */
type ReplyOperationActivePhase = "queued" | "waiting_for_deferred_maintenance" | "waiting_for_global_lane" | "preflight_compacting" | "memory_flushing" | "running";
type ReplyOperationPhase$1 = ReplyOperationActivePhase | "completed" | "yielded" | "failed" | "aborted";
type ReplyOperationResult$1 = {
  kind: "completed";
} |
/** The backend ended its own turn to await a continuation; recorded when the turn settles. */
{
  kind: "yielded";
} | {
  kind: "failed";
  code: "gateway_draining" | "command_lane_cleared" | "aborted_by_user" | "session_corruption_reset" | "run_stalled" | "run_failed";
  cause?: unknown;
} | {
  kind: "aborted";
  code: "aborted_by_user" | "aborted_for_restart" | "aborted_for_supersession";
};
/** Observe exact operation liveness without importing queue or backend contracts. */
type ReplyOperationObservation = Readonly<{
  abortSignal: AbortSignal;
  result: Exclude<ReplyOperationResult$1, {
    kind: "yielded";
  }> | null;
}>;
type ReplyOperationState = Readonly<{
  phase: ReplyOperationPhase$1;
  phaseBeforeGlobalLaneWait?: "queued" | "running";
  phaseBeforeMaintenanceWait?: "queued" | "running";
  result: ReplyOperationResult$1 | null;
  cleared: boolean;
  abortFrozen: boolean;
}>;
//#endregion
//#region src/cron/delivery-attempt-fence.d.ts
/** Host-held occurrence authority; never serialized into a tool or transport request. */
type CronCompletionDeliveryFence = {
  beforeAttempt: () => Promise<void>;
  assertCurrent: () => void;
};
//#endregion
//#region src/cron/service/list-page-types.d.ts
/** Stable sort keys supported by paginated cron listing. */
type CronJobsSortBy = "nextRunAtMs" | "updatedAtMs" | "name";
/** Sort direction for paginated cron listing. */
type CronSortDir = "asc" | "desc";
/** Input contract for filtered, sorted, offset-based cron job pages. */
type CronListPageOptions = {
  includeDisabled?: boolean;
  limit?: number;
  offset?: number;
  query?: string;
  enabled?: "all" | "enabled" | "disabled";
  scheduleKind?: "all" | "at" | "every" | "cron" | "on-exit" | "stream" | "event";
  lastRunStatus?: "all" | CronRunStatus | "unknown";
  trigger?: "all" | "conditional" | "unconditional";
  sortBy?: CronJobsSortBy;
  sortDir?: CronSortDir;
  agentId?: string;
};
/** Offset-page result. Rows are deeply frozen snapshots; clone before editing locally. */
type CronListPageResult<TJobs extends readonly CronJob[] = CronJob[]> = {
  jobs: TJobs;
  /** Opaque revision for the complete filtered, sorted result set. */
  snapshotRevision: string;
  total: number;
  offset: number;
  limit: number;
  hasMore: boolean;
  nextOffset: number | null;
};
//#endregion
//#region src/cron/service/state.d.ts
type CronExecutionIdentityAdmission = {
  ingress: ExecutionIdentityAdmissionFacts["ingress"];
  invoker?: ExecutionIdentityAdmissionFacts["invoker"];
  onPostAdmission?: (context: AdmittedRunContext) => void | Promise<void>;
};
/** Direct-run mode: respect due time, force execution, or run immediately while enabled. */
type CronRunMode = "due" | "force" | "if-enabled";
/** Main-session wake strategy used after enqueuing cron text. */
type CronWakeMode = "now" | "next-heartbeat";
type CronStatusSummary = {
  enabled: boolean;
  triggersEnabled: boolean;
  /** @deprecated Alias for `sqlitePath`. */
  storePath: string;
  storage: "sqlite";
  /** Resolved path to the shared state SQLite database. */
  sqlitePath: string;
  jobs: number;
  nextWakeAtMs: number | null;
};
type CronRunResult = {
  ok: true;
  ran: true;
} | {
  ok: true;
  enqueued: true;
  runId: string;
} | {
  ok: true;
  ran: false;
  reason: "disabled";
} | {
  ok: true;
  ran: false;
  reason: "not-due";
} | {
  ok: true;
  ran: false;
  reason: "already-running";
} | {
  ok: true;
  ran: false;
  reason: "invalid-spec";
} | {
  ok: true;
  ran: false;
  reason: "stopped";
} | {
  ok: true;
  ran: false;
  reason: "ownerless";
} | {
  ok: false;
};
/** Remove result, including deferred base-session cleanup after durable deletion. */
type CronRemoveResult = {
  ok: true;
  removed: boolean;
  activeRunCancellationRequested?: true;
  sessionCleanup?: "pending";
} | {
  ok: false;
  removed: false;
};
type CronDeclarativeAddResult = CronStoredJob & {
  created: boolean;
  updated?: boolean;
  job: CronStoredJob;
};
type CronAddResult = CronStoredJob | CronDeclarativeAddResult;
type CronUpdateResult = CronJob;
type CronListResult = CronJob[];
type CronAddInput = CronJobCreate;
type CronUpdateInput = CronJobPatch;
/** Authenticated caller provenance used only when a tool policy is explicitly adopted. */
type CronUpdateOptions = Pick<CronAddOptions, "operatorSource" | "operatorSourceExecutionRevision" | "toolsAllowProvenance" | "toolsAllowExecTarget" | "commitGuard" | "captureRuntimeAuthority" | "inferenceBinding" | "execPolicy" | "streamExecApproval" | "streamSandbox" | "sessionEntryCurrent"> & {
  /** Parent incarnation recorded by `automations bind`; only fills an absent link. */
  bindSourceConversation?: NonNullable<CronStoredJob["sourceConversation"]>;
  /** Null forbids policy adoption; undefined retains in-process operator defaults. */
  scheduledToolPolicy?: CronScheduledToolPolicy | null;
};
type CronCommitGuardOptions = {
  /** Synchronous Gateway-owned liveness check repeated at mutation admission and commit. */
  commitGuard?: () => void;
};
type CronRemoveOptions = CronCommitGuardOptions & {
  systemOwned?: boolean;
  /** The reviewed definition must still match at the store lock and durable commit. */
  expectedConfigRevision?: string;
};
/** Cron-store-locked guard evaluated against the current job before an update applies. */
type CronUpdatePrecondition = (job: CronJob, nowMs: number) => void | Promise<void>;
//#endregion
//#region src/agents/agent-run-terminal-receipt.d.ts
type AgentRunTerminalReceipt = {
  runId: string;
  sessionId: string;
  turnId: string;
  requested: ProviderModelRef;
  effective: ProviderModelRef & {
    responseModel: string;
  };
  successfulToolNames: string[];
  /** Exact saved assistant occurrence, independent of attempt terminal ownership. */
  assistantTranscriptIdempotencyKey?: string;
  /** A final reply was delivered to the external source conversation. */
  sourceReplyDelivered?: true;
  rerouted: boolean;
  terminalDisposition: "visible" | "not-visible";
};
//#endregion
//#region src/agents/provider-model-auth-source-plan.d.ts
type ProviderModelAuthEvidence = "aws-sdk" | "environment" | "none" | "profile" | "provider-config" | "runtime" | "synthetic";
/**
 * Whether config authorizes this credential, as opposed to where it was found.
 *
 * `evidence` is provenance and is reported as such by status/probe surfaces; it
 * cannot carry authorization, because a *declared* credential can legitimately
 * be discovered in the environment (a `${VAR}` marker or a SecretRef naming a
 * canonical variable). `"ambient"` means the opposite: the credential appears in
 * neither the provider entry nor `auth.profiles`/`auth.order`, so nothing in
 * config points at it and it may bill an account the operator never named here.
 */
type ProviderModelAuthAuthorization = "declared" | "ambient";
/** Secret-free credential-source fact safe to carry across request boundaries. */
type ProviderModelAuthSourceClassification = {
  kind: "profile";
} | {
  kind: "direct";
  evidence: ProviderModelAuthEvidence;
  authorization: ProviderModelAuthAuthorization;
};
//#endregion
//#region src/agents/runtime-plan/credential-source.types.d.ts
/** Secret-free credential source shared by runtime planning and terminal results. */
type AgentRuntimeCredentialSource = ProviderModelAuthSourceClassification | {
  kind: "none";
};
//#endregion
//#region src/agents/usage.d.ts
type ContextUsage$1 = NonNullable<Usage["contextUsage"]>;
type PromptTokenDetails = {
  cached_tokens?: number;
  cache_write_tokens?: number;
  cache_creation_input_tokens?: number;
};
type UsageTokenFields = {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  cacheWrite1h?: number;
  cacheWrite5m?: number;
  cacheTelemetry?: Usage["cacheTelemetry"];
  contextUsage?: ContextUsage$1;
  usageReport?: Usage["usageReport"];
  reasoningTokens?: number;
  total?: number;
};
type UsageLike = UsageTokenFields & {
  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;
  cache_creation?: {
    ephemeral_1h_input_tokens?: number;
  };
  reasoning_tokens?: number;
  completion_tokens_details?: {
    reasoning_tokens?: number;
  };
  output_tokens_details?: {
    reasoning_tokens?: number;
    thinking_tokens?: number;
  };
  cached_tokens?: number;
  input_tokens_details?: PromptTokenDetails;
  prompt_tokens_details?: PromptTokenDetails;
  cached_input_tokens?: number;
  cache_write_input_tokens?: number;
  cached?: 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;
  };
  cost?: Partial<Usage["cost"]>;
};
type NormalizedUsage = UsageTokenFields & {
  cost?: Pick<Usage["cost"], "total" | "totalOrigin"> & Partial<Pick<Usage["cost"], "input" | "output" | "cacheRead" | "cacheWrite">>;
  /** Aggregated candidate prices are authoritative, including zero and unavailable totals. */
  costStatus?: "complete" | "unavailable";
};
declare function normalizeUsage(raw?: UsageLike | null): NormalizedUsage | undefined;
//#endregion
//#region src/agents/embedded-agent-runner/result.types.d.ts
type EmbeddedAgentMeta = {
  sessionId: string;
  sessionFile?: string;
  provider: string;
  model: string;
  contextTokens?: number;
  contextTokensSource?: "runtime" | "runtime-configured" | "resolved" | "resolved-v1";
  agentHarnessId?: string;
  /** Sanitized provider-policy refusal attached to this physical attempt. */
  providerRefusal?: {
    provider?: string;
    category?: string;
    review?: ProviderRefusalReview;
    /** Physical request facts used only to retry the same model and account. */
    accessProgram?: "standard" | "daybreak_blue" | "daybreak_red";
    authProfileId?: string;
    nativeThreadId?: string;
    nativeTurnId?: string;
  };
  /** Runtime-owned selection, independent of the final response or credential source. */
  runtimeModelSelection?: ProviderModelRef;
  /** Redacted credential source selected for the terminal physical model attempt. */
  credentialSource?: AgentRuntimeCredentialSource;
  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;
  /** Billing totals may span candidates; unavailable context prevents treating them as a snapshot. */
  usage?: NormalizedUsage;
  /** Terminal cumulative usage for turn-level diagnostics and persisted CLI transcript accounting. */
  diagnosticUsage?: NormalizedUsage;
  /**
   * 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?: NormalizedUsage;
  contextBudgetStatus?: SessionContextBudgetStatus;
  /**
   * True when code mode owned the model tool surface for this run. Config
   * alone is not proof: the "auto" tier engages per model capability, raw
   * model runs and plugin-harness surfaces can decline engagement, and the
   * shell tool is also named `exec`, so consumers must read this flag
   * instead of config or tool names.
   */
  codeModeEngaged?: boolean;
  /** Completed assistant/provider round trips accumulated across run attempts. */
  assistantTurns?: number;
  /**
   * Code-mode/tool-search inner bridge calls for the run's catalog. These are
   * invisible to the provider; `toolSummary.calls` stays the outer count.
   */
  bridgeCalls?: {
    search: number;
    describe: number;
    call: number;
  };
  /** Estimated USD cost of the run's accumulated usage. Omitted when the model has no cost data. */
  costUsd?: number;
  terminalReceipt?: Omit<AgentRunTerminalReceipt, "terminalDisposition">;
};
type TraceAttempt = {
  provider: string;
  model: string;
  result: "success" | "timeout" | "surface_error" | "candidate_failed" | "rotate_profile" | "same_model_transient" | "fallback_model" | "aborted" | "error";
  reason?: string;
  stage?: "prompt" | "assistant";
  elapsedMs?: number;
  status?: number;
};
type ToolSummaryTrace = {
  calls: number;
  tools: string[];
  failures?: number;
  /** Latest tool failure not cleared by same-tool success, independent of reply presentation. */
  unresolvedError?: {
    toolName: string;
  };
  totalToolTimeMs?: number;
};
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 EmbeddedRunTerminalToolFailure = {
  source: "tool";
  toolName: "exec" | "wait";
  code: "UNKNOWN_TOOL_ID";
};
type EmbeddedAgentRunMeta = {
  durationMs: number;
  agentMeta?: EmbeddedAgentMeta;
  aborted?: boolean;
  systemPromptReport?: SessionSystemPromptReport;
  finalPromptText?: string;
  finalAssistantVisibleText?: string;
  finalAssistantRawText?: string;
  /**
   * Raw text of only the model's own latest message; "" when that message had
   * no final text (empty, or it ended in a tool call). finalAssistantRawText can
   * be cumulative (CLI) or runner-substituted earlier text, so diagnostics prefer
   * this field. Unset when the runtime exposes no message (assistantTexts only).
   */
  finalAssistantMessageRawText?: string;
  replayInvalid?: boolean;
  livenessState?: EmbeddedRunLivenessState;
  timeoutPhase?: AgentRunTimeoutPhase;
  providerStarted?: boolean;
  /** Target of a fallback/restoration notice confirmed by the transcript writer for this run. */
  modelFallbackTranscriptToModel?: string;
  /** Producer-owned terminal cause; the fallback owner decides whether a chain was stopped. */
  modelFallbackStopReason?: "agent_run_terminal_timeout" | "idle_timeout_circuit_breaker" | "provider_review_continuation";
  agentHarnessResultClassification?: "empty" | "reasoning-only" | "planning-only";
  /** An exact, successfully settled tool batch intentionally completed the turn without a reply. */
  intentionalTerminalCompletion?: "tool-batch";
  terminalReply?: AgentRunTerminalReplySnapshot;
  terminalReplyExpectation?: ReplyExpectation;
  /** Retain a failed internal result without a user-facing retry notice. */
  suppressErrorNotice?: boolean;
  yielded?: boolean;
  /** Explicit user-facing waiting status supplied to sessions_yield. */
  yieldAcknowledgment?: string;
  /**
   * A visible parent delegated its otherwise-empty result to completion children
   * or a detached media run.
   */
  continuationPending?: true;
  error?: {
    kind: "context_overflow" | "compaction_failure" | "compaction_replay_refresh_required" | "role_ordering" | "image_size" | "retry_limit" | "incomplete_turn" | "hook_block";
    message: string;
    code?: string;
    /** True only when model fallback can retry this terminal error without repeating side effects. */
    fallbackSafe?: boolean;
    /** True when the payload includes a trusted structured terminal tool summary. */
    terminalPresentation?: boolean;
  };
  failureSignal?: EmbeddedRunFailureSignal;
  /** Bounded, sanitized unresolved Code Mode failure for operator diagnostics. */
  terminalToolFailure?: EmbeddedRunTerminalToolFailure;
  /** 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?: {
    winnerProvider?: string;
    winnerModel?: string;
    attempts?: TraceAttempt[];
    fallbackUsed?: boolean;
    runner?: "embedded" | "cli";
    providerPolicyRetry?: {
      category: "cyber";
      provider: string;
      model: string;
    };
  };
  requestShaping?: {
    authMode?: string;
    thinking?: string;
    thinkingClamp?: string;
    reasoning?: string;
    verbose?: string;
    trace?: string;
    fallbackEligible?: boolean;
    blockStreaming?: string;
  };
  promptSegments?: {
    key: string;
    chars: number;
  }[];
  toolSummary?: ToolSummaryTrace;
  completion?: {
    finishReason?: string;
    stopReason?: string;
    refusal?: boolean;
  };
  contextManagement?: {
    sessionCompactions?: number;
    lastTurnCompactions?: number;
    preflightCompactionApplied?: boolean;
    postCompactionContextInjected?: boolean;
  };
};
type EmbeddedAgentRunPayload = {
  text?: string;
  mediaUrl?: string;
  mediaUrls?: string[];
  replyToId?: string;
  isError?: boolean;
  isStatusNotice?: boolean;
  isReasoning?: boolean;
  /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
  isCommentary?: boolean;
  audioAsVoice?: boolean;
  trustedLocalMedia?: boolean;
  channelData?: Record<string, unknown>;
};
//#endregion
//#region src/agents/resolved-tool-prompt.types.d.ts
/** Caller-owned guidance finalized after the native runner selects its tools. */
type ResolvedToolPromptFinalizer = (params: {
  prompt: string;
  messageToolAvailable: boolean;
}) => string;
//#endregion
//#region src/infra/outbound/source-delivery-plan.types.d.ts
/** Owner responsible for making source delivery visible to the user. */
type SourceVisibleDeliveryOwner = "automatic_source" | "message_tool" | "message_tool_then_direct_fallback" | "direct_fallback" | "none";
/** Reason code explaining why source delivery policy took this shape. */
type SourceDeliveryPlanReason = "config" | "room_event" | "cron_announce" | "cron_webhook" | "cron_none" | "media_completion" | "subagent_completion";
/** Configured or inferred destination source delivery must satisfy. */
type SourceDeliveryTarget = {
  channel?: string;
  to?: string;
  accountId?: string;
  threadId?: string | number;
};
/** Message-tool destination observed during a run. */
type SourceDeliveryMessageToolTarget = {
  tool?: string;
  provider?: string;
  accountId?: string;
  to?: string;
  threadId?: string;
  threadImplicit?: boolean;
  threadSuppressed?: boolean;
  text?: string;
  mediaUrls?: string[];
};
/** Visible message-tool delivery with target verification state. */
type SourceDeliveryVisibleDelivery = {
  via: "message_tool";
  target: SourceDeliveryMessageToolTarget;
  verifiedTarget: boolean;
};
/** Resolved source-delivery satisfaction result after a run. */
type SourceDeliveryOutcome = {
  visibleDeliveries: SourceDeliveryVisibleDelivery[];
  verifiedMessageToolDelivery: boolean;
  satisfiesSourceDelivery: boolean;
  unverifiedMessageToolDelivery: boolean;
};
/** Policy contract that decides message-tool ownership and fallback delivery. */
type SourceDeliveryPlan = {
  owner: SourceVisibleDeliveryOwner;
  reason: SourceDeliveryPlanReason;
  target: SourceDeliveryTarget;
  normalFinal: "visible" | "private";
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  messageTool: {
    enabled: boolean;
    force: boolean;
    requireExplicitTarget: boolean;
    requireExplicitTargetEvidence: boolean;
    /** Whether a delivered source send that omits `final` ends the run's turn. */
    finalByDefault: boolean;
  };
  fallback: {
    directDelivery: boolean;
    skipWhenMessageToolSentToTarget: boolean;
  };
};
//#endregion
//#region src/auto-reply/reply/session-event-contract.d.ts
type SessionEventOutcome = {
  status: "completed" | "failed" | "cancelled";
  executionStarted: boolean;
  delivered: boolean;
  /** The settled answer was committed by the existing conversation-result writer. */
  conversationResultCommitted?: true;
  summary?: string;
  nextCheckMs?: number;
  sourceDeliveryOutcome?: SourceDeliveryOutcome;
  automationResult?: CronRunTelemetry & Pick<CronRunOutcome, "replyDisposition" | "diagnostics" | "result">;
  /** Recorded controller restart outcome, before the error is flattened. */
  interruptedByRestart?: boolean;
  error?: string;
  terminalOutcome?: AgentRunTerminalOutcome$1;
  /** Structured cause from the selected, settled runtime attempt. */
  errorReason?: FailoverReason;
  /** Admission policy decides whether a durable producer may retry this refusal. */
  retryable?: boolean;
  deliveryAttempted?: boolean;
  deliveryAmbiguous?: boolean;
  deliveryError?: string;
  deliverySuppressionReason?: NormalizeReplySkipReason;
  admissionDeferred?: boolean;
  admissionDeferredReason?: CronRunOutcome["admissionDeferredReason"];
};
type SessionEventReceipt = {
  id: string;
  cancel: () => boolean;
  /** Resolves after ordinary turn adoption or committed follow-up queue admission. */
  accepted: Promise<{
    ok: true;
  } | {
    ok: false;
    error: string;
  }>;
  settled: Promise<SessionEventOutcome>;
};
type SessionEventTarget$1 = {
  /** Host-captured producer authority, never a structural plugin input. */
  assertCurrent?: () => void;
  /** Captured internal-only completion policy for a retained producer. */
  deliver?: boolean;
  sessionId: string;
  storePath?: string;
  lifecycleRevision?: string;
  generation: string;
  deliveryContext?: DeliveryContext;
  chatType?: SessionEntry["chatType"];
  settings?: Readonly<Pick<SessionEntry, "permissionMode" | "toolOverrides">> | undefined;
  toolsAllow?: string[];
  agentId?: string;
  sessionKey?: string;
};
type SessionEventOptions = {
  agentId: string;
  sessionKey: string;
  source: "exec" | "node" | "task" | "hook" | "restart" | "session" | "device" | "plugin" | "tool_handoff" | "cron" | "cron_failure_repair";
  contextKey?: string;
  /** Stable identity for durable host producers across restart handoffs. */
  sourceTurnId?: string;
  /** Run that started the producer's work; a provenance fact for this turn, never authority. */
  sourceRunId?: string;
  deliveryContext?: DeliveryContext;
  abortSignal?: AbortSignal;
  expectedTarget?: SessionEventTarget$1;
  /** Authorized fresh work may create an absent session; captured completions may not. */
  createIfMissing?: true;
  /** Submitting invocation custody lasts through acceptance only. */
  assertAcceptanceCurrent?: () => void;
  /** Durable producer commits its attempt only after normal turn adoption. */
  onAdopted?: () => void | Promise<void>;
  /** Transfer exact queued occurrences into one ordinary turn without duplicating them. */
  occurrences?: readonly SystemEvent[];
  scheduledAutomation?: ScheduledSessionAutomation;
  /** Failed promotion retains an existing passive occurrence until ordinary adoption begins. */
  preserveOccurrenceOnRejection?: true;
  /** An explicitly silent source records its result without transport delivery. */
  deliver?: boolean;
  /** Host-owned: the producer's prompt permits NO_REPLY; input provenance never selects it. */
  replyExpectation?: "optional";
  /** Host-owned: runtime error payloads stay in the transcript, out of chat delivery. */
  suppressErrorDelivery?: true;
  /** Host producer remains live through admission, execution and delivery. */
  assertCurrent?: () => void;
};
type SessionEventSourcePolicy = Readonly<Pick<SessionEventTarget$1, "toolsAllow" | "settings">>;
/** Cron-owned snapshot and live occurrence fence shared with ordinary reply admission. */
type ScheduledSessionAutomation = {
  job: CronStoredJob;
  /** The occurrence the cron service admitted; the turn's run admission mints from it. */
  occurrence: ScheduledOccurrence;
  /** Selected with this admission's config and session; never persisted on the job. */
  modelFallbackPolicy?: {
    useSubagentFallbacks: boolean;
    inheritDefaultFallbacksForAgentStringModel: boolean;
    /** Stored provenance when the turn uses the session's model selection. */
    sessionModelOverrideSource?: "auto" | "user";
  };
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /** Original Control UI admin classification, revalidated by the restored operator source. */
  controlUiAdmin?: true;
  admissionSource: NonNullable<AdmittedRunContext["admissionSource"]>;
  executionIdentity?: CronExecutionIdentityAdmission;
  deliveryAttemptFence?: CronCompletionDeliveryFence | null;
  assertCurrent: () => void;
  /** Refresh durable occurrence authority before admission or an asynchronous effect. */
  prepare?: () => Promise<void>;
  /** Rebuild source wrapping with the config selected for each admission attempt. */
  preparePrompt?: (cfg: OpenClawConfig) => Promise<string>;
  /** Selected absent notices share the receiver's exact ordinary creation operation. */
  bindSessionCreation?: (operation: SessionEntryCreationOperation) => () => void;
  beforeStart?: (operation?: ReplyOperationObservation) => boolean | NonNullable<CronRunOutcome["admissionDeferredReason"]>;
  /** Retain an on-exit occurrence until existing foreground work settles. */
  waitForIdle?: (signal?: AbortSignal, operation?: ReplyOperationObservation) => Promise<void>;
  onStarted?: () => void;
  onLaneWait?: (info: {
    waiting: boolean;
  }) => void;
  onExecutionStarted?: (info: {
    runId: string;
    sessionId?: string;
    sessionKey: string;
    provider?: string;
    model?: string;
    isFallback?: boolean;
  }) => void;
  onExecutionPhase?: (info: CronAgentExecutionPhaseUpdate) => void;
  beforeDeliver?: () => Promise<void>;
  assertDeliveryCurrent?: () => void;
  sourceDelivery?: SourceDeliveryPlan;
  finalizePromptForResolvedTools?: ResolvedToolPromptFinalizer;
};
/** Producer callbacks stay bound to the queued occurrence, not a later dispatcher. */
type SessionEventExecution = {
  /** Admitted restart continuations can pin without an inline renderer. */
  pinnedWidgetAuthoring?: true;
  /** Admit the prepared input to the occurrence's durable custody before queueing. */
  prepareInput?: (recorder: UserTurnTranscriptRecorder) => Promise<void>;
  /** Original command custody survives process eviction and deferred reply execution. */
  execRequestOwners?: readonly ExecRequestOwner[];
  /** Background producers inherit this turn's automatic-delivery restriction. */
  deliver?: false;
  /** Captured producer and current session policy remain authoritative at final tool I/O. */
  assertCurrent?: () => void;
  /** Bind the original absent target to the normal session writer before its first commit. */
  bindSessionCreation?: (operation: SessionEntryCreationOperation) => () => void;
  beforeStart?: () => Promise<void>;
  /** Scheduled source admission precedes native preparation and lifecycle start. */
  beforeScheduledStart?: (runId: string) => Promise<void>;
  onFailed?: (error: unknown) => void;
  onSuppressed?: (reason: "send-policy" | "room-event" | "silent" | "message-tool-only" | "aborted") => void;
  onStarted: (runId: string) => void;
  /** Final runtime event, after fallback selection and terminal overrides. */
  onTerminalEvent?: (event: Omit<AgentEventPayload, "seq" | "ts">) => void;
  onTerminal: (runId: string, outcome: "completed" | "failed" | "aborted", deliveryEvidence?: {
    didSendViaMessagingTool?: boolean;
    messagingToolSentTargets?: MessagingToolSend[];
    meta?: EmbeddedAgentRunMeta;
    payloads?: EmbeddedAgentRunPayload[];
    resolved?: {
      provider: string;
      model: string;
    };
  }) => void | Promise<void>;
};
//#endregion
//#region src/auto-reply/reply/queue/followup-run-payload.types.d.ts
type FollowupQueueDisposition = Parameters<NonNullable<GetReplyOptions["onFollowupQueueDisposition"]>>[0];
type FollowupRunPayload = {
  /** Original config owner, read only when this input receives a new execution admission. */
  readAdmissionConfig?: () => OpenClawConfig;
  /** External-turn eligibility; queued execution refreshes the session-selected profile. */
  personalBootstrapEligible?: boolean;
  prompt: string;
  /** Original admitted source; queued execution must not replace it with a backend run ID. */
  sourceTurnId?: string;
  /** Fresh channel ingress only; queued execution supplies its admitted owner check. */
  createChannelCronAuthority?: (runId: string, isCurrentOwner?: () => boolean) => CronCreatorAuthorityRunScope | undefined;
  /** Original operator capability retained by this turn's queue/run lifecycle. */
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /**
   * Source turn's trusted owner status for memory audience resolution only. System-owned
   * maintenance copies keep `run.senderIsOwner: false`, so they never gain owner tool authority.
   */
  memoryAudienceSenderIsOwner?: boolean;
  /** Latest session to claim without rewriting the queued run before store refresh. */
  admissionSessionId?: string;
  /** User-visible prompt body persisted to transcript; excludes runtime-only prompt context. */
  transcriptPrompt?: string;
  /** Shared lifecycle owner for the current user-turn transcript append. */
  userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
  currentInboundEventKind?: InboundEventKind;
  /** Whether the current inbound message contained audio for inbound-only TTS policy. */
  currentInboundAudio?: boolean;
  /** Host-minted participant evidence; raw channel identities never live on this object. */
  channelAdmissionEvidence?: ChannelAdmissionEvidence;
  /** Frozen original attach evidence; diagnostic only and never restored from durable queue state. */
  gatewayLocalUserIngress?: GatewayLocalUserIngress;
  /** Explicit current-turn context that should be visible for this run but not persisted as user text. */
  currentInboundContext?: CurrentInboundPromptContext;
  /** Explicit skills resolved from the authenticated inbound message. */
  explicitSkillSelections?: ExplicitSkillSelection[];
  /** Abort signal for turns that are canceled by their source-channel admission fence. */
  abortSignal?: AbortSignal;
  /** Queue-owned cancellation fence used when lifecycle cleanup invalidates pending work. */
  queueAbortSignal?: AbortSignal;
  deliveryCorrelations?: QueuedReplyDeliveryCorrelation[];
  /** Canonical ownership lifecycle for durable ingress / reply-lane transfer. */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
  /** Records terminal queue-cap outcomes at the queue owner before lifecycle cleanup. */
  onQueueDisposition?: (disposition: FollowupQueueDisposition) => void;
  /** Keep delivery bound to the source that owned admission, not later runner defaults. */
  queuedFollowupReplyDisposition?: {
    kind: "deliver";
    deliver: QueuedFollowupReplyDelivery;
  } | {
    kind: "drop";
    reason: "source-unavailable";
  };
  /** Run-lifecycle observers bound to the source request; the drain's runner may belong to another turn. */
  runObservers?: Pick<GetReplyOptions, "onAgentRunStart" | "onPreparedAgentRunStart" | "onAgentRunTerminalOutcome" | "onModelSelected"> & {
    awaitSessionDiffBaseline?: () => Promise<void>;
    prepareAssistantTranscriptMessage?: PrepareAssistantTranscriptMessage;
    resolveReplyDelivery?: ReplyDeliveryObserver;
    resolveReplyDeliveryFacts?: ReplyDeliveryFactsObserver;
    onDeliberateSilentTerminalReply?: () => void;
  };
  /** Provider message ID, when available (for deduplication). */
  messageId?: string;
  summaryLine?: string;
  /** Turn-owned tool authority captured before queue ownership transfers. */
  toolsAllow?: string[];
  disableTools?: boolean;
  /** Force individual drain; never merge this run into a collect batch. */
  disableCollectBatching?: boolean;
  /** Internal Goal nudge; admission must still observe this exact active Goal. */
  goalContinuation?: GoalContinuation;
  /** Internal marker for the one-shot stranded final recovery retry. */
  strandedReplyRetry?: boolean;
  /** This continuation owes last-resort feedback if it also stalls, including claimed input. */
  stalledTurnRecovery?: boolean;
  /** Preserve priority runs when old-item queue overflow eviction runs before drain. */
  protectFromQueueOverflow?: boolean;
  enqueuedAt: number;
  images?: Array<{
    type: "image";
    data: string;
    mimeType: string;
  }>;
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered facts represented by attachment text in this prompt. */
  media?: MediaFact[];
  /**
   * Originating channel for reply routing.
   * When set, replies should be routed back to this provider
   * instead of using the session's lastChannel.
   */
  originatingChannel?: OriginatingChannelType;
  /**
   * Originating destination for reply routing.
   * The chat/channel/user ID where the reply should be sent.
   */
  originatingTo?: string;
  /** Transport-native chat/conversation ID for hook identity context. */
  originatingChatId?: string;
  /** Provider account id (multi-account). */
  originatingAccountId?: string;
  /** Thread id for reply routing (Telegram topic id or Matrix thread event id). */
  originatingThreadId?: string | number;
  /** Provider reply target for transports that model threads as message replies. */
  originatingReplyToId?: string;
  /** Effective reply policy for deciding whether the reply target affects queued delivery. */
  originatingReplyToMode?: ReplyToMode;
  /** Chat type for context-aware threading (e.g., DM vs channel). */
  originatingChatType?: string;
  run: QueuedAgentRunParams & {
    scheduledAutomation?: ScheduledSessionAutomation;
    bootstrapContextMode?: GetReplyOptions["bootstrapContextMode"];
    internalEventExecution?: SessionEventExecution;
    /** Event origin retained after detaching from its occurrence: no channel-turn authority. */
    sessionEventOrigin?: {
      deliver?: false;
    };
    agentId: string;
    agentDir: string;
    runtimePolicySessionKey?: string;
    /** Prepared source delivery ownership; a lost source must not restore host media reads. */
    mediaNormalizationOwner?: "gateway";
    groupId?: string;
    groupChannel?: string;
    groupSpace?: string;
    /** Parent session provenance used to validate inherited group policy. */
    spawnedBy?: string;
    senderId?: string;
    senderName?: string;
    senderUsername?: string;
    senderE164?: string;
    traceAuthorized?: boolean;
    /** Inline choice stays on this run; omission follows the live session preference. */
    traceLevelOverride?: TraceLevel;
    sessionFile: string;
    config: OpenClawConfig;
    provider: string;
    model: string;
    requestedRouteResolution?: ModelFallbackRouteResolution;
    hasSessionModelOverride?: boolean;
    modelOverrideSource?: "auto" | "user";
    hasAutoFallbackProvenance?: boolean;
    /** Session belongs to a spawn-owned child; applies the subagent fallback ladder. */
    subagentSpawnLineage?: boolean;
    autoFallbackPrimaryProbe?: AutoFallbackPrimaryProbe;
    /** Prepared model metadata reused when fallbacks revalidate the immutable thinking request. */
    thinkingCatalog?: ThinkingCatalogEntry[];
    /** Original turn request; model retargeting changes only the effective thinkLevel. */
    readonly thinkLevelOverride?: ThinkLevel | "default";
    fastModeOverride?: boolean;
    fastModeAutoOnSecondsOverride?: boolean;
    /** Explicit turn choice; absent queued replies follow live session verbosity. */
    verboseLevelOverride?: VerboseLevel;
    elevatedLevel?: ElevatedLevel;
    execOverrides?: ExecToolRoutingDefaults;
    bashElevated?: {
      enabled: boolean;
      allowed: boolean;
      defaultLevel: ElevatedLevel;
    };
    blockReplyBreak: "text_end" | "message_end";
    extraSystemPromptStatic?: string;
    cliSessionBindingFacts?: CliSessionBindingFacts;
    skipProviderRuntimeHints?: boolean;
  };
};
//#endregion
//#region src/auto-reply/reply/queue/queue-settings.types.d.ts
type QueueSettings = {
  mode: QueueMode;
  debounceMs?: number;
  cap?: number;
  dropPolicy?: QueueDropPolicy;
};
//#endregion
//#region src/auto-reply/reply/reply-dispatcher.types.d.ts
type ReplyDispatchKind = "tool" | "block" | "final";
type ReplyDispatchSettledCounts = {
  delivered: number;
  deliveredNotVisible: number;
  cancelled: number;
  failedBeforeSend: number;
  failedAfterSend: number;
};
type ReplyDispatchReceipt = {
  counts: Record<ReplyDispatchKind, ReplyDispatchSettledCounts>;
  anyVisibleDelivered: boolean;
  /** Delivery is queued or ambiguous; another send could duplicate it. */
  hasPendingDelivery?: true;
};
type ReplyFollowupAdmissionBarrierTimeoutPolicy = {
  /** Absolute failsafe for owner activity that never settles. */
  maxTimeoutMs: number;
  /** Extend by another default settle interval while bounded owner work remains active. */
  shouldExtend: () => boolean;
};
type ReplyDispatchRuntimeInfo = {
  kind: ReplyDispatchKind;
  assistantMessageIndex?: number;
  /** Display identity for replies in a configured multi-agent group. */
  participant?: {
    agentId: string;
    name: string;
  };
  /** @internal Claim direct-send custody immediately before recipient-visible platform I/O. */
  onPlatformSendDispatch?: () => Promise<void>;
  /** @internal Synchronously fence custody after claiming it and before provider I/O. */
  assertPlatformSendAuthorized?: () => void;
  /** @internal Bind this delivery's host-owned completion to a transformed payload. */
  bindPendingFinalDelivery?: <T extends ReplyPayload$1>(payload: T) => T;
  /** @internal Hand this waiting reply's live progress draft to the children it waits on. */
  adoptProgressDraft?: ProgressContinuationCapability["adopt"];
  /**
   * @deprecated The 2026.9.8 receipt handoff. The host never offers it, so adapters
   * that check for it keep ordinary waiting-reply delivery. Use `adoptProgressDraft`;
   * removal requires an announced ordinary stable release window.
   */
  adoptProgressContinuation?: (this: void, receipt: ProgressContinuationReceipt) => Promise<boolean>;
};
type ReplyDispatchBeforeDeliver = (payload: ReplyPayload$1, info: ReplyDispatchRuntimeInfo) => Promise<ReplyPayload$1 | null> | ReplyPayload$1 | null;
/** An owner-declared settlement budget for one before-delivery callback. */
type ReplyDispatchBeforeDeliverOptions = {
  /** Positive finite per-callback deadline in milliseconds; omit for the dispatcher default. */
  timeoutMs?: number;
};
type ReplyDispatcher = {
  /** @internal Preserve the delivery owner's preparation through dispatcher wrappers. */
  prepareReplyPayload?: (kind: ReplyDispatchKind, payload: ReplyPayload$1) => NormalizeReplyOutcome<ReplyPayload$1>;
  sendToolResult: (payload: ReplyPayload$1) => boolean;
  sendBlockReply: (payload: ReplyPayload$1) => boolean;
  sendFinalReply: (payload: ReplyPayload$1) => boolean;
  /** Preserve prepared text and fields through dispatch without raw directive parsing. */
  sendPreparedReply?: (kind: ReplyDispatchKind, plan: OutboundPayloadPlan) => boolean;
  appendBeforeDeliver?: (hook: ReplyDispatchBeforeDeliver, options?: ReplyDispatchBeforeDeliverOptions) => void;
  supportsSettledReceipt?: true;
  waitForIdle: () => Promise<void | ReplyDispatchReceipt>;
  /** @deprecated Use settled delivery receipts; this retains admission-time counts. */
  getQueuedCounts: () => Record<ReplyDispatchKind, number>;
  /** @deprecated Read cancellation counts from settled delivery receipts. */
  getCancelledCounts?: () => Record<ReplyDispatchKind, number>;
  /** @deprecated Read failure counts from settled delivery receipts. */
  getFailedCounts: () => Record<ReplyDispatchKind, number>;
  markComplete: () => void;
  /** Owner-declared deadline for holding queued follow-ups behind all queued deliveries. */
  resolveFollowupAdmissionBarrierTimeoutPolicy?: () => ReplyFollowupAdmissionBarrierTimeoutPolicy | undefined;
};
//#endregion
//#region src/plugins/cli-backend-turn-status.types.d.ts
/** Content-free facts, never proof of model progress or authority to stop a turn. */
type CliBackendTurnAssessment = {
  state: "closed";
  basis: "process_exited" | "transport_closed";
} | {
  state: "unknown";
  basis: "process_present" | "status_unsupported" | "busy" | "transient_error";
};
/** Capture the exact native input/generation without submitting work or changing hooks. */
type CliBackendTurnStatus = {
  capture(): {
    isCurrent(): boolean;
    assess(params: {
      signal: AbortSignal;
    }): Promise<CliBackendTurnAssessment>;
  } | undefined;
};
//#endregion
//#region src/sessions/session-controller.turn-status.types.d.ts
type ReplyBackendTurnAssessment = CliBackendTurnAssessment | {
  state: "unknown";
  basis: "timeout" | "failed" | "invalid";
};
type ReplyBackendTurnStatus = {
  capture(): {
    isCurrent(): boolean;
    assess(params: {
      signal: AbortSignal;
    }): Promise<ReplyBackendTurnAssessment>;
  } | undefined;
};
//#endregion
//#region src/sessions/session-controller.watchdog-state.d.ts
type SessionWatchdogWaitKind = "global_capacity" | "deferred_maintenance" | "human_question" | "approval" | "runtime_owned" | "retry" | "backend";
type OwnedWait = {
  kind: SessionWatchdogWaitKind;
  deadlineAtMs?: number;
  rateLimitStopMessage?: string;
  /** A runtime-owned wait whose release hands a finished turn back to its run. */
  releaseStartsSemanticWindow?: boolean;
  isCurrent: () => boolean;
};
type SessionWatchdogPhase = "active" | "finishing" | "terminal" | "settled";
type SessionWatchdogSnapshot = Readonly<{
  current: boolean;
  phase: SessionWatchdogPhase;
  hasActiveAttempt?: boolean;
  semanticProgressAtMs: number;
  lastProgressReason?: string;
  warningMs: number;
  semanticDeadlineAtMs: number;
  executionDeadlineAtMs?: number;
  cleanupDeadlineAtMs?: number;
  waits: ReadonlyArray<{
    kind: SessionWatchdogWaitKind;
    deadlineAtMs?: number;
  }>;
  requests?: ReadonlyArray<{
    requestTimeoutMs?: number;
    deadlineAtMs?: number;
  }>;
  tools: ReadonlyArray<{
    toolName: string;
    toolCallId: string;
    startedAtMs: number;
    explicitDeadlineAtMs?: number;
    deadlineAtMs: number;
  }>;
  recovery?: {
    status: "pending" | "blocked" | "settled";
    startedAtMs: number;
    error?: string;
  };
}>;
type SessionWatchdogDecision = Readonly<{
  action: "observe" | "warn" | "stop" | "expire_cleanup" | "blocked";
  reason: string;
  deadlineAtMs?: number;
}>;
//#endregion
//#region src/sessions/session-controller.watchdog.types.d.ts
type SessionWatchdogProgress = "semantic" | "transport" | "source_arrival" | "finalization";
type SessionWatchdogWait = {
  close: () => void;
  updateDeadline(deadlineAtMs: number): void;
};
type SessionControllerWatchdogAttempt = {
  isCurrent(): boolean;
  progress(kind: SessionWatchdogProgress, reason?: string): boolean;
  progressModel(reason?: string): boolean;
  observeStagnation(params: {
    active: boolean;
    existingOnly?: boolean;
  }): void;
  progressTool(toolCallId: string, allowedNames: readonly string[]): boolean;
  beginWait(wait: OwnedWait): SessionWatchdogWait;
  beginTool(tool: {
    toolCallId: string;
    toolName: string;
    deadlineAtMs?: number;
  }): (completed?: boolean) => void;
  toolEvent(event: {
    phase: "start" | "end";
    toolCallId: string;
    toolName: string;
    deadlineAtMs?: number;
  }): void;
  beginRequest(params: {
    deadlineAtMs?: number;
    requestTimeoutMs?: number;
  }): (recoveryDeadlineAtMs?: number) => void;
  requestEvent(event: {
    phase: "start" | "end";
    callId: string;
    requestTimeoutMs?: number;
  }): void;
  setExecutionDeadline(deadlineAtMs: number | undefined): void;
  close(): void;
};
type SessionControllerWatchdog = {
  start(): void;
  close(): void;
  snapshot(now?: number): SessionWatchdogSnapshot;
  decide(now?: number): SessionWatchdogDecision;
  tick(now?: number): Promise<SessionWatchdogDecision>;
  progress(kind: SessionWatchdogProgress, reason?: string): boolean;
  beginWait(wait: OwnedWait): SessionWatchdogWait;
  attachAttempt(params: {
    assertCurrent: () => void;
    /** Nested maintenance shares the current attempt's lifetime without replacing it. */
    nested?: boolean;
  }): SessionControllerWatchdogAttempt;
  describeStop(): {
    staleReason: "no_activity" | "rate_limited";
    error: Error;
  };
  beginFinalization(): void;
  beginTerminal(deadlineAtMs?: number): void;
  beginExecution(getDeadlineAtMs?: () => number | undefined, recoverDeadline?: () => Promise<boolean>): {
    setDeadline(deadlineAtMs: number | undefined): void;
    close(): void;
  };
  beginFinalizationWork(timeoutMs: number): () => void;
};
//#endregion
//#region src/auto-reply/reply/reply-run-finalization-lease.d.ts
type ReplyOperationStaleReason = "terminal_unreleased" | "finalization_stalled" | "no_activity" | "rate_limited" | "stuck_recovery";
//#endregion
//#region src/config/sessions/session-actor-delivery-evidence.types.d.ts
/** Already validated by the host; live authority is checked again at commit. */
type SessionActorDeliveryEvidence = {
  result?: {
    channel: string;
    target?: {
      id: string;
    };
    platformMessageId?: string;
    resultCount?: number;
    /** Host validated every reported physical route against this exact captured context. */
    verifiedContext?: DeliveryContext;
  };
};
//#endregion
//#region src/boards/board-layout.d.ts
type BoardValidationErrorCode = "conflict" | "invalid_operation" | "not_found";
declare class BoardValidationError extends Error {
  readonly code: BoardValidationErrorCode;
  constructor(code: BoardValidationErrorCode, message: string);
}
//#endregion
//#region src/boards/board-store.d.ts
type BoardWidgetHtmlDocument = {
  html: string;
  revision: number;
  sha256: string;
  viewGeneration: string;
  grantState: "none" | "pending" | "granted" | "rejected";
  declared?: BoardWidgetDeclared;
  resourceOrigins?: string[];
};
type BoardWidgetHtmlViewMetadata = Omit<BoardWidgetHtmlDocument, "html">;
type BoardWidgetMcpAppDocument = {
  descriptor: BoardMcpAppDescriptor;
  revision: number;
  instanceId: string;
  grantState: "none" | "pending" | "granted" | "rejected";
  declaredTools: string[];
  interactive: boolean;
};
type BoardWidgetDocument = BoardWidgetHtmlDocument | BoardWidgetMcpAppDocument;
type BoardSnapshotWithHtmlViewMetadata = {
  snapshot: BoardSnapshot;
  htmlViewMetadata: ReadonlyMap<string, BoardWidgetHtmlViewMetadata>;
};
//#endregion
//#region src/boards/session-actor-board-contract.d.ts
type SessionActorBoardReads = {
  "boards.snapshot": {
    input: {
      sessionKey: string;
    };
    output: BoardSnapshotWithHtmlViewMetadata;
  };
  "boards.document": {
    input: {
      sessionKey: string;
      name: string;
      contentKind?: "mcp-app";
    };
    output: BoardWidgetDocument | undefined;
  };
};
type SessionActorBoardWrites = {
  "boards.applyOps": {
    input: {
      sessionKey: string;
      ops: readonly BoardOp[];
    };
    output: BoardSnapshot;
  };
  "boards.putWidget": {
    input: {
      sessionKey: string;
      params: BoardWidgetMaterializedPutParams;
      viewGeneration: string;
    };
    output: BoardWidgetPutResult;
  };
  "boards.grant": {
    input: {
      sessionKey: string;
      name: string;
      decision: "granted" | "rejected";
      revision: number;
      instanceId?: string;
    };
    output: BoardSnapshot;
  };
};
//#endregion
//#region src/session-cards/progress-card-values.d.ts
type ProgressCardWrite = {
  markdown?: string;
  steps?: ProgressCardStep[];
  expectedRevision?: number;
};
//#endregion
//#region src/session-cards/session-actor-progress-card-contract.d.ts
type SessionActorProgressCardReads = {
  "progressCard.get": {
    input: {
      sessionKey: string;
    };
    output: ProgressCard | null;
  };
};
type SessionActorProgressCardWrites = {
  "progressCard.put": {
    input: ProgressCardWrite & {
      sessionKey: string;
    };
    output: {
      card: ProgressCard | null;
    } | {
      cleared: true;
    };
  };
  "progressCard.clearForReset": {
    input: {
      sessionKey: string;
    };
    output: boolean;
  };
};
//#endregion
//#region src/config/sessions/session-entry-metadata-receipt.d.ts
type SessionEntryMetadataFact = {
  entry: InternalSessionEntry;
  fullEntry?: InternalSessionEntry;
  previous?: Pick<InternalSessionEntry, "sessionId" | "lifecycleRevision">;
  facts: Extract<SessionRowFacts, {
    kind: "entry";
  }>;
  sharingChange: "changed" | "unchanged";
};
type SessionEntryMetadataReceipt = SqliteCommitReceipt<SessionEntryMetadataFact, SessionEntryPublicationSource>;
//#endregion
//#region src/config/sessions/session-sharing-store.types.d.ts
type SessionSharingExpectedEntry = Pick<SessionEntry, "sessionId" | "createdActor" | "visibility" | "incognito">;
type SessionMetadataExpectedEntry = SessionSharingExpectedEntry & Pick<SessionEntry, "lifecycleRevision">;
type SessionOwnerAssignParams = {
  owner: SessionActor$1 & {
    id: string;
  };
  assignedBy: SessionActor$1 & {
    id: string;
  };
  assignedAt?: number;
  expectedSessionId?: string;
  expectedEntry?: SessionMetadataExpectedEntry;
};
type StoredSessionSuggestionState = "pending" | "accepted" | "dismissed";
type StoredSessionSuggestionResolution = "send" | "queue" | "edit" | "dismiss";
type StoredSessionSuggestion = {
  id: string;
  authorId: string;
  authorLabel?: string;
  text: string;
  createdAt: number;
  state: StoredSessionSuggestionState;
};
type SessionSuggestionListParams = {
  authorId?: string;
  pendingOnly?: boolean;
};
type SessionSuggestionDispatchClaim = {
  kind: "busy";
} | {
  kind: "mismatch";
  resolution: StoredSessionSuggestionResolution;
} | {
  kind: "claimed";
  suggestion: StoredSessionSuggestion;
  token: string;
};
type SessionSuggestionAddParams = {
  authorId: string;
  authorLabel?: string;
  text: string;
  createdAt?: number;
  id?: string;
  expectedSessionId?: string;
  expectedEntry?: SessionMetadataExpectedEntry;
};
type SessionSuggestionClaimParams = {
  id: string;
  expectedSessionId?: string;
  resolution: StoredSessionSuggestionResolution;
  now?: number;
  expectedEntry?: SessionMetadataExpectedEntry;
};
type SessionSuggestionReleaseParams = {
  id: string;
  token: string;
  expectedSessionId?: string;
};
type SessionSuggestionFinalizeParams = SessionSuggestionReleaseParams & {
  state: Exclude<StoredSessionSuggestionState, "pending">;
  expectedEntry?: SessionMetadataExpectedEntry;
};
type OwnerPublication = {
  facts?: Extract<SessionRowFacts, {
    kind: "owner";
  }>;
};
type SessionMemberAdd = {
  identityId: string;
  addedBy: string;
  addedAt?: number;
  expectedSessionId?: string;
  expectedEntry?: SessionSharingExpectedEntry;
};
type SessionParticipantRecordInput = {
  identity: SessionParticipantIdentity;
  promptedAt?: number;
  sessionAgentId?: string;
};
type RecordSessionParticipantResult = "inserted" | "updated" | "capped";
type MembershipPublication = {
  facts?: Extract<SessionRowFacts, {
    kind: "member";
  }>;
};
type ParticipantPublication = {
  projectionChanged: boolean;
  participants: Pick<SessionEntry, "participants" | "participantCount">;
  records?: SessionParticipantRecord[];
  actorVersion?: SessionActorVersion;
};
type SessionInvolvementMutation = {
  expectedSessionId: string;
  expectedEntry?: SessionMetadataExpectedEntry;
  profileIds: readonly string[];
  change: {
    kind: "visibility";
    hidden: boolean;
  } | {
    kind: "mention";
    source: NonNullable<SessionProfileInvolvement["lastMention"]>;
  };
};
type SessionSharingWorkerOperations = {
  involvement: {
    input: {
      scope: SessionAccessScope;
      params: SessionInvolvementMutation;
      profiles: {
        profileId: string;
        aliases: string[];
      }[];
    };
    output: {
      accepted: boolean;
      changed: boolean;
    };
  };
  "owner.assign": {
    input: {
      scope: SessionAccessScope;
      params: SessionOwnerAssignParams;
    };
    output: {
      value: SessionOwnerAssignment | null;
    } & OwnerPublication;
  };
  "suggestion.add": {
    input: {
      scope: SessionAccessScope;
      params: SessionSuggestionAddParams;
    };
    output: StoredSessionSuggestion;
  };
  "suggestion.claim": {
    input: {
      scope: SessionAccessScope;
      params: SessionSuggestionClaimParams;
    };
    output: SessionSuggestionDispatchClaim | null;
  };
  "suggestion.release": {
    input: {
      scope: SessionAccessScope;
      params: SessionSuggestionReleaseParams;
    };
    output: boolean;
  };
  "suggestion.finalize": {
    input: {
      scope: SessionAccessScope;
      params: SessionSuggestionFinalizeParams;
    };
    output: StoredSessionSuggestion | null;
  };
  "category.prepare": {
    input: {
      scope: SessionAccessScope;
      from: string;
    };
    output: string[];
  };
  "category.apply": {
    input: {
      scope: SessionAccessScope;
      from: string;
      to?: string;
    };
    output: Array<{
      sessionKey: string;
      sessionId: string;
    }>;
  };
  add: {
    input: {
      scope: SessionAccessScope;
      params: SessionMemberAdd;
    };
    output: {
      value: {
        member: SessionMember;
        inserted: boolean;
      };
    } & MembershipPublication;
  };
  remove: {
    input: {
      scope: SessionAccessScope;
      identityId: string;
      expected?: Pick<SessionMember, "addedBy" | "addedAt">;
      expectedSessionId?: string;
      expectedEntry?: SessionSharingExpectedEntry;
    };
    output: {
      value: SessionMember | null;
    } & MembershipPublication;
  };
  participant: {
    input: {
      scope: SessionAccessScope;
      params: SessionParticipantRecordInput;
    };
    output: {
      value: RecordSessionParticipantResult | null;
    } & ParticipantPublication;
  };
};
//#endregion
//#region src/config/sessions/session-actor-memory-collaboration-contract.d.ts
type SessionActorMemoryCollaborationReads = {
  "session.members.read": {
    input: Record<string, never>;
    output: {
      entry: InternalSessionEntry | undefined;
      members: SessionMember[];
    };
  };
  "session.participants.read": {
    input: Record<string, never>;
    output: SessionParticipantRecord[];
  };
  "session.suggestions.read": {
    input: {
      params?: SessionSuggestionListParams;
    };
    output: StoredSessionSuggestion[];
  };
  "session.reactions.read": {
    input: {
      sessionId: string;
    };
    output: Record<string, StoredMessageReactionSummary[]>;
  };
};
type SharingWrites = { [Key in Exclude<keyof SessionSharingWorkerOperations, "category.prepare" | "category.apply"> as `session.collaboration.${Key}`]: {
  input: Omit<SessionSharingWorkerOperations[Key]["input"], "scope"> & (Key extends "participant" ? {
    profileAliases?: string[];
  } : unknown);
  output: SessionSharingWorkerOperations[Key]["output"];
}; };
type SessionActorMemoryCollaborationWrites = SharingWrites & {
  "session.category.apply": {
    input: {
      from: string;
      to?: string;
    };
    output: SessionSharingWorkerOperations["category.apply"]["output"];
  };
  "session.reaction.set": {
    input: {
      params: SetSessionReactionParams;
    };
    output: SessionReactionWrite;
  };
};
//#endregion
//#region src/config/sessions/conversation-authority.types.d.ts
type ConversationAuthority = {
  conversationRef: string;
  expectedRouteFingerprint: string;
  expectedSessionId?: string;
  expectedSessionKey?: string;
};
//#endregion
//#region src/config/sessions/conversation-delivery-store.types.d.ts
type ConversationDeliveryStatus = "created" | "queued" | "sent" | "suppressed" | "rejected" | "unknown" | "replied";
type ConversationDeliveryRecord = {
  operationId: string;
  operationKind: "send" | "turn";
  conversationRef: string;
  channel: string;
  sourceSessionKey?: string;
  messageHash: string;
  status: ConversationDeliveryStatus;
  preparedMessageId?: string;
  platformMessageId?: string;
  queueId?: string;
  rejectionError?: string;
  reply?: {
    messageId: string;
    replyToId?: string;
    threadId?: string;
    text: string;
    timestamp: number;
  };
  createdAt: number;
  updatedAt: number;
};
type ConversationDeliveryInput = {
  operationKind: ConversationDeliveryRecord["operationKind"];
  conversationRef: string;
  sourceSessionKey?: string;
  message: string;
};
type ConversationDeliveryBegin = ConversationDeliveryInput & {
  operationId: string;
  preparedMessageId?: string;
  authority?: ConversationAuthority;
};
type ConversationDeliveryTransition = {
  operationId: string;
  status: ConversationDeliveryStatus;
  queueId?: string | null;
  platformMessageId?: string | null;
  rejectionError?: string | null;
  reply?: ConversationDeliveryRecord["reply"];
  allowedFrom: readonly ConversationDeliveryStatus[];
  session?: {
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
  };
};
type ConversationDeliveryLookup = {
  operationId: string;
  expectedInput?: ConversationDeliveryInput;
} | {
  conversationRef: string;
  replyToId: string;
};
//#endregion
//#region src/config/sessions/conversation-identity.d.ts
type ConversationKind = ChatType;
/** Stable transport address independent from the local session holding model context. */
type ConversationIdentity = {
  conversationRef: string;
  channel: string;
  accountId: string;
  kind: ConversationKind;
  peerId: string;
  deliveryTarget: string;
  parentConversationRef?: string;
  threadId?: string;
  nativeChannelId?: string;
  nativeDirectUserId?: string;
  label?: string;
  metadata?: Record<string, unknown>;
};
//#endregion
//#region src/config/sessions/session-actor-memory-conversation-contract.d.ts
type SessionActorMemoryConversationReads = {
  "session.conversation.read": {
    input: ConversationReadQuery;
    output: ConversationRecord[];
  };
  "session.conversation.authority": {
    input: {
      conversationRef: string;
    } | {
      operationId: string;
    };
    output: {
      operation: {
        conversationRef: string;
      } | undefined;
      conversation: ConversationRecord | undefined;
    };
  };
  "session.conversation.delivery.read": {
    input: ConversationDeliveryLookup;
    output: ConversationDeliveryRecord | undefined;
  };
};
type SessionActorMemoryConversationWrites = {
  "session.conversation.register": {
    input: {
      identities: readonly ConversationIdentity[];
      discoveredAt: number;
      query?: ConversationReadQuery;
    };
    output: ConversationRecord[] | undefined;
  };
  "session.conversation.delivery.begin": {
    input: ConversationDeliveryBegin;
    output: {
      created: boolean;
      record: ConversationDeliveryRecord;
    };
  };
  "session.conversation.delivery.transition": {
    input: ConversationDeliveryTransition;
    output: ConversationDeliveryRecord;
  };
};
//#endregion
//#region packages/memory-host-sdk/src/host/session-reset-recall.d.ts
type SessionResetRecallCutoff = {
  state: "absent";
} | {
  state: "invalid";
} | {
  cutoffLine: number;
  state: "valid";
};
//#endregion
//#region src/config/sessions/session-actor-memory-corpus-contract.d.ts
type Selection = {
  sessionId?: string;
  sessionKey?: string;
};
type SessionActorMemoryCorpusReads = {
  "session.memory.entry": {
    input: Selection & {
      includeMessages?: boolean;
    };
    output: {
      sessionId: string;
      sessionKey: string;
      events: unknown[];
      stats: SessionTranscriptStats;
    } | undefined;
  };
  "session.memory.resetRecall": {
    input: Selection;
    output: SessionResetRecallCutoff;
  };
};
//#endregion
//#region src/config/sessions/ambient-transcript-watermark-projection.d.ts
type AmbientTranscriptWatermarkUpdate = {
  key: string;
  messageId: string;
  timestampMs?: number;
  expectedSessionId?: string;
  now: number;
};
//#endregion
//#region src/config/sessions/metadata-projection.d.ts
type PreparedSessionMetaPatch = {
  /** Undefined for internal turns; an empty declaration clears the previous client. */
  clientCapabilities?: string[];
  group: {
    resolution: GroupKeyResolution;
    nextSubject: string | undefined;
    nextGroupChannel: string | undefined;
    topicName: string | undefined;
    space: string | undefined;
  } | null;
  origin: SessionOrigin | undefined;
  internalTurn: boolean;
  clearAvatar: boolean;
  privateTelegramTopicName?: string;
};
declare function projectLastRoutePatch(params: {
  channel?: string;
  to?: string;
  accountId?: string;
  threadId?: string | number;
  route?: ChannelRouteRef;
  deliveryContext?: DeliveryContext;
  existing: SessionEntry | undefined;
  sessionKey: string;
  metadata?: PreparedSessionMetaPatch;
}): Partial<SessionEntry>;
//#endregion
//#region src/config/sessions/session-entry-projection.d.ts
declare function projectCompactionAccountingPatch(current: InternalSessionEntry, params: {
  amount?: number;
  compactionKind?: "context-engine" | "native-harness" | "server-endpoint";
  now?: number;
  /** Null invalidates an earlier estimate without incrementing the boundary count. */
  tokensAfter?: number | null;
  /** Omission preserves host suppression; null clears it across the worker boundary. */
  transcriptByteCompactionLatch?: InternalSessionEntry["transcriptByteCompactionLatch"] | null;
}): Partial<InternalSessionEntry>;
//#endregion
//#region src/config/sessions/session-entry-usage.d.ts
type SessionEntryUsageUpdate = {
  usage?: NormalizedUsage;
  lastCallUsage?: NormalizedUsage;
  modelSelection: {
    provider?: string;
    model?: string;
  };
  agentHarnessId?: string;
  contextTokensUsed?: number;
  contextTokensSource?: SessionEntry["contextTokensSource"];
  contextBudgetStatus?: SessionEntry["contextBudgetStatus"];
  systemPromptReport?: SessionEntry["systemPromptReport"];
  promptTokens?: number;
  estimatedCostUsd?: number;
  currentContextTokens?: number;
  hasContextUpdate: boolean;
  hasFreshContextSnapshot: boolean;
  hasCurrentContextSnapshot: boolean;
  preserveSessionModelState: boolean;
  preserveUserFacingRunState: boolean;
  preserveFreshTotalTokensOnStaleUsage?: boolean;
};
//#endregion
//#region src/config/sessions/session-run-lifecycle-projection.d.ts
type SessionLifecycleProviderReview = Pick<ProviderReviewTerminalFact, "target" | "expectedWriterRunId" | "review">;
type SessionLifecyclePatchInput = {
  event: LifecycleEventLike;
  currentLifecycleGeneration: string;
  lastRunError?: string;
  canonicalKey: string;
  lifecycleRevision?: string;
  exactCronRun: boolean;
  providerReview?: SessionLifecycleProviderReview;
  expectedWriter?: {
    allowUnstartedFailure?: true;
    requireYielded?: true;
    runId: string;
    sessionId: string;
    lifecycleRevision?: string;
  };
};
type SessionLifecyclePatchEffects = {
  failedRun?: {
    runId: string;
    error: unknown;
    errorKind?: "state_contention";
    suppressErrorNotice?: boolean;
    notice?: string;
  };
};
type LifecycleEventLike = {
  ts: number;
  sessionId?: string;
} & {
  controlUiVisible?: boolean;
  contextClaimId?: string;
  runId?: string;
  clientRunId?: string;
  lifecycleGeneration?: string;
  data?: {
    phase?: unknown;
    startedAt?: unknown;
    endedAt?: unknown;
    aborted?: unknown;
    stopReason?: unknown;
    error?: unknown;
    errorKind?: unknown;
    errorNotice?: unknown;
    suppressErrorNotice?: unknown;
    executionStarted?: unknown;
    livenessState?: unknown;
    timeoutPhase?: unknown;
    providerStarted?: unknown;
    yielded?: unknown;
    status?: unknown;
  };
};
//#endregion
//#region src/config/sessions/session-entry-patch-operation.d.ts
type ExpectedSession = Pick<InternalSessionEntry, "sessionId"> & Partial<Pick<InternalSessionEntry, "lifecycleRevision" | "activeWriterRunId">>;
type SessionEntryBookkeepingReducer = {
  kind: "activity";
  updatedAt: number;
} | {
  kind: "usage";
  update: SessionEntryUsageUpdate;
  updatedAt: number;
} | {
  kind: "goal-continuation";
  goalId: string;
} | {
  kind: "group-intro";
  needsSystemIntro: boolean;
} | {
  kind: "fallback-notice";
  notice: InternalSessionEntry["fallbackNotice"];
} | {
  kind: "live-model";
  expected: Partial<Pick<InternalSessionEntry, "modelProvider" | "model" | "agentHarnessId" | "providerOverride" | "modelOverride" | "agentRuntimeOverride" | "authProfileOverride" | "authProfileOverrideSource" | "liveModelSwitchPending">>;
  next: Pick<InternalSessionEntry, "modelProvider" | "model" | "agentHarnessId">;
  clearPending?: true;
};
/** Closed internal operations; arbitrary updater callbacks retain prepare/CAS. */
type SessionEntryPatchStep = ({
  kind: "fields";
  patch: Partial<InternalSessionEntry>;
} | {
  kind: "writer-revoke";
  runId: string;
  terminalAtMs?: number;
} | {
  kind: "cron-session";
  sessionKey: string;
  initial?: InternalSessionEntry;
  next: InternalSessionEntry;
  creation: ReturnType<typeof buildSessionCreationStamp>;
} | {
  kind: "cron-run-continuation";
  sessionKey: string;
  source: InternalSessionEntry;
  continuation: NonNullable<InternalSessionEntry["cronRunContinuation"]>;
  create: boolean;
  creation: ReturnType<typeof buildSessionCreationStamp>;
  thinkingLevel?: string;
} | {
  kind: "inbound-metadata";
  metadata: PreparedSessionMetaPatch;
  sessionKey: string;
  creation: ReturnType<typeof buildSessionCreationStamp>;
} | {
  kind: "last-route";
  route: Omit<Parameters<typeof projectLastRoutePatch>[0], "existing">;
  creation: ReturnType<typeof buildSessionCreationStamp>;
} | {
  kind: "lifecycle";
  lifecycle: SessionLifecyclePatchInput;
} | {
  kind: "public-fields";
  patch: Partial<InternalSessionEntry>;
} | {
  kind: "observer-digest";
  digest: NonNullable<InternalSessionEntry["observerDigest"]>;
  sessionId?: string;
} | {
  kind: "activity-summary";
  summary: SessionActivitySummary;
  sessionKey: string;
} | {
  kind: "ambient-transcript-watermark";
  watermark: AmbientTranscriptWatermarkUpdate;
} | {
  kind: "ensure-identity";
  sessionId: string;
  creation: ReturnType<typeof buildSessionCreationStamp>;
} | {
  kind: "pending-final-clear";
  sessionId: string;
  intentId: string;
  now: number;
} | {
  kind: "compaction-accounting";
  accounting: Parameters<typeof projectCompactionAccountingPatch>[1];
}) & {
  expected?: ExpectedSession | null;
};
type SessionEntryPatchOperation = SessionEntryPatchStep | {
  kind: "compound";
  operations: readonly SessionEntryPatchStep[];
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-entry-equality.d.ts
type SqliteLifecycleTargetSnapshot = Array<{
  entry: InternalSessionEntry;
  sessionKey: string;
  window?: SessionEntryWindowFacts;
  sideTables?: {
    memberIdsJson: string;
    hasBoard: boolean;
  };
  row?: ResolvedSessionEntryRow["row"];
}>;
//#endregion
//#region src/config/sessions/session-entry-patch.types.d.ts
type SessionEntryPatchSelection = {
  kind: "entry";
  sessionKey: string;
  exact: boolean;
} | {
  kind: "target";
  target: {
    canonicalKey: string;
    storeKeys: string[];
  };
};
type SessionEntryPatchGuard = {
  /** Storage reads prepare before submission; grants consume the prepared host authority. */
  source?: SessionSourceAssertion;
  /** Closed ensure only; its caller revalidates the published identity before effects. */
  ensureIdentitySource?: SessionSourceTransactionGrant;
  /** Retained host authority; same-store predicates belong in the worker transaction. */
  assertCurrent?: () => void;
  /** Check live effect authority at native write and commit grants, never during preparation. */
  assertMutationAllowed?: () => void;
  /** Same-store route authority is reread inside the worker's write transaction. */
  conversation?: ConversationAuthority;
  cliHistory?: {
    sessionId: string;
    admission?: UserTurnTranscriptAdmissionReceipt;
    watermark: SessionTranscriptWatermark;
  };
  shouldCommitIf?: {
    kind: "transcript";
    sessionId: string;
    generation: string | null;
    leafEntryId: string | null;
  };
};
type SessionEntryPatchCommit = {
  selection: SessionEntryPatchSelection;
  prepared: SqliteLifecycleTargetSnapshot;
  sessionKey: string;
  writeBase: InternalSessionEntry;
  next: InternalSessionEntry | undefined;
  operationLabel: "session-entry.patch" | "session-entry-target.patch";
  validateCanonicalKeys: boolean;
  returnEntry?: false;
  retainedEntry?: {
    writeToken: string;
    writeScopes: Parameters<typeof readSqliteDatabaseScopedWriteToken>[1];
  };
  consumePendingReset?: boolean;
  providerReviewMutation?: boolean;
  shouldCommitIf?: SessionEntryPatchGuard["shouldCommitIf"];
  cliHistory?: SessionEntryPatchGuard["cliHistory"];
  conversation?: SessionEntryPatchGuard["conversation"];
  sources?: SessionSourcePredicate[];
  ensureIdentitySource?: Omit<SessionSourceTransactionGrant, "assertCurrent">;
};
type SessionEntryPatchReduction = Omit<SessionEntryPatchCommit, "prepared" | "writeBase" | "next"> & {
  operation: SessionEntryPatchOperation;
  fallbackEntry?: InternalSessionEntry;
  replaceEntry?: boolean;
  preserveActivity?: boolean;
};
type SessionEntryPatchReceipt = {
  kind: "session-entry-patch-committed";
  transferId: number;
};
//#endregion
//#region src/config/sessions/session-actor-memory-entry-contract.d.ts
type MemoryLifecycleArtifactInput = Pick<SessionLifecycleArtifactCleanupParams, "sessionKeySegmentPrefix" | "transcriptContentMarker" | "orphanTranscriptMinAgeMs" | "pluginOwnerId"> & {
  nowMs: number;
};
type MemoryLifecycleArtifactPlan = {
  entries: Array<{
    sessionKey: string;
    expected: InternalSessionEntry;
  }>;
  windows: Array<{
    sessionKey: string;
    sessionId: string;
  }>;
};
type SessionActorMemoryEntryReads = {
  "session.lifecycle.artifacts": {
    input: MemoryLifecycleArtifactInput;
    output: MemoryLifecycleArtifactPlan;
  };
  "session.entry.creation": {
    input: {
      label?: string;
    };
    output: SessionEntryCreateWithTranscriptContext;
  };
  "session.entry.read": {
    input: {
      sessionKey?: string;
      projection?: SessionEntryProjection;
    };
    output: InternalSessionEntry | undefined;
  };
  "session.entry.readById": {
    input: {
      sessionId: string;
      projection?: SessionEntryProjection;
      currentOnly?: boolean;
    };
    output: {
      sessionKey: string;
      entry: InternalSessionEntry;
    } | undefined;
  };
  "session.entries.read": {
    input: {
      projection?: SessionEntryProjection;
      sessionKeys?: readonly string[];
      includeSessionWindowOwner?: string;
      includeLabelOwners?: string;
    };
    output: Array<{
      sessionKey: string;
      entry: InternalSessionEntry;
    }>;
  };
};
/** Prepared overwrites compare the actual entry; typed patches need no read round trip. */
type SessionActorMemoryEntryReplacement = {
  sessionKey: string;
  expected: InternalSessionEntry | undefined;
  entry: InternalSessionEntry | undefined;
  routeContext?: ConversationRouteContext | null;
  label?: string;
  owner?: SessionOwnerAssignment;
  transcriptEvents?: readonly unknown[];
};
type SessionActorMemoryMaintenance = {
  config: ResolvedSessionMaintenanceConfig;
  preservation: SessionMaintenancePreservationSnapshot;
  activeSessionKey?: string;
};
type SessionActorMemoryEntryWrites = {
  "session.entry.create": {
    input: {
      entry: InternalSessionEntry;
      routeContext?: ConversationRouteContext | null;
      expected?: InternalSessionEntry;
      label?: string;
      owner?: SessionOwnerAssignment;
      cwd?: string;
      transcriptEvents?: readonly unknown[];
    };
    output: InternalSessionEntry;
  };
  "session.entry.patch": {
    input: {
      operation: SessionEntryPatchOperation;
      maintenance?: SessionActorMemoryMaintenance;
      fallbackEntry?: InternalSessionEntry;
      preserveActivity?: boolean;
      replaceEntry?: boolean;
      providerReviewMutation?: boolean;
      consumePendingReset?: boolean;
      prepareIf?: {
        kind: "live-model-switch-pending";
      };
      expected?: {
        entry: InternalSessionEntry | undefined;
      };
      guards?: Pick<SessionEntryPatchCommit, "shouldCommitIf" | "cliHistory" | "conversation" | "sources">;
    };
    output: InternalSessionEntry | undefined;
  };
  "session.entry.replace": {
    input: Omit<SessionActorMemoryEntryReplacement, "sessionKey">;
    output: InternalSessionEntry | undefined;
  };
  "session.entry.replacements": {
    input: {
      replacements: readonly SessionActorMemoryEntryReplacement[];
      consumePendingReset?: boolean;
      maintenance?: SessionActorMemoryMaintenance;
    };
    output: {
      removedSessionKeys: string[];
      updatedSessionKeys: string[];
    };
  };
  "session.lifecycle.reset": {
    input: {
      expected: InternalSessionEntry | undefined;
      nextEntry: InternalSessionEntry;
      relatedReplacements?: readonly SessionActorMemoryEntryReplacement[];
      routeContext?: ConversationRouteContext | null;
      resetBoundary?: SessionResetBoundaryWrite;
    };
    output: ResetSessionEntryLifecycleResult & {
      progressCardReset: boolean;
    };
  };
  "session.lifecycle.delete": {
    input: {
      expectedEntry?: InternalSessionEntry;
      expectedSessionId?: string | null;
      expectedLifecycleRevision?: string;
      expectedUpdatedAt?: number;
    };
    output: DeleteSessionEntryLifecycleResult;
  };
  "session.lifecycle.reclaim": {
    input: {
      entries: readonly {
        sessionKey: string;
        expected: InternalSessionEntry;
        requiresMissingTranscript?: true;
      }[];
      archives?: readonly {
        sessionKey: string;
        expected: InternalSessionEntry;
        entry: InternalSessionEntry;
      }[];
      artifacts?: {
        input: MemoryLifecycleArtifactInput;
        windows: MemoryLifecycleArtifactPlan["windows"];
      };
    };
    output: {
      removedSessionKeys: string[];
      archivedSessionKeys: string[];
      beforeCount: number;
      afterCount: number;
    };
  };
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-parent-fork.d.ts
type ParentForkSourceTranscript = {
  appendMode?: "side";
  appendParentId: string | null;
  branchEntries: TranscriptEvent[];
  cwd?: string;
  version: number;
  labelsToWrite: Array<{
    targetId: string;
    label: string;
    timestamp: string;
  }>;
  leafId: string | null;
  preserveLeafControl: boolean;
};
//#endregion
//#region src/plugin-state/plugin-state-native-binding.types.d.ts
type PluginStateNativeBindingCodec = "codex" | "agentsapi";
type PluginStateNativeBindingPlan = {
  codec: PluginStateNativeBindingCodec;
  codecSource?: {
    rootDir: string;
    source: string;
    origin: PluginOrigin$1;
  };
  predicate: {
    kind: "absent";
  } | {
    kind: "leased";
    token: string;
    value: unknown;
  };
  pluginId: string;
  namespace: string;
  key: string;
  maxEntries: number | undefined;
  overflowPolicy: PluginStateOverflowPolicy;
  ttlMs?: number;
  staleMs: number;
  deletionChanged: string;
  rollbackChanged: string;
};
//#endregion
//#region src/plugin-state/plugin-state-publication.d.ts
type PluginStateRow = Selectable<DB$1["plugin_state_entries"]>;
type Receipt$1 = SqliteCommitReceipt<PluginStateRow>;
/** Descriptive read dependencies; these snapshots never grant mutation authority. */
type PluginStateReadDependency = {
  /** A missing database uses a wildcard so its first committed creation invalidates absence. */
  identity?: string | symbol;
  pluginId: string;
  namespace: string;
  keys: readonly string[];
};
type PluginStateCommitReceipt = Receipt$1;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-lifecycle-types.d.ts
/** Transportable planning facts; live guards and native identity remain with their owners. */
type SessionDeletionPlanningParams = Omit<DeleteSessionEntryLifecycleParams, "commitGuard" | "env" | "expectedDatabaseIdentity">;
type SessionEntryDeletionPlanInput = {
  deleteParams: SessionDeletionPlanningParams;
  archiveDirectory: string;
  admissionIdentities: readonly string[];
  allowLockedEntryRemoval: boolean;
  expectedPluginOwnerId?: string;
};
type SessionEntryDeletionPlanResult = {
  kind: "missing";
} | {
  kind: "expected-entry-mismatch";
} | {
  kind: "ready";
  value: {
    archiveDirectory: string;
    current: SqliteLifecycleTargetSnapshot[number];
    entryPlans: SessionStateDeletePlan[];
    historicalGenerationIds: string[];
    targetSnapshot: SqliteLifecycleTargetSnapshot;
  };
};
type SessionDeletionPlanningValidation = {
  deleteParams: SessionDeletionPlanningParams;
  preparedTargetSnapshot: SqliteLifecycleTargetSnapshot;
  scope?: SqliteSessionDeletionScope;
};
type SessionHistoricalDeletionCheckInput = {
  validation: SessionDeletionPlanningValidation;
  sessionId: string;
  admissionIdentities: readonly string[];
};
type SessionHistoricalDeletionPlanInput = SessionHistoricalDeletionCheckInput & {
  archiveDirectory: string;
  archiveTranscript: boolean;
};
type SessionHistoricalDeletionPlanResult = {
  kind: "expected-entry-mismatch";
} | {
  kind: "skip";
} | {
  kind: "ready";
  plan: SessionStateDeletePlan;
};
type SessionHistoricalDeletionCheckResult = {
  kind: "expected-entry-mismatch";
} | {
  kind: "ready";
  protectedSessionIds: string[];
};
type SessionDeletionPlanningOperation = {
  operation: "entry";
  input: SessionEntryDeletionPlanInput;
} | {
  operation: "history";
  input: SessionHistoricalDeletionPlanInput;
} | {
  operation: "check";
  input: SessionHistoricalDeletionCheckInput;
};
type SessionDeletionPlanningResult = {
  operation: "entry";
  value: SessionEntryDeletionPlanResult;
} | {
  operation: "history";
  value: SessionHistoricalDeletionPlanResult;
} | {
  operation: "check";
  value: SessionHistoricalDeletionCheckResult;
};
type LifecycleRemovalProjectionInput = {
  allowCanonicalRepair?: boolean;
  archiveDirectory: string;
  removals: readonly SessionEntryLifecycleRemoval[];
};
type ProjectedLifecycleCommitInput = {
  projected: ProjectedLifecycleMutation;
  materializationFailed: boolean;
  allowCanonicalRepair?: boolean;
  creation?: SessionLifecycleCreation;
  maintenance: SessionEntryMaintenanceInput | null;
};
type SessionLifecycleCreation = {
  preparedTranscript?: {
    sessionKey: string;
    sessionId: string;
    events: readonly TranscriptEvent[];
  };
  ownerAssignment?: {
    sessionKey: string;
    owner: SessionOwnerAssignment;
  };
};
type ReclamationDatabaseOptions = OpenClawAgentDatabaseOptions & {
  env: NodeJS.ProcessEnv;
  path: string;
};
type ReclamationDeleteParams = Omit<DeleteSessionEntryLifecycleParams, "commitGuard" | "env">;
/** Internal scope: a historical request cannot authorize whole-entry reclamation. */
type SqliteSessionDeletionScope = {
  kind: "entry";
  phase: "plan" | "commit";
} | {
  kind: "historical-generation";
  phase: "plan" | "commit";
  sessionId: string;
};
type SessionEntryMaintenanceInput = {
  activeSessionKey?: string;
  activeSessionKeys?: readonly string[];
  archiveDirectory: string;
  forceMaintenance?: boolean;
  /** Automatic cap work yields between operations; inline cleanup remains exhaustive. */
  maxCapEntries?: number;
  /** Automatic age scans resume after each settled page, before cap cleanup. */
  maxAgeEntries?: number;
  ageContinuation?: SessionMaintenanceAgeContinuation;
  maintenance: ResolvedSessionMaintenanceConfig;
  preservation: SessionMaintenancePreservationSnapshot;
  storePath: string;
};
type SessionMaintenanceLiveProtection = Pick<SessionEntryMaintenanceInput, "activeSessionKeys" | "preservation">;
type SessionReclamationPlanBase = {
  databaseOptions: ReclamationDatabaseOptions;
  materializedPlans: MaterializedSessionStateDeletePlan[];
};
type SessionMaintenanceMetadataCommand = {
  kind: "maintenance-statistics";
} | {
  kind: "maintenance-age";
  ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
  maintenance: ResolvedSessionMaintenanceConfig;
} | {
  kind: "maintenance-plan";
  ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
  input: SessionEntryMaintenanceInput;
};
type SessionMaintenanceMetadataResult = {
  kind: "maintenance-statistics";
  value: true;
} | {
  kind: "maintenance-age";
  nextAt: number | undefined;
  ageFact?: SessionEntryMaintenanceAgeFact;
} | {
  kind: "maintenance-plan-stale";
} | {
  kind: "maintenance-plan";
  value: SessionEntryMaintenancePlan;
  nextAt: number | undefined;
  ageFact?: SessionEntryMaintenanceAgeFact;
};
type SqliteSessionReclamationPlan = (SessionReclamationPlanBase & {
  kind: "lifecycle-projection-plan";
  input: LifecycleRemovalProjectionInput;
}) | (SessionReclamationPlanBase & {
  agentId: string;
  kind: "lifecycle-projection-commit";
  input: ProjectedLifecycleCommitInput;
}) | (SessionReclamationPlanBase & {
  kind: "archive-publish-prepare";
  archiveDirectory: string;
  requested: readonly Pick<TranscriptArchivePublishPlan, "sessionId" | "generation">[];
}) | (SessionReclamationPlanBase & {
  kind: "archive-publish-record";
  results: readonly TranscriptArchivePublishResult[];
  nowMs: number;
}) | (SessionReclamationPlanBase & {
  kind: "maintenance-pages";
  maxPages?: number;
}) | (SessionReclamationPlanBase & SessionMaintenanceMetadataCommand & {
  materializedPlans: [];
}) | (SessionReclamationPlanBase & {
  agentId: string;
  entries: SessionEntryRemovalPlan[];
  kind: "maintenance-finalize";
}) | (SessionReclamationPlanBase & {
  deleteParams: ReclamationDeleteParams;
  kind: "entry";
  preparedTargetSnapshot: SqliteLifecycleTargetSnapshot;
}) | (SessionReclamationPlanBase & {
  agentId: string;
  entries: SessionEntryRemovalPlan[];
  kind: "lifecycle-artifacts";
}) | (SessionReclamationPlanBase & {
  diskBudget: {
    preserveRecentMs?: number | null;
  };
  kind: "history-eviction";
  protectedSessionIds: string[];
  sessionId: string;
}) | (SessionReclamationPlanBase & {
  deleteParams: ReclamationDeleteParams;
  kind: "historical-generation";
  preparedTargetSnapshot: SqliteLifecycleTargetSnapshot;
  protectedSessionIds: string[];
  sessionId: string;
});
type SessionEntryRemovalPlan = {
  expectedEntry: InternalSessionEntry | undefined;
  maintenanceReason?: "capped" | "model-run-pruned" | "pruned";
  sessionKey: string;
};
type SessionEntryMaintenanceCounts = {
  archived: number;
  capArchived: number;
  modelRunPruned: number;
  pruned: number;
  capped: number;
};
type SessionEntryMaintenancePlan = SessionEntryMaintenanceCounts & {
  ageContinuation?: SessionMaintenanceAgeContinuation;
  /** An exhaustive over-cap scan found only durable protection, without runtime/recent guards. */
  durableNoCandidates?: true;
  /** Exact rows written by planning; parent publication must not rescan the store. */
  archivedEntries: Array<{
    sessionKey: string;
    sessionId?: string;
  }>;
  entryRemovals: SessionEntryRemovalPlan[];
  stateDeletePlans: SessionStateDeletePlan[];
};
type ProjectedLifecycleMutation = {
  archiveRecovery?: {
    pending: boolean;
    databaseIdentity: string;
  };
  deletePlans: SessionStateDeletePlan[];
  removals: Array<{
    archiveTranscript: boolean;
    expectedEntry: InternalSessionEntry;
    removal: SessionEntryLifecycleRemoval;
    sessionKey: string;
  }>;
  upsertedEntries: Array<{
    entry: InternalSessionEntry;
    expectedEntry: InternalSessionEntry | undefined;
    routeContext?: ConversationRouteContext | null;
    resetBoundary?: SessionResetBoundaryWrite;
    sessionKey: string;
  }>;
};
//#endregion
//#region src/config/sessions/session-native-binding.types.d.ts
type SessionNativeBindingParticipants = {
  operationId: string;
  sharedSource: DatabasePathIdentity;
  participants: readonly {
    sessionKey: string;
    entry: SessionEntry;
    binding?: PluginStateNativeBindingPlan;
  }[];
};
type SessionNativeBindingDeletion = SessionNativeBindingParticipants & {
  plan: Extract<SqliteSessionReclamationPlan, {
    kind: "entry" | "lifecycle-artifacts" | "maintenance-finalize" | "lifecycle-projection-commit";
  }>;
};
type SessionNativeBindingReceipt = {
  kind: "session-native-binding";
  operationId: string;
  agent: "pending" | "committed" | "rolled-back";
  bindings: ("pending" | "absent" | "deleted" | "restored")[];
  pluginState?: PluginStateCommitReceipt | {
    kind: "unknown";
    identity: string | symbol;
  };
  receipt?: SessionEntryPatchReceipt;
  compensationFailure?: OpenClawStateWorkerErrorPayload;
};
//#endregion
//#region src/config/sessions/session-message-cut.types.d.ts
type SessionMessageCutExpectedState = Pick<InternalSessionEntry, "lifecycleRevision" | "sessionId">;
type SessionMessageCutResult = SessionMessageCutMutationResult | SessionBranchSwitchMutationResult | {
  status: "conflict";
};
type SessionMessageCutIntent = {
  canonicalSourceKey: string;
  creation?: SessionMessageCutMutationParams["creation"];
  forkWorkspace?: SessionMessageCutMutationParams["forkWorkspace"];
  entryId: string;
  expectedState: SessionMessageCutExpectedState | undefined;
  mode: "fork" | "rewind" | "switch";
  repositoryWorkspaceId?: string;
  settledLocalWorkspace?: {
    worktreeId: string;
    sessionId: string;
    lifecycleRevision: string | null;
    projectionRevision: number;
  };
  sourceKey: string;
  targetKey: string;
};
type SessionMessageCutCommit = {
  agentId: string;
  intent: SessionMessageCutIntent & {
    mode: "rewind" | "switch";
  };
  nativeBindings?: SessionNativeBindingParticipants;
};
//#endregion
//#region src/state/openclaw-agent-operation-context.d.ts
type AgentWorkerOperationContext = {
  open: () => OpenClawAgentDatabase;
  options: OpenClawAgentDatabaseOptions & {
    path: string;
  };
  admit: (stage: "prepare" | "transaction" | "commit", publication?: unknown, transferList?: Transferable[]) => void;
  writeTransaction: <T>(operationLabel: string, owner: string, write: (current: OpenClawAgentDatabase) => T, diagnosticContext?: SqliteTransactionOptions["diagnosticContext"],
  /** The owner prepared its receipt and final admission before one terminal statement. */
  singleStatement?: boolean) => T;
  /** Durable executors lend their exact admitted shared owner to native binding settlement. */
  writeSharedTransaction?: <T>(source: DatabasePathIdentity, write: (current: OpenClawStateDatabase) => T) => T;
};
//#endregion
//#region src/config/sessions/session-message-cut.worker.d.ts
declare function commitSessionMessageCut(input: Omit<SessionMessageCutCommit, "intent"> & {
  intent: SessionMessageCutIntent;
}, context: AgentWorkerOperationContext, sourceRepositoryWorkspaceId?: string): SessionEntryPatchReceipt | SessionNativeBindingReceipt;
//#endregion
//#region src/config/sessions/session-parent-fork.types.d.ts
/** Data-only patches applied to the current child row by its writer. */
type ParentForkEntryPatch = {
  /** Finish fresh child creation without replacing its current audience. */
  preserveVisibility?: boolean;
  skipExisting?: boolean;
  skipped?: Partial<SessionEntry>;
  forked?: Partial<SessionEntry>;
};
type ParentForkEntryParams = Omit<ForkSessionEntryFromParentTargetParams, "commitGuard">;
//#endregion
//#region src/config/sessions/session-actor-memory-fork-contract.d.ts
type SessionActorMemoryForkReads = {
  "session.parentFork.source": {
    input: {
      sessionKey?: string;
      sessionId?: string;
      forkFrom?: "last-completed";
    };
    output: ParentForkSourceTranscript | null;
  };
};
/** CLI capability lookup stays with the host; entry patches are command data. */
type SessionActorMemoryParentForkCallbacks = {
  supportsCliFork?: (provider: string) => boolean;
};
type SessionActorMemoryForkWrites = {
  "session.parentFork.commit": {
    input: {
      kind: "entry";
      params: Omit<ParentForkEntryParams, "agentId" | "storePath">;
      patch?: ParentForkEntryPatch;
    };
    output: ForkSessionEntryFromParentTargetResult;
  };
  "session.parentFork.transcript": {
    input: {
      sessionId: string;
      events: readonly unknown[];
    };
    output: Extract<ForkSessionFromParentTranscriptResult, {
      status: "created";
    }>;
  };
  "session.messageCut": {
    input: {
      intent: SessionMessageCutIntent;
      sourceRepositoryWorkspaceId?: string;
    };
    output: SessionMessageCutResult;
  };
};
//#endregion
//#region src/config/sessions/transcript-recent-text.d.ts
type SessionRecentConversationText = {
  id?: string;
  role: "user" | "assistant";
  text: string;
  timestamp?: number;
  sourceChannel?: string;
};
/** Internal channel-history evidence, not part of the Plugin SDK text projection. */
type SessionRecentConversationTurn = SessionRecentConversationText & {
  messageId?: string;
  isCompletedAnswer?: true;
};
type ReadRecentSessionConversationTextOptions = {
  beforeTimestampMs?: number;
  includeCronDirectDeliveryContext?: boolean;
  includeMessageToolSourceReplies?: boolean;
  limit?: number;
  minTimestampMs?: number;
  role?: "user" | "assistant";
  preferUpstreamUserText?: boolean;
};
type ReadRecentSessionConversationTurnOptions = ReadRecentSessionConversationTextOptions & {
  includeTurnIdentity?: boolean;
};
//#endregion
//#region src/sessions/transcript-anchor-page.d.ts
type TranscriptRecentReadLimits = {
  maxMessages: number;
  maxLines: number;
  maxBytes: number;
};
type TranscriptAnchorPageOptions = {
  messageId: string;
  /** Reopen the interval before a closing reset anchor, excluding that reset marker. */
  closedResetInterval?: boolean;
  /** Includes the anchor unless closedResetInterval excludes its closing reset; directional reads never backfill. */
  maxMessages: number;
  /** Optional response bound enforced before a worker returns the page. */
  maxBytes?: number;
  direction?: "older" | "newer";
  /** Continue an anchor-only byte-limited page without rereading its payload. */
  excludeAnchor?: boolean;
  captureReadWindow?: boolean;
  expectedReadWindow?: TranscriptReadWindow;
};
//#endregion
//#region src/gateway/session-transcript-read.types.d.ts
type SubagentCoordinationDisplayResolver = {
  assertCurrent?: () => void;
  isSubagentSession: (sessionKey: string) => boolean;
  isSubagentRunMessage: (runId: string, messageSeq: number | undefined) => boolean;
};
type ReadRecentSessionMessagesOptions = {
  maxMessages: number;
  maxBytes?: number;
  maxLines?: number;
};
type SessionTranscriptMessageByIdOptions = ({
  currentOnly?: false;
  maxBytes?: never;
} | {
  currentOnly: true;
  maxBytes: number;
}) & {
  historyVisibility?: {
    sessionStartedAt?: number;
    requireVisible?: boolean;
  };
};
type ReadRecentSessionMessagesResult = {
  olderOffset?: number;
  omittedOversized?: boolean;
  activeLeafEntryId?: string | null;
  deltaCursor?: string;
  displaySource?: string;
  readWindow?: TranscriptReadWindow;
  windowReset?: boolean;
  messages: unknown[];
  transcriptEvents?: TranscriptEvent[];
  transcriptPath?: string;
  transcriptSource?: "active" | "reset-archive";
  totalMessages: number;
};
type ReadSessionMessagesResult = {
  messages: unknown[];
  transcriptPath?: string;
  nextCursor?: SessionTranscriptSourceCursor;
  snapshot?: SessionTranscriptSourceSnapshot;
};
type ReadSessionMessageByIdResult = {
  /** A canonical visibility rejection must not fall through to imported history. */
  historyHidden?: true;
  historyContext?: {
    precedingMessage?: unknown;
    transcriptPath?: string;
    displaySource?: string;
  };
  message?: unknown;
  seq?: number;
  oversized: boolean;
  found: boolean;
  serializedBytes?: number;
};
type SessionTranscriptReadOptions = {
  allowResetArchiveFallback?: boolean;
  readOnly?: boolean;
};
type SessionTranscriptSourceSnapshot = {
  indexedSeq: number;
  activeEventCount: number;
  totalMessages: number;
  generation: string | undefined;
  tailEventSeq: number | undefined;
  resetSeq: number | null;
};
type SessionTranscriptSourceCursor = {
  snapshot: SessionTranscriptSourceSnapshot;
  position: number;
  messageSeq: number;
} & ({
  kind: "kept" | "active" | "off-path";
} | {
  kind: "archive";
  path: string;
  source: string;
});
type SessionTranscriptSourcePageOptions = SessionTranscriptReadOptions & {
  mode: "page";
  includeOffPathMessages?: boolean;
  /** Narrow by indexed IDs; unindexed legacy rows remain candidates for exact matching. */
  messageIds?: readonly string[];
  cursor?: SessionTranscriptSourceCursor;
};
type ReadSessionMessagesAroundIdResult = ReadRecentSessionMessagesResult & {
  found: boolean;
  hasOverreadContext: boolean;
  offset: number;
};
type SessionTranscriptPageOptions = TranscriptReadWindowOptions & SessionTranscriptReadOptions & {
  offset: number;
  maxMessages: number;
  beforeSeq?: number;
  recentAtHead?: TranscriptRecentReadLimits;
  maxBytes?: number;
  allowOversizedFirst?: boolean;
};
type SessionTranscriptReader = {
  subagentCoordination?: SubagentCoordinationDisplayResolver;
  readSessionMessageCountAsync(scope: SessionTranscriptReadScope): Promise<number>;
  readSessionMessagesWithSourceAsync(scope: SessionTranscriptReadScope, options: SessionTranscriptSourcePageOptions, signal?: AbortSignal): Promise<ReadSessionMessagesResult>;
  readSessionMessageByIdAsync(scope: SessionTranscriptReadScope, messageId: string, options?: SessionTranscriptMessageByIdOptions & {
    allowResetArchiveFallback?: boolean;
  }, signal?: AbortSignal): Promise<ReadSessionMessageByIdResult>;
  readSessionMessagesMatchingIdAsync(scope: SessionTranscriptReadScope, messageId: string): Promise<unknown[]>;
  readRecentSessionMessagesWithStatsAsync(scope: SessionTranscriptReadScope, options: ReadRecentSessionMessagesOptions & TranscriptReadWindowOptions & SessionTranscriptReadOptions): Promise<ReadRecentSessionMessagesResult>;
  readSessionMessagesPageWithStatsAsync(scope: SessionTranscriptReadScope, options: SessionTranscriptPageOptions, signal?: AbortSignal): Promise<ReadRecentSessionMessagesResult>;
  readSessionMessagesAroundIdWithStatsAsync(scope: SessionTranscriptReadScope, options: TranscriptAnchorPageOptions & SessionTranscriptReadOptions, signal?: AbortSignal): Promise<ReadSessionMessagesAroundIdResult>;
};
type SessionTranscriptProjectionSelection = {
  kind: "recent-text";
  options: ReadRecentSessionConversationTurnOptions;
} | {
  kind: "delta";
  options: SessionTranscriptRawDeltaLimits;
} | {
  kind: "count";
} | {
  kind: "recent";
  options: ReadRecentSessionMessagesOptions & TranscriptReadWindowOptions & SessionTranscriptReadOptions;
} | {
  kind: "page";
  options: SessionTranscriptPageOptions;
} | {
  kind: "around-id";
  options: TranscriptAnchorPageOptions & SessionTranscriptReadOptions;
} | {
  kind: "by-id";
  messageId: string;
  options?: SessionTranscriptMessageByIdOptions & {
    allowResetArchiveFallback?: boolean;
  };
} | {
  kind: "source";
  options: Parameters<SessionTranscriptReader["readSessionMessagesWithSourceAsync"]>[1];
} | {
  kind: "lookup";
  messageId: string;
};
type SessionTranscriptProjectionSelectionResults = {
  "recent-text": SessionRecentConversationTurn[];
  delta: SessionTranscriptDisplayDeltaResult;
  count: number;
  recent: ReadRecentSessionMessagesResult;
  page: ReadRecentSessionMessagesResult;
  "around-id": ReadSessionMessagesAroundIdResult;
  "by-id": ReadSessionMessageByIdResult;
  source: ReadSessionMessagesResult;
  lookup: {
    hasDisplayMessages: boolean;
    messages: unknown[];
  };
};
type RawDeltaPage = Extract<SessionTranscriptRawDeltaResult, {
  kind: "page";
}>;
type SessionTranscriptDisplayDeltaResult = (Omit<RawDeltaPage, "events"> & {
  activeLeafEntryId: string | null;
  events: Array<RawDeltaPage["events"][number] & {
    messageSeq?: number;
    displayPosition?: TranscriptDisplayPosition;
  }>;
}) | Exclude<SessionTranscriptRawDeltaResult, {
  kind: "page";
}>;
//#endregion
//#region src/config/sessions/session-transcript-accounting.types.d.ts
type SessionTranscriptAccountingOptions = {
  includeByteSize: boolean;
  includeTurnTaint?: boolean;
  includeUsage: boolean;
};
type SessionTranscriptUsageSnapshot$1 = {
  promptTokens?: number;
  outputTokens?: number;
  trailingMessages: AgentMessage[];
};
type SessionTranscriptAccountingSnapshot = {
  byteSize?: number;
  eventCount?: number;
  turnTainted?: boolean;
  usage?: SessionTranscriptUsageSnapshot$1;
};
//#endregion
//#region src/agents/sessions/compaction/request-budget.types.d.ts
/** Ephemeral foreground facts; a separately routed summarizer cannot reconstruct these. */
type CompactionRequestBudget = Readonly<{
  contextWindow: number;
  reserveTokens: number;
  fixedTokens: number;
  pendingTokens: number;
  /** Known queue reservation, replaced by the SDK's projected queue at submission. */
  pendingQueuedContextTokens?: number;
  /** Overlap credit applies only to the user body, never newly added context. */
  pendingUserTokens?: number;
  pendingUserIdempotencyKey?: string;
}>;
/** Input preservation exists before the foreground prompt can supply a token budget. */
type CompactionRequestConstraints = Readonly<{
  requestBudget?: CompactionRequestBudget;
  /** Source of the active run, including after its input has been processed. */
  requestFromEntryId?: string;
  pendingUserEntryId?: string;
}>;
//#endregion
//#region src/agents/tool-call-id.d.ts
type ToolCallIdMode = "strict" | "strict9";
//#endregion
//#region src/agents/transcript-policy.types.d.ts
/** Scope of transcript content sanitization before provider replay. */
type TranscriptSanitizeMode = "full" | "images-only";
/** Effective replay policy applied before sending transcript history to a provider. */
type TranscriptPolicy = {
  sanitizeMode: TranscriptSanitizeMode;
  sanitizeToolCallIds: boolean;
  toolCallIdMode?: ToolCallIdMode;
  duplicateToolCallIdStyle?: "openai";
  preserveNativeAnthropicToolUseIds: boolean;
  repairToolUseResultPairing: boolean;
  preserveSignatures: boolean;
  appendOnlyRuntimeContext?: boolean;
  inHistorySystemUpdates?: boolean;
  /**
   * Keep one system prompt per session and send later prompt changes as appended deltas.
   * The delta is an in-history system message when `inHistorySystemUpdates` allows it,
   * otherwise a user-role note.
   */
  pinnedSystemPrompt?: boolean;
  sanitizeThoughtSignatures?: {
    allowBase64Only?: boolean;
    includeCamelCase?: boolean;
  };
  dropThinkingBlocks: boolean;
  dropReasoningFromHistory?: boolean;
  applyGoogleTurnOrdering: boolean;
  validateGeminiTurns: boolean;
  validateAnthropicTurns: boolean;
  allowSyntheticToolResults: boolean;
};
//#endregion
//#region src/agents/sessions/session-manager-types.d.ts
interface SessionHeader {
  type: "session";
  version?: number;
  id: string;
  timestamp: string;
  cwd: string;
  parentSession?: string;
  /** Copied events whose paths are already counted by the source transcript or its sources. */
  inheritedThrough?: string[];
}
interface NewSessionOptions {
  id?: string;
  parentSession?: string;
}
interface SessionEntryBase {
  type: string;
  id: string;
  parentId: string | null;
  timestamp: string;
  /** This row consumes the raw side cursor instead of the visible leaf. */
  appendMode?: "side";
}
type CoreSessionEntry<Type extends SessionTreeEntry["type"]> = Extract<SessionTreeEntry, {
  type: Type;
}>;
interface SessionMessageEntry extends CoreSessionEntry<"message"> {
  /** Entry id this copy replaced when a branch rewrite re-appended it. */
  supersedesEntryId?: string;
}
interface ThinkingLevelChangeEntry extends CoreSessionEntry<"thinking_level_change"> {}
interface ModelChangeEntry extends CoreSessionEntry<"model_change"> {}
interface CompactionEntry<T = unknown> extends Omit<CoreSessionEntry<"compaction">, "details"> {
  __openclaw?: {
    runId?: string;
    itemId?: string;
  };
  /** Context estimate after compaction, retained with its ordinary transcript marker. */
  tokensAfter?: number;
  /** Extension-specific data, such as artifact indexes or version markers. */
  details?: T;
}
type ResetReason = CoreSessionEntry<"reset">["reason"];
interface ResetEntry extends CoreSessionEntry<"reset"> {}
interface BranchSummaryEntry<T = unknown> extends Omit<CoreSessionEntry<"branch_summary">, "details"> {
  /** Extension-specific data that is not sent to the model. */
  details?: T;
}
/** Extension state that is persisted but excluded from model context. */
interface CustomEntry<T = unknown> extends Omit<CoreSessionEntry<"custom">, "data"> {
  data?: T;
}
interface LabelEntry extends CoreSessionEntry<"label"> {}
interface SessionInfoEntry extends CoreSessionEntry<"session_info"> {}
/** Extension message that participates in model context. */
interface CustomMessageEntry<T = unknown> extends Omit<CoreSessionEntry<"custom_message">, "details"> {
  details?: T;
}
type SessionEntry$1 = SessionMessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | ResetEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry;
type FileEntry = SessionHeader | SessionEntry$1;
type AppendPersistenceOptions = {
  appendIntent?: "active-branch";
  /** Synchronous fresh SQLite message assertion; never serialized into an entry. */
  beforeFreshMessageCommit?: () => void;
  config?: OpenClawConfig;
  idempotencyLookup?: "scan" | "scan-assistant" | "caller-checked";
  invalidateSerializedPrefixCache?: boolean;
};
interface SessionTreeNode {
  entry: SessionEntry$1;
  children: SessionTreeNode[];
  label?: string;
  labelTimestamp?: string;
}
interface SessionContext extends SessionContext$1 {}
type PreservedOpaqueFileEntry = {
  index: number;
  record: unknown;
};
type SessionLeafControl = Extract<SessionTreeEntry, {
  type: "leaf";
}>;
//#endregion
//#region src/config/sessions/session-transcript-hydration.types.d.ts
type SessionTranscriptMaintenanceRead = {
  operation: "previous";
  beforeSeq: number;
} | {
  operation: "identity";
  eventId: string;
} | {
  operation: "version";
} | {
  operation: "custom-branch";
  leafEntryId: string | null;
  customType: string;
} | {
  operation: "nested-activity";
  scopeId: string;
  firstEntryId: string;
  lastEntryId: string;
} | {
  operation: "suffix";
  startSeq: number;
  maxBytes: number;
  maxEvents: number;
  retainedCustomDataIds: readonly string[];
};
type SessionTranscriptMaintenanceFacts = {
  kind: "transcript-maintenance";
  previous?: TranscriptEvent;
  seq?: number;
  version?: SessionTranscriptContextVersion;
  appendParentId?: string | null;
  lifecycleRevision?: SessionTranscriptWriteScope["expectedLifecycleRevision"];
  events?: TranscriptEvent[];
};
type SessionTranscriptCurrentTurnEntryRead = {
  kind: "current-turn-entry";
  version: SessionTranscriptContextVersion;
  anchor?: TranscriptEntryAnchor;
  event?: TranscriptEvent;
};
type SessionTranscriptCurrentTurnEntryRequest = {
  entryId: string;
  version: SessionTranscriptContextVersion;
  includeEntry: boolean;
};
//#endregion
//#region src/config/sessions/session-actor-memory-history-facts-contract.d.ts
type Reads = {
  "visibility-inputs": {
    input: {
      runIds: string[];
    };
    output: Array<{
      seq: number;
      message: {
        role: "user";
        idempotencyKey: unknown;
        provenance: unknown;
        __openclaw: {
          runId: unknown;
          steerTargetRunId: unknown;
          idempotencyKey: unknown;
        };
      };
    }>;
  };
  title: {
    input: {
      includeInterSession?: boolean;
      skillCommands?: SkillCommandSpec[];
    };
    output: {
      kind: "session-title-fields";
      fields: SessionTitleFields;
    };
  };
  preview: {
    input: {
      maxItems: number;
      maxChars: number;
    };
    output: {
      kind: "session-preview";
      items: SessionPreviewItem[];
    };
  };
  branches: {
    input: object;
    output: SessionBranchSummaryReadResult;
  };
  "current-turn-entry": {
    input: SessionTranscriptCurrentTurnEntryRequest;
    output: SessionTranscriptCurrentTurnEntryRead;
  };
  maintenance: {
    input: {
      request: SessionTranscriptMaintenanceRead;
    };
    output: SessionTranscriptMaintenanceFacts;
  };
  stats: {
    input: object;
    output: SessionTranscriptStats;
  };
  match: {
    input: {
      match: SessionTranscriptEventMatch;
    };
    output: {
      kind: "transcript-match";
      result: {
        event: TranscriptEvent;
      } | undefined;
    };
  };
  watermark: {
    input: object;
    output: {
      kind: "transcript-watermark";
      watermark: SessionTranscriptWatermark;
    };
  };
  "latest-assistant": {
    input: object;
    output: LatestTranscriptAssistantText | undefined;
  };
  "latest-active-message": {
    input: object;
    output: SessionTranscriptMessageEvent | undefined;
  };
  "message-presence": {
    input: object;
    output: boolean;
  };
  "recent-active-events": {
    input: {
      maxEvents: number;
    };
    output: TranscriptEvent[];
  };
  accounting: {
    input: {
      options: SessionTranscriptAccountingOptions;
    };
    output: SessionTranscriptAccountingSnapshot;
  };
  "bounded-tail": {
    input: {
      options: SessionTranscriptBoundedMessageTailOptions;
    };
    output: SessionTranscriptBoundedMessageTailPage;
  };
  "visitor-source": {
    input: {
      offset?: number;
    };
    output: {
      messages: Array<{
        message: unknown;
        seq: number;
      }>;
      nextOffset?: number;
    };
  };
};
type SessionActorMemoryHistoryFactsReads = { [Key in keyof Reads as `session.history.${Key}`]: {
  input: Reads[Key]["input"] & {
    sessionId?: string;
  } & (Key extends "title" | "preview" | "current-turn-entry" | "maintenance" | "latest-assistant" | "latest-active-message" | "recent-active-events" | "accounting" | "bounded-tail" | "visitor-source" ? {
    admission?: UserTurnTranscriptAdmissionReceipt;
  } : object);
  output: Reads[Key]["output"];
}; };
type SessionActorMemoryAnchorReads = {
  "session.history.anchors": {
    input: SessionTranscriptAnchorSelection & {
      sessionId?: string;
    };
    output: SessionTranscriptAnchorFacts;
  };
};
//#endregion
//#region src/config/sessions/session-actor-memory-history-contract.d.ts
type Target$1 = {
  sessionId?: string;
  admission?: UserTurnTranscriptAdmissionReceipt;
};
type ProjectionReads = { [Key in keyof SessionTranscriptProjectionSelectionResults as `session.history.${Key}`]: {
  input: Target$1 & Omit<Extract<SessionTranscriptProjectionSelection, {
    kind: Key;
  }>, "kind">;
  output: SessionTranscriptProjectionSelectionResults[Key];
}; };
type SessionActorMemoryHistoryReads = ProjectionReads & SessionActorMemoryHistoryFactsReads & SessionActorMemoryAnchorReads & {
  "session.history.hydrate": {
    input: Target$1 & {
      limits?: SessionTranscriptContextSelection;
      maxEventBytes?: number;
    };
    output: PreparedSessionTranscriptHydration;
  };
  "session.history.context-messages": {
    input: Target$1 & {
      seed?: SessionContextSeedRequest;
    };
    output: SessionTranscriptContextSnapshot;
  };
  "session.history.context": {
    input: Target$1 & {
      through?: TranscriptEntryAnchor;
      limits?: SessionModelContextLimits;
    };
    output: SessionTranscriptModelContext;
  };
  "session.history.raw-delta": {
    input: Target$1 & {
      limits: SessionTranscriptRawDeltaLimits;
    };
    output: SessionTranscriptRawDeltaResult;
  };
  "session.history.visible-delta": {
    input: Target$1 & {
      limits: SessionTranscriptVisibleMessageDeltaLimits;
    };
    output: SessionTranscriptVisibleMessageDeltaResult;
  };
};
//#endregion
//#region src/agents/sessions/session-compaction-persistence.types.d.ts
/** Prepared data only; the original runtime owner still authorizes the commit. */
type PreparedCompactionAppend = {
  scope: SessionTranscriptRuntimeTarget & Pick<SessionTranscriptWriteScope, "env" | "expectedLifecycleRevision" | "expectedWriterRunId" | "expectedOwner">;
  event: CompactionEntry;
  appendIntent?: "active-branch";
  expectedMutationAt?: number | null;
  initializeEntry?: boolean;
};
type CommittedCompactionAppend = {
  result: CompactionEntry;
  before: SessionTranscriptContextVersion;
  after: SessionTranscriptContextVersion;
};
type CommittedCompactionBoundary = CommittedCompactionAppend & {
  entry: InternalSessionEntry;
};
//#endregion
//#region src/config/sessions/session-transcript-writer.types.d.ts
type SessionTranscriptWriterFence = Readonly<{
  expectedLifecycleRevision: string | undefined;
  expectedWriterRunId: string;
}>;
/** A first-insert lease, bound to the original admission rather than its run id. */
type InitialSessionTranscriptWriter = Readonly<{
  writerRunId: string;
  committedFence: SessionTranscriptWriterFence | undefined;
  assertActive: SessionSourceAssertion;
  recordCommitted: (fence: SessionTranscriptWriterFence) => void;
  withTranscriptWrite: <T>(run: () => Promise<T> | T) => Promise<T>;
}>;
//#endregion
//#region src/config/sessions/session-manager-write-contract.d.ts
type MetadataTarget = Omit<SessionTranscriptWriteScope, "env"> & SessionTranscriptRuntimeTarget;
/** Host metadata capability; SDK-visible admissions do not expose the actor's other domains. */
type SessionManagerIncognitoDatabase = {
  readonly path: string;
  readonly identity: {
    readonly incarnation: string;
  };
  withMetadata<T>(assertCurrent: () => void, operation: (scope: Pick<SqliteWorkerStore<SessionMetadataOperations>, "execute">) => Promise<T>, controls?: {
    beforeFreshMessageCommit?: () => void;
    initialWriter?: InitialSessionTranscriptWriter;
  }): Promise<T>;
};
type InitialSessionEntryCommit = {
  owned: boolean;
  fence?: SessionTranscriptWriterFence;
  identity?: {
    previous: Map<string, InternalSessionEntry>;
    current: Map<string, InternalSessionEntry>;
  };
};
type SessionMetadataMessageControl = {
  pendingInput?: {
    facts: SessionPendingInputWorkerFacts;
    relocation?: string;
  };
  freshMessageCheck?: true;
};
type SessionMaintenanceOperations = {
  "session.transcript.branch": {
    input: {
      scope: MetadataTarget;
      branch: {
        sessionId: string;
        events: unknown[];
      };
      expectedLifecycleRevision: SessionTranscriptWriteScope["expectedLifecycleRevision"];
    };
    output: {
      identity: NonNullable<InitialSessionEntryCommit["identity"]>;
      version: SessionTranscriptContextVersion;
      projectionNeedsReconcile: boolean;
    };
  };
  "session.transcript.replaceSuffix": {
    input: {
      scope: MetadataTarget;
      args: [expectedEvents: readonly unknown[], nextEvents: readonly unknown[], prefixLength: number, expectedMutationAt: number | null | undefined, eventsStartAtPersistedPrefix: boolean, retainedCustomDataIds: readonly string[]];
    };
    output: {
      replaced: boolean;
      version?: SessionTranscriptContextVersion;
      projectionNeedsReconcile: boolean;
    };
  };
  "session.transcript.rewrite": {
    input: {
      scope: MetadataTarget;
      appendParentId: string | null;
      version: SessionTranscriptContextVersion;
      entries: Array<SessionEntry$1 | SessionLeafControl>;
      sources: Array<[string, SessionEntry$1]>;
      pendingInput?: {
        facts: SessionPendingInputWorkerFacts;
        relocation?: string;
      };
    };
    output: {
      version: SessionTranscriptContextVersion;
      entries: Array<SessionEntry$1 | SessionLeafControl>;
      pendingInputReceipt?: SessionPendingInputWorkerReceipt;
      projectionNeedsReconcile: boolean;
    };
  };
};
type CompactionBoundaryOperations = {
  "session.transcript.compactionBoundary": {
    input: {
      scope: Omit<PreparedCompactionAppend["scope"], "env">;
      prepared: Omit<PreparedCompactionAppend, "scope"> & {
        scope: Omit<PreparedCompactionAppend["scope"], "env">;
      };
      transcriptByteCompactionLatch: InternalSessionEntry["transcriptByteCompactionLatch"] | null;
      tokensAfter?: number;
      initialWriterRunId?: string;
    };
    output: {
      committed: CommittedCompactionBoundary;
      initialEntry?: InitialSessionEntryCommit;
      projectionNeedsReconcile: boolean;
    };
  };
};
type SessionMetadataOperations = SessionMaintenanceOperations & CompactionBoundaryOperations & {
  "session.transcript.appendMessage": {
    input: {
      scope: MetadataTarget;
      messageJson: string;
      cwd: string;
      cliWriter?: CliHistoryWriterFacts;
    } & SessionMetadataMessageControl;
    output: {
      snapshot: Result$1<TranscriptMessageWriteSnapshot<Message$1 | CustomMessage | BashExecutionMessage | undefined>, TranscriptAppendRefusal>;
      projectionNeedsReconcile: boolean;
      pendingInputReceipt?: SessionPendingInputWorkerReceipt;
    };
  };
  "session.metadata.initialize": {
    input: {
      scope: MetadataTarget;
      entry: InternalSessionEntry;
      initialWriterRunId?: string;
    };
    output: InitialSessionEntryCommit;
  };
  "session.metadata.append": {
    input: {
      scope: MetadataTarget;
      event: Omit<SessionMessageEntry, "message"> | string;
      initialModel?: ModelChangeEntry;
      cliWriter?: CliHistoryWriterFacts;
      message?: {
        messageJson: string;
        cwd: string;
        validateTurn: boolean;
        idempotencyLookup?: "scan" | "scan-assistant" | "caller-checked";
      } & SessionMetadataMessageControl;
      options: Pick<TranscriptEventAppendOptions, "appendIntent" | "expectedMutationAt">;
      view?: {
        loadedVersion?: SessionTranscriptContextVersion;
        limits?: SessionTranscriptContextSelection;
        admission?: UserTurnTranscriptAdmissionReceipt;
        questionAnswers?: readonly UserTurnTranscriptAdmissionReceipt[];
      };
    };
    output: {
      snapshot: Result$1<TranscriptWriteSnapshot<TranscriptEventAppendResult | TranscriptMessageAppendResult<SessionMessageEntry["message"] | undefined> | undefined>, TranscriptAppendRefusal>;
      projectionNeedsReconcile: boolean;
      pendingInputReceipt?: SessionPendingInputWorkerReceipt;
      initialModelParentId?: string | null;
      reload?: Result$1<PreparedSessionTranscriptHydration, OpenClawStateWorkerErrorPayload | undefined>;
    };
  };
  "session.metadata.mutation": {
    input: {
      scope: MetadataTarget;
    };
    output: number | null;
  };
};
type SessionMetadataWorkerOperations = { [Key in keyof SessionMetadataOperations]: {
  input: SessionMetadataOperations[Key]["input"];
  output: {
    ok: true;
    value: SessionMetadataOperations[Key]["output"];
  } | {
    ok: false;
    refusal?: TranscriptAppendRefusal;
  };
}; };
//#endregion
//#region src/config/sessions/session-actor-memory-metadata-contract.d.ts
type SessionActorMemoryMetadataReads = Pick<SessionMetadataOperations, "session.metadata.mutation">;
type SessionActorMemoryMetadataWrites = Omit<SessionMetadataOperations, "session.metadata.mutation">;
//#endregion
//#region src/config/sessions/session-pending-input-history.types.d.ts
type PendingInputHistoryQuery = {
  sessionKey: string;
  sessionId: string;
  limit?: number;
  before?: number;
  id?: string;
  includeTotal?: false;
  /** Exact custody captured in a committed graceful-shutdown marker. */
  queuedInputIds?: readonly string[];
  liveInputIds?: readonly string[];
};
type PendingInputHistorySnapshot = {
  rows: SessionPendingInputRow[];
  total: number | undefined;
  nextBefore?: number;
  currentSessionId?: string;
};
//#endregion
//#region src/config/sessions/session-pending-input-operations.types.d.ts
type PendingInputIdentity = {
  sessionKey: string;
  sessionId: string;
  idempotencyKey: string;
};
type PendingInputRead = PendingInputStageRead | PendingInputSourceRead;
type PendingInputStageRead = PendingInputIdentity & {
  kind: "stage";
  trackCompletion: boolean;
};
type PendingInputSourceRead = PendingInputIdentity & {
  kind: "source";
  pendingOnly: boolean;
};
type PendingInputSourceSnapshot = {
  kind: "source";
  current: boolean;
  pending?: SessionPendingInputRow;
  committed?: PersistedUserTurnMessage;
  committedMessageSeq?: number;
};
type PendingInputSnapshot = {
  kind: "stage";
  current: boolean;
  existing?: SessionPendingInputRow;
  previous?: SessionInputCompletion;
  committed?: {
    messageId: string;
    message: PersistedUserTurnMessage;
  };
};
type PendingInputSettlementIdentity = PendingInputIdentity & {
  authorityAgentId?: string;
  runId: string;
  requestHash: string;
  lifecycleGeneration: string;
};
type PendingInputMutation = (PendingInputSettlementIdentity & {
  kind: "stage";
  expected: PendingInputSnapshot;
  trackCompletion: boolean;
  inputId: string;
  messageJson: string;
}) | (PendingInputSettlementIdentity & {
  kind: "complete";
  outcome: AgentRunTerminalOutcome$1;
}) | (PendingInputSettlementIdentity & {
  kind: "finish";
  inputId: string;
  disposition: "cancelled" | "interrupted";
});
type PendingInputMutationReceipt = PendingInputIdentity & {
  kind: "pending-input-settlement";
  operation: PendingInputMutation["kind"];
  runId: string;
  requestHash: string;
  lifecycleGeneration: string;
  outcome?: AgentRunTerminalOutcome$1;
  withdrawnInputId?: string;
  stagedInput?: SessionPendingInputRow;
};
//#endregion
//#region src/config/sessions/session-pending-input-value.d.ts
declare function projectPendingInputReceipts(rows: readonly Pick<SessionPendingInputRow, "run_id" | "consumed_event_id" | "state">[]): SessionPendingInputReceipt[];
//#endregion
//#region src/config/sessions/session-actor-memory-pending-contract.d.ts
type SessionActorMemoryPendingReads = {
  "session.pendingInput.read": {
    input: PendingInputRead;
    output: PendingInputSnapshot | PendingInputSourceSnapshot;
  };
  "session.pendingInput.history": {
    input: PendingInputHistoryQuery;
    output: PendingInputHistorySnapshot;
  };
  "session.pendingInput.receipts": {
    input: {
      sessionKey: string;
      sessionId: string;
      runIds: readonly string[];
    };
    output: ReturnType<typeof projectPendingInputReceipts>;
  };
  "session.goal.receipt": {
    input: SessionGoalOperationLookup;
    output: SessionGoalOperationResult | undefined;
  };
};
type SessionActorMemoryPendingWrites = {
  "session.pendingInput.mutate": {
    input: PendingInputMutation;
    output: PendingInputMutationReceipt;
  };
  "session.goal.mutate": {
    input: SessionGoalManagementInput;
    output: SessionGoalManagementCommit;
  };
};
//#endregion
//#region src/gateway/worker-environments/transcript-commit-store.worker-contract.d.ts
type WorkerTranscriptCommitInput = {
  environmentId: string;
  sessionId: string;
  runEpoch: number;
  seq: number;
  requestHash: string;
};
type WorkerTranscriptCommitOutcome = {
  ok: true;
  result: WorkerTranscriptCommitResult;
} | {
  ok: false;
  reason: WorkerTranscriptCommitErrorReason;
};
//#endregion
//#region src/gateway/worker-environments/transcript-commit.types.d.ts
type CommittedAgentMessage = Extract<AgentMessage, {
  role: "assistant" | "toolResult" | "user" | "custom";
}> & {
  idempotencyKey: string;
};
type AppliedTranscriptMessage = {
  appended: boolean;
  message: AgentMessage;
  messageId: string;
  messageSeq?: number;
};
type ApplyTranscriptCommitResult = {
  ok: true;
  messages: AppliedTranscriptMessage[];
  lifecycleRevision: string | undefined;
} | {
  ok: false;
  reason: "invalid-batch" | "session-not-attached" | "stale-base-leaf";
};
type TranscriptCommitInput = {
  scope: Omit<SessionTranscriptWriteScope, "env"> & SessionTranscriptRuntimeTarget;
  lifecycleRevision: string | undefined;
  requestedBaseLeafId: string | null;
  recoverPersistedBatch: boolean;
  runId?: string | null;
  messages: readonly CommittedAgentMessage[];
  cwd: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-transcript-message-append.types.d.ts
type PreparedTranscriptMessageAppend<TMessage> = {
  messageJson: string;
  persistedMessage: TMessage;
  physicalPayload?: PreparedTranscriptPayload;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-transcript-reports.types.d.ts
type AbortedSessionTranscriptPartial = {
  runId: string;
  message: Record<string, unknown>;
  now?: number;
  expectedLifecycleRevision?: string | null;
};
type AbortedSessionTranscriptPartialResult = {
  skipped: true;
} | {
  skipped: false;
  append: TranscriptMessageAppendResult<Record<string, unknown>>;
  lifecycleRevision?: string;
  messageSeq?: number;
};
type CustomMessageReport = {
  customType: string;
  content: unknown;
  details?: unknown;
};
type CustomMessageReportAppend = {
  customType: string;
  content: string;
  display: boolean;
  excludeFromContext?: boolean;
  details?: unknown;
};
type TranscriptReport = {
  kind: "assistant";
  message: AssistantMessage & {
    responseId: string;
  };
} | {
  kind: "custom";
  customTypes: readonly string[];
  /** Pure selection; a definite concurrent transcript change may repeat it. */
  selectReport: (latest: CustomMessageReport | undefined) => CustomMessageReportAppend | undefined;
};
type SelectedTranscriptReport = Extract<TranscriptReport, {
  kind: "assistant";
}> | {
  kind: "custom";
  eventJson: string;
};
type TranscriptReportSelection = {
  kind: "assistant";
  responseId: string;
} | Pick<Extract<TranscriptReport, {
  kind: "custom";
}>, "kind" | "customTypes">;
type PreparedTranscriptReport = {
  appendParentId: string | null;
  suppressed: boolean;
  latest: CustomMessageReport | undefined;
};
type TranscriptReportCommit = {
  committed: boolean;
  projectionNeedsReconcile: boolean;
  cliHistoryChanged?: boolean;
  abortedPartial?: AbortedSessionTranscriptPartialResult;
  sessionEntryChanged?: boolean;
  entry?: InternalSessionEntry;
  fullEntry?: InternalSessionEntry;
};
type TranscriptReportWorkerOperations = {
  abortedPartial: {
    input: AbortedSessionTranscriptPartial & {
      preparedMessage: PreparedTranscriptMessageAppend<Record<string, unknown>>;
    };
    output: Result$1<TranscriptReportCommit, TranscriptAppendRefusal>;
  };
  prepare: {
    input: TranscriptReportSelection;
    output: Result$1<PreparedTranscriptReport, TranscriptAppendRefusal>;
  };
  append: {
    input: Extract<SelectedTranscriptReport, {
      kind: "custom";
    }>;
    output: Result$1<TranscriptReportCommit, TranscriptAppendRefusal>;
  };
  assistant: {
    input: Extract<TranscriptReport, {
      kind: "assistant";
    }> & {
      preparedMessage: PreparedTranscriptMessageAppend<Extract<TranscriptReport, {
        kind: "assistant";
      }>["message"]>;
    };
    output: Result$1<TranscriptReportCommit, TranscriptAppendRefusal>;
  };
};
//#endregion
//#region src/config/sessions/session-transcript-mutation.types.d.ts
type SessionMessageRewriteSelection = {
  scope: ResolvedTranscriptScope;
  target: {
    kind: "anchor";
    anchor: TranscriptEntryAnchor;
    active?: "exact" | "sequence";
  } | {
    kind: "terminal-assistant";
    runId: string;
  };
  expectedEntry?: {
    lifecycleRevision: string | null;
    activeWriterRunId?: string | null;
    owner?: SessionTranscriptWriteScope["expectedOwner"];
  };
};
type SessionMessageRewriteSnapshot = {
  seq: number;
  eventJson: string;
  event: Record<string, unknown>;
};
type SessionMessageRewriteCommitted = {
  kind: "session-message-rewrite";
  result: SessionMessageRewriteResult | null;
};
type SessionTranscriptCorrectionCommitted = {
  kind: "session-transcript-correction";
  generation: string | null;
};
type SessionTranscriptCorrectionInput = {
  scope: ResolvedTranscriptScope;
  fence: SessionTranscriptWriteScope;
  version: SessionTranscriptContextVersion;
  allowLaterAppends: boolean;
  rows: Array<{
    entryId: string;
    expectedEventJson: string;
    event: TranscriptEvent;
  }>;
};
//#endregion
//#region src/config/sessions/session-actor-memory-reports-contract.d.ts
type Target = {
  scope: SessionTranscriptWriteScope & {
    sessionId: string;
  };
};
type SessionActorMemoryReportsReads = {
  "session.transcript.messageFacts": {
    input: Target & Parameters<SessionTranscriptWriteLockAccessorContext["readMessageFacts"]>[0];
    output: {
      version: SessionTranscriptContextVersion;
      facts: Awaited<ReturnType<SessionTranscriptWriteLockAccessorContext["readMessageFacts"]>>;
    };
  };
  "session.rewrite.prepare": {
    input: Target & Pick<SessionMessageRewriteSelection, "target" | "expectedEntry">;
    output: SessionMessageRewriteSnapshot | null;
  };
  "session.report.prepare": {
    input: Target & {
      selection: TranscriptReportWorkerOperations["prepare"]["input"];
    };
    output: Result$1<{
      facts: PreparedTranscriptReport;
      version: SessionTranscriptContextVersion;
    }, TranscriptAppendRefusal>;
  };
  "session.correction.prepare": {
    input: Target & {
      afterSeq?: number;
    };
    output: {
      rows: Array<{
        seq: number;
        eventJson: string;
      }>;
      version: SessionTranscriptContextVersion;
    };
  };
};
type SessionActorMemoryReportsWrites = { [Key in "assistant" | "abortedPartial" as `session.report.${Key}`]: {
  input: Target & {
    report: TranscriptReportWorkerOperations[Key]["input"];
  };
  output: TranscriptReportWorkerOperations[Key]["output"];
}; } & {
  "session.event.append": {
    input: Target & {
      eventJson: string;
    };
    output: boolean;
  };
  "session.report.append": {
    input: Target & {
      version: SessionTranscriptContextVersion;
      report: TranscriptReportWorkerOperations["append"]["input"];
    };
    output: TranscriptReportWorkerOperations["append"]["output"];
  };
  "session.rewrite.commit": {
    input: SessionActorMemoryReportsReads["session.rewrite.prepare"]["input"] & {
      expected: SessionMessageRewriteSnapshot;
      message: unknown;
      returnUnchanged?: boolean;
    };
    output: SessionMessageRewriteCommitted;
  };
  "session.transcript.manualCompact": {
    input: Target & {
      maxLines: number;
      nowMs?: number;
      sources?: SessionSourcePredicate[];
    };
    output: SessionTranscriptManualTrimResult;
  };
  "session.correction.commit": {
    input: Target & Omit<SessionTranscriptCorrectionInput, "scope" | "fence">;
    output: SessionTranscriptCorrectionCommitted;
  };
  "session.workerTranscript.commit": {
    input: Target & {
      receipt: WorkerTranscriptCommitInput;
      batch: Omit<TranscriptCommitInput, "scope">;
      preparedMessages: readonly CommittedAgentMessage[];
    };
    output: {
      result: ApplyTranscriptCommitResult;
      outcome: WorkerTranscriptCommitOutcome;
      replayed: boolean;
    };
  };
};
//#endregion
//#region src/config/sessions/session-transcript-search.types.d.ts
type SessionTranscriptSearchHit = {
  sessionKey: string;
  sessionId: string;
  messageId: string;
  role: "assistant" | "user";
  timestamp: number;
  snippet: string;
  score: number;
};
type SessionTranscriptSearchResult = {
  hits: SessionTranscriptSearchHit[];
  indexing: boolean;
  truncated: boolean;
  archivedTranscriptsExcluded?: number;
};
type SessionTranscriptSearchParams = {
  agentId: string;
  env?: NodeJS.ProcessEnv;
  limit?: number;
  query: string;
  /** Interactive search completes the final word; tool queries retain exact terms. */
  match?: "prefix";
  role?: "assistant" | "user";
  sessionId?: string;
  sessionKeys?: string[];
  order?: "relevance" | "recent";
  storePath?: string;
  sessionKey?: string;
  /** Internal host-filtered recall; never enumerate the session inventory. */
  filterCandidates?: boolean;
};
//#endregion
//#region src/config/sessions/session-actor-memory-search-contract.d.ts
type SessionActorMemorySearchReads = {
  "session.history.search": {
    input: Pick<SessionTranscriptSearchParams, "query" | "limit" | "match" | "role" | "sessionId" | "sessionKeys" | "order">;
    output: SessionTranscriptSearchResult;
  };
};
//#endregion
//#region src/config/sessions/session-accessor.transcript-range.worker.d.ts
type ClosedTranscriptTurnReadResult = {
  kind: "ok";
  messages: AgentMessage[];
} | {
  kind: "non-descendant" | "projection-unavailable" | "session-rebound" | "stale" | "too-large";
};
//#endregion
//#region src/agents/agent-runtime-id.d.ts
/** Agent runtime id normalization helpers. */
type EmbeddedAgentRuntime = "openclaw" | "auto" | (string & {});
//#endregion
//#region src/agents/agent-roles.d.ts
declare const AGENT_ROLES: readonly ["coordinator", "researcher", "writer", "reviewer"];
type AgentRoleId = (typeof AGENT_ROLES)[number];
//#endregion
//#region src/system-agent/operation-types.d.ts
/** Parsed OpenClaw operation before approval/execution. */
type SystemAgentOperation = {
  kind: "none";
  message: string;
} | {
  kind: "overview";
} | {
  kind: "doctor";
} | {
  kind: "doctor-fix";
} | {
  kind: "status";
} | {
  kind: "health";
} | {
  kind: "config-validate";
} | {
  kind: "config-get";
  path: string;
} | {
  kind: "config-schema";
  path?: string;
} | {
  kind: "config-unset";
  path: string;
} | {
  kind: "config-set";
  path: string;
  value: string;
} | {
  kind: "config-set-ref";
  path: string;
  source: "env" | "file" | "exec" | "store";
  id: string;
  provider?: string;
  /** Value the owner supplied; stored as secret-store entry `id` before the ref is written. */
  secret?: string;
} | {
  kind: "setup";
  workspace?: string;
  model?: string;
  agentName?: string;
} | SystemAgentNavigationOperation | {
  kind: "channel-list";
} | {
  kind: "channel-info";
  channel: string;
} | {
  kind: "gateway-status";
} | {
  kind: "gateway-start";
} | {
  kind: "gateway-stop";
} | {
  kind: "gateway-restart";
} | {
  kind: "agents";
} | {
  kind: "models";
} | {
  kind: "plugin-list";
} | {
  kind: "plugin-search";
  query: string;
} | {
  kind: "plugin-install";
  spec: string;
} | {
  kind: "plugin-activate-artifact";
  path: string;
  sha256: string;
} | {
  kind: "plugin-uninstall";
  pluginId: string;
} | {
  kind: "audit";
} | {
  kind: "create-agent";
  agentId: string;
  name?: string;
  purpose?: string;
  role?: AgentRoleId;
  workspace?: string;
  model?: string;
  requesterAgentId?: string;
} | {
  kind: "create-team";
  coordinatorId?: string;
  prefix?: string;
  workspaceRoot?: string;
} | {
  kind: "set-default-model";
  model: string;
  agentId?: string;
};
/** Interactive actions owned by the host chat, never by delegated model turns. */
type SystemAgentNavigationOperation = {
  kind: "model-setup";
  workspace?: string;
} | {
  kind: "model-accounts";
} | {
  kind: "channel-setup";
  channel: string;
} | {
  kind: "skills-setup";
} | {
  kind: "search-setup";
} | {
  kind: "gateway-config-setup";
} | {
  kind: "memory-import";
} | {
  kind: "open-setup";
  target: "guided" | "classic" | "channels" | "search" | "gateway";
  channel?: string;
} | {
  kind: "open-tui";
  agentId?: string;
  workspace?: string;
  agentDraft?: "hatch";
};
//#endregion
//#region src/system-agent/operator-approval.d.ts
type SystemAgentProposalRef = {
  current?: string;
  operation?: SystemAgentOperation;
};
//#endregion
//#region src/agents/tools/system-agent-tool.d.ts
type SystemAgentToolOptions = {
  /** Verified inference owner, distinct from the internal OpenClaw execution agent. */
  agentId?: string;
  /** Where setup side effects run; the gateway surface never manages its own daemon. */
  surface: "cli" | "gateway";
  /** The host resolves delegated proposals under session policy, never a chat reply. */
  operatorApprovalOnly?: boolean;
  /**
   * Host-verified consent for THIS turn: true only when the host judged the
   * user's actual message to be an explicit approval. The model-supplied
   * `approved` argument alone must never authorize a mutation (prompt
   * injection, model error).
   */
  approvalArmed?: boolean;
  /**
   * Approval is scoped to one exact operation: a denied mutating call records
   * its canonical hash here (host-owned, survives turns), and an armed turn
   * may execute only a call matching that hash. Cleared after use.
   */
  proposalRef?: SystemAgentProposalRef;
  /**
   * Host handoff channel for actions the tool cannot perform itself
   * (interactive channel setup, external onboarding guidance, opening the
   * agent TUI). The engine reads it after the turn; CLI MCP hosts mirror it
   * from tool events.
   */
  directiveRef?: {
    current?: SystemAgentToolDirective;
  };
};
/** Host directives the hosting chat engine handles after the turn. */
type SystemAgentToolDirective = SystemAgentNavigationOperation | {
  kind: "approved-operation";
  operation: SystemAgentOperation;
};
//#endregion
//#region src/process/spawn-initiation.d.ts
/** Remote settlement fulfills after native launch or fenced refusal; rejection retains custody. */
type SpawnInitiation = <T>(launch: () => T, settlement?: Promise<unknown>) => T;
//#endregion
//#region src/process/supervisor/types.d.ts
type TerminationReason = "manual-cancel" | "overall-timeout" | "no-output-timeout" | "memory-limit" | "spawn-error" | "signal" | "exit";
type ProcessCleanupResult = {
  readonly reason: "forced-relay-exit";
  readonly signalRequested: "SIGKILL";
  readonly signalError?: Error;
  readonly exit: {
    readonly code: number | null;
    readonly signal: NodeJS.Signals | null;
  };
  readonly durationMs: number;
  readonly escalationAfterMs: number;
};
//#endregion
//#region packages/gateway-protocol/src/schema/plugin-retention.d.ts
/** Administrator-only, payload-free observations of the existing lifetime owner. */
declare const PluginRuntimeRetentionSchema: Type$1.TObject<{
  instanceId: Type$1.TString;
  pluginId: Type$1.TString;
  generation: Type$1.TOptional<Type$1.TInteger>;
  acceptingCalls: Type$1.TBoolean;
  replacementPending: Type$1.TBoolean;
  disposing: Type$1.TBoolean;
  total: Type$1.TInteger;
  omitted: Type$1.TInteger;
  references: Type$1.TArray<Type$1.TObject<{
    referenceId: Type$1.TString;
    kind: Type$1.TUnion<[Type$1.TLiteral<"work">, Type$1.TLiteral<"consumer">, Type$1.TLiteral<"custody">, Type$1.TLiteral<"call">, Type$1.TLiteral<"cleanup">]>;
    reason: Type$1.TUnion<[Type$1.TLiteral<"unknown">, Type$1.TLiteral<"registry-construction">, Type$1.TLiteral<"prepared-construction">, Type$1.TLiteral<"prepared-generation-lease">, Type$1.TLiteral<"invocation-scope">, Type$1.TLiteral<"service-start">, Type$1.TLiteral<"consumer">, Type$1.TLiteral<"call">, Type$1.TLiteral<"cleanup">]>;
    acquiredAtMs: Type$1.TNumber;
    ageMs: Type$1.TNumber;
    owner: Type$1.TUnion<[Type$1.TLiteral<"unknown">, Type$1.TObject<{
      agentId: Type$1.TOptional<Type$1.TString>;
      sessionKey: Type$1.TOptional<Type$1.TString>;
      runId: Type$1.TOptional<Type$1.TString>;
      serviceId: Type$1.TOptional<Type$1.TString>;
    }>]>;
    parentReferenceId: Type$1.TOptional<Type$1.TString>;
    cleanupState: Type$1.TUnion<[Type$1.TLiteral<"active">, Type$1.TLiteral<"pending">, Type$1.TLiteral<"failed">]>;
  }>>;
}>;
//#endregion
//#region src/plugins/plugin-instance.types.d.ts
/** Payload-free facts shared with administrator inspection. */
type PluginRetentionSnapshot = Static<typeof PluginRuntimeRetentionSchema>;
type PluginRetainedReference = Omit<PluginRetentionSnapshot["references"][number], "ageMs">;
/** Host-authored correlation only, never invocation or authorization authority. */
type PluginRetentionOwner = Readonly<Exclude<PluginRetainedReference["owner"], "unknown">>;
type PluginRetentionReason = PluginRetainedReference["reason"];
type PluginWorkRelease = (() => void) & {
  /** Updates observation only; never releases or revokes a hold. */
  setCleanupState?: (state: PluginRetainedReference["cleanupState"]) => void;
};
/** Disposal and admission shared by instance resources and registry handles. */
type PluginInstanceLifecycle = {
  readonly signal: AbortSignal;
  onDispose: (dispose: () => void | Promise<void>) => () => void;
  /** Detach caller context while retaining this instance's current registry and host resources. */
  runInBackgroundContext: <T>(run: () => T) => T;
};
/** Execution and host cleanup retain the same instance admission. */
type PluginInstanceExecution = {
  run<T>(run: () => T): T;
  runCleanup<T>(run: () => T): T;
};
type PluginInstanceAdmission = {
  readonly lifecycle: PluginInstanceLifecycle;
  run<T>(run: () => T): T;
};
/** Known disposal faults are reported outcomes, never new-call admission failures. */
type PluginInstanceDisposalResult = {
  errors: readonly unknown[];
};
/** A host-owned logical consumer retains only its exact instance's admitted operations. */
type PluginInstanceConsumer = {
  wrap<T>(value: T): T;
  run<T>(run: () => T): T;
  close(cleanup: () => void | Promise<void>): Promise<void>;
  release(): void;
};
/** Inventory custody owns retirement without depending on registry contributions. */
interface PluginInstanceResource {
  readonly pluginId: string;
  quiesce(): boolean;
  dispose(beforeCleanup?: () => void | Promise<void>, options?: {
    waitForSettlement?: boolean;
  }): Promise<PluginInstanceDisposalResult>;
}
/** Captured code custody survives retiring a runtime until recovery consumes or releases it. */
type PluginModuleLoaderRecovery = {
  bind(instance: PluginModuleLoaderOwner): void;
  dispose(): Promise<void>;
};
/** Runtime and setup loaders use the same instance-owned captured source. */
interface PluginModuleLoaderOwner extends PluginInstanceResource, PluginInstanceAdmission {
  controlPlaneInitialized: boolean;
  sourceDigest?: string;
  onModuleDispose(cleanup: () => void | Promise<void>): void;
  bindModuleLoader(load: (source: string) => unknown, hasSource?: (source: string) => boolean): void;
  loadModule(source: string): unknown;
  hasModuleSource(source: string): boolean | undefined;
  bindModuleLoaderRecovery(capture: () => PluginModuleLoaderRecovery | Promise<PluginModuleLoaderRecovery>): void;
  captureModuleLoaderRecovery(): Promise<PluginModuleLoaderRecovery>;
}
/** Current-call helpers retain the instance itself, not a registry or plugin-id lookup. */
interface PluginInvocationInstance extends PluginModuleLoaderOwner {
  /** The current invocation's call or retained-consumer token is still admitted. */
  readonly hasActiveCall: boolean;
  holdsPendingReplacement(token: object): boolean;
  readonly slots: Map<string | symbol, {
    runtime: unknown;
  }>;
  wrap<T>(value: T): T;
}
//#endregion
//#region src/plugins/plugin-replacement-operation.d.ts
/** Host-only operation result, distinct from reservation release and operator status. */
type PluginReplacementOutcome = Readonly<{
  kind: "applied" | "restored" | "unchanged" | "failed";
  committed: boolean;
  unavailablePluginIds: readonly string[];
}>;
type PluginReplacementOperation = Readonly<{
  operationId: string;
  settled: Promise<PluginReplacementOutcome>;
}>;
//#endregion
//#region src/plugins/hook-gateway.types.d.ts
type PluginHookGatewayContext = {
  port?: number;
  config?: OpenClawConfig;
  workspaceDir?: string;
  getCron?: () => PluginHookGatewayCronService | undefined;
  /** In gateway_start, aborts at drain to stop producers; gateway_stop owns resource disposal. */
  abortSignal?: AbortSignal;
};
type PluginHookCronReconciledContext = PluginHookGatewayContext & {
  /** Aborts when this exact scheduler snapshot is superseded or the Gateway closes. */
  abortSignal: AbortSignal;
};
type PluginHookGatewayStartEvent = {
  port: number;
};
type PluginHookGatewayStopEvent = {
  reason?: string;
};
type PluginHookCronReconciledEvent = {
  reason: "startup" | "reload";
  enabled: boolean;
};
type PluginHookGatewayCronRunStatus = "ok" | "error" | "skipped";
type PluginHookGatewayCronDeliveryStatus = "not-requested" | "delivered" | "not-delivered" | "unknown";
type PluginHookGatewayCronJobState = {
  nextRunAtMs?: number;
  runningAtMs?: number;
  lastRunAtMs?: number;
  lastRunStatus?: PluginHookGatewayCronRunStatus;
  lastError?: string;
  lastDurationMs?: number;
  lastDelivered?: boolean;
  lastDeliveryStatus?: PluginHookGatewayCronDeliveryStatus;
  lastDeliveryError?: string;
  deliverySuppressionReason?: string;
  lastFailureNotificationDelivered?: boolean;
  lastFailureNotificationDeliveryStatus?: PluginHookGatewayCronDeliveryStatus;
  lastFailureNotificationDeliveryError?: string;
  streamStatus?: "starting" | "running" | "restarting" | "stopped" | "disabled" | "error";
  streamError?: string;
  streamConsecutiveFailures?: number;
  streamRestartExhausted?: boolean;
  streamDroppedBatches?: number;
  streamCoalescedBatches?: number;
  streamLastStartedAtMs?: number;
  streamLastExitAtMs?: number;
};
type PluginHookGatewayCronJob = {
  id: string;
  declarationKey?: string;
  /** Agent id that owns this cron job. */
  agentId?: string;
  name?: string;
  description?: string;
  enabled?: boolean;
  schedule?: {
    kind: "event";
    source: string;
    options: Record<string, unknown>;
  } | {
    kind: "cron";
    expr?: string;
    tz?: string;
    staggerMs?: number;
  } | {
    kind: "at";
    at?: string;
  } | {
    kind: "every";
    everyMs?: number;
    anchorMs?: number;
  } | {
    kind: "on-exit";
    command?: string;
    cwd?: string;
  } | {
    kind: "stream";
    command?: string[];
    cwd?: string;
    mode?: "line" | "match";
    match?: string;
    batchMs?: number;
    maxBatchBytes?: number;
  };
  sessionTarget?: string;
  wakeMode?: string;
  payload?: {
    kind?: string;
    text?: string;
  };
  state?: PluginHookGatewayCronJobState;
  createdAtMs?: number;
  updatedAtMs?: number;
};
type PluginHookCronChangedEvent = {
  action: "added" | "updated" | "removed" | "started" | "finished" | "scheduled";
  jobId: string;
  job?: PluginHookGatewayCronJob;
  /** Top-level session target for downstream routing (mirrors job.sessionTarget). */
  sessionTarget?: string;
  /** Agent id that owns this cron job (mirrors job.agentId). */
  agentId?: string;
  runAtMs?: number;
  durationMs?: number;
  status?: PluginHookGatewayCronRunStatus;
  completionStatus?: "succeeded" | "failed" | "unknown";
  error?: string;
  summary?: string;
  delivered?: boolean;
  deliveryStatus?: PluginHookGatewayCronDeliveryStatus;
  deliveryError?: string;
  deliverySuppressionReason?: string;
  sessionId?: string;
  sessionKey?: string;
  runId?: string;
  nextRunAtMs?: number;
  model?: string;
  provider?: string;
};
type PluginHookGatewayCronCreateInput = {
  declarationKey?: string;
  name: string;
  description: string;
  enabled: boolean;
  schedule: {
    kind: string;
    expr: string;
    tz?: string;
  };
  sessionTarget: string;
  wakeMode: string;
  payload: {
    kind: string;
    text?: string;
  };
};
type PluginHookGatewayCronUpdateInput = Partial<PluginHookGatewayCronCreateInput>;
type PluginHookGatewayCronRemoveResult = {
  removed?: boolean;
};
type PluginHookGatewayCronService = {
  /** Effective automatic scheduling state; older hosts may omit this observation. */
  isEnabled?: () => Promise<boolean>;
  list: (opts?: {
    includeDisabled?: boolean;
  }) => Promise<PluginHookGatewayCronJob[]>;
  add: (input: PluginHookGatewayCronCreateInput) => Promise<unknown>;
  update: (id: string, patch: PluginHookGatewayCronUpdateInput) => Promise<unknown>;
  remove: (id: string) => Promise<PluginHookGatewayCronRemoveResult>;
  removeStaleJobFamily: (family: {
    declarationKey: string;
    name: string;
    ownerPluginTag: string;
  }) => Promise<number>;
};
//#endregion
//#region src/cron/service-contract.d.ts
type CronWakeResult = {
  ok: true;
} | {
  ok: false;
  reason?: string;
};
/** Result shape for direct/queued cron runs. */
type CronServiceRunResult = CronRunResult;
type CronServiceRunOptions = {
  payload?: CronPayload;
  /** Per-occurrence routing; stored delivery policy remains authoritative. */
  delivery?: Partial<Pick<CronDelivery, "mode" | "target" | "channel" | "to" | "threadId" | "accountId">>;
  /** Internal event-source runs keep their persisted trigger on force execution. */
  evaluateTrigger?: boolean;
  /** Current stream batch exposed to trigger scripts as trigger.streamBatch. */
  streamBatch?: string;
  /** Source schedule identity checked under the cron store lock before admission. */
  streamScheduleKey?: string;
  /** Logical source identity; rejects retired batches under same-schedule ABA. */
  streamSourceIdentity?: string;
  onTriggerDisposition?: (disposition: "fired" | "dropped" | "busy" | "error") => void;
  /** Synchronous caller-authority guard consumed before run reservation. */
  commitGuard?: () => void;
};
/** Public cron service facade used by gateway, plugin SDK, and tests. */
interface CronServiceContract {
  readEventSources(source: string): Promise<CronEventSourceSnapshot[]>;
  runEvent(id: string, opts: CronEventRunOptions): Promise<CronEventRunResult>;
  start(): Promise<void>;
  stop(): void;
  status(): Promise<CronStatusSummary>;
  list(opts?: {
    includeDisabled?: boolean;
  }): Promise<CronListResult>;
  /** The in-process predicate runs under the store lock and must not mutate borrowed jobs. */
  listPage(opts?: CronListPageOptions, matchesJob?: (job: CronJob) => boolean): Promise<CronListPageResult>;
  add(input: CronAddInput, opts?: CronAddOptions): Promise<CronAddResult>;
  update(id: string, patch: CronUpdateInput, opts?: CronUpdateOptions): Promise<CronUpdateResult>;
  updateWithPrecondition(id: string, patch: CronUpdateInput, precondition: CronUpdatePrecondition, opts?: CronUpdateOptions): Promise<CronUpdateResult>;
  remove(id: string, opts?: CronRemoveOptions): Promise<CronRemoveResult>;
  run(id: string, mode?: CronRunMode, opts?: CronServiceRunOptions): Promise<CronServiceRunResult>;
  enqueueRun(id: string, mode?: CronRunMode, opts?: CronCommitGuardOptions): Promise<CronServiceRunResult>;
  getJob(id: string): CronStoredJob | undefined;
  readJob(id: string): Promise<CronStoredJob | undefined>;
  getDefaultAgentId(): string | undefined;
  wake(opts: {
    expectedTarget?: SessionEventTarget$1;
    createIfMissing?: true;
    mode: CronWakeMode;
    text: string;
    sessionKey?: string;
    agentId?: string;
    commitGuard?: () => void;
  }): Promise<CronWakeResult>;
}
//#endregion
//#region src/wizard/session.d.ts
type WizardStep = WizardStep$1;
type WizardSessionStatus = NonNullable<WizardNextResult$1["status"]>;
type WizardNextResult = WizardNextResult$1 & {
  status: WizardSessionStatus;
};
declare class WizardSession {
  private runner;
  private readonly abortController;
  private readonly expiryTimer;
  private readonly runnerPromise;
  private currentStep;
  private progressSteps;
  private deliveredProgressStepIds;
  private stepDeferred;
  private cancellationLocked;
  private inputClosedError;
  private preparationCancellationLocked;
  private expiryPending;
  private settled;
  private pendingExternalUrl;
  private devicePresentation;
  private externalUrlImmediate;
  private answerDeferred;
  private status;
  private error;
  private configuredAccounts;
  private preparedModelRef;
  private modelActivation;
  private activationRejection;
  constructor(runner: (prompter: WizardPrompter, signal: AbortSignal, session: WizardSession) => Promise<void>, options?: {
    timeoutMs?: number;
  });
  next(): Promise<WizardNextResult>;
  /** A non-consuming view for polling clients; retired prompts are never replayed. */
  getCurrentStep(): WizardStep | undefined;
  private terminalResult;
  /** Record what the channels flow actually configured (channels flow only). */
  setConfiguredAccounts(accounts: ReadonlyArray<{
    channel: string;
    accountId: string;
  }>): void;
  /** Record the exact provider-owned model prepared by a setup flow. */
  setPreparedModelRef(modelRef: string): void;
  /** Record the live activation result, distinct from provider preparation. */
  setModelActivation(activation: NonNullable<WizardNextResult$1["modelActivation"]>): void;
  /** Only the activation owner can distinguish rejection from possibly committed failure. */
  setActivationRejection(rejection: NonNullable<WizardNextResult$1["activationRejection"]>): void;
  answer(stepId: string, value: unknown): Promise<string | undefined>;
  cancel(): boolean;
  /** Close client input without interrupting an operation past its commit point. */
  close(error: Error): void;
  /** The underlying mutation crossed its durable commit point and must finish. */
  lockCancellation(): void;
  /** A retained write callback cannot outlive the runner that owns setup. */
  assertPersistentEffectCurrent(): void;
  /** Protect preparation until the next client checkpoint or final commit. */
  lockCancellationForPreparation(): void;
  /** Resume cancellation after preparation, before more input or verification. */
  finishPreparation(): void;
  get signal(): AbortSignal;
  pushStep(step: WizardStep): void;
  pushProgress(message: string, presentation?: Pick<WizardStep, "title" | "deviceCode">, progressMessage?: string): void;
  private rememberDeliveredProgressStep;
  queueExternalUrl(url: string): void;
  consumeExternalUrl(retain?: boolean): string | undefined;
  private run;
  private rejectPendingAnswers;
  awaitAnswer(step: WizardStep, validate?: (value: string) => string | undefined, signal?: AbortSignal): Promise<unknown>;
  private resolveStep;
  getStatus(): WizardSessionStatus;
  /** Whether the runner has stopped and can no longer mutate setup state. */
  isSettled(): boolean;
  /** Resolves after the runner can no longer mutate setup state. */
  whenSettled(): Promise<void>;
  getError(): string | undefined;
}
//#endregion
//#region src/config/implicit-mentions.d.ts
type ResolvedChannelImplicitMentions = Required<ChannelImplicitMentionsConfig>;
/** Resolves each implicit-mention kind using account, channel, defaults, then shipped behavior. */
declare function resolveChannelImplicitMentions(params: {
  cfg: OpenClawConfig;
  channel: string;
  accountId?: string | null;
}): ResolvedChannelImplicitMentions;
//#endregion
//#region src/channels/ids.d.ts
type ChatChannelId = string;
//#endregion
//#region src/channels/mention-gating.d.ts
type InboundImplicitMentionKind = "reply_to_bot" | "quoted_bot" | "bot_thread_participant" | "native";
type InboundMentionFacts = {
  canDetectMention: boolean;
  wasMentioned: boolean;
  hasAnyMention?: boolean;
  implicitMentionKinds?: readonly InboundImplicitMentionKind[];
};
type InboundMentionPolicy = {
  isGroup: boolean;
  requireMention: boolean;
  implicitMentions?: ChannelImplicitMentionsConfig;
  allowedImplicitMentionKinds?: readonly InboundImplicitMentionKind[];
  allowTextCommands: boolean;
  hasControlCommand: boolean;
  commandAuthorized: boolean;
};
/** @deprecated Prefer the nested `{ facts, policy }` call shape for new code. */
type ResolveInboundMentionDecisionFlatParams = InboundMentionFacts & InboundMentionPolicy;
type ResolveInboundMentionDecisionNestedParams = {
  facts: InboundMentionFacts;
  policy: InboundMentionPolicy;
};
type ResolveInboundMentionDecisionParams = ResolveInboundMentionDecisionFlatParams | ResolveInboundMentionDecisionNestedParams;
type InboundMentionDecision = {
  effectiveWasMentioned: boolean;
  shouldSkip: boolean;
  implicitMention: boolean;
  matchedImplicitMentionKinds: InboundImplicitMentionKind[];
  shouldBypassMention: boolean;
};
declare function implicitMentionKindWhen(kind: InboundImplicitMentionKind, enabled: boolean): InboundImplicitMentionKind[];
declare function resolveInboundMentionDecision(params: ResolveInboundMentionDecisionParams): InboundMentionDecision;
//#endregion
//#region src/channels/message-access/types.d.ts
type ChannelIngressChannelId = ChatChannelId;
type ChannelIngressMatchContext = "dm" | "group" | "route" | "command";
type ChannelIngressIdentifierKind = "stable-id" | "username" | "email" | "phone" | "role" | `plugin:${string}`;
/** Public, redacted identifier material that can participate in allowlist matching. */
type MatchableIdentifier = {
  opaqueId: string;
  kind: ChannelIngressIdentifierKind;
  authentication?: IdentifierAuthentication;
  /** @deprecated Use `authentication: "mutable"`. Remove in the next Plugin SDK major. */
  dangerous?: boolean;
  sensitivity?: "normal" | "pii";
};
/** Internal identifier material with the raw comparable value retained. */
type InternalMatchMaterial = MatchableIdentifier & {
  value: string;
};
type InternalChannelIngressSubject = {
  identifiers: InternalMatchMaterial[];
};
/** SDK inputs remain optional; kernel consumers receive resolved authentication. */
type NormalizedIngressSubject = {
  identifiers: Array<InternalMatchMaterial & {
    authentication: IdentifierAuthentication;
  }>;
};
/** Public, redacted form of a normalized allowlist entry. */
type ChannelIngressNormalizedEntry = Omit<MatchableIdentifier, "opaqueId"> & {
  opaqueEntryId: string;
  wildcard?: boolean;
};
/** Internal normalized allowlist entry with its raw comparable value retained. */
type InternalNormalizedEntry = ChannelIngressNormalizedEntry & {
  value: string;
  identityFieldKey?: string;
};
type NormalizedIngressEntry = InternalNormalizedEntry & {
  authentication: IdentifierAuthentication;
};
type RedactedIngressEntryDiagnostic = {
  opaqueEntryId?: string;
  reasonCode: IngressReasonCode;
};
type RedactedIngressMatch = {
  matched: boolean;
  matchedEntryIds: string[];
  /** Exact redacted entry-to-subject edges retained for authentication policy. */
  matchedPairs?: {
    opaqueEntryId: string;
    opaqueSubjectId: string;
    subjectAuthentication: IdentifierAuthentication;
  }[];
};
type InternalChannelIngressNormalizeResult = {
  matchable: InternalNormalizedEntry[];
  invalid: RedactedIngressEntryDiagnostic[];
  disabled: RedactedIngressEntryDiagnostic[];
};
/** Adapter that gives the shared ingress kernel channel-specific identity matching. */
type InternalChannelIngressAdapter = {
  normalizeEntries(params: {
    entries: readonly string[];
    context: ChannelIngressMatchContext;
    accountId: string;
  }): InternalChannelIngressNormalizeResult | Promise<InternalChannelIngressNormalizeResult>;
  matchSubject(params: {
    subject: NormalizedIngressSubject;
    entries: readonly NormalizedIngressEntry[];
    context: ChannelIngressMatchContext;
  }): RedactedIngressMatch | Promise<RedactedIngressMatch>;
};
type AccessGroupMembershipFact = {
  kind: "matched";
  groupName: string;
  source: "static" | "dynamic";
  matchedEntryIds: string[];
} | {
  kind: "not-matched";
  groupName: string;
  source: "static" | "dynamic";
} | {
  kind: "missing" | "unsupported" | "failed";
  groupName: string;
  source: "static" | "dynamic";
  reasonCode: IngressReasonCode;
  diagnosticId?: string;
};
type ResolvedIngressAllowlist = {
  rawEntryCount: number;
  normalizedEntries: ChannelIngressNormalizedEntry[];
  invalidEntries: RedactedIngressEntryDiagnostic[];
  disabledEntries: RedactedIngressEntryDiagnostic[];
  matchedEntryIds: string[];
  hasConfiguredEntries: boolean;
  hasMatchableEntries: boolean;
  hasWildcard: boolean;
  accessGroups: {
    referenced: string[];
    matched: string[];
    missing: string[];
    unsupported: string[];
    failed: string[];
  };
  match: RedactedIngressMatch;
  authentication?: {
    evaluated: boolean;
    threshold: IdentifierAuthentication;
    affectedMatch: boolean;
    rejectedEntryIds: string[];
  };
};
type RedactedIngressAllowlistFacts = {
  configured: boolean;
  matched: boolean;
  reasonCode: IngressReasonCode;
  matchedEntryIds: string[];
  invalidEntryCount: number;
  disabledEntryCount: number;
  accessGroups: ResolvedIngressAllowlist["accessGroups"];
};
type RouteGateFacts = {
  id: string;
  kind: "route" | "routeSender" | "membership" | "ownerAllowlist" | "nestedAllowlist";
  gate: "not-configured" | "matched" | "not-matched" | "disabled" | "lookup-failed";
  effect: "allow" | "block-dispatch" | "ignore";
  precedence: number;
  /** How a matched route affects sender allowlist evaluation. */
  senderPolicy: "inherit" | "replace" | "deny-when-empty";
  senderAllowFrom?: Array<string | number>;
  /** Source list used when a route sender policy contributes sender entries. */
  senderAllowFromSource?: "effective-dm" | "effective-group";
  match?: RedactedIngressMatch;
};
type ResolvedRouteGateFacts = Omit<RouteGateFacts, "senderAllowFrom" | "senderAllowFromSource"> & {
  senderAllowlist?: ResolvedIngressAllowlist;
};
/** Inbound event facts used to choose command, pairing, and origin-subject rules. */
type ChannelIngressEventInput = {
  kind: "message" | "reaction" | "button" | "postback" | "native-command" | "slash-command" | "system";
  authMode: "inbound" | "command" | "origin-subject" | "route-only" | "none";
  mayPair: boolean;
  originSubject?: InternalChannelIngressSubject;
};
type RedactedChannelIngressEvent = Omit<ChannelIngressEventInput, "originSubject"> & {
  hasOriginSubject: boolean;
  originSubjectMatched: boolean;
  originSubjectAuthentication?: IdentifierAuthentication;
};
type ChannelIngressStateInput = {
  channelId: ChannelIngressChannelId;
  accountId: string;
  subject: InternalChannelIngressSubject;
  conversation: {
    kind: ChatType;
    id: string;
    parentId?: string;
    threadId?: string;
    title?: string;
  };
  adapter: InternalChannelIngressAdapter;
  accessGroups?: Record<string, AccessGroupConfig>;
  accessGroupMembership?: readonly AccessGroupMembershipFact[];
  routeFacts?: RouteGateFacts[];
  mentionFacts?: InboundMentionFacts;
  event: ChannelIngressEventInput;
  allowlists: {
    dm?: Array<string | number>;
    group?: Array<string | number>;
    commandOwner?: Array<string | number>;
    commandGroup?: Array<string | number>;
    pairingStore?: Array<string | number>;
  };
};
type ChannelIngressPolicyInput = {
  dmPolicy: DmPolicy;
  groupPolicy: GroupPolicy;
  groupAllowFromFallbackToAllowFrom?: boolean;
  minIdentifierAuthentication?: IdentifierAuthentication;
  /** @deprecated `enabled` maps to minimum `mutable`; otherwise minimum `asserted`. Remove in the next Plugin SDK major. */
  mutableIdentifierMatching?: "disabled" | "enabled";
  activation?: {
    requireMention: boolean;
    allowTextCommands: boolean;
    implicitMentions?: ResolvedChannelImplicitMentions;
    allowedImplicitMentionKinds?: readonly InboundImplicitMentionKind[];
    order?: "before-sender" | "after-command";
  };
  command?: {
    useAccessGroups?: boolean;
    allowTextCommands: boolean;
    hasControlCommand: boolean;
    modeWhenAccessGroupsOff?: "allow" | "deny" | "configured";
  };
};
type IngressReasonCode = "allowed" | "route_blocked" | "route_sender_empty" | "dm_policy_disabled" | "dm_policy_open" | "dm_policy_allowlisted" | "dm_policy_pairing_required" | "dm_policy_not_allowlisted" | "group_policy_disabled" | "group_policy_open" | "group_policy_allowed" | "group_policy_empty_allowlist" | "group_policy_not_allowlisted" | "command_authorized" | "control_command_unauthorized" | "event_authorized" | "event_unauthorized" | "event_pairing_not_allowed" | "sender_not_required" | "origin_subject_missing" | "origin_subject_not_matched" | "activation_allowed" | "activation_skipped" | "access_group_missing" | "access_group_unsupported" | "access_group_failed" | "mutable_identifier_disabled" | "identifier_authentication_too_weak" | "no_policy_match";
type AccessGraphGate = {
  id: string;
  phase: "route" | "sender" | "command" | "event" | "activation";
  kind: "route" | "routeSender" | "dmSender" | "groupSender" | "membership" | "ownerAllowlist" | "nestedAllowlist" | "command" | "event" | "mention";
  effect: "allow" | "block-dispatch" | "block-command" | "skip" | "observe" | "ignore";
  allowed: boolean;
  reasonCode: IngressReasonCode;
  match?: RedactedIngressMatch;
  allowlist?: RedactedIngressAllowlistFacts;
  identifierAuthentication?: {
    evaluated: boolean;
    affectedMatch: boolean;
  };
  sender?: {
    policy: ChannelIngressPolicyInput["dmPolicy"] | ChannelIngressPolicyInput["groupPolicy"];
  };
  command?: {
    useAccessGroups: boolean;
    allowTextCommands: boolean;
    modeWhenAccessGroupsOff?: "allow" | "deny" | "configured";
    shouldBlockControlCommand: boolean;
  };
  event?: RedactedChannelIngressEvent;
  activation?: {
    hasMentionFacts: boolean;
    requireMention: boolean;
    allowTextCommands: boolean;
    allowedImplicitMentionKinds?: readonly InboundImplicitMentionKind[];
    order?: "before-sender" | "after-command";
    shouldSkip: boolean;
    canDetectMention?: boolean;
    wasMentioned?: boolean;
    hasAnyMention?: boolean;
    implicitMentionKinds?: readonly InboundImplicitMentionKind[];
    effectiveWasMentioned?: boolean;
    shouldBypassMention?: boolean;
  };
};
/** Normalized ingress state before policy gates are reduced into a decision. */
type ChannelIngressState = {
  channelId: ChannelIngressChannelId;
  accountId: string;
  conversationKind: ChatType;
  event: RedactedChannelIngressEvent;
  mentionFacts?: InboundMentionFacts;
  routeFacts: ResolvedRouteGateFacts[];
  allowlists: {
    dm: ResolvedIngressAllowlist;
    pairingStore: ResolvedIngressAllowlist;
    group: ResolvedIngressAllowlist;
    commandOwner: ResolvedIngressAllowlist;
    commandGroup: ResolvedIngressAllowlist;
  };
};
type ChannelIngressDecision = {
  admission: "dispatch" | "observe" | "skip" | "drop" | "pairing-required";
  decision: "allow" | "block" | "pairing";
  decisiveGateId: string;
  reasonCode: IngressReasonCode;
  graph: {
    gates: AccessGraphGate[];
  };
};
//#endregion
//#region src/channels/message-access/runtime-types.d.ts
type ChannelIngressIdentityField = {
  /** Unique field key used in subject alias maps and diagnostics. */
  key?: string;
  /** Redacted identifier kind written into the access graph. */
  kind?: ChannelIngressIdentifierKind;
  /** Shared normalizer used for both entries and subjects when no side-specific normalizer exists. */
  normalize?: (value: string) => string | null | undefined;
  normalizeEntry?: (value: string) => string | null | undefined;
  normalizeSubject?: (value: string) => string | null | undefined;
  /** Static strength of this identity field. `verified` requires owning-boundary metadata. */
  authentication?: IdentifierAuthentication | ((value: string) => IdentifierAuthentication | undefined);
  /** @deprecated Use `authentication: "mutable"`. Remove in the next Plugin SDK major. */
  dangerous?: boolean | ((value: string) => boolean | undefined);
  /** Redaction hint for diagnostics and access graph consumers. */
  sensitivity?: "normal" | "pii";
};
type ChannelIngressIdentityAlias = ChannelIngressIdentityField & {
  key: string;
};
/** Identity contract for a channel resolver. Plugins provide platform normalization here. */
type ChannelIngressIdentityDescriptor = {
  /** Product identity: only when the plugin can prove the remote issuer and identifier kind. */
  resolveParticipant?: (subject: ChannelIngressIdentitySubjectInput) => {
    domain: string;
    idKind: string;
    id: string;
  } | undefined;
  /** Primary stable identity field. Prefer immutable sender ids when the platform has one. */
  primary: ChannelIngressIdentityField;
  /** Additional identifiers that can match legacy or platform-specific allowlist entries. */
  aliases?: readonly ChannelIngressIdentityAlias[];
  /** Returns true when a raw allowlist entry should authorize every sender. */
  isWildcardEntry?: (value: string) => boolean;
  /** Optional custom match hook for platform-specific identity equivalence. */
  matchEntry?: (params: {
    subject: InternalChannelIngressSubject;
    entry: InternalNormalizedEntry;
    context: ChannelIngressMatchContext;
  }) => boolean | undefined;
  /** Generates stable redacted entry ids for diagnostics. */
  resolveEntryId?: (params: {
    entry: string;
    entryIndex: number;
    fieldKey: string;
    fieldIndex: number;
  }) => string;
};
type StableChannelIngressIdentityParams = ChannelIngressIdentityField & Pick<ChannelIngressIdentityDescriptor, "aliases" | "isWildcardEntry" | "matchEntry" | "resolveParticipant"> & {
  /** Prefix used for generated entry ids when `resolveEntryId` is omitted. */
  entryIdPrefix?: string;
  /** Custom entry-id generator used in redacted diagnostics. */
  resolveEntryId?: ChannelIngressIdentityDescriptor["resolveEntryId"];
};
type ChannelIngressIdentitySubjectInput = {
  /** Stable sender id appended to effective allowlists when access groups matched. */
  stableId?: string | number | null;
  /** Optional identity aliases keyed by `ChannelIngressIdentityAlias.key`. */
  aliases?: Record<string, string | number | null | undefined>;
  /** Per-message claims keyed by the exact identity field key. */
  authentication?: Record<string, IdentifierAuthentication | undefined>;
};
type ChannelIngressConfigInput = {
  /** Static or dynamic access group definitions referenced by allowlist entries. */
  accessGroups?: ChannelIngressStateInput["accessGroups"];
} | null;
type ChannelMessageIngressCommandInput = NonNullable<ChannelIngressPolicyInput["command"]> & {
  /** Explicit command-owner allowlist; defaults to effective DM allowlist. */
  commandOwnerAllowFrom?: Array<string | number> | null;
  /** Controls whether group command owners inherit configured DM owners. */
  groupOwnerAllowFrom?: "configured" | "none";
  /** Allows direct-message command checks to reuse effective group allowlists. */
  directGroupAllowFrom?: "effective" | "none";
  /** Group command allowFrom fallback, separate from normal group sender policy. */
  commandGroupAllowFromFallbackToAllowFrom?: boolean;
};
type ChannelIngressCommandPresetInput = Omit<Partial<ChannelMessageIngressCommandInput>, "useAccessGroups"> & {
  /** Set false to omit the command gate entirely. */
  requested?: boolean;
  /** Internal override for this command decision. */
  useAccessGroups?: boolean | null;
  /** Config subset used to derive command access-group behavior. */
  cfg?: ChannelIngressConfigInput;
};
type ChannelIngressEventPresetInput = Partial<ChannelIngressEventInput> & {
  /** Convenience flag used to derive pairing defaults for group events. */
  isGroup?: boolean;
};
/** Final host-context identity that an ingress result is eligible to enter once. */
type ChannelIngressContextBinding = {
  /** Final routed agent selected by the channel producer. */
  agentId: string;
  /** Final dispatch or route session selected by the channel producer. */
  sessionKey: string;
  /** Final message id used by the host context, after any transport ID mapping. */
  messageId?: string;
  /** Match the host context's reply or conversation nativeChannelId, including when it equals id. */
  nativeChannelId?: string;
  /** Final inbound event classification used by the host context. */
  inboundEventKind: InboundEventKind;
};
/** Optional route gate, such as a room, thread, topic, guild, or group route. */
type ChannelIngressRouteDescriptor = {
  /** Stable route id used in diagnostics. */
  id: string;
  /** Route kind for diagnostics and graph consumers. */
  kind?: RouteGateFacts["kind"];
  configured?: boolean;
  matched?: boolean;
  allowed?: boolean;
  /** Whether to include this route descriptor in the graph. */
  enabled?: boolean;
  /** Ordering hint when multiple route descriptors are supplied. */
  precedence?: number;
  /** How route sender allowlists combine with effective channel allowlists. */
  senderPolicy?: RouteGateFacts["senderPolicy"];
  senderAllowFrom?: Array<string | number> | null;
  /** Indicates whether route sender entries came from effective DM or group policy. */
  senderAllowFromSource?: RouteGateFacts["senderAllowFromSource"];
  /** Optional redacted match id for the route. */
  matchId?: string;
  /** Reason used when this route blocks the event. */
  blockReason?: string;
};
/** Dynamic access-group resolver invoked for groups that need platform lookups. */
type ChannelIngressAccessGroupMembershipResolver = (params: {
  name: string;
  group: AccessGroupConfig;
  channelId: ChannelIngressChannelId;
  accountId: string;
  subject: ChannelIngressIdentitySubjectInput;
}) => boolean | Promise<boolean>;
type ResolveChannelMessageIngressParams = {
  /** Channel id used for config, diagnostics, access groups, and pairing-store reads. */
  channelId: ChannelIngressChannelId;
  /** Account id scoped to this channel instance. */
  accountId: string;
  identity: ChannelIngressIdentityDescriptor;
  subject: ChannelIngressIdentitySubjectInput;
  conversation: ChannelIngressStateInput["conversation"];
  event: ChannelIngressEventInput;
  /** Exact finalized host context this result may enter; omit for decision-only checks. */
  contextBinding?: ChannelIngressContextBinding;
  /** Opted-in public ingress: publish fresh isolated visible children of this invocation.
   * The plugin must verify every supplied context post is public; unknown audiences deny.
   * Recheck current account policy and delivery ownership synchronously at use time.
   */
  childSessionPublication?: {
    audience: "public";
    assertCurrent: () => void;
    /** Renew source authorization at run admission; return its synchronous use-time guard.
     * Return null if the original route, access tier, or public audience is no longer valid.
     * Throw for operational failures so the runner reports a retryable verification failure.
     */
    prepare?: () => Promise<(() => void) | null>;
  };
  policy: ChannelIngressPolicyInput;
  /** Raw direct-message allowlist entries. */
  allowFrom?: Array<string | number> | null;
  /** Raw group sender allowlist entries. */
  groupAllowFrom?: Array<string | number> | null;
  /** Route descriptors used to build route gates. */
  route?: ChannelIngressRouteDescriptor | readonly ChannelIngressRouteDescriptor[];
  /** Prebuilt route facts for lower-level callers. */
  routeFacts?: RouteGateFacts[];
  /** Access group config referenced by allowlist entries. */
  accessGroups?: ChannelIngressStateInput["accessGroups"];
  /** Precomputed access-group memberships for this subject. */
  accessGroupMembership?: readonly AccessGroupMembershipFact[];
  resolveAccessGroupMembership?: ChannelIngressAccessGroupMembershipResolver;
  /** Concrete sender entry appended to effective allowlists when an access group matched. */
  accessGroupMatchedAllowFromEntry?: string | number | null;
  providerMissingFallbackApplied?: boolean;
  mentionFacts?: ChannelIngressStateInput["mentionFacts"];
  /** Optional pairing-store reader for direct-message allowlist material. */
  readStoreAllowFrom?: (params: {
    channelId: ChannelIngressChannelId;
    accountId: string;
    dmPolicy: ChannelIngressPolicyInput["dmPolicy"];
  }) => Promise<readonly (string | number)[] | null | undefined>;
  /** Reads the default pairing store when no explicit reader is supplied. */
  useDefaultPairingStore?: boolean;
  /** Command gate input; omit when no command policy is requested. */
  command?: ChannelMessageIngressCommandInput;
};
/** Shared resolver defaults for repeated events from the same channel account. */
type CreateChannelIngressResolverParams = Pick<ResolveChannelMessageIngressParams, "channelId" | "accountId" | "identity" | "accessGroups" | "accessGroupMembership" | "resolveAccessGroupMembership" | "accessGroupMatchedAllowFromEntry" | "readStoreAllowFrom" | "useDefaultPairingStore"> & {
  /** Config subset used for access groups and command behavior. */
  cfg?: ChannelIngressConfigInput;
  /** Global override for access-group expansion in this resolver. */
  useAccessGroups?: boolean | null;
  /** Default DM policy for message calls that omit it. */
  defaultDmPolicy?: ChannelIngressPolicyInput["dmPolicy"];
  /** Default group policy for message calls that omit it. */
  defaultGroupPolicy?: ChannelIngressPolicyInput["groupPolicy"];
  groupAllowFromFallbackToAllowFrom?: boolean;
  /** Weakest exact-pair identifier claim allowed to authorize. */
  minIdentifierAuthentication?: ChannelIngressPolicyInput["minIdentifierAuthentication"];
  /** @deprecated Maps to `minIdentifierAuthentication`; remove in the next Plugin SDK major. */
  mutableIdentifierMatching?: ChannelIngressPolicyInput["mutableIdentifierMatching"];
};
type ChannelIngressResolverMessageParams = Omit<ResolveChannelMessageIngressParams, "channelId" | "accountId" | "identity" | "accessGroups" | "resolveAccessGroupMembership" | "accessGroupMatchedAllowFromEntry" | "readStoreAllowFrom" | "useDefaultPairingStore" | "event" | "policy" | "command"> & {
  /** Event facts or presets; defaults to a normal inbound message event. */
  event?: ChannelIngressEventPresetInput;
  dmPolicy?: ChannelIngressPolicyInput["dmPolicy"];
  groupPolicy?: ChannelIngressPolicyInput["groupPolicy"];
  /** Additional policy fields merged with resolver defaults. */
  policy?: Partial<Omit<ChannelIngressPolicyInput, "dmPolicy" | "groupPolicy">>;
  /** Command gate input, preset, or false to suppress command checks. */
  command?: ChannelIngressCommandPresetInput | false;
};
type ChannelIngressResolver = {
  /** Resolve a normal inbound message with sender, route, command, event, and activation gates. */
  message(params: ChannelIngressResolverMessageParams): Promise<ResolvedChannelMessageIngress>;
  /** Resolve a command-oriented event with command auth defaults enabled. */
  command(params: ChannelIngressResolverMessageParams): Promise<ResolvedChannelMessageIngress>;
  /** Resolve a non-message event with event-gate defaults enabled. */
  event(params: ChannelIngressResolverMessageParams): Promise<ResolvedChannelMessageIngress>;
};
type ResolveStableChannelMessageIngressParams = Omit<CreateChannelIngressResolverParams, "identity"> & ChannelIngressResolverMessageParams & {
  identity?: StableChannelIngressIdentityParams;
};
/** Sender/conversation projection consumed by channel handlers. */
type ChannelIngressSenderAccess = {
  allowed: boolean;
  /** Final ingress decision after all gates, not just the sender gate. */
  decision: ChannelIngressDecision["decision"];
  /** Sender gate reason when present, otherwise decisive ingress reason. */
  reasonCode: IngressReasonCode;
  /** Sender gate from the access graph, when one ran. */
  gate?: AccessGraphGate;
  /** Effective DM allowlist entries after store and access-group processing. */
  effectiveAllowFrom: string[];
  /** Effective group allowlist entries after fallback and access-group processing. */
  effectiveGroupAllowFrom: string[];
  providerMissingFallbackApplied: boolean;
};
type ChannelIngressCommandAccess = {
  requested: boolean;
  authorized: boolean;
  shouldBlockControlCommand: boolean;
  /** Command gate reason when present, otherwise decisive ingress reason. */
  reasonCode: IngressReasonCode;
  /** Command gate from the access graph, when one ran. */
  gate?: AccessGraphGate;
};
type ChannelIngressRouteAccess = {
  /** True when all configured route gates admit the event. */
  allowed: boolean;
  /** Route gate reason when a route gate decided. */
  reasonCode?: IngressReasonCode;
  /** Optional route-specific reason text. */
  reason?: string;
  /** Route gate from the access graph, when one ran. */
  gate?: AccessGraphGate;
};
type ChannelIngressActivationAccess = {
  ran: boolean;
  allowed: boolean;
  /** True when the event should be skipped instead of dispatched. */
  shouldSkip: boolean;
  /** Activation gate reason when present, otherwise decisive ingress reason. */
  reasonCode: IngressReasonCode;
  /** Effective mention match after command bypass and activation policy. */
  effectiveWasMentioned?: boolean;
  /** True when mention gating was bypassed by policy or command facts. */
  shouldBypassMention?: boolean;
  /** Activation gate from the access graph, when one ran. */
  gate?: AccessGraphGate;
};
type ResolvedChannelMessageIngress = {
  /** Redacted normalized state used as input to the decision engine. */
  state: ChannelIngressState;
  /** Ordered access graph plus final admission decision. */
  ingress: ChannelIngressDecision;
  senderAccess: ChannelIngressSenderAccess;
  routeAccess: ChannelIngressRouteAccess;
  commandAccess: ChannelIngressCommandAccess;
  activationAccess: ChannelIngressActivationAccess;
};
//#endregion
//#region src/state/user-channel-authorization-reference.d.ts
declare const commandReferenceSchema: z.ZodUnion<readonly [z.ZodObject<{
  version: z.ZodLiteral<1>;
  id: z.ZodUUID;
}, z.core.$strict>, z.ZodObject<{
  id: z.ZodUUID;
  version: z.ZodLiteral<2>;
}, z.core.$strict>]>;
type CommandOwnerReference = Readonly<z.infer<typeof commandReferenceSchema>>;
//#endregion
//#region src/auto-reply/command-auth.d.ts
type CommandAuthorization = {
  providerId?: ChannelId$1;
  ownerList: string[];
  senderId?: string;
  senderIsOwner: boolean;
  /** Rechecks the host-admitted owner capability after awaited work, when one is present. */
  assertOwnerCurrent?: () => void;
  isAuthorizedSender: boolean;
  from?: string;
  to?: string;
};
type CommandAuthorizationParams = {
  ctx: MsgContext;
  cfg: OpenClawConfig;
  commandAuthorized: boolean;
};
/** @deprecated Await resolveCommandAuthorizationAsync for worker-owned channel allowlists. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveCommandAuthorization(params: CommandAuthorizationParams): CommandAuthorization;
/** Prepares channel allowlists through their worker-owned runtime before evaluating live authority. */
declare function resolveCommandAuthorizationAsync(params: CommandAuthorizationParams): Promise<CommandAuthorization>;
//#endregion
//#region src/channels/message-access/admission-evidence.d.ts
declare class ChannelAdmissionAudit {
  #private;
  constructor(params: {
    enabled: boolean;
    decisionSink?: (receipt: DecisionReceiptV1) => boolean;
  });
  get enabled(): boolean;
  configure(enabled: boolean): void;
  captureCurrent(): () => boolean;
  recordDecision(receipt: DecisionReceiptV1): boolean;
  close(): void;
}
//#endregion
//#region src/gateway/chat-attachments.d.ts
type ChatAttachment = SchemaContract<Omit<Static<typeof ChatAttachmentSchema>, "origin">> & {
  origin?: MediaFact["origin"];
};
//#endregion
//#region src/gateway/session-companion-state.d.ts
type SessionCompanionContextMessage = {
  role: "assistant" | "user";
  text: string;
  ts: number;
};
type SessionCompanionPreparedContext = {
  empty: boolean;
  messages: SessionCompanionContextMessage[];
  sessionId: string;
};
type SessionCompanionThread = {
  context: SessionCompanionPreparedContext;
  digestText: string;
  exchanges: SessionCompanionExchange[];
  lastNoteSequence: number;
  busy: boolean;
  lastUsedAt: number;
};
//#endregion
//#region src/gateway/session-companion-context.d.ts
type SessionCompanionContextReadResult = {
  kind: "ready";
  context: SessionCompanionPreparedContext;
} | {
  kind: "missing";
} | {
  kind: "unavailable";
};
type SessionCompanionContextReader = {
  currentSessionId: (params: {
    agentId: string;
    sessionKey: string;
  }) => Promise<string | undefined>;
  read: typeof readSessionCompanionContext;
};
declare function readSessionCompanionContext(params: {
  agentId: string;
  sessionKey: string;
  signal?: AbortSignal;
}): Promise<SessionCompanionContextReadResult>;
//#endregion
//#region src/config/sessions/transcript-target-binding.d.ts
type StorageEnvironment = Readonly<SqliteWorkerStateContext["environment"]>;
type SessionTranscriptTargetBinding = SessionTranscriptRuntimeTarget & {
  env?: StorageEnvironment;
};
/** Bind the locator and its storage namespace before reads or caller callbacks. */
declare function captureSessionTranscriptTargetBinding<T extends {
  storePath: string;
  agentId?: string;
  env?: NodeJS.ProcessEnv;
}>(source: T): Omit<T, "storePath" | "env"> & {
  storePath: string;
  env: StorageEnvironment;
};
//#endregion
//#region src/agents/sessions/event-bus.d.ts
interface EventBus {
  emit(channel: string, data: unknown): void;
  on(channel: string, handler: (data: unknown) => void): () => void;
}
//#endregion
//#region packages/ai/src/provider-types.d.ts
declare const PROVIDER_CONTEXT_HANDOFF: unique symbol;
declare const PROVIDER_MODEL_INPUT: unique symbol;
type VideoContent = Omit<ImageContent$1, "type"> & {
  type: "video";
};
type MediaContent = ImageContent$1 | VideoContent;
type ModelInputContent = TextContent | MediaContent;
type ProviderUserMessage = Omit<UserMessage, "content"> & {
  content: string | ModelInputContent[];
};
type ProviderMessage = ProviderUserMessage | AssistantHistoryMessage | ToolResultMessage;
type ProviderContext = Omit<Context, "messages"> & {
  messages: ProviderMessage[];
};
type ProviderModel<TApi extends Api = Api> = Omit<Model<TApi>, "input"> & {
  input: ModelInputContent["type"][];
};
type ProviderContextHandoff = () => Promise<ProviderContext>;
type ProviderStreamOptions = StreamOptions & {
  [PROVIDER_CONTEXT_HANDOFF]?: ProviderContextHandoff;
  [PROVIDER_MODEL_INPUT]?: ProviderModel["input"];
};
//#endregion
//#region src/llm/stream.d.ts
declare function completeSimple<TApi extends Api>(model: Model<TApi>, context: Context, options?: SimpleStreamOptions, assertCurrent?: () => void): Promise<AssistantMessage>;
//#endregion
//#region src/agents/modes/interactive/theme/theme-schema.d.ts
declare const ThemeJsonSchema: Type$1.TObject<{
  $schema: Type$1.TOptional<Type$1.TString>;
  name: Type$1.TString;
  vars: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>>>;
  colors: Type$1.TObject<{
    accent: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    border: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    borderAccent: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    borderMuted: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    success: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    error: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    warning: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    muted: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    dim: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    text: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingText: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    selectedBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    userMessageBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    userMessageText: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    customMessageBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    customMessageText: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    customMessageLabel: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolPendingBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolSuccessBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolErrorBg: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolTitle: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolOutput: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdHeading: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdLink: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdLinkUrl: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdCode: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdCodeBlock: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdCodeBlockBorder: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdQuote: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdQuoteBorder: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdHr: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    mdListBullet: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolDiffAdded: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolDiffRemoved: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    toolDiffContext: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxComment: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxKeyword: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxFunction: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxVariable: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxString: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxNumber: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxType: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxOperator: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    syntaxPunctuation: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingOff: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingMinimal: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingLow: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingMedium: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingHigh: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    thinkingXhigh: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
    bashMode: Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>;
  }>;
  export: Type$1.TOptional<Type$1.TObject<{
    pageBg: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>>;
    cardBg: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>>;
    infoBg: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TInteger]>>;
  }>>;
}>;
type ThemeJson = Static<typeof ThemeJsonSchema>;
//#endregion
//#region src/agents/modes/interactive/theme/theme.d.ts
type ThemeColor = Exclude<keyof ThemeJson["colors"], ThemeBg>;
declare const BACKGROUND_COLOR_KEYS: readonly ["selectedBg", "userMessageBg", "customMessageBg", "toolPendingBg", "toolSuccessBg", "toolErrorBg"];
type ThemeBg = (typeof BACKGROUND_COLOR_KEYS)[number];
type ColorMode = "truecolor" | "256color";
declare class Theme {
  readonly name?: string;
  readonly sourcePath?: string;
  sourceInfo?: SourceInfo;
  private fgColors;
  private bgColors;
  private mode;
  constructor(fgColors: Record<ThemeColor, string | number>, bgColors: Record<ThemeBg, string | number>, mode: ColorMode, options?: {
    name?: string;
    sourcePath?: string;
    sourceInfo?: SourceInfo;
  });
  fg(color: ThemeColor, text: string): string;
  bg(color: ThemeBg, text: string): string;
  bold(text: string): string;
  italic(text: string): string;
  underline(text: string): string;
  inverse(text: string): string;
  strikethrough(text: string): string;
  getFgAnsi(color: ThemeColor): string;
  getBgAnsi(color: ThemeBg): string;
  getColorMode(): ColorMode;
  getThinkingBorderColor(level: "off" | "minimal" | "low" | "medium" | "high" | "xhigh"): (str: string) => string;
  getBashModeBorderColor(): (str: string) => string;
}
//#endregion
//#region src/agents/sessions/bash-executor.d.ts
interface BashResult {
  /** Combined stdout + stderr output (sanitized, possibly truncated) */
  output: string;
  /** Process exit code (undefined if killed/cancelled) */
  exitCode: number | undefined;
  /** Whether the command was cancelled via signal */
  cancelled: boolean;
  /** Whether the output was truncated */
  truncated: boolean;
  /** Path to temp file containing full output (if output exceeded truncation threshold) */
  fullOutputPath?: string;
}
//#endregion
//#region src/agents/sessions/exec.d.ts
interface ExecOptions {
  /** AbortSignal to cancel the command */
  signal?: AbortSignal;
  /** Timeout in milliseconds */
  timeout?: number;
  cwd?: string;
  /** Optional maximum retained stdout/stderr characters per stream. */
  maxOutputChars?: number;
}
interface ExecResult {
  stdout: string;
  stderr: string;
  stdoutTruncatedChars?: number;
  stderrTruncatedChars?: number;
  outputLimitExceeded?: "stdout" | "stderr";
  code: number;
  killed: boolean;
}
//#endregion
//#region src/agents/sessions/footer-data-provider.d.ts
/** Read-only footer data supplied to session extensions. */
interface ReadonlyFooterDataProvider {
  /** Current git branch, null if not in repo, "detached" if detached HEAD */
  getGitBranch(): string | null;
  /** Extension status texts set via ctx.ui.setStatus() */
  getExtensionStatuses(): ReadonlyMap<string, string>;
  /** Number of unique providers with available models (for footer display) */
  getAvailableProviderCount(): number;
  /** Subscribe to git branch changes. Returns unsubscribe function. */
  onBranchChange(callback: () => void): () => void;
}
//#endregion
//#region src/agents/sessions/keybindings.d.ts
/** OpenClaw-specific key ids added to the shared pi-tui keybinding registry. */
type AppKeybindings = Record<keyof typeof APP_KEYBINDINGS, true>;
declare module "@earendil-works/pi-tui" {
  interface Keybindings extends AppKeybindings {}
}
declare const APP_KEYBINDINGS: {
  readonly "app.interrupt": ["escape", "Cancel or abort"];
  readonly "app.clear": ["ctrl+c", "Clear editor"];
  readonly "app.exit": ["ctrl+d", "Exit when editor is empty"];
  readonly "app.suspend": ["ctrl+z" | never[], "Suspend to background"];
  readonly "app.thinking.cycle": ["shift+tab", "Cycle thinking level"];
  readonly "app.model.cycleForward": ["ctrl+p", "Cycle to next model"];
  readonly "app.model.cycleBackward": ["shift+ctrl+p", "Cycle to previous model"];
  readonly "app.model.select": ["ctrl+l", "Open model selector"];
  readonly "app.tools.expand": ["ctrl+o", "Toggle tool output"];
  readonly "app.thinking.toggle": ["ctrl+t", "Toggle thinking blocks"];
  readonly "app.session.toggleNamedFilter": ["ctrl+n", "Toggle named session filter"];
  readonly "app.editor.external": ["ctrl+g", "Open external editor"];
  readonly "app.message.followUp": ["alt+enter", "Queue follow-up message"];
  readonly "app.message.dequeue": ["alt+up", "Restore queued messages"];
  readonly "app.clipboard.pasteImage": ["alt+v" | "ctrl+v", "Paste image from clipboard"];
  readonly "app.session.new": [[], "Start a new session"];
  readonly "app.session.tree": [[], "Open session tree"];
  readonly "app.session.fork": [[], "Fork current session"];
  readonly "app.session.resume": [[], "Resume a session"];
  readonly "app.tree.foldOrUp": [["ctrl+left", "alt+left"], "Fold tree branch or move up"];
  readonly "app.tree.unfoldOrDown": [["ctrl+right", "alt+right"], "Unfold tree branch or move down"];
  readonly "app.tree.editLabel": ["shift+l", "Edit tree label"];
  readonly "app.tree.toggleLabelTimestamp": ["shift+t", "Toggle tree label timestamps"];
  readonly "app.session.togglePath": ["ctrl+p", "Toggle session path display"];
  readonly "app.session.toggleSort": ["ctrl+s", "Toggle session sort mode"];
  readonly "app.session.rename": ["ctrl+r", "Rename session"];
  readonly "app.session.delete": ["ctrl+d", "Delete session"];
  readonly "app.session.deleteNoninvasive": ["ctrl+backspace", "Delete session when query is empty"];
  readonly "app.models.save": ["ctrl+s", "Save model selection"];
  readonly "app.models.enableAll": ["ctrl+a", "Enable all models"];
  readonly "app.models.clearAll": ["ctrl+x", "Clear all models"];
  readonly "app.models.toggleProvider": ["ctrl+p", "Toggle all models for provider"];
  readonly "app.models.reorderUp": ["alt+up", "Move model up in order"];
  readonly "app.models.reorderDown": ["alt+down", "Move model down in order"];
  readonly "app.tree.filter.default": ["ctrl+d", "Tree filter: default view"];
  readonly "app.tree.filter.noTools": ["ctrl+t", "Tree filter: hide tool results"];
  readonly "app.tree.filter.userOnly": ["ctrl+u", "Tree filter: user messages only"];
  readonly "app.tree.filter.labeledOnly": ["ctrl+l", "Tree filter: labeled entries only"];
  readonly "app.tree.filter.all": ["ctrl+a", "Tree filter: show all entries"];
  readonly "app.tree.filter.cycleForward": ["ctrl+o", "Tree filter: cycle forward"];
  readonly "app.tree.filter.cycleBackward": ["shift+ctrl+o", "Tree filter: cycle backward"];
};
/** Keybinding manager that loads OpenClaw defaults plus optional user overrides. */
declare class KeybindingsManager$1 extends KeybindingsManager {
  private configPath?;
  constructor(userBindings?: KeybindingsConfig, configPath?: string | undefined);
  /** Creates a manager from the agent keybindings.json file. */
  static create(agentDir?: string): KeybindingsManager$1;
  /** Reloads user overrides from disk when this manager was created with a config path. */
  reload(): void;
  /** Returns the currently resolved keybinding map after defaults and overrides. */
  getEffectiveConfig(): KeybindingsConfig;
  private static loadFromFile;
}
//#endregion
//#region src/plugin-sdk/provider-oauth-runtime.d.ts
/** Normalized OAuth credential bundle persisted by provider auth profiles. */
type OAuthCredentials = {
  /** Refresh token or provider-equivalent long-lived credential. */
  refresh: string;
  /** Access token or provider-equivalent bearer credential. */
  access: string;
  /** Absolute epoch milliseconds when the access token should be considered expired. */
  expires: number;
  [key: string]: unknown;
};
/** Stable provider id used by OAuth credential and config routing. */
type OAuthProviderId = string;
/** Manual input prompt shown during OAuth login flows. */
type OAuthPrompt$1 = {
  /** Prompt text shown to the operator. */
  message: string;
  /** Optional placeholder for manual text entry. */
  placeholder?: string;
  /** Whether empty input should be accepted instead of reprompting. */
  allowEmpty?: boolean;
};
/** Authorization URL and optional instructions shown before OAuth completion. */
type OAuthAuthInfo = {
  /** Provider authorization URL shown to the user. */
  url: string;
  /** Optional provider-specific instruction text for manual flows. */
  instructions?: string;
};
/** One selectable OAuth login option. */
type OAuthSelectOption = {
  /** Stable option id returned when the operator selects this entry. */
  id: string;
  /** Human-readable option label shown in the selector. */
  label: string;
};
/** Selector prompt used when a provider offers multiple OAuth login choices. */
type OAuthSelectPrompt = {
  /** Prompt text shown above the selectable options. */
  message: string;
  /** Options available for the operator to choose from. */
  options: OAuthSelectOption[];
};
/** UI/runtime callbacks used by provider OAuth login implementations. */
interface OAuthLoginCallbacks {
  /** Emits authorization URL/instructions to the UI before waiting for completion. */
  onAuth: (info: OAuthAuthInfo) => void;
  /** Prompts for manual input such as pasted callback URLs or authorization codes. */
  onPrompt: (prompt: OAuthPrompt$1) => Promise<string>;
  /** Reports human-readable login progress without exposing secrets. */
  onProgress?: (message: string) => void;
  /** Optional direct manual-code entry hook used when callback-server flows cannot complete. */
  onManualCodeInput?: () => Promise<string>;
  /** Show an interactive selector and return the selected option id, or undefined on cancel. */
  onSelect?: (prompt: OAuthSelectPrompt) => Promise<string | undefined>;
  /** Cancels pending OAuth waits and prompts when aborted. */
  signal?: AbortSignal;
}
/** Provider OAuth contract implemented by provider plugins. */
interface OAuthProviderInterface {
  /** Stable provider id used for credential and config routing. */
  readonly id: OAuthProviderId;
  /** Human-readable provider name shown in login flows. */
  readonly name: string;
  /** Run the login flow and return credentials to persist. */
  login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
  /** Whether login uses a local callback server and supports manual code input. */
  usesCallbackServer?: boolean;
  /** Refresh expired credentials and return updated credentials to persist. */
  refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;
  /** Convert credentials to an API key string for the provider. */
  getApiKey(credentials: OAuthCredentials): string;
  /** Optionally adjust models for this provider, such as updating baseUrl. */
  modifyModels?(models: Model[], credentials: OAuthCredentials): Model[];
}
//#endregion
//#region src/agents/auth-profiles/path-resolve.d.ts
/** Pure producer facts; capturing a supplied runtime snapshot must not open SQLite. */
type AuthProfileOwnerScope = {
  stateDir: string;
  sharedMainDir: string;
};
//#endregion
//#region src/agents/auth-profiles/paths.d.ts
/**
 * @deprecated Display provider/profile identifiers instead. Public database-path displays are retired;
 * there is no public async path replacement. Bundled callers use AuthStorage.resolvePathForDisplayAsync.
 * Supported through 2026-12-31; removal ships in the first January 2027 stable release.
 */
declare function resolveAuthStorePathForDisplay(agentDir?: string): string;
/** Resolve the selected auth store's display path without host-thread SQLite. */
declare function resolveAuthStorePathForDisplayAsync(agentDir?: string, env?: NodeJS.ProcessEnv): Promise<string>;
//#endregion
//#region src/agents/sessions/auth-storage-types.d.ts
type ApiKeyCredential = {
  type: "api_key";
  key: string;
  /** Secret-free native presence carried only by in-memory discovery credentials. */
  nativeAuth?: {
    runtime: string;
    mode: "api-key" | "oauth" | "token";
  };
};
type OAuthCredential = {
  type: "oauth";
} & OAuthCredentials;
type TokenCredential = {
  type: "token";
  token: string;
  expires?: number;
};
type AuthCredential = ApiKeyCredential | OAuthCredential | TokenCredential;
type AuthStorageData = Record<string, AuthCredential>;
type LockResult<T> = {
  result: T;
  next?: string;
};
interface AuthStorageBackend {
  read?(): string | undefined;
  prepareProviderReady?(): Promise<void>;
  assertProviderReady?(provider?: string, baseUrl?: string): void;
  getCredentialSource?(provider: string): AuthProfileCredentialSource | undefined;
  assertCredentialReady?(source: AuthProfileCredentialSource, baseUrl?: string): void;
  withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
  withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;
}
//#endregion
//#region src/agents/sessions/auth-storage.core.d.ts
type AuthStatus = {
  configured: boolean;
  source?: "stored" | "runtime" | "environment" | "fallback" | "models_json_key" | "models_json_command";
  label?: string;
};
/**
 * Provider-keyed credential facade backed by the canonical auth-profile store.
 */
declare class AuthStorage$1 {
  private readonly config?;
  /** Resolve the selected auth store's display path without loading credentials. */
  static resolvePathForDisplayAsync: typeof resolveAuthStorePathForDisplayAsync;
  private data;
  private credentialSources;
  private runtimeOverrides;
  private fallbackResolver?;
  private loadError;
  private errors;
  private storage;
  private constructor();
  /** @deprecated Use forAgentAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static forAgent(this: void, agentDir: string, config?: OpenClawConfig): AuthStorage$1;
  static forAgentAsync(this: void, agentDir: string, config?: OpenClawConfig): Promise<AuthStorage$1>;
  static fromStorage(storage: AuthStorageBackend): AuthStorage$1;
  static inMemory(data?: AuthStorageData): AuthStorage$1;
  /**
   * Set a runtime API key override (not persisted to disk).
   * Used for CLI --api-key flag.
   */
  setRuntimeApiKey(provider: string, apiKey: string): void;
  removeRuntimeApiKey(provider: string): void;
  /**
   * Set a fallback resolver for API keys not found in canonical storage or env vars.
   * Used for custom provider keys from models.json.
   */
  setFallbackResolver(resolver: (provider: string) => string | undefined): void;
  private recordError;
  private getCanonicalLoadError;
  private assertProviderReady;
  private setData;
  /** @deprecated Use reloadAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  reload(): void;
  private loadFromStorage;
  reloadAsync(): Promise<void>;
  private mergeProviderChange;
  private persistProviderChange;
  private persistProviderChangeAsync;
  private failProviderChange;
  get(provider: string): AuthCredential | undefined;
  /** @deprecated Use setAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  set(provider: string, credential: AuthCredential): void;
  setAsync(provider: string, credential: AuthCredential): Promise<void>;
  /** @deprecated Use removeAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  remove(provider: string): void;
  removeAsync(provider: string): Promise<void>;
  list(): string[];
  has(provider: string): boolean;
  /**
   * Check if any form of auth is configured for a provider.
   * Unlike getApiKey(), this doesn't refresh OAuth tokens.
   */
  hasAuth(provider: string): boolean;
  /**
   * Return auth status without exposing credential values or refreshing tokens.
   */
  getAuthStatus(provider: string): AuthStatus;
  /**
   * Get all credentials (for passing to getOAuthApiKey).
   */
  getAll(): AuthStorageData;
  drainErrors(): Error[];
  login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks): Promise<void>;
  /** @deprecated Use logoutAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  logout(provider: string): void;
  logoutAsync(provider: string): Promise<void>;
  /**
   * Refresh OAuth token with backend locking to prevent race conditions.
   * Multiple agent sessions may try to refresh simultaneously when tokens expire.
   */
  private refreshOAuthTokenWithLock;
  /**
   * Get API key for a provider.
   * Priority:
   * 1. Runtime override (CLI --api-key)
   * 2. API key from canonical storage
   * 3. OAuth token from canonical storage (auto-refreshed with locking)
   * 4. Environment variable
   * 5. Fallback resolver (models.json custom providers)
   */
  getApiKey(providerId: string, options?: {
    includeFallback?: boolean;
    baseUrl?: string;
  }): Promise<string | undefined>;
  private resolveStoredOrFallbackApiKey;
  getOAuthProviders(): OAuthProviderInterface[];
}
//#endregion
//#region src/agents/plugin-model-catalog-read.types.d.ts
type PersistedPluginModelCatalog = {
  pluginId: string;
  contents: string;
};
//#endregion
//#region src/agents/plugin-model-catalog.d.ts
type PluginModelCatalogMetadataSnapshot = Pick<PluginMetadataSnapshot, "owners"> & {
  manifestRegistry?: Pick<PluginMetadataSnapshot["manifestRegistry"], "plugins">;
  index?: {
    plugins: ReadonlyArray<{
      enabled: boolean;
      pluginId: string;
    }>;
  };
  normalizePluginId?: (pluginId: string) => string;
};
//#endregion
//#region src/agents/sessions/model-registry-schema-definition.d.ts
declare const ProviderAuthModeSchema: Type$1.TUnion<[Type$1.TLiteral<"api-key">, Type$1.TLiteral<"aws-sdk">, Type$1.TLiteral<"oauth">, Type$1.TLiteral<"token">, Type$1.TLiteral<"none">]>;
type ProviderAuthMode = Static<typeof ProviderAuthModeSchema>;
//#endregion
//#region src/agents/sessions/model-registry-sources.d.ts
type ResolvedRequestAuth = {
  ok: true;
  apiKey?: string;
  headers?: ModelRequestHeaders;
} | {
  ok: false;
  error: string;
};
//#endregion
//#region src/agents/sessions/provider-config.d.ts
/** Shared fields accepted by extension and registry provider registration. */
interface ProviderConfigBase {
  /** Display name for the provider in UI. */
  name?: string;
  /** Base URL for the API endpoint. Required when defining models. */
  baseUrl?: string;
  /** API key or environment variable name. Required when defining models (unless oauth provided). */
  apiKey?: string;
  /** API type. Required at provider or model level when defining models. */
  api?: Api;
  streamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStreamContract;
  headers?: Record<string, string>;
  /** If true, adds Authorization: Bearer header with the resolved API key. */
  authHeader?: boolean;
}
interface ProviderModelConfig extends Pick<Model, "id" | "name" | "reasoning" | "thinkingLevelMap" | "input" | "maxTokens" | "parameterCount" | "family" | "compat">, Partial<Pick<Model, "api" | "baseUrl">> {
  /** Cost per token (for tracking, can be 0). */
  cost: {
    input: number;
    output: number;
    cacheRead: number;
    cacheWrite: number;
  };
  /** Authored catalog headers remain strings; deletion sentinels are request-time only. */
  headers?: Record<string, string>;
  /** Maximum context window size in tokens. */
  contextWindow: number;
}
interface ProviderConfig extends ProviderConfigBase {
  /** Models to register. If provided, replaces all existing models for this provider. */
  models?: ProviderModelConfig[];
  /** OAuth provider for /login support. The `id` is set automatically from the provider name. */
  oauth?: Pick<OAuthProviderInterface, "login" | "refreshToken" | "getApiKey" | "modifyModels"> & {
    /** Display name for the provider in login UI. */
    name: string;
  };
}
interface ProviderConfigInput extends ProviderConfigBase {
  auth?: ProviderAuthMode;
  /** OAuth provider for /login support */
  oauth?: Omit<OAuthProviderInterface, "id">;
  models?: Array<ProviderModelConfig & {
    contextTokens?: number;
    contextWindows?: ModelCatalogContextWindowOption[];
    contextWindowDefault?: string;
    params?: Record<string, unknown>;
  }>;
}
//#endregion
//#region src/agents/sessions/model-registry.core.d.ts
type ModelRegistryOptions$1 = {
  config?: OpenClawConfig;
  includePluginCatalogs?: boolean;
  modelsJsonContents?: string | null;
  pluginCatalogs?: readonly PersistedPluginModelCatalog[];
  excludeGeneratedProviderIds?: readonly string[];
  staticProviderConfigs?: Readonly<Record<string, ModelProviderConfig>>;
  pluginMetadataSnapshot?: PluginModelCatalogMetadataSnapshot;
  sourceSnapshot?: ModelRegistry$2;
  workspaceDir?: string;
};
declare class ModelRegistry$2 {
  private models;
  private config;
  private providerRequestConfigs;
  private modelRequestHeaders;
  private registeredProviders;
  private loadError;
  readonly authStorage: AuthStorage$1;
  private modelsJsonPath;
  private modelsJsonContents;
  private pluginCatalogs;
  private readonly excludeGeneratedProviderIds;
  private pluginCatalogReadError;
  private readonly reloadPluginCatalogs;
  private staticProviderConfigs;
  private pluginMetadataSnapshot;
  private includePluginCatalogs;
  private baseCatalogSnapshot;
  private sourceSnapshot;
  private constructor();
  private captureCatalogSnapshot;
  private restoreSourceCatalog;
  /** @deprecated Use createAsync or fromCapturedSources. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
  static create(this: void, authStorage: AuthStorage$1, modelsJsonPath: string, options?: ModelRegistryOptions$1): ModelRegistry$2;
  /** Read persisted plugin catalogs through their worker before publishing the registry. */
  static createAsync(this: void, authStorage: AuthStorage$1, modelsJsonPath: string, options?: ModelRegistryOptions$1): Promise<ModelRegistry$2>;
  /** Parse owner-prepared catalogs without opening their persistence store. */
  static fromCapturedSources(authStorage: AuthStorage$1, modelsJsonPath: string, options: ModelRegistryOptions$1 & {
    pluginCatalogs: readonly PersistedPluginModelCatalog[];
  }): ModelRegistry$2;
  private static warnNativeCatalogRead;
  static inMemory(authStorage: AuthStorage$1): ModelRegistry$2;
  /** Creates a request-isolated registry from this lifecycle-owned catalog snapshot. */
  fork(authStorage: AuthStorage$1, publishedModels?: ReadonlyMap<string, readonly Model[]>): ModelRegistry$2;
  /** @deprecated Await refreshAsync for disk-backed catalogs. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
  refresh(): void;
  private refreshFromStorage;
  refreshAsync(): Promise<void>;
  private reload;
  /** Get any root or generated plugin catalog load error. */
  getError(): string | undefined;
  /** Returns the exact plugin metadata generation captured with this registry. */
  getProviderMetadataOwners(): PluginMetadataSnapshotOwnerMaps | undefined;
  private loadModels;
  private loadCapturedPluginCatalogs;
  private loadCustomModels;
  private parseModels;
  getAll(): Model[];
  /**
   * Get only models that have auth configured.
   * This is a fast check that doesn't refresh OAuth tokens.
   */
  getAvailable(): Model[];
  find(provider: string, modelId: string): Model | undefined;
  hasConfiguredAuth(model: Model): boolean;
  private getModelProviderRequestConfig;
  private storeProviderRequestConfig;
  getApiKeyAndHeaders(model: Model): Promise<ResolvedRequestAuth>;
  /**
   * Return auth status for a provider, including request auth configured in models.json.
   * This intentionally does not execute command-backed config values.
   */
  getProviderAuthStatus(provider: string): AuthStatus;
  getProviderDisplayName(provider: string): string;
  getApiKeyForProvider(provider: string): Promise<string | undefined>;
  isUsingOAuth(model: Model): boolean;
  /**
   * Register a provider dynamically (from extensions).
   *
   * If provider has models: replaces all existing models for this provider.
   * Provider-level request settings are stored for already-known models but
   * never create implicit model rows.
   * If provider has oauth: registers OAuth provider for /login support.
   */
  registerProvider(providerName: string, config: ProviderConfigInput): void;
  /**
   * Unregister a previously registered provider.
   *
   * Removes the provider from the registry and reloads models from disk.
   * Also resets dynamic OAuth and API stream registrations before reapplying
   * remaining dynamic providers.
   * Has no effect if the provider was never registered.
   * @deprecated Use unregisterProviderAsync for disk-backed registries. Supported through 2026-12-31; removal ships in the first January 2027 stable release.
   */
  unregisterProvider(providerName: string): void;
  unregisterProviderAsync(providerName: string): Promise<void>;
  private applyProviderConfig;
}
//#endregion
//#region src/agents/sessions/model-registry.d.ts
type ModelRegistry$1 = ModelRegistry$2;
type ModelRegistryOptions = NonNullable<Parameters<typeof ModelRegistry$2.create>[2]>;
declare const ModelRegistry$1: typeof ModelRegistry$2 & {
  /** @deprecated Use createAsync or fromCapturedSources. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
  create(authStorage: AuthStorage$1, modelsJsonPath?: string, options?: ModelRegistryOptions): ModelRegistry$1;
  createAsync(authStorage: AuthStorage$1, modelsJsonPath?: string, options?: ModelRegistryOptions): Promise<ModelRegistry$1>;
};
//#endregion
//#region packages/memory-host-sdk/src/host/session-transcript-corpus.types.d.ts
type SessionTranscriptCorpusArtifactKind = "active-session" | "retained-session" | "archive-artifact";
type SessionTranscriptCorpusOptions = {
  /** Use the caller's prepared config when discovering its session store. */
  config?: OpenClawConfig;
  /** Include rotated SQLite transcript identities retained behind current logical sessions. */
  includeRetainedSqlite?: boolean;
  /** Skip per-transcript revision reads when a caller only needs discovery metadata. */
  includeContentRevision?: boolean;
  /** Read session entries without joining the agent database writable lifecycle. */
  readOnly?: boolean;
};
type SessionTranscriptCorpusEntry = {
  agentId: string;
  sessionFile: string;
  sessionId: string;
  /** Canonical source revision used by derived transcript consumers. */
  contentRevision?: string;
  artifactKind: SessionTranscriptCorpusArtifactKind;
  sessionKey?: string;
  /** Recorded owner of a plugin-managed transcript. */
  pluginOwnerId?: string;
  storePath?: string;
  /** Present when an active transcript is addressed by SQLite identity, not a JSONL path. */
  transcriptSource?: "sqlite";
  /** Session entry activity timestamp used when the source has no filesystem stat. */
  updatedAtMs?: number;
  /** True when this transcript belongs to an internal dreaming narrative run. */
  generatedByDreamingNarrative?: boolean;
  /** True when this transcript belongs to an isolated cron run session. */
  generatedByCronRun?: boolean;
  sessionKind?: MemorySessionKind;
};
//#endregion
//#region src/config/sessions/session-memory-targets.types.d.ts
type MemorySessionTarget = {
  agentId: string;
  sessionId: string;
  sessionKey?: string;
  /** Recorded owner of a plugin-managed transcript. */
  pluginOwnerId?: string;
  resolution: "live" | "archived" | "unresolved";
  hookExternalContentSource: string | null;
  channel: string | null;
  accountId: string | null;
  chatType: string | null;
  createdAt?: number;
  participants: SessionParticipantIdentity[];
};
type MemorySessionSelectors = {
  agentId: string;
  storePath?: string;
  sessionIds?: readonly string[];
  hookSources?: readonly string[];
  participants?: readonly string[];
  since?: string | number;
};
//#endregion
//#region src/sessions/session-lifecycle-events.d.ts
type SessionLifecycleEvent = {
  sessionKey: string;
  agentId?: string;
  parentSessionKey?: string;
  label?: string;
  displayName?: string;
  /** Runtime events preserve stored rows; entry events preserve worker placement facts. */
  scope?: "runtime" | "session-entry";
  /** The committed change affects model, account, or runtime catalog projection. */
  catalogChanged?: true;
} & ({
  reason: string;
  swarmGroupId?: never;
  kind?: never;
  text?: never;
} | {
  reason: "swarm-note";
  swarmGroupId: string;
  kind: "phase" | "log";
  text: string;
});
type SessionIdentityMutationTarget = {
  sessionId?: string;
  sessionKeys: readonly string[];
};
type SessionIdentityMutation = {
  /** Physical source captured by the committing database owner. */
  databaseIdentity: string | symbol;
  /** Resolved operation scope for bare keys; qualified keys retain their own agent. */
  agentId: string;
} & ({
  kind: "create" | "move" | "replace" | "reset";
  previous: SessionIdentityMutationTarget;
  current: SessionIdentityMutationTarget;
} | {
  kind: "delete";
  previous: SessionIdentityMutationTarget;
});
//#endregion
//#region src/config/sessions/runtime-types.d.ts
type RecordInboundSessionMetaParams = {
  /** Set false to only patch existing entries; missing sessions stay absent. */
  createIfMissing?: boolean;
  ctx: MsgContext;
  groupResolution?: GroupKeyResolution | null;
  /** Canonical or alias session key for the inbound conversation. */
  sessionKey: string;
  /** Explicit store target for file-backed stores and SQLite migration adapters. */
  storePath: string;
  /** Live caller authority checked by the existing write admission owner. */
  assertCommitAllowed?: () => void;
};
type UpdateSessionLastRouteParams = Omit<RecordInboundSessionMetaParams, "ctx"> & {
  accountId?: string;
  channel?: string;
  /** Optional inbound context whose session metadata is derived alongside the route. */
  ctx?: MsgContext;
  /** Explicit delivery context merged over the persisted session fallback. */
  deliveryContext?: DeliveryContext;
  route?: ChannelRouteRef;
  threadId?: string | number;
  to?: string;
};
type ReadSessionUpdatedAt = (params: {
  storePath: string;
  sessionKey: string;
}) => number | undefined;
type RecordSessionMetaFromInbound = (params: RecordInboundSessionMetaParams) => Promise<SessionEntry | null>;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-exact-read.d.ts
/** Resolves the persisted session key for a SQLite transcript session id. */
declare function resolveSessionKeyBySessionId(scope: Pick<SessionTranscriptReadScope, "agentId" | "env" | "sessionId" | "storePath">): string | undefined;
//#endregion
//#region src/state/openclaw-agent-execution-domain.d.ts
type AgentDatabaseDomainOperations = {
  "database.domain.bind": {
    input: {
      id: string;
      moduleUrl: string;
      input: unknown;
    };
    output: void;
  };
  "database.domain.execute": {
    input: {
      id: string;
      command: SqliteWorkerCommand<SqliteWorkerOperations>;
    };
    output: unknown;
  };
  "database.domain.publish": {
    input: {
      id: string;
      moduleUrl: string;
      input: unknown;
      command: SqliteWorkerCommand<SqliteWorkerOperations>;
    };
    output: unknown;
  };
  "database.domain.close": {
    input: {
      id: string;
    };
    output: void;
  };
};
//#endregion
//#region src/config/sessions/session-entry-patch.worker.d.ts
declare function readSessionEntryPatchSnapshot(database: OpenClawAgentDatabase, selection: SessionEntryPatchSelection, includeWindowFacts?: true): {
  entry: InternalSessionEntry;
  sessionKey: string;
  window?: SessionEntryWindowFacts;
  sideTables?: {
    memberIdsJson: string;
    hasBoard: boolean;
  };
  row?: ResolvedSessionEntryRow["row"];
}[];
declare function commitSessionEntryPatch(input: SessionEntryPatchCommit | SessionEntryPatchReduction, { writeTransaction, admit }: AgentWorkerOperationContext): SessionEntryPatchReceipt;
//#endregion
//#region src/talk/client-voice-session-store.d.ts
type ClientVoiceToolEffect = SchemaContract<Pick<z.output<typeof clientVoiceToolEffectSchema>, keyof typeof clientVoiceToolEffectSchema.shape>> & {
  toolCallId?: string;
  finishedAt?: number;
};
type ClientVoiceSessionRecord = SchemaContract<Omit<Pick<z.output<typeof clientVoiceSessionRecordSchema>, keyof typeof clientVoiceSessionRecordSchema.shape>, "effects">> & {
  closedAt?: number;
  effects: ClientVoiceToolEffect[];
  digestDeliveredAt?: number;
  /** Declared at create when the client speaks the transcript protocol (sent sessionKey). */
  transcriptCapable?: boolean;
  /** Set once a finalized user utterance persisted; records observed transcript capability. */
  hasUserTranscript?: boolean;
};
type ClientVoiceRunBinding = Readonly<{
  agentId: string;
  voiceSessionId: string;
  sessionKey: string;
}>;
declare const clientVoiceToolEffectSchema: z.ZodObject<{
  runId: z.ZodString;
  toolName: z.ZodString;
  startedAt: z.ZodNumber;
  status: z.ZodEnum<{
    blocked: "blocked";
    cancelled: "cancelled";
    failed: "failed";
    started: "started";
    succeeded: "succeeded";
  }>;
}, z.core.$loose>;
declare const clientVoiceSessionRecordSchema: z.ZodObject<{
  version: z.ZodLiteral<1>;
  voiceSessionId: z.ZodString;
  agentId: z.ZodString;
  sessionKey: z.ZodString;
  provider: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
  origin: z.ZodEnum<{
    client: "client";
    relay: "relay";
  }>;
  status: z.ZodEnum<{
    closed: "closed";
    open: "open";
  }>;
  createdAt: z.ZodNumber;
  updatedAt: z.ZodNumber;
  consultRunIds: z.ZodPipe<z.ZodOptional<z.ZodUnknown>, z.ZodTransform<string[], unknown>>;
  effects: z.ZodPipe<z.ZodOptional<z.ZodUnknown>, z.ZodTransform<{
    [x: string]: unknown;
    runId: string;
    toolName: string;
    startedAt: number;
    status: "blocked" | "cancelled" | "failed" | "started" | "succeeded";
  }[], unknown>>;
  transcriptFailureKeys: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnknown>, z.ZodTransform<{}, unknown>>, z.ZodArray<z.ZodString>>;
}, z.core.$loose>;
//#endregion
//#region src/config/sessions/session-turn.types.d.ts
type SqliteExpectedSessionTranscriptTurnResult = {
  runtimeTarget?: ResolvedSessionTranscriptRuntimeTarget;
  voiceSession?: ClientVoiceSessionRecord;
  transcriptVersion?: SessionTranscriptContextVersion;
  sessionTurnMutationResult?: SessionTranscriptTurnMutationResult;
  appendedMessages: TranscriptMessageAppendResult<unknown>[];
  rejectedReason?: "session-rebound";
  predicateSkipped?: boolean;
  sessionEntry: SessionEntry | undefined;
  sessionFile: string;
};
type SqliteSessionTurnOptions = {
  resolveRuntimeTarget?: true;
  /** Same-store voice bookkeeping commits atomically with its reserved transcript event. */
  voiceTranscript?: ClientVoiceRunBinding & {
    failureKey: string;
    role: "user" | "assistant";
  };
  ownerSource?: PreparedSessionSourceAuthority;
  workerPrepared?: true;
  preparedGoalId?: string;
  assertCurrent?: () => void;
  acceptedResultGuard?: SessionTranscriptTurnPersistOptions["acceptedResultGuard"];
  atomicGroup?: boolean;
  keyFormat?: "agent-qualified";
  config?: OpenClawConfig;
  cwd?: string;
  expectedLifecycleRevision?: SessionLifecycleRevisionExpectation;
  expectedWriterRunId?: SessionTranscriptTurnExpectedState["expectedWriterRunId"];
  expectedOwner?: SessionTranscriptWriteScope["expectedOwner"];
  expectedSessionState?: SessionTranscriptTurnExpectedState;
  expectedSessionId: string;
  selectedSessionId?: string | null;
  selectedLifecycleRevision?: SessionLifecycleRevisionExpectation;
  initialSessionEntry?: SessionEntry;
  messages: readonly SessionTranscriptTurnMessageAppend[];
  onMessageCommitted?: SessionTranscriptTurnPersistOptions["onMessageCommitted"];
  onCommittedSource?: (source: CapturedSessionEntryReadSource, entry: SessionEntry) => void;
  sessionLifecyclePatch?: SessionTranscriptTurnLifecyclePatch;
  sessionTurnMutation?: SessionTranscriptTurnMutation;
  sessionFile: string;
  touchSessionEntry?: boolean;
};
type SessionTurnPlan = {
  agentId: string;
  sessionKey: string;
  prepareColdTranscript?: true;
  options: Omit<SqliteSessionTurnOptions, "messages" | "onMessageCommitted" | "onCommittedSource" | "assertCurrent" | "sessionTurnMutation" | "config" | "ownerSource"> & {
    sessionTurnMutation?: Omit<SessionTranscriptTurnMutation, "assertCurrent">;
    messages: Array<Omit<SessionTranscriptTurnMessageAppend, "config" | "shouldAppend" | "shouldAppendInTransaction" | "prepareMessageAfterIdempotencyCheck" | "beforeFreshMessageCommit" | "workerPreparation" | "preparation"> & {
      preparationVersion?: SessionTranscriptContextVersion;
      sources?: SessionSourcePredicate[];
      freshGuard?: true;
      preparedMessage?: {
        prepared: boolean;
        message: unknown;
      };
    }>;
  };
  ownerSources?: SessionSourcePredicate[];
  custody?: SessionPendingInputWorkerFacts;
  relocation?: string;
  cliWriter?: CliHistoryWriterFacts;
};
type SessionTurnCommitted = {
  kind: "session-turn";
  result: SqliteExpectedSessionTranscriptTurnResult;
  sequences: Array<number | undefined>;
  projectionNeedsReconcile: boolean;
  custody?: SessionPendingInputWorkerReceipt;
  authority?: SessionPendingInputAuthorityFacts;
  publication?: SessionEntryReplacementPublication;
};
//#endregion
//#region src/config/sessions/session-actor-hydration.types.d.ts
type SessionActorStoredState = {
  agentId: string;
  path: string;
  hot: SessionActorHotState;
  /** Lookup siblings were admitted in the same hydration statement. */
  entryRows: Map<string, {
    entry: ResolvedSessionEntryRow["entry"];
    row: Omit<ResolvedSessionEntryRow["row"], keyof SessionEntrySnapshotRow> & { [K in keyof SessionEntrySnapshotRow]?: never; };
  } | undefined>;
  window: SessionEntryWindowRow | undefined;
  hasBoard: boolean;
  /** Unconsumed custody only; consumed source receipts use indexed SQLite reads. */
  pendingInputs: Map<string, SessionPendingInputRow>;
  completions: Map<string, Selectable<DB["session_input_completions"]>>;
  /** Only a complete cache can prove that a durable completion is absent. */
  completionsComplete: boolean;
  transcript: {
    /** Complete means every identity row for the session, not just the bounded window. */
    complete: boolean;
    coldArchive: Omit<Selectable<DB["session_transcript_cold_archives"]>, "archive_blob"> | undefined;
    projection: (SessionTranscriptProjectionState & {
      hasUnclassifiedEvents: boolean;
    }) | undefined;
    identities: Map<string, Selectable<DB["transcript_event_identities"]>>;
    active: Map<number, Selectable<DB["session_transcript_active_events"]>>;
    navigation: Array<Record<string, unknown> & {
      seq: number;
    }>;
    /** Current transaction's append bodies; committed receipts own them after settlement. */
    payloads: Map<number, {
      event: unknown;
      serializedBytes: number;
    }>;
    contextMetadata?: SessionTranscriptContextMetadata;
    contextStats?: SessionTranscriptContextStats;
  };
};
//#endregion
//#region src/config/sessions/session-turn.worker.d.ts
declare function prepareSessionTurn(requested: SessionTurnPlan, context: AgentWorkerOperationContext, incarnation?: string, resident?: SessionActorStoredState): {
  refusedOwnerSource: {
    index: number;
    facts: SessionSourcePredicateFacts;
  };
  ownerSourceValidation?: undefined;
  messages?: undefined;
  coldArchive?: undefined;
  version?: undefined;
  expectedSessionState?: undefined;
  goalId?: undefined;
  runtimeTarget?: ResolvedSessionTranscriptRuntimeTarget | undefined;
  result?: undefined;
} | {
  refusedOwnerSource?: undefined;
  ownerSourceValidation: SessionSourceValidation | undefined;
  result: undefined;
  messages: never[];
  coldArchive: Omit<{
    archive_blob: Uint8Array<ArrayBufferLike> | null;
    archive_bytes: number;
    archive_name: string;
    archive_sha256: string;
    archived_at: number;
    event_count: number;
    generation: string;
    last_seq: number;
    raw_bytes: number;
    session_id: string;
    storage: string;
  }, "archive_blob">;
  version: undefined;
  goalId: undefined;
  expectedSessionState?: undefined;
  runtimeTarget?: ResolvedSessionTranscriptRuntimeTarget | undefined;
} | {
  refusedOwnerSource?: undefined;
  ownerSourceValidation: SessionSourceValidation | undefined;
  result: SqliteExpectedSessionTranscriptTurnResult | undefined;
  messages: {
    pending: boolean;
    existing: {
      messageId: string;
      message: unknown;
    } | undefined;
  }[];
  coldArchive: undefined;
  version: {
    generation: string | null;
    rawSeq: number | null;
    updatedAt: number | null;
  } | undefined;
  expectedSessionState: SessionTranscriptTurnExpectedState | undefined;
  goalId: string | undefined;
  runtimeTarget?: ResolvedSessionTranscriptRuntimeTarget | undefined;
};
declare function commitSessionTurn(input: SessionTurnPlan, context: AgentWorkerOperationContext): SessionEntryPatchReceipt;
//#endregion
//#region src/config/sessions/session-reset.types.d.ts
/** The reset builder runs once on the host; the full selected target is compared in the worker. */
type SessionResetCommit = {
  agentId: string;
  target: SessionLifecycleStoreTarget;
  prepared: SqliteLifecycleTargetSnapshot;
  nextEntry: InternalSessionEntry;
  resetBoundary?: SessionResetBoundaryWrite;
};
//#endregion
//#region src/config/sessions/session-reset.worker.d.ts
declare function commitSessionReset(input: SessionResetCommit, { writeTransaction, admit }: AgentWorkerOperationContext): SessionEntryPatchReceipt;
//#endregion
//#region src/config/sessions/session-lifecycle-projection.types.d.ts
type SessionLifecycleProjectionCommit = ProjectedLifecycleCommitInput & {
  agentId: string;
  removalPlans: MaterializedSessionStateDeletePlan[];
};
//#endregion
//#region src/config/sessions/session-lifecycle-projection.worker.d.ts
declare function commitSessionLifecycleProjection(input: SessionLifecycleProjectionCommit, { writeTransaction, admit, options }: AgentWorkerOperationContext): SessionEntryPatchReceipt;
//#endregion
//#region src/config/sessions/session-entry-deletion.types.d.ts
type SessionEntryDeletionPlan = Extract<SqliteSessionReclamationPlan, {
  kind: "entry";
}>;
type SessionEntryDeletionInput = {
  plan: SessionEntryDeletionPlan;
  nativeBindings?: SessionNativeBindingParticipants;
};
//#endregion
//#region src/config/sessions/session-entry-deletion.worker.d.ts
declare function planSessionDeletionInAgentWorker(planning: SessionDeletionPlanningOperation, { open }: AgentWorkerOperationContext): SessionDeletionPlanningResult;
declare function deleteSessionEntryInAgentWorker(input: SessionEntryDeletionInput, context: AgentWorkerOperationContext): SessionEntryPatchReceipt | SessionNativeBindingReceipt;
//#endregion
//#region src/config/sessions/session-agent-purge.types.d.ts
type SessionAgentPurgeSelection = {
  cfg: OpenClawConfig;
  agentId: string;
  storeAgentId: string;
  archiveDirectory: string;
};
type SessionAgentPurgePlan = {
  deletePlans: SessionStateDeletePlan[];
  entryRemovals: SessionEntryRemovalPlan[];
};
type SessionAgentPurgeCommit = SessionAgentPurgeSelection & {
  entryRemovals: SessionEntryRemovalPlan[];
  materializedPlans: MaterializedSessionStateDeletePlan[];
  maintenance: SessionEntryMaintenanceInput;
  nativeBindings?: SessionNativeBindingParticipants;
};
//#endregion
//#region src/config/sessions/session-agent-purge.worker.d.ts
declare function prepareSessionAgentPurge(input: SessionAgentPurgeSelection, { open }: AgentWorkerOperationContext): SessionAgentPurgePlan;
declare function commitSessionAgentPurge(input: SessionAgentPurgeCommit, context: AgentWorkerOperationContext): SessionEntryPatchReceipt | SessionNativeBindingReceipt;
//#endregion
//#region src/config/sessions/session-maintenance-finalization.types.d.ts
type SessionMaintenanceFinalizationPlan = Extract<SqliteSessionReclamationPlan, {
  kind: "maintenance-finalize";
}>;
type SessionMaintenanceFinalizationInput = {
  plan: SessionMaintenanceFinalizationPlan;
  nativeBindings?: SessionNativeBindingParticipants;
};
//#endregion
//#region src/config/sessions/session-maintenance-finalization.worker.d.ts
declare function finalizeSessionMaintenance(input: SessionMaintenanceFinalizationInput, context: AgentWorkerOperationContext): SessionEntryPatchReceipt | SessionNativeBindingReceipt;
//#endregion
//#region src/config/sessions/session-native-binding.worker.d.ts
declare function deleteSessionWithNativeBindings(input: SessionNativeBindingDeletion, context: AgentWorkerOperationContext): SessionNativeBindingReceipt;
//#endregion
//#region src/trajectory/types.d.ts
type TrajectoryEventSource = "runtime" | "transcript" | "export";
type TrajectoryEvent = {
  traceSchema: "openclaw-trajectory";
  schemaVersion: 1;
  traceId: string;
  source: TrajectoryEventSource;
  type: string;
  ts: string;
  seq: number;
  sourceSeq?: number;
  sessionId: string;
  sessionKey?: string;
  runId?: string;
  workspaceDir?: string;
  provider?: string;
  modelId?: string;
  modelApi?: string | null;
  entryId?: string;
  parentEntryId?: string | null;
  data?: Record<string, unknown>;
};
//#endregion
//#region src/trajectory/runtime-store.contract.d.ts
type SqliteTrajectoryRuntimeScope = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  maxGlobalRuntimeBytes?: number;
  maxRuntimeBytes?: number;
  sessionId: string;
  storePath: string;
  assertCommitAllowed?: () => void;
};
type SerializedTrajectoryEvent = Pick<TrajectoryEvent, "runId" | "ts"> & {
  line: string;
};
type TrajectoryRuntimeWindowFacts = {
  nextSeq: number;
  retainedBytes: number;
};
type SqliteTrajectoryRuntimeAppend = Pick<SqliteTrajectoryRuntimeScope, "sessionId" | "maxRuntimeBytes" | "maxGlobalRuntimeBytes"> & {
  events: readonly SerializedTrajectoryEvent[];
  /** Facts supplied by the host inside the existing physical-store writer FIFO. */
  windowFacts?: TrajectoryRuntimeWindowFacts;
  /** The queued prefix exceeded this session's rolling window before admission. */
  discardPrevious?: boolean;
};
type SqliteTrajectoryRuntimeReadScope = Omit<SqliteTrajectoryRuntimeScope, "assertCommitAllowed" | "maxGlobalRuntimeBytes" | "maxRuntimeBytes"> & {
  /** Byte budget enforced via SQL before parsing rows; ignored for tail-bounded reads. */
  maxEventBytes?: number;
  /** Row-count budget enforced via SQL before parsing rows; ignored for tail-bounded reads. */
  maxEventCount?: number;
};
//#endregion
//#region src/trajectory/runtime-store.sqlite.d.ts
type TrajectoryRuntimeAppendResult = {
  database: OpenClawAgentDatabase;
  receipt: {
    kind: "trajectory-runtime-append";
    sessionId: string;
    windowFacts: TrajectoryRuntimeWindowFacts;
  };
};
type TrajectoryRuntimeWriter = (label: string, write: (database: OpenClawAgentDatabase) => TrajectoryRuntimeAppendResult,
/** Present only when write executes one terminal INSERT with no post-statement work. */
receipt?: TrajectoryRuntimeAppendResult["receipt"]) => TrajectoryRuntimeAppendResult;
declare function appendSqliteTrajectoryRuntimeEventsWithWriter(input: SqliteTrajectoryRuntimeAppend, sourceDatabase: OpenClawAgentDatabase, write: TrajectoryRuntimeWriter): TrajectoryRuntimeAppendResult;
//#endregion
//#region src/trajectory/runtime-retention.contract.d.ts
type TrajectoryRuntimeRetentionPlan = {
  cutoff: number;
  maxBytes: number;
  sessionId: string;
  runs: {
    sessionId: string;
    runId: string | null;
    newest: number;
    bytes: number;
    events: number;
    order: string;
  }[];
};
//#endregion
//#region src/trajectory/runtime-retention.sqlite.d.ts
/** Reconcile receipts and advance the sorted cursor before acquiring the writer lock. */
declare function selectTrajectoryRuntimeRetentionBatch(database: EngineConnection, input: {
  sweepId: string;
  snapshot?: TrajectoryRuntimeRetentionPlan;
}): {
  sweepId: string;
  runs: {
    sessionId: string;
    runId: string | null;
    newest: number;
    bytes: number;
    events: number;
    order: string;
  }[];
  refresh: true;
} | {
  refresh?: undefined;
  sweepId: string;
  runs: {
    sessionId: string;
    runId: string | null;
    newest: number;
    bytes: number;
    events: number;
    order: string;
  }[];
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-archive-store-kernel.d.ts
declare function prepareSessionTranscriptArchivePublishPlans(database: OpenClawAgentDatabase, params: {
  archiveDirectory: string;
  requested: readonly Pick<TranscriptArchivePublishPlan, "sessionId" | "generation">[];
}): TranscriptArchivePublishPlan[];
declare function recordSessionTranscriptArchivePublishResults(database: OpenClawAgentDatabase, results: readonly TranscriptArchivePublishResult[], nowMs: number): void;
//#endregion
//#region src/acp/runtime/session-meta-entry.kernel.d.ts
type AcpSessionEntryExpectation = Pick<SessionEntry, "sessionId" | "lifecycleRevision" | "sessionStartedAt"> | null;
//#endregion
//#region src/acp/runtime/session-meta-entry.types.d.ts
type AcpSessionEntryMutationInput = {
  agentId: string;
  sessionKey: string;
  mutation: AcpSessionEntryMutation;
  expectedEntry: AcpSessionEntryExpectation;
  expectedControlBinding?: AcpSessionControlBinding;
};
type AcpSessionEntryMutation = {
  kind: "touch";
  updatedAt: number;
  fallbackEntry: SessionEntry;
} | {
  kind: "clear";
};
type AcpSessionEntryMutationResult = {
  entry: SessionEntry | null;
  publication?: SessionEntryReplacementPublication;
};
//#endregion
//#region src/acp/runtime/session-meta-entry.worker.d.ts
/** Finite ACP field changes use the canonical entry kernel and its commit publication. */
declare function mutateAcpSessionEntryInWorker(opened: OpenClawAgentDatabase, options: OpenClawAgentDatabaseOptions, input: AcpSessionEntryMutationInput, admit: (stage: "transaction" | "commit", publication?: unknown) => void): AcpSessionEntryMutationResult;
//#endregion
//#region src/config/sessions/provider-review-store.worker.d.ts
declare function compareSessionProviderReviewInWorker(database: OpenClawAgentDatabase, options: OpenClawAgentDatabaseOptions, input: SessionProviderReviewComparison, admit: (stage: "transaction" | "commit", publication?: SessionEntryReplacementPublication) => void): {
  entry: SessionEntry;
  publication: SessionEntryReplacementPublication;
};
//#endregion
//#region src/config/sessions/ambient-transcript-watermark.d.ts
type AmbientTranscriptWatermarkScope = {
  channel: string;
  accountId?: string;
  conversationId: string;
  threadId?: string | number;
};
declare function resolveAmbientTranscriptWatermarkKey(scope: AmbientTranscriptWatermarkScope): string;
declare function updateAmbientTranscriptWatermark(params: {
  storePath: string;
  sessionKey: string;
  key: string;
  messageId: string;
  timestampMs?: number;
  expectedSessionId?: string;
}): Promise<SessionEntry | null>;
//#endregion
//#region src/config/sessions/session-entry-patch-authority.d.ts
/** Host checks never query SQLite; prepared sources retain their own predicate owner. */
type SessionEntryPatchAuthority = {
  kind: "host";
  assertCurrent(): void;
} | {
  kind: "source";
  source: PreparedSessionSourceAssertion;
};
//#endregion
//#region src/plugin-sdk/session-store-runtime-internal.d.ts
type SessionStoreReadParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  hydrateSkillPromptRefs?: boolean;
  readConsistency?: "latest";
  sessionKey: string;
  storePath?: string;
};
type SessionStoreEntrySummary = {
  sessionKey: string;
  entry: SessionEntry;
};
/** Loads the complete public entry through the selected asynchronous read owner. */
declare function getSessionEntryAsync(params: SessionStoreReadParams): Promise<SessionEntry | undefined>;
/** Looks up a visible current session ID in one selected store. */
declare function getSessionEntryByIdAsync(params: Omit<SessionStoreReadParams, "sessionKey"> & {
  sessionId: string;
  /** Newest normalized-ID match; omitted preserves exact-ID-first listing order. */
  orderBy?: "updatedAt";
}): Promise<SessionStoreEntrySummary | undefined>;
//#endregion
//#region src/shared/transcript-only-openclaw-assistant.d.ts
declare const SUBAGENT_COMPLETION_RESULT_KIND: "subagent-completion";
/**
 * Returns true when the message is an OpenClaw-authored transcript artifact
 * that must not be replayed to providers.
 *
 * Primary check: provider="openclaw" + model in known transcript-only set.
 * Fallback: a valid openclawDeliveryMirror marker catches observed historical
 * rows whose provider/model provenance was stripped (#99470).
 */
declare function isTranscriptOnlyOpenClawAssistantMessage(message: unknown): boolean;
//#endregion
//#region src/config/sessions/transcript-mirror.d.ts
type SessionTranscriptDeliveryMirror = {
  kind: "channel-final";
  sourceMessageId?: string;
} | {
  kind: "channel-final-suppressed";
  reason: "stale-foreground";
  sourceMessageId?: string;
};
//#endregion
//#region src/config/sessions/transcript.d.ts
type ReadRecentSessionConversationTextParams = ReadRecentSessionConversationTextOptions & {
  agentId: string;
  sessionKey: string;
  storePath?: string;
};
declare function readRecentUserAssistantTextForSession(params: ReadRecentSessionConversationTextParams): Promise<SessionRecentConversationText[]>;
//#endregion
//#region src/plugin-sdk/session-transcript-memory-hit.d.ts
type SessionTranscriptReadParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  hydrateSkillPromptRefs?: boolean;
  sessionId: string;
  sessionKey: string;
  storePath?: string;
  threadId?: string | number;
};
//#endregion
//#region src/plugin-sdk/session-transcript-runtime.d.ts
type SessionTranscriptEvent = unknown;
type SessionTranscriptTargetParams = SessionTranscriptReadParams;
/** Scoped target, bounds, and fresh-cursor start for one active-path visible-message page. */
type SessionTranscriptVisibleMessageDeltaParams = Pick<SessionTranscriptTargetParams, "agentId" | "sessionId" | "sessionKey" | "storePath"> & SessionTranscriptVisibleMessageDeltaLimits;
/** Generation-aware outcome for one bounded visible-message read. */
type SessionTranscriptVisibleMessageDeltaResult$1 = {
  kind: "page";
  /** Opaque cursor positioned after the last returned visible message. */
  cursor: string;
  /** Ordered active-path message entries selected for this page, oldest first. */
  entries: SessionTranscriptMessageEntry[];
  /** True when another visible message remains after this page. */
  hasMore: boolean;
  /** First unread event size when it cannot fit under maxBytes. */
  requiredBytes?: number;
  /** Stored JSONL bytes represented by entries. */
  serializedBytes: number;
} | {
  kind: "reset";
  /** Fresh opaque cursor; it begins where the read's `start` mode selects. */
  cursor: string;
  /**
   * Stable discontinuity that invalidated the supplied cursor:
   * `anchor_missing` (the last returned entry left the active path, for example
   * after a branch change or rewrite), `anchor_moved` (it changed position),
   * `generation_mismatch` (the transcript was replaced), `invalid_cursor`
   * (malformed or altered), `scope_mismatch` (another agent or session), or
   * `session_reset` (reset-window cursors only: a newer same-session reset
   * closed the window being drained).
   */
  reason: "anchor_missing" | "anchor_moved" | "generation_mismatch" | "invalid_cursor" | "scope_mismatch" | "session_reset";
} | {
  kind: "unavailable";
  reason: "projection_rebuilding";
} | {
  kind: "missing";
};
type SessionTranscriptMessageEntry = {
  /** Stable transcript event id for this message entry. */
  entryId: string;
  /** Parent id after active-branch normalization; null when this is a visible root. */
  parentId: string | null;
  /**
   * Ordered read metadata, not a resumable cursor. Delta reads report the one-based
   * active-path message ordinal; full reads report the original transcript line.
   */
  seq: number;
  /** Agent message payload as persisted by the runtime. */
  message: AgentMessage;
  /** Convenience mirror of message.role. */
  role: AgentMessage["role"];
  /** Entry timestamp recorded by the transcript store, when present. */
  createdAt?: string;
  /** Message idempotency key, when the persisted message has one. */
  idempotencyKey?: string;
  /** Entry id this message replaced when a transcript rewrite re-appended it. */
  supersedesEntryId?: string;
};
/**
 * Reads one bounded active-path page that resumes appends and resets after discontinuities.
 * `start: "reset-window"` begins fresh cursors at the latest reset's retained tail.
 */
declare function readSessionTranscriptVisibleMessageDelta(params: SessionTranscriptVisibleMessageDeltaParams): Promise<SessionTranscriptVisibleMessageDeltaResult$1>;
//#endregion
//#region src/state/incognito-session-error.d.ts
/** An ended actor or unsupported sync access is never an empty or successfully updated session. */
declare function rethrowIncognitoSessionError(error: unknown): void;
//#endregion
//#region src/utils/delivery-context.read.d.ts
/** Reads only the canonical persisted delivery record. */
declare function deliveryContextFromSession(entry?: Pick<SessionEntry, "delivery">): DeliveryContext | undefined;
declare function sessionDeliveryRoute(entry?: Pick<SessionEntry, "delivery">): ChannelRouteRef | undefined;
declare function sessionDeliveryOrigin(entry?: Pick<SessionEntry, "delivery">): SessionOrigin | undefined;
declare function sessionDeliveryChannel(entry?: Pick<SessionEntry, "delivery">): string | undefined;
//#endregion
//#region src/utils/delivery-context.shared.d.ts
type SessionDeliveryProjection = {
  route?: ChannelRouteRef;
  deliveryContext?: DeliveryContext;
  origin?: SessionOrigin;
  channel?: string;
  lastChannel?: string;
  lastTo?: string;
  lastAccountId?: string;
  lastThreadId?: string | number;
};
/** Builds one canonical delivery state from current turn routing facts. */
declare function normalizeSessionDeliveryState(params?: {
  route?: ChannelRouteRef;
  context?: DeliveryContext;
  origin?: SessionOrigin;
}): SessionDeliveryState;
/** Projects compatibility fields without persisting duplicate delivery state. */
declare function projectSessionDeliveryFields(delivery?: SessionDeliveryState): SessionDeliveryProjection;
//#endregion
//#region src/config/sessions/legacy-sqlite-marker.d.ts
type SqliteSessionFileMarker = {
  agentId: string;
  sessionId: string;
  storePath: string;
};
declare function formatSqliteSessionFileMarker(marker: SqliteSessionFileMarker): string;
declare function parseSqliteSessionFileMarker(sessionFile: string | undefined): SqliteSessionFileMarker | undefined;
declare function sqliteSessionFileMarkerMatchesSession(sessionFile: string | undefined, sessionId: string): boolean;
//#endregion
//#region src/config/sessions/session-key.d.ts
/**
 * Derives the raw session bucket from message context before agent/main-key normalization.
 *
 * Direct chats use sender identity, groups use channel-owned group keys, and global scope bypasses
 * sender routing entirely.
 */
declare function deriveSessionKey(scope: SessionScope, ctx: MsgContext): string;
/**
 * Resolves the persisted session-store key for an inbound message.
 *
 * Explicit session keys pass through the compatibility normalizer, direct chats collapse to the
 * agent's canonical main bucket, and group/channel sessions stay isolated under the same agent.
 */
declare function resolveSessionKey(scope: SessionScope, ctx: MsgContext, mainKey?: string, agentId?: string): string;
//#endregion
//#region src/config/sessions/main-session.d.ts
/** Canonicalizes main-session aliases to the current scoped session key. */
declare function canonicalizeMainSessionAlias(params: {
  cfg?: {
    session?: {
      scope?: SessionScope;
      mainKey?: string;
    };
  };
  agentId: string;
  sessionKey: string;
}): string;
//#endregion
//#region src/config/sessions/store-writer-state.d.ts
/** Clears session writer queues and prompt-blob caches for tests. */
declare function clearSessionStoreCacheForTest(): void;
//#endregion
//#region src/sessions/agent-harness-session-key.d.ts
type AgentHarnessSessionStoreEntry = {
  agentHarnessId?: unknown;
  modelSelectionLocked?: unknown;
  pluginOwnerId?: unknown;
  sessionId?: unknown;
};
/** True for any valid durable harness lock, including supported ordinary-key rows. */
declare function isValidAgentHarnessSessionStoreEntry(sessionKey: string, entry: AgentHarnessSessionStoreEntry): boolean;
//#endregion
//#region src/config/sessions/reset-policy.d.ts
type SessionResetMode = "none" | "daily" | "idle";
type SessionStaleReason = Exclude<SessionResetMode, "none">;
type SessionResetType = "direct" | "group" | "thread";
type SessionResetPolicy = {
  mode: SessionResetMode;
  atHour: number;
  idleMinutes?: number;
  configured?: boolean;
};
type SessionFreshness = {
  fresh: boolean;
  dailyResetAt?: number;
  idleExpiresAt?: number;
  staleReason?: SessionStaleReason;
};
/** Resolves the effective reset policy for direct, group, or thread sessions. */
declare function resolveSessionResetPolicy(params: {
  sessionCfg?: SessionConfig;
  resetType: SessionResetType;
  resetOverride?: SessionResetConfig;
}): SessionResetPolicy;
/** Evaluates whether a persisted session is still fresh under the resolved reset policy. */
declare function evaluateSessionFreshness(params: {
  updatedAt: number;
  sessionStartedAt?: number;
  lastInteractionAt?: number;
  now: number;
  policy: SessionResetPolicy;
}): SessionFreshness;
//#endregion
//#region src/config/sessions/reset.d.ts
declare function resolveSessionResetType(params: {
  sessionKey?: string | null;
  isGroup?: boolean;
  isThread?: boolean;
}): SessionResetType;
declare function resolveThreadFlag(params: {
  sessionKey?: string | null;
  messageThreadId?: string | number | null;
  threadLabel?: string | null;
  threadStarterBody?: string | null;
  parentSessionKey?: string | null;
}): boolean;
declare function resolveChannelResetConfig(params: {
  sessionCfg?: SessionConfig;
  channel?: string | null;
}): SessionResetConfig | undefined;
//#endregion
//#region src/sessions/send-policy.d.ts
/** Session send-policy decision after config and per-session overrides are evaluated. */
type SessionSendPolicyDecision = "allow" | "deny";
/** Resolves whether a session send is allowed by entry override and config rules. */
declare function resolveSendPolicy(params: {
  cfg: OpenClawConfig;
  entry?: SessionEntry;
  sessionKey?: string;
  channel?: string;
  chatType?: SessionChatType;
}): SessionSendPolicyDecision;
//#endregion
//#region src/plugin-sdk/session-store-runtime.d.ts
type SessionStoreListParams = Partial<Omit<SessionStoreReadParams, "sessionKey">>;
type SessionStoreTranscriptEvent = SessionTranscriptEvent;
type SessionStoreEntryUpdate = (entry: SessionEntry) => Promise<Partial<SessionEntry> | null> | Partial<SessionEntry> | null;
type SessionStoreEntryPatch = (entry: SessionEntry, context: {
  existingEntry?: SessionEntry;
}) => Promise<Partial<SessionEntry> | null> | Partial<SessionEntry> | null;
type PatchSessionEntryParams = SessionStoreReadParams & {
  /** Synchronous final ownership check executed inside the commit transaction. */
  assertCommitAllowed?: () => void;
  fallbackEntry?: SessionEntry;
  maintenanceConfig?: ResolvedSessionMaintenanceConfigInput;
  preserveActivity?: boolean;
  requireWriteSuccess?: boolean;
  replaceEntry?: boolean;
  skipMaintenance?: boolean;
  update: SessionStoreEntryPatch;
};
type PrepareSessionEntryPatchParams = Omit<PatchSessionEntryParams, "update" | "assertCommitAllowed"> & {
  prepare: SessionStoreEntryPatch;
  authority?: SessionEntryPatchAuthority;
};
type ApplySessionEntryPatchParams = Omit<PrepareSessionEntryPatchParams, "prepare"> & {
  patch: Partial<SessionEntry>;
  /** null requires absence; an identity requires that exact live session generation. */
  expected?: (Pick<SessionEntry, "sessionId"> & Partial<Pick<SessionEntry, "lifecycleRevision">>) | null;
};
type UpdateSessionStoreEntryParams = {
  storePath: string;
  sessionKey: string;
  update: SessionStoreEntryUpdate;
  skipMaintenance?: boolean;
  takeCacheOwnership?: boolean;
  requireWriteSuccess?: boolean;
};
type UpsertSessionEntryParams = SessionStoreReadParams & {
  entry: SessionEntry;
};
type ReadAmbientTranscriptWatermarkParams = SessionStoreReadParams & {
  key: string;
};
type DeleteSessionEntryParams = SessionStoreReadParams & {
  archiveTranscript?: boolean;
  /** Doctor-only recovery snapshot in a fresh directory, completed before deletion. */
  backupDir?: string;
  expectedSessionId?: string | null;
  expectedUpdatedAt?: number;
};
type SessionLifecycleArtifactsCleanupParams = {
  agentId?: string;
  archiveRemovedEntryTranscripts?: boolean;
  env?: NodeJS.ProcessEnv;
  orphanTranscriptMinAgeMs: number;
  pluginOwnerId?: string;
  sessionStore?: string;
  sessionKeySegmentPrefix: string;
  storePath?: string;
  transcriptContentMarker: string;
  nowMs?: number;
};
type SessionLifecycleArtifactsCleanupResult = Awaited<ReturnType<typeof cleanupSessionLifecycleArtifactsCore>>;
/** @deprecated Use getSessionEntryAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function getSessionEntry(params: SessionStoreReadParams): SessionEntry | undefined;
/** @deprecated Use getConversationSessionAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function getConversationSession(params: {
  agentId: string;
  env?: NodeJS.ProcessEnv;
  storePath?: string;
  channel: string;
  accountId: string;
  kind: "channel" | "direct" | "group";
  peerId: string;
  threadId?: string;
}): {
  sessionKey: string;
  sessionId: string;
} | undefined;
/** Reads the current binding of one canonical transport address off the Gateway thread. */
declare function getConversationSessionAsync(params: Parameters<typeof getConversationSession>[0]): Promise<{
  sessionKey: string;
  sessionId: string;
} | undefined>;
/**
 * Lists session entries for one agent. `readOnly` reads without joining the
 * agent database writable lifecycle (no create/register/migrate) — required
 * for detection/introspection paths that may run across the whole fleet.
 * @deprecated Use listSessionEntriesAsync for metadata reads. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release.
 */
declare function listSessionEntries(params?: SessionStoreListParams & {
  readOnly?: boolean;
}): SessionStoreEntrySummary[];
/** Lists public session metadata without hydrating saved prompts or opening a writable database. */
declare function listSessionEntriesAsync(params: {
  agentId: string;
  env?: NodeJS.ProcessEnv;
  storePath?: string;
  /** External readers cannot reuse the Gateway process's writer receipts. */
  readConsistency?: "latest";
}): Promise<SessionStoreEntrySummary[]>;
type SessionStoreSelectedEntries = {
  agentId: string;
  storePath: string;
  sessionKeys: readonly string[];
};
type SessionStoreSelectedEntry = SessionStoreEntrySummary & {
  agentId: string;
  storePath: string;
};
/**
 * Prepare selected stores and a fresh profile snapshot off-thread, then consume synchronously.
 * Final native session guards observe cross-process commits; stores are not one atomic snapshot.
 * Profile matching uses current canonical owners/direct participants, never display references.
 * Returned data carries no authority after the callback; caller policy must be checked inside it.
 */
declare function withSessionEntriesAsync<T>(params: {
  stores: readonly SessionStoreSelectedEntries[];
  env?: NodeJS.ProcessEnv;
  involvingProfileId?: string;
}, consume: (entries: SessionStoreSelectedEntry[]) => T): Promise<T>;
type SessionStoreTranscriptReadParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  sessionId: string;
  sessionKey?: string;
  storePath?: string;
};
/** @deprecated Use loadTranscriptEvents. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function loadTranscriptEventsSyncLegacy(params: SessionStoreTranscriptReadParams): SessionStoreTranscriptEvent[];
/** Reads ordered transcript events through the session owner's worker. */
declare function loadTranscriptEvents(params: SessionStoreTranscriptReadParams): Promise<SessionStoreTranscriptEvent[]>;
/** @deprecated Use readTranscriptStatsAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function readSessionStoreTranscriptStatsSync(params: {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  sessionId: string;
  sessionKey?: string;
  storePath?: string;
}): {
  eventCount: number;
  maxSeq: number;
  sizeBytes: number;
};
/** Reads transcript statistics through the existing session worker. */
declare const readTranscriptStatsAsync: (params: Parameters<typeof readSessionStoreTranscriptStatsSync>[0]) => Promise<ReturnType<typeof readSessionStoreTranscriptStatsSync>>;
/** @deprecated Await resolveTranscriptSessionKeyBySessionIdAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveTranscriptSessionKeyBySessionId(params: Parameters<typeof resolveSessionKeyBySessionId>[0]): string | undefined;
/** @deprecated Use prepareSessionEntryPatch or applySessionEntryPatch. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function patchSessionEntry(params: PatchSessionEntryParams): Promise<SessionEntry | null>;
/** Prepare outside SQLite, then compare the exact snapshot and commit once in its worker. */
declare function prepareSessionEntryPatch(params: PrepareSessionEntryPatchParams): Promise<SessionEntry | null>;
/** Reduce a data-only patch against the authoritative entry in one worker command. */
declare function applySessionEntryPatch(params: ApplySessionEntryPatchParams): Promise<SessionEntry | null>;
/** @deprecated Use readSessionUpdatedAtAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function readSessionUpdatedAt(params: SessionStoreReadParams): number | undefined;
/** Reads the last activity timestamp without creating a missing session store. */
declare function readSessionUpdatedAtAsync(params: SessionStoreReadParams): Promise<number | undefined>;
declare function updateSessionStoreAmbientTranscriptWatermark(params: Parameters<typeof updateAmbientTranscriptWatermark>[0]): ReturnType<typeof updateAmbientTranscriptWatermark>;
/** @deprecated Use readAmbientTranscriptWatermarkAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function readAmbientTranscriptWatermark(params: ReadAmbientTranscriptWatermarkParams): AmbientTranscriptWatermark | undefined;
/** Reads the transcript watermark through the session owner's worker. */
declare function readAmbientTranscriptWatermarkAsync(params: ReadAmbientTranscriptWatermarkParams): Promise<AmbientTranscriptWatermark | undefined>;
/** @deprecated Use prepareSessionEntryPatch. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function updateSessionStoreEntry(params: UpdateSessionStoreEntryParams): Promise<SessionEntry | null>;
/** Replaces or creates one session entry by agent/session identity. */
declare function upsertSessionEntry(params: UpsertSessionEntryParams): Promise<void>;
/** Deletes one session entry by agent/session identity. */
declare function deleteSessionEntry(params: DeleteSessionEntryParams): Promise<boolean>;
/**
 * Inventories session-store artifacts; this is not a safe live-file copy protocol.
 * Use deleteSessionEntry's backupDir option for a verified pre-repair snapshot.
 */
declare function resolveSessionStoreBackupPaths(params: {
  agentId?: string;
  storePath: string;
}): string[];
/**
 * Cleans stale lifecycle-owned session entries and orphan transcripts for one agent store.
 * Joins pending startup preparation before capturing the database identity; failed preparation
 * still surfaces through normal admission checks. Prepared agents do not wait.
 */
declare function cleanupSessionLifecycleArtifacts(params: SessionLifecycleArtifactsCleanupParams): Promise<SessionLifecycleArtifactsCleanupResult>;
declare function recordSessionMetaFromInbound(params: Parameters<typeof recordInboundSessionMeta>[0]): ReturnType<typeof recordInboundSessionMeta>;
declare function updateLastRoute(params: UpdateSessionLastRouteParams & {
  /** @deprecated Use updateLastRouteWithAuthority. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  assertCommitAllowed?: () => void;
}): Promise<SessionEntry | null>;
/** Route preparation runs before the worker's conditional commit. */
declare function updateLastRouteWithAuthority(params: UpdateSessionLastRouteParams & {
  authority: SessionEntryPatchAuthority;
}): Promise<SessionEntry | null>;
//#endregion
//#region src/config/sessions/session-reaction-store.kernel.d.ts
declare function setSessionReactionInDatabase(database: OpenClawAgentDatabase, sessionKey: string, params: SetSessionReactionParams): SessionReactionWrite;
//#endregion
//#region src/config/sessions/session-pending-input-operations.kernel.d.ts
declare function readPendingInput(database: OpenClawAgentDatabase, input: PendingInputRead): PendingInputSnapshot | PendingInputSourceSnapshot;
declare function mutatePendingInput(input: PendingInputMutation, { writeTransaction, admit }: Pick<AgentWorkerOperationContext, "writeTransaction"> & {
  admit: (stage: "transaction" | "commit", publication?: unknown) => void;
}, publish: (database: OpenClawAgentDatabase["db"], receipt: PendingInputMutationReceipt) => void): PendingInputMutationReceipt;
//#endregion
//#region src/config/sessions/session-pending-input-withdrawal.worker.d.ts
type SessionPendingInputWithdrawal = {
  sessionKey: string;
  sessionId: string;
} & ({
  runId: string;
} | {
  inputIds: readonly string[];
} | {
  lifecycleGeneration: string;
});
type RetiredPendingInputDismissalOutcome = {
  kind: "dismissed";
  inputIds: string[];
  runIds: string[];
  missingIds: string[];
} | {
  kind: "active";
  inputIds: string[];
} | {
  kind: "stale";
};
type SessionPendingInputWithdrawalResult = boolean | RetiredPendingInputDismissalOutcome;
/** Retain accepted receipts while hiding only inputs the agent has not consumed. */
declare function discardSessionPendingInputInWorker(database: OpenClawAgentDatabase, options: OpenClawAgentDatabaseOptions, input: SessionPendingInputWithdrawal, admit: (stage: "transaction" | "commit", publication?: unknown) => void): SessionPendingInputWithdrawalResult;
//#endregion
//#region src/config/sessions/session-history-archive-pruning.worker.d.ts
declare function pruneSessionArchivesByRetentionInDatabase(database: OpenClawAgentDatabase, options: OpenClawAgentDatabaseOptions, input: SessionArchiveRetentionDelete, admit: (stage: "transaction" | "commit") => void): number;
declare function deletePublishedSessionArchiveInDatabase(database: OpenClawAgentDatabase, options: OpenClawAgentDatabaseOptions, row: PublishedSessionTranscriptArchive, admit: (stage: "transaction" | "commit") => void): void;
//#endregion
//#region src/config/sessions/conversation-delivery-store.kernel.d.ts
declare function beginConversationDeliveryInDatabase(database: OpenClawAgentReadOnlyDatabase, params: ConversationDeliveryBegin): {
  created: boolean;
  record: ConversationDeliveryRecord;
};
declare function transitionConversationDeliveryInDatabase(database: OpenClawAgentReadOnlyDatabase, params: ConversationDeliveryTransition): ConversationDeliveryRecord;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-conversation.d.ts
declare function prepareConversationIdentities(identities: readonly ConversationIdentity[]): string | undefined;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-conversation-read.d.ts
declare function selectConversationRowsFromDatabase(database: Pick<OpenClawAgentDatabase, "db">, options?: ConversationReadQuery): ConversationRecord[];
//#endregion
//#region src/gateway/session-row-transcript-backfill.types.d.ts
type SessionRowTranscriptReadParams = {
  agentId: string;
  storeAgentId?: string;
  storePath: string;
  sessionKey: string;
  sessionId: string;
};
//#endregion
//#region src/gateway/session-row-transcript-backfill.worker.d.ts
/** Read and persist bounded derived facts in the existing writer's transaction. */
declare function backfillSessionRowTranscriptFieldsInDatabase(database: OpenClawAgentDatabase, params: SessionRowTranscriptReadParams): SessionRowTranscriptProjection | undefined;
//#endregion
//#region src/agents/auth-profiles/store-agent.worker.d.ts
declare function loadAgentAuthProfileOperations(): Promise<{
  "authProfiles.read": (_input: undefined, { open, admit }: AgentWorkerOperationContext) => void;
}>;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-replacement-types.d.ts
type SqliteSessionEntryReplacement = SessionEntryReplacement & {
  previousSessionKeys?: readonly string[];
};
type SessionEntryReplacementCommit = {
  sources?: SessionSourcePredicate[];
  nativeBindings?: SessionNativeBindingParticipants;
  expectedRows: Map<string, ResolvedSessionEntryRow>;
  labelOwnerKeys: string[];
  includeLabelOwners?: string;
  labelClaim?: {
    sessionKey: string;
    label: string;
  };
  preparedTranscript?: {
    sessionKey: string;
    sessionId: string;
    events: readonly TranscriptEvent[];
  };
  validationKeys: string[];
  replacements: SqliteSessionEntryReplacement[];
  checkPendingArchiveRecovery?: boolean;
  consumePendingReset?: boolean;
  maintenance?: SessionEntryMaintenanceInput;
  ownerAssignment?: {
    sessionKey: string;
    owner: SessionOwnerAssignment;
  };
};
//#endregion
//#region src/state/openclaw-agent-execution-maintenance.d.ts
type PreparationInput = Omit<Extract<SessionMaintenanceMetadataCommand, {
  kind: "maintenance-plan";
}>, "kind">;
type MetadataInput = Exclude<SessionMaintenanceMetadataCommand, {
  kind: "maintenance-plan";
}> | {
  kind: "maintenance-plan";
  protection: SessionMaintenanceLiveProtection;
};
/** Metadata preparation and commit share the canonical actor's retained snapshots. */
declare function createAgentDatabaseMaintenanceOwner(context: {
  databaseOptions: ReclamationDatabaseOptions;
  openWriter(): OpenClawAgentDatabase;
  admit(stage: "transaction" | "commit", publication?: unknown): void;
}): {
  operations: {
    "session.maintenance.prepare": (input: PreparationInput) => {
      kind: "not-committed";
      workerThreadId: number;
      value: SessionMaintenanceMetadataResult;
    } | undefined;
    "session.maintenance.metadata": (input: MetadataInput) => {
      kind: "not-committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-plan-stale";
      };
      publication?: undefined;
    } | {
      kind: "committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-statistics";
        value: true;
      } | {
        kind: "maintenance-age";
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      } | {
        kind: "maintenance-plan";
        value: SessionEntryMaintenancePlan;
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      };
      publication: SessionEntryReplacementPublication;
    };
  };
  repairStartupIntegrity(receipt: OpenClawAgentDatabaseWorkerLeaseReceipt, check: SqliteIntegrityCheck, error: unknown, assertCurrent: () => void): boolean;
  prepare(): Promise<void>;
  cleanup(input: MetadataInput): void;
  getPreparationReleases(): (() => void)[];
};
//#endregion
//#region src/hooks/bundled/session-memory/transcript.d.ts
type SessionMemoryProjection = {
  content: string;
  originClass: "agent" | "untrusted";
};
//#endregion
//#region src/hooks/bundled/session-memory/capture.types.d.ts
type SessionMemoryTranscript = ({
  status: "available";
} & (SessionMemoryProjection | {
  content: null;
  originClass: "agent";
})) | {
  status: "unavailable";
  reason: string;
};
//#endregion
//#region src/config/sessions/session-transcript-worker-read.types.d.ts
type SessionTranscriptAnchorsWorkerInput = {
  kind: "transcript-anchors";
  database: {
    agentId: string;
    path: string;
  };
  resolved: ResolvedTranscriptScope;
  selection: SessionTranscriptAnchorSelection;
  preparedEntry?: SessionTranscriptAnchorEntry;
  expectedIdentity: DatabaseFileIdentity;
};
type SessionTranscriptWatermarkWorkerInput = {
  kind: "transcript-watermark";
  database: {
    agentId: string;
    path: string;
  };
  scope: SessionTranscriptReadScope;
  expectedIdentity?: DatabaseFileIdentity;
};
type SessionTranscriptDeltaWorkerInput = Omit<SessionTranscriptWatermarkWorkerInput, "kind"> & {
  resolved: ResolvedTranscriptReadScope;
  admission?: UserTurnTranscriptAdmissionReceipt;
} & ({
  kind: "transcript-raw-delta";
  limits: SessionTranscriptRawDeltaLimits;
} | {
  kind: "transcript-visible-delta";
  limits: SessionTranscriptVisibleMessageDeltaLimits;
});
type SessionMemoryCaptureWorkerInput = Omit<SessionTranscriptWatermarkWorkerInput, "kind"> & {
  kind: "session-memory-capture";
  resolved: ResolvedTranscriptReadScope;
  messageCount: number;
  admission?: UserTurnTranscriptAdmissionReceipt;
};
//#endregion
//#region src/config/sessions/session-transcript-execution-read.types.d.ts
type CapturedRead<Input> = Omit<Input, "kind" | "database" | "expectedIdentity"> & {
  expectedIdentity: DatabaseFileIdentity;
};
type SessionTranscriptExecutionReadResult<T> = {
  ok: true;
  value: T;
} | {
  ok: false;
  error: SessionTranscriptWorkerReadError;
};
type SessionTranscriptExecutionReadInputs = {
  raw: CapturedRead<Extract<SessionTranscriptDeltaWorkerInput, {
    kind: "transcript-raw-delta";
  }>>;
  visible: CapturedRead<Extract<SessionTranscriptDeltaWorkerInput, {
    kind: "transcript-visible-delta";
  }>>;
  memory: CapturedRead<SessionMemoryCaptureWorkerInput>;
  anchors: CapturedRead<SessionTranscriptAnchorsWorkerInput>;
  watermark: CapturedRead<SessionTranscriptWatermarkWorkerInput>;
  cold: {
    sessionId: string;
    expectedIdentity: DatabaseFileIdentity;
  };
};
//#endregion
//#region src/state/openclaw-agent-execution-transcript.worker.d.ts
type TranscriptInitialization = {
  sessionKey: string;
  sessionId: string;
  cwd?: string;
};
declare function loadAgentTranscriptOperations(): Promise<{
  "session.transcript.initialize": (input: TranscriptInitialization, context: AgentWorkerOperationContext) => SessionTranscriptInitializationPublication;
}>;
declare function loadAgentTranscriptReadOperations(): Promise<{
  "session.transcript.watermark.read": (input: SessionTranscriptExecutionReadInputs["watermark"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<SessionTranscriptWatermark>;
  "session.transcript.rawDelta.read": (input: SessionTranscriptExecutionReadInputs["raw"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<{
    kind: "missing";
  } | {
    kind: "page";
    cursor: string;
    events: SessionTranscriptEventRow[];
    hasMore: boolean;
    requiredBytes?: number;
    serializedBytes: number;
  } | {
    kind: "reset";
    cursor: string;
    reason: "generation_mismatch" | "invalid_cursor" | "scope_mismatch";
  }>;
  "session.transcript.visibleDelta.read": (input: SessionTranscriptExecutionReadInputs["visible"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<SessionTranscriptVisibleMessageDeltaResult>;
  "session.transcript.memoryCapture.read": (input: SessionTranscriptExecutionReadInputs["memory"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<SessionMemoryTranscript>;
  "session.transcript.anchors.read": (input: SessionTranscriptExecutionReadInputs["anchors"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<SessionTranscriptAnchorFacts>;
  "session.transcript.coldMetadata.read": (input: SessionTranscriptExecutionReadInputs["cold"], context: AgentWorkerOperationContext) => SessionTranscriptExecutionReadResult<Omit<{
    archive_blob: Uint8Array<ArrayBufferLike> | null;
    archive_bytes: number;
    archive_name: string;
    archive_sha256: string;
    archived_at: number;
    event_count: number;
    generation: string;
    last_seq: number;
    raw_bytes: number;
    session_id: string;
    storage: string;
  }, "archive_blob"> | undefined>;
}>;
//#endregion
//#region src/infra/session-cost-usage-quarters.d.ts
declare const [QUARTERS, MODELS, MODEL_TOTALS, TOOLS, QUARTER_MISSING, MODEL_MISSING]: [0, 1, 2, 3, 4, 5];
type UsageCostQuarterRow = {
  valueJson: string;
  blob: Uint8Array<ArrayBuffer>;
};
//#endregion
//#region src/infra/session-cost-usage-rollup-codec.d.ts
type UsageCostJsonlCheckpoint = {
  kind: "jsonl";
  parsedOffset: number;
  observedSize: number;
  observedMtimeMs: number;
  device: number;
  inode: number;
  anchorHash: string;
};
type UsageCostSqliteCheckpoint = {
  kind: "sqlite";
  /** Existing transcript rewrite watermark; absent legacy checkpoints rebuild once. */
  generation?: string | null;
  maxSeq: number;
  eventCount: number;
  size: number;
  mtimeMs: number;
  anchorHash: string;
  visibleLeafId?: string;
};
type UsageCostFreshnessCheckpoint = Pick<UsageCostJsonlCheckpoint, "kind" | "observedSize" | "observedMtimeMs" | "device" | "inode"> | Pick<UsageCostSqliteCheckpoint, "kind" | "maxSeq" | "eventCount" | "size" | "mtimeMs">;
//#endregion
//#region src/infra/session-cost-usage-partitions.d.ts
type UsageCostPartition = {
  date: string;
  valueJson: string;
  blob: Uint8Array;
  /** Report summary committed with this partition; absent on partitions read back. */
  quarters?: UsageCostQuarterRow;
};
//#endregion
//#region src/infra/session-cost-usage-cache.kernel.d.ts
type SessionCostUsageRollupRow = {
  key: string;
  updatedAt: number;
  valueJson: string;
  /** Actual stored length, carried by database reads for cheap read repair. */
  bodyBytes?: number;
};
type SessionCostUsageJson = string | Uint8Array;
type SessionCostUsageRollupSnapshot = Omit<SessionCostUsageRollupRow, "valueJson"> & {
  valueJson: SessionCostUsageJson;
};
declare function writeSessionCostUsageRollupsInDatabase(db: EngineConnection, params: {
  rollupId: string;
  valueJson: Uint8Array;
  blob: Uint8Array | null;
  updatedAt: number;
  partitions?: UsageCostPartition[];
  removedDates?: string[];
  replacePartitions?: boolean;
}[]): boolean;
declare function pruneSessionCostUsageRollupsInDatabase(db: EngineConnection, existing: readonly SessionCostUsageRollupSnapshot[]): void;
//#endregion
//#region src/infra/session-cost-usage-quarters.worker.d.ts
type UsageCostQuarterBackfillRow = {
  /** Partition key shared by the quarter row. */
  key: string;
  /** Partition header observed when the quarter row was derived. */
  partitionValueJson: string;
  valueJson: string;
  blob: Uint8Array<ArrayBuffer>;
};
/**
 * Add quarter rows derived from existing partitions. Each insert copies the
 * partition's `updated_at` and applies only while the partition header is the
 * one the worker decoded, so a concurrent rewrite is never paired with stale data.
 */
declare function writeSessionCostUsageQuartersInDatabase(db: EngineConnection, rows: readonly UsageCostQuarterBackfillRow[]): boolean;
//#endregion
//#region src/state/openclaw-agent-execution-usage.worker.d.ts
declare function loadUsageCacheOperations(): Promise<{
  "usageCache.retireLegacy": (_input: undefined, { writeTransaction, admit }: AgentWorkerOperationContext) => void;
  "usageCache.writeRollup": (input: Parameters<typeof writeSessionCostUsageRollupsInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => boolean;
  "usageCache.writeQuarters": (input: Parameters<typeof writeSessionCostUsageQuartersInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => boolean;
  "usageCache.prune": (input: Parameters<typeof pruneSessionCostUsageRollupsInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => void;
}>;
//#endregion
//#region src/talk/client-voice-session-write.kernel.d.ts
type VoiceSessionMutation = ClientVoiceRunBinding & {
  now: number;
} & ({
  kind: "create";
  provider?: string;
  origin: "client" | "relay";
  transcriptCapable?: boolean;
} | {
  kind: "consult";
  runId: string;
} | {
  kind: "effect";
  event: TrustedToolExecutionEvent;
} | {
  kind: "reserve";
  failureKey: string;
  origin: "client" | "relay";
  transcriptSessionKey?: string;
} | {
  kind: "confirm";
  failureKey: string;
  role: "user" | "assistant";
} | {
  kind: "close";
  transcriptFailurePolicy: "require-success" | "retain-and-close";
  expectedOrigin?: "client";
  staleBefore?: number;
} | {
  kind: "delivered";
  deliveredAt: number;
});
/** The caller owns the transaction; all predicates use its current canonical row. */
declare function mutateVoiceSessionInDatabase(database: OpenClawAgentDatabase, input: VoiceSessionMutation): ClientVoiceSessionRecord | undefined;
//#endregion
//#region src/state/openclaw-agent-execution-voice-operations.d.ts
declare function loadAgentVoiceSessionOperations(): Promise<{
  "voice.session.read": (input: {
    voiceSessionId: string;
  }, { open }: AgentWorkerOperationContext) => {
    record: ClientVoiceSessionRecord | undefined;
    entry: InternalSessionEntry | undefined;
  };
  "voice.session.mutate": (input: Parameters<typeof mutateVoiceSessionInDatabase>[1] & {
    sources?: SessionSourcePredicate[];
    transactionSource?: Omit<SessionSourceTransactionGrant, "assertCurrent">;
  }, { writeTransaction, admit }: AgentWorkerOperationContext) => {
    record: ClientVoiceSessionRecord | undefined;
    entry: Pick<InternalSessionEntry, "lifecycleRevision" | "sessionId" | "updatedAt"> | undefined;
  };
}>;
//#endregion
//#region src/state/openclaw-agent-execution-operations.d.ts
declare function loadAgentReplacementOperations(): Promise<{
  "session.entries.replace": (input: SessionEntryReplacementCommit & {
    initializeTranscript?: TranscriptInitialization;
  }, context: AgentWorkerOperationContext) => SessionNativeBindingReceipt | {
    maintenancePlans: SessionEntryMaintenancePlan[];
    publication: SessionEntryReplacementPublication;
  };
}>;
declare function loadAgentEntryReadOperations(): Promise<{
  "session.entry.readResult": (input: SessionEntryReadWorkerInput, { open }: AgentWorkerOperationContext) => SessionEntryReadWorkerResult;
  "session.entry.read": (input: {
    sessionKey: string;
  } | SessionEntryCohortRequest, { open }: AgentWorkerOperationContext) => SessionEntryCohortResult;
}>;
declare function loadAgentEntryPatchOperations(): Promise<{
  "session.entry.patch.prepare": (input: Parameters<typeof readSessionEntryPatchSnapshot>[1], { open }: AgentWorkerOperationContext) => {
    sessionKey: string;
    entry: InternalSessionEntry;
  }[];
  "session.entry.patch.commit": typeof commitSessionEntryPatch;
}>;
declare function loadAgentCompoundOperations(): Promise<{
  "session.turn.prepare": typeof prepareSessionTurn;
  "session.turn.commit": typeof commitSessionTurn;
  "session.lifecycle.reset": typeof commitSessionReset;
  "session.lifecycle.project": typeof commitSessionLifecycleProjection;
}>;
declare function loadAgentEntryDeletionOperations(): Promise<{
  "session.lifecycle.deletePlan": typeof planSessionDeletionInAgentWorker;
  "session.lifecycle.delete": typeof deleteSessionEntryInAgentWorker;
}>;
declare function loadAgentPurgeOperations(): Promise<{
  "session.agentPurge.prepare": typeof prepareSessionAgentPurge;
  "session.agentPurge.commit": typeof commitSessionAgentPurge;
}>;
declare function loadAgentMaintenanceFinalizationOperations(): Promise<{
  "session.maintenance.finalize": typeof finalizeSessionMaintenance;
  "session.maintenance.size": (input: {
    sessionIds: string[];
  }, { open }: AgentWorkerOperationContext) => Map<string, number>;
}>;
declare function loadAgentMessageCutOperations(): Promise<{
  "session.messageCut.commit": typeof commitSessionMessageCut;
}>;
declare function loadAgentNativeBindingOperations(): Promise<{
  "session.nativeBindings.delete": typeof deleteSessionWithNativeBindings;
}>;
declare function loadAgentTrajectoryOperations(): Promise<{
  "trajectory.events.append": (input: Parameters<typeof appendSqliteTrajectoryRuntimeEventsWithWriter>[0], { open, writeTransaction, admit }: AgentWorkerOperationContext) => TrajectoryRuntimeWindowFacts;
  "trajectory.retention.begin": (_input: undefined, { open }: AgentWorkerOperationContext) => string;
  "trajectory.retention.delete": (input: Parameters<typeof selectTrajectoryRuntimeRetentionBatch>[1], { open, writeTransaction, admit }: AgentWorkerOperationContext) => {
    complete: boolean;
    refresh: boolean;
    deleted: number;
    invalidated: number;
    totalBytes: number;
  };
}>;
declare function loadAgentArchiveOperations(): Promise<{
  "session.archives.preparePublication": (input: Parameters<typeof prepareSessionTranscriptArchivePublishPlans>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => TranscriptArchivePublishPlan[];
  "session.archives.recordPublication": (input: {
    results: Parameters<typeof recordSessionTranscriptArchivePublishResults>[1];
    nowMs: number;
  }, { writeTransaction, admit }: AgentWorkerOperationContext) => void;
}>;
declare function loadAgentAcpOperations(): Promise<{
  "session.entry.acp": (input: Parameters<typeof mutateAcpSessionEntryInWorker>[2], { open, options, admit }: AgentWorkerOperationContext) => AcpSessionEntryMutationResult;
}>;
declare function loadAgentProviderReviewOperations(): Promise<{
  "session.providerReview.compare": (input: Parameters<typeof compareSessionProviderReviewInWorker>[2], { open, options, admit }: AgentWorkerOperationContext) => {
    entry: SessionEntry;
    publication: SessionEntryReplacementPublication;
  };
}>;
declare function loadAgentReactionOperations(): Promise<{
  "session.reaction.set": (input: {
    sessionKey: string;
    params: Parameters<typeof setSessionReactionInDatabase>[2];
  }, { writeTransaction, admit }: AgentWorkerOperationContext) => SessionReactionWrite;
}>;
declare function loadAgentPendingInputOperations(): Promise<{
  "session.pendingInputs.read": (input: Parameters<typeof readPendingInput>[1], { open }: AgentWorkerOperationContext) => PendingInputSnapshot | PendingInputSourceSnapshot;
  "session.pendingInputs.mutate": (input: Parameters<typeof mutatePendingInput>[0], context: AgentWorkerOperationContext) => undefined;
  "session.pendingInputs.withdraw": (input: Parameters<typeof discardSessionPendingInputInWorker>[2], { open, options, admit }: AgentWorkerOperationContext) => SessionPendingInputWithdrawalResult;
}>;
declare function loadAgentArchivePruningOperations(): Promise<{
  "session.archivePruning.pruneRetention": (input: Parameters<typeof pruneSessionArchivesByRetentionInDatabase>[2], { open, options, admit }: AgentWorkerOperationContext) => number;
  "session.archivePruning.deletePublished": (input: Parameters<typeof deletePublishedSessionArchiveInDatabase>[2], { open, options, admit }: AgentWorkerOperationContext) => void;
  "session.archivePruning.removeLegacy": (input: {
    filePath: string;
  }, { open, options, admit }: AgentWorkerOperationContext) => SessionLegacyArchiveRemovalResult;
  "session.archivePruning.reclaimPages": (input: {
    maxPages?: number;
  }, { open, admit }: AgentWorkerOperationContext) => SqliteWalReclamationResult;
}>;
declare function loadConversationDeliveryOperations(): Promise<{
  "conversation.delivery.begin": (input: Parameters<typeof beginConversationDeliveryInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => {
    created: boolean;
    record: ConversationDeliveryRecord;
  };
  "conversation.delivery.transition": (input: Parameters<typeof transitionConversationDeliveryInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => ConversationDeliveryRecord;
}>;
declare function loadConversationRegistryOperations(): Promise<{
  "conversation.register": (input: {
    identities: Parameters<typeof prepareConversationIdentities>[0];
    discoveredAt: number;
    query?: Parameters<typeof selectConversationRowsFromDatabase>[1];
  }, { writeTransaction, admit }: AgentWorkerOperationContext) => ConversationRecord[] | undefined;
  "conversation.authority": (input: {
    conversationRef: string;
  } | {
    operationId: string;
  }, { writeTransaction, admit }: AgentWorkerOperationContext) => {
    operation: {
      conversationRef: string;
    } | undefined;
    conversation: ConversationRecord | undefined;
  };
}>;
declare function loadSessionRowBackfillOperations(): Promise<{
  "session.rowTranscript.backfill": (input: Parameters<typeof backfillSessionRowTranscriptFieldsInDatabase>[1], { writeTransaction, admit }: AgentWorkerOperationContext) => SessionRowTranscriptProjection | undefined;
}>;
declare function createAgentWorkerOperationLoaders(maintenance: ReturnType<typeof createAgentDatabaseMaintenanceOwner>["operations"]): {
  "authProfiles.read": typeof loadAgentAuthProfileOperations;
  "session.entry.read": typeof loadAgentEntryReadOperations;
  "session.entry.readResult": typeof loadAgentEntryReadOperations;
  "voice.session.read": typeof loadAgentVoiceSessionOperations;
  "voice.session.mutate": typeof loadAgentVoiceSessionOperations;
  "session.entry.patch.prepare": typeof loadAgentEntryPatchOperations;
  "session.entry.patch.commit": typeof loadAgentEntryPatchOperations;
  "session.turn.prepare": typeof loadAgentCompoundOperations;
  "session.turn.commit": typeof loadAgentCompoundOperations;
  "session.lifecycle.reset": typeof loadAgentCompoundOperations;
  "session.lifecycle.project": typeof loadAgentCompoundOperations;
  "session.lifecycle.deletePlan": typeof loadAgentEntryDeletionOperations;
  "session.lifecycle.delete": typeof loadAgentEntryDeletionOperations;
  "session.agentPurge.prepare": typeof loadAgentPurgeOperations;
  "session.agentPurge.commit": typeof loadAgentPurgeOperations;
  "session.maintenance.finalize": typeof loadAgentMaintenanceFinalizationOperations;
  "session.maintenance.size": typeof loadAgentMaintenanceFinalizationOperations;
  "session.nativeBindings.delete": typeof loadAgentNativeBindingOperations;
  "session.messageCut.commit": typeof loadAgentMessageCutOperations;
  "trajectory.events.append": typeof loadAgentTrajectoryOperations;
  "trajectory.retention.begin": typeof loadAgentTrajectoryOperations;
  "trajectory.retention.delete": typeof loadAgentTrajectoryOperations;
  "session.archives.preparePublication": typeof loadAgentArchiveOperations;
  "session.archives.recordPublication": typeof loadAgentArchiveOperations;
  "session.transcript.initialize": typeof loadAgentTranscriptOperations;
  "session.transcript.rawDelta.read": typeof loadAgentTranscriptReadOperations;
  "session.transcript.watermark.read": typeof loadAgentTranscriptReadOperations;
  "session.transcript.visibleDelta.read": typeof loadAgentTranscriptReadOperations;
  "session.transcript.memoryCapture.read": typeof loadAgentTranscriptReadOperations;
  "session.transcript.anchors.read": typeof loadAgentTranscriptReadOperations;
  "session.transcript.coldMetadata.read": typeof loadAgentTranscriptReadOperations;
  "session.entries.replace": typeof loadAgentReplacementOperations;
  "session.entry.acp": typeof loadAgentAcpOperations;
  "session.providerReview.compare": typeof loadAgentProviderReviewOperations;
  "session.reaction.set": typeof loadAgentReactionOperations;
  "conversation.delivery.begin": typeof loadConversationDeliveryOperations;
  "conversation.register": typeof loadConversationRegistryOperations;
  "conversation.authority": typeof loadConversationRegistryOperations;
  "conversation.delivery.transition": typeof loadConversationDeliveryOperations;
  "session.pendingInputs.withdraw": typeof loadAgentPendingInputOperations;
  "session.pendingInputs.read": typeof loadAgentPendingInputOperations;
  "session.pendingInputs.mutate": typeof loadAgentPendingInputOperations;
  "session.archivePruning.deletePublished": typeof loadAgentArchivePruningOperations;
  "session.archivePruning.pruneRetention": typeof loadAgentArchivePruningOperations;
  "session.archivePruning.removeLegacy": typeof loadAgentArchivePruningOperations;
  "session.archivePruning.reclaimPages": typeof loadAgentArchivePruningOperations;
  "session.maintenance.prepare": () => Promise<{
    "session.maintenance.prepare": (input: {
      ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
      input: SessionEntryMaintenanceInput;
    }) => {
      kind: "not-committed";
      workerThreadId: number;
      value: SessionMaintenanceMetadataResult;
    } | undefined;
    "session.maintenance.metadata": (input: {
      kind: "maintenance-statistics";
    } | {
      kind: "maintenance-age";
      ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
      maintenance: ResolvedSessionMaintenanceConfig;
    } | {
      kind: "maintenance-plan";
      protection: SessionMaintenanceLiveProtection;
    }) => {
      kind: "not-committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-plan-stale";
      };
      publication?: undefined;
    } | {
      kind: "committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-statistics";
        value: true;
      } | {
        kind: "maintenance-age";
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      } | {
        kind: "maintenance-plan";
        value: SessionEntryMaintenancePlan;
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      };
      publication: SessionEntryReplacementPublication;
    };
  }>;
  "session.maintenance.metadata": () => Promise<{
    "session.maintenance.prepare": (input: {
      ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
      input: SessionEntryMaintenanceInput;
    }) => {
      kind: "not-committed";
      workerThreadId: number;
      value: SessionMaintenanceMetadataResult;
    } | undefined;
    "session.maintenance.metadata": (input: {
      kind: "maintenance-statistics";
    } | {
      kind: "maintenance-age";
      ageChanges?: readonly SessionEntryMaintenanceAgeChange[];
      maintenance: ResolvedSessionMaintenanceConfig;
    } | {
      kind: "maintenance-plan";
      protection: SessionMaintenanceLiveProtection;
    }) => {
      kind: "not-committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-plan-stale";
      };
      publication?: undefined;
    } | {
      kind: "committed";
      workerThreadId: number;
      value: {
        kind: "maintenance-statistics";
        value: true;
      } | {
        kind: "maintenance-age";
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      } | {
        kind: "maintenance-plan";
        value: SessionEntryMaintenancePlan;
        nextAt: number | undefined;
        ageFact?: SessionEntryMaintenanceAgeFact;
      };
      publication: SessionEntryReplacementPublication;
    };
  }>;
  "usageCache.writeRollup": typeof loadUsageCacheOperations;
  "usageCache.writeQuarters": typeof loadUsageCacheOperations;
  "usageCache.prune": typeof loadUsageCacheOperations;
  "usageCache.retireLegacy": typeof loadUsageCacheOperations;
  "session.rowTranscript.backfill": typeof loadSessionRowBackfillOperations;
};
type RegisteredAgentWorkerOperations = WorkerOperationsFromLoaders<ReturnType<typeof createAgentWorkerOperationLoaders>>;
//#endregion
//#region src/state/openclaw-agent-execution-contract.d.ts
type AgentDatabaseNativeStore = SqliteWorkerStore<AgentDatabaseOperations>;
type AgentDatabaseExecutionScope = Pick<AgentDatabaseNativeStore, "execute">;
type OpenClawAgentDatabaseExecution = OpenClawAgentDatabaseAdmissionExecution & {
  /** Observe the next terminal native/admission loss after accepted work settles; excludes idle retirement. */
  onTerminal(listener: (reason: Error) => void): () => void;
  /** The accepted native receipt; reading this never adopts the current pathname. */
  readonly fileIdentity: AgentDatabaseExecutionFileIdentity | undefined;
  /** Accept the admitted native handle used by a synchronous SDK operation. */
  adoptNativeDatabase(database: OpenClawAgentDatabase): Promise<void>;
  /** Reuse only a native generation whose preparation and registration publication settled. */
  capturePreparedGenerationClaim(): AgentDatabaseGenerationClaim | undefined;
  /** Admit a write against existing storage; a missing store remains missing. */
  runExisting<T>(source: AgentDatabaseRequestExecutionSource, operation: (scope: AgentDatabaseExecutionScope) => Promise<T>, options?: {
    retireNativeOnFailure: true;
    withAdmission?: never;
  } | {
    retireNativeOnFailure?: never;
    /** Track read admission; cancellation removes only a waiting host-queue task. */
    withAdmission: <Result>(run: () => Promise<Result>, signal: AbortSignal) => Promise<Result>;
  }): Promise<T | undefined>;
  /**
   * Join this reference's work; native cleanup failures remain with its resource owner.
   * The owner may retain one bounded idle generation.
   */
  release(): Promise<void>;
};
type AgentDatabaseOperations = AgentDatabaseDomainOperations & SessionActorOperations & RegisteredAgentWorkerOperations & {
  "database.walMaintenance": {
    input: SqliteWalPeriodicRequest;
    output: SqliteWalPeriodicResult;
  };
  "database.prepareWrite": {
    input: undefined;
    output: void;
  };
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-generation.types.d.ts
type SqliteSessionGenerationWindow = Selectable<DB["session_windows"]>;
type SqliteSessionGenerationComparison = {
  window: SqliteSessionGenerationWindow;
  coldArchive: Omit<Selectable<DB["session_transcript_cold_archives"]>, "archive_blob"> | undefined;
  contentFingerprint: string;
};
type SqliteSessionGenerationClaim = SqliteSessionGenerationComparison & {
  fingerprint: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-entry.d.ts
declare function recordInboundSessionMeta(input: RecordInboundSessionMetaParams): Promise<InternalSessionEntry | null>;
//#endregion
//#region src/infra/worker-request-diagnostics.d.ts
type WorkerRequestMetricsListener = (kind: WorkerRequestKind, requestClass: string, phase: DiagnosticWorkerRequestFields["phase"], queueDepth: number, queueWaitMs: number | undefined, durationMs: number | undefined, timing: Readonly<DiagnosticWorkerRequestFields["timing"]>) => void;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-artifact-cleanup.d.ts
declare function cleanupSessionLifecycleArtifactsCore(params: SessionLifecycleArtifactCleanupParams): Promise<SessionLifecycleArtifactCleanupResult>;
//#endregion
//#region src/config/sessions/session-entry-creation.types.d.ts
/** Facts published by the writer after its absent-row creation commits. */
type SessionEntryCreationCommit = {
  agentId: string;
  sessionKey: string;
  storePath: string;
  sessionId: string;
  lifecycleRevision?: string;
  readSource: CapturedSessionEntryReadSource;
  entry: SessionEntry;
};
//#endregion
//#region src/config/sessions/targets-collision.d.ts
/** One session store path paired with its owning agent id. */
type SessionStoreTarget = {
  agentId: string;
  storePath: string;
};
//#endregion
//#region src/agents/sticky-model-selection.d.ts
type StickyModelSelectionDispatchOutcome = "requested" | "skipped-immutable";
//#endregion
//#region src/security/install-policy.d.ts
type InstallPolicyRequestKind = "skill-install" | "plugin-dir" | "plugin-archive" | "plugin-file" | "plugin-npm" | "plugin-git";
//#endregion
//#region src/agents/conversation-recall.types.d.ts
type ConversationRecallContext = {
  /** Private conversation that requested this bounded recall pass. */
  anchorSessionKey: string;
  /** Only same-agent private transcript hits may pass. */
  scope: "same-agent-private";
  /** Product-only recall searches sessions; advanced recall keeps configured corpora. */
  corpus: "sessions" | "configured";
};
//#endregion
//#region src/plugins/memory-provider-types.d.ts
/** Host-resolved memory partition for one trusted session invocation. */
type MemoryAudience = {
  kind: "owner-private";
  agentId: string;
} | {
  kind: "conversation";
  agentId: string;
  sessionKey: string;
  sessionId: string;
};
/** Authenticated caller authority supplied by the trusted host, never inferred from IDs. */
type MemoryCallerAuthority = {
  kind: "operator";
  scopes: readonly string[];
  connId?: string;
} | {
  kind: "session";
  sessionKey: string;
  sandboxed: boolean;
  /** Host-granted bounded recall pass; the memory owner decides which hits it admits. */
  conversationRecall?: ConversationRecallContext;
  sessionId?: string;
  audience?: MemoryAudience;
} | {
  kind: "host";
  operation: string;
};
/** Facts and a live capability supplied by the trusted host caller. */
type MemoryCallerContext = {
  authority: MemoryCallerAuthority;
  assertCurrent(): void;
  signal?: AbortSignal;
};
/** Opaque identity, scoped to its provider. A reference is not an authorization grant. */
type MemoryReference = {
  providerId: string;
  id: string;
  revision?: string;
  fragment?: string;
};
type MemoryCitation = {
  label: string;
  reference?: MemoryReference;
  url?: string;
  startLine?: number;
  endLine?: number;
};
type MemorySearchHit = {
  reference: MemoryReference;
  excerpt: string;
  score?: number;
  source?: string;
  citations?: MemoryCitation[];
  /** Provider-owned trusted selection facts; missing eligibility never permits injection. */
  automaticRecall?: {
    eligible: boolean;
    projectKeys?: readonly string[];
    triggers?: string;
    importance?: number;
  };
};
type MemorySearchPage = {
  hits: MemorySearchHit[];
  nextCursor?: string;
  coverage?: "complete" | "partial";
  warning?: string;
};
type MemorySearchRequest = {
  query: string;
  maxResults?: number;
  /** Minimum score every provider must enforce. */
  minScore?: number;
  cursor?: string;
  sources?: ("memory" | "sessions")[];
  /** Provider hint that may be ignored when lexical-only search is unavailable. */
  lexicalOnly?: boolean;
  activeProjectKeys?: readonly string[];
};
type MemoryGetRequest = {
  reference: MemoryReference;
  from?: number;
  lines?: number;
};
type MemoryGetResult = {
  status: "ok";
  reference: MemoryReference;
  text: string;
  citations?: MemoryCitation[];
  truncated?: boolean;
  from?: number;
  lines?: number;
  nextFrom?: number;
} | {
  status: "not_found";
};
type MemoryHealth = {
  status: "ready" | "degraded" | "unavailable";
  message?: string;
  details?: Record<string, unknown>;
};
type MemoryCandidateRequest = {
  kind: "trigger" | "project";
  limit?: number;
  activeProjectKeys?: readonly string[];
};
type MemoryProviderCapabilities = {
  /** Corpora search can cover. Non-empty. */
  sources: readonly ("memory" | "sessions")[];
  /** search accepts `cursor` and may return `nextCursor`. */
  pagination: boolean;
  /** Candidate kinds `candidates()` can enumerate for automatic recall. */
  candidates: readonly ("trigger" | "project")[];
  /** search honours `activeProjectKeys` as a filter. */
  projectFilter: boolean;
};
/** A caller-bound lease. close releases this lease, not another caller's cached manager. */
type MemoryProviderHandle = {
  capabilities: MemoryProviderCapabilities;
  search(request: MemorySearchRequest): Promise<MemorySearchPage>;
  get(request: MemoryGetRequest): Promise<MemoryGetResult>;
  /**
   * Report readiness without revealing partition content. This must be answerable for every
   * authenticated caller, including host authority with the `status` purpose; search/get may deny.
   */
  health(): Promise<MemoryHealth>;
  candidates?(request: MemoryCandidateRequest): Promise<MemorySearchPage>;
  refresh?(): Promise<void>;
  close(): Promise<void>;
};
type MemoryProviderOpenParams = {
  cfg: OpenClawConfig;
  agentId: string;
  context: MemoryCallerContext;
  purpose?: "default" | "status" | "cli";
};
type MemoryProviderOpenResult = {
  provider: MemoryProviderHandle | null;
  error?: string;
};
//#endregion
//#region src/plugins/hook-agent-context.types.d.ts
type PluginHookContextWindow = {
  /** Resolved effective context-token budget after model/config/agent caps. */
  contextTokenBudget?: number;
  /** Source that supplied the resolved context-token budget. */
  contextWindowSource?: "model" | "modelsConfig" | "agentContextTokens" | "default";
  /** Native/configured reference window when a lower cap wins. */
  contextWindowReferenceTokens?: number;
};
type PluginHookToolAuthority = {
  /** Opaque host fingerprint for the exact turn, route, policy, and active tool surface. */
  readonly fingerprint: string;
  /** Checks whether the finalized turn surface contains this exact tool. */
  allows(toolName: string): boolean;
  /** Rejects retained or timed-out capabilities after the host dispatch closes. */
  assertActive(): void;
};
type PluginHookAgentContext = PluginHookContextWindow & {
  runId?: string;
  jobId?: string;
  trace?: DiagnosticTraceContext;
  agentId?: string;
  sessionKey?: string;
  sessionId?: string;
  /** Host-resolved memory partition for this turn. */
  memoryAudience?: MemoryAudience;
  /** Rejects the audience after any captured session incarnation changes. */
  assertMemoryAudienceCurrent?: () => void;
  /** Whether this turn's tool/runtime surface is sandboxed. */
  sandboxed?: boolean;
  workspaceDir?: string;
  /** Run-prepared repository identities; empty when the turn is outside a repository. */
  activeProjectKeys?: string[];
  modelProviderId?: string;
  modelId?: string;
  messageProvider?: string;
  /** Channel/plugin id for channel-originated runs, e.g. `discord`. */
  channel?: string;
  /** Channel account used by the agent when multiple accounts are configured. */
  accountId?: string;
  /** Conversation target id for channel-originated runs. Mirrors `channelId` for compatibility. */
  chatId?: string;
  /** Sender identity for channel-originated runs when available. */
  senderId?: string;
  trigger?: string;
  channelId?: string;
  /** Typed origin of the turn's user-role input when supplied by the producer. */
  inputProvenance?: InputProvenance;
  /** @deprecated Use `channelContext.sender` for channel-specific identities. */
  senderExternalId?: string;
  /** Channel-owned sender/chat details. Plugins may augment the nested interfaces. */
  channelContext?: PluginHookChannelContext;
  /** Present only for post-policy prompt enrichment hooks that requested tool authority. */
  toolAuthority?: PluginHookToolAuthority;
  /** Checks this prompt hook handler's result-acceptance lifetime. */
  readonly hookInvocation?: Readonly<{
    assertActive(): void;
  }>;
};
//#endregion
//#region src/plugins/hook-before-agent-start.types.d.ts
type PluginHookBeforeModelResolveAttachment = {
  kind: "image" | "video" | "audio" | "document" | "other";
  mimeType?: string;
};
type PluginHookBeforeModelResolveEvent = {
  /** User prompt for this run. No session messages are available yet in this phase. */
  prompt: string;
  /** Attachment metadata for file-aware model routing. */
  attachments?: PluginHookBeforeModelResolveAttachment[];
};
type PluginHookBeforeModelResolveResult = {
  /** Override the model for this agent run. E.g. "llama3.3:8b" */
  modelOverride?: string;
  /** Override the provider for this agent run. E.g. "local-provider" */
  providerOverride?: string;
  /** Replace this run's fallback chain. An empty list disables model fallback. */
  fallbacksOverride?: string[];
};
type PluginHookBeforePromptBuildEvent = {
  prompt: string;
  /** Current request before projection. Empty means no textual request; omission is legacy. */
  currentUserMessage?: string;
  /** Stable native admission identity across rebuilds; differs between admitted requests. */
  currentUserMessageId?: string;
  /**
   * Model-context history: fresh array/envelopes per dispatch, shared frozen transcript payloads.
   * Treat nested content as read-only; strict-mode writes to frozen leaves throw TypeError.
   * Return result fields to contribute context. Array/envelope edits stay local to this dispatch,
   * whose handlers share them in priority order; they never update core history.
   */
  messages: unknown[];
};
type PluginHookBeforePromptBuildResult = {
  systemPrompt?: string;
  prependContext?: string;
  appendContext?: string;
  /**
   * Narrows the tools submitted to the model for this turn.
   * An empty array disables optional tools; omitted leaves the existing tool policy unchanged.
   */
  toolsAllow?: string[];
  /**
   * Prepended to the agent system prompt so providers can cache it (e.g. prompt caching).
   * Use for static plugin guidance instead of prependContext to avoid per-turn token cost.
   */
  prependSystemContext?: string;
  /**
   * Appended to the agent system prompt so providers can cache it (e.g. prompt caching).
   * Use for static plugin guidance instead of prependContext to avoid per-turn token cost.
   */
  appendSystemContext?: string;
};
/** Event payload for the before_agent_run gate hook. */
type PluginHookBeforeAgentRunEvent = {
  /** The user's message that triggered this run. */
  prompt: string;
  /** Prepared current-turn images, including prompt-local references. Absent on older hosts. */
  images?: ImageContent$1[];
  /** Loaded session history before the current prompt is submitted. */
  messages: unknown[];
  /** Active system prompt prepared for this run. */
  systemPrompt?: string;
  /** Account identity when available. */
  accountId?: string;
  /** Channel the message came from. */
  channelId?: string;
  /** Sender identity when available. */
  senderId?: string;
  /** Trusted sender identity bit when available. */
  senderIsOwner?: boolean;
};
//#endregion
//#region src/plugins/hook-before-tool-call-result.d.ts
declare const PluginApprovalResolutions: {
  readonly ALLOW_ONCE: "allow-once";
  readonly ALLOW_ALWAYS: "allow-always";
  readonly DENY: "deny";
  readonly TIMEOUT: "timeout";
  readonly CANCELLED: "cancelled";
};
type PluginApprovalResolution = (typeof PluginApprovalResolutions)[keyof typeof PluginApprovalResolutions];
type PluginHookBeforeToolCallResult = {
  params?: Record<string, unknown>;
  block?: boolean;
  blockReason?: string;
  requireApproval?: {
    title: string;
    description: string;
    scope?: ApprovalScope;
    severity?: "info" | "warning" | "critical";
    timeoutMs?: number;
    /** Override timeout text and return the timeout as a blocked tool result. */
    timeoutReason?: string;
    allowedDecisions?: Array<"allow-once" | "allow-always" | "deny">;
    pluginId?: string;
    onResolution?: (decision: PluginApprovalResolution) => Promise<void> | void;
  };
};
//#endregion
//#region src/plugins/hook-decision-types.d.ts
/**
 * Structured decision returned by gate/policy hooks.
 * Core is outcome-agnostic — it handles the mechanics of each outcome
 * without knowing *why* the decision was made.
 */
type HookDecision = HookDecisionPass | HookDecisionBlock;
/** Content is fine. Proceed normally. */
type HookDecisionPass = {
  outcome: "pass";
};
/**
 * Content is blocked. `reason` is internal plugin-local detail; core must not log,
 * persist, broadcast, or expose it verbatim. `message` is user-facing detail.
 */
type HookDecisionBlock = {
  outcome: "block";
  /** Internal plugin-local reason. Do not log, persist, broadcast, or expose verbatim. */
  reason: string;
  /** Optional user-facing detail included in the block response envelope. */
  message?: string;
  /** Plugin-defined category for analytics (e.g. "violence", "pii", "cost_limit"). */
  category?: string;
  /** Opaque metadata for the plugin's own use. Core does not interpret it. */
  metadata?: Record<string, unknown>;
};
/** Outcomes valid for input gates (before_agent_run). */
type InputGateDecision = HookDecisionPass | HookDecisionBlock;
/**
 * A gate hook decision paired with the pluginId that produced it.
 * Returned by gate hook runners so callers can
 * attribute blocked entries and audit events to the originating plugin.
 */
type GateHookResult<TDecision extends HookDecision = HookDecision> = {
  decision: TDecision;
  pluginId: string;
};
//#endregion
//#region src/plugins/hook-handler.types.d.ts
type AsyncPluginHook<Event, Context, Result = void> = (event: Event, ctx: Context) => Promise<Result | void> | Result | void;
//#endregion
//#region src/hooks/message-hook-media.d.ts
/** Stable media fact exposed to message-hook consumers. */
type MessageHookMediaFact = {
  path?: string;
  url?: string;
  contentType?: string;
  kind?: MediaFact["kind"];
  transcribed?: boolean;
  messageId?: string;
  workspaceDir?: string;
};
//#endregion
//#region src/plugins/conversation-binding.types.d.ts
/** Plugin-supplied context for requesting a channel conversation binding. */
type PluginConversationBindingRequestParams = {
  summary?: string;
  detachHint?: string;
  data?: Record<string, unknown>;
};
/** Maintainer/user decision recorded for a plugin conversation binding request. */
type PluginConversationBindingResolutionDecision = "allow-once" | "allow-always" | "deny";
/** Stored binding between a plugin and an external channel conversation. */
type PluginConversationBinding = {
  bindingId: string;
  pluginId: string;
  pluginName?: string;
  pluginRoot: string;
  channel: string;
  accountId: string;
  conversationId: string;
  parentConversationId?: string;
  threadId?: string | number;
  boundAt: number;
  summary?: string;
  detachHint?: string;
  data?: Record<string, unknown>;
};
/** Result returned when a plugin asks to bind to a conversation. */
type PluginConversationBindingRequestResult = {
  status: "bound";
  binding: PluginConversationBinding;
} | {
  status: "pending";
  approvalId: string;
  reply: ReplyPayload$1;
} | {
  status: "error";
  message: string;
};
/** Event emitted after a pending conversation binding request is resolved. */
type PluginConversationBindingResolvedEvent = {
  status: "approved" | "denied";
  binding?: PluginConversationBinding;
  decision: PluginConversationBindingResolutionDecision;
  request: {
    summary?: string;
    detachHint?: string;
    data?: Record<string, unknown>;
    requestedBySenderId?: string;
    conversation: {
      channel: string;
      accountId: string;
      conversationId: string;
      parentConversationId?: string;
      threadId?: string | number;
    };
  };
};
//#endregion
//#region src/plugins/hook-message.types.d.ts
/** Provider-owned event before any durable channel ingress payload is written. */
type PluginHookBeforeChannelIngressEvent = {
  event: unknown;
};
type PluginHookBeforeChannelIngressResult = {
  event?: unknown;
};
type PluginHookBeforeChannelIngressContext = {
  channelId: string;
  accountId?: string;
  /** Admission and participating plugin lifetimes; propagate through awaited policy I/O. */
  signal: AbortSignal;
};
/** Ordered media fact exposed by inbound message hooks. */
type PluginHookMediaFact = MessageHookMediaFact;
/** Channel-neutral geographic fix carried by an inbound provider update. */
type PluginHookLocation = {
  latitude: number;
  longitude: number;
  accuracy?: number;
  name?: string;
  address?: string;
  source?: "pin" | "place" | "live";
  isLive?: boolean;
  livePeriodSeconds?: number;
  caption?: string;
};
/** Stable provider update identity for transport-level correlation and deduplication. */
type PluginHookProviderUpdate = {
  id: string;
  kind: string;
  messageId?: string;
  messageTimestamp?: number;
  editedTimestamp?: number;
};
/** Provider metadata plus deprecated media aliases retained during the SDK migration window. */
type PluginHookInboundMessageMetadata = Record<string, unknown> & {
  /** @deprecated Use the first `event.media` fact with a defined `path`. */
  mediaPath?: string;
  /** @deprecated Use the first `event.media` fact's `url ?? path`. */
  mediaUrl?: string;
  /** @deprecated Use the first `event.media` fact's `contentType ?? kind`. */
  mediaType?: string;
  /** @deprecated Collect defined `path` values from `event.media` in order. */
  mediaPaths?: string[];
  /** @deprecated Collect each defined `url ?? path` from `event.media` in order. */
  mediaUrls?: string[];
  /** @deprecated Collect each defined `contentType ?? kind` from `event.media` in order. */
  mediaTypes?: string[];
  /** @deprecated Use the first `event.originalMedia` fact with a defined `path`. */
  originalMediaPath?: string;
  /** @deprecated Use the first `event.originalMedia` fact's `url ?? path`. */
  originalMediaUrl?: string;
  /** @deprecated Use the first `event.originalMedia` fact's `contentType ?? kind`. */
  originalMediaType?: string;
  /** @deprecated Collect defined `path` values from `event.originalMedia` in order. */
  originalMediaPaths?: string[];
  /** @deprecated Collect each defined `url ?? path` from `event.originalMedia` in order. */
  originalMediaUrls?: string[];
  /** @deprecated Collect each defined `contentType ?? kind` from `event.originalMedia` in order. */
  originalMediaTypes?: string[];
  /** @deprecated Use `event.mediaStagingPending`. */
  mediaStagingPending?: boolean;
};
type PluginHookMessageContext = {
  channelId: string;
  accountId?: string;
  conversationId?: string;
  /**
   * Canonical session key for this conversation — the same value the agent
   * runtime sees as `params.sessionKey` for the run that produced the
   * outbound payload, and the same value `agent_end`/`llm_input`/`llm_output`
   * fire with. Plugins correlating per-turn state across `agent_end` and
   * `message_sending` rely on this equality.
   *
   * For inbound message hooks (`inbound_claim` etc.), this is the canonical
   * session for the inbound conversation as resolved by `resolveSessionKey`
   * / `deriveInboundMessageHookContext`.
   *
   * For outbound delivery hooks (`message_sending` and `message_sent`),
   * this mirrors `OutboundSessionContext.key` from the dispatch path when
   * delivery has a session attached. When the outbound path has no
   * resolvable session (e.g. internal smoke runs without
   * `OutboundSessionContext`), this field is omitted; plugins must treat
   * it as optional.
   */
  sessionKey?: string;
  /**
   * Per-turn run identifier (UUID), unique to one end-to-end agent turn:
   * stable across all LLM-call iterations, retry attempts (compaction,
   * empty-response, planning-only, etc.), and multi-payload reply chunks
   * within that turn; distinct for each new inbound user message and for
   * each cron/heartbeat/followup-triggered run.
   *
   * Generated once in `agent-runner-execution.ts`/`followup-runner.ts` via
   * `crypto.randomUUID()`. Currently populated for inbound message hooks
   * (`inbound_claim`, `message_received`) and for agent-runtime hooks that
   * already receive the run id (e.g. `agent_end`, `llm_input`, `llm_output`).
   * It is **not yet** plumbed through the outbound delivery path, so
   * plugins observing `message_sending` / `message_sent` should not rely
   * on `runId` to correlate against `agent_end`; use `sessionKey` for
   * outbound→inbound correlation today (with the caveat that it cannot
   * disambiguate concurrent turns in the same session).
   */
  runId?: string;
  messageId?: string;
  senderId?: string;
  replyToId?: string;
  replyToIdFull?: string;
  replyToBody?: string;
  replyToSender?: string;
  replyToIsQuote?: boolean;
  trace?: DiagnosticTraceContext;
  traceId?: string;
  spanId?: string;
  parentSpanId?: string;
  callDepth?: number;
};
type PluginHookInboundClaimContext = PluginHookMessageContext & {
  /** Resolved owner for session scopes whose canonical key does not encode an agent id. */
  agentId?: string;
  parentConversationId?: string;
  senderId?: string;
  messageId?: string;
  pluginBinding?: PluginConversationBinding;
};
type PluginHookInboundClaimEvent = PluginHookInboundMessageFacts & {
  body?: string;
  bodyForAgent?: string;
  transcript?: string;
  channel: string;
  accountId?: string;
  conversationId?: string;
  parentConversationId?: string;
  senderName?: string;
  senderUsername?: string;
  isGroup: boolean;
  commandAuthorized?: boolean;
  senderIsOwner?: boolean;
  wasMentioned?: boolean;
};
type PluginHookInboundMessageFacts = {
  content: string;
  timestamp?: number;
  threadId?: string | number;
  messageId?: string;
  senderId?: string;
  replyToId?: string;
  replyToIdFull?: string;
  replyToBody?: string;
  replyToSender?: string;
  replyToIsQuote?: boolean;
  sessionKey?: string;
  runId?: string;
  trace?: DiagnosticTraceContext;
  traceId?: string;
  spanId?: string;
  parentSpanId?: string;
  location?: PluginHookLocation;
  providerUpdate?: PluginHookProviderUpdate;
  /** Staged, locally usable attachments in stable source order. */
  media?: PluginHookMediaFact[];
  /** Original attachment facts when local staging has not completed yet. */
  originalMedia?: PluginHookMediaFact[];
  /** True when `originalMedia` is present but `media` is intentionally withheld pending staging. */
  mediaStagingPending?: boolean;
  metadata?: PluginHookInboundMessageMetadata;
};
type PluginHookMessageReceivedEvent = PluginHookInboundMessageFacts & {
  from: string;
};
type PluginHookMessageSendingEvent = {
  to: string;
  content: string;
  replyToId?: string | number;
  threadId?: string | number;
  metadata?: Record<string, unknown>;
};
type PluginHookMessageSendingResult = {
  content?: string;
  cancel?: boolean;
  cancelReason?: string;
  metadata?: Record<string, unknown>;
};
type PluginHookMessageSentEvent = {
  to: string;
  content: string;
  success: boolean;
  messageId?: string;
  sessionKey?: string;
  runId?: string;
  trace?: DiagnosticTraceContext;
  traceId?: string;
  spanId?: string;
  parentSpanId?: string;
  error?: string;
};
/** Message operation contracts share their provider-event and delivery types. */
type PluginMessageHookHandlerMap = {
  before_channel_ingress: AsyncPluginHook<PluginHookBeforeChannelIngressEvent, PluginHookBeforeChannelIngressContext, PluginHookBeforeChannelIngressResult>;
  message_received: AsyncPluginHook<PluginHookMessageReceivedEvent, PluginHookMessageContext>;
  message_sending: AsyncPluginHook<PluginHookMessageSendingEvent, PluginHookMessageContext, PluginHookMessageSendingResult>;
  message_sent: AsyncPluginHook<PluginHookMessageSentEvent, PluginHookMessageContext>;
};
//#endregion
//#region src/plugins/hook-reply-dispatch-event.types.d.ts
type PluginHookReplyDispatchEvent = {
  ctx: FinalizedMsgContext;
  runId?: string;
  sessionKey?: string;
  toolsAllow?: string[];
  images?: Array<{
    data: string;
    mimeType: string;
  }>;
  inboundAudio: boolean;
  sessionTtsAuto?: TtsAutoMode;
  ttsChannel?: string;
  suppressUserDelivery?: boolean;
  suppressReplyLifecycle?: boolean;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  shouldRouteToOriginating: boolean;
  originatingChannel?: string;
  originatingTo?: string;
  originatingAccountId?: string;
  originatingThreadId?: string | number;
  originatingChatType?: ChatType;
  /** @deprecated Await shouldSendToolSummariesAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  shouldSendToolSummaries: boolean;
  /** @deprecated Await shouldSendFullToolDetailsAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  shouldSendFullToolDetails: boolean;
  /** Fresh worker-backed visibility; supplied by current hosts. */
  shouldSendToolSummariesAsync?: () => Promise<boolean>;
  /** Fresh worker-backed detail visibility; supplied by current hosts. */
  shouldSendFullToolDetailsAsync?: () => Promise<boolean>;
  sendPolicy: "allow" | "deny";
  isTailDispatch?: boolean;
};
//#endregion
//#region src/plugins/hook-skill.types.d.ts
type PluginHookSkillArtifact = {
  name: string;
  skillKey: string;
  description?: string;
  skillFile: string;
  skillDir: string;
  source: string;
  revision: {
    declaredVersion?: string;
    contentSha256: string;
    treeSha256: string;
    sourceVersion?: string;
  };
};
type PluginHookSkillChangedEvent = {
  action: "created" | "updated" | "removed";
  source: "workshop" | "clawhub" | "source-install" | "upload";
  occurredAt: string;
  before?: PluginHookSkillArtifact;
  after?: PluginHookSkillArtifact;
};
type PluginHookSkillContext = {
  workspaceDir: string;
  agentId?: string;
};
//#endregion
//#region src/plugins/hook-tool-context.types.d.ts
type PluginHookToolKind = "code_mode_exec";
type PluginHookToolInputKind = "javascript" | "typescript";
/** Host-derived identity for the message requester that initiated a tool call. */
type PluginHookToolRequesterContext = {
  /** Channel/plugin id, for example `discord` or `telegram`. */
  readonly channel?: string;
  /** Channel account used by the agent when multiple accounts are configured. */
  readonly accountId?: string;
  /** Channel-scoped sender id when the host received one. */
  readonly senderId?: string;
  /** True only when the host resolved the sender as an owner. */
  readonly senderIsOwner?: boolean;
  /** Provider-native role ids when the channel supplies them. */
  readonly roleIds?: readonly string[];
};
type PluginHookToolContext = {
  agentId?: string;
  sessionKey?: string;
  sessionId?: string;
  runId?: string;
  /** Aborts when the owning tool call is cancelled. Hook timeout expiry does not abort this signal. */
  abortSignal?: AbortSignal;
  trace?: DiagnosticTraceContext;
  toolName: string;
  /** Host-authoritative discriminator for tools that intentionally share names. */
  toolKind?: PluginHookToolKind;
  /** Host-authoritative input/runtime family for tools whose payloads need policy distinction. */
  toolInputKind?: PluginHookToolInputKind;
  toolCallId?: string;
  getSessionExtension?: (namespace: string) => PluginJsonValue | undefined;
  channelId?: string;
  /**
   * Message requester for this turn. Absent for non-message runs and harnesses
   * that cannot prove requester identity. Authorization hooks should fail
   * closed when a required field is absent.
   */
  requester?: PluginHookToolRequesterContext;
  /** Run origin (for example "user", "cron", or "memory"); metadata, not authorization. */
  trigger?: string;
};
//#endregion
//#region src/plugins/host-hook-turn-types.d.ts
/** Placement for context injected into the next agent turn. */
type PluginNextTurnInjectionPlacement = "prepend_context" | "append_context";
/** Plugin request to inject text into the next turn for a session. */
type PluginNextTurnInjection = {
  sessionKey: string;
  /** Selected owner when the session key is unscoped, such as global. */
  agentId?: string;
  text: string;
  idempotencyKey?: string;
  placement?: PluginNextTurnInjectionPlacement;
  ttlMs?: number;
  metadata?: PluginJsonValue;
};
/** Stored next-turn injection after session/plugin metadata is attached. */
type PluginNextTurnInjectionRecord = Omit<PluginNextTurnInjection, "sessionKey" | "agentId"> & {
  id: string;
  pluginId: string;
  pluginName?: string;
  createdAt: number;
  placement: PluginNextTurnInjectionPlacement;
};
/** Result returned after enqueueing a next-turn injection. */
type PluginNextTurnInjectionEnqueueResult = {
  enqueued: boolean;
  id: string;
  sessionKey: string;
};
/** Event passed to plugins before an agent turn is prepared. */
type PluginAgentTurnPrepareEvent = {
  prompt: string;
  /**
   * Model-context history: fresh array/envelopes per dispatch, shared frozen transcript payloads.
   * Treat nested content as read-only; strict-mode writes to frozen leaves throw TypeError.
   * Return result fields to contribute context. Array/envelope edits stay local to this dispatch,
   * whose handlers share them in priority order; they never update core history.
   */
  messages: unknown[];
  queuedInjections: PluginNextTurnInjectionRecord[];
};
/** Plugin contribution to prepend or append context for a prepared agent turn. */
type PluginAgentTurnPrepareResult = {
  prependContext?: string;
  appendContext?: string;
};
/** Event passed to plugins that contribute heartbeat prompt context. */
type PluginHeartbeatPromptContributionEvent = {
  sessionKey?: string;
  agentId?: string;
  heartbeatName?: string;
};
/** Plugin contribution to heartbeat prompt context. */
type PluginHeartbeatPromptContributionResult = PluginAgentTurnPrepareResult;
//#endregion
//#region src/plugins/install-security-scan.types.d.ts
/** Skill install metadata shape passed into shared install policy evaluation. */
type SkillInstallSpecMetadata = SkillInstallSpec;
//#endregion
//#region src/plugins/session-end-transcript.d.ts
type PluginHookEndedTranscriptUnavailableReason = "conversation-access-required" | "no-stable-cutoff" | "incognito-deleted" | "archive-unavailable" | "unsupported-source";
type PluginHookEndedTranscriptReadOptions = {
  maxMessages: number;
  maxBytes: number;
};
type PluginHookEndedTranscriptReadResult = {
  messages: readonly unknown[];
  totalMessages: number;
  truncated: boolean;
};
type PluginHookEndedTranscript = {
  available: false;
  reason: PluginHookEndedTranscriptUnavailableReason;
} | {
  available: true;
  readTail(options: PluginHookEndedTranscriptReadOptions): Promise<PluginHookEndedTranscriptReadResult>;
};
type PluginHookSessionContext = {
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
  /** Undefined on older hosts. Current hosts publish a reader or an explicit reason. */
  endedTranscript?: PluginHookEndedTranscript;
};
//#endregion
//#region src/plugins/hook-types.d.ts
type PluginHookName = keyof PluginHookHandlerMap;
type PluginHookChannelPairingRequestedEvent = {
  /** Channel that created the pending pairing request. */
  channel: string;
  /** Provider account ID for multi-account channel setups. */
  accountId?: string;
  /** Channel-scoped sender ID awaiting operator approval. */
  senderId: string;
  /** Short-lived code accepted by `openclaw pairing approve`. */
  code: string;
  /** Sender-supplied channel metadata for operator notification/audit. Treat as untrusted. */
  metadata?: Record<string, string | undefined>;
};
type PluginHookChannelPairingContext = {
  channelId: string;
  accountId?: string;
  senderId: string;
};
declare const PLUGIN_HOOK_AGENT_TRIGGERS: readonly ["cron", "heartbeat", "user"];
type PluginHookAgentTrigger = (typeof PLUGIN_HOOK_AGENT_TRIGGERS)[number];
type PluginHookReplyDispatchKind = "agent" | "acp";
type PluginToolMatcher = readonly [string, ...string[]];
type PluginHookRegistrationOptions<K extends PluginHookName> = {
  priority?: number;
  registrationId?: string;
  timeoutMs?: number;
} & (K extends "before_agent_reply" ? {
  /** Host-enforced turn triggers that may invoke this reply hook. */
  eligibleTriggers?: readonly [PluginHookAgentTrigger, ...PluginHookAgentTrigger[]];
} : {
  eligibleTriggers?: never;
}) & (K extends "reply_dispatch" ? {
  /** Host-enforced dispatch paths that may invoke this hook; unknown paths remain eligible. */
  eligibleDispatchKinds?: readonly [PluginHookReplyDispatchKind, ...PluginHookReplyDispatchKind[]];
} : {
  eligibleDispatchKinds?: never;
}) & (K extends "before_tool_call" | "after_tool_call" ? {
  matcher?: PluginToolMatcher;
} : {
  matcher?: never;
}) & (K extends "before_prompt_build" ? {
  /** Run only after the host has finalized the turn's policy-filtered tool surface. */
  requiresToolAuthority?: true;
} : {
  requiresToolAuthority?: never;
});
type PluginHookUsage = Pick<NormalizedUsage, "input" | "output" | "cacheRead" | "cacheWrite" | "total">;
type PluginHookBeforeAgentReplyEvent = {
  cleanedBody: string;
};
type PluginHookBeforeAgentReplyResult = {
  handled: boolean;
  reply?: ReplyPayload$1;
  reason?: string;
};
type PluginHookLlmInputEvent = {
  runId: string;
  sessionId: string;
  provider: string;
  model: string;
  systemPrompt?: string;
  prompt: string;
  historyMessages: unknown[];
  imagesCount: number;
  tools?: unknown[];
};
type PluginHookModelCallBaseEvent = PluginHookContextWindow & {
  runId: string;
  callId: string;
  sessionKey?: string;
  sessionId?: string;
  provider: string;
  model: string;
  api?: string;
  transport?: string;
};
type PluginHookModelCallStartedEvent = PluginHookModelCallBaseEvent;
type PluginHookModelCallEndedEvent = PluginHookModelCallBaseEvent & {
  durationMs: number;
  outcome: "completed" | "error";
  errorCategory?: string;
  failureKind?: "aborted" | "connection_closed" | "connection_reset" | "terminated" | "timeout";
  requestPayloadBytes?: number;
  responseStreamBytes?: number;
  timeToFirstByteMs?: number;
  upstreamRequestIdHash?: string;
};
type PluginHookLlmOutputEvent = PluginHookContextWindow & {
  runId: string;
  sessionId: string;
  provider: string;
  model: string;
  /**
   * Fully resolved provider/model ref used for the call.
   *
   * This intentionally keeps the provider prefix so operator tooling can
   * distinguish e.g. openai/gpt-5.4 from codex/gpt-5.4 even when display
   * names collapse to just the model id.
   */
  resolvedRef?: string;
  /**
   * Harness/backend responsible for the model loop. Kept separate from
   * `resolvedRef` so provider/model consumers keep a stable parse contract.
   */
  harnessId?: string;
  /** The original user prompt that produced this output. */
  prompt?: string;
  assistantTexts: string[];
  lastAssistant?: unknown;
  usage?: PluginHookUsage;
  /**
   * Requested reasoning/think effort for this call (provider think level, e.g.
   * "off" | "low" | "medium" | "high"). Lets a passive footer show the mode the
   * user is actually running without re-deriving it.
   */
  reasoningEffort?: string;
  /** Whether fast mode was active for this call. */
  fastMode?: boolean;
};
type PluginHookAgentEndEvent = {
  runId?: string;
  messages: unknown[];
  success: boolean;
  error?: string;
  durationMs?: number;
};
type PluginHookBeforeAgentFinalizeEvent = {
  runId?: string;
  sessionId: string;
  sessionKey?: string;
  turnId?: string;
  provider?: string;
  model?: string;
  cwd?: string;
  transcriptPath?: string;
  stopHookActive: boolean;
  lastAssistantMessage?: string;
  messages?: unknown[];
};
type PluginHookBeforeAgentFinalizeResult = {
  /**
   * continue: accept normal finalization.
   * revise: block finalization and ask the harness for another model pass.
   * finalize: force finalization even if another hook requested revision.
   */
  action?: "continue" | "revise" | "finalize";
  reason?: string;
  retry?: {
    instruction: string;
    idempotencyKey?: string;
    maxAttempts?: number;
  };
};
type PluginHookBeforeCompactionEvent = {
  messageCount: number;
  compactingCount?: number;
  tokenCount?: number;
  messages?: unknown[];
  sessionFile?: string;
};
type PluginHookBeforeResetEvent = {
  sessionFile?: string;
  messages?: unknown[];
  reason?: string;
};
type PluginHookAfterCompactionEvent = {
  messageCount: number;
  tokenCount?: number;
  compactedCount: number;
  sessionFile?: string;
  /** Physical session generation replaced by this compaction, when it rotated. */
  previousSessionId?: string;
};
type PluginHookInboundClaimResult = {
  handled: boolean;
  reply?: ReplyPayload$1;
};
type PluginHookBeforeDispatchEvent = {
  messageId?: string;
  content: string;
  body?: string;
  channel?: string;
  sessionKey?: string;
  senderId?: string;
  replyToId?: string;
  replyToIdFull?: string;
  replyToBody?: string;
  replyToSender?: string;
  replyToIsQuote?: boolean;
  isGroup?: boolean;
  timestamp?: number;
};
type PluginHookBeforeDispatchContext = {
  messageId?: string;
  channelId?: string;
  accountId?: string;
  conversationId?: string;
  sessionKey?: string;
  senderId?: string;
  replyToId?: string;
  replyToIdFull?: string;
  replyToBody?: string;
  replyToSender?: string;
  replyToIsQuote?: boolean;
};
type PluginHookBeforeDispatchResult = {
  handled: boolean;
  text?: string;
};
type PluginHookReplyDispatchContext = {
  /** Host-resolved dispatch path; omitted when the caller cannot establish it. */
  dispatchKind?: PluginHookReplyDispatchKind;
  cfg: OpenClawConfig;
  dispatcher: ReplyDispatcher;
  abortSignal?: AbortSignal;
  onReplyStart?: () => Promise<void> | void;
  /** @deprecated Use onPreparedAgentRunStart. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  onAgentRunStart?: GetReplyOptions["onAgentRunStart"];
  onPreparedAgentRunStart?: GetReplyOptions["onPreparedAgentRunStart"];
  /** Host-owned input custody; adopt before backend submission and propagate refusal. */
  turnAdoption?: {
    adopt: () => Promise<void>;
    assertCurrent: () => void;
  };
  userTurnTranscriptRecorder?: GetReplyOptions["userTurnTranscriptRecorder"];
  /** Host-owned display facts applied before the assistant transcript is published. */
  prepareAssistantTranscriptMessage?: PrepareAssistantTranscriptMessage;
  recordProcessed: (outcome: "completed" | "skipped" | "error", opts?: {
    reason?: string;
    error?: string;
  }) => void;
  markIdle: (reason: string) => void;
};
type PluginHookReplyDispatchResult = {
  handled: boolean;
  queuedFinal: boolean;
  counts: Record<ReplyDispatchKind, number>;
};
/**
 * Per-turn execution state for the outbound reply, available to every harness
 * (embedded, CLI, Codex app-server) — sourced from the unified `runResult.meta`
 * at dispatch, not from the harness-specific `llm_output` hook. Lets a plugin
 * render a passive per-response footer without re-deriving run state.
 */
type PluginHookReplyUsageState = {
  provider?: string;
  model?: string;
  /** Resolved provider/model ref actually used (keeps the provider prefix). */
  resolvedRef?: string;
  /** Requested reasoning/think effort (e.g. "off" | "low" | "medium" | "high"). */
  reasoningEffort?: string;
  fastMode?: boolean;
  /** True when a model fallback was used for this turn. */
  fallbackUsed?: boolean;
  /** Owning agent + session for this reply. */
  agentId?: string;
  sessionId?: string;
  /** Chat surface kind (e.g. "direct" | "group"). */
  chatType?: string;
  /** Credential mode the turn ran under (e.g. "oauth" | "api_key"). */
  authMode?: string;
  /** Session model-override source, when a non-default model was pinned. */
  overrideSource?: string;
  /** Provider/model ref requested for the turn (vs resolvedRef actually used). */
  requested?: string;
  /** Estimated cost of this turn in USD, when a cost table is configured. */
  turnUsd?: number;
  /** Wall-clock duration of the turn in milliseconds. */
  durationMs?: number;
  /** Owning agent's configured identity (name/emoji/avatar), when set. */
  identity?: {
    name?: string;
    emoji?: string;
    avatar?: string;
  };
  compactionCount?: number;
  /** Effective context-token budget after model/config/agent caps. */
  contextTokenBudget?: number;
  /**
   * Actual context-window occupancy at the END of the turn — the final model
   * call's prompt tokens, NOT the per-turn aggregate. This is the value
   * `context.used_tokens` / `context.pct_used` must use: the aggregate prompt
   * total over a multi-call tool loop overstates occupancy (often beyond the
   * window). Absent on harnesses that don't report it (the contract then falls
   * back to the aggregate prompt total, which is correct for single-call turns).
   */
  contextUsedTokens?: number;
  usage?: PluginHookUsage;
  /**
   * Usage from the FINAL model call of the turn only — vs `usage`, which is the
   * turn aggregate summed across every tool-loop call. Lets a footer render the
   * last exchange's i/o + cache instead of the whole turn. Absent on harnesses
   * that don't report per-call usage.
   */
  lastUsage?: PluginHookUsage;
};
type PluginHookReplyPayloadSendingEvent = {
  payload: PluginHookReplyPayload;
  kind: ReplyDispatchKind;
  channel?: string;
  sessionKey?: string;
  runId?: string;
  /**
   * Per-turn usage snapshot for live dispatcher delivery. Absent on durable
   * delivery/replay paths, and whenever no exact run correlation is available.
   */
  usageState?: PluginHookReplyUsageState;
};
type PluginHookReplyPayload = Omit<ReplyPayload$1, "trustedLocalMedia">;
type PluginHookReplyPayloadSendingContext = PluginHookMessageContext;
type PluginHookReplyPayloadSendingResult = {
  payload?: PluginHookReplyPayload;
  cancel?: boolean;
  reason?: string;
};
type PluginHookBeforeToolCallEvent = {
  toolName: string;
  params: Record<string, unknown>;
  /** Host-authoritative discriminator for tools that intentionally share names. */
  toolKind?: PluginHookToolKind;
  /** Host-authoritative input/runtime family for tools whose payloads need policy distinction. */
  toolInputKind?: PluginHookToolInputKind;
  runId?: string;
  toolCallId?: string;
  /**
   * Optional best-effort destination path hints the host derived from `params`
   * for well-known tool envelopes (e.g. `apply_patch`).
   *
   * This is a convenience hint, not an authoritative parse result: the host's
   * extractor may be intentionally lenient and can return paths for malformed
   * or partial envelopes. Plugins may use `derivedPaths` as a fast path, but
   * should parse and validate `params` themselves when correctness or policy
   * decisions depend on the exact set of affected paths. Absent for tools the
   * host does not know how to derive paths for.
   */
  derivedPaths?: readonly string[];
};
type PluginHookAfterToolCallEvent = {
  toolName: string;
  params: Record<string, unknown>;
  runId?: string;
  toolCallId?: string;
  result?: unknown;
  error?: string;
  durationMs?: number;
};
type PluginHookToolResultPersistContext = {
  agentId?: string;
  sessionKey?: string;
  toolName?: string;
  toolCallId?: string;
};
type PluginHookToolResultPersistEvent = {
  toolName?: string;
  toolCallId?: string;
  message: AgentMessage;
  isSynthetic?: boolean;
};
type PluginHookToolResultPersistResult = {
  message?: AgentMessage;
};
type PluginHookBeforeMessageWriteEvent = {
  message: AgentMessage;
  sessionKey?: string;
  agentId?: string;
};
type PluginHookBeforeMessageWriteResult = {
  block?: boolean;
  message?: AgentMessage;
};
type PluginHookSessionStartEvent = {
  sessionId: string;
  sessionKey?: string;
  resumedFrom?: string;
};
type PluginHookSessionEndReason = "new" | "reset" | "idle" | "daily" | "compaction" | "deleted" | "shutdown" | "restart" | "unknown";
type PluginHookSessionEndEvent = {
  sessionId: string;
  sessionKey?: string;
  messageCount: number;
  durationMs?: number;
  reason?: PluginHookSessionEndReason;
  sessionFile?: string;
  transcriptArchived?: boolean;
  nextSessionId?: string;
  nextSessionKey?: string;
};
type PluginHookSubagentContext = {
  runId?: string;
  childSessionKey?: string;
  requesterSessionKey?: string;
};
type PluginHookSubagentTargetKind = "subagent" | "acp";
type PluginHookSubagentRequester = {
  channel?: string;
  accountId?: string;
  to?: string;
  threadId?: string | number;
  /** Native source channel/conversation id, when distinct from the routable target. */
  channelId?: string | number;
  /** Native source message that initiated the parent run, when available. */
  messageId?: string | number;
};
type PluginHookSubagentSpawnBase = {
  childSessionKey: string;
  agentId: string;
  label?: string;
  mode: "run" | "session";
  requester?: PluginHookSubagentRequester;
  threadRequested: boolean;
};
type PluginHookSubagentDeliveryTargetEvent = {
  childSessionKey: string;
  requesterSessionKey: string;
  requesterOrigin?: {
    channel?: string;
    accountId?: string;
    to?: string;
    threadId?: string | number;
  };
  childRunId?: string;
  spawnMode?: "run" | "session";
  expectsCompletionMessage: boolean;
};
/**
 * @deprecated Core route projection resolves subagent delivery targets from
 * `SessionBindingRecord` and channel `resolveDeliveryTarget`. This hook result
 * remains for plugin compatibility during the transition.
 */
type PluginHookSubagentDeliveryTargetResult = {
  origin?: {
    channel?: string;
    accountId?: string;
    to?: string;
    threadId?: string | number;
  };
};
type PluginHookSubagentSpawnedEvent = PluginHookSubagentSpawnBase & {
  runId: string;
  /** Fully resolved provider/model ref applied to the spawned child session. */
  resolvedModel?: string;
  /** Provider prefix parsed from resolvedModel when the ref includes one. */
  resolvedProvider?: string;
};
/** Portable channel presentation signal for one background child run. */
type PluginHookSubagentProgressEvent = {
  phase: "started";
  runId: string;
  childSessionKey: string;
  requester?: PluginHookSubagentRequester;
} | {
  phase: "ended";
  runId: string;
  childSessionKey: string;
  outcome: "ok" | "error" | "timeout" | "killed" | "unknown";
  requester?: PluginHookSubagentRequester;
};
type PluginHookSubagentEndedEvent = {
  targetSessionKey: string;
  targetKind: PluginHookSubagentTargetKind;
  reason: string;
  sendFarewell?: boolean;
  accountId?: string;
  runId?: string;
  endedAt?: number;
  outcome?: "ok" | "error" | "timeout" | "killed" | "reset" | "deleted";
  error?: string;
};
type PluginInstallTargetType = "skill" | "plugin";
type PluginInstallSourcePathKind = "file" | "directory";
type PluginInstallFinding = {
  ruleId: string;
  severity: "info" | "warn" | "critical";
  file: string;
  line: number;
  message: string;
};
type PluginHookBeforeInstallRequest = {
  kind: InstallPolicyRequestKind;
  mode: "install" | "update";
  requestedSpecifier?: string;
};
/** @public Part of the stable native plugin contract facade. */
type PluginHookBeforeInstallBuiltinScan = {
  status: "ok" | "error";
  scannedFiles: number;
  critical: number;
  warn: number;
  info: number;
  findings: PluginInstallFinding[];
  error?: string;
};
type PluginHookBeforeInstallSkill = {
  installId: string;
  installSpec?: SkillInstallSpecMetadata;
};
type PluginHookBeforeInstallPlugin = {
  pluginId: string;
  contentType: "bundle" | "package" | "file";
  packageName?: string;
  manifestId?: string;
  version?: string;
  extensions?: string[];
};
type PluginHookBeforeInstallContext = {
  targetType: PluginInstallTargetType;
  requestKind: InstallPolicyRequestKind;
  origin?: string;
};
type PluginHookBeforeInstallEvent = {
  targetType: PluginInstallTargetType;
  targetName: string;
  sourcePath: string;
  sourcePathKind: PluginInstallSourcePathKind;
  origin?: string;
  request: PluginHookBeforeInstallRequest;
  builtinScan: PluginHookBeforeInstallBuiltinScan;
  skill?: PluginHookBeforeInstallSkill;
  plugin?: PluginHookBeforeInstallPlugin;
};
type PluginHookBeforeInstallResult = {
  findings?: PluginInstallFinding[];
  block?: boolean;
  blockReason?: string;
};
/** Result type for before_agent_run. Returns pass/block or void (= pass). */
type PluginHookBeforeAgentRunResult = InputGateDecision | void;
type PluginHookResolveExecEnvEvent = {
  sessionKey?: string;
  toolName: "exec";
  host: "gateway" | "sandbox" | "node";
};
type PluginHookResolveExecEnvContext = PluginHookAgentContext;
type PluginHookHandlerMap = PluginMessageHookHandlerMap & {
  agent_turn_prepare: AsyncPluginHook<PluginAgentTurnPrepareEvent, PluginHookAgentContext, PluginAgentTurnPrepareResult>;
  before_model_resolve: AsyncPluginHook<PluginHookBeforeModelResolveEvent, PluginHookAgentContext, PluginHookBeforeModelResolveResult>;
  before_prompt_build: AsyncPluginHook<PluginHookBeforePromptBuildEvent, PluginHookAgentContext, PluginHookBeforePromptBuildResult>;
  before_agent_reply: AsyncPluginHook<PluginHookBeforeAgentReplyEvent, PluginHookAgentContext, PluginHookBeforeAgentReplyResult>;
  model_call_started: AsyncPluginHook<PluginHookModelCallStartedEvent, PluginHookAgentContext>;
  model_call_ended: AsyncPluginHook<PluginHookModelCallEndedEvent, PluginHookAgentContext>;
  llm_input: AsyncPluginHook<PluginHookLlmInputEvent, PluginHookAgentContext>;
  llm_output: AsyncPluginHook<PluginHookLlmOutputEvent, PluginHookAgentContext>;
  before_agent_finalize: AsyncPluginHook<PluginHookBeforeAgentFinalizeEvent, PluginHookAgentContext, PluginHookBeforeAgentFinalizeResult>;
  agent_end: AsyncPluginHook<PluginHookAgentEndEvent, PluginHookAgentContext>;
  before_compaction: AsyncPluginHook<PluginHookBeforeCompactionEvent, PluginHookAgentContext>;
  after_compaction: AsyncPluginHook<PluginHookAfterCompactionEvent, PluginHookAgentContext>;
  before_reset: AsyncPluginHook<PluginHookBeforeResetEvent, PluginHookAgentContext>;
  inbound_claim: AsyncPluginHook<PluginHookInboundClaimEvent, PluginHookInboundClaimContext, PluginHookInboundClaimResult>;
  channel_pairing_requested: AsyncPluginHook<PluginHookChannelPairingRequestedEvent, PluginHookChannelPairingContext>;
  before_dispatch: AsyncPluginHook<PluginHookBeforeDispatchEvent, PluginHookBeforeDispatchContext, PluginHookBeforeDispatchResult>;
  reply_dispatch: AsyncPluginHook<PluginHookReplyDispatchEvent, PluginHookReplyDispatchContext, PluginHookReplyDispatchResult>;
  reply_payload_sending: AsyncPluginHook<PluginHookReplyPayloadSendingEvent, PluginHookReplyPayloadSendingContext, PluginHookReplyPayloadSendingResult>;
  before_tool_call: AsyncPluginHook<PluginHookBeforeToolCallEvent, PluginHookToolContext, PluginHookBeforeToolCallResult>;
  after_tool_call: AsyncPluginHook<PluginHookAfterToolCallEvent, PluginHookToolContext>;
  tool_result_persist: (event: PluginHookToolResultPersistEvent, ctx: PluginHookToolResultPersistContext) => PluginHookToolResultPersistResult | void;
  before_message_write: (event: PluginHookBeforeMessageWriteEvent, ctx: {
    agentId?: string;
    sessionKey?: string;
  }) => PluginHookBeforeMessageWriteResult | void;
  session_start: AsyncPluginHook<PluginHookSessionStartEvent, PluginHookSessionContext>;
  session_end: AsyncPluginHook<PluginHookSessionEndEvent, PluginHookSessionContext>;
  subagent_delivery_target: AsyncPluginHook<PluginHookSubagentDeliveryTargetEvent, PluginHookSubagentContext, PluginHookSubagentDeliveryTargetResult>;
  subagent_spawned: AsyncPluginHook<PluginHookSubagentSpawnedEvent, PluginHookSubagentContext>;
  subagent_progress: AsyncPluginHook<PluginHookSubagentProgressEvent, PluginHookSubagentContext>;
  subagent_ended: AsyncPluginHook<PluginHookSubagentEndedEvent, PluginHookSubagentContext>;
  gateway_start: AsyncPluginHook<PluginHookGatewayStartEvent, PluginHookGatewayContext>;
  gateway_stop: AsyncPluginHook<PluginHookGatewayStopEvent, PluginHookGatewayContext>;
  heartbeat_prompt_contribution: AsyncPluginHook<PluginHeartbeatPromptContributionEvent, PluginHookAgentContext, PluginHeartbeatPromptContributionResult>;
  cron_reconciled: AsyncPluginHook<PluginHookCronReconciledEvent, PluginHookCronReconciledContext>;
  cron_changed: AsyncPluginHook<PluginHookCronChangedEvent, PluginHookGatewayContext>;
  skill_changed: AsyncPluginHook<PluginHookSkillChangedEvent, PluginHookSkillContext>;
  before_install: AsyncPluginHook<PluginHookBeforeInstallEvent, PluginHookBeforeInstallContext, PluginHookBeforeInstallResult>;
  before_agent_run: (event: PluginHookBeforeAgentRunEvent, ctx: PluginHookAgentContext) => Promise<PluginHookBeforeAgentRunResult> | PluginHookBeforeAgentRunResult;
  resolve_exec_env: AsyncPluginHook<PluginHookResolveExecEnvEvent, PluginHookResolveExecEnvContext, Record<string, string>>;
};
type PluginHookRegistration<K extends PluginHookName = PluginHookName> = {
  pluginId: string;
  registrationId?: string;
  hookName: K;
  handler: PluginHookHandlerMap[K];
  matcher?: PluginToolMatcher;
  priority?: number;
  timeoutMs?: number;
  eligibleTriggers?: readonly PluginHookAgentTrigger[];
  eligibleDispatchKinds?: readonly PluginHookReplyDispatchKind[];
  requiresToolAuthority?: true;
  /** Host-resolved transcript authority. Never infer this again from plugin identity. */
  conversationAccessAllowed?: true;
  source: string;
};
//#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<void>;
  /**
   * When set, after every successful `patchSessionExtension` the projected
   * value is mirrored to `SessionEntry[<slotKey>]` 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;
  matcher?: PluginToolMatcher;
  evaluate: (event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext) => PluginToolPolicyDecision | void | Promise<PluginToolPolicyDecision | void>;
};
type PluginToolMetadataRegistration = {
  toolName: string;
  displayName?: string;
  description?: string;
  risk?: "low" | "medium" | "high";
  tags?: string[];
};
type PluginControlUiTabGroup = "control" | "agent";
type PluginControlUiDescriptor = {
  id: string;
  /** "tab" adds a sidebar tab; "widget" advertises a trusted dashboard renderer. */
  /** Required for link-reader surfaces; passive models rendered by the host, never plugin JS. */
  linkReader?: ControlUiLinkReaderMetadata;
  label: string;
  description?: string;
  /** Bundled plugins may claim their matching native route as `route:<pluginId>`. */
  placement?: string;
  /** Optional single-segment Control UI address for a tab; does not register an HTTP route. */
  slug?: string;
  schema?: PluginJsonValue;
  requiredScopes?: OperatorScope[];
  /** Icon name hint for tab descriptors; unknown names fall back to a generic icon. */
  icon?: string;
  /**
   * Gateway HTTP path (e.g. /plugins/<id>/panel) rendered in a sandboxed frame
   * when the Control UI has no bundled view for this tab.
   */
  path?: string;
  /** Sidebar group for tab descriptors; defaults to "control". */
  group?: PluginControlUiTabGroup;
  /** Sort order among plugin tabs; lower renders first. */
  order?: number;
} & ({
  surface: "inline";
  version: number;
} | {
  surface: "session" | "tool" | "run" | "settings" | "tab" | "widget" | "link-reader";
  version?: never;
});
type PluginSessionActionContext = {
  pluginId: string;
  actionId: string;
  sessionKey?: string;
  agentId?: string;
  payload?: PluginJsonValue;
  client?: {
    connId?: string;
    scopes: string[];
    /**
     * Live check: whether the caller's current operator role allows this agent.
     * Re-evaluated on every call, so check it right before reading agent data.
     */
    allowsAgent?: (agentId: string) => boolean;
    /**
     * Live check: whether several people currently share this Gateway, so admin
     * scope distinguishes the owner. Re-evaluated on every call.
     */
    isSharedGateway?: () => boolean;
    /**
     * Live check: throws once this caller's request authority has ended, for
     * example when the connection closes or its grant is revoked. Pass it as
     * the config writer's `writeOptions.assertCurrent` before persisting.
     */
    assertCurrent?: () => void;
  };
};
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<PluginSessionActionResult | void>;
};
type PluginRuntimeLifecycleRegistration = {
  id: string;
  description?: string;
  /**
   * Releases this registration's resources after an owned inspection or ephemeral prepared runtime.
   * Raw loaders do not invoke this callback. Host cleanup notifications stay separate.
   */
  dispose?: () => void | Promise<void>;
  cleanup?: (ctx: {
    reason: PluginHostCleanupReason;
    sessionKey?: string;
    runId?: string;
  }) => void | Promise<void>;
};
type PluginAgentEventSubscriptionRegistration = {
  id: string;
  description?: string;
  streams?: AgentEventStream[];
  phases?: string[];
  payload?: "full" | "metadata";
  handle: (event: AgentEventPayload, ctx: {
    getRunContext: <T extends PluginJsonValue = PluginJsonValue>(namespace: string) => T | undefined;
    setRunContext: (namespace: string, value: PluginJsonValue) => void;
    clearRunContext: (namespace?: string) => void;
  }) => void | Promise<void>;
};
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<void>;
};
type PluginSessionSchedulerJobHandle = {
  id: string;
  pluginId: string;
  sessionKey: string;
  kind: string;
};
type PluginSessionAttachmentFile = {
  path: string;
};
type PluginAttachmentChannelHints = {
  parseMode?: "HTML";
  silent?: boolean;
  /** Require host detection to match this MIME before forcing document delivery. */
  forceDocumentMime?: string;
  threadId?: string | number;
  /** @deprecated Put portable attachment hints directly on `channelHints`. */
  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;
  };
  /** @deprecated Use `channelHints.threadId`. */
  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/shared/fast-mode.d.ts
type FastModeSource = "session" | "agent" | "config" | "default";
type FastModeAutoProgressState = {
  offAnnounced: boolean;
  resetAnnounced: boolean;
};
declare function resolveFastModeForElapsed(params: {
  mode?: FastMode;
  startedAtMs: number;
  fastAutoOnSeconds?: number;
  nowMs?: number;
}): {
  mode: FastMode | undefined;
  enabled: boolean;
  elapsedSeconds: number;
  fastAutoOnSeconds: number;
};
declare function formatFastModeAutoProgressText(params: {
  enabled: boolean;
  elapsedSeconds: number;
  fastAutoOnSeconds?: number;
}): string;
declare function formatFastModeStatusValue(params: {
  mode: FastMode | undefined;
  fastAutoOnSeconds?: number;
}): string;
declare function formatFastModeCommandOptions(params?: {
  fastAutoOnSeconds?: number;
}): string;
declare function formatFastModeSourceSuffix(source: FastModeSource | undefined): string;
declare function formatFastModeCurrentStatus(params: {
  mode: FastMode | undefined;
  source?: FastModeSource;
  fastAutoOnSeconds?: number;
  label?: string;
}): string;
//#endregion
//#region src/shared/session-types.d.ts
/** Runtime selection metadata for an agent row. */
type GatewayAgentRuntime = NonNullable<AgentSummary["agentRuntime"]>;
/** Thinking-level option exposed to UI clients. */
type GatewayThinkingLevelOption = NonNullable<AgentSummary["thinkingLevels"]>[number];
type GatewayContextWindowOption = NonNullable<ModelChoice["contextWindows"]>[number];
/** Assignable identity returned by the complete session-owner facet. */
type SessionOwnerFacetIdentity = SessionsAssignOwnerParams["owner"] & Pick<SessionCreatedActor$1, "label" | "avatarUrl" | "identity">;
/** Per-session Control UI face preference carried by session list rows. */
type SessionBoardFace = "chat" | "dashboard";
//#endregion
//#region src/gateway/server-model-catalog.types.d.ts
/** Catalog entries and policy come from the same completed prepared generation. */
type PreparedGatewayModelCatalog = {
  entries: ModelCatalogEntry[];
  routeVariants?: ModelCatalogEntry[];
  pluginRegistry?: ProviderThinkingRegistry;
};
type PreparedGatewayModelCatalogReadResult = PromiseSettledResult<PreparedGatewayModelCatalog | undefined>;
type GatewayModelCatalogSnapshot = ModelCatalogSnapshot & {
  agentId: string;
  agentDir: string;
  catalogComplete: boolean;
  workspaceDir: string;
  config: OpenClawConfig;
};
//#endregion
//#region src/gateway/session-utils.types.d.ts
/**
 * The child's current registry run. `paused` is a yielded run awaiting a continuation;
 * its `status` stays the terminal-looking value older clients already render.
 */
type SubagentRunState = "active" | "paused" | "interrupted" | "historical";
type GatewaySessionRow = Omit<SessionRow, "archivedBy" | "updatedAt" | "worktree"> & {
  worktree?: SessionEntry["worktree"];
  category?: string;
  subject?: string;
  groupChannel?: string;
  space?: string;
  origin?: Omit<SessionOrigin, "avatar">;
  updatedAt: number | null;
  archivedBy?: SessionEntry["archivedBy"];
  agentStatus?: SessionEntry["agentStatus"];
  observerDigest?: Pick<SessionObserverDigest, "agentId" | "runId" | "headline" | "health" | "updatedAt" | "revision">;
  placement?: SessionPlacement;
  placementMove?: SessionPlacementMove;
  systemSent?: boolean;
  abortedLastRun?: boolean;
  thinkingLevel?: string;
  contextWindow?: string;
  contextWindows?: GatewayContextWindowOption[];
  contextWindowDefault?: string;
  thinkingLevels?: GatewayThinkingLevelOption[];
  thinkingOptions?: string[];
  thinkingDefault?: string;
  cyberAccessProgram?: SessionEntry["cyberAccessProgram"];
  fastMode?: FastMode;
  effectiveFastMode?: FastMode;
  effectiveFastModeSource?: FastModeSource;
  fastAutoOnSeconds?: number;
  verboseLevel?: string;
  traceLevel?: string;
  reasoningLevel?: string;
  /** Configured agent or global reasoning default inherited when reasoningLevel is unset. */
  reasoningDefault?: "on" | "off" | "stream";
  elevatedLevel?: string;
  sendPolicy?: "allow" | "deny";
  goal?: SessionGoal;
  hasActiveRun?: boolean;
  activeRunIds?: string[];
  hasAutomation?: boolean;
  subagentRunState?: SubagentRunState;
  hasActiveSubagentRun?: boolean;
  startedAt?: number;
  endedAt?: number;
  runtimeMs?: number;
  responseUsage?: "on" | "off" | "tokens" | "full";
  effectiveResponseUsage?: "on" | "off" | "tokens" | "full";
  queueMode?: QueueMode;
  effectiveQueueMode?: QueueMode;
  modelSelectionLocked?: boolean;
  runtimeSelectionLocked?: boolean;
  agentRuntime?: GatewayAgentRuntime;
  contextBudgetStatus?: SessionEntry["contextBudgetStatus"];
  deliveryContext?: DeliveryContext;
  lastChannel?: string;
  lastTo?: string;
  lastAccountId?: string;
  lastThreadId?: string | number;
  pluginExtensions?: PluginSessionExtensionProjection[];
};
/**
 * Per-agent completed model catalogs for a session listing. Scoped listings
 * carry exactly one agent's catalog; unscoped listings carry one per configured
 * agent so row projections stay owner-scoped.
 */
type SessionListModelCatalog = ReadonlyMap<string, PreparedGatewayModelCatalog | undefined>;
//#endregion
//#region src/config/sessions/combined-store.types.d.ts
type ResolvedGatewaySessionStoreTargets = {
  groupDiscovery?: ReadonlyMap<string, {
    agentId: string;
    order: number;
  }>;
  configuredAgentIds?: ReadonlySet<string>;
  defaultAgentId: string;
  diagnostics: readonly string[];
  durableStorePath?: string;
  durableTargets: ReadonlyArray<SessionStoreTarget>;
  incognitoTargets: ReadonlyArray<SessionStoreTarget>;
  physicalTargets: ReadonlyMap<string, SessionStoreTarget>;
  requestedAgentId?: string;
  preparedAgentIds?: Set<string>;
  sharedStoreRowOwner?: {
    agentId: string;
    target: SessionStoreTarget;
  };
  storeConfig?: string;
};
type CombinedSessionStoreScopeTargets = ReadonlyMap<string, ResolvedGatewaySessionStoreTargets | Error>;
//#endregion
//#region src/gateway/session-transcript-derived-readers.d.ts
type SessionTranscriptUsageSnapshot = {
  modelProvider?: string;
  model?: string;
  inputTokens?: number;
  outputTokens?: number;
  cacheRead?: number;
  cacheWrite?: number;
  contextUsage?: ContextUsage$1;
  usageReport?: UsageLike["usageReport"];
  totalTokens?: number;
  totalTokensFresh?: boolean;
  costUsd?: number;
};
//#endregion
//#region src/config/sessions/session-row-facts.types.d.ts
/** Exact database facts shared by durable row readers and the incognito actor. */
type SessionRowDatabaseFacts = SessionEntrySummary & {
  hasBoard: boolean;
  activitySummaryWatermark?: SessionTranscriptWatermark;
  /** Undefined needs backfill; null is a completed, empty bounded projection. */
  transcriptPreview?: string | null;
  transcriptAssistantMessage: SessionRowAssistantMessageFact;
  transcriptTerminalModel?: SessionTranscriptTerminalModel | null;
};
//#endregion
//#region src/storage/types.d.ts
/** Plugin-provided transport for one kind of storage location. */
type StorageProvider = {
  id: string;
  label: string;
  /** Return a user-facing settings error, or undefined when valid. */
  validateSettings?: (settings: Readonly<Record<string, unknown>>) => string | undefined;
  /** Pure, synchronous, non-secret display target from settings; no I/O or secret resolution. */
  describeTarget?: (settings: Readonly<Record<string, unknown>>) => string | undefined;
  open: (params: StorageProviderOpenParams) => Promise<StorageBackend>;
};
type StorageProviderOpenParams = {
  locationName: string;
  settings: Readonly<Record<string, unknown>>;
  /** Resolves a SecretRef through the core secret owner. */
  resolveSecret: (ref: unknown) => Promise<string>;
  signal?: AbortSignal;
};
type StorageObjectInfo = {
  key: string;
  sizeBytes: number;
  modifiedAt?: number;
};
type StorageBackend = {
  /** Non-secret human-readable target. */
  displayTarget: string;
  probe: (opts?: {
    signal?: AbortSignal;
  }) => Promise<{
    freeBytes?: number;
    totalBytes?: number;
  }>;
  /** Never overwrite an existing key; sizeBytes is exact when provided. */
  putObject: (key: string, body: AsyncIterable<Uint8Array>, opts: {
    sizeBytes?: number;
    signal?: AbortSignal;
  }) => Promise<{
    sizeBytes: number;
  }>;
  getObject: (key: string, opts?: {
    signal?: AbortSignal;
  }) => Promise<AsyncIterable<Uint8Array> | undefined>;
  statObject: (key: string, opts?: {
    signal?: AbortSignal;
  }) => Promise<StorageObjectInfo | undefined>;
  listObjects: (prefix: string, opts?: {
    signal?: AbortSignal;
  }) => AsyncIterable<StorageObjectInfo>;
  deleteObject: (key: string, opts?: {
    signal?: AbortSignal;
  }) => Promise<void>;
  close?: () => Promise<void>;
};
//#endregion
//#region src/agents/auth-profiles/credential-state.d.ts
type AuthCredentialReasonCode = "ok" | "setup_inactive" | "missing_credential" | "invalid_expires" | "expired" | "unresolved_ref" | "malformed_api_key";
declare const DEFAULT_OAUTH_REFRESH_MARGIN_MS: number;
declare function hasUsableOAuthCredential(credential: OAuthCredential$1 | 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;
  /** Stored credentials keep their provider realm when a model route changes endpoint. */
  storedCredential?: boolean;
  metadataSnapshot?: Pick<PluginMetadataSnapshot, "plugins"> & {
    owners?: Pick<PluginMetadataSnapshot["owners"], "providerAuthAliases">;
  };
};
/** 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;
  authAliasLookupParams?: ProviderAuthAliasLookupParams;
  store: AuthProfileStore$1;
  provider: string;
  profileId: string;
  now?: number;
  /** Runtime resolvers may observe a durable pending refresh through settlement. */
  includePendingOAuthRefresh?: boolean;
}): AuthProfileEligibility;
type ResolveAuthProfileOrderParams = {
  cfg?: OpenClawConfig;
  store: AuthProfileStore$1;
  provider: string;
  /** Exact prepared metadata for request paths that must not rediscover plugin aliases. */
  authAliasLookupParams?: ProviderAuthAliasLookupParams;
  preferredProfile?: string;
  /** Model that will consume the profile, for model-scoped cooldowns. */
  forModel?: string;
  /** Account-wide selection ignores windows limited to one model. */
  cooldownScope?: "all-models";
  /** Read-only status keeps unresolved refs and leaves usage bookkeeping unchanged. */
  readinessMode?: "execution" | "read-only";
  /** Runtime resolvers may observe a durable pending refresh through settlement. */
  includePendingOAuthRefresh?: boolean;
};
/** Resolves ordered usable auth profile ids for a provider. */
declare function resolveAuthProfileOrder(params: ResolveAuthProfileOrderParams): string[];
//#endregion
//#region src/agents/auth-profiles/external-cli-discovery.d.ts
type ExternalCliAuthDiscovery = {
  mode: "none";
  allowKeychainPrompt?: false;
  config?: OpenClawConfig;
} | {
  mode: "existing";
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
} | {
  mode: "scoped";
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
  providerIds?: Iterable<string>;
  profileIds?: Iterable<string>;
};
//#endregion
//#region src/agents/auth-profiles/oauth.d.ts
type ResolveApiKeyForProfileResult = {
  apiKey: string;
  provider: string;
  email?: string;
  profileId: string;
  profileType: AuthProfileCredential["type"];
  credential?: AuthProfileCredential;
  /** Retained credential authority; null denotes a runtime-only credential. */
  readCurrentCredential: (() => AuthProfileCredential | undefined) | null;
};
type ResolveApiKeyForProfileParams = {
  cfg?: OpenClawConfig;
  store: AuthProfileStore$1;
  profileId: string;
  agentDir?: string;
  forceRefresh?: boolean;
  allowProfileFallback?: boolean;
  signal?: AbortSignal;
  /** Reject an OAuth credential before the resolver persists, adopts, or returns it. */
  validateOAuthCredential?: (credential: OAuthCredential$1) => void;
  /** Admission only: an already claimed refresh retains independent settlement. */
  assertRefreshAdmission?: () => void;
};
/** Refresh one OAuth credential and merge provider-returned token fields. */
declare function refreshOAuthCredentialForRuntime(params: {
  credential: OAuthCredential$1;
  cfg?: OpenClawConfig;
}): Promise<OAuthCredential$1 | null>;
/** Resolve a selected auth profile into the provider API key string. */
declare function resolveApiKeyForProfile(params: ResolveApiKeyForProfileParams): Promise<ResolveApiKeyForProfileResult | null>;
//#endregion
//#region src/agents/auth-profiles/profile-list.d.ts
declare function listProfilesForProvider(store: AuthProfileStore$1, provider: string): string[];
//#endregion
//#region src/agents/auth-profiles/profiles.d.ts
/** @deprecated Use upsertAuthProfileAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function upsertAuthProfile(params: {
  profileId: string;
  credential: AuthProfileCredential;
  agentDir?: string;
}): void;
/** Upsert the selected profile in the canonical writer without replacing neighboring profiles. */
declare function upsertAuthProfileAsync(params: Parameters<typeof upsertAuthProfile>[0]): Promise<void>;
/** Removes auth profiles and related state for a provider, optionally narrowed to exact IDs. */
declare function removeProviderAuthProfilesWithLock(params: {
  cfg?: OpenClawConfig;
  provider: string;
  agentDir?: string;
  profileIds?: readonly string[];
}): Promise<AuthProfileStore$1 | null>;
//#endregion
//#region src/agents/auth-profiles/external-auth.d.ts
type WithPreparedExternalAuthProfiles = <T>(params: {
  config?: OpenClawConfig;
  env?: NodeJS.ProcessEnv;
}, run: () => Promise<T>) => Promise<T>;
//#endregion
//#region src/agents/auth-profiles/legacy-source-files.d.ts
type LegacyAuthProfileSourceKind = "auth-profiles" | "auth-state" | "legacy-auth" | "legacy-oauth";
type LegacyAuthProfileSource = {
  kind: LegacyAuthProfileSourceKind;
  path: string;
};
//#endregion
//#region src/agents/auth-profiles/sqlite.d.ts
type AuthProfileDatabase = OpenClawAgentDatabase | OpenClawStateDatabase;
//#endregion
//#region src/agents/auth-profiles/runtime-read.types.d.ts
type LoadAuthProfileStoreOptions = {
  /** Limit a credential-read refusal to the provider being resolved; writes stay owner-wide. */
  migrationProvider?: string;
  deferScopedMigrationRefusals?: boolean;
  onReadOwner?: (owner: AuthProfileReadOwner) => void;
  onReadSource?: (source: {
    databasePath: string;
    hasStore: boolean;
  }) => void;
  /** Materialize only this explicitly selected personal account into the returned view. */
  profileId?: string;
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
  database?: AuthProfileDatabase;
  externalCli?: ExternalCliAuthDiscovery;
  inheritedAuthDir?: string;
  readOnly?: boolean;
  syncExternalCli?: boolean;
  externalCliProviderIds?: Iterable<string>;
  externalCliProfileIds?: Iterable<string>;
};
type AuthProfileReadOwner = {
  databasePath: string;
  candidates: LegacyAuthProfileSource[];
  readStore: () => AuthProfileStore$1 | null;
  readCurrentCredential?: () => AuthProfileCredential | undefined;
};
//#endregion
//#region src/shared/async-work-scope.d.ts
/** Outside a managed scope, the returned promise remains the caller's responsibility. */
declare function trackAsyncWork<T>(run: () => T | Promise<T>): Promise<T>;
//#endregion
//#region src/agents/auth-profiles/runtime-snapshot-owner.d.ts
type RuntimeAuthProfileLegacyCandidates = {
  local: LegacyAuthProfileSource[];
  shared: LegacyAuthProfileSource[];
};
/** Core lifecycle receipt; the public SDK snapshot shape intentionally stays unchanged. */
type OwnedRuntimeAuthProfileStoreSnapshotEntry = {
  databasePath: string;
  agentDir: string;
  store: RuntimeAuthProfileStore;
  owner: RuntimeAuthSharedOwner;
  legacyCandidates?: RuntimeAuthProfileLegacyCandidates;
};
type RuntimeAuthSharedOwner = ({
  kind: "resolved";
} & Pick<AuthProfileStoreOwner, "sharedDatabasePath" | "location">) | {
  kind: "unresolved";
  scope: AuthProfileOwnerScope;
};
//#endregion
//#region src/agents/auth-profiles/runtime-snapshot-selection.d.ts
type SharedAuthProfileStoreMutation = {
  credentialsChanged: boolean;
  profileSetChanged?: boolean;
  stateChanged: boolean;
  selectionChanged?: boolean;
  profileIds: Iterable<string>;
};
//#endregion
//#region src/agents/auth-profiles/runtime-snapshots.d.ts
declare const { invalidateRuntimeAuthProfileStoreSnapshotsForOwner, createPreparedRuntimeAuthProfileUsageReader, getRuntimeAuthProfileStoreSnapshotCore, getRuntimeAuthProfileStoreSnapshotAtDatabasePath, getPreparedRuntimeAuthProfileStoreSnapshotCore, hasRuntimeAuthProfileStoreSource, hasAnyRuntimeAuthProfileStoreSource, getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath, listOwnedRuntimeAuthProfileStoreSnapshots, listRuntimeAuthProfileStoreSnapshotsForSharedOwner }: {
  invalidateRuntimeAuthProfileStoreSnapshotsForOwner: (owner: AuthProfileStoreOwner, isCurrent?: (databasePath: string) => boolean) => void;
  createPreparedRuntimeAuthProfileUsageReader: (agentDir: string, inheritedAuthDir?: string) => (store: AuthProfileStore$1) => AuthProfileStore$1;
  getRuntimeAuthProfileStoreSnapshotCore: (agentDir?: string) => RuntimeAuthProfileStore | undefined;
  getRuntimeAuthProfileStoreSnapshotAtDatabasePath: (databasePath: string) => RuntimeAuthProfileStore | undefined;
  getPreparedRuntimeAuthProfileStoreSnapshotCore: (agentDir?: string, inheritedAuthDir?: string, env?: NodeJS.ProcessEnv) => RuntimeAuthProfileStore | undefined;
  hasRuntimeAuthProfileStoreSource: (agentDir?: string, env?: NodeJS.ProcessEnv) => boolean;
  hasAnyRuntimeAuthProfileStoreSource: (agentDir?: string) => boolean;
  getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath: (databasePath: string) => OwnedRuntimeAuthProfileStoreSnapshotEntry | undefined;
  listOwnedRuntimeAuthProfileStoreSnapshots: () => OwnedRuntimeAuthProfileStoreSnapshotEntry[];
  listRuntimeAuthProfileStoreSnapshotsForSharedOwner: (owner: AuthProfileStoreOwner, mutation?: SharedAuthProfileStoreMutation) => OwnedRuntimeAuthProfileStoreSnapshotEntry[];
};
declare const { recordRuntimeAuthProfilePersistedStore, refreshRuntimeAuthProfileStoreSources, registerRuntimeAuthProfileExternalRefresh }: {
  recordRuntimeAuthProfilePersistedStore: (databasePath: string, store: AuthProfileStore$1 | null) => void;
  refreshRuntimeAuthProfileStoreSources: () => Promise<void>;
  registerRuntimeAuthProfileExternalRefresh: (refresh: (paths: readonly string[]) => Promise<boolean>) => void;
  reset(): void;
};
/** @deprecated Use replaceRuntimeAuthProfileStoreSnapshotsAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function replaceRuntimeAuthProfileStoreSnapshots(entries: Array<{
  databasePath?: string;
  agentDir?: string;
  store: AuthProfileStore$1;
}>): void;
/** Resolve a default owner off-thread before publishing the supplied snapshot facts. */
declare function replaceRuntimeAuthProfileStoreSnapshotsAsync(entries: Array<{
  databasePath?: string;
  agentDir?: string;
  store: AuthProfileStore$1;
}>): Promise<void>;
/** Clears all runtime auth profile snapshots. */
declare function clearRuntimeAuthProfileStoreSnapshots(): void;
//#endregion
//#region src/agents/auth-profiles/store-save.d.ts
type SaveAuthProfileStoreOptions = {
  filterExternalAuthProfiles?: boolean;
  preserveOrderProfileIds?: Iterable<string>;
  preserveStateProfileIds?: Iterable<string>;
  pruneOrderProfileIds?: Iterable<string>;
  sharedStoreWrite?: boolean;
  syncExternalCli?: boolean;
};
//#endregion
//#region src/agents/auth-profiles/store.d.ts
/** @deprecated Use findPersistedAuthProfileCredentialAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function findPersistedAuthProfileCredential(params: {
  agentDir?: string;
  profileId: string;
}): AuthProfileStore$1["profiles"][string] | undefined;
/**
 * Resolve which agent dir owns a persisted profile, accounting for inherited OAuth.
 * @deprecated Use resolvePersistedAuthProfileOwnerAgentDirAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release.
 */
declare function resolvePersistedAuthProfileOwnerAgentDir(params: {
  agentDir?: string;
  profileId: string;
}): string | undefined;
//#endregion
//#region src/agents/auth-profiles/store-runtime.d.ts
declare const { createAuthProfileStoreReadScope, createAuthProfileStoreReadScopeAsync, updateAuthProfileStoreWithLock, loadAuthProfileStoreForRuntimeAsync, prepareAuthProfileProvider, findPersistedAuthProfileCredentialAsync, prepareAuthProfileCredentialRead, withAuthProfileStoreAtEffect, resolvePersistedAuthProfileOwnerAgentDirAsync, loadAuthProfileStoreForSecretsRuntimeAsync, loadAuthProfileStoreWithoutExternalProfilesAsync, loadAuthProfileStoreForCatalogAsync, ensureAuthProfileStoreAsync, ensureAuthProfileStoreWithoutExternalProfilesAsync, ensureAuthProfileStoreForLocalUpdateAsync, saveAuthProfileStoreWithPreparedOwner, saveAuthProfileStoreIfPersistenceSnapshotMatches }: Readonly<{
  loadAuthProfileStoreForRuntimeAsync: (agentDir?: string, options?: {
    migrationProvider?: string;
    deferScopedMigrationRefusals?: boolean;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }, env?: NodeJS.ProcessEnv) => Promise<AuthProfileStore$1>;
  withAuthProfileStoreAtEffect: <T>(agentDir: string | undefined, options: {
    migrationProvider?: string;
    deferScopedMigrationRefusals?: boolean;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }, consume: (reader: {
    read: () => Promise<AuthProfileStore$1>;
    assertCurrent: () => void;
  }) => Promise<T>) => Promise<T>;
  prepareAuthProfileStoreForModelRuntime: (agentDir: string, options: {
    config: OpenClawConfig;
    inheritedAuthDir?: string;
    skipCredentials?: boolean;
  }, assertCurrent: () => void, env?: NodeJS.ProcessEnv) => Promise<AuthProfileStore$1 | undefined>;
  loadAuthProfileStoreForRuntime: (agentDir?: string, options?: Omit<LoadAuthProfileStoreOptions, "onReadSource">, env?: NodeJS.ProcessEnv) => AuthProfileStore$1;
  createAuthProfileStoreReadScope: (agentDir: string, config: OpenClawConfig | undefined) => {
    agentDir: string;
    env: {
      [key: string]: string | undefined;
    };
    envOnly: boolean;
    read: () => AuthProfileStore$1;
    readAsync: () => Promise<AuthProfileStore$1>;
    getRuntimeSnapshots: () => RuntimeAuthProfileStore[];
    assertCredentialReady: (source: AuthProfileCredentialSource, baseUrl?: string) => void;
    prepareProviderReady: () => Promise<void>;
    assertProviderReady: (provider?: string, baseUrl?: string) => void;
    store: AuthProfileStore$1;
  };
  createAuthProfileStoreReadScopeAsync: (agentDir: string, config: OpenClawConfig | undefined) => Promise<{
    agentDir: string;
    env: {
      [key: string]: string | undefined;
    };
    envOnly: boolean;
    read: () => AuthProfileStore$1;
    readAsync: () => Promise<AuthProfileStore$1>;
    getRuntimeSnapshots: () => RuntimeAuthProfileStore[];
    assertCredentialReady: (source: AuthProfileCredentialSource, baseUrl?: string) => void;
    prepareProviderReady: () => Promise<void>;
    assertProviderReady: (provider?: string, baseUrl?: string) => void;
    store: AuthProfileStore$1;
  }>;
  updateAuthProfileStoreWithLock: (params: {
    agentDir?: string;
    profileId?: string;
    sharedStoreWrite?: boolean;
    stateDir?: string;
    saveOptions?: SaveAuthProfileStoreOptions;
    assertCurrent?: () => void;
    updater: (store: AuthProfileStore$1, owner?: PreparedAuthProfileStoreOwner, sharedStore?: AuthProfileStore$1 | null) => boolean;
  }) => Promise<AuthProfileStore$1 | null>;
  loadAuthProfileStoreForSecretsRuntime: (agentDir?: string, options?: Pick<LoadAuthProfileStoreOptions, "config" | "profileId" | "externalCli" | "externalCliProviderIds" | "externalCliProfileIds" | "inheritedAuthDir">) => AuthProfileStore$1;
  loadAuthProfileStoreForSecretsRuntimeAsync: (agentDir?: string, options?: Parameters<(agentDir?: string, options?: Pick<LoadAuthProfileStoreOptions, "config" | "profileId" | "externalCli" | "externalCliProviderIds" | "externalCliProfileIds" | "inheritedAuthDir">) => AuthProfileStore$1>[1]) => Promise<AuthProfileStore$1>;
  loadAuthProfileStoreWithoutExternalProfiles: (agentDir?: string, loadOptions?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir" | "profileId">) => AuthProfileStore$1;
  loadAuthProfileStoreWithoutExternalProfilesAsync: (agentDir?: string, options?: Parameters<(agentDir?: string, loadOptions?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir" | "profileId">) => AuthProfileStore$1>[1]) => Promise<AuthProfileStore$1>;
  loadAuthProfileStoreForCatalogAsync: (agentDir: string, options?: Parameters<(agentDir?: string, loadOptions?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir" | "profileId">) => AuthProfileStore$1>[1]) => Promise<{
    store: AuthProfileStore$1;
    displayPath: string;
  }>;
  ensureAuthProfileStore: (agentDir?: string, options?: {
    migrationProvider?: string;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }) => AuthProfileStore$1;
  ensureAuthProfileStoreAsync: (agentDir?: string, options?: Parameters<(agentDir?: string, options?: {
    migrationProvider?: string;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }) => AuthProfileStore$1>[1]) => Promise<AuthProfileStore$1>;
  ensureAuthProfileStoreWithoutExternalProfiles: (agentDir?: string, options?: Omit<{
    migrationProvider?: string;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }, "externalCli" | "externalCliProviderIds" | "externalCliProfileIds">) => AuthProfileStore$1;
  ensureAuthProfileStoreWithoutExternalProfilesAsync: (agentDir?: string, options?: Parameters<(agentDir?: string, options?: Omit<{
    migrationProvider?: string;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
  }, "externalCli" | "externalCliProviderIds" | "externalCliProfileIds">) => AuthProfileStore$1>[1]) => Promise<AuthProfileStore$1>;
  ensureAuthProfileStoreForLocalUpdate: (agentDir?: string) => AuthProfileStore$1;
  ensureAuthProfileStoreForLocalUpdateAsync: (agentDir?: string) => Promise<AuthProfileStore$1>;
  saveAuthProfileStore: (store: AuthProfileStore$1, agentDir?: string, options?: SaveAuthProfileStoreOptions, database?: AuthProfileDatabase) => void;
  saveAuthProfileStoreWithPreparedOwner: (store: AuthProfileStore$1, agentDir: string | undefined, options: SaveAuthProfileStoreOptions | undefined, database: AuthProfileDatabase, owner: AuthProfileStoreOwner | PreparedAuthProfileStoreOwner) => void;
  saveAuthProfileStoreIfPersistenceSnapshotMatches: (params: {
    store: AuthProfileStore$1;
    snapshot: {
      owner: PreparedAuthProfileStoreOwner;
      credentialsRaw: unknown;
      stateRaw: unknown;
      runtimeCaptured: boolean;
      runtimeRevision?: number;
      runtimeRevisionAtSaveEdge?: number;
      runtimeRevisionBeforePublication?: number;
      runtimeEntry?: OwnedRuntimeAuthProfileStoreSnapshotEntry;
      derivedRuntimeStores?: Array<OwnedRuntimeAuthProfileStoreSnapshotEntry & {
        runtimeRevision: number;
      }>;
      derivedRuntimeRevisionsAtSaveEdge?: {
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }[];
      derivedRuntimeRevisionsBeforePublication?: {
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }[];
    };
    agentDir?: string;
    options?: SaveAuthProfileStoreOptions;
    stateDir?: string;
  }) => {
    owned: {
      owner: PreparedAuthProfileStoreOwner;
      credentialsRaw: unknown;
      stateRaw: unknown;
      runtimeCaptured: boolean;
      runtimeRevision?: number;
      runtimeRevisionAtSaveEdge?: number;
      runtimeRevisionBeforePublication?: number;
      runtimeEntry?: OwnedRuntimeAuthProfileStoreSnapshotEntry;
      derivedRuntimeStores?: Array<OwnedRuntimeAuthProfileStoreSnapshotEntry & {
        runtimeRevision: number;
      }>;
      derivedRuntimeRevisionsAtSaveEdge?: {
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }[];
      derivedRuntimeRevisionsBeforePublication?: {
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }[];
    };
    publishRuntimeSnapshots: () => boolean;
  };
  findPersistedAuthProfileCredential: typeof findPersistedAuthProfileCredential;
  findPersistedAuthProfileCredentialAsync: (params: {
    agentDir?: string;
    profileId: string;
  }) => Promise<AuthProfileStore$1["profiles"][string] | undefined>;
  prepareAuthProfileCredentialRead: (params: {
    agentDir?: string;
    profileId: string;
    store: AuthProfileStore$1;
  }) => Promise<(() => AuthProfileStore$1["profiles"][string] | undefined) | null>;
  resolvePersistedAuthProfileOwnerAgentDirAsync: (params: {
    agentDir?: string;
    profileId: string;
  }) => Promise<string | undefined>;
  prepareAuthProfileProvider: (params: {
    agentDir: string;
    profileId: string;
  }) => Promise<{
    provider: string | undefined;
  }>;
}>;
/**
 * @deprecated Await loadAuthProfileStoreForRuntimeAsync from openclaw/plugin-sdk/agent-runtime
 * with readOnly: true and allowKeychainPrompt: false. Supported through 2026-12-31. Removal in the first January 2027 stable release.
 */
declare const loadAuthProfileStoreForSecretsRuntime: (agentDir?: string, options?: Pick<LoadAuthProfileStoreOptions, "config" | "profileId" | "externalCli" | "externalCliProviderIds" | "externalCliProfileIds" | "inheritedAuthDir">) => AuthProfileStore$1;
/**
 * @deprecated Use updateAuthProfileStoreWithLock from openclaw/plugin-sdk/provider-auth.
 * Supported through 2026-12-31. Removal in the first January 2027 stable release.
 */
declare const saveAuthProfileStore: (store: AuthProfileStore$1, agentDir?: string, options?: SaveAuthProfileStoreOptions, database?: AuthProfileDatabase) => void;
/** @deprecated Use loadAuthProfileStoreForRuntimeAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare const loadAuthProfileStoreForRuntime: (agentDir?: string, options?: Omit<LoadAuthProfileStoreOptions, "onReadSource">, env?: NodeJS.ProcessEnv) => AuthProfileStore$1;
/** @deprecated Use loadAuthProfileStoreWithoutExternalProfilesAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare const loadAuthProfileStoreWithoutExternalProfiles: (agentDir?: string, loadOptions?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir" | "profileId">) => AuthProfileStore$1;
/** @deprecated Use ensureAuthProfileStoreAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare const ensureAuthProfileStore: (agentDir?: string, options?: {
  migrationProvider?: string;
  profileId?: string;
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
  externalCli?: ExternalCliAuthDiscovery;
  inheritedAuthDir?: string;
  readOnly?: boolean;
  syncExternalCli?: boolean;
  externalCliProviderIds?: Iterable<string>;
  externalCliProfileIds?: Iterable<string>;
}) => AuthProfileStore$1;
/** @deprecated Use ensureAuthProfileStoreForLocalUpdateAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare const ensureAuthProfileStoreForLocalUpdate: (agentDir?: string) => AuthProfileStore$1;
//#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$1, profileId: string, now?: number, forModel?: string | null): boolean;
/** Clear each expired window in memory; the next store write persists it. */
declare function clearExpiredCooldowns(store: AuthProfileStore$1, now?: number): boolean;
/**
 * 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$1;
  profileIds: string[];
  now?: number;
}): AuthProfileFailureReason | null;
/** Resolves the display-facing unusable timestamp, honoring provider bypasses. */
declare function resolveProfileUnusableUntilForDisplay(store: AuthProfileStore$1, profileId: string): number | null;
//#endregion
//#region src/agents/auth-profiles/usage.d.ts
/** Marks a profile blocked until a provider-reported reset timestamp. */
declare function markAuthProfileBlockedUntil(params: {
  store: AuthProfileStore$1;
  profileId: string;
  blockedUntil: number;
  source: AuthProfileBlockedSource;
  agentDir?: string;
  runId?: string;
  modelId?: string;
}): Promise<void>;
//#endregion
//#region src/plugins/provider-auth-availability.d.ts
declare const { isProviderApiKeyConfiguredAsync, listUsableProviderAuthProfileIdsAsync, isProviderAuthProfileConfiguredAsync, resolveProviderAuthProfileApiKey }: Readonly<{
  isProviderApiKeyConfigured: (params: Parameters<(params: Pick<{
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }, "provider" | "cfg" | "agentDir" | "profileTypes" | "capability"> & {
    acceptsApiKey?: (apiKey: string) => boolean;
    store?: AuthProfileStore$1;
  }, persistedCredential?: AuthProfileCredential | null) => boolean>[0]) => boolean;
  isProviderApiKeyConfiguredAsync: (params: Parameters<(params: Parameters<(params: Pick<{
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }, "provider" | "cfg" | "agentDir" | "profileTypes" | "capability"> & {
    acceptsApiKey?: (apiKey: string) => boolean;
    store?: AuthProfileStore$1;
  }, persistedCredential?: AuthProfileCredential | null) => boolean>[0]) => boolean>[0]) => Promise<boolean>;
  listUsableProviderAuthProfileIds: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => {
    agentDir: string;
    profileIds: string[];
  };
  listUsableProviderAuthProfileIdsAsync: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => Promise<{
    agentDir: string;
    profileIds: string[];
  }>;
  isProviderAuthProfileConfigured: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => boolean;
  isProviderAuthProfileConfiguredAsync: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => Promise<boolean>;
  resolveProviderAuthProfileApiKey: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => Promise<string | undefined>;
}>;
/** @deprecated Use isProviderApiKeyConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare const isProviderApiKeyConfigured: (params: Parameters<(params: Pick<{
  provider: string;
  cfg?: OpenClawConfig;
  agentDir?: string;
  profileTypes?: readonly AuthProfileCredential["type"][];
  capability?: string;
  allowKeychainPrompt?: boolean;
  includeExternalCliAuth?: boolean;
}, "provider" | "cfg" | "agentDir" | "profileTypes" | "capability"> & {
  acceptsApiKey?: (apiKey: string) => boolean;
  store?: AuthProfileStore$1;
}, persistedCredential?: AuthProfileCredential | null) => boolean>[0]) => boolean;
/** @deprecated Use listUsableProviderAuthProfileIdsAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare const listUsableProviderAuthProfileIds: (params: {
  provider: string;
  cfg?: OpenClawConfig;
  agentDir?: string;
  profileTypes?: readonly AuthProfileCredential["type"][];
  capability?: string;
  allowKeychainPrompt?: boolean;
  includeExternalCliAuth?: boolean;
}) => {
  agentDir: string;
  profileIds: string[];
};
/** @deprecated Use isProviderAuthProfileConfiguredAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare const isProviderAuthProfileConfigured: (params: {
  provider: string;
  cfg?: OpenClawConfig;
  agentDir?: string;
  profileTypes?: readonly AuthProfileCredential["type"][];
  capability?: string;
  allowKeychainPrompt?: boolean;
  includeExternalCliAuth?: boolean;
}) => boolean;
//#endregion
//#region src/realtime-transcription/websocket-session.d.ts
type RealtimeTranscriptionWebSocketTransport = {
  readonly callbacks: RealtimeTranscriptionSessionCallbacks;
  closeNow(): void;
  failConnect(error: Error): void;
  isOpen(): boolean;
  isReady(): boolean;
  markReady(): void;
  sendBinary(payload: Buffer): boolean;
  sendJson(payload: unknown): boolean;
};
/** Provider-specific hooks for creating a websocket transcription session. */
type RealtimeTranscriptionWebSocketSessionOptions<Event = unknown> = {
  callbacks: RealtimeTranscriptionSessionCallbacks;
  connectClosedBeforeReadyMessage?: string;
  connectTimeoutMessage?: string;
  connectTimeoutMs?: number;
  closeTimeoutMs?: number;
  headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
  maxQueuedBytes?: number;
  maxReconnectAttempts?: number;
  onClose?: (transport: RealtimeTranscriptionWebSocketTransport) => void;
  onMessage?: (event: Event, transport: RealtimeTranscriptionWebSocketTransport) => void;
  onOpen?: (transport: RealtimeTranscriptionWebSocketTransport) => void;
  parseMessage?: (payload: Buffer) => Event;
  providerId: string;
  readyOnOpen?: boolean;
  reconnectDelayMs?: number;
  reconnectLimitMessage?: string;
  sendAudio: (audio: Buffer, transport: RealtimeTranscriptionWebSocketTransport) => void;
  url: string | (() => string | Promise<string>);
};
/** Creates a reusable websocket session wrapper for a provider implementation. */
declare function createRealtimeTranscriptionWebSocketSession<Event = unknown>(options: RealtimeTranscriptionWebSocketSessionOptions<Event>): RealtimeTranscriptionSession;
//#endregion
//#region src/version.d.ts
declare const VERSION: string;
//#endregion
//#region src/agents/provider-attribution.d.ts
type ProviderRequestTransport = "stream" | "websocket" | "http" | "media-understanding";
type ProviderRequestCapability = "llm" | "audio" | "image" | "video" | "other";
//#endregion
//#region src/agents/provider-request-config.d.ts
type RequestApi = Api | ModelDefinitionConfig["api"];
type ProviderRequestHeaderPrecedence = "caller-wins" | "defaults-win";
declare function resolveProviderRequestHeaders(params: {
  provider: string;
  api?: RequestApi;
  baseUrl?: string;
  capability?: ProviderRequestCapability;
  transport?: ProviderRequestTransport;
  callerHeaders?: ModelRequestHeaders;
  defaultHeaders?: ModelRequestHeaders;
  precedence?: ProviderRequestHeaderPrecedence;
  request?: ProviderRequestTransportOverrides;
}): ModelRequestHeaders | undefined;
/** Attaches model-scoped provider request transport metadata without mutating the model. */
declare function attachModelProviderRequestTransport<TModel extends object>(model: TModel, request: ModelProviderRequestTransportOverrides$1 | undefined): TModel;
declare function getModelProviderRequestTransport(model: object): ModelProviderRequestTransportOverrides$1 | undefined;
//#endregion
//#region src/agents/model-auth-runtime-shared.d.ts
type ResolvedProviderAuth = {
  apiKey?: string;
  profileId?: string;
  source: string;
  mode: "api-key" | "oauth" | "token" | "aws-sdk";
  /** Provider-owned OAuth grant family; distinct from credential renewal mode. */
  authFlow?: string;
  nativeAuth?: ProviderSyntheticAuthResult["nativeAuth"];
};
declare function requireApiKey(auth: ResolvedProviderAuth, provider: string): string;
//#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<ResolvedProviderAuth, "apiKey"> & {
  apiKey?: string;
  baseUrl?: string;
  request?: ModelProviderRequestTransportOverrides$1;
  expiresAt?: number;
};
//#endregion
//#region src/agents/model-auth-env.d.ts
type EnvApiKeyResult = {
  apiKey: string;
  source: string;
};
type EnvApiKeyLookupOptions = {
  config?: OpenClawConfig;
  workspaceDir?: string;
  aliasMap?: Readonly<Record<string, string>>;
  candidateMap?: Readonly<Record<string, readonly string[]>>;
  authEvidenceMap?: Readonly<Record<string, readonly ProviderAuthEvidence[]>>;
  setupProviderFallbackRefs?: readonly string[];
  skipSetupProviderFallback?: boolean;
};
declare function resolveEnvApiKey(provider: string, env?: NodeJS.ProcessEnv, options?: EnvApiKeyLookupOptions): EnvApiKeyResult | null;
//#endregion
//#region src/agents/model-auth-provider.d.ts
type ProviderCredentialPrecedence = "profile-first" | "env-first";
/** Resolves the credential that should be used for one provider request. */
declare function resolveApiKeyForProviderCore(input: {
  provider: string;
  cfg?: OpenClawConfig;
  profileId?: string;
  preferredProfile?: string;
  store?: AuthProfileStore$1;
  agentDir?: string;
  workspaceDir?: string;
  /** Cancels this credential lookup, not an independently owned OAuth refresh. */
  signal?: AbortSignal;
  /** When true, treat profileId as a user-locked selection that must not be
   *  silently replaced by another profile or env/config credentials. */
  lockedProfile?: boolean;
  forceRefresh?: boolean;
  /** Gates a new native refresh claim, not independently owned settlement. */
  assertRefreshAdmission?: () => void;
  validateOAuthCredential?: Parameters<typeof resolveApiKeyForProfile>[0]["validateOAuthCredential"];
  credentialPrecedence?: ProviderCredentialPrecedence;
  /** Skip implicit profile discovery for a prepared env/config fallback attempt. */
  allowAuthProfileFallback?: boolean;
  /** Skip plugin setup fallback when the prepared route already excludes it. */
  skipSetupProviderFallback?: boolean;
  modelId?: string;
  modelApi?: string;
  modelBaseUrl?: string;
  capability?: string;
  /** Keep SecretRef-backed model credentials opaque until a sentinel-aware transport boundary. */
  secretSentinels?: boolean;
}): Promise<ResolvedProviderAuth>;
//#endregion
//#region src/agents/model-auth-markers.d.ts
/** @deprecated MiniMax provider-owned marker; do not use from third-party plugins. */
declare const MINIMAX_OAUTH_MARKER = "minimax-oauth";
/** @deprecated Bundled local-provider marker; do not use from third-party plugins. */
declare const CUSTOM_LOCAL_AUTH_MARKER = "custom-local";
/** @deprecated Codex provider-owned marker; do not use from third-party plugins. */
declare const CODEX_APP_SERVER_AUTH_MARKER = "codex-app-server";
/** Return true for recognized env-var API-key placeholders, excluding AWS SDK markers. */
declare function isKnownEnvApiKeyMarker(value: string): boolean;
/** Build the persisted OAuth marker for one provider id. */
declare function resolveOAuthApiKeyMarker(providerId: string): string;
/** Return true for persisted non-secret placeholders that should not be treated as real keys. */
declare function isNonSecretApiKeyMarker(value: string, opts?: {
  includeEnvVarName?: boolean;
}): boolean;
//#endregion
//#region src/agents/model-auth-model.d.ts
type ModelAuthMode = "api-key" | "oauth" | "token" | "mixed" | "aws-sdk" | "unknown";
/** @deprecated Use resolveModelAuthModeAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveModelAuthMode(provider?: string, cfg?: OpenClawConfig, store?: AuthProfileStore$1, options?: {
  workspaceDir?: string;
}): ModelAuthMode | undefined;
declare function resolveModelAuthModeAsync(provider?: string, cfg?: OpenClawConfig, store?: AuthProfileStore$1, options?: {
  workspaceDir?: string;
}): Promise<ModelAuthMode | undefined>;
//#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<Record<ProviderSystemPromptSectionId, string>>;
};
//#endregion
//#region src/llm/model-registry.d.ts
/** Registry abstraction used by model pickers and provider availability checks. */
type ModelRegistry = {
  getAll(): Model[];
  getAvailable(): Model[];
  find(provider: string, modelId: string): Model | undefined;
  hasConfiguredAuth(model: Model): boolean;
};
//#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<WizardPrompter["progress"]>;
  openUrl: (url: string) => Promise<unknown>;
  localBrowserMessage: string;
  manualPromptMessage?: string;
  manualPromptSignal?: AbortSignal;
}): {
  onAuth: (event: {
    url: string;
  }) => Promise<void>;
  onPrompt: (prompt: OAuthPrompt) => Promise<string>;
};
//#endregion
//#region src/plugins/provider-authentication.types.d.ts
type ProviderAuthProfile = {
  profileId: string;
  credential: AuthProfileCredential;
  /** Request host-owned SecretRef materialization at the final persistence boundary. */
  secretStorage?: {
    /** Final persistence target. The inline credential remains available for staged validation. */
    kind: "store";
    /** Environment-style prefix used for the host-owned secret-store entry. */
    namePrefix: string;
  };
};
type HeaderPatch<T> = Omit<T, "headers"> & {
  headers?: Record<string, SecretInput | undefined>;
};
/** Standard result payload returned by provider auth methods. */
type ProviderAuthResult = {
  profiles: ProviderAuthProfile[];
  /**
   * Optional config patch to merge after credentials are written.
   *
   * Use this for provider-owned onboarding defaults such as
   * `models.providers.<id>` entries, default aliases, or agent model helpers.
   * The caller still persists auth-profile bindings separately.
   * Undefined header entries delete superseded credentials during the merge.
   */
  configPatch?: Omit<Partial<OpenClawConfig>, "models"> & {
    models?: Omit<NonNullable<OpenClawConfig["models"]>, "providers"> & {
      providers?: Record<string, Omit<HeaderPatch<ModelProviderConfigInput>, "request"> & {
        request?: HeaderPatch<NonNullable<ModelProviderConfigInput["request"]>>;
      }>;
    };
  };
  defaultModel?: string;
  /** Setup routes the selected agent's model through this runtime, without changing global defaults. */
  agentRuntimeId?: 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;
  /** Host-authorized profiles available for reconnect; personal flows supply only their owner's selection. */
  existingProfiles?: readonly ProviderAuthProfile[];
  /** Save connection credentials without discovering or selecting a starter model. */
  credentialOnly?: boolean;
  env?: NodeJS.ProcessEnv;
  agentDir?: string;
  workspaceDir?: string;
  prompter: WizardPrompter;
  runtime: RuntimeEnv;
  /** Cancels browser callbacks, device polling, and other app-owned auth work. */
  signal?: AbortSignal;
  /** Personal-account methods must recheck live caller authority immediately before external effects. */
  assertCurrent?: () => void;
  /**
   * 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/store 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<void>;
  oauth: {
    createVpsAwareHandlers: typeof createVpsAwareOAuthHandlers;
    authorize?: (params: {
      state: string;
      timeoutMs: number;
      buildAuthorizationUrl: (redirectUrl: string) => string;
    }) => Promise<{
      code: string;
      state: string;
      iss?: string;
    }>;
  };
};
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<string, string>;
};
type ProviderAuthMethodNonInteractiveContext = {
  authChoice: string;
  config: OpenClawConfig;
  baseConfig: OpenClawConfig;
  opts: ProviderAuthOptionBag;
  runtime: RuntimeEnv;
  agentDir?: string;
  workspaceDir?: string;
  resolveApiKey: (params: ProviderResolveNonInteractiveApiKeyParams) => Promise<ProviderNonInteractiveApiKeyResult | null>;
  toApiKeyCredential: (params: ProviderNonInteractiveApiKeyCredentialParams) => ApiKeyCredential$1 | null;
};
/** Read-only context for app-guided discovery of already available inference. */
type ProviderAppGuidedSetupContext = {
  config: OpenClawConfig;
  env: NodeJS.ProcessEnv;
  workspaceDir?: string;
  signal?: AbortSignal;
};
type ProviderAppGuidedSetupCandidate = {
  /** Canonical provider/model reference returned unchanged during activation. */
  modelRef: string;
  /** Optional provider-owned detail shown beside the auth-choice label. */
  detail?: string;
};
type ProviderAppGuidedSetup = {
  /**
   * Report whether the provider's local service is reachable, even when no
   * model is suitable for automatic activation. This probe must be read-only.
   */
  detectAvailability?: (ctx: ProviderAppGuidedSetupContext) => Promise<boolean>;
  /** Detection is read-only: no model pull, download, login, or config write. */
  detect: (ctx: ProviderAppGuidedSetupContext) => Promise<ProviderAppGuidedSetupCandidate | null>;
  /** Recheck one detected model and return the config required for a live probe. */
  prepare: (ctx: ProviderAppGuidedSetupContext & {
    modelRef: string;
  }) => Promise<ProviderAuthResult | null>;
};
type ProviderAuthMethod = {
  id: string;
  label: string;
  hint?: string;
  kind: "oauth" | "api_key" | "token" | "device_code" | "custom";
  /** Provider-owned model used to validate app-guided secret setup. */
  starterModel?: string;
  /** One-time import attempted only after the user starts this login method. */
  credentialImport?: {
    migrationProviderId: string;
    itemId: string;
    credentialKind: "oauth" | "api_key" | "token";
  };
  /**
   * 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;
  /** Proven provider identity for reconnecting an owned personal account; absent means a new slot. */
  matchesPersonalAccount?: (credential: AuthProfileCredential, existing: AuthProfileCredential) => boolean;
  run: (ctx: ProviderAuthContext) => Promise<ProviderAuthResult>;
  runNonInteractive?: (ctx: ProviderAuthMethodNonInteractiveContext) => Promise<OpenClawConfig | null>;
  /** Side-effect-free prerequisite validation used before destructive reset handling. */
  validateNonInteractive?: (ctx: Omit<ProviderAuthMethodNonInteractiveContext, "toApiKeyCredential">) => Promise<boolean>;
  /** Provider-owned local model discovery for the shared guided setup ladder. */
  appGuidedSetup?: ProviderAppGuidedSetup;
};
type ProviderPluginWizardSetup = {
  modelTarget?: "utility";
  choiceId?: string;
  choiceLabel?: string;
  choiceHint?: string;
  assistantPriority?: number;
  assistantVisibility?: "visible" | "manual-only" | "detected-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?: PluginManifestOnboardingScope[];
  /**
   * 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 `<provider>: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" | "event" | "heartbeat" | "manual" | "memory" | "overflow" | "user";
};
type ProviderTransformSystemPromptContext = ProviderSystemPromptContributionContext & {
  systemPrompt: string;
};
//#endregion
//#region src/plugins/provider-runtime.types.d.ts
type ModelProviderRequestTransportOverrides = ModelProviderRequestTransportOverrides$1;
/**
 * 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 = ProviderPreferRuntimeResolvedModelContext & {
  agentRuntimeId?: string;
  modelRegistry: ModelRegistry;
  providerConfig?: Partial<Pick<ModelProviderConfig, "baseUrl" | "api" | "auth" | "models">> & {
    headers?: unknown;
    request?: ModelProviderConfig["request"];
  };
  authProfileId?: string;
  authProfileMode?: AuthProfileCredential["type"] | "aws-sdk";
};
/**
 * Optional async preparation for dynamic model resolution.
 *
 * Called only from async model resolution paths. Providers can return the
 * requested model directly or refresh reusable metadata before the sync retry.
 */
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 = ProviderPreferRuntimeResolvedModelContext & {
  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 = Pick<ProviderPreferRuntimeResolvedModelContext, "provider" | "modelId">;
/**
 * 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 = ProviderPreferRuntimeResolvedModelContext & {
  env: NodeJS.ProcessEnv;
  model: ProviderRuntimeModel;
  apiKey: string;
  authMode: string;
  profileId?: string;
  /** Cancel caller-owned exchanges when the run stops or its auth budget expires. */
  signal?: AbortSignal;
};
/** Transport identity available to every inference capability, without invented chat limits. */
type ProviderRuntimeAuthModel = Pick<ProviderRuntimeModel, "id" | "provider"> & Partial<Pick<ProviderRuntimeModel, "name" | "api" | "baseUrl" | "headers">>;
/** Capability-aware exchange; the legacy hook retains its shipped full chat-model contract. */
type ProviderPrepareRuntimeAuthContextV2 = Omit<ProviderPrepareRuntimeAuthContext, "model"> & {
  capability: "chat" | "decision";
  model: ProviderRuntimeAuthModel;
};
/**
 * 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 = {
  /** Cancel provider-owned work when the usage collection deadline expires. */
  signal?: AbortSignal;
  config: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  /** @deprecated Await resolveApiKeyCandidatesFromConfigAndStore instead. Removal follows an announced ordinary stable release window. */
  resolveApiKeyFromConfigAndStore: (params?: {
    providerIds?: string[];
    envDirect?: Array<string | undefined>;
  }) => string | undefined;
  /** Ordered API-key/token candidates, including resolved SecretRefs, for credential classification. */
  resolveApiKeyCandidatesFromConfigAndStore?: (params?: {
    providerIds?: string[];
    envDirect?: Array<string | undefined>;
  }) => Promise<string[]>;
  resolveOAuthToken: (params?: {
    provider?: string;
    excludeProfileIds?: string[];
  }) => Promise<ProviderUsageAuthToken | null>;
};
type ProviderUsageAuthToken = {
  token: string;
  /** Provider-owned grant family used to authorize the usage endpoint. */
  authFlow?: string;
  accountId?: string;
  /** Non-secret plan metadata from the resolved credential (e.g. Claude "max"). */
  subscriptionType?: string;
  rateLimitTier?: string;
  /** Account email captured on the resolved credential, when known. */
  email?: 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 = ProviderUsageAuthToken & {
  /** Custom transports must preserve this signal; fetchFn already includes it. */
  signal?: AbortSignal;
  config: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  authProfileId?: string;
  timeoutMs: number;
  fetchFn: typeof fetch;
};
/**
 * Provider-owned auth-doctor hint input.
 *
 * Called when OAuth refresh fails and OpenClaw wants a provider-specific repair
 * hint to append to the generic re-auth message. Use this for legacy profile-id
 * migrations or other provider-owned auth-store cleanup guidance.
 */
type ProviderAuthDoctorHintContext = {
  config?: OpenClawConfig;
  store: AuthProfileStore$1;
  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 = ProviderPreferRuntimeResolvedModelContext & {
  agentId?: string;
  /** Selected credential facts; excludes credential material. */
  auth?: {
    mode: string;
    authFlow?: string;
  };
  nativeWebSearchAllowedByToolPolicy?: boolean;
  model?: ProviderRuntimeModel;
  extraParams?: Record<string, unknown>;
  /** Provider-facing effort after OpenClaw lowers orchestration-only modes. */
  thinkingLevel?: Exclude<ThinkLevel, "ultra">;
};
type ProviderExtraParamsForTransportContext = Omit<ProviderPrepareExtraParamsContext, "extraParams"> & {
  transport?: "sse" | "websocket" | "websocket-cached" | "auto";
  extraParams: Record<string, unknown>;
};
type ProviderExtraParamsForTransportResult = {
  patch?: Record<string, unknown> | null;
};
type ProviderResolvePromptOverlayContext = ProviderSystemPromptContributionContext & {
  baseOverlay?: ProviderSystemPromptContribution;
};
type ProviderFollowupFallbackRouteContext = ProviderPreferRuntimeResolvedModelContext & {
  payload: ReplyPayload$1;
  originatingChannel?: string;
  originatingTo?: string;
  originRoutable: boolean;
  dispatcherAvailable: boolean;
};
type ProviderFollowupFallbackRouteResult = {
  route?: "origin" | "dispatcher" | "drop";
  reason?: string;
};
type ProviderResolveAuthProfileIdContext = ProviderPreferRuntimeResolvedModelContext & {
  preferredProfileId?: string;
  lockedProfileId?: string;
  profileOrder: string[];
  authStore: AuthProfileStore$1;
};
//#endregion
//#region src/plugins/provider-replay.types.d.ts
type ProviderReasoningOutputMode = "native" | "tagged";
/**
 * 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?: "full" | "images-only";
  sanitizeToolCallIds?: boolean;
  toolCallIdMode?: "strict" | "strict9";
  duplicateToolCallIdStyle?: "openai";
  preserveNativeAnthropicToolUseIds?: boolean;
  preserveSignatures?: boolean;
  /** Keep per-turn runtime context in place to preserve signed thinking prefixes. */
  appendOnlyRuntimeContext?: boolean;
  /** Append system-authority updates instead of rewriting the stable prompt prefix. */
  inHistorySystemUpdates?: 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;
  /** Host-resolved model, endpoint, and authentication eligibility. */
  inHistorySystemUpdates?: boolean;
};
type ProviderReplaySessionEntry = {
  customType: string;
  data?: unknown;
};
/** @deprecated Use ProviderReplaySessionStateV2; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
type ProviderReplaySessionState = {
  getCustomEntries(): ProviderReplaySessionEntry[];
  /** @deprecated Use ProviderReplaySessionStateV2.appendCustomEntryAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  appendCustomEntry(customType: string, data: unknown): void;
};
/** Worker-backed host state. The legacy synchronous adapter remains available for its deprecation window. */
type ProviderReplaySessionStateV2 = ProviderReplaySessionState & {
  appendCustomEntryAsync(customType: string, data: unknown): Promise<string>;
};
/**
 * 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.
 * @deprecated Use ProviderSanitizeReplayHistoryContextV2; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release.
 */
type ProviderSanitizeReplayHistoryContext = ProviderReplayPolicyContext & {
  sessionId: string;
  messages: AgentMessage[];
  allowedToolNames?: Iterable<string>;
  sessionState?: ProviderReplaySessionState;
};
/** Replay input with required worker-backed persistence when session state is present. */
type ProviderSanitizeReplayHistoryContextV2 = Omit<ProviderSanitizeReplayHistoryContext, "sessionState"> & {
  sessionState?: ProviderReplaySessionStateV2;
};
/**
 * 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;
//#endregion
//#region src/infra/provider-usage.types.d.ts
type UsageWindow = {
  label: string;
  groupLabel?: string;
  usedPercent: number;
  resetAt?: number;
};
/** Provider-reported monetary or credit facts. Units may be ISO currencies or provider credits. */
type ProviderUsageBilling = {
  type: "balance";
  label?: string;
  amount: number;
  unit: string;
} | {
  type: "spend";
  label?: string;
  amount: number;
  unit: string;
  period?: string;
  resetAt?: number;
} | {
  type: "budget";
  label?: string;
  used: number;
  limit: number;
  unit: string;
  period?: string;
  resetAt?: number;
};
/** Provider-reported daily cost and token totals. Costs are actual provider billing, not estimates. */
type ProviderUsageCostDaily = {
  date: string;
  amount: number;
  requests?: number;
  inputTokens: number;
  cacheReadTokens: number;
  cacheWriteTokens: number;
  outputTokens: number;
  totalTokens: number;
};
type ProviderUsageModelBreakdown = Omit<ProviderUsageCostDaily, "date" | "amount"> & {
  name: string;
};
type ProviderUsageSnapshot = {
  provider: UsageProviderId;
  displayName: string;
  windows: UsageWindow[];
  billing?: ProviderUsageBilling[];
  /** Provider-reported cost history and attribution for one bounded UTC window. */
  costHistory?: {
    unit: string;
    periodDays: number;
    scope?: string;
    daily: ProviderUsageCostDaily[];
    models: ProviderUsageModelBreakdown[];
    categories: {
      name: string;
      amount: number;
    }[];
  };
  summary?: string;
  plan?: string;
  /** Account identity (email) the usage was fetched under, when known. */
  accountEmail?: string;
  error?: string;
};
/** Normalized provider id. Usage providers are discovered from plugin hooks at runtime. */
type UsageProviderId = string;
//#endregion
//#region src/agents/provider-local-service-reconcile.d.ts
type ProviderLocalServiceReconcileContext = {
  baseUrl: string;
  signal?: AbortSignal;
};
//#endregion
//#region src/plugins/provider-transport.types.d.ts
/**
 * 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 = ProviderNormalizeResolvedModelContext & {
  /**
   * Optional host-owned, selected-credential capability. Resolve immediately before
   * each physical request, including private continuation/recovery requests,
   * and call the result's assertCurrent immediately before dispatch. Never cache
   * its result or fall back to a captured bearer when it rejects.
   * Absent on legacy hosts and calls without an owner-bound renewable credential.
   */
  requestAuth?: {
    version: 1;
    resolve(params: {
      signal?: AbortSignal;
    }): Promise<{
      apiKey: string;
      assertCurrent(): void;
    }>;
  };
};
/**
 * 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 & {
  /** Per-model params only, with agent-specific model params taking precedence. */
  modelParams?: Record<string, unknown>;
  /** Host-classified urgency; providers may translate it into native scheduling hints. */
  modelCallUrgency?: ModelCallUrgency;
  /** Wire-format API before simple completion projects an internal transport alias. */
  sourceApi?: ProviderRuntimeModel["api"];
  streamFn?: StreamFn$1;
};
/** Healthy local service boundary before the provider request is sent. */
type ProviderReconcileLocalServiceContext = ProviderLocalServiceReconcileContext;
/**
 * Provider-owned WebSocket session policy.
 */
type ProviderWebSocketSessionPolicy = {
  headers?: Record<string, string>;
  degradeCooldownMs?: number;
};
/**
 * 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<string, string>;
  metadata?: Record<string, string>;
  websocket?: ProviderWebSocketSessionPolicy;
};
/**
 * 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 = ProviderResolveWebSocketSessionPolicyContext & {
  turnId: string;
  attempt: number;
  transport: "stream" | "websocket";
};
/**
 * Provider-owned WebSocket session policy input.
 */
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<number[]>;
  embedBatch: (texts: string[], options?: {
    signal?: AbortSignal;
  }) => Promise<number[][]>;
  embedBatchInputs?: (inputs: unknown[], options?: {
    signal?: AbortSignal;
  }) => Promise<number[][]>;
  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<string, string>;
  };
  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;
  baseUrl?: string;
  supportsPromptCacheKey?: boolean;
};
/**
 * 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;
};
//#endregion
//#region src/agents/provider-auth-resolver.types.d.ts
/** Resolves full provider auth state for callers that need mode and profile provenance. */
type ProviderAuthResolver = (provider: string, options?: {
  oauthMarker?: string;
  excludeProfileIds?: readonly string[];
}) => {
  apiKey: string | undefined;
  discoveryApiKey?: string;
  mode: "api_key" | "aws-sdk" | "oauth" | "token" | "none";
  source: "env" | "profile" | "none";
  profileId?: string;
  preparationFailed?: boolean;
  authFlow?: string;
};
//#endregion
//#region src/plugins/provider-catalog.types.d.ts
declare const PROVIDER_CATALOG_ORDERS: readonly ["simple", "profile", "paired", "late"];
type ProviderCatalogOrder = (typeof PROVIDER_CATALOG_ORDERS)[number];
type ProviderConfiguredModelRef = {
  provider: string;
  modelId: string;
  baseUrl?: string;
};
type ProviderCatalogContext = {
  /** Acquisition lifetime; release awaited work and join its cleanup when aborted. */
  signal?: AbortSignal;
  config: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  /** Normalized provider identities selected for this catalog owner; absent means the full catalog. */
  providerIds?: readonly string[];
  resolveProviderApiKey: (providerId?: string) => {
    apiKey: string | undefined;
    discoveryApiKey?: string;
    profileId?: string;
    /** Credential kind from this lookup when known; never infer it from another selection. */
    mode?: "api_key" | "oauth" | "token";
  };
  resolveProviderAuth: (providerId?: string, options?: {
    oauthMarker?: string;
  }) => ReturnType<ProviderAuthResolver>;
};
type ProviderCatalogResult = {
  provider: ModelProviderConfig;
  outcomes?: readonly ProviderCatalogOutcome[];
} | {
  providers: Record<string, ModelProviderConfig>;
  outcomes?: readonly ProviderCatalogOutcome[];
} | null | undefined;
type ProviderPluginCatalog = {
  order?: ProviderCatalogOrder;
  run: (ctx: ProviderCatalogContext) => Promise<ProviderCatalogResult>;
  /** Pure advisory projection; skip other endpoints and never perform discovery or I/O. */
  getUnlistedConfiguredModelIds?: (catalog: NonNullable<ProviderCatalogOutcome["modelIdCatalog"]>, configuredModels: readonly ProviderConfiguredModelRef[]) => readonly string[];
};
type UnifiedModelCatalogProviderContext = ProviderCatalogContext & {
  includeLive?: boolean;
  timeoutMs?: number;
};
type UnifiedModelCatalogProviderPlugin = {
  provider: string;
  kinds: readonly UnifiedModelCatalogKind[];
  staticCatalog?: (ctx: UnifiedModelCatalogProviderContext) => readonly UnifiedModelCatalogEntry[] | Promise<readonly UnifiedModelCatalogEntry[] | null | undefined> | null | undefined;
  liveCatalog?: NonNullable<UnifiedModelCatalogProviderPlugin["staticCatalog"]>;
};
/**
 * Built-in model suppression hook context.
 *
 * @deprecated Use manifest `modelCatalog.suppressions`. Runtime suppression
 * hooks are no longer called by model resolution.
 */
type ProviderBuiltInModelSuppressionContext$1 = ProviderBuildUnknownModelHintContext;
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[];
};
//#endregion
//#region src/plugins/cli-backend.types.d.ts
type CliBackendNoOutputWatchdog = {
  /** Fraction of overall timeout used when fixed timeout is not set. */
  noOutputTimeoutRatio?: number;
  minMs?: number;
  maxMs?: number;
};
/** Static command adapter owned by a CLI backend plugin registration. */
type CliBackendConfig = {
  /** CLI command to execute (absolute path or on PATH). */
  command: string;
  /** Base args applied to every invocation. */
  args?: string[];
  /** Output parsing mode (default: json). */
  output?: "json" | "text" | "jsonl";
  resumeOutput?: "json" | "text" | "jsonl";
  /** JSONL event dialect for CLIs with provider-specific stream formats. */
  jsonlDialect?: "claude-stream-json" | "gemini-stream-json";
  liveSession?: "claude-stdio";
  /** Prompt input mode (default: arg). */
  input?: "arg" | "stdin";
  /** Max prompt length for arg mode (if exceeded, stdin is used). */
  maxPromptArgChars?: number;
  env?: Record<string, string>;
  clearEnv?: string[];
  modelArg?: string;
  /** Model aliases mapping (OpenClaw model id → CLI model id). */
  modelAliases?: Record<string, string>;
  /** Args used to pass a session id (use {sessionId} placeholder). */
  sessionArgs?: string[];
  /** Alternate args to use when resuming a session (use {sessionId} placeholder). */
  resumeArgs?: string[];
  /** Argument appended to one explicitly forked resume invocation. */
  forkArg?: string;
  /** Argument followed by an assistant checkpoint id to bound one resumed fork. */
  resumeAtArg?: string;
  sessionMode?: "always" | "existing" | "none";
  /** JSON fields to read session id from (in order). */
  sessionIdFields?: string[];
  systemPromptArg?: string;
  systemPromptFileArg?: string;
  /** Config override flag used to pass a system prompt file (e.g. -c). */
  systemPromptFileConfigArg?: string;
  systemPromptFileConfigKey?: string;
  systemPromptMode?: "append" | "replace";
  systemPromptWhen?: "first" | "always" | "never";
  imageArg?: string;
  imageMode?: "repeat" | "list";
  imagePathScope?: "temp" | "workspace";
  serialize?: boolean;
  /** Opt in to bounded raw transcript reseed before compaction for safe session resets. */
  reseedFromRawTranscriptWhenUncompacted?: boolean;
  /**
   * Controls fresh recovery after a recoverable resumed-session failure.
   *
   * Undefined and `replace-binding` preserve the legacy clear-and-reseed behavior.
   * `invalidated-only` retries fresh only when the failure proves the binding expired.
   */
  freshSessionRecovery?: "replace-binding" | "invalidated-only";
  reliability?: {
    watchdog?: {
      fresh?: CliBackendNoOutputWatchdog;
      resume?: CliBackendNoOutputWatchdog;
    };
  };
};
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;
  /** Effective catalog context-window option selected for this run. */
  contextWindow?: string;
  /** Effective OpenClaw context budget selected for this run. */
  contextTokenBudget?: number;
  /** Effective OpenClaw thinking level selected for this run. */
  thinkingLevel?: CliBackendThinkingLevel;
  authProfileId?: string;
  executionMode?: CliBackendExecutionMode;
  /** Exact runtime tool surface the backend must enforce for this run. */
  toolAvailability?: CliBackendToolAvailability;
  /** Core-prepared environment, including any bundled MCP settings path. */
  env?: Readonly<Record<string, string>>;
};
type CliBackendPreparedExecution = {
  env?: Record<string, string>;
  clearEnv?: string[];
  /**
   * Backend-owned staging that must run after the core CLI queue admits the turn.
   * Use this for mutable per-profile CLI homes that the launched process also owns.
   */
  beforeExecution?: () => Promise<void>;
  cleanup?: () => Promise<void>;
  /** Positive acknowledgement for `prepare-execution` tool enforcement. */
  toolAvailabilityEnforced?: true;
  /** Optional plugin-owned execution transport for this prepared local run. */
  execute?: CliBackendExecute;
};
type CliBackendThinkingLevel = ModelThinkingLevel | "adaptive";
type CliBackendExecutionMode = "agent" | "side-question";
/** Exact backend-native plus canonical OpenClaw tool surface for one CLI run. */
type CliBackendToolAvailability = {
  native: readonly string[];
  /** Read-only native discovery of the already-authorized catalog; grants no execution authority. */
  discovery?: readonly string[];
  /** Canonical OpenClaw tool names served through the host-isolated transport. */
  openClaw: readonly string[];
};
/** Native action a plugin-owned runtime asks the admitted host run to authorize. */
type CliBackendToolPermissionRequest = {
  /** Actual working directory reported by the native permission hook. */
  cwd?: string;
  toolName: string;
  toolInput: Record<string, unknown>;
  toolCallId?: string;
  abortSignal?: AbortSignal;
};
/** Host-owned native action decision; plugins never acquire approval authority. */
type CliBackendToolPermissionResult = {
  behavior: "allow";
  updatedInput: Record<string, unknown>;
} | {
  behavior: "deny";
  message: string;
};
type CliBackendUserInputOption = {
  label: string;
  description?: string;
};
type CliBackendUserInputQuestion = {
  id: string;
  header: string;
  question: string;
  multiSelect?: boolean;
  isOther?: boolean;
  options?: readonly CliBackendUserInputOption[] | null;
};
/** Structured operator input requested by a plugin-owned native runtime. */
type CliBackendUserInputRequest = {
  toolName: string;
  questions: readonly CliBackendUserInputQuestion[];
  intro?: string;
  toolCallId?: string;
  abortSignal?: AbortSignal;
};
type CliBackendUserInputResult = {
  status: "answered";
  answers: Record<string, string[]>;
} | {
  status: "cancelled";
  message: string;
};
/** Lifecycle reasons accepted by a plugin-owned reusable execution process. */
type CliBackendLiveSessionCloseReason = "idle" | "restart" | "abort" | "mcp-capture-rotation";
/** Plugin-owned process lifecycle registered with the generic host owner. */
type CliBackendLiveSessionHandle = {
  generation: string;
  fingerprint: string;
  isIdle(): boolean;
  close(reason: CliBackendLiveSessionCloseReason, error?: unknown): void;
  waitForExit(): Promise<void>;
};
/** Closure-bound host capability for one admitted reusable-runtime turn. */
type CliBackendLiveSessionCapability = {
  fingerprint: string;
  current(): CliBackendLiveSessionHandle | undefined;
  /** Retires the current process and awaits host-owned cleanup before replacement. */
  restart(): Promise<void>;
  register(handle: CliBackendLiveSessionHandle): void;
  /** Rebinds this exact admitted turn to the registered process's stable capture. */
  activate(handle: CliBackendLiveSessionHandle): void;
  remove(handle: CliBackendLiveSessionHandle): void;
};
/** Plugin-owned input sink for the admitted turn; the host revalidates authority at each effect. */
type CliBackendMessageInjection = {
  isAvailable(): boolean;
  /**
   * Ask the host to prepare current authority and invoke the synchronous native write.
   * Resolve only after the runtime acknowledges consumption, not after the write.
   */
  queueMessage(text: string, withCurrent: (submit: () => void) => Promise<void>,
  /** Per-input attribution and private context; never inherit the initial turn's. */
  options?: Pick<CliBackendExecuteContext, "promptOrigin" | "promptContext">): Promise<void>;
};
/** Graceful end of the admitted turn without retiring its reusable native session. */
type CliBackendTurnInterrupt = {
  /** Request the turn end; its execution stream must then finish normally. */
  interrupt(reason: "yield"): Promise<void>;
};
/** Turn-only context that must not become an operator-authored native transcript row. */
type CliBackendPromptContext = {
  prependContext?: string;
  appendContext?: string;
};
/** Exact prepared local process facts consumed by a plugin-owned execution transport. */
type CliBackendExecuteContext = {
  command: string;
  /** Preserve a verified invocation name when command resolves through a PATH shim. */
  argv0?: string;
  args: readonly string[];
  cwd: string;
  env: Record<string, string>;
  prompt: string;
  promptContext?: CliBackendPromptContext;
  /**
   * `host`: OpenClaw generated or forwarded this input, rather than a person
   * typing it in this session. Apply the native non-user input marker when available.
   * Canonical transcript provenance owns its visibility and sender attribution.
   */
  promptOrigin?: "host";
  modelId: string;
  systemPrompt: string;
  sessionId?: string;
  useResume: boolean;
  abortSignal?: AbortSignal;
  /** Revalidate the host-owned run and caller before deferred credential use or dispatch. */
  assertCurrent?: () => void;
  timeoutMs: number;
  executionMode?: CliBackendExecutionMode;
  toolAvailability?: CliBackendToolAvailability;
  /** Exact host-owned reusable process lifecycle and current-turn admission. */
  liveSession?: CliBackendLiveSessionCapability;
  /** Offers same-turn input for this run; the host drops it when the run closes. */
  registerMessageInjection?: (injection: CliBackendMessageInjection) => void;
  /** Offers graceful turn interruption; the host drops the registration when this run closes. */
  registerTurnInterrupt?: (interrupt: CliBackendTurnInterrupt) => void;
  /** Optional read-only assessment outside the prompt queue; the host owns its time bound. */
  registerTurnStatus?: (status: CliBackendTurnStatus) => void;
  /** Closure-bound approval capability; retained copies fail after the run closes. */
  requestToolPermission: (request: CliBackendToolPermissionRequest) => Promise<CliBackendToolPermissionResult>;
  /** Closure-bound structured-input capability; retained copies fail after the run closes. */
  requestUserInput: (request: CliBackendUserInputRequest) => Promise<CliBackendUserInputResult>;
};
/** Plugin-owned runtime yielding the backend's existing structured stream records. */
type CliBackendExecute = (context: CliBackendExecuteContext) => AsyncIterable<Record<string, unknown>>;
type CliBackendResolveExecutionArgsContext = Omit<CliBackendPrepareExecutionContext, "agentDir" | "contextWindow" | "contextTokenBudget" | "env"> & {
  /** Agent identity used to resolve per-agent execution policy. */
  agentId?: string;
  /** Effective fast mode at spawn, after queue admission and backend preparation. */
  fastMode?: boolean;
  /** Canonical tools routed through OpenClaw; disable equivalent native tools. */
  hostOwnedTools?: readonly string[];
  useResume: boolean;
  /** The backend process is executing a native control operation. */
  controlOperation?: "compact";
  baseArgs: readonly string[];
};
type CliBackendResolveExecutionArgs = (ctx: CliBackendResolveExecutionArgsContext) => readonly string[] | null | undefined;
type CliBackendResolveModelIdContext = {
  modelId: string;
  contextWindow?: string;
};
type CliBackendJsonlUsage = Pick<NormalizedUsage, "input" | "output" | "cacheRead" | "cacheWrite" | "cacheWrite1h" | "total">;
type CliBackendParsedJsonlEvent = {
  kind: "text";
  text: string;
} | {
  kind: "thinking";
  text: string;
} | {
  kind: "toolStart";
  toolCallId: string;
  name: string;
  args?: Record<string, unknown>;
} | {
  kind: "toolResult";
  toolCallId: string;
  name?: string;
  isError?: boolean;
  result?: unknown;
} | {
  kind: "result";
  text?: string;
  sessionId?: string;
  usage?: CliBackendJsonlUsage;
  errorText?: string;
} | {
  kind: "sessionId";
  sessionId: string;
};
type CliBackendParseJsonlEventContext = {
  backendId: string;
  backend: Readonly<CliBackendConfig>;
};
type CliBackendParseJsonlEvent = (line: string, ctx: CliBackendParseJsonlEventContext) => CliBackendParsedJsonlEvent | readonly CliBackendParsedJsonlEvent[] | null | undefined;
type CliBackendParsedJsonlLifecycleEvent = {
  kind: "compaction";
  phase: "start";
} | {
  kind: "compaction";
  phase: "end";
  completed: boolean;
};
type CliBackendParseJsonlLifecycleEvent = (line: string, ctx: CliBackendParseJsonlEventContext) => CliBackendParsedJsonlLifecycleEvent | readonly CliBackendParsedJsonlLifecycleEvent[] | null | undefined;
type CliBackendAuthEpochMode = "combined" | "profile-only";
type CliBackendNativeToolMode = "none" | "always-on" | "selectable";
/** Backend-owned mechanism that enforces exact per-run tool availability. */
type CliBackendToolAvailabilityEnforcement = "execution-args" | "prepare-execution";
type CliBackendSideQuestionToolMode = "disabled";
type CliBackendExactToolAvailabilityVersionPolicy = Readonly<{
  /** Inclusive floor for stable package releases. */
  stableMinimum: string;
  /** Inclusive floors keyed by the first SemVer prerelease identifier. */
  prereleaseMinimums?: Readonly<Record<string, string>>;
}>;
type CliBackendNormalizeConfigContext = {
  config?: OpenClawConfig;
  backendId: string;
  agentId?: string;
};
/** Backend-owned implementation boundary for script-backed CLI executables. */
type CliBackendRuntimeArtifactPolicy = Readonly<{
  kind: "bundled-package-tree";
  /** Exact package.json name whose complete installed tree owns inference. */
  packageName: string;
  /** Only the command itself may be the package entrypoint. */
  entrypoint: "command";
  /** Supported package release lines when a run requests exact tool availability. */
  exactToolAvailabilityVersionPolicy?: CliBackendExactToolAvailabilityVersionPolicy;
  /** Canonical basenames allowed when this backend ships a self-contained native build. */
  nativeExecutableNames?: readonly string[];
}>;
/** Complete backend-owned contract for in-place native session compaction. */
type CliBackendManualCompaction = Readonly<{
  /** Builds the exact backend command for the resumed native session. */
  buildPrompt: (customInstructions?: string) => string;
  /** Prompt transport required by the backend control command. */
  input: "arg" | "stdin";
  /** Positively confirms that a successful process exit performed compaction. */
  validateOutput: (rawOutput: string) => {
    ok: true;
  } | {
    ok: false;
    reason: string;
  };
}>;
/** Plugin-owned CLI backend defaults used by the text-only CLI runner. */
type CliBackendPluginBase = {
  /** 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;
  /** Static command adapter owned by this plugin. */
  config: CliBackendConfig;
  /**
   * Context-engine host capabilities provided by this backend when it is
   * driven through the generic CLI runner.
   */
  contextEngineHostCapabilities?: readonly ContextEngineHostCapability[];
  /**
   * Whether embedded runs opted into `cliBackendDispatch: "subscription-auth"`
   * execute through this backend when the selected credential is
   * subscription-scoped (oauth/token) or unresolvable.
   *
   * Set only when this backend's model provider rejects or meters direct API
   * calls on subscription tokens, so the passthrough would fail or silently
   * bill outside plan limits. API-key credentials always keep the passthrough.
   */
  subscriptionAuthDispatch?: 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;
    };
  };
  /** Required whenever this backend can become a verified inference owner. */
  runtimeArtifact?: CliBackendRuntimeArtifactPolicy;
  /**
   * 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;
  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;
    /** Short IDs of OpenClaw MCP tools exposed to this invocation after policy filtering. */
    openClawMcpToolNames?: readonly 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;
  /**
   * Whether `prepareExecution` may auto-select a configured auth profile.
   *
   * Defaults to true for auth bridges. Set false for environment/config-only
   * hooks that do not consume OpenClaw auth profiles.
   */
  autoSelectAuthProfile?: boolean;
  /**
   * 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> | 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;
  /** Backend-owned native model id selected from validated session metadata. */
  resolveModelId?: (ctx: CliBackendResolveModelIdContext) => string;
  /** How this backend enforces an exact per-run `toolAvailability` contract. */
  toolAvailabilityEnforcement?: CliBackendToolAvailabilityEnforcement;
  /**
   * Maps the observed native list, intersected with the host selection, to equivalent
   * cron capabilities: read/write/edit/apply_patch/exec/process/web_search/web_fetch.
   * Never infer capabilities decided by unobserved model or sandbox settings.
   * Core rejects other names before grant/capture and excludes node/tool-disabled runs.
   */
  projectNativeToolAuthority?: (nativeTools: readonly string[]) => readonly string[];
  /** Native tool that only discovers schemas from the authorized MCP catalog. */
  nativeToolSearch?: string;
  /**
   * Operator-selected native tools kept on OpenClaw-mediated agent turns, which
   * otherwise expose no native tools. Core applies the same list to ordinary and
   * verified completion turns, so return only tools that confer no capability
   * through `projectNativeToolAuthority`; caller caps, restricted senders,
   * delegated execution, and workspace-only runs still receive none.
   */
  resolveManagedNativeTools?: (ctx: {
    config?: OpenClawConfig;
    agentId: string;
  }) => readonly string[];
  /**
   * Backend-owned JSONL line parser for provider-specific stream formats.
   *
   * Tool events report execution already performed by the backend. OpenClaw
   * renders them but does not treat them as host tool execution or delivery evidence.
   */
  parseJsonlEvent?: CliBackendParseJsonlEvent;
  /** Normalize backend-native failures into diagnostic codes without changing retry policy. */
  classifyErrorCode?: (message: string) => string | undefined;
  /**
   * Optional lifecycle parser kept separate from the legacy JSONL event union.
   * Existing plugins can continue exhaustively matching `parseJsonlEvent` results.
   */
  parseJsonlLifecycleEvent?: CliBackendParseJsonlLifecycleEvent;
  /**
   * Whether this CLI backend can expose native tools outside OpenClaw's tool
   * catalog. Exact restricted runs require `selectable` plus a declared
   * `toolAvailabilityEnforcement`; `always-on` backends fail closed.
   */
  nativeToolMode?: CliBackendNativeToolMode;
  /** Default local coding tools owned by OpenClaw instead of the native CLI.
   * Applies only with bundled loopback MCP, outside exact or node runs.
   * The execution-args adapter must disable the equivalent native tools.
   */
  hostOwnedTools?: readonly string[];
  /**
   * Side-question native tool behavior.
   *
   * Set to `disabled` only when `executionMode: "side-question"` reliably
   * launches the CLI without native tools, even if normal agent turns expose
   * backend-owned tools.
   */
  sideQuestionToolMode?: CliBackendSideQuestionToolMode;
};
type CliBackendNativeCompactionContract = {
  /** Backend-owned compaction for a persisted resumable CLI transcript. */
  ownsNativeCompaction: true;
  /** Optional control operation for explicit manual compaction. */
  manualCompaction?: CliBackendManualCompaction;
} | {
  /** Boolean-compatible ownership for existing plugins without manual compaction. */
  ownsNativeCompaction?: boolean;
  manualCompaction?: never;
};
type CliBackendPlugin = CliBackendPluginBase & CliBackendNativeCompactionContract;
//#endregion
//#region src/plugins/provider-config-context.types.d.ts
/**
 * Provider-owned config normalization for `models.providers.<id>` 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-plugin.types.d.ts
type ProviderPlugin = {
  id: string;
  pluginId?: string;
  /** Loader-owned dependency root, shared by lightweight and full registration. */
  pluginRoot?: 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[];
  /** Physical credential owner, matching canonical catalog metadata. */
  authScope?: "agent" | "plugin";
  /**
   * 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 `<provider>/<entry.id>`
   * composition instead of the canonical (deduped) key.
   *
   * `modelKey` strips a duplicate `<provider>/` 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 `<provider>/` segment in the native model id is
   * a meaningful vendor namespace (e.g. NVIDIA's `nvidia/nemotron-...`
   * alongside `moonshotai/kimi-k2.5`).
   */
  preserveLiteralProviderPrefix?: boolean;
  /**
   * 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. Async model discovery belongs in
   * `prepareDynamicModel`, which can return the prepared model directly.
   */
  resolveDynamicModel?: (ctx: ProviderResolveDynamicModelContext) => ProviderRuntimeModel | null | undefined;
  /**
   * Optional async preparation for dynamic model resolution.
   *
   * OpenClaw calls this only from async model resolution paths. Return the
   * requested model directly, or return nothing to retry `resolveDynamicModel`.
   */
  prepareDynamicModel?: (ctx: ProviderPrepareDynamicModelContext) => Promise<ProviderRuntimeModel | void>;
  /**
   * 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.<id>`.
   *
   * 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;
  /**
   * 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;
  /**
   * @deprecated Use sanitizeReplayHistoryAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release.
   * 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> | AgentMessage[] | null | undefined;
  /** Replay hook with worker-backed persistence; preferred over the legacy hook when both exist. */
  sanitizeReplayHistoryAsync?: (ctx: ProviderSanitizeReplayHistoryContextV2) => Promise<AgentMessage[] | null | undefined> | 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> | 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.<provider>/<model>.params`.
   */
  prepareExtraParams?: (ctx: ProviderPrepareExtraParamsContext) => Record<string, unknown> | 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$1 | null | undefined;
  /**
   * Opt custom streams into the internal stable/dynamic system-prompt boundary.
   * The transport must consume the boundary before sending its provider payload.
   * Otherwise the host strips it before invoking the custom stream.
   */
  supportsSystemPromptCacheBoundary?: boolean;
  /**
   * 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$1 & {
    /** A decorator that leaves shared request and output compatibility policy active. */
    preservesGenericCompatibility?: boolean;
  }) | null | undefined;
  /**
   * Provider-owned wrapper for direct `completeSimple` callers.
   *
   * Opt in only when the provider must enforce the same wire contract outside
   * the embedded agent runtime.
   * The factory runs once per prepared model; its returned stream retains
   * wrapper-local state and reads per-request options on each invocation.
   */
  wrapSimpleCompletionStreamFn?: (ctx: ProviderWrapStreamFnContext) => StreamFn$1 | null | undefined;
  /** Cheap, idempotent provider repair after local-service health and before each request. */
  reconcileLocalService?: (ctx: ProviderReconcileLocalServiceContext) => Promise<void>;
  /**
   * 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.
   *
   * @deprecated Return `websocket` from `resolveTransportTurnState`. When both
   * hooks provide a field, the new hook takes precedence.
   */
  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> | 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<ProviderPreparedRuntimeAuth | null | undefined>;
  /** Preferred exchange for chat and Decision inference; takes precedence over the legacy hook. */
  prepareRuntimeAuthV2?: (ctx: ProviderPrepareRuntimeAuthContextV2) => Promise<ProviderPreparedRuntimeAuth | null | undefined>;
  /**
   * 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> | 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> | 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$1) => 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<ModelCatalogEntry> | ReadonlyArray<ModelCatalogEntry> | Promise<Array<ModelCatalogEntry> | ReadonlyArray<ModelCatalogEntry> | null | undefined> | null | 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 clamps execution by profile
   * rank without replacing the stored preference.
   */
  resolveThinkingProfile?: (ctx: ProviderDefaultThinkingPolicyContext) => ProviderThinkingProfile | null | undefined;
  /** Whether Fast can affect this selected request; undefined retains existing unknown behavior. */
  resolveFastModeSupport?: (ctx: ProviderFastModePolicyContext) => boolean | undefined;
  /** Known model/route service tiers; undefined retains account discovery and route defaults. */
  resolveServiceTiers?: (ctx: ProviderFastModePolicyContext) => readonly string[] | 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;
  /**
   * Provider-owned OAuth login adapter for the session SDK AuthStorage API.
   *
   * This keeps the public callback-based login contract usable without seeding
   * provider implementations into core. Modern setup flows should use `auth`.
   */
  loginOAuth?: (callbacks: OAuthLoginCallbacks) => Promise<OAuthCredentials>;
  /**
   * Legacy auth-profile ids that generic auth must ignore and `openclaw doctor` should remove.
   *
   * 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. A runtime-only external CLI profile remains usable by its exact
   * provider when it intentionally reuses a retired id.
   */
  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. The optional second argument is the caller's
   * effective config; prefer it over reading global runtime config.
   */
  refreshOAuth?: (cred: OAuthCredential$1, config?: OpenClawConfig) => Promise<OAuthCredential$1>;
  /**
   * 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<string | null | undefined> | 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.
   *
   * 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;
  /**
   * Prepare external availability before synchronous synthetic-auth reads.
   * Keep process/network I/O here; OpenClaw publishes the completed result for this generation.
   */
  prepareSyntheticAuth?: (ctx: ProviderResolveSyntheticAuthContext & {
    env?: NodeJS.ProcessEnv;
    signal?: AbortSignal;
    pluginRoot?: string;
  }) => Promise<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<ProviderExternalAuthProfile> | ReadonlyArray<ProviderExternalAuthProfile> | 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<void>;
};
/** Provider runtime registered with its owning plugin and source. */
type PluginProviderRegistration = {
  pluginId: string;
  pluginName?: string;
  provider: ProviderPlugin;
  source: string;
  rootDir?: string;
};
//#endregion
//#region src/plugins/capability-catalog.types.d.ts
/** Default export of capabilityCatalogEntry. Each present family is complete, even when empty. */
type PluginCapabilityCatalog = {
  speechProviders?: readonly SpeechProviderPlugin[];
  realtimeTranscriptionProviders?: readonly RealtimeTranscriptionProviderPlugin[];
  realtimeVoiceProviders?: readonly RealtimeVoiceProviderPlugin[];
};
//#endregion
//#region src/plugins/plugin-runtime-artifact-selection.d.ts
type PluginRuntimeArtifact = {
  source: string;
  rootDir: string;
};
//#endregion
//#region src/plugins/sdk-alias.d.ts
type PluginSdkResolutionPreference = "auto" | "dist" | "src";
//#endregion
//#region src/plugins/loader-types.d.ts
type ChannelPluginLoadIntent = "full" | "setup";
/** Host-owned recovery of one previously admitted runtime, never current package discovery. */
type PluginRuntimeRecovery = {
  module: PluginModuleLoaderRecovery;
  runtimeEntry: PluginRuntimeArtifact;
  setupEntry?: PluginRuntimeArtifact;
};
/** Inputs shared by runtime, snapshot, and CLI-metadata plugin loading. */
type PluginLoadOptions = {
  config?: OpenClawConfig;
  /** Provider lookup config before activation copies; only captured generations may share. */
  registrationConfigOrigin?: OpenClawConfig;
  activationSourceConfig?: OpenClawConfig;
  autoEnabledReasons?: Readonly<Record<string, string[]>>;
  workspaceDir?: string;
  installRecords?: Record<string, PluginInstallRecord>;
  /** Resolve plugin roots and load paths against an explicit environment. */
  env?: NodeJS.ProcessEnv;
  /** Apply the config IO env-substitution pass to direct raw-config callers. */
  resolveRawConfigEnvVars?: boolean;
  logger?: PluginLogger;
  coreGatewayHandlers?: Record<string, GatewayRequestHandler>;
  coreGatewayMethodNames?: readonly string[];
  /** Registry-construction fact supplied by the process composition root. */
  allowProcessHomeSessionCatalogs?: boolean;
  hostServices?: PluginRegistryParams["hostServices"];
  runtimeOptions?: CreatePluginRuntimeOptions;
  startupTrace?: {
    detail: (name: string, metrics: ReadonlyArray<readonly [string, number | string]>) => void;
    run?: <T>(name: string, run: () => T) => T;
  };
  pluginSdkResolution?: PluginSdkResolutionPreference;
  cache?: boolean;
  mode?: "full" | "validate" | "cli-metadata";
  onlyPluginIds?: readonly string[];
  includeSetupOnlyChannelPlugins?: boolean;
  forceSetupOnlyChannelPlugins?: boolean;
  /** Select full runtime registration or the lightweight unconfigured-channel setup path. */
  channelPluginLoadIntent?: ChannelPluginLoadIntent;
  /** Built hosts prefer canonical checkout artifacts by default; false retains source execution. */
  preferBuiltPluginArtifacts?: boolean;
  toolDiscovery?: boolean;
  /** Native host operations supplied by a runtime composition root. */
  capabilityCatalogContext?: PluginCapabilityCatalogHostContext;
  /** Resolve declared descriptors for this family without full runtime registration. */
  capabilityCatalog?: {
    family: keyof PluginCapabilityCatalog;
    context: PluginCapabilityCatalogHostContext;
  };
  activate?: boolean;
  /** Staged Gateway candidates expose runtime APIs only after publication or owner preparation. */
  runtimeSideEffects?: boolean;
  previousRegistry?: PluginRegistry;
  /**
   * Live runtime registry whose unchanged records a non-activating load lists without
   * loading its own copies. The lender keeps custody and retirement of those instances.
   */
  borrowRegistry?: PluginRegistry;
  replacePluginIds?: readonly string[];
  moduleRecoveries?: ReadonlyMap<string, PluginRuntimeRecovery>;
  /** Preserve host cleanup hooks before failed registration removes its contributions. */
  prepareRegistrationFailureCleanup?: (registry: PluginRegistry, record: PluginRecord) => void;
  /** Validate captured source before evaluation; this never grants plugin authority. */
  expectedSourceDigests?: Readonly<Record<string, string>>;
  loadModules?: boolean;
  throwOnLoadError?: boolean;
  /** Prepared alias identity shared by selection, normalization, and registration. */
  normalizePluginId?: NormalizePluginId;
  /** Exact lifecycle inventory supplied by a prepared load owner. */
  metadataSnapshot?: PluginMetadataSnapshot;
  manifestRegistry?: PluginManifestRegistry;
  discovery?: PluginDiscoveryResult;
};
//#endregion
//#region src/plugins/provider-hook-runtime-core.d.ts
type ProviderRuntimePluginLookupParams = {
  provider: string;
  providerOwner?: string;
  modelId?: string | null;
  config?: OpenClawConfig;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  applyAutoEnable?: boolean;
  pluginMetadataSnapshot?: PluginMetadataRegistryView;
};
type ProviderRuntimePluginHandle = ProviderRuntimePluginLookupParams & {
  plugin?: ProviderPlugin;
};
//#endregion
//#region src/plugins/provider-hook-runtime.d.ts
declare const { attachModelProviderRuntimePluginHandle, getModelProviderRuntimePluginHandle, resolveLoadedProviderPluginsForHooks, resolveProviderPluginsForHooks, resolveProviderRuntimePlugin, resolveLoadedProviderRuntimePlugin, resolveProviderHookPlugin, resolveProviderRuntimePluginHandle, ensureProviderRuntimePluginHandle, resolveProviderAuthProfileId, resolveProviderFollowupFallbackRoute, wrapProviderSimpleCompletionStreamFn }: Readonly<{
  attachModelProviderRuntimePluginHandle: <TModel extends object>(model: TModel, runtimeHandle: ProviderRuntimePluginHandle) => TModel;
  getModelProviderRuntimePluginHandle: (model: object | undefined) => ProviderRuntimePluginHandle | undefined;
  resolveLoadedProviderPluginsForHooks: (params: {
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  }) => ProviderPlugin[] | undefined;
  resolveProviderPluginsForHooks: (params: Parameters<(params: {
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  }) => ProviderPlugin[] | undefined>[0]) => ProviderPlugin[];
  resolveProviderRuntimePlugin: (params: {
    provider: string;
    providerOwner?: string;
    modelId?: string | null;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  }) => ProviderPlugin | undefined;
  resolveLoadedProviderRuntimePlugin: (params: {
    provider: string;
    providerOwner?: string;
    modelId?: string | null;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  }) => ProviderPlugin | undefined;
  resolveProviderHookPlugin: (params: {
    provider: string;
    modelId?: string | null;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
  }) => ProviderPlugin | undefined;
  resolveProviderRuntimePluginHandle: (params: {
    provider: string;
    providerOwner?: string;
    modelId?: string | null;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  }, registryScope?: "loaded") => ProviderRuntimePluginHandle;
  ensureProviderRuntimePluginHandle: (params: {
    provider: string;
    providerOwner?: string;
    modelId?: string | null;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    applyAutoEnable?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
  } & {
    runtimeHandle?: ProviderRuntimePluginHandle;
  }) => ProviderRuntimePluginHandle;
  resolveProviderAuthProfileId: (params: {
    provider: string;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    runtimeHandle?: ProviderRuntimePluginHandle;
    context: ProviderResolveAuthProfileIdContext;
  }) => string | undefined;
  resolveProviderFollowupFallbackRoute: (params: {
    provider: string;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    runtimeHandle?: ProviderRuntimePluginHandle;
    context: ProviderFollowupFallbackRouteContext;
  }) => ProviderFollowupFallbackRouteResult | undefined;
  wrapProviderSimpleCompletionStreamFn: (params: {
    provider: string;
    config?: OpenClawConfig;
    workspaceDir?: string;
    env?: NodeJS.ProcessEnv;
    runtimeHandle?: ProviderRuntimePluginHandle;
    context: ProviderWrapStreamFnContext;
  }) => StreamFn | undefined;
}>;
//#endregion
//#region src/plugins/provider-external-auth.d.ts
declare const { resolveExternalAuthProfilesWithPlugins }: Readonly<{
  resolveExternalAuthProfilesWithPlugins: (params: Parameters<ProviderExternalAuthProfileResolver>[0]) => ReturnType<ProviderExternalAuthProfileResolver>;
  withPreparedExternalAuthProfiles: WithPreparedExternalAuthProfiles;
}>;
//#endregion
//#region src/plugins/provider-catalog-augment.d.ts
type CatalogHookParams = {
  providerIds?: readonly string[];
  config?: OpenClawConfig;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  metadataSnapshot?: PluginMetadataSnapshot;
};
declare function augmentModelCatalogWithProviderPlugins(params: CatalogHookParams & {
  context: ProviderAugmentModelCatalogContext;
}): Promise<ModelCatalogEntry[]>;
//#endregion
//#region src/plugins/provider-runtime.d.ts
type ProviderRuntimeLookup = Pick<Parameters<typeof resolveProviderRuntimePlugin>[0], "provider" | "config" | "workspaceDir" | "env">;
declare const runProviderDynamicModel: (params: ProviderRuntimeLookup & {
  context: ProviderResolveDynamicModelContext;
}) => (Omit<Model<Api>, "compat"> & {
  compat?: ModelCompatConfig;
  contextWindows?: ModelCatalogContextWindowOption[];
  contextWindowDefault?: string;
  contextTokens?: number;
  contextWindowSource?: "synthetic";
  maxTokensSource?: "configured" | "discovered";
  params?: Record<string, unknown>;
  requestTimeoutMs?: number;
  toolSearchMode?: "tools" | false;
  compactionThinkingDefault?: NonNullable<ProviderThinkingProfile["defaultLevel"]>;
  mediaInput?: ModelMediaInputConfig;
}) | undefined;
declare const prepareProviderDynamicModel: (params: ProviderRuntimeLookup & {
  context: ProviderResolveDynamicModelContext;
}) => Promise<void | ProviderRuntimeModel | undefined>;
declare function shouldPreferProviderRuntimeResolvedModel(params: ProviderRuntimeLookup & {
  context: ProviderPreferRuntimeResolvedModelContext;
}): boolean;
declare function normalizeProviderResolvedModelWithPlugin(params: ProviderRuntimeLookup & {
  pluginMetadataSnapshot?: PluginMetadataRegistryView;
  context: ProviderNormalizeResolvedModelContext;
}): ProviderRuntimeModel | undefined;
declare function applyProviderResolvedTransportWithPlugin(params: ProviderRuntimeLookup & {
  context: ProviderNormalizeResolvedModelContext;
}): ProviderRuntimeModel | undefined;
declare function normalizeProviderTransportWithPlugin(params: ProviderRuntimeLookup & {
  modelId?: string | null;
  context: ProviderNormalizeTransportContext;
}): {
  api?: string | null;
  baseUrl?: string;
} | undefined;
declare const buildProviderUnknownModelHintWithPlugin: (params: ProviderRuntimeLookup & {
  context: ProviderBuildUnknownModelHintContext;
}) => string | undefined;
//#endregion
//#region src/infra/net/pinned-dispatcher-pool.d.ts
type PinnedDispatcherLease = {
  dispatcher: Dispatcher;
  reused: boolean;
  release: () => Promise<void>;
};
/**
 * Bounded cache of reusable DNS-pinned dispatchers.
 *
 * Callers must perform fresh DNS and SSRF validation before every acquisition
 * and include the resulting origin, address set, and connection policy in the key.
 */
declare class PinnedDispatcherPool {
  private readonly entries;
  private closed;
  acquire(params: {
    key: string;
    createDispatcher: () => Dispatcher;
  }): PinnedDispatcherLease | undefined;
  closeAll(): Promise<void>;
  private createLease;
  private retireEntry;
  private startClose;
}
//#endregion
//#region src/infra/net/fetch-guard.d.ts
type FetchLike$1 = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
declare const GUARDED_FETCH_MODE: {
  readonly STRICT: "strict";
  readonly TRUSTED_ENV_PROXY: "trusted_env_proxy";
  readonly TRUSTED_EXPLICIT_PROXY: "trusted_explicit_proxy";
};
type GuardedFetchMode = (typeof GUARDED_FETCH_MODE)[keyof typeof GUARDED_FETCH_MODE];
type GuardedFetchOptions = {
  url: string;
  fetchImpl?: FetchLike$1;
  /** Final synchronous check after transport preparation and before each request or redirect. */
  beforeRequest?: () => void | undefined;
  /** Observes response headers for each hop, including redirects, before cleanup. */
  onResponse?: (status: number) => void;
  init?: RequestInit;
  capture?: false | {
    flowId?: string;
    meta?: Record<string, unknown>;
    sensitiveRequestHeaderNames?: readonly string[];
  };
  maxRedirects?: number;
  /**
   * Allow replaying unsafe request methods and bodies across cross-origin redirects.
   * Sensitive cross-origin headers (for example Authorization/Cookie) are still stripped.
   * Defaults to false.
   */
  allowCrossOriginUnsafeRedirectReplay?: boolean;
  /** Reject cross-origin redirects that would replay an unsafe body. Mutually exclusive with allow. */
  rejectCrossOriginUnsafeRedirectReplay?: boolean;
  timeoutMs?: number;
  /** Header/body inactivity budget; does not impose a whole-stream or connect deadline. */
  streamTimeoutMs?: number;
  signal?: AbortSignal;
  requireHttps?: boolean;
  policy?: SsrFPolicy;
  lookupFn?: LookupFn;
  dispatcherPolicy?: PinnedDispatcherPolicy;
  /** Resolve a synchronous per-hop override so redirects can change proxy or direct routing. */
  resolveDispatcherPolicy?: (url: URL) => PinnedDispatcherPolicy | undefined;
  retainAuthorizationRedirectHostnameAllowlist?: string[];
  mode?: GuardedFetchMode;
  pinDns?: boolean;
  /** @deprecated use `mode: "trusted_env_proxy"` for trusted/operator-controlled URLs. */
  proxy?: "env";
  /**
   * @deprecated use `mode: "trusted_env_proxy"` instead.
   */
  dangerouslyAllowEnvProxyWithoutPinnedDns?: boolean;
  auditContext?: string;
  /** Internal opt-in for reusing freshly revalidated, direct pinned dispatchers. */
  dispatcherPool?: PinnedDispatcherPool;
};
type GuardedFetchResult = {
  response: Response;
  /** The request caller/deadline signal, active until release. */
  signal?: AbortSignal;
  finalUrl: string;
  release: () => Promise<void>;
  refreshTimeout?: () => void;
  dispatcherReused?: boolean;
};
declare function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<GuardedFetchResult>;
//#endregion
//#region src/infra/http-response-body.d.ts
type ReadResponseTextPrefixOptions = {
  signal?: AbortSignal;
  chunkTimeoutMs?: number;
  onIdleTimeout?: (params: {
    chunkTimeoutMs: number;
  }) => Error;
  /** Static timeout or lazy resolver evaluated immediately before body consumption. */
  timeoutMs?: number | (() => number);
  onTimeout?: (params: {
    timeoutMs: number;
  }) => Error;
};
/** Reads a response body under byte, idle, and overall timeout bounds. */
declare function readResponseWithLimit(response: Response, maxBytes: number, options?: ReadResponseTextPrefixOptions & {
  onOverflow?: (params: {
    size: number;
    maxBytes: number;
    res: Response;
  }) => Error;
}): Promise<Buffer>;
/** Reads a small collapsed text prefix from a response body for diagnostics/errors. */
declare function readResponseTextSnippet(response: Response, options?: ReadResponseTextPrefixOptions & {
  maxBytes?: number;
  maxChars?: number;
}): Promise<string | undefined>;
//#endregion
//#region src/agents/provider-http-errors.d.ts
type ProviderResponseReadOptions = ReadResponseTextPrefixOptions & {
  maxBytes?: number;
  onOverflow?: (params: {
    size: number;
    maxBytes: number;
    res: Response;
  }) => Error;
  /** Credentials that must not appear in malformed-response diagnostics. */
  requestHeaders?: HeadersInit;
  /** Caller-facing message for malformed JSON or a non-object JSON response. */
  malformedResponseError?: string;
};
type ProviderHttpErrorOptions = {
  statusPrefix?: string;
  signal?: AbortSignal;
  maxBodyBytes?: number;
  bodyTimeoutMs?: ReadResponseTextPrefixOptions["timeoutMs"];
  onBodyTimeout?: NonNullable<ReadResponseTextPrefixOptions["onTimeout"]>;
  /** Scrub reflected request credentials before retaining response diagnostics. */
  requestHeaders?: HeadersInit;
};
/** Reads a successful provider text response under a byte cap. */
declare function readProviderTextResponse(response: Response, label: string, opts?: ProviderResponseReadOptions): Promise<string>;
type ProviderErrorPayloadMetadata = {
  detail?: string;
  code?: string;
  type?: string;
};
type ProviderHttpErrorInfo = ProviderErrorPayloadMetadata & {
  body?: string;
  requestId?: string;
  retryAfterMs?: number;
};
declare class ProviderHttpError extends Error {
  readonly status: number;
  readonly statusCode: number;
  retryAfterMs?: number;
  readonly code?: string;
  readonly errorCode?: string;
  readonly errorType?: string;
  readonly errorBody?: string;
  readonly requestId?: string;
  constructor(message: string, params: Omit<ProviderHttpErrorInfo, "detail"> & {
    status: number;
  });
}
declare function createProviderHttpError(response: Response, label: string, options?: ProviderHttpErrorOptions): Promise<ProviderHttpError>;
/**
 * Parses a provider JSON response under a byte cap and wraps malformed JSON with the caller's label.
 *
 * The body is read through the same bounded reader as binary responses so a provider that streams an
 * unbounded JSON body cannot force the runtime to buffer the whole payload before parsing.
 */
declare function readProviderJsonResponse<T>(response: Response, label: string, opts?: ProviderResponseReadOptions): Promise<T>;
//#endregion
//#region src/infra/errors.d.ts
declare function formatErrorMessage(err: unknown): string;
declare function formatUncaughtError(err: unknown): string;
//#endregion
//#region src/logging/redact-pattern-runtime.d.ts
declare function readRedactMatch(args: unknown[]): {
  match: string;
  groups: string[];
  input: string;
  offset: number;
};
type RedactMatch = ReturnType<typeof readRedactMatch> & {
  replacement?: string;
};
type RedactContext = {
  pattern: ResolvedRedactPattern;
  /** Prepend one complete, newline-bounded source block; true means older input cannot matter. */
  prepend: () => {
    consume: (text: string) => void;
    finish: () => boolean;
  };
  /** Resolve the prepended history from its newline-boundary state (false at byte zero). */
  resolve: (active: boolean) => void;
  /** Return the state after a complete, newline-bounded window without changing pattern. */
  advance: (text: string) => boolean;
};
/**
 * Programmatic synchronous rule; never serialized into logging.redactPatterns.
 * Each call uses its current input and fresh local state. Yield nonempty exact
 * matches in order without overlap, with UTF-16 offsets and that same input.
 * groups uses "" for unmatched captures; the last nonempty capture selects the
 * secret's last occurrence in match, or an empty array selects the whole match.
 * replacement carries a fixed policy mask; absent values use the caller's token hints.
 */
type RedactMatcher = {
  readonly source: string;
  readonly exec: (text: string) => Iterable<RedactMatch>;
  readonly createContext?: () => RedactContext;
};
type ResolvedRedactPattern = RegExp | RedactMatcher;
type RedactPattern = string | ResolvedRedactPattern;
//#endregion
//#region src/logging/redact.d.ts
type RedactSensitiveMode = "off" | "tools";
type RedactOptions = {
  mode?: RedactSensitiveMode;
  patterns?: readonly RedactPattern[];
};
declare function redactSensitiveText(text: string, options?: RedactOptions): string;
declare function redactToolPayloadText(text: string): string;
declare function redactSensitiveFieldValue(key: string, value: string, options?: RedactOptions): string;
//#endregion
//#region src/plugins/capability-catalog-context.types.d.ts
/** Host operations stay native; catalog construction must not start sessions or read stores. */
type PluginCapabilityCatalogContext = {
  /** @deprecated Use isProviderApiKeyConfiguredAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  isProviderApiKeyConfigured: typeof isProviderApiKeyConfigured;
  isProviderApiKeyConfiguredAsync?: typeof isProviderApiKeyConfiguredAsync;
  /** @deprecated Use isProviderAuthProfileConfiguredAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  isProviderAuthProfileConfigured: typeof isProviderAuthProfileConfigured;
  isProviderAuthProfileConfiguredAsync?: typeof isProviderAuthProfileConfiguredAsync;
  resolveAgentDir: typeof resolveAgentDir;
  createRealtimeTranscriptionWebSocketSession: typeof createRealtimeTranscriptionWebSocketSession;
  resolveProviderRequestHeaders: typeof resolveProviderRequestHeaders;
  resolveProviderAuthProfileApiKey: typeof resolveProviderAuthProfileApiKey;
  resolveApiKeyForProvider: typeof resolveApiKeyForProviderCore;
  /** @deprecated Use the host context's captureWsEventAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  captureWsEvent: typeof captureWsEvent;
  createDebugProxyWebSocketAgent: typeof createDebugProxyWebSocketAgent;
  resolveDebugProxySettings: typeof resolveDebugProxySettings;
  fetchWithSsrFGuard: typeof fetchWithSsrFGuard;
  createProviderHttpError: typeof createProviderHttpError;
  readProviderJsonResponse: typeof readProviderJsonResponse;
  readProviderTextResponse: typeof readProviderTextResponse;
  formatErrorMessage: typeof formatErrorMessage;
  warn: typeof warn;
  redactSensitiveText: typeof redactSensitiveText;
};
type PluginCapabilityCatalogEntry = PluginCapabilityCatalog | ((context: PluginCapabilityCatalogContext) => PluginCapabilityCatalog);
/** Native hosts supply asynchronous capture while preserving the legacy plugin context. */
type PluginCapabilityCatalogHostContext = PluginCapabilityCatalogContext & {
  isProviderApiKeyConfiguredAsync: typeof isProviderApiKeyConfiguredAsync;
  isProviderAuthProfileConfiguredAsync: typeof isProviderAuthProfileConfiguredAsync;
  captureWsEventAsync: typeof captureWsEventAsync;
};
type PluginCapabilityCatalogHostEntry = PluginCapabilityCatalog | ((context: PluginCapabilityCatalogHostContext) => PluginCapabilityCatalog);
//#endregion
//#region src/plugins/worker-profile-suggestion.types.d.ts
/** A proposed config entry; it cannot be used for placement until the Gateway saves it. */
type SuggestedWorkerProfile = {
  id: string;
  profile: CloudWorkerProfileConfig;
  providerDisplayId?: string;
};
/** Plugin-owned discovery caches belong to the setup inventory; adoption explicitly refreshes them. */
type WorkerProfileSuggestionDiscovery = (params: {
  refresh?: boolean;
}) => Promise<SuggestedWorkerProfile | undefined>;
//#endregion
//#region src/plugins/config-schema.d.ts
type BuildPluginConfigSchemaOptions = {
  /** @deprecated Declare top-level `uiHints` in `openclaw.plugin.json`. */
  uiHints?: Record<string, PluginConfigUiHint>;
  safeParse?: OpenClawPluginConfigSchema["safeParse"];
};
type BuildJsonPluginConfigSchemaOptions = BuildPluginConfigSchemaOptions & {
  cacheKey?: string;
};
/** Build a plugin config schema from JSON Schema with runtime validation/default support. */
declare function buildJsonPluginConfigSchema(schema: JsonSchemaObject, options?: BuildJsonPluginConfigSchemaOptions): OpenClawPluginConfigSchema;
/** Build a plugin config schema from Zod, exporting JSON Schema when the Zod runtime supports it. */
declare function buildPluginConfigSchema(schema: ZodTypeAny, options?: BuildPluginConfigSchemaOptions): OpenClawPluginConfigSchema;
/** Return a schema for plugins that intentionally accept no config keys. */
declare function emptyPluginConfigSchema(): OpenClawPluginConfigSchema;
//#endregion
//#region src/plugin-sdk/plugin-entry.d.ts
type ProviderBuiltInModelSuppressionContext = ProviderBuiltInModelSuppressionContext$1;
/** Options for a plugin entry that registers providers, tools, commands, or services. */
type DefinePluginEntryOptions = {
  id: string;
  name: string;
  description: string;
  /**
   * @deprecated Declare exclusive plugin kind in `openclaw.plugin.json` via
   * manifest `kind`. Runtime-entry `kind` remains only as a compatibility
   * fallback for older plugins.
   */
  kind?: OpenClawPluginDefinition["kind"];
  configSchema?: OpenClawPluginConfigSchema | (() => OpenClawPluginConfigSchema);
  reload?: OpenClawPluginDefinition["reload"];
  nodeHostCommands?: OpenClawPluginDefinition["nodeHostCommands"];
  securityAuditCollectors?: OpenClawPluginDefinition["securityAuditCollectors"];
  register: NonNullable<OpenClawPluginDefinition["register"]>;
};
/** Normalized object shape that OpenClaw loads from a plugin entry module. */
type DefinedPluginEntry = Omit<DefinePluginEntryOptions, "configSchema"> & {
  configSchema: OpenClawPluginConfigSchema;
};
/**
 * Canonical entry helper for non-channel plugins.
 *
 * Use this for provider, tool, command, service, memory, and context-engine
 * plugins. Channel plugins should use `defineChannelPluginEntry(...)` from
 * `openclaw/plugin-sdk/core` so they inherit the channel capability wiring.
 *
 * @experimental Pin and test OpenClaw host versions; existing compatibility windows still apply.
 */
declare function definePluginEntry({ id, name, description, kind, configSchema, reload, nodeHostCommands, securityAuditCollectors, register }: DefinePluginEntryOptions): DefinedPluginEntry;
//#endregion
//#region src/channels/plugins/outbound/presentation-limits.d.ts
/** Limit native controls while preserving authored and fallback text in full. */
declare function adaptMessagePresentationForChannel(params: {
  presentation: MessagePresentation;
  capabilities?: ChannelPresentationCapabilities;
}): MessagePresentation;
/** Return the subset of buttons that can still be rendered under action limits. */
declare function applyPresentationActionLimits(buttons: readonly MessagePresentationButton[], capabilities?: ChannelPresentationCapabilities): MessagePresentationButton[];
/** Resolve an action page size that leaves room for reserved actions on the target channel. */
declare function presentationPageSize(capabilities?: ChannelPresentationCapabilities, reservedActions?: number, maxPageSize?: number): number;
//#endregion
//#region src/model-picker/capabilities.d.ts
type ModelPickerCapabilityProfile = {
  presentation: ChannelPresentationCapabilities;
  callback: {
    limit: number;
    unit: "utf8-bytes" | "utf16-units";
  };
  response: {
    supportsEphemeral: boolean;
    supportsEdit: boolean;
    supportsReplace: boolean;
  };
};
//#endregion
//#region src/channels/plugins/outbound/presentation-delivery.d.ts
/** Apply the same native rendering and fallback policy to every channel delivery path. */
declare function renderPresentationForDelivery(handler: {
  presentationCapabilities?: ChannelPresentationCapabilities;
  renderPresentation?: (payload: ReplyPayload$1 & {
    presentation: MessagePresentation;
  }, sourcePresentation?: MessagePresentation) => ReplyPayload$1 | null | Promise<ReplyPayload$1 | null>;
}, payload: ReplyPayload$1): Promise<ReplyPayload$1>;
//#endregion
//#region src/plugin-sdk/interactive-runtime.d.ts
/** @deprecated Use MessagePresentation helpers for new rendering paths. */
declare const reduceInteractiveReply: typeof reduceLegacyInteractiveReply;
//#endregion
//#region src/channels/plugins/media-payload.d.ts
/** Input media item used by channel outbound payload builders. */
type MediaPayloadInput = Required<Pick<MediaFact, "path">> & Pick<MediaFact, "contentType">;
/**
 * Legacy-compatible media payload shape consumed by plugin send helpers.
 * @deprecated Inbound contexts use `media`; outbound replies use lowercase
 * `ReplyPayload.mediaUrl`/`mediaUrls`.
 */
type MediaPayload = Omit<MediaFactLegacyProjection, "MediaTranscribedIndexes">;
/**
 * Builds single-item and list legacy media fields.
 * @deprecated Inbound contexts use `media`; outbound replies use lowercase
 * `ReplyPayload.mediaUrl`/`mediaUrls`.
 */
declare function buildMediaPayload(mediaList: MediaPayloadInput[], opts?: {
  preserveMediaTypeCardinality?: boolean;
}): MediaPayload;
//#endregion
//#region src/plugin-sdk/reply-payload.d.ts
/** Plugin-facing reply payload without core-only trusted local media internals. */
type ReplyPayload = Omit<ReplyPayload$1, "trustedLocalMedia">;
/** The shared dispatcher will persist confirmed delivery; channel adapters must not mirror it. */
declare function hasReplyPayloadFinalDeliveryCapture(payload: ReplyPayload): boolean;
type AskUserQuestionOptionIndices = ReadonlyMap<string, ReadonlyMap<string, number>>;
/** Read bounded Gateway-owned option ordering for one native ask_user question. */
declare function resolveAskUserQuestionOptionIndices(payload: Pick<ReplyPayload, "channelData">): AskUserQuestionOptionIndices | undefined;
/** Match one presented choice to its Gateway-owned option index. */
declare function resolveAskUserQuestionOptionIndex(params: {
  questionOptionIndices?: AskUserQuestionOptionIndices;
  questionId: string;
  optionValue: string;
}): number | undefined;
/** Normalized outbound reply payload accepted by channel send helpers. */
type OutboundReplyPayload = {
  /** Plain text reply body. */
  text?: string;
  /** Visible body a channel adapter may use when native structured content requires text. */
  fallbackText?: {
    text: string;
    /** Batch payload replaced when the adapter adopts this fallback body. */
    replacesPayloadIndex?: number;
  };
  /** Ordered media attachments for channels that can send multiple media items. */
  mediaUrls?: string[];
  /** Legacy single media attachment. */
  mediaUrl?: string;
  /** Rich presentation payload for channels that support structured replies. */
  presentation?: ReplyPayload$1["presentation"];
  /**
   * @deprecated Use presentation. Runtime support remains for legacy producers.
   */
  interactive?: ReplyPayload$1["interactive"];
  /** Channel-specific opaque data forwarded to outbound adapters. */
  channelData?: ReplyPayload$1["channelData"];
  /** Marks media as sensitive for channel-specific spoiler/safety handling. */
  sensitiveMedia?: boolean;
  /** Platform message id that the outbound reply should target when supported. */
  replyToId?: string;
  /** Portable geographic location or named place. */
  location?: ReplyPayload$1["location"];
  /** Ask supporting channels to render video media as a round video note. */
  videoAsNote?: boolean;
};
/** Minimal payload shape used to identify reasoning/thinking replies. */
type ReasoningReplyPayload = {
  /** Reply text that may carry hidden reasoning markers. */
  text?: string;
  /** Explicit reasoning flag from upstream payload producers. */
  isReasoning?: boolean;
  /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
  isCommentary?: boolean;
};
type SendPayloadContext = Parameters<NonNullable<ChannelOutboundAdapter["sendPayload"]>>[0];
type SendPayloadResult = Awaited<ReturnType<NonNullable<ChannelOutboundAdapter["sendPayload"]>>>;
type SendPayloadAdapter = Pick<ChannelOutboundAdapter, "sendMedia" | "sendText" | "chunker" | "textChunkLimit">;
/** Detect reasoning replies from explicit flags or common reasoning text prefixes. */
declare function isReasoningReplyPayload(payload: ReasoningReplyPayload): boolean;
/** Extract the supported outbound reply fields from loose tool or agent payload objects. */
declare function normalizeOutboundReplyPayload(payload: Record<string, unknown>): OutboundReplyPayload;
/** Wrap a deliverer so callers can hand it arbitrary payloads while channels receive normalized data. */
declare function createNormalizedOutboundDeliverer(handler: (payload: OutboundReplyPayload) => Promise<void>): (payload: unknown) => Promise<void>;
/** Resolve media URLs from a channel sendPayload context after legacy fallback normalization. */
declare function resolvePayloadMediaUrls(payload: SendPayloadContext["payload"]): string[];
/** Check whether an outbound payload includes any sendable text, media, or rich reply content. */
declare function hasOutboundReplyContent(payload: {
  text?: string;
  mediaUrls?: string[];
  mediaUrl?: string;
  presentation?: unknown;
  interactive?: unknown;
  channelData?: unknown;
}, options?: {
  trimText?: boolean;
}): boolean;
/** Preserve caller-provided chunking, but fall back to the full text when chunkers return nothing. */
declare function resolveTextChunksWithFallback(text: string, chunks: readonly string[]): string[];
/** Send media-first payloads intact, or chunk text-only payloads through the caller's transport hooks. */
declare function sendPayloadWithChunkedTextAndMedia<TContext extends {
  payload: object;
}, TResult>(params: {
  /** Caller context containing the loose outbound payload. */
  ctx: TContext;
  /** Text length limit passed to the chunker for text-only payloads. */
  textChunkLimit?: number;
  /** Optional text chunker used only when no media URLs are present. */
  chunker?: ((text: string, limit: number) => string[]) | null;
  /** Transport hook for text-only chunks. */
  sendText: (ctx: TContext & {
    text: string;
  }) => Promise<TResult>;
  /** Transport hook for media sends; first media receives the caption text. */
  sendMedia: (ctx: TContext & {
    text: string;
    mediaUrl: string;
  }) => Promise<TResult>;
  /** Result returned when payload has neither text nor media. */
  emptyResult: TResult;
  /** Host callback that persists each completed sub-send before the next one starts. */
  onResult?: (result: TResult) => Promise<void> | void;
}): Promise<TResult>;
/**
 * Sends non-empty media URLs with caption text on the first actual send.
 * Returns the last send result, or undefined when every URL is empty.
 */
declare function sendPayloadMediaSequence<TResult>(params: {
  /** Caption text attached to the first non-empty media URL only. */
  text: string;
  /** Ordered media URLs to send, with empty entries skipped. */
  mediaUrls: readonly string[];
  send: (input: {
    /** Caption text for the first media send, otherwise empty. */
    text: string;
    /** Media URL for this send. */
    mediaUrl: string;
    /** Original index in `mediaUrls`. */
    index: number;
    /** Whether this is the first non-empty media entry sent. */
    isFirst: boolean;
  }) => Promise<TResult>;
  /** Called after each successful media send and before the next send starts. */
  onResult?: (result: TResult) => Promise<void> | void;
}): Promise<TResult | undefined>;
/** Sends text chunks sequentially and returns the last send result. */
declare function sendPayloadTextChunkSequence<TResult>(params: {
  /** Ordered text chunks to send. */
  chunks: readonly string[];
  send: (input: {
    text: string;
    index: number;
    isFirst: boolean;
  }) => Promise<TResult>;
  /** Called after each successful chunk send and before the next send starts. */
  onResult?: (result: TResult) => Promise<void> | void;
}): Promise<TResult | undefined>;
/** Sends a media sequence or returns a fallback when no media item is sent. */
declare function sendPayloadMediaSequenceOrFallback<TResult>(params: {
  /** Caption text attached to the first non-empty media URL only. */
  text: string;
  /** Ordered media URLs to send, with empty entries skipped. */
  mediaUrls: readonly string[];
  send: (input: {
    text: string;
    mediaUrl: string;
    index: number;
    isFirst: boolean;
  }) => Promise<TResult>;
  onResult?: (result: TResult) => Promise<void> | void;
  /** Result returned when no media item is sent. */
  fallbackResult: TResult;
  /** Optional callback used instead of `fallbackResult` when no media item is sent. */
  sendNoMedia?: () => Promise<TResult>;
}): Promise<TResult>;
/** Sends media when present, then always runs finalization and returns its result. */
declare function sendPayloadMediaSequenceAndFinalize<TMediaResult, TResult>(params: {
  /** Caption text attached to the first non-empty media URL only. */
  text: string;
  /** Ordered media URLs to send before finalization. */
  mediaUrls: readonly string[];
  send: (input: {
    text: string;
    mediaUrl: string;
    index: number;
    isFirst: boolean;
  }) => Promise<TMediaResult>;
  onResult?: (result: TMediaResult) => Promise<void> | void;
  /** Final callback whose result is returned after optional media sends. */
  finalize: () => Promise<TResult>;
}): Promise<TResult>;
/** Sends normalized text/media payloads through a channel outbound adapter. */
declare function sendTextMediaPayload(params: {
  /** Channel id used in the empty fallback result. */
  channel: string;
  /** Channel send payload context. */
  ctx: SendPayloadContext;
  /** Adapter transport hooks for text, media, and optional chunking. */
  adapter: SendPayloadAdapter;
}): Promise<SendPayloadResult>;
/** Detect numeric-looking target ids for channels that distinguish ids from handles. */
declare function isNumericTargetId(raw: string): boolean;
/** Append attachment links to plain text when the channel cannot send media inline. */
declare function formatTextWithAttachmentLinks(text: string | undefined, mediaUrls: string[]): string;
/** Send a caption with only the first media item, mirroring caption-limited channel transports. */
declare function sendMediaWithLeadingCaption(params: {
  mediaUrls: string[];
  caption: string;
  send: (payload: {
    mediaUrl: string;
    caption?: string;
  }) => Promise<void>;
  onError?: (params: {
    error: unknown;
    mediaUrl: string;
    caption?: string;
    index: number;
    isFirst: boolean;
  }) => Promise<void> | void;
}): Promise<boolean>;
/** Deliver media with leading caption when possible, otherwise fall back to chunked text. */
declare function deliverTextOrMediaReply(params: {
  payload: OutboundReplyPayload;
  text: string;
  chunkText?: (text: string) => readonly string[];
  sendText: (text: string) => Promise<void>;
  sendMedia: (payload: {
    mediaUrl: string;
    caption?: string;
  }) => Promise<void>;
  onMediaError?: (params: {
    error: unknown;
    mediaUrl: string;
    caption?: string;
    index: number;
    isFirst: boolean;
  }) => Promise<void> | void;
}): Promise<"empty" | "text" | "media">;
/** Send text with attachment links appended for channels without native media upload. */
declare function deliverFormattedTextWithAttachments(params: {
  payload: OutboundReplyPayload;
  send: (params: {
    text: string;
    replyToId?: string;
  }) => Promise<void>;
}): Promise<boolean>;
//#endregion
//#region extensions/telegram/src/button-types.d.ts
type TelegramButtonStyle = "danger" | "success" | "primary";
type TelegramInlineButton = {
  text: string;
  callback_data?: string;
  url?: string;
  web_app?: {
    url: string;
  };
  disabled?: Record<string, never>;
  style?: TelegramButtonStyle;
};
type TelegramCallbackButton = Pick<TelegramInlineButton, "text" | "style"> & {
  callback_data: string;
};
type TelegramInlineButtons = ReadonlyArray<ReadonlyArray<TelegramInlineButton>>;
//#endregion
//#region src/channels/plugins/account-action-gate.d.ts
type ActionGate<T extends Record<string, boolean | undefined>> = (key: keyof T, defaultValue?: boolean) => boolean;
/**
 * Creates an action gate where account-specific flags override channel-level defaults.
 */
declare function createAccountActionGate<T extends Record<string, boolean | undefined>>(params: {
  baseActions?: T;
  accountActions?: T;
}): ActionGate<T>;
//#endregion
//#region src/config/channel-account-config.d.ts
type AccountMergeOptions = {
  omitKeys?: string[];
  nestedObjectKeys?: string[];
  inheritEmptyKeys?: Record<string, "array" | "object">;
  preserveRootAllowFrom?: boolean;
};
/** Merge authored account overrides over channel defaults, with owner-selected collection rules. */
declare function mergeAccountConfig<TConfig extends Record<string, unknown>>(params: AccountMergeOptions & {
  channelConfig: TConfig | undefined;
  accountConfig: Partial<TConfig> | undefined;
}): TConfig;
/** Resolve a named account before applying the shared channel inheritance rules. */
declare function resolveMergedAccountConfig<TConfig extends Record<string, unknown>>(params: AccountMergeOptions & {
  channelConfig: TConfig | undefined;
  accounts: Record<string, Partial<TConfig>> | undefined;
  accountId: string;
  normalizeAccountId?: (accountId: string) => string;
  channelId?: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
}): TConfig;
//#endregion
//#region src/channels/plugins/account-helpers.d.ts
declare function createAccountListHelpers<TConfig extends Record<string, unknown> = Record<string, unknown>>(channelKey: string, options?: {
  normalizeAccountId?: (id: string) => string;
  omitKeys?: Array<(keyof TConfig & string) | "defaultAccount">;
  nestedObjectKeys?: Array<keyof TConfig & string>;
  allowUnlistedDefaultAccount?: boolean;
  additionalAccountIds?: (cfg: OpenClawConfig) => Iterable<string>;
  fallbackAccountIdWhenEmpty?: string | false;
  implicitDefaultAccount?: {
    channelKeys?: readonly string[];
    envVars?: readonly string[];
  };
  hasImplicitDefaultAccount?: (cfg: OpenClawConfig) => boolean;
  resolveImplicitAccountId?: (cfg: OpenClawConfig) => string | undefined;
}): {
  listConfiguredAccountIds: (cfg: OpenClawConfig) => string[];
  listAccountIds: (cfg: OpenClawConfig) => string[];
  resolveDefaultAccountId: (cfg: OpenClawConfig) => string;
  resolveAccountConfig: (cfg: OpenClawConfig, accountId: string) => TConfig;
};
declare function hasConfiguredAccountValue(value: unknown): boolean;
declare function listCombinedAccountIds(params: {
  configuredAccountIds: Iterable<string>;
  additionalAccountIds?: Iterable<string>;
  implicitAccountId?: string | undefined;
  fallbackAccountIdWhenEmpty?: string | undefined;
}): string[];
declare function resolveListedDefaultAccountId(params: {
  accountIds: readonly string[];
  configuredDefaultAccountId?: string | undefined;
  allowUnlistedDefaultAccount?: boolean;
  ambiguousFallbackAccountId?: string | undefined;
  normalizeListedAccountId?: ((accountId: string) => string) | undefined;
}): string;
type AccountSnapshotInput = {
  accountId?: string | null;
  enabled?: boolean | null;
  name?: string | null | undefined;
};
declare function describeAccountSnapshot(params: {
  account: AccountSnapshotInput;
  configured?: boolean | undefined;
  extra?: Record<string, unknown> | undefined;
}): ChannelAccountSnapshot;
declare function describeWebhookAccountSnapshot(params: {
  account: AccountSnapshotInput;
  configured?: boolean | undefined;
  mode?: string | undefined;
  extra?: Record<string, unknown> | undefined;
}): ChannelAccountSnapshot;
//#endregion
//#region src/plugin-sdk/account-configured-ids.d.ts
/** List normalized configured account ids from a raw channel account record map. */
declare function listConfiguredAccountIds(params: {
  accounts: Record<string, unknown> | undefined;
  normalizeAccountId: (accountId: string) => string;
}): string[];
//#endregion
//#region src/plugin-sdk/account-core.d.ts
/** Resolve an account by id, then fall back to the default account when the primary lacks credentials. */
declare function resolveAccountWithDefaultFallback<TAccount>(params: {
  accountId?: string | null;
  normalizeAccountId: (accountId?: string | null) => string;
  resolvePrimary: (accountId: string) => TAccount;
  hasCredential: (account: TAccount) => boolean;
  resolveDefaultAccountId: () => string;
}): TAccount;
//#endregion
//#region src/infra/net/proxy-fetch.d.ts
/**
 * Create a fetch function that routes requests through the given HTTP proxy.
 * Uses undici's ProxyAgent under the hood.
 */
declare function makeProxyFetch(proxyUrl: string): typeof fetch;
//#endregion
//#region extensions/telegram/src/fetch.d.ts
type TelegramDispatcherAttempt = {
  dispatcherPolicy?: PinnedDispatcherPolicy;
};
declare function shouldRetryTelegramTransportFallback(err: unknown): boolean;
type TelegramTransport = {
  fetch: typeof fetch;
  sourceFetch: typeof fetch;
  dispatcherAttempts?: TelegramDispatcherAttempt[];
  /**
   * Promote this transport to its next fallback dispatcher before the next
   * request. The original error, when available, is retained in diagnostics.
   * Returns false when no fallback path exists.
   */
  forceFallback?: (reason: string, err?: unknown) => boolean;
  /**
   * Release all dispatchers owned by this transport and the TCP sockets they
   * hold. Safe to call multiple times; subsequent calls resolve immediately.
   *
   * Callers that pass their own `proxyFetch` own the underlying dispatcher
   * lifecycle themselves and this is effectively a no-op. Callers that let
   * this module construct the transport MUST invoke `close()` when the
   * transport is no longer needed (e.g. on polling session dispose or when
   * swapping transports after a network stall); otherwise undici keeps the
   * keep-alive sockets open indefinitely, leaking hundreds of connections
   * to api.telegram.org over long-running sessions.
   */
  close(): Promise<void>;
};
declare function resolveTelegramTransport(proxyFetch?: typeof fetch, options?: {
  network?: TelegramNetworkConfig$1;
}): TelegramTransport;
declare function resolveTelegramFetch(proxyFetch?: typeof fetch, options?: {
  network?: TelegramNetworkConfig$1;
}): typeof fetch;
//#endregion
//#region extensions/telegram/src/token.d.ts
type CredentialUnavailableDiagnostic$1 = Extract<ReturnType<typeof tryReadSecretFileSync>, {
  status: "configured_unavailable";
}>["diagnostic"];
type TelegramTokenSource = "env" | "tokenFile" | "config" | "none";
type TelegramTokenResolution = BaseTokenResolution & {
  source: TelegramTokenSource;
  credentialDiagnostics?: CredentialUnavailableDiagnostic$1[];
};
type ResolveTelegramTokenOpts = {
  envToken?: string | null;
  accountId?: string | null;
  logMissingFile?: (message: string) => void;
};
declare function resolveTelegramToken(cfg?: OpenClawConfig, opts?: ResolveTelegramTokenOpts): TelegramTokenResolution;
//#endregion
//#region extensions/telegram/src/account-config.d.ts
declare function resolveTelegramAccountConfig(cfg: OpenClawConfig, accountId: string): TelegramAccountConfig$1 | undefined;
declare function mergeTelegramAccountConfig(cfg: OpenClawConfig, accountId: string): TelegramAccountConfig$1;
//#endregion
//#region extensions/telegram/src/account-selection.d.ts
declare const { listAccountIds: listTelegramAccountIds }: {
  listConfiguredAccountIds: (cfg: OpenClawConfig) => string[];
  listAccountIds: (cfg: OpenClawConfig) => string[];
  resolveDefaultAccountId: (cfg: OpenClawConfig) => string;
  resolveAccountConfig: (cfg: OpenClawConfig, accountId: string) => Record<string, unknown>;
};
//#endregion
//#region extensions/telegram/src/accounts.d.ts
type CredentialUnavailableDiagnostic = NonNullable<ReturnType<typeof resolveTelegramToken>["credentialDiagnostics"]>[number];
type ResolvedTelegramAccount = {
  accountId: string;
  enabled: boolean;
  name?: string;
  token: string;
  tokenSource: "env" | "tokenFile" | "config" | "none";
  tokenStatus: "available" | "configured_unavailable" | "missing";
  credentialDiagnostics?: CredentialUnavailableDiagnostic[];
  config: TelegramAccountConfig$1;
};
type TelegramMediaRuntimeOptions = {
  token: string;
  transport?: TelegramTransport;
  apiRoot?: string;
  trustedLocalFileRoots?: readonly string[];
  dangerouslyAllowPrivateNetwork?: boolean;
};
declare function resolveDefaultTelegramAccountId(cfg: OpenClawConfig): string;
declare function createTelegramActionGate(params: {
  cfg: OpenClawConfig;
  accountId?: string | null;
}): (key: keyof TelegramActionConfig$1, defaultValue?: boolean) => boolean;
declare function resolveTelegramMediaRuntimeOptions(params: {
  cfg: OpenClawConfig;
  accountId?: string | null;
  token: string;
  transport?: TelegramTransport;
}): TelegramMediaRuntimeOptions;
type TelegramPollActionGateState = {
  sendMessageEnabled: boolean;
  pollEnabled: boolean;
  enabled: boolean;
};
declare function resolveTelegramPollActionGateState(isActionEnabled: (key: keyof TelegramActionConfig$1, defaultValue?: boolean) => boolean): TelegramPollActionGateState;
declare function resolveTelegramAccount(params: {
  cfg: OpenClawConfig;
  accountId?: string | null;
}): ResolvedTelegramAccount;
declare function listEnabledTelegramAccounts(cfg: OpenClawConfig): ResolvedTelegramAccount[];
//#endregion
//#region src/channels/plugins/binding-types.d.ts
/**
 * Stateful target descriptor produced by a binding consumer.
 */
type StatefulBindingTargetDescriptor = {
  kind: "stateful";
  driverId: string;
  sessionKey: string;
  agentId: string;
  label?: string;
};
/**
 * Materialized binding record plus the stateful target it points at.
 */
type ConfiguredBindingRecordResolution = {
  record: SessionBindingRecord;
  statefulTarget: StatefulBindingTargetDescriptor;
};
/**
 * Compiled binding rule with provider matcher, target factory, and static target facts.
 */
type CompiledConfiguredBinding = {
  channel: ChannelId$1;
  accountPattern?: string;
  binding: AgentBinding;
  bindingConversationId: string;
  target: ChannelConfiguredBindingConversationRef;
  agentId: string;
  provider: ChannelConfiguredBindingProvider;
  targetFactory: {
    driverId: string;
    materialize: (params: {
      accountId: string;
      conversation: ChannelConfiguredBindingConversationRef;
    }) => ConfiguredBindingRecordResolution;
  };
};
/**
 * Full configured binding resolution used to rewrite routes and prepare target sessions.
 */
type ConfiguredBindingResolution = ConfiguredBindingRecordResolution & {
  conversation: ConversationRef;
  compiledBinding: CompiledConfiguredBinding;
  match: ChannelConfiguredBindingMatch;
};
//#endregion
//#region src/channels/plugins/binding-routing.d.ts
type ConfiguredBindingRouteResult = {
  bindingResolution: ConfiguredBindingResolution | null;
  route: ResolvedAgentRoute;
  boundSessionKey?: string;
  boundAgentId?: string;
};
type RuntimeConversationBindingRouteResult = {
  /** False only when the authoritative channel-owned binding store is temporarily unavailable. */
  bindingOwnerAvailable?: boolean;
  bindingRecord: SessionBindingRecord | null;
  route: ResolvedAgentRoute;
  boundSessionKey?: string;
  boundAgentId?: string;
  pluginId?: string;
};
type RuntimeConversationBindingRouteResolver<Result = ResolvedAgentRoute> = (selection: {
  inspection: ReturnType<typeof inspectSessionBindingByConversation>;
  bindingOwnerAvailable: boolean;
  bindingRecord: SessionBindingRecord | null;
  boundAgentId?: string;
}) => Result;
type RuntimeConversationBindingRouteInput<Result = ResolvedAgentRoute> = {
  route: ResolvedAgentRoute;
  resolveRoute?: never;
} | {
  route?: never;
  resolveRoute: RuntimeConversationBindingRouteResolver<Result>;
};
type ConfiguredBindingRouteConversationInput = {
  conversation: ConversationRef;
} | {
  channel: string;
  accountId: string;
  conversationId: string;
  parentConversationId?: string;
};
declare function resolveConfiguredBindingRoute(params: {
  cfg: OpenClawConfig;
  route: ResolvedAgentRoute;
} & ConfiguredBindingRouteConversationInput): ConfiguredBindingRouteResult;
/** @deprecated Use resolveRuntimeConversationBindingRouteAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveRuntimeConversationBindingRoute(params: RuntimeConversationBindingRouteInput & {
  touchBinding?: boolean;
} & ConfiguredBindingRouteConversationInput): RuntimeConversationBindingRouteResult;
declare function ensureConfiguredBindingRouteReady(params: {
  assertActive?: () => void;
  cfg: OpenClawConfig;
  bindingResolution: ConfiguredBindingResolution | null;
}): Promise<{
  ok: true;
} | {
  ok: false;
  error: string;
}>;
//#endregion
//#region src/channels/conversation-label.d.ts
declare function resolveConversationLabel(ctx: MsgContext): string | undefined;
//#endregion
//#region src/channels/session.types.d.ts
type InboundLastRouteUpdate = {
  sessionKey: string;
  channel: string;
  to: string;
  accountId?: string;
  threadId?: string | number;
  route?: ChannelRouteRef;
  mainDmOwnerPin?: {
    ownerRecipient: string;
    senderRecipient: string;
    onSkip?: (params: {
      ownerRecipient: string;
      senderRecipient: string;
    }) => void;
  };
};
type RecordInboundSession$1 = (params: {
  storePath: string;
  sessionKey: string;
  ctx: MsgContext;
  groupResolution?: GroupKeyResolution | null;
  createIfMissing?: boolean;
  updateLastRoute?: InboundLastRouteUpdate;
  onRecordError: (err: unknown) => void | Promise<void>;
  trackSessionMetaTask?: (task: Promise<unknown>) => void;
  assertAuthority?: () => void;
}) => Promise<void>;
//#endregion
//#region src/channels/session.d.ts
declare function recordInboundSession(params: Parameters<RecordInboundSession$1>[0]): Promise<void>;
//#endregion
//#region src/channels/session-meta.d.ts
declare function recordInboundSessionMetaSafe(params: {
  cfg: OpenClawConfig;
  agentId: string;
  sessionKey: string;
  ctx: MsgContext;
  onError?: (error: unknown) => void;
}): Promise<void>;
//#endregion
//#region src/channels/thread-binding-id.d.ts
declare function resolveThreadBindingConversationIdFromBindingId(params: {
  accountId: string;
  bindingId?: string;
}): string | undefined;
//#endregion
//#region src/channels/plugins/threading-helpers.d.ts
type ReplyToModeResolver = NonNullable<ChannelThreadingAdapter["resolveReplyToMode"]>;
declare function createStaticReplyToModeResolver(mode: ReplyToMode): ReplyToModeResolver;
declare function createTopLevelChannelReplyToModeResolver(channelId: string): ReplyToModeResolver;
declare function createScopedAccountReplyToModeResolver<TAccount>(params: {
  resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) => TAccount;
  resolveReplyToMode: (account: TAccount, chatType?: string | null) => ReplyToMode | null | undefined;
  fallback?: ReplyToMode;
}): ReplyToModeResolver;
//#endregion
//#region src/channels/thread-bindings-messages.d.ts
declare function formatThreadBindingDurationLabel(durationMs: number): string;
declare function resolveThreadBindingThreadName(params: {
  agentId?: string;
  label?: string;
}): string;
declare function resolveThreadBindingIntroText(params: {
  agentId?: string;
  label?: string;
  idleTimeoutMs?: number;
  maxAgeMs?: number;
  sessionCwd?: string;
  sessionDetails?: string[];
}): string;
declare function resolveThreadBindingFarewellText(params: {
  reason?: string;
  farewellText?: string;
  idleTimeoutMs: number;
  maxAgeMs: number;
}): string;
//#endregion
//#region src/shared/thread-binding-lifecycle.d.ts
/** Persisted timestamps and optional TTL overrides for one channel thread binding. */
type ThreadBindingLifecycleRecord = {
  /** Epoch milliseconds when the binding was created. */
  boundAt: number;
  /** Epoch milliseconds of the latest activity seen for the bound conversation. */
  lastActivityAt: number;
  /** Optional idle timeout override in milliseconds; zero disables idle expiry. */
  idleTimeoutMs?: number;
  /** Optional max-age override in milliseconds; zero disables max-age expiry. */
  maxAgeMs?: number;
};
/** Resolves the next expiration for a channel thread binding from idle and max-age limits. */
declare function resolveThreadBindingLifecycle(params: {
  /** Stored binding timestamps and optional timeout overrides. */
  record: ThreadBindingLifecycleRecord;
  /** Fallback idle timeout in milliseconds when the record has no override. */
  defaultIdleTimeoutMs: number;
  /** Fallback max-age timeout in milliseconds when the record has no override. */
  defaultMaxAgeMs: number;
}): {
  expiresAt?: number;
  reason?: "idle-expired" | "max-age-expired";
};
//#endregion
//#region src/channels/thread-bindings-policy.d.ts
type ThreadBindingSpawnKind = "subagent" | "acp";
type ThreadBindingSpawnPolicy = {
  channel: string;
  accountId: string;
  enabled: boolean;
  spawnEnabled: boolean;
  defaultSpawnContext: ThreadBindingSpawnContext;
};
type ThreadBindingSpawnContext = "isolated" | "fork";
/** Resolves thread-binding idle timeout with channel/account override before session default. */
declare function resolveThreadBindingIdleTimeoutMs(params: {
  channelIdleHoursRaw: unknown;
  sessionIdleHoursRaw: unknown;
}): number;
/** Resolves thread-binding max age with channel/account override before session default. */
declare function resolveThreadBindingMaxAgeMs(params: {
  channelMaxAgeHoursRaw: unknown;
  sessionMaxAgeHoursRaw: unknown;
}): number;
declare function resolveThreadBindingEffectiveExpiresAt(params: {
  record: ThreadBindingLifecycleRecord;
  defaultIdleTimeoutMs: number;
  defaultMaxAgeMs: number;
}): number | undefined;
declare function resolveThreadBindingsEnabled(params: {
  channelEnabledRaw: unknown;
  sessionEnabledRaw: unknown;
}): boolean;
/** Resolves effective spawn policy from account, channel, then global thread-binding config. */
declare function resolveThreadBindingSpawnPolicy(params: {
  cfg: OpenClawConfig;
  channel: string;
  accountId?: string;
  kind: ThreadBindingSpawnKind;
}): ThreadBindingSpawnPolicy;
declare function resolveThreadBindingIdleTimeoutMsForChannel(params: {
  cfg: OpenClawConfig;
  channel: string;
  accountId?: string;
}): number;
declare function resolveThreadBindingMaxAgeMsForChannel(params: {
  cfg: OpenClawConfig;
  channel: string;
  accountId?: string;
}): number;
declare function formatThreadBindingDisabledError(params: {
  channel: string;
  accountId: string;
  kind: ThreadBindingSpawnKind;
}): string;
declare function formatThreadBindingSpawnDisabledError(params: {
  channel: string;
  accountId: string;
  kind: ThreadBindingSpawnKind;
}): string;
//#endregion
//#region src/pairing/pairing-store.types.d.ts
type PairingChannel = ChannelId$1;
/** Reads approved ids from a channel/account allowFrom store. */
type ReadChannelAllowFromStoreForAccount = (params: {
  channel: PairingChannel;
  accountId: string;
  env?: NodeJS.ProcessEnv;
}) => Promise<string[]>;
/** Deletes one approved id from a channel/account allowFrom store. */
type RemoveChannelAllowFromStoreEntryForAccount = (params: {
  channel: PairingChannel;
  entry: string | number;
  accountId: string;
  env?: NodeJS.ProcessEnv;
  pairingAdapter?: ChannelPairingAdapter;
}) => Promise<{
  changed: boolean;
  allowFrom: string[];
}>;
/** Creates or reuses a pending pairing request for one channel account. */
type UpsertChannelPairingRequestForAccount = (params: {
  channel: PairingChannel;
  id: string | number;
  accountId: string;
  meta?: Record<string, string | undefined | null>;
  env?: NodeJS.ProcessEnv;
  pairingAdapter?: ChannelPairingAdapter;
}) => Promise<{
  code: string;
  created: boolean;
}>;
//#endregion
//#region src/pairing/pairing-labels.d.ts
declare function resolvePairingIdLabel(channel: PairingChannel): string;
//#endregion
//#region src/pairing/pairing-messages.d.ts
declare function buildPairingReply(params: {
  channel: PairingChannel;
  idLine: string;
  code: string;
}): string;
//#endregion
//#region src/pairing/pairing-store.read.d.ts
/** Prepare current allowlist facts; the channel owner still admits the message. */
declare function readChannelAllowFromStore(channel: PairingChannel, env?: NodeJS.ProcessEnv, accountId?: string): Promise<string[]>;
//#endregion
//#region src/pairing/pairing-store.d.ts
/** @deprecated Await readChannelAllowFromStore; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function readChannelAllowFromStoreSync(channel: PairingChannel, env?: NodeJS.ProcessEnv, accountId?: string): string[];
declare function upsertChannelPairingRequest(params: {
  channel: PairingChannel;
  id: string | number;
  accountId: string;
  meta?: Record<string, string | undefined | null>;
  env?: NodeJS.ProcessEnv;
  /** Extension channels can pass their adapter directly to bypass registry lookup. */
  pairingAdapter?: ChannelPairingAdapter;
}): Promise<{
  code: string;
  created: boolean;
}>;
//#endregion
//#region src/plugins/conversation-binding-pending.d.ts
type PendingPluginBindingRequest = PluginConversationBindingResolvedEvent["request"] & {
  id: string;
  pluginId: string;
  pluginName?: string;
  pluginRoot: string;
};
//#endregion
//#region src/plugins/conversation-binding.d.ts
type PluginBindingApprovalDecision = PluginConversationBindingResolutionDecision;
type PluginBindingConversation = PluginConversationBindingResolvedEvent["request"]["conversation"];
type PluginBindingApprovalAction = {
  approvalId: string;
  decision: PluginBindingApprovalDecision;
};
type PluginBindingResolveResult = {
  status: "approved";
  binding: PluginConversationBinding;
  request: PendingPluginBindingRequest;
  decision: Exclude<PluginBindingApprovalDecision, "deny">;
} | {
  status: "denied";
  request: PendingPluginBindingRequest;
} | {
  status: "expired";
};
declare function buildPluginBindingApprovalCustomId(approvalId: string, decision: PluginBindingApprovalDecision): string;
declare function parsePluginBindingApprovalCustomId(value: string): PluginBindingApprovalAction | null;
declare function requestPluginConversationBinding(params: {
  pluginId: string;
  pluginName?: string;
  pluginRoot: string;
  conversation: PluginBindingConversation;
  requestedBySenderId?: string;
  binding: PluginConversationBindingRequestParams | undefined;
  assertCurrent?: () => void;
}): Promise<PluginConversationBindingRequestResult>;
declare function resolvePluginConversationBindingApproval(params: {
  approvalId: string;
  decision: PluginBindingApprovalDecision;
  senderId?: string;
}): Promise<PluginBindingResolveResult>;
declare function buildPluginBindingResolvedText(params: PluginBindingResolveResult): string;
//#endregion
//#region src/channels/message-access/effective-allow-from.d.ts
/**
 * Merge configured direct, group, and pairing-store allowlists into the
 * effective lists consumed by sender and context-visibility checks.
 */
declare function resolveChannelIngressEffectiveAllowFromLists(params: {
  allowFrom?: Array<string | number> | null;
  groupAllowFrom?: Array<string | number> | null;
  storeAllowFrom?: Array<string | number> | null;
  dmPolicy?: string | null;
  groupAllowFromFallbackToAllowFrom?: boolean | null;
}): {
  effectiveAllowFrom: string[];
  effectiveGroupAllowFrom: string[];
};
//#endregion
//#region src/channels/message-access/store-allow-from.d.ts
/**
 * Read pairing-store allowlist entries when a direct-message policy permits
 * store fallback.
 */
declare function readChannelIngressStoreAllowFromForDmPolicy(params: {
  provider: PairingChannel;
  accountId: string;
  dmPolicy?: string | null;
  shouldRead?: boolean | null;
  readStore?: (provider: PairingChannel, accountId: string) => Promise<string[]>;
}): Promise<string[]>;
//#endregion
//#region src/security/dm-policy-shared.d.ts
/**
 * Derive a stable main-DM owner from a single-entry allowlist.
 * Wildcards, multi-owner lists, and non-main DM scopes stay unpinned so callers keep route-specific sessions.
 */
declare function resolvePinnedMainDmOwnerFromAllowlist(params: {
  dmScope?: string | null;
  allowFrom?: Array<string | number> | null;
  normalizeEntry: (entry: string) => string | undefined;
}): string | null;
/** Admission decision returned by legacy DM/group access helpers. */
type DmGroupAccessDecision = "allow" | "block" | "pairing";
/** Stable reason codes used by channel plugins, command auth, and diagnostics. */
declare const DM_GROUP_ACCESS_REASON: {
  readonly GROUP_POLICY_ALLOWED: "group_policy_allowed";
  readonly GROUP_POLICY_DISABLED: "group_policy_disabled";
  readonly GROUP_POLICY_EMPTY_ALLOWLIST: "group_policy_empty_allowlist";
  readonly GROUP_POLICY_NOT_ALLOWLISTED: "group_policy_not_allowlisted";
  readonly DM_POLICY_OPEN: "dm_policy_open";
  readonly DM_POLICY_DISABLED: "dm_policy_disabled";
  readonly DM_POLICY_ALLOWLISTED: "dm_policy_allowlisted";
  readonly DM_POLICY_PAIRING_REQUIRED: "dm_policy_pairing_required";
  readonly DM_POLICY_NOT_ALLOWLISTED: "dm_policy_not_allowlisted";
};
/** Machine-readable reason code for a DM/group access decision. */
type DmGroupAccessReasonCode = (typeof DM_GROUP_ACCESS_REASON)[keyof typeof DM_GROUP_ACCESS_REASON];
type DmGroupAccessResult = {
  decision: DmGroupAccessDecision;
  reasonCode: DmGroupAccessReasonCode;
  reason: string;
};
/**
 * Resolve sender access for `dmPolicy=open`, where `*` means fully open and a configured
 * allowlist still restricts the accepted sender set.
 *
 * @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
 */
declare function resolveOpenDmAllowlistAccess(params: {
  effectiveAllowFrom: Array<string | number>;
  isSenderAllowed: (allowFrom: string[]) => boolean;
}): DmGroupAccessResult;
type DmGroupAccessInputParams = {
  isGroup: boolean;
  dmPolicy?: string | null;
  groupPolicy?: string | null;
  allowFrom?: Array<string | number> | null;
  groupAllowFrom?: Array<string | number> | null;
  storeAllowFrom?: Array<string | number> | null;
  groupAllowFromFallbackToAllowFrom?: boolean | null;
  isSenderAllowed: (allowFrom: string[]) => boolean;
};
/**
 * Resolve legacy DM/group sender admission and return the effective allowlists used.
 *
 * @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
 */
declare function resolveDmGroupAccessWithLists(params: DmGroupAccessInputParams): {
  decision: DmGroupAccessDecision;
  reasonCode: DmGroupAccessReasonCode;
  reason: string;
  effectiveAllowFrom: string[];
  effectiveGroupAllowFrom: string[];
};
//#endregion
//#region extensions/telegram/src/bot-access.d.ts
type NormalizedAllowFrom = {
  entries: string[];
  hasWildcard: boolean;
  hasEntries: boolean;
  invalidEntries: string[];
};
//#endregion
//#region src/channels/plugins/group-policy-warnings.d.ts
type GroupPolicyWarningCollector = (groupPolicy: GroupPolicy) => string[];
type AccountGroupPolicyWarningCollector<ResolvedAccount> = (params: {
  account: ResolvedAccount;
  cfg: OpenClawConfig;
}) => string[];
type ConfigGroupPolicyWarningCollector<Params extends {
  cfg: OpenClawConfig;
}> = (params: Params) => string[];
type WarningCollector<Params> = (params: Params) => string[];
declare function composeWarningCollectors<Params>(...collectors: Array<WarningCollector<Params> | null | undefined>): WarningCollector<Params>;
declare function projectWarningCollector<Params, Projected>(project: (params: Params) => Projected, collector: WarningCollector<Projected>): WarningCollector<Params>;
declare function projectConfigWarningCollector<Params extends {
  cfg: OpenClawConfig;
}>(collector: WarningCollector<{
  cfg: OpenClawConfig;
}>): WarningCollector<Params>;
declare function projectConfigAccountIdWarningCollector<Params extends {
  cfg: OpenClawConfig;
  accountId?: string | null;
}>(collector: WarningCollector<{
  cfg: OpenClawConfig;
  accountId?: string | null;
}>): WarningCollector<Params>;
declare function projectAccountWarningCollector<ResolvedAccount, Params extends {
  account: ResolvedAccount;
}>(collector: WarningCollector<ResolvedAccount>): WarningCollector<Params>;
declare function projectAccountConfigWarningCollector<ResolvedAccount, ProjectedCfg, Params extends {
  account: ResolvedAccount;
  cfg: OpenClawConfig;
}>(projectCfg: (cfg: OpenClawConfig) => ProjectedCfg, collector: WarningCollector<{
  account: ResolvedAccount;
  cfg: ProjectedCfg;
}>): WarningCollector<Params>;
declare function createSecurityAuditFindingCollector<Params>(options: {
  collectWarnings: (params: Params) => string[];
  checkId: string;
  severity: SecurityAuditFinding["severity"];
  title: string;
}): (params: Params) => SecurityAuditFinding[];
declare const createConditionalWarningCollector: (<Params>(...collectors: Array<(params: Params) => string | string[] | null | undefined | false>) => WarningCollector<Params>) & {
  findings: typeof createSecurityAuditFindingCollector;
};
declare function composeAccountWarningCollectors<ResolvedAccount, Params extends {
  account: ResolvedAccount;
}>(baseCollector: WarningCollector<Params>, ...collectors: Array<(account: ResolvedAccount) => string | string[] | null | undefined | false>): WarningCollector<Params>;
declare function buildOpenGroupPolicyWarning(params: {
  surface: string;
  openBehavior: string;
  remediation: string;
}): string;
declare function buildOpenGroupPolicyRestrictSendersWarning(params: {
  surface: string;
  openScope: string;
  groupPolicyPath: string;
  groupAllowFromPath: string;
  mentionGated?: boolean;
}): string;
declare function buildOpenGroupPolicyNoRouteAllowlistWarning(params: {
  surface: string;
  routeAllowlistPath: string;
  routeScope: string;
  groupPolicyPath: string;
  groupAllowFromPath: string;
  mentionGated?: boolean;
}): string;
declare function buildOpenGroupPolicyConfigureRouteAllowlistWarning(params: {
  surface: string;
  openScope: string;
  groupPolicyPath: string;
  routeAllowlistPath: string;
  mentionGated?: boolean;
}): string;
declare function collectOpenGroupPolicyRestrictSendersWarnings(params: Parameters<typeof buildOpenGroupPolicyRestrictSendersWarning>[0] & {
  groupPolicy: "open" | "allowlist" | "disabled";
}): string[];
declare function collectAllowlistProviderRestrictSendersWarnings(params: {
  cfg: OpenClawConfig;
  providerConfigPresent: boolean;
  configuredGroupPolicy?: GroupPolicy | null;
} & Omit<Parameters<typeof collectOpenGroupPolicyRestrictSendersWarnings>[0], "groupPolicy">): string[];
/** Build an account-aware allowlist-provider warning collector for sender-restricted groups. */
declare function createAllowlistProviderRestrictSendersWarningCollector<ResolvedAccount>(params: {
  providerConfigPresent: (cfg: OpenClawConfig) => boolean;
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
} & Omit<Parameters<typeof collectAllowlistProviderRestrictSendersWarnings>[0], "cfg" | "providerConfigPresent" | "configuredGroupPolicy">): AccountGroupPolicyWarningCollector<ResolvedAccount>;
/** Build a direct account-aware warning collector when the policy already lives on the account. */
declare function createOpenGroupPolicyRestrictSendersWarningCollector<ResolvedAccount>(params: {
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
  defaultGroupPolicy?: GroupPolicy;
} & Omit<Parameters<typeof collectOpenGroupPolicyRestrictSendersWarnings>[0], "groupPolicy">): (account: ResolvedAccount) => string[];
declare const { collectWarnings: collectAllowlistProviderGroupPolicyWarnings, createCollector: createAllowlistProviderGroupPolicyWarningCollector }: {
  collectWarnings: (params: {
    cfg: OpenClawConfig;
    providerConfigPresent: boolean;
    configuredGroupPolicy?: GroupPolicy | null;
    collect: GroupPolicyWarningCollector;
  }) => string[];
  createCollector: <Params extends {
    cfg: OpenClawConfig;
  }>(params: {
    providerConfigPresent: (cfg: OpenClawConfig) => boolean;
    resolveGroupPolicy: (params: Params) => GroupPolicy | null | undefined;
    collect: (params: Params & {
      groupPolicy: GroupPolicy;
    }) => string[];
  }) => ConfigGroupPolicyWarningCollector<Params>;
};
declare const { collectWarnings: collectOpenProviderGroupPolicyWarnings, createCollector: createOpenProviderGroupPolicyWarningCollector }: {
  collectWarnings: (params: {
    cfg: OpenClawConfig;
    providerConfigPresent: boolean;
    configuredGroupPolicy?: GroupPolicy | null;
    collect: GroupPolicyWarningCollector;
  }) => string[];
  createCollector: <Params extends {
    cfg: OpenClawConfig;
  }>(params: {
    providerConfigPresent: (cfg: OpenClawConfig) => boolean;
    resolveGroupPolicy: (params: Params) => GroupPolicy | null | undefined;
    collect: (params: Params & {
      groupPolicy: GroupPolicy;
    }) => string[];
  }) => ConfigGroupPolicyWarningCollector<Params>;
};
/** Build an account-aware allowlist-provider warning collector for simple open-policy warnings. */
declare function createAllowlistProviderOpenWarningCollector<ResolvedAccount>(params: {
  providerConfigPresent: (cfg: OpenClawConfig) => boolean;
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
  buildOpenWarning: Parameters<typeof buildOpenGroupPolicyWarning>[0];
}): AccountGroupPolicyWarningCollector<ResolvedAccount>;
declare function collectOpenGroupPolicyRouteAllowlistWarnings(params: {
  groupPolicy: "open" | "allowlist" | "disabled";
  routeAllowlistConfigured: boolean;
  restrictSenders: Parameters<typeof buildOpenGroupPolicyRestrictSendersWarning>[0];
  noRouteAllowlist: Parameters<typeof buildOpenGroupPolicyNoRouteAllowlistWarning>[0];
}): string[];
/** Build an account-aware allowlist-provider warning collector for route-allowlisted groups. */
declare function createAllowlistProviderRouteAllowlistWarningCollector<ResolvedAccount>(params: {
  providerConfigPresent: (cfg: OpenClawConfig) => boolean;
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
  resolveRouteAllowlistConfigured: (account: ResolvedAccount) => boolean;
  restrictSenders: Parameters<typeof buildOpenGroupPolicyRestrictSendersWarning>[0];
  noRouteAllowlist: Parameters<typeof buildOpenGroupPolicyNoRouteAllowlistWarning>[0];
}): AccountGroupPolicyWarningCollector<ResolvedAccount>;
declare function collectOpenGroupPolicyConfiguredRouteWarnings(params: {
  groupPolicy: "open" | "allowlist" | "disabled";
  routeAllowlistConfigured: boolean;
  configureRouteAllowlist: Parameters<typeof buildOpenGroupPolicyConfigureRouteAllowlistWarning>[0];
  missingRouteAllowlist: Parameters<typeof buildOpenGroupPolicyWarning>[0];
}): string[];
/** Build an account-aware open-provider warning collector for configured-route channels. */
declare function createOpenProviderConfiguredRouteWarningCollector<ResolvedAccount>(params: {
  providerConfigPresent: (cfg: OpenClawConfig) => boolean;
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
  resolveRouteAllowlistConfigured: (account: ResolvedAccount) => boolean;
  configureRouteAllowlist: Parameters<typeof buildOpenGroupPolicyConfigureRouteAllowlistWarning>[0];
  missingRouteAllowlist: Parameters<typeof buildOpenGroupPolicyWarning>[0];
}): AccountGroupPolicyWarningCollector<ResolvedAccount>;
//#endregion
//#region src/channels/plugins/helpers.d.ts
declare function formatPairingApproveHint(channelId: string): string;
declare function parseOptionalDelimitedEntries(value?: string): string[] | undefined;
declare function buildAccountScopedDmSecurityPolicy(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  accountId?: string | null;
  fallbackAccountId?: string | null;
  policy?: string | null;
  allowFrom?: Array<string | number> | null;
  defaultPolicy?: string;
  allowFromPathSuffix?: string;
  policyPathSuffix?: string;
  approveChannelId?: string;
  approveHint?: string;
  normalizeEntry?: (raw: string) => string;
  classifyEntryAuthentication?: ChannelSecurityDmPolicy["classifyEntryAuthentication"];
  inheritSharedDefaultsFromDefaultAccount?: boolean;
}): ChannelSecurityDmPolicy;
//#endregion
//#region src/config/group-scope-tree.d.ts
type ScopeNode = {
  requireMention?: boolean;
  tools?: GroupToolPolicyConfig;
  toolsBySender?: GroupToolPolicyBySenderConfig;
  introHint?: string;
};
type ScopeTree = {
  defaults?: ScopeNode;
  scopes: Record<string, ScopeNode>;
};
type ScopePath = string[];
declare const encodeScopeSegment: (value: string) => string;
declare function scopeKey(...segments: Array<readonly [prefix: string, value: string]>): string;
declare function buildChannelGroupsScopeTree(cfg: OpenClawConfig, channel: ChannelId$1, accountId?: string | null): ScopeTree;
declare function resolveScopeKeyCaseInsensitive(tree: ScopeTree, key: string | null | undefined): string | undefined;
declare function resolveScopeRequireMention(params: {
  tree: ScopeTree;
  path: ScopePath;
  requireMentionOverride?: boolean;
  overrideOrder?: "before-config" | "after-config";
  configuredScopeDefaultsToNoMention?: boolean;
}): boolean;
declare function resolveScopeToolsPolicy(params: {
  tree: ScopeTree;
  path: ScopePath;
} & GroupToolPolicySender): GroupToolPolicyConfig | undefined;
declare function resolveScopeIntroHint(params: {
  tree: ScopeTree;
  path: ScopePath;
}): string | undefined;
//#endregion
//#region src/plugin-sdk/channel-policy.d.ts
type GroupRouteAccessDecision = {
  allowed: boolean;
  groupPolicy: GroupPolicy;
  reason: "allowed" | "disabled" | "empty_allowlist" | "route_not_allowlisted" | "route_disabled";
};
type SenderGroupAccessDecision = {
  allowed: boolean;
  groupPolicy: GroupPolicy;
  providerMissingFallbackApplied: boolean;
  reason: "allowed" | "disabled" | "empty_allowlist" | "sender_not_allowlisted";
};
/** @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`. */
declare function resolveSenderScopedGroupPolicy(params: {
  groupPolicy: GroupPolicy;
  groupAllowFrom: string[];
}): GroupPolicy;
/** @deprecated Use route descriptors with `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`. */
declare function evaluateGroupRouteAccessForPolicy(params: {
  groupPolicy: GroupPolicy;
  routeAllowlistConfigured: boolean;
  routeMatched: boolean;
  routeEnabled?: boolean;
}): GroupRouteAccessDecision;
/** @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`. */
declare function evaluateSenderGroupAccessForPolicy(params: {
  groupPolicy: GroupPolicy;
  providerMissingFallbackApplied?: boolean;
  groupAllowFrom: string[];
  senderId: string;
  isSenderAllowed: (senderId: string, allowFrom: string[]) => boolean;
}): SenderGroupAccessDecision;
/** Normalizes allowFrom entries into trimmed unique string identifiers. */
declare function normalizeAllowFromList(list: Array<string | number> | undefined | null): string[];
/** Coerces native feature settings to the supported boolean/auto shape. */
declare function coerceNativeSetting(value: unknown): boolean | "auto" | undefined;
/**
 * Candidate allowlist inspected for dangerous name/email/nick matching warnings.
 * `pathLabel` is emitted in doctor output, so callers should pass the exact config path.
 */
type ChannelMutableAllowlistCandidate = {
  pathLabel: string;
  list: unknown;
};
type StandardAllowlistScope = {
  prefix: string;
  account: Record<string, unknown>;
};
/** Collect the common account, nested-DM, and group/room allowlist paths for doctor warnings. */
declare function collectStandardAllowlistLists(scope: StandardAllowlistScope, options?: {
  includeAllowFrom?: boolean;
  includeGroupAllowFrom?: boolean;
  includeDm?: boolean;
  includeGroups?: boolean;
  groupsKey?: string;
  groupField?: string;
}): ChannelMutableAllowlistCandidate[];
/** Build a mutable-name detector by stripping channel prefixes and recognizing stable IDs. */
declare function buildMutableAllowEntryDetector(params: {
  prefixes?: readonly string[];
  stableIdPattern: RegExp;
}): (entry: string) => boolean;
/**
 * Create a warning collector for mutable name/email/nick allowlists while stable-id matching is required.
 * Channel plugins provide a detector for entries that depend on dangerous name matching.
 */
declare function createDangerousNameMatchingMutableAllowlistWarningCollector(params: {
  channel: string;
  detector: (entry: string) => boolean;
  collectLists: (scope: {
    prefix: string;
    account: Record<string, unknown>;
    dangerousFlagPath: string;
  }) => ChannelMutableAllowlistCandidate[];
}): ({ cfg }: {
  cfg: OpenClawConfig;
}) => string[];
/**
 * Compose the common account-scoped DM policy resolver with restrict-senders group warnings.
 * This is the shared adapter shape for channels whose DM security and group policy live together.
 */
declare function createRestrictSendersChannelSecurity<ResolvedAccount extends {
  accountId?: string | null;
}>(params: {
  /** Channel config key used for default account lookup and warning collection. */
  channelKey: string;
  /** Reads the account-level DM policy value before shared defaults are applied. */
  resolveDmPolicy: (account: ResolvedAccount) => string | null | undefined;
  /** Reads account-level sender allowlist entries for DM policy resolution. */
  resolveDmAllowFrom: (account: ResolvedAccount) => Array<string | number> | null | undefined;
  /** Reads the group policy value used by restrict-senders warnings. */
  resolveGroupPolicy: (account: ResolvedAccount) => GroupPolicy | null | undefined;
  /** Operator-facing surface name in warning text. */
  surface: string;
  /** Operator-facing description of who can trigger when group policy is open. */
  openScope: string;
  /** Config path shown for the group policy field that should be restricted. */
  groupPolicyPath: string;
  /** Config path shown for the group sender allowlist field. */
  groupAllowFromPath: string;
  /** Whether group replies require mentions, reducing open-policy warning severity. */
  mentionGated?: boolean;
  /** Existing channel label used by the audit and Doctor finding renderer. */
  findingTitle?: string;
  /** Override for channels whose provider presence is not the channel config key itself. */
  providerConfigPresent?: (cfg: OpenClawConfig) => boolean;
  /** Fallback account id used when scoped config inherits from another account. */
  resolveFallbackAccountId?: (account: ResolvedAccount) => string | null | undefined;
  /** Default DM policy when the account and shared defaults omit one. */
  defaultDmPolicy?: string;
  /** Account-scoped allowlist path suffix for warning/proof output. */
  allowFromPathSuffix?: string;
  /** Account-scoped policy path suffix for warning/proof output. */
  policyPathSuffix?: string;
  /** Channel id used when formatting pairing approval hints. */
  approveChannelId?: string;
  /** Explicit pairing approval hint, when the default channel hint is not correct. */
  approveHint?: string;
  /** Normalizes configured DM allowlist entries before sender matching. */
  normalizeDmEntry?: (raw: string) => string;
  classifyEntryAuthentication?: ChannelSecurityDmPolicy["classifyEntryAuthentication"];
  /** Allows non-default accounts to inherit shared defaults from the default account. */
  inheritSharedDefaultsFromDefaultAccount?: boolean;
  dmRouting?: ChannelSecurityAdapter<ResolvedAccount>["dmRouting"];
}): ChannelSecurityAdapter<ResolvedAccount>;
//#endregion
//#region extensions/telegram/src/group-config-helpers.d.ts
type TelegramGroupConfigResolver = (chatId: string | number, messageThreadId: number | undefined, cfg: OpenClawConfig) => {
  groupConfig?: TelegramGroupConfig | TelegramDirectConfig;
  topicConfig?: TelegramTopicConfig;
};
//#endregion
//#region extensions/telegram/src/thread-spec.d.ts
type TelegramThreadSpec = {
  id?: number;
  /** dm is the historical bot-private topic scope. */
  scope: "direct-messages" | "dm" | "forum" | "none";
};
//#endregion
//#region src/auto-reply/reply/inbound-context.d.ts
type FinalizeInboundContextOptions = {
  forceBodyForAgent?: boolean;
  forceBodyForCommands?: boolean;
  forceChatType?: boolean;
};
declare function finalizeInboundContext<T extends Record<string, unknown>>(ctx: T, opts?: FinalizeInboundContextOptions): Omit<T, LegacyMediaContextKey> & FinalizedRuntimeMsgContext;
/** Preserve SDK media projections while exposing the finalizer's prepared command fact. */
declare function finalizeInboundContextForSdk<T extends Record<string, unknown>>(ctx: T, opts?: FinalizeInboundContextOptions): T & FinalizedMsgContext & CanonicalInboundText & Pick<FinalizedRuntimeMsgContext, "CommandTurn">;
//#endregion
//#region src/plugins/runtime/types-native-subagent.d.ts
/** Native children retain the current requester's authority and parent lineage. */
type NativeSubagentSpawnParams = {
  /** Stable within this parent turn and plugin; replay returns the native accepted child. */
  requestId: string;
  task: string;
  /** Local id registered by this plugin; cannot select another plugin’s profile. */
  profile?: string;
  taskName?: string;
  label?: string;
  model?: string;
  thinking?: string;
  fastMode?: boolean | "auto" | "ultrafast";
  context?: "fork" | "isolated";
  /** Hosts advertising `native-subagent-blind-v1`: the child's prompt omits its model and workspace. */
  blind?: boolean;
  runTimeoutSeconds?: number;
  outputSchema?: Record<string, unknown>;
};
/** Control facts recorded by the host; absent fields are unknown, not defaults. */
type NativeSubagentSelection = {
  /** Explicit spawn inputs. Empty when the collecting invocation has no recorded request. */
  requested: {
    model?: string;
    thinking?: string;
    fastMode?: boolean | "auto" | "ultrafast";
  };
  /** Current child-session controls, not a claim that a provider honored them. */
  resolved?: {
    model?: string;
    thinking?: string;
    fastMode?: boolean | "auto" | "ultrafast";
  };
  /** Present only when the host has independent execution observations. */
  observed?: {
    model?: string;
    thinking?: string;
    fastMode?: boolean | "auto" | "ultrafast";
  };
};
type NativeSubagentAccepted = {
  runId: string;
  childSessionKey: string;
  completionMode: "collect";
  selection?: NativeSubagentSelection;
};
type NativeSubagentCollectParams = {
  ids: string[];
  /** Zero reads current status. Omit to use the native bounded wait. */
  timeoutSeconds?: number;
  /** Join all results without polling; mutually exclusive with timeoutSeconds. */
  awaitResults?: boolean;
};
type NativeSubagentCollection = {
  completed: Array<{
    runId: string;
    sessionKey: string;
    status: "done" | "failed" | "killed" | "timeout";
    result: string;
    /** The result may be incomplete: its complete answer was unavailable or exceeded 100 KB. */
    resultTruncated?: true;
    structured?: unknown;
    error?: string;
    schemaError?: string;
    label?: string;
    usage?: {
      inputTokens: number;
      outputTokens: number;
    };
    selection?: NativeSubagentSelection;
  }>;
  pending: string[];
  errors?: Array<{
    runId: string;
    error: "not_found" | "not_owner";
  }>;
  success?: false;
};
type NativeSubagentRuntime = {
  spawn(params: NativeSubagentSpawnParams): Promise<NativeSubagentAccepted>;
  collect(params: NativeSubagentCollectParams): Promise<NativeSubagentCollection>;
  /** Most recent 200 children owned by this plugin, requester and exact parent incarnation. */
  list?(this: void, params?: {
    status?: NativeSubagentChild["status"];
  }): Promise<NativeSubagentChild[]>;
};
type NativeSubagentChild = {
  runId: string;
  childSessionKey: string;
  requestId: string;
  label?: string;
  /** Native completion when known; otherwise the recorded execution state. */
  status: "queued" | "running" | "interrupted" | "terminal" | "done" | "failed" | "killed" | "timeout";
};
//#endregion
//#region src/plugins/runtime/types-scheduled-turns.d.ts
/** Requester-bound schedules use the native scheduler; destinations and authority are host-owned. */
type PluginCommandScheduleRequest = {
  /** Invocation-local idempotency key. Reusing it with different input is refused. */
  requestId: string;
  /** Canonical command name, without slash, owned by this same plugin. */
  command: string;
  args?: string;
  schedule: {
    kind: "at";
    at: string;
  } | {
    kind: "every";
    everyMs: number;
  };
  /** Absolute deadline, at most seven days from this invocation. */
  deadlineAtMs: number;
  /** Maximum admitted attempts, including interrupted attempts (1-100). */
  maxRuns: number;
};
type PluginCommandScheduledTurns = {
  schedule: (request: PluginCommandScheduleRequest) => Promise<{
    jobId: string;
    deadlineAtMs: number;
    maxRuns: number;
    /**
     * Whether this schedule continues after a Gateway restart (`command-scheduled-turns-restart-v1`
     * hosts, for plugins whose loaded source has a captured digest). When false, re-enroll from a
     * later requester command after a restart.
     */
    survivesRestart: boolean;
  }>;
};
//#endregion
//#region src/plugins/runtime/native-subagent-context.d.ts
type NativeSubagentRuntimeGuard = {
  pluginId: string;
  assertCurrent: () => void;
  signal?: AbortSignal;
  /** Host-selected command metadata, never plugin-supplied factory arguments. */
  command?: {
    requireAuth?: boolean;
    runtimeCapabilities?: readonly string[];
  };
};
/** Core-only command factory; plugins cannot supply a requester or operator authority. */
type NativeSubagentCommandFactory = (guard: NativeSubagentRuntimeGuard) => Promise<(NativeSubagentRuntime & {
  scheduledTurns?: PluginCommandScheduledTurns;
}) | undefined>;
//#endregion
//#region src/infra/exec-approvals-contracts.d.ts
type AllowAlwaysPersistenceReason = "no-reusable-pattern" | "prompt-only" | "runtime-payload" | "unplanned";
type AllowAlwaysPersistenceDecision = {
  kind: "patterns";
  patterns: readonly AllowAlwaysPattern[];
  commandText?: string;
} | {
  kind: "exact-command";
  commandText: string;
} | {
  kind: "one-shot";
  reasons: AllowAlwaysPersistenceReason[];
};
//#endregion
//#region src/infra/exec-approvals-policy.d.ts
declare function minSecurity(a: ExecSecurity, b: ExecSecurity): ExecSecurity;
declare function maxAsk(a: ExecAsk, b: ExecAsk): ExecAsk;
declare function resolveExecApprovalAllowedDecisions(params?: {
  ask?: string | null;
  allowAlwaysPersistence?: AllowAlwaysPersistenceDecision | null;
}): readonly ExecApprovalDecision[];
declare function resolveExecApprovalRequestAllowedDecisions(params?: {
  ask?: string | null;
  unavailableDecisions?: readonly ExecApprovalUnavailableDecision[] | readonly string[] | null;
}): readonly ExecApprovalDecision[];
//#endregion
//#region src/agents/sandbox/runtime-status.d.ts
type SandboxRuntimeIsolation = {
  sandboxRequired: false;
  isolationSubject?: never;
  createdActor?: never;
  workspaceAccess?: never;
} | {
  sandboxRequired: true;
  isolationSubject: SandboxIsolationSubject;
  createdActor?: SessionCreatedActor;
  workspaceAccess: SandboxWorkspaceAccess;
};
type SandboxRuntimeStatusParams = {
  cfg?: OpenClawConfig;
  sessionKey?: string;
  agentId?: string;
  /** Independent execution identity used for sandbox mode and policy classification. */
  classificationSessionKey?: string;
  classificationAgentId?: string;
  /** Trusted canonical candidate for the classification identity; null means no stored entry. */
  preparedSessionEntry?: Pick<SessionEntry, "sandbox" | "sandboxMode" | "createdActor"> | null;
};
declare function resolveSandboxRuntimeStatus(params: SandboxRuntimeStatusParams): {
  agentId: string;
  sessionKey: string;
  classificationAgentId: string;
  classificationSessionKey: string;
  mainSessionKey: string;
  mode: SandboxConfig["mode"];
  sandboxed: boolean;
  toolPolicy: SandboxToolPolicyResolved;
} & SandboxRuntimeIsolation;
//#endregion
//#region src/agents/exec-defaults.d.ts
/** Session-scoped exec fields that may be carried across an isolated runtime boundary. */
type ExecSessionDefaults = Pick<SessionEntry, "execHost" | "execNode" | "execCwd" | "permissionMode" | "sandbox" | "sandboxMode" | "createdActor">;
type ExecPolicyOverrides = Pick<ExecToolConfig, "host" | "mode" | "security" | "ask" | "node">;
//#endregion
//#region src/agents/tools/cron-tool.types.d.ts
type CronCreatorToolAllowlistEntry = string | {
  /** Canonical policy name persisted into toolsAllow caps. */
  name: string;
  pluginId?: string;
  /** Runtime-specific alias the creator surface presented for this tool. */
  aliasName?: string;
  /** Runtime owner that supplied exec; required for process-bearing stream writes. */
  execOrigin?: "openclaw" | "native";
  /** Restrict-only execution policy carried by a host-created alias projection. */
  execTarget?: {
    host: "gateway";
    ask?: "always";
  };
};
type CronToolsAllowCaptureProvenance = {
  version: 1;
  source: "final-executable-surface";
};
type CronToolsAllowCaptureRef = {
  value?: CronToolsAllowCaptureProvenance;
};
type CronCreatorToolAuthorityMaterialization = {
  tools: readonly CronCreatorToolAllowlistEntry[];
  provenance: CronToolsAllowCaptureProvenance;
  /** Opaque runtime-owned authority captured with the same exact executable surface. */
  runtimeAuthority?: CronRuntimeAuthority;
};
type CronCreatorToolAuthoritySnapshot = Omit<CronCreatorToolAuthorityMaterialization, "runtimeAuthority"> & {
  /** Gateway-process one-shot proof consumed only at the matching cron write. */
  grant: CronCreatorAuthorityGrant;
  /** The creator captured runtime app authority (Codex apps); its default list stays concrete. */
  holdsRuntimeAuthority?: true;
};
type CronToolOptions = {
  agentSessionKey?: string;
  agentId?: string;
  /** Authenticated source account; authority must not be inferred from delivery. */
  agentAccountId?: string;
  /**
   * Resolved config for the calling context. Shapes the advertised schema and
   * description: when cron.triggers.enabled is off, trigger-gated surfaces
   * (trigger, script payloads, stream schedules) are not advertised. Omitting
   * config keeps the full surface for config-less callers.
   */
  config?: OpenClawConfig;
  /** Exact session and run-local exec policy used by this creator turn. */
  execSession?: ExecSessionDefaults;
  execOverrides?: ExecPolicyOverrides;
  /** Whether auto host selection resolves into this turn's sandbox. */
  sandboxed?: boolean;
  /** Actual host-prepared target; a sandboxed flag cannot grant persistent execution. */
  sandboxContext?: SandboxContext;
  currentDeliveryContext?: DeliveryContext;
  /**
   * Effective tool surface visible to the caller that created or edited a cron job.
   * Cron agent turns and trigger scripts use fresh runtimes, so agent-origin jobs
   * need this cap persisted before the original session policy is lost.
   */
  creatorToolAllowlist?: CronCreatorToolAllowlistEntry[];
  /** Host-owned proof that creatorToolAllowlist reached the final executable surface. */
  creatorToolAllowlistCaptureRef?: CronToolsAllowCaptureRef;
  /** Attempt-cached authority resolved only when a mutation changes its tool cap. */
  resolveCreatorToolAuthority?: (options?: {
    signal?: AbortSignal;
  }) => Promise<CronCreatorToolAuthoritySnapshot>;
  /** Visible fail-closed reason when a queued local turn cannot retain fresh MCP authority. */
  creatorAuthorityUnavailableReason?: "queued-local-operator-configured-mcp";
  selfRemoveOnlyJobId?: string;
  runId?: string;
};
//#endregion
//#region src/agents/cron-creator-authority-context.d.ts
/** Opaque in-process capability minted only by an admitted exact run. */
type CronCreatorAuthorityCapability = CronCreatorAuthorityRunScope;
//#endregion
//#region src/media-understanding/extracted-file-images.d.ts
type ExtractedFileImage = ImageContent$1 & {
  attachmentIndex: number;
};
//#endregion
//#region src/tts/tts-preferences.d.ts
type PreparedTtsPreferences = Readonly<{
  machinePrefsPath?: 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/prompt-session-context.d.ts
type ReplyConversationFields = Pick<TemplateContext, "Provider" | "Surface" | "ChatType" | "OriginatingChannel" | "OriginatingTo" | "AccountId" | "MessageThreadId" | "GroupSubject" | "GroupChannel" | "GroupSpace">;
type PreparedReplyConversation = {
  fields: ReplyConversationFields;
  group: {
    channel?: string;
    groupId?: string;
    groupChannel?: string;
    groupSpace?: string;
    accountId?: string;
  };
  activation?: SessionEntry["groupActivation"];
};
//#endregion
//#region src/agents/accepted-session-spawn.d.ts
type AcceptedSessionSpawn = {
  runId: string;
  childSessionKey: string;
  sessionUrl?: string;
  publicRead?: boolean;
  label?: string;
  /** True only when this child owns a terminal completion for its requester. */
  expectsCompletionMessage?: boolean;
  /** Host-recorded: the requester collects this child itself (sessions_spawn collect=true). */
  collector?: true;
};
//#endregion
//#region src/agents/mcp-connect-action.d.ts
type McpConnectAction = {
  serverName: string;
  authorizationUrl: string;
};
//#endregion
//#region src/shared/mcp-app-extensions.d.ts
declare const mcpAppIconSchema: z.ZodObject<{
  src: z.ZodString;
  mimeType: z.ZodOptional<z.ZodString>;
  sizes: z.ZodOptional<z.ZodArray<z.ZodString>>;
  theme: z.ZodOptional<z.ZodEnum<{
    dark: "dark";
    light: "light";
  }>>;
}, z.core.$strip>;
declare const mcpAppEntrypointSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
  type: z.ZodLiteral<"global">;
  quickAction: z.ZodOptional<z.ZodObject<{
    title: z.ZodString;
    icons: z.ZodArray<z.ZodObject<{
      src: z.ZodString;
      mimeType: z.ZodOptional<z.ZodString>;
      sizes: z.ZodOptional<z.ZodArray<z.ZodString>>;
      theme: z.ZodOptional<z.ZodEnum<{
        dark: "dark";
        light: "light";
      }>>;
    }, z.core.$strip>>;
    target: z.ZodObject<{
      type: z.ZodLiteral<"tool">;
      name: z.ZodString;
      arguments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
    }, z.core.$strip>;
  }, z.core.$strip>>;
}, z.core.$strip>, z.ZodObject<{
  type: z.ZodLiteral<"thread">;
}, z.core.$strip>, z.ZodObject<{
  type: z.ZodLiteral<"file">;
  extensions: z.ZodArray<z.ZodString>;
}, z.core.$strip>, z.ZodObject<{
  type: z.ZodLiteral<"settings">;
  searchTerms: z.ZodOptional<z.ZodArray<z.ZodString>>;
}, z.core.$strip>], "type">;
declare const mcpAppSettingsCapabilitySchema: z.ZodObject<{
  readTool: z.ZodString;
  updateTool: z.ZodString;
}, z.core.$strip>;
type McpAppIcon = SchemaContract<z.infer<typeof mcpAppIconSchema>>;
type McpAppEntrypoint = SchemaContract<z.infer<typeof mcpAppEntrypointSchema>>;
type McpAppToolExtensions = {
  entrypoints?: McpAppEntrypoint[];
  mentionSearch?: true;
  icons?: McpAppIcon[];
  preferredModelDisplayMode?: "inline" | "fullscreen";
};
type McpAppSettingsCapability = z.infer<typeof mcpAppSettingsCapabilitySchema>;
//#endregion
//#region src/agents/mcp-codex-tool-approval.d.ts
type McpCodexToolAnnotations = {
  readOnlyHint?: boolean;
  destructiveHint?: boolean;
  idempotentHint?: boolean;
  openWorldHint?: boolean;
};
//#endregion
//#region src/agents/agent-bundle-mcp-types.d.ts
type McpServerCatalog = {
  serverName: string;
  safeServerName?: string;
  launchSummary: string;
  pluginId?: string;
  marketplace?: string;
  title?: string;
  icons?: McpAppIcon[];
  /** Complete server-level guidance from the upstream initialize result. */
  instructions?: string;
  settings?: McpAppSettingsCapability;
  toolCount: number;
  resources?: {
    listChanged?: boolean;
  };
  prompts?: {
    listChanged?: boolean;
  };
  tools?: {
    listChanged?: boolean;
    filteredCount?: number;
  };
  requestTimeoutMs?: number;
  supportsParallelToolCalls?: boolean;
  toolFilter?: McpServerToolFilterConfig;
  deniedToolNames?: string[];
  codexApprovalMode?: McpCodexToolApprovalMode;
};
/** MCP tool entry after server-name sanitization and schema normalization. */
type McpCatalogTool = {
  serverName: string;
  safeServerName: string;
  toolName: string;
  title?: string;
  description?: string;
  inputSchema: TSchema;
  fallbackDescription: string;
  appExtensions?: McpAppToolExtensions;
  uiResourceUri?: string;
  uiVisibility?: Array<"app" | "model">;
  /** Listed by the server but excluded from OpenClaw's callable tool catalog. */
  excludedFromOpenClawCatalog?: true;
  deniedBySession?: true;
  codexAnnotations?: McpCodexToolAnnotations;
  /** Trusted requester OAuth sign-in bootstrap; never dispatches into the server's tools. */
  oauthConnectBootstrap?: true;
};
type McpToolCatalog = {
  version: number;
  generatedAt: number;
  servers: Record<string, McpServerCatalog>;
  tools: McpCatalogTool[];
  /** Complete raw catalog used to project policy into native MCP clients. */
  policyTools?: McpCatalogTool[];
  /** Listed tools hidden only by the session override, retained for read-only inventory. */
  sessionDeniedTools?: McpCatalogTool[];
  diagnostics?: readonly McpToolCatalogDiagnostic[];
};
/** Transient requester sign-in surface kept outside the remembered live catalog. */
type RequesterMcpConnect = {
  catalog: McpToolCatalog;
  authorizedServerNames: readonly string[];
  configFingerprint: string;
  createExecute: (serverName: string) => AnyAgentTool["execute"] | undefined;
};
type McpToolCatalogDiagnostic = {
  serverName: string;
  safeServerName: string;
  launchSummary: string;
  message: string;
};
type McpRequestOptions = {
  failureBackoff?: "track" | "ignore";
  _meta?: Record<string, unknown>;
};
/** Trusted requester identity used to scope per-user MCP connections. */
type SessionMcpRequesterScope = {
  requesterSenderId: string;
  agentAccountId?: string;
  messageChannel?: string;
};
/** Supplied only by the authenticated Gateway profile owner, never inferred from a channel sender. */
type McpAppRequesterIdentity = {
  kind: "gateway-profile";
  profileId: string;
};
/** Live MCP runtime bound to one session/workspace. */
type SessionMcpRuntime = {
  appRequester?: McpAppRequesterIdentity;
  sessionId: string;
  sessionKey?: string;
  workspaceDir: string;
  agentDir?: string;
  configFingerprint: string;
  /** Present when this runtime is keyed by requester-scoped connection identity. */
  requesterScope?: SessionMcpRequesterScope;
  requesterConnect?: RequesterMcpConnect;
  /**
   * True when the named server's connection is requester-scoped. App producers
   * require an explicit Gateway-profile mapping before minting a private view.
   * Transport sender ids must never be used as Gateway profile identities.
   */
  isRequesterScopedServer?: (serverName: string) => boolean;
  /** True only when the existing server transport can read files on this host. */
  canReadLocalFiles?: (serverName: string) => boolean;
  mcpAppsEnabled?: boolean;
  /** Native adapter proves its exact thread/client binding is still current. */
  assertOwnerCurrent?: () => void;
  /** Blocks a deferred-retirement view from restoring context across reset. */
  mcpAppModelContextRevoked?: boolean;
  createdAt: number;
  lastUsedAt: number;
  activeLeases?: number;
  acquireLease?: () => () => void;
  /** Terminal server outcome recorded at retirement, with no callable tools. */
  readonly retiredCatalog?: McpToolCatalog;
  /** Lists tools if needed and may connect MCP transports. */
  getCatalog: () => Promise<McpToolCatalog>;
  /** Returns the cached catalog only; must not start runtimes, connect transports, or issue tools/list. */
  peekCatalog: () => McpToolCatalog | null;
  /** Returns the configured request timeout for a server from the connected session, without touching the catalog. */
  getServerRequestTimeoutMs?: (serverName: string) => number | undefined;
  markUsed: () => void;
  callTool: (serverName: string, toolName: string, input: unknown, options?: {
    _meta?: Record<string, unknown>;
    assertCurrent?: () => void;
  }) => Promise<CallToolResult>;
  listTools?: (serverName: string, params?: {
    cursor?: string;
  }) => Promise<ListToolsResult>;
  listResources?: (serverName: string, options?: McpRequestOptions) => Promise<unknown>;
  readResource?: (serverName: string, uri: string, options?: McpRequestOptions) => Promise<unknown>;
  listResourceTemplates?: (serverName: string, params?: {
    cursor?: string;
  }) => Promise<ListResourceTemplatesResult>;
  listPrompts?: (serverName: string) => Promise<unknown>;
  getPrompt?: (serverName: string, name: string, args?: Record<string, string>) => Promise<GetPromptResult>;
  /** Joins cleanup already owned by this runtime, without closing live shared peers.
   * Rejects when an earlier retirement or disposal could not confirm closure. */
  joinCleanup?: () => Promise<void>;
  dispose: () => Promise<void>;
};
/** Acquisition owns a lease before any caller can observe the runtime. */
type SessionMcpRuntimeLease = {
  runtime: SessionMcpRuntime;
  releaseLease: () => void;
  /** Retires unleased discovery servers outside the final prepared bundle. */
  retireUnusedServers?: (retainedServerNames: ReadonlySet<string>) => Promise<void>;
};
//#endregion
//#region src/agents/mcp-ui-resource.d.ts
type McpAppChannelView = {
  viewId: string;
};
//#endregion
//#region src/agents/embedded-agent-runner/types.d.ts
type BlockReplyFlushContext = {
  /** Boundary that requested the flush. */
  reason: "message_end" | "terminal";
} | {
  /** Tool boundary separating pre-tool narration from the eventual answer. */
  reason: "tool_start";
  assistantMessageIndex: number;
} | {
  /** Pre-compaction delivery is safe only for a completed assistant attempt. */
  reason: "pre_compaction";
  attemptAccepted: boolean;
};
type EmbeddedAgentRunResult = {
  latestMcpAppChannelView?: McpAppChannelView;
  latestMcpConnectAction?: McpConnectAction;
  payloads?: EmbeddedAgentRunPayload[];
  meta: EmbeddedAgentRunMeta;
  diagnosticTrace?: DiagnosticTraceContext;
  /** Suppresses confirmation text after a messaging tool successfully sends. */
  didSendViaMessagingTool?: boolean;
  didDeliverSourceReplyViaMessageTool?: boolean;
  sourceReplyDelivered?: true;
  /** Current-input custody; unlike aggregate sends, this is reset when another input is admitted. */
  sourceReplyDeliveryState?: ReplyDeliveryState;
  didSendDeterministicApprovalPrompt?: boolean;
  messagingToolSentTexts?: string[];
  messagingToolSentMediaUrls?: string[];
  messagingToolSentTargets?: MessagingToolSend[];
  messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[];
  acceptedSessionSpawns?: AcceptedSessionSpawn[];
  /** An asynchronous tool task started during this run; its owner tracks completion. */
  asyncWorkStarted?: true;
  /** Completed core yield settlement, not a requester-visible final reply. */
  requesterContinuationSettled?: true;
  successfulCronAdds?: number;
};
type EmbeddedAgentCompactResult = {
  ok: boolean;
  compacted: boolean;
  compactionKind?: "context-engine" | "native-harness" | "server-endpoint";
  reason?: string;
  /** Structured failure metadata used by model fallback classification. */
  failure?: {
    reason?: string;
    status?: number;
    code?: string;
    rawError?: string;
  };
  result?: {
    /** Identifies summaryless provider compaction in RPC and UI consumers. */
    kind?: "server-endpoint";
    sessionTarget?: ContextEngineSessionTarget;
    /** Server-endpoint compaction has no transcript summary or first-kept entry. */
    summary?: string;
    firstKeptEntryId?: string;
    tokensBefore: number;
    tokensAfter?: number;
    details?: unknown;
    sessionId?: string;
    sessionFile?: string;
  };
};
type EmbeddedFullAccessBlockedReason = "sandbox" | "host-policy" | "channel" | "runtime";
//#endregion
//#region src/auto-reply/reply/reply-operation-run-state.d.ts
declare const REPLY_OPERATION_RUN_STATE: unique symbol;
type ReplyOptionsWithOperationRunState = {
  [REPLY_OPERATION_RUN_STATE]?: ReplyOperationRunState;
};
//#endregion
//#region src/auto-reply/reply/reply-source-binding.types.d.ts
declare const replySource: unique symbol;
type ReplySourceBinding = {
  [replySource]?: SessionControllerInput;
};
//#endregion
//#region src/auto-reply/reply/get-reply.types.d.ts
type ReplySessionBinding = {
  sessionKey?: string;
  sessionId: string;
  lifecycleRevision?: string;
  storePath?: string;
};
type PendingContinuationSettlement = {
  /** Accept visible status delivery or an explicit silent handoff; false releases custody. */
  settle: (statusDelivered: boolean) => Promise<void>;
};
type ReplyRunVerbosity = {
  verboseLevelOverride?: VerboseLevel;
  resolvedVerboseLevel: VerboseLevel;
};
type InternalReplySessionOptions = {
  /** Normalize a machine-selected thinking preference against the execution model. */
  normalizeThinkingLevelOverride?: boolean;
  /** Dispatch-owned command requester binding; never part of the public plugin API. */
  withCommandNativeSubagents?: <T>(binding: {
    agentId: string;
    sessionKey: string;
    entry: SessionEntry;
    storePath?: string;
    commandBody?: string;
  }, run: (create: NativeSubagentCommandFactory | undefined) => Promise<T>) => Promise<T>;
  /** Settles attribution before tool effects; model preparation may run concurrently. */
  awaitSessionDiffBaseline?: () => Promise<void>;
  /** One-shot model selection for host-owned turns; never persisted as a user preference. */
  modelOverride?: string;
  /** Host-owned scheduling authority retained through ordinary session execution. */
  scheduledAutomation?: ScheduledSessionAutomation;
  /** Host-owned silence permission for a producer's turn; never derived from provenance. */
  replyExpectation?: "optional";
  /** Producer callbacks follow this occurrence through queueing and delivery. */
  internalEventExecution?: SessionEventExecution;
  /** Host-only fallback eligibility; false preserves a caller without a profile grant. */
  sessionPrincipalTurn?: boolean;
  /** Source-owned cancellation retained when dispatch borrows an active lane for queued followups. */
  queuedFollowupAbortSignal?: AbortSignal;
  /** Host-minted original operator authority; never restored from session metadata. */
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /** Live channel policy retained from ingress through awaited lifecycle mutations. */
  assertChannelAuthority?: () => void;
  extractedFileImages?: ExtractedFileImage[];
  /** Rechecks the live Gateway caller before a chat login has a durable effect. */
  assertProviderLoginAuthority?: () => void;
  getProviderLoginConfig?: () => OpenClawConfig;
  /** Invocation-owned conversation facts; never execution or sender authority. */
  replyConversation?: PreparedReplyConversation;
  preparedTtsPreferences?: PreparedTtsPreferences;
  prepareAssistantTranscriptMessage?: PrepareAssistantTranscriptMessage;
  /** Internal delivery owner that stages reply media using current Gateway session policy. */
  mediaNormalizationOwner?: "gateway";
  /** Exact authority-bearing settings captured by Gateway chat admission. */
  admittedSessionSettings?: Readonly<Pick<SessionEntry, "permissionMode" | "toolOverrides">>;
  /** Host-stamped exact-run capability for late Codex creator-authority capture. */
  cronCreatorAuthorityCapability?: CronCreatorAuthorityCapability;
  /** Current external dashboard turn only; never persisted or inherited by another run. */
  dashboardReadAdmission?: DashboardMessageReadAdmission;
  expectedExistingSessionId?: string;
  /** Activity committed with this input before ACK; initialization reuses its timestamp. */
  recordedSessionActivity?: {
    sessionId: string;
    sessionKey: string;
    at: number;
  };
  /** Retained predecessor evidence; reply admission must verify its session lineage and store. */
  expectedActiveReplyOperation?: ReplyOperation;
  /** First dispatch only: admission created this exact pinned session before reply initialization. */
  newlyCreatedSessionId?: string;
  onDeliberateSilentTerminalReply?: () => void;
  /** Source-specific final delivery, e.g. a committed answer in the current WebChat history. */
  resolveReplyDelivery?: ReplyDeliveryObserver;
  /** Distinguishes committed source-tool custody from ordinary transcript presentation. */
  resolveReplyDeliveryFacts?: ReplyDeliveryFactsObserver;
  /** Retire the run's bundle MCP runtime at settlement. Set by one-shot isolated runs whose session ID is never reused. */
  cleanupBundleMcpOnRunEnd?: boolean;
  /** Defers child completion until the waiting status or explicit silent handoff settles. */
  onPendingContinuation?: (settlement?: PendingContinuationSettlement) => void;
  bindSessionCreation?: SessionEventExecution["bindSessionCreation"];
  /** Follow the admitted turn's own first-store registration in its retained request facts. */
  onDatabaseRegistration?: AgentDatabaseRequestExecutionSource["onRegistryChange"];
  onSessionCreated?: (created: SessionEntryCreationCommit) => void;
  /** Receives the LLM's own final response text — pre-delivery-normalization, sentinels included. */
  onRawLlmResponse?: (response: string) => void;
  onSessionPrepared?: (binding: ReplySessionBinding) => void;
  /** Observes one transcript-start reader preparation; completion cannot control the run. */
  onTranscriptStartPreparation?: () => (() => void) | undefined;
  onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void;
  /** Publishes each executing turn's preferences without persisting them to its session. */
  onRunVerbosityResolved?: (settings: ReplyRunVerbosity) => void;
  /** Prevent implicit rollover after a caller has durably admitted this exact session. */
  pinExpectedExistingSession?: boolean;
  requestedSessionId?: string;
  resumeRequestedSession?: boolean;
  sessionPromptSourceReplyDeliveryMode?: GetReplyOptions["sourceReplyDeliveryMode"];
  /** Overrides persisted queue mode for this reply only. */
  queueModeOverride?: QueueMode;
  /** Dispatch-owned operation used to defer hooks until durable run admission. */
  replyOperation?: ReplyOperation;
  /** Observe the admitted owner without transferring the runner's settlement custody. */
  onReplyOperationAdmitted?: (operation: ReplyOperation) => void;
  /** Return true only when the caller accepts settlement custody for this exact operation. */
  onReplyOperationOwned?: (operation: ReplyOperation) => boolean | void;
  skillOverrides?: SessionToolOverrides["skills"];
  skillLibraryAuthoring?: SkillLibraryAuthoringCapability;
};
type InternalGetReplyOptions = GetReplyOptions & PluginCommandReplyOptions & InternalReplySessionOptions & ReplyOptionsWithOperationRunState & ReplySourceBinding;
type ReplyResolver<Options extends GetReplyOptions> = (ctx: MsgContext, opts?: Options, configOverride?: OpenClawConfig) => Promise<ReplyPayload$1 | ReplyPayload$1[] | undefined>;
/** Reply resolver signature used by dispatchers and tests for dependency injection. */
type GetReplyFromConfig = ReplyResolver<GetReplyOptions>;
type InternalGetReplyFromConfig = ReplyResolver<InternalGetReplyOptions>;
//#endregion
//#region src/channels/typing.d.ts
type TypingCallbacks = {
  onReplyStart: () => Promise<void>;
  onIdle?: () => void;
  /** Called when the typing controller is cleaned up (e.g. on NO_REPLY). */
  onCleanup?: () => void;
};
type CreateTypingCallbacksParams = {
  start: () => Promise<void>;
  stop?: () => Promise<void>;
  onStartError: (err: unknown) => void;
  onStopError?: (err: unknown) => void;
  keepaliveIntervalMs?: number;
  /** Stop keepalive after this many consecutive start() failures. Default: 2 */
  maxConsecutiveFailures?: number;
  /** Maximum duration for typing indicator before auto-cleanup (safety TTL). Default: 60s */
  maxDurationMs?: number;
};
declare function createTypingCallbacks(params: CreateTypingCallbacksParams): TypingCallbacks;
//#endregion
//#region src/shared/silent-reply-policy.d.ts
type SilentReplyConversationType = "direct" | "group" | "internal";
//#endregion
//#region src/auto-reply/reply/response-prefix-template.d.ts
type ResponsePrefixContext = {
  /** Short model name (e.g., "gpt-5.4", "claude-opus-4-6") */
  model?: string;
  /** Full model ID including provider. */
  modelFull?: string;
  /** Provider name (e.g., "openai", "anthropic") */
  provider?: string;
  /** Current thinking level (e.g., "high", "low", "off") */
  thinkingLevel?: string;
  /** Agent identity name */
  identityName?: string;
};
//#endregion
//#region src/auto-reply/reply/reply-dispatcher.d.ts
type ReplyDispatcherOptions = {
  deliver: (payload: ReplyPayload$1, info: ReplyDispatchRuntimeInfo) => Promise<unknown>;
  /**
   * Receives a fresh plan after normalization and modifiers. When omitted, prepared
   * sends fall back to deliver(payload, info), retaining that adapter's raw contract.
   */
  deliverPrepared?: (plan: OutboundPayloadPlan, info: ReplyDispatchRuntimeInfo) => Promise<unknown>;
  /** The delivery callback admits custody before external I/O and owns failure settlement. */
  pendingFinalDeliveryAdmission?: "deliver";
  silentReplyContext?: {
    cfg?: OpenClawConfig;
    sessionKey?: string;
    surface?: string;
    conversationType?: SilentReplyConversationType;
  };
  responsePrefix?: string;
  transformReplyPayload?: (payload: ReplyPayload$1) => ReplyPayload$1 | null;
  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> | void;
  onError?: (err: unknown, info: ReplyDispatchRuntimeInfo) => Promise<void> | void;
  /** Let ingress retry proven-unsent work only when outbound recovery holds no delivery. */
  propagateRetryableNoSendFailure?: boolean;
  /** Lets channels detect silent/empty drops for their empty-response fallback. */
  onSkip?: (payload: ReplyPayload$1, info: ReplyDispatchRuntimeInfo & {
    reason: NormalizeReplySkipReason;
  }) => void;
  humanDelay?: HumanDelayConfig;
  beforeDeliver?: ReplyDispatchBeforeDeliver;
  /** Owner-declared deadline for the constructor before-delivery callback. */
  beforeDeliverOptions?: ReplyDispatchBeforeDeliverOptions;
  onBeforeDeliverCancelled?: (payload: ReplyPayload$1, info: ReplyDispatchRuntimeInfo) => Promise<void> | void;
  /** Observe each queued payload settling, including cancellation and delivery failure. */
  onDeliverySettled?: (info: ReplyDispatchRuntimeInfo) => void;
  /** Resolve an owner activity policy for holding queued follow-ups behind delivery. */
  resolveFollowupAdmissionBarrierTimeoutPolicy?: (context: {
    queuedCounts: Readonly<Record<ReplyDispatchKind, number>>;
    humanDelayBudgetMs: number;
  }) => ReplyFollowupAdmissionBarrierTimeoutPolicy | undefined;
};
type ReplyDispatcherWithTypingOptions = Omit<ReplyDispatcherOptions, "onIdle"> & {
  typingCallbacks?: TypingCallbacks;
  onReplyStart?: () => Promise<void> | void;
  onIdle?: () => Promise<void> | void;
  onSettled?: () => unknown;
  onFreshSettledDelivery?: () => unknown;
  /** Called when the typing controller is cleaned up (e.g., on NO_REPLY). */
  onCleanup?: () => void;
};
type ReplyDispatcherWithTypingResult = {
  dispatcher: ReturnType<typeof createReplyDispatcher>;
  replyOptions: Pick<GetReplyOptions, "onReplyStart" | "onTypingController" | "onTypingCleanup">;
  markDispatchIdle: () => void;
  /** Signal that the model run is complete so the typing controller can stop. */
  markRunComplete: () => void;
};
declare function createReplyDispatcher(options: ReplyDispatcherOptions): ReplyDispatcher & Required<Pick<ReplyDispatcher, "sendPreparedReply">>;
declare function createReplyDispatcherWithTyping(options: ReplyDispatcherWithTypingOptions): ReplyDispatcherWithTypingResult;
//#endregion
//#region src/infra/outbound/payloads.d.ts
type NormalizedOutboundPayload = {
  text: string;
  mediaUrls: string[];
  audioAsVoice?: boolean;
  presentation?: MessagePresentation;
  presentationTextMode?: ReplyPayload$1["presentationTextMode"];
  delivery?: ReplyPayloadDelivery;
  interactive?: LegacyInteractiveReply;
  channelData?: Record<string, unknown>;
  location?: ReplyPayload$1["location"];
  /** Hook-only content for audio-only TTS payloads. Never used as channel text/caption. */
  hookContent?: string;
  /** Preserves the status/answer distinction through delivery hooks. */
  isStatusNotice?: boolean;
};
type OutboundPayloadJson = Omit<NormalizedOutboundPayload, "mediaUrls" | "hookContent" | "isStatusNotice"> & Pick<ReplyPayload$1, "isError" | "mediaUrls"> & {
  mediaUrl: string | null;
};
type OutboundPayloadPlanContext = {
  cfg?: OpenClawConfig;
  sessionKey?: string;
  surface?: string;
  conversationType?: SilentReplyConversationType;
  extractMarkdownImages?: boolean;
};
/** Parses raw reply text before building the canonical outbound payload plan. */
declare function createOutboundPayloadPlan(payloads: readonly ReplyPayload$1[], context?: OutboundPayloadPlanContext): OutboundPayloadPlan[];
/** Plans admitted payload fields without reapplying lane policy or interpreting text directives. */
declare function createStructuredOutboundPayloadPlan(payloads: readonly ReplyPayload$1[]): OutboundPayloadPlan[];
declare function projectOutboundPayloadPlanForDelivery(plan: readonly OutboundPayloadPlan[]): ReplyPayload$1[];
declare function projectOutboundPayloadPlanForJson(plan: readonly OutboundPayloadPlan[]): OutboundPayloadJson[];
//#endregion
//#region src/config/sessions/session-delivery-generation.types.d.ts
type SessionDeliveryGeneration = Readonly<{
  agentId: string;
  storePath: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision: string | null;
}>;
//#endregion
//#region src/sessions/background-session-result.d.ts
/** Identifies which background producer wrote a result row. */
type BackgroundSessionResultProvenance = {
  kind: "cron";
  jobId: string;
  runId: string;
} | {
  kind: typeof SUBAGENT_COMPLETION_RESULT_KIND;
};
//#endregion
//#region src/infra/delivery-queue-sqlite.types.d.ts
type DeliveryQueueCompletionRetention = "permanent" | Readonly<{
  idPrefix: string;
  maxAgeMs: number;
  maxEntries: number;
}>;
/** Persisted queue entry fields common to all delivery queue payloads. */
type DeliveryQueueEntryState = {
  id: string;
  enqueuedAt: number;
  retryCount: number;
  availableAt?: number;
  /** Only explicit reusable producers retain a platform-send ownership lease. */
  requiresProducerClaim?: boolean;
  producerClaimId?: string;
  /** Durable delivery-call count reserved before invoking the provider path. */
  attemptCount?: number;
  completionRetention?: DeliveryQueueCompletionRetention;
  /** Failure-only ownership fence; successful acknowledgement ignores this field. */
  retainOnFailure?: true;
  acknowledgedAt?: number;
  lastAttemptAt?: number;
  lastError?: string;
  /** UUID fencing one platform attempt even when clock timestamps collide. */
  platformSendAttemptId?: string;
  platformSendStartedAt?: number;
  recoveryState?: string;
  /** Producer-specific durable attempt budget; an unconfirmed final-text replay caps it. */
  maxRetries?: number;
};
//#endregion
//#region src/infra/delivery-queue-state-context.d.ts
type DeliveryQueueStateContext = {
  stateDir: string;
  workerContext: OpenClawStateWorkerContext;
  supervisorMode?: "external";
};
//#endregion
//#region src/infra/outbound/identity.d.ts
/** Resolves an agent's configured identity into channel-safe outbound metadata. */
declare function resolveAgentOutboundIdentity(cfg: OpenClawConfig, agentId: string): OutboundIdentity | undefined;
//#endregion
//#region src/infra/outbound/prepared-batch.d.ts
declare const PREPARED_OUTBOUND_BATCH_SCHEMA_VERSION: 1;
type PreparedOutboundAcceptedEntry = {
  sourceIndex: number;
  status: "accepted";
  payload: ReplyPayload$1;
  replyHookChanged: boolean;
  messageHookChanged: boolean;
  preparedMediaCount: number;
};
type PreparedOutboundSuppressedEntry = Omit<Extract<OutboundPayloadDeliveryOutcome, {
  status: "suppressed";
}>, "index"> & {
  sourceIndex: number;
};
type PreparedOutboundBatchEntry = PreparedOutboundAcceptedEntry | PreparedOutboundSuppressedEntry;
/** Canonical post-policy payload custody persisted by the durable outbound queue. */
type PreparedOutboundBatch = {
  schemaVersion: typeof PREPARED_OUTBOUND_BATCH_SCHEMA_VERSION;
  sourcePayloadCount: number;
  /** True only when accepted payloads already passed post-policy channel normalization. */
  channelNormalized?: true;
  runId?: string;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  entries: PreparedOutboundBatchEntry[];
};
//#endregion
//#region src/infra/outbound/session-context.d.ts
type OutboundSessionContext = {
  /**
   * Canonical session key used for internal hook dispatch.
   *
   * MUST equal the agent runtime's `params.sessionKey` for the run that
   * produced the payload being delivered. Plugins observing both
   * `agent_end`/`llm_input`/`llm_output`/`before_tool_call`/`after_tool_call`
   * and `message_sending`/`message_sent` rely on this equality to correlate
   * per-turn state across the agent-loop and delivery boundaries.
   *
   * Callers populating this field should use the same value the agent runner
   * received as its sessionKey — in the chat path that is
   * `targetSessionKey || ctx.SessionKey` (see
   * `auto-reply/reply/get-reply.ts`). Followup, ACP, command, and cron
   * delivery paths each have their own canonical value to forward; consult
   * the relevant runner.
   *
   * Destination history treats this key as the producing conversation: a
   * confirmed send back into it is not recorded again. Sends without a
   * producing turn must leave it unset and use `policyKey` instead.
   */
  key?: string;
  /**
   * Session key used for policy resolution when delivery differs from the
   * control session. Used to look up silent-reply policy, send rate limits,
   * agent-scoped channel preferences, etc., for the chat the reply is being
   * delivered into. May equal `key` when there is no redirect; otherwise
   * `policyKey` describes the *delivery target*'s session while `key`
   * describes the *control session* whose hooks fire.
   */
  policyKey?: string;
  /** Explicit conversation type for policy resolution when a session key is generic. */
  conversationType?: SilentReplyConversationType;
  /**
   * Caller-declared destination conversation kind for metadata-only audit
   * projection. Never derived from session-key parsing: policy keys can name
   * an acted-on session that is not the delivery destination, and a wrong
   * "direct" here over-collects under audit.messages="direct".
   */
  conversationKind?: "direct" | "group" | "channel";
  /** Active agent id used for workspace-scoped media roots. */
  agentId?: string;
  /** Originating account id used for requester-scoped group policy resolution. */
  requesterAccountId?: string;
  /** Originating sender id used for sender-scoped outbound media policy. */
  requesterSenderId?: string;
  /** Originating sender display name for name-keyed sender policy matching. */
  requesterSenderName?: string;
  /** Originating sender username for username-keyed sender policy matching. */
  requesterSenderUsername?: string;
  /** Originating sender E.164 phone number for e164-keyed sender policy matching. */
  requesterSenderE164?: string;
};
/** Builds the outbound delivery session context, omitting empty policy fields. */
declare function buildOutboundSessionContext(params: {
  cfg: OpenClawConfig;
  sessionKey?: string | null;
  policySessionKey?: string | null;
  conversationType?: string | null;
  isGroup?: boolean | null;
  agentId?: string | null;
  requesterAccountId?: string | null;
  requesterSenderId?: string | null;
  requesterSenderName?: string | null;
  requesterSenderUsername?: string | null;
  requesterSenderE164?: string | null;
}): OutboundSessionContext | undefined;
//#endregion
//#region src/infra/outbound/delivery-queue-types.d.ts
/** Serializable owner callback for a durable queue entry. */
type DurableDeliveryCompletion = {
  kind: "conversation";
  agentId: string;
  operationId: string;
  storePath?: string;
  /** Present on Gateway-owned conversation intents created with route authorization. */
  routeFingerprint?: string;
} | {
  kind: "pending-final";
  /** Null means an owner was admitted without recoverable authority; fail closed. */
  commandOwnerReference?: CommandOwnerAssertion["recoveryReference"];
  /** Older queue records retain the canonical locator's original owner selection. */
  agentId?: string;
  deliveryId: string;
  intentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
  sessionWriterDeliveryAuthority?: SessionWriterDeliveryAuthority;
};
type QueuedReplyPayloadSendingHook = {
  kind: ReplyDispatchKind;
  channel?: string;
  sessionKey?: string;
  runId?: string;
  context: PluginHookReplyPayloadSendingContext;
};
type QueuedDeliveryPayload = {
  sessionGeneration?: SessionDeliveryGeneration;
  transcriptProvenance?: BackgroundSessionResultProvenance;
  channel: string;
  to: string;
  accountId?: string;
  queuePolicy?: "required" | "best_effort";
  requireUnknownSendReconciliation?: boolean;
  retryAmbiguousFinalText?: true;
  /** Current failed attempt had a typed transport error and no accepted message. */
  ambiguousTransportError?: true;
  requiresProducerClaim?: boolean;
  preparedBatch?: PreparedOutboundBatch;
  payloads?: ReplyPayload$1[];
  renderedBatchPlan?: RenderedMessageBatchPlan;
  threadId?: string | number | null;
  reply?: OutboundReplyFacts;
  formatting?: OutboundDeliveryFormattingOptions;
  identity?: OutboundIdentity;
  bestEffort?: boolean;
  gifPlayback?: boolean;
  forceDocument?: boolean;
  silent?: boolean;
  /** Retained persisted metadata; never used for delivery, hooks, or transcript ownership. */
  mirror?: {
    sessionKey: string;
    agentId?: string;
    text?: string;
    mediaUrls?: string[];
    idempotencyKey?: string;
    expectedSessionId?: string;
    deliveryMirror?: SessionTranscriptDeliveryMirror;
    isGroup?: boolean;
    groupId?: string;
  };
  session?: OutboundSessionContext;
  gatewayClientScopes?: readonly string[];
  preparedMessageId?: string;
  deliveryCompletion?: DurableDeliveryCompletion;
  completionRetention?: DeliveryQueueCompletionRetention;
  legacyUnknownSendReconciliation?: Exclude<ChannelMessageUnknownSendReconciliationResult, {
    status: "unresolved";
  }>;
  legacyPreparedContentUnavailable?: true;
  maxRetries?: number;
};
type DeliveryFailureSettlement = {
  error: string;
  unknownSendCleanup?: true;
  terminals?: readonly IndexedOutboundAuditTerminal[];
} & ({
  outcome: "unknown";
} | {
  outcome: "failed";
  rejectionError?: string;
});
type QueuedDelivery = Omit<QueuedDeliveryPayload, "preparedBatch" | "payloads"> & Omit<DeliveryQueueEntryState, "attemptCount" | "recoveryState" | "acknowledgedAt"> & {
  preparedBatch: PreparedOutboundBatch;
  attemptCount: number;
  effectiveReplyToId?: string | null;
  recoveryState?: "producer_claimed" | "send_attempt_started" | "unknown_after_send" | "settlement_pending";
  settlement?: DeliveryFailureSettlement;
};
//#endregion
//#region src/infra/outbound/delivery-queue-settlement.types.d.ts
type AckDeliveryOptions = {
  /** Caller holds a GC-visible recovery lease until its active adapter settles. */
  retainSpoolArtifacts?: boolean;
  /** An intentionally suppressed pre-send batch must not become a success receipt. */
  suppressCompletionReceipt?: boolean;
  /** Prevent an older provider attempt from settling a replacement owner. */
  expectedPlatformSendAttemptId?: string | null;
};
//#endregion
//#region src/infra/outbound/delivery-queue-ack.kernel.d.ts
/** Retires an unsent live claim while its adapter preparation still owns resources. */
declare function retireUnsentDeliveryInDatabase(database: OpenClawStateDatabase, params: {
  id: string;
  producerClaimId: string;
  stateDir?: string;
}, terminalOutcome?: "failed"): {
  spoolPaths: string[];
  retention?: string;
} | undefined;
//#endregion
//#region src/infra/outbound/delivery-queue-ack.d.ts
/** Retires an unsent live claim while its adapter preparation still owns resources. */
declare function retireUnsentDelivery(params: Parameters<typeof retireUnsentDeliveryInDatabase>[1], context?: DeliveryQueueStateContext, terminalOutcome?: "failed"): Promise<(() => Promise<void>) | undefined>;
/** Remove a successfully delivered entry, or retain its producer-owned receipt. */
declare function ackDelivery(id: string, requestedStateDir?: string, options?: AckDeliveryOptions, context?: DeliveryQueueStateContext): Promise<void>;
//#endregion
//#region src/infra/outbound/deliver-queue-state.d.ts
type QueuedDeliveryFailureRecorder = (id: string, error: string, stateDir?: string, expectedPlatformSendAttemptId?: string | null) => Promise<void>;
/** Keeps live and recovered queue transitions on the same producer claim. */
declare function createQueuedDeliveryOwner(params: {
  queueId: string;
  stateDir?: string;
  expectedPlatformSendAttemptId?: string | null;
  signal?: AbortSignal;
}, context?: DeliveryQueueStateContext): {
  queueId: string;
  stateDir: string | undefined;
  claimId: string | null | undefined;
  signal: AbortSignal | undefined;
  readonly custody: "held" | "released";
  project(error: unknown, evidence?: Omit<ConstructorParameters<typeof OutboundDeliveryError>[1], "cause">): OutboundDeliveryError;
  retireUnsent(terminalOutcome?: "failed"): ReturnType<typeof retireUnsentDelivery>;
  ack(options?: Parameters<typeof ackDelivery>[2]): Promise<void>;
  finalizeFailure(entry: QueuedDelivery): Promise<boolean>;
  fail(record: QueuedDeliveryFailureRecorder, error: string, ambiguousTransportError?: true): Promise<void>;
  retire(): Promise<void>;
};
type QueuedDeliveryOwner = ReturnType<typeof createQueuedDeliveryOwner>;
//#endregion
//#region src/infra/outbound/reply-policy.d.ts
/** Resolved reply target plus whether it came from payload or ambient context. */
type ReplyToResolution = {
  replyToId?: string;
  source?: "explicit" | "implicit";
};
/** Creates a reply-to supplier that consumes implicit single-use reply ids once. */
declare function createReplyToFanout(params: {
  replyToId?: string | null;
  replyToMode?: ReplyToMode;
  replyToIdSource?: ReplyToResolution["source"];
}): () => string | undefined;
//#endregion
//#region src/shared/requirements.d.ts
type Requirements = {
  bins: string[];
  anyBins: string[];
  env: string[];
  config: string[];
  os: string[];
};
type RequirementsMetadata = {
  requires?: Partial<Pick<Requirements, "bins" | "anyBins" | "env" | "config">>;
  os?: string[];
};
//#endregion
//#region src/hooks/types.d.ts
type HookInstallSpec = {
  id?: string;
  kind: "bundled" | "npm" | "git";
  label?: string;
  package?: string;
  repository?: string;
  bins?: string[];
};
type OpenClawHookMetadata = RequirementsMetadata & {
  always?: boolean;
  hookKey?: string;
  emoji?: string;
  homepage?: string;
  /** Events this hook handles (e.g., ["command:new", "session:start"]) */
  events: string[];
  /** Optional export name (default: "default") */
  export?: string;
  install?: HookInstallSpec[];
};
type ParsedHookFrontmatter = Record<string, string>;
type Hook = {
  name: string;
  description: string;
  source: "openclaw-bundled" | "openclaw-managed" | "openclaw-workspace" | "openclaw-plugin";
  pluginId?: string;
  filePath: string;
  baseDir: string;
  handlerPath: string;
};
type HookEntry = {
  hook: Hook;
  frontmatter: ParsedHookFrontmatter;
  metadata?: OpenClawHookMetadata;
  invocation?: {
    enabled: boolean;
  };
};
//#endregion
//#region src/plugins/hook-registry.types.d.ts
/** Legacy hook registration stored by the global hook runner registry. */
type PluginLegacyHookRegistration = {
  pluginId: string;
  entry: HookEntry;
  events: string[];
  source: string;
  rootDir?: string;
};
/** Hook runner registry state for legacy and typed plugin hooks. */
type HookRunnerRegistry = {
  hooks: PluginLegacyHookRegistration[];
  typedHooks: PluginHookRegistration[];
};
/** Global hook runner registry snapshot with plugin load status. */
type GlobalHookRunnerRegistry = HookRunnerRegistry & {
  plugins: Array<{
    id: string;
    packageVersion?: string;
    status: "loaded" | "disabled" | "error";
  }>;
};
//#endregion
//#region src/plugins/hook-runner-types.d.ts
type HookEvent<K extends PluginHookName> = Parameters<PluginHookHandlerMap[K]>[0];
type HookContext$1<K extends PluginHookName> = Parameters<PluginHookHandlerMap[K]>[1];
type HookFailurePolicy = "fail-open" | "fail-closed";
type VoidHookRunOptions = {
  unrefTimeout?: boolean;
};
type BeforeAgentFinalizeRetry = NonNullable<PluginHookBeforeAgentFinalizeResult["retry"]>;
type BeforeAgentFinalizeResultWithRetryCandidates = PluginHookBeforeAgentFinalizeResult & {
  retryCandidates?: BeforeAgentFinalizeRetry[];
};
type HookRunnerOptions = {
  logger?: {
    debug?: (message: string) => void;
    warn: (message: string) => void;
    error: (message: string) => void;
  };
  /** If true, errors in hooks will be caught and logged instead of thrown */
  catchErrors?: boolean;
  failurePolicyByHook?: Partial<Record<PluginHookName, HookFailurePolicy>>;
  voidHookTimeoutMsByHook?: Partial<Record<PluginHookName, number>>;
  modifyingHookTimeoutMsByHook?: Partial<Record<PluginHookName, number>>;
};
//#endregion
//#region src/plugins/runtime/subagent-requester-context.d.ts
type PluginSubagentRequesterContext = Readonly<{
  sessionKey: string;
  origin: Readonly<DeliveryContext>;
}>;
//#endregion
//#region src/plugins/hooks.d.ts
type PluginTargetedInboundClaimOutcome = {
  status: "handled";
  result: PluginHookInboundClaimResult;
} | {
  status: "missing_plugin";
} | {
  status: "no_handler";
} | {
  status: "declined";
} | {
  status: "error";
  error: string;
};
declare function createHookRunner(registry: GlobalHookRunnerRegistry, options?: HookRunnerOptions): {
  runBeforeModelResolve: (event: PluginHookBeforeModelResolveEvent, ctx: PluginHookAgentContext) => Promise<PluginHookBeforeModelResolveResult | undefined>;
  runAgentTurnPrepare: (event: PluginAgentTurnPrepareEvent, ctx: PluginHookAgentContext) => Promise<PluginAgentTurnPrepareResult | undefined>;
  runBeforePromptBuild: (event: PluginHookBeforePromptBuildEvent, ctx: PluginHookAgentContext) => Promise<PluginHookBeforePromptBuildResult | undefined>;
  runAuthorizedPromptBuild: (event: PluginHookBeforePromptBuildEvent, ctx: PluginHookAgentContext, params: {
    toolAuthorityFingerprint: string;
    activeToolNames: readonly string[];
    assertHostActive: () => void;
  }) => Promise<PluginHookBeforePromptBuildResult | undefined>;
  hasAuthorizedPromptBuildHooks: (ctx?: Partial<HookContext$1<"before_prompt_build">>) => boolean;
  runBeforeAgentReply: (event: PluginHookBeforeAgentReplyEvent, ctx: PluginHookAgentContext, runHandler?: ((run: () => Promise<void | PluginHookBeforeAgentReplyResult>) => Promise<void | PluginHookBeforeAgentReplyResult>) | undefined) => Promise<PluginHookBeforeAgentReplyResult | undefined>;
  runModelCallStarted: (event: PluginHookContextWindow & {
    runId: string;
    callId: string;
    sessionKey?: string;
    sessionId?: string;
    provider: string;
    model: string;
    api?: string;
    transport?: string;
  }, ctx: PluginHookAgentContext) => Promise<void>;
  runModelCallEnded: (event: PluginHookModelCallEndedEvent, ctx: PluginHookAgentContext) => Promise<void>;
  runLlmInput: (event: PluginHookLlmInputEvent, ctx: PluginHookAgentContext) => Promise<void>;
  runLlmOutput: (event: PluginHookLlmOutputEvent, ctx: PluginHookAgentContext) => Promise<void>;
  runBeforeAgentFinalize: (event: HookEvent<"before_agent_finalize">, ctx: HookContext$1<"before_agent_finalize">) => Promise<BeforeAgentFinalizeResultWithRetryCandidates | undefined>;
  runAgentEnd: (event: HookEvent<"agent_end">, ctx: HookContext$1<"agent_end">, optionsLocal?: VoidHookRunOptions) => Promise<void>;
  runBeforeCompaction: (event: {
    messageCount: number;
    compactingCount?: number;
    tokenCount?: number;
    messages?: unknown[];
    sessionFile?: string;
  }, ctx: PluginHookAgentContext) => Promise<void>;
  runAfterCompaction: (event: {
    messageCount: number;
    tokenCount?: number;
    compactedCount: number;
    sessionFile?: string;
    previousSessionId?: string;
  }, ctx: PluginHookAgentContext) => Promise<void>;
  runBeforeReset: (event: {
    sessionFile?: string;
    messages?: unknown[];
    reason?: string;
  }, ctx: PluginHookAgentContext) => Promise<void>;
  runBeforeChannelIngress: (event: HookEvent<"before_channel_ingress">, ctx: HookContext$1<"before_channel_ingress">) => Promise<{
    event: unknown;
    assertCurrent: () => void;
  } | undefined>;
  runBeforeAgentRun: (event: PluginHookBeforeAgentRunEvent, ctx: PluginHookAgentContext) => Promise<GateHookResult<InputGateDecision> | undefined>;
  runInboundClaim: (event: PluginHookInboundClaimEvent, ctx: PluginHookInboundClaimContext, runHandler?: ((run: () => Promise<void | PluginHookInboundClaimResult>) => Promise<void | PluginHookInboundClaimResult>) | undefined) => Promise<PluginHookInboundClaimResult | undefined>;
  runInboundClaimForPlugin: (pluginId: string, event: PluginHookInboundClaimEvent, ctx: PluginHookInboundClaimContext) => Promise<PluginHookInboundClaimResult | undefined>;
  runInboundClaimForPluginOutcome: (pluginId: string, event: PluginHookInboundClaimEvent, ctx: PluginHookInboundClaimContext) => Promise<PluginTargetedInboundClaimOutcome>;
  runChannelPairingRequested: (event: {
    channel: string;
    accountId?: string;
    senderId: string;
    code: string;
    metadata?: Record<string, string | undefined>;
  }, ctx: {
    channelId: string;
    accountId?: string;
    senderId: string;
  }) => Promise<void>;
  runMessageReceived: (event: PluginHookMessageReceivedEvent, ctx: PluginHookMessageContext) => Promise<void>;
  runBeforeDispatch: (event: PluginHookBeforeDispatchEvent, ctx: PluginHookBeforeDispatchContext, requester?: PluginSubagentRequesterContext) => Promise<PluginHookBeforeDispatchResult | undefined>;
  runReplyDispatch: (event: PluginHookReplyDispatchEvent, ctx: PluginHookReplyDispatchContext, runHandler?: ((run: () => Promise<void | PluginHookReplyDispatchResult>) => Promise<void | PluginHookReplyDispatchResult>) | undefined) => Promise<PluginHookReplyDispatchResult | undefined>;
  runReplyPayloadSending: (event: PluginHookReplyPayloadSendingEvent, ctx: PluginHookMessageContext) => Promise<PluginHookReplyPayloadSendingResult | undefined>;
  runMessageSending: (event: HookEvent<"message_sending">, ctx: HookContext$1<"message_sending">) => Promise<{
    content?: string;
    cancel?: boolean;
    cancelReason?: string;
    metadata?: Record<string, unknown>;
  } | undefined>;
  runMessageSent: (event: PluginHookMessageSentEvent, ctx: PluginHookMessageContext) => Promise<void>;
  runBeforeToolCall: (event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext, receipt?: Readonly<{
    token: ExecutionIdentityAdmissionToken;
    assertAuthority: () => boolean | void;
    markOwnerDecision?: () => void;
  }>) => Promise<PluginHookBeforeToolCallResult | undefined>;
  runAfterToolCall: (event: HookEvent<"after_tool_call">, ctx: HookContext$1<"after_tool_call">) => Promise<void>;
  runToolResultPersist: (event: PluginHookToolResultPersistEvent, ctx: PluginHookToolResultPersistContext) => PluginHookToolResultPersistResult | undefined;
  runBeforeMessageWrite: (event: PluginHookBeforeMessageWriteEvent, ctx: {
    agentId?: string;
    sessionKey?: string;
  }) => PluginHookBeforeMessageWriteResult | undefined;
  runSessionStart: (event: PluginHookSessionStartEvent, ctx: PluginHookSessionContext) => Promise<void>;
  runSessionEnd: (event: HookEvent<"session_end">, ctx: HookContext$1<"session_end">) => Promise<void>;
  runSubagentDeliveryTarget: (event: {
    childSessionKey: string;
    requesterSessionKey: string;
    requesterOrigin?: {
      channel?: string;
      accountId?: string;
      to?: string;
      threadId?: string | number;
    };
    childRunId?: string;
    spawnMode?: "run" | "session";
    expectsCompletionMessage: boolean;
  }, ctx: {
    runId?: string;
    childSessionKey?: string;
    requesterSessionKey?: string;
  }) => Promise<PluginHookSubagentDeliveryTargetResult | undefined>;
  runSubagentSpawned: (event: {
    childSessionKey: string;
    agentId: string;
    label?: string;
    mode: "run" | "session";
    requester?: {
      channel?: string;
      accountId?: string;
      to?: string;
      threadId?: string | number;
      channelId?: string | number;
      messageId?: string | number;
    };
    threadRequested: boolean;
  } & {
    runId: string;
    resolvedModel?: string;
    resolvedProvider?: string;
  }, ctx: {
    runId?: string;
    childSessionKey?: string;
    requesterSessionKey?: string;
  }) => Promise<void>;
  runSubagentProgress: (event: {
    phase: "started";
    runId: string;
    childSessionKey: string;
    requester?: {
      channel?: string;
      accountId?: string;
      to?: string;
      threadId?: string | number;
      channelId?: string | number;
      messageId?: string | number;
    };
  } | {
    phase: "ended";
    runId: string;
    childSessionKey: string;
    outcome: "ok" | "error" | "timeout" | "killed" | "unknown";
    requester?: {
      channel?: string;
      accountId?: string;
      to?: string;
      threadId?: string | number;
      channelId?: string | number;
      messageId?: string | number;
    };
  }, ctx: {
    runId?: string;
    childSessionKey?: string;
    requesterSessionKey?: string;
  }) => Promise<void>;
  runSubagentEnded: (event: {
    targetSessionKey: string;
    targetKind: "acp" | "subagent";
    reason: string;
    sendFarewell?: boolean;
    accountId?: string;
    runId?: string;
    endedAt?: number;
    outcome?: "ok" | "error" | "timeout" | "killed" | "reset" | "deleted";
    error?: string;
  }, ctx: {
    runId?: string;
    childSessionKey?: string;
    requesterSessionKey?: string;
  }) => Promise<void>;
  runGatewayStart: (event: PluginHookGatewayStartEvent, ctx: PluginHookGatewayContext) => Promise<void>;
  runGatewayStop: (event: PluginHookGatewayStopEvent, ctx: PluginHookGatewayContext) => Promise<void>;
  runHeartbeatPromptContribution: (event: PluginHeartbeatPromptContributionEvent, ctx: PluginHookAgentContext) => Promise<PluginAgentTurnPrepareResult | undefined>;
  runCronReconciled: (event: PluginHookCronReconciledEvent, ctx: PluginHookCronReconciledContext) => Promise<void>;
  runCronChanged: (event: PluginHookCronChangedEvent, ctx: PluginHookGatewayContext) => Promise<void>;
  runSkillChanged: (event: PluginHookSkillChangedEvent, ctx: PluginHookSkillContext) => Promise<void>;
  runBeforeInstall: (event: PluginHookBeforeInstallEvent, ctx: PluginHookBeforeInstallContext) => Promise<{
    findings?: {
      ruleId: string;
      severity: "info" | "warn" | "critical";
      file: string;
      line: number;
      message: string;
    }[];
    block?: boolean;
    blockReason?: string;
  } | undefined>;
  runResolveExecEnv: (event: PluginHookResolveExecEnvEvent, ctx: PluginHookResolveExecEnvContext) => Promise<Record<string, string>>;
  hasHooks: <K extends PluginHookName>(hookName: K, ctx?: Partial<HookContext$1<K>>) => boolean;
  getHookCount: (hookName: PluginHookName) => number;
};
type HookRunner = ReturnType<typeof createHookRunner>;
//#endregion
//#region src/plugins/hook-runner-global.d.ts
/**
 * Initialize the global hook runner with a plugin registry.
 * Called on every plugin registry activation and by SDK consumers. The runner
 * instance stays stable so references captured mid-run keep seeing current hooks.
 */
declare function initializeGlobalHookRunner(registry: GlobalHookRunnerRegistry): void;
/**
 * Get the global hook runner.
 * Returns null if plugins haven't been loaded yet.
 */
declare function getGlobalHookRunner(): HookRunner | null;
/**
 * Reset the global hook runner (for testing).
 */
declare function resetGlobalHookRunner(): void;
//#endregion
//#region src/infra/outbound/message-sent-hook.d.ts
type MessageSentEvent = {
  success: boolean;
  content: string;
  error?: string;
  messageId?: string;
};
//#endregion
//#region src/infra/outbound/outbound-session.d.ts
type OutboundSessionRoute = {
  sessionKey: string;
  baseSessionKey: string;
  /** Route authority for explicit recipient session selection. */
  recipientSessionExact?: boolean | "direct-alias" | "delivery-identity";
  peer: RoutePeer;
  chatType: "direct" | "group" | "channel";
  /** Canonical conversation identity mirrored into MsgContext.From. */
  from: string;
  /** Routable delivery address mirrored into MsgContext.To. */
  to: string;
  threadId?: string | number;
  /** Trusted human-readable target name resolved before delivery. */
  displayName?: string;
};
//#endregion
//#region src/infra/outbound/deliver-contracts.d.ts
type ConversationDeliveryAttemptAuthority = Omit<Extract<DurableDeliveryCompletion, {
  kind: "conversation";
}>, "kind">;
type OutboundHandoff = <T>(initiate: () => Promise<T>) => Promise<T>;
type OutboundDeliveryIntent = {
  id: string;
  channel: string;
  to: string;
  accountId?: string;
  queuePolicy: OutboundDeliveryQueuePolicy;
};
type DurableFinalDeliveryRequirement = keyof NonNullable<ChannelDeliveryCapabilities["durableFinal"]>;
type DurableFinalDeliveryRequirements = Partial<Record<DurableFinalDeliveryRequirement, boolean>>;
type OutboundChannelContext = {
  cfg: OpenClawConfig;
  channel: string;
  to: string;
  accountId?: string;
  formatting?: OutboundDeliveryFormattingOptions;
  threadId?: string | number | null;
  identity?: OutboundIdentity;
  deps?: OutboundSendDeps;
  gifPlayback?: boolean;
  forceDocument?: boolean;
  silent?: boolean;
  abortSignal?: AbortSignal;
  mediaAccess?: OutboundMediaAccess;
  gatewayClientScopes?: readonly string[];
  conversationReadOrigin?: "delegated" | "direct-operator";
  /** @internal Opaque durable intent id forwarded to provider reconciliation hooks. */
  deliveryQueueId?: string;
  /** @internal Channel-valid id reserved before a correlated conversation turn is sent. */
  preparedMessageId?: string;
  /** @internal Recheck the concrete post-hook send shape before platform I/O. */
  requiredUnknownSendReconciliation?: boolean;
  /** @internal Revalidate caller authority before direct adapter code can run. */
  onDirectAdapterHandoff?: () => Promise<void>;
  /** @internal Initiates the platform method inside the caller's final authority grant. */
  withDirectAdapterHandoff?: OutboundHandoff;
  /** @internal Synchronously fence authority at the final adapter invocation. */
  assertDirectAdapterHandoff?: () => void;
  /** @internal Refresh durable timing before recipient-visible or finalizing platform I/O. */
  onPlatformSendDispatch?: () => Promise<void>;
  /** @internal Runs after each identified platform result, before further fallible work. */
  onDeliveryResult?: (result: OutboundDeliveryResult) => Promise<void> | void;
};
type DeliverOutboundPayloadsCoreParams = OutboundChannelContext & {
  payloads: ReplyPayload$1[];
  /** Admitted run correlation copied into the prepared durable batch. */
  runId?: string;
  /** @internal Exact admitted execution provenance copied into durable custody. */
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  /** @internal Canonical post-policy batch used by queue recovery and physical delivery. */
  preparedBatch?: PreparedOutboundBatch;
  reply?: OutboundReplyFacts;
  replyPayloadSendingHook?: QueuedReplyPayloadSendingHook;
  bestEffort?: boolean;
  onError?: (err: unknown, payload: NormalizedOutboundPayload) => void;
  onPayload?: (payload: NormalizedOutboundPayload) => void;
  /** @internal Reports the effective payload only after an identified platform send. */
  onDeliveredPayload?: (payload: NormalizedOutboundPayload) => void;
  onPayloadDeliveryOutcome?: (outcome: OutboundPayloadDeliveryOutcome) => void;
  /** @internal Reports a settled native payload for post-terminal message_sent observation. */
  onMessageSentEvent?: (event: MessageSentEvent, sourceIndex: number) => void;
  /** @internal Persists ambiguous-send state immediately before platform I/O. */
  onPlatformSendStart?: (route: PlatformSendRoute, sourceIndex?: number) => Promise<void>;
  /** @internal Stable producer id used to make queue creation idempotent across crashes. */
  deliveryIntentId?: string;
  /** @internal Retain the completed receipt for a producer-owned replayable intent. */
  completionRetention?: DeliveryQueueCompletionRetention;
  /** @internal Producer-specific durable recovery attempt budget. */
  maxRetries?: number;
  /** @internal Marks an agent final; ordinary text may be resent once when its send is unconfirmed. */
  retryAmbiguousFinalText?: true;
  /** @internal Retry this producer's pending intent only when no platform send began. */
  reusePendingDeliveryIntent?: boolean;
  /** @internal Serializable owner state finalized after live or recovered delivery. */
  deliveryCompletion?: DurableDeliveryCompletion;
  /** @internal The caller resends proven-not-sent payloads itself, so recovery must not. */
  deliveryRetryOwner?: "caller";
  /** @internal Ephemeral route authority for a recovered attempt; never owns completion. */
  conversationDeliveryAttemptAuthority?: ConversationDeliveryAttemptAuthority;
  /** @internal Revalidates authority once per durable queue execution, before adapter fanout. */
  onDeliveryAttempt?: () => Promise<void>;
  /** @internal Caller preflight explicitly required provider unknown-send reconciliation. */
  requireUnknownSendReconciliation?: boolean;
  /** Session/agent context used for hooks and media local-root scoping. */
  session?: OutboundSessionContext;
  /** Known destination conversation route; `null` when the caller proved there is none. */
  transcriptRoute?: OutboundSessionRoute | null;
  /** @internal Another owner records this send's destination history. */
  skipDestinationHistory?: boolean;
  /** @internal Stable delivery identity, independent of provider reconciliation markers. */
  transcriptDeliveryId?: string;
  /** @internal State root captured for this delivery; history never follows a later ambient root. */
  transcriptStateDir?: string;
  /** Pins destination history to the caller's conversation when several share an address. */
  transcriptExpectedGeneration?: {
    sessionKey?: string;
  };
  /** Background producer recorded on destination history rows. */
  transcriptProvenance?: BackgroundSessionResultProvenance;
  /** Receives warnings when a confirmed send could not be added to history. */
  onTranscriptDiagnostic?: (message: string) => void;
  /** Revalidates the producer before destination history is written. */
  assertTranscriptCurrent?: () => void;
};
/**
 * @deprecated Direct outbound delivery is compatibility/runtime substrate.
 * New message lifecycle code should use `sendDurableMessageBatch` from
 * `src/channels/message/send.ts` or `deliverInboundReplyWithMessageSendContext`
 * from `src/channels/turn/durable-delivery.ts`. Keep direct use only for
 * outbound substrate, recovery, and compatibility paths.
 */
type DeliverOutboundPayloadsParams = DeliverOutboundPayloadsCoreParams & {
  replyToId?: string | null;
  replyToMode?: ReplyToMode;
  /** @internal Skip write-ahead queue (used by crash-recovery to avoid re-enqueueing). */
  skipQueue?: boolean;
  /** @internal Fence recovery ownership at the same provider boundary as live sends. */
  deliveryProducerClaimId?: string;
  deliveryQueueOwner?: QueuedDeliveryOwner;
  /** @internal Keep the exact live producer claim alive during platform preparation. */
  deliveryProducerLeaseRequired?: boolean;
  /** @internal Recovery already ran provider admission after its pending-row re-read. */
  deferredDeliveryAdmissionPassed?: true;
  /** @internal State directory that owns the existing recovery queue entry. */
  deliveryQueueStateDir?: string;
  /** @internal Let recovery run commit hooks after it has acked the recovered queue entry. */
  deferCommitHooks?: boolean;
  queuePolicy?: OutboundDeliveryQueuePolicy;
  renderedBatchPlan?: RenderedMessageBatchPlan;
  onDeliveryIntent?: (intent: OutboundDeliveryIntent) => void;
};
//#endregion
//#region src/auto-reply/reply/source-reply-delivery-mode.d.ts
type SourceReplyDeliveryModeContext = Pick<MsgContext, "ChatType" | "SessionKey" | "InboundEventKind" | "Provider" | "Surface" | "ExplicitDeliverRoute" | "CommandAuthorized" | "CommandBody" | "CommandSource" | "CommandTurn" | "BotUsername" | "WasMentioned" | "MentionSource" | "InputProvenance">;
//#endregion
//#region src/channels/reply-prefix.d.ts
type ModelSelectionContext = Parameters<NonNullable<GetReplyOptions["onModelSelected"]>>[0];
/**
 * Mutable response-prefix state shared between reply setup and model selection callbacks.
 */
type ReplyPrefixContextBundle = {
  prefixContext: ResponsePrefixContext;
  responsePrefix?: string;
  responsePrefixContextProvider: () => ResponsePrefixContext;
  onModelSelected: (ctx: ModelSelectionContext) => void;
};
type ReplyPrefixOptions = Pick<ReplyPrefixContextBundle, "responsePrefix" | "responsePrefixContextProvider" | "onModelSelected">;
declare function createReplyPrefixContext(params: {
  cfg: OpenClawConfig;
  agentId: string;
  channel?: string;
  accountId?: string;
}): ReplyPrefixContextBundle;
declare function createReplyPrefixOptions(params: Parameters<typeof createReplyPrefixContext>[0]): ReplyPrefixOptions;
//#endregion
//#region src/channels/message/reply-pipeline.d.ts
type ReplyPrefixContext = ReplyPrefixContextBundle["prefixContext"];
declare function resolveChannelSourceReplyDeliveryMode(params: {
  cfg: OpenClawConfig;
  ctx: SourceReplyDeliveryModeContext;
  requested?: SourceReplyDeliveryMode;
  messageToolAvailable?: boolean;
}): SourceReplyDeliveryMode;
type ChannelReplyPipeline = ReplyPrefixOptions & {
  /** Resolves a response prefix against the pipeline's live selected-model context. */
  resolveResponsePrefix?: () => string | undefined;
  typingCallbacks?: TypingCallbacks;
  transformReplyPayload?: (payload: ReplyPayload$1) => ReplyPayload$1 | null;
};
type CreateChannelReplyPipelineParams = {
  cfg: Parameters<typeof createReplyPrefixOptions>[0]["cfg"];
  agentId: string;
  channel?: string;
  accountId?: string;
  typing?: CreateTypingCallbacksParams;
  /** Prebuilt typing callbacks that take precedence over `typing`. */
  typingCallbacks?: TypingCallbacks;
  /** Explicit payload transform; avoids channel plugin lookup when provided. */
  transformReplyPayload?: (payload: ReplyPayload$1) => ReplyPayload$1 | null;
};
declare function createChannelReplyPipeline(params: CreateChannelReplyPipelineParams): ChannelReplyPipeline;
//#endregion
//#region src/plugin-sdk/pair-loop-guard-runtime.d.ts
/** User-facing pair-loop guard config accepted by channel plugins. */
type PairLoopGuardConfig = {
  /** Enables or disables loop protection for the channel/account scope. */
  enabled?: boolean;
  /** Number of pair events allowed before cooldown starts. */
  maxEventsPerWindow?: number;
  /** Rolling event window size in seconds for config files. */
  windowSeconds?: number;
  /** Suppression duration in seconds for config files. */
  cooldownSeconds?: number;
};
/** Result of recording one pair interaction against the loop guard. */
type PairLoopGuardResult = {
  suppressed: false;
} | {
  suppressed: true;
  cooldownUntilMs: number;
};
//#endregion
//#region src/channels/turn/bot-loop-protection.d.ts
type ChannelBotLoopProtectionFacts = {
  scopeId: string;
  conversationId: string;
  senderId: string;
  receiverId: string;
  eventId?: string;
  config?: PairLoopGuardConfig;
  defaultsConfig?: PairLoopGuardConfig;
  defaultEnabled: boolean;
  nowMs?: number;
};
declare function recordChannelBotPairLoopAndCheckSuppression(params: ChannelBotLoopProtectionFacts): PairLoopGuardResult;
//#endregion
//#region src/channels/turn/delivery-outcome.d.ts
/** Provider-visible delivery facts shared by channel turns and outbound entrypoints. */
type ChannelDeliveryOutcome = {
  messageIds?: string[];
  receipt?: MessageReceipt;
  threadId?: string;
  replyToId?: string;
  visibleReplySent?: boolean;
  /** Final provider-visible text used for this logical payload's terminal observation. */
  content?: string;
};
type ChannelDeliveryIntent = {
  id: string;
  kind: "outbound_queue";
  queuePolicy: OutboundDeliveryQueuePolicy;
};
type ChannelDeliveryResult = ChannelDeliveryOutcome & {
  deliveryIntent?: ChannelDeliveryIntent;
  /** Intentional no-send outcome after payload policy or modifying hooks settle. */
  suppression?: {
    reason: OutboundPayloadDeliverySuppressionReason | "channel_transform" | "no_visible_result";
    cancelReason?: string;
    metadata?: Record<string, unknown>;
  };
  /** Same-payload native settlement; resolved fields override this result before observation. */
  finalization?: Promise<ChannelDeliveryOutcome>;
};
//#endregion
//#region src/channels/turn/types.d.ts
type ChannelTurnAdmission = {
  kind: "dispatch";
  reason?: string;
} | {
  kind: "observeOnly";
  reason: string;
} | {
  kind: "handled";
  reason: string;
} | {
  kind: "drop";
  reason: string;
  recordHistory?: boolean;
};
type ChannelEventClass = {
  kind: "message" | "command" | "interaction" | "reaction" | "lifecycle" | "unknown";
  canStartAgentTurn: boolean;
  requiresImmediateAck?: boolean;
};
type NormalizedTurnInput = {
  id: string;
  timestamp?: number;
  rawText: string;
  textForAgent?: string;
  textForCommands?: string;
  raw?: unknown;
};
type SenderFacts = {
  id?: string;
  name?: string;
  username?: string;
  tag?: string;
  roles?: string[];
  isBot?: boolean;
  isSelf?: boolean;
  displayLabel?: string;
};
type ConversationFacts = {
  kind: ChatType;
  id: string;
  label?: string;
  spaceId?: string;
  parentId?: string;
  threadId?: string;
  nativeChannelId?: string;
  avatar?: string;
  routePeer?: {
    kind: ChatType;
    id: string;
  };
};
type RouteFacts = {
  agentId: string;
  dmScope?: DmScope;
  accountId?: string;
  routeSessionKey: string;
  dispatchSessionKey?: string;
  persistedSessionKey?: string;
  parentSessionKey?: string;
  modelParentSessionKey?: string;
  mainSessionKey?: string;
  createIfMissing?: boolean;
};
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";
};
type MessageFacts = {
  inboundEventKind?: InboundEventKind;
  body?: string;
  rawBody: string;
  bodyForAgent?: string;
  commandBody?: string;
  envelopeFrom?: string;
  senderLabel?: string;
  preview?: string;
  inboundHistory?: HistoryEntry[];
  sourceModality?: InboundSourceModality;
};
type CommandFacts = {
  kind: CommandTurnKind;
  body?: string;
  name?: string;
  authorized?: boolean;
};
type InboundMediaFacts = Omit<MediaFact, "staged" | "workspaceDir">;
type MaybePromise$3<T> = T | Promise<T>;
type PreflightFacts = {
  admission?: ChannelTurnAdmission;
  command?: CommandFacts;
  message?: Partial<MessageFacts>;
  media?: readonly InboundMediaFacts[] | (() => MaybePromise$3<readonly InboundMediaFacts[] | readonly HistoryMediaEntry[] | null | undefined>);
  supplemental?: SupplementalContextFacts;
  history?: ChannelTurnDroppedHistoryOptions;
};
type ChannelDeliveryInfo = ReplyDispatchRuntimeInfo;
type ChannelCoreManagedDeliveryInfo = Omit<ChannelDeliveryInfo, "assertPlatformSendAuthorized" | "bindPendingFinalDelivery" | "onPlatformSendDispatch">;
type ChannelProviderOwnedDeliveryInfo = ChannelDeliveryInfo & {
  assertPlatformSendAuthorized: () => void;
  onPlatformSendDispatch: () => Promise<void>;
};
type ChannelTurnDurableDeliveryOptions = Pick<DeliverOutboundPayloadsParams, "deps" | "formatting" | "identity" | "mediaAccess" | "replyToMode" | "silent" | "threadId"> & {
  /** Validate the admitted sender or restore its account view from current Gateway config. */
  prepareRuntimeHandoff?: (cfg: OpenClawConfig) => OpenClawConfig;
  to?: string | null;
  replyToId?: string | null;
  requiredCapabilities?: DurableFinalDeliveryRequirements;
  /**
   * @deprecated Ignored. Core marks every durable final itself; an ordinary final text is
   * resent once after an unconfirmed send on every channel that cannot reconcile it.
   */
  retryAmbiguousFinalText?: true;
};
type ChannelDeliveryAdapterBase = {
  /** Return null when channel policy intentionally suppresses this logical payload. */
  preparePayload?: (payload: ReplyPayload$1, info: ChannelDeliveryInfo) => MaybePromise$3<ReplyPayload$1 | null>;
  onDelivered?: (payload: ReplyPayload$1, info: ChannelDeliveryInfo, result: ChannelDeliveryResult | void) => Promise<void> | void;
  /** Let core emit the one canonical `message_sent` after non-durable provider settlement. */
  observeMessageSent?: true;
  onError?: (err: unknown, info: {
    kind: string;
  }) => void;
};
type ChannelCoreManagedTurnDeliveryAdapter = ChannelDeliveryAdapterBase & {
  deliver: (payload: ReplyPayload$1, info: ChannelCoreManagedDeliveryInfo) => Promise<ChannelDeliveryResult | void>;
  /** Receives an explicitly prepared plan without interpreting its text as directives. */
  deliverPrepared?: (plan: OutboundPayloadPlan, info: ChannelCoreManagedDeliveryInfo) => Promise<ChannelDeliveryResult | void>;
  durable?: false | ChannelTurnDurableDeliveryOptions | ((payload: ReplyPayload$1, info: ChannelDeliveryInfo) => false | ChannelTurnDurableDeliveryOptions | Promise<false | ChannelTurnDurableDeliveryOptions>);
};
/** Delivery adapter used by legacy caller-assembled channel turns. */
type ChannelEventDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter;
type ChannelProviderOwnedMessageSendingDeliveryAdapter = ChannelDeliveryAdapterBase & {
  /**
   * Provider funnel that owns `message_sending` after its native payload preparation.
   * Use only when delivery cannot declare its durable/direct branch before entering the
   * provider funnel; core still owns `reply_payload_sending` for this routed turn.
   */
  deliverWithProviderMessageSending: (payload: ReplyPayload$1, info: ChannelProviderOwnedDeliveryInfo) => Promise<ChannelDeliveryResult | void>;
  deliverPreparedWithProviderMessageSending?: (plan: OutboundPayloadPlan, info: ChannelProviderOwnedDeliveryInfo) => Promise<ChannelDeliveryResult | void>;
  deliver?: never;
  deliverPrepared?: never;
  durable?: never;
};
/** Delivery adapter used by modern routed channel turns. */
type ChannelTurnDeliveryAdapter = (ChannelCoreManagedTurnDeliveryAdapter & {
  deliverWithProviderMessageSending?: never;
  deliverPreparedWithProviderMessageSending?: never;
}) | ChannelProviderOwnedMessageSendingDeliveryAdapter;
type ChannelTurnRecordOptions = {
  /**
   * Override the session used for metadata and transcript context.
   * Must be non-empty and contain no surrounding whitespace.
   */
  sessionKey?: string;
  groupResolution?: GroupKeyResolution | null;
  createIfMissing?: boolean;
  updateLastRoute?: InboundLastRouteUpdate;
  onRecordError?: (err: unknown) => void;
  trackSessionMetaTask?: (task: Promise<unknown>) => void;
};
type ChannelTurnHistoryFinalizeOptions = {
  isGroup?: boolean;
  historyKey?: string;
  historyMap?: Map<string, HistoryEntry[]>;
  limit?: number;
};
type ChannelTurnDroppedHistoryOptions = {
  key: string;
  limit: number;
  historyMap: Map<string, HistoryEntry[]>;
  recordOnDrop?: boolean;
  mediaLimit?: number;
  shouldRecord?: () => boolean;
};
type ChannelTurnContext = {
  channel: string;
  accountId?: string;
  routeSessionKey: string;
  storePath: string;
  ctxPayload: FinalizedMsgContext;
  recordInboundSession: RecordInboundSession$1;
  /** Current channel authority at record and dispatch initiation, after awaited preparation. */
  assertAuthority?: () => void;
  afterRecord?: () => void | Promise<void>;
  record?: ChannelTurnRecordOptions;
  history?: ChannelTurnHistoryFinalizeOptions;
  admission?: Extract<ChannelTurnAdmission, {
    kind: "dispatch" | "observeOnly";
  }>;
  botLoopProtection?: ChannelBotLoopProtectionFacts;
  /** Transport-defined outbound source identity, such as a webhook id. */
  outboundEchoSourceId?: string;
  log?: (event: ChannelTurnLogEvent) => void;
  messageId?: string;
};
type AssembledChannelTurn = ChannelTurnContext & {
  cfg: OpenClawConfig;
  agentId: string;
  dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher$2;
  delivery: ChannelEventDeliveryAdapter;
  replyPipeline?: Omit<CreateChannelReplyPipelineParams, "cfg" | "agentId" | "channel" | "accountId">;
  dispatcherOptions?: Omit<ReplyDispatcherWithTypingOptions, "deliver" | "deliverPrepared" | "onError">;
  toolsAllow?: string[];
  /** Reply options plus the opaque native command ownership decision carried by channel turns. */
  replyOptions?: Omit<GetReplyOptions, "onBlockReply" | "onPreparedBlockReply"> & PluginCommandReplyOptions;
  replyResolver?: GetReplyFromConfig;
  /** Instance-bound reply dispatcher supplied by the owning plugin runtime. */
  dispatchReplyFromConfig?: DispatchReplyFromConfig$1;
  sessionInitRetry?: {
    delaysMs: readonly number[];
    signal?: AbortSignal;
    sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
  };
  /** Canonical adoption lifecycle threaded into replyOptions. */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
};
type PreparedChannelTurnDispatchLifecycle = {
  /** Exact adoption lifecycle captured by runDispatch, or undefined for non-durable turns. */
  turnAdoptionLifecycle: TurnAdoptionLifecycle | undefined;
  /** Releases resources that runDispatch would otherwise settle when dispatch is skipped. */
  onDispatchSkipped: (reason: "botLoopProtection" | "observeOnly" | "outboundEcho") => void | Promise<void>;
};
type PreparedChannelTurn<TDispatchResult = DispatchFromConfigResult> = ChannelTurnContext & {
  onPreDispatchFailure?: (err: unknown) => void | Promise<void>;
  runDispatch: () => Promise<TDispatchResult>;
  /** Optional for the legacy direct prepared runner; inbound adapters use the stricter type. */
  runDispatchLifecycle?: PreparedChannelTurnDispatchLifecycle;
  observeOnlyDispatchResult?: TDispatchResult;
};
type RoutedChannelTurn<T> = Omit<T, "routeSessionKey" | "storePath" | "recordInboundSession"> & {
  route: {
    agentId: string;
    dmScope?: DmScope;
    sessionKey: string;
  };
};
type InboundPreparedChannelTurn<TDispatchResult = DispatchFromConfigResult> = PreparedChannelTurn<TDispatchResult> & {
  runDispatchLifecycle: PreparedChannelTurnDispatchLifecycle;
};
type ChannelTurnPlan<TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = RoutedChannelTurn<Omit<AssembledChannelTurn, "agentId" | "delivery" | "dispatchReplyWithBufferedBlockDispatcher"> & {
  delivery: TDelivery;
}>;
type ChannelTurnResolved<TDispatchResult = DispatchFromConfigResult, TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = ChannelTurnPlan<TDelivery> | (RoutedChannelTurn<InboundPreparedChannelTurn<TDispatchResult>> & {
  cfg: OpenClawConfig;
}) | AssembledChannelTurn | InboundPreparedChannelTurn<TDispatchResult>;
type ChannelTurnLogEvent = {
  stage: "ingest" | "classify" | "preflight" | "resolve" | "authorize" | "assemble" | "record" | "dispatch" | "finalize";
  event: "start" | "done" | "drop" | "handled" | "error" | "warning";
  channel: string;
  accountId?: string;
  messageId?: string;
  sessionKey?: string;
  admission?: ChannelTurnAdmission["kind"];
  reason?: string;
  error?: unknown;
};
type ChannelTurnResult<TDispatchResult = DispatchFromConfigResult> = DispatchedChannelTurnResult<TDispatchResult> | {
  admission: ChannelTurnAdmission;
  dispatched: false;
  ctxPayload?: MsgContext;
  routeSessionKey?: string;
};
type DispatchedChannelTurnResult<TDispatchResult = DispatchFromConfigResult> = {
  admission: Extract<ChannelTurnAdmission, {
    kind: "dispatch" | "observeOnly";
  }>;
  dispatched: true;
  ctxPayload: MsgContext;
  routeSessionKey: string;
  dispatchResult: TDispatchResult;
};
type RunChannelTurnParams<TRaw, TDispatchResult = DispatchFromConfigResult, TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = {
  channel: string;
  accountId?: string;
  raw: TRaw;
  adapter: {
    ingest: (raw: TRaw) => MaybePromise$3<NormalizedTurnInput | null>;
    classify?: (input: NormalizedTurnInput) => MaybePromise$3<ChannelEventClass>;
    preflight?: (input: NormalizedTurnInput, eventClass: ChannelEventClass) => MaybePromise$3<PreflightFacts | ChannelTurnAdmission | null | undefined>;
    resolveTurn: (input: NormalizedTurnInput, eventClass: ChannelEventClass, preflight: PreflightFacts) => MaybePromise$3<ChannelTurnResolved<TDispatchResult, TDelivery>>;
    onFinalize?: (result: ChannelTurnResult<TDispatchResult>) => Promise<void> | void;
  };
  log?: (event: ChannelTurnLogEvent) => void;
  /** Canonical adoption lifecycle for this turn. */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
};
//#endregion
//#region src/channels/inbound-event/context.d.ts
type MaybePromise$2<T> = T | Promise<T>;
type ChannelInboundSupplementalMediaResolver = () => MaybePromise$2<readonly InboundMediaFacts[] | null | undefined>;
type ChannelInboundSupplementalQuoteFacts = NonNullable<SupplementalContextFacts["quote"]> & {
  isSelf?: boolean;
  media?: readonly InboundMediaFacts[] | ChannelInboundSupplementalMediaResolver;
};
type ChannelInboundSupplementalFacts = Omit<SupplementalContextFacts, "quote"> & {
  quote?: ChannelInboundSupplementalQuoteFacts;
};
/**
 * @deprecated Prefer passing `resolveSupplementalMedia: true` directly to
 * `buildChannelInboundEventContext` without naming this compatibility type.
 */
type ChannelInboundSupplementalResolutionOptions = {
  resolveSupplementalMedia: true;
  suppressSelfQuoteBody?: boolean;
  suppressSelfQuoteMedia?: boolean;
};
type BuildChannelInboundEventAccess = {
  commands?: Pick<ChannelIngressCommandAccess, "authorized">;
  /** @deprecated Resolve policy through security.resolveDirectToolPolicy or groups.resolveToolPolicy. Retained for the original external request until a later stable release after an announced deprecation window and explicit maintainer approval; no removal date is set. */
  toolPolicy?: GroupToolPolicyConfig;
  mentions?: {
    canDetectMention: boolean;
    wasMentioned: boolean;
    hasAnyMention?: boolean;
    explicitlyMentionedBot?: boolean;
    mentionedUserIds?: string[];
    mentionedSubteamIds?: string[];
    mentionSource?: MentionSource;
    implicitMentionKinds?: readonly InboundImplicitMentionKind[];
    requireMention?: boolean;
    effectiveWasMentioned?: boolean;
  };
};
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;
  sessionTranscript?: SessionTranscriptContext;
  access?: BuildChannelInboundEventAccess;
  command?: CommandFacts;
  commandTurn?: CommandTurnContext;
  media?: InboundMediaFacts[];
  supplemental?: ChannelInboundSupplementalFacts;
  channelContext?: PluginHookChannelContext;
  contextVisibility?: ContextVisibilityMode;
  finalize?: FinalizeInboundContextFn;
  finalizeOptions?: FinalizeInboundContextOptions;
  extra?: Record<string, unknown>;
  /** Exact host-resolved ingress result, or an explicit unsupported adapter marker. */
  channelIngress?: ResolvedChannelMessageIngress | readonly ResolvedChannelMessageIngress[] | "unsupported";
};
/**
 * @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<string, unknown>, opts?: FinalizeInboundContextOptions) => unknown;
/**
 * @deprecated Used by deprecated `finalizeChannelInboundContext`; new channel
 * code should pass facts to `buildChannelInboundEventContext`.
 */
type FinalizeChannelInboundContextParams<T extends Record<string, unknown>> = {
  context: T;
  supplemental?: SupplementalContextFacts | ChannelInboundSupplementalFacts;
  contextVisibility?: ContextVisibilityMode;
  media?: readonly InboundMediaFacts[];
  finalize?: FinalizeInboundContextFn;
  finalizeOptions?: FinalizeInboundContextOptions;
};
/**
 * @deprecated Prefer `FinalizeChannelInboundContextParams<T>` with
 * `resolveSupplementalMedia: true` when lazy quote media must be resolved.
 */
type FinalizeChannelInboundContextAsyncParams<T extends Record<string, unknown>> = FinalizeChannelInboundContextParams<T> & {
  resolveSupplementalMedia: true;
} & Pick<ChannelInboundSupplementalResolutionOptions, "suppressSelfQuoteBody" | "suppressSelfQuoteMedia">;
/**
 * @deprecated Result type for deprecated `finalizeChannelInboundContext`.
 */
type FinalizeChannelInboundContextResult<T extends Record<string, unknown>> = {
  context: T & FinalizedMsgContext;
  supplemental?: SupplementalContextFacts;
  quoteHidden: boolean;
  forwardedHidden: boolean;
  threadHidden: boolean;
};
declare function filterChannelInboundSupplementalContext(params: {
  supplemental?: SupplementalContextFacts;
  contextVisibility?: ContextVisibilityMode;
}): SupplementalContextFacts | undefined;
/** Resolves whether a supplemental-context sender passes the active group policy. */
declare function resolveInboundSupplementalSenderAllowed<TAllowFrom>(params: {
  isGroup: boolean;
  groupPolicy: string;
  allowFrom: readonly TAllowFrom[];
  isSenderAllowed: (allowFrom: readonly TAllowFrom[]) => boolean;
}): boolean;
declare function filterChannelInboundQuoteContext(contextVisibility: ContextVisibilityMode | undefined, quote: SupplementalContextFacts["quote"] | undefined): SupplementalContextFacts["quote"] | undefined;
/**
 * @deprecated Public compatibility for callers that already prepared legacy
 * prompt fields. New channel code should use `buildChannelInboundEventContext`.
 */
declare function finalizeChannelInboundContext<T extends Record<string, unknown>>(params: FinalizeChannelInboundContextAsyncParams<T>): Promise<FinalizeChannelInboundContextResult<T>>;
declare function finalizeChannelInboundContext<T extends Record<string, unknown>>(params: FinalizeChannelInboundContextParams<T>): FinalizeChannelInboundContextResult<T>;
declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextAsyncParams): Promise<BuiltChannelInboundEventContext>;
declare function buildChannelInboundEventContext(params: BuildChannelInboundEventContextParams): BuiltChannelInboundEventContext;
//#endregion
//#region src/channels/turn/run-channel-turn.d.ts
declare function recordDroppedChannelTurnHistory(params: {
  input: NormalizedTurnInput;
  preflight: PreflightFacts;
  admission?: ChannelTurnAdmission;
}): Promise<void>;
//#endregion
//#region src/plugin-sdk/reply-options.d.ts
type PublicReplyOptions<T> = T extends undefined ? undefined : Omit<T, "replyExpectation" | "internalEventExecution" | "onReplyOperationAdmitted" | "onReplyOperationOwned" | "assertChannelAuthority">;
type PublicReplyFunction<T> = T extends ((params: infer P) => infer R) ? (params: PublicReplyParams<P>) => R : T;
type PublicReplyResolver<T> = T extends ((ctx: infer C, options?: infer O, config?: infer F) => infer R) ? (ctx: C, options?: PublicReplyOptions<O>, config?: F) => R : T;
type PublicReplyParams<T> = { [K in keyof T]: K extends "replyOptions" ? PublicReplyOptions<T[K]> : K extends "replyResolver" ? PublicReplyResolver<T[K]> : K extends "dispatchReplyFromConfig" | "dispatchReplyWithBufferedBlockDispatcher" ? PublicReplyFunction<T[K]> : T[K]; };
type PublicChannelTurnParams<TRaw, TResult, TDelivery extends ChannelTurnDeliveryAdapter> = Omit<RunChannelTurnParams<TRaw, TResult, TDelivery>, "adapter"> & {
  adapter: Omit<RunChannelTurnParams<TRaw, TResult, TDelivery>["adapter"], "resolveTurn"> & {
    resolveTurn: (...args: Parameters<RunChannelTurnParams<TRaw, TResult, TDelivery>["adapter"]["resolveTurn"]>) => PublicReplyParams<ChannelTurnResolved<TResult, TDelivery>> | Promise<PublicReplyParams<ChannelTurnResolved<TResult, TDelivery>>>;
  };
};
//#endregion
//#region src/channels/turn/dispatch-result.d.ts
type ChannelTurnDispatchResultLike = {
  queuedFinal?: boolean;
  counts?: Partial<Record<ReplyDispatchKind, number>>;
  settledReceipt?: {
    anyVisibleDelivered: boolean;
    counts: Partial<Record<ReplyDispatchKind, {
      delivered: number;
      failedAfterSend: number;
    }>>;
  };
  observedReplyDelivery?: boolean;
  deferredToActiveRun?: "steer" | "followup";
} | null | undefined;
/** Extra delivery signals observed outside the normal dispatch count payload. */
type ChannelTurnVisibleDeliverySignals = {
  observedReplyDelivery?: boolean;
  fallbackDelivered?: boolean;
  deliverySummaryDelivered?: boolean;
};
type FinalDeliverySignals = Pick<ChannelTurnVisibleDeliverySignals, "fallbackDelivered" | "deliverySummaryDelivered">;
declare function resolveChannelTurnDispatchCounts(result: ChannelTurnDispatchResultLike): {
  tool: number;
  block: number;
  final: number;
};
declare function hasVisibleChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: ChannelTurnVisibleDeliverySignals): boolean;
declare function hasFinalChannelTurnDispatch(result: ChannelTurnDispatchResultLike, signals?: FinalDeliverySignals): boolean;
//#endregion
//#region src/auto-reply/group-thread-context.d.ts
type GroupThreadParticipant = {
  agentId: string;
  name: string;
};
type GroupThreadTurn = GroupThreadParticipant & {
  round: number;
  messageId: string;
  digest?: string;
};
/** Data-only delivery identity, including unlabeled single-participant groups. */
declare function getGroupThreadDeliverySession(): {
  agentId: string;
  sessionKey: string;
} | undefined;
//#endregion
//#region src/auto-reply/group-thread.d.ts
/** One owner reserves participant turns before launch; transports retain delivery ownership. */
declare function runGroupThread<T>(params: {
  cfg: OpenClawConfig;
  group: ResolvedGroupThreadConfig;
  channel: string;
  accountId?: string;
  peerId: string;
  threadId?: string | number;
  messageId?: string;
  text: string;
  mentionedAgentIds?: string[];
  abortSignal?: AbortSignal;
  formatReply?: (text: string, participant: GroupThreadParticipant) => string;
  runTurn: (turn: GroupThreadTurn) => Promise<T>;
  onError?: (error: unknown, turn: GroupThreadTurn) => void;
}): Promise<{
  results: T[];
  turnsStarted: number;
  failedTurns: number;
}>;
//#endregion
//#region src/auto-reply/group-thread-config.d.ts
declare function resolveGroupThreadConfig(params: {
  cfg: OpenClawConfig;
  channel: string;
  peerId: string;
}): ResolvedGroupThreadConfig | undefined;
declare function isGroupThreadRouteExclusive(params: {
  sessionKey?: string;
  acpBinding?: boolean;
}): boolean;
declare function resolveGroupThreadMentionFacts(params: {
  cfg: OpenClawConfig;
  channel: string;
  peerId: string;
  text: string;
  sessionKey?: string;
  acpBinding?: boolean;
}): GroupThreadMentionFacts | undefined;
//#endregion
//#region src/channels/turn/agent-run-terminal-outcome.d.ts
type AgentRunTerminalOutcome = "completed" | "failed";
declare function readAgentRunTerminalOutcome(result: unknown): AgentRunTerminalOutcome | undefined;
//#endregion
//#region src/plugin-sdk/access-groups.d.ts
/** Resolves membership for an access group using the full OpenClaw config. */
type AccessGroupMembershipResolver = (params: {
  /** Full config, available when membership needs cross-channel or provider state. */
  cfg: OpenClawConfig;
  /** Access group name referenced by `accessGroup:<name>`. */
  name: string;
  /** Access group config selected by name. */
  group: AccessGroupConfig;
  /** Channel where the inbound sender is being checked. */
  channel: ChannelId$1;
  /** Channel account id for account-scoped membership checks. */
  accountId: string;
  /** Inbound sender id or handle being authorized. */
  senderId: string;
}) => boolean | Promise<boolean>;
type AccessGroupAllowFromParams<TMembership> = {
  /** Raw allowlist entries that may include `accessGroup:<name>` references. */
  allowFrom: Array<string | number> | null | undefined;
  /** Channel where the inbound sender is being checked. */
  channel: ChannelId$1;
  /** Channel account id for account-scoped membership checks. */
  accountId: string;
  /** Inbound sender id or handle being authorized. */
  senderId: string;
  /** Static sender matcher used for `message.senders` groups. */
  isSenderAllowed?: (senderId: string, allowFrom: string[]) => boolean;
  /** Optional resolver for non-static or integration-backed group types. */
  resolveMembership?: TMembership;
};
/** Returns the matched `accessGroup:<name>` allowlist entries for a sender. */
declare function resolveAccessGroupAllowFromMatches(params: AccessGroupAllowFromParams<AccessGroupMembershipResolver> & {
  /** Full config containing `accessGroups`. */
  cfg?: OpenClawConfig;
}): Promise<string[]>;
/** Expands a matching access-group allowlist with the concrete sender entry. */
declare function expandAllowFromWithAccessGroups(params: Parameters<typeof resolveAccessGroupAllowFromMatches>[0] & {
  /** Concrete allowlist entry appended after a group match; defaults to `senderId`. */
  senderAllowEntry?: string;
}): Promise<string[]>;
//#endregion
//#region src/channels/command-gating.d.ts
/**
 * Shared text-control command authorization policy for channel runtimes.
 *
 * These helpers are re-exported through the plugin SDK so built-in and external
 * channels make the same access-groups decisions for native command text.
 */
/** One channel-specific authorization source for text control commands. */
type CommandAuthorizer = {
  /** True when this channel/user identity has an access-group rule configured. */
  configured: boolean;
  /** True when the configured rule permits the command. Ignored when unconfigured. */
  allowed: boolean;
};
/** Fallback policy for channels that have access groups globally disabled. */
type CommandGatingModeWhenAccessGroupsOff = "allow" | "deny" | "configured";
/** Resolves whether any configured authorizer permits a control command. */
declare function resolveCommandAuthorizedFromAuthorizers(params: {
  /** Global access-group switch for the channel/runtime. */
  useAccessGroups: boolean;
  /** Independent authorization sources, such as sender id and actor id. */
  authorizers: CommandAuthorizer[];
  /** Policy used only when `useAccessGroups` is false. Defaults to open. */
  modeWhenAccessGroupsOff?: CommandGatingModeWhenAccessGroupsOff;
}): boolean;
/** Resolves command authorization and whether the current text command should be blocked. */
declare function resolveControlCommandGate(params: Parameters<typeof resolveCommandAuthorizedFromAuthorizers>[0] & {
  /** Channel setting that enables text commands as an input surface. */
  allowTextCommands: boolean;
  /** True when the current inbound message parsed as a control command. */
  hasControlCommand: boolean;
}): {
  commandAuthorized: boolean;
  shouldBlock: boolean;
};
//#endregion
//#region src/channels/direct-dm-access.d.ts
/** Runtime hooks needed by the legacy direct-DM access resolver. */
type DirectDmCommandAuthorizationRuntime = {
  shouldComputeCommandAuthorized: (rawBody: string, cfg: OpenClawConfig) => boolean;
  /** @deprecated Command authorization is resolved by channel ingress. Kept for runtime injection compatibility. */
  resolveCommandAuthorizedFromAuthorizers?: typeof resolveCommandAuthorizedFromAuthorizers;
};
/**
 * Legacy direct-DM ingress decision with command-authorization compatibility fields.
 * @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
 */
type ResolvedInboundDirectDmAccess = {
  access: {
    decision: "allow" | "block" | "pairing";
    reasonCode: DmGroupAccessReasonCode;
    reason: string;
    effectiveAllowFrom: string[];
  };
  shouldComputeAuth: boolean;
  senderAllowedForCommands: boolean;
  commandAuthorized: boolean | undefined;
};
/**
 * Resolves legacy direct-DM access lists, pairing-store entries, and command authorization.
 * @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
 */
declare function resolveInboundDirectDmAccessWithRuntime(params: {
  cfg: OpenClawConfig;
  channel: ChannelId$1;
  accountId: string;
  dmPolicy?: string | null;
  allowFrom?: Array<string | number> | null;
  senderId: string;
  rawBody: string;
  isSenderAllowed: (senderId: string, allowFrom: string[]) => boolean;
  resolveAccessGroupMembership?: AccessGroupMembershipResolver;
  runtime: DirectDmCommandAuthorizationRuntime;
  modeWhenAccessGroupsOff?: "allow" | "deny" | "configured";
  readStoreAllowFrom?: (provider: ChannelId$1, accountId: string) => Promise<string[]>;
}): Promise<ResolvedInboundDirectDmAccess>;
/**
 * Creates a pre-crypto authorizer that can issue pairing challenges before payload decryption.
 * @deprecated Use `resolveChannelMessageIngress` from `openclaw/plugin-sdk/channel-ingress-runtime`.
 */
declare function createPreCryptoDirectDmAuthorizer(params: {
  resolveAccess: (senderId: string) => Promise<Pick<ResolvedInboundDirectDmAccess, "access"> | ResolvedInboundDirectDmAccess>;
  issuePairingChallenge?: (params: {
    senderId: string;
    reply: (text: string) => Promise<void>;
  }) => Promise<void>;
  onBlocked?: (params: {
    senderId: string;
    reason: string;
    reasonCode: DmGroupAccessReasonCode;
  }) => void;
}): (input: {
  senderId: string;
  reply: (text: string) => Promise<void>;
}) => Promise<"allow" | "block" | "pairing">;
//#endregion
//#region src/channels/direct-dm-guard-policy.d.ts
/** Runtime limits applied before direct-DM encrypted payloads are decrypted. */
type DirectDmPreCryptoGuardPolicy = {
  /** Accepted encrypted event kinds before decryption, e.g. Nostr kind 4. */
  allowedKinds: readonly number[];
  /** Maximum sender timestamp skew allowed into the future. */
  maxFutureSkewSec: number;
  /** Maximum encrypted payload bytes accepted before decrypt work starts. */
  maxCiphertextBytes: number;
  /** Maximum decrypted plaintext bytes accepted after decrypt succeeds. */
  maxPlaintextBytes: number;
  /** Per-sender and global throttles for encrypted DM ingress. */
  rateLimit: {
    /** Fixed rate-limit window size. */
    windowMs: number;
    /** Maximum messages per sender key inside one window. */
    maxPerSenderPerWindow: number;
    /** Maximum messages across all sender keys inside one window. */
    maxGlobalPerWindow: number;
    /** Maximum sender keys retained by the in-memory limiter. */
    maxTrackedSenderKeys: number;
  };
};
/** Partial overrides for channel plugins that need stricter pre-crypto limits. */
type DirectDmPreCryptoGuardPolicyOverrides = Partial<Omit<DirectDmPreCryptoGuardPolicy, "rateLimit">> & {
  rateLimit?: Partial<DirectDmPreCryptoGuardPolicy["rateLimit"]>;
};
/** Builds the shared policy object for DM-style pre-crypto guardrails. */
declare function createDirectDmPreCryptoGuardPolicy(overrides?: DirectDmPreCryptoGuardPolicyOverrides): DirectDmPreCryptoGuardPolicy;
//#endregion
//#region src/channels/direct-dm.d.ts
type DirectDmRoutePeer = {
  kind: "direct";
  id: string;
};
type DirectDmRoute = {
  agentId: string;
  sessionKey: string;
  accountId?: string;
};
type DispatchInboundDirectDmParams = {
  cfg: OpenClawConfig;
  channel: string;
  channelLabel: string;
  accountId: string;
  peer: DirectDmRoutePeer;
  senderId: string;
  senderAddress: string;
  recipientAddress: string;
  conversationLabel: string;
  rawBody: string;
  messageId: string;
  timestamp?: number;
  commandAuthorized?: boolean;
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
  /** Shipped SDK callers may omit provenance; bundled callers must classify it explicitly. */
  channelIngress?: ResolvedChannelMessageIngress | "unsupported";
  /** Resolve the exact admitted result after this helper owns the final route. */
  resolveChannelIngress?: (contextBinding: ChannelIngressContextBinding) => Promise<ResolvedChannelMessageIngress>;
  /** Opaque record-scoped runtime injected by a registered native channel. */
  channelRuntime?: {
    inbound?: {
      buildContext?: unknown;
    };
  };
  /** Set only after the channel's sender/pairing guard admits this event. */
  inboundAccessAuthorized?: boolean;
  /** Recheck channel-owned live authority after preparation and at effect initiation. */
  assertAuthority?: () => void;
  bodyForAgent?: string;
  commandBody?: string;
  provider?: string;
  surface?: string;
  originatingChannel?: string;
  originatingTo?: string;
  extraContext?: Record<string, unknown>;
  deliver: (payload: OutboundReplyPayload) => Promise<void>;
  onRecordError: (err: unknown) => void;
  onDispatchError: (err: unknown, info: {
    kind: string;
  }) => void;
};
declare function dispatchInboundDirectDm(params: DispatchInboundDirectDmParams): Promise<{
  route: DirectDmRoute;
  ctxPayload: FinalizedMsgContext;
}>;
/** @deprecated Use dispatchInboundDirectDm. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function dispatchInboundDirectDmWithRuntime(params: Omit<DispatchInboundDirectDmParams, "resolveChannelIngress"> & {
  runtime: PluginRuntime;
}): Promise<{
  route: DirectDmRoute;
  storePath: string;
  ctxPayload: FinalizedMsgContext;
}>;
//#endregion
//#region src/channels/mention-pattern-policy.d.ts
type ResolveMentionPatternPolicyParams = {
  cfg?: OpenClawConfig;
  provider?: string;
  conversationId?: string | null;
  providerPolicy?: MentionPatternsPolicyConfig;
  agentId?: string;
};
type ResolvedMentionPatternPolicy = {
  effectiveMode: MentionPatternsMode;
  allowMatched: boolean;
  denyMatched: boolean;
  enabled: boolean;
};
declare function resolveMentionPatternPolicy(params: ResolveMentionPatternPolicyParams): ResolvedMentionPatternPolicy;
//#endregion
//#region src/auto-reply/reply/mentions.types.d.ts
/** Options for building mention regexes without binding config/agent id. */
type BuildMentionRegexesOptions = Omit<ResolveMentionPatternPolicyParams, "cfg" | "agentId">;
/** Builds mention regexes for the current config and agent. */
type BuildMentionRegexes = (cfg: OpenClawConfig | undefined, agentId?: string, options?: BuildMentionRegexesOptions) => RegExp[];
/** Tests plain text against mention regexes. */
type MatchesMentionPatterns = (text: string, mentionRegexes: RegExp[]) => boolean;
/** Explicit mention metadata supplied by channel adapters. */
type ExplicitMentionSignal = {
  hasAnyMention: boolean;
  isExplicitlyMentioned: boolean;
  canResolveExplicit: boolean;
};
/** Tests mention state using regexes plus explicit channel mention metadata. */
type MatchesMentionWithExplicit = (params: {
  text: string;
  mentionRegexes: RegExp[];
  explicit?: ExplicitMentionSignal;
  transcript?: string;
}) => boolean;
//#endregion
//#region src/auto-reply/reply/mentions.d.ts
declare function buildMentionRegexes(cfg: OpenClawConfig | undefined, agentId?: string, options?: BuildMentionRegexesOptions): RegExp[];
declare function normalizeMentionText(text: string): string;
declare function matchesMentionPatterns(text: string, mentionRegexes: RegExp[]): boolean;
declare function matchesMentionWithExplicit(params: {
  text: string;
  mentionRegexes: RegExp[];
  explicit?: ExplicitMentionSignal;
  transcript?: string;
}): boolean;
//#endregion
//#region src/channels/inbound-debounce-policy.d.ts
declare function shouldDebounceTextInbound(params: {
  text: string | null | undefined;
  cfg: OpenClawConfig;
  hasMedia?: boolean;
  commandOptions?: CommandNormalizeOptions;
  allowDebounce?: boolean;
}): boolean;
/** Snapshot timing by default; resolveDebounceMs opts into per-entry timing. */
declare function createChannelInboundDebouncer<T>(params: Omit<InboundDebounceCreateParams<T>, "debounceMs"> & {
  cfg: OpenClawConfig;
  channel: string;
  debounceMsOverride?: number;
}): {
  debounceMs: number;
  debouncer: ReturnType<typeof createInboundDebouncer<T>>;
};
//#endregion
//#region src/channels/session-envelope.d.ts
/** @deprecated Await resolveInboundSessionEnvelopeContextAsync. Retained during stable deprecation. */
declare function resolveInboundSessionEnvelopeContext(params: {
  cfg: OpenClawConfig;
  agentId: string;
  sessionKey: string;
}): {
  storePath: string;
  envelopeOptions: EnvelopeFormatOptions;
  previousTimestamp: number | undefined;
};
/** Prepares descriptive session facts before building an inbound envelope. */
declare function resolveInboundSessionEnvelopeContextAsync(params: Parameters<typeof resolveInboundSessionEnvelopeContext>[0]): Promise<{
  storePath: string;
  envelopeOptions: EnvelopeFormatOptions;
  previousTimestamp: number | undefined;
}>;
//#endregion
//#region src/channels/inbound-event/classification.d.ts
type ClassifyChannelInboundEventParams = {
  conversation: Pick<ConversationFacts, "kind">;
  unmentionedGroupPolicy?: InboundEventKind;
  wasMentioned?: boolean;
  hasControlCommand?: boolean;
  hasAbortRequest?: boolean;
  commandSource?: "native" | "text";
};
declare function classifyChannelInboundEvent(params: ClassifyChannelInboundEventParams): InboundEventKind;
declare function resolveUnmentionedGroupInboundPolicy(params: {
  cfg: OpenClawConfig;
  agentId?: string;
}): InboundEventKind;
//#endregion
//#region src/channels/feedback-reflection.d.ts
declare const DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS = 300000;
declare function recordChannelFeedbackEvent(params: {
  cfg: OpenClawConfig;
  agentId: string;
  sessionKey: string;
  event: TranscriptEvent;
}): Promise<boolean>;
type ChannelFeedbackReflectionResult = {
  status: "cooldown";
} | {
  status: "empty";
} | {
  status: "complete";
  learning: string;
  storePath: string;
  followUp: boolean;
  userMessage?: string;
  responseLength: number;
};
declare function runChannelFeedbackReflection(params: {
  cfg: OpenClawConfig;
  channel: string;
  channelLabel: string;
  accountId?: string;
  agentId: string;
  sessionKey: string;
  conversationId: string;
  conversationKind: "direct" | "group" | "channel";
  thumbedDownResponse?: string;
  userComment?: string;
  cooldownMs?: number;
  onRecordError?: (error: unknown) => void;
  onDispatchError?: (error: unknown) => void;
}): Promise<ChannelFeedbackReflectionResult>;
declare namespace durable_delivery_d_exports {
  export { DurableInboundReplyDeliveryOptions, DurableInboundReplyDeliveryParams, StructuredDurableInboundReplyDeliveryParams, deliverInboundReplyWithMessageSendContextCore, deliverStructuredInboundReplyWithMessageSendContextCore, isDurableInboundReplyDeliveryHandled, throwIfDurableInboundReplyDeliveryFailed };
}
type DurableInboundReplyDeliveryOptions = ChannelTurnDurableDeliveryOptions;
type DurableInboundReplyDeliveryParams = DurableInboundReplyDeliveryOptions & {
  cfg: OpenClawConfig;
  channel: string;
  accountId?: string;
  agentId: string;
  ctxPayload: FinalizedMsgContext;
  payload: ReplyPayload$1;
  info: ChannelDeliveryInfo;
  runId?: string;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
};
type StructuredDurableInboundReplyDeliveryParams = Omit<DurableInboundReplyDeliveryParams, "payload"> & {
  plan: OutboundPayloadPlan;
};
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;
  /** False requires affirmative no-dispatch proof; omission preserves ambiguity. */
  sentBeforeError?: boolean;
};
declare function isDurableInboundReplyDeliveryHandled(result: DurableInboundReplyDeliveryResult): result is Extract<DurableInboundReplyDeliveryResult, {
  status: "handled_visible" | "handled_no_send";
}>;
declare function throwIfDurableInboundReplyDeliveryFailed(result: DurableInboundReplyDeliveryResult): void;
declare function deliverInboundReplyWithMessageSendContextCore(params: DurableInboundReplyDeliveryParams): Promise<DurableInboundReplyDeliveryResult>;
/** Delivers a prepared final reply through the same durable owner without parsing its text. */
declare function deliverStructuredInboundReplyWithMessageSendContextCore(params: StructuredDurableInboundReplyDeliveryParams): Promise<DurableInboundReplyDeliveryResult>;
//#endregion
//#region src/channels/message/receipt.d.ts
type MessageReceiptInputResult = MessageReceiptSourceResult & {
  receipt?: MessageReceipt;
};
/** Builds one normalized receipt from platform send results or nested adapter receipts. */
declare function createMessageReceiptFromOutboundResults(params: {
  results: readonly MessageReceiptInputResult[];
  kind?: MessageReceiptPartKind;
  threadId?: string;
  replyToId?: string;
  sentAt?: number;
}): MessageReceipt;
/** Lists unique platform message ids in receipt order. */
declare function listMessageReceiptPlatformIds(receipt: MessageReceipt): string[];
/** Resolves the explicit primary platform id, falling back to the first unique receipt id. */
declare function resolveMessageReceiptPrimaryId(receipt: MessageReceipt): string | undefined;
//#endregion
//#region src/channels/turn/partial-delivery-error.d.ts
declare const CHANNEL_PARTIAL_DELIVERY_ERROR_CODE = "CHANNEL_PARTIAL_DELIVERY";
type ChannelPartialDeliveryEnvelope = {
  cause?: unknown;
  code: typeof CHANNEL_PARTIAL_DELIVERY_ERROR_CODE;
  deliveryResult: ChannelDeliveryOutcome & {
    visibleReplySent: true;
  };
};
type ChannelPartialDeliveryError = Error & ChannelPartialDeliveryEnvelope;
/** Preserves provider-visible delivery facts when a later native operation fails. */
declare function createChannelPartialDeliveryError(cause: unknown, deliveryResult: ChannelDeliveryOutcome & {
  visibleReplySent: true;
}): ChannelPartialDeliveryError & {
  sentBeforeError: true;
  visibleReplySent: true;
};
declare function isChannelPartialDeliveryError(error: unknown): error is ChannelPartialDeliveryEnvelope;
//#endregion
//#region src/channels/turn/delivery-result.d.ts
type ReceiptParams = Parameters<typeof createMessageReceiptFromOutboundResults>[0];
/** Accumulates accepted sends without recording text or identity from failed attempts. */
declare function createChannelDeliveryAccumulator(params?: Pick<ReceiptParams, "kind" | "replyToId">): {
  readonly size: number;
  add(result: ReceiptParams["results"][number], content?: string): void;
  result(): {
    visibleReplySent: false;
    suppression: {
      reason: "no_visible_result";
    };
  } | {
    messageIds: string[];
    receipt: MessageReceipt;
    visibleReplySent: true;
    content?: string;
  };
  partialError(error: unknown): unknown;
};
/** Aggregates caller-confirmed sends, preserving nested receipts before legacy message IDs. */
declare function createAcceptedChannelDeliveryResult(params: Pick<ReceiptParams, "kind" | "replyToId"> & {
  results?: ReceiptParams["results"];
  deliveryResults?: readonly ChannelDeliveryOutcome[];
  content?: string;
}): {
  messageIds: string[];
  receipt: MessageReceipt;
  visibleReplySent: true;
  content?: string;
};
//#endregion
//#region src/channels/inbound-event/media.d.ts
/** Attachment metadata accepted from channel plugins before core normalization. */
type ChannelInboundMediaInput = {
  path?: string | null;
  url?: string | null;
  contentType?: string | null;
  fileName?: string | null;
  kind?: InboundMediaFacts["kind"] | null;
  durationMs?: number | null;
  width?: number | null;
  height?: number | null;
  transcribed?: boolean | null;
  messageId?: string | null;
};
type MediaPlaceholderTextFact = Readonly<Pick<ChannelInboundMediaInput, "contentType" | "kind" | "path" | "url">>;
/** Renders structured media facts for channel surfaces that can carry text only. */
declare function formatMediaPlaceholderText(media: readonly MediaPlaceholderTextFact[]): string;
/**
 * Legacy environment fields consumed by prompt/context builders.
 * @deprecated Pass ordered `InboundMediaFacts[]` as the context's `media` field.
 */
type ChannelInboundMediaPayload = MediaFactLegacyProjection;
/** Appends an unavailable-media notice to real caption text, or returns the notice alone. */
declare function formatInboundMediaUnavailableText(params: {
  body?: string | null;
  notice: string;
}): string;
/** Normalizes plugin-provided attachments into ordered runtime facts. */
declare function toInboundMediaFacts(media: readonly ChannelInboundMediaInput[] | null | undefined, defaults?: {
  kind?: InboundMediaFacts["kind"];
  messageId?: string;
  transcribed?: (media: ChannelInboundMediaInput, index: number) => boolean;
}): InboundMediaFacts[];
/** Adds best-effort audio/video metadata without probing URL-only media. */
declare function toInboundMediaFactsWithMetadata(media: readonly ChannelInboundMediaInput[] | null | undefined, defaults?: Parameters<typeof toInboundMediaFacts>[1]): Promise<InboundMediaFacts[]>;
/** Projects facts into history without transient turn-only fields. */
declare function toHistoryMediaEntries(media: readonly ChannelInboundMediaInput[] | null | undefined, defaults?: {
  kind?: InboundMediaFacts["kind"];
  messageId?: string;
}): HistoryMediaEntry[];
/**
 * Builds the legacy singular/plural environment projection.
 * @deprecated Pass ordered facts as `media`; use `toInboundMediaFacts` to normalize inputs.
 */
declare function buildChannelInboundMediaPayload(media: readonly InboundMediaFacts[] | null | undefined): ChannelInboundMediaPayload;
//#endregion
//#region src/plugin-sdk/channel-inbound.d.ts
/**
 * Deprecated turn-context input alias that still accepts the old `inboundTurnKind` name.
 *
 * @deprecated Use `BuildChannelInboundEventContextParams`.
 */
type BuildChannelTurnContextParams = Omit<BuildChannelInboundEventContextParams, "message"> & {
  message: BuildChannelInboundEventContextParams["message"] & {
    inboundTurnKind?: InboundEventKind;
  };
};
/**
 * Deprecated turn-context result alias with the historical `InboundTurnKind` field.
 *
 * @deprecated Use `BuiltChannelInboundEventContext`.
 */
type BuiltChannelTurnContext = BuiltChannelInboundEventContext & {
  InboundTurnKind: InboundEventKind;
};
/**
 * Builds inbound-event context for callers still passing `inboundTurnKind`.
 *
 * @deprecated Use `buildChannelInboundEventContext`.
 */
declare function buildChannelTurnContext(params: BuildChannelTurnContextParams): BuiltChannelTurnContext;
/**
 * Deprecated supplemental-context filter alias retained for channel SDK compatibility.
 *
 * @deprecated Use `filterChannelInboundSupplementalContext`.
 */
declare const filterChannelTurnSupplementalContext: typeof filterChannelInboundSupplementalContext;
type ChannelInboundEventRunnerParams<TRaw, TDispatchResult = DispatchFromConfigResult> = PublicChannelTurnParams<TRaw, TDispatchResult, ChannelCoreManagedTurnDeliveryAdapter>;
type PreparedInboundReply<TDispatchResult> = PreparedChannelTurn<TDispatchResult>;
type AssembledInboundReply = PublicReplyParams<AssembledChannelTurn>;
type ChannelInboundTurnPlan<TOwnership extends "core" | "provider_message_sending" = "core"> = PublicReplyParams<ChannelTurnPlan<TOwnership extends "provider_message_sending" ? ChannelProviderOwnedMessageSendingDeliveryAdapter : ChannelCoreManagedTurnDeliveryAdapter>>;
type InboundReplyDispatchResult<TDispatchResult> = ChannelTurnResult<TDispatchResult>;
declare function runPreparedInboundReply<TDispatchResult>(params: PreparedChannelTurn<TDispatchResult>): Promise<ChannelTurnResult<TDispatchResult>>;
declare function runChannelInboundEvent<TRaw, TDispatchResult = DispatchFromConfigResult>(params: PublicChannelTurnParams<TRaw, TDispatchResult, ChannelProviderOwnedMessageSendingDeliveryAdapter>): Promise<ChannelTurnResult<TDispatchResult>>;
declare function runChannelInboundEvent<TRaw, TDispatchResult = DispatchFromConfigResult>(params: ChannelInboundEventRunnerParams<TRaw, TDispatchResult>): Promise<ChannelTurnResult<TDispatchResult>>;
declare function dispatchChannelInboundReply(params: AssembledInboundReply): Promise<ChannelTurnResult>;
declare function dispatchChannelInboundTurn(params: PublicReplyParams<ChannelTurnPlan<ChannelTurnDeliveryAdapter>>): Promise<ChannelTurnResult>;
declare function dispatchChannelInboundTurn(params: ChannelInboundTurnPlan<"provider_message_sending">): Promise<ChannelTurnResult>;
declare function dispatchChannelInboundTurn(params: ChannelInboundTurnPlan): Promise<ChannelTurnResult>;
//#endregion
//#region extensions/telegram/src/bot/body-helpers.d.ts
type TelegramMediaKind = Exclude<NonNullable<ChannelInboundMediaInput["kind"]>, "unknown">;
declare function buildSenderName(msg: Message): string | undefined;
declare function buildSenderLabel(msg: Message, senderId?: number | string): string;
type TelegramTextEntity = NonNullable<Message["entities"]>[number];
type TelegramTextMessage = Pick<Message, "text" | "caption" | "entities" | "caption_entities" | "poll" | "contact"> & {
  rich_message?: Message.RichMessageMessage["rich_message"];
};
declare function isBinaryContent(text: string): boolean;
declare function getTelegramTextParts(msg: TelegramTextMessage): {
  text: string;
  entities: TelegramTextEntity[];
};
declare function hasBotMention(msg: Message, botUsername: string, botId?: number): boolean;
type TelegramForwardedContext = {
  from: string;
  date?: number;
  fromType: string;
  fromId?: string;
  fromUsername?: string;
  fromTitle?: string;
  fromSignature?: string;
  fromChatType?: Chat["type"];
  fromMessageId?: number;
};
declare function normalizeForwardedContext(msg: Message): TelegramForwardedContext | null;
declare function extractTelegramLocation(msg: Message): NormalizedLocation | null;
//#endregion
//#region src/infra/outbound/mirror.d.ts
/**
 * @deprecated Confirmed sends record destination history automatically; removed in the next
 * Plugin SDK major. Accepted for source compatibility and otherwise ignored.
 */
type DeliveryMirror = {
  sessionKey: string;
  agentId?: string;
  text?: string;
  mediaUrls?: string[];
  idempotencyKey?: string;
  expectedSessionId?: string;
  deliveryMirror?: SessionTranscriptDeliveryMirror;
  isGroup?: boolean;
  groupId?: string;
};
//#endregion
//#region src/channels/message/send.d.ts
type DurableMessageBatchSendParams = Omit<DeliverOutboundPayloadsParams, "abortSignal" | "onDeliveryIntent" | "payloads" | "queuePolicy"> & {
  payloads: ReplyPayload$1[];
  attempt?: number;
  signal?: AbortSignal;
  /** @deprecated Use `signal`. */
  abortSignal?: AbortSignal;
  previousReceipt?: MessageReceipt;
  /** @deprecated Destination history is automatic; removed in the next Plugin SDK major. */
  mirror?: DeliveryMirror;
};
type DurableMessageSuppressionReason = OutboundPayloadDeliverySuppressionReason | "no_visible_result";
type DurableMessageFailureStage = "platform_send" | "queue" | "unknown";
type DurableMessagePayloadDeliveryOutcome = Exclude<OutboundPayloadDeliveryOutcome, {
  status: "suppressed";
}> | (Omit<Extract<OutboundPayloadDeliveryOutcome, {
  status: "suppressed";
}>, "reason"> & {
  reason: DurableMessageSuppressionReason;
});
type DurableMessageBatchSendResult = {
  status: "sent";
  results: OutboundDeliveryResult[];
  receipt: MessageReceipt;
  deliveryIntent?: OutboundDeliveryIntent;
  payloadOutcomes?: DurableMessagePayloadDeliveryOutcome[];
} | {
  status: "suppressed";
  results: [];
  receipt: MessageReceipt;
  deliveryIntent?: OutboundDeliveryIntent;
  reason: DurableMessageSuppressionReason;
  payloadOutcomes?: DurableMessagePayloadDeliveryOutcome[];
} | {
  status: "partial_failed";
  results: OutboundDeliveryResult[];
  receipt: MessageReceipt;
  error: unknown;
  sentBeforeError: true;
  deliveryIntent?: OutboundDeliveryIntent;
  payloadOutcomes?: DurableMessagePayloadDeliveryOutcome[];
} | {
  status: "failed";
  error: unknown;
  stage?: DurableMessageFailureStage;
  payloadOutcomes?: DurableMessagePayloadDeliveryOutcome[];
};
type SerializedDurableMessagePayloadOutcome = {
  index: number;
  status: "sent";
  resultCount: number;
} | Extract<DurableMessagePayloadDeliveryOutcome, {
  status: "suppressed";
}> | {
  index: number;
  status: "failed";
  error: string;
  sentBeforeError: boolean;
  stage: DurableMessageFailureStage;
};
type DurableMessageSendContextParams = DurableMessageBatchSendParams & {
  durability?: Exclude<MessageDurabilityPolicy, "disabled">;
  /** Runs after the durable queue intent exists and before platform delivery starts. */
  onDeliveryIntent?: (intent: DurableMessageSendIntent) => void;
  preview?: LiveMessageState<ReplyPayload$1>;
  onPreviewUpdate?: (rendered: RenderedMessageBatch<ReplyPayload$1>, state: LiveMessageState<ReplyPayload$1>) => Promise<LiveMessageState<ReplyPayload$1>> | LiveMessageState<ReplyPayload$1>;
  onEditReceipt?: (receipt: MessageReceipt, rendered: RenderedMessageBatch<ReplyPayload$1>) => Promise<MessageReceipt> | MessageReceipt;
  onDeleteReceipt?: (receipt: MessageReceipt) => Promise<void> | void;
  onCommitReceipt?: (receipt: MessageReceipt) => Promise<void> | void;
  onSendFailure?: (error: unknown) => Promise<void> | void;
};
type DurableMessageSendContext = MessageSendContext<ReplyPayload$1, DurableMessageBatchSendResult>;
//#endregion
//#region src/agents/agent-activity-presentation.d.ts
declare function projectAgentActivityItem<Item extends {
  kind?: string;
  name?: string;
  status?: string;
  phase?: string;
  hideFromChannelProgress?: boolean;
}>(item: Item, facts?: {
  args?: unknown;
  result?: unknown;
  nativeOperation?: "wait" | "process.poll";
}): Item & {
  hideFromChannelProgress?: boolean;
};
declare function isCompleteAgentPreamble(item: {
  phase?: string;
  progressText?: string;
}): boolean;
//#endregion
//#region src/channels/message/outbound-echo.d.ts
type OutboundMessageIdentity = {
  channel: string;
  accountId?: string;
  conversationId: string;
} & ({
  messageId: string;
  sourceId?: string;
} | {
  messageId?: string;
  sourceId: string;
});
/** Records a platform message id emitted by a channel's own outbound send path. */
declare function recordOutboundMessageIdentity(identity: OutboundMessageIdentity): void;
/** Returns whether an inbound platform message matches a recently emitted outbound id. */
declare function isRecentOutboundMessageIdentity(identity: OutboundMessageIdentity): boolean;
//#endregion
//#region src/channels/message/ingress-queue.types.d.ts
type ChannelIngressQueueRecord<TPayload, TMetadata = unknown> = ChannelIngressScope & {
  id: string;
  payload: TPayload;
  metadata?: TMetadata;
  receivedAt: number;
  updatedAt: number;
  laneKey?: string;
  attempts: number;
  lastAttemptAt?: number;
  lastError?: string;
};
type ChannelIngressQueueClaim<TPayload, TMetadata = unknown> = ChannelIngressQueueRecord<TPayload, TMetadata> & {
  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;
  };
};
/** Claim identity available when a stale row's payload cannot be decoded. */
type ChannelIngressQueueCorruptClaim = ChannelIngressScope & {
  id: string;
  laneKey?: string;
  reason: "corrupt_payload";
  claim: ChannelIngressQueueClaim<unknown>["claim"];
};
/** Completed ingress event tombstone retained for duplicate detection. */
type ChannelIngressQueueCompletedRecord<TCompletedMetadata = unknown> = ChannelIngressScope & {
  id: string;
  completedAt: number;
  metadata?: TCompletedMetadata;
};
type ChannelIngressQueuePruneOptions = {
  pendingTtlMs?: number;
  completedTtlMs?: number;
  failedTtlMs?: number;
  pendingMaxEntries?: number;
  completedMaxEntries?: number;
  failedMaxEntries?: number;
  protectIds?: Iterable<string>;
  now?: number;
};
/** Failed ingress event tombstone retained for duplicate detection. */
type ChannelIngressQueueFailedRecord = ChannelIngressScope & {
  id: string;
  failedAt: number;
  reason: string;
  message?: string;
};
/** Rich failed ingress event retained for diagnostics and operator recovery. */
type ChannelIngressQueueDeadLetterRecord<TPayload = unknown, TMetadata = unknown> = ChannelIngressQueueFailedRecord & {
  payload?: TPayload;
  metadata?: TMetadata;
  receivedAt: number;
  updatedAt: number;
  laneKey?: string;
  attempts: number;
  lastAttemptAt?: number;
};
type ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata> = {
  kind: "accepted";
  duplicate: false;
  record: ChannelIngressQueueRecord<TPayload, TMetadata>;
} | {
  kind: "pending";
  duplicate: true;
  record: ChannelIngressQueueRecord<TPayload, TMetadata>;
} | {
  kind: "claimed";
  duplicate: true;
  record: ChannelIngressQueueClaim<TPayload, TMetadata>;
} | {
  kind: "completed";
  duplicate: true;
  record: ChannelIngressQueueCompletedRecord<TCompletedMetadata>;
} | {
  kind: "failed";
  duplicate: true;
  record: ChannelIngressQueueFailedRecord;
};
type ChannelIngressQueueInput<TPayload, TMetadata> = {
  id: string;
  payload: TPayload;
  metadata?: TMetadata;
  receivedAt?: number;
  laneKey?: string;
};
type ChannelIngressQueue<TPayload, TMetadata = unknown, TCompletedMetadata = unknown> = {
  /** One durable admission for a transport batch; optional for external queue implementations. */
  enqueueBatch?(events: ReadonlyArray<ChannelIngressQueueInput<TPayload, TMetadata>>): Promise<Array<ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata>>>;
  /** Atomic batch admission under current policy authority; absence is unsupported. */
  enqueueBatchAuthorized?(events: ReadonlyArray<ChannelIngressQueueInput<TPayload, TMetadata>>, options: {
    assertCurrent: () => void;
  }): Promise<Array<ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata>>>;
  /** Claim a fresh singleton only when no pending or claimed row precedes it. */
  enqueueAndClaim?(id: string, payload: TPayload, options: {
    ownerId: string;
    metadata?: TMetadata;
    receivedAt?: number;
    laneKey?: string;
  }): Promise<{
    result: ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata>;
    freshClaim?: ChannelIngressQueueClaim<TPayload, TMetadata>;
  }>;
  enqueue(id: string, payload: TPayload, options?: {
    metadata?: TMetadata;
    receivedAt?: number;
    laneKey?: string;
  }): Promise<ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata>>;
  /** Current-authority enqueue; absence is unsupported, never fall back to unguarded intake. */
  enqueueAuthorized?: (id: string, payload: TPayload, options: {
    metadata?: TMetadata;
    receivedAt?: number;
    laneKey?: string;
    assertCurrent: () => void;
  }) => Promise<ChannelIngressQueueEnqueueResult<TPayload, TMetadata, TCompletedMetadata>>;
  listPending(options?: {
    limit?: number | "all";
    orderBy?: "received" | "id";
  }): Promise<Array<ChannelIngressQueueRecord<TPayload, TMetadata>>>;
  listClaims(): Promise<Array<ChannelIngressQueueClaim<TPayload, TMetadata>>>;
  /** Coherent lane state; optional for existing external queue implementations. */
  listUnsettled?(options?: {
    orderBy?: "received" | "id";
  }): Promise<{
    pending: Array<ChannelIngressQueueRecord<TPayload, TMetadata>>;
    claims: Array<ChannelIngressQueueClaim<TPayload, TMetadata>>;
  }>;
  /** Additive SDK seam; optional so existing external queue test doubles remain compatible. */
  listFailed?(options?: {
    limit?: number | "all";
  }): Promise<Array<ChannelIngressQueueDeadLetterRecord<TPayload, TMetadata>>>;
  claimNext(options?: {
    ownerId?: string;
    blockedLaneKeys?: Iterable<string>;
    staleMs?: number;
    orderBy?: "received" | "id";
    scanLimit?: number;
    candidateIds?: Iterable<string>;
    deriveLaneKey?: (record: ChannelIngressQueueRecord<TPayload, TMetadata>) => string | undefined;
    /** Authorize a changed durable lane before the atomic pending-to-claimed transition. */
    reconcileStoredLaneKey?: (record: ChannelIngressQueueRecord<TPayload, TMetadata>, storedLaneKey: string, derivedLaneKey: string) => boolean;
  }): Promise<ChannelIngressQueueClaim<TPayload, TMetadata> | null>;
  claim(id: string, options?: {
    ownerId?: string;
    laneKey?: string;
  }): Promise<ChannelIngressQueueClaim<TPayload, TMetadata> | null>;
  refreshClaim?(claim: ChannelIngressQueueClaimRef, options?: {
    refreshedAt?: number;
  }): Promise<boolean>;
  complete(idOrClaim: string | ChannelIngressQueueClaimRef, options?: {
    metadata?: TCompletedMetadata;
    completedAt?: number;
  }): Promise<boolean>;
  release(idOrClaim: string | ChannelIngressQueueClaimRef, options?: {
    lastError?: string;
    releasedAt?: number;
    recordAttempt?: boolean;
  }): Promise<boolean>;
  fail(idOrClaim: string | ChannelIngressQueueClaimRef, options: {
    reason: string;
    message?: string;
    failedAt?: number;
  }): Promise<boolean>;
  /** Additive SDK seam; actual runtime queues support operator resubmission. */
  resubmit?(id: string, options?: {
    resubmittedAt?: number;
  }): Promise<{
    kind: "resubmitted";
    record: ChannelIngressQueueRecord<TPayload, TMetadata>;
    previous: ChannelIngressQueueDeadLetterRecord<TPayload, TMetadata>;
  } | {
    kind: "not-found";
  } | {
    kind: "completed";
    record: ChannelIngressQueueCompletedRecord<TCompletedMetadata>;
  } | {
    kind: "active";
    status: "pending" | "claimed";
  } | {
    kind: "unrecoverable";
    record: ChannelIngressQueueDeadLetterRecord<TPayload, TMetadata>;
  }>;
  delete(idOrClaim: string | ChannelIngressQueueRecord<TPayload, TMetadata> | ChannelIngressQueueClaimRef): Promise<boolean>;
  recoverStaleClaims(options?: {
    staleMs?: number;
    now?: number;
    shouldRecover?: (claim: ChannelIngressQueueClaim<TPayload, TMetadata>) => boolean | Promise<boolean>;
    shouldRecoverCorrupt?: (claim: ChannelIngressQueueCorruptClaim) => boolean | Promise<boolean>;
  }): Promise<number>;
  prune(options?: ChannelIngressQueuePruneOptions): Promise<number>;
  /**
   * Delete all rows after callers stop the account's producers and drain.
   * Optional for existing plugin-supplied queue inputs; core queues implement it.
   * Cancellation before commit admission preserves every row.
   */
  purge?(options?: {
    signal?: AbortSignal;
  }): Promise<number>;
};
type CreateChannelIngressQueueOptions = {
  channelId: string;
  accountId?: string;
  stateDir?: string;
  now?: () => number;
  /**
   * Read-only inspection never creates, migrates, chmods, or configures the shared
   * state file. Read-write listings retain canonical database admission.
   */
  access?: "read-write" | "read-only";
};
type ChannelIngressScope = {
  channelId: string;
  accountId: string;
  queueName: string;
};
//#endregion
//#region src/channels/message/ingress-retry-policy.d.ts
declare const DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS = 8;
declare const DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS: number;
type IngressRetryPolicyConfig = {
  maxAttempts?: number;
  deadLetterMinAgeMs?: number;
  baseMs?: number;
  maxMs?: number;
};
type IngressNonRetryableFailure = {
  reason: string;
  message: string;
};
//#endregion
//#region src/channels/message/ingress-dead-letter-notice.d.ts
type IngressDeadLetterNotice<TPayload, TMetadata> = (claim: ChannelIngressQueueClaim<TPayload, TMetadata>, failure: IngressNonRetryableFailure, signal: AbortSignal) => void | Promise<void>;
//#endregion
//#region src/channels/message/ingress-drain-lifecycle.d.ts
/** Full pre-adoption -> adoption ownership lifecycle for one claimed event. */
type ChannelIngressDispatchLifecycle = {
  /** Pre-adoption only. After adopt the drain treats this signal as inert. */
  abortSignal: AbortSignal;
  /**
   * Same-lane rows admitted but not yet handed off, excluding this event.
   * Lets channel buffers that span lane rows wait for input that is already durable.
   */
  readLaneBacklog?: () => Promise<readonly ChannelIngressQueueRecord<unknown>[]>;
  /**
   * Fires when recovery-relevant session/run state is durable.
   * Drain completes (tombstones) the claim here -- never at settle.
   */
  onAdopted: () => void | Promise<void>;
  /**
   * Turn ownership deferred to reply-lane admission (queued followup).
   * Claim remains held until adopted or abandoned.
   */
  onDeferred: () => void;
  /** Pre-adoption liveness while waiting for reply-lane admission or preflight compaction. */
  onDeferredHeartbeat?: () => void;
  deferredHeartbeatIntervalMs?: number;
  /**
   * Durable adoption finalization is in progress (e.g. settlement hold while
   * committing dedupe). Clears the pre-adoption stall watchdog so a timeout
   * settlement cannot race and dead-letter an about-to-complete claim.
   * Claim stays held until onAdopted / onAbandoned / fail.
   */
  onAdoptionFinalizing: () => void;
  /** Deferred work terminally failed after dispatch returned. */
  onFailed?: (error: unknown) => void | Promise<void>;
  /** Explicit cancellation before adoption; releases without consuming retry budget. */
  onCancelled?: () => void | Promise<void>;
  /**
   * Deferred turn finished without ever owning the reply lane.
   * Drain releases the claim for retry.
   */
  onAbandoned: () => void | Promise<void>;
};
/** Maps a drain lifecycle onto the reply-lane ownership surface. */
declare function bindIngressLifecycleToReplyOptions(lifecycle: ChannelIngressDispatchLifecycle): {
  turnAdoptionLifecycle: Omit<ChannelIngressDispatchLifecycle, "onAdoptionFinalizing" | "onFailed" | "onCancelled" | "readLaneBacklog"> & {
    admission: "exclusive";
  };
};
//#endregion
//#region src/channels/message/ingress-drain-state.d.ts
type ChannelIngressDrainDispatchResult = {
  kind: "completed";
} |
/** The dispatch owner already committed this claim to its durable receipt. */
{
  kind: "transferred";
} |
/** Normal admission backpressure; the caller owns the next wake. */
{
  kind: "pending";
} | {
  kind: "deferred";
} | {
  kind: "failed-retryable";
  error: unknown;
};
//#endregion
//#region src/channels/message/ingress-drain-supersede.d.ts
type IngressSupersedeDecision = boolean | (() => boolean);
//#endregion
//#region src/channels/message/ingress-drain.d.ts
/** Default claim→adoption stall before applying the shared retry disposition. */
declare const DEFAULT_INGRESS_ADOPTION_STALL_MS: number;
type DeferredLaneOccupancy = "hold" | "release";
type CreateChannelIngressDrainOptions<TPayload, TMetadata = unknown, TCompletedMetadata = unknown> = {
  queue: ChannelIngressQueue<TPayload, TMetadata, TCompletedMetadata>;
  /**
   * Dispatch a claimed event. Wire lifecycle into reply options (see
   * bindIngressLifecycleToReplyOptions). Return deferred when ownership will
   * transfer at reply-lane admission; otherwise complete or throw.
   */
  dispatchClaimedEvent: (event: ChannelIngressQueueClaim<TPayload, TMetadata>, lifecycle: ChannelIngressDispatchLifecycle) => Promise<ChannelIngressDrainDispatchResult | void> | ChannelIngressDrainDispatchResult | void;
  resolveNonRetryableFailure?: (err: unknown) => IngressNonRetryableFailure | null;
  /** Best-effort transport notice, only after this claim's dead-letter write commits. */
  onDeadLetter?: IngressDeadLetterNotice<TPayload, TMetadata>;
  /** A returned guard is checked synchronously before cancelling pre-adoption work. */
  shouldSupersedePending?: (newEvent: ChannelIngressQueueRecord<TPayload, TMetadata> | ChannelIngressQueueClaim<TPayload, TMetadata>, pendingEvent: ChannelIngressQueueClaim<TPayload, TMetadata>) => IngressSupersedeDecision | Promise<IngressSupersedeDecision>;
  deriveLaneKey?: (record: ChannelIngressQueueRecord<TPayload, TMetadata>) => string | undefined;
  reconcileStoredLaneKey?: (record: ChannelIngressQueueRecord<TPayload, TMetadata>, storedLaneKey: string, derivedLaneKey: string) => boolean;
  ownerId?: string;
  adoptionStallTimeoutMs?: number;
  claimLeaseMs?: number;
  /**
   * Whether a claimed event keeps occupying its ingress serialization lane after
   * dispatch hands ownership to deferred work. Default "hold" (current behavior).
   */
  deferredLaneOccupancy?: DeferredLaneOccupancy;
  retryPolicy?: IngressRetryPolicyConfig;
  now?: () => number;
  formatError?: (err: unknown) => string;
  onLog?: (message: string) => void;
  abortSignal?: AbortSignal;
  orderBy?: "received" | "id";
  scanLimit?: number;
  startLimit?: number;
};
type ChannelIngressDrain = {
  recoverStaleClaims: () => Promise<number>;
  drainOnce: (options?: {
    shouldStop?: () => boolean;
  }) => Promise<{
    started: number;
  }>;
  activeLaneKeys: () => ReadonlySet<string>;
  waitForIdle: () => Promise<void>;
  dispose: () => void;
};
type OwnedChannelIngressDrain = ChannelIngressDrain & {
  dispose(this: void, options: {
    waitForSettlements: true;
  }): Promise<void>;
};
/** Creates a channel-agnostic durable ingress drain over an existing queue. */
declare function createChannelIngressDrain<TPayload, TMetadata = unknown, TCompletedMetadata = unknown>(options: CreateChannelIngressDrainOptions<TPayload, TMetadata, TCompletedMetadata>, retainOwnerUntilDispose?: boolean): OwnedChannelIngressDrain;
//#endregion
//#region src/channels/message/ingress-monitor-types.d.ts
/** Stable identity and serialization lane extracted before durable admission. */
type ChannelIngressMonitorFacts = {
  eventId: string;
  laneKey: string;
};
/** Versioned body presented to a channel's persisted-payload encoder. */
type ChannelIngressPayloadEnvelope<TBody> = {
  version: number;
  body: TBody;
};
/** Claim ownership lifecycle handed to one channel delivery. */
type ChannelIngressMonitorLifecycle = ChannelIngressDispatchLifecycle & {
  admission: "exclusive";
};
type ChannelIngressMonitorDeliveryResult = ChannelIngressDrainDispatchResult;
type ChannelIngressMonitorAdmissionResult<TResult> = {
  readonly kind: "ignored";
  readonly queueResult?: undefined;
} | {
  readonly kind: "durable";
  readonly queueResult: TResult;
};
type ChannelIngressMonitorInspectionContext = {
  phase: "admission";
} | {
  phase: "claim";
  claimedId: string;
  claimedLaneKey: string | undefined;
};
type ChannelIngressMonitorRetention = {
  pruneIntervalMs: number;
  pendingTtlMs?: number;
  pendingMaxEntries?: number;
  completedTtlMs?: number;
  completedMaxEntries?: number;
  failedTtlMs?: number;
  failedMaxEntries?: number;
};
type ChannelIngressMonitorClaimErrorKind = "invalid-version" | "identity-mismatch";
type ChannelIngressMonitorPayloadCodec<TRaw, TBody, TStoredPayload, TMetadata> = {
  version: number;
  serialize: (raw: TRaw, context: {
    facts: ChannelIngressMonitorFacts;
    receivedAt: number;
  }) => TBody;
  deserialize: (body: TBody, context: {
    claim: ChannelIngressQueueClaim<TStoredPayload, TMetadata>;
  }) => TRaw;
  createClaimError: (kind: ChannelIngressMonitorClaimErrorKind, claim: ChannelIngressQueueClaim<TStoredPayload, TMetadata>) => Error;
} & ((TBody extends string ? {
  storage: "raw-event";
} : never) | {
  storage?: "custom";
  encode: (envelope: ChannelIngressPayloadEnvelope<TBody>) => TStoredPayload;
  decode: (payload: TStoredPayload, context: {
    claim: ChannelIngressQueueClaim<TStoredPayload, TMetadata>;
  }) => {
    version: unknown;
    body: TBody;
  };
});
type ChannelIngressMonitorDrainOptions<TStoredPayload, TMetadata> = Omit<CreateChannelIngressDrainOptions<TStoredPayload, TMetadata>, "queue" | "dispatchClaimedEvent" | "abortSignal" | "now" | "ownerId" | "claimLeaseMs">;
type CreateChannelIngressMonitorOptions<TRaw, TBody, TStoredPayload, TMetadata> = {
  queue: ChannelIngressQueue<TStoredPayload, TMetadata> | (() => ChannelIngressQueue<TStoredPayload, TMetadata>);
  inspect: (raw: TRaw, context: ChannelIngressMonitorInspectionContext) => ChannelIngressMonitorFacts | null;
  /** Preferred over inspect when the host supports asynchronous inspection. */
  inspectAsync?: (raw: TRaw, context: ChannelIngressMonitorInspectionContext) => Promise<ChannelIngressMonitorFacts | null>;
  /** Await a provider-validated replacement before serialization; policy errors refuse intake. */
  prepareAdmission?: (raw: TRaw, context: {
    facts: ChannelIngressMonitorFacts;
    receivedAt: number;
    signal: AbortSignal;
  }) => Promise<{
    raw: TRaw;
    assertCurrent: () => void;
  } | undefined>;
  payload: ChannelIngressMonitorPayloadCodec<TRaw, TBody, TStoredPayload, TMetadata>;
  /**
   * Reuse admission identity when this monitor appends and claims a fresh event.
   * Payload deserialization still runs; claim inspection must not prepare delivery
   * data or authorize effects. Replayed and previously stored events still inspect.
   */
  reuseAdmissionFactsForFreshClaims?: boolean;
  deliver: (raw: TRaw, lifecycle: ChannelIngressMonitorLifecycle, claim: ChannelIngressQueueClaim<TStoredPayload, TMetadata>) => Promise<ChannelIngressMonitorDeliveryResult | void> | ChannelIngressMonitorDeliveryResult | void;
  /**
   * Recovery sweep interval (minimum five minutes); admissions and retries wake directly.
   * External queue writes, including CLI resubmission, do not wake this monitor.
   * Eligible rows wait up to the effective interval; an unrefreshed live-process claim first
   * expires its lease (30 minutes by default). Startup recovery runs immediately.
   */
  pollIntervalMs: number;
  retention: "standard" | Partial<ChannelIngressMonitorRetention>;
  appendRetryDelaysMs?: readonly number[];
  /**
   * Runs after every durable enqueue. `isNew` means this admission inserted the queue
   * row; a pruned event can become new again. It does not imply claim or delivery.
   */
  onDurableAdmission?: (raw: TRaw, context: {
    facts: ChannelIngressMonitorFacts;
    receivedAt: number;
    isNew: boolean;
  }) => void | Promise<void>;
  onAdmissionFailure?: (raw: TRaw, error: unknown) => void | Promise<void>;
  /** False lets repeated requests fill drain capacity while earlier claims remain active. */
  waitForDeliveryIdleBeforeRepump?: boolean;
  /** Runs each pump under a channel-owned async context such as a detached request root. */
  runPumpTask?: (work: () => Promise<void>) => Promise<void>;
  /** False lets a channel apply its own bounded delivery grace before final disposal. */
  waitForDeliveryIdleOnStop?: boolean;
  /** Tracks deferred reply ownership through stop, abort, or an explicit channel-owned wait. */
  deferredClaims?: "wait-on-stop" | "settle-on-abort" | "manual";
  drain?: ChannelIngressMonitorDrainOptions<TStoredPayload, TMetadata>;
  abortSignal?: AbortSignal;
  now?: () => number;
  onError?: (error: unknown) => void;
  onActivityChange?: (active: boolean) => void;
  createStoppedError?: () => Error;
  /** Durable-after-stop preserves append-only admission for handlers selected before unregister. */
  admissionMode?: "until-stopped" | "while-running" | "durable-after-stop";
};
//#endregion
//#region src/channels/message/ingress-monitor.d.ts
/** Replay-guard retention defaults; changing a value requires a per-channel keyspace audit. */
declare const CHANNEL_INGRESS_RETENTION_DEFAULTS: Readonly<{
  pruneIntervalMs: number;
  completedTtlMs: number;
  completedMaxEntries: number;
  failedTtlMs: number;
  failedMaxEntries: number;
}>;
/**
 * Creates the shared monitor around a durable queue and ingress drain.
 * Channel code keeps transport inspection, payload shape, and delivery policy.
 */
declare function createChannelIngressMonitor<TRaw, TBody, TStoredPayload, TMetadata = unknown>(options: CreateChannelIngressMonitorOptions<TRaw, TBody, TStoredPayload, TMetadata>): {
  admit: (raw: TRaw, admitOptions?: {
    receivedAt?: number;
    facts?: ChannelIngressMonitorFacts;
  }) => Promise<ChannelIngressMonitorAdmissionResult<{
    kind: "accepted";
    duplicate: false;
    record: ChannelIngressQueueRecord<TStoredPayload, TMetadata>;
  } | {
    kind: "pending";
    duplicate: true;
    record: ChannelIngressQueueRecord<TStoredPayload, TMetadata>;
  } | {
    kind: "claimed";
    duplicate: true;
    record: ChannelIngressQueueClaim<TStoredPayload, TMetadata>;
  } | {
    kind: "completed";
    duplicate: true;
    record: ChannelIngressQueueCompletedRecord<unknown>;
  } | {
    kind: "failed";
    duplicate: true;
    record: ChannelIngressScope & {
      id: string;
      failedAt: number;
      reason: string;
      message?: string;
    };
  }>>;
  admitBatch: (rawEvents: readonly TRaw[], admitOptions?: {
    receivedAt?: number;
  }) => Promise<ChannelIngressMonitorAdmissionResult<{
    kind: "accepted";
    duplicate: false;
    record: ChannelIngressQueueRecord<TStoredPayload, TMetadata>;
  } | {
    kind: "pending";
    duplicate: true;
    record: ChannelIngressQueueRecord<TStoredPayload, TMetadata>;
  } | {
    kind: "claimed";
    duplicate: true;
    record: ChannelIngressQueueClaim<TStoredPayload, TMetadata>;
  } | {
    kind: "completed";
    duplicate: true;
    record: ChannelIngressQueueCompletedRecord<unknown>;
  } | {
    kind: "failed";
    duplicate: true;
    record: ChannelIngressScope & {
      id: string;
      failedAt: number;
      reason: string;
      message?: string;
    };
  }>[]>;
  start: () => void;
  ensureQueueAvailable: () => void;
  requestDrain: () => void;
  pause: () => Promise<void>;
  stop: () => Promise<void>;
  waitForIdle: () => Promise<void>;
  waitForDeferredClaims: () => Promise<void>;
  waitForPumpIdle: () => Promise<void>;
  isRunning: () => boolean;
  isStopped: () => boolean;
};
//#endregion
//#region src/channels/message/ingress-errors.d.ts
/** Named ingress error factory shared by channel payload and admission failures. */
type ChannelIngressErrorClass<TError extends Error, TArgs extends unknown[]> = {
  new (...args: TArgs): TError;
  readonly name: string;
  readonly prototype: TError;
};
declare function createChannelIngressError(name: string): ChannelIngressErrorClass<Error, [message: string, options?: ErrorOptions]>;
declare function createChannelIngressError<TReason extends string>(name: string, options: {
  withReason: true;
}): ChannelIngressErrorClass<Error & {
  readonly reason: TReason;
}, [reason: TReason, message: string, errorOptions?: ErrorOptions]>;
//#endregion
//#region src/channels/message/ingress-claim-owner.d.ts
declare const INGRESS_CLAIM_PROCESS_ID: string;
declare function processPidFromOwnerId(ownerId: string): number;
//#endregion
//#region src/channels/typing-lifecycle.d.ts
type AsyncTick = () => Promise<void> | void;
/** Creates a cancellable keepalive loop for channel typing indicators. */
declare function createTypingKeepaliveLoop(params: {
  intervalMs: number;
  onTick: AsyncTick;
}): {
  tick: () => Promise<void>;
  start: () => void;
  stop: () => void;
  isRunning: () => boolean;
};
//#endregion
//#region src/channels/draft-stream-loop.d.ts
/** Throttled draft-stream sender used by channels that edit in-progress replies. */
type DraftStreamLoop<T = string> = Omit<ReturnType<typeof createDraftStreamLoop<T>>, "takePending"> & {
  /** Removes queued (not in-flight) text atomically and cancels its scheduled flush. */
  takePending?: () => T;
};
declare function createDraftStreamLoop<T = string>(params: {
  throttleMs: number;
  /** Keep background updates arriving during a send in the next throttle window. */
  coalesceInFlight?: boolean;
  isStopped: () => boolean;
  sendOrEditStreamMessage: (value: T) => Promise<void | boolean>;
  /** Empty sentinel and predicate for non-string payloads. */
  emptyValue?: T;
  isEmpty?: (value: T) => boolean;
  onBackgroundFlushError?: (err: unknown) => void;
}): {
  update: (value: T) => void;
  flush: () => Promise<void>;
  stop: () => void;
  resetPending: () => void;
  resetThrottleWindow: () => void;
  waitForInFlight: () => Promise<void>;
  takePending: () => T;
};
//#endregion
//#region src/channels/draft-stream-controls.d.ts
type FinalizableDraftStreamState = {
  stopped: boolean;
  final: boolean;
};
type StopAndClearMessageIdParams<T> = {
  stopForClear: () => Promise<void>;
  readMessageId: () => T | undefined;
  clearMessageId: () => void;
};
type ClearFinalizableDraftMessageParams<T> = StopAndClearMessageIdParams<T> & {
  isValidMessageId: (value: unknown) => value is T;
  deleteMessage: (messageId: T) => Promise<boolean | void>;
  onDeleteFailure?: (messageId: T) => void;
  onDeleteSuccess?: (messageId: T) => void;
  warn?: (message: string) => void;
  warnPrefix: string;
};
type DraftStreamOptions<T> = Omit<Parameters<typeof createDraftStreamLoop<T>>[0], "isStopped" | "onBackgroundFlushError">;
type FinalizableDraftLifecycleParams<TMessageId, TUpdate = string> = Omit<ClearFinalizableDraftMessageParams<TMessageId>, "onDeleteFailure" | "stopForClear"> & DraftStreamOptions<TUpdate> & {
  state: FinalizableDraftStreamState;
};
/**
 * Creates controls for streaming preview messages that can be finalized, sealed, or cleared.
 */
declare function createFinalizableDraftStreamControls<T = string>(params: DraftStreamOptions<T> & {
  isStopped: () => boolean;
  isFinal: () => boolean;
  markStopped: () => void;
  markFinal: () => void;
}): {
  loop: {
    update: (value: T) => void;
    flush: () => Promise<void>;
    stop: () => void;
    resetPending: () => void;
    resetThrottleWindow: () => void;
    waitForInFlight: () => Promise<void>;
    takePending: () => T;
  };
  update: (value: T) => void;
  stop: () => Promise<void>;
  seal: () => Promise<void>;
  discardPending: () => Promise<void>;
  stopForClear: () => Promise<void>;
};
declare function createFinalizableDraftStreamControlsForState<T = string>(params: DraftStreamOptions<T> & {
  state: FinalizableDraftStreamState;
}): {
  loop: {
    update: (value: T) => void;
    flush: () => Promise<void>;
    stop: () => void;
    resetPending: () => void;
    resetThrottleWindow: () => void;
    waitForInFlight: () => Promise<void>;
    takePending: () => T;
  };
  update: (value: T) => void;
  stop: () => Promise<void>;
  seal: () => Promise<void>;
  discardPending: () => Promise<void>;
  stopForClear: () => Promise<void>;
};
declare function takeMessageIdAfterStop<T>(params: StopAndClearMessageIdParams<T>): Promise<T | undefined>;
/**
 * Stops a draft stream and deletes its preview message when the stored id is valid.
 * Claims the current id before deletion; stateful callers can retain failures through
 * onDeleteFailure without making overlapping clears delete the same message twice.
 */
declare function clearFinalizableDraftMessage<T>(params: ClearFinalizableDraftMessageParams<T>): Promise<void>;
declare function createFinalizableDraftLifecycle<TMessageId, TUpdate = string>(params: FinalizableDraftLifecycleParams<TMessageId, TUpdate>): {
  loop: {
    update: (value: TUpdate) => void;
    flush: () => Promise<void>;
    stop: () => void;
    resetPending: () => void;
    resetThrottleWindow: () => void;
    waitForInFlight: () => Promise<void>;
    takePending: () => TUpdate;
  };
  update: (value: TUpdate) => void;
  seal: () => Promise<void>;
  discardPending: () => Promise<void>;
  stopForClear: () => Promise<void>;
  generation: number;
  reset: (mode?: "preserve" | "discard", throttle?: "reset" | "keep") => void;
  resetMessage: (throttle?: "reset" | "keep") => void;
  createMessage: (send: () => Promise<TMessageId | undefined>, publish: (messageId: TMessageId | undefined) => boolean, retirementOptions?: {
    defer?: boolean;
  }) => Promise<boolean>;
  retireCurrent: (stopForClear: () => Promise<void>) => Promise<void>;
  stop: () => Promise<void>;
  clear: () => Promise<void>;
  clearWithStop: (stopForClear: () => Promise<void>, messageIdOwner?: Pick<StopAndClearMessageIdParams<TMessageId>, "readMessageId" | "clearMessageId">) => Promise<void>;
  retire: (messageId: TMessageId, options?: {
    defer?: boolean;
  }) => Promise<void>;
  cleanupPending: (prepareCleanup?: () => void) => Promise<void>;
};
//#endregion
//#region src/channels/run-state-machine.d.ts
type RunStateStatusPatch = {
  busy?: boolean;
  activeRuns?: number;
  lastRunActivityAt?: number | null;
  activeRunStartedAt?: number | null;
};
type RunStateStatusSink = (patch: RunStateStatusPatch) => void;
type RunStateMachineParams = {
  setStatus?: RunStateStatusSink;
  abortSignal?: AbortSignal;
  heartbeatMs?: number;
  now?: () => number;
};
declare function createRunStateMachine(params: RunStateMachineParams): {
  isActive(): boolean;
  onRunStart(): void;
  onRunEnd(): void;
  deactivate: () => void;
};
//#endregion
//#region src/channels/transport/stall-watchdog.d.ts
type StallWatchdogTimeoutMeta = {
  idleMs: number;
  timeoutMs: number;
};
/** Public control surface for a transport stall watchdog instance. */
type ArmableStallWatchdog = ReturnType<typeof createArmableStallWatchdog>;
/** Creates a watchdog that reports once when an armed transport goes idle. */
declare function createArmableStallWatchdog(params: {
  label: string;
  timeoutMs: number;
  checkIntervalMs?: number;
  abortSignal?: AbortSignal;
  runtime?: RuntimeEnv;
  onTimeout: (meta: StallWatchdogTimeoutMeta) => void;
}): {
  arm: (atMs?: number) => void;
  touch: (atMs?: number) => void;
  disarm: () => void;
  stop: () => void;
  isArmed: () => boolean;
};
//#endregion
//#region src/channels/draft-streaming-chunking.d.ts
type ChannelDraftStreamingChunking = {
  minChars: number;
  maxChars: number;
  breakPreference: "paragraph" | "newline" | "sentence";
};
declare function resolveChannelDraftStreamingChunking(cfg: OpenClawConfig | undefined, channelId: ChannelId$1, accountId: string | null | undefined, opts: {
  fallbackLimit: number;
}): ChannelDraftStreamingChunking;
//#endregion
//#region src/channels/plugins/runtime-forwarders.d.ts
type MaybePromise$1<T> = T | Promise<T>;
type DirectoryMethod = "self" | "listPeersLive" | "listGroupsLive" | "listGroupMembers";
type OutboundMethod = "renderPresentation" | "sendPayload" | "sendText" | "sendMedia" | "sendPoll";
/**
 * Creates a directory adapter whose methods forward to a lazily resolved runtime.
 */
declare function createRuntimeDirectoryLiveAdapter<Runtime>(params: {
  getRuntime: () => MaybePromise$1<Runtime>;
} & { [Method in DirectoryMethod]?: (runtime: Runtime) => ChannelDirectoryAdapter[Method] | null | undefined; }): Pick<ChannelDirectoryAdapter, DirectoryMethod>;
/**
 * Creates outbound delegates whose methods forward to a lazily resolved runtime.
 */
declare function createRuntimeOutboundDelegates<Runtime>(params: {
  getRuntime: () => MaybePromise$1<Runtime>;
} & { [Method in OutboundMethod]?: {
  resolve: (runtime: Runtime) => ChannelOutboundAdapter[Method] | null | undefined;
  unavailableMessage?: string;
}; }): Pick<ChannelOutboundAdapter, OutboundMethod>;
//#endregion
//#region src/plugin-sdk/channel-lifecycle.core.d.ts
type CloseAwareServer = {
  once: (event: "close", listener: () => void) => unknown;
};
type PassiveAccountLifecycleParams<Handle> = {
  abortSignal?: AbortSignal;
  start: () => Promise<Handle>;
  stop?: (handle: Handle) => void | Promise<void>;
  onStop?: () => void | Promise<void>;
};
/** Runtime context passed to queued channel work. */
type ChannelRunQueueTaskContext = {
  /** Signal tied to the channel/account lifecycle that owns the queued work. */
  lifecycleSignal?: AbortSignal;
};
/** Per-key async queue used by channel plugins to serialize account or thread work. */
type ChannelRunQueue = {
  /** Enqueue work under a serialization key such as account id, thread id, or chat id. */
  enqueue: (key: string, task: (context: ChannelRunQueueTaskContext) => Promise<void>) => void;
  /** Stop accepting meaningful work and mark the lifecycle as inactive. */
  deactivate: () => void;
};
/** Hooks used to wire channel queue state into runtime status and error reporting. */
type ChannelRunQueueParams = {
  /** Receives busy/idle lifecycle snapshots from the shared run-state machine. */
  setStatus?: RunStateStatusSink;
  /** Lifecycle signal propagated to queued tasks. */
  abortSignal?: AbortSignal;
  /** Best-effort sink for task failures after enqueueing. */
  onError?: (error: unknown) => void;
};
/** Bind a fixed account id into a status writer so lifecycle code can emit partial snapshots. */
declare function createAccountStatusSink(params: {
  accountId: string;
  setStatus: (next: ChannelAccountSnapshot) => void;
}): (patch: Omit<ChannelAccountSnapshot, "accountId">) => void;
/**
 * Serialize channel work per key while keeping lifecycle/busy accounting out of
 * channel-specific message handlers. The queue does not impose run timeouts;
 * callers should rely on session/tool/runtime lifecycle for long-running work.
 */
declare function createChannelRunQueue(params: ChannelRunQueueParams): ChannelRunQueue;
/**
 * Return a promise that resolves when the signal is aborted.
 *
 * If no signal is provided, the promise stays pending forever. When provided,
 * `onAbort` runs once before the promise resolves.
 */
declare function waitUntilAbort(signal?: AbortSignal, onAbort?: () => void | Promise<void>): Promise<void>;
/**
 * Keep a passive account task alive until abort, then run optional cleanup.
 */
declare function runPassiveAccountLifecycle<Handle>(params: PassiveAccountLifecycleParams<Handle>): Promise<void>;
/**
 * Keep a channel/provider task pending until the HTTP server closes.
 *
 * When an abort signal is provided, `onAbort` is invoked once and should
 * trigger server shutdown. The returned promise resolves only after `close`.
 */
declare function keepHttpServerTaskAlive(params: {
  server: CloseAwareServer;
  abortSignal?: AbortSignal;
  onAbort?: () => void | Promise<void>;
}): Promise<void>;
//#endregion
//#region src/infra/outbound/reply-media-entries.d.ts
/** Preserve attachment associations before media URLs are filtered or deduplicated. */
declare function collectReplyMediaEntries(payload: Pick<ReplyPayload$1, "mediaUrls" | "mediaUrl" | "attachments">, projectedMediaUrls?: readonly string[]): Array<{
  url: string;
  attachment: ReplyMediaAttachment | undefined;
  sourceUrls?: readonly string[];
}>;
//#endregion
//#region src/infra/outbound/sanitize-text.d.ts
/**
 * Convert common HTML tags to their plain-text/lightweight-markup equivalents
 * and strip anything that remains.
 *
 * The function is intentionally conservative — it only targets tags that models
 * are known to produce and avoids false positives on angle brackets in normal
 * prose (e.g. `a < b`), in fenced blocks, and in inline code spans.
 */
declare function sanitizeForPlainText(text: string, options?: {
  style?: "markdown";
}): string;
//#endregion
//#region src/channels/progress-work-counter.d.ts
/**
 * Per-turn work counters for live channel progress surfaces. These describe the
 * turn while it runs; nothing here survives into the finished transcript.
 */
declare function createChannelProgressWorkCounter(params?: {
  now?: () => number;
}): {
  noteItem(item: Partial<Pick<AgentItemEventData, "kind" | "hideFromChannelProgress" | "suppressChannelProgress">> & {
    phase?: string;
  }): void;
  noteToolCall(toolName?: string): void;
  reset(): void;
  readonly toolCalls: number;
  readonly elapsedSeconds: number;
};
//#endregion
//#region src/channels/progress-draft-compositor.d.ts
declare function createChannelProgressDraftCompositor(params: ChannelProgressDraftCompositorParams): {
  pushToolEvent: (payload: {
    itemId?: string;
    toolCallId?: string;
    name?: string;
    phase?: string;
    args?: Record<string, unknown>;
  } & {
    detailMode?: "explain" | "raw";
  }) => Promise<boolean>;
  pushCommandOutputEvent: (payload: {
    itemId?: string;
    toolCallId?: string;
    phase?: string;
    title?: string;
    name?: string;
    status?: string;
    exitCode?: number | null;
  }) => Promise<boolean>;
  pushPatchEvent: (payload: {
    itemId?: string;
    toolCallId?: string;
    phase?: string;
    title?: string;
    name?: string;
    added?: string[];
    modified?: string[];
    deleted?: string[];
    summary?: string;
  }) => Promise<boolean>;
  previewToolProgressEnabled: boolean;
  commentaryProgressEnabled: boolean;
  suppressDefaultToolProgressMessages: boolean;
  hasStarted: boolean;
  isVisible: boolean;
  hasStatusHeadline: boolean;
  hasPlanProgress: boolean;
  getSnapshot: () => ChannelProgressDraftCompositorSnapshot;
  getText: () => string;
  markFinalReplyStarted(): void;
  markFinalReplyDelivered(): void;
  beginNewTurn(options?: {
    force?: boolean;
  }): boolean;
  reset(): void;
  resetActivity(options?: {
    suppressed?: boolean;
  }): void;
  beginAssistantMessage(): void;
  resetReasoningProgress(this: void): void;
  mergeReasoningProgress: (this: void, text?: string, options?: {
    snapshot?: boolean;
  }) => string;
  suppress(): void;
  cancel(): void;
  start(): Promise<void>;
  noteActivity(options?: {
    startImmediately?: boolean;
  }): Promise<boolean>;
  pushToolProgress: (line?: ChannelProgressDraftCompositorLine, options?: {
    toolName?: string;
    startImmediately?: boolean;
    flush?: boolean;
  }) => Promise<boolean>;
  pushItemEvent: (payload: Parameters<(payload: ItemProgressPayload) => Promise<boolean>>[0]) => Promise<boolean>;
  pushApprovalEvent(payload: Parameters<(payload: {
    approvalId?: string;
    phase?: string;
    title?: string;
    command?: string;
    reason?: string;
    message?: string;
  }) => Promise<boolean>>[0]): Promise<boolean>;
  pushPlanProgress(steps?: AgentPlanStep[], options?: {
    explanation?: string;
    explanationFormat?: "plain";
  }): Promise<boolean>;
  pushPreambleHeadline(text?: string, options?: {
    itemId?: string;
  }): Promise<boolean>;
  pushNarrationProgress(text?: string): Promise<boolean>;
  pushReasoningProgress(text?: string, options?: {
    snapshot?: boolean;
  }): Promise<boolean>;
  pushCommentaryProgress(text?: string, options?: {
    itemId?: string;
    complete?: boolean;
  }): Promise<boolean>;
};
//#endregion
//#region src/channels/message/capabilities.d.ts
/** Derives the adapter capabilities core needs before it can require durable final delivery. */
declare function deriveDurableFinalDeliveryRequirements(params: DeriveDurableFinalDeliveryRequirementsParams): DurableFinalDeliveryRequirementMap;
//#endregion
//#region src/channels/message/adapter.d.ts
declare const defaultManualReceiveAdapter: {
  readonly defaultAckPolicy: "manual";
  readonly supportedAckPolicies: readonly ["manual"];
};
type ChannelMessageAdapterWithDefaultReceive<TAdapter extends ChannelMessageAdapterShape> = TAdapter & {
  receive: TAdapter["receive"] extends undefined ? typeof defaultManualReceiveAdapter : NonNullable<TAdapter["receive"]>;
};
/** Defines a message adapter while defaulting receive acknowledgement to manual. */
declare function defineChannelMessageAdapter<const TAdapter extends ChannelMessageAdapterShape>(adapter: TAdapter): ChannelMessageAdapter<ChannelMessageAdapterWithDefaultReceive<TAdapter>>;
//#endregion
//#region src/channels/message/outbound-bridge.d.ts
/** Send result accepted from legacy outbound bridge methods before receipt normalization. */
type ChannelMessageOutboundBridgeResult = MessageReceiptSourceResult & {
  receipt?: MessageReceipt;
  messageId?: string;
};
type ChannelMessageOutboundBridgeContext<TContext> = Omit<TContext, "onDeliveryResult"> & {
  onDeliveryResult?: (result: ChannelMessageOutboundBridgeResult) => Promise<void> | void;
};
/** Legacy outbound adapter shape bridged into the channel message adapter contract. */
type ChannelMessageOutboundBridgeAdapter<TConfig = unknown> = {
  deliveryCapabilities?: {
    durableFinal?: DurableFinalDeliveryRequirementMap;
  };
  sendText?: (ctx: ChannelMessageOutboundBridgeContext<ChannelMessageSendTextContext<TConfig>>) => Promise<ChannelMessageOutboundBridgeResult>;
  sendMedia?: (ctx: ChannelMessageOutboundBridgeContext<ChannelMessageSendMediaContext<TConfig>>) => Promise<ChannelMessageOutboundBridgeResult>;
  sendPayload?: (ctx: ChannelMessageOutboundBridgeContext<ChannelMessageSendPayloadContext<TConfig>>) => Promise<ChannelMessageOutboundBridgeResult>;
  sendPoll?: (ctx: ChannelMessageOutboundBridgeContext<ChannelMessageSendPollContext<TConfig>>) => Promise<ChannelMessageOutboundBridgeResult>;
};
/** Options for building a message adapter from legacy outbound send functions. */
type CreateChannelMessageAdapterFromOutboundParams<TConfig = unknown> = {
  id?: string;
  outbound: ChannelMessageOutboundBridgeAdapter<TConfig>;
  capabilities?: DurableFinalDeliveryRequirementMap;
  live?: ChannelMessageLiveAdapterShape;
  receive?: ChannelMessageReceiveAdapterShape;
};
/** Converts legacy outbound send methods into a typed channel message adapter. */
declare function createChannelMessageAdapterFromOutbound<TConfig = unknown>(params: CreateChannelMessageAdapterFromOutboundParams<TConfig>): ChannelMessageAdapterShape<TConfig>;
//#endregion
//#region src/channels/message/durable-receive.d.ts
/** Pending inbound receive record kept until agent dispatch or durable send completes. */
type DurableInboundReceivePendingRecord<TPayload, TMetadata = unknown> = Omit<ChannelIngressQueueRecord<TPayload, TMetadata>, "channelId" | "accountId" | "queueName" | "laneKey">;
type DurableInboundReceiveAcceptResult<TPayload, TMetadata, TCompletedMetadata> = {
  kind: "accepted";
  duplicate: false;
  record: DurableInboundReceivePendingRecord<TPayload, TMetadata>;
} | {
  kind: "pending";
  duplicate: true;
  record: DurableInboundReceivePendingRecord<TPayload, TMetadata>;
} | {
  kind: "completed";
  duplicate: true;
  record: Pick<ChannelIngressQueueCompletedRecord<TCompletedMetadata>, "id" | "completedAt" | "metadata">;
};
type DurableInboundReceiveJournal<TPayload, TMetadata, TCompletedMetadata> = {
  accept(id: string, payload: TPayload, options?: {
    metadata?: TMetadata;
    receivedAt?: number;
  }): Promise<DurableInboundReceiveAcceptResult<TPayload, TMetadata, TCompletedMetadata>>;
  pending(): Promise<Array<DurableInboundReceivePendingRecord<TPayload, TMetadata>>>;
  complete(id: string, options?: {
    metadata?: TCompletedMetadata;
    completedAt?: number;
  }): Promise<void>;
  release(id: string, options?: {
    lastError?: string;
    releasedAt?: number;
  }): Promise<boolean>;
  deletePending(id: string): Promise<boolean>;
};
declare function createDurableInboundReceiveJournalFromQueue<TPayload, TMetadata = unknown, TCompletedMetadata = unknown>(options: {
  queue: ChannelIngressQueue<TPayload, TMetadata, TCompletedMetadata>;
  retention?: ChannelIngressQueuePruneOptions;
}): DurableInboundReceiveJournal<TPayload, TMetadata, TCompletedMetadata>;
//#endregion
//#region src/channels/message/contracts.d.ts
type ContractProofs<TKey extends string> = Partial<Record<TKey, () => Promise<void> | void>>;
type ProofStatus = "verified" | "not_declared";
type CapabilityProofResult<TKey extends string> = {
  capability: TKey;
  status: ProofStatus;
};
declare function verifyDurableFinalCapabilityProofs(params: {
  adapterName: string;
  capabilities?: DurableFinalDeliveryRequirementMap;
  proofs: ContractProofs<DurableFinalDeliveryCapability>;
}): Promise<CapabilityProofResult<DurableFinalDeliveryCapability>[]>;
declare function verifyChannelMessageAdapterCapabilityProofs(params: {
  adapterName: string;
  adapter: Pick<ChannelMessageAdapterShape, "durableFinal">;
  proofs: ContractProofs<DurableFinalDeliveryCapability>;
}): Promise<CapabilityProofResult<DurableFinalDeliveryCapability>[]>;
declare function verifyChannelMessageReceiveAckPolicyAdapterProofs(params: {
  adapterName: string;
  adapter: Pick<ChannelMessageAdapterShape, "receive">;
  proofs: ContractProofs<ChannelMessageReceiveAckPolicy>;
}): Promise<{
  policy: ChannelMessageReceiveAckPolicy;
  status: ProofStatus;
}[]>;
declare function verifyChannelMessageLiveFinalizerProofs(params: {
  adapterName: string;
  adapter: Pick<ChannelMessageAdapterShape, "live">;
  proofs: ContractProofs<LivePreviewFinalizerCapability>;
}): Promise<CapabilityProofResult<LivePreviewFinalizerCapability>[]>;
declare function verifyChannelMessageLiveCapabilityAdapterProofs(params: {
  adapterName: string;
  adapter: Pick<ChannelMessageAdapterShape, "live">;
  proofs: ContractProofs<ChannelMessageLiveCapability>;
}): Promise<CapabilityProofResult<ChannelMessageLiveCapability>[]>;
//#endregion
//#region src/channels/message/live.d.ts
/** A transport-owned preview. discardPending must stop new work before awaiting in-flight work. */
type LivePreviewFinalizerDraft<TId> = {
  flush: () => Promise<void>;
  id: () => TId | undefined;
  seal?: () => Promise<void>;
  discardPending?: () => Promise<void>;
  clear: () => Promise<void>;
};
type LivePreviewDraft<TId> = Omit<LivePreviewFinalizerDraft<TId>, "clear"> & {
  clear: () => Promise<boolean | void>;
};
type LivePreviewDeliveryResult = ChannelDeliveryResult & {
  visibleReplySent: boolean;
};
type PreviewSendResult = LivePreviewDeliveryResult | boolean | void;
type LivePreviewFinalizerResultKind = "normal-delivered" | "normal-skipped" | "preview-finalized" | "preview-retained";
type LivePreviewFinalizerResult<TPayload> = {
  kind: LivePreviewFinalizerResultKind;
  liveState?: LiveMessageState<TPayload>;
  deliveryResult?: LivePreviewDeliveryResult;
};
type PublishedPreviewAdapter<TPayload, TId, TEdit> = {
  draft?: LivePreviewFinalizerDraft<TId>;
  buildFinalEdit: (payload: TPayload) => TEdit | undefined;
  editFinal: (id: TId, edit: TEdit) => Promise<void>;
  resolveFinalizedId?: (id: TId, edit: TEdit) => TId | undefined;
  createPreviewReceipt?: (id: TId, edit: TEdit) => MessageReceipt;
  onPreviewFinalized?: (id: TId, receipt: MessageReceipt, liveState: LiveMessageState<TPayload>) => Promise<void> | void;
  buildSupplementalPayload?: (payload: TPayload) => TPayload | undefined;
  deliverSupplemental?: (payload: TPayload) => Promise<boolean | void>;
  handlePreviewEditError?: (params: {
    error: unknown;
    id: TId;
    edit: TEdit;
    payload: TPayload;
    liveState: LiveMessageState<TPayload>;
  }) => "fallback" | "retain" | Promise<"fallback" | "retain">;
  logPreviewEditFailure?: (error: unknown) => void;
};
type FinalizableLivePreviewAdapter<TPayload, TId, TEdit> = Omit<PublishedPreviewAdapter<TPayload, TId, TEdit>, "draft" | "buildFinalEdit" | "editFinal" | "deliverSupplemental"> & {
  draft?: LivePreviewDraft<TId>;
  buildFinalEdit?: (payload: TPayload) => TEdit | undefined;
  editFinal?: (id: TId, edit: TEdit) => Promise<void | LivePreviewDeliveryResult>;
  deliverSupplemental?: (payload: TPayload) => Promise<PreviewSendResult>;
};
declare function defineFinalizableLivePreviewAdapter<TPayload, TId, TEdit>(adapter: PublishedPreviewAdapter<TPayload, TId, TEdit>): PublishedPreviewAdapter<TPayload, TId, TEdit>;
declare function createPreviewMessageReceipt(params: {
  id: unknown;
  threadId?: string;
  replyToId?: string;
  sentAt?: number;
  raw?: unknown;
}): MessageReceipt;
/** Published adapter contract; shares the stateful owner's delivery implementation. */
declare function deliverWithFinalizableLivePreviewAdapter<TPayload, TId, TEdit>(params: {
  kind: "tool" | "block" | "final";
  payload: TPayload;
  liveState?: LiveMessageState<TPayload>;
  adapter?: PublishedPreviewAdapter<TPayload, TId, TEdit>;
  deliverNormally: (payload: TPayload) => Promise<boolean | void>;
  onNormalDelivered?: () => Promise<void> | void;
}): Promise<LivePreviewFinalizerResult<TPayload>>;
type LivePreviewLifecycle<TPayload, TId> = {
  readonly previewFinalized: boolean;
  readonly finalDelivered: boolean;
  readonly finalSucceeded: boolean;
  readonly finalFailed: boolean;
  readonly finalStarted: boolean;
  readonly finalSuppressed: boolean;
  beginFinalDelivery: () => void;
  deliver<TEdit = never>(params: {
    kind: "tool" | "block" | "final";
    payload: TPayload;
    isError?: boolean;
    adapter?: Omit<FinalizableLivePreviewAdapter<TPayload, TId, TEdit>, "draft">;
    deliverNormally: (payload: TPayload) => Promise<LivePreviewDeliveryResult>;
    onNormalDelivered?: () => Promise<void> | void;
  }): Promise<LivePreviewFinalizerResult<TPayload>>;
  observeDelivery: (result: LivePreviewDeliveryResult, options?: {
    isError?: boolean;
  }) => Promise<void>;
  observeFailure: (result?: LivePreviewDeliveryResult) => void;
  observeSuppression: () => void;
  cleanup: (options?: {
    failed?: boolean;
  }) => Promise<void>;
  retainPreview: () => void;
  reset: () => void;
};
/** Owns one admitted turn's final facts and preview custody, not provider wire semantics. */
declare function createLivePreviewLifecycle<TPayload, TId>(options?: {
  draft?: LivePreviewDraft<TId>;
  retainOnError?: boolean;
  cleanupUndelivered?: boolean;
  onFinalStarted?: () => void;
  onFinalDelivered?: () => void;
  onCleanupFailure?: (error: unknown) => void;
}): LivePreviewLifecycle<TPayload, TId>;
//#endregion
//#region src/channels/message/receive.d.ts
type MessageAckPolicy = ChannelMessageReceiveAckPolicy;
type MessageAckStage = "receive_record" | "agent_dispatch" | "durable_send" | "manual";
type MessageAckState = "pending" | "acked" | "nacked";
/** Mutable receive context passed through durable inbound message processing. */
type MessageReceiveContext<TMessage = unknown> = {
  id: string;
  channel: string;
  accountId?: string;
  message: TMessage;
  ackPolicy: MessageAckPolicy;
  ackState: MessageAckState;
  ackedAt?: number;
  nackErrorMessage?: string;
  receivedAt: number;
  signal: AbortSignal;
  shouldAckAfter(stage: MessageAckStage): boolean;
  ack(): Promise<void>;
  nack(error: unknown): Promise<void>;
};
/** Creates a receive context with idempotent ack and explicit nack state transitions. */
declare function createMessageReceiveContext<TMessage>(params: {
  id: string;
  channel: string;
  accountId?: string;
  message: TMessage;
  ackPolicy?: MessageAckPolicy;
  receivedAt?: number;
  signal?: AbortSignal;
  onAck?: () => Promise<void> | void;
  onNack?: (error: unknown) => Promise<void> | void;
}): MessageReceiveContext<TMessage>;
//#endregion
//#region src/channels/streaming-final-text.d.ts
declare function isPotentialTruncatedFinal(finalText: string): boolean;
declare function selectLongerFinalText(params: {
  finalText: string;
  candidateTexts: readonly (string | undefined)[];
}): string | undefined;
declare function resolveTranscriptBackedChannelFinalText(params: {
  payload?: ReplyPayload$1;
  finalText: string;
  resolveCandidateText: () => Promise<string | undefined>;
}): Promise<string>;
//#endregion
//#region src/plugin-sdk/channel-outbound.d.ts
type ChannelDurableDeliveryModule = typeof durable_delivery_d_exports;
/** Keep the current operation media selection when recovering other reply fields. */
declare function preserveReplyPayloadMediaSelection(source: ReplyPayload, recovered: ReplyPayload): ReplyPayload;
/** @deprecated The streaming.progress.render key was retired (#122927). */
type ChannelProgressDraftRenderMode = "rich" | "text";
/**
 * @deprecated Load-only bridge: the published Slack channel package
 * (2026.7.2-beta.7 and earlier) imports this at module top level, so removing
 * it makes the installed plugin fail to load after a core upgrade. The config
 * key it read is retired and doctor strips it, so this resolves the same
 * "text"/"rich" answer pre-doctor configs produced and the default otherwise.
 * Remove once managed releases have replaced the old npm latest/extended-stable
 * packages and their upgrade window has closed.
 */
declare function resolveChannelProgressDraftRender(entry: StreamingCompatEntry | null | undefined, defaultValue?: ChannelProgressDraftRenderMode): ChannelProgressDraftRenderMode;
/** Lazily forwards inbound reply delivery through the channel turn durable-delivery module. */
declare const deliverInboundReplyWithMessageSendContext: ChannelDurableDeliveryModule["deliverInboundReplyWithMessageSendContextCore"];
/** Delivers a producer's prepared plan without reparsing literal text. */
declare const deliverStructuredInboundReplyWithMessageSendContext: ChannelDurableDeliveryModule["deliverStructuredInboundReplyWithMessageSendContextCore"];
/** Sends a durable message batch without eager-loading channel message runtime internals. */
declare function sendDurableMessageBatch(
/**
 * Durable send context and outbound batch data forwarded to the channel runtime.
 */
params: DurableMessageSendContextParams): Promise<DurableMessageBatchSendResult>;
/** Runs work inside a durable message send context loaded through the SDK lazy boundary. */
declare function withDurableMessageSendContext<T>(
/**
 * Durable send context used to bind sends, receipts, and lifecycle callbacks.
 */
params: DurableMessageSendContextParams,
/**
 * Callback executed with the loaded durable-send runtime context.
 */
run: (ctx: DurableMessageSendContext) => Promise<T>): Promise<T>;
//#endregion
//#region extensions/telegram/src/bot/types.d.ts
type TelegramChatDetails = {
  id?: number | string;
  available_reactions?: ChatFullInfo["available_reactions"] | null;
  is_forum?: boolean;
};
type TelegramGetChat = (chatId: number | string) => Promise<TelegramChatDetails>;
interface StickerMetadata {
  emoji?: string;
  setName?: string;
  /** Telegram file_id for sending the sticker back. */
  fileId?: string;
  /** Stable file_unique_id for cache deduplication. */
  fileUniqueId?: string;
  /** Cached description from previous vision processing (skip re-processing if present). */
  cachedDescription?: string;
}
//#endregion
//#region extensions/telegram/src/preview-streaming.d.ts
declare function resolveTelegramPreviewStreamMode(params?: {
  streaming?: unknown;
}): StreamingMode;
//#endregion
//#region extensions/telegram/src/bot/helpers.d.ts
type TelegramThreadParams = {
  direct_messages_topic_id?: number;
  message_thread_id?: number;
};
declare function extractTelegramForumFlag(value: unknown): boolean | undefined;
declare function resolveTelegramForumFlag(params: {
  chatId: string | number;
  chatType?: Chat["type"];
  isGroup: boolean;
  isForum?: boolean;
  isTopicMessage?: boolean;
  getChat?: TelegramGetChat;
}): Promise<boolean>;
declare function withResolvedTelegramForumFlag<T extends {
  chat: object;
}>(message: T, isForum: boolean): T;
declare function resolveTelegramGroupAllowFromContext(params: {
  cfg: OpenClawConfig;
  chatId: string | number;
  accountId?: string;
  dmPolicy?: DmPolicy;
  allowFrom?: Array<string | number>;
  senderId?: string;
  isGroup?: boolean;
  isForum?: boolean;
  messageThreadId?: number | null;
  threadSpec?: TelegramThreadSpec;
  groupAllowFrom?: Array<string | number>;
  skipPairingStoreRead?: boolean;
  readChannelAllowFromStore?: typeof readChannelAllowFromStore;
  resolveTelegramGroupConfig: TelegramGroupConfigResolver;
}): Promise<{
  threadSpec: TelegramThreadSpec;
  resolvedThreadId?: number;
  dmThreadId?: number;
  storeAllowFrom: string[];
  groupConfig?: TelegramGroupConfig | TelegramDirectConfig;
  topicConfig?: TelegramTopicConfig;
  groupAllowOverride?: Array<string | number>;
  effectiveGroupAllow: NormalizedAllowFrom;
  hasGroupAllowOverride: boolean;
}>;
declare function resolveTelegramForumThreadId(params: {
  isForum?: boolean;
  messageThreadId?: number | null;
}): number | undefined;
declare function resolveTelegramThreadSpec(params: {
  isGroup: boolean;
  isForum?: boolean;
  messageThreadId?: number | null;
}): TelegramThreadSpec;
declare function buildTelegramThreadParams(thread?: TelegramThreadSpec | null): TelegramThreadParams | undefined;
declare function buildTelegramRoutingTarget(chatId: number | string, thread?: TelegramThreadSpec | null): string;
declare function buildTypingThreadParams(messageThreadId?: number): {
  message_thread_id: number;
} | undefined;
declare function buildTelegramGroupPeerId(chatId: number | string, thread?: number | TelegramThreadSpec): string;
declare function buildTelegramGroupFrom(chatId: number | string, thread?: number | TelegramThreadSpec): string;
declare function buildTelegramParentPeer(params: {
  isGroup: boolean;
  resolvedThreadId?: number;
  chatId: number | string;
}): {
  kind: "group";
  id: string;
} | undefined;
declare function buildGroupLabel(msg: Message, chatId: number | string, messageThreadId?: number): string;
type TelegramReplyTarget = {
  id?: string;
  sender: string;
  senderId?: string;
  senderUsername?: string;
  body?: string;
  mediaType?: TelegramMediaKind;
  kind: "reply" | "quote";
  source: "reply_to_message" | "external_reply";
  quoteText?: string;
  quotePosition?: number;
  quoteEntities?: TelegramTextEntity[];
  /** Forward context if the reply target was itself a forwarded message (issue #9619). */
  forwardedFrom?: TelegramForwardedContext;
  quoteSourceText?: string;
  quoteSourceEntities?: TelegramTextEntity[];
};
declare function describeReplyTarget(msg: Message): TelegramReplyTarget | null;
//#endregion
//#region extensions/telegram/src/prompt-context-projection.d.ts
type TelegramPromptContextSource = {
  transcriptMessageId: string;
};
type TelegramPromptContextProjection = TelegramPromptContextSource & {
  partIndex: number;
  finalPart: boolean;
};
declare function createTelegramPromptContextProjectionCursor(source: TelegramPromptContextSource): {
  source: TelegramPromptContextSource;
  nextPartIndex: number;
  complete: boolean;
  invalidate(): void;
  take(finalPart: boolean): TelegramPromptContextProjection;
};
//#endregion
//#region extensions/telegram/src/rich-block-model.d.ts
type RichText = string | RichText[] | {
  type: "bold" | "italic" | "underline" | "strikethrough" | "code" | "spoiler" | "marked" | "subscript" | "superscript";
  text: RichText;
} | {
  type: "url";
  text: RichText;
  url: string;
} | {
  type: "text_mention";
  text: RichText;
  user: User;
} | {
  type: "anchor_link";
  text: RichText;
  anchor_name: string;
} | {
  type: "mathematical_expression";
  expression: string;
} | {
  type: "custom_emoji";
  custom_emoji_id: string;
  alternative_text: string;
};
type RichBlockTableCellAlign = "left" | "center" | "right";
type RichBlockTableCell = {
  text?: RichText;
  is_header?: true;
  colspan?: number;
  rowspan?: number;
  align: RichBlockTableCellAlign;
  valign: "top" | "middle" | "bottom";
};
type InputRichBlockParagraph = {
  type: "paragraph";
  text: RichText;
};
type RichBlockCaption = {
  text: RichText;
  credit?: RichText;
};
type InputRichBlockListItem = {
  blocks: InputRichBlock[];
  has_checkbox?: true;
  is_checked?: true;
  value?: number;
  type?: "a" | "A" | "i" | "I" | "1";
};
type InputMediaUrl<K extends string> = {
  type: K;
  media: string;
};
type InputRichBlock = InputRichBlockParagraph | {
  type: "heading";
  text: RichText;
  size: 1 | 2 | 3 | 4 | 5 | 6;
} | {
  type: "pre";
  text: string;
  language?: string;
} | {
  type: "blockquote";
  blocks: InputRichBlock[];
  credit?: RichText;
} | {
  type: "table";
  cells: RichBlockTableCell[][];
  is_bordered?: true;
  is_striped?: true;
  caption?: RichText;
} | {
  type: "divider";
} | {
  type: "anchor";
  name: string;
} | {
  type: "footer";
  text: RichText;
} | {
  type: "pullquote";
  text: RichText;
  credit?: RichText;
} | {
  type: "mathematical_expression";
  expression: string;
} | {
  type: "details";
  summary: RichText;
  blocks: InputRichBlock[];
  is_open?: true;
} | {
  type: "list";
  items: InputRichBlockListItem[];
} | {
  type: "photo";
  photo: InputMediaUrl<"photo">;
  caption?: RichBlockCaption;
} | {
  type: "video";
  video: InputMediaUrl<"video">;
  caption?: RichBlockCaption;
} | {
  type: "audio";
  audio: InputMediaUrl<"audio">;
  caption?: RichBlockCaption;
} | {
  type: "animation";
  animation: InputMediaUrl<"animation">;
  caption?: RichBlockCaption;
} | {
  type: "voice_note";
  voice_note: InputMediaUrl<"voice_note">;
  caption?: RichBlockCaption;
} | {
  type: "collage";
  blocks: InputRichBlock[];
  caption?: RichBlockCaption;
} | {
  type: "slideshow";
  blocks: InputRichBlock[];
  caption?: RichBlockCaption;
} | {
  type: "map";
  location: {
    latitude: number;
    longitude: number;
  };
  zoom: number;
  width: number;
  height: number;
  caption?: RichBlockCaption;
};
//#endregion
//#region extensions/telegram/src/rich-message.d.ts
type TelegramInputRichMessage = Omit<InputRichMessage, "blocks"> & {
  blocks: InputRichBlock[];
};
//#endregion
//#region extensions/telegram/src/send-context.d.ts
type TelegramApi = Bot["api"];
type TelegramApiOverride = Partial<TelegramApi>;
type TelegramApiContext = {
  cfg: OpenClawConfig;
  account: ResolvedTelegramAccount;
  ownerAgentId: string;
  api: TelegramApi;
};
//#endregion
//#region packages/media-understanding-common/src/active-model.d.ts
type ActiveMediaModel = {
  provider: string;
  model?: string;
  /** Effective API captured from the prepared model selection. */
  api?: string;
};
//#endregion
//#region src/media-understanding/audio-preflight.d.ts
type AudioPreflightParams = {
  ctx: RuntimeMsgContext;
  cfg: OpenClawConfig;
  assertCurrent?: () => void;
  agentDir?: string;
  workspaceDir?: string;
  providers?: Record<string, MediaUnderstandingProvider>;
  activeModel?: ActiveMediaModel;
};
/**
 * Transcribes the first audio attachment BEFORE mention checking.
 * This allows voice notes to be processed in group chats with requireMention: true.
 * Returns the transcript or undefined if transcription fails or no audio is found.
 */
declare function transcribeFirstAudio$1(params: AudioPreflightParams): Promise<string | undefined>;
//#endregion
//#region src/media-understanding/provider-execution.d.ts
type MediaExecutionContext = {
  signal: AbortSignal;
  assertCurrent: () => void;
};
//#endregion
//#region src/media-understanding/runner.d.ts
declare function resolveAutoImageModel$1(params: {
  cfg: OpenClawConfig;
  agentId?: string;
  agentDir?: string;
  workspaceDir?: string;
  activeModel?: ActiveMediaModel;
}): Promise<ActiveMediaModel | null>;
//#endregion
//#region src/media/audio.d.ts
/** Checks whether MIME type or filename is compatible with voice-message delivery. */
declare function isVoiceMessageCompatibleAudio(opts: {
  contentType?: string | null;
  fileName?: string | null;
}): boolean;
//#endregion
//#region packages/media-core/src/base64.d.ts
/** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */
declare function estimateBase64DecodedBytes(base64: string): number;
/**
 * Normalizes and validates a base64 string, returning canonical no-whitespace
 * base64 only when the input has valid alphabet, padding, and length.
 */
declare function canonicalizeBase64(base64: string): string | undefined;
//#endregion
//#region packages/media-core/src/content-length.d.ts
/** Parses a Content-Length header as a safe integer or rejects malformed values. */
declare function parseMediaContentLength(raw: string | null): number | null;
//#endregion
//#region src/media/store-path.d.ts
declare function getMediaDir(): string;
//#endregion
//#region src/media/fetch.d.ts
type FetchMediaResult = {
  buffer: Buffer;
  contentType?: string;
  fileName?: string;
};
type SavedRemoteMedia = SavedMedia & {
  fileName?: string;
};
type MediaFetchErrorCode = "max_bytes" | "http_error" | "fetch_failed";
/** Retry policy applied around the complete guarded fetch and body read/save operation. */
type MediaFetchRetryOptions = RetryOptions;
declare class MediaFetchError extends Error {
  readonly code: MediaFetchErrorCode;
  readonly status?: number;
  constructor(code: MediaFetchErrorCode, message: string, options?: {
    cause?: unknown;
    status?: number;
  });
}
type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
/** Alternate dispatcher/lookup pair tried inside a single guarded fetch attempt. */
type FetchDispatcherAttempt = {
  dispatcherPolicy?: PinnedDispatcherPolicy;
  lookupFn?: LookupFn;
};
type FetchMediaOptions = {
  url: string;
  fetchImpl?: FetchLike;
  /** Final synchronous check repeated for every media attempt and redirect. */
  beforeRequest?: GuardedFetchOptions["beforeRequest"];
  requestInit?: RequestInit;
  filePathHint?: string;
  maxBytes?: number;
  maxRedirects?: number;
  /** Require HTTPS for the initial URL and every redirect target. */
  requireHttps?: boolean;
  /** Abort the complete guarded fetch and body operation after this deadline (ms). */
  timeoutMs?: number;
  /** Abort if final response headers have not arrived by this deadline (ms). */
  responseHeaderTimeoutMs?: number;
  /** Abort if the response body stops yielding data for this long (ms). */
  readIdleTimeoutMs?: number;
  ssrfPolicy?: SsrFPolicy;
  lookupFn?: LookupFn;
  dispatcherPolicy?: PinnedDispatcherPolicy;
  dispatcherAttempts?: FetchDispatcherAttempt[];
  shouldRetryFetchError?: (error: unknown) => boolean;
  /**
   * Retries the complete guarded fetch/read-or-save operation. Dispatcher
   * attempts still run inside each retry attempt.
   */
  retry?: MediaFetchRetryOptions;
  /**
   * Allow an operator-configured explicit proxy to resolve target DNS after
   * hostname-policy checks instead of forcing local pinned-DNS first.
   */
  trustExplicitProxyDns?: boolean;
};
type SaveResponseMediaOptions = {
  sourceUrl?: string;
  filePathHint?: string;
  maxBytes?: number;
  readIdleTimeoutMs?: number;
  fallbackContentType?: string;
  subdir?: string;
  originalFilename?: string;
};
type SaveRemoteMediaOptions = FetchMediaOptions & {
  /** Revalidate caller-owned read authority through transport and file publication. */
  assertCurrent?: () => void;
  fallbackContentType?: string;
  subdir?: string;
  originalFilename?: string;
};
/** Validates and saves a caller-provided response without performing a new fetch. */
declare function saveResponseMedia(res: Response, options?: SaveResponseMediaOptions): Promise<SavedRemoteMedia>;
/** Fetches media through SSRF guards and saves the body into the media store. */
declare function saveRemoteMedia(options: SaveRemoteMediaOptions): Promise<SavedRemoteMedia>;
/** Preserve the public buffer result while internal text consumers retain decoder metadata. */
declare function readRemoteMediaBuffer(options: FetchMediaOptions): Promise<FetchMediaResult>;
/** @deprecated Use `readRemoteMediaBuffer` for buffer reads or `saveRemoteMedia` for URL-to-store. */
declare const fetchRemoteMedia: typeof readRemoteMediaBuffer;
//#endregion
//#region src/media/ffmpeg-limits.d.ts
/** Maximum audio duration accepted by ffmpeg-backed media flows. */
declare const MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS: number;
//#endregion
//#region src/media/audio-transcode.d.ts
/** Transcodes arbitrary audio input into mono Opus using a scoped temp workspace. */
declare function transcodeAudioBufferToOpus(params: {
  audioBuffer: Buffer;
  inputExtension?: string;
  inputFileName?: string;
  tempPrefix?: string;
  outputFileName?: string;
  timeoutMs?: number;
  sampleRateHz?: number;
  bitrate?: string;
  channels?: number;
  /** Maximum output duration passed to ffmpeg's `-t` option. */
  maxDurationSeconds?: number;
}): Promise<Buffer>;
/** Outcome for lightweight container transcodes that may be unsupported or intentionally skipped. */
type AudioContainerTranscodeOutcome = {
  ok: true;
  buffer: Buffer;
} | {
  ok: false;
  reason: "platform-unsupported" | "invalid-extension" | "noop-same-container" | "no-recipe" | "transcoder-failed";
  detail?: string;
};
/** Transcodes known audio container pairs, currently using macOS afconvert recipes where needed. */
declare function transcodeAudioBuffer(params: {
  audioBuffer: Buffer;
  sourceExtension: string;
  targetExtension: string;
  timeoutMs?: number;
}): Promise<AudioContainerTranscodeOutcome>;
//#endregion
//#region src/media/ffmpeg-exec.d.ts
/** Process limits and optional stdin payload for ffmpeg/ffprobe helper calls. */
type MediaExecOptions = {
  timeoutMs?: number;
  maxBufferBytes?: number;
  input?: Buffer | string;
  stdinFileDescriptor?: number;
};
/** Resolves ffmpeg from trusted system paths before command execution. */
declare function resolveFfmpegBin(): string;
/** Runs ffprobe with optional stdin input. */
declare function runFfprobe(args: string[], options?: MediaExecOptions): Promise<string>;
/** Runs ffmpeg with bounded timeout and buffer settings. */
declare function runFfmpeg(args: string[], options?: MediaExecOptions): Promise<string>;
/** Parses codec and positive sample rate from compact ffprobe stream output. */
declare function parseFfprobeCodecAndSampleRate(stdout: string): {
  codec: string | null;
  sampleRateHz: number | null;
};
//#endregion
//#region src/media/media-probe.d.ts
type VideoDimensions = {
  width: number;
  height: number;
};
/** Probes a video buffer while preserving the existing public media-runtime API. */
declare function probeVideoDimensions(buffer: Buffer): Promise<VideoDimensions | undefined>;
//#endregion
//#region src/media/outbound-attachment.d.ts
/** Loads a remote/local media URL and stages it into the outbound media store. */
declare function resolveOutboundAttachmentFromUrl(mediaUrl: string, maxBytes: number, options?: {
  mediaAccess?: OutboundMediaAccess;
  localRoots?: readonly string[];
  readFile?: (filePath: string) => Promise<Buffer>;
  /** Host-selected publication intent; does not grant file-read or delivery authority. */
  htmlPublication?: "explicit";
}): Promise<{
  path: string;
  contentType?: string;
}>;
//#endregion
//#region src/media/png-encode.d.ts
/**
 * Writes one RGBA pixel into a width-strided buffer.
 * Out-of-bounds coordinates are ignored so fixture drawing code can clip shapes cheaply.
 */
declare function fillPixel(buf: Buffer, x: number, y: number, width: number, r: number, g: number, b: number, a?: number): void;
/** Encodes tightly packed RGBA bytes (`width * height * 4`) as a PNG image. */
declare function encodePngRgba(buffer: Buffer, width: number, height: number): Buffer;
//#endregion
//#region src/media/qr-image.d.ts
type QrPngRenderOptions = {
  scale?: number;
  marginModules?: number;
};
/** Renders QR text as raw PNG base64 after validating bounded renderer options. */
declare function renderQrPngBase64(input: string, opts?: QrPngRenderOptions): Promise<string>;
declare function renderQrPngDataUrl(input: string, opts?: QrPngRenderOptions): Promise<string>;
/** Writes QR PNG output into a scoped temp directory and returns that directory as a media root. */
declare function writeQrPngTempFile(input: string,
/** Temp-file write options kept to filename segments so callers cannot choose parent paths. */
opts: QrPngRenderOptions & {
  tmpRoot: string;
  dirPrefix: string;
  fileName?: string;
}): Promise<{
  filePath: string;
  dirPath: string;
  mediaLocalRoots: string[];
}>;
//#endregion
//#region src/media/qr-terminal.d.ts
/** Renders QR text for terminal display, with an optional compact half-block mode. */
declare function renderQrTerminal(input: string, opts?: {
  small?: boolean;
}): Promise<string>;
//#endregion
//#region src/media/temp-files.d.ts
/** Best-effort temp-file cleanup helper for optional paths from media conversion flows. */
declare function unlinkIfExists(filePath: string | null | undefined): Promise<void>;
//#endregion
//#region src/channels/plugins/media-limits.d.ts
/** Resolves channel media limit bytes from account-specific config or agent defaults. */
declare function resolveChannelMediaMaxBytes(params: {
  cfg: OpenClawConfig;
  resolveChannelLimitMb: (params: {
    cfg: OpenClawConfig;
    accountId: string;
  }) => number | undefined;
  accountId?: string | null;
}): number | undefined;
//#endregion
//#region src/channels/plugins/outbound/direct-text-media.d.ts
type DirectSendOptions = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  replyToId?: string | null;
  mediaUrl?: string;
  mediaAccess?: OutboundMediaAccess;
  mediaLocalRoots?: readonly string[];
  mediaReadFile?: (filePath: string) => Promise<Buffer>;
  maxBytes?: number;
};
type DirectSendResult = {
  messageId: string;
  [key: string]: unknown;
};
type DirectSendFn<TOpts extends Record<string, unknown>, TResult extends DirectSendResult> = (to: string, text: string, opts: TOpts) => Promise<TResult>;
declare function createScopedChannelMediaMaxBytesResolver(channel: string): (params: {
  cfg: OpenClawConfig;
  accountId?: string | null;
}) => number | undefined;
declare function createDirectTextMediaOutbound<TOpts extends Record<string, unknown>, TResult extends DirectSendResult>(params: {
  channel: string;
  resolveSender: (deps: OutboundSendDeps | undefined) => DirectSendFn<TOpts, TResult>;
  resolveMaxBytes: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => number | undefined;
  buildTextOptions: (params: DirectSendOptions) => TOpts;
  buildMediaOptions: (params: DirectSendOptions) => TOpts;
}): ChannelOutboundAdapter;
//#endregion
//#region src/media-understanding/defaults.d.ts
/** Resolves the default provider model for a media capability from config or manifest metadata. */
declare function resolveDefaultMediaModel(params: {
  providerId: string;
  capability: MediaUnderstandingCapability;
  cfg?: OpenClawConfig;
  workspaceDir?: string;
  providerRegistry?: Map<string, MediaUnderstandingProvider>;
  includeConfiguredImageModels?: boolean;
}): string | undefined;
/** Resolves auto-discovery provider order for a media capability using manifest priorities. */
declare function resolveAutoMediaKeyProviders(params: {
  capability: MediaUnderstandingCapability;
  cfg?: OpenClawConfig;
  workspaceDir?: string;
  providerRegistry?: Map<string, MediaUnderstandingProvider>;
}): string[];
//#endregion
//#region src/plugin-sdk/media-runtime.d.ts
/** Transcribes the first audio attachment without loading the runner during plugin registration. */
declare const transcribeFirstAudio: typeof transcribeFirstAudio$1;
/** Resolves an image model through the media runner when selection is requested. */
declare const resolveAutoImageModel: typeof resolveAutoImageModel$1;
//#endregion
//#region extensions/telegram/src/send-message-types.d.ts
type TelegramSendOpts = {
  cfg: OpenClawConfig;
  token?: string;
  accountId?: string;
  verbose?: boolean;
  mediaUrl?: string;
  mediaUrls?: readonly string[];
  mediaAccess?: OutboundMediaAccess;
  mediaLocalRoots?: readonly string[];
  mediaReadFile?: (filePath: string) => Promise<Buffer>;
  gatewayClientScopes?: readonly string[];
  maxBytes?: number;
  api?: TelegramApiOverride;
  retry?: RetryConfig;
  textMode?: "markdown" | "html";
  tableMode?: MarkdownTableMode;
  textLimit?: number;
  chunkMode?: ChunkMode;
  /** Send audio as voice message instead of audio file. Defaults to false. */
  asVoice?: boolean;
  /** Send video as video note instead of regular video. Defaults to false. */
  asVideoNote?: boolean;
  /** Send message silently (no notification). Defaults to false. */
  silent?: boolean;
  /** Shared cursor keeps one transcript projection contiguous across concrete sends. */
  promptContextProjectionPlan?: {
    cursor: ReturnType<typeof createTelegramPromptContextProjectionCursor>;
    finalPart: boolean;
  };
  /** Message ID to reply to (for threading) */
  replyToMessageId?: number;
  /** Whether replyToMessageId came from ambient context or explicit payload/action input. */
  replyToIdSource?: "explicit" | "implicit";
  /** Controls whether replyToMessageId is applied to every internal text chunk. */
  replyToMode?: ReplyToMode;
  /** Quote text for Telegram reply_parameters. */
  quoteText?: string;
  /** Forum topic thread ID (for forum supergroups) */
  messageThreadId?: number;
  /** Channel Direct Messages topic ID. */
  directMessagesTopicId?: number;
  /** Inline keyboard buttons (reply markup). */
  buttons?: TelegramInlineButtons;
  /** Send image as document to avoid Telegram compression. Defaults to false. */
  forceDocument?: boolean;
  /** Persist each concrete platform send before any later chunk can fail. */
  onDeliveryResult?: (result: TelegramSendResult) => Promise<void> | void;
  /** @internal Cancel remaining physical sends for the current delivery. */
  signal?: AbortSignal;
  /** @internal Revalidate durable custody before a send operation, not after throttle waits. */
  onPlatformSendDispatch?: () => Promise<void>;
  /** @internal Synchronously fence custody after refresh and immediately before Telegram I/O. */
  assertPlatformSendAuthorized?: () => void;
};
type TelegramApiCallOpts = Pick<TelegramSendOpts, "cfg" | "token" | "accountId" | "verbose" | "api" | "retry" | "gatewayClientScopes">;
type TelegramThreadedSendOpts = TelegramApiCallOpts & Pick<TelegramSendOpts, "replyToMessageId" | "messageThreadId" | "assertPlatformSendAuthorized">;
type TelegramMessageActionOpts = TelegramApiCallOpts & Pick<TelegramSendOpts, "signal" | "assertPlatformSendAuthorized"> & {
  notify?: boolean;
};
type TelegramSendResult = {
  messageId: string;
  chatId: string;
  receipt?: MessageReceipt;
  meta?: {
    telegramDeliveredText?: string;
    telegramHasInlineKeyboard?: boolean;
  };
};
type TelegramLocationSendOpts = TelegramThreadedSendOpts & Pick<TelegramSendOpts, "buttons" | "quoteText" | "promptContextProjectionPlan" | "silent" | "onDeliveryResult" | "onPlatformSendDispatch" | "assertPlatformSendAuthorized">;
//#endregion
//#region extensions/telegram/src/send-actions.d.ts
type TelegramReactionOpts = Omit<TelegramMessageActionOpts, "notify"> & {
  remove?: boolean;
};
type TelegramTypingOpts = Omit<TelegramApiCallOpts, "gatewayClientScopes"> & Pick<TelegramSendOpts, "messageThreadId" | "signal" | "assertPlatformSendAuthorized">;
declare function sendTypingTelegram(to: string, opts: TelegramTypingOpts): Promise<{
  ok: true;
}>;
declare function reactMessageTelegram(chatIdInput: string | number, messageIdInput: string | number, emoji: string, opts: TelegramReactionOpts): Promise<{
  ok: true;
} | {
  ok: false;
  warning: string;
}>;
declare function deleteMessageTelegram(chatIdInput: string | number, messageIdInput: string | number, opts: TelegramMessageActionOpts): Promise<{
  ok: true;
} | {
  ok: false;
  warning: string;
}>;
declare function pinMessageTelegram(chatIdInput: string | number, messageIdInput: string | number, opts: TelegramMessageActionOpts): Promise<{
  ok: true;
  messageId: string;
  chatId: string;
}>;
declare function unpinMessageTelegram(chatIdInput: string | number, messageIdInput: string | number | undefined, opts: TelegramMessageActionOpts): Promise<{
  ok: true;
  chatId: string;
  messageId?: string;
}>;
//#endregion
//#region extensions/telegram/src/send-forum-topics.d.ts
type TelegramCreateForumTopicParams = NonNullable<Parameters<TelegramApiContext["api"]["createForumTopic"]>[2]>;
type TelegramEditForumTopicOpts = TelegramMessageActionOpts & {
  name?: string;
  iconCustomEmojiId?: string;
};
declare function editForumTopicTelegram(chatIdInput: string | number, messageThreadIdInput: string | number, opts: TelegramEditForumTopicOpts): Promise<{
  ok: true;
  chatId: string;
  messageThreadId: number;
  name?: string;
  iconCustomEmojiId?: string;
}>;
declare function renameForumTopicTelegram(chatIdInput: string | number, messageThreadIdInput: string | number, name: string, opts: TelegramMessageActionOpts): Promise<{
  ok: true;
  chatId: string;
  messageThreadId: number;
  name: string;
}>;
type TelegramCreateForumTopicOpts = TelegramApiCallOpts & Pick<TelegramMessageActionOpts, "assertPlatformSendAuthorized"> & {
  /** Icon color for the topic (must be one of 0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, 0xFB6F5F). */
  iconColor?: TelegramCreateForumTopicParams["icon_color"];
  /** Custom emoji ID for the topic icon. */
  iconCustomEmojiId?: string;
};
type TelegramCreateForumTopicResult = {
  topicId: number;
  name: string;
  chatId: string;
};
/** Requires the bot's can_manage_topics permission. */
declare function createForumTopicTelegram(chatId: string, name: string, opts: TelegramCreateForumTopicOpts): Promise<TelegramCreateForumTopicResult>;
//#endregion
//#region extensions/telegram/src/send-edit.d.ts
type TelegramEditReplyMarkupOpts = TelegramApiCallOpts & Pick<TelegramSendOpts, "buttons" | "signal" | "assertPlatformSendAuthorized">;
type TelegramEditOpts = TelegramEditReplyMarkupOpts & Pick<TelegramSendOpts, "textMode"> & {
  /** Native blocks prepared by the existing progress preview renderer. */
  richMessage?: TelegramInputRichMessage;
  /** Controls whether link previews are shown in the edited message. */
  linkPreview?: boolean;
  /** Use Telegram's media-caption edit endpoint, or fall back to it when text edits target media. */
  editMode?: "text" | "caption" | "auto";
};
declare function editMessageReplyMarkupTelegram(chatIdInput: string | number, messageIdInput: string | number, buttons: TelegramInlineButtons, opts: TelegramEditReplyMarkupOpts): Promise<{
  ok: true;
  messageId: string;
  chatId: string;
}>;
declare function editMessageTelegram(chatIdInput: string | number, messageIdInput: string | number, text: string, opts: TelegramEditOpts): Promise<{
  ok: true;
  messageId: string;
  chatId: string;
}>;
//#endregion
//#region extensions/telegram/src/send-location.d.ts
/** Send a standalone location pin or named venue through Telegram's native payload. */
declare function sendLocationTelegram(to: string, input: OutboundLocation, opts: TelegramLocationSendOpts): Promise<TelegramSendResult>;
//#endregion
//#region extensions/telegram/src/send-message.d.ts
declare function sendMessageTelegram(to: string, text: string, opts: TelegramSendOpts): Promise<TelegramSendResult>;
//#endregion
//#region extensions/telegram/src/send-special.d.ts
type TelegramPollSendResult = {
  messageId: string;
  chatId: string;
  pollId: string;
  pollAnswerRouting?: "enabled" | "unavailable";
  warning?: string;
};
declare function sendStickerTelegram(to: string, fileId: string, opts: TelegramThreadedSendOpts): Promise<TelegramSendResult>;
type TelegramPollOpts = TelegramThreadedSendOpts & Pick<TelegramSendOpts, "assertPlatformSendAuthorized" | "onPlatformSendDispatch" | "silent"> & {
  /** Whether votes are anonymous. Defaults to true (Telegram default). */
  isAnonymous?: boolean;
};
declare function sendPollTelegram(to: string, poll: PollInput, opts: TelegramPollOpts): Promise<TelegramPollSendResult>;
//#endregion
//#region src/plugin-sdk/runtime-store.d.ts
type PluginRuntimeStoreKeyOptions = {
  /** Explicit global registry key for shared runtime slots. */
  key: string;
  /** Error thrown by getRuntime before setRuntime initializes this slot. */
  errorMessage: string;
};
type PluginRuntimeStorePluginOptions = {
  /** Plugin id used to derive a stable cross-module runtime slot key. */
  pluginId: string;
  /** Error thrown by getRuntime before setRuntime initializes this slot. */
  errorMessage: string;
};
type PluginRuntimeStoreOptions = PluginRuntimeStoreKeyOptions | PluginRuntimeStorePluginOptions;
/**
 * Create a process-local runtime slot that throws when accessed before initialization.
 *
 * String keys create isolated module-local stores; option objects create global
 * named slots so duplicate SDK module instances share the same plugin runtime.
 */
declare function createPluginRuntimeStore<T>(errorMessage: string): {
  setRuntime: (next: T) => void;
  clearRuntime: () => void;
  tryGetRuntime: () => T | null;
  getRuntime: () => T;
};
/** Create a globally shared runtime slot keyed by plugin id or explicit registry key. */
declare function createPluginRuntimeStore<T>(options: PluginRuntimeStoreOptions): {
  setRuntime: (next: T) => void;
  clearRuntime: () => void;
  tryGetRuntime: () => T | null;
  getRuntime: () => T;
};
//#endregion
//#region packages/acp-core/src/runtime/errors.d.ts
declare const ACP_ERROR_CODES: readonly ["ACP_BACKEND_MISSING", "ACP_BACKEND_UNAVAILABLE", "ACP_BACKEND_UNSUPPORTED_CONTROL", "ACP_DISPATCH_DISABLED", "ACP_INVALID_RUNTIME_OPTION", "ACP_SESSION_INIT_FAILED", "ACP_TURN_FAILED"];
type AcpRuntimeErrorCode = (typeof ACP_ERROR_CODES)[number];
/** Error type used at ACP runtime boundaries so callers can preserve structured failure codes. */
declare class AcpRuntimeError extends Error {
  readonly code: AcpRuntimeErrorCode;
  /**
   * Backend-specific structured failure code (e.g. acpx "SESSION_RESUME_REQUIRED"),
   * preserved so recovery decisions key on the failure kind rather than parsing
   * the human-readable message.
   */
  readonly detailCode?: string;
  readonly cause?: unknown;
  constructor(code: AcpRuntimeErrorCode, message: string, options?: {
    cause?: unknown;
    detailCode?: string;
  });
}
//#endregion
//#region src/channels/plugins/setup-promotion-helpers.d.ts
type ChannelSetupPromotionSurface = Pick<ChannelSetupAdapter, "accountKeyPolicy" | "configPromotion" | "singleAccountKeysToMove" | "namedAccountPromotionKeys" | "resolveSingleAccountPromotionTarget">;
//#endregion
//#region src/channels/plugins/setup-helpers.d.ts
declare function applyAccountNameToChannelSection(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  accountId: string;
  name?: string;
  alwaysUseAccounts?: boolean;
}): OpenClawConfig;
/** Moves a root-level channel name into `accounts.default` before adding named accounts. */
declare function migrateBaseNameToDefaultAccount(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  alwaysUseAccounts?: boolean;
}): OpenClawConfig;
/** Applies setup-time account naming and optional root-name migration in one step. */
declare function prepareScopedSetupConfig(params: Parameters<typeof applyAccountNameToChannelSection>[0] & {
  migrateBaseName?: boolean;
}): OpenClawConfig;
/** Applies a setup patch using account-scoped config semantics. */
declare function applySetupAccountConfigPatch(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  accountId: string;
  patch: Record<string, unknown>;
}): OpenClawConfig;
/** Creates a setup adapter that turns validated setup input into an account config patch. */
declare function createPatchedAccountSetupAdapter<Input extends {
  name?: string;
} = ChannelSetupInput>(params: {
  channelKey: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  alwaysUseAccounts?: boolean;
  ensureChannelEnabled?: boolean;
  ensureAccountEnabled?: boolean;
  validateInput?: ChannelSetupAdapter<Input>["validateInput"];
  buildPatch: (input: Input) => Record<string, unknown>;
}): ChannelSetupAdapter<Input>;
type SetupInputPresenceRequirement = {
  someOf: string[];
  message: string;
};
declare function createSetupInputPresenceValidator<Input extends {
  name?: string;
  useEnv?: boolean;
} = ChannelSetupInput>(params: {
  defaultAccountOnlyEnvError?: string;
  whenNotUseEnv?: SetupInputPresenceRequirement[];
  validate?: NonNullable<ChannelSetupAdapter<Input>["validateInput"]>;
}): NonNullable<ChannelSetupAdapter<Input>["validateInput"]>;
/** Creates a setup adapter that supports env-backed default account auth and patched credentials. */
declare function createEnvPatchedAccountSetupAdapter(params: Parameters<typeof createPatchedAccountSetupAdapter<ChannelSetupInput>>[0] & {
  defaultAccountOnlyEnvError: string;
  missingCredentialError: string;
  hasCredentials: (input: ChannelSetupInput) => boolean;
}): ChannelSetupAdapter;
/** Patches channel config at root for default accounts or under `accounts.<id>` for named accounts. */
declare function patchScopedAccountConfig(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  accountId: string;
  patch: Record<string, unknown>;
  accountPatch?: Record<string, unknown>;
  clearFields?: readonly string[];
  ensureChannelEnabled?: boolean;
  ensureAccountEnabled?: boolean;
  scopeDefaultToAccounts?: boolean;
}): OpenClawConfig;
/**
 * Promotes legacy single-account channel fields into the account map for multi-account setup.
 */
declare function moveSingleAccountChannelSectionToDefaultAccount(params: {
  cfg: OpenClawConfig;
  channelKey: string;
  setupSurface?: ChannelSetupAdapter | ChannelSetupPromotionSurface;
}): OpenClawConfig;
//#endregion
//#region src/channels/plugins/config-helpers.d.ts
/**
 * Updates an account enabled flag in a channel config section.
 */
declare function setAccountEnabledInConfigSection(params: {
  cfg: OpenClawConfig;
  sectionKey: string;
  accountId: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  enabled: boolean;
  allowTopLevel?: boolean;
}): OpenClawConfig;
/**
 * Deletes one account from a channel config section, pruning empty channel/accounts objects.
 */
declare function deleteAccountFromConfigSection(params: {
  cfg: OpenClawConfig;
  sectionKey: string;
  accountId: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  clearBaseFields?: string[];
}): OpenClawConfig;
/**
 * Clears selected fields from one account entry and reports whether configured data was removed.
 */
declare function clearAccountEntryFields<TAccountEntry extends object>(params: {
  accounts?: Record<string, TAccountEntry>;
  channelId?: string;
  accountId: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  fields: string[];
  isValueSet?: (value: unknown) => boolean;
  markClearedOnFieldPresence?: boolean;
}): {
  nextAccounts?: Record<string, TAccountEntry>;
  changed: boolean;
  cleared: boolean;
};
/** Clear plugin-selected account fields and prune only the config branches changed by cleanup. */
declare function clearAccountFieldsFromConfigSection(params: {
  cfg: OpenClawConfig;
  sectionKey: string;
  accountId: string;
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  fields: string[];
  markClearedOnFieldPresence?: boolean;
}): {
  nextConfig: OpenClawConfig;
  changed: boolean;
  cleared: boolean;
};
//#endregion
//#region src/channels/plugins/pairing-message.d.ts
declare const PAIRING_APPROVED_MESSAGE = "✅ OpenClaw access approved. Send a message to start chatting.";
//#endregion
//#region src/channels/chat-meta-shared.d.ts
/**
 * Metadata shown for built-in chat channels in setup, status, and selection UIs.
 */
type ChatChannelMeta = ChannelMeta;
//#endregion
//#region src/channels/chat-meta.d.ts
/**
 * Returns metadata for one built-in chat channel id.
 * Shipped plugin-SDK contract: callers pass bundled ids, so absence is an invariant
 * violation; drift-tolerant core paths use findChatChannelMeta instead.
 */
declare function getChatChannelMeta(id: ChatChannelId): ChatChannelMeta;
//#endregion
//#region src/acp/persistent-bindings.types.d.ts
type ConfiguredAcpBindingChannel = ChannelId$1;
type ConfiguredAcpBindingSpec = {
  channel: ConfiguredAcpBindingChannel;
  accountId: string;
  conversationId: string;
  parentConversationId?: string;
  /** Owning OpenClaw agent id (used for session identity/storage). */
  agentId: string;
  /** ACP harness agent id override (falls back to agentId when omitted). */
  acpAgentId?: string;
  mode: AcpRuntimeSessionMode;
  model?: string;
  /** Owner agent's effective thinking default, forwarded as the ACP session's thinking runtime option. */
  thinking?: string;
  cwd?: string;
  backend?: string;
  label?: string;
};
type ResolvedConfiguredAcpBinding = {
  spec: ConfiguredAcpBindingSpec;
  record: SessionBindingRecord;
};
//#endregion
//#region src/plugin-sdk/channel-send-result.d.ts
/**
 * Legacy raw send result shape accepted from channel SDK adapters.
 * @deprecated Return `OutboundDeliveryResult` and use
 * `createAttachedChannelResultAdapter`. Removal with the next plugin-SDK major.
 */
type ChannelSendRawResult = {
  /** Whether the channel send operation succeeded. */
  ok: boolean;
  /** Platform message id; null/undefined normalizes to the empty-id sentinel. */
  messageId?: string | null;
  /** Legacy error text converted to an Error for outbound callers. */
  error?: string | null;
};
/** Attaches the channel id to a single outbound send result. */
declare function attachChannelToResult<T extends object>(
/** Channel id to stamp onto the returned delivery result. */
channel: string,
/** Delivery-shaped result without channel metadata. */
result: T): T & {
  channel: string;
};
/** Attaches the channel id to each outbound send result in order. */
declare function attachChannelToResults<T extends object>(
/** Channel id to stamp onto every returned delivery result. */
channel: string,
/** Ordered delivery-shaped results without channel metadata. */
results: readonly T[]): (T & {
  channel: string;
})[];
/** Creates an empty outbound delivery result for send paths that produced no platform id. */
declare function createEmptyChannelResult(
/** Channel id attached to the synthetic empty result. */
channel: string,
/** Additional delivery metadata to preserve alongside the empty message id. */
result?: Partial<Omit<OutboundDeliveryResult, "channel" | "messageId">> & {
  messageId?: string;
}): OutboundDeliveryResult;
type MaybePromise<T> = T | Promise<T>;
type SendTextParams = Parameters<NonNullable<ChannelOutboundAdapter["sendText"]>>[0];
type SendMediaParams = Parameters<NonNullable<ChannelOutboundAdapter["sendMedia"]>>[0];
type SendPollParams = Parameters<NonNullable<ChannelOutboundAdapter["sendPoll"]>>[0];
/** Wraps outbound send methods that already return delivery-shaped results without channel ids. */
declare function createAttachedChannelResultAdapter(params: {
  /** Channel id attached to every wrapped send result. */
  channel: string;
  /** Text sender that returns an outbound result without channel metadata. */
  sendText?: (ctx: SendTextParams) => MaybePromise<Omit<OutboundDeliveryResult, "channel">>;
  /** Media sender that returns an outbound result without channel metadata. */
  sendMedia?: (ctx: SendMediaParams) => MaybePromise<Omit<OutboundDeliveryResult, "channel">>;
  /** Poll sender that returns a poll result without channel metadata. */
  sendPoll?: (ctx: SendPollParams) => MaybePromise<Omit<ChannelPollResult, "channel">>;
}): Pick<ChannelOutboundAdapter, "sendText" | "sendMedia" | "sendPoll">;
/** Wraps legacy raw text/media send methods and normalizes their results. */
declare function createRawChannelSendResultAdapter(params: {
  /** Channel id attached to every normalized legacy send result. */
  channel: string;
  /** Legacy text sender that returns ok/messageId/error fields. */
  sendText?: (ctx: SendTextParams) => MaybePromise<ChannelSendRawResult>;
  /** Legacy media sender that returns ok/messageId/error fields. */
  sendMedia?: (ctx: SendMediaParams) => MaybePromise<ChannelSendRawResult>;
}): Pick<ChannelOutboundAdapter, "sendText" | "sendMedia">;
/** Normalize raw channel send results into the shape shared outbound callers expect. */
declare function buildChannelSendResult(
/** Channel id attached to the normalized delivery result. */
channel: string,
/** Legacy raw channel result to normalize. */
result: ChannelSendRawResult): {
  channel: string;
  ok: boolean;
  messageId: string;
  error: Error | undefined;
};
//#endregion
//#region packages/memory-host-sdk/src/host/remote-http.d.ts
/** Resolve current credentials for one request, or refresh after an expired-token rejection. */
type RemoteEmbeddingRequestAuth = (params: {
  forceRefresh: boolean;
  signal?: AbortSignal;
}) => Promise<Record<string, string>>;
//#endregion
//#region src/plugins/embedding-provider-types.d.ts
/** Input accepted by embedding providers, including multimodal inline-data parts. */
type EmbeddingInput$1 = string | {
  text: string;
  parts?: Array<{
    type: "text";
    text: string;
  } | {
    type: "inline-data";
    mimeType: string;
    data: string;
  }>;
};
/** Provider-reported token counts for one embedding request. */
type EmbeddingUsage = {
  promptTokens: number;
  totalTokens: number;
};
/** Per-call options passed to embedding provider calls. */
type EmbeddingProviderCallOptions = {
  signal?: AbortSignal;
  inputType?: "query" | "document" | "semantic" | "classification" | "clustering";
  /** The host applied an explicit query instruction; skip provider query templates. */
  queryInstructionApplied?: boolean;
  /** The host applied an explicit document format; skip provider document templates. */
  documentFormatApplied?: boolean;
  /** Report each successful upstream request before resolving; undefined means usage unavailable. */
  onUsage?: (usage: EmbeddingUsage | undefined) => void;
} & MemorySearchDeadlineControlOptions;
/** Runtime metadata returned with a created embedding provider. */
type EmbeddingProviderRuntime = {
  id: string;
  cacheKeyData?: Record<string, unknown>;
  /** Equivalent prior identities; alias cache reads require matching published index metadata. */
  indexIdentityAliases?: Array<{
    model: string;
    cacheKeyData: Record<string, unknown>;
  }>;
  inlineQueryTimeoutMs?: number;
  inlineBatchTimeoutMs?: number;
  /** Positive safe integer cap on simultaneous non-batch indexing jobs; omit for the host default. */
  inlineIndexConcurrency?: number;
} & Partial<EmbeddingProviderBatchRuntime>;
/** Provider-owned canonical identity and exact aliases for persisted indexes. */
type EmbeddingProviderIndexIdentity = {
  model: string;
  cacheKeyData: Record<string, unknown>;
  aliases?: Array<{
    model: string;
    cacheKeyData: Record<string, unknown>;
  }>;
};
/** Created embedding provider instance used by memory/search callers. */
type EmbeddingProvider = {
  id: string;
  model: string;
  dimensions?: number;
  maxInputTokens?: number;
  /** Positive safe integer cap for memory embedding requests; omit when the endpoint limit is unknown. */
  maxInputsPerRequest?: number;
  embed: (input: EmbeddingInput$1, options?: EmbeddingProviderCallOptions) => Promise<number[]>;
  embedBatch: (inputs: EmbeddingInput$1[], options?: EmbeddingProviderCallOptions) => Promise<number[][]>;
  close?: () => Promise<void> | void;
};
/** Options passed to embedding provider adapters when creating providers. */
type EmbeddingProviderCreateOptions = {
  config: OpenClawConfig;
  agentDir?: string;
  provider?: string;
  remote?: {
    baseUrl?: string;
    apiKey?: SecretInput;
    headers?: Record<string, string>;
  };
  model: string;
  inputType?: string;
  queryInputType?: string;
  documentInputType?: string;
  local?: {
    modelPath?: string;
    modelCacheDir?: string;
  };
  dimensions?: number;
  taskType?: string;
};
/** Result returned by an embedding provider adapter create call. */
type EmbeddingProviderCreateResult = {
  provider: EmbeddingProvider | null;
  runtime?: EmbeddingProviderRuntime;
};
/** Adapter contract registered by core or plugin embedding providers. */
type EmbeddingProviderAdapter = {
  id: string;
  /** Alternate lookup ids; creation and index identity retain the canonical id. */
  aliases?: readonly string[];
  defaultModel?: string;
  transport?: "local" | "remote";
  authProviderId?: string;
  /** Canonical model from config only: synchronous, without auth or network access. */
  normalizeModel?: (options: EmbeddingProviderCreateOptions) => string;
  resolveIndexIdentity?: (options: EmbeddingProviderCreateOptions) => EmbeddingProviderIndexIdentity;
  create: (options: EmbeddingProviderCreateOptions) => Promise<EmbeddingProviderCreateResult>;
  formatSetupError?: (err: unknown) => string;
};
//#endregion
//#region packages/memory-host-sdk/src/host/embeddings-remote-provider.d.ts
/** HTTP client details required by a remote embedding provider. */
type RemoteEmbeddingClient = {
  baseUrl: string;
  headers: Record<string, string>;
  ssrfPolicy?: SsrFPolicy;
  fetchImpl?: typeof fetch;
  resolveRequestHeaders?: RemoteEmbeddingRequestAuth;
  model: string;
};
//#endregion
//#region packages/memory-host-sdk/src/host/embedding-inputs.d.ts
/** Provider-facing input while preserving the plain text fallback. */
type EmbeddingInput = {
  text: string;
  parts?: Array<{
    type: "text";
    text: string;
  } | {
    type: "inline-data";
    mimeType: string;
    data: string;
  }>;
};
//#endregion
//#region src/plugins/registry-contribution-types.d.ts
type ContextEngineFactoryContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
};
type ContextEngineFactory = (ctx: ContextEngineFactoryContext) => ContextEngine | Promise<ContextEngine>;
type ContextEngineRegistrationLifecycle = "runtime" | "readOnlyDiscovery";
type ContextEngineRegistration = {
  factory: ContextEngineFactory;
  owner: string;
  lifecycle: ContextEngineRegistrationLifecycle;
};
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;
    previousSummary?: string;
  }): Promise<string>;
}
type RegisteredCompactionProvider = {
  provider: CompactionProvider;
  ownerPluginId?: string;
};
type MemoryEmbeddingBatchChunk = EmbeddingBatchChunk & {
  embeddingInput?: EmbeddingInput;
};
type MemoryEmbeddingBatchOptions = Omit<EmbeddingBatchOptions, "chunks"> & {
  chunks: MemoryEmbeddingBatchChunk[];
};
type MemoryEmbeddingProviderRuntime = Omit<EmbeddingProviderRuntime, "batchEmbed"> & {
  batchEmbed?: (options: MemoryEmbeddingBatchOptions) => Promise<number[][] | null>;
};
type MemoryEmbeddingProvider = EmbeddingProvider;
type MemoryEmbeddingProviderCreateOptions = Omit<EmbeddingProviderCreateOptions, "local"> & {
  fallback?: string;
  local?: NonNullable<EmbeddingProviderCreateOptions["local"]> & {
    contextSize?: number | "auto";
  };
};
type MemoryEmbeddingProviderCreateResult = Omit<EmbeddingProviderCreateResult, "runtime"> & {
  runtime?: MemoryEmbeddingProviderRuntime;
};
type MemoryEmbeddingProviderAdapter = Omit<EmbeddingProviderAdapter, "create"> & {
  autoSelectPriority?: number;
  allowExplicitWhenConfiguredAuto?: boolean;
  supportsMultimodalEmbeddings?: (params: {
    model: string;
  }) => boolean;
  create: (options: MemoryEmbeddingProviderCreateOptions) => Promise<MemoryEmbeddingProviderCreateResult>;
  shouldContinueAutoSelection?: (err: unknown) => boolean;
};
type MemoryPromptSectionParams = {
  availableTools: Set<string>;
  citationsMode?: MemoryCitationsMode;
  agentId?: string;
  agentSessionKey?: string;
  sandboxed?: boolean;
  /** Host-resolved repository identity for this run; the plugin owns any memory-format guidance. */
  projectKey?: string;
};
type MemoryPromptSectionBuilder = (params: MemoryPromptSectionParams) => string[];
/** Provider-owned /learn guidance for the tools tool policy leaves this turn; [] when it cannot learn. */
type MemoryLearnGuidanceBuilder = (params: {
  availableTools: Set<string>;
}) => string[];
type MemoryPromptSectionPreparer = (params: MemoryPromptSectionParams) => Promise<readonly string[]>;
type PreparedMemoryPromptSection = Readonly<{
  context: Readonly<{
    availableTools: readonly string[];
    citationsMode?: MemoryCitationsMode;
    agentId?: string;
    agentSessionKey?: string;
    sandboxed: boolean;
    projectKey?: string;
  }>;
  lines: readonly string[];
}>;
type MemoryCorpusSearchResult = {
  corpus: string;
  path: string;
  title?: string;
  kind?: string;
  score: number;
  snippet: string;
  id?: string;
  startLine?: number;
  endLine?: number;
  citation?: string;
  source?: string;
  provenanceLabel?: string;
  sourceType?: string;
  sourcePath?: string;
  updatedAt?: string;
};
type MemoryCorpusGetResult = {
  corpus: string;
  path: string;
  title?: string;
  kind?: string;
  content: string;
  fromLine: number;
  lineCount: number;
  id?: string;
  provenanceLabel?: string;
  sourceType?: string;
  sourcePath?: string;
  updatedAt?: string;
};
type MemoryCorpusSupplement = {
  search(params: {
    query: string;
    maxResults?: number;
    agentId?: string;
    agentSessionKey?: string;
    sandboxed?: boolean;
  }): Promise<MemoryCorpusSearchResult[]>;
  get(params: {
    lookup: string;
    fromLine?: number;
    lineCount?: number;
    agentId?: string;
    agentSessionKey?: string;
    sandboxed?: boolean;
  }): Promise<MemoryCorpusGetResult | null>;
};
type MemoryCorpusSupplementRegistration = {
  pluginId: string;
  supplement: MemoryCorpusSupplement;
};
type MemoryPromptSupplementRegistration = {
  pluginId: string;
  builder: MemoryPromptSectionBuilder;
};
type MemoryPromptPreparationRegistration = {
  pluginId: string;
  prepare: MemoryPromptSectionPreparer;
};
/** A file-persistence flush plan with its resolved timing. */
type MemoryFlushPlan = {
  softThresholdTokens: number;
  forceFlushTranscriptBytes: number;
  reserveTokensFloor: number;
  prompt: string;
  systemPrompt: string;
  relativePath: string;
};
/** Flush timing the host resolves from memory-flush config and the model context window. */
type MemoryFlushPlanTiming = Pick<MemoryFlushPlan, "softThresholdTokens" | "forceFlushTranscriptBytes" | "reserveTokensFloor">;
/**
 * A file plan as a resolver may return it: omitted timing fields are filled by the host, and
 * defined ones deliberately override it.
 */
type MemoryFlushFilePlanDraft = Omit<MemoryFlushPlan, keyof MemoryFlushPlanTiming> & Partial<MemoryFlushPlanTiming> & {
  persistenceToolNames?: never;
  lookupToolNames?: never;
};
/**
 * Tool persistence for the selected memory slot owner. The host fills omitted timing;
 * defined values deliberately override it.
 */
type MemoryFlushToolsPlan = Partial<MemoryFlushPlanTiming> & {
  prompt: string;
  systemPrompt: string;
  /** Absent on every tools plan; a tools plan never names a workspace file. */
  relativePath?: never;
  persistenceToolNames: readonly string[];
  /** Read-only helper tools the flush may use to inspect existing provider memory. */
  lookupToolNames?: readonly string[];
};
type MemoryFlushPlanResolverParams = {
  cfg?: OpenClawConfig;
  nowMs?: number;
  contextWindowTokens?: number;
};
/** Resolves a complete file flush plan. */
type MemoryFlushPlanResolver = (params: MemoryFlushPlanResolverParams) => MemoryFlushPlan | null;
/**
 * Resolves a flush plan the host completes: a file plan whose omitted timing the host fills,
 * or a tools plan that persists through the selected slot owner's own tools.
 */
type MemoryProviderFlushPlanResolver = (params: MemoryFlushPlanResolverParams) => MemoryFlushFilePlanDraft | MemoryFlushToolsPlan | null;
type RegisteredMemorySearchManager = Omit<MemorySearchManager, "readFile"> & {
  readFile(params: Parameters<MemorySearchManager["readFile"]>[0]): Promise<LegacyMemoryReadResult | MemoryReadResult>;
};
type MemoryRuntimeBackendConfig = {
  backend: "builtin";
};
type MemoryPluginRuntime = {
  /** CLI search and recall recording run under the same plugin instance. */
  searchForCli?(params: MemoryCliSearchParams): Promise<MemoryCliSearchResult>;
  getMemorySearchManager(params: {
    cfg: OpenClawConfig;
    agentId: string;
    purpose?: "default" | "status" | "cli";
    /** Request a read-only source freshness scan; runtimes may ignore unsupported diagnostics. */
    inspectSources?: boolean;
  }): Promise<{
    manager: RegisteredMemorySearchManager | null;
    debug?: {
      backend?: "builtin";
      purpose?: "default" | "status" | "cli";
      managerMs?: number;
    };
    error?: string;
  }>;
  resolveMemoryBackendConfig(params: {
    cfg: OpenClawConfig;
    agentId: string;
  }): MemoryRuntimeBackendConfig;
  /** Authorize raw hits before caller-visible use; absent runtimes must not expose session hits. */
  authorizeSearchHits?(params: {
    cfg: OpenClawConfig;
    agentId: string;
    requesterSessionKey: string | undefined;
    sandboxed: boolean;
    hits: MemorySearchResult[];
    /** A sessionless host or operator caller acting for `agentId` may keep only that agent's hits. */
    trustedAgentScope?: boolean;
    /** The session caller's host-granted recall pass, exactly as its tool context received it. */
    conversationRecall?: ConversationRecallContext;
  }): Promise<MemorySearchResult[]>;
  /** The classifier consumes pinned read sources without probing Gateway-local paths. */
  supportsWorkspaceMemoryReadSources?: true;
  classifyWorkspaceMemoryPaths?(params: {
    cfg: OpenClawConfig;
    agentId: string;
    workspaceDir: string;
    relativePaths: string[];
    /** Already-read remote files; an absent canonical path must remain untrusted. */
    readSources?: readonly {
      relativePath: string;
      canonicalRelativePath?: string;
    }[];
  }): Promise<Array<{
    relativePath: string;
    originClass: MemoryOriginClass;
  }>>;
  /** Fence and drain managers consuming these exact retiring capability objects. */
  prepareReload?(change: {
    retireRuntime: boolean;
    retiringEmbeddingProviders: readonly MemoryEmbeddingProviderAdapter[];
  }): {
    drain(): Promise<void | {
      errors: readonly unknown[];
    }>;
    resume(): void;
  };
  closeMemorySearchManager?(params: {
    cfg: OpenClawConfig;
    agentId: string;
  }): Promise<void>;
  closeAllMemorySearchManagers?(): Promise<void>;
};
/** Additive runtime; lifecycle hooks share the existing memory runtime cleanup owner. */
type MemoryProviderRuntime = Pick<MemoryPluginRuntime, "prepareReload" | "closeMemorySearchManager" | "closeAllMemorySearchManagers"> & {
  open(params: MemoryProviderOpenParams): Promise<MemoryProviderOpenResult>;
};
type MemoryPluginPublicArtifactContentType = "markdown" | "json" | "text";
type MemoryPluginPublicArtifact = {
  kind: string;
  workspaceDir: string;
  relativePath: string;
  absolutePath: string;
  agentIds: string[];
  contentType: MemoryPluginPublicArtifactContentType;
};
type MemoryPluginPublicArtifactsProvider = {
  listArtifacts(params: {
    cfg: OpenClawConfig;
  }): Promise<MemoryPluginPublicArtifact[]>;
};
type MemoryPluginCapability = {
  promptBuilder?: MemoryPromptSectionBuilder;
  flushPlanResolver?: MemoryFlushPlanResolver;
  /** Host-completed flush plans, including tool persistence; preferred over flushPlanResolver. */
  providerFlushPlanResolver?: MemoryProviderFlushPlanResolver;
  runtime?: MemoryPluginRuntime;
  /** Provider-neutral host integration; preferred over runtime when present. */
  providerRuntime?: MemoryProviderRuntime;
  publicArtifacts?: MemoryPluginPublicArtifactsProvider;
  /** Agent-facing tools Active Memory may use for provider-owned deep recall. */
  recallToolNames?: readonly string[];
  /** Local deterministic recall tool required by provider-owned direct lookup. */
  deterministicRecallToolName?: string;
  /** Whether recall may read protected same-agent private session transcripts. */
  supportsPrivateTranscriptRecall?: boolean;
  /** Tools a /learn turn may use to persist lessons; the host checks them against tool policy. */
  learnToolNames?: readonly string[];
  /** Guidance appended to /learn when some learnToolNames are available. */
  learnGuidanceBuilder?: MemoryLearnGuidanceBuilder;
};
type MemoryPluginCapabilityRegistration = {
  pluginId: string;
  capability: MemoryPluginCapability;
  /**
   * Registrar-provided memory slot ownership. Only the slot owner may displace
   * earlier fields during resolution; undeclared registrations contribute what
   * the owner lacks but never take over its runtime or consolidation surface.
   */
  memorySlotSelected?: boolean;
};
type SessionDiscussionProvider = {
  id: string;
  info(params: {
    sessionKey: string;
    agentId: string;
  }): Promise<SessionDiscussionInfo>;
  open(params: {
    sessionKey: string;
    agentId: string;
  }): Promise<SessionDiscussionInfo>;
};
type ResolvedPluginRuntimeArtifact = {
  source: string;
  rootDir: string;
};
//#endregion
//#region src/plugins/memory-state.d.ts
declare function registerMemoryCorpusSupplement(requestedPluginId: string, supplement: MemoryCorpusSupplement): void;
declare function registerMemoryCapability(requestedPluginId: string, capability: MemoryPluginCapability): void;
declare function getMemoryCapabilityRegistration(): MemoryPluginCapabilityRegistration | undefined;
declare function buildMemoryPromptSection(params: MemoryPromptSectionParams, prepared?: PreparedMemoryPromptSection): string[];
declare function listActiveMemoryPublicArtifacts(params: {
  cfg: OpenClawConfig;
}): Promise<MemoryPluginPublicArtifact[]>;
declare function clearMemoryPluginState(): void;
//#endregion
//#region src/channels/allowlist-match.d.ts
type AllowlistMatchSource = "wildcard" | "id" | "name" | "tag" | "username" | "prefixed-id" | "prefixed-user" | "prefixed-name" | "slug" | "localpart";
type AllowlistMatch<TSource extends string = AllowlistMatchSource> = {
  allowed: boolean;
  matchKey?: string;
  matchSource?: TSource;
};
type CompiledAllowlist = {
  set: ReadonlySet<string>;
  wildcard: boolean;
};
/** Formats match metadata for diagnostics without leaking channel-specific text. */
declare function formatAllowlistMatchMeta(match?: {
  matchKey?: string;
  matchSource?: string;
} | null): string;
/** Compiles normalized allowlist entries and records wildcard presence. */
declare function compileAllowlist(entries: ReadonlyArray<string>): CompiledAllowlist;
declare function resolveAllowlistCandidates<TSource extends string>(params: {
  compiledAllowlist: CompiledAllowlist;
  candidates: Array<{
    value?: string;
    source: TSource;
  }>;
}): AllowlistMatch<TSource>;
/** Applies wildcard and empty-list semantics before candidate matching. */
declare function resolveCompiledAllowlistMatch<TSource extends string>(params: {
  compiledAllowlist: CompiledAllowlist;
  candidates: Array<{
    value?: string;
    source: TSource;
  }>;
}): AllowlistMatch<TSource>;
/** Convenience wrapper for callers that do not need to reuse a compiled list. */
declare function resolveAllowlistMatchByCandidates<TSource extends string>(params: {
  allowList: ReadonlyArray<string>;
  candidates: Array<{
    value?: string;
    source: TSource;
  }>;
}): AllowlistMatch<TSource>;
/** Matches simple sender id/name allowlists used by legacy channel config. */
declare function resolveAllowlistMatchSimple(params: {
  allowFrom: ReadonlyArray<string | number>;
  senderId: string;
  senderName?: string | null;
  allowNameMatching?: boolean;
}): AllowlistMatch<"wildcard" | "id" | "name">;
//#endregion
//#region src/plugin-sdk/keyed-async-queue.d.ts
/** Optional lifecycle hooks fired around each queued task. */
type KeyedAsyncQueueHooks = {
  onEnqueue?: () => void;
  onSettle?: () => void;
};
type KeyedAsyncTask<T, TKey> = {
  tails: {
    get(key: TKey): Promise<unknown> | undefined;
    set(key: TKey, tail: Promise<void>): unknown;
    delete(key: TKey): boolean;
  };
  task: () => Promise<T>;
  hooks?: KeyedAsyncQueueHooks;
  /** Cancel admission only; a running task retains its keys until it settles. */
  signal?: AbortSignal;
} & ({
  key: TKey;
} | {
  keys: readonly TKey[];
});
/** Reserve every task key before yielding; unrelated keys remain independent. */
declare function enqueueKeyedTask<T, TKey>(params: KeyedAsyncTask<T, TKey>): Promise<T>;
declare function enqueueKeyedTask<T>(params: {
  tails: Map<string, Promise<void>>;
  key: string;
  task: () => Promise<T>;
  hooks?: KeyedAsyncQueueHooks;
  signal?: AbortSignal;
}): Promise<T>;
/** Small per-key async queue wrapper for plugin runtimes that need serialized work. */
declare class KeyedAsyncQueue {
  private readonly tails;
  /**
   * @deprecated Retained for shipped Plugin SDK compatibility. New callers must
   * not depend on queue storage; remove in a declared Plugin SDK breaking window.
   */
  getTailMapForTesting(): Map<string, Promise<void>>;
  enqueue<T>(key: string, task: () => Promise<T>, hooks?: KeyedAsyncQueueHooks): Promise<T>;
}
//#endregion
//#region src/infra/dedupe.d.ts
/** Small in-memory TTL/LRU-style cache for replay and duplicate suppression. */
type DedupeCache = {
  /** Returns true for a recent duplicate; records the key and optional owner when absent. */
  check: (key: string | undefined | null, now?: number, ownerToken?: object) => boolean;
  /** Returns true for a recent duplicate without refreshing or recording the key. */
  peek: (key: string | undefined | null, now?: number) => boolean;
  delete: (key: string | undefined | null, ownerToken?: object) => void;
  clear: () => void;
  size: () => number;
};
/** Dedupe cache bounds; ttlMs <= 0 disables expiry, maxSize <= 0 disables storage. */
type DedupeCacheOptions = {
  ttlMs: number;
  maxSize: number;
};
/** Creates a bounded in-memory dedupe cache with optional TTL expiry. */
declare function createDedupeCache(options: DedupeCacheOptions): DedupeCache;
/** Resolves a process-global dedupe cache for hot paths that can load this module twice. */
declare function resolveGlobalDedupeCache(key: symbol, options: DedupeCacheOptions): DedupeCache;
//#endregion
//#region src/infra/secure-random.d.ts
/** Generates a cryptographically secure UUID for runtime ids and cache keys. */
declare function generateSecureUuid(): string;
type SecureTokenOptions = {
  bytes?: number;
  redact: true;
  /** Encode and prefix before registering the exact wire value for redaction. */
  encoding?: "base64url" | "base64";
  prefix?: string;
};
/** Generates a cryptographic token, URL-safe unless its protocol requires base64. */
declare function generateSecureToken(options: SecureTokenOptions): string;
declare function generateSecureToken(bytes?: number): string;
//#endregion
//#region src/shared/tailscale-status.d.ts
type TailscaleStatusCommandResult = {
  code: number | null;
  stdout: string;
};
type TailscaleStatusCommandRunner = (argv: string[], opts: {
  timeoutMs: number;
}) => Promise<TailscaleStatusCommandResult>;
/** Resolves the host published to clients for tailnet or Tailscale Serve gateway modes. */
declare function resolveTailscalePublishedHost(params: {
  tailscaleMode: string;
  tailnetHost: string | null;
  /** @deprecated Managed Gateway ingress no longer supports named Services. */
  serviceName?: string | null;
}): string | null;
/** Runs known Tailscale status commands and returns the first DNS name or tailnet IP found. */
declare function resolveTailnetHostWithRunner(runCommandWithTimeout?: TailscaleStatusCommandRunner): Promise<string | null>;
/** Finds persistent HTTPS Serve routes whose root proxy targets this gateway port. */
declare function resolveTailscaleServeGatewayUrlsWithRunner(gatewayPort: number, runCommandWithTimeout?: TailscaleStatusCommandRunner): Promise<string[]>;
//#endregion
//#region src/context-engine/delegate.d.ts
/**
 * Delegate a context-engine compaction request to OpenClaw's built-in runtime compaction path.
 *
 * This is the same bridge used by the legacy context engine. Third-party
 * engines can call it from their own `compact()` implementations when they do
 * not own the compaction algorithm but still need `/compact` and overflow
 * recovery to use the stock runtime behavior.
 *
 * Note: `compactionTarget` is part of the public `compact()` contract, but the
 * built-in runtime compaction path does not expose that knob. This helper
 * ignores it to preserve legacy behavior; engines that need target-specific
 * compaction should implement their own `compact()` algorithm.
 */
declare function delegateCompactionToRuntime(params: Parameters<ContextEngine["compact"]>[0]): Promise<CompactResult>;
declare function buildMemorySystemPromptAddition(params: MemoryPromptSectionParams): string | undefined;
/** Prepare memory state asynchronously, then render it without prompt-path I/O. */
declare function prepareMemorySystemPromptAddition(params: MemoryPromptSectionParams): Promise<string | undefined>;
//#endregion
//#region src/shared/gateway-bind-url.d.ts
type GatewayBindUrlResult = {
  url: string;
  source: "gateway.bind=custom" | "gateway.bind=tailnet" | "gateway.bind=lan";
} | {
  error: string;
} | null;
/** Resolves the externally advertised gateway URL for non-loopback bind modes. */
declare function resolveGatewayBindUrl(params: {
  bind?: string;
  customBindHost?: string;
  scheme: "ws" | "wss";
  port: number;
  pickTailnetHost: () => string | null;
  pickLanHost: () => string | null;
}): GatewayBindUrlResult;
//#endregion
//#region src/gateway/net.d.ts
declare function isTrustedProxyAddress(ip: string | undefined, trustedProxies?: string[]): boolean;
declare function resolveClientIp(params: {
  remoteAddr?: string;
  forwardedFor?: string;
  realIp?: string;
  trustedProxies?: string[];
  /** Default false: only trust X-Real-IP when explicitly enabled. */
  allowRealIpFallback?: boolean;
}): string | undefined;
/**
 * Check if a hostname or IP refers to the local machine.
 * Handles: localhost, 127.x.x.x, ::1, [::1], ::ffff:127.x.x.x
 * Note: 0.0.0.0 and :: are NOT loopback - they bind to all interfaces.
 */
declare function isLoopbackHost(host: string): boolean;
/**
 * Check if a hostname or IP refers to a private or loopback address.
 * Handles the same hostname formats as isLoopbackHost, but also accepts
 * RFC 1918, link-local, CGNAT, and IPv6 ULA/link-local addresses.
 */
declare function isPrivateOrLoopbackHost(host: string): boolean;
//#endregion
//#region src/infra/format-time/format-datetime.d.ts
type FormatTimestampOptions = {
  /** Include seconds in the output. Default: false */
  displaySeconds?: boolean;
};
/**
 * Format a Date with timezone display using Intl.DateTimeFormat.
 *
 * Without seconds: `2024-01-15 14:30 EST`
 * With seconds:    `2024-01-15 14:30:05 EST`
 *
 * Returns undefined if Intl formatting fails.
 */
declare function formatZonedTimestamp(date: Date, options?: FormatTimestampOptions & {
  /** IANA timezone string (e.g., 'America/New_York'). Default: system timezone */
  timeZone?: string;
  /** Include an abbreviated weekday before the date. Default: false */
  displayWeekday?: boolean;
}): string | undefined;
//#endregion
//#region src/acp/persistent-bindings.resolve.d.ts
declare function resolveConfiguredAcpBindingRecord(params: {
  cfg: OpenClawConfig;
  channel: string;
  accountId: string;
  conversationId: string;
  parentConversationId?: string;
}): ResolvedConfiguredAcpBinding | null;
//#endregion
//#region src/channels/plugins/chat-target-prefixes.d.ts
type ParsedChatTarget = {
  kind: "chat_id";
  chatId: number;
} | {
  kind: "chat_guid";
  chatGuid: string;
} | {
  kind: "chat_identifier";
  chatIdentifier: string;
};
type ParsedChatAllowTarget = ParsedChatTarget | {
  kind: "handle";
  handle: string;
};
type ChatSenderAllowParams = {
  allowFrom: Array<string | number>;
  sender: string;
  chatId?: number | null;
  chatGuid?: string | null;
  chatIdentifier?: string | null;
  allowConversationTargets?: boolean | null;
};
declare function isAllowedParsedChatSender(params: ChatSenderAllowParams & {
  normalizeSender: (sender: string) => string;
  parseAllowTarget: (entry: string) => ParsedChatAllowTarget;
}): boolean;
/** Remove one of the known provider prefixes from a free-form target string. */
declare function stripChannelTargetPrefix(raw: string, ...providers: string[]): string;
/** Remove generic target-kind prefixes such as `user:` or `group:`. */
declare function stripTargetKindPrefix(raw: string): string;
//#endregion
//#region src/plugin-sdk/core.d.ts
/** Ensure a configured ACP binding has live runtime state before channel delivery uses it. */
declare function ensureConfiguredAcpBindingReady(params: {
  cfg: OpenClawConfig;
  configuredBinding: ResolvedConfiguredAcpBinding | null;
}): Promise<{
  ok: true;
} | {
  ok: false;
  error: string;
}>;
/** Params passed to a channel adapter when resolving outbound session routing. */
type ChannelOutboundSessionRouteParams = Parameters<NonNullable<ChannelMessagingAdapter["resolveOutboundSessionRoute"]>>[0];
declare function getChatChannelMetaForSdk(id: ChatChannelId): ChannelMeta;
/**
 * Build the canonical outbound session route payload returned by channel
 * message adapters.
 */
declare function buildChannelOutboundSessionRoute(params: {
  cfg: OpenClawConfig;
  agentId: string;
  channel: string;
  accountId?: string | null;
  recipientSessionExact?: boolean | "direct-alias" | "delivery-identity";
  peer: {
    kind: "direct" | "group" | "channel";
    id: string;
  };
  chatType: "direct" | "group" | "channel";
  from: string;
  to: string;
  threadId?: string | number;
}): ChannelOutboundSessionRoute;
/** Candidate source used when choosing a thread id for outbound session routing. */
type ThreadAwareOutboundSessionRouteThreadSource = "replyToId" | "threadId" | "currentSession";
/** Recovery context passed before reusing the current session thread id. */
type ThreadAwareOutboundSessionRouteRecoveryContext = {
  route: ChannelOutboundSessionRoute;
  currentBaseSessionKey: string;
  currentThreadId: string;
};
/** Recover the current thread id when the current session belongs to the same base route. */
declare function recoverCurrentThreadSessionId(params: {
  route: ChannelOutboundSessionRoute;
  currentSessionKey?: string | null;
  canRecover?: (context: ThreadAwareOutboundSessionRouteRecoveryContext) => boolean;
}): string | undefined;
/** Add thread-aware session keys and route thread ids to an outbound channel route. */
declare function buildThreadAwareOutboundSessionRoute(params: {
  route: ChannelOutboundSessionRoute;
  replyToId?: string | number | null;
  threadId?: string | number | null;
  currentSessionKey?: string | null;
  precedence?: readonly ThreadAwareOutboundSessionRouteThreadSource[];
  useSuffix?: boolean;
  parentSessionKey?: string;
  normalizeThreadId?: (threadId: string) => string;
  canRecoverCurrentThread?: (context: ThreadAwareOutboundSessionRouteRecoveryContext) => boolean;
}): ChannelOutboundSessionRoute;
/** Options for a channel plugin entry that should register a channel capability. */
type ChannelEntryConfigSchema<TPlugin> = TPlugin extends ChannelPlugin<unknown> ? NonNullable<TPlugin["configSchema"]> : ChannelConfigSchema;
type DefineChannelPluginEntryOptions<TPlugin = ChannelPlugin> = {
  id: string;
  name: string;
  description: string;
  plugin: TPlugin;
  configSchema?: ChannelEntryConfigSchema<TPlugin> | (() => ChannelEntryConfigSchema<TPlugin>);
  setRuntime?: (runtime: PluginRuntime) => void;
  registerCliMetadata?: (api: OpenClawPluginApi) => void;
  registerFull?: (api: OpenClawPluginApi) => void;
  registerCapabilities?: (api: OpenClawPluginApi) => void;
};
type DefinedChannelPluginEntry<TPlugin> = {
  id: string;
  name: string;
  description: string;
  configSchema: ChannelConfigSchema;
  register: (api: OpenClawPluginApi) => void;
  channelPlugin: TPlugin;
  setChannelRuntime?: (runtime: PluginRuntime) => void;
};
type CreateChannelPluginBaseOptions<TResolvedAccount> = {
  id: ChannelPlugin<TResolvedAccount>["id"];
  meta?: Partial<NonNullable<ChannelPlugin<TResolvedAccount>["meta"]>>;
  setupWizard?: NonNullable<ChannelPlugin<TResolvedAccount>["setupWizard"]>;
  capabilities?: ChannelPlugin<TResolvedAccount>["capabilities"];
  commands?: ChannelPlugin<TResolvedAccount>["commands"];
  doctor?: ChannelPlugin<TResolvedAccount>["doctor"];
  agentPrompt?: ChannelPlugin<TResolvedAccount>["agentPrompt"];
  streaming?: ChannelPlugin<TResolvedAccount>["streaming"];
  reload?: ChannelPlugin<TResolvedAccount>["reload"];
  gatewayMethods?: ChannelPlugin<TResolvedAccount>["gatewayMethods"];
  gatewayMethodDescriptors?: ChannelPlugin<TResolvedAccount>["gatewayMethodDescriptors"];
  configSchema?: ChannelPlugin<TResolvedAccount>["configSchema"];
  config?: ChannelPlugin<TResolvedAccount>["config"];
  security?: ChannelPlugin<TResolvedAccount>["security"];
  setup?: NonNullable<ChannelPlugin<TResolvedAccount>["setup"]>;
  setupContract?: NonNullable<ChannelPlugin<TResolvedAccount>["setupContract"]>;
  groups?: ChannelPlugin<TResolvedAccount>["groups"];
};
type CreatedChannelPluginBase<TResolvedAccount> = Pick<ChannelPlugin<TResolvedAccount>, "id" | "meta"> & Partial<Pick<ChannelPlugin<TResolvedAccount>, Exclude<keyof CreateChannelPluginBaseOptions<TResolvedAccount>, "id" | "meta">>>;
/**
 * Canonical entry helper for channel plugins.
 *
 * Registers the channel capability and optionally exposes full-runtime hooks
 * such as tools or gateway handlers outside setup-only registration modes.
 */
declare function defineChannelPluginEntry<TPlugin>({ id, name, description, plugin, configSchema, setRuntime, registerCliMetadata, registerFull, registerCapabilities }: DefineChannelPluginEntryOptions<TPlugin>): DefinedChannelPluginEntry<TPlugin>;
/**
 * Minimal setup-entry helper for channels that ship a separate `setup-entry.ts`.
 *
 * The setup entry only needs to export `{ plugin }`, but using this helper
 * keeps the shape explicit in examples and generated typings.
 */
declare function defineSetupPluginEntry<TPlugin>(plugin: TPlugin): {
  plugin: TPlugin;
};
type ChatChannelPluginBase<Plugin> = Omit<Plugin, "capabilities"> & Partial<Pick<ChannelPlugin, "capabilities">>;
type ChatChannelSecurityOptions<TResolvedAccount extends {
  accountId?: string | null;
}> = {
  dm: {
    channelKey: string;
    resolvePolicy: (account: TResolvedAccount) => string | null | undefined;
    resolveAllowFrom: (account: TResolvedAccount) => Array<string | number> | null | undefined;
    resolveFallbackAccountId?: (account: TResolvedAccount) => string | null | undefined;
    defaultPolicy?: string;
    allowFromPathSuffix?: string;
    policyPathSuffix?: string;
    approveChannelId?: string;
    approveHint?: string;
    normalizeEntry?: (raw: string) => string;
    classifyEntryAuthentication?: ChannelSecurityDmPolicy["classifyEntryAuthentication"];
    inheritSharedDefaultsFromDefaultAccount?: boolean;
  };
  dmRouting?: ChannelSecurityAdapter<TResolvedAccount>["dmRouting"];
  collectWarnings?: ChannelSecurityAdapter<TResolvedAccount>["collectWarnings"];
  collectAuditFindings?: ChannelSecurityAdapter<TResolvedAccount>["collectAuditFindings"];
};
type ChatChannelPairingOptions = {
  text: {
    idLabel: string;
    message: string;
    normalizeAllowEntry?: ChannelPairingAdapter["normalizeAllowEntry"];
    notify: (params: Parameters<NonNullable<ChannelPairingAdapter["notifyApproval"]>>[0] & {
      message: string;
    }) => Promise<void> | void;
  };
};
type ChatChannelThreadingReplyModeOptions<TResolvedAccount> = {
  topLevelReplyToMode: string;
} | {
  scopedAccountReplyToMode: {
    resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) => TResolvedAccount;
    resolveReplyToMode: (account: TResolvedAccount, chatType?: string | null) => ReplyToMode | null | undefined;
    fallback?: ReplyToMode;
  };
} | {
  resolveReplyToMode: NonNullable<ChannelThreadingAdapter["resolveReplyToMode"]>;
};
type ChatChannelThreadingOptions<TResolvedAccount> = ChatChannelThreadingReplyModeOptions<TResolvedAccount> & Omit<ChannelThreadingAdapter, "resolveReplyToMode">;
type ChatChannelAttachedOutboundOptions = {
  base: Omit<ChannelOutboundAdapter, "sendText" | "sendMedia" | "sendPoll">;
  attachedResults: Parameters<typeof createAttachedChannelResultAdapter>[0];
};
/**
 * Build a chat-style channel plugin by composing common security, pairing,
 * threading, and outbound adapters around a channel-specific base.
 */
declare function createChatChannelPlugin<TResolvedAccount extends {
  accountId?: string | null;
}, Probe = unknown, Audit = unknown, GatewayVersion extends 1 | 2 = 1>(params: {
  base: ChatChannelPluginBase<ChannelPlugin<TResolvedAccount, Probe, Audit, GatewayVersion>>;
  security?: ChannelSecurityAdapter<TResolvedAccount> | ChatChannelSecurityOptions<TResolvedAccount>;
  pairing?: ChannelPairingAdapter | ChatChannelPairingOptions;
  threading?: ChannelThreadingAdapter | ChatChannelThreadingOptions<TResolvedAccount>;
  outbound?: ChannelOutboundAdapter | ChatChannelAttachedOutboundOptions;
}): ChannelPlugin<TResolvedAccount, Probe, Audit, GatewayVersion>;
/** Create the shared base object for channel plugins that override only selected surfaces. */
declare function createChannelPluginBase<TResolvedAccount>(params: CreateChannelPluginBaseOptions<TResolvedAccount>): CreatedChannelPluginBase<TResolvedAccount>;
//#endregion
//#region src/plugin-sdk/channel-config-ui-hints.d.ts
type HintMap = Record<string, ChannelConfigUiHint>;
declare const STREAMING_HINT_LABELS: {
  readonly "": "Streaming Mode";
  readonly mode: "Streaming Mode";
  readonly chunkMode: "Chunk Mode";
  readonly "block.enabled": "Block Streaming Enabled";
  readonly "block.coalesce": "Block Streaming Coalesce";
  readonly nativeTransport: "Native Streaming";
  readonly "preview.chunk.minChars": "Draft Chunk Min Chars";
  readonly "preview.chunk.maxChars": "Draft Chunk Max Chars";
  readonly "preview.chunk.breakPreference": "Draft Chunk Break Preference";
  readonly "preview.toolProgress": "Draft Tool Progress";
  readonly "preview.commandText": "Draft Command Text";
  readonly "progress.style": "Progress Style";
  readonly "progress.nativeTaskCards": "Native Progress Task Cards";
};
type StreamingHintKey = keyof typeof STREAMING_HINT_LABELS;
type StreamingHintValue = string | {
  label: string;
  help: string;
};
declare function createChannelConfigUiHints(params: {
  channelLabel: string;
  dmPolicy?: {
    channelKey: string;
    includeLegacyNestedPolicy?: boolean;
    legacyNestedPolicyOrder?: "before" | "after";
  };
  configWrites?: boolean;
  mentionPatterns?: {
    targetDescription: string;
    policyTargetDescription?: string;
    policyNote?: string;
    denyNote?: string;
  };
  nativeCommands?: boolean;
  implicitMentions?: boolean;
  progress?: {
    includeCommentary?: boolean;
    commentaryOrder?: "before-command" | "after-command";
    labels?: "openclaw";
    titleWording?: boolean;
  };
  streaming?: Partial<Record<StreamingHintKey, StreamingHintValue>>;
  retry?: boolean;
}): HintMap;
//#endregion
//#region extensions/telegram/src/config-schema.d.ts
declare const TelegramConfigSchema: z.ZodObject<{
  dmPolicy: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
    allowlist: "allowlist";
    disabled: "disabled";
    open: "open";
    pairing: "pairing";
  }>>>;
  groupPolicy: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
    allowlist: "allowlist";
    disabled: "disabled";
    open: "open";
  }>>>;
  name: z.ZodOptional<z.ZodString>;
  markdown: z.ZodOptional<z.ZodObject<{
    tables: z.ZodOptional<z.ZodEnum<{
      block: "block";
      bullets: "bullets";
      code: "code";
      off: "off";
    }>>;
  }, z.core.$strict>>;
  configWrites: z.ZodOptional<z.ZodBoolean>;
  enabled: z.ZodOptional<z.ZodBoolean>;
  contextVisibility: z.ZodOptional<z.ZodEnum<{
    all: "all";
    allowlist: "allowlist";
    allowlist_quote: "allowlist_quote";
  }>>;
  historyLimit: z.ZodOptional<z.ZodNumber>;
  dmHistoryLimit: z.ZodOptional<z.ZodNumber>;
  dms: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
    historyLimit: z.ZodOptional<z.ZodNumber>;
  }, z.core.$strict>>>>;
  textChunkLimit: z.ZodOptional<z.ZodNumber>;
  healthMonitor: z.ZodOptional<z.ZodObject<{
    enabled: z.ZodOptional<z.ZodBoolean>;
  }, z.core.$strict>>;
  responsePrefix: z.ZodOptional<z.ZodString>;
  capabilities: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodObject<{
    inlineButtons: z.ZodOptional<z.ZodEnum<{
      all: "all";
      allowlist: "allowlist";
      dm: "dm";
      group: "group";
      off: "off";
    }>>;
  }, z.core.$strict>]>>;
  allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
  defaultTo: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
  groupAllowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
  mentionPatterns: z.ZodOptional<z.ZodObject<{
    mode: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"allow">, z.ZodLiteral<"deny">]>>;
    allowIn: z.ZodOptional<z.ZodArray<z.ZodString>>;
    denyIn: z.ZodOptional<z.ZodArray<z.ZodString>>;
  }, z.core.$strict>>;
  streaming: z.ZodOptional<z.ZodObject<{
    mode: z.ZodOptional<z.ZodEnum<{
      block: "block";
      off: "off";
      partial: "partial";
      progress: "progress";
    }>>;
    chunkMode: z.ZodOptional<z.ZodEnum<{
      length: "length";
      newline: "newline";
    }>>;
    preview: z.ZodOptional<z.ZodObject<{
      chunk: z.ZodOptional<z.ZodObject<{
        minChars: z.ZodOptional<z.ZodNumber>;
        maxChars: z.ZodOptional<z.ZodNumber>;
        breakPreference: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"paragraph">, z.ZodLiteral<"newline">, z.ZodLiteral<"sentence">]>>;
      }, z.core.$strict>>;
      toolProgress: z.ZodOptional<z.ZodBoolean>;
      commandText: z.ZodOptional<z.ZodEnum<{
        raw: "raw";
        status: "status";
      }>>;
    }, z.core.$strict>>;
    progress: z.ZodOptional<z.ZodObject<{
      label: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
      labels: z.ZodOptional<z.ZodArray<z.ZodString>>;
      maxLines: z.ZodOptional<z.ZodNumber>;
      maxLineChars: z.ZodOptional<z.ZodNumber>;
      toolProgress: z.ZodOptional<z.ZodBoolean>;
      commandText: z.ZodOptional<z.ZodEnum<{
        raw: "raw";
        status: "status";
      }>>;
      commentary: z.ZodOptional<z.ZodBoolean>;
      narration: z.ZodOptional<z.ZodBoolean>;
    }, z.core.$strict>>;
    block: z.ZodOptional<z.ZodObject<{
      enabled: z.ZodOptional<z.ZodBoolean>;
      coalesce: z.ZodOptional<z.ZodObject<{
        minChars: z.ZodOptional<z.ZodNumber>;
        maxChars: z.ZodOptional<z.ZodNumber>;
        idleMs: z.ZodOptional<z.ZodNumber>;
      }, z.core.$strict>>;
    }, z.core.$strict>>;
  }, z.core.$strict>>;
  mediaMaxMb: z.ZodOptional<z.ZodNumber>;
  replyToMode: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"off">, z.ZodLiteral<"first">, z.ZodLiteral<"all">, z.ZodLiteral<"batched">]>>;
  ackReaction: z.ZodOptional<z.ZodString>;
  joinIntro: z.ZodOptional<z.ZodBoolean>;
  execApprovals: z.ZodOptional<z.ZodObject<{
    enabled: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
    approvers: z.ZodOptional<z.ZodArray<z.ZodTypeAny>>;
    agentFilter: z.ZodOptional<z.ZodArray<z.ZodString>>;
    sessionFilter: z.ZodOptional<z.ZodArray<z.ZodString>>;
    target: z.ZodOptional<z.ZodEnum<{
      both: "both";
      channel: "channel";
      dm: "dm";
    }>>;
  }, z.core.$strict>>;
  commands: z.ZodOptional<z.ZodObject<{
    native: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
    nativeSkills: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
  }, z.core.$strict>>;
  customCommands: z.ZodOptional<z.ZodArray<z.ZodObject<{
    command: z.ZodString;
    description: z.ZodString;
  }, z.core.$strict>>>;
  botToken: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
    source: z.ZodLiteral<"env">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"store">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"file">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"exec">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>], "source">]>>;
  tokenFile: z.ZodOptional<z.ZodString>;
  groups: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
    requireMention: z.ZodOptional<z.ZodBoolean>;
    tools: z.ZodOptional<z.ZodObject<{
      allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>;
    toolsBySender: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>>>;
    skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
    enabled: z.ZodOptional<z.ZodBoolean>;
    allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
    systemPrompt: z.ZodOptional<z.ZodString>;
    requireMentionInBotThreads: z.ZodOptional<z.ZodBoolean>;
    ingest: z.ZodOptional<z.ZodBoolean>;
    disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
    groupPolicy: z.ZodOptional<z.ZodEnum<{
      allowlist: "allowlist";
      disabled: "disabled";
      open: "open";
    }>>;
    topics: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      requireMention: z.ZodOptional<z.ZodBoolean>;
      requireMentionInBotThreads: z.ZodOptional<z.ZodBoolean>;
      ingest: z.ZodOptional<z.ZodBoolean>;
      disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
      groupPolicy: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        disabled: "disabled";
        open: "open";
      }>>;
      skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
      enabled: z.ZodOptional<z.ZodBoolean>;
      allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
      systemPrompt: z.ZodOptional<z.ZodString>;
      agentId: z.ZodOptional<z.ZodString>;
      errorPolicy: z.ZodOptional<z.ZodEnum<{
        always: "always";
        once: "once";
        silent: "silent";
      }>>;
    }, z.core.$strict>>>>;
    errorPolicy: z.ZodOptional<z.ZodEnum<{
      always: "always";
      once: "once";
      silent: "silent";
    }>>;
  }, z.core.$strict>>>>;
  direct: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
    dmPolicy: z.ZodOptional<z.ZodEnum<{
      allowlist: "allowlist";
      disabled: "disabled";
      open: "open";
      pairing: "pairing";
    }>>;
    tools: z.ZodOptional<z.ZodObject<{
      allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>;
    toolsBySender: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
      deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>>>;
    skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
    enabled: z.ZodOptional<z.ZodBoolean>;
    allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
    systemPrompt: z.ZodOptional<z.ZodString>;
    topics: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      requireMention: z.ZodOptional<z.ZodBoolean>;
      ingest: z.ZodOptional<z.ZodBoolean>;
      disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
      groupPolicy: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        disabled: "disabled";
        open: "open";
      }>>;
      skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
      enabled: z.ZodOptional<z.ZodBoolean>;
      allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
      systemPrompt: z.ZodOptional<z.ZodString>;
      agentId: z.ZodOptional<z.ZodString>;
      errorPolicy: z.ZodOptional<z.ZodEnum<{
        always: "always";
        once: "once";
        silent: "silent";
      }>>;
    }, z.core.$strict>>>>;
    errorPolicy: z.ZodOptional<z.ZodEnum<{
      always: "always";
      once: "once";
      silent: "silent";
    }>>;
    requireTopic: z.ZodOptional<z.ZodBoolean>;
    autoTopicLabel: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
      enabled: z.ZodOptional<z.ZodBoolean>;
      prompt: z.ZodOptional<z.ZodString>;
    }, z.core.$strict>]>>;
  }, z.core.$strict>>>>;
  richMessages: z.ZodOptional<z.ZodBoolean>;
  widgets: z.ZodOptional<z.ZodBoolean>;
  network: z.ZodOptional<z.ZodObject<{
    autoSelectFamily: z.ZodOptional<z.ZodBoolean>;
    dnsResultOrder: z.ZodOptional<z.ZodEnum<{
      ipv4first: "ipv4first";
      verbatim: "verbatim";
    }>>;
    dangerouslyAllowPrivateNetwork: z.ZodOptional<z.ZodBoolean>;
  }, z.core.$strict>>;
  proxy: z.ZodOptional<z.ZodString>;
  webhookUrl: z.ZodOptional<z.ZodString>;
  webhookSecret: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
    source: z.ZodLiteral<"env">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"store">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"file">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    source: z.ZodLiteral<"exec">;
    provider: z.ZodString;
    id: z.ZodString;
  }, z.core.$strict>], "source">]>>;
  webhookPath: z.ZodOptional<z.ZodString>;
  legacyWebhook: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodObject<{
    port: z.ZodNumber;
    host: z.ZodOptional<z.ZodString>;
  }, z.core.$strict>]>>;
  webhookCertPath: z.ZodOptional<z.ZodString>;
  actions: z.ZodOptional<z.ZodObject<{
    reactions: z.ZodOptional<z.ZodBoolean>;
    sendMessage: z.ZodOptional<z.ZodBoolean>;
    poll: z.ZodOptional<z.ZodBoolean>;
    deleteMessage: z.ZodOptional<z.ZodBoolean>;
    editMessage: z.ZodOptional<z.ZodBoolean>;
    sticker: z.ZodOptional<z.ZodBoolean>;
    createForumTopic: z.ZodOptional<z.ZodBoolean>;
    editForumTopic: z.ZodOptional<z.ZodBoolean>;
  }, z.core.$strict>>;
  threadBindings: z.ZodOptional<z.ZodObject<{
    enabled: z.ZodOptional<z.ZodBoolean>;
    idleHours: z.ZodOptional<z.ZodNumber>;
    maxAgeHours: z.ZodOptional<z.ZodNumber>;
    spawnSessions: z.ZodOptional<z.ZodBoolean>;
    defaultSpawnContext: z.ZodOptional<z.ZodEnum<{
      fork: "fork";
      isolated: "isolated";
    }>>;
  }, z.core.$strict>>;
  linkPreview: z.ZodOptional<z.ZodBoolean>;
  silentErrorReplies: z.ZodOptional<z.ZodBoolean>;
  errorPolicy: z.ZodOptional<z.ZodEnum<{
    always: "always";
    once: "once";
    silent: "silent";
  }>>;
  apiRoot: z.ZodOptional<z.ZodString>;
  trustedLocalFileRoots: z.ZodOptional<z.ZodArray<z.ZodString>>;
  autoTopicLabel: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
    enabled: z.ZodOptional<z.ZodBoolean>;
    prompt: z.ZodOptional<z.ZodString>;
  }, z.core.$strict>]>>;
  accounts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
    name: z.ZodOptional<z.ZodString>;
    markdown: z.ZodOptional<z.ZodObject<{
      tables: z.ZodOptional<z.ZodEnum<{
        block: "block";
        bullets: "bullets";
        code: "code";
        off: "off";
      }>>;
    }, z.core.$strict>>;
    configWrites: z.ZodOptional<z.ZodBoolean>;
    enabled: z.ZodOptional<z.ZodBoolean>;
    dmPolicy: z.ZodOptional<z.ZodEnum<{
      allowlist: "allowlist";
      disabled: "disabled";
      open: "open";
      pairing: "pairing";
    }>>;
    groupPolicy: z.ZodOptional<z.ZodEnum<{
      allowlist: "allowlist";
      disabled: "disabled";
      open: "open";
    }>>;
    contextVisibility: z.ZodOptional<z.ZodEnum<{
      all: "all";
      allowlist: "allowlist";
      allowlist_quote: "allowlist_quote";
    }>>;
    historyLimit: z.ZodOptional<z.ZodNumber>;
    dmHistoryLimit: z.ZodOptional<z.ZodNumber>;
    dms: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      historyLimit: z.ZodOptional<z.ZodNumber>;
    }, z.core.$strict>>>>;
    textChunkLimit: z.ZodOptional<z.ZodNumber>;
    healthMonitor: z.ZodOptional<z.ZodObject<{
      enabled: z.ZodOptional<z.ZodBoolean>;
    }, z.core.$strict>>;
    responsePrefix: z.ZodOptional<z.ZodString>;
    capabilities: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodObject<{
      inlineButtons: z.ZodOptional<z.ZodEnum<{
        all: "all";
        allowlist: "allowlist";
        dm: "dm";
        group: "group";
        off: "off";
      }>>;
    }, z.core.$strict>]>>;
    allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
    defaultTo: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
    groupAllowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
    mentionPatterns: z.ZodOptional<z.ZodObject<{
      mode: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"allow">, z.ZodLiteral<"deny">]>>;
      allowIn: z.ZodOptional<z.ZodArray<z.ZodString>>;
      denyIn: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>;
    streaming: z.ZodOptional<z.ZodObject<{
      mode: z.ZodOptional<z.ZodEnum<{
        block: "block";
        off: "off";
        partial: "partial";
        progress: "progress";
      }>>;
      chunkMode: z.ZodOptional<z.ZodEnum<{
        length: "length";
        newline: "newline";
      }>>;
      preview: z.ZodOptional<z.ZodObject<{
        chunk: z.ZodOptional<z.ZodObject<{
          minChars: z.ZodOptional<z.ZodNumber>;
          maxChars: z.ZodOptional<z.ZodNumber>;
          breakPreference: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"paragraph">, z.ZodLiteral<"newline">, z.ZodLiteral<"sentence">]>>;
        }, z.core.$strict>>;
        toolProgress: z.ZodOptional<z.ZodBoolean>;
        commandText: z.ZodOptional<z.ZodEnum<{
          raw: "raw";
          status: "status";
        }>>;
      }, z.core.$strict>>;
      progress: z.ZodOptional<z.ZodObject<{
        label: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
        labels: z.ZodOptional<z.ZodArray<z.ZodString>>;
        maxLines: z.ZodOptional<z.ZodNumber>;
        maxLineChars: z.ZodOptional<z.ZodNumber>;
        toolProgress: z.ZodOptional<z.ZodBoolean>;
        commandText: z.ZodOptional<z.ZodEnum<{
          raw: "raw";
          status: "status";
        }>>;
        commentary: z.ZodOptional<z.ZodBoolean>;
        narration: z.ZodOptional<z.ZodBoolean>;
      }, z.core.$strict>>;
      block: z.ZodOptional<z.ZodObject<{
        enabled: z.ZodOptional<z.ZodBoolean>;
        coalesce: z.ZodOptional<z.ZodObject<{
          minChars: z.ZodOptional<z.ZodNumber>;
          maxChars: z.ZodOptional<z.ZodNumber>;
          idleMs: z.ZodOptional<z.ZodNumber>;
        }, z.core.$strict>>;
      }, z.core.$strict>>;
    }, z.core.$strict>>;
    mediaMaxMb: z.ZodOptional<z.ZodNumber>;
    replyToMode: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"off">, z.ZodLiteral<"first">, z.ZodLiteral<"all">, z.ZodLiteral<"batched">]>>;
    ackReaction: z.ZodOptional<z.ZodString>;
    joinIntro: z.ZodOptional<z.ZodBoolean>;
    execApprovals: z.ZodOptional<z.ZodObject<{
      enabled: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
      approvers: z.ZodOptional<z.ZodArray<z.ZodTypeAny>>;
      agentFilter: z.ZodOptional<z.ZodArray<z.ZodString>>;
      sessionFilter: z.ZodOptional<z.ZodArray<z.ZodString>>;
      target: z.ZodOptional<z.ZodEnum<{
        both: "both";
        channel: "channel";
        dm: "dm";
      }>>;
    }, z.core.$strict>>;
    commands: z.ZodOptional<z.ZodObject<{
      native: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
      nativeSkills: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"auto">]>>;
    }, z.core.$strict>>;
    customCommands: z.ZodOptional<z.ZodArray<z.ZodObject<{
      command: z.ZodString;
      description: z.ZodString;
    }, z.core.$strict>>>;
    botToken: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
      source: z.ZodLiteral<"env">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"store">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"file">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"exec">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>], "source">]>>;
    tokenFile: z.ZodOptional<z.ZodString>;
    groups: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      requireMention: z.ZodOptional<z.ZodBoolean>;
      tools: z.ZodOptional<z.ZodObject<{
        allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
      }, z.core.$strict>>;
      toolsBySender: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
        allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
      }, z.core.$strict>>>>;
      skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
      enabled: z.ZodOptional<z.ZodBoolean>;
      allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
      systemPrompt: z.ZodOptional<z.ZodString>;
      requireMentionInBotThreads: z.ZodOptional<z.ZodBoolean>;
      ingest: z.ZodOptional<z.ZodBoolean>;
      disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
      groupPolicy: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        disabled: "disabled";
        open: "open";
      }>>;
      topics: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
        requireMention: z.ZodOptional<z.ZodBoolean>;
        requireMentionInBotThreads: z.ZodOptional<z.ZodBoolean>;
        ingest: z.ZodOptional<z.ZodBoolean>;
        disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
        groupPolicy: z.ZodOptional<z.ZodEnum<{
          allowlist: "allowlist";
          disabled: "disabled";
          open: "open";
        }>>;
        skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
        enabled: z.ZodOptional<z.ZodBoolean>;
        allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
        systemPrompt: z.ZodOptional<z.ZodString>;
        agentId: z.ZodOptional<z.ZodString>;
        errorPolicy: z.ZodOptional<z.ZodEnum<{
          always: "always";
          once: "once";
          silent: "silent";
        }>>;
      }, z.core.$strict>>>>;
      errorPolicy: z.ZodOptional<z.ZodEnum<{
        always: "always";
        once: "once";
        silent: "silent";
      }>>;
    }, z.core.$strict>>>>;
    direct: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
      dmPolicy: z.ZodOptional<z.ZodEnum<{
        allowlist: "allowlist";
        disabled: "disabled";
        open: "open";
        pairing: "pairing";
      }>>;
      tools: z.ZodOptional<z.ZodObject<{
        allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
      }, z.core.$strict>>;
      toolsBySender: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
        allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        alsoAllow: z.ZodOptional<z.ZodArray<z.ZodString>>;
        deny: z.ZodOptional<z.ZodArray<z.ZodString>>;
      }, z.core.$strict>>>>;
      skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
      enabled: z.ZodOptional<z.ZodBoolean>;
      allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
      systemPrompt: z.ZodOptional<z.ZodString>;
      topics: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodObject<{
        requireMention: z.ZodOptional<z.ZodBoolean>;
        ingest: z.ZodOptional<z.ZodBoolean>;
        disableAudioPreflight: z.ZodOptional<z.ZodBoolean>;
        groupPolicy: z.ZodOptional<z.ZodEnum<{
          allowlist: "allowlist";
          disabled: "disabled";
          open: "open";
        }>>;
        skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
        enabled: z.ZodOptional<z.ZodBoolean>;
        allowFrom: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
        systemPrompt: z.ZodOptional<z.ZodString>;
        agentId: z.ZodOptional<z.ZodString>;
        errorPolicy: z.ZodOptional<z.ZodEnum<{
          always: "always";
          once: "once";
          silent: "silent";
        }>>;
      }, z.core.$strict>>>>;
      errorPolicy: z.ZodOptional<z.ZodEnum<{
        always: "always";
        once: "once";
        silent: "silent";
      }>>;
      requireTopic: z.ZodOptional<z.ZodBoolean>;
      autoTopicLabel: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
        enabled: z.ZodOptional<z.ZodBoolean>;
        prompt: z.ZodOptional<z.ZodString>;
      }, z.core.$strict>]>>;
    }, z.core.$strict>>>>;
    richMessages: z.ZodOptional<z.ZodBoolean>;
    widgets: z.ZodOptional<z.ZodBoolean>;
    network: z.ZodOptional<z.ZodObject<{
      autoSelectFamily: z.ZodOptional<z.ZodBoolean>;
      dnsResultOrder: z.ZodOptional<z.ZodEnum<{
        ipv4first: "ipv4first";
        verbatim: "verbatim";
      }>>;
      dangerouslyAllowPrivateNetwork: z.ZodOptional<z.ZodBoolean>;
    }, z.core.$strict>>;
    proxy: z.ZodOptional<z.ZodString>;
    webhookUrl: z.ZodOptional<z.ZodString>;
    webhookSecret: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
      source: z.ZodLiteral<"env">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"store">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"file">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>, z.ZodObject<{
      source: z.ZodLiteral<"exec">;
      provider: z.ZodString;
      id: z.ZodString;
    }, z.core.$strict>], "source">]>>;
    webhookPath: z.ZodOptional<z.ZodString>;
    legacyWebhook: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodObject<{
      port: z.ZodNumber;
      host: z.ZodOptional<z.ZodString>;
    }, z.core.$strict>]>>;
    webhookCertPath: z.ZodOptional<z.ZodString>;
    actions: z.ZodOptional<z.ZodObject<{
      reactions: z.ZodOptional<z.ZodBoolean>;
      sendMessage: z.ZodOptional<z.ZodBoolean>;
      poll: z.ZodOptional<z.ZodBoolean>;
      deleteMessage: z.ZodOptional<z.ZodBoolean>;
      editMessage: z.ZodOptional<z.ZodBoolean>;
      sticker: z.ZodOptional<z.ZodBoolean>;
      createForumTopic: z.ZodOptional<z.ZodBoolean>;
      editForumTopic: z.ZodOptional<z.ZodBoolean>;
    }, z.core.$strict>>;
    threadBindings: z.ZodOptional<z.ZodObject<{
      enabled: z.ZodOptional<z.ZodBoolean>;
      idleHours: z.ZodOptional<z.ZodNumber>;
      maxAgeHours: z.ZodOptional<z.ZodNumber>;
      spawnSessions: z.ZodOptional<z.ZodBoolean>;
      defaultSpawnContext: z.ZodOptional<z.ZodEnum<{
        fork: "fork";
        isolated: "isolated";
      }>>;
    }, z.core.$strict>>;
    linkPreview: z.ZodOptional<z.ZodBoolean>;
    silentErrorReplies: z.ZodOptional<z.ZodBoolean>;
    errorPolicy: z.ZodOptional<z.ZodEnum<{
      always: "always";
      once: "once";
      silent: "silent";
    }>>;
    apiRoot: z.ZodOptional<z.ZodString>;
    trustedLocalFileRoots: z.ZodOptional<z.ZodArray<z.ZodString>>;
    autoTopicLabel: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
      enabled: z.ZodOptional<z.ZodBoolean>;
      prompt: z.ZodOptional<z.ZodString>;
    }, z.core.$strict>]>>;
    reactionLevel: z.ZodOptional<z.ZodEnum<{
      ack: "ack";
      extensive: "extensive";
      minimal: "minimal";
      off: "off";
    }>>;
    reactionNotifications: z.ZodOptional<z.ZodEnum<{
      all: "all";
      off: "off";
      own: "own";
    }>>;
  }, z.core.$strict>>>>;
  defaultAccount: z.ZodOptional<z.ZodString>;
  reactionLevel: z.ZodOptional<z.ZodEnum<{
    ack: "ack";
    extensive: "extensive";
    minimal: "minimal";
    off: "off";
  }>>;
  reactionNotifications: z.ZodOptional<z.ZodEnum<{
    all: "all";
    off: "off";
    own: "own";
  }>>;
}, z.core.$strict>;
//#endregion
//#region src/channels/account-snapshot-fields.d.ts
declare const CREDENTIAL_STATUS_KEYS: readonly ["tokenStatus", "botTokenStatus", "appTokenStatus", "signingSecretStatus", "userTokenStatus"];
type CredentialStatusKey = (typeof CREDENTIAL_STATUS_KEYS)[number];
declare const CREDENTIAL_SOURCE_KEYS: readonly ["tokenSource", "botTokenSource", "appTokenSource", "signingSecretSource", "userTokenSource", "credentialSource", "secretSource"];
type CredentialSnapshotFields = Pick<Partial<ChannelAccountSnapshot>, CredentialStatusKey | (typeof CREDENTIAL_SOURCE_KEYS)[number]>;
/** Status inspection must not redeem credentials to detect configured-but-unavailable accounts. */
declare function resolveConfiguredFromCredentialStatuses(account: unknown): boolean | undefined;
/** Infers configured state only from the credential status keys required by a channel. */
declare function resolveConfiguredFromRequiredCredentialStatuses(account: unknown, requiredKeys: CredentialStatusKey[]): boolean | undefined;
/** Projects credential source/status metadata while omitting raw credential values. */
declare function projectCredentialSnapshotFields(account: unknown): CredentialSnapshotFields;
//#endregion
//#region src/channels/plugins/status-issues/shared.d.ts
declare function formatMatchMetadata(params: {
  matchKey?: unknown;
  matchSource?: unknown;
}): string | undefined;
declare function appendMatchMetadata(message: string, params: {
  matchKey?: unknown;
  matchSource?: unknown;
}): string;
declare function resolveEnabledConfiguredAccountId(account: {
  accountId?: unknown;
  enabled?: unknown;
  configured?: unknown;
}): string | null;
declare function collectIssuesForEnabledAccounts<T extends {
  accountId?: unknown;
  enabled?: unknown;
}>(params: {
  accounts: ChannelAccountSnapshot[];
  readAccount: (value: ChannelAccountSnapshot) => T | null;
  collectIssues: (params: {
    account: T;
    accountId: string;
    issues: ChannelStatusIssue[];
  }) => void;
}): ChannelStatusIssue[];
//#endregion
//#region src/plugin-sdk/status-helpers.d.ts
type RuntimeLifecycleSnapshot = {
  linked?: boolean | null;
  running?: boolean | null;
  connected?: boolean | null;
  restartPending?: boolean | null;
  reconnectAttempts?: number | null;
  lastConnectedAt?: number | null;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | null;
  lastEventAt?: number | null;
  lastTransportActivityAt?: number | null;
  healthState?: string | null;
  lifecycle?: ChannelAccountSnapshot["lifecycle"] | null;
  ingressUnavailable?: true | null;
  terminalDisconnect?: boolean | null;
  lastStartAt?: number | null;
  lastStopAt?: number | null;
  lastError?: string | null;
  lastInboundAt?: number | null;
  lastOutboundAt?: number | null;
  busy?: boolean | null;
  activeRuns?: number | null;
  lastRunActivityAt?: number | null;
  activeRunStartedAt?: number | null;
};
type StatusSnapshotExtra = Record<string, unknown>;
type ComputedAccountStatusBase = {
  accountId: string;
  name?: string;
  enabled?: boolean;
  configured?: boolean;
};
type ComputedAccountStatusAdapterParams<ResolvedAccount, Probe, Audit> = {
  account: ResolvedAccount;
  cfg: OpenClawConfig;
  runtime?: ChannelAccountSnapshot;
  probe?: Probe;
  audit?: Audit;
};
type ComputedAccountStatusSnapshot<TExtra extends StatusSnapshotExtra = StatusSnapshotExtra> = ComputedAccountStatusBase & {
  extra?: TExtra;
};
type ConfigIssueAccount = {
  accountId?: string | null;
  configured?: boolean | null;
} & Record<string, unknown>;
declare const ACCOUNT_STATUS_SNAPSHOT_FIELDS: readonly ["accountId", "enabled", "configured", "running", "connected"];
type AccountStatusSnapshot<TField extends string = never> = Record<(typeof ACCOUNT_STATUS_SNAPSHOT_FIELDS)[number] | TField, unknown>;
/** Coerce a status row to the standard account fields plus channel-owned extras. */
declare function readAccountStatusSnapshot<TField extends string>(value: unknown, extraFields: readonly TField[]): AccountStatusSnapshot<TField> | null;
/** Build the standard warning for an enabled/configured account with open DM policy. */
declare function standardDmPolicyOpenIssue(params: {
  channel: ChannelStatusIssue["channel"];
  accountId: string;
  channelLabel: string;
  configPath: string;
}): ChannelStatusIssue;
/** Build a standard authentication issue for an enabled but unconfigured account. */
declare function standardNotConfiguredIssue(params: {
  channel: ChannelStatusIssue["channel"];
  accountId: string;
  message: string;
  fix: string;
}): ChannelStatusIssue;
/** Create the baseline runtime snapshot shape used by channel/account status stores. */
declare function createDefaultChannelRuntimeState<T extends Record<string, unknown>>(accountId: string, extra?: T): {
  accountId: string;
  running: false;
  lastStartAt: null;
  lastStopAt: null;
  lastError: null;
} & T;
/** Normalize a channel-level status summary so missing lifecycle fields become explicit nulls. */
declare function buildBaseChannelStatusSummary<TExtra extends StatusSnapshotExtra>(snapshot: {
  configured?: boolean | null;
  running?: boolean | null;
  lastStartAt?: number | null;
  lastStopAt?: number | null;
  lastError?: string | null;
}, extra?: TExtra): {
  configured: boolean;
} & TExtra & {
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
};
/** Extend the base summary with probe fields while preserving stable null defaults. */
declare function buildProbeChannelStatusSummary<TExtra extends Record<string, unknown>>(snapshot: Parameters<typeof buildBaseChannelStatusSummary>[0] & {
  probe?: unknown;
  lastProbeAt?: number | null;
}, extra?: TExtra): {
  configured: boolean;
} & TExtra & {
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  probe: unknown;
  lastProbeAt: number | null;
};
/** Build webhook channel summaries with a stable default mode. */
declare function buildWebhookChannelStatusSummary<TExtra extends StatusSnapshotExtra>(snapshot: Parameters<typeof buildBaseChannelStatusSummary>[0] & {
  mode?: string | null;
}, extra?: TExtra): {
  configured: boolean;
} & {
  mode: string;
} & TExtra & {
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
};
/** Build the standard per-account status payload from config metadata plus runtime state. */
declare function buildBaseAccountStatusSnapshot<TExtra extends StatusSnapshotExtra>(params: {
  account: ComputedAccountStatusBase;
  runtime?: RuntimeLifecycleSnapshot | null;
  probe?: unknown;
}, extra?: TExtra): {
  accountId: string;
  name: string | undefined;
  enabled: boolean | undefined;
  configured: boolean | undefined;
  lastInboundAt: number | null;
  lastOutboundAt: number | null;
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  probe: unknown;
  linked?: boolean | undefined;
  connected?: boolean | undefined;
  restartPending?: boolean | undefined;
  reconnectAttempts?: number | undefined;
  lastConnectedAt?: number | undefined;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | undefined;
  lastEventAt?: number | undefined;
  lastTransportActivityAt?: number | undefined;
  healthState?: string | undefined;
  lifecycle?: "blocked" | "ready" | "recovering" | "starting" | "stopped" | undefined;
  ingressUnavailable?: true | undefined;
  terminalDisconnect?: true | undefined;
  busy?: boolean | undefined;
  activeRuns?: number | undefined;
  lastRunActivityAt?: number | undefined;
  activeRunStartedAt?: number | undefined;
} & TExtra;
/** Convenience wrapper when the caller already has flattened account fields instead of an account object. */
declare function buildComputedAccountStatusSnapshot<TExtra extends StatusSnapshotExtra>(params: ComputedAccountStatusBase & {
  runtime?: RuntimeLifecycleSnapshot | null;
  probe?: unknown;
}, extra?: TExtra): {
  accountId: string;
  name: string | undefined;
  enabled: boolean | undefined;
  configured: boolean | undefined;
  lastInboundAt: number | null;
  lastOutboundAt: number | null;
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  probe: unknown;
  linked?: boolean | undefined;
  connected?: boolean | undefined;
  restartPending?: boolean | undefined;
  reconnectAttempts?: number | undefined;
  lastConnectedAt?: number | undefined;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | undefined;
  lastEventAt?: number | undefined;
  lastTransportActivityAt?: number | undefined;
  healthState?: string | undefined;
  lifecycle?: "blocked" | "ready" | "recovering" | "starting" | "stopped" | undefined;
  ingressUnavailable?: true | undefined;
  terminalDisconnect?: true | undefined;
  busy?: boolean | undefined;
  activeRuns?: number | undefined;
  lastRunActivityAt?: number | undefined;
  activeRunStartedAt?: number | undefined;
} & TExtra;
/** Build a full status adapter when only configured/extras vary per account. */
declare function createComputedAccountStatusAdapter<ResolvedAccount, Probe = unknown, Audit = unknown, TExtra extends StatusSnapshotExtra = StatusSnapshotExtra>(options: Omit<ChannelStatusAdapter<ResolvedAccount, Probe, Audit>, "buildAccountSnapshot"> & {
  resolveAccountSnapshot: (params: ComputedAccountStatusAdapterParams<ResolvedAccount, Probe, Audit>) => ComputedAccountStatusSnapshot<TExtra>;
}): ChannelStatusAdapter<ResolvedAccount, Probe, Audit>;
/** Async variant for channels that compute configured state or snapshot extras from I/O. */
declare function createAsyncComputedAccountStatusAdapter<ResolvedAccount, Probe = unknown, Audit = unknown, TExtra extends StatusSnapshotExtra = StatusSnapshotExtra>(options: Omit<ChannelStatusAdapter<ResolvedAccount, Probe, Audit>, "buildAccountSnapshot"> & {
  resolveAccountSnapshot: (params: ComputedAccountStatusAdapterParams<ResolvedAccount, Probe, Audit>) => Promise<ComputedAccountStatusSnapshot<TExtra>>;
}): ChannelStatusAdapter<ResolvedAccount, Probe, Audit>;
/** Normalize runtime-only account state into the shared status snapshot fields. */
declare function buildRuntimeAccountStatusSnapshot<TExtra extends StatusSnapshotExtra>(params: {
  runtime?: RuntimeLifecycleSnapshot | null;
  probe?: unknown;
}, extra?: TExtra): {
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  probe: unknown;
  linked?: boolean | undefined;
  connected?: boolean | undefined;
  restartPending?: boolean | undefined;
  reconnectAttempts?: number | undefined;
  lastConnectedAt?: number | undefined;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | undefined;
  lastEventAt?: number | undefined;
  lastTransportActivityAt?: number | undefined;
  healthState?: string | undefined;
  lifecycle?: "blocked" | "ready" | "recovering" | "starting" | "stopped" | undefined;
  ingressUnavailable?: true | undefined;
  terminalDisconnect?: true | undefined;
  busy?: boolean | undefined;
  activeRuns?: number | undefined;
  lastRunActivityAt?: number | undefined;
  activeRunStartedAt?: number | undefined;
} & TExtra;
/** Build token-based channel status summaries with optional mode reporting. */
declare function buildTokenChannelStatusSummary(snapshot: Parameters<typeof buildProbeChannelStatusSummary>[0] & {
  tokenSource?: string | null;
  mode?: string | null;
}, opts?: {
  includeMode?: boolean;
}): {
  configured: boolean;
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  tokenSource: string;
  probe: unknown;
  lastProbeAt: number | null;
} | {
  configured: boolean;
  running: boolean;
  lastStartAt: number | null;
  lastStopAt: number | null;
  lastError: string | null;
  tokenSource: string;
  probe: unknown;
  lastProbeAt: number | null;
  mode: string | null;
};
/** Build a config-issue collector from snapshot-safe source metadata only. */
declare function createDependentCredentialStatusIssueCollector(options: {
  channel: string;
  dependencySourceKey: string;
  missingPrimaryMessage: string;
  missingDependentMessage: string;
  isDependencyConfigured?: ((value: unknown) => boolean) | undefined;
}): (accounts: ConfigIssueAccount[]) => ChannelStatusIssue[];
/** Convert account runtime errors into the generic channel status issue format. */
declare function collectStatusIssuesFromLastError(channel: string, accounts: Array<{
  accountId: string;
  lastError?: unknown;
}>): ChannelStatusIssue[];
//#endregion
//#region extensions/telegram/src/bot-info.d.ts
type TelegramBotInfo = UserFromGetMe;
//#endregion
//#region extensions/telegram/src/probe.d.ts
type TelegramProbe = BaseProbeResult & {
  status?: number | null;
  elapsedMs: number;
  bot?: {
    id?: number | null;
    isBot?: boolean | null;
    firstName?: string | null;
    username?: string | null;
    canJoinGroups?: boolean | null;
    canReadAllGroupMessages?: boolean | null;
    canManageBots?: boolean | null;
    supportsInlineQueries?: boolean | null;
    canConnectToBusiness?: boolean | null;
    hasMainWebApp?: boolean | null;
    hasTopicsEnabled?: boolean | null;
    allowsUsersToCreateTopics?: boolean | null;
  };
  botInfo?: TelegramBotInfo;
  webhook?: {
    url?: string | null;
    hasCustomCert?: boolean | null;
  };
};
type TelegramProbeOptions = {
  proxyUrl?: string;
  network?: TelegramNetworkConfig$1;
  accountId?: string;
  apiRoot?: string;
  includeWebhookInfo?: boolean;
  abortSignal?: AbortSignal;
};
declare function probeTelegram(token: string, timeoutMs: number, proxyOrOptions?: string | TelegramProbeOptions): Promise<TelegramProbe>;
//#endregion
//#region extensions/telegram/src/audit.types.d.ts
type TelegramGroupMembershipAuditEntry = {
  chatId: string;
  ok: boolean;
  status?: string | null;
  error?: string | null;
  matchKey?: string;
  matchSource?: "id";
};
type TelegramGroupMembershipAudit = {
  ok: boolean;
  checkedGroups: number;
  unresolvedGroups: number;
  hasWildcardUnmentionedGroups: boolean;
  groups: TelegramGroupMembershipAuditEntry[];
  elapsedMs: number;
};
type AuditTelegramGroupMembershipParams = {
  token: string;
  botId: number;
  groupIds: string[];
  proxyUrl?: string;
  network?: TelegramNetworkConfig$1;
  apiRoot?: string;
  timeoutMs: number;
};
//#endregion
//#region extensions/telegram/src/audit.d.ts
declare function collectTelegramUnmentionedGroupIds(groups: Record<string, TelegramGroupConfig> | undefined): {
  groupIds: string[];
  unresolvedGroups: number;
  hasWildcardUnmentionedGroups: boolean;
};
declare function auditTelegramGroupMembership(params: AuditTelegramGroupMembershipParams): Promise<TelegramGroupMembershipAudit>;
//#endregion
//#region extensions/telegram/src/group-access.d.ts
declare const resolveTelegramRuntimeGroupPolicy: typeof resolveOpenProviderRuntimeGroupPolicy;
//#endregion
//#region src/infra/exec-approval-reply.d.ts
type ExecApprovalReplyDecision = ExecApprovalDecision;
type ExecApprovalReplyMetadata = {
  approvalId: string;
  approvalSlug: string;
  approvalKind: ChannelApprovalKind;
  agentId?: string;
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
  sessionKey?: string;
};
type ExecApprovalPendingReplyParams = {
  warningText?: string;
  approvalId: string;
  approvalSlug: string;
  approvalCommandId?: string;
  ask?: string | null;
  agentId?: string | null;
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
  command: string;
  cwd?: string;
  host: ExecHost;
  nodeId?: string;
  scope?: ApprovalScope | null;
  sessionKey?: string | null;
  expiresAtMs?: number;
  nowMs?: number;
};
type BuildExecApprovalActionDescriptorsParams = {
  approvalCommandId: string;
  ask?: string | null;
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
};
declare function buildExecApprovalActionDescriptors(params: BuildExecApprovalActionDescriptorsParams): ExecApprovalActionDescriptor[];
declare function buildApprovalPresentationFromActionDescriptors(actions: readonly ExecApprovalActionDescriptor[]): MessagePresentation | undefined;
type BuildApprovalPresentationParams = {
  approvalId: string;
  ask?: string | null;
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
};
/** Build the shipped command-backed portable approval controls. */
declare function buildApprovalButtonPresentation(params: BuildApprovalPresentationParams): MessagePresentation | undefined;
declare function buildTypedApprovalPresentation(params: BuildApprovalPresentationParams & {
  approvalKind: ChannelApprovalKind;
}): MessagePresentation | undefined;
/** Build the shipped command-backed exec-approval presentation. */
declare function buildExecApprovalPresentation(params: BuildExecApprovalActionDescriptorsParams): MessagePresentation | undefined;
declare function getExecApprovalApproverDmNoticeText(): string;
declare function parseExecApprovalCommandText(raw: string): {
  approvalId: string;
  decision: ExecApprovalReplyDecision;
} | null;
declare function formatExecApprovalExpiresIn(expiresAtMs: number, nowMs: number): string;
declare function getExecApprovalReplyMetadata(payload: ReplyPayload$1): ExecApprovalReplyMetadata | null;
declare function buildExecApprovalPendingReplyPayload(params: ExecApprovalPendingReplyParams): ReplyPayload$1;
declare function buildTypedExecApprovalPendingReplyPayload(params: ExecApprovalPendingReplyParams): ReplyPayload$1;
//#endregion
//#region src/infra/exec-approval-command-display.d.ts
/** Resolves sanitized command and preview text for exec approval prompts. */
declare function resolveExecApprovalCommandDisplay(request: ExecApprovalRequestPayload): {
  /** Primary command text rendered in the approval prompt. */
  commandText: string;
  /** Optional shorter preview, omitted when it would duplicate the primary command text. */
  commandPreview: string | null;
};
//#endregion
//#region src/infra/approval-display-paths.d.ts
/** Formats user-home paths compactly for approval prompts without normalizing unsafe paths. */
declare function formatApprovalDisplayPath(value: string): string;
//#endregion
//#region src/infra/approval-request-account-binding.d.ts
type ApprovalRequestLike$1 = Pick<ApprovalRequestInput, "id" | "request" | "createdAtMs" | "expiresAtMs">;
type ApprovalRequestSessionParams = {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike$1;
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
};
type ApprovalRequestSessionDelivery = Pick<SessionEntry, "sessionId" | "updatedAt" | "delivery">;
/** Resolves the account id an approval request belongs to for an optional channel filter. */
declare function resolveApprovalRequestAccountIdFromDelivery(params: {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike$1;
  channel?: string | null;
}, sessionDelivery: ApprovalRequestSessionDelivery | null): string | null;
/** Resolves an approval request account only when the request can be routed to a channel. */
declare function resolveApprovalRequestChannelAccountIdFromDelivery(params: {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike$1;
  channel: string;
}, sessionDelivery: ApprovalRequestSessionDelivery | null): string | null;
/** Checks whether a channel/account pair is eligible to handle an approval request. */
declare function doesApprovalRequestMatchChannelAccountFromDelivery(params: {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike$1;
  channel: string;
  accountId?: string | null;
}, sessionDelivery: ApprovalRequestSessionDelivery | null): boolean;
/** Selects the one channel account that owns a native approval request. */
declare function doesApprovalRequestSelectChannelAccountFromDelivery(params: {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike$1;
  channel: string;
  accountId?: string | null;
  defaultAccountId: string;
  eligibleAccountIds: readonly string[];
}, sessionDelivery: ApprovalRequestSessionDelivery | null): boolean;
/** Reads one current routing snapshot through the session owner; supplied facts are reused. */
declare function resolveApprovalRequestSessionDeliveryAsync(params: ApprovalRequestSessionParams): Promise<ApprovalRequestSessionDelivery | null>;
/** @deprecated Use resolveApprovalRequestAccountIdAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveApprovalRequestAccountId(params: Parameters<typeof resolveApprovalRequestAccountIdFromDelivery>[0]): ReturnType<typeof resolveApprovalRequestAccountIdFromDelivery>;
declare function resolveApprovalRequestAccountIdAsync(params: Parameters<typeof resolveApprovalRequestAccountIdFromDelivery>[0] & ApprovalRequestSessionParams): Promise<ReturnType<typeof resolveApprovalRequestAccountIdFromDelivery>>;
/** @deprecated Use resolveApprovalRequestChannelAccountIdAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveApprovalRequestChannelAccountId(params: Parameters<typeof resolveApprovalRequestChannelAccountIdFromDelivery>[0]): ReturnType<typeof resolveApprovalRequestChannelAccountIdFromDelivery>;
declare function resolveApprovalRequestChannelAccountIdAsync(params: Parameters<typeof resolveApprovalRequestChannelAccountIdFromDelivery>[0] & ApprovalRequestSessionParams): Promise<ReturnType<typeof resolveApprovalRequestChannelAccountIdFromDelivery>>;
/** @deprecated Use doesApprovalRequestMatchChannelAccountAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function doesApprovalRequestMatchChannelAccount(params: Parameters<typeof doesApprovalRequestMatchChannelAccountFromDelivery>[0]): ReturnType<typeof doesApprovalRequestMatchChannelAccountFromDelivery>;
declare function doesApprovalRequestMatchChannelAccountAsync(params: Parameters<typeof doesApprovalRequestMatchChannelAccountFromDelivery>[0] & ApprovalRequestSessionParams): Promise<ReturnType<typeof doesApprovalRequestMatchChannelAccountFromDelivery>>;
/** @deprecated Use doesApprovalRequestSelectChannelAccountAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function doesApprovalRequestSelectChannelAccount(params: Parameters<typeof doesApprovalRequestSelectChannelAccountFromDelivery>[0]): ReturnType<typeof doesApprovalRequestSelectChannelAccountFromDelivery>;
declare function doesApprovalRequestSelectChannelAccountAsync(params: Parameters<typeof doesApprovalRequestSelectChannelAccountFromDelivery>[0] & ApprovalRequestSessionParams): Promise<ReturnType<typeof doesApprovalRequestSelectChannelAccountFromDelivery>>;
//#endregion
//#region src/infra/exec-approval-session-target.d.ts
/** Delivery target recovered from an approval request's live turn-source or stored session. */
type ExecApprovalSessionTarget = {
  channel?: string;
  to: string;
  accountId?: string;
  threadId?: string | number;
};
/** Parsed session conversation metadata used by channel-native approval routing. */
type ApprovalRequestSessionConversation = {
  channel: string;
  kind: "group" | "channel";
  id: string;
  rawId: string;
  threadId?: string;
  baseSessionKey: string;
  baseConversationId: string;
  parentConversationCandidates: string[];
};
type ApprovalRequestLike = ApprovalRequestInput;
type ApprovalRequestOriginTargetResolver<TTarget> = {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike;
  channel: string;
  accountId?: string | null;
  resolveTurnSourceTarget: (request: ApprovalRequestLike) => TTarget | null;
  resolveSessionTarget: (sessionTarget: ExecApprovalSessionTarget) => TTarget | null;
  targetsMatch: (a: TTarget, b: TTarget) => boolean;
  resolveFallbackTarget?: (request: ApprovalRequestLike) => TTarget | null;
};
/** Resolves the conversation encoded in an approval request session key for an optional channel. */
declare function resolveApprovalRequestSessionConversation(params: {
  request: ApprovalRequestLike;
  channel?: string | null;
  bundledFallback?: boolean;
}): ApprovalRequestSessionConversation | null;
/** Resolve delivery using the shared turn-source fields, independent of approval kind. */
declare function resolveSessionTargetFromDelivery(params: {
  turnSourceChannel?: string | null;
  turnSourceTo?: string | null;
  turnSourceAccountId?: string | null;
  turnSourceThreadId?: string | number | null;
}, entry: ApprovalRequestSessionDelivery | null): ExecApprovalSessionTarget | null;
/** Resolves the best known message target for either exec or plugin approval requests. */
declare function resolveApprovalRequestSessionTargetFromDelivery(params: {
  cfg: OpenClawConfig;
  request: ApprovalRequestLike;
}, sessionDelivery: ApprovalRequestSessionDelivery | null): ExecApprovalSessionTarget | null;
/** @deprecated Use resolveExecApprovalSessionTargetAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveExecApprovalSessionTarget(params: Parameters<typeof resolveSessionTargetFromDelivery>[0] & {
  cfg: OpenClawConfig;
  request: ExecApprovalRequest;
}): ExecApprovalSessionTarget | null;
declare function resolveExecApprovalSessionTargetAsync(params: Parameters<typeof resolveExecApprovalSessionTarget>[0] & {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
}): Promise<ExecApprovalSessionTarget | null>;
/** @deprecated Use resolveApprovalRequestSessionTargetAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveApprovalRequestSessionTarget(params: Parameters<typeof resolveApprovalRequestSessionTargetFromDelivery>[0]): ExecApprovalSessionTarget | null;
declare function resolveApprovalRequestSessionTargetAsync(params: Parameters<typeof resolveApprovalRequestSessionTargetFromDelivery>[0] & {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
}): Promise<ExecApprovalSessionTarget | null>;
/** @deprecated Use resolveApprovalRequestOriginTargetAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveApprovalRequestOriginTarget<TTarget>(params: ApprovalRequestOriginTargetResolver<TTarget>): TTarget | null;
declare function resolveApprovalRequestOriginTargetAsync<TTarget>(params: ApprovalRequestOriginTargetResolver<TTarget> & {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
}): Promise<TTarget | null>;
//#endregion
//#region src/plugin-sdk/approval-native-helpers.types.d.ts
type ApprovalRequest$2 = ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
type DeliverySuppressionInput = Parameters<NonNullable<NonNullable<ChannelApprovalCapability["delivery"]>["shouldSuppressForwardingFallback"]>>[0];
type NativeApprovalForwardTarget = DeliverySuppressionInput["target"];
type LocalNativeExecApprovalConfig = {
  enabled?: boolean | "auto";
  mode?: string | null;
  agentFilter?: string[];
  sessionFilter?: string[];
};
type ChannelApprovalForwardTarget = DeliverySuppressionInput["target"];
type ApprovalResolverParams = {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
  cfg: OpenClawConfig;
  accountId?: string | null;
  approvalKind?: ChannelApprovalKind;
  request: ApprovalRequest$2;
};
/** Inputs for checking whether one approval request can use session-native forwarding. */
type ChannelApprovalForwardingEligibilityParams = {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
  /** Full config containing exec/plugin approval forwarding settings. */
  cfg: OpenClawConfig;
  /** Optional channel account id for account-scoped transport checks. */
  accountId?: string | null;
  /** Approval family whose forwarding config should be evaluated. */
  approvalKind: ChannelApprovalKind;
  /** Approval request being considered for native delivery. */
  request: ApprovalRequest$2;
};
/** Inputs for checking whether approval forwarding is configured for a channel route. */
type ChannelApprovalPotentialRouteParams = {
  /** Full config containing exec/plugin approval forwarding settings. */
  cfg: OpenClawConfig;
  /** Optional channel account id for account-scoped transport checks. */
  accountId?: string | null;
  /** Approval family whose forwarding config should be evaluated. */
  approvalKind: ChannelApprovalKind;
  /** When true, ignore explicit target routes and only consider session/native origin routes. */
  nativeSessionOnly?: boolean;
};
/** Inputs for checking whether one configured target can receive an approval request. */
type ChannelApprovalExplicitTargetEligibilityParams = ChannelApprovalForwardingEligibilityParams & {
  /** Forwarding target that may be handled by the channel-native approval route. */
  target: ChannelApprovalForwardTarget;
};
type NativeApprovalTargetNormalizer<TTarget> = (target: TTarget, request: ApprovalRequest$2) => TTarget | null | undefined;
type NativeApprovalForwardingFallbackSuppressorParams<TTarget extends NativeApprovalTarget> = {
  channel: string;
  normalizeForwardTarget: (target: NativeApprovalForwardTarget) => TTarget | null;
  resolveAccountId?: (params: {
    forwardingTarget: TTarget;
    target: NativeApprovalForwardTarget;
    request: ApprovalRequest$2;
  }) => string | null | undefined;
  resolveApprovalKind?: (params: {
    approvalKind?: ChannelApprovalKind;
    request: ApprovalRequest$2;
  }) => ChannelApprovalKind;
  isSessionRouteEligible: (params: ChannelApprovalForwardingEligibilityParams) => boolean;
  isExplicitTargetEligible?: (params: ChannelApprovalExplicitTargetEligibilityParams) => boolean;
  resolveForwardingTargetForMatch?: (params: {
    forwardingTarget: TTarget;
    accountId?: string | null;
    target: NativeApprovalForwardTarget;
    approvalKind: ChannelApprovalKind;
    request: ApprovalRequest$2;
  }) => TTarget | null;
  resolveOriginTarget: (params: ChannelApprovalForwardingEligibilityParams) => TTarget | null;
  resolveApproverDmTargets: (params: ChannelApprovalForwardingEligibilityParams) => readonly TTarget[];
  targetsMatch?: (left: TTarget, right: TTarget) => boolean;
};
type NativeApprovalForwardingFallbackSuppressorAsyncParams<TTarget extends NativeApprovalTarget> = Omit<NativeApprovalForwardingFallbackSuppressorParams<TTarget>, "isSessionRouteEligible" | "isExplicitTargetEligible" | "resolveOriginTarget" | "resolveApproverDmTargets"> & {
  isSessionRouteEligible: (params: ChannelApprovalForwardingEligibilityParams) => boolean | Promise<boolean>;
  isExplicitTargetEligible?: (params: ChannelApprovalExplicitTargetEligibilityParams) => boolean | Promise<boolean>;
  resolveOriginTarget: (params: ChannelApprovalForwardingEligibilityParams) => TTarget | null | Promise<TTarget | null>;
  resolveApproverDmTargets: (params: ChannelApprovalForwardingEligibilityParams) => readonly TTarget[] | Promise<readonly TTarget[]>;
};
type NativeApprovalChannelRouteGateParams<TTarget extends NativeApprovalTarget> = {
  channel: string;
  defaultForwardingMode: ExecApprovalForwardingMode;
  isTransportEnabled: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  listAccountIds: (cfg: OpenClawConfig) => readonly string[];
  resolveDefaultAccountId: (cfg: OpenClawConfig) => string;
  normalizeForwardTarget: (target: NativeApprovalForwardTarget) => TTarget | null;
  resolveTurnSourceTarget: (request: ApprovalRequest$2) => TTarget | null;
  targetsMatch?: (left: TTarget, right: TTarget) => boolean;
};
type NativeApprovalChannelRouteGates = {
  canApprovalPotentiallyRouteToChannel: (params: ChannelApprovalPotentialRouteParams) => boolean;
  canAnyApprovalPotentiallyRouteToChannel: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    nativeSessionOnly?: boolean;
  }) => boolean;
  isNativeApprovalHandlerConfigured: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  isSessionApprovalEligible: (params: ChannelApprovalForwardingEligibilityParams) => boolean;
  isExplicitTargetEligible: (params: ChannelApprovalExplicitTargetEligibilityParams) => boolean;
  shouldHandleApprovalRequest: (params: ApprovalResolverParams) => boolean;
};
type BaseOriginResolverParams<TTarget> = {
  /** Channel id whose origin target should be resolved. */
  channel: string;
  /** Optional gate; returning false prevents native origin delivery. */
  shouldHandleRequest?: (params: ApprovalResolverParams) => boolean;
  /** Maps request turn-source metadata to a native target. */
  resolveTurnSourceTarget: (request: ApprovalRequest$2) => TTarget | null;
  /** Maps a persisted session target to a native target. */
  resolveSessionTarget: (sessionTarget: ExecApprovalSessionTarget, request: ApprovalRequest$2) => TTarget | null;
  /** Normalizes the returned target before delivery. */
  normalizeTarget?: NativeApprovalTargetNormalizer<TTarget>;
  /** Normalizes only matcher inputs when delivery target shape must stay native. */
  normalizeTargetForMatch?: NativeApprovalTargetNormalizer<TTarget>;
  /** Optional fallback target when neither turn-source nor session target resolves. */
  resolveFallbackTarget?: (request: ApprovalRequest$2) => TTarget | null;
};
type NativeOriginResolverParams<TTarget extends NativeApprovalTarget> = BaseOriginResolverParams<TTarget> & {
  /** Optional native target matcher; defaults to route-exact target matching. */
  targetsMatch?: (a: TTarget, b: TTarget) => boolean;
};
type CustomOriginResolverParams<TTarget> = BaseOriginResolverParams<TTarget> & {
  /** Custom matcher required when target shape is not `NativeApprovalTarget`. */
  targetsMatch: (a: TTarget, b: TTarget) => boolean;
};
/** Standard channel-native approval destination used by route and origin matchers. */
type NativeApprovalTarget = {
  /** Channel-local destination id. */
  to: string;
  /** Optional channel account id associated with the destination. */
  accountId?: string | null;
  /** Optional thread/topic id inside the destination. */
  threadId?: string | number | null;
};
//#endregion
//#region src/plugin-sdk/approval-native-target-resolvers.d.ts
/** Compare channel-native approval targets with the same normalization used by outbound routes. */
declare function nativeApprovalTargetsMatch(params: {
  /** Channel id used for route target normalization. */
  channel?: string | null;
  /** Left native target to compare. */
  left: NativeApprovalTarget;
  /** Right native target to compare. */
  right: NativeApprovalTarget;
}): boolean;
/** @deprecated Use createChannelNativeOriginTargetResolverAsync for worker-owned session reads. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createChannelNativeOriginTargetResolver<TTarget extends NativeApprovalTarget>(params: NativeOriginResolverParams<TTarget>): (input: ApprovalResolverParams) => TTarget | null;
/** @deprecated Use createChannelNativeOriginTargetResolverAsync for worker-owned session reads. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createChannelNativeOriginTargetResolver<TTarget>(params: CustomOriginResolverParams<TTarget>): (input: ApprovalResolverParams) => TTarget | null;
/** @deprecated Use createChannelApproverDmTargetResolverAsync with awaited account eligibility. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createChannelApproverDmTargetResolver<TApprover, TTarget extends NativeApprovalTarget = NativeApprovalTarget>(params: {
  /** Optional gate; returning false skips approver DM delivery for the request. */
  shouldHandleRequest?: (params: ApprovalResolverParams) => boolean;
  /** Resolves approver records from config and optional account scope. */
  resolveApprovers: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => readonly TApprover[];
  /** Maps one approver record to a native DM target; nullish results are skipped. */
  mapApprover: (approver: TApprover, params: ApprovalResolverParams) => TTarget | null | undefined;
}): (input: ApprovalResolverParams) => TTarget[];
type AsyncOriginResolverParams<TTarget> = Omit<CustomOriginResolverParams<TTarget>, "shouldHandleRequest"> & {
  shouldHandleRequest?: (params: ApprovalResolverParams) => boolean | Promise<boolean>;
};
/** Resolve native origin targets through worker-owned session reads. */
declare function createChannelNativeOriginTargetResolverAsync<TTarget extends NativeApprovalTarget>(params: Omit<NativeOriginResolverParams<TTarget>, "shouldHandleRequest"> & {
  shouldHandleRequest?: (params: ApprovalResolverParams) => boolean | Promise<boolean>;
}): (input: ApprovalResolverParams) => Promise<TTarget | null>;
declare function createChannelNativeOriginTargetResolverAsync<TTarget>(params: AsyncOriginResolverParams<TTarget>): (input: ApprovalResolverParams) => Promise<TTarget | null>;
/** Resolve configured approver DM targets after asynchronous account eligibility. */
declare function createChannelApproverDmTargetResolverAsync<TApprover, TTarget extends NativeApprovalTarget = NativeApprovalTarget>(params: {
  shouldHandleRequest?: (params: ApprovalResolverParams) => boolean | Promise<boolean>;
  resolveApprovers: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => readonly TApprover[];
  mapApprover: (approver: TApprover, params: ApprovalResolverParams) => TTarget | null | undefined;
}): (input: ApprovalResolverParams) => Promise<TTarget[]>;
//#endregion
//#region src/plugin-sdk/approval-native-helpers.d.ts
/**
 * Create the standard target adapters for messaging channels whose native
 * approval destination is a normalized `to` value.
 */
declare function createNativeApprovalMessagingTargetResolvers(params: {
  /** Lowercase channel id used by forwarding and turn-source routes. */
  channel: string;
  /** Channel-owned destination normalizer. */
  normalizeTo: (to: string) => string | null | undefined;
}): {
  normalizeForwardTarget: (target: NativeApprovalForwardTarget) => NativeApprovalTarget | null;
  resolveTurnSourceTarget: (request: ApprovalRequest$2) => NativeApprovalTarget | null;
  resolveSessionTarget: (sessionTarget: ExecApprovalSessionTarget) => NativeApprovalTarget | null;
  normalizeTarget: (target: NativeApprovalTarget) => NativeApprovalTarget | null;
};
/** Decide whether a channel-native exec approval route replaces the local text prompt. */
declare function shouldSuppressLocalNativeExecApprovalPrompt(params: {
  /** Full config containing top-level or channel-specific approval settings. */
  cfg: OpenClawConfig;
  /** Optional channel account id for account-scoped native delivery checks. */
  accountId?: string | null;
  /** Reply payload that may already contain exec approval metadata. */
  payload: ReplyPayload;
  /** Outbound payload hint proving an active native exec approval route. */
  hint?: ChannelOutboundPayloadHint;
  /** Legacy transport gate for native delivery. */
  isTransportEnabled?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  /** Preferred transport gate for native delivery. */
  isNativeDeliveryEnabled?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  /** Optional channel-specific approval config resolver. */
  resolveApprovalConfig?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    metadata: ExecApprovalReplyMetadata;
  }) => LocalNativeExecApprovalConfig | undefined;
  /** Whether the resolved approval config must be enabled before suppressing local prompt. */
  requireApprovalConfigEnabled?: boolean;
  /** Whether forwarding mode must be session/both unless exact target proof is present. */
  enforceForwardingMode?: boolean;
  /** Optional session-route gate for the approval metadata. */
  isSessionRouteEligible?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    metadata: ExecApprovalReplyMetadata;
  }) => boolean;
  /** Proof that target-mode forwarding already matched this exact native target. */
  hasExactTargetProof?: boolean;
  /** Whether agent filters may fall back to the agent segment in sessionKey. */
  fallbackAgentIdFromSessionKey?: boolean;
}): boolean;
/** Infer approval family from the request shape unless the caller already knows it. */
declare function resolveApprovalKind(request: ApprovalRequest$2, approvalKind?: ChannelApprovalKind): ChannelApprovalKind;
/** @deprecated Use createNativeApprovalChannelRouteGatesAsync for worker-owned session reads. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createNativeApprovalChannelRouteGates<TTarget extends NativeApprovalTarget>(params: NativeApprovalChannelRouteGateParams<TTarget>): NativeApprovalChannelRouteGates;
/** Create native route gates whose session-dependent checks run through the history worker. */
declare function createNativeApprovalChannelRouteGatesAsync<TTarget extends NativeApprovalTarget>(params: NativeApprovalChannelRouteGateParams<TTarget>): Omit<NativeApprovalChannelRouteGates, "isSessionApprovalEligible" | "shouldHandleApprovalRequest"> & {
  isSessionApprovalEligible: (input: ChannelApprovalForwardingEligibilityParams) => Promise<boolean>;
  shouldHandleApprovalRequest: (input: ApprovalResolverParams) => Promise<boolean>;
};
/** @deprecated Use createNativeApprovalForwardingFallbackSuppressorAsync with awaited route eligibility. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createNativeApprovalForwardingFallbackSuppressor<TTarget extends NativeApprovalTarget>(params: NativeApprovalForwardingFallbackSuppressorParams<TTarget>): NonNullable<NonNullable<ChannelApprovalCapability["delivery"]>["shouldSuppressForwardingFallback"]>;
/** Create a fallback suppressor for asynchronously prepared native routes. */
declare function createNativeApprovalForwardingFallbackSuppressorAsync<TTarget extends NativeApprovalTarget>(params: NativeApprovalForwardingFallbackSuppressorAsyncParams<TTarget>): NonNullable<NonNullable<ChannelApprovalCapability["delivery"]>["shouldSuppressForwardingFallbackAsync"]>;
//#endregion
//#region src/plugin-sdk/approval-auth-helpers.d.ts
type ApproverInput$1 = string | number;
type ApprovalApproverInputs = {
  explicit?: readonly ApproverInput$1[] | null;
  allowFrom?: readonly ApproverInput$1[] | null;
  extraAllowFrom?: readonly ApproverInput$1[] | null;
  defaultTo?: string | null;
};
type ApprovalContext = {
  cfg: OpenClawConfig;
  accountId?: string | null;
};
type ApprovalActorContext = ApprovalContext & {
  senderId?: string | null;
};
type ChannelApprovalAuth = {
  resolveApprovers: (context: ApprovalContext) => string[];
  isAuthorizedSender: (context: ApprovalActorContext) => boolean;
  approvalAuth: ReturnType<typeof createResolvedApproverActionAuthAdapter>;
};
type ApprovalAuthorizationResult = {
  /** Whether the actor may perform the approval action. */
  authorized: boolean;
  /** User-facing denial reason when authorization fails. */
  reason?: string;
};
/**
 * Marks an authorization result as the implicit same-chat fallback used when a
 * channel has no configured approver allowlist.
 */
declare function markImplicitSameChatApprovalAuthorization(
/** Authorization result to tag as the empty-approver same-chat fallback. */
result: ApprovalAuthorizationResult): ApprovalAuthorizationResult;
/**
 * Checks whether an authorization result came from the implicit same-chat
 * fallback instead of an explicitly configured approver allowlist.
 */
declare function isImplicitSameChatApprovalAuthorization(
/** Authorization result returned by approval auth helpers. */
result: ApprovalAuthorizationResult | null | undefined): boolean;
/**
 * Builds the approval authorization adapter shared by channels that resolve
 * approvers from account-scoped config.
 */
declare function createResolvedApproverActionAuthAdapter(params: {
  /** Human-readable channel label used in denial messages. */
  channelLabel: string;
  /** Resolves normalized approver ids from config and optional account scope. */
  resolveApprovers: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => string[];
  /** Optional sender normalizer; defaults to trimmed string normalization. */
  normalizeSenderId?: (value: string) => string | undefined;
}): {
  authorizeActorAction({ cfg, accountId, senderId, approvalKind }: {
    /** Full config used to resolve account-scoped approvers. */
    cfg: OpenClawConfig;
    /** Optional channel account id for account-scoped approver config. */
    accountId?: string | null;
    /** Actor attempting the approval action. */
    senderId?: string | null;
    /** Approval action being authorized. */
    action: "approve";
    /** Approval kind used in user-facing denial copy. */
    approvalKind: ChannelApprovalKind;
  }): ApprovalAuthorizationResult | {
    readonly reason?: undefined;
    readonly authorized: true;
  } | {
    readonly authorized: false;
    readonly reason: `❌ You are not authorized to approve exec requests on ${string}.` | `❌ You are not authorized to approve plugin requests on ${string}.` | `❌ You are not authorized to approve system-agent requests on ${string}.`;
  };
};
declare function createChannelApprovalAuth(params: {
  channelLabel: string;
  resolveInputs: (params: ApprovalContext) => ApprovalApproverInputs;
  normalizeApprover: (value: ApproverInput$1) => string | undefined;
  normalizeDefaultTo?: (value: string) => string | undefined;
  normalizeSenderId?: (value: string) => string | undefined;
  isWildcardAuthorized?: (params: {
    purpose: "sender" | "action";
    senderId?: string;
    inputs: ApprovalApproverInputs;
    approvers: readonly string[];
  }) => boolean;
}): ChannelApprovalAuth;
//#endregion
//#region src/infra/approval-request-filters.d.ts
/** Minimal approval request identity used by agent/session filter checks. */
type ApprovalRequestFilterInput = {
  agentId?: string | null;
  sessionKey?: string | null;
};
/**
 * Applies optional approval request filters for agent ids and session keys.
 * Agent id can be parsed from the session key only when the caller opts in.
 */
declare function matchesApprovalRequestFilters(params: {
  request: ApprovalRequestFilterInput;
  agentFilter?: string[];
  sessionFilter?: string[];
  fallbackAgentIdFromSessionKey?: boolean;
}): boolean;
//#endregion
//#region src/plugin-sdk/approval-client-helpers.d.ts
type ApprovalRequest$1 = ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
type ApprovalTarget = "dm" | "channel" | "both";
type ChannelExecApprovalEnableMode = boolean | "auto";
type ChannelApprovalConfig = {
  /** Whether the channel approval client is enabled for this account. */
  enabled?: ChannelExecApprovalEnableMode;
  /** Preferred approval delivery target for this account. */
  target?: ApprovalTarget;
  /** Optional agent filters for forwarded approval requests. */
  agentFilter?: string[];
  /** Optional session filters for forwarded approval requests. */
  sessionFilter?: string[];
};
type ApprovalProfileParams = {
  /** Full config used to resolve account-scoped approval settings. */
  cfg: OpenClawConfig;
  /** Optional channel account id for account-scoped approval settings. */
  accountId?: string | null;
};
/** Return whether a channel account has an enabled approval client and at least one approver. */
declare function isChannelExecApprovalClientEnabledFromConfig(params: {
  /** Configured channel approval enable mode. */
  enabled?: ChannelExecApprovalEnableMode;
  /** Number of configured approvers after account resolution. */
  approverCount: number;
}): boolean;
/**
 * Return whether a sender is one of the configured global exec approval forward targets.
 * Channel plugins provide the target matcher because `to` shapes differ by provider.
 */
declare function isChannelExecApprovalTargetRecipient(params: {
  /** Full config containing global exec approval target routing. */
  cfg: OpenClawConfig;
  /** Sender id or handle to compare with configured forward targets. */
  senderId?: string | null;
  /** Optional channel account id for account-scoped target matching. */
  accountId?: string | null;
  /** Channel id receiving the approval action. */
  channel: string;
  /** Optional sender normalizer; defaults to trimmed string normalization. */
  normalizeSenderId?: (value: string) => string | undefined;
  /** Channel-specific matcher for normalized sender ids against target records. */
  matchTarget: (params: {
    target: ExecApprovalForwardTarget;
    normalizedSenderId: string;
    normalizedAccountId?: string;
  }) => boolean;
}): boolean;
/**
 * Build the common approval-client profile used by channel plugins.
 * The returned helpers centralize enablement, approver auth, request filters, and local prompt suppression.
 */
type ChannelExecApprovalProfileParams = {
  /** Resolves channel approval config for the current account. */
  resolveConfig: (params: ApprovalProfileParams) => ChannelApprovalConfig | undefined;
  /** Resolves normalized approver ids for the current account. */
  resolveApprovers: (params: ApprovalProfileParams) => string[];
  /** Optional sender normalizer; defaults to trimmed string normalization. */
  normalizeSenderId?: (value: string) => string | undefined;
  /** Optional global approval-target matcher for sender authorization. */
  isTargetRecipient?: (params: ApprovalProfileParams & {
    senderId?: string | null;
  }) => boolean;
  /** Optional account matcher for filtering forwarded approval requests. */
  matchesRequestAccount?: (params: ApprovalProfileParams & {
    request: ApprovalRequest$1;
  }) => boolean;
  fallbackAgentIdFromSessionKey?: boolean;
  /** Allows local prompt suppression even when the remote approval client is disabled. */
  requireClientEnabledForLocalPromptSuppression?: boolean;
};
/** @deprecated Use createChannelExecApprovalProfileAsync for worker-owned account matching. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createChannelExecApprovalProfile(params: ChannelExecApprovalProfileParams): {
  shouldHandleRequest: (input: ApprovalProfileParams & {
    request: ApprovalRequest$1;
  }) => boolean;
  /** Whether this account has an enabled channel approval client and approvers. */
  isClientEnabled: (input: ApprovalProfileParams) => boolean;
  /** Whether a sender is in the resolved approver set. */
  isApprover: (input: ApprovalProfileParams & {
    senderId?: string | null;
  }) => boolean;
  /** Whether a sender is either an approver or a configured approval target. */
  isAuthorizedSender: (input: ApprovalProfileParams & {
    senderId?: string | null;
  }) => boolean;
  /** Preferred delivery target, defaulting to approver DMs. */
  resolveTarget: (input: ApprovalProfileParams) => ApprovalTarget;
  /** Whether a local approval prompt should be suppressed for an already-rendered payload. */
  shouldSuppressLocalPrompt: (input: ApprovalProfileParams & {
    payload: ReplyPayload;
  }) => boolean;
};
/** Build a profile that awaits worker-owned account eligibility. */
declare function createChannelExecApprovalProfileAsync(params: Omit<ChannelExecApprovalProfileParams, "matchesRequestAccount"> & {
  matchesRequestAccount?: (params: ApprovalProfileParams & {
    request: ApprovalRequest$1;
  }) => boolean | Promise<boolean>;
}): {
  /** Whether this account has an enabled channel approval client and approvers. */
  isClientEnabled: (input: ApprovalProfileParams) => boolean;
  /** Whether a sender is in the resolved approver set. */
  isApprover: (input: ApprovalProfileParams & {
    senderId?: string | null;
  }) => boolean;
  /** Whether a sender is either an approver or a configured approval target. */
  isAuthorizedSender: (input: ApprovalProfileParams & {
    senderId?: string | null;
  }) => boolean;
  /** Preferred delivery target, defaulting to approver DMs. */
  resolveTarget: (input: ApprovalProfileParams) => ApprovalTarget;
  /** Whether a local approval prompt should be suppressed for an already-rendered payload. */
  shouldSuppressLocalPrompt: (input: ApprovalProfileParams & {
    payload: ReplyPayload;
  }) => boolean;
  shouldHandleRequest: (input: ApprovalProfileParams & {
    request: ApprovalRequest$1;
  }) => Promise<boolean>;
};
//#endregion
//#region src/infra/exec-approval-channel-runtime.d.ts
type ExecApprovalChannelRuntimeAdapter<TPending, TRequest extends ApprovalRequestInput = ExecApprovalRequest, TResolved extends ApprovalResolved = ExecApprovalResolved> = {
  label: string;
  clientDisplayName: string;
  cfg: OpenClawConfig;
  gatewayUrl?: string;
  /** Defaults to exec-only; include plugin when the adapter can handle plugin approvals. */
  eventKinds?: readonly ChannelApprovalKind[];
  isConfigured: () => boolean;
  shouldHandle: (request: NormalizedApprovalRequest<TRequest>) => boolean;
  deliverRequested: (request: NormalizedApprovalRequest<TRequest>) => Promise<TPending[]>;
  beforeGatewayClientStart?: () => Promise<void> | void;
  finalizeResolved: (params: {
    request: NormalizedApprovalRequest<TRequest>;
    resolved: TResolved;
    entries: TPending[];
  }) => Promise<void>;
  finalizeExpired?: (params: {
    request: NormalizedApprovalRequest<TRequest>;
    entries: TPending[];
  }) => Promise<void>;
  onStopped?: () => Promise<void> | void;
  nowMs?: () => number;
};
type ExecApprovalChannelRuntimeAdapterAsync<TPending, TRequest extends ApprovalRequestInput = ExecApprovalRequest, TResolved extends ApprovalResolved = ExecApprovalResolved> = Omit<ExecApprovalChannelRuntimeAdapter<TPending, TRequest, TResolved>, "isConfigured" | "shouldHandle"> & {
  isConfigured: () => boolean | Promise<boolean>;
  shouldHandle: (request: NormalizedApprovalRequest<TRequest>) => boolean | Promise<boolean>;
};
type ExecApprovalChannelRuntime<TRequest extends ApprovalRequestInput = ExecApprovalRequest, TResolved extends ApprovalResolved = ExecApprovalResolved> = {
  start: () => Promise<void>;
  stop: () => Promise<void>;
  handleRequested: (request: TRequest) => Promise<void>;
  handleResolved: (resolved: TResolved) => Promise<void>;
  handleExpired: (approvalId: string) => Promise<void>;
  request: <T = unknown>(method: string, params: Record<string, unknown>) => Promise<T>;
};
//#endregion
//#region src/infra/approval-native-runtime.d.ts
type ApprovalRequest = ApprovalRequestInput;
type ChannelNativeApprovalRuntimeAdapter<TPendingEntry, TPreparedTarget, TPendingContent, TRequest extends ApprovalRequest = ApprovalRequest, TResolved extends ApprovalResolved = ApprovalResolved> = Omit<ExecApprovalChannelRuntimeAdapterAsync<TPendingEntry, TRequest, TResolved>, "deliverRequested"> & ChannelNativeApprovalTransportSpec<TPendingEntry, TPreparedTarget, TPendingContent, TRequest> & ChannelNativeApprovalDeliveryCallbacks<TPendingEntry, TPreparedTarget, TPendingContent, TRequest> & {
  channel?: string;
  channelLabel?: string;
  accountId?: string | null;
  nativeAdapter?: ChannelApprovalNativeAdapter | ChannelApprovalNativeAdapterAsync | null;
  /** @deprecated Trusted compatibility override; omit to derive ownership from the payload. */
  resolveApprovalKind?: (request: TRequest) => ChannelApprovalKind;
  buildPendingContent: (params: {
    request: TRequest;
    approvalKind: ChannelApprovalKind;
    nowMs: number;
  }) => TPendingContent | Promise<TPendingContent>;
  onStopped?: () => Promise<void> | void;
};
/** Creates a channel-native approval runtime with synchronous availability callbacks. */
declare function createChannelNativeApprovalRuntime<TPendingEntry, TPreparedTarget, TPendingContent, TRequest extends ApprovalRequest = ApprovalRequest, TResolved extends ApprovalResolved = ApprovalResolved>(adapter: Omit<ChannelNativeApprovalRuntimeAdapter<TPendingEntry, TPreparedTarget, TPendingContent, TRequest, TResolved>, "isConfigured" | "shouldHandle" | "nativeAdapter"> & Pick<ExecApprovalChannelRuntimeAdapter<TPendingEntry, TRequest, TResolved>, "isConfigured" | "shouldHandle"> & {
  nativeAdapter?: ChannelApprovalNativeAdapter | null;
}): ExecApprovalChannelRuntime<TRequest, TResolved>;
//#endregion
//#region src/plugin-sdk/approval-delivery-helpers.types.d.ts
type NativeApprovalDeliveryMode = "dm" | "channel" | "both";
type ApprovalAdapterParams = {
  sessionDelivery?: ApprovalRequestSessionDelivery | null;
  /** Full config used to inspect channel approval settings. */
  cfg: OpenClawConfig;
  /** Optional channel account id for account-scoped approval settings. */
  accountId?: string | null;
  /** Actor attempting the approval action. */
  senderId?: string | null;
};
type DeliverySuppressionParams = {
  /** Full config used to inspect native approval delivery settings. */
  cfg: OpenClawConfig;
  /** Approval kind being delivered. */
  approvalKind: ChannelApprovalKind;
  /** Forwarding fallback target under consideration. */
  target: {
    channel: string;
    accountId?: string | null;
  };
  /** Approval request metadata, including original turn source when available. */
  request: {
    request: {
      turnSourceChannel?: string | null;
      turnSourceAccountId?: string | null;
    };
  };
};
type ApproverRestrictedNativeApprovalCommonParams = {
  /** Channel id that owns this native approval capability. */
  channel: string;
  /** Human-readable channel label used in denial messages. */
  channelLabel: string;
  /** Optional setup description helper shown when exec approvals are unavailable. */
  describeExecApprovalSetup?: ChannelApprovalCapability["describeExecApprovalSetup"];
  /** Optional setup description helper shown when plugin approvals are unavailable. */
  describePluginApprovalSetup?: ChannelApprovalCapability["describePluginApprovalSetup"];
  /** Native runtime hooks used by channel-specific delivery implementations. */
  nativeRuntime?: ChannelApprovalCapability["nativeRuntime"];
  nativeRuntimeAsync?: ChannelApprovalCapability["nativeRuntimeAsync"];
};
type ApproverRestrictedNativeApprovalFlatParams = {
  /** Lists configured account ids so DM-route availability can scan every account. */
  listAccountIds: (cfg: OpenClawConfig) => string[];
  /** Whether an account has approvers configured. */
  hasApprovers: (params: ApprovalAdapterParams) => boolean;
  /** Whether a sender can approve exec approvals for this account. */
  isExecAuthorizedSender: (params: ApprovalAdapterParams) => boolean;
  /** Optional plugin approval authorization hook; defaults to exec authorization. */
  isPluginAuthorizedSender?: (params: ApprovalAdapterParams & {
    request?: PluginApprovalRequest$1;
  }) => boolean;
  /** Whether native approval delivery is enabled for an account. */
  isNativeDeliveryEnabled: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  /** Native delivery target preference for an account. */
  resolveNativeDeliveryMode: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => NativeApprovalDeliveryMode;
  /** Requires the approval request's original turn channel to match this channel before suppression. */
  requireMatchingTurnSourceChannel?: boolean;
  /** Optional account id resolver used when deciding forwarding-fallback suppression. */
  resolveSuppressionAccountId?: (params: DeliverySuppressionParams) => string | undefined;
  /** Resolves the original channel target for native approval delivery. */
  resolveOriginTarget?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    approvalKind: ChannelApprovalKind;
    request: ApprovalRequestInput;
  }) => NativeApprovalTarget | null | Promise<NativeApprovalTarget | null>;
  /** Resolves approver DM targets for native approval delivery. */
  resolveApproverDmTargets?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    approvalKind: ChannelApprovalKind;
    request: ApprovalRequestInput;
  }) => NativeApprovalTarget[] | Promise<NativeApprovalTarget[]>;
  /** Whether DM-only native delivery should also notify the origin channel. */
  notifyOriginWhenDmOnly?: boolean;
};
type ApproverRestrictedNativeApprovalAsyncParams = Omit<ApproverRestrictedNativeApprovalFlatParams, "isNativeDeliveryEnabled" | "isExecAuthorizedSender" | "isPluginAuthorizedSender"> & {
  isExecAuthorizedSender: (params: ApprovalAdapterParams) => boolean | Promise<boolean>;
  isPluginAuthorizedSender?: (params: ApprovalAdapterParams & {
    request?: PluginApprovalRequest$1;
  }) => boolean | Promise<boolean>;
  isNativeDeliveryEnabled: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    approvalKind?: ChannelApprovalKind;
  }) => Promise<boolean>;
};
//#endregion
//#region src/plugin-sdk/approval-delivery-helpers.d.ts
type StandardNativeApprovalRouting = Pick<ReturnType<typeof createNativeApprovalChannelRouteGates>, "canApprovalPotentiallyRouteToChannel" | "canAnyApprovalPotentiallyRouteToChannel" | "isNativeApprovalHandlerConfigured" | "shouldHandleApprovalRequest"> & {
  getActionAvailabilityState: NonNullable<ChannelApprovalCapability["getActionAvailabilityState"]>;
  getExecInitiatingSurfaceState: NonNullable<ChannelApprovalCapability["getExecInitiatingSurfaceState"]>;
  delivery: NonNullable<ChannelApprovalCapability["delivery"]>;
  native: NonNullable<ChannelApprovalCapability["native"]>;
};
type ApproverRestrictedNativeApprovalRoutedParams = {
  /** Standard forwarding-backed native routing assembled inside the capability factory. */
  routing: StandardNativeApprovalRoutingParams;
  /** Channel-owned authorization, including any implicit same-chat fallback marker. */
  authorizeActorAction: NonNullable<ChannelApprovalCapability["authorizeActorAction"]>;
  /** Builds native runtime hooks after the shared routing policy exists. */
  createNativeRuntime?: (routing: StandardNativeApprovalRouting) => ChannelApprovalCapability["nativeRuntime"];
  /** Render hooks for pending and resolved approval payloads. */
  render?: ChannelApprovalCapability["render"];
};
type StandardNativeApprovalRoutingParams = {
  /** Default forwarding mode when top-level approval config omits one. */
  defaultForwardingMode: "session" | "targets" | "both";
  /** Whether the channel transport is available for an account. */
  isTransportEnabled: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => boolean;
  /** Lists channel account ids for route and DM availability checks. */
  listAccountIds: (cfg: OpenClawConfig) => readonly string[];
  /** Resolves the channel's default account id. */
  resolveDefaultAccountId: (cfg: OpenClawConfig) => string;
  /** Normalizes a channel-local messaging destination. */
  normalizeTo: (to: string) => string | null | undefined;
  /** Resolves configured native approval recipients. */
  resolveApprovers: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => readonly string[];
  /** Optional origin safety gate, such as requiring approvers for group conversations. */
  isOriginTargetAllowed?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    approvalKind?: ChannelApprovalKind;
    request: ApprovalRequestInput;
    target: NativeApprovalTarget;
  }) => boolean;
  /** Whether explicit target forwarding participates in exact-match fallback suppression. */
  suppressExplicitTargetFallback?: boolean;
  /** Whether DM-only native delivery should also notify the origin channel. */
  notifyOriginWhenDmOnly?: boolean;
};
/** @deprecated Use createApproverRestrictedNativeApprovalCapabilityAsync with awaited account eligibility. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createApproverRestrictedNativeApprovalCapability(params: ApproverRestrictedNativeApprovalCommonParams & ApproverRestrictedNativeApprovalFlatParams): ChannelApprovalCapability;
/** Build approver-restricted native delivery using worker-owned account eligibility. */
declare function createApproverRestrictedNativeApprovalCapabilityAsync(params: ApproverRestrictedNativeApprovalCommonParams & ApproverRestrictedNativeApprovalAsyncParams): ChannelApprovalCapability;
/** Build the split approval adapter shape for approver-restricted native channels. */
declare function createApproverRestrictedNativeApprovalAdapter(params: ApproverRestrictedNativeApprovalCommonParams & ApproverRestrictedNativeApprovalFlatParams): {
  auth: {
    authorizeActorAction?: ChannelApprovalCapability["authorizeActorAction"];
    authorizeActorActionAsync?: ChannelApprovalCapability["authorizeActorActionAsync"];
    getActionAvailabilityState?: ChannelApprovalCapability["getActionAvailabilityState"];
    getActionAvailabilityStateAsync?: ChannelApprovalCapability["getActionAvailabilityStateAsync"];
    getExecInitiatingSurfaceState?: ChannelApprovalCapability["getExecInitiatingSurfaceState"];
    getExecInitiatingSurfaceStateAsync?: ChannelApprovalCapability["getExecInitiatingSurfaceStateAsync"];
    resolveApproveCommandBehavior?: ChannelApprovalCapability["resolveApproveCommandBehavior"];
  };
  delivery: ChannelApprovalCapability["delivery"];
  nativeRuntime: ChannelApprovalCapability["nativeRuntime"];
  nativeRuntimeAsync: ChannelApprovalCapability["nativeRuntimeAsync"];
  render: ChannelApprovalCapability["render"];
  native: ChannelApprovalCapability["native"];
  nativeAsync: ChannelApprovalCapability["nativeAsync"];
  describeExecApprovalSetup: ChannelApprovalCapability["describeExecApprovalSetup"];
  describePluginApprovalSetup: ChannelApprovalCapability["describePluginApprovalSetup"];
};
/** Assemble a channel approval capability from its auth, delivery, render, and native surfaces. */
declare function createChannelApprovalCapability(params: {
  /** Authorizes actors attempting approval actions. */
  authorizeActorAction?: ChannelApprovalCapability["authorizeActorAction"];
  authorizeActorActionAsync?: ChannelApprovalCapability["authorizeActorActionAsync"];
  /** Reports whether approval actions are generally available. */
  getActionAvailabilityState?: ChannelApprovalCapability["getActionAvailabilityState"];
  getActionAvailabilityStateAsync?: ChannelApprovalCapability["getActionAvailabilityStateAsync"];
  /** Reports whether exec approvals can start from the initiating surface. */
  getExecInitiatingSurfaceState?: ChannelApprovalCapability["getExecInitiatingSurfaceState"];
  getExecInitiatingSurfaceStateAsync?: ChannelApprovalCapability["getExecInitiatingSurfaceStateAsync"];
  /** Optional command behavior override for approval replies. */
  resolveApproveCommandBehavior?: ChannelApprovalCapability["resolveApproveCommandBehavior"];
  /** Optional setup copy for unavailable exec approval paths. */
  describeExecApprovalSetup?: ChannelApprovalCapability["describeExecApprovalSetup"];
  /** Optional setup copy for unavailable plugin approval paths. */
  describePluginApprovalSetup?: ChannelApprovalCapability["describePluginApprovalSetup"];
  /** Delivery fallback and DM-route helpers. */
  delivery?: ChannelApprovalCapability["delivery"];
  /** Native runtime hooks for channel-specific approval delivery. */
  nativeRuntime?: ChannelApprovalCapability["nativeRuntime"];
  nativeRuntimeAsync?: ChannelApprovalCapability["nativeRuntimeAsync"];
  /** Render hooks for pending/resolved approval payloads. */
  render?: ChannelApprovalCapability["render"];
  /** Native target/capability discovery hooks. */
  native?: ChannelApprovalCapability["native"];
  nativeAsync?: ChannelApprovalCapability["nativeAsync"];
}): ChannelApprovalCapability;
/** Split the canonical approval capability into the adapter shape older channel loaders consume. */
declare function splitChannelApprovalCapability(capability: ChannelApprovalCapability): {
  auth: {
    authorizeActorAction?: ChannelApprovalCapability["authorizeActorAction"];
    authorizeActorActionAsync?: ChannelApprovalCapability["authorizeActorActionAsync"];
    getActionAvailabilityState?: ChannelApprovalCapability["getActionAvailabilityState"];
    getActionAvailabilityStateAsync?: ChannelApprovalCapability["getActionAvailabilityStateAsync"];
    getExecInitiatingSurfaceState?: ChannelApprovalCapability["getExecInitiatingSurfaceState"];
    getExecInitiatingSurfaceStateAsync?: ChannelApprovalCapability["getExecInitiatingSurfaceStateAsync"];
    resolveApproveCommandBehavior?: ChannelApprovalCapability["resolveApproveCommandBehavior"];
  };
  delivery: ChannelApprovalCapability["delivery"];
  nativeRuntime: ChannelApprovalCapability["nativeRuntime"];
  nativeRuntimeAsync: ChannelApprovalCapability["nativeRuntimeAsync"];
  render: ChannelApprovalCapability["render"];
  native: ChannelApprovalCapability["native"];
  nativeAsync: ChannelApprovalCapability["nativeAsync"];
  describeExecApprovalSetup: ChannelApprovalCapability["describeExecApprovalSetup"];
  describePluginApprovalSetup: ChannelApprovalCapability["describePluginApprovalSetup"];
};
/** @deprecated Use createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutesAsync for worker-owned session reads. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutes(params: ApproverRestrictedNativeApprovalCommonParams & ApproverRestrictedNativeApprovalRoutedParams): {
  capability: ChannelApprovalCapability;
  routing: StandardNativeApprovalRouting;
};
type StandardNativeApprovalRoutingAsync = Omit<StandardNativeApprovalRouting, "shouldHandleApprovalRequest" | "native"> & {
  shouldHandleApprovalRequest: ReturnType<typeof createNativeApprovalChannelRouteGatesAsync>["shouldHandleApprovalRequest"];
  nativeAsync: NonNullable<ChannelApprovalCapability["nativeAsync"]>;
};
/** Build forwarding routes with worker-owned session and account resolution. */
declare function createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutesAsync(params: ApproverRestrictedNativeApprovalCommonParams & Omit<ApproverRestrictedNativeApprovalRoutedParams, "createNativeRuntime"> & {
  createNativeRuntime?: (routing: StandardNativeApprovalRoutingAsync) => ChannelApprovalCapability["nativeRuntimeAsync"];
}): {
  capability: ChannelApprovalCapability;
  routing: StandardNativeApprovalRoutingAsync;
};
//#endregion
//#region src/plugin-sdk/approval-approvers.d.ts
type ApproverInput = string | number;
/** Resolves explicit approvers first, then allow-from/default fallbacks with dedupe. */
declare function resolveApprovalApprovers(params: {
  explicit?: readonly ApproverInput[] | null;
  allowFrom?: readonly ApproverInput[] | null;
  extraAllowFrom?: readonly ApproverInput[] | null;
  defaultTo?: string | null;
  normalizeApprover: (value: ApproverInput) => string | undefined;
  normalizeDefaultTo?: (value: string) => string | undefined;
}): string[];
//#endregion
//#region src/plugin-sdk/approval-renderers.d.ts
type BuildApprovalPendingReplyPayloadParams = {
  /** Stable approval id used by `/approve` commands and metadata correlation. */
  approvalId: string;
  /** Short channel-facing approval slug for compact metadata displays. */
  approvalSlug: string;
  /** Visible approval request text sent to the channel. */
  text: string;
  /** Optional agent id associated with the approval request. */
  agentId?: string | null;
  /** Decisions rendered as buttons and accepted by the approval command. */
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
  /** Optional session key associated with the approval request. */
  sessionKey?: string | null;
  /** Channel-specific metadata merged with the shared approval metadata. */
  channelData?: Record<string, unknown>;
};
/** Build a shipped command-backed approval payload. */
declare function buildApprovalPendingReplyPayload(params: BuildApprovalPendingReplyPayloadParams & {
  approvalKind?: ChannelApprovalKind;
}): ReplyPayload;
/** Build a resolved approval reply payload with approval metadata but no controls. */
declare function buildApprovalResolvedReplyPayload(params: {
  /** Stable approval id used by `/approve` commands and metadata correlation. */
  approvalId: string;
  /** Short channel-facing approval slug for compact metadata displays. */
  approvalSlug: string;
  /** Visible resolved-state text sent to the channel. */
  text: string;
  /** Channel-specific metadata merged with the shared approval metadata. */
  channelData?: Record<string, unknown>;
}): ReplyPayload;
type BuildPluginApprovalPendingReplyPayloadParams = {
  /** Plugin approval request to render. */
  request: PluginApprovalRequest$1;
  /** Current time used for request expiry copy. */
  nowMs: number;
  /** Optional visible text override. */
  text?: string;
  /** Optional compact approval slug; defaults to the request id prefix. */
  approvalSlug?: string;
  /** Optional decision override; defaults to the request's allowed decisions. */
  allowedDecisions?: readonly ExecApprovalReplyDecision[];
  /** Channel-specific metadata merged with the shared approval metadata. */
  channelData?: Record<string, unknown>;
};
/** Build pending plugin approval copy and metadata from a plugin approval request. */
declare function buildPluginApprovalPendingReplyPayload(params: BuildPluginApprovalPendingReplyPayloadParams): ReplyPayload;
/** Build a plugin approval prompt with canonical typed decision actions. */
declare function buildTypedPluginApprovalPendingReplyPayload(params: BuildPluginApprovalPendingReplyPayloadParams): ReplyPayload;
/** Build resolved plugin approval copy and metadata from a plugin approval event. */
declare function buildPluginApprovalResolvedReplyPayload(params: {
  /** Resolved plugin approval event to render. */
  resolved: PluginApprovalResolved;
  /** Optional visible text override. */
  text?: string;
  /** Optional compact approval slug; defaults to the resolved id prefix. */
  approvalSlug?: string;
  /** Channel-specific metadata merged with the shared approval metadata. */
  channelData?: Record<string, unknown>;
}): ReplyPayload;
//#endregion
//#region src/plugin-sdk/approval-terminal.d.ts
type SystemAgentResolvedView = Extract<ResolvedApprovalView, {
  approvalKind: "system-agent";
}>;
/** Label a recorded decision without implying that a system change was applied. */
declare function formatApprovalDecisionLabel(decision: ResolvedApprovalView["decision"]): string;
/** Format a rich terminal label, retaining transport-specific decision spelling. */
declare function formatChannelApprovalResolvedLabel(view: ResolvedApprovalView, formatDecision?: (decision: ResolvedApprovalView["decision"]) => string): string;
/** Describe a system change using denial-first prose and a prepared operation summary. */
declare function buildSystemAgentApprovalResolvedText(view: SystemAgentResolvedView): string;
//#endregion
//#region src/plugin-sdk/approval-native-controls.d.ts
type NativeApprovalBinding = {
  token: string;
  expiresAtMs: number;
};
/** Own one plugin's process-local native controls through resolution and card updates. */
declare function createNativeApprovalControlRegistry<TBinding extends NativeApprovalBinding>(params: {
  releaseClaimOnLookupExpiry: boolean;
  onComplete?: (binding: TBinding) => void;
}): {
  createToken: () => string;
  register(binding: TBinding): boolean;
  get: (token: string) => TBinding | null;
  values: () => MapIterator<TBinding>;
  pruneExpired(nowMs: number): void;
  unregister(tokens: readonly string[]): void;
  settle<TResult>(token: string, resolveAndUpdate: (binding: TBinding) => Promise<TResult>): Promise<{
    kind: "missing";
  } | {
    kind: "in-flight";
  } | {
    kind: "not-found";
    binding: TBinding;
  } | {
    kind: "settled";
    binding: TBinding;
    result: TResult;
  }>;
};
//#endregion
//#region extensions/telegram/src/exec-approval-forwarding.d.ts
declare function shouldSuppressTelegramExecApprovalForwardingFallback(params: {
  cfg: OpenClawConfig;
  target: {
    channel: string;
    accountId?: string | null;
  };
  request: ExecApprovalRequest;
}): boolean;
declare function buildTelegramExecApprovalPendingPayload(params: {
  request: ExecApprovalRequest;
  nowMs: number;
}): ReplyPayload$1;
//#endregion
//#region extensions/telegram/src/channel-actions.d.ts
declare const telegramMessageActions: ChannelMessageActionAdapter;
//#endregion
//#region extensions/telegram/src/monitor.types.d.ts
type MonitorTelegramOpts = {
  token?: string;
  accountId?: string;
  ownerAgentId?: string;
  config?: OpenClawConfig;
  runtime?: RuntimeEnv;
  channelRuntime?: ChannelRuntimeSurface;
  abortSignal?: AbortSignal;
  useWebhook?: boolean;
  webhookPath?: string;
  legacyWebhook?: false | {
    port: number;
    host?: string;
  };
  webhookSecret?: string;
  proxyFetch?: typeof fetch;
  webhookUrl?: string;
  webhookCertPath?: string;
  botInfo?: TelegramBotInfo;
  setStatus?: (patch: Omit<ChannelAccountSnapshot, "accountId">) => void;
};
//#endregion
//#region extensions/telegram/src/monitor.d.ts
declare function monitorTelegramProvider(opts?: MonitorTelegramOpts): Promise<void>;
//#endregion
//#region extensions/telegram/src/thread-bindings-reconcile.d.ts
type TelegramAcpBindingReconciliationParams = {
  runtime: PluginRuntime;
  accountId: string;
  persist: boolean;
  prepareSession?: AcpSessionEntryPreparer;
};
declare function reconcileTelegramAcpBindingsOnStartup(params: TelegramAcpBindingReconciliationParams): Promise<void>;
//#endregion
//#region src/infra/outbound/account-scoped-conversation-bindings.d.ts
/** Binding record scoped to one channel account and conversation id. */
type AccountScopedConversationBindingRecord<TKind extends string = string> = {
  accountId: string;
  conversationId: string;
  targetKind: TKind;
  targetSessionKey: string;
  agentId?: string;
  label?: string;
  boundBy?: string;
  boundAt: number;
  lastActivityAt: number;
};
//#endregion
//#region extensions/telegram/src/thread-bindings-store.d.ts
type TelegramBindingTargetKind = "subagent" | "acp";
type TelegramThreadBindingRecord = AccountScopedConversationBindingRecord<TelegramBindingTargetKind> & {
  idleTimeoutMs?: number;
  maxAgeMs?: number;
  metadata?: Record<string, unknown>;
};
type TelegramThreadBindingManager = {
  accountId: string;
  shouldPersistMutations: () => boolean;
  getIdleTimeoutMs: () => number;
  getMaxAgeMs: () => number;
  getByConversationId: (conversationId: string) => TelegramThreadBindingRecord | undefined;
  listBySessionKey: (targetSessionKey: string) => TelegramThreadBindingRecord[];
  listBindings: () => TelegramThreadBindingRecord[];
  touchConversation: (conversationId: string, at?: number) => Promise<TelegramThreadBindingRecord | null>;
  unbindConversation: (params: {
    conversationId: string;
    reason?: string;
    sendFarewell?: boolean;
    throwOnPersistError?: boolean;
  }) => Promise<TelegramThreadBindingRecord | null>;
  unbindBySessionKey: (params: {
    targetSessionKey: string;
    reason?: string;
    sendFarewell?: boolean;
    throwOnPersistError?: boolean;
  }) => Promise<TelegramThreadBindingRecord[]>;
  updateBySessionKey: (targetSessionKey: string, update: (entry: TelegramThreadBindingRecord, now: number) => TelegramThreadBindingRecord) => Promise<TelegramThreadBindingRecord[]>;
  /** @deprecated Use touchConversation or updateBySessionKey; compatible through 2026-12-31, removed in the first January 2027 stable. */
  updateConversationSync: (conversationId: string, update: (entry: TelegramThreadBindingRecord) => TelegramThreadBindingRecord | undefined) => TelegramThreadBindingRecord | null;
  stop: () => Promise<void>;
};
//#endregion
//#region extensions/telegram/src/thread-bindings.d.ts
type TelegramThreadBindingManagerParams = {
  cfg: OpenClawConfig;
  accountId?: string;
  persist?: boolean;
  idleTimeoutMs?: number;
  maxAgeMs?: number;
  enableSweeper?: boolean;
  prepareAcpSession?: Parameters<typeof reconcileTelegramAcpBindingsOnStartup>[0]["prepareSession"];
};
declare function createTelegramThreadBindingManager(params: TelegramThreadBindingManagerParams): Promise<TelegramThreadBindingManager>;
declare function getTelegramThreadBindingManager(accountId?: string): TelegramThreadBindingManager | null;
type TelegramThreadBindingLifecycleField = "idleTimeoutMs" | "maxAgeMs";
type TelegramThreadBindingLifecycleParams<Field extends TelegramThreadBindingLifecycleField> = {
  targetSessionKey: string;
  accountId?: string;
} & Record<Field, number>;
declare const setTelegramThreadBindingIdleTimeoutBySessionKeyAsync: (params: TelegramThreadBindingLifecycleParams<"idleTimeoutMs">) => Promise<TelegramThreadBindingRecord[]>;
declare const setTelegramThreadBindingMaxAgeBySessionKeyAsync: (params: TelegramThreadBindingLifecycleParams<"maxAgeMs">) => Promise<TelegramThreadBindingRecord[]>;
/** @deprecated Use setTelegramThreadBindingIdleTimeoutBySessionKeyAsync; compatible through 2026-12-31, removed in the first January 2027 stable. */
declare const setTelegramThreadBindingIdleTimeoutBySessionKey: (params: TelegramThreadBindingLifecycleParams<"idleTimeoutMs">) => TelegramThreadBindingRecord[];
/** @deprecated Use setTelegramThreadBindingMaxAgeBySessionKeyAsync; compatible through 2026-12-31, removed in the first January 2027 stable. */
declare const setTelegramThreadBindingMaxAgeBySessionKey: (params: TelegramThreadBindingLifecycleParams<"maxAgeMs">) => TelegramThreadBindingRecord[];
//#endregion
//#region extensions/telegram/src/runtime.d.ts
declare const { setRuntime: setTelegramRuntime, getRuntime: getTelegramRuntime, tryGetRuntime: getOptionalTelegramRuntime }: {
  setRuntime: (next: PluginRuntime) => void;
  clearRuntime: () => void;
  tryGetRuntime: () => PluginRuntime | null;
  getRuntime: () => PluginRuntime;
};
//#endregion
//#region extensions/telegram/src/topic-conversation.d.ts
type ParsedTelegramTopicConversation = {
  chatId: string;
  thread: TelegramThreadSpec;
  canonicalConversationId: string;
};
declare function parseTelegramTopicConversation(params: {
  conversationId: string;
  parentConversationId?: string;
}): ParsedTelegramTopicConversation | null;
//#endregion
//#region extensions/telegram/src/poll-visibility.d.ts
declare function resolveTelegramPollVisibility(params: {
  pollAnonymous?: boolean;
  pollPublic?: boolean;
}): boolean | undefined;
//#endregion
//#region extensions/telegram/runtime-api.d.ts
type TelegramAccountConfig = NonNullable<NonNullable<OpenClawConfig["channels"]>["telegram"]>;
type TelegramActionConfig = NonNullable<TelegramAccountConfig["actions"]>;
type TelegramNetworkConfig = NonNullable<TelegramAccountConfig["network"]>;
//#endregion
//#region src/agents/sessions/model-prompt-projection-append.d.ts
declare const sessionManagerAppendPromptContext: unique symbol;
type PrepareModelPromptProjection = () => Promise<PreparedModelPromptProjection | undefined>;
//#endregion
//#region src/agents/sessions/session-manager-view-types.d.ts
type SessionManagerPersistenceTarget = SessionTranscriptTargetBinding;
type SessionManagerBoundedContextLimits = SessionTranscriptContextSelection;
type PreparedSessionTranscriptReload = PreparedSessionTranscriptHydration;
type SessionManagerTranscriptCohort = {
  selection: NonNullable<SessionEntryCohortRequest["transcript"]>;
  consume: (prepared: PreparedSessionTranscriptReload, assertView: () => void) => void;
};
type SessionManagerBoundedView = Pick<SessionTranscriptBoundedActiveContext, "activeLeafEntryId" | "version" | "opaqueParents" | "parents" | "firstKeptRanges" | "cacheTtlProjectionPrefixes">;
type SessionManagerBoundedContext = SessionManagerBoundedView & Pick<SessionTranscriptBoundedActiveContext, "persistedSuffixStartSeq" | "boundaryCount" | "transcriptMutationAt"> & {
  limits: SessionManagerBoundedContextLimits;
};
/** Public read-only methods; the facade supplies their exact signatures. */
type SessionManagerReadMethod = "getCwd" | "getSessionId" | "getSessionTarget" | "getLeafId" | "getAppendParentId" | "getAppendMode" | "getLeafEntry" | "getEntry" | "getLabel" | "getBranch" | "getHeader" | "getEntries" | "getTree" | "getSessionName";
//#endregion
//#region src/agents/sessions/session-manager-current-turn.d.ts
/** @internal Replay preparation is not part of the public SessionManager API. */
declare const sessionManagerPrepareCurrentTurnReplay: unique symbol;
/** @internal Runtime model history is not the raw persistence/navigation window. */
declare const sessionManagerReadInitialContext: unique symbol;
/** @internal Committed manager facts for the current execution boundary. */
declare const sessionManagerReadTranscriptStart: unique symbol;
type CurrentTurnReplaySelection = {
  entryId: string;
  version: SessionTranscriptContextVersion;
  assertCurrent: () => void;
};
//#endregion
//#region src/agents/sessions/session-manager-message-anchor.d.ts
/** @internal The last message append's immutable postimage, never current authority. */
declare const sessionManagerReadMessageAnchor: unique symbol;
/** @internal Completed-turn consumers validate this historical selector at their own boundary. */
declare const completedTurnMessageAnchor: unique symbol;
type CompletedTurnMessageAnchor = Readonly<{
  anchor: TranscriptEntryAnchor;
  assertCurrent: () => void;
}>;
//#endregion
//#region src/agents/sessions/session-manager-persistence-entry.d.ts
type PersistRecordResult = undefined | {
  anchor?: TranscriptEntryAnchor;
  lifecycleRevision?: string;
  appended: boolean;
  adoptedMessageId?: string;
  effectiveParentId: string | null;
  reloadAfterAppend?: boolean;
};
type PersistWorkerRecordResult = {
  result: PersistRecordResult;
  reload?: PreparedSessionTranscriptReload;
  committedVersion: SessionTranscriptContextVersion;
  viewFailure?: Error;
  modelPromptProjection?: NonNullable<SessionActorAppendCommitted["modelPromptProjection"]>["result"];
};
type PersistRecordOptions = AppendPersistenceOptions & {
  /** Retry fence captured from the durable snapshot that passed validation. */
  expectedMutationAt?: number | null;
};
//#endregion
//#region src/config/sessions/session-entry-codec.d.ts
declare function parseOpaqueLeafEntry(record: unknown): {
  id: string;
  parentId: string | null;
  targetId: string | null;
  appendParentId?: string | null;
  appendMode?: "side";
} | undefined;
//#endregion
//#region src/config/sessions/session-entry-navigation.d.ts
type SessionNavigationEntry = Pick<SessionEntryBase, "id" | "parentId"> & {
  timestamp?: string;
  appendMode?: unknown;
} & ({
  type: "label";
  targetId: string;
  label?: string;
} | {
  type: Exclude<SessionEntry$1["type"], "label">;
});
/** One navigation owner for runtime sessions and streaming transcript operations. */
declare class SessionEntryNavigation<T extends SessionNavigationEntry> {
  protected byId: Map<string, T>;
  protected opaqueParentsById: Map<string, string | null>;
  protected logicalParentsById: Map<string, string | null>;
  protected invalidLeafControlIds: Set<string>;
  protected labelsById: Map<string, string>;
  protected labelTimestampsById: Map<string, T["timestamp"]>;
  protected leafId: string | null;
  protected appendParentId: string | null;
  protected appendMode: "side" | undefined;
  private latestResetId;
  private resetDescendantIds;
  protected clearNavigation(): void;
  protected finishNavigation(): void;
  private recordResetDescendant;
  protected resolveOpaqueLeafTargetId(targetId: string | null): string | null;
  protected resolveOpaqueAppendParentId(parentId: string | null): string | null;
  protected resolveOpaqueLeafControl(leafEntry: ReturnType<typeof parseOpaqueLeafEntry>): {
    leafId: string | null;
    appendParentId: string | null;
    appendMode?: "side";
  } | undefined;
  protected appendOpaqueNavigationRecord(opaqueRecord: unknown): void;
  protected appendCanonicalNavigationEntry(entry: T, hasParentId?: boolean): void;
  protected resolveCanonicalParentId(parentId: string | null): string | null;
  protected resolveEntryParentId(entry: T): string | null;
  protected normalizeEntryParent(entry: T): T;
  getBranch(fromId?: string): T[];
}
//#endregion
//#region src/agents/sessions/session-manager-core.d.ts
/** @internal Fresh payload adoption and metadata consumption share one history admission. */
declare const sessionManagerReloadTranscriptCohort: unique symbol;
/** @internal Initial hydration and its synchronous replay decision share one admission. */
declare const sessionManagerOpenTranscriptCohort: unique symbol;
/** @internal Compaction planning retains its transcript and metadata from one read snapshot. */
declare const sessionManagerOpenCompaction: unique symbol;
declare class SessionManagerCore extends SessionEntryNavigation<SessionEntry$1> {
  migrated: boolean;
  protected sessionId: string;
  protected transcriptVersion: SessionTranscriptContextVersion | undefined;
  private transcriptViewFailure;
  private hydrationRevision;
  protected cwd: string;
  protected fileEntries: FileEntry[];
  protected opaqueFileEntries: PreservedOpaqueFileEntry[];
  protected boundedParentIds: Map<string, string | null>;
  private boundedFirstKeptById;
  protected cacheTtlProjectionPrefixes: SessionTranscriptBoundedActiveContext["cacheTtlProjectionPrefixes"];
  protected pendingDeliberateAppend: boolean;
  protected persistenceTarget: SessionManagerPersistenceTarget | undefined;
  protected persistenceHeaderPending: boolean;
  protected boundedContextLimits: SessionManagerBoundedContextLimits | undefined;
  protected boundedContextIncomplete: boolean;
  protected persistedBoundaryCount: number | undefined;
  protected persistedSuffixStartSeq: number | undefined;
  protected transcriptMutationAt: number | null | undefined;
  constructor(cwd: string, persistenceTarget?: SessionManagerPersistenceTarget, loadedEntries?: readonly unknown[], boundedContext?: SessionManagerBoundedContext, version?: SessionTranscriptContextVersion);
  /** @deprecated Await setSessionTargetAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  setSessionTarget(target: SessionTranscriptRuntimeTarget): void;
  protected setSessionTargetSync(target: SessionTranscriptRuntimeTarget): void;
  /** Prepare off-thread and publish the entire view only while this manager is unchanged. */
  setSessionTargetAsync(target: SessionTranscriptRuntimeTarget, signal?: AbortSignal): Promise<void>;
  private hydrateSessionTarget;
  [sessionManagerReloadTranscriptCohort](selection: NonNullable<SessionEntryCohortRequest["transcript"]>, consume: (prepared: PreparedSessionTranscriptReload, assertView: () => void) => void, signal?: AbortSignal): Promise<boolean>;
  /** Reload an existing view without changing the runtime working directory. */
  reloadPersistedTranscriptAsync(signal?: AbortSignal): Promise<void>;
  /** Active-only loads can omit sibling rows even when they fit the context limits. */
  protected ensureCompletePersistedHistory(): void;
  protected ensureCompletePersistedHistoryAsync(): Promise<void>;
  protected setLoadedSessionTarget(target: SessionManagerPersistenceTarget | undefined, entries: readonly unknown[], bounded?: SessionManagerBoundedView, version?: SessionTranscriptContextVersion): void;
  protected adoptSelectedTranscriptPath(appendParentId: string | null, parents: Iterable<readonly [string, string | null]>): void;
  /** The loaded view only: bounded managers must never hydrate inactive history for a rewrite. */
  protected captureTranscriptView(): {
    sessionId: string;
    transcriptVersion: SessionTranscriptContextVersion | undefined;
    persistenceHeaderPending: boolean;
    migrated: boolean;
    fileEntries: FileEntry[];
    opaqueFileEntries: PreservedOpaqueFileEntry[];
    byId: Map<string, SessionEntry$1>;
    opaqueParentsById: Map<string, string | null>;
    logicalParentsById: Map<string, string | null>;
    invalidLeafControlIds: Set<string>;
    labelsById: Map<string, string>;
    labelTimestampsById: Map<string, string>;
    boundedFirstKeptById: Map<string, string>;
    boundedParentIds: Map<string, string | null>;
    cacheTtlProjectionPrefixes: CacheTtlProjectionPrefix[] | undefined;
    boundedContextIncomplete: boolean;
    boundedContextLimits: SessionTranscriptContextSelection | undefined;
    persistedBoundaryCount: number | undefined;
    persistedSuffixStartSeq: number | undefined;
    transcriptMutationAt: number | null | undefined;
    leafId: string | null;
    appendParentId: string | null;
    appendMode: "side" | undefined;
    pendingDeliberateAppend: boolean;
  };
  /** @deprecated Await reloadPersistedTranscriptAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  reloadPersistedTranscript(): void;
  protected reloadPersistedTranscriptSync(): void;
  /** Reloads a committed append without adopting a later user turn. */
  protected reloadPersistedTranscriptAfterAppend(expectedMutationAt: number | null, expectedEntryId: string, admittedUserId: string): void;
  /** Adopt owner-prepared bytes without reading SQLite again on the receiving thread. */
  protected adoptPreparedTranscriptReload(prepared: PreparedSessionTranscriptReload, append?: {
    expectedMutationAt: number | null;
    expectedEntryId: string;
    admittedUserId: string;
  }, target?: SessionTranscriptTargetBinding | undefined): void;
  newSession(options?: NewSessionOptions): string | undefined;
  private initializeSession;
  protected buildIndex(): void;
  protected normalizeEntryParent(entry: SessionEntry$1): SessionEntry$1;
  protected resolveBranchTargetId(branchFromId: string): string | null | undefined;
  protected clampOpaqueFileEntryIndexes(): void;
  protected createLeafControl(parentId: string | null, appendParentId?: string | null, appendMode?: "side"): SessionLeafControl;
  protected rememberLeafControl(leafEntry: SessionLeafControl): void;
  getSessionName(): string | undefined;
  getChildren(parentId: string): SessionEntry$1[];
  getLabel(id: string): string | undefined;
  getBoundaryCount(): number;
  getHeader(): SessionHeader | null;
  getEntries(): SessionEntry$1[];
  getTree(): SessionTreeNode[];
  getLeafId(): string | null;
  getLeafEntry(): SessionEntry$1 | undefined;
  getEntry(id: string): SessionEntry$1 | undefined;
  getAppendParentId(): string | null;
  getAppendMode(): "side" | undefined;
  protected getPersistedFileEntries(leafAppendMode?: "side"): unknown[];
  getPersistedEntries(): unknown[];
  clearPreservedOpaqueFileEntries(): void;
  protected invalidateTranscriptView(error: Error): void;
  protected assertTranscriptViewAvailable(): void;
  getBranch(fromId?: string): SessionEntry$1[];
  isPersisted(): boolean;
  getCwd(): string;
  getSessionId(): string;
  getSessionTarget(): SessionManagerPersistenceTarget | undefined;
}
//#endregion
//#region src/agents/sessions/session-manager-write-admission.d.ts
type SessionManagerWriteAdmission = {
  database: OpenClawAgentDatabaseExecution | SessionManagerIncognitoDatabase;
  options: OpenClawAgentDatabaseOptions;
  assertCurrent(): void;
};
//#endregion
//#region src/agents/sessions/session-manager-append-admission.d.ts
type SessionManagerActorAppendAdmission = {
  actor: SessionActor;
  options: OpenClawAgentDatabaseOptions;
  assertCurrent(): void;
};
type SessionManagerAppendAdmission = SessionManagerActorAppendAdmission | SessionManagerWriteAdmission;
//#endregion
//#region src/agents/sessions/session-manager-native-persistence.d.ts
/** Released synchronous SDK methods keep their native transaction and publication contract. */
declare class SessionManagerNativePersistence extends SessionManagerCore {
  #private;
  protected get initialTranscriptWriter(): InitialSessionTranscriptWriter | undefined;
  protected recordTranscriptNavigationChange(): void;
  /** Local branch selections revoke pending writes; committed view adoption does not. */
  protected captureTranscriptNavigationAssertion(): () => void;
  protected retainTranscriptWriter(): void;
  protected assertTranscriptWriteActive(): void;
  protected hasNewerPublishedTranscriptView(version: SessionTranscriptContextVersion): boolean;
  /** @deprecated Await persistAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  persist(entry: SessionEntry$1, options?: PersistRecordOptions): PersistRecordResult;
  protected persistRecord(entry: unknown, options?: PersistRecordOptions, preparedMessage?: PreparedTranscriptMessageAppend<AgentMessage>): PersistRecordResult;
}
//#endregion
//#region src/agents/sessions/session-manager-persistence.d.ts
declare class SessionManagerPersistence extends SessionManagerNativePersistence {
  protected persistWorkerRecord(entry: SessionEntry$1 | SessionLeafControl, appendIntent: "active-branch" | undefined, writeAdmission: SessionManagerAppendAdmission, message?: Omit<NonNullable<SessionMetadataWorkerOperations["session.metadata.append"]["input"]["message"]>, "messageJson"> & {
    prepared: PreparedTranscriptMessageAppend<AgentMessage>;
  }, beforeFreshMessageCommit?: () => void, expectedMutationAt?: number | null, retryMutationConflicts?: boolean, assertNavigation?: () => void, initialModel?: ModelChangeEntry, modelPromptProjection?: SessionActorAppend["modelPromptProjection"]): Promise<PersistWorkerRecordResult>;
  persistAsync(entry: SessionEntry$1, options?: PersistRecordOptions): Promise<PersistRecordResult>;
}
//#endregion
//#region src/agents/sessions/session-manager-suffix-persistence.d.ts
declare class SessionManagerSuffixPersistence extends SessionManagerPersistence {
  /** @deprecated Await removeTrailingEntriesAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  removeTrailingEntries(predicate: (entry: SessionEntry$1) => boolean, options?: {
    preserveTrailing?: (entry: SessionEntry$1) => boolean;
  }): number;
  removeTrailingEntriesAsync(predicate: (entry: SessionEntry$1) => boolean, options?: {
    preserveTrailing?: (entry: SessionEntry$1) => boolean;
  }): Promise<number>;
  private prepareTrailingEntriesRemoval;
}
//#endregion
//#region src/agents/sessions/session-manager-append.d.ts
declare class SessionManagerAppend extends SessionManagerSuffixPersistence {
  #private;
  [sessionManagerReadMessageAnchor](entryId: string | null | undefined): Readonly<{
    agentId: string;
    sessionId: string;
    sessionKey: string;
    storePath: string;
    generation: string;
    entryId: string;
    rawSeq: number;
    effectiveParentId: string | null;
    activeMessagePosition: number;
    idempotencyKey?: string;
  }> | undefined;
  protected appendEntryAsync<T extends SessionEntry$1>(entry: T, options?: AppendPersistenceOptions, preserveParent?: boolean, modelPromptProjection?: PreparedModelPromptProjection): Promise<{
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
    viewWasSuperseded?: true;
  }>;
  protected appendEntry<T extends SessionEntry$1>(entry: T, options?: AppendPersistenceOptions, preserveParent?: boolean): {
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  protected adoptWorkerCommittedEntry<T extends SessionEntry$1>(entry: T, committed: PersistWorkerRecordResult, admittedUserId?: string, initialModel?: ModelChangeEntry): Promise<{
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
    viewWasSuperseded?: true;
  }>;
  protected adoptPersistedEntry<T extends SessionEntry$1>(canonicalEntry: T, persistenceResult: PersistRecordResult, admittedUserId: string | undefined, reload: (append?: {
    expectedMutationAt: number | null;
    expectedEntryId: string;
    admittedUserId: string;
  }) => void): {
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  resolveCurrentTurnEntryId(isInterruptedTail?: (entry: SessionEntry$1) => boolean, options?: {
    /** @deprecated Await openAsync and traverse the complete view without this option. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
    includeOmittedCustomMessages?: boolean;
  }): string | null;
  [sessionManagerPrepareCurrentTurnReplay](isInterruptedTail: (entry: SessionEntry$1) => boolean, matchesUser: (entry: SessionEntry$1 | undefined) => boolean, signal?: AbortSignal): Promise<CurrentTurnReplaySelection | undefined>;
  /** @deprecated Await appendMessageAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendMessage(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): string;
  appendMessageAsync(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): Promise<string | undefined>;
  appendMessageWithTranscriptAnchorAsync(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): Promise<ReturnType<SessionManagerAppend["appendMessageWithTranscriptAnchor"]> & {
    viewWasSuperseded?: true;
  }>;
  /** @deprecated Await appendMessageWithTranscriptAnchorAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendMessageWithTranscriptAnchor(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): {
    entryId: string;
    message: SessionMessageEntry["message"];
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  protected appendMessageWithTranscriptAnchorSync(message: SessionMessageEntry["message"], options?: AppendPersistenceOptions): {
    entryId: string;
    message: SessionMessageEntry["message"];
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
}
//#endregion
//#region src/agents/sessions/session-manager-entries.d.ts
type LeafControlSelection = {
  targetId: string | null;
  appendParentId: string | null;
  appendMode?: "side";
};
declare class SessionManagerEntries extends SessionManagerAppend {
  private createEntry;
  appendCompactionAsync(summary: string, firstKeptEntryId: string, tokensBefore: number, details?: unknown, fromHook?: boolean, metadata?: CompactionEntry["__openclaw"], tokensAfter?: number): Promise<string>;
  /** @deprecated Await appendCompactionAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendCompaction(summary: string, firstKeptEntryId: string, tokensBefore: number, details?: unknown, fromHook?: boolean, metadata?: CompactionEntry["__openclaw"], tokensAfter?: number): string;
  appendResetBoundaryAsync(reason: ResetReason, firstKeptEntryId?: string): Promise<string>;
  /** @deprecated Await appendResetBoundaryAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendResetBoundary(reason: ResetReason, firstKeptEntryId?: string): string;
  appendCustomEntryAsync(customType: string, data?: unknown): Promise<string>;
  /** @deprecated Await appendCustomEntryAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendCustomEntry(customType: string, data?: unknown): string;
  appendSessionInfoAsync(name: string): Promise<string>;
  /** @deprecated Await appendSessionInfoAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendSessionInfo(name: string): string;
  appendCustomMessageEntryAsync(customType: string, content: string | (TextContent | ImageContent$1)[], display: boolean, details?: unknown, timestamp?: number): Promise<string>;
  [sessionManagerAppendPromptContext](message: CustomMessage, prepare: PrepareModelPromptProjection): Promise<string>;
  /** @deprecated Await appendCustomMessageEntryAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendCustomMessageEntry(customType: string, content: string | (TextContent | ImageContent$1)[], display: boolean, details?: unknown, timestamp?: number): string;
  appendLeafControlAsync(params: LeafControlSelection): Promise<SessionLeafControl>;
  /** @deprecated Await appendLeafControlAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendLeafControl(params: LeafControlSelection): SessionLeafControl;
  private validateLeafControl;
  protected appendLeafControlSync(params: LeafControlSelection): SessionLeafControl;
  private createSelectedLeafControl;
  private adoptLeafSelection;
  appendLabelChangeAsync(targetId: string, label: string | undefined): Promise<string>;
  /** @deprecated Await appendLabelChangeAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendLabelChange(targetId: string, label: string | undefined): string;
  buildSessionContext(): SessionContext;
  /** Omitted projection metadata follows its retained branch anchors, outside model history. */
  getToolResultProjectionEntries(): (Record<string, unknown> | SessionEntry$1)[];
  branchAsync(branchFromId: string): Promise<void>;
  /** @deprecated Await branchAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  branch(branchFromId: string): void;
  protected branchSync(branchFromId: string): void;
  private selectBranch;
  resetLeaf(): void;
  resetLeafAsync(): Promise<void>;
  branchWithSummaryAsync(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): Promise<string>;
  /** @deprecated Await branchWithSummaryAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string;
  private createBranchSummary;
}
//#endregion
//#region src/agents/sessions/session-manager-metadata.d.ts
/** @internal Session factory initialization is not part of the public SessionManager API. */
declare const sessionManagerAppendInitialMetadata: unique symbol;
declare class SessionManagerMetadata extends SessionManagerEntries {
  private appendMetadataEntry;
  private publishMetadataCommit;
  [sessionManagerAppendInitialMetadata](provider: string, modelId: string, thinkingLevel: string): Promise<string>;
  appendThinkingLevelChange(thinkingLevel: string): Promise<string>;
  appendModelChange(provider: string, modelId: string): Promise<string>;
}
//#endregion
//#region src/agents/sessions/session-manager-branching.d.ts
declare class SessionManagerBranching extends SessionManagerMetadata {
  /** A context-only view must not rewind past omitted, user-visible entries. */
  hasLoadedTranscriptTail(entryId: string, parentId: string | null): boolean;
  private collectBranchedSessionPath;
  createBranchedSession(leafId: string): Promise<string | undefined>;
}
//#endregion
//#region src/agents/sessions/session-manager.d.ts
declare class SessionManager extends SessionManagerBranching {
  private preparedInitialContext?;
  private constructor();
  [sessionManagerReadTranscriptStart](): {
    agentId: string;
    sessionId: string;
    sessionKey: string;
    storePath: string;
    generation: string | null;
    maxSeq: number | null;
  } | null;
  [sessionManagerReadInitialContext](): Promise<SessionContext$1>;
  /** No buffered writes remain here; asynchronous metadata methods own their settlement. */
  flushPendingPersistence(): void;
  /** @deprecated Await appendMessageAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendMessage(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): string;
  /** @deprecated Await appendMessageWithTranscriptAnchorAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendMessageWithTranscriptAnchor(message: Message$1 | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): {
    entryId: string;
    message: SessionMessageEntry["message"];
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  /** @deprecated Await prepareTranscriptRewriteAsync and its commit. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  prepareTranscriptRewrite(): {
    sessionManager: SessionManager;
    commit: (ids: ReadonlyMap<string, string>) => void;
  };
  /** Preparation returns a detached branch; only its awaited commit publishes changes. */
  prepareTranscriptRewriteAsync(): Promise<{
    sessionManager: SessionManager;
    commit: (ids: ReadonlyMap<string, string>) => Promise<void>;
  }>;
  private prepareTranscriptRewriteView;
  /** Opens an existing store off-thread; empty transcripts keep lazy header initialization. */
  static openAsync(target: SessionTranscriptRuntimeTarget, cwdOverride?: string, contextLimits?: SessionManagerBoundedContextLimits, signal?: AbortSignal): Promise<SessionManager>;
  /** @internal Read complete current context and compaction facts in one owner snapshot. */
  static [sessionManagerOpenCompaction](target: SessionTranscriptRuntimeTarget, options?: {
    cwd?: string;
    signal?: AbortSignal;
  }): Promise<{
    sessionTarget: SessionTranscriptRuntimeTarget;
    entry: InternalSessionEntry | undefined;
    runtimeEntry: InternalSessionEntry | undefined;
    primaryConversation: ConversationRecord | undefined;
    eventCount: number;
    sessionManager: SessionManager;
  }>;
  /** @deprecated Await openAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static open(target: SessionTranscriptRuntimeTarget, cwdOverride?: string, contextLimits?: SessionManagerBoundedContextLimits): SessionManager;
  /** @deprecated Await openBoundedAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static openBounded(target: SessionTranscriptRuntimeTarget, options: SessionManagerBoundedContextLimits & {
    cwd?: string;
    onTruncated?: () => void;
  }): SessionManager;
  /** Reads an existing store's bounded view under the history worker's database custody. */
  static [sessionManagerOpenTranscriptCohort](target: SessionTranscriptRuntimeTarget, options: SessionManagerBoundedContextLimits & {
    cwd?: string;
    signal?: AbortSignal;
  }, selection: SessionManagerTranscriptCohort["selection"], consume: (manager: SessionManager, ...prepared: Parameters<SessionManagerTranscriptCohort["consume"]>) => void): Promise<SessionManager>;
  /** Reads an existing store's bounded view under the history worker's database custody. */
  static openBoundedAsync(target: SessionTranscriptRuntimeTarget, options: SessionManagerBoundedContextLimits & {
    cwd?: string;
    onTruncated?: () => void;
    signal?: AbortSignal;
  }): Promise<SessionManager>;
  private static detachBounded;
  /** Detach the prepared bounded branch without retaining database custody. */
  static openDetachedBoundedAsync(target: SessionTranscriptRuntimeTarget, options: Parameters<typeof SessionManager.openBoundedAsync>[1]): Promise<SessionManager>;
  /** @deprecated Await openDetachedBoundedAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static openDetachedBounded(target: SessionTranscriptRuntimeTarget, options: Parameters<typeof SessionManager.openBounded>[1]): SessionManager;
  /** @deprecated Await openModelContextAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static openModelContext(target: SessionTranscriptRuntimeTarget, options?: {
    cwd?: string;
    admission?: UserTurnTranscriptAdmissionReceipt;
    through?: TranscriptEntryAnchor;
    limits?: SessionModelContextLimits;
  }): SessionManager;
  /** The same detached model view, with durable transcript scanning off the event loop. */
  static openModelContextAsync(target: SessionTranscriptRuntimeTarget, options?: {
    cwd?: string;
    admission?: UserTurnTranscriptAdmissionReceipt;
    signal?: AbortSignal;
    through?: TranscriptEntryAnchor;
    limits?: SessionModelContextLimits;
  }): Promise<SessionManager>;
  /** The source snapshot's version, including writes beyond a selected admission prefix. */
  getTranscriptSnapshotVersion(): Readonly<SessionTranscriptContextVersion> | undefined;
  private static fromSelectedEntries;
  /** @deprecated Await readSessionContextAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  static readSessionContext<T>(target: SessionTranscriptRuntimeTarget, read: (messages: Iterable<AgentMessage>, header: unknown) => T, options?: {
    admission?: UserTurnTranscriptAdmissionReceipt;
  }): T;
  /** Consume a full-fidelity snapshot while retaining its owner through the consumer. */
  static readSessionContextAsync<T>(target: SessionTranscriptRuntimeTarget, read: (messages: Iterable<AgentMessage>, header: unknown) => T | Promise<T>, options?: {
    admission?: UserTurnTranscriptAdmissionReceipt;
    signal?: AbortSignal;
  }): Promise<T>;
  /**
   * @deprecated Await appendMessageToTranscriptAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release.
   */
  static appendMessageToTranscript(target: SessionTranscriptRuntimeTarget, message: Message$1 | CustomMessage | BashExecutionMessage, options?: Pick<AppendPersistenceOptions, "config">): string;
  static appendMessageToTranscriptAsync(target: SessionTranscriptRuntimeTarget, message: Message$1 | CustomMessage | BashExecutionMessage, options?: Pick<AppendPersistenceOptions, "config">): Promise<string>;
  static inMemory(cwd?: string): SessionManager;
  static fromEntries(entries: readonly unknown[], cwdOverride?: string): SessionManager;
}
type ReadonlySessionManager = Pick<SessionManager, SessionManagerReadMethod>;
//#endregion
//#region src/agents/sessions/slash-commands.d.ts
type SlashCommandSource = "extension" | "prompt" | "skill";
interface SlashCommandInfo {
  name: string;
  description?: string;
  source: SlashCommandSource;
  sourceInfo: SourceInfo;
}
//#endregion
//#region src/agents/sessions/diagnostics.d.ts
interface ResourceCollision {
  resourceType: "extension" | "skill" | "prompt" | "theme";
  name: string;
  winnerPath: string;
  loserPath: string;
  winnerSource?: string;
  loserSource?: string;
}
interface ResourceDiagnostic {
  type: "warning" | "error" | "collision";
  message: string;
  path?: string;
  collision?: ResourceCollision;
}
//#endregion
//#region src/agents/sessions/system-prompt-metadata.d.ts
/** Prompt metadata exposed to before_agent_start extensions. */
interface BuildSystemPromptOptions {
  customPrompt?: string;
  selectedTools?: string[];
  toolSnippets?: Record<string, string>;
  promptGuidelines?: string[];
  appendSystemPrompt?: string;
  cwd: string;
  contextFiles?: Array<{
    path: string;
    content: string;
  }>;
  skills?: Skill[];
}
//#endregion
//#region src/agents/sessions/tools/bash-operations.d.ts
/**
 * Minimal shell execution interface injected into bash session tools.
 */
interface BashOperations {
  exec: (command: string, cwd: string, options: {
    /**
     * stdout and stderr are independent pipes, so each needs its own decode
     * state; tag chunks to keep them apart. Untagged chunks share one lane,
     * preserving behavior for operations that cannot distinguish streams.
     */
    onData: (data: Buffer, stream?: "stdout" | "stderr") => void;
    signal?: AbortSignal;
    timeout?: number;
    env?: NodeJS.ProcessEnv;
  }) => Promise<{
    exitCode: number | null;
  }>;
}
//#endregion
//#region src/agents/sessions/tools/tool-schemas.d.ts
declare const bashSchema: Type$1.TObject<{
  title: Type$1.TOptional<Type$1.TString>;
  command: Type$1.TString;
  timeout: Type$1.TOptional<Type$1.TNumber>;
}>;
declare const editSchema: Type$1.TObject<{
  path: Type$1.TString;
  edits: Type$1.TArray<Type$1.TObject<{
    oldText: Type$1.TString;
    newText: Type$1.TString;
  }>>;
}>;
declare const EditToolOutputSchema: Type$1.TUnion<[Type$1.TObject<{
  changed: Type$1.TLiteral<false>;
}>, Type$1.TObject<{
  changed: Type$1.TLiteral<true>;
  diff: Type$1.TString;
  patch: Type$1.TString;
  firstChangedLine: Type$1.TOptional<Type$1.TInteger>;
}>]>;
declare const findSchema: Type$1.TObject<{
  pattern: Type$1.TString;
  path: Type$1.TOptional<Type$1.TString>;
  limit: Type$1.TOptional<Type$1.TInteger>;
}>;
declare const grepSchema: Type$1.TObject<{
  pattern: Type$1.TString;
  path: Type$1.TOptional<Type$1.TString>;
  glob: Type$1.TOptional<Type$1.TString>;
  ignoreCase: Type$1.TOptional<Type$1.TBoolean>;
  literal: Type$1.TOptional<Type$1.TBoolean>;
  context: Type$1.TOptional<Type$1.TNumber>;
  limit: Type$1.TOptional<Type$1.TNumber>;
}>;
declare const lsSchema: Type$1.TObject<{
  path: Type$1.TOptional<Type$1.TString>;
  limit: Type$1.TOptional<Type$1.TNumber>;
  after: Type$1.TOptional<Type$1.TString>;
}>;
declare const readToolInputSchema: Type$1.TObject<{
  path: Type$1.TString;
  offset: Type$1.TOptional<Type$1.TInteger>;
  limit: Type$1.TOptional<Type$1.TNumber>;
  cursor: Type$1.TOptional<Type$1.TInteger>;
  optional: Type$1.TOptional<Type$1.TLiteral<true>>;
}>;
declare const readToolOutputSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"text">;
  content: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"image">;
  content: Type$1.TString;
  mimeType: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"truncated">;
  content: Type$1.TString;
  truncation: Type$1.TObject<{
    truncated: Type$1.TLiteral<true>;
    truncatedBy: Type$1.TUnion<[Type$1.TLiteral<"lines">, Type$1.TLiteral<"bytes">]>;
    totalLines: Type$1.TOptional<Type$1.TInteger>;
    totalBytes: Type$1.TOptional<Type$1.TInteger>;
    outputLines: Type$1.TInteger;
    outputBytes: Type$1.TInteger;
    lastLinePartial: Type$1.TBoolean;
    firstLineExceedsLimit: Type$1.TBoolean;
    maxLines: Type$1.TInteger;
    maxBytes: Type$1.TInteger;
  }>;
  continuation: Type$1.TUnion<[Type$1.TObject<{
    offset: Type$1.TInteger;
    limit: Type$1.TOptional<Type$1.TInteger>;
    kind: Type$1.TLiteral<"line">;
  }>, Type$1.TObject<{
    offset: Type$1.TInteger;
    limit: Type$1.TOptional<Type$1.TInteger>;
    kind: Type$1.TLiteral<"cursor">;
    cursor: Type$1.TInteger;
  }>]>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"not_found">;
  status: Type$1.TLiteral<"not_found">;
  path: Type$1.TString;
  optional: Type$1.TLiteral<true>;
}>]>;
declare const writeSchema: Type$1.TObject<{
  path: Type$1.TString;
  content: Type$1.TString;
}>;
//#endregion
//#region src/agents/sessions/tools/tool-contracts.d.ts
type BashToolInput = Static<typeof bashSchema>;
interface BashToolDetails {
  truncation?: TruncationResult;
  fullOutputPath?: string;
}
type EditToolInput = Static<typeof editSchema>;
type EditToolDetails = Static<typeof EditToolOutputSchema>;
type FindToolInput = Static<typeof findSchema>;
interface FindToolDetails {
  content: string;
  truncation?: Omit<TruncationResult, "content">;
  resultLimitReached?: number;
}
type GrepToolInput = Static<typeof grepSchema>;
interface GrepToolDetails {
  content: string;
  truncation?: Omit<TruncationResult, "content">;
  matchLimitReached?: number;
  linesTruncated?: boolean;
}
type LsToolInput = Static<typeof lsSchema>;
interface LsToolDetails {
  content: string;
  nextAfter?: string;
}
type ReadToolInput = Static<typeof readToolInputSchema>;
type ReadToolDetails = Static<typeof readToolOutputSchema>;
type WriteToolInput = Static<typeof writeSchema>;
//#endregion
//#region src/agents/sessions/extensions/types.d.ts
interface ExtensionUIDialogOptions {
  /** AbortSignal to programmatically dismiss the dialog. */
  signal?: AbortSignal;
  /** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */
  timeout?: number;
}
interface ExtensionWidgetOptions {
  /** Where the widget is rendered. Defaults to "aboveEditor". */
  placement?: "aboveEditor" | "belowEditor";
}
/** Working indicator configuration for the interactive streaming loader. */
interface WorkingIndicatorOptions {
  /** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */
  frames?: string[];
  /** Frame interval in milliseconds for animated indicators. */
  intervalMs?: number;
}
type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager$1) => EditorComponent;
/**
 * UI context for extensions to request interactive UI.
 * Each mode (interactive, RPC, print) provides its own implementation.
 */
interface ExtensionUIContext {
  select(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
  confirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;
  input(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
  notify(message: string, type?: "info" | "warning" | "error"): void;
  /** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */
  onTerminalInput(handler: (data: string) => {
    consume?: boolean;
    data?: string;
  } | undefined): () => void;
  /** Set status text in the footer/status bar. Pass undefined to clear. */
  setStatus(key: string, text: string | undefined): void;
  /** Set the working/loading message shown during streaming. Call with no argument to restore default. */
  setWorkingMessage(message?: string): void;
  /** Show or hide the built-in interactive working loader row during streaming. */
  setWorkingVisible(visible: boolean): void;
  /**
   * Configure the interactive working indicator shown during streaming.
   *
   * - Omit the argument to restore the default animated spinner.
   * - Use `frames: ["●"]` for a static indicator.
   * - Use `frames: []` to hide the indicator entirely.
   * - Custom frames are rendered as provided, so extensions must add their own colors.
   */
  setWorkingIndicator(options?: WorkingIndicatorOptions): void;
  /** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */
  setHiddenThinkingLabel(label?: string): void;
  /** Set a widget to display above or below the editor. Accepts string array or component factory. */
  setWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;
  setWidget(key: string, content: ((tui: TUI, theme: Theme) => Component & {
    dispose?(): void;
  }) | undefined, options?: ExtensionWidgetOptions): void;
  /** Set a custom footer component, or undefined to restore the built-in footer.
   *
   * The factory receives a FooterDataProvider for data not otherwise accessible:
   * git branch and extension statuses from setStatus(). Token stats, model info,
   * etc. are available via ctx.sessionManager and ctx.model.
   */
  setFooter(factory: ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & {
    dispose?(): void;
  }) | undefined): void;
  /** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */
  setHeader(factory: ((tui: TUI, theme: Theme) => Component & {
    dispose?(): void;
  }) | undefined): void;
  /** Set the terminal window/tab title. */
  setTitle(title: string): void;
  /** Show a custom component with keyboard focus. */
  custom<T>(factory: (tui: TUI, theme: Theme, keybindings: KeybindingsManager$1, done: (result: T) => void) => (Component & {
    dispose?(): void;
  }) | Promise<Component & {
    dispose?(): void;
  }>, options?: {
    overlay?: boolean;
    /** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */
    overlayOptions?: OverlayOptions | (() => OverlayOptions);
    /** Called with the overlay handle after the overlay is shown. Use to control visibility. */
    onHandle?: (handle: OverlayHandle) => void;
  }): Promise<T>;
  /** Paste text into the editor, triggering paste handling (collapse for large content). */
  pasteToEditor(text: string): void;
  setEditorText(text: string): void;
  getEditorText(): string;
  /** Show a multi-line editor for text editing. */
  editor(title: string, prefill?: string): Promise<string | undefined>;
  /** Stack additional autocomplete behavior on top of the built-in provider. */
  addAutocompleteProvider(factory: (current: AutocompleteProvider) => AutocompleteProvider): void;
  /**
   * Set a custom editor component via factory function.
   * Pass undefined to restore the default editor.
   *
   * The factory receives:
   * - `theme`: EditorTheme for styling borders and autocomplete
   * - `keybindings`: KeybindingsManager for app-level keybindings
   *
   * For full app keybinding support (escape, ctrl+d, model switching, etc.),
   * extend `CustomEditor` from `openclaw/plugin-sdk/agent-sessions` and call
   * `super.handleInput(data)` for keys you don't handle.
   *
   * @example
   * ```ts
   * import { CustomEditor } from "openclaw/plugin-sdk/agent-sessions";
   *
   * class VimEditor extends CustomEditor {
   *   private mode: "normal" | "insert" = "insert";
   *
   *   handleInput(data: string): void {
   *     if (this.mode === "normal") {
   *       // Handle vim normal mode keys...
   *       if (data === "i") { this.mode = "insert"; return; }
   *     }
   *     super.handleInput(data);  // App keybindings + text editing
   *   }
   * }
   *
   * ctx.ui.setEditorComponent((tui, theme, keybindings) =>
   *   new VimEditor(tui, theme, keybindings)
   * );
   * ```
   */
  setEditorComponent(factory: EditorFactory | undefined): void;
  /** Get the currently configured custom editor factory, or undefined when using the default editor. */
  getEditorComponent(): EditorFactory | undefined;
  readonly theme: Theme;
  getAllThemes(): {
    name: string;
    path: string | undefined;
  }[];
  /** Load a theme by name without switching to it. Returns undefined if not found. */
  getTheme(name: string): Theme | undefined;
  setTheme(theme: string | Theme): {
    success: boolean;
    error?: string;
  };
  getToolsExpanded(): boolean;
  setToolsExpanded(expanded: boolean): void;
}
interface ContextUsage {
  /** Estimated context tokens, or null if any (e.g. right after compaction, before next LLM response). */
  tokens: number | null;
  contextWindow: number;
  /** Context usage as percentage of context window, or null if tokens is unknown. */
  percent: number | null;
}
interface CompactOptions {
  customInstructions?: string;
  onComplete?: (result: CompactionResult) => void;
  onError?: (error: Error) => void;
}
interface ExtensionContext {
  ui: ExtensionUIContext;
  /** Whether UI is available (false in print/RPC mode) */
  hasUI: boolean;
  cwd: string;
  sessionManager: ReadonlySessionManager;
  /** Model registry for API key resolution */
  modelRegistry: ModelRegistry$1;
  model: Model | undefined;
  /** Whether the agent is idle (not streaming) */
  isIdle(): boolean;
  /** The current abort signal, or undefined when the agent is not streaming. */
  signal: AbortSignal | undefined;
  abort(): void;
  hasPendingMessages(): boolean;
  /** Gracefully shut down OpenClaw and exit. Available in all contexts. */
  shutdown(): void;
  getContextUsage(): ContextUsage | undefined;
  /** Trigger compaction without awaiting completion. */
  compact(options?: CompactOptions): void;
  getSystemPrompt(): string;
}
/**
 * Extended context for command handlers.
 * Includes session control methods only safe in user-initiated commands.
 */
interface ExtensionCommandContext extends ExtensionContext {
  /** Wait for the agent to finish streaming */
  waitForIdle(): Promise<void>;
  /** Start a new session, optionally with initialization. */
  newSession(options?: {
    parentSession?: string;
    setup?: (sessionManager: SessionManager) => Promise<void>;
    withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
  }): Promise<{
    cancelled: boolean;
  }>;
  /** Fork from a specific entry, creating a new session file. */
  fork(entryId: string, options?: {
    position?: "before" | "at";
    withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
  }): Promise<{
    cancelled: boolean;
  }>;
  /** Navigate to a different point in the session tree. */
  navigateTree(targetId: string, options?: {
    summarize?: boolean;
    customInstructions?: string;
    replaceInstructions?: boolean;
    label?: string;
  }): Promise<{
    cancelled: boolean;
  }>;
  /** Switch to a different session file. */
  switchSession(sessionPath: string, options?: {
    withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
  }): Promise<{
    cancelled: boolean;
  }>;
  /** Reload extensions, skills, prompts, and themes. */
  reload(): Promise<void>;
}
/**
 * Fresh command-capable context bound to the replacement session after a session switch.
 *
 * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.
 */
interface ReplacedSessionContext extends ExtensionCommandContext {
  sendMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
    triggerTurn?: boolean;
    deliverAs?: "steer" | "followUp" | "nextTurn";
  }): Promise<void>;
  sendUserMessage(content: string | (TextContent | ImageContent$1)[], options?: {
    deliverAs?: "steer" | "followUp";
  }): Promise<void>;
}
interface ToolRenderResultOptions {
  expanded: boolean;
  /** Whether this is a partial/streaming result */
  isPartial: boolean;
}
interface ToolRenderContext<TState = unknown, TArgs = unknown> extends ToolRenderResultOptions {
  /** Current tool call arguments. Shared across call/result renders for the same tool call. */
  args: TArgs;
  /** Unique id for this tool execution. Stable across call/result renders for the same tool call. */
  toolCallId: string;
  /** Invalidate just this tool execution component for redraw. */
  invalidate: () => void;
  /** Previously returned component for this render slot, if any. */
  lastComponent: Component | undefined;
  /** Shared renderer state for this tool row. Initialized by tool-execution.ts. */
  state: TState;
  cwd: string;
  executionStarted: boolean;
  argsComplete: boolean;
  /** Whether inline images are currently shown in the TUI. */
  showImages: boolean;
  isError: boolean;
}
type BivariantCallback<TArgs extends unknown[], TResult> = {
  bivarianceHack(...args: TArgs): TResult;
}["bivarianceHack"];
interface ToolDefinition$1<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown> extends Pick<AgentTool<TParams, TDetails>, "name" | "label" | "hideFromChannelProgress" | "resultContentSource" | "description" | "parameters" | "outputSchema" | "prepareArguments" | "async"> {
  /** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */
  promptSnippet?: string;
  /** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */
  promptGuidelines?: string[];
  /** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */
  renderShell?: "default" | "self";
  executionMode?: ToolExecutionMode;
  execute(toolCallId: string, params: Static<TParams>, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<TDetails> | undefined, ctx: ExtensionContext): Promise<AgentToolResult<TDetails>>;
  renderCall?: BivariantCallback<[args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>], Component>;
  renderResult?: BivariantCallback<[result: AgentToolResult<TDetails>, options: ToolRenderResultOptions, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>], Component>;
}
/** Fired after session_start to allow extensions to provide additional resource paths. */
interface ResourcesDiscoverEvent {
  type: "resources_discover";
  cwd: string;
  reason: "startup" | "reload";
}
interface ResourcesDiscoverResult {
  skillPaths?: string[];
  promptPaths?: string[];
  themePaths?: string[];
}
/** Fired when a session is started, loaded, or reloaded */
interface SessionStartEvent {
  type: "session_start";
  reason: "startup" | "reload" | "new" | "resume" | "fork";
  /** Previously active session file. Present for "new", "resume", and "fork". */
  previousSessionFile?: string;
}
/** Fired before switching to another session (can be cancelled) */
interface SessionBeforeSwitchEvent {
  type: "session_before_switch";
  reason: "new" | "resume";
  targetSessionFile?: string;
}
/** Fired before forking a session (can be cancelled) */
interface SessionBeforeForkEvent {
  type: "session_before_fork";
  entryId: string;
  position: "before" | "at";
}
/** Fired before context compaction (can be cancelled or customized) */
interface SessionBeforeCompactEvent {
  type: "session_before_compact";
  preparation: CompactionPreparation;
  branchEntries: SessionEntry$1[];
  customInstructions?: string;
  signal: AbortSignal;
  /** Prepared reasoning level for extension-owned summarization. */
  thinkingLevel?: ThinkingLevel;
  /** Prepared provider stream for extension-owned summarization. */
  streamFn?: StreamFn$1;
}
/** Fired after context compaction */
interface SessionCompactEvent {
  type: "session_compact";
  compactionEntry: CompactionEntry;
  fromExtension: boolean;
}
/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */
interface SessionShutdownEvent {
  type: "session_shutdown";
  reason: "quit" | "reload" | "new" | "resume" | "fork";
  /** Destination session file when shutting down due to session replacement. */
  targetSessionFile?: string;
}
interface TreePreparation {
  targetId: string;
  oldLeafId: string | null;
  commonAncestorId: string | null;
  entriesToSummarize: SessionEntry$1[];
  userWantsSummary: boolean;
  customInstructions?: string;
  /** If true, customInstructions replaces the default prompt instead of being appended */
  replaceInstructions?: boolean;
  /** Label to attach to the branch summary entry */
  label?: string;
}
/** Fired before navigating in the session tree (can be cancelled) */
interface SessionBeforeTreeEvent {
  type: "session_before_tree";
  preparation: TreePreparation;
  signal: AbortSignal;
}
/** Fired after navigating in the session tree */
interface SessionTreeEvent {
  type: "session_tree";
  newLeafId: string | null;
  oldLeafId: string | null;
  summaryEntry?: BranchSummaryEntry;
  fromExtension?: boolean;
}
/** Fired before each LLM call. Can modify messages. */
interface ContextEvent {
  type: "context";
  messages: AgentMessage[];
}
/** Fired before a provider request is sent. Can replace the payload. */
interface BeforeProviderRequestEvent {
  type: "before_provider_request";
  payload: unknown;
}
/** Fired after a provider response is received and before the response stream is consumed. */
interface AfterProviderResponseEvent {
  type: "after_provider_response";
  status: number;
  headers: Record<string, string>;
}
/** Fired after user submits prompt but before agent loop. */
interface BeforeAgentStartEvent {
  type: "before_agent_start";
  /** The raw user prompt text (after expansion). */
  prompt: string;
  images?: ImageContent$1[];
  systemPrompt: string;
  /** Structured options used to build the system prompt. Extensions can inspect this without re-discovering resources. */
  systemPromptOptions: BuildSystemPromptOptions;
}
type RuntimeAgentEvent<Type extends AgentEvent$1["type"]> = Extract<AgentEvent$1, {
  type: Type;
}>;
interface AgentStartEvent extends RuntimeAgentEvent<"agent_start"> {}
interface AgentEndEvent extends RuntimeAgentEvent<"agent_end"> {}
/** Fired once the session has no automatic retry, compaction, or queued continuation left. */
interface AgentSettledEvent {
  type: "agent_settled";
}
interface TurnStartEvent extends RuntimeAgentEvent<"turn_start"> {
  turnIndex: number;
  timestamp: number;
}
interface TurnEndEvent extends RuntimeAgentEvent<"turn_end"> {
  turnIndex: number;
}
/** Fired when a message starts (user, assistant, or toolResult) */
interface MessageStartEvent extends RuntimeAgentEvent<"message_start"> {}
/** Fired during assistant message streaming with token-by-token updates */
interface MessageUpdateEvent extends RuntimeAgentEvent<"message_update"> {}
interface MessageEndEvent extends RuntimeAgentEvent<"message_end"> {}
interface ToolExecutionStartEvent extends Omit<RuntimeAgentEvent<"tool_execution_start">, "hideFromChannelProgress"> {}
/** Fired during tool execution with partial/streaming output */
interface ToolExecutionUpdateEvent extends Omit<RuntimeAgentEvent<"tool_execution_update">, "hideFromChannelProgress"> {}
interface ToolExecutionEndEvent extends Omit<RuntimeAgentEvent<"tool_execution_end">, "assistantTurnId" | "executionStarted" | "errorKind" | "hideFromChannelProgress"> {}
interface ModelSelectEvent {
  type: "model_select";
  model: Model;
  previousModel: Model | undefined;
  source: "set" | "cycle" | "restore";
}
interface ThinkingLevelSelectEvent {
  type: "thinking_level_select";
  level: ThinkingLevel;
  previousLevel: ThinkingLevel;
}
/** Fired when user executes a bash command via ! or !! prefix */
interface UserBashEvent {
  type: "user_bash";
  command: string;
  /** True if !! prefix was used (excluded from LLM context) */
  excludeFromContext: boolean;
  cwd: string;
}
type InputSource = "interactive" | "rpc" | "extension";
/** Fired when user input is received, before agent processing */
interface InputEvent {
  type: "input";
  text: string;
  images?: ImageContent$1[];
  source: InputSource;
}
type InputEventResult = {
  action: "continue";
} | {
  action: "transform";
  text: string;
  images?: ImageContent$1[];
} | {
  action: "handled";
};
interface ToolCallEventBase<TName extends string, TInput> {
  type: "tool_call";
  toolCallId: string;
  toolName: TName;
  input: TInput;
}
/**
 * Fired before a tool executes. Can block.
 *
 * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
 * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.
 */
type ToolCallEvent = ToolCallEventBase<"bash", BashToolInput> | ToolCallEventBase<"read", ReadToolInput> | ToolCallEventBase<"edit", EditToolInput> | ToolCallEventBase<"write", WriteToolInput> | ToolCallEventBase<"grep", GrepToolInput> | ToolCallEventBase<"find", FindToolInput> | ToolCallEventBase<"ls", LsToolInput> | ToolCallEventBase<string, Record<string, unknown>>;
interface ToolResultEventBase<TName extends string, TDetails> {
  type: "tool_result";
  toolCallId: string;
  toolName: TName;
  input: Record<string, unknown>;
  content: (TextContent | ImageContent$1)[];
  details: TDetails;
  isError: boolean;
  terminate?: boolean;
}
/** Fired after a tool executes. Can modify result. */
type ToolResultEvent = ToolResultEventBase<"bash", BashToolDetails | undefined> | ToolResultEventBase<"read", ReadToolDetails | undefined> | ToolResultEventBase<"edit", EditToolDetails | undefined> | ToolResultEventBase<"write", undefined> | ToolResultEventBase<"grep", GrepToolDetails | undefined> | ToolResultEventBase<"find", FindToolDetails | undefined> | ToolResultEventBase<"ls", LsToolDetails | undefined> | ToolResultEventBase<string, unknown>;
type ExtensionEvent = ResourcesDiscoverEvent | (SessionStartEvent | SessionBeforeSwitchEvent | SessionBeforeForkEvent | SessionBeforeCompactEvent | SessionCompactEvent | SessionShutdownEvent | SessionBeforeTreeEvent | SessionTreeEvent) | ContextEvent | BeforeProviderRequestEvent | AfterProviderResponseEvent | BeforeAgentStartEvent | AgentStartEvent | AgentEndEvent | AgentSettledEvent | TurnStartEvent | TurnEndEvent | MessageStartEvent | MessageUpdateEvent | MessageEndEvent | ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent | ModelSelectEvent | ThinkingLevelSelectEvent | UserBashEvent | InputEvent | ToolCallEvent | ToolResultEvent;
interface ContextEventResult {
  messages?: AgentMessage[];
}
interface ToolCallEventResult {
  /** Block tool execution. To modify arguments, mutate `event.input` in place instead. */
  block?: boolean;
  reason?: string;
}
interface UserBashEventResult {
  /** Custom operations to use for execution */
  operations?: BashOperations;
  /** Full replacement: extension handled execution, use this result */
  result?: BashResult;
}
interface ToolResultEventResult extends AfterToolCallResult {}
interface MessageEndEventResult {
  /** Replace the finalized message. The replacement must keep the original message role. */
  message?: AgentMessage;
}
interface BeforeAgentStartEventResult {
  message?: Pick<CustomMessage, "customType" | "content" | "display" | "details">;
  /** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */
  systemPrompt?: string;
}
interface SessionBeforeSwitchResult {
  cancel?: boolean;
}
interface SessionBeforeForkResult {
  cancel?: boolean;
  skipConversationRestore?: boolean;
}
interface SessionBeforeCompactResult {
  cancel?: boolean;
  compaction?: CompactionResult;
}
interface SessionBeforeTreeResult {
  cancel?: boolean;
  summary?: {
    summary: string;
    details?: unknown;
  };
  /** Override custom instructions for summarization */
  customInstructions?: string;
  /** Override whether customInstructions replaces the default prompt */
  replaceInstructions?: boolean;
  /** Override label to attach to the branch summary entry */
  label?: string;
}
interface MessageRenderOptions {
  expanded: boolean;
}
type MessageRenderer<T = unknown> = (message: CustomMessage<T>, options: MessageRenderOptions, theme: Theme) => Component | undefined;
interface RegisteredCommand {
  name: string;
  sourceInfo: SourceInfo;
  description?: string;
  getArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;
  handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
}
interface ResolvedCommand extends RegisteredCommand {
  invocationName: string;
}
type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;
interface ExtensionAPI {
  on(event: "resources_discover", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;
  on(event: "session_start", handler: ExtensionHandler<SessionStartEvent>): void;
  on(event: "session_before_switch", handler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>): void;
  on(event: "session_before_fork", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;
  on(event: "session_before_compact", handler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>): void;
  on(event: "session_compact", handler: ExtensionHandler<SessionCompactEvent>): void;
  on(event: "session_shutdown", handler: ExtensionHandler<SessionShutdownEvent>): void;
  on(event: "session_before_tree", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;
  on(event: "session_tree", handler: ExtensionHandler<SessionTreeEvent>): void;
  on(event: "context", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;
  on(event: "before_provider_request", handler: ExtensionHandler<BeforeProviderRequestEvent, unknown>): void;
  on(event: "after_provider_response", handler: ExtensionHandler<AfterProviderResponseEvent>): void;
  on(event: "before_agent_start", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;
  on(event: "agent_start", handler: ExtensionHandler<AgentStartEvent>): void;
  on(event: "agent_end", handler: ExtensionHandler<AgentEndEvent>): void;
  on(event: "agent_settled", handler: ExtensionHandler<AgentSettledEvent>): void;
  on(event: "turn_start", handler: ExtensionHandler<TurnStartEvent>): void;
  on(event: "turn_end", handler: ExtensionHandler<TurnEndEvent>): void;
  on(event: "message_start", handler: ExtensionHandler<MessageStartEvent>): void;
  on(event: "message_update", handler: ExtensionHandler<MessageUpdateEvent>): void;
  on(event: "message_end", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): void;
  on(event: "tool_execution_start", handler: ExtensionHandler<ToolExecutionStartEvent>): void;
  on(event: "tool_execution_update", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;
  on(event: "tool_execution_end", handler: ExtensionHandler<ToolExecutionEndEvent>): void;
  on(event: "model_select", handler: ExtensionHandler<ModelSelectEvent>): void;
  on(event: "thinking_level_select", handler: ExtensionHandler<ThinkingLevelSelectEvent>): void;
  on(event: "tool_call", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;
  on(event: "tool_result", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;
  on(event: "user_bash", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;
  on(event: "input", handler: ExtensionHandler<InputEvent, InputEventResult>): void;
  registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(tool: ToolDefinition$1<TParams, TDetails, TState>): void;
  registerCommand(name: string, options: Omit<RegisteredCommand, "name" | "sourceInfo">): void;
  registerShortcut(shortcut: KeyId, options: Omit<ExtensionShortcut, "shortcut" | "extensionPath">): void;
  registerFlag(name: string, options: Omit<ExtensionFlag, "name" | "extensionPath">): void;
  getFlag(name: string): boolean | string | undefined;
  /** Register a custom renderer for CustomMessageEntry. */
  registerMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;
  /** Send a custom message to the session. */
  sendMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
    triggerTurn?: boolean;
    deliverAs?: "steer" | "followUp" | "nextTurn";
  }): void;
  /**
   * Send a user message to the agent. Always triggers a turn.
   * When the agent is streaming, use deliverAs to specify how to queue the message.
   */
  sendUserMessage(content: string | (TextContent | ImageContent$1)[], options?: {
    deliverAs?: "steer" | "followUp";
  }): void;
  /** @deprecated Await appendEntryAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  appendEntry(customType: string, data?: unknown): void;
  /** Persist a custom entry and return its id after the worker commits. */
  appendEntryAsync(customType: string, data?: unknown): Promise<string>;
  /** @deprecated Await setSessionNameAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  setSessionName(name: string): void;
  /** Set the display name and publish the change after the worker commits. */
  setSessionNameAsync(name: string): Promise<void>;
  getSessionName(): string | undefined;
  /** @deprecated Await setLabelAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  setLabel(entryId: string, label: string | undefined): void;
  /** Set or clear an entry label after the worker commits. */
  setLabelAsync(entryId: string, label: string | undefined): Promise<void>;
  exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
  getActiveTools(): string[];
  /** Get all configured tools with parameter schema and source metadata. */
  getAllTools(): ToolInfo[];
  setActiveTools(toolNames: string[]): void;
  /** Get available slash commands in the current session. */
  getCommands(): SlashCommandInfo[];
  /** Set the current model. Returns false if no API key available. */
  setModel(model: Model): Promise<boolean>;
  getThinkingLevel(): ThinkingLevel;
  /** Set thinking level (clamped to model capabilities). */
  setThinkingLevel(level: ThinkingLevel): Promise<void>;
  /**
   * Register a model provider.
   *
   * If `models` is provided: replaces all existing models for this provider.
   * If `oauth` is provided: registers OAuth provider for /login support.
   * If `streamSimple` is provided: registers a custom API stream handler.
   *
   * During initial extension load this call is queued and applied once the
   * runner has bound its context. After that it takes effect immediately, so
   * it is safe to call from command handlers or event callbacks without
   * requiring a `/reload`.
   *
   * @example
   * // Register a new provider with custom models
   * api.registerProvider("my-proxy", {
   *   baseUrl: "https://proxy.example.com",
   *   apiKey: "PROXY_API_KEY",
   *   api: "anthropic-messages",
   *   models: [
   *     {
   *       id: "claude-sonnet-4-20250514",
   *       name: "Claude 4 Sonnet (proxy)",
   *       reasoning: false,
   *       input: ["text", "image"],
   *       cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
   *       contextWindow: 200000,
   *       maxTokens: 16384
   *     }
   *   ]
   * });
   *
   * @example
   * // Override baseUrl for an existing provider
   * api.registerProvider("anthropic", {
   *   baseUrl: "https://proxy.example.com"
   * });
   *
   * @example
   * // Register provider with OAuth support
   * api.registerProvider("corporate-ai", {
   *   baseUrl: "https://ai.corp.com",
   *   api: "openai-responses",
   *   models: [...],
   *   oauth: {
   *     name: "Corporate AI (SSO)",
   *     async login(callbacks) { ... },
   *     async refreshToken(credentials) { ... },
   *     getApiKey(credentials) { return credentials.access; }
   *   }
   * });
   */
  registerProvider(name: string, config: ProviderConfig): void;
  /**
   * Unregister a previously registered provider.
   *
   * Removes all models belonging to the named provider and reloads the configured
   * model registry. Has no effect if the provider is not currently registered.
   *
   * Like `registerProvider`, this takes effect immediately when called after
   * the initial load phase.
   *
   * @example
   * api.unregisterProvider("my-proxy");
   */
  unregisterProvider(name: string): void;
  /** Shared event bus for extension communication. */
  events: EventBus;
}
interface RegisteredTool {
  definition: ToolDefinition$1;
  sourceInfo: SourceInfo;
}
interface ExtensionFlag {
  name: string;
  description?: string;
  type: "boolean" | "string";
  default?: boolean | string;
  extensionPath: string;
}
interface ExtensionShortcut {
  shortcut: KeyId;
  description?: string;
  handler: (ctx: ExtensionContext) => Promise<void> | void;
  extensionPath: string;
}
type RefreshToolsHandler = () => void;
type ToolInfo = Pick<ToolDefinition$1, "name" | "description" | "parameters"> & {
  sourceInfo: SourceInfo;
};
/**
 * Shared state created by loader, used during registration and runtime.
 * Contains flag values (defaults set during registration, CLI values set after).
 */
interface ExtensionRuntimeState {
  flagValues: Map<string, boolean | string>;
  /** Provider registrations queued during extension loading, processed when runner binds */
  pendingProviderRegistrations: Array<{
    name: string;
    config: ProviderConfig;
    extensionPath: string;
  }>;
  /** Throws when this extension instance is stale after runtime replacement. */
  assertActive: () => void;
  /** Marks this extension instance as stale after runtime replacement or reload. */
  invalidate: (message?: string) => void;
  /**
   * Register or unregister a provider.
   *
   * Before bindCore(): queues registrations / removes from queue.
   * After bindCore(): calls ModelRegistry directly for immediate effect.
   */
  registerProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;
  unregisterProvider: (name: string, extensionPath?: string) => void;
}
/**
 * Action implementations for ExtensionAPI methods.
 * Provided to runner.initialize(), copied into the shared runtime.
 * @deprecated Use ExtensionActionsV2. Supported through 2026-12-31. Removal in the first January 2027 stable release.
 */
interface ExtensionActions extends Pick<ExtensionAPI, "sendMessage" | "sendUserMessage" | "appendEntry" | "setSessionName" | "getSessionName" | "setLabel" | "getActiveTools" | "getAllTools" | "setActiveTools" | "getCommands" | "setModel" | "getThinkingLevel" | "setThinkingLevel"> {
  refreshTools: RefreshToolsHandler;
}
/** Host actions with required worker-backed persistence capabilities. */
interface ExtensionActionsV2 extends ExtensionActions, Pick<ExtensionAPI, "appendEntryAsync" | "setSessionNameAsync" | "setLabelAsync"> {}
/** Actions for the live extension context, supplied by each runtime mode. */
interface ExtensionContextActions extends Pick<ExtensionContext, "isIdle" | "abort" | "hasPendingMessages" | "shutdown" | "getContextUsage" | "compact" | "getSystemPrompt"> {
  getModel: () => ExtensionContext["model"];
  getSignal: () => ExtensionContext["signal"];
}
/** Session controls provided by modes that support extension commands. */
interface ExtensionCommandContextActions extends Pick<ExtensionCommandContext, "waitForIdle" | "newSession" | "fork" | "navigateTree" | "switchSession" | "reload"> {}
/**
 * Full runtime = state + actions.
 * Created by loader with throwing action stubs, completed by runner.initialize().
 * @deprecated Use ExtensionRuntimeV2. Supported through 2026-12-31. Removal in the first January 2027 stable release.
 */
interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions, Partial<Pick<ExtensionActionsV2, "appendEntryAsync" | "setSessionNameAsync" | "setLabelAsync">> {}
interface Extension {
  path: string;
  resolvedPath: string;
  sourceInfo: SourceInfo;
  handlers: Map<string, ((...args: unknown[]) => Promise<unknown>)[]>;
  tools: Map<string, RegisteredTool>;
  messageRenderers: Map<string, MessageRenderer>;
  commands: Map<string, RegisteredCommand>;
  flags: Map<string, ExtensionFlag>;
  shortcuts: Map<KeyId, ExtensionShortcut>;
}
interface LoadExtensionsResult {
  extensions: Extension[];
  errors: Array<{
    path: string;
    error: string;
  }>;
  /** Shared runtime - actions are throwing stubs until runner.initialize() */
  runtime: ExtensionRuntime;
}
interface ExtensionError {
  extensionPath: string;
  event: string;
  error: string;
  stack?: string;
}
//#endregion
//#region src/agents/sessions/extensions/runner.d.ts
interface BeforeAgentStartCombinedResult {
  messages?: NonNullable<BeforeAgentStartEventResult["message"]>[];
  systemPrompt?: string;
}
type DiscoveredResourcePaths = Record<keyof ResourcesDiscoverResult, Array<{
  path: string;
  extensionPath: string;
}>>;
/**
 * Events handled by the generic emit() method.
 * Events with dedicated emitXxx() methods are excluded for stronger type safety.
 */
type RunnerEmitEvent = Exclude<ExtensionEvent, ToolCallEvent | ToolResultEvent | UserBashEvent | ContextEvent | BeforeProviderRequestEvent | BeforeAgentStartEvent | MessageEndEvent | ResourcesDiscoverEvent | InputEvent>;
type RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends {
  type: "session_before_switch";
} ? SessionBeforeSwitchResult | undefined : TEvent extends {
  type: "session_before_fork";
} ? SessionBeforeForkResult | undefined : TEvent extends {
  type: "session_before_compact";
} ? SessionBeforeCompactResult | undefined : TEvent extends {
  type: "session_before_tree";
} ? SessionBeforeTreeResult | undefined : undefined;
type ExtensionErrorListener = (error: ExtensionError) => void;
type ShutdownHandler = () => void;
declare class ExtensionRunner {
  private extensions;
  private runtime;
  private cwd;
  private sessionManager;
  private modelRegistry;
  private uiContext;
  private errorListeners;
  private getModel;
  private isIdleFn;
  private getSignalFn;
  private waitForIdleFn;
  private abortFn;
  private hasPendingMessagesFn;
  private getContextUsageFn;
  private compactFn;
  private getSystemPromptFn;
  private newSessionHandler;
  private forkHandler;
  private navigateTreeHandler;
  private switchSessionHandler;
  private reloadHandler;
  private shutdownHandler;
  private shortcutDiagnostics;
  private commandDiagnostics;
  private staleMessage;
  constructor(extensions: Extension[], runtime: ExtensionRuntime, cwd: string, sessionManager: SessionManager, modelRegistry: ModelRegistry$1);
  /** Bind host actions with worker-backed persistence; legacy bindCore remains source-compatible. */
  bindCoreAsync(actions: ExtensionActionsV2, contextActions: ExtensionContextActions, providerActions?: Parameters<ExtensionRunner["bindCore"]>[2]): void;
  /** @deprecated Use bindCoreAsync with ExtensionActionsV2. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
  bindCore(actions: ExtensionActions, contextActions: ExtensionContextActions, providerActions?: {
    registerProvider?: (name: string, config: ProviderConfig) => void;
    unregisterProvider?: (name: string) => void;
  }): void;
  private bindCoreActions;
  bindCommandContext(actions?: ExtensionCommandContextActions): void;
  setUIContext(uiContext?: ExtensionUIContext): void;
  getUIContext(): ExtensionUIContext;
  hasUI(): boolean;
  getExtensionPaths(): string[];
  /** Get all registered tools from all extensions (first registration per name wins). */
  getAllRegisteredTools(): RegisteredTool[];
  getToolDefinition(toolName: string): RegisteredTool["definition"] | undefined;
  getFlags(): Map<string, ExtensionFlag>;
  setFlagValue(name: string, value: boolean | string): void;
  getFlagValues(): Map<string, boolean | string>;
  getShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut>;
  getShortcutDiagnostics(): ResourceDiagnostic[];
  invalidate(message?: string): void;
  private requireActive;
  onError(listener: ExtensionErrorListener): () => void;
  emitError(error: ExtensionError): void;
  hasHandlers(eventType: string): boolean;
  getMessageRenderer(customType: string): MessageRenderer | undefined;
  private resolveRegisteredCommands;
  getRegisteredCommands(): ResolvedCommand[];
  getCommandDiagnostics(): ResourceDiagnostic[];
  getCommand(name: string): ResolvedCommand | undefined;
  /**
   * Request a graceful shutdown. Called by extension tools and event handlers.
   * The actual shutdown behavior is provided by the mode via bindExtensions().
   */
  shutdown(): void;
  /**
   * Create an ExtensionContext for use in event handlers and tool execution.
   * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.
   */
  createContext(): ExtensionContext;
  createCommandContext(): ExtensionCommandContext;
  private dispatchHandlers;
  emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>>;
  emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined>;
  emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined>;
  emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined>;
  emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined>;
  emitContext(messages: AgentMessage[]): Promise<AgentMessage[]>;
  emitBeforeProviderRequest(payload: unknown): Promise<unknown>;
  emitBeforeAgentStart(prompt: string, images: ImageContent$1[] | undefined, systemPrompt: string, systemPromptOptions: BuildSystemPromptOptions): Promise<BeforeAgentStartCombinedResult | undefined>;
  emitResourcesDiscover(cwd: string, reason: ResourcesDiscoverEvent["reason"]): Promise<DiscoveredResourcePaths>;
  /** Emit input event. Transforms chain, "handled" short-circuits. */
  emitInput(text: string, images: ImageContent$1[] | undefined, source: InputSource): Promise<InputEventResult>;
}
//#endregion
//#region src/agents/sessions/prompt-templates.d.ts
interface PromptTemplate {
  name: string;
  description: string;
  argumentHint?: string;
  content: string;
  sourceInfo: SourceInfo;
  filePath: string;
}
//#endregion
//#region src/agents/sessions/resource-loader.d.ts
interface ResourceExtensionPaths {
  skillPaths?: Array<{
    path: string;
    metadata: PathMetadata;
  }>;
  promptPaths?: Array<{
    path: string;
    metadata: PathMetadata;
  }>;
  themePaths?: Array<{
    path: string;
    metadata: PathMetadata;
  }>;
}
interface ResourceLoader {
  getExtensions(): LoadExtensionsResult;
  getSkills(): {
    skills: Skill[];
    diagnostics: ResourceDiagnostic[];
  };
  getPrompts(): {
    prompts: PromptTemplate[];
    diagnostics: ResourceDiagnostic[];
  };
  getThemes(): {
    themes: Theme[];
    diagnostics: ResourceDiagnostic[];
  };
  extendResources(paths: ResourceExtensionPaths): void;
  reload(): Promise<void>;
}
//#endregion
//#region src/agents/sessions/settings-storage.d.ts
interface CompactionSettings {
  maxSummaryChars?: number;
  enabled?: boolean;
  reserveTokens?: number;
  keepRecentTokens?: number;
}
interface BranchSummarySettings {
  reserveTokens?: number;
  skipPrompt?: boolean;
}
interface ProviderRetrySettings {
  timeoutMs?: number;
  maxRetries?: number;
  maxRetryDelayMs?: number;
}
interface RetrySettings {
  enabled?: boolean;
  maxRetries?: number;
  baseDelayMs?: number;
  provider?: ProviderRetrySettings;
}
interface TerminalSettings {
  showImages?: boolean;
  imageWidthCells?: number;
  clearOnShrink?: boolean;
  showTerminalProgress?: boolean;
}
interface ImageSettings {
  autoResize?: boolean;
  blockImages?: boolean;
}
interface ThinkingBudgetsSettings extends ThinkingBudgets {}
interface MarkdownSettings {
  codeBlockIndent?: string;
}
interface WarningSettings {
  anthropicExtraUsage?: boolean;
}
type TransportSetting = Transport;
/**
 * Package source for npm/git packages.
 * - String form: load all resources from the package
 * - Object form: filter which resources to load
 */
type PackageSource = string | {
  source: string;
  extensions?: string[];
  skills?: string[];
  prompts?: string[];
  themes?: string[];
};
interface Settings {
  lastChangelogVersion?: string;
  defaultProvider?: string;
  defaultModel?: string;
  defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
  transport?: TransportSetting;
  steeringMode?: "all" | "one-at-a-time";
  followUpMode?: "all" | "one-at-a-time";
  theme?: string;
  compaction?: CompactionSettings;
  branchSummary?: BranchSummarySettings;
  retry?: RetrySettings;
  hideThinkingBlock?: boolean;
  shellPath?: string;
  quietStartup?: boolean;
  shellCommandPrefix?: string;
  npmCommand?: string[];
  collapseChangelog?: boolean;
  enableInstallTelemetry?: boolean;
  packages?: PackageSource[];
  extensions?: string[];
  skills?: string[];
  prompts?: string[];
  themes?: string[];
  enableSkillCommands?: boolean;
  terminal?: TerminalSettings;
  images?: ImageSettings;
  enabledModels?: string[];
  doubleEscapeAction?: "fork" | "tree" | "none";
  treeFilterMode?: "default" | "no-tools" | "user-only" | "labeled-only" | "all";
  thinkingBudgets?: ThinkingBudgetsSettings;
  editorPaddingX?: number;
  autocompleteMaxVisible?: number;
  showHardwareCursor?: boolean;
  markdown?: MarkdownSettings;
  warnings?: WarningSettings;
  sessionDir?: string;
  httpIdleTimeoutMs?: number;
}
//#endregion
//#region src/agents/sessions/settings-manager.d.ts
declare class SettingsManager {
  private settings;
  private baseSettings;
  private runtimeOverrides;
  private constructor();
  static inMemory(settings?: Partial<Settings>): SettingsManager;
  getGlobalSettings(): Settings;
  private recomputeSettings;
  /** Layer runtime policy above the prepared settings and local default changes. */
  applyOverrides(overrides: Partial<Settings>): void;
  private setGlobalSettings;
  private setGlobalNestedSetting;
  setDefaultModelAndProvider(provider: string, modelId: string): void;
  getSteeringMode(): "all" | "one-at-a-time";
  setSteeringMode(mode: "all" | "one-at-a-time"): void;
  getFollowUpMode(): "all" | "one-at-a-time";
  setFollowUpMode(mode: "all" | "one-at-a-time"): void;
  getDefaultThinkingLevel(): Settings["defaultThinkingLevel"];
  setDefaultThinkingLevel(level: NonNullable<Settings["defaultThinkingLevel"]>): void;
  getTransport(): TransportSetting;
  getCompactionEnabled(): boolean;
  setCompactionEnabled(enabled: boolean): void;
  getCompactionReserveTokens(): number;
  getCompactionKeepRecentTokens(): number;
  getCompactionSettings(): {
    enabled: boolean;
    reserveTokens: number;
    keepRecentTokens: number;
    maxSummaryChars?: number;
  };
  getRetryEnabled(): boolean;
  setRetryEnabled(enabled: boolean): void;
  getRetrySettings(): {
    enabled: boolean;
    maxRetries: number;
    baseDelayMs: number;
  };
  getProviderRetrySettings(): {
    timeoutMs?: number;
    maxRetries?: number;
    maxRetryDelayMs: number;
  };
  getEnableInstallTelemetry(): boolean;
  getThinkingBudgets(): ThinkingBudgetsSettings | undefined;
  getBlockImages(): boolean;
}
//#endregion
//#region src/agents/sessions/agent-session-types.d.ts
/** The embedded request boundary owns threshold checks while this flag is set. */
declare const agentSessionDeferThresholdCompaction: unique symbol;
/** Runs provider checkpoint work without aborting or restarting the current tool loop. */
declare const agentSessionRunProviderCompaction: unique symbol;
type AgentSessionCompactionOutcome = {
  status: "completed";
  tokensBefore: number;
  tokensAfter: number;
  willRetry: boolean;
  qualityDegraded?: true;
} | {
  status: "skipped";
  reason: string;
} | {
  status: "failed";
  reason: string;
} | {
  status: "aborted";
};
type AgentSessionCompactionEndEvent = {
  type: "compaction_end";
  hooksHandled?: boolean;
  itemId?: string;
  reason: "manual" | "threshold" | "overflow";
  outcome: AgentSessionCompactionOutcome;
};
type AgentSessionEvent = Exclude<AgentEvent$1, {
  type: "agent_end";
}> | {
  type: "agent_end";
  messages: AgentMessage[];
  willRetry: boolean;
  assistantEntryId?: string;
} | {
  type: "queue_update";
} | {
  type: "agent_settled";
} | {
  type: "agent_handoff";
} | {
  type: "compaction_start";
  reason: "manual" | "threshold" | "overflow";
  itemId?: string;
  hooksHandled?: boolean;
} | {
  type: "session_info_changed";
  name: string | undefined;
} | {
  type: "thinking_level_changed";
  level: ThinkingLevel;
} | AgentSessionCompactionEndEvent | {
  type: "auto_retry_start";
} | {
  type: "auto_retry_end";
};
type AgentSessionEventListener = (event: AgentSessionEvent) => unknown;
type AgentSessionWriteSettlementRunner = <T>(run: () => Promise<T> | T) => Promise<T>;
interface AgentSessionConfig {
  agent: Agent$1;
  /** Exact system prompt prepared by the runtime owner. */
  systemPrompt: string;
  sessionManager: SessionManager;
  settingsManager: SettingsManager;
  cwd: string;
  resourceLoader: ResourceLoader;
  /** SDK custom tools registered outside extensions. */
  customTools?: ToolDefinition$1[];
  modelRegistry: ModelRegistry$1;
  /** Runtime-owned tool allowlist, also used for initial activation. */
  allowedToolNames: string[];
  /** Mutable reference used by Agent to access the current extension runner. */
  extensionRunnerRef?: {
    current?: ExtensionRunner;
  };
  /** Settlement boundary for session writes and write-capable hooks. */
  withSessionWriteSettlement?: AgentSessionWriteSettlementRunner;
  /** Owner of reactive context-overflow recovery. Defaults to the session. */
  contextOverflowRecoveryOwner?: "session" | "caller";
  /** Resolve the admitted compaction policy from the active model, including provider defaults. */
  resolveCompactionThinkingLevel?: (model: Model & {
    compactionThinkingDefault?: ThinkLevel;
  }, inheritedLevel: ThinkingLevel) => ThinkingLevel;
  /** Whether disposing this object ends the durable provider session. Defaults to true. */
  cleanupProviderSessionResourcesOnDispose?: boolean;
}
interface ExtensionBindings {
  uiContext?: ExtensionUIContext;
  commandContextActions?: ExtensionCommandContextActions;
  abortHandler?: () => void;
  shutdownHandler?: ShutdownHandler;
  onError?: ExtensionErrorListener;
}
interface PromptOptions {
  /** Expand file-based prompt templates. Defaults to true. */
  expandPromptTemplates?: boolean;
  images?: ImageContent$1[];
  /** Queue behavior when an agent is already streaming. */
  streamingBehavior?: "steer" | "followUp";
  /** Source of input for extension input handlers. Defaults to interactive. */
  source?: InputSource;
  /** Internal RPC hook for prompt preflight acceptance or rejection. */
  preflightResult?: (success: boolean) => void;
  /** Internal identity for a current user turn that is already durable. */
  persistedUserIdempotencyKey?: string;
}
//#endregion
//#region src/agents/sessions/agent-session-base.d.ts
declare abstract class AgentSessionBase {
  readonly agent: Agent$1;
  readonly sessionManager: SessionManager;
  readonly settingsManager: SettingsManager;
  protected unsubscribeAgent?: () => void;
  private eventListeners;
  /** Tracks pending steering messages for UI display. Removed when delivered. */
  protected steeringMessages: Array<{
    text: string;
  }>;
  /** Tracks pending follow-up messages for UI display. Removed when delivered. */
  protected followUpMessages: Array<{
    text: string;
  }>;
  /** Messages queued to be included with the next user prompt as context ("asides"). */
  protected pendingNextTurnMessages: CustomMessage[];
  protected compactionAbortController: AbortController | undefined;
  protected autoCompactionAbortController: AbortController | undefined;
  protected overflowRecoveryAttempts: number;
  protected contextOverflowRecoveryOwner: "session" | "caller";
  protected resolveCompactionThinkingLevel?: AgentSessionConfig["resolveCompactionThinkingLevel"];
  private extensionModifiedToolResultIds;
  protected retryAbortController: AbortController | undefined;
  protected retryCount: number;
  protected currentExtensionRunner: ExtensionRunner;
  private turnIndex;
  protected sessionResourceLoader: ResourceLoader;
  protected customTools: ToolDefinition$1[];
  protected cwd: string;
  protected extensionRunnerRef?: {
    current?: ExtensionRunner;
  };
  protected allowedToolNames: Set<string>;
  protected withExternalSessionWriteSettlement?: AgentSessionWriteSettlementRunner;
  protected extensionUIContext?: ExtensionUIContext;
  protected extensionCommandContextActions?: ExtensionCommandContextActions;
  protected extensionAbortHandler?: () => void;
  protected extensionShutdownHandler?: ShutdownHandler;
  protected extensionErrorListener?: ExtensionErrorListener;
  protected extensionErrorUnsubscriber?: () => void;
  private readonly cleanupProviderSessionResourcesOnDispose;
  protected sessionModelRegistry: ModelRegistry$1;
  protected toolRegistry: Map<string, AgentTool>;
  protected toolDefinitions: Map<string, RegisteredTool>;
  protected baseSystemPrompt: string;
  protected baseSystemPromptOptions: BuildSystemPromptOptions;
  protected systemPromptOverride: string | undefined;
  constructor(config: AgentSessionConfig);
  get modelRegistry(): ModelRegistry$1;
  protected getRequiredRequestAuth(model: Model): Promise<{
    apiKey: string;
    headers?: ModelRequestHeaders;
  }>;
  protected getCompactionRequestAuth(model: Model): Promise<{
    apiKey?: string;
    headers?: ModelRequestHeaders;
  }>;
  protected runWithSessionWriteSettlement<T>(run: () => Promise<T> | T): Promise<T>;
  /**
   * Hooks resolve the current extension runner at execution time so reloads
   * need no reinstall. Wrappers only adapt registered tools to extension context.
   */
  protected installAgentToolHooks(): void;
  /** Copy-on-write listener registration keeps dispatch stable without per-event snapshots. */
  protected emit(event: AgentSessionEvent): void;
  /** Terminal listeners form a barrier before retry, compaction, or queue draining. */
  private emitTerminal;
  protected emitQueueUpdate(): void;
  protected trackQueuedUserMessage(message: AgentMessage, owner: "steering" | "followUp", text: string): void;
  protected lastAssistantMessage: AssistantHistoryMessage | undefined;
  private lastAssistantEntryId;
  protected lastRunEndedForTurnHandoff: boolean;
  /** Internal handler for agent events - shared by subscribe and reconnect */
  protected handleAgentEvent: (event: AgentEvent$1, signal?: AbortSignal) => Promise<void>;
  private handleAgentEventUnlocked;
  private willRetryAfterAgentEnd;
  /** Find the last assistant message in agent state (including aborted ones) */
  protected findLastAssistantMessage(): AssistantHistoryMessage | undefined;
  private emitExtensionEvent;
  /**
   * Subscribe to agent events.
   * Session persistence is handled internally (saves messages on message_end).
   * Multiple listeners can be added. Returns unsubscribe function for this listener.
   */
  subscribe(listener: AgentSessionEventListener): () => void;
  /**
   * Temporarily disconnect from agent events.
   * User listeners are preserved and will receive events again after resubscribe().
   * Used internally during operations that need to pause event processing.
   */
  protected disconnectFromAgent(): void;
  /**
   * Reconnect to agent events after disconnectFromAgent().
   * Preserves all existing listeners.
   */
  protected reconnectToAgent(): void;
  /**
   * Remove all listeners and disconnect from agent.
   * Call this when completely done with the session.
   */
  dispose(): void;
  get state(): AgentState;
  get model(): Model | undefined;
  get thinkingLevel(): ThinkingLevel;
  get isStreaming(): boolean;
  /** Current effective system prompt (includes any per-turn extension modifications) */
  get systemPrompt(): string;
  getActiveToolNames(): string[];
  /** All configured tools with their schema and source metadata. */
  getAllTools(): ToolInfo[];
  getToolDefinition(name: string): ToolDefinition$1 | undefined;
  /**
   * Set active tools by name.
   * Only tools in the registry can be enabled. Unknown tool names are ignored.
   * An execution cap preserves these definitions and refuses denied calls.
   * Refreshes extension prompt metadata while preserving the runtime-owned prompt.
   * Changes take effect on the next agent turn.
   */
  setActiveToolsByName(toolNames: string[], callableToolNames?: readonly string[]): void;
  /** Set an exact base prompt owned by the current runtime. */
  setBaseSystemPrompt(systemPrompt: string): void;
  /** Whether manual or automatic compaction is currently running */
  get isCompacting(): boolean;
  /** All messages including custom types like BashExecutionMessage */
  get messages(): AgentMessage[];
  get steeringMode(): "all" | "one-at-a-time";
  get followUpMode(): "all" | "one-at-a-time";
  /** Current persisted transcript target, or undefined for in-memory sessions. */
  get sessionTarget(): SessionTranscriptTargetBinding | undefined;
  /** Current persisted session key, or undefined for in-memory sessions. */
  get sessionKey(): string | undefined;
  /** @deprecated Compatibility token; returns the session key, not a file path. */
  get sessionFile(): string | undefined;
  get sessionId(): string;
  get sessionName(): string | undefined;
  /** File-based prompt templates */
  get promptTemplates(): ReadonlyArray<PromptTemplate>;
  private refreshSystemPromptMetadata;
  protected abstract isRetryableError(message: AssistantHistoryMessage): boolean;
  protected abstract prepareRetry(message: AssistantHistoryMessage): Promise<boolean>;
  protected abstract checkCompaction(assistantMessage: AssistantHistoryMessage, skipAbortedCheck?: boolean, requestBudget?: CompactionRequestBudget): Promise<boolean>;
  abstract abortRetry(): void;
  abstract abortCompaction(): void;
}
//#endregion
//#region src/agents/sessions/agent-session-prompting.d.ts
type PromptAdmission = (onAdmitted: (commit?: () => void) => void) => Promise<void>;
/** @internal Host preparation runs after SDK prompt hooks and owns its run cancellation. */
declare const agentSessionSetPromptPreparation: unique symbol;
/** @internal Queue prompt-owned context with cleanup for preflight exits. */
declare const agentSessionQueuePromptContext: unique symbol;
declare abstract class AgentSessionPrompting extends AgentSessionBase {
  private logicalPromptActive;
  private promptPreparation?;
  [agentSessionQueuePromptContext](message: CustomMessage): () => void;
  [agentSessionQueuePromptContext](message: CustomMessage, options: {
    delivery: "current-request";
  }): Promise<void>;
  [agentSessionSetPromptPreparation](prepare: (() => Promise<void | PromptAdmission>) | undefined): void;
  dispose(): void;
  private runAgentPrompt;
  private runPreparedAgentLoop;
  private handlePostAgentRun;
  private createUserMessage;
  /**
   * Send a prompt to the agent.
   * - Handles extension commands immediately, even during streaming
   * - Expands file-based prompt templates by default
   * - During streaming, queues via steer() or followUp() based on streamingBehavior option
   * - Validates model and API key before sending (when not streaming)
   * @throws Error if streaming and no streamingBehavior specified
   * @throws Error if no model selected or no API key available (when not streaming)
   */
  prompt(text: string, options?: PromptOptions): Promise<void>;
  private tryExecuteExtensionCommand;
  /**
   * Expand skill commands (/skill:name args) to their full content.
   * Returns the expanded text, or the original text if not a skill command or skill not found.
   * Emits errors via extension runner if file read fails.
   */
  private expandSkillCommand;
  private expandPrompt;
  /**
   * Queue a steering message while the agent is running.
   * Delivered before the next unstarted tool launch or model call. Running tools
   * continue; suppressed calls receive paired synthetic results.
   * Expands skill commands and prompt templates. Errors on extension commands.
   * @param userTurnTranscriptRecorder Prepared channel fields for transcript-only persistence
   * @param currentInboundContext This turn's runtime facts, separate from its command and transcript
   * @throws Error if text is an extension command
   */
  steer(text: string, images?: ImageContent$1[], userTurnTranscriptRecorder?: UserTurnTranscriptRecorder, media?: MediaFact[], imageOrder?: PromptImageOrderEntry[], queueIdentity?: string, canInject?: () => boolean, currentInboundContext?: CurrentInboundPromptContext, prepareInjection?: () => Promise<void>, onAccepted?: () => void): Promise<void>;
  /**
   * Queue a follow-up message to be processed after the agent finishes.
   * Delivered only when agent has no more tool calls or steering messages.
   * Expands skill commands and prompt templates. Errors on extension commands.
   * @throws Error if text is an extension command
   */
  followUp(text: string, images?: ImageContent$1[]): Promise<void>;
  private createSteeringMessage;
  /** Install only queue state here; arbitrary listeners run after admission cleanup. */
  private queueSteer;
  /** Queue pre-expanded follow-up input without an extension-command check. */
  private queueFollowUp;
  private throwIfExtensionCommand;
  /**
   * Send a custom message to the session. Creates a CustomMessageEntry.
   *
   * Handles three cases:
   * - Streaming: queues message, processed when loop pulls from queue
   * - Not streaming + triggerTurn: appends to state/session, starts new turn
   * - Not streaming + no trigger: appends to state/session, no turn
   *
   * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
   */
  sendCustomMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
    triggerTurn?: boolean;
    deliverAs?: "steer" | "followUp" | "nextTurn";
  }): Promise<void>;
  private persistCustomMessage;
  /**
   * Send a user message to the agent. Always triggers a turn.
   * When the agent is streaming, use deliverAs to specify how to queue the message.
   */
  sendUserMessage(content: string | (TextContent | ImageContent$1)[], options?: {
    deliverAs?: "steer" | "followUp";
  }): Promise<void>;
  /**
   * Clear all queued messages and return them.
   * Useful for restoring to editor when user aborts.
   */
  clearQueue(): {
    steering: string[];
    followUp: string[];
  };
  /** Number of pending messages (includes both steering and follow-up) */
  get pendingMessageCount(): number;
  getSteeringMessages(): readonly string[];
  getFollowUpMessages(): readonly string[];
  get resourceLoader(): ResourceLoader;
  /** Abort the current run; yield callers pass a turnHandoff reason to skip interruption guidance. */
  abort(reason?: unknown): Promise<void>;
}
//#endregion
//#region src/agents/sessions/agent-session-inspection.d.ts
declare abstract class AgentSessionInspection extends AgentSessionPrompting {
  private emitModelSelect;
  /** Set the model after validating its current auth at write admission. */
  setModel(model: Model): Promise<void>;
  /**
   * Set thinking level.
   * Clamps to model capabilities based on available thinking levels.
   * Saves to session and settings only if the level actually changes.
   */
  setThinkingLevel(level: ThinkingLevel): Promise<void>;
  private planThinkingLevel;
  private appendThinkingSelection;
  private emitThinkingLevelSelect;
  private failAfterMetadataCommit;
  private captureMetadataOwner;
  supportsThinking(): boolean;
  private getThinkingLevelForModelSwitch;
  /** Update steering mode and persist it to settings. */
  setSteeringMode(mode: "all" | "one-at-a-time"): void;
  /** Update follow-up mode and persist it to settings. */
  setFollowUpMode(mode: "all" | "one-at-a-time"): void;
  /** @deprecated Await setSessionNameAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  setSessionName(name: string): void;
  /** Persist the display name before publishing its changed event. */
  setSessionNameAsync(name: string): Promise<void>;
  getContextUsage(): ContextUsage | undefined;
  getLastAssistantText(): string | undefined;
}
//#endregion
//#region src/agents/sessions/agent-session-compaction.d.ts
type SummaryOutputPolicy = "none" | "retry-invalid-once" | "deterministic";
type AutomaticCompactionOptions = CompactionRequestConstraints & {
  onSummaryReady?: () => void;
};
type CompactionWorkOutcome = {
  status: "completed";
  result: CompactionResult;
  tokensAfter: number;
} | {
  status: "aborted";
} | {
  status: "skipped";
  reason: string;
};
type SettledCompactionWorkOutcome = Exclude<CompactionWorkOutcome, {
  status: "aborted";
}>;
/** @internal */
declare const agentSessionAutomaticCompaction: unique symbol;
/** Installs a synchronous callback for model-context replacement during compaction. */
declare const agentSessionSetContextReplacementHook: unique symbol;
declare abstract class AgentSessionCompaction extends AgentSessionInspection {
  [agentSessionDeferThresholdCompaction]: boolean;
  private onContextReplaced?;
  private assertContextReplacementActive?;
  [agentSessionRunProviderCompaction]<T>(run: (signal: AbortSignal, committed: (tokensBefore: number, tokensAfter: number) => void) => Promise<T>, hooksHandled?: boolean): Promise<T>;
  [agentSessionSetContextReplacementHook](callback: ((tokensAfter: number, tokensBefore: number, details?: unknown) => void) | undefined, assertActive?: () => void): void;
  dispose(): void;
  /**
   * Manually compact the session context.
   * Aborts current agent operation first.
   */
  compact(customInstructions?: string): Promise<CompactionResult>;
  [agentSessionAutomaticCompaction](customInstructions?: string, requestState?: "unresolved", summaryOutputPolicy?: SummaryOutputPolicy, constraints?: AutomaticCompactionOptions): Promise<SettledCompactionWorkOutcome>;
  private compactWithSessionWriteSettlement;
  private emitCompletedCompaction;
  /** Cancel in-progress compaction (manual or auto). */
  abortCompaction(): void;
  private runCompactionWork;
  protected checkCompaction(assistantMessage: AssistantHistoryMessage, skipAbortedCheck?: boolean, requestBudget?: CompactionRequestBudget): Promise<boolean>;
  private runAutoCompaction;
  get autoCompactionEnabled(): boolean;
}
//#endregion
//#region src/agents/sessions/agent-session.d.ts
/**
 * Core abstraction for agent lifecycle and session management.
 *
 * Shared by interactive, print, and RPC modes. Mode-specific I/O stays above
 * this class while the feature layers below own session behavior.
 */
declare class AgentSession extends AgentSessionCompaction {
  constructor(config: AgentSessionConfig);
  get extensionRunner(): ExtensionRunner;
  bindExtensions(bindings: ExtensionBindings): Promise<void>;
  private extendResourcesFromExtensions;
  private buildExtensionResourcePaths;
  private applyExtensionBindings;
  private refreshCurrentModelFromRegistry;
  private bindExtensionCore;
  /** Replace a runtime-owned tool surface without restarting its active agent loop. */
  replaceCustomTools(customTools: ToolDefinition$1[], activeToolNames: string[]): void;
  private refreshToolRegistry;
  protected buildRuntime(options: {
    activeToolNames?: string[];
    flagValues?: Map<string, boolean | string>;
  }): void;
  reload(): Promise<void>;
  /**
   * Check if an error is retryable (overloaded, rate limit, server errors).
   * Context overflow errors are NOT retryable (handled by compaction instead).
   */
  protected isRetryableError(message: AssistantHistoryMessage): boolean;
  /**
   * Prepare a retryable error for continuation with exponential backoff.
   * @returns true if the caller should continue the agent, false otherwise
   */
  protected prepareRetry(message: AssistantHistoryMessage): Promise<boolean>;
  /** Cancel an in-progress retry. */
  abortRetry(): void;
}
//#endregion
//#region src/agents/sessions/auth-storage.d.ts
type AuthStorage = AuthStorage$1;
declare const AuthStorage: typeof AuthStorage$1 & {
  /** @deprecated Use forAgentAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  forAgent(agentDir?: string, config?: OpenClawConfig): AuthStorage;
  forAgentAsync(agentDir?: string, config?: OpenClawConfig): Promise<AuthStorage>;
  /**
   * @deprecated Use AuthStorage.forAgentAsync(agentDir). The path-taking compatibility
   * form remains supported through 2026-12-31; removal ships in the first
   * January 2027 stable. It no longer reads or writes JSON.
   */
  create(authPath?: string): AuthStorage;
};
//#endregion
//#region src/agents/model-catalog-lookup.d.ts
type ModelThinkingCompat = {
  thinkingFormat?: ModelCompatConfig["thinkingFormat"];
  supportedReasoningEfforts?: readonly string[] | null;
};
type PreparedModelThinkingCapability = Readonly<{
  provider: string;
  modelId: string;
  agentRuntime: string;
  /** Present only when the capability came from a physical provider route. */
  route?: Readonly<{
    api: string;
    baseUrl: string;
  }>;
  compat: ModelThinkingCompat;
}>;
/** Prefers canonical identity; the shipped SDK's case-insensitive fallback must be unique. */
declare function findModelInCatalog<T extends Pick<ModelCatalogEntry, "provider" | "id">>(catalog: readonly T[], provider: string, modelId: string): T | undefined;
/** Finds a model entry, requiring uniqueness when provider is omitted. */
declare function findModelCatalogEntry(catalog: ModelCatalogEntry[], params: {
  provider?: string;
  modelId: string;
}): ModelCatalogEntry | undefined;
//#endregion
//#region src/agents/model-catalog.d.ts
/**
 * Check if a model supports image input based on its catalog entry.
 */
declare function modelSupportsVision(entry: ModelCatalogEntry | undefined): boolean;
//#endregion
//#region src/plugins/prepared-message-tool-catalog.d.ts
type PreparedMessageToolCatalogEntry = Readonly<{
  id: string;
  actions?: ChannelMessageActionAdapter;
  reconcilesUnknownSend: boolean;
}>;
type PreparedMessageToolCatalog = Readonly<{
  version: number;
  channels: readonly PreparedMessageToolCatalogEntry[];
  getChannel: (id: string) => PreparedMessageToolCatalogEntry | undefined;
}>;
//#endregion
//#region src/model-catalog/remote-bundle.d.ts
type RemoteModelCatalogPrice = {
  cost: ModelCatalogCost;
  explicit: boolean;
};
/**
 * Upstream vendor/model rates in source priority order. Direct lookups use the first;
 * passthrough providers use the first whose source their policy allows.
 */
type RemoteModelCatalogUpstreamPrice = {
  rates: Array<{
    source: string;
    cost: ModelCatalogCost;
  }>;
  passthroughOnly: boolean;
};
//#endregion
//#region src/model-catalog/remote-overlay.d.ts
type RemoteCatalogPublicationResult = "published" | "unchanged" | "superseded";
type RemoteModelCatalogOverlay = Readonly<Record<string, ModelCatalogProvider>>;
type RemoteModelCatalogMetadata = {
  sourceUrl: string;
  generatedAt: number;
};
type ActiveRemoteModelCatalog = RemoteModelCatalogMetadata & {
  revision: string;
  providers: RemoteModelCatalogOverlay;
  recommendations: Readonly<Record<string, readonly string[]>>;
  pricing: Readonly<Record<string, RemoteModelCatalogPrice>>;
  upstreamPricing: Readonly<Record<string, RemoteModelCatalogUpstreamPrice>>;
};
//#endregion
//#region src/plugins/plugin-invocation-scope.d.ts
/** Finite execution custody for one host-selected registry and its exact instances. */
declare class PluginInvocationScope {
  readonly registry: PluginRegistry;
  private readonly bindings;
  private readonly consumers;
  private closed;
  constructor(registry: PluginRegistry, instances: Iterable<PluginInstanceHandle>, options?: {
    retained?: boolean;
    parent?: PluginInvocationScope;
    kind?: "work" | "custody";
  });
  private consumer;
  private assertOpen;
  get pendingReplacementInstances(): readonly PluginInstanceHandle[];
  get holdsPendingReplacement(): boolean;
  lookup(instance: PluginInstanceHandle): PluginInvocationBinding | undefined;
  run<T>(run: () => T): T;
  wrap<T>(value: T): T;
  /** Transfer custody before revoking callbacks captured by ordinary engine operations. */
  beginCleanup(): {
    scope: PluginInvocationScope;
    release: () => Promise<void>;
  };
  release(): void;
}
//#endregion
//#region src/plugins/registry-registration-resources.d.ts
type RegistrationDisposer = {
  id: string;
  dispose: () => void | Promise<void>;
};
type RegistrationCleanup = (run: () => Promise<void>) => Promise<void>;
//#endregion
//#region src/plugins/registry-inspection-resources.d.ts
/** Owns only an explicitly acquired, uncached inspection's registration resources. */
declare class PluginRegistryInspectionResources {
  #private;
  private retire;
  constructor(retire: ((registry: PluginRegistry | undefined, rollbackInstances: ReadonlySet<object>) => Promise<void>) | undefined);
  attach(registry: PluginRegistry): void;
  register(pluginId: string, disposer: RegistrationDisposer): void;
  runRegistration(pluginId: string, run: () => void, runCleanup?: RegistrationCleanup): void;
  trackRegistration(pending: Promise<unknown>): void;
  rollback(pluginId: string, retire?: () => Promise<void>, instance?: object): void;
  /** Publish same-context retained instances and their registration resources together. */
  adoptRetainedRegistrations(previous: PluginRegistry): void;
  /** Copied callbacks keep their source through this inspection's final disposer. */
  retainDependency(dependency: PluginRegistryInspectionResources): void;
  /** Adopt executable donor custody before the acquired view can escape to a caller. */
  adoptInvocations(registry: PluginRegistry, donor: PluginRegistry | undefined): void;
  wrapAdoptedValue<T>(value: T): T;
  /** Logical use owns its execution consumers separately from this inspection's physical claims. */
  createInvocationScope(registry: PluginRegistry, instances?: Iterable<PluginInstanceHandle>): PluginInvocationScope;
  /** Recorded coverage survives retirement; retain() still checks this inspection's lifetime. */
  coversSource(source: PluginRegistryInspectionResources): boolean;
  /** Retains physical resources without extending this inspection's authority. */
  retain(): {
    release: () => Promise<void>;
  };
  release(): Promise<void>;
}
//#endregion
//#region src/shared/device-bootstrap-profile.d.ts
type DeviceBootstrapPurpose = "control-ui" | "control-ui-owner" | "mobile-full" | "voice-node" | "cloud-worker";
/** Normalized roles/scopes carried by a bootstrap token during device handoff. */
type DeviceBootstrapProfile = {
  roles: string[];
  scopes: string[];
  purpose?: DeviceBootstrapPurpose;
};
/** Caller-provided bootstrap profile before role/scope normalization and bounding. */
type DeviceBootstrapProfileInput = {
  roles?: readonly string[];
  scopes?: readonly string[];
  purpose?: DeviceBootstrapPurpose;
};
/** Operator scopes allowed to cross the short-lived bootstrap handoff boundary. */
declare const BOOTSTRAP_HANDOFF_OPERATOR_SCOPES: readonly ["operator.approvals", "operator.questions", "operator.read", "operator.talk.secrets", "operator.write"];
/** Existing least-privilege setup-code/QR profile. */
declare const PAIRING_SETUP_BOOTSTRAP_PROFILE: DeviceBootstrapProfile;
/** Normalize caller-provided bootstrap roles/scopes without applying handoff bounds. */
declare function normalizeDeviceBootstrapProfile(input: DeviceBootstrapProfileInput | undefined): DeviceBootstrapProfile;
//#endregion
//#region src/infra/device-pairing.types.d.ts
/** Pending device pairing request awaiting owner approval. */
type DevicePairingPendingRequest = SchemaContract<Static<typeof DevicePairRequestedEventSchema>>;
/** Bearer token issued to one paired device role. */
type DeviceAuthToken = {
  token: string;
  role: string;
  scopes: string[];
  issuer?: {
    kind: "shared-gateway-auth";
    generation: string;
  };
  createdAtMs: number;
  rotatedAtMs?: number;
  revokedAtMs?: number;
  lastUsedAtMs?: number;
};
/**
 * How the latest pairing approval was granted. "silent" is a same-host local
 * policy approval and the only prune-eligible kind: local clients re-pair
 * silently and cannot collide with another machine's records. "trusted-cidr"
 * and "ssh-verified" are also non-interactive but cross hosts, so they are
 * never pruned automatically (display metadata is not a machine identity).
 * "trusted-proxy" records were approved from an authenticated proxy identity.
 * "remote-ingress" records were approved through a live plugin grant.
 * "owner" and "bootstrap" approvals required a user action. None of these
 * cross-host or interactive approval kinds are pruned automatically.
 */
type PairedDeviceApprovalKind = "owner" | "silent" | "trusted-cidr" | "trusted-proxy" | "remote-ingress" | "ssh-verified" | "bootstrap";
/**
 * Approved node capability surface for a node-role device. Device pairing
 * grants connection auth; this grants command/capability exposure (node
 * command gating). displayName here is the operator-facing node name set at
 * approval or via node.rename; it must not be clobbered by reconnect
 * metadata refreshes, which is why it lives apart from the device fields.
 */
type PairedDeviceNodeSurface = {
  displayName?: string;
  version?: string;
  coreVersion?: string;
  uiVersion?: string;
  modelIdentifier?: string;
  caps?: string[];
  commands?: string[];
  permissions?: Record<string, boolean>;
  bins?: string[];
  /** Last current-generation runner publication explicitly enabled session hosting. */
  sessionHost?: boolean;
  createdAtMs: number;
  approvedAtMs: number;
  lastConnectedAtMs?: number;
  lastDisconnectedAtMs?: number;
  lastHostStats?: NodeHostStats;
};
/**
 * Pending node-surface approval awaiting an operator decision (one per
 * device). Carries its own metadata snapshot so approval UIs can show what
 * the node declared at request time. `revision` guards the reconnect-vs-
 * approve race: reconnect cleanup only deletes the revision it observed, so
 * a refreshed request survives concurrent approval flows.
 */
type PairedDevicePendingNodeSurface = {
  requestId: string;
  revision: string;
  displayName?: string;
  platform?: string;
  version?: string;
  coreVersion?: string;
  uiVersion?: string;
  clientId?: string;
  clientMode?: string;
  deviceFamily?: string;
  modelIdentifier?: string;
  caps?: string[];
  commands?: string[];
  permissions?: Record<string, boolean>;
  remoteIp?: string;
  silent?: boolean;
  ts: number;
};
/** Persisted approved device record, including durable approval and active role tokens. */
type PairedDevice = Omit<DevicePairingPendingRequest, "requestId" | "silent" | "isRepair" | "ts"> & {
  operatorLabel?: string;
  approvedScopes?: string[];
  tokens?: Record<string, DeviceAuthToken>;
  approvedVia?: PairedDeviceApprovalKind;
  nodeSurface?: PairedDeviceNodeSurface;
  pendingNodeSurface?: PairedDevicePendingNodeSurface;
  createdAtMs: number;
  approvedAtMs: number;
  lastSeenAtMs?: number;
  lastSeenReason?: string;
};
/** Persisted bootstrap token state, including binding and role/scope redemption progress. */
type DeviceBootstrapTokenRecord = {
  token: string;
  setupId?: string;
  ts: number;
  deviceId?: string;
  publicKey?: string;
  profile?: DeviceBootstrapProfile;
  redeemedProfile?: DeviceBootstrapProfile;
  pendingProfile?: DeviceBootstrapProfile;
  issuedAtMs: number;
  lastUsedAtMs?: number;
};
//#endregion
//#region src/infra/device-pairing-core.types.d.ts
type PairedDeviceTokenIdentity = {
  deviceId: string;
  key: string;
};
/** Paired-device access metadata refreshed when an existing device reconnects. */
type DevicePairingAccessMetadata = Pick<PairedDevice, "displayName" | "remoteIp" | "lastSeenAtMs" | "lastSeenReason">;
/** Authorization failure categories for owner approval and bootstrap approval flows. */
type DevicePairingForbiddenReason = "caller-scopes-required" | "caller-missing-scope" | "scope-outside-requested-roles" | "approval-policy-changed" | "bootstrap-role-not-allowed" | "bootstrap-scope-not-allowed";
type DevicePairingForbiddenResult = {
  status: "forbidden";
  reason: DevicePairingForbiddenReason;
  scope?: string;
  role?: string;
};
type ApproveDevicePairingResult = {
  status: "approved";
  requestId: string;
  device: PairedDevice;
  /** Existing connected node transports must be retired before success is returned. */
  nodePairingGenerationChanged?: true;
} | DevicePairingForbiddenResult | null;
type DevicePairingApprovalOptions = {
  callerScopes?: readonly string[];
  accessMetadata?: DevicePairingAccessMetadata;
  approvedVia?: Extract<PairedDeviceApprovalKind, "owner" | "silent" | "trusted-cidr" | "trusted-proxy" | "remote-ingress" | "ssh-verified">;
  /** Revalidate automatic approval against current policy after all pairing-lock awaits. */
  isApprovalCurrent?: (state: {
    pending: Readonly<DevicePairingPendingRequest>;
    existing: Readonly<PairedDevice> | undefined;
  }) => boolean;
  /**
   * Replace pending scopes for a new operator device, or a trusted ingress
   * same-key upgrade. The live role set is rechecked under the pairing lock.
   */
  autoApproveNewDeviceScopes?: readonly string[];
};
//#endregion
//#region src/infra/system-presence.d.ts
type SystemPresence = SchemaContract<Omit<PresenceEntry, "tags" | "text" | "user">> & {
  user?: PresenceEntry["user"];
  text: string;
};
//#endregion
//#region src/gateway/auth-policy.types.d.ts
type GatewayAuthPolicy = Readonly<{
  /** Transport admission policy; changes require a fresh handshake. */
  generation: string;
  /** The original principal's access, independent of transport admission. */
  grantGeneration: string;
  role?: string;
  authMethod?: GatewayAuthResult["method"];
  /** Fixed startup mode attested by the auth resolver, independent of file-mode edits. */
  authModeOverride?: ResolvedGatewayAuth["mode"];
  /** Only operator WebSocket admission consumes identity grants. */
  verifiedIdentity?: string;
  /** Handshake-attested origin facts remain authoritative after transport retirement. */
  browserOrigin?: Readonly<GatewayWsBrowserOrigin>;
}>;
//#endregion
//#region src/gateway/github-user-identity.types.d.ts
/** Connection-held identity synchronization contract, independent of its transport. */
type AuthenticatedGitHubIdentitySyncResult = CachedGitHubIdentity & {
  enterprise?: {
    accountId: number;
    login: string;
    avatarUrl?: string;
  };
};
type AuthenticatedGitHubIdentitySync = () => Promise<AuthenticatedGitHubIdentitySyncResult>;
//#endregion
//#region src/gateway/server-methods/response-types.d.ts
/** Callback used by method handlers to emit one protocol response frame. */
type RespondFn = (ok: boolean, payload?: unknown, error?: ErrorShape, meta?: Record<string, unknown>) => void;
//#endregion
//#region src/gateway/plugin-node-capability.d.ts
/** Path marker used to scope plugin-hosted node URLs with one-time capabilities. */
declare const PLUGIN_NODE_CAPABILITY_PATH_PREFIX = "/__openclaw__/cap";
declare const DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS: number;
type PluginNodeCapabilitySurface = {
  surface: string;
  ttlMs?: number;
  scopeKey?: string;
};
type PluginNodeCapabilityClient = {
  /** Retired clients cannot back HTTP capability auth or its renewal while close is pending. */
  invalidated?: boolean;
  /** Handshake-resolved host, retained so newly enabled surfaces need no reconnect. */
  pluginSurfaceBaseUrl?: string;
  pluginSurfaceUrls?: Record<string, string>;
  pluginNodeCapabilitySurfaces?: Record<string, PluginNodeCapabilitySurface>;
  pluginNodeCapabilities?: Record<string, {
    capability: string;
    expiresAtMs: number;
  }>;
};
type NormalizedPluginNodeCapabilityUrl = {
  pathname: string;
  capability?: string;
  rewrittenUrl?: string;
  scopedPath: boolean;
  malformedScopedPath: boolean;
};
declare function mintPluginNodeCapabilityToken(): string;
declare function buildPluginNodeCapabilityScopedHostUrl(baseUrl: string, capability: string): string | undefined;
/** Parse and rewrite scoped capability URLs into canonical paths plus query tokens. */
declare function normalizePluginNodeCapabilityScopedUrl(rawUrl: string): NormalizedPluginNodeCapabilityUrl;
//#endregion
//#region src/agents/run-session-target.types.d.ts
/** Identifies a run transcript target without naming the current storage artifact. */
type AgentRunSessionTarget = {
  agentId?: string;
  sessionId?: string;
  sessionKey?: string;
  storePath?: string;
  threadId?: string | number;
  /** Internal admission fence paired with sessionId for run-owned transcript writes. */
  expectedLifecycleRevision?: string;
  /** Internal durable writer claim installed after session-lane admission. */
  expectedWriterRunId?: string;
};
type BoundAgentRunSessionTarget = Required<Pick<AgentRunSessionTarget, "agentId" | "sessionId" | "sessionKey" | "storePath">> & Pick<AgentRunSessionTarget, "expectedLifecycleRevision" | "expectedWriterRunId">;
//#endregion
//#region src/gateway/worker-environments/connection-identity.d.ts
/** Hash-only worker identity retained after admission. */
type WorkerConnectionIdentity = {
  environmentId: string;
  credentialHash: string;
  bundleHash: string;
  sessionId: string | null;
  runId: string | null;
  turnClaim: WorkerSessionTurnClaim | null;
  ownerEpoch: number;
  rpcSetVersion: number;
  protocolFeatures: string[];
  credentialExpiresAtMs: number;
};
type WorkerInferenceExecutor = (params: {
  identity: WorkerConnectionIdentity;
  request: WorkerInferenceStartParams;
  signal: AbortSignal;
  emit: (event: WorkerInferenceEventParams["event"]) => void;
  isCurrent(): boolean;
  sessionTarget: BoundAgentRunSessionTarget;
}) => Promise<WorkerInferenceTerminalOutcome>;
//#endregion
//#region src/gateway/serialized-json.d.ts
/** Owned immutable segments; only transports that require contiguous bytes materialize them. */
declare class SerializedGatewayFrame {
  #private;
  readonly segments: readonly Uint8Array[];
  readonly byteLength: number;
  constructor(segments: readonly Uint8Array[]);
  toBuffer(): Buffer;
  toString(): string;
}
//#endregion
//#region src/gateway/server/connection-transport.d.ts
type GatewayConnectionFrame = Buffer | ArrayBuffer | Buffer[];
/** Ordered frames and transport retirement, independent of the physical connection. */
type GatewayConnectionTransport = {
  /** Uses the WebSocket ready-state values; 1 means open. */
  readonly readyState: number;
  readonly bufferedAmount: number;
  /** Installed codec can reuse worker-produced raw deflate with the default 15-bit window. */
  readonly acceptsDeflatedSegments?: boolean;
  /** Physical WebSockets record accepted event frames and their encoded payload size. */
  recordEventSent?(event: string, frame: Buffer | SerializedGatewayFrame, sessionEvent?: GatewayWsSessionEventAttribution, presenceMode?: GatewayWsPresenceMode, wireBytes?: number | void): void;
  /** Combine writes until the next tick without changing frame order or callbacks. */
  batchWrites?(): void;
  /** Send a secret-bearing frame outside negotiated compression; transports that compress must provide it. */
  sendUncompressed?(frame: string, callback?: (error?: Error) => void): void;
  /**
   * Accept JSON text frames in order, including byte-backed text. The optional callback settles after transport
   * delivery or with an error; it is not a peer acknowledgement.
   * Returns encoded payload bytes when known synchronously, for wire diagnostics.
   */
  send(frame: string, callback?: (error?: Error) => void): number | void;
  send(frame: Buffer | SerializedGatewayFrame, options: {
    binary: false;
  }, callback?: (error?: Error) => void): number | void;
  close(code?: number, reason?: string): void;
  terminate(): void;
  on(event: "message", listener: (data: GatewayConnectionFrame) => void): unknown;
  off(event: "message", listener: (data: GatewayConnectionFrame) => void): unknown;
  off(event: "close", listener: (code: number, reason: Buffer) => void): unknown;
  once(event: "message", listener: (data: GatewayConnectionFrame) => void): unknown;
  once(event: "close", listener: (code: number, reason: Buffer) => void): unknown;
};
//#endregion
//#region src/gateway/server/ws-types.d.ts
type GatewayWsConnectionKind = "gateway" | "worker";
type PresenceDeliverySnapshot = {
  version: number;
  rows: Map<string, SystemPresence>;
};
type GatewayWsClient = PluginNodeCapabilityClient & {
  socket: GatewayConnectionTransport;
  /** Physical WS liveness capability; absent on transports without ping/pong. */
  webSocket?: Pick<WebSocket, "ping" | "once" | "off">;
  connect: ConnectParams;
  connId: string;
  /** Host-owned transport retirement notification; never accepted from wire params. */
  connectionSignal?: AbortSignal;
  /** Service grant lifetime, independent of individual socket retirement. */
  remoteControlUiIngress?: RemoteControlUiIngressContext;
  connectionKind?: GatewayWsConnectionKind;
  worker?: WorkerConnectionIdentity;
  isDeviceTokenAuth?: boolean;
  /** Client id verified against the server-approved device pairing record. */
  pairedClientId?: string;
  usesSharedGatewayAuth: boolean;
  sharedGatewaySessionGeneration?: string;
  authPolicy?: GatewayAuthPolicy;
  presenceKey?: string;
  /** Last projected roster handed to this transport; absent after a drop or reset request. */
  presenceSnapshot?: PresenceDeliverySnapshot;
  /** Connection-local override for clients that opt out of roster message bodies. */
  includeSessionMessageBodies?: boolean;
  /** Connection-owned timing facts, reconciled across live peers independently of the TTL cache. */
  personPresence?: {
    onlineSince: number;
    lastActivityAt?: number;
  };
  /** Accepted interaction on this exact connection, never copied from another client. */
  connectionLastActivityAt?: number;
  authenticatedUserId?: string;
  /** Configured Enterprise account verified by trusted-proxy handshake admission. */
  authenticatedFactoryGitHubAccountId?: number;
  /** Verified Tailscale provider identity; generic proxy identities must not infer this. */
  authenticatedUserIsTailscaleProvider?: boolean;
  authenticatedGitHubIdentitySync?: AuthenticatedGitHubIdentitySync;
  /** Lifecycle-prepared canonical recipient; never a scope or authorization grant. */
  preparedRecipientProfileId?: string;
  preparedSessionProfile?: UserProfileIdentity;
  authenticatedUserProfile?: GatewayAuthenticatedUserProfile;
  clientIp?: string;
  /** Server-attested inputs for rechecking browser-origin policy after config publication. */
  browserOrigin?: GatewayWsBrowserOrigin;
  internal?: {
    /** Authenticated operator transport ingress; never accepted from wire params. */
    authenticatedOperator?: true;
    /** Exact accepted/issued operator token; null attests a tokenless ingress. */
    operatorDeviceTokenIdentity?: Readonly<PairedDeviceTokenIdentity> | null;
    /** Handshake-attested direct-local transport; never accepted from wire params. */
    isLocalClient?: true;
    /** Authenticated Control UI operator ingress; never accepted from wire params. */
    authenticatedControlUi?: true;
    /** Authenticated Control UI admin admission; never accepted from wire params. */
    controlUiAdmin?: true;
    approvalRuntime?: boolean;
    agentRuntimeIdentity?: AgentRuntimeIdentity;
    /** Server-attested role-policy actor; never accepted from WebSocket wire params. */
    operatorRoleActor?: GatewayOperatorRoleActor;
    /** Host-bound delegation, never accepted from a client or caller-supplied profile. */
    remoteIngressPrincipal?: RemoteIngressPrincipalSnapshot;
    /** Additional access captured at authenticated admission; independent of socket lifetime. */
    operatorAccessAuthority?: GatewayOperatorAccessAuthority | null;
  };
  invalidatedReason?: string;
};
//#endregion
//#region src/channels/message-access/child-session-publication.d.ts
/** Host-only, single-run intent for fresh immediate children; never serialized into a session. */
declare class ChildSessionPublication {
  #private;
  readonly requesterSessionKey: string;
  private assertSourceCurrent;
  private readonly prepareSource?;
  constructor(requesterSessionKey: string, assertSourceCurrent: () => void, prepareSource?: (() => Promise<(() => void) | null>) | undefined);
  prepare(): Promise<void>;
  private prepareSourceAuthorization;
  bind(run: OperationalRunInstanceRef, assertRunCurrent: () => void): void;
  assertCurrent(): void;
  claim(params: {
    sessionKey: string;
    entry: SessionEntry;
    parentSessionKey?: string;
    parent?: SessionEntry;
    isNew: boolean;
    fork?: boolean;
  }): void;
}
//#endregion
//#region src/gateway/session-creation-provenance.d.ts
type TrustedSessionCreation = Partial<AgentRuntimeSessionSpawnContext> & {
  skillLibrarySelections?: SkillLibrarySelection[];
  via: SessionCreatedVia;
  surface?: "plugin-dock";
  actor?: SessionCreatedActor;
  /** Creator-owned isolation requirement resolved only by the trusted Gateway boundary. */
  sandbox?: "required";
  /** Exact spawning session retained separately from the stable actor identity. */
  requesterSessionKey?: string;
  /** Live host-only ingress intent; never accepted from wire arguments. */
  childSessionPublication?: ChildSessionPublication;
};
//#endregion
//#region src/gateway/server-methods/client-types.d.ts
/** Trusted in-process spawn control plane that already owns this run's task row.
    Gateway CLI tracking only covers runs nobody else records, so a marked run
    must never get a second row. */
type GatewayAgentRunTaskOwner = "plugin_subagent" | "native_subagent";
/** Caller identity captured by a built-in agent tool before trusted in-process dispatch. */
type TrustedAgentToolCaller = Readonly<{
  agentId: string;
  sessionKey: string;
  requesterOrigin?: RequesterOrigin;
  /** Parent audit binding captured with this caller; never grants execution authority. */
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  /** Exact admitted requester lifetime; identity alone does not establish live authority. */
  assertCurrent?: () => void;
}>;
/** Closure-bound streaming hooks attached only to trusted plugin-owned synthetic clients. */
type GatewayNodeInvokeStream = {
  onProgress: (chunk: string) => void;
  onDispatchReady: (invokeId: string) => void;
  idleTimeoutMs?: number;
  isRuntimeCurrent: () => boolean;
};
/** Handshake metadata retained for RPCs; transport retirement does not cancel admitted work. */
type GatewayClient = Pick<GatewayWsClient, "connect" | "authPolicy" | "invalidated" | "connectionSignal" | "remoteControlUiIngress" | "browserOrigin" | "presenceKey" | "presenceSnapshot" | "includeSessionMessageBodies" | "clientIp" | "pairedClientId" | "authenticatedUserId" | "authenticatedFactoryGitHubAccountId" | "authenticatedUserIsTailscaleProvider" | "authenticatedGitHubIdentitySync" | "preparedSessionProfile" | "pluginSurfaceUrls" | "pluginNodeCapabilitySurfaces" | "pluginNodeCapabilities" | "isDeviceTokenAuth" | "sharedGatewaySessionGeneration"> & {
  usesSharedGatewayAuth?: boolean;
  connId?: string;
  authenticatedUserProfile?: Omit<NonNullable<GatewayWsClient["authenticatedUserProfile"]>, "avatarRevision"> & {
    avatarRevision?: string;
  };
  internal?: NonNullable<GatewayWsClient["internal"]> & {
    /** Marks the server-constructed client used by trusted in-process dispatch. */
    syntheticClient?: true;
    /** Original source restriction carried only by trusted in-process run admission. */
    operatorRunAuthority?: AdmittedRunOperatorAuthority;
    /** Overrides persisted sender attribution without changing the authorizing client identity. */
    senderAttribution?: {
      id: string;
      name?: string;
      identity?: TranscriptSenderIdentity;
    };
    /** Trusted session creation provenance; never accepted from Gateway wire params. */
    sessionCreation?: TrustedSessionCreation;
    /** Trusted built-in agent tool caller; never accepted from Gateway wire params. */
    agentToolCaller?: TrustedAgentToolCaller;
    allowModelOverride?: boolean;
    approvalRuntime?: boolean;
    /** Host-bound owner for one plugin approval request, without reviewer authority. */
    pluginApprovalRequestOwnerId?: string;
    cronRunContinuation?: boolean;
    pluginRuntimeOwnerId?: string;
    /** Host-attested session provenance for a trusted official plugin node invocation. */
    nodeInvokeApprovalSessionKey?: string;
    /** Plugin-owned in-process invoke hooks; never accepted from Gateway wire params. */
    nodeInvokeStream?: GatewayNodeInvokeStream;
    agentRunTracking?: GatewayAgentRunTaskOwner;
    /** Host-captured requester lineage for opt-in plugin subagent completion delivery. */
    pluginSubagentRequester?: PluginSubagentRequesterContext;
    runtimeContextFragments?: RuntimeContextFragment[];
    /** Host-owned: deliver only authored output, never runtime error payloads. */
    internalDeliverySuppressErrors?: boolean;
    /** Plugin-owned tools authorized for this internal subagent run. */
    runtimePluginToolGrant?: RuntimePluginToolGrant;
    /** Host-owned exact tool cap for a tracked plugin subagent run. */
    pluginSubagentToolsAllow?: string[];
    /** Opaque in-process subagent-completion capability; never accepted from wire params. */
    delegatedToolPolicyHandoffId?: string;
  };
};
//#endregion
//#region src/gateway/methods/descriptor.d.ts
type GatewayReadSharing = {
  /** Null keeps request-local reads out of response sharing. */
  shareKey: (caller: {
    client: GatewayClient | null;
    read?: {
      shareable?: boolean;
    };
  }, params: Record<string, unknown>) => string | null;
  shareInvalidationEvents: readonly string[];
  /** Absolute lifetime, including computation; the host also enforces its safety ceiling. */
  shareMaxAgeMs: number;
};
/** Scope marker for methods that only authenticated node clients may call. */
declare const NODE_GATEWAY_METHOD_SCOPE: "node";
/** Scope marker for methods whose handler derives the required operator scope at runtime. */
declare const DYNAMIC_GATEWAY_METHOD_SCOPE: "dynamic";
type GatewayMethodScope = OperatorScope | typeof NODE_GATEWAY_METHOD_SCOPE | typeof DYNAMIC_GATEWAY_METHOD_SCOPE;
type GatewayMethodOwner = {
  kind: "core";
  area: string;
} | {
  kind: "plugin";
  pluginId: string;
} | {
  kind: "channel";
  channelId: string;
} | {
  kind: "aux";
  area: string;
};
/** Startup availability flag exposed to clients as retryable startup-unavailable errors. */
type GatewayMethodStartupAvailability = "available" | "unavailable-until-sidecars";
type GatewayMethodProfileAccess = "independent" | "required";
/** A plugin operation addresses one existing session through the shared participation policy. */
type GatewayMethodSessionAccess = {
  mode: "write";
  allowOwnSessionScope?: boolean;
  /** Reuse the complete effective session tool policy for this capability. */
  requiredTool?: string;
};
type GatewayMethodHandler = (opts: never) => unknown;
type GatewayMethodDescriptor = Partial<GatewayReadSharing> & {
  name: string;
  handler: GatewayMethodHandler;
  scope: GatewayMethodScope;
  owner: GatewayMethodOwner;
  profileAccess: GatewayMethodProfileAccess;
  sessionAccess?: GatewayMethodSessionAccess;
  since?: string;
  startup?: GatewayMethodStartupAvailability;
  /** Observes another owner's result; cancelled on requester disconnect and restart drain. */
  lifetime?: "observation";
  controlPlaneWrite?: boolean;
  advertise?: boolean;
  description?: string;
};
type GatewayMethodRegistryView = {
  /** Opaque registry handle carried into request scope by the gateway composition root. */
  pluginRegistry?: object;
  getDescriptor: (name: string) => GatewayMethodDescriptor | undefined;
  getHandler: (name: string) => GatewayMethodHandler | undefined;
  listMethods: () => string[];
  listAdvertisedMethods: () => string[];
  getScope: (name: string) => GatewayMethodScope | undefined;
  getSessionAccess?: (name: string) => GatewayMethodSessionAccess | undefined;
  getReadSharing?: (name: string) => GatewayReadSharing | undefined;
  isStartupUnavailable: (name: string) => boolean;
  isObservation: (name: string) => boolean;
  isControlPlaneWrite: (name: string) => boolean;
  requiresAuthenticatedProfile: (name: string) => boolean;
  descriptors: () => readonly GatewayMethodDescriptor[];
};
//#endregion
//#region src/agents/auth-profiles/authorization-contract.d.ts
/** One credential owner’s live authorization lifetime, separate from bearer material. */
type AuthProfileAuthorization = {
  /** Opaque, non-secret, stable across token refresh; changes after disconnect/replacement. */
  readonly authorizationId: string;
  /** Cheap current-owner assertion for the final admission/commit boundary. */
  assertCurrent: () => void;
  /** Observe canonical owner state before intake/admission, including other-process changes. */
  revalidate: () => Promise<void>;
  dispose: () => void;
};
//#endregion
//#region src/plugins/types.mcp-connection.d.ts
/**
 * Trusted runtime identity for per-requester MCP connection resolution.
 * Only host-provided fields; plugins must not invent sender identity.
 * Future trusted fields (for example cron/subagent user context) can be added additively.
 */
type McpServerConnectionResolveContext = {
  /** Trusted message sender id. Required; runs without one fail closed. */
  requesterSenderId: string;
  /** Channel account id that received the message. */
  agentAccountId?: string;
  /** Message channel id (for example telegram or slack). */
  messageChannel?: string;
  /** Event consumers need an owner-held authorization observation, not only credentials. */
  requireLiveAuthority?: true;
};
/** Transport connection resolved for one requester-scoped MCP server. */
type McpServerConnectionResolved = {
  url: string;
  /** Per-user credentials; never logged, fingerprinted, or persisted by core. */
  headers?: Record<string, string>;
  /** Required when requireLiveAuthority is set. Disposal releases observation, not the account. */
  authority?: AuthProfileAuthorization;
};
/**
 * Plugin-owned connection resolver for a statically declared MCP server.
 * Server name/tool surface stay static; only the transport is requester-bound.
 */
type OpenClawPluginMcpServerConnectionResolver = {
  /** Server name matching `mcp.servers` / bundle MCP declaration. */
  serverName: string;
  resolve: (ctx: McpServerConnectionResolveContext) => McpServerConnectionResolved | null | Promise<McpServerConnectionResolved | null>;
};
/** Registry entry for a plugin MCP server connection resolver. */
type PluginMcpServerConnectionResolverRegistration = {
  pluginId: string;
  pluginName?: string;
  resolver: OpenClawPluginMcpServerConnectionResolver;
  source: string;
  rootDir?: string;
};
//#endregion
//#region src/plugins/model-catalog.types.d.ts
/** Read-only model choices admitted for the current requester and session incarnation. */
type PluginRequesterModelCatalog = {
  /** Opaque content revision; changes when the public projection changes. */
  revision: string;
  /** Pending inventory is incomplete and must never be treated as proof of availability. */
  state: "prepared" | "pending";
  models: {
    id: string;
    provider: string;
    name: string;
    /**
     * Canonical developer lineage from provider or catalog metadata, such as `anthropic` on
     * every route serving a Claude model. Compare by equality; absent means unknown.
     */
    family?: string;
    thinkingLevels?: string[];
    fastModes?: (boolean | "auto")[];
  }[];
  selectionPolicy?: {
    restricted: true;
    defaultModel: string | null;
  };
};
/** No selectors, refresh, credential access, or authority to execute a model. */
type PluginRequesterModels = {
  list: () => Promise<PluginRequesterModelCatalog>;
};
//#endregion
//#region src/plugins/plugin-command.types.d.ts
type ChannelId = ChannelId$1;
type PluginCommandDiagnosticsSession = Pick<PluginCommandContext, "sessionKey" | "sessionId" | "sessionTarget" | "sessionFile" | "channelId" | "accountId" | "messageThreadId" | "threadParentId"> & {
  /** Embedded agent harness selected for this session. */
  agentHarnessId?: string;
  /** Channel/provider for this session when available. */
  channel?: string;
};
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;
  /** Revalidate admitted owner authority before privileged effects, after awaited preparation. */
  assertOwnerCurrent?: () => void;
  /** Gateway client scopes for internal control-plane callers */
  gatewayClientScopes?: string[];
  /** Host-resolved agent that owns the active session. */
  agentId?: string;
  /** Stable host session key for the active conversation when available. */
  sessionKey?: string;
  /** Ephemeral host session id for the active conversation when available. */
  sessionId?: string;
  /** Canonical SQLite identity for active transcript access. */
  sessionTarget?: SessionTranscriptRuntimeTarget;
  /**
   * Deprecated transcript locator for the active OpenClaw session when available.
   *
   * SQLite-backed sessions use a `sqlite:<agentId>:<sessionId>:<storePath>`
   * marker, not a filesystem path. Use session id/key plus transcript-runtime
   * helpers for active transcript reads.
   *
   * @deprecated Use session identity fields with `plugin-sdk/session-transcript-runtime`.
   */
  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?: {
    /** Read-only requester/session-bound catalog, when explicitly requested and admitted. */
    models?: PluginRequesterModels;
    llm?: Pick<PluginRuntimeCore["llm"], "complete">;
    /** Native helpers bound to this authenticated command invocation. */
    subagents?: NativeSubagentRuntime;
    /** Bounded native schedules admitted by this external requester invocation only. */
    scheduledTurns?: PluginCommandScheduledTurns;
    compactCurrent?: () => Promise<{
      compacted: boolean;
      reason?: string;
      tokensBefore?: number;
      tokensAfter?: number;
    }>;
  };
  /** 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<PluginConversationBindingRequestResult>;
  detachConversationBinding: () => Promise<{
    removed: boolean;
  }>;
  getCurrentConversationBinding: () => Promise<PluginConversationBinding | null>;
};
type PluginCommandResult = ReplyPayload$1 & {
  /** Allows the agent session to continue processing after the command. */
  continueAgent?: boolean;
  /** Suppresses channel fallback replies when the handler already delivered a response. */
  suppressReply?: boolean;
};
type PluginCommandHandler = (ctx: PluginCommandContext) => PluginCommandResult | Promise<PluginCommandResult>;
declare const AGENT_PROMPT_SURFACE_KINDS: readonly ["openclaw_main",
/** @deprecated Use 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;
/** Opt-in command runtime families; future families extend this union. */
type PluginCommandRuntimeCapability = "subagents" | "models" | "scheduledTurns";
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<Record<string, string>> & {
    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<Record<string, string>> & {
    default?: string;
  };
  /** Description shown in /help and command menus */
  description: string;
  /** Localized descriptions for native command surfaces that support them. */
  descriptionLocalizations?: Record<string, string>;
  /**
   * 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;
  /** Optional bounded presentation for clients that explicitly support it. */
  clientPresentation?: {
    /** Parsed invocation shape eligible for client handling. */
    when: "no-arguments";
    action: {
      kind: "device-pairing";
    };
  };
  /** 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[];
  /** Optional invocation capabilities; subagents requires a manifest contract and requireAuth: true. */
  runtimeCapabilities?: readonly PluginCommandRuntimeCapability[];
  /** 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";
  handler: PluginCommandHandler;
};
//#endregion
//#region src/plugins/bundle-mcp.types.d.ts
type BundleMcpServerConfig = Record<string, unknown>;
type BundleMcpConfig = {
  mcpServers: Record<string, BundleMcpServerConfig>;
};
type BundleMcpDataDirOwnership = {
  pluginId: string;
  dataDir: string;
};
type BundleMcpDiagnostic = {
  pluginId: string;
  message: string;
};
//#endregion
//#region src/agents/bundle-mcp-config.d.ts
type MergedBundleMcpConfig = {
  config: BundleMcpConfig;
  diagnostics: BundleMcpDiagnostic[];
  pluginIdsByServer?: Record<string, string>;
  prepareDataDirsByServer: Record<string, BundleMcpDataDirOwnership>;
};
/** Session-shared harness connections must exclude requester-owned credentials. */
declare function loadStaticBundleMcpConfig(params: Parameters<typeof loadMergedBundleMcpConfig>[0]): MergedBundleMcpConfig & {
  requesterScopedServerNames: string[];
};
/** Loads enabled bundled MCP servers and overlays user config by server name. */
declare function loadMergedBundleMcpConfig(params: {
  workspaceDir: string;
  cfg?: OpenClawConfig;
  manifestRegistry?: Pick<PluginManifestRegistry, "plugins">;
  toolOverrides?: Pick<SessionToolOverrides, "mcpServers">;
}): MergedBundleMcpConfig;
//#endregion
//#region src/agents/mcp-stdio-client.d.ts
type McpStdioClientParams = {
  command: string;
  args?: string[];
  /** Exact child environment; nothing is inherited. */
  env: NodeJS.ProcessEnv;
  clientInfo: {
    name: string;
    version: string;
  };
  /** The server must answer initialize with exactly this version. */
  protocolVersion: string;
  startupTimeoutMs: number;
  maxPendingRequests: number;
  maxFrameBytes: number;
  errors: {
    /** Process, lifecycle, admission, deadline, and cancellation failures. */
    unavailable: (message: string, cause?: unknown) => Error;
    /** Malformed frames, JSON-RPC errors, and handshake contract violations. */
    protocol: (message: string, cause?: unknown) => Error;
  };
};
type McpStdioClient = {
  isAvailable(): boolean;
  readonly cleanupResult?: ProcessCleanupResult;
  request(method: string, params: Record<string, unknown>, options: {
    timeoutMs: number;
    signal?: AbortSignal;
  }): Promise<Record<string, unknown>>;
  stop(): Promise<void>;
};
/**
 * A strict client for a caller-owned stdio MCP proxy process fronting a stateful driver.
 * Any connection anomaly retires the whole connection; the caller supplies the error taxonomy.
 */
declare function createMcpStdioClient(params: McpStdioClientParams): McpStdioClient;
//#endregion
//#region src/agents/codex-mcp-config.types.d.ts
/** Codex app-server `mcp_servers` config map. */
type CodexMcpServersConfig = Record<string, Record<string, unknown>>;
type CodexBundleMcpThreadConfig = {
  configPatch?: {
    mcp_servers: CodexMcpServersConfig;
  };
  diagnostics: BundleMcpDiagnostic[];
  evaluated: boolean;
  fingerprint?: string;
  /** Enabled static servers across bundle defaults and owner config. */
  staticServerNames: string[];
  /** Enabled static servers originating from owner `mcp.servers` config. */
  userStaticServerNames: string[];
};
type LoadCodexBundleMcpThreadConfigParams = {
  workspaceDir: string;
  agentId?: string;
  /** Read-only initialization cannot provision data directories or requester transports. */
  preparationOnly?: true;
  cfg?: OpenClawConfig;
  toolsEnabled?: boolean;
  disableTools?: boolean;
  toolsAllow?: string[];
  manifestRegistry?: Pick<PluginManifestRegistry, "plugins">;
  toolOverrides?: Pick<SessionToolOverrides, "mcpServers" | "mcpToolsDeny">;
};
//#endregion
//#region src/agents/delegated-tool-policy.d.ts
type DelegatedToolPolicy = NonNullable<SessionEntry["delegatedToolPolicy"]>;
type DelegatedToolPolicyContext = {
  inheritedToolAllowlist?: string[];
  inheritedToolDenylist?: string[];
  /** Prepared by the host before policy flattening; never accepted from tool arguments. */
  delegatedToolDenyFloor?: DelegatedToolDenyFloor;
  /** Immediate requester execution snapshot; ordinary inherited denies retain revocation fallback. */
  requesterToolDenylist?: string[];
  /** Bound at tool construction so an awaited spawn cannot pin a superseded runtime config. */
  readDelegationConfig?: () => OpenClawConfig;
  /** A mediated producer cannot export its active native delegation exception. */
  delegatedToolPolicyUnavailable?: boolean;
  /** Restrictive requester policy originated at trusted sender/channel ingress. */
  inheritedToolPolicySource?: "sender";
};
type DelegatedToolDenyFloor = {
  policyAgentId: string;
  deny: string[];
  continuation?: Pick<DelegatedToolPolicy, "requesterSessionKey" | "targetAgentId">;
};
//#endregion
//#region src/agents/subagents/spawn/subagent-session-store.d.ts
type PersistedSessionCapabilityEntry = Pick<SessionEntry, "sessionId" | "lifecycleRevision" | "createdVia" | "spawnDepth" | "subagentRole" | "subagentControlScope" | "spawnedBy" | "completionOwnerSessionKey" | "inheritedToolPolicyVersion" | "inheritedToolPolicySource" | "inheritedToolAllow" | "inheritedToolDeny" | "delegatedToolPolicy">;
type SessionCapabilityEntry = { [Key in keyof PersistedSessionCapabilityEntry]?: unknown; } & {
  clientCapabilities?: string[];
};
/** A complete store view; reads are memoized only for the current synchronous resolution. */
type SessionCapabilityLookup = {
  /** Cross-agent owner projection: missing rows are authoritative, never a database fallback. */
  authoritative?: true;
  /** Reuse this memo when depth fallback revisits the same logical store. */
  scope?: {
    storePath: string;
    agentId: string;
  };
  get: (sessionKey: string) => SessionCapabilityEntry | undefined;
  getById: (sessionId: string) => SessionCapabilityEntry | undefined;
};
type SessionCapabilityStore = Record<string, SessionCapabilityEntry> | SessionCapabilityLookup;
/** Facts from an owning read in the same synchronous policy resolution. */
type PreparedSessionCapabilityEntry = {
  sessionKey: string;
  entry: SessionCapabilityEntry;
};
type SessionCapabilityRead = {
  storePath: string;
  agentId: string;
} & ({
  sessionKey: string;
  sessionId?: never;
} | {
  sessionId: string;
  sessionKey?: never;
});
/** Data-only inputs consumed by a prepared requester policy, including absent rows. */
type SessionCapabilitySnapshot = {
  query: SessionCapabilityRead;
  facts: Array<{
    field: keyof PersistedSessionCapabilityEntry;
    value: unknown;
  }> | undefined;
};
//#endregion
//#region src/agents/conversation-capability-profile.d.ts
type ConversationCapabilityProfileParams = {
  requesterOrigin?: RequesterOrigin;
  operatorProfileId?: string;
  /** Captured policy owner; null excludes ambient request authority. */
  operatorAuthority?: AdmittedRunOperatorAuthority | null;
  /** Original authenticated conversation, independent of the execution session route. */
  conversationId?: string | null;
  chatType?: string;
  messageThreadId?: string | number | null;
  memberRoleIds?: readonly string[];
  config?: OpenClawConfig;
  sessionKey?: string;
  /** Live conversation key when a sandbox/policy key is used for tool filtering. */
  runSessionKey?: string;
  /** Session key used for subagent capability inheritance when it differs from sessionKey. */
  sandboxSessionKey?: string;
  /** Owner-read session metadata consumed synchronously during policy preparation. */
  preparedSessionEntry?: PreparedSessionCapabilityEntry;
  /** Complete owner-prepared lineage; no database reads during policy projection. */
  preparedSessionCapabilityStore?: SessionCapabilityStore;
  sessionId?: string;
  runId?: string;
  agentId?: string;
  agentAccountId?: string | null;
  messageProvider?: string | null;
  messageChannel?: string | null;
  conversationToolPolicy?: GroupToolPolicyConfig;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  spawnedBy?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
  senderIsOwner?: boolean;
  modelProvider?: string;
  modelId?: string;
  workspaceDir?: string;
  cwd?: string;
  spawnWorkspaceDir?: string;
  sandboxToolPolicy?: SandboxToolPolicy;
  runtimeToolAllowlist?: string[];
  /** Persist the runtime allowlist as real parent authority on spawned children. */
  inheritRuntimeToolAllowlist?: boolean;
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "plugins">;
  inputProvenance?: InputProvenance;
  /** Consumed in-process completion capability; public callers cannot set this fact. */
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  /** Trusted server-stamped authority for an explicitly capped scheduled run. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
};
/** Prepare the authoritative inbound surface once for each tool catalog. */
declare function resolveConversationQuestionInputMode(params: Pick<ConversationCapabilityProfileParams, "messageChannel" | "messageProvider">): "native" | "buttons" | "none";
declare function resolveConversationCapabilityProfile(params: ConversationCapabilityProfileParams): {
  requesterOrigin: Readonly<{
    sessionKey: string;
    operatorProfileId?: string;
    delegatedCreatorProfileId?: string | null;
    messageProvider?: string | null;
    accountId?: string | null;
    chatType?: ChatType;
    conversationId?: string | null;
    messageThreadId?: string | number | null;
    groupId?: string | null;
    groupChannel?: string | null;
    groupSpace?: string | null;
    senderId?: string | null;
    senderName?: string | null;
    senderUsername?: string | null;
    senderE164?: string | null;
  }> | undefined;
  agentId: string | undefined;
  serviceIdentity: {
    accountId: string | null | undefined;
  };
  model: {
    provider: string | undefined;
    id: string | undefined;
  };
  conversation: {
    sessionKey: string | undefined;
    policySessionKey: string | undefined;
    runSessionKey: string | undefined;
    sessionId: string | undefined;
    messageProvider: string | null | undefined;
    messageChannel: string | null | undefined;
    questionInputMode: "buttons" | "native" | "none";
    groupId: string | null | undefined;
    groupChannel: string | null | undefined;
    groupSpace: string | null | undefined;
    spawnedBy: string | null | undefined;
  };
  sender: {
    isOwner: boolean | undefined;
  };
  workspace: {
    workspaceRoot: string;
    runtimeRoot: string;
    spawnWorkspaceRoot: string | undefined;
  };
  policy: {
    agentId: string | undefined;
    sources: Partial<Record<"agent" | "agentProvider" | "global" | "globalProvider" | "profile" | "providerProfile", {
      kind: "profile" | "config" | "session" | "runtime";
      path?: string;
      profile?: string;
      alsoAllowPath?: string;
    }>>;
    profiles: {
      profile: ToolProfileId;
      source: string;
      active: boolean;
    }[];
    globalPolicy: SandboxToolPolicy | undefined;
    globalProviderPolicy: SandboxToolPolicy | undefined;
    agentPolicy: SandboxToolPolicy | undefined;
    agentProviderPolicy: SandboxToolPolicy | undefined;
    profile: "coding" | "full" | "messaging" | "minimal" | undefined;
    providerProfile: ToolProfileId | undefined;
    gatewayConfigReadAllowed: boolean;
    sessionKey: string | undefined;
    subagentSessionKey: string | undefined;
    trustedGroup: {
      groupId: string | null | undefined;
      dropped: boolean;
    };
    profilePolicy: {
      allow?: string[];
      deny?: string[];
    } | undefined;
    providerProfilePolicy: {
      allow?: string[];
      deny?: string[];
    } | undefined;
    profileAlsoAllow: string[] | undefined;
    providerProfileAlsoAllow: string[] | undefined;
    groupPolicy: SandboxToolPolicy | undefined;
    senderPolicy: SandboxToolPolicy | undefined;
    sandboxPolicy: SandboxToolPolicy | undefined;
    sandboxSessionRenameOnly: boolean;
    subagentPolicy: SandboxToolPolicy | undefined;
    inheritedToolPolicy: SandboxToolPolicy | undefined;
    sessionInheritedToolPolicy: SandboxToolPolicy | undefined;
    inheritedToolPolicyForSpawn: SandboxToolPolicy | undefined;
    delegatedToolPolicy: {
      requesterSessionKey: string;
      targetAgentId: string;
      deny: string[];
      requesterDeny: string[];
    } | undefined;
    inheritedToolPolicySource: "sender" | undefined;
    delegated: boolean;
    requesterPolicySource: "completion-handoff" | "current-request" | "persisted-child";
    runtimeToolPolicyForInheritance: {
      allow: string[];
    } | undefined;
    inheritancePolicies: ({
      allow?: string[];
      deny?: string[];
    } | {
      allow: string[];
    } | undefined)[];
    explicitToolAllowlist: string[];
    explicitToolOverrideAllowlist: string[];
    explicitToolDenylist: string[];
    runtimePluginToolGrant: RuntimePluginToolGrant | undefined;
  };
};
type ResolvedConversationCapabilityProfile = ReturnType<typeof resolveConversationCapabilityProfile>;
//#endregion
//#region src/agents/agent-bundle-mcp-harness.d.ts
type RequesterScopedHarnessMcpTools = {
  /** Executable tools for this turn (live binding or not-connected stubs). */
  tools: AnyAgentTool[];
  /**
   * Session-stable advertised tool surface for dynamic-tool fingerprints.
   * Identical for every sender once the session has observed a scoped catalog.
   */
  advertisedTools: AnyAgentTool[];
  dispose: () => Promise<void>;
};
type InteractiveConfiguredMcpApprovalRequest = {
  signal?: AbortSignal;
  safeToolName: string;
  toolCallId: string;
  serverName: string;
  toolName: string;
  mode: "auto" | "prompt";
  isActive: () => boolean;
};
type MaterializeRequesterScopedMcpToolsForHarnessRunParams = {
  sessionId: string;
  sessionKey?: string;
  agentId?: string;
  workspaceDir: string;
  agentDir?: string;
  cfg?: OpenClawConfig;
  manifestRegistry?: Pick<PluginManifestRegistry, "plugins">;
  toolOverrides?: Pick<SessionToolOverrides, "mcpServers" | "mcpToolsDeny">;
  requesterSenderId?: string | null;
  agentAccountId?: string | null;
  messageChannel?: string | null;
  reservedToolNames?: Iterable<string>;
  toolsAllow?: string[];
  /** When set, applies the same final effective tool policy as the embedded runner. */
  conversationCapabilityProfile?: ResolvedConversationCapabilityProfile;
  /** Builds a capability profile when conversationCapabilityProfile is omitted. */
  policyContext?: Omit<ConversationCapabilityProfileParams, "runtimeToolAllowlist">;
  /** Exact established Codex yolo predicate; no other profile bypasses approval metadata. */
  autoApproveCodexAppServerApprovals?: boolean;
  /** Interactive turns request approval before the original MCP executor runs. */
  requestInteractiveCodexApproval?: (params: InteractiveConfiguredMcpApprovalRequest) => Promise<void>;
  warn?: (message: string) => void;
};
/**
 * Materialize requester-scoped MCP tools for a harness run (e.g. Codex dynamic tools).
 * Updates the session advertised-catalog cache when a requester resolves a catalog.
 * Before any requester resolves in the session, returns undefined (nothing to advertise).
 */
declare function materializeRequesterScopedMcpToolsForHarnessRunCore(params: MaterializeRequesterScopedMcpToolsForHarnessRunParams): Promise<RequesterScopedHarnessMcpTools | undefined>;
//#endregion
//#region src/sessions/session-controller.backend-contracts.d.ts
type ReplyBackendCancelReason = "user_abort" | "restart" | "superseded";
type ReplyBackendQueueMessageOptions = {
  /** Prepared context for this queue item, separate from its transcript and answer text. */
  currentInboundContext?: CurrentInboundPromptContext;
  steeringMode?: "all";
  /** True when this queue item came from the channel's current user turn. */
  isInboundUserMessage?: boolean;
  /** Host-captured human reply identity, independent of pending-question eligibility. */
  isInboundUserReply?: boolean;
  /** User-authorized controls retain sender authority but are not answers to pending questions. */
  allowPendingUserInputAnswer?: false;
  terminalReplyExpectation?: ReplyExpectation;
  /** Exact tool authority resolved for an inbound user turn before steering. */
  toolAuthorityFingerprint?: string;
  /** Internal proof that a mismatched route recomputes to the active run's full authority. */
  pendingInputAuthorityFingerprint?: string;
  debounceMs?: number;
  /** Ordered current-turn images to inject with the steering text. */
  images?: ImageContent$1[];
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered facts represented by attachment text in this steering prompt. */
  media?: MediaFact[];
  deliveryTimeoutMs?: number;
  waitForTranscriptCommit?: boolean;
  /** Stable source identity for exact queued-message commit/cancellation matching. */
  queueIdentity?: string;
  abortSignal?: AbortSignal;
  /** Releases arrival ordering once the runtime has actually accepted this queue item. */
  onQueueAccepted?: (accepted: boolean) => void;
  /** Releases per-input custody after commit, cancellation, or terminal rejection. */
  onQueueSettled?: () => void;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  /** Prepared channel turn to merge only at transcript persistence. */
  userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
};
type ReplyToolAuthorityRoute = Readonly<{
  provider: string;
  model: string;
}>;
/** Per-message authority facts projected against an active run's frozen owner state. */
type ReplyToolAuthorityOverlay = Readonly<{
  /** Internal admission decision; never used for explicit cross-session requests. */
  allowCollaborativeSteering?: true;
  sessionKey?: string;
  operatorAuthority?: AdmittedRunOperatorAuthority;
  permissionMode?: SessionEntry["permissionMode"];
  toolOverrides?: SessionEntry["toolOverrides"];
  originatingChannel?: OriginatingChannelType;
  messageProvider?: string;
  chatType?: ChatType;
  agentAccountId?: string;
  conversationToolPolicy?: GroupToolPolicyConfig;
  conversationId?: string;
  messageThreadId?: string | number;
  groupId?: string;
  groupChannel?: string;
  groupSpace?: string;
  memberRoleIds?: string[];
  spawnedBy?: string;
  senderId?: string;
  senderName?: string;
  senderUsername?: string;
  senderE164?: string;
  senderIsOwner: boolean;
  /** Attribution carried by the originating request; grants no operator permission. */
  gitContributorProfileId?: string;
  inputProvenance?: InputProvenance;
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  scheduledToolPolicy?: ScheduledToolPolicyContext;
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  toolsAllow?: string[];
  disableTools: boolean;
  traceAuthorized: boolean;
  approvalReviewerDeviceId?: string;
  clientCaps?: string[];
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  toolBindings?: Readonly<Record<string, unknown>>;
}>;
/** Fresh delegation facts projected at its destination, separate from a source tool ceiling. */
type ReplyToolAuthorityRequester = Readonly<{
  requesterOrigin: RequesterOrigin;
  config: OpenClawConfig;
}>;
type ReplyTurnParticipantInput = Pick<ReplyToolAuthorityOverlay, "operatorAuthority" | "senderId" | "senderName" | "gatewayUiCommandTarget"> & {
  requesterOrigin?: RequesterOrigin;
};
type ReplyToolAuthoritySnapshot = Readonly<{
  /** Authenticated requester identity, independent of permissions and client reconnections. */
  requesterPrincipalKey?: string;
  close?(): void;
  personalToolOwner?: ReplyTurnParticipantInput;
  /** Selection admitted before runtime fallback or hooks choose a concrete model. */
  requestedRoute?: ReplyToolAuthorityRoute;
  /** @deprecated Use fingerprintAsync for worker-backed preparation. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  fingerprint(route?: ReplyToolAuthorityRoute): string;
  /** @deprecated Use projectAsync for worker-backed preparation. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  project: (overlay: ReplyToolAuthorityOverlay, route: ReplyToolAuthorityRoute) => string;
  fingerprintAsync?(route?: ReplyToolAuthorityRoute): Promise<string>;
  projectAsync?(overlay: ReplyToolAuthorityOverlay, route: ReplyToolAuthorityRoute): Promise<string>;
  projectRequester?(requester: ReplyToolAuthorityRequester, route: ReplyToolAuthorityRoute): string;
  projectRequesterAsync?(requester: ReplyToolAuthorityRequester, route: ReplyToolAuthorityRoute): Promise<string>;
}>;
type ReplyTurnParticipant = Readonly<{
  profileId: string;
  senderId: string;
  name: string;
  /** Host-issued source; independent children acquire their own custody before turn close. */
  operatorAuthority: AdmittedRunOperatorAuthority;
  requesterOrigin?: RequesterOrigin;
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  assertCurrent: () => void;
}>;
type ReplyTurnParticipants = {
  accept(participant: ReplyTurnParticipantInput): void;
  resolve(this: void, user?: string, options?: {
    allowTurnOwner?: () => boolean;
  }): ReplyTurnParticipant | undefined;
  close(): void;
};
type ReplyBackendQueueMessageResult = {
  /** Input is non-replayable, but its delivery or commitment could not be confirmed. */
  transcriptCommit: "unconfirmed";
  errorMessage: string;
};
type ReplyBackendMessageInjection = {
  /** Runtime-owned admission state; independent from token streaming. */
  isAvailable(): boolean;
  queueMessage(text: string, options?: ReplyBackendQueueMessageOptions): Promise<void | ReplyBackendQueueMessageResult>;
};
/** V2 sinks invoke the host-owned, per-injection assertion at their final effect. */
type ReplyToolAuthorityPreparation = {
  assertCurrent(this: void): void;
  prepareCurrent(this: void): Promise<void>;
  /** Pending-question compatibility still checks mutable policy synchronously. */
  compatAssertCurrent(this: void): void;
};
type ReplyBackendMessageInjectionV2 = {
  readonly version: 2;
  isAvailable(): boolean;
  /** @deprecated Use queueMessageAsync with fresh policy preparation. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  queueMessage(text: string, options: ReplyBackendQueueMessageOptions | undefined, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<void | ReplyBackendQueueMessageResult>;
  queueMessageAsync?(text: string, options: ReplyBackendQueueMessageOptions | undefined, preparation: ReplyToolAuthorityPreparation, authorityKind: "run" | "source-bound"): Promise<void | ReplyBackendQueueMessageResult>;
  /** @deprecated Use claimPendingUserInputAnswerAsync with fresh policy preparation. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  claimPendingUserInputAnswer?(text: string, options: ReplyBackendQueueMessageOptions | undefined, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<boolean>;
  claimPendingUserInputAnswerAsync?(text: string, options: ReplyBackendQueueMessageOptions | undefined, preparation: ReplyToolAuthorityPreparation, authorityKind: "run" | "source-bound"): Promise<boolean>;
  /** @deprecated Use cancelPendingUserInputAsync with fresh policy preparation. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  cancelPendingUserInput?(resolvedBy: string, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<boolean>;
  cancelPendingUserInputAsync?(resolvedBy: string, preparation: ReplyToolAuthorityPreparation, authorityKind: "run" | "source-bound"): Promise<boolean>;
};
type ReplyBackendHandle = {
  readonly kind: "embedded" | "cli";
  readonly runId?: string;
  /** Exact authority of this concrete backend attempt, after fallback selection. */
  readonly toolAuthorityFingerprint?: string;
  readonly sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  readonly terminalReplyExpectation?: ReplyExpectation;
  /** The sink records a human reply obligation only upon accepted steering. */
  readonly supportsUserReplyPromotion?: boolean;
  readonly taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  /** True only when queueMessage preserves images supplied in its options. */
  readonly supportsQueueMessageImages?: boolean;
  /** True only when queueMessage can hold its receipt until the transcript commit. */
  readonly supportsTranscriptCommitWait?: boolean;
  /** False keeps inbound steering with the turn owner's profile; omission permits other profiles. */
  readonly supportsCrossProfileSteering?: boolean;
  claimPendingUserInputAnswer?: (text: string, options?: ReplyBackendQueueMessageOptions) => Promise<boolean>;
  cancelPendingUserInput?: (resolvedBy: string) => Promise<boolean>;
  cancel(reason?: ReplyBackendCancelReason): void;
  readonly messageInjection?: ReplyBackendMessageInjection;
  /** V1 remains compatible with v2026.8.1; source-bound input requires V2. */
  readonly messageInjectionV2?: ReplyBackendMessageInjectionV2;
  /** @deprecated Compatibility for shipped embedded handles. Use messageInjection. */
  isStreaming?: () => boolean;
  isStopped?: () => boolean;
  /** True after this backend accepted an abort, even while its cleanup is retained. */
  isAborted?: () => boolean;
  isAbortable?: () => boolean;
  /** Recover a stalled model request while retaining this native turn for fallback. */
  recoverStalledModelCall?: () => boolean;
  /** Stable within one registration; re-read identity because it can be replaced or cleared. */
  readonly turnStatus?: ReplyBackendTurnStatus;
  /** @deprecated Compatibility for shipped embedded handles. Use messageInjection. */
  queueMessage?: ReplyBackendMessageInjection["queueMessage"];
  /**
   * Compatibility-only hook so legacy "abort compacting runs" paths can still
   * find embedded runs that are compacting during the main run phase.
   */
  isCompacting?: () => boolean;
};
//#endregion
//#region src/sessions/session-controller.target.d.ts
/** Captured logical/store identity. Incarnation is evidence, never live authorization. */
type SessionTarget = Readonly<{
  storeScope: string;
  /** Prepared storage observation only; never scheduling identity or live authority. */
  physicalStorePath?: string;
  sessionKey: string;
  aliases: readonly string[];
  agentId: string | undefined;
  incarnation: string | undefined;
}>;
//#endregion
//#region src/sessions/session-controller.queries.d.ts
/** Resolves the active run for one logical key, narrowed to a physical owner when provided. */
declare function resolveActiveSessionRunId(sessionKey: string, target?: SessionTarget): string | undefined;
//#endregion
//#region src/agents/embedded-agent-runner/runs.d.ts
/**
 * Abort embedded OpenClaw runs.
 *
 * - With a sessionId, aborts that single run.
 * - With no sessionId, supports targeted abort modes (for example, compacting runs only).
 */
declare function abortEmbeddedAgentRun(sessionId: string, opts?: {
  reason?: "restart";
}): boolean;
declare function abortEmbeddedAgentRun(sessionId: undefined, opts: {
  mode: "all" | "compacting";
  reason?: "restart";
}): boolean;
type AbortAndDrainEmbeddedAgentRunResult = {
  aborted: boolean;
  drained: boolean;
  forceCleared: boolean;
  recoveringModelAttempt?: true;
};
type AbortAndDrainEmbeddedAgentRunParams = {
  sessionId: string;
  sessionKey?: string;
  settleMs?: number;
  forceClear?: boolean;
  reason?: string;
};
declare function abortAndDrainEmbeddedAgentRun(params: AbortAndDrainEmbeddedAgentRunParams): Promise<AbortAndDrainEmbeddedAgentRunResult>;
declare function attachActiveEmbeddedRun(sessionId: string, handle: EmbeddedAgentQueueHandle, sessionKey?: string, sessionFile?: string, agentId?: string, admittedOperation?: ReplyOperation, lifecycleGeneration?: string): ActiveEmbeddedRunAttachment | undefined;
//#endregion
//#region src/agents/harness/user-input-types.d.ts
type AgentHarnessUserInputOption = QuestionOption;
type AgentHarnessUserInputQuestion = Omit<QuestionRequestQuestion, "questionId" | "options" | "defaultAnswers" | "secretStore"> & {
  id: string;
  defaultAnswers?: readonly string[];
  options?: readonly AgentHarnessUserInputOption[] | null;
};
type AgentHarnessUserInputAnswers = {
  answers: Record<string, {
    answers: string[];
  }>;
};
//#endregion
//#region src/agents/harness/gateway-question-dispatch.d.ts
type AgentHarnessQuestionGatewayCall = (method: string, opts: {
  timeoutMs?: number;
}, params?: unknown, extra?: {
  signal?: AbortSignal;
}) => Promise<unknown>;
/** Custom transports opt into enforcing authority after preparation, immediately before I/O. */
type AgentQuestionDispatcher = {
  version: 2;
  call: (request: {
    method: string;
    options: {
      timeoutMs?: number;
    };
    params?: unknown;
    signal?: AbortSignal;
    authority: {
      kind: "unscoped";
    } | {
      kind: "source-bound";
      /** @deprecated For preparation, await assertCurrentAsync; keep the final effect assertion. Sync preparation is supported through 2026-12-31. Removal in the first January 2027 stable release. */
      assertCurrent: () => void;
      assertCurrentAsync?: () => Promise<void>;
    };
  }) => Promise<unknown>;
};
//#endregion
//#region src/agents/harness/user-input-bridge.d.ts
type AgentHarnessUserInputPromptOptions = {
  intro?: string;
  formatText?: (text: string) => string;
  secretWarning?: string;
  otherLabel?: string;
  presentation?: MessagePresentation;
};
type RunAgentHarnessGatewayQuestionParams = {
  questions: readonly AgentHarnessUserInputQuestion[];
  sessionKey: string;
  agentId?: string;
  runId?: string;
  timeoutMs: number;
  gatewayCall?: AgentHarnessQuestionGatewayCall | AgentQuestionDispatcher;
  delivery: Pick<EmbeddedRunAttemptParams, "onBlockReply" | "onPartialReply"> & {
    hostCapabilities?: AgentHarnessHostCapabilities;
  };
  promptOptions?: AgentHarnessUserInputPromptOptions;
  signal?: AbortSignal;
  questionId?: string;
};
type PromptDeliveryParams = Pick<EmbeddedRunAttemptParams, "onBlockReply" | "onPartialReply">;
declare function emptyAgentHarnessUserInputAnswers(): AgentHarnessUserInputAnswers;
declare function formatAgentHarnessUserInputPrompt(questions: readonly AgentHarnessUserInputQuestion[], options?: AgentHarnessUserInputPromptOptions): string;
declare function deliverAgentHarnessUserInputPrompt(params: PromptDeliveryParams, questions: readonly AgentHarnessUserInputQuestion[], options?: AgentHarnessUserInputPromptOptions): Promise<void>;
declare function buildAgentHarnessUserInputAnswers(questions: readonly AgentHarnessUserInputQuestion[], inputText: string): AgentHarnessUserInputAnswers;
declare function normalizeAgentHarnessUserInputAnswer(answer: string, question: AgentHarnessUserInputQuestion): string | undefined;
//#endregion
//#region src/agents/harness/gateway-question.d.ts
/** Owns reservation and persistence; absent questions return before checking caller authority. */
declare function claimPendingAgentQuestionAnswer(params: {
  sessionKey?: string;
  text: string;
  persist?: () => Promise<void>;
  sourceRecorder?: UserTurnTranscriptRecorder;
  authority?: QuestionInputAuthority;
}): Promise<boolean>;
/** Cancels a question before the same inbound message takes another route. */
declare function cancelPendingAgentQuestionForSession(params: {
  sessionKey?: string;
  resolvedBy: string;
  authority?: QuestionInputAuthority;
}): Promise<boolean>;
/** Registers, presents, and waits for one harness-owned gateway question record. */
declare function runAgentHarnessGatewayQuestion(params: RunAgentHarnessGatewayQuestionParams): Promise<QuestionWaitAnswerResult>;
//#endregion
//#region src/agents/harness/structured-input-boundary.d.ts
type StructuredInputScalar = string | number | boolean | null;
type StructuredInputValue = StructuredInputScalar | StructuredInputValue[] | StructuredInputRecord;
type StructuredInputRecord = {
  [key: string]: StructuredInputValue;
};
type StructuredInputAnswerValue = string | number | boolean | string[];
type StructuredInputDecodeResult = {
  kind: "absent";
} | {
  kind: "invalid";
  message: string;
} | {
  kind: "present";
  entries: Array<[string, StructuredInputAnswerValue]>;
};
type StructuredInputField = {
  question: AgentHarnessUserInputQuestion;
  decode: (values: readonly string[]) => StructuredInputDecodeResult;
};
type StructuredInputPlan = {
  kind: "form";
  intro: string;
  fields: StructuredInputField[];
} | {
  kind: "url";
  question: AgentHarnessUserInputQuestion;
};
type StructuredInputCompileResult = {
  kind: "ready";
  plan: StructuredInputPlan;
} | {
  kind: "unsupported";
  message: string;
};
/** The existing MCP view owner supplies and retires this capability with the elicitation. */
type StructuredInputResourceContext = {
  viewId: string;
  uploads: boolean;
  previews: boolean;
  /** Checks resources admitted by this exact pending form, never arbitrary URI syntax. */
  isUploadedResource: (questionId: string, uri: string) => boolean;
};
type StructuredInputCompilerOptions = {
  protocolName: string;
  allowEmptyForm?: boolean;
  minimumChoiceCount?: 1 | 2;
  allowEnumNames?: boolean;
  allowImagePicker?: boolean;
  /** OpenAI rich forms, including suggestions, thumbnails, and resource choices. */
  allowRichForms?: boolean;
  resourceContext?: StructuredInputResourceContext;
  booleanLabels?: readonly [string, string];
  metadata?: {
    secretPath?: readonly string[];
    otherAnswerPath?: readonly string[];
    otherQuestionIdPath?: readonly string[];
  };
};
/** Copies only bounded, enumerable own data properties without invoking accessors. */
declare function snapshotStructuredInput(value: unknown, options?: {
  richForm?: boolean;
}): StructuredInputValue | undefined;
declare function isStructuredInputRecord(value: unknown): value is StructuredInputRecord;
//#endregion
//#region src/agents/harness/structured-input.d.ts
/** Wraps already bounded protocol questions in the shared execution plan. */
declare function compileStructuredInputQuestions(params: {
  questions: readonly AgentHarnessUserInputQuestion[];
  intro: string;
}): StructuredInputCompileResult;
/** Compiles a bounded object schema into Gateway questions plus answer decoders. */
declare function compileStructuredInputForm(params: {
  schema: unknown;
  message: string | undefined;
  fallbackMessage: string;
  options: StructuredInputCompilerOptions;
}): StructuredInputCompileResult;
/** Keeps browser navigation separate from confirmation that the external step is complete. */
declare function compileStructuredInputUrl(params: {
  url: unknown;
  elicitationId: unknown;
  message: unknown;
  fallbackMessage: string;
  protocolName: string;
}): StructuredInputCompileResult;
//#endregion
//#region src/agents/harness/structured-input-execution.d.ts
type StructuredInputExecutionResult = {
  status: "answered";
  answers: Record<string, string[]>;
  content: Record<string, StructuredInputAnswerValue>;
} | {
  status: "declined";
  message?: string;
} | {
  status: "cancelled";
  message?: string;
} | {
  status: "unsupported";
  message: string;
};
type StructuredInputExecutionParams = {
  input: StructuredInputCompileResult;
  sessionKey: string;
  agentId?: string;
  runId?: string;
  timeoutMs: number;
  gatewayCall?: Parameters<typeof runAgentHarnessGatewayQuestion>[0]["gatewayCall"];
  delivery: Parameters<typeof runAgentHarnessGatewayQuestion>[0]["delivery"];
  signal?: AbortSignal;
  isActive?: () => boolean;
  questionId?: (batch: number) => string | undefined;
  promptOptions?: AgentHarnessUserInputPromptOptions & {
    unsupportedIntro?: string;
    urlIntro?: string;
  };
};
/** Executes one compiled form or URL with shared batching, secret, and fencing semantics. */
declare function runStructuredInput(params: StructuredInputExecutionParams): Promise<StructuredInputExecutionResult>;
//#endregion
//#region src/agents/tool-policy-match.d.ts
/** Snapshot one synchronous filtering operation; execution checks must prepare current policy. */
declare function createToolPolicyMatcher(policy?: SandboxToolPolicy, writeAllowsApplyPatch?: boolean): (name: string) => boolean;
//#endregion
//#region src/plugins/agent-executor-controller.types.d.ts
/** A native agent session's connection to a self-hosted executor. */
type AgentExecutorBinding = {
  sessionKey: string;
  agentId: string;
  nativeSessionId: string;
  environmentId: string;
  remoteUrl: string;
  workspaceDirectory: string;
};
/** Authority for this operation; recheck after awaits and before side effects. */
type AgentExecutorContext = {
  signal: AbortSignal;
  assertCurrent: () => void;
};
/** One plugin owns connection management for its configured executor workspace. */
type AgentExecutorController = {
  /** Absolute path on the executor, which may differ from the Gateway workspace. */
  workspaceDirectory: string;
  /** Idempotently establish or reconnect this exact native environment. */
  ensure: (binding: AgentExecutorBinding, context: AgentExecutorContext) => Promise<void>;
  /** Idempotently retire this connection after native session work has settled. */
  retire: (binding: AgentExecutorBinding, context: AgentExecutorContext) => Promise<void>;
};
//#endregion
//#region src/plugins/agent-executor-controller.d.ts
/** Retained for published AgentsAPI imports; controller ownership cannot be recreated. */
declare function resolveAgentExecutorController(pluginId: string): AgentExecutorController;
//#endregion
//#region src/agents/agent-run-terminal-reply.d.ts
type PreparedAgentRunTerminalReply = {
  text: string;
  terminalReply: AgentRunTerminalReplySnapshot;
};
declare function prepareAgentRunTerminalReply(params: {
  rawText?: string;
}): PreparedAgentRunTerminalReply;
//#endregion
//#region src/auto-reply/reply/reply-directives.d.ts
type ReplyDirectiveParseResult = {
  text: string;
  mediaUrls?: string[];
  mediaFailures?: ReplyMediaFailure[];
  replyToId?: string;
  replyToCurrent?: boolean;
  replyToTag: boolean;
  audioAsVoice?: boolean;
};
//#endregion
//#region src/auto-reply/reply/streaming-directives.d.ts
type ConsumeOptions = {
  final?: boolean;
};
type StreamingDirectiveAccumulator = {
  readonly sourceText: string;
  consume(raw: string, options?: ConsumeOptions): ReplyDirectiveParseResult | null;
  reset(): void;
};
declare function createStreamingDirectiveAccumulator(): StreamingDirectiveAccumulator;
//#endregion
//#region src/agents/harness/projection-tool-output.d.ts
declare const TOOL_PROGRESS_OUTPUT_MAX_CHARS = 8000;
declare function formatToolProgressOutput(output: string, options?: {
  maxChars?: number;
}): string | undefined;
//#endregion
//#region src/session-cards/progress-card-channel-summary.d.ts
/** Projects checklist counts or readable notes through the shared Markdown owner. */
declare function projectProgressCardChannelUpdate(input: unknown): {
  steps: {
    step: string;
    status: "completed" | "in_progress" | "pending";
  }[];
  explanation?: string | undefined;
  explanationFormat?: "plain" | undefined;
} | undefined;
//#endregion
//#region src/agents/embedded-agent-message-tool-source-reply.d.ts
/** Resolves whether a delivered source send ends the turn; an omitted `final` takes the run's default. */
declare function resolveMessageToolSourceReplyFinal(args: unknown, finalByDefault?: boolean): boolean;
declare function isDeliveredMessagingToolResult(params: {
  toolName?: string;
  args?: unknown;
  result?: unknown;
  hookResult?: unknown;
  isError?: boolean;
  requirePluginDeliveryId?: boolean;
}): boolean;
declare function isDeliveredMessageToolOnlySourceReplyResult(params: {
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  toolName: string;
  args?: unknown;
  result?: unknown;
  hookResult?: unknown;
  isError?: boolean;
  allowExplicitSourceRoute?: boolean;
  deliveryConfirmed?: boolean;
}): boolean;
//#endregion
//#region src/agents/harness/errors.d.ts
/** A harness lost ownership of the session generation before the attempt could start. */
declare class AgentHarnessSessionSupersededError extends Error {
  constructor(message: string, options?: ErrorOptions);
}
/** Required native cleanup failed; the host must preserve the current session generation. */
declare class AgentHarnessSessionCleanupError extends Error {
  constructor(message: string, options?: ErrorOptions);
}
/** A model-independent harness preflight failed before an attempt could start. */
declare class AgentHarnessPreflightError extends Error {
  /** Stable machine-readable reason when the owner provides one. */
  readonly code?: string;
  /** Opts fallback into skipping only candidates owned by the selected harness. */
  readonly scope?: "harness";
  /** Owner-authored public explanation; message and cause remain diagnostic. */
  readonly userMessage?: string;
  constructor(message: string, options?: ErrorOptions & {
    scope?: "harness";
    userMessage?: string;
  });
}
//#endregion
//#region src/agents/harness/settled-turn-finalization-result.d.ts
/**
 * Projects a harness-owned full attempt engine into the narrow finalization
 * contract, rejecting canonical failure or capability evidence first.
 */
declare function projectSettledTurnFinalizationAttemptResult(result: AgentHarnessAttemptResult): AgentHarnessSettledTurnFinalizationResult;
//#endregion
//#region src/agents/harness/transcript-visibility.d.ts
/**
 * Keep internal messages in the audit/model transcript without
 * projecting them into user-facing chat history.
 */
declare function projectAgentHarnessTranscriptMessageForDisplay<T extends AgentMessage>(params: {
  hidden: boolean;
  inputProvenance?: InputProvenance;
  runId?: string;
  message: T;
}): T;
//#endregion
//#region src/sessions/user-turn-transcript.metadata.d.ts
/**
 * Runtime hooks may rewrite roles and redact display/transport fields. Restore only
 * operational facts here; canonical admission preparation deliberately protects more.
 */
declare function restorePreparedUserTurnOperationalMetaForRuntime<TMessage extends AgentMessage>(params: {
  runtimeMessage: TMessage;
  preparedMessage?: PersistedUserTurnMessage;
}): TMessage;
//#endregion
//#region src/agents/execution-auth-binding.d.ts
/** Ephemeral proof of the credential or opaque runtime that completed one agent run. */
type AgentExecutionAuthBinding = {
  authProfileId?: string;
  /** Exact embedded harness that completed the successful turn, including openclaw. */
  agentHarnessId?: string;
  /** Exact model selected by the successful embedded run. */
  modelId?: string;
  /** Exact transport used to select that run's credential. */
  modelApi?: string;
  /** Non-reversible identity hash; credential material never leaves the runner. */
  authFingerprint?: string;
  /** Runtime-owned principal/session shape used when credentials are intentionally opaque. */
  runtimeOwnerFingerprint?: string;
  /** Exact opaque owner, or plugin harness carrying a credential-backed turn. */
  runtimeOwnerKind?: OpaqueRuntimeOwnerKind;
  /** Exact backend/harness id that owned the successful turn. */
  runtimeOwnerId?: string;
  /** Exact CLI or plugin-harness implementation used by the successful turn. */
  runtimeArtifactFingerprint?: string;
  runtimeArtifactId?: string;
  /** The prepared CLI bridge used only the selected profile, not ambient CLI auth. */
  skipLocalCredential?: true;
};
type OpaqueRuntimeOwnerKind = "cli-runtime" | "plugin-harness" | "aws-sdk";
/** Fingerprint a profile after materializing its selected SecretRef value. */
declare function fingerprintResolvedAuthProfileCredential(params: {
  profileId: string;
  credential: AuthProfileCredential;
  resolvedAuth: ResolvedProviderAuth | null | undefined;
}): string | undefined;
//#endregion
//#region src/process/command-queue.types.d.ts
type CommandQueueTaskDeadline = {
  kind: "bounded";
  deadlineAtMs: number;
} | {
  kind: "unlimited";
};
type CommandQueueEnqueueOptions = {
  sessionTarget?: Readonly<{
    agentId?: string;
    sessionKey?: string;
    sessionId: string;
  }>;
  /** Enqueue-time provenance for diagnostics only; never used for admission. */
  taskIdentity?: Readonly<{
    taskKind: string;
    sessionKey?: string;
    runId?: string;
    requesterSessionKey?: string;
    /** The outer model chain owns this candidate's FailoverError diagnostics. */
    modelFallbackCandidate?: boolean;
  }>;
  /** Owner-resolved capacity, installed atomically with this enqueue. */
  maxConcurrent?: number;
  /** Cancels queued admission; the task owns cancellation after it starts. */
  abortSignal?: AbortSignal;
  /** Called only when this entry remains queued after immediate lane admission. */
  onQueued?: () => void;
  warnAfterMs?: number;
  onWait?: (waitMs: number, queuedAhead: number) => void;
  taskTimeoutMs?: number;
  taskTimeoutProgressAtMs?: () => number | undefined;
  /** Replaces idle timing with an owner deadline; undefined restores idle timing. */
  taskTimeoutSubscribe?: (onDeadline: (deadline: CommandQueueTaskDeadline | undefined) => void) => () => void;
  taskTimeoutAbortSignal?: AbortSignal;
  taskTimeoutAbortGraceMs?: number;
  /** Ends the task after a caller-owned timeout cleanup grace has already elapsed. */
  taskTimeoutReleaseSignal?: AbortSignal;
  priority?: "foreground" | "normal" | "background";
};
type CommandQueueEnqueueFn = <T>(task: () => Promise<T>, opts?: CommandQueueEnqueueOptions) => Promise<T>;
//#endregion
//#region src/agents/agent-tools.memory-flush.types.d.ts
/** Provider-owned persistence surface for one tools-arm memory flush run. */
type MemoryFlushToolRunContext = {
  flushId: string;
  ownerPluginId: string;
  persistenceToolNames: readonly string[];
  lookupToolNames?: readonly string[];
  recordPersistenceToolSuccess: () => void;
};
//#endregion
//#region src/agents/assistant-error-transcript.d.ts
/** Defers failed-attempt display without changing the append-only transcript. */
declare function createAssistantErrorTranscript(): {
  clear: () => void;
  bindStream(source: AgentMessage, replaceStream: (visible: boolean) => void): void;
  snapshot(): {
    source: AgentMessage;
    replaceStream?: (visible: boolean) => void;
  } | undefined;
  restore(snapshot: {
    source: AgentMessage;
    replaceStream?: (visible: boolean) => void;
  } | undefined): void;
  record(source: AgentMessage): void;
  settle(failed: boolean): void;
};
type AssistantErrorTranscript = ReturnType<typeof createAssistantErrorTranscript>;
//#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<string | number> | 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: `allow-once` with low/medium risk permits one execution;
 * `ask` requests human approval. Plugin consumers must handle `deny` explicitly:
 * do not run, return the rationale and rejection guidance to the agent, and never
 * escalate that denial to human approval. The configured exec reviewer maps
 * provider failures, timeouts, and invalid responses to `ask`; detected
 * reviewer-directed prompt injection maps to `deny` with high risk.
 */
type ExecAutoReviewDecision = {
  decision: "allow-once";
  rationale: string;
  risk: "low" | "medium";
  userAuthorization?: ExecAutoReviewRisk;
} | {
  decision: "deny";
  rationale: string;
  risk: ExecAutoReviewRisk;
  userAuthorization?: ExecAutoReviewRisk;
} | {
  decision: "ask";
  rationale: string;
  risk: ExecAutoReviewRisk;
  userAuthorization?: ExecAutoReviewRisk;
};
/** Execution host whose command policy context is being reviewed. */
type ExecAutoReviewHost = "gateway" | "node" | "codex-app-server";
type ExecAutoReviewTranscriptEntry = {
  kind: "user" | "assistant" | "tool_call" | "tool_result";
  text: string;
  toolName?: string;
  toolCallId?: string;
  origin?: "operator" | "channel" | "inter_session" | "internal_system" | "unknown";
  truncated?: boolean;
};
type ExecAutoReviewTranscript = {
  entries: readonly ExecAutoReviewTranscriptEntry[];
  omittedEntries: number;
  truncated: boolean;
};
/** Command and policy facts supplied to an exec auto-reviewer. */
type ExecAutoReviewInput = {
  transcript?: ExecAutoReviewTranscript;
  command: string;
  /** Exact prepared shell command when execution is on another host. */
  executionCommand?: string;
  argv?: readonly string[];
  resolvedPath?: string | null;
  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> | ExecAutoReviewDecision;
//#endregion
//#region src/secrets/store/secret-store.d.ts
type SecretStoreEgressBinding = {
  name: string;
  sentinel: string;
  allowedHosts: string[];
};
type SecretStoreExecEnvironment = {
  env?: Record<string, string>;
  secretSentinels?: Record<string, string>;
  secretEgressBindings?: SecretStoreEgressBinding[];
};
//#endregion
//#region src/agents/sandbox/workspace-mounts.d.ts
/** Managed skill directory projected read-only into the sandbox workspace. */
type ReadOnlyWorkspaceSkillMount = {
  hostPath: string;
  containerPath: string;
};
//#endregion
//#region src/agents/bash-tools.shared.d.ts
type BashSandboxConfig = {
  containerName: string;
  workspaceDir: string;
  containerWorkdir: string;
  workdirValidation?: SandboxBackendHandle["workdirValidation"];
  validateWorkdir?: SandboxBackendHandle["validateWorkdir"];
  discardPreparedWorkdir?: SandboxBackendHandle["discardPreparedWorkdir"];
  workdirRoots?: readonly string[];
  /** Approved read-only skill mounts that may be selected as an exec workdir. */
  readOnlyWorkspaceSkillMounts?: readonly ReadOnlyWorkspaceSkillMount[];
  env?: Record<string, string>;
  prepareProcessCleanup?: SandboxBackendHandle["prepareProcessCleanup"];
  buildExecSpec?: SandboxBackendHandle["buildExecSpec"];
  finalizeExec?: SandboxBackendHandle["finalizeExec"];
};
//#endregion
//#region src/agents/exec-approval-transport.d.ts
/** Registration result returned before an approval decision is available. */
type ExecApprovalRegistration = {
  id: string;
  expiresAtMs: number;
  finalDecision?: string | null;
};
type ExecApprovalExecution = {
  command: string;
  execCommand: string;
  cwd: string;
  env: Record<string, string>;
  pty: boolean;
};
/** One exec call's remote review and approval lifetime; never shared between commands. */
type ExecApprovalTransport = {
  bindExecution(input: ExecApprovalExecution): void;
  assertExecution(input: ExecApprovalExecution): void;
  review(input: ExecAutoReviewInput): Promise<ExecAutoReviewDecision>;
  request(input: {
    id: string;
    warningText?: string;
  }): Promise<ExecApprovalRegistration>;
  waitDecision(input: {
    id: string;
  }): Promise<{
    decision: string | null;
    terminalReason?: string;
  }>;
};
//#endregion
//#region src/agents/exec-auto-reviewer.d.ts
type ExecReviewerConfig = NonNullable<NonNullable<ToolsConfig["exec"]>["reviewer"]>;
//#endregion
//#region src/agents/github-tool-identity.types.d.ts
type PreparedGitHubToolEnvironment = Readonly<{
  credentialScrubEnv: Readonly<Record<string, string>>;
  localIdentityEnv: Readonly<Record<string, string>>;
  /** Append after selecting local Git parameters; never replace unrelated settings. */
  localGitConfigParameters?: string;
  excludedStoreNames: readonly string[];
  /** A local process must retain the host-selected profile and author identity. */
  managedLocalIdentity: boolean;
  /** Selected credentials require the host-owned exec lifecycle, not a runtime shell overlay. */
  hostExecutionRequired?: true;
}>;
//#endregion
//#region src/agents/bash-tools.exec-types.d.ts
type ExecToolDefaults = ExecToolRoutingDefaults & {
  hasCronTool?: boolean;
  mode?: ExecMode;
  bypassHostApprovalFloors?: boolean;
  trigger?: string;
  pathPrepend?: string[];
  safeBins?: string[];
  strictInlineEval?: boolean;
  commandHighlighting?: boolean;
  safeBinTrustedDirs?: string[];
  safeBinProfiles?: Record<string, SafeBinProfileFixture>;
  reviewer?: ExecReviewerConfig;
  config?: OpenClawConfig;
  /** Host-prepared non-secret environment and store projection exclusions. */
  preparedRunEnvironment?: PreparedGitHubToolEnvironment;
  /** An explicit snapshot, including an empty one, replaces local store access. */
  preparedStoreEnvironment?: Readonly<SecretStoreExecEnvironment>;
  /** Host-prepared routing hint; remote workers have no Gateway session database. */
  preparedSubagentExecution?: boolean;
  autoReviewer?: ExecAutoReviewer;
  createApprovalTransport?: (toolCallId: string, signal?: AbortSignal) => ExecApprovalTransport;
  /** Reads current attempt context only when a command needs review. */
  reviewTranscript?: () => ExecAutoReviewTranscript | undefined;
  agentId?: string;
  /** Credential owner when execution borrows another agent's tool policy. */
  executionAgentId?: string;
  backgroundMs?: number;
  cleanupMs?: number;
  timeoutSec?: number;
  approvalWarningText?: string;
  approvalFollowupText?: string;
  approvalFollowup?: ExecApprovalFollowupFactory;
  approvalFollowupMode?: "agent" | "direct";
  approvalRunningNoticeMs?: number;
  sandbox?: BashSandboxConfig;
  /** Immutable session policy that forbids execution outside its provisioned sandbox. */
  sandboxRequired?: boolean;
  elevated?: ExecElevatedDefaults;
  allowBackground?: boolean;
  /** Final run-local availability of the process continuation tool. */
  processToolAvailabilityRef?: {
    value?: boolean;
  };
  scopeKey?: string;
  sessionKey?: string;
  /** Executing session when tool policy is borrowed from a different session. */
  runSessionKey?: string;
  /** Stable agent run that owns any approval created by this tool. */
  runId?: string;
  /** Exact admitted execution instance that owns secret-egress proxy access. */
  operationalRunInstance?: OperationalRunInstanceRef;
  /** Durable session that receives detached exec completion events and approval followups. */
  notifySessionKey?: string;
  /** Ephemeral session UUID active when this exec tool was built. Regenerated
   *  on `/new` and `/reset`, so it pins exec-approval followups to the original
   *  session instance and lets stale followups drop after a session rebind. */
  sessionId?: string;
  /** `session.store` template from the runtime config. Lets the direct/denied
   *  exec approval followup path resolve the session key's current sessionId and
   *  drop the followup when the key was rebound by `/new` or `/reset`. */
  sessionStore?: string;
  /** @deprecated SDK declaration compatibility; coding-tool routing comes from config. */
  mainKey?: string;
  /** @deprecated SDK declaration compatibility; coding-tool routing comes from config. */
  sessionScope?: "per-sender" | "global";
  /** Start-time routing policy for detached exec system events. */
  eventRouting?: EventSessionRoutingPolicy;
  messageProvider?: string;
  currentChannelId?: string;
  /** Actual conversation reply destination, including an auto-created thread. */
  currentMessagingTarget?: string;
  currentThreadTs?: string;
  /** Channel-owned sender/chat metadata. Exec subprocesses receive only sender/chat IDs. */
  channelContext?: PluginHookChannelContext;
  accountId?: string;
  approvalReviewerDeviceId?: string;
  /** Deny approval-requiring commands without creating operator approval events. */
  nonInteractiveApproval?: boolean;
  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;
  exitReason?: TerminationReason;
  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<string | undefined>;
/** 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/bash-tools.exec-approval-output.d.ts
type ExecApprovalContinuationPromptRange = {
  start: number;
  end: number;
};
//#endregion
//#region src/agents/requester-tool-policy.d.ts
type RequesterToolPolicySource = "current-request" | "persisted-child" | "completion-handoff";
type RequesterToolPolicyResolution = {
  delegated: boolean;
  /** Diagnostic fact identifying whether policy came from live ingress or delegated state. */
  requesterPolicySource: RequesterToolPolicySource;
  groupPolicy?: SandboxToolPolicy;
  senderPolicy?: SandboxToolPolicy;
  subagentPolicy?: SandboxToolPolicy;
  inheritedToolPolicy?: SandboxToolPolicy;
  /** The requester's own ceiling, excluding a completion's replayed authority. */
  sessionInheritedToolPolicy?: SandboxToolPolicy;
  /** Full ancestor ceiling retained by descendants and completion, even when execution differs. */
  inheritedToolPolicyForSpawn?: SandboxToolPolicy;
  delegatedToolPolicy?: DelegatedToolPolicy;
  inheritedToolPolicySource?: "sender";
};
type SenderPolicyMode = "always" | "when-sender-id" | "never";
type RequesterToolPolicyParams = {
  requesterOrigin?: RequesterOrigin;
  conversationId?: string | null;
  chatType?: string;
  config?: OpenClawConfig;
  agentId?: string;
  sessionKey?: string;
  subagentSessionKey?: string;
  preparedSessionEntry?: PreparedSessionCapabilityEntry;
  preparedSessionCapabilityStore?: SessionCapabilityStore;
  spawnedBy?: string | null;
  messageProvider?: string | null;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  accountId?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
  inputProvenance?: InputProvenance;
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  sessionId?: string;
  modelProvider?: string;
  modelId?: string;
  senderPolicyMode?: SenderPolicyMode;
  /** Group session selected by a trusted scheduled authority envelope. */
  groupPolicySessionKey?: string;
  /** Fail closed when scheduled authority names a removed non-default account. */
  requireConfiguredGroupAccount?: boolean;
  /** Policy prepared by the trusted channel ingress owner for this conversation. */
  conversationPolicy?: SandboxToolPolicy;
};
/** Resolve current requester permissions alongside any persisted child execution envelope. */
declare function resolveRequesterToolPolicies(params: RequesterToolPolicyParams): RequesterToolPolicyResolution;
//#endregion
//#region src/agents/delegation-capability.d.ts
type DelegationCapability = "full" | "host_only" | "report_only";
//#endregion
//#region src/agents/tool-fs-policy.types.d.ts
type PreparedSessionPermissionPolicy = Readonly<{
  root: string;
  mode: SessionPermissionMode;
}>;
type ToolFsPolicy = {
  workspaceOnly: boolean;
  root?: string;
  /** Host-owned roots that read-only tools may consume outside the workspace. */
  readOnlyRoots?: string[];
};
//#endregion
//#region src/plugins/runtime/gateway-request-scope.types.d.ts
type PluginRuntimeGatewayRequestScope = {
  /** Exact registration and Gateway owner retained across awaited system operations. */
  assertSystemOwnerCurrent?: () => void;
  /** Recheck the admitted HTTP device or cookie grant before effects/disclosure; rejection sends HTTP 401 and throws. */
  revalidate?: () => Promise<void>;
  /** Contextual ingress owns asynchronous stream work through its actual settlement. */
  trackWork?: <T>(work: Promise<T>) => Promise<T>;
  /** Exact placement owner captured before the local harness begins. */
  assertNodeExecutionCurrent?: (request: {
    runId: string;
    agentId: string;
    nodeId: string;
    workspace: OpenClawPluginNodeWorkspace;
  }) => void;
  /** In-process admitted owner only; never projected into RPC parameters. */
  invokeWithSessionNodeAuthority?: <T>(request: {
    pluginId: string;
    command: string;
    source: "session-full" | "human-approved";
    nodeId: string;
    workspace: OpenClawPluginNodeWorkspace;
  }, invoke: (assertCurrent: () => void, signal: AbortSignal) => Promise<T>) => Promise<T | undefined>;
  /** Closure-bound admitted owner used to validate placement grant bindings. */
  nodePlacementGrantAuthority?: {
    agentId: string;
    sessionKey: string;
    runId: string;
    assertCurrent: (request: {
      pluginId: string;
      command: string;
      nodeId: string;
      workspace: OpenClawPluginNodeWorkspace;
    }) => void;
  };
  context?: GatewayRequestContext;
  resolveGatewayContext?: GatewayContextResolver;
  client?: GatewayRequestOptions["client"];
  /** Original request-owned cancellation and live transport authority, never wire data. */
  signal?: GatewayRequestOptions["signal"];
  hasCurrentClientAuthority?: GatewayRequestOptions["hasCurrentClientAuthority"];
  isWebchatConnect: GatewayRequestOptions["isWebchatConnect"];
  pluginId?: string;
  pluginSource?: string;
  pluginOrigin?: PluginOrigin$1;
  pluginTrustedOfficialInstall?: boolean;
  gatewayMethodDispatchAllowed?: boolean;
  pluginRegistry?: PluginRegistry;
  declaredProviderOwners?: DeclaredProviderOwnerIndex;
};
//#endregion
//#region src/gateway/mcp-grant-store.d.ts
/** Set by MCP authentication; caller-token conversation headers cannot select a binding. */
type McpCurrentConversationOrigin = "run-bound-grant" | "server-session" | "caller-token";
//#endregion
//#region src/process/lanes.d.ts
type CommandLaneConfiguration = {
  readonly lane: string;
  readonly maxConcurrent: number;
};
//#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 = Pick<ReplyPayload$1, "text" | "mediaUrls" | "attachments" | "audioAsVoice" | "trustedLocalMedia" | "sensitiveMedia" | "isReasoning" | "isCommentary" | "replyToId" | "replyToTag" | "replyToCurrent" | "presentation" | "presentationTextMode" | "channelData">;
//#endregion
//#region src/agents/fast-mode.d.ts
type FastModeState = {
  mode: FastMode;
  /** Undefined preserves an inherited provider tier instead of manufacturing Standard. */
  requestMode: FastMode | undefined;
  enabled: boolean;
  source: FastModeSource;
  fastAutoOnSeconds: number;
};
declare function resolveFastModeState(params: {
  cfg: OpenClawConfig | undefined;
  provider: string;
  model: string;
  agentId?: string;
  sessionEntry?: Pick<SessionEntry, "fastMode"> | undefined;
}): FastModeState;
//#endregion
//#region src/context-engine/host-compat.d.ts
type ContextEngineHostSupport = {
  id: string;
  label: string;
  capabilities: readonly ContextEngineHostCapability[];
};
declare const CODEX_APP_SERVER_CONTEXT_ENGINE_HOST: {
  readonly id: "codex-app-server";
  readonly label: "Codex app-server harness";
  readonly capabilities: readonly ["bootstrap", "assemble-before-prompt", "after-turn", "maintain", "compact", "runtime-llm-complete", "thread-bootstrap-projection"];
};
/** Assert that a context engine can safely run under the supplied host. */
declare function assertContextEngineHostSupport(params: {
  contextEngine: ContextEngine;
  operation: ContextEngineOperation;
  host: ContextEngineHostSupport;
}): void;
//#endregion
//#region src/agents/harness/context-engine-logical-turn.d.ts
type EffectiveContextEngineRef = Readonly<{
  engine: ContextEngine;
  registeredId: string;
  ownerPluginId?: string;
  mode: "configured" | "legacy-degraded";
  reason?: string;
}>;
type ContextEngineLogicalTurnLease = {
  /** Compatibility getter for internal callers while the single context object is threaded. */
  readonly engine: ContextEngine;
  readonly effectiveEngine: ContextEngine;
  readonly effectiveEngineId: string;
  readonly effectiveEnginePluginId?: string;
  readonly degraded: boolean;
  readonly degradedReason?: string;
  readonly disposed: boolean;
  selectForHost: (params: {
    host: ContextEngineHostSupport;
    operation: ContextEngineOperation;
    requiresDurableCommit: boolean;
  }) => EffectiveContextEngineRef;
  degradeBeforeStart: (reason: string) => EffectiveContextEngineRef;
  begin: () => EffectiveContextEngineRef;
  /**
   * Hands a started turn to a reloaded plugin generation at a step boundary. It disposes
   * this generation's engines now, so the reload can drain them, and keeps the turn's
   * settlements for its end. `rebind()` then resolves the same engine id again.
   */
  handOver: () => Promise<void>;
  /** After `handOver()`, resolves the turn's engines from the current registry. */
  rebind: () => Promise<void>;
  onDispose: (key: string, settle: () => Promise<void>) => void;
  deferDisposalUntil: (promise: Promise<unknown>) => void;
  dispose: () => Promise<void>;
};
//#endregion
//#region src/agents/harness/context-engine-turn-attempt.d.ts
type ContextEngineTurnAttemptFacts = {
  boundary: TranscriptTurnBoundary;
  sessionIdUsed: string;
  sessionKey?: string;
  sessionTarget?: ContextEngineSessionTarget;
  promptError: boolean;
  aborted: boolean;
  yieldAborted: boolean;
  runtimeContext?: ContextEngineTurnRuntimeContext;
};
//#endregion
//#region src/agents/command/shared-types.d.ts
/** Best-effort provider stream parameter overrides for an agent command. */
type AgentStreamParams = {
  temperature?: number;
  topP?: number;
  maxTokens?: number;
  /** Stop sequences forwarded to the provider (best-effort). */
  stop?: string[];
  fastMode?: boolean;
  responseFormat?: Record<string, unknown>;
  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<string, unknown>;
    /** Strict argument enforcement (Responses API). Propagated from the request. */
    strict?: boolean;
  };
};
type AgentRunClientContext = Pick<QueuedAgentRunParams, "clientCaps" | "bootstrapUserProfileId" | "gatewayUiCommandTarget"> & {
  /** Host-admitted dashboard authoring without an originating inline renderer. */
  pinnedWidgetAuthoring?: boolean;
};
type AgentRunMessageContext = Pick<QueuedAgentRunParams, "agentAccountId" | "senderIsOwner" | "gitContributorProfileId" | "sourceReplyDeliveryMode" | "taskSuggestionDeliveryMode"> & {
  /** Opaque host-issued capability for current-turn channel message actions. */
  messageActionTurnCapability?: string;
  /** Current channel ID for auto-threading (Slack). */
  currentChannelId?: string;
  /** Current thread timestamp for auto-threading (Slack). */
  currentThreadTs?: string;
  /** Authentication-derived provenance for MCP conversation fields. */
  currentConversationOrigin?: McpCurrentConversationOrigin;
  /** Current inbound message id for action fallbacks (e.g. Telegram react). */
  currentMessageId?: string | number;
  currentInboundAudio?: boolean;
  /** Reply-to mode for Slack auto-threading. */
  replyToMode?: ReplyToMode;
  /** Require explicit message tool targets (no implicit last-route sends). */
  requireExplicitMessageTarget?: boolean;
  /**
   * Whether a delivered source send that omits `final` ends the turn. Absent means yes:
   * a send answers the inbound message. Runs that only deliver to a configured target
   * set false, so post-send work still runs.
   */
  messageToolFinalByDefault?: boolean;
};
type AgentRunChannelContext = Pick<QueuedAgentRunParams, "messageProvider" | "chatType" | "channelContext" | "approvalReviewerDeviceId"> & {
  requesterOrigin?: RequesterOrigin;
  operatorProfileId?: string;
  /** Original authenticated conversation, independent of destination routing. */
  conversationId?: string | null;
  /** Canonical transport channel when it differs from the tool-policy provider. */
  messageChannel?: string;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
  /** 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;
};
type AgentRunModelOptions = Pick<QueuedAgentRunParams, "authProfileId" | "thinkLevel" | "thinkingExplicit" | "fastMode" | "fastModeAutoOnSeconds" | "cyberAccessProgram"> & {
  /** Vision capability resolved by the run owner from its prepared model catalog. */
  modelHasVision?: boolean;
  /** Session-selected context-window option id carried by the run owner. */
  contextWindow?: string;
  model?: string;
  /** Outer model-fallback owner facts for this admitted attempt. */
  modelRoutingProvenance?: ModelFallbackAttemptProvenance;
  /** Stable outer-run start time for auto fast-mode cutoff across retries/fallbacks. */
  fastModeStartedAtMs?: number;
  /** Shared notification state for nested harnesses that can observe the same tool boundary. */
  fastModeAutoProgressState?: FastModeAutoProgressState;
  isFinalFallbackAttempt?: boolean;
};
type AgentRunInputContext = Pick<QueuedAgentRunParams, "workspaceDir" | "cwd" | "toolOverrides" | "skillsSnapshot" | "ownerNumbers" | "inputProvenance" | "extraSystemPrompt" | "extraSystemPromptTurnContext"> & {
  /** Canonical agent workspace used for bootstrap files when execution runs elsewhere. */
  bootstrapWorkspaceDir?: string;
  agentDir?: string;
  /**
   * Run config consumed by core paths (model selection, tools, plugin
   * activation). Plugin harnesses resolve `plugins.entries.<id>.config` from
   * the live global config, NOT from this object — per-run plugin-config
   * overrides are unsupported; use an explicit run param instead.
   */
  config?: OpenClawConfig;
  prompt: string;
  /** User-visible prompt body to submit and persist; runtime context travels separately. */
  transcriptPrompt?: string;
  currentInboundEventKind?: InboundEventKind;
  images?: ImageContent$1[];
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered facts represented by attachment text in the current prompt. */
  media?: MediaFact[];
  /** Seen bootstrap truncation warning signatures for this session (once mode dedupe). */
  bootstrapPromptWarningSignaturesSeen?: string[];
  bootstrapPromptWarningSignature?: string;
  bootstrapContextRunKind?: BootstrapContextRunKind;
};
type AgentRunTranscriptContext = Pick<QueuedAgentRunParams, "sessionId" | "sessionKey" | "suppressNextUserMessagePersistence"> & {
  /** Host-admitted private completion; retain its transcript without user-facing projection. */
  privateCompletion?: true;
  /** Caller-owned in-memory transcript for ephemeral helper runs. */
  sessionManager?: SessionManager;
  prepareAssistantTranscriptMessage?: PrepareAssistantTranscriptMessage;
  userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
  /** Context engine resolved once by the outer logical-turn owner. */
  contextEngineLogicalTurnLease?: ContextEngineLogicalTurnLease;
  /** Emits immutable attempt facts for selection by the outer logical-turn owner. */
  onContextEngineTurnCandidate?: (facts: ContextEngineTurnAttemptFacts) => void;
  onUserMessagePersisted?: (message: Extract<AgentMessage, {
    role: "user";
  }>) => void;
};
type AgentRunLifecycle = Pick<QueuedAgentRunParams, "providerReviewAcknowledgment" | "timeoutMs" | "runTimeoutOverrideMs" | "scheduledToolPolicy"> & {
  /** Already-admitted internal execution; mutually exclusive with preparedRunAdmission. */
  admittedRunContext?: AdmittedRunContext;
  /** Host-only post-prepare continuation, removed before plugin invocation. */
  preparedRunAdmission?: PreparedAgentRunAdmission;
  agentId?: string;
  runId: string;
  /** Exact attempt authority attached to the active steering backend. */
  toolAuthorityFingerprint?: string;
  /** Immutable gateway lifecycle ownership captured when this execution was admitted. */
  lifecycleGeneration?: string;
  lane?: string;
  swarmExecutionLane?: CommandLaneConfiguration;
  /** Stable cron job identifier populated for cron-triggered runs. */
  jobId?: string;
  /** Disable built-in tools for this run (LLM-only mode). */
  disableTools?: boolean;
  abortSignal?: AbortSignal;
  onPartialReply?: (payload: PartialReplyPayload) => boolean | void | Promise<boolean | void>;
  onBlockReply?: (payload: BlockReplyPayload, context?: BlockReplyContext) => void | Promise<void>;
  replyOperation?: ReplyOperation;
  /**
   * Dispose bundled MCP runtimes when the overall run ends instead of preserving
   * the session-scoped cache. Intended for one-shot local CLI runs that must
   * exit promptly after emitting the final JSON result.
   */
  cleanupBundleMcpOnRunEnd?: boolean;
  /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */
  oneShotCliRun?: boolean;
};
type AgentRunExecutionContext = AgentRunClientContext & AgentRunMessageContext & AgentRunChannelContext & AgentRunModelOptions & AgentRunInputContext & AgentRunTranscriptContext & AgentRunLifecycle;
//#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;
};
type BlockChunkMetadata = {
  sourceText: string;
  sourceGeneration: number;
  reconciledSourceBreak?: true;
  sourceStart: number;
  sourceEnd: number;
  startsAtLineStart: boolean;
};
type BlockChunkDrain = {
  force: boolean;
  /** Only for cumulative previews that replace previously emitted text. */
  mutablePreview?: boolean;
  emit: (chunk: string, options?: BlockChunkMetadata) => void;
};
declare class EmbeddedBlockChunker {
  #private;
  constructor(chunking?: BlockReplyChunking);
  append(text: string): void;
  /** Start a new source scope without emitting pending text. */
  reset(sourceBreaks?: readonly number[], sourceOffset?: number): void;
  /** UTF-16 source positions exclude synthetic framing and include skipped whitespace. */
  get consumedLength(): number;
  /** Prepared source boundaries are not evidence that a recipient received a chunk. */
  get preparedSourceBreaks(): readonly number[];
  get sourceLength(): number;
  /** Replace pending source; the snapshot owner can attest that the consumed prefix is unchanged. */
  replace(text: string, sourceOffset?: number, prefixRetained?: boolean): boolean;
  get bufferedText(): string;
  hasBuffered(): boolean;
  drain(params: BlockChunkDrain): 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$1 = "explain" | "raw";
type EmbeddedAgentEvent = {
  stream: string;
  /** Internal callback facts; never included in publicly emitted event data. */
  transcriptStart?: PreparedReplyTranscriptStart | null;
  data: Record<string, unknown> & Omit<Partial<AgentCommandOutputEventFields>, "phase" | "status"> & {
    phase?: string;
    status?: string;
    args?: Record<string, unknown>;
    summary?: string;
    commandBearing?: boolean;
    isError?: boolean;
  };
  sessionKey?: string;
};
//#endregion
//#region src/agents/harness/runtime-artifact.types.d.ts
/** Harness-owned binding to a local implementation or configured remote service. */
type AgentHarnessRuntimeArtifactBinding = Readonly<{
  id: string;
  fingerprint: string;
}>;
/** Runtime artifact a verified continuation must keep using. */
type ExpectedAgentHarnessRuntimeArtifact = Readonly<{
  harnessId: string;
  artifact: AgentHarnessRuntimeArtifactBinding;
}>;
//#endregion
//#region src/agents/embedded-agent-runner/run/auth-profile-failure-policy.types.d.ts
/**
 * Scope used when classifying auth-profile failures for retry/fallback decisions.
 */
type AuthProfileFailurePolicy = "shared" | "local" | "local_transient";
//#endregion
//#region src/agents/embedded-agent-runner/run/params.d.ts
type RunEmbeddedAgentParams = Pick<QueuedAgentRunParams, "toolBindings" | "conversationRoutePeerId" | "conversationToolPolicy" | "memberRoleIds" | "permissionMode" | "sessionRoot" | "blindPrompt" | "modelSelectionLocked" | "authProfileIdSource" | "verboseLevel" | "reasoningLevel" | "trustedInternalHandoff" | "runtimePluginToolGrant" | "silentReplyPromptMode" | "enforceFinalTag" | "silentExpected" | "terminalReplyExpectation" | "suppressTranscriptOnlyAssistantPersistence" | "skillLibraryAuthoring"> & {
  /** Settles the session's initial workspace attribution before tools can act. */
  awaitSessionDiffBaseline?: () => Promise<void>;
  /** Host-minted parent audience inherited by a trusted internal child run. */
  memoryAudience?: MemoryAudience;
  /** Detached runs may read session identity but never write its durable transcript or metadata. */
  sessionPersistence?: "durable" | "detached";
  /** Storage-neutral transcript/session target. Defaults to sessionId/sessionKey/agentId. */
  sessionTarget?: AgentRunSessionTarget;
  /** 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;
  /** Explicit sandbox and tool-policy owner when the policy session key is unscoped. */
  sandboxAgentId?: string;
  /** The user, event, automation, or maintenance owner that initiated this run. */
  trigger?: EmbeddedRunTrigger;
  /** Store-private runtime authority forwarded only by the cron execution owner. */
  scheduledRuntimeAuthority?: CronRuntimeAuthority;
  /** A known runtime-specific authority envelope was explicitly cleared. */
  scheduledRuntimeAuthorityRecoveryRequired?: boolean;
  /** Relative workspace path that memory-triggered writes are allowed to append to. */
  memoryFlushWritePath?: string;
  /** Provider-owned persistence surface for a tools-arm memory flush. */
  memoryFlushTools?: MemoryFlushToolRunContext;
  /** Sticky source-turn taint inherited by an internal maintenance run. */
  initialTurnTainted?: boolean;
  /** Delivery target for topic/thread routing. */
  messageTo?: string;
  /** Thread/topic identifier for routing replies to the originating thread. */
  messageThreadId?: string | number;
  /** Whether workspaceDir points at the canonical agent workspace for bootstrap purposes. */
  isCanonicalWorkspace?: boolean;
  /** Transport-native chat/conversation ID for hook identity context. */
  chatId?: string;
  /** Routable target for the current conversation when it differs from the native channel ID. */
  currentMessagingTarget?: string;
  /** Mutable ref to track if a reply was sent (for "first" mode). */
  hasRepliedRef?: {
    value: boolean;
  };
  /** If true, omit the message tool from the tool list. */
  disableMessageTool?: boolean;
  swarmCollector?: boolean;
  swarmOutputSchema?: Record<string, unknown>;
  /** Invocation-owned Code Mode activation; limits still come from config. */
  codeModeOverride?: boolean | "auto";
  /** Internal one-shot model probe mode: no tools, no workspace/chat prompt policy. */
  modelRun?: boolean;
  /** Setup can reject unavailable endpoints without spending the session retry budget. */
  retryConnectionErrors?: boolean;
  /** Auxiliary callers can defer transient provider failures to their own scheduler. */
  retryTransientErrors?: boolean;
  /** Disable trajectory persistence for auxiliary runs with no durable session owner. */
  disableTrajectory?: boolean;
  /**
   * Background Workshop review of this conversation: edits of existing skills require a prior
   * view, and changes credit "review" with this originating session key as their provenance.
   */
  skillWorkshopReviewOf?: string;
  /** 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;
  /** Allow runtime plugins for this run to late-bind the gateway subagent. */
  allowGatewaySubagentBinding?: boolean;
  /** @deprecated Use sessionTarget plus sessionId/sessionKey/agentId for runtime identity. */
  sessionFile?: string;
  /** Require file tools to stay within the task workspace without changing exec policy. */
  requireWorkspaceOnly?: true;
  /** Context supplied by internal producers, separate from inbound prompt text. */
  runtimeContextFragments?: RuntimeContextFragment[];
  /** Finalizes caller-owned guidance after the submitted tool surface is known. */
  finalizePromptForResolvedTools?: ResolvedToolPromptFinalizer;
  currentInboundContext?: CurrentInboundPromptContext;
  explicitSkillSelections?: ExplicitSkillSelection[];
  /** Optional client-provided tools (OpenResponses hosted tools). */
  clientTools?: ClientToolDefinition[];
  provider?: string;
  /** Caller-owned upper bound for this run's effective context budget. */
  contextTokenBudget?: number;
  /** Route-bound thinking capability resolved from the selected prepared catalog row. */
  modelThinkingCapability?: PreparedModelThinkingCapability;
  /** Effective model fallback chain for this session attempt. Undefined uses config defaults. */
  modelFallbacksOverride?: string[];
  /** Prepared fallback availability fact shared by selection and failure reporting. */
  modelFallbackAvailability?: ModelFallbackAvailability;
  /** 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;
  /** Verified setup continuation: pin both the harness and its local implementation. */
  expectedAgentHarnessRuntimeArtifact?: ExpectedAgentHarnessRuntimeArtifact;
  /** Caller-owned credential lifetime; independent of interactive pin provenance. */
  authProfileBinding?: {
    profileId: string;
    authRequirement: ProviderModelRouteAuthRequirement;
    assertCurrent(): void;
    revalidate(): Promise<void>;
  };
  /** Disable fallback from the user-selected auth profile for a verification run. */
  allowAuthProfileFallback?: boolean;
  toolResultFormat?: ToolResultFormat;
  toolProgressDetail?: ToolProgressDetailMode$1;
  /** Bootstrap context mode for workspace file injection. */
  bootstrapContextMode?: "full" | "lightweight";
  /** Optional tool allow-list; when set, only these tools are sent to the model. */
  toolsAllow?: string[];
  /** Preserve the visible tool schemas while allowing execution only for these names. */
  toolExecutionAllow?: readonly string[];
  /** Host-stamped exact-run capability for late Codex creator-authority capture. */
  cronCreatorAuthorityCapability?: CronCreatorAuthorityCapability;
  /** Ephemeral reason fresh local-operator cron authority cannot survive this queued turn. */
  cronCreatorAuthorityUnavailableReason?: "queued-local-operator";
  /** Canonical persisted exec policy for this session. */
  execSession?: ExecSessionDefaults;
  /** Session-owned presentation facts; never current-turn delivery or tool authority. */
  sessionPromptDelivery?: SessionDeliveryState;
  execOverrides?: Pick<ExecToolDefaults, "host" | "mode" | "security" | "ask" | "node" | "nodeCwd" | "notifyOnExit" | "notifyOnExitEmptySuccess">;
  bashElevated?: ExecElevatedDefaults;
  /** Trusted approved-exec runtime prompt span awaiting the resolved attempt cap. */
  execApprovalContinuationPromptRange?: ExecApprovalContinuationPromptRange;
  /** Corresponding span in the undecorated transcript prompt. */
  execApprovalContinuationTranscriptPromptRange?: ExecApprovalContinuationPromptRange;
  /** Trusted runtime-only authorization for one bounded cross-conversation recall pass. */
  conversationRecall?: ConversationRecallContext;
  onExecutionStarted?: (info?: {
    lifecycleGeneration?: string;
    backend?: string;
  }) => unknown;
  onExecutionPhase?: (info: EmbeddedAgentExecutionPhaseInfo) => void;
  onLaneWait?: (info: {
    waitMs: number;
    queuedAhead: number;
    waiting?: boolean;
  }) => void;
  onRunProgress?: (info: {
    reason: string;
    provider?: string;
    model?: string;
    backend?: string;
  }) => void;
  onSessionIdChanged?: (sessionId: string) => void;
  shouldEmitToolResult?: () => boolean;
  shouldEmitToolOutput?: () => boolean;
  onAssistantMessageStart?: () => void | Promise<void>;
  onBlockReplyFlush?: (context: BlockReplyFlushContext) => void | Promise<void>;
  /** Source-owned final receipt/custody for this input, never mere callback or preview acceptance. */
  resolveReplyDelivery?: ReplyDeliveryObserver;
  blockReplyBreak?: "text_end" | "message_end";
  blockReplyChunking?: BlockReplyChunking;
  onReasoningStream?: (payload: ReasoningStreamPayload) => void | Promise<void>;
  streamReasoningInNonStreamModes?: boolean;
  onReasoningEnd?: () => void | Promise<void>;
  onToolResult?: (payload: ReplyPayload$1) => void | Promise<void>;
  /** Synchronous private observer for the sanitized per-tool result. */
  onAgentToolResult?: (event: {
    toolName: string;
    result: unknown;
    isError: boolean;
  }) => void;
  /** Reports a committed generic recovery compaction before its retry starts. */
  onAutoCompactionSucceeded?: (count: number) => void;
  onAgentEvent?: (evt: EmbeddedAgentEvent) => void | Promise<void>;
  onToolStreamBoundary?: () => void | Promise<void>;
  /**
   * Emit lifecycle "finishing" when the attempt ends; the caller owns the
   * final lifecycle "end" or "error" after fallback and post-turn work settle.
   */
  deferTerminalLifecycle?: boolean;
  /** @deprecated Use deferTerminalLifecycle. */
  deferTerminalLifecycleEnd?: boolean;
  enqueue?: CommandQueueEnqueueFn;
  gitCoauthorPrompt?: string;
  internalEvents?: AgentInternalEvent[];
  streamParams?: AgentStreamParams;
  /** Skip per-chunk live visible-text parsing when no live stream consumer exists (e.g. subagents). */
  suppressLiveStreamOutput?: boolean;
  /**
   * Legacy default for callers without terminalReplyExpectation.
   * An explicit required reply cannot be waived by this flag or model output.
   */
  allowEmptyAssistantReplyAsSilent?: boolean;
  authProfileFailurePolicy?: AuthProfileFailurePolicy;
  /**
   * Use the provider's subscription CLI for one-shot helpers within plan limits.
   * Direct Anthropic OAuth passthrough uses metered extra usage and fails without balance.
   * `toolsAllow` bounds both backend-visible tools and server-side loopback MCP grants;
   * native and non-allowlisted tools, including a disabled message tool, stay unavailable.
   * Unset retains direct-API passthrough.
   */
  cliBackendDispatch?: "subscription-auth";
  /**
   * Probe one transiently cooled profile when sibling models may still be available.
   */
  allowTransientCooldownProbe?: boolean;
  assistantErrorTranscript?: AssistantErrorTranscript;
  /** Keep an internal continuation prompt from being replaced by the original prepared turn. */
  skipPreparedUserTurnMessage?: boolean;
  onUserMessagePersistenceInvalidated?: () => void;
} & AgentRunExecutionContext;
type EmbeddedForegroundPromptContext = Pick<RunEmbeddedAgentParams, "agentDir" | "sandboxAgentId" | "promptCacheKey" | "reasoningLevel" | "clientCaps" | "gatewayUiCommandTarget" | "toolBindings" | "trigger" | "messageTo" | "messageThreadId" | "conversationToolPolicy" | "memberRoleIds" | "isCanonicalWorkspace" | "chatId" | "currentMessagingTarget" | "disableMessageTool" | "conversationRecall" | "toolOverrides" | "permissionMode" | "execOverrides" | "skillsSnapshot" | "currentInboundEventKind" | "clientTools" | "disableTools" | "contextWindow" | "promptMode" | "forceMessageTool" | "allowGatewaySubagentBinding" | "extraSystemPrompt" | "extraSystemPromptTurnContext" | "sessionPromptDelivery" | "gitCoauthorPrompt" | "silentReplyPromptMode" | "ownerNumbers" | "toolsAllow" | "runtimePluginToolGrant" | "inputProvenance" | "scheduledToolPolicy" | "modelThinkingCapability" | "modelFallbacksOverride"> & AgentRunMessageContext & AgentRunChannelContext & {
  /** SDK observation of the completed attempt; new runs recheck publication availability. */
  githubPublicationAvailable?: boolean;
  agentId: string;
  workspaceDir: string;
  cwd?: string;
  sandboxSessionKey: string;
  cronCreatorCallerOrigin?: CronScheduledToolCallerOrigin;
};
//#endregion
//#region packages/gateway-protocol/src/schema/worker-turn-admission.d.ts
declare const WorkerTurnAdmissionParamsSchema: Type$1.TObject<{
  runEpoch: Type$1.TInteger;
  systemPrompt: Type$1.TString;
  prompt: Type$1.TString;
  messages: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
    role: Type$1.TLiteral<"user">;
    content: Type$1.TUnion<[Type$1.TString, Type$1.TArray<Type$1.TObject<{
      type: Type$1.TLiteral<"text">;
      text: Type$1.TString;
      textSignature: Type$1.TOptional<Type$1.TString>;
    }>>]>;
    timestamp: Type$1.TInteger;
    runtimeContext: Type$1.TObject<{
      retained: Type$1.TOptional<Type$1.TBoolean>;
    }>;
  }>, Type$1.TObject<{
    role: Type$1.TLiteral<"user">;
    content: Type$1.TUnion<[Type$1.TString, Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"text">;
      text: Type$1.TString;
      textSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"image">;
      data: Type$1.TString;
      mimeType: Type$1.TString;
    }>]>>]>;
    timestamp: Type$1.TInteger;
    operatorMessage: Type$1.TOptional<Type$1.TObject<{
      turnScoped: Type$1.TBoolean;
    }>>;
  }>, Type$1.TObject<{
    role: Type$1.TLiteral<"assistant">;
    content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"text">;
      text: Type$1.TString;
      textSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"thinking">;
      thinking: Type$1.TString;
      thinkingSignature: Type$1.TOptional<Type$1.TString>;
      redacted: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"toolCall">;
      id: Type$1.TString;
      name: Type$1.TString;
      arguments: Type$1.TRecord<"^.*$", Type$1.TUnknown>;
      thoughtSignature: Type$1.TOptional<Type$1.TString>;
      executionMode: Type$1.TOptional<Type$1.TEnum<["sequential", "parallel"]>>;
    }>]>>;
    api: Type$1.TString;
    provider: Type$1.TString;
    model: Type$1.TString;
    responseModel: Type$1.TOptional<Type$1.TString>;
    responseId: Type$1.TOptional<Type$1.TString>;
    providerReplay: Type$1.TOptional<Type$1.TObject<{
      v: Type$1.TLiteral<1>;
      type: Type$1.TString;
      id: Type$1.TOptional<Type$1.TString>;
      data: Type$1.TString;
      replayIndex: Type$1.TOptional<Type$1.TInteger>;
      provider: Type$1.TString;
      api: Type$1.TString;
      model: Type$1.TString;
      baseUrlHash: Type$1.TOptional<Type$1.TString>;
      sessionHash: Type$1.TOptional<Type$1.TString>;
      authProfileHash: Type$1.TOptional<Type$1.TString>;
    }>>;
    usage: Type$1.TObject<{
      input: Type$1.TNumber;
      output: Type$1.TNumber;
      cacheRead: Type$1.TNumber;
      cacheWrite: Type$1.TNumber;
      usageReport: Type$1.TOptional<Type$1.TObject<{
        state: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"unavailable">]>;
      }>>;
      contextUsage: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        state: Type$1.TLiteral<"available">;
        promptTokens: Type$1.TNumber;
        totalTokens: Type$1.TNumber;
      }>, Type$1.TObject<{
        state: Type$1.TLiteral<"unavailable">;
      }>]>>;
      totalTokens: Type$1.TNumber;
      cost: Type$1.TOptional<Type$1.TObject<{
        input: Type$1.TNumber;
        output: Type$1.TNumber;
        cacheRead: Type$1.TNumber;
        cacheWrite: Type$1.TNumber;
        total: Type$1.TNumber;
        totalOrigin: Type$1.TOptional<Type$1.TLiteral<"provider-billed">>;
      }>>;
    }>;
    timestamp: Type$1.TInteger;
    diagnostics: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      type: Type$1.TString;
      timestamp: Type$1.TInteger;
      error: Type$1.TOptional<Type$1.TObject<{
        name: Type$1.TOptional<Type$1.TString>;
        message: Type$1.TString;
        stack: Type$1.TOptional<Type$1.TString>;
        code: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber]>>;
      }>>;
      details: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnknown>>;
    }>>>;
    stopReason: Type$1.TEnum<["stop", "length", "toolUse", "error", "aborted"]>;
    errorMessage: Type$1.TOptional<Type$1.TString>;
    errorCode: Type$1.TOptional<Type$1.TString>;
    errorType: Type$1.TOptional<Type$1.TString>;
    errorBody: Type$1.TOptional<Type$1.TString>;
    retryAfterMs: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
  }>, Type$1.TObject<{
    role: Type$1.TLiteral<"toolResult">;
    toolCallId: Type$1.TString;
    toolName: Type$1.TString;
    content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"text">;
      text: Type$1.TString;
      textSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"image">;
      data: Type$1.TString;
      mimeType: Type$1.TString;
    }>]>>;
    details: Type$1.TOptional<Type$1.TUnknown>;
    isError: Type$1.TBoolean;
    timestamp: Type$1.TInteger;
  }>]>>;
}>;
type WorkerTurnAdmissionParams = Static<typeof WorkerTurnAdmissionParamsSchema>;
//#endregion
//#region src/process/gateway-work-admission.d.ts
type GatewayRootWorkAdmissionContinuationScope = {
  release: () => void;
  run: <T>(run: () => Promise<T>) => Promise<T>;
  /** Synchronous producers transfer accepted work to its own drain before returning. */
  runSync: <T>(run: () => T) => T;
};
//#endregion
//#region packages/gateway-protocol/src/schema/worker-exec-approval-schemas.d.ts
declare const WorkerExecApprovalParamsSchema: Type$1.TUnion<[Type$1.TObject<{
  binding: Type$1.TObject<{
    command: Type$1.TString;
    execCommand: Type$1.TString;
    cwd: Type$1.TString;
    environment: Type$1.TString;
    pty: Type$1.TBoolean;
  }>;
  toolCallId: Type$1.TString;
  operation: Type$1.TLiteral<"review">;
  review: Type$1.TObject<{
    argv: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    resolvedPath: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    envKeys: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    reason: Type$1.TEnum<["approval-required", "allowlist-miss", "strict-inline-eval", "heredoc", "execution-plan-miss"]>;
    analysis: Type$1.TObject<{
      parsed: Type$1.TBoolean;
      allowlistMatched: Type$1.TBoolean;
      safeBinMatched: Type$1.TOptional<Type$1.TBoolean>;
      durableApprovalMatched: Type$1.TOptional<Type$1.TBoolean>;
      inlineEval: Type$1.TBoolean;
      heredoc: Type$1.TOptional<Type$1.TBoolean>;
      shellWrapper: Type$1.TOptional<Type$1.TBoolean>;
    }>;
  }>;
}>, Type$1.TObject<{
  binding: Type$1.TObject<{
    command: Type$1.TString;
    execCommand: Type$1.TString;
    cwd: Type$1.TString;
    environment: Type$1.TString;
    pty: Type$1.TBoolean;
  }>;
  toolCallId: Type$1.TString;
  operation: Type$1.TLiteral<"request">;
  id: Type$1.TString;
  warningText: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  binding: Type$1.TObject<{
    command: Type$1.TString;
    execCommand: Type$1.TString;
    cwd: Type$1.TString;
    environment: Type$1.TString;
    pty: Type$1.TBoolean;
  }>;
  toolCallId: Type$1.TString;
  operation: Type$1.TLiteral<"wait">;
  id: Type$1.TString;
}>]>;
type WorkerExecApprovalParams = Static<typeof WorkerExecApprovalParamsSchema>;
//#endregion
//#region src/gateway/worker-environments/worker-gateway-tool-contract.d.ts
type WorkerGatewayToolSink = {
  send(frame: WorkerGatewayToolUpdateFrame): void;
};
//#endregion
//#region src/gateway/worker-environments/worker-github-binding-contract.d.ts
type WorkerGitHubBindingRefresh = {
  generation: number;
  token: string;
  expiresAtMs?: number;
};
//#endregion
//#region src/gateway/worker-environments/placement-turn-claim-events.d.ts
type WorkerTurnExecutionIdentity = Readonly<{
  agentId: string;
  delegatedAuthority: AgentRunDelegatedAuthority;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  operationalRunInstance: OperationalRunInstanceRef;
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /** Authenticated requester facts remain on the host and confer no worker authority. */
  requesterOrigin?: RequesterOrigin;
  /** Original presence reader, retained on the Gateway without a worker-writable claim. */
  assertPresenceSourceCurrent?: () => void;
  receiptAuthority: () => void;
  sessionKey: string;
  sessionTarget: Readonly<BoundAgentRunSessionTarget & ReturnType<typeof captureSessionTranscriptTargetBinding>>;
  turnClaim: WorkerSessionTurnClaim;
}>;
type WorkerTurnTranscriptSource = Pick<WorkerTurnExecutionIdentity, "sessionTarget" | "receiptAuthority">;
type WorkerTurnExecutionIdentityCapability = WorkerTurnTranscriptSource & Readonly<{
  assertPresenceSourceCurrent?: () => void;
  run<T>(callback: (identity: WorkerTurnExecutionIdentity) => Promise<T> | T): Promise<T>;
}>;
//#endregion
//#region src/agents/model-fallback-attempt.d.ts
type ModelFallbackResultClassification = {
  message: string;
  reason?: FailoverReason;
  status?: number;
  code?: string;
  rawError?: string;
  rateLimitRetriesExhausted?: number;
  preserveResultOnExhaustion?: boolean;
  preserveResultPriority?: number;
} | {
  error: unknown;
} | null | undefined;
//#endregion
//#region src/agents/runtime-plan/types.d.ts
type AgentRuntimeTransport = "sse" | "websocket" | "websocket-cached" | "auto";
type AgentRuntimeThinkLevel = ModelThinkingLevel | "adaptive";
type AgentRuntimeModel = {
  id?: string;
  name?: string;
  api?: string;
  provider?: string;
  baseUrl?: string;
  reasoning?: boolean;
  input?: readonly string[];
  cost?: {
    input: number;
    output: number;
    cacheRead: number;
    cacheWrite: number;
  };
  contextWindow?: number;
  maxTokens?: number;
  contextTokens?: number;
  compat?: unknown;
};
type AgentRuntimeTextReplacement = {
  from: string | RegExp;
  to: string;
};
type PreparedAgentRuntimeProviderHandle = {
  provider: string;
  modelId?: string | null;
  config?: unknown;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  applyAutoEnable?: boolean;
} & {
  modelId: string | null;
  prepared: true;
};
type AgentRuntimeSystemPromptContributionContext = {
  config?: unknown;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  promptMode: "full" | "minimal" | "none";
  runtimeChannel?: string;
  runtimeCapabilities?: string[];
  agentId?: string;
  trigger?: EmbeddedRunTrigger;
};
type AgentRuntimeResolvedRef = {
  provider: string;
  modelId: string;
  modelApi?: string;
  harnessId?: string;
  transport?: AgentRuntimeTransport;
};
type AgentRuntimeAuthModelRoute = {
  provider: string;
  modelId: string;
  api: ModelApi;
  baseUrl: string;
  authRequirement: "api-key" | "subscription";
  /** Secret-free request behavior that the selected runtime must reproduce. */
  requestTransportOverrides: ProviderRouteOverridePresence;
  /** Provider-owned native-runtime compatibility for this concrete route. */
  runtimePolicy?: ProviderModelRouteRuntimePolicy;
};
/** Actual provider/model/source tuple owned by one physical model attempt. */
type AgentRuntimeModelAttempt = {
  provider: string;
  model: string;
  credentialSource: AgentRuntimeCredentialSource;
};
type AgentRuntimeAuthPlan = {
  providerForAuth: string;
  /** Model whose order, cooldown, and route facts produced this plan. */
  modelId?: string;
  authProfileProviderForAuth: string;
  harnessAuthProvider?: string;
  /** Preferred or user-locked profile; automatic selection may not have resolved its secret yet. */
  forwardedAuthProfileId?: string;
  forwardedAuthProfileSource?: "auto" | "user";
  /** Ordered exhaustive candidates for the selected route; a singleton is terminal. */
  forwardedAuthProfileCandidateIds?: string[];
  /** Exact selected credential/config mode; secret-free route materialization input. */
  selectedAuthMode?: string;
  selectedAuthFlow?: string;
  /** Concrete provider-owned route selected before runtime dispatch. */
  modelRoute?: AgentRuntimeAuthModelRoute;
  /** Secret-free support shared by every route deferred to harness-owned auth. */
  /** Common native-runtime support proven across every route left to the harness. */
  deferredRouteSupport?: {
    requestTransportOverrides: ProviderRouteOverridePresence;
    runtimePolicy: ProviderModelRouteRuntimePolicy;
  };
  /** Redacted source selected for this concrete physical attempt. */
  credentialSource?: AgentRuntimeCredentialSource;
};
/** Prepared plugin metadata snapshot kept opaque to runtime-plan consumers. */
type AgentRuntimePreparedMetadataSnapshot = object;
type AgentRuntimeModelOverrides = {
  workspaceDir?: string;
  modelApi?: string;
  model?: AgentRuntimeModel;
};
type AgentRuntimeDeliveryPlan = {
  resolveFollowupRoute(params: {
    payload: ReplyPayload$1;
    originatingChannel?: string;
    originatingTo?: string;
    originRoutable: boolean;
    dispatcherAvailable: boolean;
  }): {
    route?: "origin" | "dispatcher" | "drop";
    reason?: string;
  } | undefined;
};
type AgentRuntimePlan = {
  resolvedRef: AgentRuntimeResolvedRef;
  providerRuntimeHandle?: PreparedAgentRuntimeProviderHandle;
  auth: AgentRuntimeAuthPlan;
  prompt: {
    provider: string;
    modelId: string;
    textTransforms?: {
      input?: AgentRuntimeTextReplacement[];
      output?: AgentRuntimeTextReplacement[];
    };
    resolveSystemPromptContribution(context: AgentRuntimeSystemPromptContributionContext): ProviderSystemPromptContribution | undefined;
    transformSystemPrompt(context: AgentRuntimeSystemPromptContributionContext & {
      systemPrompt: string;
    }): string;
  };
  tools: {
    /** Prepared metadata loader used by tool planning without eager manifest reads. */
    preparedPlanning?: {
      metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot;
    };
    normalize<TSchemaType extends TSchema = TSchema, TResult = unknown>(tools: AgentTool<TSchemaType, TResult>[], params?: AgentRuntimeModelOverrides): AgentTool<TSchemaType, TResult>[];
    logDiagnostics(tools: AgentTool[], params?: AgentRuntimeModelOverrides): void;
  };
  transcript: {
    policy: TranscriptPolicy;
    resolvePolicy(params?: AgentRuntimeModelOverrides & {
      directApiKey?: boolean;
    }): TranscriptPolicy;
  };
  delivery: AgentRuntimeDeliveryPlan;
  outcome: {
    classifyRunResult: (params: {
      provider: string;
      model: string;
      result: unknown;
      hasDirectlySentBlockReply?: boolean;
      hasBlockReplyPipelineOutput?: boolean;
    }) => ModelFallbackResultClassification;
  };
  transport: {
    extraParams: Record<string, unknown>;
    resolveExtraParams(params?: {
      extraParamsOverride?: Record<string, unknown>;
      thinkingLevel?: AgentRuntimeThinkLevel;
      agentId?: string;
      workspaceDir?: string;
      model?: AgentRuntimeModel;
      resolvedTransport?: AgentRuntimeTransport;
    }): Record<string, unknown>;
  };
  observability: AgentRuntimeResolvedRef & {
    resolvedRef: string;
    authProfileId?: string;
  };
};
type BuildAgentRuntimeDeliveryPlanParams = {
  config?: unknown;
  workspaceDir?: string;
  agentDir?: string;
  provider: string;
  modelId: string;
  providerRuntimeHandle?: PreparedAgentRuntimeProviderHandle;
};
type BuildAgentRuntimePlanParams = BuildAgentRuntimeDeliveryPlanParams & {
  /** Current transport/auth config; prompt and tool policy retain the admitted config. */
  transportConfig?: unknown;
  model?: AgentRuntimeModel;
  modelApi?: string | null;
  harnessId?: string;
  harnessRuntime?: string;
  allowHarnessAuthProfileForwarding?: boolean;
  /** Canonical route/auth decision prepared before attempt orchestration. */
  preparedAuthPlan?: AgentRuntimeAuthPlan;
  authProfileProvider?: string;
  authProfileMode?: string;
  sessionAuthProfileId?: string;
  sessionAuthProfileSource?: "auto" | "user" | "user-link";
  sessionAuthProfileCandidateIds?: string[];
  authProfileStore?: AuthProfileStore$1;
  modelRoute?: AgentRuntimeAuthModelRoute;
  agentId?: string;
  thinkingLevel?: AgentRuntimeThinkLevel;
  extraParamsOverride?: Record<string, unknown>;
  resolvedTransport?: AgentRuntimeTransport;
  /** Omit only when a standalone caller intentionally resolves provider hooks lazily. */
  providerRuntimeHandle?: PreparedAgentRuntimeProviderHandle;
  /** Lifecycle-owned plugin metadata prepared before the attempt starts. */
  metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot;
};
//#endregion
//#region src/sessions/session-controller.execution-selection.d.ts
type ExecutionSelectionEntry = Pick<SessionEntry, "execHost" | "execNode" | "execCwd" | "elevatedLevel" | "authProfileOverride" | "authProfileOverrideSource" | "authProfileOverrideCompactionCount" | "spawnedWorkspaceDir" | "spawnedCwd" | "sessionRoot" | "agentRuntimeOverride" | "agentHarnessId" | "modelSelectionLocked" | "providerOverride" | "modelOverride" | "modelOverrideSource">;
type ExecutionSelectionRun = {
  config?: OpenClawConfig;
  agentId?: string;
  agentDir?: string;
  sessionFile: string;
  workspaceDir: string;
  cwd?: string;
  authProfileId?: string;
  authProfileIdSource?: "auto" | "user" | "user-link";
};
/** Capture from the admitted producer, never from a later steering-time store read. */
declare function captureReplyExecutionSelection(params: {
  run: ExecutionSelectionRun;
  sessionEntry: Partial<ExecutionSelectionEntry> | undefined;
}): {
  kind: "execution";
  binding: {
    agentDir: string | undefined;
    sessionFile: string;
    workspaceDir: string;
    cwd: string | undefined;
    authProfile: {
      id: string | undefined;
    } | undefined;
  };
  session: {
    kind: "session";
    agentId: string | undefined;
    session: {
      execHost: string | undefined;
      execNode: string | undefined;
      execCwd: string | undefined;
      elevatedLevel: string | undefined;
      spawnedWorkspaceDir: string | undefined;
      spawnedCwd: string | undefined;
      sessionRoot: string | undefined;
      agentRuntimeOverride: string | undefined;
      agentHarnessId: string | undefined;
      modelSelectionLocked: boolean | undefined;
      model: {
        provider: string | undefined;
        model: string | undefined;
        source: "default" | "user" | undefined;
      } | undefined;
      authProfile: {
        id: string | undefined;
        source: "user" | "user-link";
      } | undefined;
    };
    configuration: {
      globalExec: ExecToolConfig | undefined;
      agentExec: ExecToolConfig | undefined;
      globalElevation: {
        enabled?: boolean;
        allowFrom?: AgentElevatedAllowFromConfig;
      } | undefined;
      agentElevation: {
        enabled?: boolean;
        allowFrom?: AgentElevatedAllowFromConfig;
      } | undefined;
      elevatedDefault: "ask" | "full" | "off" | "on" | undefined;
      runtime: {
        type: "embedded";
      } | {
        type: "acp";
        acp?: {
          agent?: string | undefined;
          backend?: string | undefined;
          mode?: "oneshot" | "persistent" | undefined;
          cwd?: string | undefined;
        } | undefined;
      } | undefined;
      configuredWorkspace: string | undefined;
      configuredCwd: string | undefined;
    } | undefined;
  };
};
//#endregion
//#region src/sessions/session-controller.message-join-observation.d.ts
/** Historical observations belong to the selected policy binding, not a later session read. */
declare function captureReplyMessageJoinObservation(params: {
  run: Parameters<typeof captureReplyExecutionSelection>[0]["run"];
  sessionEntry: Partial<SessionEntry> | undefined;
}): {
  executionSelection: {
    kind: "execution";
    binding: {
      agentDir: string | undefined;
      sessionFile: string;
      workspaceDir: string;
      cwd: string | undefined;
      authProfile: {
        id: string | undefined;
      } | undefined;
    };
    session: {
      kind: "session";
      agentId: string | undefined;
      session: {
        execHost: string | undefined;
        execNode: string | undefined;
        execCwd: string | undefined;
        elevatedLevel: string | undefined;
        spawnedWorkspaceDir: string | undefined;
        spawnedCwd: string | undefined;
        sessionRoot: string | undefined;
        agentRuntimeOverride: string | undefined;
        agentHarnessId: string | undefined;
        modelSelectionLocked: boolean | undefined;
        model: {
          provider: string | undefined;
          model: string | undefined;
          source: "default" | "user" | undefined;
        } | undefined;
        authProfile: {
          id: string | undefined;
          source: "user" | "user-link";
        } | undefined;
      };
      configuration: {
        globalExec: ExecToolConfig | undefined;
        agentExec: ExecToolConfig | undefined;
        globalElevation: {
          enabled?: boolean;
          allowFrom?: AgentElevatedAllowFromConfig;
        } | undefined;
        agentElevation: {
          enabled?: boolean;
          allowFrom?: AgentElevatedAllowFromConfig;
        } | undefined;
        elevatedDefault: "ask" | "full" | "off" | "on" | undefined;
        runtime: {
          type: "embedded";
        } | {
          type: "acp";
          acp?: {
            agent?: string | undefined;
            backend?: string | undefined;
            mode?: "oneshot" | "persistent" | undefined;
            cwd?: string | undefined;
          } | undefined;
        } | undefined;
        configuredWorkspace: string | undefined;
        configuredCwd: string | undefined;
      } | undefined;
    };
  };
};
type ReplyMessageJoinObservation = ReturnType<typeof captureReplyMessageJoinObservation>;
//#endregion
//#region src/agents/embedded-agent-runner/run-entry.types.d.ts
type ResolvedRunEntryModelSelection = {
  provider: string;
  modelId: string;
} & Pick<PluginHookBeforeModelResolveResult, "fallbacksOverride">;
//#endregion
//#region src/infra/diagnostic-model-request-provenance.d.ts
type CoreModelRequestOwnerGeneration = object;
type DiagnosticEmbeddedRunOwner = Readonly<{
  generation: CoreModelRequestOwnerGeneration;
  runId?: string;
  sessionId: string;
  sessionKey?: string;
  workKey: string;
  watchdogAttempt?: SessionControllerWatchdogAttempt;
}>;
//#endregion
//#region src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.d.ts
type DeferredEmbeddedRunLifecycleOwner = {
  beginRetryWait: (deadlineAtMs: number, signal: AbortSignal, wait?: {
    rateLimitStopMessage?: string;
  }) => ((completed?: boolean) => void) | undefined;
  complete: () => Promise<void>;
  discard: () => void | Promise<void>;
};
//#endregion
//#region src/agents/embedded-agent-runner/run/terminal-retry-state.d.ts
type EmbeddedRunCompletionCheck = {
  unfinishedPlan: boolean;
  checked: boolean;
};
//#endregion
//#region src/agents/embedded-agent-runner/run/internal-params.d.ts
type CompactionAccountingTarget = Readonly<SessionTranscriptRuntimeTarget & Pick<InternalSessionEntry, "lifecycleRevision" | "activeWriterRunId">>;
/** Ordered producer observations; unknown context never borrows an older request's usage. */
type EmbeddedContextAccountingEvent = Readonly<{
  kind: "compaction";
  tokensAfter: number | undefined;
} | {
  kind: "model";
  contextTokens: number | undefined;
  successful: boolean;
}>;
/** Writer custody is independent of telemetry; an absent snapshot is not observed unknown context. */
type CompactionAccountingFact = Readonly<{
  count: number;
  currentContextSnapshot?: {
    tokens: number | undefined;
  };
} & ({
  kind: "durable";
  target: CompactionAccountingTarget;
  /** Present only when the host committed a successor session rotation. */
  previousSessionId?: string;
  /** Ordered, host-committed identity changes; never inferred from a returned session ID. */
  admissionTransitions?: readonly SessionAdmissionTransition[];
  /** Native-thread compaction leaves the host transcript unchanged. */
  hostCompactionCommitted?: boolean;
} | {
  kind: "presentation-only";
})>;
type RunEmbeddedAgentInternalParams = RunEmbeddedAgentParams & {
  /** The reply owner checkpoints the source before recovery rewrites its context. */
  beforeRecoveryCompaction?: (context: {
    sessionId: string;
    provider: string;
    model: string;
    authProfileId?: string;
    authProfileIdSource: "auto" | "user";
    contextTokenBudget: number;
  }) => Promise<string>;
  /** A recovery checkpoint must not compact away the history it is trying to save. */
  disableCompactionRecovery?: true;
  /** Original admitted settings, retained by the host across private runtime selection. */
  joinObservation?: ReplyMessageJoinObservation;
  /** The logical run already invoked model routing before preparing its candidate chain. */
  resolvedModelSelection?: ResolvedRunEntryModelSelection;
  preparedTtsPreferences?: PreparedTtsPreferences;
  /** Fail-closed caller input admission against the actual prepared model, before dispatch. */
  assertModelInput?: (model: Pick<Model, "input">) => void;
  /** Keep source-owned custody separate from streamed-block completion in one observation. */
  resolveReplyDeliveryFacts?: ReplyDeliveryFactsObserver;
  /** Reset deferred terminal facts when the host admits a new attempt, before preparation. */
  onAttemptStart?: () => void;
  /** Retire superseded terminal facts only after the host accepts isolated recovery. */
  onAttemptTerminalReplaced?: () => void;
  /** Keep a bounded auxiliary tool set directly visible after runtime admission. */
  disableToolSearch?: true;
  /** Restrict history/search to an explicitly observed session, not this run's store key. */
  sessionReadScopeKey?: string;
  /** Candidate producers have already resolved the model against their captured metadata. */
  requestedRouteResolution?: ModelFallbackRouteResolution;
  onCompactionRequestBudget?: (budget: CompactionRequestBudget | undefined) => void;
  onCompactionAccounting?: (fact: CompactionAccountingFact | undefined) => void;
  /** Attempt-local context observer, installed by the host loop before dispatch. */
  onContextAccountingEvent?: (event: EmbeddedContextAccountingEvent) => void;
  onSuccessfulAuthBinding?: (binding: AgentExecutionAuthBinding) => void;
  /** Maintenance needs the winning profile, not native runtime artifact capture. */
  onSuccessfulAuthProfile?: (profileId: string | undefined) => void;
  authProfileStateMode?: "read-write" | "read-only";
  /** Prepare only the requested candidate with this runtime; fallbacks keep their own policy. */
  agentHarnessRuntimePreparationHint?: string;
  /** Keep staged setup config and credentials outside configured Gateway ownership. */
  preparedModelRuntimeMode?: "isolated-read-only";
  /** Setup may initialize missing account catalog facts before its live inference probe. */
  refreshModelCatalog?: boolean;
  /** Ring-zero tool override, supplied only by the OpenClaw orchestrator. */
  systemAgentTool?: SystemAgentToolOptions;
  /** Gateway-private lifecycle generation selected before command admission. */
  pluginGeneration?: PreparedModelRuntimePluginGeneration;
  /** Re-admit from the committed transcript without persisting the original prompt again. */
  pluginRuntimeRefreshContinuation?: true;
  pluginRuntimeRefreshUserPrompt?: EmbeddedRunAttemptParams["pluginRuntimeRefreshUserPrompt"];
  pluginRuntimeRefreshMessages?: EmbeddedRunAttemptParams["pluginRuntimeRefreshMessages"];
  /** Actual generation cleanup, including source callbacks after native terminal publication. */
  runCleanupSettlement?: Promise<void>;
  /** Host-only transfer of attempt terminal resources to the logical turn. */
  onDeferredLifecycleOwner?: (owner: DeferredEmbeddedRunLifecycleOwner) => void;
  /** Aborts the logical turn when its retained embedded handle is cancelled. */
  onDeferredLifecycleAbort?: (reason?: "user_abort" | "restart" | "superseded") => void;
  /** Protects an admitted provider wait through the retained logical-turn owner. */
  onRetryWait?: (deadlineAtMs: number, signal?: AbortSignal, wait?: {
    rateLimitStopMessage?: string;
  }) => ((completed?: boolean) => void) | undefined;
};
type EmbeddedRunAttemptInternalParams = EmbeddedRunAttemptParams & Pick<RunEmbeddedAgentInternalParams, "onContextAccountingEvent" | "onCompactionRequestBudget" | "runCleanupSettlement" | "joinObservation"> & {
  bindWatchdogAttempt?: (attempt: SessionControllerWatchdogAttempt) => void;
  /** The dispatch owner already selected this target, including any compaction successor. */
  preparedSessionTarget?: {
    readonly target: Readonly<BoundAgentRunSessionTarget & SessionTranscriptTargetBinding>;
    assertCurrent: PreparedSessionSourceAssertion;
  };
  /** Frozen source-attempt model view; transcript writer custody remains unchanged. */
  settledTurnFinalizationMessages?: readonly AgentMessage[];
  compactionCountOwner?: "subscription" | "caller";
  /** Current-run committed plan facts; retained across attempts, never loaded from history. */
  completionCheck?: EmbeddedRunCompletionCheck;
  /** Host-private receiver for the native owner's admitted Gateway-local settings cwd. */
  prepareContinuationRetryCount?: (workspace: {
    cwd: string;
  }) => void;
};
//#endregion
//#region src/agents/embedded-agent-runner/compact.types.d.ts
type CompactEmbeddedAgentSessionParams = Pick<RunEmbeddedAgentParams, "requireWorkspaceOnly" | "sessionTarget" | "sessionId" | "sessionKey" | "agentId" | "sandboxSessionKey" | "sandboxAgentId" | "messageChannel" | "messageProvider" | "clientCaps" | "pinnedWidgetAuthoring" | "chatType" | "agentAccountId" | "conversationRoutePeerId" | "conversationToolPolicy" | "requesterOrigin" | "operatorProfileId" | "conversationId" | "messageThreadId" | "currentChannelId" | "currentThreadTs" | "currentMessageId" | "authProfileId" | "authProfileIdSource" | "groupId" | "groupChannel" | "groupSpace" | "memberRoleIds" | "spawnedBy" | "inputProvenance" | "trustedInternalHandoff" | "toolsAllow" | "disableTools" | "runtimePluginToolGrant" | "scheduledToolPolicy" | "workspaceDir" | "bootstrapWorkspaceDir" | "cwd" | "permissionMode" | "sessionRoot" | "agentDir" | "config" | "toolOverrides" | "skillsSnapshot" | "senderIsOwner" | "provider" | "model" | "modelFallbacksOverride" | "contextTokenBudget" | "agentHarnessId" | "modelSelectionLocked" | "thinkLevel" | "reasoningLevel" | "bashElevated" | "lane" | "enqueue" | "extraSystemPrompt" | "sourceReplyDeliveryMode" | "ownerNumbers" | "abortSignal" | "allowGatewaySubagentBinding" | "oneShotCliRun"> & {
  /** Explicit session owner captured before fallback agent resolution. */
  contextEngineAgentId?: string;
  runId?: string;
  /** Host-resolved memory partition inherited from the compacted session. */
  memoryAudience?: MemoryAudience;
  /** Host-resolved sandbox fact paired with the compacted session authority. */
  memorySandboxed?: boolean;
  /** Trusted sender id from inbound context for scoped message-tool discovery. */
  senderId?: string;
  senderName?: string;
  senderUsername?: string;
  senderE164?: string;
  /** Host-resolved provider credential for native harness compaction. */
  resolvedApiKey?: string;
  /** Host-resolved ambient native-tool boundary for this compaction operation. */
  nativeToolSurface?: "unrestricted" | "host-isolated";
  sessionFile: string;
  /** Optional caller-observed live prompt tokens used for compaction diagnostics. */
  currentTokenCount?: number;
  /** Caller-resolved model/provider shape used by native harness compactors. */
  runtimeModel?: Model;
  /** Optional caller-resolved context engine for harness-owned compaction. */
  contextEngine?: ContextEngine;
  /** Optional caller-resolved runtime context for harness-owned context-engine compaction. */
  contextEngineRuntimeContext?: ContextEngineRuntimeContext;
  /** Resumable native CLI session targeted by an explicit manual compaction. */
  cliSessionId?: string;
  /** Complete persisted CLI binding targeted by an explicit manual compaction. */
  cliSessionBinding?: CliSessionBinding;
  /** Owning session facts required for placement and runtime preparation. */
  sessionEntry?: SessionEntry;
  /** OpenClaw-owned runtime policy prepared for this compaction path. */
  runtimePlan?: AgentRuntimePlan;
  /** Host-prepared route and credential selection for native harness compaction. */
  runtimeAuthPlan?: AgentRuntimeAuthPlan;
  execOverrides?: Pick<ExecToolDefaults, "host" | "mode" | "security" | "ask" | "node" | "nodeCwd">;
  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";
  /** Source-turn urgency survives replacing its trigger with a compaction reason. */
  modelCallUrgency?: ModelCallUrgency;
  /**
   * 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;
  /** @internal Refreshes the host watchdog when delegated native compaction makes progress. */
  compactionTimeoutReset?: () => void;
  /** @internal Host watchdog ceiling (epoch ms); the summary request ends one window before it. */
  compactionDeadlineAt?: number;
  onCompactionHookMessages?: (payload: {
    phase: "before" | "after";
    messages: string[];
    sessionId: string;
    sessionKey: string;
  }) => void | Promise<void>;
};
//#endregion
//#region src/plugins/agent-tool-result-middleware-types.d.ts
type OpenClawAgentToolResult<TResult = unknown> = AgentToolResult<TResult>;
type AgentToolResultMiddlewareRuntime = "openclaw" | "codex" | "agentsapi";
type AgentToolResultMiddlewareEvent = {
  threadId?: string;
  turnId?: string;
  toolCallId: string;
  toolName: string;
  args: Record<string, unknown>;
  cwd?: string;
  isError?: boolean;
  result: OpenClawAgentToolResult;
};
type AgentToolResultMiddlewareContext = {
  runtime: AgentToolResultMiddlewareRuntime;
  agentId?: string;
  sessionId?: string;
  sessionKey?: string;
  runId?: string;
};
type AgentToolResultMiddlewareResult = {
  result: OpenClawAgentToolResult;
};
type AgentToolResultMiddleware = (event: AgentToolResultMiddlewareEvent, ctx: AgentToolResultMiddlewareContext) => Promise<AgentToolResultMiddlewareResult | void> | AgentToolResultMiddlewareResult | void;
type AgentToolResultMiddlewareOptions = {
  matcher?: PluginToolMatcher;
  /** Defaults to the plugin's contracts.agentToolResultMiddleware declaration. */
  runtimes?: AgentToolResultMiddlewareRuntime[];
};
type AgentToolResultMiddlewareScope = {
  matcher?: PluginToolMatcher;
  runtimes: AgentToolResultMiddlewareRuntime[];
};
//#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<string, unknown>;
  result: AgentToolResult<unknown>;
};
/** 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<unknown>;
};
/** Runtime event surface exposed to Codex app-server extension factories. */
type CodexAppServerExtensionRuntime = {
  on: (event: "tool_result", handler: (event: CodexAppServerToolResultEvent, ctx: CodexAppServerExtensionContext) => Promise<CodexAppServerToolResultHandlerResult | void> | CodexAppServerToolResultHandlerResult | void) => void;
};
/** Factory signature for Codex app-server plugin extensions. */
type CodexAppServerExtensionFactory = (runtime: CodexAppServerExtensionRuntime) => Promise<void> | void;
//#endregion
//#region src/agents/harness/native-hook-relay-types.d.ts
type NativeHookRelayApprovalContext = Pick<HookContext, "approvalReviewerDeviceId" | "trigger" | "turnSourceAccountId" | "turnSourceChannel" | "turnSourceThreadId" | "turnSourceTo">;
declare const NATIVE_HOOK_RELAY_EVENTS: readonly ["pre_tool_use", "post_tool_use", "permission_request", "before_agent_finalize"];
type NativeHookRelayEvent = (typeof NATIVE_HOOK_RELAY_EVENTS)[number];
type NativeHookRelayProvider = "codex";
type NativeHookRelayInvocation = {
  provider: NativeHookRelayProvider;
  relayId: string;
  event: NativeHookRelayEvent;
  nativeEventName?: string;
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
  runId: string;
  cwd?: string;
  model?: string;
  turnId?: string;
  transcriptPath?: string;
  permissionMode?: string;
  stopHookActive?: boolean;
  lastAssistantMessage?: string;
  toolName?: string;
  toolUseId?: string;
  rawPayload: PluginJsonValue;
  receivedAt: string;
};
type NativeHookRelayProcessResponse = {
  stdout: string;
  stderr: string;
  exitCode: number;
  failureDisposition?: Exclude<BeforeToolCallFailureDisposition, "blocked">;
};
type NativeHookRelayRegistration = {
  relayId: string;
  provider: NativeHookRelayProvider;
  generationMismatchGraceExpiresAtMs?: number;
  generationMismatchGraceAcceptedGeneration?: string;
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
  config?: OpenClawConfig;
  deferMcpToolApprovals?: boolean;
  runId: string;
  channelId?: string;
  requester?: PluginHookToolRequesterContext;
  approvalContext?: NativeHookRelayApprovalContext;
  allowedEvents: readonly NativeHookRelayEvent[];
  /** Keep host policy active for every native tool even without plugin hooks. */
  requirePreToolUse?: boolean;
  /** Wall-clock epoch expiry shared through the cross-process bridge record. */
  expiresAtMs: number;
  signal?: AbortSignal;
  /** Exact host policy capability for authority-bearing native callbacks. */
  runBeforeToolCall?: AgentHarnessHostCapabilities["runBeforeToolCall"];
  /** Foreground-only approval authority supplied by the admitted bundled host. */
  approvalHost?: Pick<AgentHarnessHostCapabilities, "requestApproval" | "waitForApproval">;
  /** Revalidates the exact admitted owner after authority-bearing awaits. */
  assertActive?: AgentHarnessHostCapabilities["assertActive"];
  /** Reads worker-owned execution policy before returning permission to the native runtime. */
  assertActiveAsync?: () => Promise<void>;
  onPreToolUseFailure?: (failure: {
    toolName: string;
    toolCallId: string;
    disposition: Exclude<BeforeToolCallFailureDisposition, "blocked">;
    durationMs: number;
  }) => void | Promise<void>;
};
type NativeHookRelayRegistrationHandle = NativeHookRelayRegistration & {
  generation?: string;
  shouldRelayEvent: (event: NativeHookRelayEvent) => boolean;
  toolMatcherForEvent: (event: NativeHookRelayEvent) => readonly string[] | undefined;
  commandForEvent: (event: NativeHookRelayEvent, options?: NativeHookRelayCommandForEventOptions) => string;
  renew: (ttlMs?: number) => void;
  unregister: () => void;
};
type RegisterNativeHookRelayParams = {
  provider: NativeHookRelayProvider;
  relayId?: string;
  generation?: string;
  generationMismatchGraceMs?: number;
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
  config?: OpenClawConfig;
  autoApproveMcpTools?: boolean;
  projectedMcpServers?: CodexMcpServersConfig;
  runId: string;
  channelId?: string;
  requester?: PluginHookToolRequesterContext;
  approvalContext?: NativeHookRelayApprovalContext;
  allowedEvents?: readonly NativeHookRelayEvent[];
  /** Whether this relay should run OpenClaw loop detection from native PreToolUse hooks. */
  preToolUseLoopDetection?: boolean;
  /** Never prune the all-tool PreToolUse policy relay. Requires runBeforeToolCall. */
  requirePreToolUse?: boolean;
  ttlMs?: number;
  command?: NativeHookRelayCommandOptions;
  signal?: AbortSignal;
  runBeforeToolCall?: NativeHookRelayRegistration["runBeforeToolCall"];
  assertActive?: NativeHookRelayRegistration["assertActive"];
  assertActiveAsync?: NativeHookRelayRegistration["assertActiveAsync"];
  onPreToolUseFailure?: NativeHookRelayRegistration["onPreToolUseFailure"];
};
type NativeHookRelayCommandOptions = {
  executable?: string;
  nice?: number | false;
  nodeExecutable?: string;
  timeoutMs?: number;
};
type NativeHookRelayCommandForEventOptions = {
  timeoutMs?: number;
  remoteCredentialPath?: string;
};
type InvokeNativeHookRelayParams = {
  provider: unknown;
  relayId: unknown;
  generation?: unknown;
  event: unknown;
  rawPayload: unknown;
  requireGeneration?: boolean;
};
type NativeHookRelayPermissionDecision = "allow" | "deny";
type NativeHookRelayPermissionApprovalResult = NativeHookRelayPermissionDecision | "allow-always" | "timed-out" | "defer";
type ActiveNativeHookRelayRegistrationHandle = NativeHookRelayRegistrationHandle & {
  generation: string;
};
type NativeHookRelayPermissionApprovalRequest = {
  provider: NativeHookRelayProvider;
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
  runId: string;
  toolName: string;
  toolCallId?: string;
  cwd?: string;
  model?: string;
  toolInput: Record<string, PluginJsonValue>;
  signal?: AbortSignal;
};
type NativeHookRelayPermissionApprovalRequester = (request: NativeHookRelayPermissionApprovalRequest) => Promise<NativeHookRelayPermissionApprovalResult>;
type NativeHookRelayDeferredApprovalOutcome = {
  handled: true;
  outcome: "approved-once";
} | {
  handled: true;
  outcome: "denied";
  reason: string;
  failureDisposition?: Exclude<BeforeToolCallFailureDisposition, "blocked">;
};
//#endregion
//#region src/agents/harness/native-hook-relay-approval-presentation.d.ts
declare function formatPermissionApprovalDescription(request: NativeHookRelayPermissionApprovalRequest): string;
//#endregion
//#region src/agents/harness/native-hook-relay-permissions.d.ts
type NativeHookRelayDeferredToolApprovalRequester = typeof requestDeferredPluginToolApproval;
declare function resolveNativeHookRelayDeferredToolApproval(params: {
  relayId: string;
  toolUseId?: string;
  signal?: AbortSignal;
}): Promise<NativeHookRelayDeferredApprovalOutcome | undefined>;
declare function permissionRequestContentFingerprint(request: NativeHookRelayPermissionApprovalRequest): string;
declare function setNativeHookRelayPermissionApprovalRequesterForTests(requester: NativeHookRelayPermissionApprovalRequester): void;
declare function setNativeHookRelayDeferredToolApprovalRequesterForTests(requester: NativeHookRelayDeferredToolApprovalRequester): void;
//#endregion
//#region src/agents/harness/native-hook-relay-command.d.ts
declare function buildNativeHookRelayCommand(params: Omit<Parameters<typeof buildNativeHookRelayCommandWithStateDatabase>[0], "stateDbPath">): string;
declare function buildNativeHookRelayCommandWithStateDatabase(params: {
  provider: NativeHookRelayProvider;
  relayId: string;
  stateDbPath?: string;
  remoteCredentialPath?: string;
  generation?: string;
  event: NativeHookRelayEvent;
  preToolUseUnavailable?: "noop";
  timeoutMs?: number;
  executable?: string;
  nice?: number | false;
  nodeExecutable?: string;
}): string;
//#endregion
//#region src/agents/harness/native-hook-relay.d.ts
declare function registerNativeHookRelay(params: RegisterNativeHookRelayParams): ActiveNativeHookRelayRegistrationHandle;
declare function invokeNativeHookRelay(params: InvokeNativeHookRelayParams, invocationSignal?: AbortSignal): Promise<NativeHookRelayProcessResponse>;
declare function hasNativeHookRelayInvocation(params: {
  relayId: string;
  event: NativeHookRelayEvent;
  toolUseId?: string;
}): boolean;
declare const testing: {
  readonly clearNativeHookRelaysForTests: () => Promise<void>;
  readonly getNativeHookRelayInvocationsForTests: () => NativeHookRelayInvocation[];
  readonly getNativeHookRelayRegistrationForTests: (relayId: string) => NativeHookRelayRegistration | undefined;
  readonly getNativeHookRelayBridgeRecordForTests: (relayId: string) => Promise<Record<string, unknown> | undefined>;
  readonly formatPermissionApprovalDescriptionForTests: typeof formatPermissionApprovalDescription;
  readonly permissionRequestContentFingerprintForTests: typeof permissionRequestContentFingerprint;
  readonly setNativeHookRelayPermissionApprovalRequesterForTests: typeof setNativeHookRelayPermissionApprovalRequesterForTests;
  readonly setNativeHookRelayDeferredToolApprovalRequesterForTests: typeof setNativeHookRelayDeferredToolApprovalRequesterForTests;
};
//#endregion
//#region src/plugins/hook-agent-context.d.ts
/** Builds channel/provider fields for plugin agent hook context. */
declare function buildAgentHookContextChannelFields(params: {
  sessionKey?: string | null;
  messageChannel?: string | null;
  messageProvider?: string | null;
  currentChannelId?: string | null;
  messageTo?: string | null;
  senderId?: string | null;
  agentAccountId?: string | null;
}): Pick<PluginHookAgentContext, "accountId" | "channel" | "channelId" | "chatId" | "messageProvider" | "senderId">;
//#endregion
//#region src/agents/run-cleanup-timeout.d.ts
type AgentCleanupLogger = {
  warn: (message: string) => void;
};
type AgentCleanupStepParams = {
  runId: string;
  sessionId: string;
  step: string;
  cleanup: () => Promise<void>;
  getTimeoutDetails?: () => string | undefined;
  log: AgentCleanupLogger;
  env?: NodeJS.ProcessEnv;
  timeoutMs?: number;
};
/** Run one cleanup step with timeout logging and late-rejection handling. */
declare function runAgentCleanupStep(params: AgentCleanupStepParams): Promise<void>;
//#endregion
//#region src/agents/run-termination.d.ts
declare function resolveAgentRunAbortLifecycleFields(signal: AbortSignal | undefined): {
  aborted?: true;
  stopReason?: typeof AGENT_RUN_ABORTED_STOP_REASON | typeof AGENT_RUN_RESTART_ABORT_STOP_REASON | typeof AGENT_RUN_SUPERSEDED_STOP_REASON | "stop" | "auth-revoked" | "timeout";
};
//#endregion
//#region src/agents/agent-tools.ring-zero-context.d.ts
/**
 * Read a host-owned tool fact for the current run. This does not activate or
 * grant a tool; only the host can bind executable authority to the run scope.
 */
declare function isHostScopedAgentToolActive(toolName: string): boolean;
//#endregion
//#region src/agents/embedded-agent-runner/logger.d.ts
declare const log: SubsystemLogger;
//#endregion
//#region src/agents/runtime-plan/build.d.ts
declare function buildAgentRuntimePlan(params: BuildAgentRuntimePlanParams): AgentRuntimePlan;
//#endregion
//#region src/agents/runtime-plan/prepare-auth.d.ts
type PrepareAgentRuntimeAuthPlanParams = {
  provider: string;
  modelId: string;
  modelApi?: string | null;
  modelBaseUrl?: unknown;
  /** Physical catalog rows for the logical model; replaces the single api/baseUrl observation. */
  observedRoutes?: readonly ProviderModelRouteSource[];
  requestTransportOverrides?: ProviderRouteOverridePresence;
  config?: OpenClawConfig;
  agentId?: string;
  routeIntent?: ProviderResolveModelRoutesContext["routeIntent"];
  env?: NodeJS.ProcessEnv;
  agentDir?: string;
  workspaceDir?: string;
  metadataSnapshot?: PluginMetadataSnapshot;
  authProfileStore?: AuthProfileStore$1;
  sessionAuthProfileId?: string;
  /** Required by a durable caller, without turning automatic selection into a user pin. */
  requiredAuthProfileId?: string;
  sessionAuthProfileSource?: "auto" | "user" | "user-link";
  allowAuthProfileFallback?: boolean;
  harnessId?: string;
  harnessRuntime?: string;
  harnessAuthBootstrap?: "harness";
  allowHarnessAuthProfileForwarding?: boolean;
  allowTransientCooldownProbe?: boolean;
  resolveProviderPreferredProfileId?(context: ProviderResolveAuthProfileIdContext): string | undefined;
};
type PreparedAgentRuntimeAuthAttempt = {
  kind: "profile";
  plan: AgentRuntimeAuthPlan;
  profileId: string;
  allowAuthProfileFallback?: never;
  requiresPriorProfileAttempt?: never;
} | {
  kind: "direct";
  plan: AgentRuntimeAuthPlan;
  profileId?: never;
  /** Direct lookup cannot re-enter automatic profile discovery. */
  allowAuthProfileFallback: false;
  /** Fail closed when every prepared profile became cooldown-blocked before dispatch. */
  requiresPriorProfileAttempt: boolean;
} | {
  kind: "implicit";
  plan: AgentRuntimeAuthPlan;
  profileId?: never;
  allowAuthProfileFallback?: never;
  requiresPriorProfileAttempt?: never;
};
type PreparedAgentRuntimeAuth = {
  plan: AgentRuntimeAuthPlan;
  /** Ordered physical attempts; every route/profile tuple was selected by this planner. */
  attempts: readonly PreparedAgentRuntimeAuthAttempt[];
};
/** Selects concrete provider routes and ordered credentials as one immutable preparation. */
declare function prepareAgentRuntimeAuth(input: PrepareAgentRuntimeAuthPlanParams): PreparedAgentRuntimeAuth;
//#endregion
//#region src/agents/embedded-agent-runner/result-fallback-classifier.d.ts
/** Delivered output, deliberate silence, hook blocks, and aborts must not trigger another model. */
declare function classifyEmbeddedAgentRunResultForModelFallback(params: {
  provider: string;
  model: string;
  result: unknown;
  hasDirectlySentBlockReply?: boolean;
  hasBlockReplyPipelineOutput?: boolean;
}): ModelFallbackResultClassification;
//#endregion
//#region src/agents/tools/in-process-gateway.d.ts
/** Whether Gateway routing belongs to this caller or the hosting process. */
declare function hasGatewayToolRoutingContext(): boolean;
//#endregion
//#region src/agents/tools/nodes-utils.d.ts
type DefaultNodeFallback = "none" | "first";
type DefaultNodeSelectionOptions = {
  capability?: string;
  fallback?: DefaultNodeFallback;
  preferLocalMac?: boolean;
};
declare function selectDefaultNodeFromList(nodes: NodeListNode[], options?: DefaultNodeSelectionOptions): NodeListNode | null;
declare function listNodes(opts: GatewayCallOptions, signal?: AbortSignal): Promise<NodeListNode[]>;
declare function resolveNodeIdFromList(nodes: NodeListNode[], query?: string, allowDefault?: boolean, options?: {
  allowCompactDisplayName?: boolean;
}): string;
//#endregion
//#region src/auto-reply/tool-meta.d.ts
type ToolAggregateOptions = {
  markdown?: boolean;
};
/** Formats one grouped tool-progress label from a tool name and metadata entries. */
declare function formatToolAggregate(toolName?: string, metas?: string[], options?: ToolAggregateOptions): string;
//#endregion
//#region src/agents/embedded-agent-messaging.d.ts
/** Return true for core or channel-plugin messaging tool names. */
declare function isMessagingTool(toolName: string): boolean;
/** Return true when the specific tool invocation is an outbound send. */
declare function isMessagingToolSendAction(toolName: string, args: Record<string, unknown>): boolean;
//#endregion
//#region src/agents/embedded-agent-message-delivery.d.ts
type EmbeddedMessageDeliveryFact = {
  status: "settled" | "suppressed" | "dryRun" | "failed";
  sourceReplyDelivered?: true;
  primaryPlatformMessageId?: string;
  deliveredTargets?: string[];
  partialDelivery: boolean;
  createdThreadIds: string[];
};
declare function projectPluginMessageDeliveryFact(value: unknown): EmbeddedMessageDeliveryFact | undefined;
declare function readEmbeddedMessageDeliveryFact(value: unknown): EmbeddedMessageDeliveryFact | undefined;
//#endregion
//#region src/agents/embedded-agent-messaging-extraction.d.ts
declare function extractMessagingToolSourceReplyPayload(result: unknown): MessagingToolSourceReplyPayload | undefined;
declare function extractMessagingToolSend(toolName: string, args: Record<string, unknown>, options?: {
  config?: OpenClawConfig;
  currentChannelId?: string;
  currentMessagingTarget?: string;
  currentThreadId?: string;
  currentMessageId?: string | number;
  replyToMode?: "off" | "first" | "all" | "batched";
  hasRepliedRef?: {
    value: boolean;
  };
}): MessagingToolSend | undefined;
/** Reconciles pending send evidence with the provider's successful action result. */
declare function extractMessagingToolSendResult(pending: MessagingToolSend, result: unknown): MessagingToolSend;
declare function isDeliveredMessagingToolSendToCurrentSource(params: {
  send: MessagingToolSend | undefined;
  config?: OpenClawConfig;
  currentProvider?: string;
  currentAccountId?: string;
  currentChannelId?: string;
  currentMessagingTarget?: string;
  currentThreadId?: string;
  sessionKey?: string;
  deliveredPayload?: unknown;
}): boolean;
//#endregion
//#region src/agents/embedded-agent-tool-authored-source-reply.d.ts
/**
 * Reads the final reply a `canDeliverSourceReply` tool authored and keys it to its
 * tool call. The host delivers the payload and writes its transcript row after a
 * successful send, so nothing is persisted here. Callers must already have verified
 * the tool's capability, that the result is not an error, and that the call is a
 * direct model call rather than a nested program call. Returns undefined when the
 * result carries no deliverable reply.
 */
declare function captureToolAuthoredSourceReply(params: {
  /** Effective tool result after hooks and middleware; only `details.sourceReply` is read. */
  result: unknown;
  toolCallId: string;
  /** Stable scope: the issuing assistant turn, else the run id or harness turn id. */
  idempotencyScope: string;
}): MessagingToolSourceReplyPayload | undefined;
//#endregion
//#region src/agents/embedded-agent-tool-media.d.ts
declare function filterToolResultMediaUrls(toolName: string | undefined, mediaUrls: string[], result?: unknown, trustedLocalMediaToolNames?: ReadonlySet<string>): string[];
type ToolResultMediaArtifact = {
  mediaUrls: string[];
  attachments?: ReplyMediaAttachment[];
  audioAsVoice?: boolean;
  trustedLocalMedia?: boolean;
};
declare function extractToolResultMediaArtifact(result: unknown): ToolResultMediaArtifact | undefined;
//#endregion
//#region src/agents/embedded-agent-tool-results.d.ts
declare function sanitizeToolResult(result: string): string;
declare function sanitizeToolResult(result: unknown): unknown;
declare function extractToolErrorMessage(result: unknown): string | undefined;
//#endregion
//#region src/agents/tool-effect-receipt.d.ts
/** Host-owned effect provenance for one completed tool lifecycle. */
type ToolEffectReceipt = Readonly<{
  state: "not_started" | "read_completed" | "failed_no_effect" | "mutation_committed" | "uncertain";
}>;
//#endregion
//#region src/agents/tool-result-error.d.ts
declare function isToolResultError(result: unknown): boolean;
type ToolResultFailureKind = "blocked" | "cancelled" | "failed" | "timed_out";
/** Classify a thrown tool error without inferring cancellation from message text. */
declare function resolveToolExecutionErrorKind(error: unknown): "failed" | "timed_out";
/** Format a tool error without allowing hostile getters to escape observability. */
declare function formatToolExecutionErrorMessage(error: unknown, fallback: string): string;
/** Classify a resolved structured tool result through the shared terminal contract. */
declare function resolveToolResultFailureKind(result: unknown): ToolResultFailureKind | undefined;
//#endregion
//#region src/agents/tool-operator-hint.d.ts
declare function readToolOperatorHint(error: unknown): string | undefined;
//#endregion
//#region src/plugin-sdk/agent-scope-runtime.d.ts
/** Preserve the SDK's writable array while core readers share immutable roster facts. */
declare function listAgentIdsCompatibility(config: Parameters<typeof listAgentIds>[0]): string[];
type SessionAgentResolutionParams = Parameters<typeof resolveSessionAgentIdsStrict>[0];
/**
 * @deprecated Use `resolveSessionAgentIdsStrict` with an explicit or prepared
 * owner. Retained through 2026-11-29 for plugins shipped before strict
 * multi-agent ownership was introduced.
 */
declare function resolveSessionAgentIdsCompatibility(params: SessionAgentResolutionParams): {
  defaultAgentId: string;
  sessionAgentId: string;
};
/**
 * @deprecated Use `resolveSessionAgentIdStrict` with an explicit or prepared
 * owner. Retained through 2026-11-29 for plugins shipped before strict
 * multi-agent ownership was introduced.
 */
declare function resolveSessionAgentIdCompatibility(params: SessionAgentResolutionParams): string;
//#endregion
//#region src/agents/model-tool-support.d.ts
declare function supportsModelTools(model: {
  compat?: unknown;
}): boolean;
//#endregion
//#region src/agents/tool-replay-safety.d.ts
/**
 * Tool names are not ownership boundaries. Callers must reject plugin/channel
 * instances before using this audited core-tool allowlist.
 */
declare function isAgentToolReplaySafe(tool: {
  name?: string;
}, options?: {
  declaredReplaySafe?: (tool: {
    name?: string;
  }) => boolean | undefined;
}): boolean;
//#endregion
//#region src/agents/channel-tool-metadata.d.ts
type ChannelAgentToolMeta = {
  channelId: string;
};
/** Read channel metadata attached to a channel-owned agent tool. */
declare function getChannelAgentToolMeta(tool: ChannelAgentTool): ChannelAgentToolMeta | undefined;
//#endregion
//#region src/agents/skill-workshop-prompt.d.ts
/** System-prompt contribution that keeps the agent's learned (Workshop) skills current. */
declare const SKILL_WORKSHOP_TOOL_NAME = "skill_workshop";
/** Build the system-prompt section for Skill Workshop. */
declare function buildSkillWorkshopPromptSection(): string[];
//#endregion
//#region src/agents/delegation-guidance.d.ts
declare function resolveMainSessionDelegationMode(params: {
  config?: OpenClawConfig;
  agentId?: string;
  sessionKey?: string;
}): SubagentDelegationMode;
declare function buildDelegationGuidanceSection(params: {
  mode: SubagentDelegationMode;
  isMinimal: boolean;
  hiddenDelegationTool: string;
  hasVisibleSessionSpawn: boolean;
  hasSessionsYield: boolean;
  inTurnCollectionGuidance?: string;
  hasSubagentsList: boolean;
  hasSessionsSend: boolean;
  sessionsCreateToolName?: string;
  suggestTaskToolName?: string;
}): string[];
//#endregion
//#region src/agents/tools/message-tool-discovery.d.ts
type MessageToolCurrentContextOptions = {
  agentSessionKey?: string;
  sessionId?: string;
  currentChannelId?: string;
  currentChannelProvider?: string;
  currentChatType?: ChatType;
  currentMessagingTarget?: string;
};
/** Use the message tool's effective route and target defaulting for reply guidance. */
declare function hasMessageToolSourceConversation(options?: MessageToolCurrentContextOptions): boolean;
//#endregion
//#region src/agents/ui-presentation-prompt.d.ts
/** Tool eligibility and results own surface support; do not infer it from channel names. */
declare function buildUiPresentationPrompt(params: {
  screenToolName?: string;
  showWidgetToolName?: string;
  dashboardToolName?: string;
  portalToolName?: string;
  messageTool?: {
    name: string;
    parameters: unknown;
  };
}): string;
//#endregion
//#region src/auto-reply/source-reply-delivery-mode.d.ts
declare function buildHarnessVisibleReplyGuidance(params: {
  sourceReplyDeliveryMode?: string;
  messageToolAvailable: boolean;
  currentConversation: NonNullable<Parameters<typeof hasMessageToolSourceConversation>[0]>;
  requireExplicitMessageTarget?: boolean;
  messageToolFinalByDefault?: boolean;
  uiPresentation?: Parameters<typeof buildUiPresentationPrompt>[0];
}): string;
//#endregion
//#region src/agents/credential-safety-prompt.d.ts
declare function buildCredentialSafetyPrompt(
/**
 * @deprecated The legacy string argument is ignored and supported through
 * 2026-11-30. Use the options object `{ controlToolsAvailable }` instead.
 */
input?: string | {
  controlToolsAvailable?: boolean;
}): string;
//#endregion
//#region src/agents/tools/ask-user-tool-normalization.d.ts
/** Shared human-question wait contract, including credential entry and harness watchdogs. */
declare function normalizeQuestionTimeoutSeconds(rawTimeoutSeconds: unknown): number;
//#endregion
//#region src/decisions/provider-context.d.ts
/** Private prepared facts supplied only to the selected executor; never projected in results. */
type DecisionProviderContextV2 = {
  readonly model: Omit<ModelCatalogEntry, "api"> & Partial<Pick<Model, "api" | "headers">>;
  readonly config: OpenClawConfig;
  readonly agentId?: string;
  readonly workspaceDir?: string;
  readonly auth: Readonly<Pick<ResolvedProviderAuth, "apiKey" | "mode" | "profileId">>;
  readonly signal: AbortSignal;
  readonly deadlineMonotonicMs: number;
  readonly reasoning?: "auto" | "off" | "on";
  /** Check synchronously at physical dispatch, including after DNS or worker queue waits.
   * False closes this request; a thrown caller authority assertion remains terminal. */
  readonly isAdmissible: () => boolean;
};
//#endregion
//#region src/decisions/types.d.ts
/** Typed decision contract, version 1. */
type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
  readonly [key: string]: JsonValue;
};
type DecisionEntry = string | null | readonly JsonValue[] | {
  readonly [key: string]: JsonValue;
};
type DecisionQuestion = {
  readonly type: "choice";
  readonly instructions?: DecisionEntry;
  readonly criteria: Readonly<Record<string, DecisionEntry>>;
} | {
  readonly type: "score";
  readonly instructions?: DecisionEntry;
  readonly criteria: readonly DecisionEntry[];
} | {
  readonly type: "boolean";
  readonly instructions?: DecisionEntry;
  readonly criteria?: {
    readonly true?: DecisionEntry;
    readonly false?: DecisionEntry;
  } | null;
};
type DecisionBatch = {
  readonly state: DecisionEntry;
  readonly questions: Readonly<Record<string, DecisionQuestion>>;
};
type DecisionAnswer = {
  readonly type: "choice";
  /** Provider-reported label; not required to be the rounded distribution's argmax. */
  readonly choice: string;
  /** Provider-reported estimates in [0, 1]; rounding may make their sum differ from one. */
  readonly probabilities: Readonly<Record<string, number>>;
  /** Provider-specific distribution metric, not correctness probability. */
  readonly confidence?: number;
} | {
  readonly type: "score";
  /** Provider's fractional zero-based rubric estimate, bounded by its first and last positions. */
  readonly score: number;
  /** Index-aligned estimates in [0, 1]; may be rounded independently of the score. */
  readonly probabilities: readonly number[];
  readonly confidence?: number;
} | {
  readonly type: "boolean";
  readonly probabilityTrue: number;
};
type DecisionBatchResult = {
  /** Resolved vendor model identity, not a host conversational-model record. */
  readonly model: string;
  readonly answers: Readonly<Record<string, DecisionAnswer>>;
  readonly usage?: {
    readonly inputTokens?: number;
    readonly outputTokens?: number;
  };
};
type ProviderFailureReason = "credentials-unavailable" | "authentication" | "rate-limited" | "transport" | "unsupported-input" | "invalid-response";
type UnavailableReason = ProviderFailureReason | "disabled" | "not-configured" | "retiring" | "overloaded" | "circuit-open" | "deadline";
type ProviderDecisionOutcome = {
  readonly status: "ok";
  readonly result: DecisionBatchResult;
} | {
  readonly status: "unavailable";
  readonly reason: ProviderFailureReason;
  /** Validated and bounded by host; does not cause an automatic retry. */
  readonly retryAfterMs?: number;
};
type DecisionOutcome = {
  readonly status: "ok";
  readonly result: DecisionBatchResult;
  readonly provenance: {
    readonly providerId: string;
    readonly rubricVersion: string;
    /** Host-owned opaque identity; no secret values or SecretRef IDs. */
    readonly runtimeGeneration: string;
  };
} | {
  readonly status: "unavailable";
  readonly reason: UnavailableReason;
};
interface DecisionProviderV1 {
  readonly id: string;
  readonly contractVersion: 1;
  /** Prepared local credential availability only; must not perform I/O.
   * Omission leaves readiness unconfirmed without blocking evaluation. */
  isReady?(): boolean;
  evaluate(batch: DecisionBatch, context: {
    /** Explicit model selected by the host's decisionModel role. */
    readonly model: string;
    readonly agentId?: string;
    /** Composed by host from caller, per-call deadline, and retirement. */
    readonly signal: AbortSignal;
    /** Deadline on the same process-local performance.now() time base. */
    readonly deadlineMonotonicMs: number;
    /** Host-owned request admission. Check synchronously immediately before external I/O.
     * False closes this evaluation; a thrown authority assertion remains terminal.
     * Omission preserves explicit evaluations and older hosts. */
    readonly isAdmissible?: () => boolean;
  }): Promise<ProviderDecisionOutcome>;
}
/**
 * Supplied by the host, bound to its consumer's live authority/lifecycle.
 * Not a constructible global service or an unbound registry lookup.
 */
interface DecisionRuntimeV1 {
  evaluate(batch: DecisionBatch, options: {
    /** Omit for the default role; agent-owned work supplies its owner agent. */
    readonly agentId?: string;
    readonly purpose: string;
    /** Defaults to requested; optional work leaves capacity for requested evaluations. */
    readonly priority?: "requested" | "optional";
    readonly rubricVersion: string;
    /** Budget includes preparation; provider cleanup remains physically awaited. */
    readonly timeoutMs: number;
    readonly signal: AbortSignal;
  }): Promise<DecisionOutcome>;
}
//#endregion
//#region src/decisions/types-v2.d.ts
/** Explicit evidence supplied by the caller; the host collects no additional context. */
type DecisionContentV2 = {
  readonly type: "text";
  readonly text: string;
} | {
  readonly type: "json";
  readonly value: JsonValue;
} | {
  readonly type: "image";
  readonly dataUri: string;
  readonly text?: string;
} | {
  readonly type: "list";
  readonly items: readonly {
    readonly id: string;
    readonly content: DecisionEntry;
  }[];
};
type DecisionQuestionV2 = DecisionQuestion | {
  readonly type: "sort";
  readonly instructions?: DecisionEntry;
} | {
  readonly type: "box";
  readonly instructions: Exclude<DecisionEntry, null>;
} | {
  readonly type: "tags";
  readonly instructions?: DecisionEntry;
  readonly criteria: Readonly<Record<string, DecisionEntry>>;
};
type DecisionBatchV2 = {
  readonly state: DecisionContentV2;
  readonly questions: Readonly<Record<string, DecisionQuestionV2>>;
};
type DecisionAnswerV2 = ((({
  readonly type: "boolean";
} & ({
  /** Native P(true), independent from any explicit answer. */
  readonly probabilityTrue: number;
  readonly answer?: boolean | null;
} | {
  /** At least answer or probabilityTrue is required; null is explicit abstention. */
  readonly answer: boolean | null;
  readonly probabilityTrue?: number;
})) | {
  readonly type: "choice";
  readonly choice: string | null;
  /** Route-declared estimates; independent maps may be all-zero. Never normalized. */
  readonly probabilities?: Readonly<Record<string, number>>;
  /** Selected provider estimate, not derived from the map. */
  readonly probability?: number | null;
  readonly confidence?: number | null;
} | {
  readonly type: "score";
  readonly score: number;
  /** An absent distribution must not be synthesized. */
  readonly probabilities?: readonly number[];
  readonly confidence?: number | null;
} | {
  readonly type: "box";
  /** Edges normalized to image width/height, measured from the top-left corner. */
  readonly box: {
    readonly top: number;
    readonly bottom: number;
    readonly left: number;
    readonly right: number;
  };
  readonly confidence?: number | null;
} | {
  readonly type: "sort";
  readonly order: readonly string[];
  readonly confidence?: number | null;
} | {
  readonly type: "tags";
  readonly tags: readonly {
    readonly id: string;
    readonly probability?: number;
    readonly applies: boolean | null;
  }[];
}) & {
  readonly metadata?: Readonly<Record<string, JsonValue>>;
}) | {
  readonly type: "error";
  readonly code: "unsupported-input" | "invalid-input" | "provider-error";
  readonly providerCode?: string;
};
type DecisionBatchResultV2 = {
  readonly model: string;
  readonly answers: Readonly<Record<string, DecisionAnswerV2>>;
  readonly usage?: {
    readonly inputTokens?: number;
    readonly outputTokens?: number;
    readonly costUsd?: number;
    readonly units?: {
      readonly unit: "decision-units" | "requests";
      readonly amount: number;
    };
    readonly raw?: JsonValue;
  };
  readonly metadata?: Readonly<Record<string, JsonValue>>;
};
type ProviderDecisionOutcomeV2 = {
  readonly status: "ok";
  readonly result: DecisionBatchResultV2;
} | Extract<ProviderDecisionOutcome, {
  status: "unavailable";
}>;
type DecisionOutcomeV2 = {
  readonly status: "ok";
  readonly result: DecisionBatchResultV2;
  readonly provenance: Extract<DecisionOutcome, {
    status: "ok";
  }>["provenance"];
} | Extract<DecisionOutcome, {
  status: "unavailable";
}>;
/** Execution options add only provider-declared reasoning to the established caller contract. */
type DecisionEvaluateOptionsV2 = Parameters<DecisionRuntimeV1["evaluate"]>[1] & {
  readonly reasoning?: DecisionProviderContextV2["reasoning"];
};
/** Shares normal model catalog, route and credential ownership with conversational inference. */
interface DecisionProviderV2 {
  readonly id: string;
  readonly contractVersion: 2;
  /** Omit when this plugin has already registered the same normal provider. */
  readonly provider?: Omit<ProviderPlugin, "id">;
  evaluate(batch: DecisionBatchV2, context: DecisionProviderContextV2): Promise<ProviderDecisionOutcomeV2>;
}
interface DecisionRuntimeV2 extends DecisionRuntimeV1 {
  evaluateV2(batch: DecisionBatchV2, options: DecisionEvaluateOptionsV2): Promise<DecisionOutcomeV2>;
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-prompt-helpers.d.ts
declare function resolveAttemptFsWorkspaceOnly(params: {
  config?: OpenClawConfig;
  sessionAgentId: string;
}): boolean;
type AfterTurnRuntimeContextAttempt = Pick<EmbeddedRunAttemptParams, "sessionTarget" | "trigger" | "bootstrapContextRunKind" | "currentInboundEventKind" | "inputProvenance" | "spawnedBy" | "trustedInternalHandoff" | "contextEngineAgentId" | "sessionKey" | "sandboxSessionKey" | "sandboxAgentId" | "messageChannel" | "messageProvider" | "agentAccountId" | "currentChannelId" | "currentThreadTs" | "currentMessageId" | "config" | "skillsSnapshot" | "toolsAllow" | "senderId" | "provider" | "modelId" | "agentHarnessId" | "modelSelectionLocked" | "thinkLevel" | "reasoningLevel" | "bashElevated" | "extraSystemPrompt" | "ownerNumbers" | "authProfileId" | "authProfileIdSource" | "runtimePlan" | "userTurnTranscriptRecorder"> & {
  sessionId?: EmbeddedRunAttemptParams["sessionId"];
};
declare function buildAfterTurnRuntimeContext(params: {
  attempt: AfterTurnRuntimeContextAttempt;
  workspaceDir: string;
  cwd?: string;
  agentDir: string;
  activeAgentId?: string;
  contextEnginePluginId?: string;
  tokenBudget?: number;
  currentTokenCount?: number;
  promptCache?: ContextEnginePromptCacheInfo;
}): ContextEngineRuntimeContext;
declare function buildAfterTurnRuntimeContextFromUsage(params: Omit<Parameters<typeof buildAfterTurnRuntimeContext>[0], "currentTokenCount"> & {
  lastCallUsage?: NormalizedUsage;
}): ContextEngineRuntimeContext;
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-thread-helpers.d.ts
/**
 * Returns the workspace path that must be mounted for sandboxed spawn attempts.
 * Read-only sandbox modes need the resolved workspace explicitly; full rw
 * access uses the normal workspace wiring.
 */
declare function resolveAttemptSpawnWorkspaceDir(params: {
  sandbox?: {
    enabled?: boolean;
    workspaceAccess?: string;
  } | null;
  resolvedWorkspace: string;
}): string | undefined;
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-run-context.d.ts
type AttemptToolRunFacts = Pick<RunEmbeddedAgentParams, "clientCaps" | "gatewayUiCommandTarget" | "pinnedWidgetAuthoring" | "toolBindings" | "chatType" | "agentAccountId" | "messageTo" | "messageThreadId" | "chatId" | "messageActionTurnCapability" | "groupId" | "groupChannel" | "groupSpace" | "memberRoleIds" | "spawnedBy" | "senderId" | "senderName" | "senderUsername" | "senderE164" | "senderIsOwner" | "gitContributorProfileId" | "requesterOrigin" | "operatorProfileId" | "conversationId" | "scheduledToolPolicy" | "approvalReviewerDeviceId" | "currentChannelId" | "currentMessagingTarget" | "currentThreadTs" | "currentMessageId" | "replyToMode" | "hasRepliedRef" | "sourceReplyDeliveryMode" | "messageToolFinalByDefault" | "taskSuggestionDeliveryMode">;
/**
 * Builds the shared tool-run context for embedded and plugin harness attempts.
 * Pass per-run overrides separately to avoid copying the complete attempt.
 */
declare function buildEmbeddedAttemptToolRunContext(params: AttemptToolRunFacts & {
  model?: Pick<EmbeddedRunAttemptParams["model"], "provider" | "id">;
  thinkLevel?: ThinkLevel;
  thinkingExplicit?: boolean;
  trigger?: EmbeddedRunTrigger;
  jobId?: string;
  memoryFlushWritePath?: string;
  memoryFlushTools?: RunEmbeddedAgentParams["memoryFlushTools"];
  toolsAllow?: string[];
  forceMessageTool?: boolean;
  swarmCollector?: boolean;
  swarmOutputSchema?: Record<string, unknown>;
  conversationToolPolicy?: GroupToolPolicyConfig;
  trace?: DiagnosticTraceContext;
  currentInboundAudio?: boolean;
  sessionId?: string;
  sessionKey?: string;
  replyOperation?: {
    readonly acceptedSteeredInboundAudio: boolean;
  };
}, overrides?: {
  forceMessageTool?: boolean;
  trace?: DiagnosticTraceContext;
}): {
  clientCaps: string[] | undefined;
  gatewayUiCommandTarget: Readonly<{
    connId: string;
    profileId?: string;
  }> | undefined;
  pinnedWidgetAuthoring: boolean | undefined;
  toolBindings: Readonly<Record<string, unknown>> | undefined;
  chatType: ChatType | undefined;
  agentAccountId: string | undefined;
  messageTo: string | undefined;
  messageThreadId: string | number | undefined;
  nativeChannelId: string | undefined;
  messageActionTurnCapability: string | undefined;
  groupId: string | null | undefined;
  groupChannel: string | null | undefined;
  groupSpace: string | null | undefined;
  memberRoleIds: string[] | undefined;
  spawnedBy: string | null | undefined;
  senderId: string | null | undefined;
  senderName: string | null | undefined;
  senderUsername: string | null | undefined;
  senderE164: string | null | undefined;
  senderIsOwner: boolean | undefined;
  gitContributorProfileId: string | undefined;
  requesterOrigin: Readonly<{
    sessionKey: string;
    operatorProfileId?: string;
    delegatedCreatorProfileId?: string | null;
    messageProvider?: string | null;
    accountId?: string | null;
    chatType?: ChatType;
    conversationId?: string | null;
    messageThreadId?: string | number | null;
    groupId?: string | null;
    groupChannel?: string | null;
    groupSpace?: string | null;
    senderId?: string | null;
    senderName?: string | null;
    senderUsername?: string | null;
    senderE164?: string | null;
  }> | undefined;
  operatorProfileId: string | undefined;
  conversationId: string | null | undefined;
  scheduledToolPolicy: ScheduledToolPolicyContext | undefined;
  approvalReviewerDeviceId: string | undefined;
  currentChannelId: string | undefined;
  currentMessagingTarget: string | undefined;
  currentThreadTs: string | undefined;
  currentMessageId: string | number | undefined;
  replyToMode: "all" | "batched" | "first" | "off" | undefined;
  hasRepliedRef: {
    value: boolean;
  } | undefined;
  sourceReplyDeliveryMode: SourceReplyDeliveryMode | undefined;
  messageToolFinalByDefault: boolean | undefined;
  taskSuggestionDeliveryMode: "gateway" | undefined;
  requesterThinkingLevel: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
  requesterThinkingExplicit: boolean | undefined;
  requesterModel: {
    provider: string;
    model: string;
  } | undefined;
  trigger: EmbeddedRunTrigger | undefined;
  jobId: string | undefined;
  memoryFlushWritePath: string | undefined;
  memoryFlushTools: MemoryFlushToolRunContext | undefined;
  swarmCollector: boolean | undefined;
  swarmOutputSchema: Record<string, unknown> | undefined;
  currentInboundAudio: boolean | undefined;
  hasCurrentInboundAudio: () => boolean;
  runtimeToolAllowlist?: string[] | undefined;
  conversationToolPolicy?: {
    allow?: string[] | undefined;
    alsoAllow?: string[] | undefined;
    deny?: string[] | undefined;
  } | undefined;
  trace?: DiagnosticTraceContext | undefined;
};
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-tool-construction-plan.d.ts
/**
 * Applies a runtime allowlist to a concrete tool list after expanding tool and
 * plugin groups. Undefined allowlists keep all tools; an explicit empty list
 * intentionally disables all runtime tools.
 */
declare function applyEmbeddedAttemptToolsAllow<T extends {
  name: string;
}>(tools: T[], toolsAllow?: string[], options?: {
  toolMeta?: (tool: T) => {
    pluginId: string;
  } | undefined;
  toolAliases?: (tool: T) => readonly string[];
}): T[];
/**
 * Decides which tool families need to be constructed for an embedded attempt.
 * This keeps allowlisted plugin/channel tools available without forcing every
 * local core tool factory to run for narrow plugin-only configurations.
 */
declare function resolveEmbeddedAttemptToolConstructionPlan(params: {
  disableTools?: boolean;
  isRawModelRun?: boolean;
  toolsEnabled?: boolean;
  toolsAllow?: string[];
  forceMessageTool?: boolean;
}): {
  constructTools: boolean;
  includeCoreTools: boolean;
  runtimeToolAllowlist?: string[];
  codingToolConstructionPlan: OpenClawCodingToolConstructionPlan;
};
//#endregion
//#region src/plugins/tool-metadata.d.ts
/** MCP bridge metadata attached to plugin tools surfaced through agent tool lists. */
type PluginToolMcpMeta = {
  serverName: string;
  safeServerName: string;
  toolName: string;
  operation: "tool" | "resources_list" | "resources_read" | "prompts_list" | "prompts_get";
  excludedFromOpenClawCatalog?: true;
  deniedBySession?: true;
  /** Server-level instructions advertised by this tool's MCP server, if any. */
  instructions?: string;
  /** Trusted requester OAuth sign-in bootstrap; exempt from per-call MCP approval. */
  oauthConnectBootstrap?: true;
  codexApproval?: {
    mode?: McpCodexToolApprovalMode;
    annotations?: McpCodexToolAnnotations;
  };
  node?: {
    id: string;
    displayName?: string;
  };
};
/** Runtime metadata used to trace an agent tool back to its owning plugin registration. */
type PluginToolMeta = {
  pluginId: string;
  kind?: PluginManifestRecord["kind"];
  optional: boolean;
  workspaceAccess?: boolean | "execute";
  replaySafe?: boolean;
  sideEffecting?: boolean;
  trustedLocalMedia?: boolean;
  mcp?: PluginToolMcpMeta;
};
/** Reads plugin ownership metadata for a concrete agent tool instance. */
declare function getPluginToolMeta(tool: AnyAgentTool): PluginToolMeta | undefined;
/** Binds a side-effect declaration to the concrete plugin tool that owns it. */
declare function getPluginToolSideEffectOwnerKey(tool: AnyAgentTool): string | undefined;
//#endregion
//#region src/agents/agent-tool-availability.d.ts
type ToolDefinition = Pick<AnyAgentTool, "name" | "parameters" | "description">;
/** Finalize owner-controlled affordances after filtering; never rebind or grant tools. */
declare function finalizeAgentToolAvailability<T extends ToolDefinition>(tools: readonly T[], options?: {
  toolExecutionAllow?: readonly string[];
  onPrepared?: (tool: T) => void;
  beforeNormalization?: true;
}): T[];
//#endregion
//#region src/agents/harness/registry.d.ts
declare function disposeRegisteredAgentHarnesses(): Promise<void>;
//#endregion
//#region src/agents/embedded-agent-runner/tool-schema-runtime.d.ts
type ProviderToolSchemaParams<TSchemaType extends TSchema = TSchema, TResult = unknown> = {
  tools: AgentTool<TSchemaType, TResult>[];
  provider: string;
  config?: OpenClawConfig;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  modelId?: string;
  modelApi?: string | null;
  model?: ProviderRuntimeModel;
  runtimeHandle?: ProviderRuntimePluginHandle;
  allowRuntimePluginLoad?: boolean;
};
/**
 * Runs provider-owned tool-schema normalization without encoding provider
 * families in the embedded runner.
 */
declare function normalizeProviderToolSchemas<TSchemaType extends TSchema = TSchema, TResult = unknown>(params: ProviderToolSchemaParams<TSchemaType, TResult>): AgentTool<TSchemaType, TResult>[];
//#endregion
//#region src/agents/tool-schema-projection.d.ts
type RuntimeToolSchemaDiagnostic = {
  readonly toolName: string;
  readonly toolIndex: number;
  readonly violations: readonly string[];
};
/** Runtime tool list split into compatible tools and schema diagnostics. */
type RuntimeToolSchemaInspection<TTool extends Pick<AnyAgentTool, "name" | "parameters">> = {
  readonly tools: TTool[];
  readonly diagnostics: readonly RuntimeToolSchemaDiagnostic[];
};
/** Inspects runtime tool schemas and returns diagnostics without filtering tools. */
declare function inspectRuntimeToolInputSchemas(tools: readonly Pick<AnyAgentTool, "name" | "parameters">[]): RuntimeToolSchemaDiagnostic[];
/** Filters tools to those that providers can normalize before dispatch. */
declare function filterProviderNormalizableTools<TTool extends Pick<AnyAgentTool, "name" | "parameters">>(tools: readonly TTool[]): RuntimeToolSchemaInspection<TTool>;
//#endregion
//#region src/agents/runtime-plan/tools.d.ts
type AgentRuntimeToolPolicyParams<TSchemaType extends TSchema = TSchema, TResult = unknown> = Omit<Parameters<typeof normalizeProviderToolSchemas<TSchemaType, TResult>>[0], "allowRuntimePluginLoad"> & {
  runtimePlan?: AgentRuntimePlan;
  allowProviderRuntimePluginLoad?: boolean;
  /**
   * Invoked on every normalization, including with an empty list, so
   * consumers can observe the all-clear and retire stale quarantine state.
   */
  onPreNormalizationSchemaDiagnostics?: (diagnostics: readonly RuntimeToolSchemaDiagnostic[], tools: readonly AgentTool<TSchemaType, TResult>[]) => void;
};
declare function normalizeAgentRuntimeTools<TSchemaType extends TSchema = TSchema, TResult = unknown>(params: Omit<AgentRuntimeToolPolicyParams<TSchemaType, TResult>, "tools"> & {
  tools: readonly AgentTool<TSchemaType, TResult>[];
}): AgentTool<TSchemaType, TResult>[];
declare function logAgentRuntimeToolDiagnostics(params: AgentRuntimeToolPolicyParams): void;
//#endregion
//#region src/agents/bundle-mcp-adapter.d.ts
declare function decodeHeaderEnvPlaceholder(value: string): {
  envVar: string;
  bearer: boolean;
} | null;
//#endregion
//#region src/agents/agent-bundle-mcp-names.d.ts
/**
 * Assign safe server names from the full declared set in declaration order,
 * independent of which servers resolve for a requester. Declaration order
 * preserves legacy collision-suffix ownership for existing static configs;
 * sorting here would silently swap safe names between colliding servers.
 */
declare function assignSafeServerNames(serverNames: Iterable<string>): Map<string, string>;
//#endregion
//#region src/agents/sandbox/context.d.ts
type ResolveSandboxContextParams = {
  config?: OpenClawConfig;
  agentId?: string;
  execOverrides?: ExecPolicyOverrides;
  requireCurrentConfig?: boolean;
  assertCurrent?: () => void;
  abortSignal?: AbortSignal;
  admittedRunContext?: AdmittedRunContext;
  sessionKey?: string;
  skillsSnapshot?: SkillSnapshot;
  workspaceDir?: string;
  /** Classification already prepared for this session's workspace setup. */
  preparedRuntimeStatus?: ReturnType<typeof resolveSandboxRuntimeStatus>;
};
declare function resolveSandboxContext(params: ResolveSandboxContextParams): Promise<SandboxContext | null>;
//#endregion
//#region src/agents/sandbox/bind-spec.d.ts
/**
 * Parser for Docker-style host:container[:options] bind specs.
 */
/** Splits a bind spec while preserving Windows drive-letter prefixes in host paths. */
declare function splitSandboxBindSpec(spec: string, options?: {
  allowWindowsContainerPath?: boolean;
}): {
  host: string;
  container: string;
  options: string;
} | null;
//#endregion
//#region src/agents/sandbox/fs-paths.d.ts
declare function resolveWritableSandboxBindHostRoots(binds: readonly string[] | undefined): string[];
declare function hasSandboxBindContainerPathAliases(binds: readonly string[] | undefined): boolean;
declare function hasSandboxBindReadonlyHostShadows(binds: readonly string[] | undefined): boolean;
//#endregion
//#region src/agents/embedded-agent-helpers/context-file.d.ts
/** Context file passed into embedded agents as preloaded workspace content. */
type EmbeddedContextFile = {
  path: string;
  content: string;
  /** Preserved from authenticated bootstrap selection across workspace remapping. */
  personalUser?: true;
};
//#endregion
//#region src/config/sessions/session-system-prompt-report.d.ts
/** Persisted size and provenance summary for one assembled system prompt. */
type SessionSystemPromptReport = {
  source: "run" | "estimate";
  generatedAt: number;
  sessionId?: string;
  sessionKey?: string;
  provider?: string;
  model?: string;
  workspaceDir?: string;
  bootstrapMaxChars?: number;
  bootstrapTotalMaxChars?: number;
  bootstrapTruncation?: {
    warningMode?: "off" | "once" | "always";
    warningShown?: boolean;
    promptWarningSignature?: string;
    warningSignaturesSeen?: string[];
    truncatedFiles?: number;
    nearLimitFiles?: number;
    totalNearLimit?: boolean;
  };
  sandbox?: {
    mode?: string;
    sandboxed?: boolean;
  };
  systemPrompt: {
    chars: number;
    projectContextChars: number;
    nonProjectContextChars: number;
    hash?: string;
  };
  currentTurn?: {
    kind?: "user_request" | "room_event";
    promptChars: number;
    runtimeContextChars: number;
    modelOnlyPromptChars?: number;
  };
  injectedWorkspaceFiles: Array<{
    name: string;
    path: string;
    origin?: {
      kind: "agent-workspace" | "execution-project" | "personal" | "other";
      rootPath?: string;
    };
    missing: boolean;
    rawChars: number;
  } & ({
    injectionStatus?: "verified";
    injectedChars: number;
    truncated: boolean;
  } | {
    injectionStatus: "native_unverified";
    injectedChars: null;
    truncated: null;
  })>;
  skills: {
    promptChars: number;
    hash?: string;
    entries: Array<{
      name: string;
      blockChars: number;
    }>;
  };
  tools: {
    listChars: number;
    schemaChars: number;
    entries: Array<{
      name: string;
      source?: "openclaw" | "mcp" | "client";
      sourceName?: string;
      serverName?: string;
      summaryChars: number;
      summaryHash?: string;
      schemaChars: number;
      schemaHash?: string;
      propertiesCount?: number | null;
    }>;
    /** Available schemas, not part of the consumed schemaChars total. */
    deferred?: {
      /** Sum of known sizes; entries with null sizes remain unmeasured. */
      schemaChars: number;
      entries: Array<{
        name: string;
        source: "openclaw" | "mcp" | "client";
        sourceName?: string;
        serverName?: string;
        schemaChars: number | null;
      }>;
    };
  };
};
//#endregion
//#region src/agents/workspace-bootstrap-policy.d.ts
/**
 * Canonical bootstrap filenames in prompt order. Single source for the runtime
 * validation set, the name union, and the Control UI core-files list; a private
 * copy anywhere else silently drifts when a file is retired.
 */
declare const WORKSPACE_BOOTSTRAP_FILENAMES: readonly ["AGENTS.md", "SOUL.md", "IDENTITY.md", "USER.md", "BOOTSTRAP.md", "MEMORY.md"];
type WorkspaceBootstrapFileName = (typeof WORKSPACE_BOOTSTRAP_FILENAMES)[number];
type WorkspaceBootstrapFile = {
  name: WorkspaceBootstrapFileName;
  path: string;
  content?: string;
  missing: boolean;
  /** Set only by the authenticated personal USER loader, never inferred from a path. */
  personalUser?: true;
  origin?: SessionSystemPromptReport["injectedWorkspaceFiles"][number]["origin"];
};
/** Restrict a workspace adapter to native bootstrap reads and owner-document writes. */
declare function createWorkspaceBootstrapFilePolicy(params: {
  workspaceDir: string;
  config?: OpenClawConfig;
}): {
  canRead: (relativePath: string) => boolean;
  canList: (relativePath: string) => boolean;
  canWrite: (relativePath: string) => boolean;
};
//#endregion
//#region src/agents/workspace.d.ts
type EnsureAgentWorkspaceParams = {
  dir?: string;
  ensureBootstrapFiles?: boolean;
  /** Approved custom-agent instructions; never replaces an existing AGENTS.md. */
  purpose?: string;
  /** Creation-time role content; existing workspace files are still preserved. */
  templates?: Partial<Record<"AGENTS.md" | "SOUL.md" | "IDENTITY.md", string>>;
  /** Guard each new mutation after async preparation; admitted effects may settle. */
  guard?: WorkspaceStateGuard;
  /**
   * List of optional bootstrap filenames to skip writing.
   * Applies only to SOUL.md, USER.md, IDENTITY.md.
   * Required workspace setup such as AGENTS.md still runs.
   */
  skipOptionalBootstrapFiles?: string[];
  /**
   * Workspace provisioning mode. "runtime-managed-implicit" marks a workspace
   * owned by a runtime-managed (ACP) agent without an explicit workspace and
   * with a distinct authoritative cwd: only the directory is provisioned, and
   * bootstrap files, workspace setup state, and `git init` are skipped (#92015).
   */
  provisioning?: "standard" | "runtime-managed-implicit";
};
type EnsuredAgentWorkspace = {
  dir: string;
  agentsPath?: string;
  soulPath?: string;
  identityPath?: string;
  userPath?: string;
  bootstrapPath?: string;
  bootstrapPending?: boolean;
  identityPathCreated?: boolean;
};
declare function ensureAgentWorkspace(params?: EnsureAgentWorkspaceParams): Promise<EnsuredAgentWorkspace>;
//#endregion
//#region src/agents/bootstrap-files.d.ts
type BootstrapContextMode = "full" | "lightweight";
/** Resolves hook-adjusted, session-filtered bootstrap files for a run. */
type BootstrapFileResolutionParams = {
  bootstrapUserProfileId?: string;
  workspaceDir: string;
  executionWorkspaceDir?: string;
  config?: OpenClawConfig;
  sessionKey?: string;
  sessionId?: string;
  chatType?: ChatType;
  agentId?: string;
  warn?: (message: string) => void;
  contextMode?: BootstrapContextMode;
  runKind?: BootstrapContextRunKind;
  readOnlyState?: boolean;
};
declare function resolveBootstrapFilesForRun(params: BootstrapFileResolutionParams): Promise<WorkspaceBootstrapFile[]>;
/** Resolves both raw bootstrap metadata and bounded context files for a run. */
declare function resolveBootstrapContextForRun(params: BootstrapFileResolutionParams): Promise<{
  bootstrapFiles: WorkspaceBootstrapFile[];
  contextFiles: EmbeddedContextFile[];
}>;
//#endregion
//#region src/agents/embedded-agent-helpers/bootstrap.d.ts
/** Builds bounded context files from already-resolved bootstrap file metadata. */
declare function buildBootstrapContextForFiles(bootstrapFiles: WorkspaceBootstrapFile[], params: {
  config?: OpenClawConfig;
  agentId?: string | null;
  warn?: (message: string) => void;
}): EmbeddedContextFile[];
//#endregion
//#region src/agents/harness/workspace-instructions.d.ts
/** Projects already-bounded agent instructions without changing bootstrap budgets. */
declare function buildAgentWorkspaceInstructionSnapshot(contextFiles: readonly EmbeddedContextFile[], workspaceDir: string): {
  files: EmbeddedContextFile[];
  instructions: string;
};
//#endregion
//#region src/agents/harness/workspace-context.d.ts
type BootstrapFile = Awaited<ReturnType<typeof resolveBootstrapFilesForRun>>[number];
type AgentWorkspaceContextParams = Parameters<typeof resolveBootstrapFilesForRun>[0] & {
  scope: "full" | "instructions-only";
  memoryToolRouted?: boolean;
  memoryTools?: {
    /** Complete policy-admitted tool set available to the active memory prompt builder. */
    toolNames: readonly string[];
    citationsMode?: Parameters<typeof prepareMemorySystemPromptAddition>[0]["citationsMode"];
    sandboxed?: boolean;
  };
  projectPath?: (filePath: string) => string;
  nativeProjectDocBasenames?: ReadonlySet<string>;
  contextFileOrder?: ReadonlyMap<string, number>;
  promptMemoryWorkspaceDir?: string;
  onMemoryPreparationError?: (error: unknown) => void;
};
type AgentWorkspaceContext = {
  bootstrapFiles: BootstrapFile[];
  contextFiles: EmbeddedContextFile[];
  instructionSnapshot: ReturnType<typeof buildAgentWorkspaceInstructionSnapshot>;
  personaFiles: EmbeddedContextFile[];
  personaInstructions?: string;
  /** Safe for carriers inherited by delegated agents; excludes selected personal profiles. */
  sharedPersonaInstructions?: string;
  promptContextFiles: EmbeddedContextFile[];
  memoryReferenceFiles: EmbeddedContextFile[];
  memoryToolRoutedBootstrapFiles: BootstrapFile[];
  memoryRecallInstructions?: string;
};
/** Prepares Gateway workspace facts; the harness owns their native carriers and lifetime. */
declare function prepareAgentWorkspaceContext(params: AgentWorkspaceContextParams): Promise<AgentWorkspaceContext>;
//#endregion
//#region src/plugin-sdk/session-write-lock-runtime.d.ts
/**
 * @deprecated Session write leases were removed. This compatibility type is scheduled for
 * removal in the 2026.10 release train; use the session lane and durable writer claim/fence.
 */
type SessionWriteLockAcquireTimeoutConfig = OpenClawConfig;
type LockParams = {
  sessionFile: string;
  timeoutMs?: number;
  staleMs?: number;
  maxHoldMs?: number;
  signal?: AbortSignal;
} & ({
  targetKind: "session-key";
  allowReentrant?: boolean;
  reentrantOwner?: never;
} | {
  targetKind?: "file";
  reentrantOwner?: string;
  allowReentrant?: never;
});
/**
 * @deprecated Session write leases were removed. This compatibility stub is scheduled for
 * removal in the 2026.10 release train; use the session lane and durable writer claim/fence.
 */
declare function resolveSessionWriteLockAcquireTimeoutMs(_config?: SessionWriteLockAcquireTimeoutConfig, _env?: NodeJS.ProcessEnv): number;
/**
 * @deprecated Session write leases were removed. This compatibility stub is scheduled for
 * removal in the 2026.10 release train; use the session lane and durable writer claim/fence.
 */
declare function resolveSessionWriteLockOptions(_config?: SessionWriteLockAcquireTimeoutConfig, _params?: {
  env?: NodeJS.ProcessEnv;
  maxHoldMsFallback?: number;
}): {
  timeoutMs: number;
  staleMs: number;
  maxHoldMs: number;
};
/**
 * @deprecated Session write leases were removed. This no-op compatibility stub is scheduled
 * for removal in the 2026.10 release train; use the session lane and durable writer claim/fence.
 */
declare function acquireSessionWriteLock(_params: LockParams): Promise<{
  assertOwned: () => void;
  release: () => Promise<void>;
}>;
//#endregion
//#region src/agents/tool-mutation.d.ts
/** Return true only for tool calls whose structured contract proves replay safety. */
declare function isReplaySafeToolCall(toolName: string, args: unknown): boolean;
//#endregion
//#region src/agents/harness/hook-context.d.ts
/**
 * Only stable run/session/model facts are forwarded to plugin hooks; config remains a local
 * construction input so hooks do not accidentally depend on mutable raw configuration.
 */
type AgentHarnessHookContext = Omit<PluginHookAgentContext, "activeProjectKeys" | "senderExternalId" | "toolAuthority" | "hookInvocation" | "assertMemoryAudienceCurrent"> & {
  config?: OpenClawConfig;
};
//#endregion
//#region src/agents/harness/prompt-compaction-hook-helpers.d.ts
type AgentHarnessPromptBuildResult = {
  prompt: string;
  developerInstructions: string;
  /** Stable policy and per-turn context for harnesses with separate instruction carriers. */
  threadDeveloperInstructions?: string;
  turnDeveloperInstructions?: string;
  /** Optional per-turn tool restriction requested by before_prompt_build hooks. */
  toolsAllow?: string[];
  /** Span within prompt containing the original prompt input. */
  promptInputRange?: {
    start: number;
    end: number;
  };
};
type AgentHarnessDeveloperInstructionBuilder = {
  build: (params: {
    toolsAllow?: string[];
    hasToolRestrictions: boolean;
  }) => string | undefined;
};
declare function resolveAgentHarnessBeforePromptBuildResult(params: {
  prompt: string;
  currentInboundContext?: CurrentInboundPromptContext;
  currentUserMessage?: string | Pick<PersistedUserTurnMessage, "content" | "idempotencyKey">;
  currentUserMessageId?: string;
  developerInstructions: string | AgentHarnessDeveloperInstructionBuilder;
  messages: unknown[] | (() => Promise<unknown[]>);
  ctx: AgentHarnessHookContext;
  bootstrapContextRunKind?: BootstrapContextRunKind;
  toolAuthority?: {
    fingerprint?: string;
    activeToolNames: () => readonly string[];
    assertActive: () => void;
  };
}): Promise<AgentHarnessPromptBuildResult>;
/** Runs best-effort before-compaction hooks for a harness session. */
declare function runAgentHarnessBeforeCompactionHook(params: {
  sessionFile: string;
  messages?: AgentMessage[];
  ctx: AgentHarnessHookContext;
}): Promise<void>;
/** Runs best-effort after-compaction hooks for a harness session. */
declare function runAgentHarnessAfterCompactionHook(params: {
  sessionFile: string;
  messages?: AgentMessage[];
  ctx: AgentHarnessHookContext;
  compactedCount: number;
}): Promise<void>;
//#endregion
//#region src/agents/harness/codex-app-server-extensions.d.ts
/** Retained for published Codex plugins; new transforms use runtime-neutral middleware. */
declare function createCodexAppServerToolResultExtensionRunner(ctx: CodexAppServerExtensionContext, factories?: CodexAppServerExtensionFactory[]): {
  applyToolResultExtensions(event: CodexAppServerToolResultEvent): Promise<AgentToolResult<unknown>>;
};
//#endregion
//#region src/agents/harness/tool-result-middleware.d.ts
declare function createAgentToolResultMiddlewareRunner(ctx: AgentToolResultMiddlewareContext, handlers?: AgentToolResultMiddleware[]): {
  applyToolResultMiddleware(event: AgentToolResultMiddlewareEvent): Promise<OpenClawAgentToolResult>;
};
//#endregion
//#region src/agents/harness/context-engine-lifecycle.d.ts
type HarnessRuntimeSettingsParams = HarnessSourceScope & {
  runtimeSettings?: ContextEngineRuntimeSettings;
  contextEngineHostSupport?: ContextEngineHostSupport;
  harnessId?: string | null;
  runtimeId?: string | null;
  providerId?: string | null;
  requestedModelId?: string | null;
  modelId?: string | null;
  modelFamily?: string | null;
  tokenBudget?: number | null;
  maxOutputTokens?: number | null;
  fallbackReason?: string | null;
  degradedReason?: string | null;
  contextEngine?: ContextEngine;
};
type HarnessSourceScope = {
  admittedRunContext?: AdmittedRunContext;
  preparedRunAdmission?: PreparedAgentRunAdmission;
};
declare function bootstrapHarnessContextEngine(params: Omit<HarnessRuntimeSettingsParams, "modelFamily"> & {
  hadSessionFile: boolean;
  sessionId: string;
  sessionKey?: string;
  sessionTarget?: ContextEngineSessionTarget;
  sessionFile: string;
  sessionManager?: unknown;
  runtimeContext?: ContextEngineRuntimeContext;
  transcriptReadFence?: UserTurnTranscriptAdmissionReceipt;
  runMaintenance?: typeof runHarnessContextEngineMaintenance;
  config?: OpenClawConfig;
  warn: (message: string) => void;
}): Promise<void>;
type HarnessContextEngineAssemblyParams = Omit<HarnessRuntimeSettingsParams, "modelId" | "tokenBudget"> & {
  sessionId: string;
  sessionKey?: string;
  agentId?: string;
  appendOnlyRuntimeContext?: boolean;
  clearsTurnScopedSystemUpdates?: boolean;
  messages: AgentMessage[];
  tokenBudget?: number;
  availableTools?: Set<string>;
  citationsMode?: MemoryCitationsMode;
  sandboxed?: boolean;
  /** Current repository identity passed to memory prompt sections. */
  memoryProjectKey?: string;
  modelId: string;
  prompt?: string;
  runtimeContext?: ContextEngineRuntimeContext;
  transcriptReadFence?: UserTurnTranscriptAdmissionReceipt;
  promptBudget?: {
    contextTokens?: number;
    reserveTokens: number;
    inputTokens?: number;
    systemPrompt: string;
    prompt: string;
  };
};
declare function assembleHarnessContextEngine(params: HarnessContextEngineAssemblyParams): Promise<AssembleResult | undefined>;
declare function finalizeHarnessContextEngineTurn(params: Omit<HarnessRuntimeSettingsParams, "modelFamily" | "tokenBudget"> & {
  promptError: boolean;
  aborted: boolean;
  yieldAborted: boolean;
  sessionIdUsed: string;
  sessionKey?: string;
  sessionTarget?: ContextEngineSessionTarget;
  sessionFile: string;
  messagesSnapshot: AgentMessage[];
  prePromptMessageCount: number;
  tokenBudget?: number;
  runtimeContext?: ContextEngineRuntimeContext;
  runMaintenance?: typeof runHarnessContextEngineMaintenance;
  sessionManager?: unknown;
  config?: OpenClawConfig;
  warn: (message: string) => void;
  modelContextWindow?: number;
  abortSignal?: AbortSignal;
  turnCandidate?: {
    admission?: UserTurnTranscriptAdmissionReceipt;
    terminalEntryId?: string | null;
    [completedTurnMessageAnchor]?: CompletedTurnMessageAnchor;
    record: (facts: ContextEngineTurnAttemptFacts) => void;
  };
}): Promise<{
  postTurnFinalizationSucceeded: boolean;
}>;
declare function runHarnessContextEngineMaintenance(params: Omit<HarnessRuntimeSettingsParams, "modelFamily"> & {
  sessionId: string;
  sessionKey?: string;
  sessionTarget?: ContextEngineSessionTarget;
  sessionFile: string;
  reason: "bootstrap" | "compaction" | "turn";
  sessionManager?: unknown;
  runtimeContext?: ContextEngineRuntimeContext;
  executionMode?: "foreground" | "background";
  onDeferredMaintenance?: (promise: Promise<void>) => void;
  withSessionManagerRewriteLock?: <T>(operation: () => Promise<T> | T) => Promise<T>;
  config?: OpenClawConfig;
}): Promise<TranscriptRewriteResult | undefined>;
declare function isActiveHarnessContextEngine(contextEngine: ContextEngine | undefined): contextEngine is ContextEngine;
//#endregion
//#region src/agents/embedded-agent-runner/compaction-safety-timeout.d.ts
declare function resolveCompactionTimeoutMs(cfg?: OpenClawConfig): number;
declare function compactWithSafetyTimeout<T>(compact: (abortSignal: AbortSignal | undefined, resetTimeout: () => void) => Promise<T>, timeoutMs?: number, opts?: {
  abortSignal?: AbortSignal;
  onCancel?: () => void;
  /** Epoch ms ceiling; defaults to COMPACTION_CEILING_WINDOWS windows from now. */
  deadlineAt?: number;
}): Promise<T>;
type ContextEngineCompactParams = Parameters<ContextEngine["compact"]>[0];
/**
 * Built-in delegation and engines declaring onProgress may refresh the host
 * window. Both share the composed cancellation signal and finite ceiling.
 */
declare function compactContextEngineWithSafetyTimeout(contextEngine: Pick<ContextEngine, "compact" | "info">, params: ContextEngineCompactParams, timeoutMs?: number, abortSignal?: AbortSignal): Promise<CompactResult>;
//#endregion
//#region src/agents/context-pressure.d.ts
/**
 * Sole owner of context-pressure decisions.
 *
 * Only a request that cannot fit the model window may fail a turn. Every other
 * pressure signal (reserve thresholds, measured occupancy, provider soft
 * triggers) can only schedule maintenance, and maintenance runs only at a
 * boundary where the current tool batch can continue afterwards.
 *
 * | request > window | maintenance due | boundary safe | declined this run | decision      |
 * |------------------|-----------------|---------------|-------------------|---------------|
 * | yes              | any             | any           | any               | "overflow"    |
 * | no               | yes             | yes           | no                | "maintenance" |
 * | no               | yes             | yes           | yes               | send          |
 * | no               | yes             | no            | any               | send (defer)  |
 * | no               | no              | any           | any               | send          |
 *
 * "overflow" may end in a failed turn when recovery cannot make the request
 * fit. "maintenance" compacts and then always continues the same turn,
 * whatever the compaction outcome.
 */
type ContextPressure = "overflow" | "maintenance";
//#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/preemptive-compaction.d.ts
declare const PREEMPTIVE_OVERFLOW_ERROR_TEXT = "Context overflow: prompt too large for the model (precheck).";
type CompactionPressureDecision = {
  route: PreemptiveCompactionRoute;
  shouldCompact: boolean;
  estimatedPromptTokens: number;
  pressureSource?: string;
  promptBudgetBeforeReserve: number;
  overflowTokens: number;
  toolResultReducibleChars: number;
  effectiveReserveTokens: number;
};
/** Diagnostic maximum plus the independently selected outgoing checkpoint's budget. */
type PreemptiveCompactionDecision = CompactionPressureDecision & {
  compactionReplay?: CompactionPressureDecision;
};
type CompactionReplayPressureContext = {
  model: Model;
  sessionId?: string;
  enabled?: boolean;
};
/** Token pressure reported by the rendered provider-boundary prompt when available. */
type LlmBoundaryTokenPressure = {
  estimatedPromptTokens: number;
  source: string;
  renderedChars?: number;
};
/** Estimates only the rendered prompt/system portion when history has already been accounted for. */
declare function estimateRenderedLlmBoundaryTokenPressure(params: {
  systemPrompt?: string;
  prompt: string;
}): number;
/**
 * Decides whether a run should compact before submitting the prompt, and
 * whether reducible tool results can avoid or follow compaction. Rendered LLM
 * boundary pressure wins over local transcript estimates when supplied.
 */
declare function shouldPreemptivelyCompactBeforePrompt(params: {
  messages: AgentMessage[];
  unwindowedMessages?: AgentMessage[];
  systemPrompt?: string;
  prompt: string;
  contextTokenBudget: number;
  reserveTokens: number;
  toolResultMaxChars?: number;
  estimateRecoverableToolResultChars?: () => number;
  toolSchemaTokens?: number;
  llmBoundaryTokenPressure?: LlmBoundaryTokenPressure;
  replay?: CompactionReplayPressureContext;
}): PreemptiveCompactionDecision;
declare function formatPrePromptPrecheckLog(params: {
  result: PreemptiveCompactionDecision;
  sessionKey?: string;
  sessionId?: string;
  provider: string;
  modelId: string;
  messageCount: number;
  unwindowedMessageCount?: number;
  contextTokenBudget: number;
  reserveTokens: number;
  sessionFile?: string;
}): string;
//#endregion
//#region src/context-engine/registry.d.ts
/**
 * Return the trusted plugin id that registered a resolved context engine.
 * Downgraded engines intentionally report no plugin owner.
 */
declare function resolveContextEngineOwnerPluginId(engine: ContextEngine | undefined | null): string | undefined;
//#endregion
//#region src/agents/harness/hook-helpers.d.ts
/** Runs best-effort after-tool-call hooks for a completed tool invocation. */
declare function runAgentHarnessAfterToolCallHook(params: {
  toolName: string;
  toolCallId: string;
  runId?: string;
  agentId?: string;
  sessionId?: string;
  sessionKey?: string;
  channelId?: string;
  startArgs: Record<string, unknown>;
  result?: unknown;
  error?: string;
  startedAt?: number;
}): Promise<void>;
/** Runs before-message-write hooks and returns the possibly rewritten message. */
declare function runAgentHarnessBeforeMessageWriteHook(params: {
  message: AgentMessage;
  agentId?: string;
  sessionKey?: string;
  prepareAssistantTranscriptMessage?: PrepareAssistantTranscriptMessage;
  skipBeforeMessageWriteHooks?: boolean;
}): AgentMessage | null;
//#endregion
//#region src/agents/harness/lifecycle-hook-helpers.d.ts
type AgentHarnessHookRunner = ReturnType<typeof getGlobalHookRunner>;
type AgentHarnessHookParams<Event> = {
  event: Event;
  ctx: AgentHarnessHookContext;
  hookRunner?: AgentHarnessHookRunner;
};
declare function getAgentHarnessHookRunner(): AgentHarnessHookRunner;
/** Dispatches best-effort LLM input hooks for a harness attempt. */
declare function runAgentHarnessLlmInputHook(params: AgentHarnessHookParams<PluginHookLlmInputEvent>): void;
/** Dispatches best-effort LLM output hooks for a harness attempt. */
declare function runAgentHarnessLlmOutputHook(params: AgentHarnessHookParams<PluginHookLlmOutputEvent>): void;
/** Starts agent_end hooks with unref timeout behavior. */
declare function runAgentHarnessAgentEndHook(params: AgentHarnessHookParams<PluginHookAgentEndEvent>): void;
/** Runs agent_end hooks and waits for completion. */
declare function awaitAgentHarnessAgentEndHook(params: AgentHarnessHookParams<PluginHookAgentEndEvent>): Promise<void>;
type AgentHarnessBeforeAgentFinalizeOutcome = {
  action: "continue";
} | {
  action: "revise";
  reason: string;
} | {
  action: "finalize";
  reason?: string;
};
/** Runs before-finalize hooks and normalizes finalize/revise/continue decisions. */
declare function runAgentHarnessBeforeAgentFinalizeHook(params: AgentHarnessHookParams<PluginHookBeforeAgentFinalizeEvent>): Promise<AgentHarnessBeforeAgentFinalizeOutcome>;
//#endregion
//#region src/agents/harness/agent-end-side-effects.d.ts
type BaseAgentEndSideEffectsParams = Parameters<typeof runAgentHarnessAgentEndHook>[0];
type AgentEndSideEffectsParams = Omit<BaseAgentEndSideEffectsParams, "ctx"> & {
  [completedTurnMessageAnchor]?: CompletedTurnMessageAnchor;
  /** Exact completed-turn boundary; context loading stays off the foreground path. */
  skillExperienceReviewSource?: Pick<TranscriptEntryAnchor, "agentId" | "sessionId" | "sessionKey" | "storePath" | "entryId">;
  ctx: BaseAgentEndSideEffectsParams["ctx"] & {
    authProfileId?: string;
    modelIterations?: number;
    modelContextWindowTokens?: number;
    skillWorkshopAvailable?: boolean;
    compacted?: boolean;
    foregroundPromptContext?: EmbeddedForegroundPromptContext;
  };
};
/** @deprecated Await runAgentEndSideEffectsAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function runAgentEndSideEffects(params: AgentEndSideEffectsParams): void;
/** Keep the turn lease through anchor preparation, then start plugin hooks without waiting. */
declare function runAgentEndSideEffectsAsync(params: AgentEndSideEffectsParams): Promise<void>;
/** Runs agent-end side effects and waits for plugin/core completion. */
declare function awaitAgentEndSideEffects(params: AgentEndSideEffectsParams): Promise<void>;
//#endregion
//#region src/agents/embedded-agent-runner/run/agent-end-context.d.ts
type EmbeddedForegroundPromptContextRun = Pick<EmbeddedRunAttemptParams, Exclude<keyof EmbeddedForegroundPromptContext, "agentDir" | "agentId" | "cronCreatorCallerOrigin">> & Pick<EmbeddedRunAttemptParams, "cronCreatorAuthorityCapability" | "sessionId" | "sessionKey"> & {
  agentId: string;
};
declare function buildEmbeddedForegroundPromptContext(run: EmbeddedForegroundPromptContextRun, agentDir: string): EmbeddedForegroundPromptContext;
//#endregion
//#region src/agents/tool-display-exec.d.ts
type ToolDetailMode = "explain" | "raw";
//#endregion
//#region src/agents/tool-display.d.ts
declare function inferToolMetaFromArgsCore(toolName: string, args: unknown, options?: {
  detailMode?: ToolDetailMode;
}): string | undefined;
//#endregion
//#region src/plugin-sdk/agent-harness-runtime.d.ts
/** Core exec mode algebra for plugin-owned policy adapters. */
declare const execPolicy: Readonly<{
  resolveExecModePolicy: typeof resolveExecModePolicy;
  minSecurity: typeof minSecurity;
  maxAsk: typeof maxAsk;
}>;
/**
 * Renders the Watched Sessions prompt block for plugin-owned harness prompts.
 * Harness runtimes that assemble their own instruction layers (e.g. Codex)
 * must surface the same watched-session facts as the embedded prompt, or the
 * model keeps refusing cross-session questions on those runtimes (openclaw#114797).
 * @deprecated Await prepareWatchedSessionsHarnessContext with current host authority. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release.
 */
declare function buildWatchedSessionsHarnessContext(params: {
  config?: OpenClawConfig;
  sessionKey?: string;
  sandboxed?: boolean;
  toolNames: Iterable<string>;
  capabilityToolNames?: Iterable<string>;
}): string | undefined;
/** Prepares current watched-session facts through the worker before rendering them. */
declare function prepareWatchedSessionsHarnessContext(params: Parameters<typeof buildWatchedSessionsHarnessContext>[0] & {
  assertCurrent: () => void;
}): Promise<string | undefined>;
declare const agentHarnessAttemptTerminal: {
  merge: typeof mergeAgentRunAttemptTerminal;
  normalize: typeof normalizeAgentRunAttemptTerminal;
  project: typeof projectAgentRunAttemptTerminal;
  setFailure: typeof setAgentRunAttemptTerminalFailure;
};
type EmbeddedRunAttemptParamsBase = Omit<EmbeddedRunAttemptParams, "thinkingExplicit" | "admittedRunContext" | "disableToolSearch" | "sessionReadScopeKey" | "blindPrompt" | "authoredContextTokenCap" | "contextEngineLogicalTurnLease" | "onContextEngineTurnCandidate" | "pluginHarnessToolPolicySafeDeniedTools" | "trajectoryRecorder"> & {
  /** Per-model context cap authored by the operator and forwarded to harness runtimes. */
  authoredContextTokenCap?: number;
  /** Audited exact denies that the plugin harness must enforce against native equivalents. */
  pluginHarnessToolPolicySafeDeniedTools?: readonly string[];
};
/**
 * @deprecated Use EmbeddedRunAttemptParamsV2. The optional capability keeps
 * existing harness source compatible through 2026-10-12.
 */
type EmbeddedRunAttemptParams$1 = EmbeddedRunAttemptParamsBase & {
  hostCapabilities?: AgentHarnessHostCapabilities;
};
/** Current host-prepared attempt contract for agent harnesses. */
type EmbeddedRunAttemptParamsV2 = EmbeddedRunAttemptParamsBase & {
  hostCapabilities: AgentHarnessHostCapabilities;
};
/** Bounded structured-input compilation and execution for native agent harnesses. */
declare const agentHarnessStructuredInput: Readonly<{
  compileForm: typeof compileStructuredInputForm;
  compileQuestions: typeof compileStructuredInputQuestions;
  compileUrl: typeof compileStructuredInputUrl;
  isRecord: typeof isStructuredInputRecord;
  run: typeof runStructuredInput;
  snapshot: typeof snapshotStructuredInput;
}>;
type AgentHarnessActiveRunHandle = Omit<Parameters<typeof attachActiveEmbeddedRun>[1], symbol>;
/** Registers within the host-bound attempt and returns cleanup for this exact native run. */
declare function setActiveEmbeddedRun(sessionId: string, handle: AgentHarnessActiveRunHandle, sessionKey?: string, sessionFile?: string, agentId?: string): ((reason?: string) => void) | undefined;
/** A retained cleanup closes only its captured run, including after a successor registers. */
declare function clearActiveEmbeddedRun(sessionId: string, handle: AgentHarnessActiveRunHandle, sessionKey?: string, sessionFile?: string, reason?: string, cleanup?: ReturnType<typeof setActiveEmbeddedRun>): void;
/**
 * @deprecated Active-run queueing is an internal runtime concern. This legacy
 * boolean API reports whether the active turn or sessionless native sink could
 * take input now; it cannot observe the later outcome and never retries a refusal.
 */
declare function queueAgentHarnessMessage(sessionId: string, text: string, options?: EmbeddedAgentQueueMessageOptions): boolean;
/** Detect prompt image references and load them through the same limits used by embedded runs. */
declare function detectAndLoadAgentHarnessPromptImages(params: {
  prompt: string;
  userTurnTranscriptRecorder?: EmbeddedAgentQueueMessageOptions["userTurnTranscriptRecorder"];
  workspaceDir: string;
  agentWorkspaceDir?: string;
  model: {
    input?: string[];
  };
  existingImages?: ImageContent$1[];
  imageOrder?: PromptImageOrderEntry[];
  media?: MediaFact[];
  config?: OpenClawConfig;
  workspaceOnly?: boolean;
  localRoots?: readonly string[];
  sandbox?: {
    root: string;
    bridge: SandboxFsBridge;
  };
}): Promise<{
  images: ImageContent$1[];
  imageFactIndexes: Array<number | null>;
  detectedRefs: Array<{
    raw: string;
    resolved: string;
    type: "path" | "media-uri";
  }>;
  loadedCount: number;
  skippedCount: number;
  failedMediaCount: number;
}>;
/** Load static MCP metadata without connecting transports or discovering tools. */
declare function loadAgentHarnessMcpConfig(params: Parameters<typeof loadStaticBundleMcpConfig>[0]): Promise<ReturnType<typeof loadStaticBundleMcpConfig>>;
/** Load Codex bundle MCP thread config without forcing the heavy config module into SDK imports. */
declare function loadCodexBundleMcpThreadConfig(params: LoadCodexBundleMcpThreadConfigParams): Promise<CodexBundleMcpThreadConfig>;
/** Lazily load the strict MCP proxy client with core-owned framing, startup, and shutdown. */
declare const mcpStdioRuntime: Readonly<{
  load(): Promise<{
    createMcpStdioClient: typeof createMcpStdioClient;
  }>;
}>;
/**
 * Materialize an MCP App view for a tool executed by a harness-native MCP client.
 * The harness supplies a runtime adapter so the view keeps using that exact connection.
 */
declare function prepareHarnessNativeMcpAppPreview(params: {
  runtime: SessionMcpRuntime;
  agentId?: string;
  serverName: string;
  toolName: string;
  uiResourceUri: string;
  toolCallId: string;
  toolInput: unknown;
  toolResult: import("@modelcontextprotocol/sdk/types.js").CallToolResult;
  allowedAppToolNames: ReadonlySet<string>;
  resultMetaState?: "unavailable";
}): Promise<{
  mcpAppPreview: unknown;
} | undefined>;
/**
 * Materialize requester-scoped MCP tools for a harness run (dynamic tools, not
 * harness-native MCP config). Lazy-loaded so harness plugins avoid the MCP manager graph.
 */
declare function materializeRequesterScopedMcpToolsForHarnessRun(params: Parameters<typeof materializeRequesterScopedMcpToolsForHarnessRunCore>[0]): Promise<Awaited<ReturnType<typeof materializeRequesterScopedMcpToolsForHarnessRunCore>>>;
/**
 * Derive the same compact user-facing tool detail that embedded OpenClaw uses for progress logs.
 */
type ToolProgressDetailMode = "explain" | "raw";
/** Inputs used to classify a finished harness turn with little or no visible assistant output. */
type AgentHarnessTerminalOutcomeInput = {
  assistantTexts: readonly string[];
  reasoningText?: string | null;
  planText?: string | null;
  promptError?: unknown;
  turnCompleted: boolean;
};
/** Terminal fallback classification emitted by agent harness adapters. */
type AgentHarnessTerminalOutcomeClassification = NonNullable<EmbeddedRunAttemptResult["agentHarnessResultClassification"]>;
/**
 * Classify terminal harness turns that completed without assistant output that
 * should advance fallback. Deliberate silent replies such as NO_REPLY count as
 * intentional output, while whitespace-only text remains fallback-eligible.
 */
declare function classifyAgentHarnessTerminalOutcome(params: AgentHarnessTerminalOutcomeInput): AgentHarnessTerminalOutcomeClassification | undefined;
declare const toolPolicy: Readonly<{
  createToolPolicyMatcher: typeof createToolPolicyMatcher;
  expandToolGroups: typeof expandToolGroups;
}>;
//#endregion
//#region src/plugins/web-provider-types.d.ts
type WebSearchProviderToolDefinition = {
  description: string;
  parameters: TSchema;
  execute: (args: Record<string, unknown>, context?: WebSearchProviderToolExecutionContext) => Promise<Record<string, unknown>>;
};
type WebFetchProviderToolDefinition = {
  description: string;
  parameters: TSchema;
  execute: (args: Record<string, unknown>, context?: {
    signal?: AbortSignal;
  }) => Promise<Record<string, unknown>>;
};
type WebSearchProviderContext = {
  config?: OpenClawConfig;
  searchConfig?: Record<string, unknown>;
  runtimeMetadata?: RuntimeWebSearchMetadata;
  agentDir?: string;
};
type WebSearchProviderToolExecutionContext = {
  signal?: AbortSignal;
  /** Synchronous caller fence; non-HTTP transports must invoke it before each side effect. */
  assertCurrent?: () => void;
};
type WebFetchProviderContext = {
  config?: OpenClawConfig;
  fetchConfig?: Record<string, unknown>;
  runtimeMetadata?: RuntimeWebFetchMetadata;
};
type WebSearchCredentialResolutionSource = "config" | "secretRef" | "env" | "missing";
type WebSearchProviderSetupContext = {
  config: OpenClawConfig;
  runtime: RuntimeEnv;
  prompter: WizardPrompter;
  quickstartDefaults?: boolean;
  secretInputMode?: SecretInputMode;
};
type WebFetchCredentialResolutionSource = "config" | "secretRef" | "env" | "missing";
type WebProviderPluginBase = {
  id: string;
  label: string;
  hint: string;
  requiresCredential?: boolean;
  credentialLabel?: string;
  envVars: string[];
  placeholder: string;
  signupUrl: string;
  docsUrl?: string;
  autoDetectOrder?: number;
  credentialPath: string;
  inactiveSecretPaths?: string[];
  getCredentialValue: (config?: Record<string, unknown>) => unknown;
  setCredentialValue: (configTarget: Record<string, unknown>, value: unknown) => void;
  getConfiguredCredentialValue?: (config?: OpenClawConfig) => unknown;
  setConfiguredCredentialValue?: (configTarget: OpenClawConfig, value: unknown) => void;
  getConfiguredCredentialFallback?: (config?: OpenClawConfig) => {
    path: string;
    value: unknown;
  } | undefined;
  applySelectionConfig?: (config: OpenClawConfig) => OpenClawConfig;
};
type WebSearchProviderPlugin = WebProviderPluginBase & {
  /** Settings subtree relative to this plugin's config; null hides inline settings. Defaults to ["webSearch"]. */
  configPath?: readonly string[] | null;
  onboardingScopes?: readonly "text-inference"[];
  /** Optional model-provider auth profile id that can satisfy this web provider without a tool-specific API key. */
  authProviderId?: string;
  /** Optional note shown before credential collection for provider-specific prerequisites. */
  credentialNote?: string;
  runSetup?: (ctx: WebSearchProviderSetupContext) => OpenClawConfig | Promise<OpenClawConfig>;
  resolveRuntimeMetadata?: (ctx: Omit<WebSearchProviderContext, "agentDir"> & {
    resolvedCredential?: {
      value?: string;
      source: WebSearchCredentialResolutionSource;
      fallbackEnvVar?: string;
    };
  }) => Partial<RuntimeWebSearchMetadata> | Promise<Partial<RuntimeWebSearchMetadata>>;
  createTool: (ctx: WebSearchProviderContext) => WebSearchProviderToolDefinition | null;
};
type PluginWebSearchProviderEntry = WebSearchProviderPlugin & {
  pluginId: string;
};
type WebFetchProviderPlugin = WebProviderPluginBase & {
  resolveRuntimeMetadata?: (ctx: WebFetchProviderContext & {
    resolvedCredential?: {
      value?: string;
      source: WebFetchCredentialResolutionSource;
      fallbackEnvVar?: string;
    };
  }) => Partial<RuntimeWebFetchMetadata> | Promise<Partial<RuntimeWebFetchMetadata>>;
  createTool: (ctx: WebFetchProviderContext) => WebFetchProviderToolDefinition | null;
};
//#endregion
//#region src/plugins/logger-types.d.ts
/** 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;
};
//#endregion
//#region src/plugins/migration-provider.types.d.ts
type PluginConfigMigration = (config: OpenClawConfig) => {
  config: OpenClawConfig;
  changes: string[];
} | null | undefined;
/** Provider guarantee required before onboarding defers non-rollbackable effects. */
type MigrationDeferredApplyContract = {
  retrySafe: true;
};
type MigrationItem = {
  id: string;
  kind: ("auth" | "config" | "secret" | "memory" | "skill" | "workspace" | "session" | "file" | "archive" | "manual") | (string & {});
  action: ("copy" | "create" | "update" | "merge" | "append" | "archive" | "skip" | "manual") | (string & {});
  status: "planned" | "migrated" | "skipped" | "warning" | "conflict" | "error";
  source?: string;
  target?: string;
  message?: string;
  reason?: string;
  sensitive?: boolean;
  /** Onboarding may defer non-rollbackable effects only for retry-safe providers. */
  applyPhase?: "before-promotion" | "after-promotion";
  /** Retry-safe deferred apply may report a non-mutating already-satisfied terminal result. */
  deferredCompletion?: true;
  /** Core-owned source revision bound by reviewed embedded migration flows. */
  sourceRevision?: {
    algorithm: "sha256";
    digest: string;
  };
  details?: Record<string, unknown>;
};
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<string, unknown>;
};
type MigrationApplyResult = MigrationPlan & {
  backupPath?: string;
  reportDir?: string;
};
type MigrationProviderPreparation = {
  dispose?: () => void | Promise<void>;
};
type MigrationConfigRuntime = Pick<NonNullable<PluginRuntime["config"]>, "current" | "mutateConfigFile">;
type MigrationProviderContext = {
  config: OpenClawConfig;
  runtime?: PluginRuntime;
  /** Host-owned config mutation target for isolated embedded migration flows. */
  configRuntime?: MigrationConfigRuntime;
  logger: PluginLogger;
  stateDir: string;
  /** Explicit destination agent for embedded migration surfaces such as Control UI. */
  targetAgentId?: string;
  /** Optional item-kind scope used by embedded migration surfaces to avoid unrelated discovery. */
  itemKinds?: readonly string[];
  source?: string;
  includeSecrets?: boolean;
  overwrite?: boolean;
  providerOptions?: Record<string, unknown>;
  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;
  /** Item kinds this provider can expose without requiring a full plan. */
  supportedItemKinds?: readonly string[];
  /** Required when this provider plans items for `after-promotion`. */
  deferredApply?: MigrationDeferredApplyContract;
  detect?: (ctx: MigrationProviderContext) => MigrationDetection | Promise<MigrationDetection>;
  prepareApply?: (ctx: MigrationProviderContext) => MigrationProviderPreparation | Promise<MigrationProviderPreparation | undefined> | undefined;
  plan: (ctx: MigrationProviderContext) => MigrationPlan | Promise<MigrationPlan>;
  apply: (ctx: MigrationProviderContext, plan?: MigrationPlan) => MigrationApplyResult | Promise<MigrationApplyResult>;
};
type PluginSetupAutoEnableProbe = (ctx: {
  config: OpenClawConfig;
  env: NodeJS.ProcessEnv;
}) => string | string[] | null | undefined;
//#endregion
//#region src/plugins/tool-types.d.ts
type OpenClawPluginActiveModelContext = {
  provider?: string;
  modelId?: string;
  modelRef?: string;
};
/** Current-turn outbound delivery capability bound to the host-selected route and media policy. */
type OpenClawPluginToolDelivery = {
  send: (params: {
    text?: string;
    mediaUrl?: string;
  }) => Promise<void>;
};
/** Commands stay in the calling run's sandbox; paths are sandbox paths, never host paths. */
type OpenClawPluginToolSandbox = {
  workspaceDir: string;
  /** Only selected, host-installed skills protected by the sandbox owner are exposed. */
  installedSkillRoots: Readonly<Record<string, string>>;
  run: (params: {
    argv: readonly string[];
    input?: string;
    signal?: AbortSignal;
    /** Complete captured bytes per stream, at most the sandbox command buffer limit. */
    maxOutputBytes?: number;
  }) => Promise<{
    stdout: string;
    stderr: string;
    code: number;
  }>;
};
type OpenClawPluginToolModelExecution = {
  /** Published CLI entry in the running host installation, never resolved from guest input. */
  readonly cliEntryPath: string;
  /** Admits explicit choices or permitted defaults, retaining the caller through execution. */
  run: <T>(selection: {
    model: string | null;
    explicit: boolean;
  }, action: (scope: {
    signal: AbortSignal;
    assertCurrent: () => void;
    model: string;
    agentId: string;
  }) => Promise<T>, signal?: AbortSignal) => Promise<T>;
};
/** Trusted execution context passed to plugin-owned agent tool factories. */
type OpenClawPluginToolContextBase = {
  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;
  /** Host-selected reviewer devices for an approval request; not an approval grant. */
  approvalReviewerDeviceIds?: readonly string[];
  /** Ephemeral session UUID - regenerated on /new and /reset. Use for per-conversation isolation. */
  sessionId?: string;
  /** Host run id of the agent turn that builds this tool. Correlation only; never authority. */
  runId?: string;
  /**
   * Host-stamped origin of this turn's input, when its producer supplied one. A background
   * exec completion wake names the run that started the command:
   * `{ kind: "internal_system", sourceTool: "exec", runId }`. A fact for plugin-owned
   * policy; it never grants owner identity.
   */
  inputProvenance?: InputProvenance;
  /** Out-of-band plugin-owned bindings attached by the current run initiator. */
  toolBindings?: Readonly<Record<string, unknown>>;
  /** Host-prepared repository identities for project-aware tool behavior. */
  activeProjectKeys?: readonly string[];
  /** Trusted runtime-only authorization for one bounded cross-conversation recall pass. */
  conversationRecall?: ConversationRecallContext;
  /**
   * 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;
    /** Prepared local exec parity; not standalone authority or permission for remote browsers. */
    allowLocalLoopback?: boolean;
    assertLocalLoopbackCurrent?: () => void;
  };
  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<string | undefined>;
  /** Trusted ambient delivery route for the active agent/session. */
  deliveryContext?: DeliveryContext;
  /** Host-bound current-route delivery. Retained copies fail after the owning turn closes. */
  delivery?: OpenClawPluginToolDelivery;
  /** Trusted platform-native conversation id for the active inbound turn. */
  nativeChannelId?: string;
  /** Trusted sender id from inbound context (runtime-provided, not tool args). */
  requesterSenderId?: string;
  /** Trusted owner bit from inbound context (runtime-provided, not tool args). */
  senderIsOwner?: boolean;
  /** Host-resolved memory partition for this turn. Providers must not reconstruct it. */
  memoryAudience?: MemoryAudience;
  /** Stable identity for one provider-owned pre-compaction flush cycle. */
  memoryFlush?: {
    flushId: string;
  };
  /** Rejects a retained audience after any captured session incarnation changes. */
  assertMemoryAudienceCurrent?: () => void;
  /** Live host-bound authority. Recheck inside the final synchronous effect/write guard. */
  assertInvocationCurrent?: () => void;
  /**
   * Host-bound client-input policy. Pure synchronous guard for final storage admission;
   * performs no database reads and grants no invocation or mutation authority.
   * Omitted for agent-generated input. Do not apply to accepted results or cleanup.
   */
  assertInputCommitAllowed?: () => void;
  /**
   * Server-owned origin for this operation. Missing values are delegated.
   * Plugins must use it only for conversation-read visibility policy.
   */
  conversationReadOrigin?: ConversationReadInvocationOrigin;
  sandboxed?: boolean;
  /** Refuses a complete result that the current direct/full-value route cannot deliver. */
  assertCompleteResult?: (text: string) => void;
  /** Invocation-bound execution, present only for an actual prepared sandbox. */
  sandbox?: OpenClawPluginToolSandbox;
  /** Model authorization scope; does not execute inference or grant tool permissions. */
  modelExecution?: OpenClawPluginToolModelExecution;
  /**
   * True for explicit one-shot local CLI runs that must release plugin-owned
   * process resources before the command exits.
   */
  oneShotCliRun?: boolean;
};
/** Version 1 is the source-compatible direct-turn context; version 2 requires final-effect authority. */
type OpenClawPluginToolContext<Version extends 1 | 2 = 1> = Version extends 2 ? OpenClawPluginToolContextBase & {
  assertInvocationCurrent: () => void;
  /** Optional on older hosts and on turns without admitted requester/session authority. */
  runtimeContext?: {
    models?: PluginRequesterModels;
  };
} : OpenClawPluginToolContextBase;
/** A version 2 descriptor explicitly opts into owner-authorized continuations. */
type OpenClawPluginToolFactory<Version extends 1 | 2 = 1> = Version extends 2 ? {
  contextVersion: 2;
  create: (ctx: OpenClawPluginToolContext<2>) => ReturnType<OpenClawPluginToolFactory>;
} : (ctx: OpenClawPluginToolContext) => AnyAgentTool | AnyAgentTool[] | null | undefined;
type OpenClawPluginToolOptions$1 = {
  name?: string;
  names?: string[];
  optional?: boolean;
  /** False: independent; execute: pure factory with workspace use; true/omitted: factory may use it. */
  workspaceAccess?: boolean | "execute";
};
type OpenClawPluginHookOptions = {
  entry?: HookEntry;
  name?: string;
  description?: string;
  register?: boolean;
};
//#endregion
//#region src/hooks/internal-hook-types.d.ts
type InternalHookEventType = "command" | "session" | "agent" | "gateway" | "message";
interface InternalHookEvent {
  type: InternalHookEventType;
  /** The specific action within the type (e.g., 'new', 'reset', 'stop') */
  action: string;
  sessionKey: string;
  context: Record<string, unknown>;
  timestamp: Date;
  /** Messages to send back to the user (hooks can push to this array) */
  messages: string[];
}
type InternalHookHandler = (event: InternalHookEvent) => Promise<void> | void;
//#endregion
//#region src/plugins/runtime/gateway-context-binding.d.ts
declare const { bindGatewayContextResolver, getGatewayContextLifetime, getGatewayContextResolver, clearGatewayContextResolver }: {
  bindGatewayContextResolver: (owner: object, resolver: GatewayContextResolver | undefined) => void;
  getGatewayContextLifetime: (resolver: GatewayContextResolver) => AbortController;
  getGatewayContextResolver: (owner: object) => GatewayContextResolver | undefined;
  clearGatewayContextResolver: (owner: object) => boolean;
};
//#endregion
//#region src/plugins/runtime/gateway-request-scope.d.ts
declare function getPluginRuntimeGatewayRequestScope(): PluginRuntimeGatewayRequestScope | undefined;
//#endregion
//#region src/plugins/capability-provider-runtime.d.ts
declare function prepareMediaCapabilityProviders(params: {
  cfg?: OpenClawConfig;
  pluginMetadataSnapshot: Pick<PluginMetadataSnapshot, "index" | "plugins">;
  registry?: PluginRegistry;
}): Readonly<{
  mediaUnderstandingProviders: readonly MediaUnderstandingProvider[] | undefined;
  imageGenerationProviders: readonly ImageGenerationProvider[] | undefined;
  videoGenerationProviders: readonly VideoGenerationProvider[] | undefined;
  musicGenerationProviders: readonly MusicGenerationProvider[] | undefined;
}>;
//#endregion
//#region src/plugins/provider-discovery.d.ts
type PreparedProviderStaticCatalogEntry = Readonly<{
  provider: ProviderPlugin;
  providerConfigs: Readonly<Record<string, ModelProviderConfig>>;
  /** The static run failed: its providers are unavailable, not empty. */
  failed?: true;
}>;
type PreparedProviderStaticCatalog = Readonly<{
  /** Provider handles captured for this config/workspace generation. */
  providers?: readonly ProviderPlugin[];
  entries: readonly PreparedProviderStaticCatalogEntry[];
}>;
//#endregion
//#region src/agents/embedded-agent-runner/model.inline-provider.d.ts
/**
 * Normalizes inline `models.providers` config into runtime model entries.
 */
type InlineModelEntry = Omit<ModelDefinitionConfig, "api" | "contextWindow" | "input"> & {
  api?: Api;
  contextWindow?: number;
  input: ReturnType<typeof resolveProviderModelInput>;
  provider: string;
  baseUrl?: string;
  headers?: Record<string, string>;
};
/** Resolves model input modalities with Foundry legacy vision-model compatibility. */
declare function resolveProviderModelInput(params: {
  provider?: string;
  modelId?: string;
  modelName?: string;
  input?: unknown;
  fallbackInput?: unknown;
}): Array<"text" | "image">;
//#endregion
//#region src/agents/agent-auth-credential-modes.d.ts
/** Secret-free credential modes captured by a prepared agent runtime. */
type PreparedAgentCredentialMode = "api_key" | "oauth" | "token" | Readonly<{
  source: "native";
  mode: "api_key" | "oauth" | "token";
}>;
type PreparedAgentCredentialModes = Readonly<Record<string, PreparedAgentCredentialMode>>;
//#endregion
//#region src/agents/model-auth-selected-credential.d.ts
type SelectedModelCredential = {
  source: "harness";
} | ({
  mode?: string;
  requirement?: ProviderModelRouteAuthRequirement;
  identityKey: string;
} & ({
  source: "profile";
  profileId: string;
} | {
  source: "direct";
  provider: string;
}));
//#endregion
//#region src/agents/prepared-model-runtime-auth.d.ts
type ModelServiceTierObservation = {
  modelId: string;
  runtimeId: string;
  api: string;
  baseUrl: string;
  requestedTier: string;
  responseTier?: string;
};
/** Selected-account inventory belongs to the prepared generation, not an RPC projector. */
type PreparedAccountCatalogAccess = {
  reconcileAuth: (authStore: AuthProfileStore$1, includesProvider: (provider: string) => boolean, profileIds?: readonly string[]) => void;
  readServiceTierObservations: (params: {
    identityKey: string;
    modelId: string;
    runtimeId: string;
    api: string;
    baseUrl: string;
  }) => Pick<ModelServiceTierObservation, "requestedTier" | "responseTier">[];
  prepareServiceTierObserver: (params: {
    selectedCredential: SelectedModelCredential;
    credential?: AuthProfileCredential;
  }) => (observation: ModelServiceTierObservation) => boolean;
  acquire: (params: {
    profileId: string;
    credential: AuthProfileCredential;
    allowDiscovery: boolean;
    refresh?: boolean;
    load: () => Promise<readonly ProviderCatalogOutcome[]>;
  }) => Promise<{
    outcomes: readonly ProviderCatalogOutcome[];
    /** Distinguishes an authoritative empty publication from a cold private catalog. */
    hasPublishedCatalog: boolean;
    isCurrent: () => boolean;
  }>;
};
//#endregion
//#region src/agents/prepared-model-catalog.types.d.ts
type PublishedModelCatalogOwnerCandidate = Readonly<{
  /** Captured during preparation; undefined is a known-unbound runtime. */
  catalogOwner: Readonly<{
    agentId: string;
    workspaceDir: string;
  }> | undefined;
  agentId?: string;
  agentDir: string;
  workspaceDir?: string;
  config: OpenClawConfig;
  /** Native observations retain preparation identity across model-neutral config publications. */
  observationConfig: OpenClawConfig;
  /** Secret-free usable auth modes captured by this exact lifecycle generation. */
  authModes: PreparedAgentCredentialModes;
  authStore?: AuthProfileStore$1;
  metadataSnapshot: PluginMetadataSnapshot;
  /** Registry owned by this prepared generation; omitted from read-only builds. */
  pluginRegistry?: PluginRegistry;
  /** Reports whether this exact lifecycle generation is still published. */
  isCurrent: () => boolean;
  /** Configured turn facts; full inventory discovery stays outside startup publication. */
  modelCatalog: ModelCatalogSnapshot;
  accountCatalog?: PreparedAccountCatalogAccess;
}>;
//#endregion
//#region src/agents/prepared-model-runtime.types.d.ts
type PreparedConfiguredRuntimeModel = Readonly<{
  provider: string;
  modelId: string;
  model: ProviderRuntimeModel;
}>;
type PreparedModelCatalogRefreshOptions = {
  refresh?: boolean;
  providerIds?: readonly string[];
  /** Lifecycle publication renews changed providers; native harnesses wait for demand. */
  changedOnly?: boolean;
  /** Await acquisition instead of returning published rows after the foreground deadline. */
  wait?: boolean;
};
type PreparedNativeModelSelection = {
  provider: string;
  modelId: string;
  runtime: string;
};
type PreparedMediaCapabilityProviderSource = Readonly<{
  registry: PluginRegistry;
  resources: Pick<PluginRegistryInspectionResources, "retain" | "createInvocationScope">;
}>;
type PreparedMediaCapabilityProviderAcquisition = Readonly<{
  providers: ReturnType<typeof prepareMediaCapabilityProviders>;
  assertOpen: () => void;
  release: () => Promise<void>;
}>;
type PreparedModelRuntimePluginGeneration = Readonly<{
  remoteCatalog: ActiveRemoteModelCatalog | null;
  pluginMetadataSnapshot: PluginMetadataSnapshot;
  messageToolCatalog?: PreparedMessageToolCatalog;
  mediaCapabilityProviders?: ReturnType<typeof prepareMediaCapabilityProviders>;
  mediaCapabilityProviderSource?: PreparedMediaCapabilityProviderSource;
  preparedStaticProviderCatalog?: PreparedProviderStaticCatalog;
  /** Captured static rows; cleared when catalog discovery expands the provider registry. */
  providerStaticModels?: readonly ProviderRuntimeModel[];
  inlineProviderModels: readonly InlineModelEntry[];
  configuredCatalogEntries: readonly ModelCatalogEntry[];
  pluginRegistry?: PluginRegistry;
  inboundPluginRegistry?: PluginRegistry;
  /** Immutable artifact choice for every registry reuse in this generation. */
  preferBuiltPluginArtifacts?: boolean;
}>;
type PreparedModelRuntimeSnapshot = Omit<PublishedModelCatalogOwnerCandidate, "authStore"> & Readonly<{
  inheritedAuthDir?: string;
  /** Run-prepared repository root; null means discovery completed without a match. */
  repoRoot?: string | null;
  /** Stable identity derived from repoRoot; null means the run is outside a repository. */
  projectKey?: string | null;
  /** Session active project set, ordered most-recent first; empty before run binding. */
  activeProjectKeys: readonly string[];
  messageToolCatalog?: PreparedMessageToolCatalog;
  mediaCapabilityProviders?: ReturnType<typeof prepareMediaCapabilityProviders>;
  /** Borrows an inspected source; raw prepared hosts retain their existing external ownership. */
  acquireMediaCapabilityProviders?: () => PreparedMediaCapabilityProviderAcquisition;
  allowGatewaySubagentBinding: boolean;
  /** Reads accepted inventory without scheduling discovery or expiry renewal. */
  readFullModelCatalog?: () => ModelCatalogSnapshot | undefined;
  /** Inventory demand may renew expired providers without waiting or replacing saved rows. */
  refreshExpiredModelCatalog?: () => void;
  /** Rechecks native CLI login availability without refreshing provider inventory. */
  recheckNativeLogin?: (options?: {
    force?: boolean;
  }) => void | Promise<void>;
  /** Reads validated executable rows from this owner's accepted provider publication. */
  readPublishedModels?: () => ReadonlyMap<string, readonly Model[]> | undefined;
  /** Builds this generation's full control-plane catalog without replacing turn facts. */
  loadFullModelCatalog?: (options?: PreparedModelCatalogRefreshOptions) => Promise<ModelCatalogSnapshot>;
  /** Acquires native inventory on demand, or just the runtime selected for execution. */
  loadNativeModelCatalog?: (selection?: PreparedNativeModelSelection) => Promise<ModelCatalogSnapshot>;
  /** Full static models for configured refs, resolved once at the lifecycle boundary. */
  configuredRuntimeModels: readonly PreparedConfiguredRuntimeModel[];
  /** Exact logical IDs precede static equivalence within this policy generation. */
  findConfiguredRuntimeModel: (provider: string, modelId: string) => ProviderRuntimeModel | undefined;
  /** Supported aliases for this immutable turn generation, separate from catalog metadata. */
  configuredModelAliases?: readonly Readonly<{
    alias: string;
    provider: string;
    model: string;
  }>[];
  /** Inline provider projection prepared once for all resolutions owned by this snapshot. */
  inlineProviderModels: readonly InlineModelEntry[];
  createStores: (publishedModels?: ReadonlyMap<string, readonly Model[]>) => PreparedModelRuntimeStores;
  /** Bounded metadata shared by runs; replacing the model/auth generation drops the memo. */
  routeModelResolutionMemo?: Map<string, Promise<Model>>;
}>;
type PreparedModelRuntimeStores = {
  authStorage: AuthStorage;
  modelRegistry: ModelRegistry$1;
};
//#endregion
//#region src/agents/prepared-model-runtime.d.ts
declare const { applyRemoteModelCatalogUpdate, advancePreparedModelRuntimeConfig }: {
  applyRemoteModelCatalogUpdate: (getConfig: () => OpenClawConfig, signal?: AbortSignal | undefined) => Promise<RemoteCatalogPublicationResult>;
  advancePreparedModelRuntimeConfig: (config: OpenClawConfig) => void;
};
//#endregion
//#region src/agents/embedded-agent-runner/model.provider-hooks.types.d.ts
type ProviderRuntimeHooks = {
  resolveToolSearchMode?: (context: ProviderToolSearchPolicyContext) => "tools" | false | undefined;
  applyProviderResolvedTransportWithPlugin?: (params: Parameters<typeof applyProviderResolvedTransportWithPlugin>[0]) => unknown;
  buildProviderUnknownModelHintWithPlugin: typeof buildProviderUnknownModelHintWithPlugin;
  prepareProviderDynamicModel: typeof prepareProviderDynamicModel;
  runProviderDynamicModel: (params: Parameters<typeof runProviderDynamicModel>[0]) => unknown;
  shouldPreferProviderRuntimeResolvedModel?: typeof shouldPreferProviderRuntimeResolvedModel;
  normalizeProviderResolvedModelWithPlugin: (params: Parameters<typeof normalizeProviderResolvedModelWithPlugin>[0]) => unknown;
  normalizeProviderTransportWithPlugin: typeof normalizeProviderTransportWithPlugin;
};
//#endregion
//#region src/agents/embedded-agent-runner/model.d.ts
type AsyncModelResolutionOptions = {
  assertCurrent?: () => void;
  authStorage?: AuthStorage$1;
  modelRegistry?: ModelRegistry$2;
  agentId?: string;
  runtimeHooks?: ProviderRuntimeHooks;
  skipProviderRuntimeHooks?: boolean;
  workspaceDir?: string;
  authProfileId?: string;
  authProfileMode?: AuthProfileCredential["type"] | "aws-sdk";
  preferredProfile?: string;
  abortSignal?: AbortSignal;
  /** Selected executable IDs must not pass through input aliases again. */
  modelIdSource?: "input" | "selected";
  allowBundledStaticCatalogFallback?: boolean;
  /** Only harness-owned execution may replace configured transport with catalog defaults. */
  preferBundledStaticCatalogTransport?: boolean;
  agentRuntimeId?: string;
  skipAgentDiscovery?: boolean;
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  /** Resolve local provider facts without starting asynchronous catalog discovery. */
  deferProviderDynamicModelPreparation?: boolean;
};
type ModelResolution = {
  authStorage: AuthStorage$1;
  modelRegistry: ModelRegistry$2;
} & ({
  model: Model;
  logicalRef: Readonly<ProviderModelRef>;
  error?: undefined;
} | {
  model?: undefined;
  error: string;
  /** Local preparation exhausted its facts without invoking the provider's async model owner. */
  deferred?: "provider-dynamic-model";
});
declare function resolveModelAsync(provider: string, modelId: string, agentDir?: string, cfg?: OpenClawConfig, options?: AsyncModelResolutionOptions): Promise<ModelResolution>;
//#endregion
//#region src/agents/simple-completion-scope.d.ts
/** Shipped SDK resolver callbacks do not supply core-owned logical reference facts. */
type SimpleCompletionModelResolver = (...args: Parameters<typeof resolveModelAsync>) => Promise<Omit<Awaited<ReturnType<typeof resolveModelAsync>>, "logicalRef">>;
//#endregion
//#region src/agents/simple-completion.types.d.ts
type PrepareModelWithCredentialsParams = {
  cfg: OpenClawConfig | undefined;
  agentId?: string;
  provider: string;
  modelId: string;
  modelIdSource?: "input" | "selected";
  agentDir?: string;
  profileId?: string;
  preferredProfile?: string;
  authStore?: AuthProfileStore$1;
  /** Resolve the model again for the account the selected credential belongs to. */
  credentialScopedModelMetadata?: boolean;
  allowMissingApiKeyModes?: ReadonlyArray<ResolvedProviderAuth["mode"]>;
  allowBundledStaticCatalogFallback?: boolean;
  skipAgentDiscovery?: boolean;
  bindAuthOwner?: boolean;
  modelResolver?: SimpleCompletionModelResolver;
  signal?: AbortSignal;
  /** Internal caller-owned generation. Public plugin callers use the agent helper below. */
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  workspaceDir?: string;
  agentRuntimeId?: string;
  /** Internal stream callers own provider transport construction and embedded policy. */
  transport?: "simple-completion" | "provider-stream";
};
type PrepareSimpleCompletionModelParams = PrepareModelWithCredentialsParams & {
  /** Internal worker RPC owner; sessionless helper callers cannot supply this authority. */
  workerInferenceAuthority?: {
    assertCurrent: () => void;
  };
};
type PreparedSimpleCompletionModel = {
  model: Model;
  auth: ResolvedProviderAuth;
  /** Non-reversible owner proof captured from the same auth snapshot. */
  sourceAuthFingerprint?: string;
} | {
  error: string;
  auth?: ResolvedProviderAuth;
};
//#endregion
//#region src/gateway/session-companion-policy.d.ts
/** Reasoning and speed chosen for one Side chat question; omitted fields use model defaults. */
type SessionCompanionRunControls = {
  thinkLevel?: ThinkLevel;
  fastMode?: FastMode;
};
/** Operator-chosen model controls for one Side chat question. */
type SessionCompanionAskSelection = {
  /** Validated allowlisted model; omitted uses the utility model and its fallbacks. */
  model?: {
    provider: string;
    model: string;
  };
  controls?: SessionCompanionRunControls;
};
//#endregion
//#region src/gateway/session-observer-contract.d.ts
type SessionObserverEvent = AgentEventPayload;
type SessionObserverCompanionSnapshot = {
  agentId: string;
  runId?: string;
  digest?: SessionObserverDigest;
  notes: Array<{
    sequence: number;
    text: string;
  }>;
};
type SessionObserverService = {
  /** @deprecated Await handleEventAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  handleEvent: (event: SessionObserverEvent) => void;
  handleEventAsync: (event: SessionObserverEvent) => Promise<void>;
  setConnectionVisibility: (connId: string, visible: boolean) => void;
  removeConnection: (connId: string) => void;
  /** @deprecated Await getCompanionSnapshotAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  getCompanionSnapshot: (sessionKey: string, agentId?: string) => SessionObserverCompanionSnapshot;
  getCompanionSnapshotAsync: (sessionKey: string, agentId?: string) => Promise<SessionObserverCompanionSnapshot>;
  /** @deprecated Use disposeAsync to join accepted work before closing database workers. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  dispose: () => void;
  disposeAsync: () => Promise<void>;
};
//#endregion
//#region src/gateway/session-companion-ask.d.ts
type SessionCompanionAskDeps = {
  getConfig: () => OpenClawConfig;
  sessionObserver: {
    getCompanionSnapshotAsync: (sessionKey: string, agentId?: string) => Promise<SessionObserverCompanionSnapshot>;
  };
  contextReader: SessionCompanionContextReader;
};
type SessionCompanionAskRuntimeParams = SessionCompanionAskDeps & {
  threads: Map<string, SessionCompanionThread>;
  now: () => number;
  isDisposed: () => boolean;
};
type SessionCompanionCancellationKind = "backing-session-revoked" | "disposed" | "explicit-reset" | "request-aborted" | "timeout";
declare function createSessionCompanionAskRuntime(params: SessionCompanionAskRuntimeParams): {
  ask: (request: {
    agentId: string;
    sessionKey: string;
    question: string;
    selectionContext?: string;
    attachments?: ChatAttachment[];
    selection?: SessionCompanionAskSelection;
    connId: string;
    ownerId: string;
    operatorAuthority?: AdmittedRunOperatorAuthority;
    assertSourceCurrent?: () => void;
    assertInputCurrent?: () => void;
    signal?: AbortSignal;
  }) => Promise<{
    answer: string;
    ts: number;
  }>;
  activeKeys: () => MapIterator<string>;
  cancel(threadKey: string, cancellation: Extract<SessionCompanionCancellationKind, "backing-session-revoked" | "explicit-reset">): void;
  dispose(): void;
};
//#endregion
//#region src/gateway/session-companion.d.ts
/** `ownerId` names the requester whose private thread is addressed. */
type SessionCompanionTarget = {
  sessionKey: string;
  agentId: string;
  ownerId: string;
};
type SessionCompanionService = {
  ask: ReturnType<typeof createSessionCompanionAskRuntime>["ask"];
  state: (target: SessionCompanionTarget) => SessionsCompanionStateResult;
  reset: (target: SessionCompanionTarget) => void;
  dispose: () => void;
};
//#endregion
//#region src/gateway/session-activity-summary-completion.d.ts
type SessionActivitySummaryCompletion = {
  take(): SessionActivitySummary | undefined;
  committed(entry: SessionEntry): void;
  release(): void;
};
//#endregion
//#region src/gateway/session-activity-summary-state.d.ts
type ActivitySummaryTarget = {
  key: string;
  agentId: string;
};
//#endregion
//#region src/gateway/session-sharing-target.types.d.ts
type SessionSharingTarget = {
  agentId: string;
  canonicalKey: string;
  entry: SessionEntry;
  storeKey: string;
  storeKeys: string[];
  storePath: string;
  /** Physical source selected by the store reader, independent of its configured locator. */
  readSource?: CapturedSessionEntryReadSource;
};
//#endregion
//#region src/agents/model-runtime-policy.d.ts
/** A stored-row owner is already selected; request hints still require normal admission. */
type AgentRuntimePolicyScope = {
  sessionKey?: string;
} & ({
  agentId?: string;
  agentScope?: never;
} | {
  agentId?: never;
  agentScope: {
    kind: "prepared";
    agentId: string;
  };
});
/** Runtime policy plus the config surface that supplied it. */
type ResolvedModelRuntimePolicy = {
  policy?: AgentRuntimePolicyConfig;
  /** Config surface that supplied a resolved model runtime policy. */
  source?: "model" | "provider";
  matchedProvider?: string;
  forcedByEnvironment?: true;
};
/** Resolves the effective runtime policy for an agent/model/provider selection. */
declare function resolveModelRuntimePolicy(params: {
  config?: OpenClawConfig;
  provider?: string;
  modelId?: string;
} & AgentRuntimePolicyScope): ResolvedModelRuntimePolicy;
//#endregion
//#region src/agents/model-catalog-view.d.ts
/** Keep capability donors bound to one model and runtime without merging sibling metadata. */
declare function selectModelCatalogRuntimeEntry(params: {
  entry: ModelCatalogEntry;
  routeVariants: readonly ModelCatalogEntry[];
  runtimeId: string;
  /** Capacity belongs to its runtime; API capability donors cannot supply native limits. */
  allowApiFallback?: boolean;
}): {
  entry: ModelCatalogEntry;
  variants: ModelCatalogEntry[];
};
//#endregion
//#region src/agents/session-model-ref.d.ts
type SessionModelEntry = SessionEntry | Pick<SessionEntry, "model" | "modelProvider" | "modelOverride" | "providerOverride" | "modelOverrideRouteResolution" | "modelOverrideFallbackOriginProvider" | "modelOverrideFallbackOriginModel">;
/** Keep prepared host metadata outside the published session-model resolver contract. */
declare function resolveSessionModelRef(cfg: OpenClawConfig, entry?: SessionModelEntry, agentId?: string, options?: {
  allowPluginNormalization?: boolean;
}): {
  provider: string;
  model: string;
};
//#endregion
//#region src/agents/subagents/spawn/subagent-spawn.types.d.ts
declare const SUBAGENT_SPAWN_MODES: readonly ["run", "session"];
type SpawnSubagentMode = (typeof SUBAGENT_SPAWN_MODES)[number];
//#endregion
//#region src/agents/subagents/subagent-run-outcome.types.d.ts
type SubagentRunOutcome = {
  status: AgentInternalEventStatus;
  error?: string;
  startedAt?: number;
  endedAt?: number;
  elapsedMs?: number;
};
//#endregion
//#region src/agents/subagents/registry/subagent-lifecycle-events.d.ts
declare const SUBAGENT_ENDED_REASON_COMPLETE: "subagent-complete";
declare const SUBAGENT_ENDED_REASON_ERROR: "subagent-error";
declare const SUBAGENT_ENDED_REASON_KILLED: "subagent-killed";
type SubagentLifecycleEndedReason = typeof SUBAGENT_ENDED_REASON_COMPLETE | typeof SUBAGENT_ENDED_REASON_ERROR | typeof SUBAGENT_ENDED_REASON_KILLED;
//#endregion
//#region src/agents/subagents/registry/subagent-registry-read.types.d.ts
type PendingFinalDeliveryPayload = {
  requesterSessionKey: string;
  requesterOrigin?: DeliveryContext;
  requesterDisplayKey: string;
  childSessionKey: string;
  childRunId: string;
  task: string;
  label?: string;
  startedAt?: number;
  endedAt?: number;
  outcome?: SubagentRunOutcome;
  expectsCompletionMessage?: boolean;
  completionTarget?: "parent";
  completionRequesterSessionId?: string;
  spawnMode?: SpawnSubagentMode;
  wakeOnDescendantSettle?: boolean;
  terminalReply?: AgentRunTerminalReplySnapshot;
};
type SubagentDeliveryDisposition = "delivered" | "session_queued" | "intentional_non_delivery" | "retryable" | "ambiguous" | "permanent_failure";
type SubagentCompletionDeliveryState = {
  status: "not_required" | "pending" | "in_progress" | "delivered" | "failed" | "suspended" | "discarded";
  payload?: PendingFinalDeliveryPayload;
  createdAt?: number;
  enqueuedAt?: number;
  deliveredAt?: number;
  announcedAt?: number;
  /** Requester transcript custody, independent of an external reply or retry policy. */
  requesterDelivery?: ({
    state: "waiting";
    runId?: string;
  } | {
    state: "consumed";
    runId: string;
  }) & {
    at?: number;
    blockingRunId?: string;
  };
  /** Exact requester turn and completed child batch that already produced its visible final. */
  requesterVisibleFinal?: {
    requesterTurnRunId: string;
    batchRunIds: string[];
  };
  lastAttemptAt?: number;
  attemptCount?: number;
  lastError?: string | null;
  /** Closed result of the latest transport attempt; never doubles as delivery success. */
  disposition?: SubagentDeliveryDisposition;
  /** Logical obligation generation. Redrive increments it and never revives an old row. */
  generation?: number;
  queueId?: string;
  windowStartedAt?: number;
  deadlineAt?: number;
  nextAttemptAt?: number;
  suspendedAt?: number;
  suspendedReason?: "expiry" | "permanent_failure";
  dismissedAt?: number;
  discardedAt?: number;
  discardReason?: "expired" | "task-missing";
  discardedPayloadSummary?: {
    requesterSessionKey?: string;
    childSessionKey?: string;
    childRunId?: string;
    endedAt?: number;
    status?: string;
    lastError?: string | null;
  };
  lastDropReason?: "queue_cap" | "parent_run_ended" | "sink_unavailable" | "steer_dropped" | "message_tool_delivery_missing" | "visible_reply_missing" | "dedupe" | "waiting_for_requester_turn";
};
type SwarmCollectorStatus = "done" | "failed" | "killed" | "timeout";
/** Persisted fields shared by compact registry reads and the full runtime record. */
type SubagentRunReadRecord = {
  runId: string;
  /** Logical task ownership survives replacement of the physical execution run. */
  taskRunId?: string;
  /** Stable public collector id; gateway execution ids can change across dispatch/recovery. */
  swarmRunId?: string;
  /** Stable scheduler slot identity across Gateway run replacements. */
  schedulerSlotId?: string;
  /** Replay identity selects one collector payload before hydration. */
  swarmLaunchReplayKey?: string;
  /** Collector-mode runs remain waitable and never announce to the requester. */
  collect?: boolean;
  groupId?: string;
  /** Stable spawning-session owner for caps, scheduling, and wait authorization. */
  swarmRequesterSessionKey?: string;
  childSessionKey: string;
  /** Selected child agent; historical qualified keys may carry ownership without this field. */
  childAgentId?: string;
  controllerSessionKey?: string;
  requesterSessionKey: string;
  /** Effective requester agent, including cron/hook overrides not encoded in the session key. */
  requesterAgentId?: string;
  requesterStorePath?: string;
  controllerStorePath?: string;
  model?: string;
  /** Monotonic ownership generation within one child session. */
  generation?: number;
  createdAt: number;
  sessionStartedAt?: number;
  accumulatedRuntimeMs?: number;
  runTimeoutSeconds?: number;
  endedReason?: SubagentLifecycleEndedReason;
  pauseReason?: "sessions_yield";
  cleanupCompletedAt?: number;
  /** Durable outbox marker for parent/external completion delivery. */
  delivery?: SubagentCompletionDeliveryState;
  execution: {
    status: "queued" | "running" | "interrupted" | "terminal";
    /** Recorded execution timing remains readable for retained task history. */
    startedAt?: number;
    endedAt?: number;
    outcome?: SubagentRunOutcome;
  };
  collectorCompletion?: {
    status: SwarmCollectorStatus;
  };
};
//#endregion
//#region src/agents/subagents/registry/subagent-registry.types.d.ts
type SubagentProgressOrigin = {
  channel?: string;
  accountId?: string;
  to?: string;
  threadId?: string | number;
  channelId?: string | number;
  messageId?: string | number;
};
type SubagentExecutionState = SubagentRunReadRecord["execution"] & {
  /** Gateway lifecycle that owns child-session effects for this run. */
  lifecycleGeneration?: string;
  /** Sticky terminal policy: this run must never mutate its child session again. */
  suppressSessionEffects?: true;
  acceptedAt?: number;
  transcriptTarget?: AgentRunSessionTarget;
};
type SubagentCompletionState = {
  required: boolean;
  resultText?: string | null;
  capturedAt?: number;
  fallbackResultText?: string | null;
  fallbackCapturedAt?: number;
  terminalReply?: AgentRunTerminalReplySnapshot;
};
type SwarmCollectorCompletion = NonNullable<SubagentRunReadRecord["collectorCompletion"]> & {
  structured?: unknown;
  schemaError?: string;
  usage?: {
    inputTokens: number;
    outputTokens: number;
  };
  /** Set only when the registry sweeper settled a collector that yielded without a result. */
  reason?: "yielded_without_result";
};
type SwarmStructuredOutputState = {
  structured?: unknown;
  schemaError?: string;
  invalidAttempts: number;
};
/** Durable outbox state for the top-level requester settle wake. */
type RequesterSettleWakeState = {
  /** Pending message-wait notice; consuming it leaves the completion cohort armed. */
  pauseNotice?: {
    acknowledgment: string;
  };
  status: "pending" | "dispatching";
  /** Number of delivery attempts already admitted. */
  attemptCount: number;
  /** Raw private input retained with its exact dispatch identity until this wake settles. */
  privateInput?: {
    runId: string;
    message: string;
  };
  /** Retained retry receipt from an admitted attempt; mailbox admission owns scheduling. */
  nextAttemptAt?: number;
  /** Frozen wave membership after delivery admission or requester-yield re-admission. */
  batchRunIds?: string[];
  /** Batch frozen while its spawning requester turn was yielding. */
  requesterYieldBatch?: true;
  /** Exact parked lifecycle this cohort must settle if no continuation starts. */
  requesterRunId?: string;
  /** Present only when an idle requester needs a new turn after yielding. */
  afterRequesterYield?: true;
  /**
   * A yielded batch with private results was admitted with a deliverable requester
   * final. Absent on a dispatching private batch means an earlier build admitted it
   * as a private turn; replay keeps that policy.
   */
  yieldedFinalDeliverable?: true;
  /** Monotonic process generation protecting a newer yield from stale completion. */
  rearmGeneration?: number;
  /** Reference to the conversation receipt for this presentation, not completion credit. */
  progressOperationId?: string;
  lastError?: string | null;
  /** Cleanup wanted to retire this row; defer deletion until the outbox resolves. */
  retireAfterSettle?: boolean;
};
type SubagentKillReconciliationState = {
  /** Actual cancellation time; a yielded run may have an older execution end. */
  killedAt: number;
  /** The current lifecycle accepted a live kill claim before terminalization. */
  taskCancellationAccepted?: true;
  /** Requester aborts must not re-inject a delayed completion after queues are cleared. */
  suppressTaskDelivery?: boolean;
  /** Durable ownership boundary even after the newer registry row is released. */
  supersededAt?: number;
};
type SubagentKillIntent = {
  requestedAt: number;
  reason: string;
  lifecycleGeneration?: string;
  sessionId?: string;
  sessionLifecycleRevision?: string;
  suppressTaskDelivery?: boolean;
};
type SubagentRunRecord = Omit<SubagentRunReadRecord, "execution" | "collectorCompletion"> & {
  /** Host-captured SDK spawn provenance; absence never establishes plugin ownership. */
  nativePluginOwner?: {
    version: 1;
    pluginId: string;
    requesterProfileId: string;
    requestId: string;
  };
  /** Exact package instructions used at child creation; not runtime authority. */
  subagentProfile?: {
    pluginId: string;
    id: string;
    instructionsFile: string;
    instructionsSha256: string;
  };
  /** Child identity stays fixed when a live turn redirects transcript writes. */
  childSessionIdentity?: Pick<SessionEntry, "sessionId" | "lifecycleRevision">;
  /** Exact requester attempt for cancellation, independent of completion messaging. */
  requesterTurnRunId?: string;
  /** Durable proof that this requester attempt invoked sessions_yield. */
  requesterTurnYielded?: true;
  /** Durable explicit continuation wait, independent of the one-shot pause notice. */
  waitForMessage?: true;
  /** Completion-producing row retirement deferred until requesterTurnRunId settles. */
  retireAfterRequesterTurn?: boolean;
  requesterOrigin?: DeliveryContext;
  /** Durable source locator for transport-neutral progress presentation. */
  progressOrigin?: SubagentProgressOrigin;
  requesterDisplayKey: string;
  task: string;
  taskName?: string;
  cleanup: "delete" | "keep";
  label?: string;
  agentDir?: string;
  workspaceDir?: string;
  spawnMode?: SpawnSubagentMode;
  archiveAtMs?: number;
  cleanupHandled?: boolean;
  suppressAnnounceReason?: "steer-restart" | "killed";
  /** Present only while a current-version killed run awaits bounded reconciliation. */
  killReconciliation?: SubagentKillReconciliationState;
  /** Durable operator cancellation ownership before runtime side effects complete. */
  killIntent?: SubagentKillIntent;
  /** Durable requester-delivery closure until silent completion cleanup finishes. */
  suppressCompletionDelivery?: boolean;
  expectsCompletionMessage?: boolean;
  completionTarget?: "parent";
  completionRequesterSessionId?: string;
  completionRequesterLifecycleRevision?: string;
  wakeOnDescendantSettle?: boolean;
  execution: SubagentExecutionState;
  completion?: SubagentCompletionState;
  /** Set after the subagent_ended hook has been emitted successfully once. */
  endedHookEmittedAt?: number;
  /** Set after cleanupBrowserSessionsForLifecycleEnd has been dispatched once. */
  browserCleanupDispatchedAt?: number;
  /** Set immediately before irreversible sessions.delete cleanup is dispatched. */
  deleteCleanupDispatchedAt?: number;
  /** Requester wake owned by the live child task. */
  requesterSettleWake?: RequesterSettleWakeState;
  /** Generated identity under the host-owned per-agent attachment root. */
  attachmentId?: string;
  /** Legacy persisted absolute paths are never used for cleanup. */
  attachmentsDir?: string;
  attachmentsRootDir?: string;
  retainAttachmentsOnKeep?: boolean;
  /** Spawner plus ancestor sessions authorized to wait, frozen when the collector is registered. */
  swarmWaitOwnerSessionKeys?: string[];
  /** Exact host-reserved Gateway request identity for the current collector turn. */
  swarmLaunchIdempotencyKey?: string;
  /** Canonical collector request hash paired with a host-reserved launch identity. */
  swarmLaunchRequestFingerprint?: string;
  /** True only between host reservation and accepted Gateway dispatch. */
  swarmLaunchPending?: boolean;
  outputSchema?: Record<string, unknown>;
  structuredOutput?: SwarmStructuredOutputState;
  /** Durable retry obligation for a prepared collector session whose launch failed. */
  collectorLaunchCleanupPending?: boolean;
  /** Set after failed-launch context-engine cleanup succeeds, preventing duplicate end hooks. */
  contextEngineCleanupCompletedAt?: number;
  collectorCompletion?: SwarmCollectorCompletion;
};
//#endregion
//#region src/agents/subagents/registry/subagent-registry-queries.d.ts
type SubagentRunReadIndex<T extends SubagentRunReadRecord = SubagentRunRecord> = {
  inputs: {
    runs: Map<string, T>;
    inMemoryRuns: Iterable<T>;
  };
  /** Identity of published topology facts, shared by clock-specific views. */
  revision: object;
  /** Reuse prepared topology while leaving the captured view unchanged. */
  atTime(now: number): SubagentRunReadIndex<T>;
  /** Mutate this owner's topology; callers retire earlier views before applying changes. */
  patch(changes: ReadonlyMap<string, T | undefined>, inMemoryChanges: ReadonlyMap<string, T | undefined>, now?: number): SubagentRunReadIndex<T>;
  getDisplaySubagentRun(childSessionKey: string): T | null;
  latestRunsByChildSessionKey: ReadonlyMap<string, T>;
  runsByChildSessionKey: ReadonlyMap<string, readonly T[]>;
  requesterSessionKeys(): Iterable<string>;
  countActiveDescendantRuns(rootSessionKey: string): number;
  /** Inclusive grace boundary; time-dependent facts are unchanged through this instant. */
  nextChangeAt(rootSessionKey: string): number;
  hasUnendedRuns(rootSessionKey: string): boolean;
  countPendingDescendantRuns(rootSessionKey: string, options?: {
    excludeSuspendedDelivery?: boolean;
  }): number;
  hasDescendantRunAwaitingSettle(rootSessionKey: string, excludeRunId?: string, settledBefore?: number): boolean;
  listDescendantRunsForRequester(rootSessionKey: string): T[];
  runsByControllerSessionKey: ReadonlyMap<string, readonly T[]>;
  swarmRunsByRequesterSessionKey: ReadonlyMap<string, readonly T[]>;
};
//#endregion
//#region src/gateway/current-user-profile-display.d.ts
type CurrentUserProfileDisplay = {
  kind: "resolved";
  profileId: string;
  label?: string;
  avatarUrl: string;
  hasUploadedAvatar: boolean;
} | {
  kind: "unresolved";
};
//#endregion
//#region src/gateway/session-list-order.d.ts
type SessionEntryPair = [string, InternalSessionEntry];
declare function compareSessionEntryPairs(a: SessionEntryPair, b: SessionEntryPair, sortBy?: SessionsListParams["sortBy"]): number;
//#endregion
//#region src/gateway/session-identity-projection.d.ts
type SessionActorProfileIdentity = Extract<CurrentUserProfileDisplay, {
  kind: "resolved";
}>;
type SessionIdentityProjection = ReturnType<typeof createSessionIdentityProjection>;
/** The row owner invalidates these facts on profile/config publication; entry replacement is exact. */
declare function createSessionIdentityProjection(): {
  readonly revision: {};
  invalidate(): void;
  involvement(this: void, entry: InternalSessionEntry, profiles: Parameters<typeof projectSessionProfileInvolvements>[1]): ReadonlyMap<string, SessionProfileInvolvement>;
  owner: (entry: InternalSessionEntry | undefined, profiles: Map<string, {
    kind: "resolved";
    profileId: string;
    label?: string;
    avatarUrl: string;
    hasUploadedAvatar: boolean;
  } | undefined> | undefined, cfg: OpenClawConfig, configuredAgentIds: ReadonlySet<string> | undefined) => ({
    actor: {
      type: "agent" | "human" | "system";
      id?: string | undefined;
      label?: string | undefined;
      avatarUrl?: string | undefined;
      identity?: {
        type: "profile";
        id: string;
      } | {
        type: "agent";
        id: string;
      } | {
        type: "remote";
        pluginId: string;
        domain: string;
        idKind: string;
        id: string;
      } | {
        type: "observation";
        pluginId: string | null;
        accountId: string | null;
        senderKind: "bot" | "human" | "unknown";
        id: string;
      } | {
        type: "legacy";
        actorType: string;
        source: string | null;
        id: string;
      } | undefined;
    };
    assignedBy?: {
      type: "agent" | "human" | "system";
      id?: string | undefined;
      label?: string | undefined;
      avatarUrl?: string | undefined;
      identity?: {
        type: "profile";
        id: string;
      } | {
        type: "agent";
        id: string;
      } | {
        type: "remote";
        pluginId: string;
        domain: string;
        idKind: string;
        id: string;
      } | {
        type: "observation";
        pluginId: string | null;
        accountId: string | null;
        senderKind: "bot" | "human" | "unknown";
        id: string;
      } | {
        type: "legacy";
        actorType: string;
        source: string | null;
        id: string;
      } | undefined;
    } | undefined;
    assignedAt?: number | undefined;
  } & {
    actor: SessionOwnerFacetIdentity;
  }) | undefined;
  participants(this: void, ...args: Parameters<typeof projectSessionParticipants>): ReadonlyMap<string, SessionParticipant>;
  people(this: void, ...args: Parameters<typeof projectSessionPeople>): readonly SessionPerson[];
};
/** Resolve merged profiles without rewriting personal choices in other agent stores. */
declare function projectSessionProfileInvolvements(entry: InternalSessionEntry, profiles: Map<string, SessionActorProfileIdentity | undefined>): Map<string, SessionProfileInvolvement>;
declare function projectSessionParticipants(entry: InternalSessionEntry | undefined, userProfileIdentityById: Map<string, SessionActorProfileIdentity | undefined> | undefined, cfg: OpenClawConfig): Map<string, SessionParticipant>;
/** Participation, creation, and responsibility are associations, never access grants. */
declare function projectSessionPeople(entry: InternalSessionEntry, identities: Map<string, SessionActorProfileIdentity | undefined>, owner?: SessionOwnerFacetIdentity): SessionPerson[];
//#endregion
//#region src/gateway/session-utils-contracts.d.ts
type GatewayModelThinkingProfile = {
  thinkingLevels: ReturnType<typeof listThinkingLevelOptions>;
  thinkingDefault?: ThinkLevel;
};
type GatewayModelThinkingFacts = {
  profile: ReturnType<typeof resolveThinkingProfile>;
  metadata: GatewayModelThinkingProfile;
};
type GatewaySessionModelSource = {
  entry: SessionEntry | undefined;
  readSourceEntry: (key: string) => SessionEntry | undefined;
};
type SessionListRowContext = {
  identityProjection?: SessionIdentityProjection;
  workerPlacementEnvironment?: NodeJS.ProcessEnv;
  projectedAgentRuns?: ProjectedAgentRunIndex;
  projectedSubagentActivity?: ReadonlySet<string>;
  subagentRuns: SubagentRunReadIndex<SubagentRunReadRecord>;
  subagentRunsByChildSessionKey: ReadonlyMap<string, readonly SubagentRunReadRecord[]>;
  configuredDefaultModelByAgent: Map<string, ReturnType<typeof resolveSessionModelRef>>;
  thinkingFactsByModelRef: Map<string, GatewayModelThinkingFacts>;
  findModelCatalogEntry: typeof findModelCatalogEntry;
  selectModelCatalogRuntimeEntry: typeof selectModelCatalogRuntimeEntry;
  displayModelIdentityByKey: Map<string, {
    metadataSnapshot?: PluginMetadataSnapshot | null;
    identity: {
      provider?: string;
      model?: string;
    };
  }>;
  modelCostConfigByModelRef: Map<string, ModelCostConfig | undefined>;
  userProfileIdentityById: Map<string, SessionActorProfileIdentity | undefined>;
};
type SessionChildActivity = {
  revision?: object;
  childSessions: string[] | undefined;
  hasActiveSubagentRun: boolean;
};
//#endregion
//#region src/sessions/stored-model-overrides.d.ts
/** Model override loaded from the current session or its parent session. */
type StoredModelOverride = {
  provider?: string;
  model: string;
  source: "session" | "parent";
  routeResolution: ModelFallbackRouteResolution;
};
/** @deprecated Use resolveStoredModelOverrideAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveStoredModelOverride(params: {
  loadSessionEntry?: (sessionKey: string) => SessionEntry | undefined;
  sessionEntry?: SessionEntry;
  sessionStore?: Record<string, SessionEntry>;
  sessionKey?: string;
  parentSessionKey?: string;
  defaultProvider: string;
  allowPluginNormalization?: boolean;
}): StoredModelOverride | null;
/** Resolve inherited model selection without synchronous session-store access. */
declare function resolveStoredModelOverrideAsync(params: Omit<Parameters<typeof resolveStoredModelOverride>[0], "loadSessionEntry"> & {
  loadSessionEntry?: (sessionKey: string) => SessionEntry | undefined | Promise<SessionEntry | undefined>;
}): Promise<StoredModelOverride | null>;
//#endregion
//#region packages/acp-core/src/types.d.ts
type SessionAcpIdentitySource = "ensure" | "status" | "event";
type SessionAcpIdentityState = "pending" | "resolved";
type SessionAcpIdentity = {
  /** Pending identities may expose provisional ids; resolved identities are safe for resume output. */
  state: SessionAcpIdentityState;
  acpxRecordId?: string;
  acpxSessionId?: string;
  agentSessionId?: string;
  /** Runtime lifecycle point that last supplied the identity fields. */
  source: SessionAcpIdentitySource;
  lastUpdatedAt: number;
};
type AcpSessionRuntimeOptions = {
  /**
   * ACP runtime mode set via session/set_mode (for example: "plan", "normal", "auto").
   */
  runtimeMode?: string;
  /** ACP runtime config option: model id. */
  model?: string;
  /** ACP runtime config option: thinking/reasoning effort. */
  thinking?: string;
  /** Working directory override for ACP session turns. */
  cwd?: string;
  /** ACP runtime config option: permission profile id. */
  permissionProfile?: string;
  /** ACP runtime config option: per-turn timeout in seconds. */
  timeoutSeconds?: number;
  /** Backend-specific option bag mapped through session/set_config_option. */
  backendExtras?: Record<string, string>;
};
type SessionAcpMeta = {
  backend: string;
  agent: string;
  runtimeSessionName: string;
  /** Canonical backend/agent ids used for resume hints and thread/status details. */
  identity?: SessionAcpIdentity;
  mode: "persistent" | "oneshot";
  runtimeOptions?: AcpSessionRuntimeOptions;
  cwd?: string;
  state: "idle" | "running" | "error";
  lastActivityAt: number;
  lastError?: string;
};
//#endregion
//#region src/config/sessions/targets.d.ts
type ExistingAgentSessionStoreTargetResolver = (agentId: string, excludeStorePath?: string) => SessionStoreTarget[];
//#endregion
//#region src/config/sessions/combined-store-model-sources.d.ts
type GatewayStoredSessionTarget = GatewaySessionModelSource & {
  agentId: string;
  /** Exact stored key when a list uses an internal key to retain sentinel owners. */
  storeKey?: string;
  storeTarget: SessionStoreTarget;
  resolveSourceKey: (key: string) => string;
};
//#endregion
//#region src/gateway/session-row-placement-projection.types.d.ts
type SessionRowPlacementFacts = {
  placement: WorkerSessionPlacementRecord | undefined;
  move: WorkerPlacementMoveIntent | undefined;
  environment: WorkerEnvironmentPlacementFacts | undefined;
  workspaceResultReconciling: boolean;
  workspaceRecoveryPending: boolean;
};
type SessionRowPlacementFactsReader = {
  getProjectionFacts(id: string): SessionRowPlacementFacts | undefined;
};
//#endregion
//#region src/gateway/worker-environments/placement-projector.d.ts
type WorkerSessionPlacementReader = Pick<WorkerSessionPlacementStore, "getMany"> & Partial<Pick<WorkerSessionPlacementStore, "getManyAsync" | "prepareSessionPlacement" | "prepareRuntimeRefresh" | "getWorkspaceResultReconcilingSessionIds" | "getWorkspaceResultReconcilingSessionIdsAsync" | "listPendingWorkspaceResults" | "listPendingWorkspaceResultsAsync" | "registerTurnClaimClosedHandler">>;
type WorkerPlacementDiskSpaceReader = {
  read(record: WorkerSessionPlacementRecord): SessionPlacementDiskSpace | undefined;
  version(): number;
};
type WorkerPlacementRunnerAvailabilityReader = {
  read(record: WorkerSessionPlacementRecord, environment?: Pick<WorkerEnvironmentPlacementFacts, "providerId" | "state" | "ownerEpoch" | "attachedSessionIds" | "nodeDeviceId"> | null): SessionPlacementRunner | undefined;
  version(): number;
};
type WorkerPlacementRuntimeInstallReader = {
  read(record: WorkerSessionPlacementRecord, environment?: Pick<WorkerEnvironmentPlacementFacts, "nodeDeviceId"> | null): SessionPlacementWorkerRuntimeInstall | undefined;
  version(): number;
};
//#endregion
//#region src/gateway/server-methods/session-placement-read-projection.d.ts
/** Acquire row facts once; selected rows refresh placement facts after owner publications. */
declare function readSessionRowFacts(params: {
  cfg: OpenClawConfig;
  target: Pick<GatewayStoredSessionTarget, "agentId" | "storeTarget"> & {
    key: string;
  };
  entry: SessionEntry;
  preparedRuntimeOwnership?: AgentHarnessSessionRuntimeOwnership | null;
  context?: {
    workerPlacementDiskSpaceReader?: WorkerPlacementDiskSpaceReader;
    workerPlacementRunnerAvailabilityReader?: WorkerPlacementRunnerAvailabilityReader;
    workerPlacementRuntimeInstallReader?: WorkerPlacementRuntimeInstallReader;
    workerEnvironmentService?: Pick<WorkerEnvironmentServiceContract, "get" | "readMachineShape">;
  };
  placementFactsReader?: SessionRowPlacementFactsReader;
  activitySummaryEnabled?: boolean;
  databaseFacts: Pick<SessionRowDatabaseFacts, "hasBoard" | "activitySummaryWatermark">;
}): {
  hasBoard: boolean;
  matchesRuntimeOwnership: (next: AgentHarnessSessionRuntimeOwnership | null | undefined) => boolean;
  matches(next: Parameters<typeof readSessionRowFacts>[0]): boolean;
  refreshActivitySummary(databaseFacts?: Pick<SessionRowDatabaseFacts, "activitySummaryWatermark" | "hasBoard">): void;
  present: () => Readonly<Pick<GatewaySessionRow, "activitySummary" | "permissionModePending" | "placement" | "placementMove" | "sessionModelRevision">>;
};
//#endregion
//#region src/shared/session-list-visibility.d.ts
/**
 * Classify internal lanes from provenance or reserved keys, never transcript text.
 * Legacy rows without either and operator-named CLI sessions remain discoverable.
 * Cron rows belong to the separate automation filter even when a system created them.
 */
declare function isSystemCreatedSessionRow(row: {
  key: string;
  createdActor?: {
    type: string;
  };
  createdVia?: string;
  label?: string;
  displayName?: string;
  subject?: string;
  classification?: string;
}): boolean;
//#endregion
//#region src/gateway/session-utils-core.d.ts
type SessionChildLink = {
  key: string;
  entry: SessionEntry;
  agentId?: string;
  storePath?: string;
};
//#endregion
//#region src/gateway/session-utils-row.d.ts
declare function readSessionRowInputs(params: {
  cfg: OpenClawConfig;
  storePath: string;
  storeAgentId?: string;
  active?: boolean;
  /** A supplied resident model avoids transcript reads; null uses only stored model facts. */
  activeModel?: {
    provider: string;
    model: string;
  } | null;
  terminalModel?: {
    modelProvider: string;
    model: string;
  } | null;
  store: Record<string, SessionEntry>;
  modelSource?: GatewaySessionModelSource;
  key: string;
  entry?: InternalSessionEntry;
  preparedAcpMeta?: SessionEntry["acp"] | null;
  preparedRuntimeOwnership?: AgentHarnessSessionRuntimeOwnership | null;
  preparedModelMetadata?: PluginMetadataSnapshot | null;
  preparedRepositoryWorkspace?: Readonly<SessionRepositoryWorkspaceRecord> | null;
  modelCatalog?: SessionListModelCatalog | ModelCatalogEntry[];
  now?: number;
  preparedTitle?: Pick<GatewaySessionRow, "derivedTitle" | "lastMessagePreview" | "lastAssistantMessage">;
  childLinks?: readonly SessionChildLink[];
  excludedChildKeys?: ReadonlySet<string>;
  rowContext?: SessionListRowContext;
  configuredAgentIds?: ReadonlySet<string>;
  agentId: string;
  skipTranscriptUsageFallback?: boolean;
  transcriptUsage?: SessionTranscriptUsageSnapshot | null;
  lightweightListRow?: boolean;
  includeSwarmChildren?: boolean;
}): {
  inputs: {
    cfg: OpenClawConfig;
    key: string;
    entry: InternalSessionEntry | undefined;
    lightweight: boolean;
    preparedRuntimeOwnership: AgentHarnessSessionRuntimeOwnership | null | undefined;
    swarm: {
      groups: {
        groupId: string;
        createdAt: number;
        children?: {
          sessionKey: string;
          status: "done" | "failed" | "queued" | "running";
        }[] | undefined;
        queued: number;
        running: number;
        done: number;
        failed: number;
      }[];
      otherActiveGroups: number;
    } | undefined;
    permissionModePending: boolean;
    repository: {
      url: string;
      ref?: string | undefined;
      branch: string;
    } | undefined;
    userProfileIdentityById: Map<string, {
      kind: "resolved";
      profileId: string;
      label?: string;
      avatarUrl: string;
      hasUploadedAvatar: boolean;
    } | undefined>;
    identityProjection: {
      readonly revision: {};
      invalidate(): void;
      involvement(this: void, entry: InternalSessionEntry, profiles: Parameters<typeof projectSessionProfileInvolvements>[1]): ReadonlyMap<string, SessionProfileInvolvement>;
      owner: (entry: InternalSessionEntry | undefined, profiles: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig, configuredAgentIds: ReadonlySet<string> | undefined) => ({
        actor: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        };
        assignedBy?: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        } | undefined;
        assignedAt?: number | undefined;
      } & {
        actor: SessionOwnerFacetIdentity;
      }) | undefined;
      participants(this: void, entry: InternalSessionEntry | undefined, userProfileIdentityById: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig): ReadonlyMap<string, SessionParticipant>;
      people(this: void, entry: InternalSessionEntry, identities: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined>, owner?: SessionOwnerFacetIdentity | undefined): readonly SessionPerson[];
    } | undefined;
    configuredAgentIds: ReadonlySet<string> | undefined;
    agentId: string;
    displayName: string | undefined;
    derivedTitle: string | undefined;
    lastMessagePreview: string | undefined;
    lastAssistantMessage: {
      text: string;
      timestamp: number;
    } | undefined;
    thinkingProjection: {
      acpMeta: SessionAcpMeta | undefined;
      catalogEntry: ModelCatalogEntry | undefined;
      capacityCatalogEntry: ModelCatalogEntry | undefined;
      capacityRuntime: string;
      agentRuntime: {
        id: string;
        source: "implicit" | "model" | "provider" | "session" | "session-key";
      };
      runtimeSelectionLocked: boolean;
      thinkingLevel: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
      effectiveThinkingLevel: NonNullable<"adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined> | undefined;
      thinkingLevels: {
        id: ThinkLevel;
        label: string;
      }[];
      thinkingOptions: string[];
      thinkingDefault: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
    };
    agentRuntime: {
      id: string;
      fallback?: "none" | "openclaw" | undefined;
      workspaceEnvironment?: {
        kind: "provider-hosted";
        label: string;
      } | undefined;
      cloudPlacementSupported?: boolean | undefined;
      cloudPlacementExecutionMode?: "remote-exec" | "worker-turn" | undefined;
      devicePlacement?: {
        requiredNodeCommands: string[];
        consumesWorkerSlot: boolean;
      } | undefined;
      devicePlacementSupported?: boolean | undefined;
      source: "agent" | "defaults" | "env" | "implicit" | "model" | "provider" | "session" | "session-key";
    } & {
      cloudPlacementSupported: boolean;
      cloudPlacementExecutionMode?: WorkerPlacementExecutionMode;
      devicePlacement?: NonNullable<GatewayAgentRuntime["devicePlacement"]>;
      devicePlacementSupported: boolean;
    };
    contextWindowProfile: {
      contextWindow: string | undefined;
      contextWindows: ModelCatalogContextWindowOption[] | undefined;
      contextWindowDefault: string | undefined;
      contextTokens: number | undefined;
    };
    fastModeState: {
      mode: FastMode;
      requestMode: FastMode | undefined;
      enabled: boolean;
      source: FastModeSource;
      fastAutoOnSeconds: number;
    };
    hasAutomation: boolean | undefined;
    rowModelIdentity: {
      provider?: string;
      model?: string;
    };
    selectedModel: {
      provider: string;
      model: string;
    } & {
      storedOverrideSource: StoredModelOverride["source"] | null;
    };
    contextTokens: number | undefined;
    pluginExtensions: PluginSessionExtensionProjection[];
    includeSwarmSummary: boolean;
    childLinks: readonly SessionChildLink[] | undefined;
    usageByFallbackModel: Map<string | undefined, {
      estimatedCostUsd?: number;
      totalTokens?: number;
      totalTokensFresh?: boolean;
      usageReport?: SessionEntry["usageReport"];
    } | null> | undefined;
    freshSessionTotalTokens: number | undefined;
    estimatedCostUsd: number | undefined;
    subagentRunInputs: {
      runs: Map<string, SubagentRunReadRecord>;
      inMemoryRuns: Iterable<SubagentRunReadRecord>;
    };
  };
  presentation: {
    now: number;
    subagentRuns: SubagentRunReadIndex<SubagentRunReadRecord>;
    projectedAgentRuns: ProjectedAgentRunIndex;
    projectedSubagentActivity: ReadonlySet<string> | undefined;
    activeModel: {
      provider: string;
      model: string;
    } | undefined;
    excludedChildKeys: ReadonlySet<string> | undefined;
  };
};
declare function materializeSessionRow(input: ReturnType<typeof readSessionRowInputs>["inputs"]): Readonly<{
  row: Readonly<GatewaySessionRow>;
  source: Readonly<{
    parsedKey: ParsedAgentSessionKey | null;
    cfg: OpenClawConfig;
    entry: InternalSessionEntry | undefined;
    selectedModel: {
      provider: string;
      model: string;
    } & {
      storedOverrideSource: StoredModelOverride["source"] | null;
    };
    rowModelIdentity: {
      provider?: string;
      model?: string;
    };
    thinkingProjection: {
      acpMeta: SessionAcpMeta | undefined;
      agentRuntime: {
        id: string;
        source: "implicit" | "model" | "provider" | "session" | "session-key";
      };
    };
    userProfileIdentityById: Map<string, {
      kind: "resolved";
      profileId: string;
      label?: string;
      avatarUrl: string;
      hasUploadedAvatar: boolean;
    } | undefined>;
    identityProjection: {
      readonly revision: {};
      invalidate(): void;
      involvement(this: void, entry: InternalSessionEntry, profiles: Parameters<typeof projectSessionProfileInvolvements>[1]): ReadonlyMap<string, SessionProfileInvolvement>;
      owner: (entry: InternalSessionEntry | undefined, profiles: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig, configuredAgentIds: ReadonlySet<string> | undefined) => ({
        actor: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        };
        assignedBy?: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        } | undefined;
        assignedAt?: number | undefined;
      } & {
        actor: SessionOwnerFacetIdentity;
      }) | undefined;
      participants(this: void, entry: InternalSessionEntry | undefined, userProfileIdentityById: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig): ReadonlyMap<string, SessionParticipant>;
      people(this: void, entry: InternalSessionEntry, identities: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined>, owner?: SessionOwnerFacetIdentity | undefined): readonly SessionPerson[];
    } | undefined;
    configuredAgentIds: ReadonlySet<string> | undefined;
    lightweight: boolean;
    usageByFallbackModel: Map<string | undefined, {
      estimatedCostUsd?: number;
      totalTokens?: number;
      totalTokensFresh?: boolean;
      usageReport?: SessionEntry["usageReport"];
    } | null> | undefined;
    freshSessionTotalTokens: number | undefined;
    estimatedCostUsd: number | undefined;
    subagentRunInputs: {
      runs: Map<string, SubagentRunReadRecord>;
      inMemoryRuns: Iterable<SubagentRunReadRecord>;
    };
    lastMessagePreview: string | undefined;
    lastAssistantMessage: {
      text: string;
      timestamp: number;
    } | undefined;
    childLinks: Readonly<{
      key: string;
      agentId: string | undefined;
      storePath: string | undefined;
      parsedKey: ParsedAgentSessionKey | null;
      entry: {
        sessionId: string;
        lifecycleRevision: string | undefined;
        updatedAt: number;
        archivedAt: number | undefined;
        status: PersistedSessionRunStatus | undefined;
        startedAt: number | undefined;
        endedAt: number | undefined;
        spawnedBy: string | undefined;
        parentSessionKey: string | undefined;
        sidebarRoot: boolean | undefined;
        createdActor: SessionCreatedActor | undefined;
        visibility: NonNullable<"draft" | "read-only" | "shared" | "suggest" | undefined> | undefined;
        incognito: true | undefined;
      };
    }[] | undefined>;
  }>;
}>;
//#endregion
//#region src/gateway/session-list-target.d.ts
declare function readSessionListSelectionFacts(key: string, entry?: {
  sessionId?: string;
  updatedAt?: number | null;
  spawnedBy?: string;
  category?: string;
  heartbeatIsolatedBaseSessionKey?: string;
  createdSurface?: "plugin-dock";
} & Omit<Parameters<typeof isSystemCreatedSessionRow>[0], "key" | "classification">): {
  agentId: string | undefined;
  isCronRun: boolean;
  isCron: boolean;
  isDock: boolean;
  isSystem: boolean;
  isSubagent: boolean;
  isPhantom: boolean;
};
//#endregion
//#region src/gateway/session-row-selection-facts.d.ts
/** Accepted selection facts exclude replaceable display graphs. */
type SelectionRow = {
  key: string;
  agentId: string;
  storeTarget: SessionStoreTarget;
  entry: InternalSessionEntry;
  selection: ReturnType<typeof readSessionListSelectionFacts>;
  hasBoard?: boolean;
  generation: string | symbol;
  selectionFactsRevision?: object;
};
//#endregion
//#region src/gateway/session-row-projection-record.d.ts
type ProjectionOptions = {
  cfg: OpenClawConfig;
  getConfig?: () => OpenClawConfig;
  getPolicyConfig?: () => OpenClawConfig;
  modelCatalog?: Inputs["modelCatalog"];
  getModelCatalog?: () => Promise<Inputs["modelCatalog"]>;
  context?: Parameters<typeof readSessionRowFacts>[0]["context"];
  placementFactsReader?: Pick<WorkerSessionPlacementStore, "readProjection">;
};
type PreparedSessionRowDatabaseFacts = SessionRowDatabaseFacts & {
  acpMeta: SessionAcpMeta | null;
  runtimeOwnership: AgentHarnessSessionRuntimeOwnership | null;
  runtimeOwnershipDependencies: readonly PluginStateReadDependency[];
  repositoryWorkspace: SessionRepositoryWorkspaceRecord | null;
};
/** Undefined shared facets await their owner; null is acknowledged absence. */
type RetainedSessionRowDatabaseFacts = SessionRowDatabaseFacts & Partial<Pick<PreparedSessionRowDatabaseFacts, "acpMeta" | "runtimeOwnership" | "runtimeOwnershipDependencies" | "repositoryWorkspace">>;
type SessionRowStore = {
  target: SessionStoreTarget;
  agentId: string;
  discoveryAgentId: string | null;
  discoveryOrder?: number;
  identity: OpenClawAgentDatabaseIdentity;
  birthtime: string | undefined;
  filename: string;
};
type Row = {
  key: string;
  agentId: string;
  storeTarget: SessionStoreTarget;
  storedEntry?: InternalSessionEntry;
  /** Committed archive metadata awaits the lineage registry before entry acquisition. */
  entryAcquisitionPending?: true;
  /** Accepted under retained database custody; presentation consumes the whole snapshot. */
  pendingDatabaseFacts?: PreparedSessionRowDatabaseFacts;
  /** Presentation retains committed facets until their owner publishes or the row is demoted. */
  retainedDatabaseFacts?: RetainedSessionRowDatabaseFacts;
  /** Durable search metadata survives archive demotion, until its owner invalidates it. */
  preparedAcpMeta?: SessionAcpMeta | null;
  preparedRuntimeOwnership?: AgentHarnessSessionRuntimeOwnership | null;
  runtimeOwnershipDependencies?: readonly PluginStateReadDependency[];
  databaseFactsRevision: number;
  publishedSource?: SessionEntryPublicationSource;
  /** Category uncertainty keeps identity resident; earlier structural uncertainty dominates. */
  unresolvedDatabaseFacts?: true | "category";
  /** Current committed sharing facts remain usable while display materialization is dirty. */
  sharingEntry?: InternalSessionEntry;
  entry?: InternalSessionEntry;
  selection: ReturnType<typeof readSessionListSelectionFacts>;
  /** One accepted selection snapshot shared by recents and list consumers. */
  selectionSnapshot?: SelectionRow;
  materialized?: ReturnType<typeof materializeSessionRow>;
  materializedSequence?: number;
  profileRevision?: number;
  subagentRevision?: number;
  lastMessagePreview?: string;
  lastAssistantMessage?: GatewaySessionRow["lastAssistantMessage"];
  fallbackModel?: ReturnType<typeof readSessionRowInputs>["presentation"]["activeModel"];
  facts?: ReturnType<typeof readSessionRowFacts>;
  hasBoard?: boolean;
  membership: ReadonlySet<string>;
  parents: Set<string>;
  generation: string | symbol;
  /** Exact private reads retain their session claim only for the consuming frame. */
  privateSource?: {
    identity: SessionActorVersion["epoch"];
    assertCurrent(): void;
  };
  preparedPrivate?: {
    relatedRows: Record<string, Pick<EntryRow, "key" | "agentId" | "storeTarget" | "entry">>;
    entries: Record<string, InternalSessionEntry>;
    databaseFacts: PreparedSessionRowDatabaseFacts;
    titleFields?: SessionTitleFields;
    terminalModel?: {
      modelProvider: string;
      model: string;
    };
  };
};
type SelectionChange = {
  kind: "reset";
} | {
  kind: "row";
  id: string;
  key: string;
  agentId: string;
  row: SelectionRow | undefined;
  /** Synchronous internal publication scope; deferred refreshes have no causal label. */
  scope?: string;
};
type Query = {
  agentId?: string;
  storePath?: string;
  key?: string;
  sessionIdOrKey?: string;
  candidateSessionIdsOrKeys?: ReadonlySet<string>;
  /** Prepared qualified rows carry identity; raw keys retain alias resolution. */
  parentSessionKey?: string | Pick<Row, "key" | "agentId">;
  sortBy?: Parameters<typeof compareSessionEntryPairs>[2] | null;
};
type Inputs = Parameters<typeof readSessionRowInputs>[0];
type SnapshotOptions = Pick<Inputs, "now" | "excludedChildKeys"> & {
  childActivity?: SessionChildActivity;
  includeDerivedTitles?: boolean;
  includeLastMessage?: boolean;
  active?: boolean;
  subagentRuns?: SessionListRowContext["subagentRuns"];
  preparedFacts?: ReturnType<NonNullable<Row["facts"]>["present"]>;
};
type Lookup = {
  agentId: string;
  key: string;
  storePath?: string;
};
type EntryRow = Row & Required<Pick<Row, "entry">>;
type MaterializedRow = EntryRow & Required<Pick<Row, "materialized">>;
declare function present(record: MaterializedRow, context: SessionListRowContext, options?: SnapshotOptions): GatewaySessionRow;
//#endregion
//#region src/gateway/session-row-child-activity.d.ts
/** The resident projection updates child contributions; consumers reuse their visible aggregate. */
declare function createSessionRowChildActivity(): {
  invalidate: (key?: string) => void;
  invalidateRuntime(keys?: Iterable<string>): void;
  remove: (record: Pick<Row, "agentId" | "key" | "storeTarget">) => void;
  clear(): void;
  read(record: MaterializedRow, context: SessionListRowContext, now: number, excluded?: ReadonlySet<string>, exclusionRevision?: object): SessionChildActivity;
};
//#endregion
//#region src/gateway/session-row-child-visibility.d.ts
type Visibility = {
  childKey?: string;
  swarmKey?: string;
  excludedChildKeys?: ReadonlySet<string>;
  excludedSwarmKeys?: ReadonlySet<string>;
  revision: object;
};
/** Committed child publications invalidate only their dependent parents' sharing results. */
declare function createSessionRowChildVisibility(): {
  clear: () => void;
  invalidate(key?: string): void;
  remove(record: Pick<Row, "agentId" | "key" | "storeTarget">): void;
  read(record: MaterializedRow, audienceKey: string, canRead: (key: string, entry: SessionSharingTarget["entry"], agentId?: string, storePath?: string) => boolean, selectEntries: (query: {
    key: string;
  }) => EntryRow[], includeSwarm?: boolean): Visibility;
};
//#endregion
//#region src/gateway/session-utils-store-candidates.d.ts
type GatewaySessionStoreDiscovery = {
  existing: readonly Readonly<SessionStoreTarget>[];
  fallback: SessionStoreTarget;
};
/**
 * Sharing resolves every returned row, but store targets are stable within one request.
 * Keep discovery agent-scoped here or each row repeats registry probes and agent-root scans.
 */
type GatewaySessionStoreDiscoveryCache = Map<string, GatewaySessionStoreDiscovery>;
//#endregion
//#region src/gateway/session-utils-store-read.d.ts
/** Request-local, read-only views avoid rematerializing a store for each sharing lookup. */
type GatewaySessionStoreView = {
  store: Record<string, SessionEntry>;
  readSource?: SessionEntryReadSource;
  capturedReadSource?: CapturedSessionEntryReadSource;
};
type GatewaySessionStoreCache = Map<string, GatewaySessionStoreView>;
type GatewaySessionStoreRead = {
  storePath: string;
  clone?: boolean;
  agentId?: string;
  options: {
    env?: NodeJS.ProcessEnv;
    readOnly?: boolean;
    cache?: GatewaySessionStoreCache;
    exactKeys?: readonly string[];
    projection?: SessionEntryReadScope["projection"];
    readConsistency?: SessionEntryReadScope["readConsistency"];
    readSource?: SessionEntryReadSource;
  };
  result?: Record<string, SessionEntry>;
  readSource?: SessionEntryReadSource;
  capturedReadSource?: CapturedSessionEntryReadSource;
};
/** Single-target resolution keeps its original lazy read and failure order. */
declare function readGatewaySessionStore(read: GatewaySessionStoreRead): Record<string, SessionEntry>;
//#endregion
//#region src/gateway/session-utils-store-lookup.d.ts
type GatewaySessionStoreLookupParams = {
  env?: NodeJS.ProcessEnv;
  cfg: OpenClawConfig;
  key: string;
  agentId?: string;
  preserveQualifiedAddress?: boolean;
  clone?: boolean;
  projection?: SessionEntryReadScope["projection"];
  readConsistency?: SessionEntryReadScope["readConsistency"];
  readOnly?: boolean;
  exactRead?: boolean;
  includeStoreChildEntries?: boolean;
  store?: Record<string, SessionEntry>;
  storeCache?: GatewaySessionStoreCache;
  targetDiscoveryCache?: GatewaySessionStoreDiscoveryCache;
  resolveExistingTargets?: ExistingAgentSessionStoreTargetResolver;
  readStore?: typeof readGatewaySessionStore;
};
//#endregion
//#region src/gateway/session-row-prepared-read.d.ts
type SessionRowSelectionPreparationOptions = {
  metadataOnly?: boolean;
  includeCatalog?: boolean;
  requireCurrentCatalog?: boolean;
  catalogSignal?: AbortSignal;
};
type SessionRowPreparationOptions = {
  includeAncestors?: boolean;
  /** Queries select canonical durable roster keys; private exact reads use the default path. */
  selection?: boolean | SessionRowSelectionPreparationOptions;
};
type SessionRowReadView = {
  readChildVisibility: ReturnType<typeof createSessionRowChildVisibility>["read"];
  readChildActivity(record: MaterializedRow, now: number, excluded?: ReadonlySet<string>, exclusionRevision?: object): ReturnType<ReturnType<typeof createSessionRowChildActivity>["read"]>;
  describe(query: Lookup, captured?: Row, repositoryWorkspace?: Readonly<SessionRepositoryWorkspaceRecord> | null): MaterializedRow | undefined;
  readSource(row: MaterializedRow): CapturedSessionEntryReadSource | undefined;
  readMembership(query: Lookup): ReadonlySet<string> | undefined;
  present(record: MaterializedRow, options?: SnapshotOptions): ReturnType<typeof present>;
  selectEntries(query: {
    key: string;
  }): EntryRow[];
  readonly physicalPaths: (locator: string, agentId?: string) => readonly string[];
  readonly state: {
    cfg: OpenClawConfig;
    policyConfig: OpenClawConfig;
    rowContext: SessionListRowContext;
  };
};
//#endregion
//#region src/gateway/session-row-scope.d.ts
/** Discover current keys in SQLite, then prepare every physical competitor before federation. */
declare function readSessionRowLookup(selection: {
  kind: "session-id-or-key";
  sessionIdOrKey: string;
} | {
  kind: "label";
  label: string;
}, owner: {
  agentId?: string;
  env: NodeJS.ProcessEnv;
  stores: ReadonlyMap<string, SessionRowStore>;
  paths: ReadonlyMap<string, number>;
  matching: (query: {
    key: string;
  }) => Row[];
}): Promise<Lookup[]>;
/** Resolve query-specific federation once when the physical topology is published. */
declare function prepareSessionRowScopes(cfg: OpenClawConfig, agentIds: Iterable<string>, residentPaths: ReadonlyMap<string, string>, prepared: CombinedSessionStoreScopeTargets): {
  select: (options: {
    agentId?: string;
    configuredAgentsOnly?: boolean;
  }) => {
    targets: readonly SessionStoreTarget[];
    paths: Map<string, number>;
    path: string;
    configuredAgentIds: ReadonlySet<string> | undefined;
    ownerAgentIds: ReadonlySet<string>;
    agentId: string | undefined;
  };
  physicalPaths(this: void, locator: string, agentId?: string): readonly string[];
};
//#endregion
//#region src/gateway/session-row-projection.d.ts
/** Committed publications own invalidation; each admitted physical store is hydrated once. */
declare function createSessionRowProjection(params: ProjectionOptions): Promise<{
  readChildVisibility: (...args: Parameters<(record: MaterializedRow, audienceKey: string, canRead: (key: string, entry: SessionSharingTarget["entry"], agentId?: string, storePath?: string) => boolean, selectEntries: (query: {
    key: string;
  }) => EntryRow[], includeSwarm?: boolean) => {
    childKey?: string;
    swarmKey?: string;
    excludedChildKeys?: ReadonlySet<string>;
    excludedSwarmKeys?: ReadonlySet<string>;
    revision: object;
  }>) => {
    childKey?: string;
    swarmKey?: string;
    excludedChildKeys?: ReadonlySet<string>;
    excludedSwarmKeys?: ReadonlySet<string>;
    revision: object;
  };
  readChildActivity: (record: MaterializedRow, now: number, excluded?: ReadonlySet<string>, revision?: object) => SessionChildActivity;
  present(record: MaterializedRow, options?: SnapshotOptions): GatewaySessionRow;
  modelFacts: (query: Lookup, metadataPrepared?: boolean) => Readonly<{
    parsedKey: ParsedAgentSessionKey | null;
    cfg: OpenClawConfig;
    entry: InternalSessionEntry | undefined;
    selectedModel: {
      provider: string;
      model: string;
    } & {
      storedOverrideSource: StoredModelOverride["source"] | null;
    };
    rowModelIdentity: {
      provider?: string;
      model?: string;
    };
    thinkingProjection: {
      acpMeta: SessionAcpMeta | undefined;
      agentRuntime: {
        id: string;
        source: "implicit" | "model" | "provider" | "session" | "session-key";
      };
    };
    userProfileIdentityById: Map<string, {
      kind: "resolved";
      profileId: string;
      label?: string;
      avatarUrl: string;
      hasUploadedAvatar: boolean;
    } | undefined>;
    identityProjection: {
      readonly revision: {};
      invalidate(): void;
      involvement(this: void, entry: InternalSessionEntry, profiles: Parameters<typeof projectSessionProfileInvolvements>[1]): ReadonlyMap<string, SessionProfileInvolvement>;
      owner: (entry: InternalSessionEntry | undefined, profiles: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig, configuredAgentIds: ReadonlySet<string> | undefined) => ({
        actor: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        };
        assignedBy?: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        } | undefined;
        assignedAt?: number | undefined;
      } & {
        actor: SessionOwnerFacetIdentity;
      }) | undefined;
      participants(this: void, entry: InternalSessionEntry | undefined, userProfileIdentityById: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined> | undefined, cfg: OpenClawConfig): ReadonlyMap<string, SessionParticipant>;
      people(this: void, entry: InternalSessionEntry, identities: Map<string, {
        kind: "resolved";
        profileId: string;
        label?: string;
        avatarUrl: string;
        hasUploadedAvatar: boolean;
      } | undefined>, owner?: SessionOwnerFacetIdentity | undefined): readonly SessionPerson[];
    } | undefined;
    configuredAgentIds: ReadonlySet<string> | undefined;
    lightweight: boolean;
    usageByFallbackModel: Map<string | undefined, {
      estimatedCostUsd?: number;
      totalTokens?: number;
      totalTokensFresh?: boolean;
      usageReport?: SessionEntry["usageReport"];
    } | null> | undefined;
    freshSessionTotalTokens: number | undefined;
    estimatedCostUsd: number | undefined;
    subagentRunInputs: {
      runs: Map<string, SubagentRunReadRecord>;
      inMemoryRuns: Iterable<SubagentRunReadRecord>;
    };
    lastMessagePreview: string | undefined;
    lastAssistantMessage: {
      text: string;
      timestamp: number;
    } | undefined;
    childLinks: Readonly<{
      key: string;
      agentId: string | undefined;
      storePath: string | undefined;
      parsedKey: ParsedAgentSessionKey | null;
      entry: {
        sessionId: string;
        lifecycleRevision: string | undefined;
        updatedAt: number;
        archivedAt: number | undefined;
        status: PersistedSessionRunStatus | undefined;
        startedAt: number | undefined;
        endedAt: number | undefined;
        spawnedBy: string | undefined;
        parentSessionKey: string | undefined;
        sidebarRoot: boolean | undefined;
        createdActor: SessionCreatedActor | undefined;
        visibility: NonNullable<"draft" | "read-only" | "shared" | "suggest" | undefined> | undefined;
        incognito: true | undefined;
      };
    }[] | undefined>;
  }> | {
    selectedModel: {
      provider: string;
      model: string;
    } & {
      storedOverrideSource: StoredModelOverride["source"] | null;
    };
    rowModelIdentity: {
      provider?: string;
      model?: string;
    };
    thinkingProjection: {
      acpMeta: SessionAcpMeta | undefined;
      catalogEntry: ModelCatalogEntry | undefined;
      capacityCatalogEntry: ModelCatalogEntry | undefined;
      capacityRuntime: string;
      agentRuntime: {
        id: string;
        source: "implicit" | "model" | "provider" | "session" | "session-key";
      };
      runtimeSelectionLocked: boolean;
      thinkingLevel: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
      effectiveThinkingLevel: NonNullable<"adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined> | undefined;
      thinkingLevels: {
        id: ThinkLevel;
        label: string;
      }[];
      thinkingOptions: string[];
      thinkingDefault: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh" | undefined;
    };
    catalogEntry: ModelCatalogEntry | undefined;
  };
  modelSearchMayMatch(search: string): boolean;
  readCapabilityEntry: (query: {
    agentId: string;
    storePath: string;
  } & ({
    key: string;
    sessionId?: never;
  } | {
    sessionId: string;
    key?: never;
  })) => {
    entry: InternalSessionEntry | undefined;
  } | undefined;
  findUrlCandidates(selection: {
    shortId: string;
  } | {
    key: string;
    slug?: string;
  }, agentId?: string): {
    agentId: string;
    key: string;
    storePath: string;
  }[];
  readPreview(query: Lookup): {
    entry: InternalSessionEntry;
    sessionKey: string;
    agentId: string;
    title: string | undefined;
    derivedTitle: string | undefined;
    kind: "direct" | "global" | "group" | "unknown";
    channel: string | undefined;
    updatedAt: number;
    lastMessagePreview: string | undefined;
    archived: boolean;
  } | null | undefined;
  readLookup(selection: Parameters<typeof readSessionRowLookup>[0], agentId?: string): Promise<{
    queries: Lookup[];
    isCurrent: () => boolean;
  }>;
  capture(query: Lookup): Row | undefined;
  findBySessionId(query: Parameters<(query: {
    sessionId: string;
    agentId?: string;
    storePath?: string;
    federated?: boolean;
  }, owner: {
    disposed: boolean;
    assertCurrent: () => void;
    lookup: (query: Lookup) => Row | undefined;
    matching: (query: Query, kind?: string) => Row[];
    scope: ReturnType<typeof prepareSessionRowScopes>;
  }) => Row[]>[0]): Row[];
  readMembership(query: Lookup): ReadonlySet<string> | undefined;
  readSource(target: Row | Lookup): CapturedSessionEntryReadSource | undefined;
  prepareMembership(): Promise<void>;
  needsMembershipPreparation: () => boolean;
  sessionGroupTargets(): ReadonlyMap<string, readonly Readonly<{
    sessionKey: string;
    agentId: string;
  }>[]>;
  sharingTarget: (query: Lookup) => {
    agentId: string;
    generation: string | symbol;
    canonicalKey: string;
    entry: InternalSessionEntry;
    storeKey: string;
    storeKeys: string[];
    storePath: string;
  } | null;
  sharingTargetState(query: Lookup): {
    status: "missing";
    target?: undefined;
  } | {
    status: "pending";
    target?: undefined;
  } | {
    status: "ready";
    target: {
      agentId: string;
      generation: string | symbol;
      canonicalKey: string;
      entry: InternalSessionEntry;
      storeKey: string;
      storeKeys: string[];
      storePath: string;
    };
  };
  hasMembership: (storePath: string, key: string, identity: string) => boolean;
  ancestorRows: (record: MaterializedRow, read?: SessionRowReadView) => MaterializedRow[] | undefined;
  withPreparedExactRows: <T>(queries: (config: Inputs["cfg"]) => readonly Lookup[], consume: (read: SessionRowReadView) => T, options?: SessionRowPreparationOptions) => Promise<T>;
  onSelectionChange: (this: void, listener: (change: SelectionChange) => void) => void;
  onFactsChange: (this: void, listener: (change: {
    kind: "reset";
  } | {
    kind: "row";
    key: string;
  }) => void) => void;
  readTaskPublicationRevision: () => object;
  hasLogicalChildEntries: (parent: Pick<Row, "agentId" | "key">) => boolean;
  physicalPaths: (this: void, locator: string, agentId?: string) => readonly string[];
  readPreparedRowContext: () => SessionListRowContext | undefined;
  readPreparedSpawnedBy: (this: void, query: Lookup) => string | undefined;
  describe: (query: Lookup, captured?: Row, repositoryWorkspace?: Readonly<SessionRepositoryWorkspaceRecord> | null) => MaterializedRow | undefined;
  setArchivePageSize: (size: number) => void;
  ensureMaterialized: () => Promise<void>;
  prepareSelection: (options?: SessionRowSelectionPreparationOptions & {
    yieldForCatalog?: boolean;
  }, candidateIds?: () => Iterable<string>) => Promise<void> | undefined;
  withSelectionPreparation: <T>(this: void, consume: () => Promise<T>) => Promise<T>;
  needsSelectionPreparation: (options?: SessionRowSelectionPreparationOptions, candidateIds?: () => Iterable<string>) => boolean;
  materializedCount: number;
  dirtyRowCount: number;
  needsMaterialization: boolean;
  getPolicyConfig: () => OpenClawConfig;
  sharingRevision: object | undefined;
  state: {
    revision: object;
    cfg: OpenClawConfig;
    policyConfig: OpenClawConfig;
    modelCatalog: ModelCatalogEntry[] | SessionListModelCatalog | undefined;
    rowContext: SessionListRowContext;
    scope: (options: {
      agentId?: string;
      configuredAgentsOnly?: boolean;
    }) => {
      targets: readonly SessionStoreTarget[];
      paths: Map<string, number>;
      path: string;
      configuredAgentIds: ReadonlySet<string> | undefined;
      ownerAgentIds: ReadonlySet<string>;
      agentId: string | undefined;
    };
    physicalStorePaths: (this: void, locator: string, agentId?: string) => readonly string[];
  };
  isCurrent: (row: Row) => boolean;
  selectEntries: (query?: Query, metadataPrepared?: boolean) => EntryRow[];
  projectRecentCandidates: (this: void, profileIds: ReadonlySet<string>) => Promise<Iterable<SelectionRow>>;
  listCreatedActors: () => ReturnType<(selectPaths: () => ReadonlyMap<string, number>, matching: (query: {
    key: string;
  }) => Row[]) => ({
    type: "agent" | "human" | "system";
    id: string;
    label: string | undefined;
  } | SessionCreatedActor)[]>;
  snapshot: (query: Lookup, options?: SnapshotOptions) => {
    row: GatewaySessionRow;
    lifecycleRunId: string | undefined;
  } | {
    lifecycleRunId?: undefined;
    row: null;
  };
  dispose: () => void;
}>;
type SessionRowProjection = Awaited<ReturnType<typeof createSessionRowProjection>>;
//#endregion
//#region src/gateway/session-activity-summaries.d.ts
type SessionActivitySummaryService = {
  beginCompletion(target: {
    key: string;
    agentId?: string;
    storePath: string;
  }, entry: SessionEntry | undefined): SessionActivitySummaryCompletion | undefined;
  ensure(target: ActivitySummaryTarget, entry?: SessionEntry): Promise<SessionActivitySummary$1>;
  handleEvent: (event: SessionObserverEvent) => void;
  handleLifecycle: (event: SessionLifecycleEvent) => void;
  dispose: () => Promise<void>;
};
//#endregion
//#region src/shared/current-read-authority.d.ts
type CurrentReadAuthority = {
  assertCurrent?: () => void;
  withCurrent?: <T>(consume: () => T) => Promise<Awaited<T>>;
};
//#endregion
//#region src/gateway/model-account-authority.d.ts
/** Transaction-local role facts; the host still owns connection and policy authority. */
type ModelAccountRole = {
  profileId: string;
  role: string | null;
};
/** In-process account authority shared by connect and selection owners; never serialized. */
type ModelAccountConnectAction = {
  owner: string;
  assertCurrent: () => void;
};
type ModelAccountConnectWorkerAction = ModelAccountConnectAction & {
  actorProfileId?: string;
  assertCurrent: (roles?: readonly ModelAccountRole[]) => void;
};
type UserModelAccountSelection = ModelAccountConnectAction & {
  authProfileId: string;
};
//#endregion
//#region src/gateway/server-methods/chat-metadata-contract.d.ts
declare const chatMetadataSessionFields: readonly ["sessionId", "lifecycleRevision", "sessionStartedAt", "agentHarnessId", "agentRuntimeOverride", "modelSelectionLocked", "pluginOwnerId", "providerOverride", "modelOverride", "modelOverrideSource", "modelOverrideRouteResolution", "modelOverrideFallbackOriginProvider", "modelOverrideFallbackOriginModel", "authProfileOverride", "authProfileOverrideSource", "authProfileOverrideCompactionCount"];
type ChatMetadataSessionEntry = Partial<Pick<SessionEntry, (typeof chatMetadataSessionFields)[number]>>;
type ChatMetadataReadParams = {
  agentId: string;
  includeModels?: boolean;
  ifRevision?: string;
  sessionKey?: string;
  storePath?: string;
  requesterProfileId?: string;
  sessionEntry?: ChatMetadataSessionEntry;
  /** Exact active placement fact prepared by the worker placement owner. */
  workerInference?: "worker";
  /** Saved reads retain their selected row and physical store until response settlement. */
  isCurrent?: () => boolean;
  assertCurrent?: () => void;
  /** Refresh saved-session authority and begin preparation before yielding again. */
  withCurrent?: CurrentReadAuthority["withCurrent"];
  /** Synchronous saved-session authority at credential-bearing provider dispatch. */
  beforeRequest?: () => void;
  release?: () => void;
  draftAccountSelection?: UserModelAccountSelection;
};
type ChatMetadataResult = {
  revision?: string;
  unchanged?: true;
  commands?: unknown[];
  models?: ModelChoice[];
  modelSelectionPolicy?: ModelsListResult["modelSelectionPolicy"];
  swarmEnabled: boolean;
  runtimeSelectionLocked?: boolean;
  /** Current required worker-inference policy, not placement readiness or send authority. */
  requiredWorkerInferenceProfileId?: string;
  accountSelection?: ChatAccountSelection;
};
//#endregion
//#region src/gateway/server-methods/models-list-context.d.ts
type PreparedModelsListRequest = {
  agentId: string;
  params: ModelsListParams;
  includeManualSelection?: boolean;
  requesterProfileId?: string;
  readScope?: ChatMetadataReadParams;
};
//#endregion
//#region src/gateway/server-shared-auth-generation.d.ts
type SharedAuthConfigTransition = {
  previous: OpenClawConfig;
  next: OpenClawConfig;
};
type SharedGatewaySessionGenerationOwnership = {
  generation: string | undefined;
  previousGeneration: string | undefined;
  revision: number;
};
type SharedAuthInvalidation = {
  kind: "generation";
  generation: string | undefined;
} | {
  kind: "policy";
  config: OpenClawConfig;
} | {
  kind: "all";
};
/** One Gateway owns its generation fields, revision and read-only admission capability. */
declare class SharedGatewaySessionGenerationState {
  #private;
  constructor(initial: {
    current: string | undefined;
    required: string | undefined | null;
  });
  get current(): string | undefined;
  get required(): string | undefined | null;
  get requiredGeneration(): string | undefined;
  get reader(): GenerationReader;
  static fromReader(read: GenerationReader | undefined): SharedGatewaySessionGenerationState | undefined;
  /** Follow committed policy even after the originating client leaves the socket set. */
  onInvalidated(generation: string | undefined, listener: () => void, authPolicy?: GatewayAuthPolicy): () => void;
  publishInvalidation(event: SharedAuthInvalidation): void;
  capture(): SharedGatewaySessionGenerationOwnership;
  owns(ownership: SharedGatewaySessionGenerationOwnership): boolean;
  claim(ownership: SharedGatewaySessionGenerationOwnership, generation: string | undefined): SharedGatewaySessionGenerationOwnership | null;
  publish(next: {
    current: string | undefined;
    required: string | undefined | null;
  }): void;
  replace(ownership: SharedGatewaySessionGenerationOwnership, next: {
    current: string | undefined;
    required: string | undefined | null;
  }): boolean;
  restoreCurrent(ownership: SharedGatewaySessionGenerationOwnership, current: string | undefined): boolean;
  setRequired(ownership: SharedGatewaySessionGenerationOwnership, required: string | undefined | null): SharedGatewaySessionGenerationOwnership | null;
  finalize(ownership: SharedGatewaySessionGenerationOwnership, transition?: SharedAuthConfigTransition): boolean;
}
type GenerationReader = () => string | undefined;
//#endregion
//#region src/commands/daemon-runtime.d.ts
type GatewayDaemonRuntime = "bun" | "node" | "standalone";
//#endregion
//#region src/commands/onboard-types.d.ts
type OnboardMode = "local" | "remote";
/**
 * Auth choices are plugin-owned contract ids plus a few legacy aliases that
 * are normalized elsewhere (for example `oauth` -> `setup-token`).
 */
type BuiltInAuthChoice =
/** @deprecated Use `setup-token`. */
"oauth" | "setup-token" | "token" | "apiKey" | "custom-api-key" | "skip";
type AuthChoice = BuiltInAuthChoice | (string & {});
type ResetScope = "config" | "config+creds+sessions" | "full";
declare const NODE_MANAGER_CHOICES: readonly ["npm", "pnpm", "bun"];
type NodeManagerChoice = (typeof NODE_MANAGER_CHOICES)[number];
declare const ONBOARD_FLOWS: readonly ["quickstart", "advanced", "manual", "import"];
type OnboardFlow = (typeof ONBOARD_FLOWS)[number];
type OnboardDynamicProviderOptions = {
  /**
   * Provider-specific non-interactive auth flags are plugin-owned and keyed by
   * manifest `providerAuthChoices[].optionKey` values.
   */
  [optionKey: string]: unknown;
};
/** Parsed options accepted by `openclaw onboard`. */
type OnboardOptions = OnboardDynamicProviderOptions & {
  mode?: OnboardMode;
  /** "manual" is an alias for "advanced". */
  flow?: OnboardFlow;
  /** Force the classic multi-step interactive wizard instead of guided setup. */
  classic?: boolean;
  /** Force the terminal hatch instead of the guided browser handoff. */
  tui?: boolean;
  workspace?: string;
  /** Name for the first persisted agent; defaults to `main` in non-interactive setup. */
  agentName?: string;
  /** Create the bundled coordinator and specialists on a fresh install. */
  team?: boolean;
  nonInteractive?: boolean;
  /** Required for non-interactive setup; skips the interactive risk prompt when true. */
  acceptRisk?: boolean;
  reset?: boolean;
  resetScope?: ResetScope;
  authChoice?: AuthChoice;
  /** Used when `authChoice=token` in non-interactive mode. */
  tokenProvider?: string;
  /** Used when `authChoice=token` in non-interactive mode. */
  token?: string;
  /** Used when `authChoice=token` in non-interactive mode. */
  tokenProfileId?: string;
  /** Used when `authChoice=token` in non-interactive mode. */
  tokenExpiresIn?: string;
  /** API key persistence mode for setup flows (default: plaintext). */
  secretInputMode?: SecretInputMode;
  arceeaiApiKey?: string;
  cloudflareAiGatewayAccountId?: string;
  cloudflareAiGatewayGatewayId?: string;
  customBaseUrl?: string;
  customApiKey?: string;
  /** Mark the custom endpoint as not enforcing auth (--custom-no-auth). */
  customNoAuth?: boolean;
  lmstudioApiKey?: string;
  customModelId?: string;
  /** Prepared during reset preflight; not a CLI flag. */
  customModelIds?: string[];
  customProviderId?: string;
  customCompatibility?: "openai" | "openai-responses" | "anthropic";
  customImageInput?: boolean;
  gatewayPort?: number;
  gatewayBind?: "loopback" | "lan" | "auto" | "custom" | "tailnet";
  gatewayAuth?: "token" | "password";
  gatewayToken?: string;
  gatewayTokenRefEnv?: string;
  gatewayPassword?: string;
  tailscale?: "off" | "serve" | "funnel";
  installDaemon?: boolean;
  daemonRuntime?: GatewayDaemonRuntime;
  skipChannels?: boolean;
  skipSkills?: boolean;
  skipBootstrap?: boolean;
  skipSearch?: boolean;
  skipHealth?: boolean;
  skipUi?: boolean;
  suppressGatewayTokenOutput?: boolean;
  skipHooks?: boolean;
  nodeManager?: NodeManagerChoice;
  remoteUrl?: string;
  remoteToken?: string;
  remotePassword?: string;
  importFrom?: string;
  importSource?: string;
  importSecrets?: boolean;
  json?: boolean;
};
//#endregion
//#region src/gateway/server-methods/wizard.d.ts
type SetupWizardRunner = (opts: OnboardOptions, runtime: RuntimeEnv, prompter: WizardPrompter) => Promise<void>;
type ChannelSetupWizardRunner = (opts: {
  channel?: string;
  onConfigured?: (accounts: Array<{
    channel: string;
    accountId: string;
  }>) => void;
  beforePersistentEffect?: () => Promise<void>;
  assertPersistentEffectCurrent?: () => void;
}, runtime: RuntimeEnv, prompter: WizardPrompter) => Promise<void>;
//#endregion
//#region src/gateway/methods/registry.d.ts
type GatewayMethodRegistry = GatewayMethodRegistryView & {
  pluginRegistry?: PluginRegistry;
};
//#endregion
//#region src/state/github-publication-task-reads.worker.d.ts
type TaskPublicationSession = {
  agentId: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision: string | null;
};
type TaskPublicationRead = {
  sessions: TaskPublicationSession[];
  ownerProfileId?: string;
  branchUrls?: string[];
};
//#endregion
//#region src/gateway/control-ui-contract.d.ts
type ControlUiSessionPullRequestChecks = {
  state: "pending" | "passing" | "failing";
  passed: number;
  failed: number;
  skipped: number;
  /** Queued/in-progress runs plus stale conclusions GitHub invalidated. */
  running: number;
};
/** A pull request associated with the session's working branch. */
type ControlUiSessionPullRequest = {
  number: number;
  /** Login-only to avoid browser avatar requests; absent for deleted accounts. */
  author?: {
    login: string;
  };
  owner: string;
  repo: string;
  branch: string;
  title: string;
  url: string;
  state: "open" | "draft" | "merged" | "closed";
  additions?: number;
  deletions?: number;
  changedFiles?: number;
  /** Latest check-run rollup for the head commit; absent when no checks ran. */
  checks?: ControlUiSessionPullRequestChecks;
  checksUrl?: string;
  /** Head binding for on-demand CI details; not a client-selected repository revision. */
  headSha?: string;
};
/** Local Git facts stay available while GitHub quota is exhausted. */
type ControlUiSessionBranch = {
  owner: string;
  repo: string;
  branch: string;
  /** Working-tree diff vs the merge base with the remote default branch. */
  additions?: number;
  deletions?: number;
  changedFiles?: number;
  /** Absent while the branch is unpushed or has nothing to compare. */
  createUrl?: string;
};
/** A PR durably published by this task or an accessible descendant. */
type ControlUiSessionTaskPullRequest = {
  url: string;
  owner: string;
  repo: string;
  number: number;
  branch: string;
  title?: string;
  sourceSessionKey: string;
  sourceAgentId: string;
  /** Verified GitHub metadata; absent on a cold lookup failure. */
  pullRequest?: ControlUiSessionPullRequest;
};
type ControlUiSessionPullRequests = {
  /** The current bound PR could not be verified; discard previously displayed facts. */
  discardPrevious?: true;
  /** Branch facts were not refreshed; empty fields do not invalidate retained UI facts. */
  branchRead?: false;
  taskPullRequests?: ControlUiSessionTaskPullRequest[];
  /** Total distinct publications, independent of the bounded preview. */
  taskPullRequestCount?: number;
  /** Total distinct task and current-branch PRs; absent when branch membership is unknown. */
  pullRequestCount?: number;
  pullRequests: ControlUiSessionPullRequest[];
  /** GitHub remote identity, independent of whether a PR or branch row exists. */
  repository?: {
    owner: string;
    repo: string;
  };
  /** Non-default branch with a creatable PR or local changed files. */
  branch?: ControlUiSessionBranch;
  /** GitHub quota exhausted; entries may be stale until the limit resets. */
  rateLimited: boolean;
  /** A failed PR lookup may still carry independently resolved repository facts. */
  status?: "ready" | "rate-limited" | "unavailable";
};
/** Per-session pushed state; unavailable snapshots preserve prior UI state. */
type ControlUiSessionPullRequestSnapshot = ControlUiSessionPullRequests & {
  status: NonNullable<ControlUiSessionPullRequests["status"]>;
};
//#endregion
//#region src/gateway/control-ui-session-pr-request.d.ts
type SessionPullRequestReadCredential = {
  token: string;
  apiBaseUrl: string;
  assertCurrent: () => void;
};
//#endregion
//#region src/state/agent-database-admission.d.ts
type AgentDatabaseAdmissionRefusal = {
  agentId: string;
  paths: string[];
  reason: string;
  repairHint: string;
} & ({
  code: "agent-database-ownership-mismatch";
  embeddedOwnerId: string;
} | {
  code: "agent-database-inspection-pending" | "agent-database-inspection-failed" | "agent-database-held";
  embeddedOwnerId?: undefined;
});
//#endregion
//#region src/gateway/control-ui-session-pr-read.d.ts
type ControlUiSessionPrTarget = {
  sessionId?: string;
  lifecycleRevision?: string;
  params: {
    sessionKey: string;
    agentId: string;
  };
  identity: string;
  branchIdentity?: string;
  taskReceipts?: TaskPublicationRead;
  taskReceiptsOnly?: boolean;
  readSource: {
    agentId: string;
    path: string;
  };
  source: string | GitCheckoutContext | null;
  githubHost?: string;
  githubPullRequest?: SessionGitHubPullRequestBinding;
  ownGitHubProfileId?: string;
  ownGitHubIdentity?: string;
  refreshIndex?: boolean;
  assertCurrent?: () => void;
};
type ControlUiSessionPrReadContext = {
  target: ControlUiSessionPrTarget;
  sourceIdentity: string;
  projection?: "publication";
  onBranchRead?: (snapshot: ControlUiSessionPullRequests) => void;
  /** Same-source branch-only facts retained by the subscription owner, not a fresh read. */
  branchSnapshot?: ControlUiSessionPullRequests;
  retainReadAuthority?: (assertCurrent: () => void, credential?: SessionPullRequestReadCredential) => void;
  assertCurrent: () => void;
};
type ControlUiSessionPrRead = () => Promise<ControlUiSessionPrTarget | undefined>;
//#endregion
//#region src/gateway/control-ui-session-prs.d.ts
type ControlUiSessionPullRequestsParams = {
  sessionKey: string;
  agentId?: string;
  refresh?: boolean;
};
//#endregion
//#region src/gateway/control-ui-session-pr-subscriptions.d.ts
type SubscriptionDeps = {
  broadcastToConnIds: GatewayBroadcastToConnIdsFn;
  prepareRead: (connId: string, session: Pick<ControlUiSessionPullRequestsParams, "sessionKey" | "agentId"> & {
    taskReceiptsOnly: boolean;
  }) => Promise<ControlUiSessionPrRead | undefined>;
  isConnectionActive?: (connId: string) => boolean;
  scheduler: GatewayScheduler;
  getSessionRowProjection?: () => SessionRowProjection | undefined;
};
/**
 * Owns the union of connection replace-sets. Only this union drives GitHub
 * refreshes, so hidden/disconnected clients cannot leave orphan polling work.
 */
declare function createControlUiSessionPullRequestSubscriptions(deps: SubscriptionDeps): {
  read: (target: ControlUiSessionPrTarget, assertCurrent: () => void, projection?: ControlUiSessionPrReadContext["projection"]) => Promise<ControlUiSessionPullRequestSnapshot>;
  readPrepared: (target: ControlUiSessionPrTarget, admitLoad?: (() => boolean) | undefined) => ControlUiSessionPullRequestSnapshot | undefined;
  replace: (connId: string, sessionKeys: readonly string[], requestedRefreshSessionKeys?: ReadonlySet<string>, passiveSessionKeys?: ReadonlySet<string>) => Promise<void>;
  unsubscribe: (connId: string) => void;
  pollNow: () => Promise<void>;
  stop: () => Promise<void>;
};
//#endregion
//#region src/gateway/server/client-registry.d.ts
declare class GatewayClientRegistry extends Set<GatewayWsClient> {
  #private;
  onChange?: () => void;
  get unscopedSessionEventConnIds(): ReadonlySet<string>;
  get authorityClients(): Iterable<GatewayWsClient>;
  retainRequest(client: GatewayWsClient): () => void;
  constructor(clients?: Iterable<GatewayWsClient>, onRemove?: (client: GatewayWsClient) => void);
  add(client: GatewayWsClient): this;
  delete(client: GatewayWsClient): boolean;
  clear(): void;
  getByConnectionId(connId: string): GatewayWsClient | undefined;
  getByConnectionIds(connIds: ReadonlySet<string>): GatewayWsClient[];
}
//#endregion
//#region src/gateway/session-viewer-presence.d.ts
type SessionViewerPresenceDeclarationsDeps = {
  clients: GatewayClientRegistry;
  publishPresence: () => void;
};
/** Owns one replace-set per websocket connection until empty declaration or disconnect. */
declare function createSessionViewerPresenceDeclarations(deps: SessionViewerPresenceDeclarationsDeps): {
  replace: (connId: string, sessionKeys: readonly string[]) => readonly string[];
  unsubscribe: (connId: string) => void;
  isViewedOnDevice: (deviceId: string, sessionKey: string) => boolean;
  stop: () => void;
};
//#endregion
//#region src/plugins/lifecycle.d.ts
/** A receipt describes the published runtime, never authority to invoke it. */
type PluginRuntimeApplication = {
  operationId: string;
  generation: number;
  pluginIds: string[];
  sourceDigests?: Record<string, string>;
  selectedEntries?: Record<string, string>;
  /** Registration applied, but process-shared code needs a Gateway restart. */
  restartRequired?: boolean;
  warnings?: string[];
};
type PluginLifecycleReason = "install" | "enable" | "disable" | "uninstall" | "reload" | "metadata";
type PluginLifecycleRuntimeApply = (params: {
  config: OpenClawConfig;
  write?: Pick<ConfigReplaceResult, "persistedHash" | "persistedSourceConfig">;
  pluginIds: readonly string[];
  reason: PluginLifecycleReason;
  /** Explicit reload admission wait; cancellation never owns recovery or published cleanup. */
  waitForDrain?: boolean;
  drainSignal?: AbortSignal;
  expectedSourceDigests?: Readonly<Record<string, string>>;
  /** Private invoker authority; never part of the published runtime receipt. */
  assertInvokerOwned?: () => void;
}) => Promise<PluginRuntimeApplication>;
//#endregion
//#region src/gateway/desktop/managed-linux-audio.d.ts
/** Raw interleaved PCM s16le, 48000 Hz, stereo. No microphone or host mix. */
type DesktopAudioSource = {
  start(signal: AbortSignal, assertAuthority?: () => void): Promise<{
    stream: Readable;
    stop(): Promise<void>;
  }>;
};
//#endregion
//#region src/gateway/desktop/managed-linux.d.ts
type ManagedLinuxDesktopStatus = {
  state: "not-started";
} | {
  state: "starting";
  display?: number;
  port?: number;
} | {
  state: "running";
  display: number;
  port: number;
} | {
  state: "failed";
  error: string;
  display?: number;
  port?: number;
};
//#endregion
//#region src/gateway/desktop/attachment.d.ts
type RfbAttachment = {
  kind: "unix-socket";
  socketPath: string;
} | {
  kind: "tcp";
  host: "127.0.0.1";
  port: number;
};
/** One already-connected RFB transport published by a remote desktop source. */
type RfbStreamAttachment = {
  kind: "stream";
  streamId: string;
};
type DesktopRfbAttachment = RfbAttachment | RfbStreamAttachment;
//#endregion
//#region src/gateway/desktop/observe-requester.d.ts
type DesktopObserveRequester = {
  connId?: string;
  /** Display identity from authenticated Gateway metadata, never wire-supplied client labels. */
  operatorName?: string;
  signal?: AbortSignal;
  remoteIngressPrincipal?: RemoteIngressPrincipalSnapshot;
  isCurrent: () => boolean;
};
//#endregion
//#region src/gateway/desktop/session-registry.d.ts
type DesktopSessionObserver = {
  control: boolean;
  operatorName?: string;
  /** Epoch the observer token was minted against; a stale token must not reach a newer entry. */
  ownerEpoch: number;
  close(code: number, reason: string): void;
};
type DesktopSessionAcquireResult = {
  attachment: DesktopRfbAttachment;
  auth?: "vnc-password" | "ard-account";
  vncPassword?: string;
  resolveAudio?: () => DesktopAudioSource | undefined;
  /** Internal setup detail; project only a fixed availability code to viewers. */
  readonly audioUnavailableReason?: string;
};
type DesktopSessionAcquireRequest = {
  sourceKey: string;
  ownerEpoch: number;
  /** Lifecycle events stop this exact owner; the stop promise joins initialization. */
  start: (isCurrent: () => boolean, stop: () => Promise<void>) => Promise<DesktopSessionAcquireResult>;
  teardown?: () => Promise<void>;
  /** Release source resources only after initialization and transport teardown have joined. */
  dispose?: () => Promise<void>;
};
type DesktopSessionActivateRequest = Omit<DesktopSessionAcquireRequest, "start">;
/** Owns per-source desktop sessions and their connected observer lifetimes. */
declare function createDesktopSessionRegistry(): {
  acquire: (request: DesktopSessionAcquireRequest) => Promise<DesktopSessionAcquireResult>;
  activate: (request: DesktopSessionActivateRequest) => Promise<void>;
  attachObserver: (sourceKey: string, observer: DesktopSessionObserver) => {
    release(): void;
  } | undefined;
  takeControl: (sourceKey: string, ownerEpoch: number) => void;
  claimStream: (sourceKey: string, attachment: {
    kind: "stream";
    streamId: string;
  }) => Duplex | undefined;
  createStream: (params: {
    sourceKey: string;
    ownerEpoch: number;
    onStopped(): void;
  }) => {
    signal: AbortSignal;
    readonly stopped: boolean;
    reserve(): boolean;
    connect<T extends {
      stream: Duplex;
    }>(pending: {
      attached: Promise<T>;
      cancel(): void;
    }, invoke: () => Promise<{
      error?: {
        message?: string;
      } | null;
    }>): Promise<T>;
    publish(): {
      readonly kind: "stream";
      readonly streamId: `${string}-${string}-${string}-${string}-${string}`;
    } | undefined;
    expireAt(expiresAtMs: number): void;
    stop: () => Promise<void>;
  };
  retainActivity: (sourceKey: string, ownerEpoch: number) => {
    isCurrent: () => boolean;
    release(): void;
  } | undefined;
  hasActivity: (sourceKey: string, ownerEpoch: number) => boolean;
  hasController: (sourceKey: string, ownerEpoch: number) => boolean;
  onControlChanged: (sourceKey: string, ownerEpoch: number, changed: (controlled: boolean) => void) => () => void;
  claimOwnerEpoch: (sourceKey: string, ownerEpoch: number) => boolean;
  isOwnerEpochCurrent: (sourceKey: string, ownerEpoch: number) => boolean;
  stop: (sourceKey: string, ownerEpoch?: number) => Promise<void>;
  stopSuperseded: (sourceKey: string, ownerEpoch: number) => Promise<void>;
  stopAll: () => Promise<void>;
};
type DesktopSessionRegistry = ReturnType<typeof createDesktopSessionRegistry>;
//#endregion
//#region src/gateway/desktop/host-source.d.ts
type HostDesktopStatus = {
  enabled: false;
  state: "disabled";
  port: number;
} | {
  enabled: true;
  state: "attached";
  port: number;
  security: string;
} | {
  enabled: true;
  state: "unavailable";
  port: number;
  security?: string;
} | {
  enabled: true;
  state: "managed";
  managedState: ManagedLinuxDesktopStatus["state"] | "unknown";
  port: number;
  display?: number;
  error?: string;
  security?: "VncAuth";
};
type HostDesktopService = ReturnType<typeof createHostDesktopService>;
/** Combines host acquisition, registry ownership, and observer-token minting. */
declare function createHostDesktopService(params: {
  getConfig: () => DesktopHostConfig | undefined;
  registry: DesktopSessionRegistry;
}): {
  observe(observeParams: {
    control: boolean;
    requester?: DesktopObserveRequester;
    credentials?: {
      username?: string;
      password?: string;
    };
  }): Promise<{
    transport: "rfb";
    wsPath: string;
    expiresAtMs: number;
    control: boolean;
    auth: "ard-account" | "vnc-password";
    audio?: {
      wsPath: string;
      encoding: "pcm-s16le";
      sampleRate: 48000;
      channels: 2;
    } | undefined;
    preauthenticated?: boolean | undefined;
    audioUnavailableReason?: "setup-unavailable" | undefined;
    vncPassword?: string | undefined;
  }>;
  acquireComputer(computerParams: {
    onStop(): Promise<void>;
  }): Promise<{
    env: NodeJS.ProcessEnv;
    isCurrent: () => boolean;
    release(): void;
  }>;
  status(): Promise<HostDesktopStatus>;
  reconcileRuntimePolicy: () => Promise<void>;
};
//#endregion
//#region src/gateway/desktop/computer-service.d.ts
type GatewayComputerStatus$1 = {
  configured: boolean;
  available: boolean;
  computerUse?: ComputerUseCapabilityDescriptor;
  error?: string;
};
type ComputerInvokeRequest = ComputerInvokeParams & {
  owner: string;
  signal?: AbortSignal;
  ownerSignal?: AbortSignal;
  assertCurrent(): void;
};
type GatewayComputerService = ReturnType<typeof createGatewayComputerService>;
/** Owns the Gateway transport, while registered providers retain native action semantics. */
declare function createGatewayComputerService(options: {
  getConfig(): OpenClawConfig;
  getPluginRegistry(): PluginRegistry;
  hostDesktopService?: HostDesktopService;
}): {
  reconcileRuntimePolicy(): Promise<void>;
  preparePluginReload(this: void, { changedPluginIds }: {
    changedPluginIds: ReadonlySet<string>;
  }): {
    drain: () => Promise<void>;
    resume: () => void;
  };
  status({ probe }?: {
    probe?: boolean;
  }): Promise<GatewayComputerStatus$1>;
  invoke(request: ComputerInvokeRequest): Promise<unknown>;
  close(): Promise<void>;
  revokeRunAuthority(authority: AgentRunDelegatedAuthority): void;
};
//#endregion
//#region src/gateway/worker-environments/session-attachment.d.ts
type WorkerEnvironmentSessionIdentity = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  sessionLifecycleRevision?: string;
};
/** A secondary machine owned by a conversation, independent of its execution placement. */
type WorkerEnvironmentAttachment = WorkerEnvironmentSessionIdentity & {
  environmentId: string;
  ownerEpoch: number;
  generation: number;
};
type WorkerEnvironmentAttachmentRecord = Omit<WorkerEnvironmentAttachment, "ownerEpoch"> & {
  createdAtMs: number;
  lastUsedAtMs: number;
  closedAtMs: number | null;
};
type WorkerEnvironmentSessionCreateRequest = WorkerEnvironmentSessionIdentity & {
  profileId: string;
  idempotencyKey: string;
  machineClass?: string;
  os?: string;
};
/** Requester presentation must succeed before a newly reserved machine can be allocated. */
type WorkerEnvironmentSessionReservationHandler = (reservation: {
  environmentId: string;
  reused: boolean;
}) => Promise<void>;
//#endregion
//#region src/worker/worker-build-identity.d.ts
type ExpectedWorkerBuild = {
  bundleHash: WorkerAdmissionHandshake["bundleHash"];
  openclawVersion: WorkerAdmissionHandshake["openclawVersion"];
  protocolFeatures: readonly string[];
};
//#endregion
//#region src/gateway/worker-environments/node-bootstrap-artifact-contract.d.ts
type WorkerBundleArtifact = ExpectedWorkerBuild & {
  install: "bundle";
  tarballBytes: number;
  tarballSha256: string;
  tarballPath: string;
};
//#endregion
//#region src/gateway/worker-environments/bundle.d.ts
type WorkerNpmArtifact = ExpectedWorkerBuild & {
  install: "npm";
  packageIntegrity: string;
  packageSpec: string;
};
type WorkerInstallationArtifact = WorkerBundleArtifact | WorkerNpmArtifact;
//#endregion
//#region src/gateway/worker-environments/inference-store.types.d.ts
type WorkerInferenceTurnInput = {
  environmentId: string;
  sessionId: string;
  runEpoch: number;
  runId: string;
  turnId: string;
  requestHash: string;
};
type WorkerInferenceTurnBeginResult = {
  kind: "claimed";
} | {
  kind: "recover";
} | {
  kind: "replay";
  outcome: WorkerInferenceTerminalOutcome;
} | {
  kind: "rejected";
  reason: "conflict";
};
type WorkerInferenceRetentionPolicy = {
  maxAgeMs: number;
  maxRows: number;
  maxBytes: number;
};
//#endregion
//#region src/gateway/worker-environments/inference-store.kernel.d.ts
/** The shared-state worker supplies the already-admitted transaction connection. */
declare function createWorkerInferenceStoreKernel(options: {
  db: EngineConnection;
  now: () => number;
  retention?: Partial<WorkerInferenceRetentionPolicy>;
}): {
  begin: (rawInput: WorkerInferenceTurnInput) => WorkerInferenceTurnBeginResult;
  cancelPending: (params: Omit<WorkerInferenceTurnInput, "requestHash"> & {
    outcome: WorkerInferenceTerminalOutcome;
  }) => void;
  complete: (rawInput: WorkerInferenceTurnInput & {
    outcome: WorkerInferenceTerminalOutcome;
  }) => WorkerInferenceTerminalOutcome;
  recoverPending: (outcome: WorkerInferenceTerminalOutcome) => void;
};
//#endregion
//#region src/gateway/worker-environments/inference-store.d.ts
type Kernel = ReturnType<typeof createWorkerInferenceStoreKernel>;
declare function createWorkerInferenceStore(options?: {
  path?: string;
  now?: () => number;
  retention?: Partial<WorkerInferenceRetentionPolicy>;
}): {
  begin: (input: Parameters<Kernel["begin"]>[0], assertCurrent?: () => void) => Promise<WorkerInferenceTurnBeginResult>;
  complete: (input: Parameters<Kernel["complete"]>[0], assertCurrent?: () => void) => Promise<{
    type: "done";
    message: {
      role: "assistant";
      content: ({
        type: "text";
        text: string;
        textSignature?: string | undefined;
      } | {
        type: "thinking";
        thinking: string;
        thinkingSignature?: string | undefined;
        redacted?: boolean | undefined;
      } | {
        type: "toolCall";
        id: string;
        name: string;
        arguments: Record<string, unknown>;
        thoughtSignature?: string | undefined;
        executionMode?: "parallel" | "sequential" | undefined;
      })[];
      api: string;
      provider: string;
      model: string;
      responseModel?: string | undefined;
      responseId?: string | undefined;
      providerReplay?: {
        v: 1;
        type: string;
        id?: string | undefined;
        data: string;
        replayIndex?: number | undefined;
        provider: string;
        api: string;
        model: string;
        baseUrlHash?: string | undefined;
        sessionHash?: string | undefined;
        authProfileHash?: string | undefined;
      } | undefined;
      timestamp: number;
      usage: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        usageReport?: {
          state: "available" | "unavailable";
        } | undefined;
        contextUsage?: {
          state: "available";
          promptTokens: number;
          totalTokens: number;
        } | {
          state: "unavailable";
        } | undefined;
        totalTokens: number;
        cost: {
          input: number;
          output: number;
          cacheRead: number;
          cacheWrite: number;
          total: number;
          totalOrigin?: "provider-billed" | undefined;
        };
      };
      stopReason: "length" | "stop" | "toolUse";
    };
  } | {
    type: "error";
    reason: "cancelled" | "epoch-mismatch" | "invalid-context" | "model-not-approved" | "provider-error" | "session-not-attached";
    message: string;
    usage?: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      usageReport?: {
        state: "available" | "unavailable";
      } | undefined;
      contextUsage?: {
        state: "available";
        promptTokens: number;
        totalTokens: number;
      } | {
        state: "unavailable";
      } | undefined;
      totalTokens: number;
      cost: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        total: number;
        totalOrigin?: "provider-billed" | undefined;
      };
    } | undefined;
    retryAfterMs?: number | null | undefined;
  }>;
  cancelPending: (input: Parameters<Kernel["cancelPending"]>[0], assertCurrent?: () => void) => Promise<void>;
  recoverPending: (input: Parameters<Kernel["recoverPending"]>[0], assertCurrent?: () => void) => Promise<void>;
};
type WorkerInferenceStore = ReturnType<typeof createWorkerInferenceStore>;
//#endregion
//#region src/gateway/worker-environments/inference.types.d.ts
type WorkerInferenceSink = {
  connectionId: string;
  send(frame: WorkerInferenceEventFrame | WorkerInferenceTerminalFrame): void;
};
type RevalidateInference = () => Extract<WorkerInferenceErrorReason, "epoch-mismatch" | "session-not-attached"> | null;
type WorkerInferenceStartApplicationResult = {
  ok: true;
  result: WorkerInferenceStartResult;
  launch(): void;
} | {
  ok: false;
  reason: WorkerInferenceErrorReason;
};
type WorkerInferenceCancelApplicationResult = {
  ok: true;
  result: WorkerInferenceCancelResult;
} | {
  ok: false;
  reason: WorkerInferenceErrorReason;
};
type WorkerInferenceManagerOptions = {
  execute: WorkerInferenceExecutor;
  store?: WorkerInferenceStore;
  requestMaxBytes?: number;
  streamMaxBytes?: number;
};
//#endregion
//#region src/gateway/worker-environments/inference-control-internal.d.ts
type WorkerInferenceSessionDrain = {
  drained: Promise<void>;
  hasWork(): boolean;
  release(): void;
};
type AcceptedWorkerInferenceSessionDrain = WorkerInferenceSessionDrain & {
  start(assertCurrent?: () => void): void;
};
type WorkerInferenceCancellation = {
  readonly runIds: readonly string[];
  /** Physical execution for precisely these captured registrations, not cancellation ACKs. */
  readonly settled: Promise<void>;
  readonly executing: boolean;
  cancel(control?: {
    assertCurrent?: () => void;
    onCancelled?: (runId: string) => void;
  }): Promise<string[]>;
};
//#endregion
//#region src/gateway/worker-environments/inference.d.ts
declare function createWorkerInferenceManager(options: WorkerInferenceManagerOptions): {
  ready: () => Promise<void>;
  start: (params: {
    identity: WorkerConnectionIdentity;
    request: WorkerInferenceStartParams;
    sink: WorkerInferenceSink;
    sessionTarget: BoundAgentRunSessionTarget;
    assertSourceCurrent?: () => void;
    revalidate?: RevalidateInference;
  }) => Promise<WorkerInferenceStartApplicationResult>;
  cancel: (params: Parameters<(params: {
    identity: WorkerConnectionIdentity;
    request: WorkerInferenceCancelParams;
    revalidate?: RevalidateInference;
  }) => Promise<WorkerInferenceCancelApplicationResult>>[0]) => Promise<WorkerInferenceCancelApplicationResult>;
  cancelEnvironment: (environmentId: string) => Promise<void>;
  cancelClaim: (claim: WorkerSessionTurnClaim) => Promise<void>;
  cancelSession: (sessionId: string, runId?: string) => Promise<string[]>;
  captureSessionCancellation: (sessionId: string, runId?: string) => WorkerInferenceCancellation;
  reserveSessionDrain: (sessionId: string) => AcceptedWorkerInferenceSessionDrain;
  hasSession: (sessionId: string, runId?: string) => boolean;
  resolveSessionTargetForRunId: (runId: string) => BoundAgentRunSessionTarget | undefined;
  stop: () => Promise<void>;
};
//#endregion
//#region src/agents/session-placement-admission.types.d.ts
type LocalTurnPlacementClaim = {
  sessionId: string;
  agentId?: string;
  sessionKey?: string;
  runId: string;
};
/** Shared admission operation; request contracts must not import the agent runtime. */
type RequiredSessionPlacementAdmission = <T>(identity: Omit<LocalTurnPlacementClaim, "runId">, task: (assertPlacementCurrent: SessionSourceAssertion) => Promise<T>, assertCurrent?: SessionSourceAssertion, signal?: AbortSignal, preparation?: {
  waitForReady: false;
  retainDispatch?: () => () => void;
}) => Promise<T>;
//#endregion
//#region src/gateway/worker-environments/live-event-window.d.ts
type WorkerLiveCredentialRotation = Readonly<{
  credentialHash: string;
  environmentId: string;
  previousCredentialHash: string;
  runEpoch: number;
  sessionId: string;
} & ({
  newProcessTurn: true;
  ackedSeq: number;
} | {
  newProcessTurn?: false;
})>;
//#endregion
//#region src/gateway/worker-environments/live-events.d.ts
type WorkerLiveEventApplicationResult = {
  ok: true;
  result: WorkerLiveEventResult;
} | {
  ok: false;
  details: WorkerLiveEventErrorDetails;
};
type WorkerLiveEventReceiverOptions = {
  maxActiveRuns?: number;
  maxSessions?: number;
  windowSize?: number;
};
declare function createWorkerLiveEventReceiver(options?: WorkerLiveEventReceiverOptions): {
  apply: (params: {
    identity: WorkerConnectionIdentity;
    request: WorkerLiveEventParams;
    source: WorkerTurnTranscriptSource;
    readAckedSeq: () => number;
  }) => Promise<WorkerLiveEventApplicationResult>;
  clear: () => void;
  clearEnvironment: (environmentId: string) => void;
  rotateCredential: (rotation: WorkerLiveCredentialRotation) => boolean;
};
type WorkerLiveEventReceiver = ReturnType<typeof createWorkerLiveEventReceiver>;
//#endregion
//#region src/gateway/worker-environments/placement-worker-gate.d.ts
type WorkerPlacementBinding = Readonly<{
  sessionId: string;
  environmentId: string;
  ownerEpoch: number;
}>;
type WorkerSessionPlacementGate = {
  fenceWorkerTurnForRecovery: (claim: WorkerSessionTurnClaim) => void;
  /** Refresh runtime bytes without changing the retained workspace's owner epoch. */
  prepareWorkerRuntimeRefresh(binding: WorkerPlacementBinding): Promise<{
    generation: number;
    reclaimResult?: WorkerWorkspacePendingResult;
    assertCurrent: () => void;
    release: () => void;
  }>;
  /** Credential verification only; this does not grant operational worker authority. */
  readWorkerTurnClaim(binding: WorkerPlacementBinding): WorkerSessionTurnClaim | undefined;
  getExecutionIdentityCapability?(claim: WorkerSessionTurnClaim): WorkerTurnExecutionIdentityCapability | undefined;
  readWorkerTurnLiveAckCursor(claim: WorkerSessionTurnClaim): number;
  validateWorkerTurn(claim: WorkerSessionTurnClaim): boolean;
  isWorkerTurnToolAuthorized(claim: WorkerSessionTurnClaim, toolName: string): boolean;
  updateAckCursors(input: {
    claim: WorkerSessionTurnClaim;
    transcriptSeq?: number;
    liveSeq?: number;
    assertCurrent?: () => void;
  }): Promise<void>;
  prepareWorkspaceResultOwnerRevocation(binding: WorkerPlacementBinding, error: Error, assertCurrent?: () => void): Promise<void>;
  registerTurnClaimClosedHandler(handler: (claim: WorkerSessionTurnClaim) => void): () => void;
};
//#endregion
//#region src/gateway/worker-environments/credential.d.ts
type WorkerCredentialRecord = {
  environmentId: string;
  credentialHash: string;
  bundleHash: string;
  sessionId: string | null;
  rpcSetVersion: number;
  ownerEpoch: number;
  expiresAtMs: number;
  deliveredAtMs: number | null;
};
type MintedWorkerCredential = Omit<WorkerCredentialRecord, "credentialHash" | "deliveredAtMs"> & {
  credential: string;
  deliveryId: string;
  turnClaim?: WorkerSessionTurnClaim;
};
type WorkerCredentialBinding = Pick<WorkerCredentialRecord, "environmentId" | "ownerEpoch" | "sessionId">;
//#endregion
//#region src/gateway/worker-environments/store-write-types.d.ts
type WorkerEnvironmentTransitionPatch = {
  leaseId?: string | null;
  nodeDeviceId?: string | null;
  sshEndpoint?: WorkerSshEndpoint | null;
  sharedHost?: boolean;
  desktop?: WorkerDesktopEndpoint | null;
  bootstrapReceipt?: WorkerEnvironmentBootstrapReceipt;
  attachedSessionIds?: readonly string[];
  lastError?: string | null;
  credential?: CredentialInput;
};
type CredentialInput = {
  credentialHash: string;
  sessionId: string | null;
  rpcSetVersion: number;
  expiresAtMs: number;
};
type CredentialRevocationInput = {
  environmentId: string;
  expectedOwnerEpoch?: number;
};
type TransitionInput = {
  assertCurrent?: () => void;
  environmentId: string;
  from: WorkerEnvironmentState;
  to: WorkerEnvironmentState;
  expectedOwnerEpoch?: number;
  placementBinding?: PreparedEnvironmentPlacementBinding;
  patch?: WorkerEnvironmentTransitionPatch;
};
type BootstrapRefreshInput = {
  environmentId: string;
  expectedOwnerEpoch: number;
  expectedNodeDeviceId: string | null;
  expectedBootstrapReceipt: WorkerEnvironmentBootstrapReceipt;
  bootstrapReceipt: WorkerEnvironmentBootstrapReceipt;
  assertCurrent: () => void;
} & ({
  expectedState: "attached";
  expectedPlacementGeneration: number;
  expectedReclaimResult?: WorkerWorkspacePendingResult;
} | {
  expectedState: "ready" | "idle";
  expectedPlacementGeneration?: never;
});
type WorkerEnvironmentPruneInput = {
  nowMs?: number;
  limit?: number;
  canPruneDemand?: (record: WorkerEnvironmentRecord, nowMs: number) => boolean;
};
//#endregion
//#region src/gateway/worker-environments/store.types.d.ts
/** Native mutation signatures own the host callbacks and the worker's serializable contract. */
type WorkerEnvironmentMutationMethods = {
  createIntent(input: WorkerEnvironmentIntentInput): WorkerEnvironmentRecord;
  ensureNodeEnrollment(environmentId: string): WorkerEnvironmentRecord;
  revokeEnvironmentCredential(input: CredentialRevocationInput): void;
  reconcileSharedHost(input: {
    environmentId: string;
    state: WorkerEnvironmentState;
    leaseId: string;
    sharedHost: boolean;
  }): WorkerEnvironmentRecord;
  adoptProvisionCleanupFailure(input: {
    environmentId: string;
    leaseId: string;
    lastError: string;
  }): WorkerEnvironmentRecord;
  requestDestroy(input: {
    environmentId: string;
    state: WorkerEnvironmentState;
    terminalState?: WorkerEnvironmentTeardownTerminalState;
    assertCurrent?: () => void;
    lastError?: string;
  }): WorkerEnvironmentRecord;
  refreshBootstrapReceipt(input: BootstrapRefreshInput): WorkerEnvironmentRecord;
  transition(input: TransitionInput): WorkerEnvironmentRecord;
  renewCredential(input: CredentialInput & {
    environmentId: string;
    expectedOwnerEpoch: number;
    assertCurrent?: () => void;
  }): WorkerCredentialRecord;
  markCredentialDelivered(input: {
    environmentId: string;
    credentialHash: string;
    ownerEpoch: number;
    sessionId: string | null;
    deliveredAtMs: number;
    assertCurrent?: () => void;
  }): void;
  recordError(input: {
    environmentId: string;
    state: WorkerEnvironmentState;
    error: string;
    assertCurrent?: () => void;
  }): WorkerEnvironmentRecord;
  ensurePreparedIntent(input: {
    intent: WorkerEnvironmentIntentInput & {
      preparation: WorkerEnvironmentPreparationIntent;
    };
    projectKey: string;
    target: number;
    maxTotal: number;
    assertCurrent: () => void;
  }): WorkerEnvironmentRecord | undefined;
  requestPreparedDestroy(input: {
    environmentId: string;
    ownerEpoch: number;
    preparationKey: string;
    reason: "expired" | "invalidated";
    assertCurrent: () => void;
  }): WorkerEnvironmentRecord | undefined;
  createSessionAttachmentIntent(input: WorkerEnvironmentIntentInput & WorkerEnvironmentSessionIdentity, assertCurrent: () => void): {
    attachment: WorkerEnvironmentAttachmentRecord;
    environment: WorkerEnvironmentRecord;
  };
  closeSessionAttachment(sessionId: string, assertCurrent?: () => void): WorkerEnvironmentAttachmentRecord | undefined;
  cancelSessionAttachmentReservation(record: WorkerEnvironmentAttachmentRecord): void;
  touchSessionAttachment(record: WorkerEnvironmentAttachmentRecord, assertCurrent: () => void): void;
  pruneTerminalEnvironments(input: {
    environmentIds: string[];
    cutoffMs: number;
    limit: number;
  }): number;
};
//#endregion
//#region src/gateway/worker-environments/prepared-environment-store.d.ts
type PreparedReservationCandidate = Pick<WorkerEnvironmentRecord, "environmentId" | "profileId" | "profileSnapshot" | "leaseId" | "state" | "preparation" | "destroyRequestedAtMs" | "createdAtMs">;
declare function selectPreparedEnvironmentReservations(records: readonly PreparedReservationCandidate[]): {
  environmentId: string;
  profileId: string;
  leaseId: string | null;
  cleanupOrder: number;
  state: WorkerEnvironmentLeasedState | WorkerEnvironmentUnleasedState;
  purpose: "build" | "reserve";
  projectKey: string;
  createdAtMs: number;
}[];
type Reservations = ReturnType<typeof selectPreparedEnvironmentReservations>;
declare function preparedCapacityFromReservations(reserved: Reservations, input: {
  profileId: string;
  projectKey: string;
  target: number;
  maxTotal: number;
}): number;
declare function isPreparedReservationWithinCapacity(reservations: Reservations, input: {
  environmentId: string;
  target: number;
  maxTotal: number;
}): boolean;
//#endregion
//#region src/gateway/worker-environments/store.d.ts
type Input<Method extends keyof WorkerEnvironmentMutationMethods> = Parameters<WorkerEnvironmentMutationMethods[Method]>[0];
declare function createWorkerEnvironmentStore(options?: {
  database?: OpenClawStateDatabase;
  now?: () => number;
}): Promise<{
  close: () => Promise<void>;
  ready: () => Promise<void>;
  hasSessionAttachment(environmentId: string): Promise<boolean>;
  inventoryVersion: () => number;
  get: (id: string) => WorkerEnvironmentRecord | undefined;
  list: () => WorkerEnvironmentRecord[];
  listForReconcile: () => WorkerEnvironmentRecord[];
  getCredential: (id: string) => WorkerCredentialRecord | undefined;
  findCredentialByHash: (hash: string) => WorkerCredentialRecord | undefined;
  getTransferOwner: (id: string) => {
    environment: {
      ownerEpoch: number;
      attachedSessionIds: string[];
      destroyRequestedAtMs: number | null;
      state: WorkerEnvironmentLeasedState | WorkerEnvironmentUnleasedState;
    };
    credential: {
      ownerEpoch: number;
      expiresAtMs: number;
      sessionId: string | null;
    } | undefined;
  } | undefined;
  hasNodeEnrollmentOwner: (nodeId: string) => boolean;
  hasPendingNodeEnrollmentSetup: (setup: string, device: string) => boolean;
  preparedCapacity: (input: Parameters<typeof preparedCapacityFromReservations>[1]) => number;
  preparedReservationEnvironmentIds: () => string[];
  isPreparedIntentWithinCapacity: (input: Parameters<typeof isPreparedReservationWithinCapacity>[1]) => boolean;
  getSessionAttachmentRecord: (id: string) => WorkerEnvironmentAttachmentRecord | undefined;
  listSessionAttachmentRecords: () => WorkerEnvironmentAttachmentRecord[];
  findSessionAttachmentRecord(input: Pick<WorkerEnvironmentSessionIdentity, "agentId" | "sessionKey">): WorkerEnvironmentAttachmentRecord | undefined;
  onCredentialRevoked(listener: (id: string) => void): () => void;
  createIntent: (input: Input<"createIntent">, assertCurrent?: () => void) => Promise<WorkerEnvironmentRecord>;
  ensureNodeEnrollment: (input: string) => Promise<WorkerEnvironmentRecord>;
  revokeEnvironmentCredential(input: string, opts?: {
    fenceWorkspaceTransfers?: boolean;
    expectedOwnerEpoch?: number;
    assertCurrent?: () => void;
  }): Promise<void>;
  reconcileSharedHost: (input: Input<"reconcileSharedHost">) => Promise<WorkerEnvironmentRecord>;
  adoptProvisionCleanupFailure: (input: Input<"adoptProvisionCleanupFailure">) => Promise<WorkerEnvironmentRecord>;
  requestDestroy({ assertCurrent, ...input }: Input<"requestDestroy">): Promise<WorkerEnvironmentRecord>;
  refreshBootstrapReceipt({ assertCurrent, ...input }: Input<"refreshBootstrapReceipt">): Promise<WorkerEnvironmentRecord>;
  transition({ assertCurrent, placementBinding, ...input }: Input<"transition">): Promise<WorkerEnvironmentRecord>;
  renewCredential({ assertCurrent, ...input }: Input<"renewCredential">): Promise<WorkerCredentialRecord>;
  markCredentialDelivered({ assertCurrent, ...input }: Input<"markCredentialDelivered">): Promise<void>;
  recordError({ assertCurrent, ...input }: Input<"recordError">): Promise<WorkerEnvironmentRecord>;
  ensurePreparedIntent({ assertCurrent, ...input }: Input<"ensurePreparedIntent">): Promise<WorkerEnvironmentRecord | undefined>;
  requestPreparedDestroy({ assertCurrent, ...input }: Input<"requestPreparedDestroy">): Promise<WorkerEnvironmentRecord | undefined>;
  createSessionAttachmentIntent(input: Input<"createSessionAttachmentIntent">, assertCurrent: () => void): Promise<{
    attachment: WorkerEnvironmentAttachmentRecord;
    environment: {
      environmentId: string;
      providerId: string;
      profileId: string;
    } & {
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
    } & {
      state: WorkerEnvironmentUnleasedState;
      leaseId: null;
      sshEndpoint: null;
    };
  }>;
  closeSessionAttachment(input: string, assertCurrent?: () => void): Promise<WorkerEnvironmentAttachmentRecord | undefined>;
  cancelSessionAttachmentReservation(input: Input<"cancelSessionAttachmentReservation">): Promise<void>;
  touchSessionAttachment(input: Input<"touchSessionAttachment">, assertCurrent: () => void): Promise<void>;
  pruneTerminalEnvironments(input?: WorkerEnvironmentPruneInput): Promise<number>;
}>;
type WorkerEnvironmentStore = Awaited<ReturnType<typeof createWorkerEnvironmentStore>>;
//#endregion
//#region src/gateway/worker-environments/transcript-commit.d.ts
type WorkerTranscriptCommitApplication = (params: {
  identity: WorkerConnectionIdentity;
  request: WorkerTranscriptCommitParams;
  sessionTarget: BoundAgentRunSessionTarget;
  assertCurrent: () => undefined;
  onCommitted?: (outcome: WorkerTranscriptCommitOutcome) => Promise<void>;
}) => Promise<WorkerTranscriptCommitOutcome>;
//#endregion
//#region src/gateway/worker-environments/worker-turn-computer-rpc.d.ts
type WorkerComputerExecutor = (params: {
  identity: WorkerConnectionIdentity;
  request: WorkerComputerParams;
  signal?: AbortSignal;
  assertCurrent: () => void;
}) => Promise<WorkerComputerResult>;
//#endregion
//#region src/gateway/worker-environments/worker-turn-rpc.types.d.ts
type WorkerTranscriptCommitServiceResult = WorkerTranscriptCommitOutcome | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerLiveEventServiceResult = WorkerLiveEventApplicationResult | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerInferenceServiceResult<K extends "start" | "cancel"> = Awaited<ReturnType<ReturnType<typeof createWorkerInferenceManager>[K]>> | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
//#endregion
//#region src/worker/node-workspace-prepared-protocol.d.ts
declare const Result: z.ZodObject<{
  gatewayNamespace: z.ZodString;
  environmentId: z.ZodString;
  preparationKey: z.ZodString;
  cacheKey: z.ZodString;
  workspaceDir: z.ZodString;
  homeDir: z.ZodString;
  sourceManifestRef: z.ZodString;
  preparedManifestRef: z.ZodString;
}, z.core.$strict>;
type NodeWorkerPreparedWorkspaceResult = z.infer<typeof Result>;
//#endregion
//#region src/gateway/worker-environments/ssh.d.ts
type WorkerSshIdentityResolver = (keyRef: WorkerSshEndpoint["keyRef"], context: {
  assertCurrent: () => void;
}) => Promise<WorkerSshIdentity>;
//#endregion
//#region src/gateway/worker-environments/tunnel-ssh-runner.d.ts
type WorkerSshProcessExit = {
  code: number | null;
  signal: NodeJS.Signals | null;
  stderrTail?: string;
};
type WorkerSshProcess = {
  ready: Promise<void>;
  exited: Promise<WorkerSshProcessExit>;
  stop(): Promise<void>;
};
type WorkerSshRunner = {
  start(argv: string[], options: CommandOptions): WorkerSshProcess;
  run(argv: string[], options: CommandOptions): Promise<SpawnResult>;
};
//#endregion
//#region src/gateway/worker-environments/tunnel.d.ts
type WorkerTunnelStartRequest = WorkerTunnelRequest & {
  bundleHash: string;
  ssh: WorkerSshEndpoint;
  sharedHost?: boolean;
  resolveIdentity: WorkerSshIdentityResolver;
};
type WorkerTunnelManagerOptions = {
  runner?: WorkerSshRunner;
  desktopSessionRegistry?: DesktopSessionRegistry;
};
/** Owns SSH workspace state for remote-exec environments and fences replacement epochs. */
declare function createWorkerTunnelManager(options?: WorkerTunnelManagerOptions): {
  desktop: {
    acquire: (request: {
      environmentId: string;
      ownerEpoch: number;
      ssh: WorkerSshEndpoint;
      desktop: WorkerDesktopEndpoint;
      resolveIdentity: WorkerSshIdentityResolver;
    }) => Promise<{
      attachment: DesktopRfbAttachment;
      auth?: "vnc-password" | "ard-account";
      vncPassword?: string;
      resolveAudio?: () => DesktopAudioSource | undefined;
      readonly audioUnavailableReason?: string;
    }>;
    attachObserver: (sourceKey: string, observer: {
      control: boolean;
      operatorName?: string;
      ownerEpoch: number;
      close(code: number, reason: string): void;
    }) => {
      release(): void;
    } | undefined;
    launchApp: (request: {
      environmentId: string;
      ownerEpoch: number;
      ssh: WorkerSshEndpoint;
      app: WorkerDesktopApp;
      resolveIdentity: WorkerSshIdentityResolver;
    }) => Promise<void>;
    stop: (environmentId: string, ownerEpoch?: number) => Promise<void>;
    stopAll: () => Promise<void>;
  };
  start: (request: WorkerTunnelStartRequest) => Promise<WorkerTunnelHandle>;
  stop: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  stopAll: () => Promise<void>;
  status(environmentId: string): WorkerTunnelStatus;
};
type WorkerTunnelManager = ReturnType<typeof createWorkerTunnelManager>;
//#endregion
//#region src/worker/node-bundle-install-protocol.d.ts
type NodeWorkerBundleInstallResult = WorkerAdmissionHandshake;
//#endregion
//#region src/infra/node-commands.d.ts
declare const NODE_WORKER_PRIVATE_COMMANDS: readonly ["worker.bundle.install.v1", "worker.launch.v1", "worker.status.v1", "worker.cancel.v1", "worker.environment.stop.v1", "worker.processes.v1", "worker.workspace.exec.v1", "worker.workspace.prepare.v1", "worker.workspace.retain.v1", "worker.desktop.stream.v1", "worker.desktop.launch.v1", "worker.desktop.computer.v1", "worker.portal.stream.v1"];
//#endregion
//#region src/infra/node-runner-inventory.d.ts
declare const NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE = "node-worker-supervisor-v6";
declare const NODE_RUNNER_UPDATE_REQUIRED_ISSUE: {
  readonly code: "update-required";
  readonly action: "update-and-reconnect";
  readonly updateCommand: "openclaw update";
  readonly headlessReconnectCommand: "openclaw node restart";
};
type NodeRunnerInventoryIssue = typeof NODE_RUNNER_UPDATE_REQUIRED_ISSUE | {
  code: "worker-host-unavailable";
  message: string;
};
declare const WorkerHost: z.ZodPipe<z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  enabled: z.ZodLiteral<false>;
  reason: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  enabled: z.ZodLiteral<true>;
  capacity: z.ZodTransform<{
    total: number;
    available: number;
    reclaimableIdle?: number | undefined;
  }, unknown>;
  bundlePrewarm: z.ZodOptional<z.ZodLiteral<1>>;
  bundleRetention: z.ZodOptional<z.ZodLiteral<1>>;
  bundlePrefetch: z.ZodOptional<z.ZodLiteral<1>>;
  bundleStatus: z.ZodOptional<z.ZodLiteral<1>>;
  portalStream: z.ZodOptional<z.ZodLiteral<1>>;
  environmentSession: z.ZodOptional<z.ZodLiteral<1>>;
  statusWait: z.ZodOptional<z.ZodLiteral<1>>;
  deviceFolders: z.ZodOptional<z.ZodLiteral<true>>;
  preparedWorkspace: z.ZodOptional<z.ZodLiteral<1>>;
  capturedExecPolicy: z.ZodOptional<z.ZodLiteral<true>>;
  workspaceResultVersion: z.ZodOptional<z.ZodLiteral<2>>;
  workspaceQuiescence: z.ZodOptional<z.ZodLiteral<1>>;
  launchToolNames: z.ZodOptional<z.ZodArray<z.ZodString>>;
  idleRetention: z.ZodOptional<z.ZodLiteral<true>>;
  nativeInference: z.ZodOptional<z.ZodLiteral<1>>;
  promptContext: z.ZodOptional<z.ZodLiteral<1>>;
}, z.core.$strip>>]>, z.ZodTransform<{
  enabled: false;
  reason?: string | undefined;
} | {
  enabled: true;
  capacity: {
    total: number;
    available: number;
    reclaimableIdle?: number | undefined;
  };
  bundlePrewarm?: 1 | undefined;
  bundleRetention?: 1 | undefined;
  bundlePrefetch?: 1 | undefined;
  bundleStatus?: 1 | undefined;
  portalStream?: 1 | undefined;
  environmentSession?: 1 | undefined;
  statusWait?: 1 | undefined;
  deviceFolders?: true | undefined;
  preparedWorkspace?: 1 | undefined;
  capturedExecPolicy?: true | undefined;
  workspaceResultVersion?: 2 | undefined;
  workspaceQuiescence?: 1 | undefined;
  launchToolNames?: string[] | undefined;
  idleRetention?: true | undefined;
  nativeInference?: 1 | undefined;
  promptContext?: 1 | undefined;
}, {
  enabled: false;
  reason?: string | undefined;
} | {
  enabled: true;
  capacity: {
    total: number;
    available: number;
    reclaimableIdle?: number | undefined;
  };
  bundlePrewarm?: 1 | undefined;
  bundleRetention?: 1 | undefined;
  bundlePrefetch?: 1 | undefined;
  bundleStatus?: 1 | undefined;
  portalStream?: 1 | undefined;
  environmentSession?: 1 | undefined;
  statusWait?: 1 | undefined;
  deviceFolders?: true | undefined;
  preparedWorkspace?: 1 | undefined;
  capturedExecPolicy?: true | undefined;
  workspaceResultVersion?: 2 | undefined;
  workspaceQuiescence?: 1 | undefined;
  launchToolNames?: string[] | undefined;
  idleRetention?: true | undefined;
  nativeInference?: 1 | undefined;
  promptContext?: 1 | undefined;
}>>;
type NodeWorkerHostDeclaration = z.infer<typeof WorkerHost>;
//#endregion
//#region src/gateway/node-invoke.types.d.ts
type NodeSystemRunEventSource = {
  expectedTarget: SessionEventTarget$1;
  release: () => void;
};
type NodeInvokeParams = {
  nodeId: string;
  expectedConnId?: string;
  expectedPairingGeneration?: string;
  command: string;
  params?: unknown;
  timeoutMs?: number;
  /** Process-local monotonic deadline inherited from invocation admission. */
  deadlineAtMs?: number;
  /** Inactivity deadline reset by each ordered progress chunk. */
  idleTimeoutMs?: number;
  onProgress?: (chunk: string) => void;
  signal?: AbortSignal;
  idempotencyKey?: string;
  sessionKey?: string;
  /** Host-bound source conversation, independent of the model session or node payload. */
  turnSource?: DeliveryContext;
  /** Host-only caller custody for delayed system.run notices; never forwarded to the node. */
  prepareSystemRunEventSource?: (sessionKey: string) => Promise<NodeSystemRunEventSource | undefined>;
  /** Receives the id and armed hard deadline after a successful dispatch. */
  onDispatchReady?: (invokeId: string, deadlineAtMs?: number) => void;
  /** Prepares durable approval authority after transport preparation, before the final guard. */
  authorizeDispatch?: () => Promise<boolean>;
  /** Revalidates caller authority at the registry-owned transport handoff. */
  isDispatchAuthorized?: () => boolean;
};
/** Result payload returned from node.invoke. */
type NodeInvokeResult = {
  ok: boolean;
  payload?: unknown;
  payloadJSON?: string | null;
  error?: {
    code?: string;
    message?: string;
    details?: unknown;
  } | null;
};
//#endregion
//#region src/infra/device-bootstrap.worker-types.d.ts
type CloudWorkerSetupMutationAdmission = {
  environmentId: string;
  setupId: string;
  credentialDigest: string;
  provisionOperationId: string;
  ownerEpoch: number;
};
//#endregion
//#region src/infra/node-pairing-surface.d.ts
type NodeApprovalSurface = {
  caps: string[];
  commands: string[];
  permissions?: Record<string, boolean>;
};
//#endregion
//#region src/infra/device-pairing-read.types.d.ts
type DevicePairingBinding = {
  identity: string;
  generation?: string;
};
//#endregion
//#region src/infra/device-pairing.d.ts
declare function listDevicePairing(baseDir?: string): Promise<{
  pending: DevicePairingPendingRequest[];
  paired: PairedDevice[];
}>;
//#endregion
//#region src/infra/device-pairing-node-state.d.ts
/** Registry projection of a paired device's authenticated node-role state. */
type PairedDeviceNodeBinding = DevicePairingBinding;
//#endregion
//#region src/gateway/node-event-payload.d.ts
declare const SERIALIZED_EVENT_PAYLOAD: unique symbol;
type SerializedEventPayload = {
  readonly json: string;
  readonly [SERIALIZED_EVENT_PAYLOAD]: true;
};
//#endregion
//#region src/gateway/node-session.types.d.ts
/** Connected node session advertised over Gateway websocket. */
type NodeSession = {
  nodeId: string;
  connId: string;
  /** Persistent device key and node-token identity authenticated for this connection. */
  pairingIdentity?: string;
  /** Persistent pairing generation authenticated before this session was registered. */
  pairingGeneration?: string;
  client: GatewayWsClient;
  clientId?: string;
  clientMode?: string;
  displayName?: string;
  platform?: string;
  version?: string;
  coreVersion?: string;
  uiVersion?: string;
  deviceFamily?: string;
  modelIdentifier?: string;
  remoteIp?: string;
  declaredCaps: string[];
  sessionCapsCeiling?: string[];
  caps: string[];
  declaredCommands: string[];
  sessionCommandsCeiling?: string[];
  commands: string[];
  declaredComputerUse?: ComputerUseCapabilityDescriptor;
  computerUse?: ComputerUseCapabilityDescriptor;
  declaredNodePluginTools: NodePluginToolDescriptor[];
  nodePluginTools: NodePluginToolDescriptor[];
  nodeSkills: NodeSkillDescriptor[];
  declaredPermissions?: Record<string, boolean>;
  permissions?: Record<string, boolean>;
  pathEnv?: string;
  connectedAtMs: number;
  lastActiveAtMs?: number;
  presenceUpdatedAtMs?: number;
  /** Source of the current connection's activity sample; reset with that sample. */
  presenceActivitySource?: "app" | "system";
  hostStats?: NodeHostStats;
  desktopAvailability?: DesktopAvailability;
};
type NodeEventPayloadPreparation = (connId: string) => {
  payloadJSON: SerializedEventPayload | null;
  onSent?: () => void;
} | undefined;
type NodeConnectivityResult = {
  ok: true;
} | {
  ok: false;
  error: {
    code: string;
    message: string;
  };
};
/** Event transport for nodes that cannot keep a WebSocket open, such as watchOS. */
type NodeEventTransport = {
  send: (event: string, payload: unknown) => boolean;
  sendRaw: (event: string, payloadJSON?: SerializedEventPayload | null) => boolean;
  checkConnectivity?: (timeoutMs: number) => Promise<NodeConnectivityResult>;
};
//#endregion
//#region src/gateway/node-registry.invoke-stream.d.ts
type PendingSystemRunEvent = {
  runId: string;
  sessionKey?: string;
  invocationDeliveryContext?: DeliveryContext;
  timeoutMs?: number | null;
  source?: NodeSystemRunEventSource;
};
type PendingInvoke = {
  nodeId: string;
  connId: string;
  command: string;
  systemRunEvent?: PendingSystemRunEvent;
  resolve: (value: NodeInvokeResult) => void;
  reject: (err: Error) => void;
  deadlineAtMs?: number;
  cancelHardDeadline?: () => void;
  idleTimer?: ReturnType<typeof setTimeout>;
  idleTraceContext?: DiagnosticTraceContext;
  idleTimeoutMs?: number;
  onProgress?: (chunk: string) => void;
  receivedProgress?: boolean;
  nextProgressSeq: number;
  progressChunks: Map<number, string>;
  nextInputSeq: number;
  removeAbortListener?: () => void;
  admissionContinuation?: GatewayRootWorkAdmissionContinuationScope;
  isCompletionAuthorized?: () => boolean;
};
type NodeInvokeProgressParams = NodeInvokeProgressParams$1 & {
  connId: string | undefined;
};
type NodeInvokeResultParams = NodeInvokeResult & {
  id: string;
  nodeId: string;
  connId: string | undefined;
};
//#endregion
//#region src/gateway/node-registry.system-run.d.ts
type AuthorizedSystemRunEvent = PendingSystemRunEvent & {
  nodeId: string;
  connId: string;
  expiresAtMs: number | null;
  expiryTimer?: ReturnType<typeof setTimeout>;
};
/** Owns delayed notices independently of the inline invocation's request lifetime. */
declare class NodeSystemRunEvents {
  private readonly pendingInvokes;
  private readonly getNode;
  private authorizedSystemRunEvents;
  constructor(pendingInvokes: Map<string, PendingInvoke>, getNode: (nodeId: string) => NodeSession | undefined);
  authorize(params: {
    nodeId: string;
    connId?: string;
    runId?: string;
    sessionKey: string;
    terminal: boolean;
  }): (Pick<PendingSystemRunEvent, "invocationDeliveryContext"> & {
    expectedTarget?: SessionEventTarget$1;
    release?: () => void;
    holdNotice?: (notify: () => void) => void;
  }) | null;
  remember(event: Omit<AuthorizedSystemRunEvent, "expiresAtMs">): void;
  forget(event: Omit<AuthorizedSystemRunEvent, "expiresAtMs">): void;
  disconnect(connId: string): void;
  private matchAuthorizedSystemRunEvent;
  private allowsLegacyMacRunIdFallback;
  private pruneAuthorizedSystemRunEvents;
}
//#endregion
//#region src/gateway/node-runner-inventory-runtime.d.ts
type NodeWorkerHostClientId = typeof GATEWAY_CLIENT_IDS.NODE_HOST | typeof GATEWAY_CLIENT_IDS.MACOS_APP;
type NodeWorkerBundleStatusObservation = {
  bundleHash: string;
  status: NodeWorkerBundleStatus;
};
type NodeWorkerSupervisorNodeProof = {
  nodeId: string;
  connId: string;
  pairingIdentity: string;
  pairingGeneration: string;
  clientId: NodeWorkerHostClientId;
  clientMode: "node";
  protocolFeature: typeof NODE_WORKER_SUPERVISOR_PROTOCOL_FEATURE;
  workerHost: Extract<NodeWorkerHostDeclaration, {
    enabled: true;
  }>;
  commands: readonly string[];
};
//#endregion
//#region src/gateway/node-registry-private.d.ts
type NodeWorkerPrivateCommand = (typeof NODE_WORKER_PRIVATE_COMMANDS)[number];
type NodeWorkerSupervisorTransport = {
  getCurrentNode(nodeId: string): Promise<NodeWorkerSupervisorNodeProof | undefined>;
  listCurrentNodes(): Promise<readonly NodeWorkerSupervisorNodeProof[]>;
  hasCurrentRunner(nodeId: string): boolean;
  /** Diagnostic connection presence, independent of session-host eligibility. */
  isConnected?(nodeId: string): boolean;
  getIssue?(nodeId: string): NodeRunnerInventoryIssue | undefined;
  getBundleStatus?(nodeId: string): NodeWorkerBundleStatusObservation | undefined;
  acceptBundleStatus?(node: NodeWorkerSupervisorNodeProof, observation: NodeWorkerBundleStatusObservation | undefined): boolean;
  isCurrent(node: NodeWorkerSupervisorNodeProof, requireLaunchEligibility?: boolean, requiredCommands?: readonly string[], requireCapturedExecPolicy?: boolean): boolean;
  invoke(params: {
    node: NodeWorkerSupervisorNodeProof;
    command: NodeWorkerPrivateCommand;
    params?: unknown;
    timeoutMs?: number;
    signal?: AbortSignal;
    idempotencyKey?: string;
    authorizeDispatch?: () => Promise<boolean>;
    isDispatchAuthorized: () => boolean;
    /** Completed effects may retain response custody after their dispatch snapshot changes. */
    isCompletionAuthorized?: () => boolean;
    onDispatchReady?: (invokeId: string) => void;
  }): Promise<NodeInvokeResult>;
};
//#endregion
//#region src/gateway/worker-environments/node-worker-bundle-installer.d.ts
type GatewayNodeWorkerBundleInstall = (params: {
  deviceId: string;
  artifact: Extract<WorkerInstallationArtifact, {
    install: "bundle";
  }>;
  signal?: AbortSignal;
  assertCurrent?: () => void;
  onProgress?: () => void;
} & ({
  reason: "prefetch";
  environmentId?: never;
  prewarm?: never;
} | {
  reason: "provision" | "refresh";
  environmentId: string;
  prewarm: boolean;
})) => Promise<NodeWorkerBundleInstallResult>;
//#endregion
//#region src/gateway/worker-environments/preparation-identity.schema.d.ts
declare const WorkerPreparationArtifactsSchema: z.ZodObject<{
  nodeBootstrapSha256: z.ZodString;
  enabledPluginIds: z.ZodArray<z.ZodString>;
  workerBundleHash: z.ZodString;
  workerArchiveSha256: z.ZodString;
  openclawVersion: z.ZodString;
  protocolFeatures: z.ZodArray<z.ZodString>;
}, z.core.$strict>;
declare const Preparation: z.ZodObject<{
  key: z.ZodString;
  cacheKey: z.ZodString;
  contractVersion: z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>;
  setupRecipe: z.ZodOptional<z.ZodString>;
  runSetupScript: z.ZodOptional<z.ZodBoolean>;
  recipe: z.ZodOptional<z.ZodObject<{
    source: z.ZodEnum<{
      detected: "detected";
      devcontainer: "devcontainer";
      none: "none";
      script: "script";
    }>;
    identity: z.ZodOptional<z.ZodString>;
    inputs: z.ZodRecord<z.ZodString, z.ZodString>;
    env: z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodString>>;
    secretNames: z.ZodOptional<z.ZodArray<z.ZodString>>;
    ignoredPropertiesNote: z.ZodOptional<z.ZodString>;
    onCreate: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
    updateContent: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
    postCreate: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
    postStart: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
    detectedInstall: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
  }, z.core.$strict>>;
  target: z.ZodObject<{
    machineClass: z.ZodString;
    platform: z.ZodString;
    arch: z.ZodOptional<z.ZodString>;
    profileKey: z.ZodOptional<z.ZodString>;
  }, z.core.$strict>;
  artifacts: z.ZodObject<{
    nodeBootstrapSha256: z.ZodString;
    enabledPluginIds: z.ZodArray<z.ZodString>;
    workerBundleHash: z.ZodString;
    workerArchiveSha256: z.ZodString;
    openclawVersion: z.ZodString;
    protocolFeatures: z.ZodArray<z.ZodString>;
  }, z.core.$strict>;
}, z.core.$strict>;
declare const EmptyPreparation: z.ZodObject<{
  key: z.ZodString;
  cacheKey: z.ZodString;
  contractVersion: z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>;
  target: z.ZodObject<{
    machineClass: z.ZodString;
    platform: z.ZodString;
    arch: z.ZodOptional<z.ZodString>;
    profileKey: z.ZodOptional<z.ZodString>;
  }, z.core.$strict>;
  artifacts: z.ZodObject<{
    nodeBootstrapSha256: z.ZodString;
    enabledPluginIds: z.ZodArray<z.ZodString>;
    workerBundleHash: z.ZodString;
    workerArchiveSha256: z.ZodString;
    openclawVersion: z.ZodString;
    protocolFeatures: z.ZodArray<z.ZodString>;
  }, z.core.$strict>;
  source: z.ZodLiteral<"empty">;
}, z.core.$strict>;
type WorkerPreparationArtifacts = z.infer<typeof WorkerPreparationArtifactsSchema>;
type WorkerProjectPreparationIdentity = z.infer<typeof Preparation>;
type WorkerEmptyPreparationIdentity = z.infer<typeof EmptyPreparation>;
//#endregion
//#region src/gateway/worker-environments/environment-recipe.d.ts
declare const EnvironmentRecipeSchema: z.ZodObject<{
  source: z.ZodEnum<{
    detected: "detected";
    devcontainer: "devcontainer";
    none: "none";
    script: "script";
  }>;
  identity: z.ZodOptional<z.ZodString>;
  inputs: z.ZodRecord<z.ZodString, z.ZodString>;
  env: z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodString>>;
  secretNames: z.ZodOptional<z.ZodArray<z.ZodString>>;
  ignoredPropertiesNote: z.ZodOptional<z.ZodString>;
  onCreate: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
  updateContent: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
  postCreate: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
  postStart: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
  detectedInstall: z.ZodOptional<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>]>>;
}, z.core.$strict>;
type EnvironmentRecipe = z.infer<typeof EnvironmentRecipeSchema>;
//#endregion
//#region src/gateway/worker-environments/repository-project-source.schema.d.ts
declare const RepositoryWorkerProjectSchema: z.ZodObject<{
  key: z.ZodString;
  baseCommit: z.ZodString;
  source: z.ZodObject<{
    kind: z.ZodLiteral<"repository">;
    url: z.ZodString;
    repositoryId: z.ZodString;
    owner: z.ZodObject<{
      agent: z.ZodObject<{
        agentId: z.ZodString;
        provenance: z.ZodNullable<z.ZodObject<{
          agentId: z.ZodString;
          createdVia: z.ZodEnum<{
            agent: "agent";
            operator: "operator";
            template: "template";
          }>;
          creatorAgentId: z.ZodNullable<z.ZodString>;
          createdAtMs: z.ZodNumber;
        }, z.core.$strict>>;
      }, z.core.$strict>;
      identity: z.ZodDiscriminatedUnion<[z.ZodObject<{
        source: z.ZodLiteral<"anonymous">;
      }, z.core.$strict>, z.ZodObject<{
        source: z.ZodLiteral<"system-detected">;
        accountId: z.ZodNumber;
      }, z.core.$strict>, z.ZodObject<{
        source: z.ZodEnum<{
          "agent-override": "agent-override";
          "system-configured": "system-configured";
        }>;
        profileId: z.ZodString;
        accountId: z.ZodNumber;
      }, z.core.$strict>], "source">;
    }, z.core.$strict>;
  }, z.core.$strict>;
}, z.core.$strip>;
type RepositoryWorkerProjectSnapshot = z.infer<typeof RepositoryWorkerProjectSchema>;
//#endregion
//#region src/gateway/worker-environments/workspace-git-base.d.ts
type WorkerLocalProjectSnapshot = {
  key: string;
  root: string;
  baseCommit: string;
  label?: string;
};
type WorkerProjectSnapshot = WorkerLocalProjectSnapshot | RepositoryWorkerProjectSnapshot;
//#endregion
//#region src/gateway/worker-environments/project-preparation.d.ts
type ProjectPreparation = NonNullable<NonNullable<Parameters<WorkerProvider["provision"]>[2]>["project"]>;
type PreparationResult = Awaited<ReturnType<ProjectPreparation["prepare"]>>;
declare function createWorkerProjectPreparation(params: {
  project: WorkerProjectSnapshot;
  namespace: string;
  preparation?: {
    key: string;
    cacheKey: string;
    purpose: "session" | "reserve";
    demandAtMs: number;
    setupRecipe?: string;
    runSetupScript?: boolean;
    recipe?: EnvironmentRecipe;
  };
  setupAuthorized?: boolean;
  revalidateRepositorySource?: (signal: AbortSignal) => Promise<void>;
  prepareRepositoryGitPack?: (input: {
    temporaryRoot: string;
    signal: AbortSignal;
  }) => Promise<string>;
  requireCurrent: () => void;
  signal?: AbortSignal;
}): {
  project: ProjectPreparation;
  getPreparedWorkspace: () => PreparationResult["preparedWorkspace"];
  close: () => void;
};
//#endregion
//#region src/gateway/worker-environments/provider-lifecycle.types.d.ts
type WorkerEnvironmentAbandonment = {
  sessionId: string;
  ownerEpoch: number;
  authorize?: () => void;
};
type WorkerProviderLifecycleInputOptions = {
  store: WorkerEnvironmentStore;
  getConfig: () => OpenClawConfig;
  resolveProvider: (providerId: string) => WorkerProvider | undefined;
  prepareInstallation: (install: WorkerInstallationArtifact["install"]) => Promise<WorkerInstallationArtifact>;
  bootstrapWorker: (params: {
    operationId: string;
    sshEndpoint: WorkerSshEndpoint;
    installation: WorkerInstallationArtifact;
    resolveIdentity: WorkerSshIdentityResolver;
    signal: AbortSignal;
    assertCurrent?: () => void;
  }) => Promise<WorkerAdmissionHandshake>;
  resolveSshIdentity?: (params: {
    provider: WorkerProvider;
    leaseId: string;
    profile: WorkerProfile;
    keyRef: SecretRef;
    assertAuthorized: () => void;
  }) => Promise<WorkerSshIdentity>;
  ensureNodeWorkerBundle?: GatewayNodeWorkerBundleInstall;
  prepareNodeBootstrap?: (record: WorkerEnvironmentRecord, signal?: AbortSignal) => Promise<string>;
  prepareNodeRuntime?: (record: WorkerEnvironmentRecord, bundle: Extract<WorkerInstallationArtifact, {
    install: "bundle";
  }>, signal?: AbortSignal) => Promise<WorkerNodeRuntimePreparation>;
  closeNodeRuntime?: (preparation: WorkerNodeRuntimePreparation) => void;
  prepareNodeArtifacts?: (profileSnapshot: WorkerProfile, signal?: AbortSignal) => Promise<{
    artifacts: WorkerPreparationArtifacts;
  }>;
  registerPreparedWorkspace?: (params: {
    record: WorkerEnvironmentRecord;
    deviceId: string;
    workspace: NonNullable<ReturnType<ReturnType<typeof createWorkerProjectPreparation>["getPreparedWorkspace"]>>;
    assertCurrent: () => void;
    signal?: AbortSignal;
  }) => Promise<void>;
  bindPreparedWorkspace?: (params: {
    environmentId: string;
    ownerEpoch: number;
    sessionId: string;
    sessionKey: string;
    preparationKey: string;
    cacheKey: string;
    signal?: AbortSignal;
    assertCurrent: () => void;
  }) => Promise<NodeWorkerPreparedWorkspaceResult>;
  prepareNodeEnrollment?: (record: WorkerEnvironmentRecord, signal?: AbortSignal) => Promise<WorkerNodeEnrollment>;
  closeNodeEnrollment?: (enrollment: WorkerNodeEnrollment) => void;
  retireNodeEnrollment?: (record: WorkerEnvironmentRecord) => Promise<void>;
  projectNamespace?: string;
  placementStore?: WorkerSessionPlacementGate;
  providerCallTimeoutMs?: number;
  now?: () => number;
};
//#endregion
//#region src/gateway/worker-environments/provider-runtime-refresh.d.ts
type WorkerRuntimeRefreshInFlight = {
  /** Settles after the refresh finishes or fails; never rejects. */
  readonly settled: Promise<void>;
  /** Observe real install progress until the returned function unsubscribes. */
  onProgress(listener: () => void): () => void;
};
//#endregion
//#region src/gateway/worker-environments/preparation-identity.d.ts
type WorkerProviderPreparedIntent = {
  providerId: string;
  profileSnapshot: WorkerProfile & ({
    project?: WorkerProjectSnapshot & {
      preparation?: WorkerProjectPreparationIdentity;
    };
    runtimePreparation?: never;
  } | {
    project?: never;
    runtimePreparation: WorkerEmptyPreparationIdentity;
  });
};
//#endregion
//#region src/gateway/worker-environments/provider-intent.d.ts
type WorkerProviderIntentPreparationOptions = {
  inherited?: {
    providerId: string;
    profileSnapshot: WorkerProfile;
  };
  machineClass?: string;
  os?: string;
  executionMode?: WorkerExecutionMode;
  projectPath?: string;
  projectCommit?: string;
  /** Refill only: the retained source already admitted an empty committed workspace. */
  emptyWorkspace?: true;
  repository?: {
    agentId: string;
    url: string;
    ref?: string;
    baseCommit?: string;
  };
  projectRepository?: RepositoryWorkerProjectSnapshot;
  runSetupScript?: boolean;
  signal?: AbortSignal;
  setupAuthorized?: boolean;
  beforeProvision?: () => void;
};
//#endregion
//#region src/gateway/worker-environments/environment-reconcile.types.d.ts
type WorkerEnvironmentReconcileCore = (signal?: AbortSignal, retainProviderSettlement?: (settled: Promise<void>) => void) => Promise<void>;
type WorkerEnvironmentReconcileGuard = (environmentId: string, reconcileCore: WorkerEnvironmentReconcileCore, signal: AbortSignal) => Promise<void>;
//#endregion
//#region src/gateway/node-plugin-tool-snapshot.d.ts
type RegisteredNodePluginToolCommand = {
  pluginId: string;
  command: {
    command?: string;
    agentTool?: {
      name?: string;
      description?: string;
      parameters?: unknown;
      mcp?: {
        server?: string;
        tool?: string;
      };
    };
  };
};
//#endregion
//#region src/gateway/node-registry.host-stats.d.ts
type PersistNodeHostStats = (params: {
  nodeId: string;
  hostStats: NodeHostStats;
  expectedPairingGeneration: {
    nodeId: string;
    key: string;
  };
}) => Promise<boolean>;
//#endregion
//#region src/gateway/node-registry.presence.d.ts
type NodePresenceActivityUpdate = {
  nodeId: string;
  connId?: string;
  idleSeconds: number;
  source?: "app" | "system";
  saturated?: boolean;
  observedAtMs?: number;
};
//#endregion
//#region src/gateway/node-registry.d.ts
type PairingBoundNodeSession = NodeSession & {
  pairingIdentity: string;
};
type NodeSessionRegistrationOptions = {
  remoteIp?: string | undefined;
  pairingIdentity: string;
  pairingGeneration?: string | undefined;
  approvedSurface?: NodeApprovalSurface;
};
type NodeRegistryOptions = {
  listRegisteredNodePluginToolCommands?: (() => readonly RegisteredNodePluginToolCommand[] | undefined) | undefined;
  getConfig?: () => OpenClawConfig;
  resolveCurrentPairingState?: (nodeId: string) => Promise<PairedDeviceNodeBinding | undefined>;
  isPairingStateCurrent?: (nodeId: string, expected: PairedDeviceNodeBinding) => boolean;
  onPairingGenerationChanged?: (params: {
    nodeId: string;
    previousPairingGeneration: string;
    nextPairingGeneration: string;
    preserveSessionState: boolean;
  }) => void;
  onPairingInvalidated?: (params: {
    nodeId: string;
    connId: string;
  }) => void;
  onDesktopAvailabilityChanged?: (nodeId: string) => void;
  persistHostStats?: PersistNodeHostStats;
};
declare class NodeRegistry {
  private readonly options;
  private nodesById;
  private nodesByConn;
  private eventTransportsByConn;
  private pendingInvokes;
  private invokeStreams;
  private systemRunEvents;
  private pairingGenerationEventChains;
  private committedConfig;
  private hostStatsCheckpoints;
  constructor(options?: NodeRegistryOptions);
  private listConnectedSessions;
  private capturePairingLease;
  private currentSessionForLease;
  private settlePairingLease;
  private resolvePairingLease;
  private refreshSessionPolicy;
  private isCommandAllowed;
  refreshRuntimePolicy(config?: OpenClawConfig | undefined): NodeSession[];
  /** Register a websocket client as the current connection for its node id. */
  register(client: GatewayWsClient, opts: NodeSessionRegistrationOptions): PairingBoundNodeSession;
  /** Register a node whose events are delivered by an HTTP polling transport. */
  registerTransport(client: GatewayWsClient, opts: NodeSessionRegistrationOptions, transport: NodeEventTransport): PairingBoundNodeSession;
  private registerSession;
  /** Unregister one connection and reject invokes tied to that connection. */
  unregister(connId: string): string | null;
  listConnected(): NodeSession[];
  /** Filter connected sessions against an already-loaded pairing-state snapshot. */
  listConnectedForPairingStates(currentPairingStates: ReadonlyMap<string, PairedDeviceNodeBinding>): NodeSession[];
  /** Reconcile connected sessions against the pairing owner's committed publication. */
  listCurrentConnectedSync(): NodeSession[];
  /** Resolve persistent pairing state before projecting connected sessions. */
  listCurrentConnected(): Promise<NodeSession[]>;
  getCurrentConnected(nodeId: string): Promise<NodeSession | undefined>;
  private resolveCurrentConnectedSessions;
  private projectNodePairingLeaseResolutions;
  private invalidateSessionForPairingChange;
  /** Immediately retires one exact transport after its persisted pairing authority changes. */
  invalidateConnectionForPairingChange(connId: string, reason?: string): boolean;
  get(nodeId: string): NodeSession | undefined;
  private getRegisteredSession;
  /** Return only the session authenticated for the requested persistent pairing generation. */
  getForPairingGeneration(nodeId: string, pairingGeneration: string): NodeSession | undefined;
  private getRegisteredSessionForPairingGeneration;
  /** Revalidates that one inbound node connection still owns its persisted pairing state. */
  isConnectionCurrentPairingState(connId: string): Promise<boolean>;
  private clearDesktopAvailability;
  /** Records operational state without publishing activity or retaining it across connections. */
  updateDesktopAvailability(params: {
    nodeId: string;
    connId?: string;
    availability: DesktopAvailability;
  }): boolean | null;
  /** Stores the latest resource snapshot for the exact authenticated node connection. */
  updateHostStats(params: {
    nodeId: string;
    connId?: string;
    stats: NodeHostStatsPayload;
    observedAtMs?: number;
  }): NodeHostStats | null;
  /** Updates recent input activity for the exact authenticated node connection. */
  updatePresenceActivity(params: NodePresenceActivityUpdate): NodeSession | null;
  /** Clears recent input activity for the exact authenticated node connection. */
  clearPresenceActivity(params: {
    nodeId: string;
    connId?: string;
  }): boolean | null;
  /** Returns the connected node with the freshest reported local input. */
  getActiveNode(connectedNodes?: readonly NodeSession[]): NodeSession | undefined;
  private publishActiveNodeContext;
  /** Probe websocket liveness with ping/pong when the socket supports it. */
  checkConnectivity(nodeId: string, timeoutMs?: number): Promise<NodeConnectivityResult>;
  updateNodePluginTools(nodeId: string, connId: string | undefined, tools: readonly NodePluginToolDescriptor[]): NodeSession | null;
  updateNodeSkills(nodeId: string, connId: string | undefined, skills: readonly NodeSkillDescriptor[]): NodeSession | null;
  updateSurface(nodeId: string, surface: {
    caps?: readonly string[];
    commands: readonly string[];
    permissions?: Record<string, boolean> | undefined;
  }, generationTransition?: {
    expectedConnId: string;
    expectedPairingIdentity: string;
    expectedPairingGeneration?: string;
    nextPairingGeneration: string;
  }): NodeSession | null;
  invoke(params: NodeInvokeParams): Promise<NodeInvokeResult>;
  /** Internal cleanup retains its owner through replies without admitting new root work. */
  invokeLifecycle(params: NodeInvokeParams & {
    isDispatchAuthorized: () => boolean;
  }): Promise<NodeInvokeResult>;
  /** Send one ordered input frame to a pending streaming invoke. */
  sendInvokeInput(invokeId: string, payload: unknown): void;
  /** Synchronous effect fence for callbacks retained across awaited host work. */
  isInvokeCurrent(invokeId: string, nodeId: string, connId: string): boolean;
  handleInvokeProgress(params: NodeInvokeProgressParams): boolean;
  /** Continues only the exact live owner of a pending node invocation. */
  runPendingInvokeContinuation<T>(params: {
    invokeId: string;
    nodeId: string;
    connId: string | undefined;
    run: () => Promise<T>;
  }): Promise<T> | null;
  /** Authorize an inbound system.run event against a recently issued node invoke. */
  authorizeSystemRunEvent(params: {
    nodeId: string;
    connId?: string;
    runId?: string;
    sessionKey: string;
    terminal: boolean;
  }): boolean;
  authorizeSystemRunEventWithState(params: Parameters<NodeSystemRunEvents["authorize"]>[0]): (Pick<PendingSystemRunEvent, "invocationDeliveryContext"> & {
    expectedTarget?: SessionEventTarget$1;
    release?: () => void;
    holdNotice?: (notify: () => void) => void;
  }) | null;
  private disconnectSessionInvokes;
  handleInvokeResult(params: NodeInvokeResultParams): boolean;
  sendEvent(nodeId: string, event: string, payload?: unknown): boolean;
  sendEventRaw(nodeId: string, event: string, payloadJSON?: SerializedEventPayload | null): boolean;
  /** Sends command-free events only to the exact authenticated pairing connection. */
  sendEventForPairingIdentity(params: {
    nodeId: string;
    connId: string;
    pairingIdentity: string;
    event: string;
    payload?: unknown;
  }): Promise<boolean>;
  /** Sends only to a session that still owns the requested persistent pairing generation. */
  sendEventRawForPairingGeneration(nodeId: string, pairingGeneration: string, event: string, payloadJSON?: SerializedEventPayload | null, preparePayload?: NodeEventPayloadPreparation): Promise<boolean>;
  private sendEventInternal;
  private sendEventRawInternal;
  private sendEventToSession;
  private observeEventSend;
}
//#endregion
//#region src/gateway/desktop/node-stream-broker.d.ts
type NodeDesktopStreamMetadata = {
  auth: "vnc-password" | "ard-account";
  /** Managed RFB password for VncAuth or ARD; never returned to a browser. */
  vncPassword?: string;
};
type AttachedNodeDesktopStream = NodeDesktopStreamMetadata & {
  stream: Duplex;
};
type AttachedNodePortalStream = {
  stream: Duplex;
};
type NodeDesktopStreamBinding = {
  nodeId: string;
  connId: string;
  pairingGeneration: string;
};
type TicketNodeRegistry = Pick<NodeRegistry, "getForPairingGeneration" | "isConnectionCurrentPairingState">;
/** Owns one-time node stream tickets and pairs authenticated desktop or portal duplexes. */
declare function createNodeDesktopStreamBroker(): {
  mint: (binding: NodeDesktopStreamBinding) => {
    ticket: string;
    attachPath: string;
    expiresAtMs: number;
    attached: Promise<AttachedNodeDesktopStream>;
    cancel(): void;
  };
  mintPortal: (binding: NodeDesktopStreamBinding) => {
    ticket: string;
    attachPath: string;
    expiresAtMs: number;
    attached: Promise<AttachedNodePortalStream>;
    cancel(): void;
  };
  handleUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer, registry: TicketNodeRegistry) => Promise<boolean>;
};
type NodeDesktopStreamBroker = ReturnType<typeof createNodeDesktopStreamBroker>;
//#endregion
//#region src/gateway/worker-environments/node-carrier-binding.d.ts
type WorkerNodeCarrierRuntime = {
  transport: NodeWorkerSupervisorTransport;
  streamBroker: NodeDesktopStreamBroker;
};
//#endregion
//#region src/gateway/worker-environments/portal-node-carrier.d.ts
/** Opens one ticketed node connection per request while its durable portal owner remains current. */
declare function createWorkerNodePortalCarrier(options: {
  store: Pick<WorkerEnvironmentStore, "get">;
}): {
  bindRuntime(next: WorkerNodeCarrierRuntime): void;
  supports(environmentId: string, ownerEpoch: number): Promise<boolean>;
  open(request: {
    environmentId: string;
    ownerEpoch: number;
    remotePort: number;
  }): Promise<{
    connect: (assertCurrent?: () => void, touch?: () => Promise<void>) => Promise<Duplex>;
    close: () => Promise<void>;
  }>;
  stop(environmentId: string, ownerEpoch?: number): Promise<void>;
  stopAll(): Promise<void>;
};
type WorkerNodePortalCarrier = ReturnType<typeof createWorkerNodePortalCarrier>;
//#endregion
//#region src/gateway/worker-environments/node-desktop-carrier.d.ts
type WorkerNodeDesktopCarrierOptions = {
  store: Pick<WorkerEnvironmentStore, "get">;
  desktopRegistry: DesktopSessionRegistry;
};
/** Carries one durable worker environment's desktop over its private node connection. */
declare function createWorkerNodeDesktopCarrier(options: WorkerNodeDesktopCarrierOptions): {
  bindRuntime(next: WorkerNodeCarrierRuntime): void;
  launchApp: (request: {
    record: WorkerEnvironmentRecord;
    app: WorkerDesktopApp;
  }) => Promise<void>;
  observe: (request: {
    record: WorkerEnvironmentRecord;
    control: boolean;
    requester?: DesktopObserveRequester;
  }) => Promise<WorkerDesktopObserveResult>;
  stop: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  stopAll: () => Promise<void>;
};
type WorkerNodeDesktopCarrier = ReturnType<typeof createWorkerNodeDesktopCarrier>;
//#endregion
//#region src/worker/node-supervisor-protocol.d.ts
declare const LaunchInput: z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  environmentSession: z.ZodLiteral<1>;
  sessionKey: z.ZodOptional<z.ZodCustom<string, string>>;
  idleRetention: z.ZodOptional<z.ZodLiteral<true>>;
  launchId: z.ZodCustom<string, string>;
  gatewayNamespace: z.ZodCustom<string, string>;
  expectedBundleHash: z.ZodCustom<string, string>;
  descriptor: z.ZodTransform<WorkerLaunchPlan, unknown>;
  placementGeneration: z.ZodCustom<number, number>;
}, z.core.$strip>>;
declare const Receipt: z.ZodUnion<readonly [z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  launchId: z.ZodCustom<string, string>;
  planHash: z.ZodCustom<string, string>;
  environmentId: z.ZodCustom<string, string>;
  sessionId: z.ZodCustom<string, string>;
  ownerEpoch: z.ZodCustom<number, number>;
  placementGeneration: z.ZodCustom<number, number>;
  runId: z.ZodCustom<string, string>;
  state: z.ZodEnum<{
    pending: "pending";
    running: "running";
  }>;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  launchId: z.ZodCustom<string, string>;
  planHash: z.ZodCustom<string, string>;
  environmentId: z.ZodCustom<string, string>;
  sessionId: z.ZodCustom<string, string>;
  ownerEpoch: z.ZodCustom<number, number>;
  placementGeneration: z.ZodCustom<number, number>;
  runId: z.ZodCustom<string, string>;
  state: z.ZodLiteral<"completed">;
  resultJson: z.ZodCustom<string, string>;
}, z.core.$strip>>, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
  launchId: z.ZodCustom<string, string>;
  planHash: z.ZodCustom<string, string>;
  environmentId: z.ZodCustom<string, string>;
  sessionId: z.ZodCustom<string, string>;
  ownerEpoch: z.ZodCustom<number, number>;
  placementGeneration: z.ZodCustom<number, number>;
  runId: z.ZodCustom<string, string>;
  state: z.ZodEnum<{
    cancelled: "cancelled";
    failed: "failed";
    interrupted: "interrupted";
  }>;
  errorText: z.ZodCustom<string, string>;
}, z.core.$strip>>]>;
type NodeWorkerLaunchInput = z.infer<typeof LaunchInput>;
type NodeWorkerSupervisorReceipt = z.infer<typeof Receipt>;
//#endregion
//#region src/gateway/worker-environments/node-launch-adapter.d.ts
type TerminalNodeWorkerSupervisorReceipt = Extract<NodeWorkerSupervisorReceipt, {
  state: "completed" | "failed" | "interrupted" | "cancelled";
}>;
type DeviceWorkerLaunchRequest = {
  deviceId: string;
  input: NodeWorkerLaunchInput;
  isDispatchAuthorized: () => boolean;
  isCancellationAuthorized: () => boolean;
  timeoutMs: number;
  credentialExpiresAtMs?: number;
  signal?: AbortSignal;
  /** Shutdown bounds receipt waits independently of the turn's cancellation. */
  cancellationSignal?: AbortSignal;
  onDispatchReady?: () => void;
};
type NodeWorkerLaunchAdapterOptions = {
  getTransport: () => NodeWorkerSupervisorTransport | undefined;
  now?: () => number;
  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
};
declare function createNodeWorkerLaunchAdapter(options: NodeWorkerLaunchAdapterOptions): {
  launch: (request: DeviceWorkerLaunchRequest) => Promise<TerminalNodeWorkerSupervisorReceipt>;
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-http-contract.d.ts
type NodeWorkspaceTransferHttpRoute = {
  kind: "manifest" | "pack";
  direction: "download";
  environmentId: string;
  manifestRef: string;
} | {
  kind: "blob";
  direction: "download";
  environmentId: string;
  sha256: string;
} | {
  kind: "reconcile";
  direction: "upload";
  environmentId: string;
  baseManifestRef: string;
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-owner.d.ts
type NodeWorkspaceTransferOwner = {
  credential: {
    ownerEpoch: number;
    sessionId: string | null;
  } | undefined;
  environment: {
    ownerEpoch: number;
    attachedSessionIds: string[];
    destroyRequestedAtMs: number | null;
    state: string;
  };
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-snapshot.d.ts
type NodeWorkspaceTransferSnapshot = Awaited<ReturnType<typeof captureWorkspaceSnapshot>> & {
  root: string;
  /** Sparse checkpoint payloads contain only these paths from the complete manifest. */
  blobPaths?: ReadonlySet<string>;
  /** Opaque checkpoint delta; upstream objects stay on the independently cloned worker. */
  gitPackPath?: string;
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-upload-reader.d.ts
type NodeWorkspaceTransferUpload = {
  base: WorkerWorkspaceManifest;
  baseManifestRef: string;
  baseRaw: string;
  current: WorkerWorkspaceManifest;
  currentManifestRef: string;
  currentRaw: string;
  stagingRoot: string;
  gitHistory?: WorkerWorkspaceGitHistory;
  gitPackPath?: string;
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-service.d.ts
type TransferBinding = {
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
};
type DownloadCapability = {
  direction: "download";
  token: string;
  manifestRef: string;
  expiresAtMs: number;
  isAuthorized: () => boolean;
  signal?: AbortSignal;
};
type UploadOperation = {
  direction: "upload";
  token: string;
  baseManifestRef: string;
  resultVersion?: 2;
  expiresAtMs: number;
  state: "ready" | "receiving" | "completed";
  isAuthorized: () => boolean;
  uploaded?: NodeWorkspaceTransferUpload;
  abortController: AbortController;
  receiving?: {
    result: Promise<{
      manifestRef: string;
    }>;
    signal: AbortSignal;
  };
  disposal?: Promise<void>;
};
type TransferContext = TransferBinding & {
  localPath?: string;
  temporaryRoot: string;
  currentManifestRef: string;
  snapshots: Map<string, NodeWorkspaceTransferSnapshot>;
  baseCommit: string | null;
  pack?: Promise<string>;
  downloads: Map<string, DownloadCapability>;
  upload?: UploadOperation;
  abortController: AbortController;
  signal: AbortSignal;
  isAuthorized: () => boolean;
};
type TransferAuthorization = {
  context: TransferContext;
  capability: DownloadCapability | UploadOperation;
  route: NodeWorkspaceTransferHttpRoute;
};
type TransferPreparation = Pick<TransferContext, "environmentId" | "ownerEpoch" | "sessionId" | "isAuthorized"> & {
  signal?: AbortSignal;
  authorize?: () => void;
};
type RepositoryPreparation = TransferPreparation & {
  baseCommit: string;
  baseManifestRef: string;
};
type SyncPreparation = TransferPreparation & {
  localPath: string;
};
declare function createNodeWorkspaceTransferService(options: {
  getOwner: (environmentId: string) => NodeWorkspaceTransferOwner | undefined;
  now?: () => number;
  temporaryRoot?: string;
}): {
  initialize: () => Promise<void>;
  prepareAttachments(params: {
    environmentId: string;
    localPath: string;
    isAuthorized: () => boolean;
    signal: AbortSignal;
  }): Promise<{
    snapshot: {
      manifest: WorkerWorkspaceManifest;
      manifestRef: string;
      rawManifest: string;
      root: string;
    };
    token: string;
  }>;
  prepareRepository: (params: RepositoryPreparation) => Promise<void>;
  prepareSync: (params: SyncPreparation) => Promise<{
    snapshot: NodeWorkspaceTransferSnapshot;
    token: string;
  }>;
  prepareUpload(environmentId: string, baseManifestRef: string, authorize?: () => void, resultVersion?: 2): string;
  takeUpload(environmentId: string, baseManifestRef: string): NodeWorkspaceTransferUpload;
  discardUpload(environmentId: string, token: string): Promise<void>;
  getSnapshot(environmentId: string, manifestRef: string): NodeWorkspaceTransferSnapshot | undefined;
  publishSnapshot(environmentId: string, snapshot: NodeWorkspaceTransferSnapshot, authorize?: () => void): string;
  revoke(environmentId: string, token: string): Promise<void>;
  authorize(params: {
    route: NodeWorkspaceTransferHttpRoute;
    token: string;
  }): TransferAuthorization | undefined;
  isAuthorizationCurrent: (authorization: TransferAuthorization) => boolean;
  authorizationSignal(authorization: TransferAuthorization): AbortSignal;
  snapshot(authorization: TransferAuthorization): NodeWorkspaceTransferSnapshot | undefined;
  pack(authorization: TransferAuthorization): Promise<string | undefined>;
  blob(authorization: TransferAuthorization): {
    path: string;
    size: number;
    sha256: string;
  } | undefined;
  receiveUpload(params: {
    authorization: TransferAuthorization;
    request: IncomingMessage;
    signal: AbortSignal;
  }): Promise<{
    manifestRef: string;
  }>;
  verifyBlob(params: {
    path: string;
    size: number;
    sha256: string;
  }): Promise<boolean>;
  fenceEnvironment(environmentId: string, reason?: Error): void;
  close: (environmentId: string) => Promise<void>;
  closeAll(): Promise<void>;
};
type NodeWorkspaceTransferService = ReturnType<typeof createNodeWorkspaceTransferService>;
//#endregion
//#region src/gateway/worker-environments/node-worker-tunnel.types.d.ts
type NodeWorkerTunnelManagerOptions = {
  gatewayDeviceId: string;
  getEnvironment: (environmentId: string) => WorkerEnvironmentRecord | undefined;
  listEnvironments: () => readonly WorkerEnvironmentRecord[];
  getTransport: () => NodeWorkerSupervisorTransport | undefined;
  launchNodeWorker: ReturnType<typeof createNodeWorkerLaunchAdapter>["launch"];
  validateWorkerTurn: (claim: WorkerSessionTurnClaim) => boolean;
  workspaceTransfer: NodeWorkspaceTransferService;
};
type NodeWorkerTunnelStartRequest = {
  executionMode: "worker-turn" | "remote-exec";
  environmentId: string;
  ownerEpoch: number;
  deviceId: string;
  sessionId: string;
  expectedBuild: WorkerAdmissionHandshake;
  authorize?: () => void;
};
type NodeWorkerWorkspaceBinding = {
  source: {
    kind: "local";
    path: string;
  } | {
    kind: "device-folder";
    deviceId: string;
    path: string;
  } | {
    kind: "repository";
    baseCommit: string;
    baseManifestRef: string;
  };
  manifestRef: string;
  remoteWorkspaceDir: string;
  sessionKey?: string;
};
//#endregion
//#region src/gateway/worker-environments/node-worker-workspace-drain.d.ts
type NodeWorkerWorkspaceBindingIdentity = {
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
};
type NodeWorkerWorkspaceBindingResolver = ((binding: NodeWorkerWorkspaceBindingIdentity) => Promise<NodeWorkerWorkspaceBinding | undefined>) & {
  /** Durable placement read for teardown; never resolves session or worktree state. */
  durableDeviceFolder?: (binding: NodeWorkerWorkspaceBindingIdentity) => Promise<string | undefined>;
};
//#endregion
//#region src/gateway/worker-environments/node-worker-tunnel.d.ts
/** Owns node-channel handles without treating the persistent machine as a disposable lease. */
declare function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOptions): {
  observeProcesses: (input: Omit<NodeWorkerProcessInput, "gatewayNamespace">, assertCurrent: () => void, signal?: AbortSignal) => Promise<{
    sessionId: string;
    processes: {
      processId: string;
      instanceId: string;
      name: string;
      status: "completed" | "failed" | "killed" | "running";
      startedAt: number;
      endedAt?: number | undefined;
      tail: string;
      truncated: boolean;
      canStop: boolean;
      exitCode?: number | null | undefined;
      exitSignal?: string | number | null | undefined;
      exitReason?: string | undefined;
    }[];
    truncated: boolean;
  } | {
    requested: boolean;
  }>;
  runSessionCommand(binding: {
    environmentId: string;
    ownerEpoch: number;
    sessionId: string;
    sessionKey: string;
  }, command: WorkerWorkspaceCommand): Promise<NodeWorkerWorkspaceExecResult>;
  bindWorkspaceBindingResolver(resolver: NodeWorkerWorkspaceBindingResolver): void;
  start(request: NodeWorkerTunnelStartRequest): Promise<WorkerTurnTunnelHandle>;
  beginClose: () => void;
  cleanupSignal: AbortSignal;
  stop: (environmentId: string, ownerEpoch?: number, reason?: WorkerTunnelStopReason) => Promise<void>;
  stopAll(): Promise<void>;
  status(environmentId: string): WorkerTunnelStatus;
};
type NodeWorkerTunnelManager = ReturnType<typeof createNodeWorkerTunnelManager>;
//#endregion
//#region src/gateway/worker-environments/environment-access.d.ts
type WorkerEnvironmentNodeTunnel = Pick<NodeWorkerTunnelManager, "status" | "start" | "stop" | "stopAll" | "beginClose" | "observeProcesses">;
//#endregion
//#region src/gateway/worker-environments/prepared-pool-presence.types.d.ts
type PreparedPoolPresenceDemand = {
  revision: number;
  profileId: string;
  requestedRef: string | null;
  preparationKey: string;
  project: RepositoryWorkerProjectSnapshot;
  lastPresentAtMs: number;
  retireAtMs: number | null;
};
//#endregion
//#region src/gateway/worker-environments/prepared-pool-presence.d.ts
type PreparedPoolPresenceOptions = {
  store: WorkerEnvironmentStore;
  getConfig: () => OpenClawConfig;
  prepareIntent: (profileId: string, options: {
    projectRepository?: RepositoryWorkerProjectSnapshot;
    repository?: {
      agentId: string;
      url: string;
      ref?: string;
    };
    executionMode?: "worker-turn" | "remote-exec";
    signal?: AbortSignal;
  }) => Promise<WorkerProviderPreparedIntent>;
  assertIntentCurrent: (profileId: string, intent: WorkerProviderPreparedIntent) => void;
  resolveHumanPresenceDemand?: () => {
    profileId: string;
    executionMode: "worker-turn" | "remote-exec";
    repository: {
      agentId: string;
      url: string;
      ref?: string;
    };
  } | undefined;
  presenceDemandStore?: {
    read: () => Promise<PreparedPoolPresenceDemand | undefined>;
    write: (value: PreparedPoolPresenceDemand | null, assertCurrent: () => void) => Promise<PreparedPoolPresenceDemand | undefined>;
  };
  now: () => number;
  signal: AbortSignal;
  schedule: () => Promise<void>;
};
//#endregion
//#region src/gateway/worker-environments/session-attachment-service.d.ts
type WorkerEnvironmentSessionAttachmentOptions = {
  prepareAttachedComputer?: (authority: WorkerEnvironmentComputerAuthority) => Promise<PreparedWorkerComputer | undefined>;
  closeEnvironmentComputers?: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  hasAttachedEnvironmentActivity?: (environmentId: string, ownerEpoch: number) => boolean;
  runSessionEnvironmentCommand?: NodeWorkerTunnelManager["runSessionCommand"];
};
//#endregion
//#region src/gateway/worker-environments/service.types.d.ts
type WorkerEnvironmentCreateRequest = {
  profileId: string;
  idempotencyKey: string;
  machineClass?: string;
  executionMode?: WorkerExecutionMode;
  projectPath?: string;
  signal?: AbortSignal;
  os?: string;
  runSetupScript?: boolean;
  inheritedProfile?: {
    providerId: string;
    profileSnapshot: WorkerProfile;
  };
  admittedIntent?: WorkerProviderPreparedIntent;
  /** Revalidate caller authority after preparation, immediately before provider effects. */
  beforeProvision?: () => void;
};
type WorkerEnvironmentServiceOptions = WorkerProviderLifecycleInputOptions & Pick<PreparedPoolPresenceOptions, "resolveHumanPresenceDemand" | "presenceDemandStore"> & WorkerEnvironmentSessionAttachmentOptions & {
  resolveGatewayContext?: GatewayContextResolver;
  prepareComputer?: (claim: WorkerSessionTurnClaim) => Promise<PreparedWorkerComputer | undefined>;
  executeComputer?: WorkerComputerExecutor;
  closeComputers?: () => Promise<void>;
  tunnelManager?: WorkerTunnelManager;
  nodeTunnelManager?: WorkerEnvironmentNodeTunnel;
  nodeDesktopCarrier?: WorkerNodeDesktopCarrier;
  nodePortalCarrier?: WorkerNodePortalCarrier;
  closeWorkerPortals?: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  stopNodeEnrollmentWaits?: () => void;
  admitsNodeSetupCompletion?: (setup: CloudWorkerSetupMutationAdmission) => boolean;
  closeNodeBootstrapArtifacts?: () => Promise<void>;
  stopNodeWorkerBundleTransfers?: () => void | Promise<void>;
  maintainProviders?: (signal: AbortSignal) => Promise<void>;
  scheduler: GatewayScheduler;
  reconcileIntervalMs?: number;
  bootstrapCallTimeoutMs?: number;
  workerCredentialTtlMs?: number;
  generateWorkerCredential?: (bytes: number) => string;
  logger?: {
    warn: (message: string) => void;
  };
  applyTranscriptCommit?: WorkerTranscriptCommitApplication;
  liveEvents?: Pick<WorkerLiveEventReceiver, "apply" | "clear" | "clearEnvironment" | "rotateCredential">;
  inferenceStore?: WorkerInferenceStore;
  createGatewayTools?: (params: {
    identity: WorkerConnectionIdentity;
    inheritedToolPolicySource?: "sender";
    inheritedToolDenylist?: string[];
    delegatedToolPolicyActive?: boolean;
    skillWorkshop?: AnyAgentTool;
    portalAvailable?: boolean;
    prepareTools?: (adapters: AnyAgentTool[]) => AnyAgentTool[] | Promise<AnyAgentTool[]>;
  }) => Promise<AnyAgentTool[]>;
};
//#endregion
//#region src/gateway/worker-environments/service.d.ts
declare function createWorkerEnvironmentService(options: WorkerEnvironmentServiceOptions): {
  getCleanupError: (record: WorkerEnvironmentRecord) => string | undefined;
  captureSessionAttachment(identity: WorkerEnvironmentSessionIdentity): {
    binding: WorkerEnvironmentAttachment;
    assertCurrent: () => void;
    touch: () => Promise<void>;
  };
  cancelSessionAttachmentCreations(): void;
  getSessionAttachment: (sessionId: string) => WorkerEnvironmentAttachment | undefined;
  findSessionAttachment: (identity: Pick<WorkerEnvironmentSessionIdentity, "agentId" | "sessionKey">) => WorkerEnvironmentAttachment | undefined;
  getSessionAttachmentStatus(sessionId: string): {
    attachment: {
      sessionId: string;
      sessionKey: string;
      agentId: string;
      sessionLifecycleRevision?: string;
      environmentId: string;
      generation: number;
      createdAtMs: number;
      lastUsedAtMs: number;
      closedAtMs: number | null;
      ownerEpoch: number;
    };
    environment: {
      environmentId: string;
      providerId: string;
      profileId: string;
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | {
        purpose: "reserve" | "build";
        key: string;
        demandAtMs: number;
        expiresAtMs: number;
        consumedAtMs: number | null;
        project: {
          label?: string | undefined;
          baseCommit: string;
        };
      } | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
      state: WorkerEnvironmentLeasedState;
      leaseId: string;
      sshEndpoint: WorkerSshEndpoint | null;
      inference?: "worker";
      startStatus?: {
        mode: "snapshot";
        phase?: "saving" | undefined;
      } | {
        mode: "cold";
        reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
        phase: "preparing" | "provisioning" | "saving";
      } | undefined;
      error?: string | undefined;
      desktopAvailable: boolean;
      desktopApps: ("browser" | "terminal")[];
      tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
    } | {
      environmentId: string;
      providerId: string;
      profileId: string;
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | {
        purpose: "reserve" | "build";
        key: string;
        demandAtMs: number;
        expiresAtMs: number;
        consumedAtMs: number | null;
        project: {
          label?: string | undefined;
          baseCommit: string;
        };
      } | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
      state: WorkerEnvironmentUnleasedState;
      leaseId: null;
      sshEndpoint: null;
      inference?: "worker";
      startStatus?: {
        mode: "snapshot";
        phase?: "saving" | undefined;
      } | {
        mode: "cold";
        reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
        phase: "preparing" | "provisioning" | "saving";
      } | undefined;
      error?: string | undefined;
      desktopAvailable: boolean;
      desktopApps: ("browser" | "terminal")[];
      tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
    };
  } | undefined;
  assertSessionAttachment: (binding: WorkerEnvironmentAttachment, prepared?: WorkerEnvironmentSessionIdentity) => void;
  touchSessionAttachment: (binding: WorkerEnvironmentAttachment) => Promise<void>;
  destroySessionAttachment(request: {
    sessionId: string;
    environmentId?: string;
  }, authorize: () => void): Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | undefined>;
  reconcileSessionAttachments(): Promise<void>;
  retireSessionIdentityMutation(mutation: SessionIdentityMutation): void;
  createSessionAttachment: (...args: Parameters<(input: WorkerEnvironmentSessionCreateRequest, authorize: () => void, callerSignal?: AbortSignal, onReserved?: WorkerEnvironmentSessionReservationHandler) => Promise<{
    attachment: {
      sessionId: string;
      sessionKey: string;
      agentId: string;
      sessionLifecycleRevision?: string;
      environmentId: string;
      generation: number;
      createdAtMs: number;
      lastUsedAtMs: number;
      closedAtMs: number | null;
      ownerEpoch: number;
    };
    environment: {
      environmentId: string;
      providerId: string;
      profileId: string;
    } & {
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
    } & {
      state: WorkerEnvironmentLeasedState;
      leaseId: string;
      sshEndpoint: WorkerSshEndpoint | null;
    };
    reused: boolean;
  }>>) => Promise<{
    attachment: {
      sessionId: string;
      sessionKey: string;
      agentId: string;
      sessionLifecycleRevision?: string;
      environmentId: string;
      generation: number;
      createdAtMs: number;
      lastUsedAtMs: number;
      closedAtMs: number | null;
      ownerEpoch: number;
    };
    reused: boolean;
    environment: {
      environmentId: string;
      providerId: string;
      profileId: string;
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | {
        purpose: "reserve" | "build";
        key: string;
        demandAtMs: number;
        expiresAtMs: number;
        consumedAtMs: number | null;
        project: {
          label?: string | undefined;
          baseCommit: string;
        };
      } | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
      state: WorkerEnvironmentLeasedState;
      leaseId: string;
      sshEndpoint: WorkerSshEndpoint | null;
      inference?: "worker";
      startStatus?: {
        mode: "snapshot";
        phase?: "saving" | undefined;
      } | {
        mode: "cold";
        reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
        phase: "preparing" | "provisioning" | "saving";
      } | undefined;
      error?: string | undefined;
      desktopAvailable: boolean;
      desktopApps: ("browser" | "terminal")[];
      tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
    } | {
      environmentId: string;
      providerId: string;
      profileId: string;
      profileSnapshot: WorkerProfile;
      preparation: WorkerEnvironmentPreparation | {
        purpose: "reserve" | "build";
        key: string;
        demandAtMs: number;
        expiresAtMs: number;
        consumedAtMs: number | null;
        project: {
          label?: string | undefined;
          baseCommit: string;
        };
      } | null;
      provisionOperationId: string;
      nodeSetupId: string | null;
      nodeDeviceId: string | null;
      sharedHost: boolean | null;
      desktop: WorkerDesktopEndpoint | null;
      bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
      ownerEpoch: number;
      teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
      attachedSessionIds: string[];
      lastError: string | null;
      createdAtMs: number;
      updatedAtMs: number;
      stateChangedAtMs: number;
      lastActivatedAtMs: number | null;
      idleSinceAtMs: number | null;
      destroyRequestedAtMs: number | null;
      state: WorkerEnvironmentUnleasedState;
      leaseId: null;
      sshEndpoint: null;
      inference?: "worker";
      startStatus?: {
        mode: "snapshot";
        phase?: "saving" | undefined;
      } | {
        mode: "cold";
        reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
        phase: "preparing" | "provisioning" | "saving";
      } | undefined;
      error?: string | undefined;
      desktopAvailable: boolean;
      desktopApps: ("browser" | "terminal")[];
      tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
    };
  }>;
  prepareAttachedComputer: ((authority: WorkerEnvironmentComputerAuthority) => Promise<PreparedWorkerComputer | undefined>) | undefined;
  execSessionAttachment: (binding: WorkerEnvironmentAttachment, command: WorkerWorkspaceCommand) => Promise<NodeWorkerWorkspaceExecResult>;
  openNodePortal: (request: {
    environmentId: string;
    ownerEpoch: number;
    remotePort: number;
  }) => Promise<{
    connect: (assertCurrent?: () => void, touch?: () => Promise<void>) => Promise<import("node:stream").Duplex>;
    close: () => Promise<void>;
  }>;
  admitWorker: (admission: WorkerConnectParams["admission"]) => Promise<{
    ok: true;
    identity: WorkerConnectionIdentity;
  } | {
    ok: false;
    reason: WorkerAdmissionFailureReason;
  } | {
    readonly ok: false;
    readonly reason: "environment-unavailable";
  } | {
    readonly ok: false;
    readonly reason: "credential-expired" | "placement-mismatch";
  }>;
  validateWorkerConnection: (identity: WorkerConnectionIdentity, request?: {
    toolSurface: true;
  }) => "admission-rejected" | "bundle-mismatch" | "credential-expired" | "credential-replaced" | "environment-mismatch" | "environment-unavailable" | "gateway-shutdown" | "gateway-unavailable" | "invalid-credential" | "invalid-frame" | "invalid-handshake" | "invalid-heartbeat" | "method-not-allowed" | "owner-epoch-mismatch" | "placement-mismatch" | "protocol-features-mismatch" | "protocol-mismatch" | "rpc-set-mismatch" | "session-mismatch" | "slow-consumer" | "version-mismatch" | null;
  commitTranscript: (identity: WorkerConnectionIdentity, request: WorkerTranscriptCommitParams) => Promise<WorkerTranscriptCommitServiceResult>;
  pushLiveEvent: (identity: WorkerConnectionIdentity, input: WorkerLiveEventParams) => Promise<WorkerLiveEventServiceResult>;
  getToolSurface: (identity: WorkerConnectionIdentity) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: true;
    result: {
      generation: string;
      presentation: {
        codeMode: {
          enabled: boolean;
          executor: "node" | "quickjs";
          mode: "only";
          timeoutMs: number;
          memoryLimitBytes: number;
          maxOutputBytes: number;
          maxSnapshotBytes: number;
          maxPendingToolCalls: number;
          snapshotTtlSeconds: number;
          searchDefaultLimit: number;
          maxSearchLimit: number;
        };
        toolSearch: {
          enabled: boolean;
          mode: "directory" | "tools";
          include?: {
            source?: "client" | "mcp" | "openclaw" | undefined;
            name?: string | undefined;
          }[] | undefined;
          exclude?: {
            source?: "client" | "mcp" | "openclaw" | undefined;
            name?: string | undefined;
          }[] | undefined;
          searchDefaultLimit: number;
          maxSearchLimit: number;
        };
        toolSearchDirectoryLean?: boolean | undefined;
        forceDirectMessageTool: boolean;
        skills?: {
          name: string;
          description: string;
          location: string;
        }[] | undefined;
      };
      tools: {
        id: string;
        execution: "gateway" | "placement";
        replay?: true | undefined;
        plugin?: {
          pluginId: string;
          optional: boolean;
          replaySafe?: boolean | undefined;
          sideEffecting?: boolean | undefined;
          mcp?: {
            serverName: string;
            safeServerName: string;
            toolName: string;
            operation: "prompts_get" | "prompts_list" | "resources_list" | "resources_read" | "tool";
            node?: {
              id: string;
              displayName?: string | undefined;
            } | undefined;
          } | undefined;
        } | undefined;
        timeout?: {
          minimumMs?: number | undefined;
          argument?: string | undefined;
          defaultSeconds?: number | undefined;
          paddingMs?: number | undefined;
        } | undefined;
        definition: {
          name: string;
          label: string;
          description: string;
          parameters: Record<string, unknown>;
          outputSchema?: Record<string, unknown> | undefined;
          hideFromChannelProgress?: true | undefined;
          resultContentSource?: "network" | undefined;
          executionMode?: "parallel" | "sequential" | undefined;
          catalogMode?: "direct-only" | undefined;
          async?: false | undefined;
        };
      }[];
      policy: {
        workspaceOnly: boolean;
        readOnly: boolean;
        applyPatchEnabled: boolean;
        applyPatchWorkspaceOnly: boolean;
        applyPatchContainmentSource?: "config" | "required-root" | "session" | undefined;
        modelContextWindowTokens?: number | undefined;
        modelHasVision?: boolean | undefined;
        memoryFlushWritePath?: string | undefined;
        imageSanitization: {
          maxBytes?: number | undefined;
          maxDimensionPx?: number | undefined;
        };
      };
    };
  }>;
  execApproval: (identity: WorkerConnectionIdentity, request: WorkerExecApprovalParams, signal?: AbortSignal) => Promise<{
    ok: true;
    result: {
      operation: "review";
      binding: string;
      decision: {
        decision: "allow-once";
        risk: "low" | "medium";
        rationale: string;
        userAuthorization?: "high" | "low" | "medium" | "unknown" | undefined;
      } | {
        decision: "ask" | "deny";
        risk: "high" | "low" | "medium" | "unknown";
        rationale: string;
        userAuthorization?: "high" | "low" | "medium" | "unknown" | undefined;
      };
    } | {
      operation: "request";
      binding: string;
      id: string;
      expiresAtMs: number;
      decision?: "allow-once" | "deny" | null | undefined;
    } | {
      operation: "wait";
      binding: string;
      decision: "allow-once" | "deny" | null;
      terminalReason?: string | undefined;
    };
  }>;
  refreshGitHubBinding: (identity: WorkerConnectionIdentity, generation?: number) => Promise<{
    ok: false;
    closeReason: "placement-mismatch";
  } | {
    ok: true;
    readonly result: WorkerGitHubBindingRefresh | undefined;
    assertCurrent: () => void;
  }>;
  invokeGatewayTool: (identity: WorkerConnectionIdentity, request: WorkerGatewayToolInvokeParams, sink: WorkerGatewayToolSink, signal?: AbortSignal) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: true;
    result: {
      content: ({
        type: "text";
        text: string;
        textSignature?: string | undefined;
      } | {
        type: "image";
        data: string;
        mimeType: string;
      })[];
      details?: unknown;
      isError?: boolean | undefined;
      terminate?: boolean | undefined;
      progress?: {
        text: string;
        visibility: "channel";
        privacy: "public";
        id?: string | undefined;
      } | undefined;
      mcpGuestResult?: unknown;
      mcpBlockedReason?: string | undefined;
    } | {
      content: (TextContent | ImageContent$1)[];
      details: {
        status: string;
        error: string;
      };
      progress?: AgentToolProgress;
      terminate?: boolean;
      isError: boolean;
    };
  }>;
  cancelGatewayTool: (identity: WorkerConnectionIdentity, request: WorkerGatewayToolCancelParams) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: true;
    result: {
      cancelled: boolean;
    };
  }>;
  executeComputer: (identity: WorkerConnectionIdentity, request: WorkerComputerParams, signal?: AbortSignal) => Promise<{
    ok: true;
    result: WorkerComputerResult;
  } | {
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: false;
    reason: WorkerProtocolCloseReason;
    message?: string;
  }>;
  startInference: (identity: WorkerConnectionIdentity, request: WorkerInferenceStartParams, sink: WorkerInferenceSink) => Promise<WorkerInferenceServiceResult<"start">>;
  admitTurn: (identity: WorkerConnectionIdentity, request: WorkerTurnAdmissionParams) => Promise<{
    ok: false;
    closeReason: "placement-mismatch";
    result?: undefined;
  } | {
    closeReason?: undefined;
    ok: true;
    result: {
      outcome: "allow";
      baseLeafId: string | null;
    } | {
      outcome: "block";
    };
  }>;
  cancelInference: (identity: WorkerConnectionIdentity, request: WorkerInferenceCancelParams) => Promise<WorkerInferenceServiceResult<"cancel">>;
  prepare: (request: {
    profileId: string;
    projectPath: string;
  }, authorize?: () => void) => Promise<{
    environmentId: string;
    preparationKey: string;
    reused: boolean;
  }>;
  isStopping: () => boolean;
  recordError: (record: WorkerEnvironmentRecord, error: unknown, assertCurrent?: () => void) => Promise<WorkerEnvironmentRecord>;
  list: () => ({
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  })[];
  readPreparedPoolSummary: () => {
    maxTotal: number;
    reservedEnvironmentIds: string[];
  };
  readReadyWorkerTarget: (profileId: string) => number;
  readRuntimeRefresh: (environmentId: string) => WorkerRuntimeRefreshInFlight | undefined;
  supportsProviderExecutionMode: (providerId: string, mode: WorkerExecutionMode) => boolean;
  supportsExecutionMode: (profileId: string, mode: WorkerExecutionMode) => boolean;
  requiresNodeEnrollment: (profileId: string, providerId?: string) => boolean;
  get: (environmentId: string) => {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | undefined;
  getDedicatedNodeLeaseSignal: (environmentId: string) => AbortSignal | undefined;
  prepareProjectIntent: (...args: Parameters<(profileId: string, createOptions?: WorkerProviderIntentPreparationOptions) => Promise<WorkerProviderPreparedIntent>>) => Promise<WorkerProviderPreparedIntent>;
  assertPreparedIntentCurrent: (profileId: string, intent: WorkerProviderPreparedIntent) => void;
  getPreparedCandidates: (intent: WorkerProviderPreparedIntent) => ({
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  })[];
  schedulePreparedRefill: (environmentId?: string) => undefined;
  setHumanPresence: (present: boolean) => Promise<void>;
  inventoryVersion: () => number;
  machineShapeVersion: () => number;
  machineShapeNotifications: {
    onChanged: (_profileId: string) => void;
  };
  readMachineShape: (environmentId: string, prepared?: WorkerEnvironmentPlacementFacts) => {
    class?: string | undefined;
    os?: string | undefined;
    osLabel?: string | undefined;
    cpu?: number | undefined;
    memoryGb?: number | undefined;
  } | undefined;
  supportsNodePortal: (environmentId: string, ownerEpoch: number) => Promise<boolean>;
  hasPendingNodeEnrollmentSetup: (setup: string, device: string) => boolean;
  admitsNodeSetupCompletion: ((setup: CloudWorkerSetupMutationAdmission) => boolean) | undefined;
  readProviderDisplayId: (profileId: string) => string | undefined;
  listMachineOptions: (profileId: string) => Promise<readonly Readonly<{
    id: string;
    label: string;
    cpu?: number | undefined;
    memoryGb?: number | undefined;
    default?: boolean | undefined;
    os?: string | undefined;
  }>[] | undefined>;
  listOperatingSystems: (profileId: string) => Promise<readonly Readonly<{
    id: string;
    label: string;
    default?: boolean | undefined;
    disabledReason?: string | undefined;
  }>[] | undefined>;
  bindPreparedWorkspace: (request: Parameters<NonNullable<((params: {
    environmentId: string;
    ownerEpoch: number;
    sessionId: string;
    sessionKey: string;
    preparationKey: string;
    cacheKey: string;
    signal?: AbortSignal;
    assertCurrent: () => void;
  }) => Promise<NodeWorkerPreparedWorkspaceResult>) | undefined>>[0]) => Promise<{
    gatewayNamespace: string;
    environmentId: string;
    preparationKey: string;
    cacheKey: string;
    workspaceDir: string;
    homeDir: string;
    sourceManifestRef: string;
    preparedManifestRef: string;
    assertCurrent: () => void;
  }>;
  runProjectLifecycleCommand: (environmentId: string, ownerEpoch: number, command: Parameters<NonNullable<WorkerProvider["runSetupCommand"]>>[1]) => Promise<SpawnResult | undefined>;
  createWithRequest: ({ profileId, idempotencyKey, inheritedProfile, admittedIntent, ...selection }: WorkerEnvironmentCreateRequest) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  create: (...args: Parameters<WorkerEnvironmentServiceContract["create"]>) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  destroy: (environmentId: string, abandonment?: WorkerEnvironmentAbandonment, forceAbandon?: () => Promise<void>, authorize?: () => void) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  reclaim: (environmentId: string) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  requestDestroy: (environmentId: string) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  destroyUnattached: (environmentId: string, authorize?: () => void) => Promise<{
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentLeasedState;
    leaseId: string;
    sshEndpoint: WorkerSshEndpoint | null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  } | {
    environmentId: string;
    providerId: string;
    profileId: string;
    profileSnapshot: WorkerProfile;
    preparation: WorkerEnvironmentPreparation | {
      purpose: "reserve" | "build";
      key: string;
      demandAtMs: number;
      expiresAtMs: number;
      consumedAtMs: number | null;
      project: {
        label?: string | undefined;
        baseCommit: string;
      };
    } | null;
    provisionOperationId: string;
    nodeSetupId: string | null;
    nodeDeviceId: string | null;
    sharedHost: boolean | null;
    desktop: WorkerDesktopEndpoint | null;
    bootstrapReceipt: WorkerEnvironmentBootstrapReceipt | null;
    ownerEpoch: number;
    teardownTerminalState: WorkerEnvironmentTeardownTerminalState | null;
    attachedSessionIds: string[];
    lastError: string | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    lastActivatedAtMs: number | null;
    idleSinceAtMs: number | null;
    destroyRequestedAtMs: number | null;
    state: WorkerEnvironmentUnleasedState;
    leaseId: null;
    sshEndpoint: null;
    inference?: "worker";
    startStatus?: {
      mode: "snapshot";
      phase?: "saving" | undefined;
    } | {
      mode: "cold";
      reason: "backend-cannot-snapshot" | "capture-paused" | "class-unknown" | "no-snapshot-yet" | "os-unsupported" | "setup-changed" | "snapshot-retiring" | "snapshot-unavailable" | "warm-images-off";
      phase: "preparing" | "provisioning" | "saving";
    } | undefined;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  observeDesktop: (request: {
    environmentId: string;
    control: boolean;
    requester?: DesktopObserveRequester;
  }) => Promise<WorkerDesktopObserveResult>;
  launchDesktopApp: (request: {
    environmentId: string;
    app: "browser" | "terminal";
  }, authorize?: () => void) => Promise<WorkerDesktopLaunchResult>;
  reconcileDesktopPolicy: () => Promise<void>;
  fenceWorkerTurnForRecovery: (claim: WorkerSessionTurnClaim) => void;
  createGatewayTools: ((params: {
    identity: WorkerConnectionIdentity;
    inheritedToolPolicySource?: "sender";
    inheritedToolDenylist?: string[];
    delegatedToolPolicyActive?: boolean;
    skillWorkshop?: AnyAgentTool;
    portalAvailable?: boolean;
    prepareTools?: (adapters: AnyAgentTool[]) => AnyAgentTool[] | Promise<AnyAgentTool[]>;
  }) => Promise<AnyAgentTool[]>) | undefined;
  prepareComputer: ((claim: WorkerSessionTurnClaim) => Promise<PreparedWorkerComputer | undefined>) | undefined;
  resolveSshIdentity: (environmentId: string) => Promise<WorkerSshIdentity>;
  attachSession: (request: WorkerCredentialBinding & {
    sessionId: string;
    assertCurrent?: () => void;
    placementBinding?: PreparedEnvironmentPlacementBinding;
  }) => Promise<MintedWorkerCredential>;
  takeMintedCredential: (binding: WorkerCredentialBinding) => MintedWorkerCredential | undefined;
  acquireTurnCredential: (claim: WorkerSessionTurnClaim) => Promise<MintedWorkerCredential>;
  acknowledgeCredentialDelivery: (grant: MintedWorkerCredential) => Promise<boolean>;
  observeProcesses: (input: Omit<NodeWorkerProcessInput, "gatewayNamespace" | "expectedBundleHash">, assertCurrent: () => void, signal?: AbortSignal) => Promise<{
    sessionId: string;
    processes: {
      processId: string;
      instanceId: string;
      name: string;
      status: "completed" | "failed" | "killed" | "running";
      startedAt: number;
      endedAt?: number | undefined;
      tail: string;
      truncated: boolean;
      canStop: boolean;
      exitCode?: number | null | undefined;
      exitSignal?: string | number | null | undefined;
      exitReason?: string | undefined;
    }[];
    truncated: boolean;
  } | {
    requested: boolean;
  }>;
  startTunnel: (request: WorkerTunnelRequest) => Promise<WorkerTunnelHandle>;
  stopTunnel: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  beginClose: () => void;
  installReconcileEnvironmentGuard: (guard: WorkerEnvironmentReconcileGuard) => () => Promise<void>;
  reconcileEnvironment: (environmentId: string) => Promise<void>;
  reconcileOnce: (environmentId?: string) => Promise<void>;
  ready: () => Promise<void>;
  start: () => void;
  stop: () => Promise<void>;
};
type WorkerEnvironmentService = ReturnType<typeof createWorkerEnvironmentService>;
//#endregion
//#region src/gateway/worker-environments/session-workspace.d.ts
/** Durable session workspace ownership is independent of its current worker placement. */
type WorkerSessionWorkspace = {
  kind: "local";
  path: string;
} | {
  kind: "device-folder";
  deviceId: string;
  path: string;
} | {
  kind: "repository";
  repository: SessionRepositoryWorkspaceRecord;
};
//#endregion
//#region src/gateway/worker-environments/workspace-operation-coordinator.d.ts
type WorkerWorkspaceOperationCoordinator = {
  run<T>(environmentId: string, operation: () => Promise<T>, signal?: AbortSignal): Promise<T>;
};
//#endregion
//#region src/gateway/worker-environments/repository-workspace-mutation.d.ts
declare function createRepositoryWorkspaceMutationService(options: {
  placements: WorkerSessionPlacementStore;
  environments: Pick<WorkerEnvironmentService, "get" | "startTunnel">;
  workspaceOperations: WorkerWorkspaceOperationCoordinator;
  resolveWorkspace: (identity: WorkerSessionPlacementIdentity) => Promise<WorkerSessionWorkspace>;
}): {
  mutate<T>(params: WorkerSessionPlacementIdentity & {
    assertCurrent: () => void;
    assertEntryCurrent?: (entry: SessionEntryCurrentFacts | undefined) => void;
    mutate: (assertCurrent: () => void) => Promise<{
      changed: boolean;
      value: T;
    }>;
  }): Promise<T>;
};
//#endregion
//#region src/gateway/session-utils-store-worker.d.ts
/** Acquire the ordered lookup's data while its discovery and physical readers remain current. */
declare function resolveGatewaySessionStoreTargetInWorker(params: GatewaySessionStoreLookupParams & {
  assertActive?: () => void;
  signal?: AbortSignal;
  onSelected?: (target: GatewaySessionStoreTargetWithStore) => void;
}): Promise<GatewaySessionStoreTargetWithStore>;
/** Entry preparation shares the Gateway's alias, discovery, and reader owners. */
declare function loadGatewaySessionEntryReadOnlyInWorker(params: Parameters<typeof resolveGatewaySessionStoreTargetInWorker>[0] & {
  excludeInternalEffects?: boolean;
  includeStoreChildEntries?: boolean;
}): Promise<{
  agentId: string;
  storePath: string;
  canonicalKey: string;
  storeKeys: string[];
  canonicalValidationError?: Error;
  store: Record<string, InternalSessionEntry>;
  readSource?: SessionEntryReadSource;
  capturedReadSource?: CapturedSessionEntryReadSource;
  capturedReadSources?: CapturedSessionEntryReadSource[];
  lifecycleTimestamps?: SessionLifecycleTimestamps;
  transcript?: SessionTranscriptAnchorFacts;
  cfg: OpenClawConfig;
  entry: InternalSessionEntry | undefined;
  legacyKey: string | undefined;
}>;
//#endregion
//#region src/gateway/github-publication-session.types.d.ts
type PublicationSessionIdentity = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  lifecycleRevision?: string | null;
};
type PublicationSessionRead = Pick<Awaited<ReturnType<typeof loadGatewaySessionEntryReadOnlyInWorker>>, "agentId" | "canonicalKey" | "storePath" | "entry">;
//#endregion
//#region src/state/github-publication-read.types.d.ts
type GitHubPublicationRow = DB$1["github_publication_requests"];
type SharedGitHubPublicationReadInput = {
  session: {
    agentId: string;
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string | null;
  };
  selector: {
    requestId: string;
  } | {
    idempotencyKey?: string;
    status?: "published";
  };
  entry: {
    archivedAt?: number;
    repositoryWorkspaceId?: string;
    lifecycleRevision?: string;
    worktree?: {
      id: string;
      branch: string;
      repoRoot: string;
      githubPullRequest?: SessionGitHubPullRequestBinding;
    };
  };
};
//#endregion
//#region src/agents/github-oauth-records.d.ts
declare const scope: z.ZodEnum<{
  agent: "agent";
  system: "system";
}>;
type GitHubIdentityScope = z.infer<typeof scope>;
//#endregion
//#region src/gateway/github-publication-availability.d.ts
/** The selected publication metadata is invalidated by the session writer's receipts. */
declare function prepareGitHubPublicationSession(sessionKey: string, options?: {
  agentId?: string;
  cfg?: OpenClawConfig;
  assertCurrent?: () => void;
  target?: AgentRunSessionTarget;
  fields?: readonly (keyof NonNullable<PublicationSessionRead["entry"]>)[];
  /** Saved snapshots a consumer compares; stored reads omit them by default. */
  projection?: readonly SessionEntrySnapshotField[];
}): Promise<{
  loaded: PublicationSessionRead;
  readCurrent: () => PublicationSessionRead;
  release: () => void;
  [Symbol.dispose]: () => void;
}>;
//#endregion
//#region src/gateway/github-publication-shared-read.d.ts
type SharedGitHubPublicationSelector = SharedGitHubPublicationReadInput["selector"];
/** Observation retains the selected session while the existing-only shared reader runs. */
declare function readSharedGitHubPublication(session: PublicationSessionIdentity, selector: SharedGitHubPublicationSelector, preparedRead?: Awaited<ReturnType<typeof prepareGitHubPublicationSession>>["readCurrent"]): Promise<GithubPublicationRequests | GithubRepositoryPublicationRequests | undefined>;
//#endregion
//#region src/gateway/github-publication-recovery.d.ts
type GitHubPublicationRecoveryBackoff = ReturnType<typeof createGitHubPublicationRecoveryBackoff>;
/** Backoff is process-local; the receipt age also bounds recovery across restarts. */
declare function createGitHubPublicationRecoveryBackoff(): {
  clear: () => void;
  retain(requestIds: string[]): void;
  run(row: {
    request_id: string;
    created_at_ms: number;
  }, operation: () => Promise<SessionGitHubPublicationResult | void>, settle: (result: SessionGitHubPublicationResult) => Promise<SessionGitHubPublicationResult>): Promise<void | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>;
  describe(result: SessionGitHubPublicationResult): SessionGitHubPublicationResult;
};
//#endregion
//#region src/state/github-publication-requester.d.ts
declare const requesterSchema: z.ZodObject<{
  version: z.ZodLiteral<1>;
  actor: z.ZodDiscriminatedUnion<[z.ZodObject<{
    kind: z.ZodLiteral<"operator">;
    profileId: z.ZodString;
  }, z.core.$strict>, z.ZodObject<{
    kind: z.ZodLiteral<"system">;
  }, z.core.$strict>], "kind">;
  scopes: z.ZodArray<z.ZodString>;
  grant: z.ZodNullable<z.ZodObject<{
    pluginId: z.ZodString;
    grantId: z.ZodUUID;
    aliasBindingIds: z.ZodArray<z.ZodUUID>;
  }, z.core.$strict>>;
}, z.core.$strict>;
type RequesterData = z.infer<typeof requesterSchema>;
type GitHubPublicationRequesterSnapshot = Readonly<Omit<RequesterData, "actor" | "scopes" | "grant"> & {
  actor: Readonly<RequesterData["actor"]>;
  scopes: readonly string[];
  grant: Readonly<Omit<NonNullable<RequesterData["grant"]>, "aliasBindingIds"> & {
    aliasBindingIds: readonly string[];
  }> | null;
}>;
//#endregion
//#region src/gateway/github-publication-source.d.ts
/** A host-minted capability; serialized predicates alone never authorize publication. */
type GitHubPublicationSourceCapability = Readonly<{
  version: 1;
  release(): Promise<void>;
}>;
//#endregion
//#region src/agents/operator-model-policy.types.d.ts
type PreparedOperatorModelPolicy = Readonly<{
  /** Ordered concrete choices for Default and automatic fallback; never a global catalog. */
  models: readonly ProviderModelRef[];
  /** Compares resolved logical identities, preserving provider/auth routing. */
  allows: (ref: ProviderModelRef) => boolean;
}>;
//#endregion
//#region src/gateway/operator-run-authority.d.ts
/** Transfers the original operator restriction into accepted work, independently of its request. */
declare function captureGatewayOperatorRunAuthority(input: {
  client: GatewayClient | null;
  context: Pick<GatewayRequestContext, "getRuntimeConfig" | "getCommittedRuntimeConfig" | "resolveGatewayContext">;
  hasCurrentClientAuthority?: () => boolean;
  sourceAuthority?: Readonly<{
    assertCurrent: () => void;
    signal?: AbortSignal;
    gatewayAccessGrant?: AdmittedRunOperatorAuthority["gatewayAccessGrant"];
    /** Transfer the prepared principal/session facts to this admitted lifetime. */
    release?: () => void;
  }> | null;
  /** Additional request lifetime; never replaces the authenticated access grant. */
  invocationAuthority?: Readonly<{
    assertCurrent: () => void;
    signal?: AbortSignal;
  }>;
}): Promise<{
  authority: AdmittedRunOperatorAuthority;
  release: () => void;
} | undefined>;
//#endregion
//#region src/gateway/github-publication-requester.d.ts
type PublicationSession = {
  sessionKey: string;
  agentId: string;
};
/** @deprecated Use GitHubPublicationRequesterPolicyV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
type GitHubPublicationRequesterPolicy = Readonly<{
  snapshot: GitHubPublicationRequesterSnapshot;
  assertCurrent: () => void;
}>;
/** @deprecated Use GitHubPublicationRequesterV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
type GitHubPublicationRequester = GitHubPublicationRequesterPolicy & Readonly<{
  /** An accepted row keeps its own policy while the current invocation retains its fences. */
  assertInvocationCurrent: () => void;
}>;
/** Prepared host policy and a required live source capability for worker-owned writes. */
type GitHubPublicationRequesterPolicyV2 = GitHubPublicationRequesterPolicy & Readonly<{
  version: 2;
  signal: AbortSignal;
  prepareSource(selector: GitHubPublicationSourceSelector): Promise<GitHubPublicationSourceCapability>;
}>;
type GitHubPublicationRequesterV2 = GitHubPublicationRequesterPolicyV2 & Pick<GitHubPublicationRequester, "assertInvocationCurrent">;
/** Capture from the admitted caller, never request arguments, publisher, or session attribution. */
declare function prepareGitHubPublicationRequesterV2(options: Parameters<typeof captureGatewayOperatorRunAuthority>[0] & Pick<GatewayRequestHandlerOptions, "signal" | "sessionMutationAuthorization">, session: PublicationSession): Promise<{
  requester: GitHubPublicationRequesterV2;
  release: () => void;
}>;
//#endregion
//#region src/gateway/github-publication-coordinator-methods.d.ts
/** @deprecated Use GitHubPublicationClaimRequestV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
type GitHubPublicationClaimRequest = {
  claim: WorkerSessionTurnClaim;
  sessionKey: string;
  agentId: string;
  idempotencyKey: string;
  title?: string;
  body?: string;
  draft?: boolean;
  requester: GitHubPublicationRequester;
  expectedPublisher?: GitHubPublicationPublisher;
};
/** @deprecated Use GitHubPublicationSessionRequestV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
type GitHubPublicationSessionRequest = SessionGitHubPublishParams & {
  agentId: string;
  expectedRunId?: string;
  requester: GitHubPublicationRequester;
};
type GitHubPublicationClaimRequestV2 = Omit<GitHubPublicationClaimRequest, "requester"> & {
  requester: GitHubPublicationRequesterV2;
};
type GitHubPublicationSessionRequestV2 = Omit<GitHubPublicationSessionRequest, "requester"> & {
  requester: GitHubPublicationRequesterV2;
};
//#endregion
//#region src/gateway/github-personal-status.d.ts
type PersonalGitHubAction = {
  owner: string;
  assertCurrent: () => void;
};
declare function revalidatePersonalGitHubStatus(action: PersonalGitHubAction, prepared: PersonalGitHubStatus): PersonalGitHubStatus;
declare function resolvePersonalGitHubStatus(action: PersonalGitHubAction): Promise<PersonalGitHubStatus>;
//#endregion
//#region src/gateway/github-repository-publication-workspace.d.ts
declare function prepareReceiptOwner(row: {
  session_key: string;
  agent_id: string;
  workspace_id: string;
}): Promise<{
  workspace: Readonly<SessionRepositoryWorkspaceRecord> | undefined;
  assertSourceCurrent: () => void;
  current: () => Readonly<SessionRepositoryWorkspaceRecord> | undefined;
  session: {
    loaded: PublicationSessionRead;
    readCurrent: () => PublicationSessionRead;
    release: () => void;
    [Symbol.dispose]: () => void;
  };
  release: () => void;
}>;
//#endregion
//#region src/gateway/github-personal-publication-status.d.ts
type PreparedRepositoryPublicationStatus = {
  requestId: string;
  workspaceId: string;
  repository: Awaited<ReturnType<typeof prepareReceiptOwner>>;
  release: () => void;
};
declare function preparePersonalRepositoryPublicationStatus(requestId: string): Promise<{
  requestId: string;
  workspaceId: string;
  repository: {
    workspace: Readonly<SessionRepositoryWorkspaceRecord> | undefined;
    assertSourceCurrent: () => void;
    current: () => Readonly<SessionRepositoryWorkspaceRecord> | undefined;
    session: {
      loaded: PublicationSessionRead;
      readCurrent: () => PublicationSessionRead;
      release: () => void;
      [Symbol.dispose]: () => void;
    };
    release: () => void;
  };
  release: () => void;
} | undefined>;
//#endregion
//#region src/gateway/github-personal-publication.d.ts
/** @deprecated Use PersonalGitHubSessionActionV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
type PersonalGitHubSessionAction = PersonalGitHubAction & {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  lifecycleRevision: string | null;
};
type PersonalGitHubSessionActionV2 = PersonalGitHubSessionAction & Pick<GitHubPublicationRequesterV2, "version" | "signal" | "prepareSource">;
//#endregion
//#region src/gateway/github-publication.d.ts
type GitHubPublicationTranscriptReport = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  result: SessionGitHubPublicationResult;
  /** Run whose tool call requested this publication, when it is known to this process. */
  runId?: string;
};
type GitHubPublicationCoordinator = ReturnType<typeof createGitHubPublicationCoordinator>;
declare function createGitHubPublicationCoordinator(params: {
  placements: WorkerSessionPlacementStore;
  getCommittedRuntimeConfig: () => OpenClawConfig;
  assertCurrent?: () => void;
  signal?: AbortSignal;
  recovery?: {
    shared: GitHubPublicationRecoveryBackoff;
    repository: GitHubPublicationRecoveryBackoff;
  };
}): {
  sharedStatus(session: PublicationSessionIdentity, requestId: string): Promise<SessionGitHubStatusResult | undefined>;
  latestPublishedShared(session: PublicationSessionIdentity, preparedRead: Parameters<typeof readSharedGitHubPublication>[2]): Promise<SessionGitHubStatusResult | null>;
  latestShared(session: PublicationSessionIdentity, idempotencyKey?: string, isSuperseded?: (snapshot: Pick<GitHubPublicationRow, "repository" | "branch" | "source_head_commit" | "workspace_tree">) => Promise<boolean>, preparedRead?: Parameters<typeof readSharedGitHubPublication>[2]): Promise<SessionGitHubStatusResult | null>;
  /** @deprecated Use requestForClaimV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  requestForClaim: (_request: GitHubPublicationClaimRequest) => Promise<SessionGitHubPublicationResult>;
  requestForClaimV2: (request: GitHubPublicationClaimRequestV2) => Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>;
  prepareClaimWorkspace(claim: WorkerSessionTurnClaim): Promise<void>;
  /** @deprecated Use deferClaimPreparationAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  deferClaimPreparation(_claim: WorkerSessionTurnClaim): void;
  deferClaimPreparationAsync(claim: WorkerSessionTurnClaim): Promise<void>;
  /** @deprecated Use requestForSessionV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  requestForSession(_input: GitHubPublicationSessionRequest): Promise<SessionGitHubPublicationResult>;
  requestForSessionV2(input: Parameters<(input: GitHubPublicationSessionRequestV2) => Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>>[0]): Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>;
  /** @deprecated Use requestPersonalForSessionV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  requestPersonalForSession(_input: {
    sessionKey?: string | undefined;
    agentId?: string | undefined;
    idempotencyKey: string;
    workspacePath?: string | undefined;
    title?: string | undefined;
    body?: string | undefined;
    draft?: boolean | undefined;
    selection?: {
      source: "shared";
      expected?: {
        accountId: number;
        login: string;
        source: "agent-override" | "system-configured" | "system-detected";
      } | undefined;
    } | {
      source: "personal";
      generation: string;
      account: {
        accountId: number;
        login: string;
      };
    } | undefined;
  }, _action: PersonalGitHubSessionAction): Promise<SessionGitHubPublicationResult>;
  requestPersonalForSessionV2(input: {
    sessionKey?: string | undefined;
    agentId?: string | undefined;
    idempotencyKey: string;
    workspacePath?: string | undefined;
    title?: string | undefined;
    body?: string | undefined;
    draft?: boolean | undefined;
    selection?: {
      source: "shared";
      expected?: {
        accountId: number;
        login: string;
        source: "agent-override" | "system-configured" | "system-detected";
      } | undefined;
    } | {
      source: "personal";
      generation: string;
      account: {
        accountId: number;
        login: string;
      };
    } | undefined;
  }, action: PersonalGitHubSessionActionV2): Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>;
  preparePersonalStatus: typeof preparePersonalRepositoryPublicationStatus;
  /** @deprecated Use personalStatusAsync and await completion. */
  personalStatus(action: PersonalGitHubAction, session: PublicationSessionIdentity, requestId: string, prepared: PreparedRepositoryPublicationStatus | undefined): SessionGitHubStatusResult;
  personalStatusAsync(action: PersonalGitHubAction, session: PublicationSessionIdentity, requestId: string, prepared: PreparedRepositoryPublicationStatus | undefined): Promise<{
    result: {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "requested";
      message: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "publishing";
      message: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "published";
      url: string;
      repository: string;
      branch: string;
      headCommit: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "failed";
      code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
      message: string;
      nextAction: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "needs_confirmation";
      message: string;
    };
    confirmation: {
      requestDigest: string;
      generation: string;
      account: {
        accountId: number;
        login: string;
      };
      pushRepository: string;
      repository: string;
      branch: string;
      baseBranch: string;
      sourceHeadCommit: string;
      sourceIndexTree: string;
      workspaceTree: string;
    } | null;
  }>;
  personalPending(action: PersonalGitHubAction, session: PublicationSessionIdentity & {
    archivedAt?: number | null;
  }): Promise<{
    result: {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "requested";
      message: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "publishing";
      message: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "published";
      url: string;
      repository: string;
      branch: string;
      headCommit: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "failed";
      code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
      message: string;
      nextAction: string;
    } | {
      requestId: string;
      publisher?: {
        accountId: number;
        login: string;
        source: "agent-override" | "personal" | "system-configured" | "system-detected";
      } | undefined;
      effect?: {
        kind: "pull_request" | "push";
        status: "dispatched" | "observed";
        headCommit?: string | undefined;
        url?: string | undefined;
      } | undefined;
      status: "needs_confirmation";
      message: string;
    };
    confirmation: {
      requestDigest: string;
      generation: string;
      account: {
        accountId: number;
        login: string;
      };
      pushRepository: string;
      repository: string;
      branch: string;
      baseBranch: string;
      sourceHeadCommit: string;
      sourceIndexTree: string;
      workspaceTree: string;
    } | null;
  } | null>;
  /** @deprecated Use confirmPersonalV2; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  confirmPersonal(_input: {
    sessionKey: string;
    agentId?: string | undefined;
    requestId: string;
    generation: string;
    account: {
      accountId: number;
      login: string;
    };
    requestDigest: string;
  }, _action: PersonalGitHubSessionAction): Promise<SessionGitHubPublicationResult>;
  confirmPersonalV2(input: {
    sessionKey: string;
    agentId?: string | undefined;
    requestId: string;
    generation: string;
    account: {
      accountId: number;
      login: string;
    };
    requestDigest: string;
  }, action: PersonalGitHubSessionActionV2): Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  }>;
  processClaim(claim: WorkerSessionTurnClaim): Promise<({
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  })[]>;
  resumeSessionRequests(isStopping?: () => boolean, isPendingEmpty?: (kind: "shared" | "repository") => boolean): Promise<void>;
  /** @deprecated Use deferOrphanedRequestsAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  deferOrphanedRequests(): void;
  deferOrphanedRequestsAsync(isPendingEmpty?: (kind: "shared" | "repository") => boolean): Promise<void>;
  /** @deprecated Use listUnreportedResultsAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  listUnreportedResults(): GitHubPublicationTranscriptReport[];
  listUnreportedResultsAsync(): Promise<GitHubPublicationTranscriptReport[]>;
  /** @deprecated Use readAsync and await completion. */
  read(_requestId: string): SessionGitHubPublicationResult | undefined;
  readAsync(requestId: string): Promise<{
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "requested";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "publishing";
    message: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "published";
    url: string;
    repository: string;
    branch: string;
    headCommit: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "failed";
    code: "github_rejected" | "identity_changed" | "identity_unavailable" | "no_changes" | "not_git" | "not_github" | "push_rejected" | "session_changed" | "unavailable" | "workspace_changed";
    message: string;
    nextAction: string;
  } | {
    requestId: string;
    publisher?: {
      accountId: number;
      login: string;
      source: "agent-override" | "personal" | "system-configured" | "system-detected";
    } | undefined;
    effect?: {
      kind: "pull_request" | "push";
      status: "dispatched" | "observed";
      headCommit?: string | undefined;
      url?: string | undefined;
    } | undefined;
    status: "needs_confirmation";
    message: string;
  } | undefined>;
  readReportLifecycleAsync(report: GitHubPublicationTranscriptReport): Promise<string | null>;
  /** @deprecated Use markReportedAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  markReported(_requestId: string): void;
  markReportedAsync(requestId: string): Promise<void>;
};
//#endregion
//#region src/gateway/github-oauth-lifecycle.d.ts
declare function createGitHubOAuthLifecycle(params: {
  getConfig: () => OpenClawConfig;
  getPersistedConfig?: () => Promise<OpenClawConfig>;
  warn: (message: string) => void;
  scheduler: GatewayScheduler;
}): {
  personal: {
    status: typeof resolvePersonalGitHubStatus;
    revalidateStatus: typeof revalidatePersonalGitHubStatus;
    startAuthorization(action: PersonalGitHubAction): Promise<UsersGitHubAuthorizeStartResult>;
    pollAuthorization(action: PersonalGitHubAction, requestId: string): Promise<UsersGitHubAuthorizePollResult>;
    cancelAuthorization(action: PersonalGitHubAction, requestId: string): boolean;
    cancelAuthorizationAsync(action: PersonalGitHubAction, requestId: string): Promise<boolean>;
    disconnect(action: PersonalGitHubAction): void;
    disconnectAsync(action: PersonalGitHubAction): Promise<void>;
    refresh: (owner: string) => Promise<void>;
    maintain(): Promise<void>;
    stop(): Promise<void>;
  };
  startAuthorization: (input: {
    scope: GitHubIdentityScope;
    agentId: string;
  }) => Promise<ToolsGitHubAuthorizeStartResult>;
  pollAuthorization: (requestId: string) => Promise<ToolsGitHubAuthorizePollResult>;
  /** @deprecated Use cancelAuthorizationAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  cancelAuthorization(requestId: string): boolean;
  cancelAuthorizationAsync: (requestId: string) => Promise<boolean>;
  status: (agentId: string, selectedScope: GitHubIdentityScope) => Promise<{
    agentId: string;
    selectedScope: "agent" | "system";
    selected: {
      scope: "agent" | "system";
      configured: boolean;
      identity: {
        stale?: boolean | undefined;
        source: "agent-override" | "system-configured" | "system-detected";
        credentialKind: "app-installation" | "managed-oauth" | "managed-pat" | "native";
        credentialState: "available" | "configured_unavailable" | "rate_limited" | "unavailable" | "unverified";
        account: {
          login: string;
        } | null;
        gitAuthor: {
          name: string | null;
          email: string | null;
        };
        evidence: "github-api" | "none" | "rate-limited" | "unverified";
        accessExpiresAtMs: number | null;
        refreshState: "available" | "expired" | "failed" | "not_applicable" | "refreshing" | "unavailable";
        oauthScopes: string[];
        repositoryGrants: "unknown";
      } | null;
    };
    effective: {
      stale?: boolean | undefined;
      source: "agent-override" | "system-configured" | "system-detected";
      credentialKind: "app-installation" | "managed-oauth" | "managed-pat" | "native";
      credentialState: "available" | "configured_unavailable" | "rate_limited" | "unavailable" | "unverified";
      account: {
        login: string;
      } | null;
      gitAuthor: {
        name: string | null;
        email: string | null;
      };
      evidence: "github-api" | "none" | "rate-limited" | "unverified";
      accessExpiresAtMs: number | null;
      refreshState: "available" | "expired" | "failed" | "not_applicable" | "refreshing" | "unavailable";
      oauthScopes: string[];
      repositoryGrants: "unknown";
    };
  }>;
  /** @deprecated Use retireProfileAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  retireProfile(profileId: string): void;
  retireProfileAsync: (profileId: string) => Promise<void>;
  refreshEffectiveIdentity: (agentId: string) => Promise<void>;
  maintain: () => Promise<void>;
  start: () => void;
  stop: () => Promise<void>;
};
//#endregion
//#region src/gateway/model-account-connect.d.ts
/** One Gateway lifetime owns sign-in steps and authority; provider methods only stage credentials. */
declare function createModelAccountConnectService(options: {
  getConfig: () => OpenClawConfig;
  onChanged?: () => void;
}): {
  /** @deprecated Await listLinksAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  listLinks(action: ModelAccountConnectAction): UsersListAuthLinksResult;
  /** @deprecated Await linkAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  link(action: ModelAccountConnectAction, authProfileId: string): UsersLinkAuthProfileResult;
  /** @deprecated Await unlinkAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  unlink(action: ModelAccountConnectAction, provider: string): UsersUnlinkAuthProfileResult;
  /** @deprecated Await listAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  list(action: ModelAccountConnectAction, cursor?: string): UsersListModelAccountsResult;
  /** @deprecated Await selectAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  select(action: ModelAccountConnectAction, authProfileId: string): UsersSelectModelAccountResult;
  /** @deprecated Await statusAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  status(action: ModelAccountConnectAction, connectId: string): UsersAuthConnectStatusResult;
  /** @deprecated Await cancelAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  cancel(action: ModelAccountConnectAction, connectId: string): UsersAuthConnectStatusResult;
  listLinksAsync(action: ModelAccountConnectAction): Promise<UsersListAuthLinksResult>;
  linkAsync(action: ModelAccountConnectWorkerAction, authProfileId: string): Promise<UsersLinkAuthProfileResult>;
  unlinkAsync(action: ModelAccountConnectWorkerAction, provider: string): Promise<UsersUnlinkAuthProfileResult>;
  listAsync(action: ModelAccountConnectAction, cursor?: string): Promise<UsersListModelAccountsResult>;
  catalog(action: ModelAccountConnectAction): UsersAuthConnectCatalogResult;
  selectAsync(action: ModelAccountConnectWorkerAction, authProfileId: string): Promise<UsersSelectModelAccountResult>;
  start(action: ModelAccountConnectAction, provider: string, methodId: string): Promise<UsersAuthConnectStartResult>;
  statusAsync(action: ModelAccountConnectAction, connectId: string): Promise<UsersAuthConnectStatusResult>;
  answer(action: ModelAccountConnectAction, connectId: string, stepId: string, value?: unknown): Promise<UsersAuthConnectStatusResult>;
  cancelAsync(action: ModelAccountConnectAction, connectId: string): Promise<UsersAuthConnectStatusResult>;
  supersede: (owner: string, provider: string) => void;
  stop(): Promise<void>;
};
//#endregion
//#region src/infra/voicewake-routing.d.ts
type VoiceWakeRouteTarget = {
  mode: "current";
  agentId?: undefined;
  sessionKey?: undefined;
} | {
  agentId: string;
  sessionKey?: undefined;
  mode?: undefined;
} | {
  sessionKey: string;
  agentId?: undefined;
  mode?: undefined;
};
type VoiceWakeRouteRule = {
  trigger: string;
  target: VoiceWakeRouteTarget;
};
type VoiceWakeRoutingConfig = {
  version: 1;
  defaultTarget: VoiceWakeRouteTarget;
  routes: VoiceWakeRouteRule[];
  updatedAtMs: number;
};
//#endregion
//#region src/sessions/session-agent-work-admission.d.ts
type AgentWorkAdmissionIdentity = {
  agentId: string;
  statePath: string;
};
//#endregion
//#region src/sessions/session-controller.lifecycle-diagnostics.d.ts
type QueueKind = "lifecycle" | "mutation";
type SessionLifecycleDiagnosticLabel = "acp-spawn-cleanup" | "archived-delete" | "assign-owner" | "background-result" | "compact" | "compaction" | "create" | "cron-cleanup" | "delete" | "delete-prepare" | "drain" | "history-evict" | "placement-dispatch" | "placement-failed-reclaim" | "placement-reclaim" | "plugin-create" | "read-marker" | "recover" | "recovery-drain" | "recovery-mark" | "reset" | "sharing" | "subagent-kill" | "subagent-kill-sweep" | "workspace-edit" | "worktree-cleanup";
type Phase$1 = "admission" | "activation" | "prepare" | "run-admission" | "run" | "finalize" | "release";
type LifecycleDiagnosticOperation = {
  readonly id: number;
  readonly operation: "lifecycle" | "mutation" | "compaction";
  readonly mutationKind?: SessionLifecycleDiagnosticLabel;
  readonly scopeIdentity: string;
  readonly identityCount: number;
  readonly signal?: AbortSignal;
  readonly traceId?: string;
  readonly spanId?: string;
  readonly parentSpanId?: string;
  readonly traceFlags?: string;
  readonly observedHolder: boolean;
  readonly acquiredAt: number;
  hasSlowWaiter: boolean;
  phase: Phase$1;
  hold(): void;
  mark(phase: Phase$1): void;
  wait(kind: QueueKind, currentHolder: () => LifecycleDiagnosticOperation | undefined): () => void;
  finish(finishedAt?: number): void;
};
//#endregion
//#region src/infra/gateway-suspend-coordinator.d.ts
/** Private identity of one live process-owning host iteration, never a wire token. */
type GatewaySuspendHandoffOwner = {
  isCurrent: () => boolean;
  /** Transfers a validated suspension into this host's synchronous one-way shutdown. */
  commitStop?: () => void;
};
//#endregion
//#region src/gateway/server-channel-runtime.types.d.ts
type ChannelRuntimeSnapshotOptions = {
  channelId?: ChannelId$1;
  /** Controls read recorded state without invoking fallible diagnostic inspectors. */
  inspectAccounts?: boolean;
};
type ChannelRuntimeSnapshot = {
  /** Host admission is paused; status must use captured facts without invoking plugin callbacks. */
  reloadingChannels?: ReadonlyMap<ChannelId$1, string | undefined>;
  channels: Partial<Record<ChannelId$1, ChannelAccountSnapshot>>;
  channelAccounts: Partial<Record<ChannelId$1, Record<string, ChannelAccountSnapshot>>>;
};
/** The lifecycle owner's decision for one requested account start, separate from connectivity. */
type ChannelAccountStartOutcome = {
  status: "handed-off";
} | {
  status: "retry";
  reason: "stop-in-flight" | "task-owned";
} | {
  status: "skipped";
  reason: "unsupported" | "autostart-suppressed" | "ambient-suppressed" | "disabled" | "unconfigured" | "secret-unavailable" | "unlinked" | "manual-stop";
};
type StartChannelOptions = {
  /** Lifecycle trigger, recorded once when an account is handed to its plugin. */
  reason?: "startup" | "autostart-recovery" | "auto-restart" | "stop-recovery" | "health-monitor" | "config-reload" | "plugin-reload" | "secrets-reload" | "host-thaw";
  preserveRestartAttempts?: boolean;
  preserveManualStop?: boolean;
  /** Reload leaves snapshot-cold accounts stopped without bypassing credential-file reinspection. */
  skipUnavailableAccounts?: boolean;
  manual?: boolean;
};
//#endregion
//#region src/gateway/server-public.d.ts
type GatewayShutdownBudget = {
  timeoutMs: number;
  reserveMs: number;
  nativeStopBudget: boolean;
};
/** A capability for one host iteration; native completion belongs to the host. */
type GatewayHostLifecycle = {
  /** Present only when this host owns process exit; the identity never crosses RPC. */
  externalRestart?: GatewaySuspendHandoffOwner;
  getShutdownBudget?(): GatewayShutdownBudget | undefined;
  request(action: "start" | "stop" | "restart", assertCaller: () => void): Promise<Result$1<{
    outcome: "already-running" | "scheduled";
  }, string>>;
};
//#endregion
//#region src/gateway/server-request-entry.d.ts
type RequestEntryOptions = Pick<GatewayRequestOptions, "client" | "context"> & {
  req: Pick<GatewayRequestOptions["req"], "method" | "params">;
};
type GatewayRequestEntry = {
  assertOpen: () => void;
  release: () => void;
};
/** One Gateway's preparation leases; handler execution belongs to its existing runtime owner. */
declare class GatewayRequestEntryLifetime {
  private readonly stopping;
  private readonly retained;
  private readonly active;
  private sealed;
  readonly signal: AbortSignal;
  readonly retainedSignal: AbortSignal;
  enter(options: RequestEntryOptions): GatewayRequestEntry;
  beginClose(): void;
  /** Accepted ingress authority outlives admission until restart custody is recorded. */
  retire(reason?: Error): void;
  waitForPendingEntries(): Promise<void>;
  sealAndJoin(): Promise<void>;
}
//#endregion
//#region src/gateway/session-mutation-authorization-error.d.ts
type SessionMutationTarget = {
  sessionKey: string;
  agentId?: string;
};
//#endregion
//#region src/gateway/expected-profile.d.ts
/** Request-local selection precondition, independent of socket and accepted-run lifetime. */
declare function createExpectedProfileBinding(expectedProfileId: string | undefined, client: GatewayClient | null, assertRequestCurrent?: () => void): Promise<{
  assertCurrent: () => void;
  /** Compare a profile resolved by the storage owner on its transaction connection. */
  assertMatchesResolvedProfile: (profileId: string | undefined) => void;
  markInvoked: () => void;
  guardResponse: (respond: RespondFn) => RespondFn;
} | undefined>;
type ExpectedProfileBinding = NonNullable<Awaited<ReturnType<typeof createExpectedProfileBinding>>>;
//#endregion
//#region src/gateway/talk/session-target.types.d.ts
type PreparedTalkSessionTarget = Readonly<{
  agentId: string;
  /** Voice records and close/resume retain the client's exact key, not its storage alias. */
  sessionKey: string;
  canonicalKey: string;
  storePath: string;
  assertCurrent(cfg: OpenClawConfig): void;
}>;
//#endregion
//#region src/gateway/slow-request-diagnostics.d.ts
type SessionSubscribePhase = "setup" | "projectionReadiness" | "accessFacts" | "handlerPreparation" | "retainedReadAdmission" | "replayPreparation" | "observerCommit" | "response" | "cleanup";
//#endregion
//#region src/gateway/session-access-authority.d.ts
type RetainedGatewaySessionAccess = {
  readonly signal: AbortSignal;
  assertCurrent: () => void;
  release: () => void;
};
type GatewaySessionAccessAuthority = {
  readonly target: Readonly<{
    agentId: string;
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
  }>;
  readonly sandboxRequired: boolean;
  /** Invocation guard, including the admitted model turn when applicable. */
  assertCurrent: () => void;
  /** Retain original actor, grant, sharing and tool policy for a viewer or accepted operation. */
  retain: () => RetainedGatewaySessionAccess;
  /** Session resource lifetime only. Revoking one collaborator must not destroy shared state. */
  retainSession: () => RetainedGatewaySessionAccess;
  /** Router-owned preparation hold; each service borrow has its own release. */
  release: () => void;
};
//#endregion
//#region src/gateway/server-methods/prepared-read.d.ts
/** Authority belongs to each reader; only run's successful response may be shared. */
type GatewayPreparedRead = {
  shareable?: boolean;
  run: (respond: RespondFn) => Promise<void> | void;
  assertCurrent?: () => void;
  respond?: RespondFn;
  release?: (outcome: "returned" | "threw") => void;
  beforeRespond?: () => void;
};
type GatewayReadPreparation = (options: GatewayRequestHandlerOptions) => Promise<GatewayPreparedRead | undefined> | GatewayPreparedRead | undefined;
type GatewayReadErrorHandler = (error: unknown, options: GatewayRequestHandlerOptions) => void;
//#endregion
//#region src/cli/deps.types.d.ts
type CliDeps = OutboundSendDeps;
//#endregion
//#region src/gateway/agent-runtime-approval-authority.d.ts
type AgentRuntimeApprovalAuthorityValidator = (identity: AgentRuntimeIdentity) => boolean;
//#endregion
//#region src/gateway/server-in-process-dispatch.types.d.ts
type GatewayMethodDispatchResponse = SchemaContract<Omit<ResponseFrame, "type" | "id" | "error">> & {
  error?: ErrorShape;
  meta?: Record<string, unknown>;
};
//#endregion
//#region src/gateway/server-methods/agent-request-types.d.ts
type AgentRunRequest = Omit<Static<typeof AgentParamsSchema>, "attachments" | "internalEvents" | "inputProvenance"> & {
  attachments?: Array<Pick<ChatAttachment, "type" | "mimeType" | "fileName" | "content">>;
  internalEvents?: AgentInternalEvent[];
  inputProvenance?: InputProvenance;
  workspaceDir?: string;
};
//#endregion
//#region src/gateway/agent-turn/internal-facade.types.d.ts
type InternalAgentTurnPrincipalOptions = {
  assertContextCurrent?: () => void;
  client: GatewayClient;
  isWebchatConnect?: (params: ConnectParams | null | undefined) => boolean;
};
type AgentTurnStartOwner = {
  observe: () => {
    executionStarted: boolean;
    /** Exact controller budget; null means a live owner wait has no deadline. */
    startDeadlineAtMs?: number | null;
  } | undefined;
  abort: () => boolean;
};
/** A live frozen settle cohort may identify an already accepted legacy source. */
type RequesterSettleWakeReplay = {
  sourceSessionKeys: readonly string[];
  assertCurrent: () => void;
};
type InternalAgentTurnDispatchOptions = {
  /** Exact in-process mailbox source reserved by the input owner. */
  controllerInput?: SessionControllerInput;
  /** Internal completion delivery owns its hidden input and durable processing receipt. */
  privateCompletion?: true;
  /** Trusted input-owner policy; not accepted from the wire request. */
  replyExpectation?: ReplyExpectation;
  settleWakeReplay?: RequesterSettleWakeReplay;
  /** Refresh the source before dispatch; accepted turns own their later execution. */
  prepareDispatchCurrent?: () => Promise<void>;
  assertAdmissionCurrent?: () => void;
  /** Validates cancellation publication independently of the canceled execution lifetime. */
  assertCancellationCurrent?: () => void;
  /** Accepted execution retains this permission check through tool and delivery effects. */
  executionSource?: SessionSourceAssertion;
  cancelOnDeadline?: boolean;
  expectFinal?: boolean;
  onAccepted?: (payload: unknown) => void;
  onStartOwner?: (owner: AgentTurnStartOwner) => void;
  onExecutionStarted?: () => void;
  onSignalAbort?: () => Promise<void> | void;
  signal?: AbortSignal;
  timeoutMs?: number;
};
type InternalAgentTurnFacade = {
  dispatch: <T = unknown>(request: AgentRunRequest, options?: InternalAgentTurnDispatchOptions | number) => Promise<T>;
  dispatchRaw: (request: AgentRunRequest, options?: InternalAgentTurnDispatchOptions) => Promise<GatewayMethodDispatchResponse>;
  wait: <T = unknown>(params: AgentWaitParams, timeoutMs?: number, signal?: AbortSignal, onSignalAbort?: () => Promise<void> | void, prepareDispatchCurrent?: () => Promise<void>) => Promise<T>;
};
type InternalAgentTurnFacadeFactory = (principal: InternalAgentTurnPrincipalOptions) => InternalAgentTurnFacade | Promise<InternalAgentTurnFacade>;
//#endregion
//#region src/gateway/config-reload-status.types.d.ts
type GatewayHotReloadStatus = "active" | "disabled";
/** Channel reload work currently waiting for active Gateway work to drain. */
type GatewayDeferredChannelReload = {
  channel: string;
  /** False when plugin publication committed before newly activated channels wait to start. */
  publicationPending: boolean;
};
//#endregion
//#region src/gateway/config-revision-token.d.ts
type GatewayConfigRevisionProjector = {
  projectRawHash: (hash: string) => string;
  projectResolvedHash: (hash: string) => string;
  hashResponseSessionBearer: (bearer: string) => string;
};
//#endregion
//#region src/gateway/device-scope-upgrade.d.ts
type UpgradeOwner = {
  deviceId: string;
  publicKey: string;
};
type ScopeUpgradeWaitResult = ScopeUpgradeResult | {
  status: "insufficient-scopes";
  requestId: string;
};
/** Coordinates live device scope-upgrade waiters with the durable pairing store. */
declare class ScopeUpgradeCoordinator {
  private readonly entries;
  private readonly work;
  private readonly scheduler;
  private lifetimeBound;
  constructor(scheduler: GatewayScheduler);
  private bindGatewayLifetime;
  close(): Promise<void>;
  register(params: {
    requestId: string;
    expiresAtMs: number;
    owner: UpgradeOwner;
    requestedScopes: string[];
    initialToken?: string;
    initialApprovedAtMs?: number;
  }): boolean;
  notify(requestId: string, resolution: "approved" | "rejected"): void;
  wait(requestId: string, owner: UpgradeOwner): Promise<ScopeUpgradeWaitResult | null>;
  private waitForResult;
  private readDurableResult;
  private scheduleCleanup;
}
//#endregion
//#region src/gateway/operator-approval-placement-grants.d.ts
type PlacementStandingGrantMintSpec = NonNullable<PluginApprovalRequestPayload["placementGrant"]>;
type PlacementStandingGrantRecord = PlacementStandingGrantMintSpec & {
  mintedByApprovalId: string;
  expiresAtMs: number;
};
type ConsumePlacementStandingGrantResult = {
  outcome: "consumed";
  grant: PlacementStandingGrantRecord;
} | {
  outcome: "no-grant" | "expired" | "approval-missing" | "approval-not-allow-always" | "placement-missing" | "placement-changed" | "node-changed" | "pairing-changed";
};
type PlacementGrantResolutionInput = Pick<PlacementStandingGrantMintSpec, "pluginId" | "command" | "approvalScope" | "agentId" | "sessionKey" | "nodeId" | "pairingGeneration">;
type RetainPlacementGrantInput = PlacementStandingGrantMintSpec & {
  approvalId: string;
  nowMs: number;
  expiresAtMs: number | null;
};
type PlacementStandingGrantRuntime = {
  /** @deprecated Released SDK compatibility; use resolveBindingAsync. */
  resolveBinding: (input: PlacementGrantResolutionInput) => PlacementStandingGrantMintSpec | null;
  /** @deprecated Released SDK compatibility; use retainAsync. */
  retain: (grant: RetainPlacementGrantInput) => boolean;
  /** @deprecated Released SDK compatibility; use validateAsync. */
  validate: (binding: PlacementStandingGrantMintSpec) => ConsumePlacementStandingGrantResult;
  /** Final receipt guard; prepare with consumeAsync immediately before transport handoff. */
  consume: (binding: PlacementStandingGrantMintSpec) => ConsumePlacementStandingGrantResult;
  resolveBindingAsync?: (input: PlacementGrantResolutionInput) => Promise<PlacementStandingGrantMintSpec | null>;
  resolveAsync?: (input: PlacementGrantResolutionInput) => Promise<{
    binding: PlacementStandingGrantMintSpec | null;
    approvalId?: string;
  }>;
  retainAsync?: (grant: RetainPlacementGrantInput) => Promise<boolean>;
  consumeAsync?: (binding: PlacementStandingGrantMintSpec) => Promise<ConsumePlacementStandingGrantResult>;
  validateAsync?: (binding: PlacementStandingGrantMintSpec) => Promise<ConsumePlacementStandingGrantResult>;
};
//#endregion
//#region src/gateway/operator-approval-standing-grants.types.d.ts
/** Cron identity plus exact operation binding recorded at approval creation. */
type CronStandingGrantMintSpec = {
  agentId: string;
  cronJobId: string;
  jobConfigRevision: string;
  operationBinding: string;
};
//#endregion
//#region src/gateway/exec-approval-manager.types.d.ts
type ExecApprovalReadAuthority = {
  assertCurrent: () => void;
  guard: OperatorApprovalStoreGuard;
};
type ExecApprovalResolveOptions = {
  /** Explicit grant expiry override; undefined defers to the configured default. */
  grantExpiresAtMs?: number | null;
  assertCurrent?: () => void;
  guard?: OperatorApprovalStoreGuard;
};
type ExecApprovalResolutionSource = "operator" | "auto-review";
type ExecApprovalRecord<TPayload = ExecApprovalRequestPayload> = {
  id: string;
  request: TPayload;
  createdAtMs: number;
  expiresAtMs: number;
  requestedByConnId?: string | null;
  requestedByDeviceId?: string | null;
  requestedByClientId?: string | null;
  requestedByDeviceTokenAuth?: boolean;
  approvalReviewerDeviceIds?: string[];
  resolvedAtMs?: number;
  decision?: ExecApprovalDecision;
  consumedDecision?: ExecApprovalDecision;
  resolutionSource?: ExecApprovalResolutionSource;
  askFallbackConsumed?: boolean;
  resolvedBy?: string | null;
  status?: OperatorApprovalStatus;
  terminalReason?: OperatorApprovalTerminalReason | null;
  runtimeEpoch?: string;
  resolverKind?: OperatorApprovalResolver["kind"] | null;
  consumedAtMs?: number | null;
  consumedBy?: string | null;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  /** Exact source authority retained only for use-time liveness validation. */
  agentRuntimeDelegatedAuthority?: AgentRuntimeDelegatedAuthority;
  /** Closure-bound authority for approvals created by in-process delegated tools. */
  approvalAuthority?: () => boolean | void;
  approvalSignals?: readonly AbortSignal[];
  /** Process-local persistence proof; never serialized with approval presentation. */
  mcpToolApprovalActive?: () => boolean;
};
type OperatorApprovalLifecycleEvent = {
  phase: "pending" | "terminal";
  record: OperatorApprovalRecord;
};
type OperatorStandingGrantMintSpec = ({
  kind: "cron";
} & CronStandingGrantMintSpec) | {
  kind: "mcp-tool";
  agentId: string;
  server: string;
  tool: string;
} | ({
  kind: "placement";
} & PlacementStandingGrantMintSpec);
type ExecApprovalManagerOptions<TPayload> = {
  scheduler: GatewayScheduler;
  approvalKind?: OperatorApprovalKind;
  persistence: {
    runtimeEpoch: string;
    databaseOptions?: OpenClawStateDatabaseOptions;
  };
  resolveAllowedDecisions?: (request: TPayload) => readonly ExecApprovalDecision[];
  /** Gateway may await lineage preparation; absence seeds only the requesting session. */
  resolveAudienceSessionKeys?: (sourceSessionKey: string, sourceAgentId?: string | null) => string[] | Promise<string[]>;
  onError?: (error: Error, context: {
    approvalId: string;
    approvalKind: OperatorApprovalKind;
    operation: "expire";
  }) => void;
  onLifecycle?: (event: OperatorApprovalLifecycleEvent) => void;
  /** Eligible allow-always requests derive one scoped grant, or return null. */
  resolveStandingGrantMint?: (request: TPayload) => OperatorStandingGrantMintSpec | null;
  /** Installs a placement grant after the durable approval CAS succeeds. */
  retainPlacementStandingGrant?: PlacementStandingGrantRuntime["retain"];
  retainPlacementStandingGrantAsync?: PlacementStandingGrantRuntime["retainAsync"];
  resolveStandingGrantExpiresAtMs?: (nowMs: number) => number | null;
  /** Timer, lookup, and replay expiry must all release the same local waiter. */
  onExpired?: (record: OperatorApprovalRecord, liveRecord: ExecApprovalRecord<TPayload>) => void;
  validateAgentRuntimeDelegatedAuthority?: (authority: AgentRuntimeDelegatedAuthority) => boolean;
};
type WithLiveRecord<TResult, TPayload> = TResult extends {
  record: OperatorApprovalRecord;
} ? TResult & {
  liveRecord?: ExecApprovalRecord<TPayload>;
} : TResult;
type ExecApprovalResolveResult<TPayload = ExecApprovalRequestPayload> = WithLiveRecord<ResolveOperatorApprovalResult, TPayload>;
type ExecApprovalForceDenyResult<TPayload = ExecApprovalRequestPayload> = WithLiveRecord<ForceDenyOperatorApprovalResult, TPayload>;
type ExecApprovalDurableLookup = {
  outcome: "found";
  record: OperatorApprovalRecord;
} | {
  outcome: "missing" | "corrupt";
  id: string;
};
type ExecApprovalIdLookupResult = {
  kind: "exact" | "prefix";
  id: string;
} | {
  kind: "ambiguous";
  ids: string[];
} | {
  kind: "none";
};
//#endregion
//#region src/gateway/exec-approval-recovery.d.ts
type ExecApprovalMutationPersistence = ExecApprovalManagerOptions<unknown>["persistence"] & {
  workerContext?: OpenClawStateWorkerContext;
};
//#endregion
//#region src/gateway/exec-approval-lifecycle.d.ts
type DecisionHandoff = {
  start: (decision: ExecApprovalDecision | null) => void;
  cancel: () => void;
};
type PendingEntry<TPayload> = {
  record: ExecApprovalRecord<TPayload>;
  resolve: (decision: ExecApprovalDecision | null) => void;
  expiryJob: GatewayScheduledJob | null;
  cleanupJob: GatewayScheduledJob | null;
  handoffRetainCount: number;
  handoffReleasedAtMs: number | null;
  retainForManagerLifetime: boolean;
  promise: Promise<ExecApprovalDecision | null>;
  handoffs: Set<DecisionHandoff>;
  admissionContinuation: GatewayRootWorkAdmissionContinuationScope | null;
  mutation?: Promise<void>;
  expiryPersistence?: ExecApprovalMutationPersistence;
  expiryRefusals?: number;
  uncertainVerdict?: {
    assertCurrent: () => void;
    autoReview?: {
      committedResolutionKey?: string;
    };
  };
  terminalPublication?: Pick<OperatorApprovalRecord, "kind" | "runtimeEpoch" | "status" | "decision" | "terminalReason" | "resolvedAtMs" | "updatedAtMs">;
};
/** Owns local observations and genuine decision effects, never durable decision policy. */
declare abstract class ExecApprovalLifecycle<TPayload> {
  protected readonly scheduler: GatewayScheduler;
  protected readonly pending: Map<string, PendingEntry<TPayload>>;
  protected retired: boolean;
  private observingClosed;
  private readonly observers;
  private readonly work;
  private draining;
  constructor(scheduler: GatewayScheduler);
  abstract get runtimeEpoch(): string;
  protected abstract expireDue(recordId: string, authority?: ExecApprovalReadAuthority): Promise<boolean>;
  abstract get approvalKind(): OperatorApprovalKind;
  protected abstract readonly options: Pick<ExecApprovalManagerOptions<TPayload>, "onError" | "onExpired" | "onLifecycle">;
  protected emitLifecycle(event: OperatorApprovalLifecycleEvent): void;
  protected retainUncertainVerdict(record: ExecApprovalRecord<TPayload> | undefined, uncertainty: NonNullable<PendingEntry<TPayload>["uncertainVerdict"]>): void;
  protected assertPendingPersistenceCurrent(entry: PendingEntry<TPayload> | undefined): void;
  protected clearUncommittedVerdict(record: ExecApprovalRecord<TPayload>): void;
  protected settleLocalStorageFailure(recordId: string): void;
  protected settleLocalFromStore(record: OperatorApprovalRecord, localDecision?: ExecApprovalDecision | null, localResolvedBy?: string | null, localResolutionSource?: ExecApprovalResolutionSource): boolean;
  /** Settle one durable terminal transition and report whether this manager published it. */
  reconcileDurableTerminal(record: OperatorApprovalRecord): Promise<boolean>;
  protected reportError(error: unknown, context: {
    approvalId: string;
    operation: "expire";
  }): void;
  beginClose(): void;
  retire(): void;
  drain(): Promise<void>;
  trackActiveWork<T>(run: () => T | Promise<T>): Promise<T>;
  /** Accepted mutations retain their result and any committed handoff through retirement. */
  protected trackMutation<T>(run: () => Promise<T>, recordId?: string): Promise<T>;
  /** Native readers cannot publish ahead of the accepted winner's process-local provenance. */
  protected waitForMutations(recordId: string): Promise<boolean>;
  protected canUseRetainedBinding(): boolean;
  protected assertNotRetired(): void;
  protected registerEntry(record: ExecApprovalRecord<TPayload>): Promise<ExecApprovalDecision | null>;
  /** Registers the real effect before an observer can leave or a synchronous verdict can win. */
  registerDecisionHandoff(recordId: string, run: (decision: ExecApprovalDecision | null) => Promise<void>): {
    observation: Promise<void>;
    abandon: () => void;
  };
  protected observeEntry<T>(entry: PendingEntry<TPayload>, completion: Promise<T>): Promise<T>;
  protected settleLocalEntry(params: {
    recordId: string;
    decision: ExecApprovalDecision | null;
    resolvedAtMs: number;
    resolvedBy: string | null;
    resolverKind: OperatorApprovalResolver["kind"] | null;
    status: OperatorApprovalStatus;
    terminalReason: OperatorApprovalTerminalReason | null;
    consumedAtMs?: number | null;
    consumedBy?: string | null;
    resolutionSource?: ExecApprovalResolutionSource;
    retainForManagerLifetime?: boolean;
  }): boolean;
  private scheduleResolvedCleanup;
  protected resolvedGraceAnchorMs(entry: PendingEntry<TPayload>, nowMs: number): number | null;
  /** Final release starts a fresh grace only while the manager still owns its lifecycle. */
  retainForHandoff(recordId: string): (() => void) | null;
  protected abstract scheduleExpiry(entry: PendingEntry<TPayload>, delayMs?: number): void;
  getSnapshot(recordId: string, authority?: ExecApprovalReadAuthority): Promise<ExecApprovalRecord<TPayload> | null>;
  /** Pure binding lookup for synchronous resource authorization; never grants a decision. */
  getLocalSnapshot(recordId: string): ExecApprovalRecord<TPayload> | null;
  /** Reads a live local binding without entering durable storage or mutating expiry. */
  getLiveSnapshot(recordId: string): ExecApprovalRecord<TPayload> | null;
  /**
   * One-shot ask-fallback re-admission for a timed-out approval. This is
   * pre-gate policy on the process-local record only: the durable row stays
   * `expired` and no execution authority is minted here. The shipped askFallback
   * policy (docs/tools/exec-approvals.md) still applies; system.run replay
   * uses this flag to keep re-admission single-use.
   */
  consumeAskFallback(recordId: string): boolean;
  /** Re-enters only the pending approval's exact original root. */
  runPendingContinuation<T>(recordId: string, run: () => Promise<T>): Promise<T> | null;
  listPendingRecords(authority?: ExecApprovalReadAuthority): Promise<ExecApprovalRecord<TPayload>[]>;
  /** Closure callbacks revoke these bindings synchronously before awaiting persistence. */
  listLocalPendingRecords(): ExecApprovalRecord<TPayload>[];
  lookupApprovalId(input: string, opts?: {
    includeResolved?: boolean;
    authority?: ExecApprovalReadAuthority;
    filter?: (record: ExecApprovalRecord<TPayload>) => boolean | Promise<boolean>;
  }): Promise<ExecApprovalIdLookupResult>;
  lookupLocalApprovalId(input: string, opts?: {
    includeResolved?: boolean;
    filter?: (record: ExecApprovalRecord<TPayload>) => boolean;
  }): ExecApprovalIdLookupResult;
}
//#endregion
//#region src/gateway/exec-approval-expiry.d.ts
/** The existing pending entry owns its deadline and any definite-refusal retry. */
declare abstract class ExecApprovalExpiry<TPayload> extends ExecApprovalLifecycle<TPayload> {
  protected abstract readonly options: Pick<ExecApprovalManagerOptions<TPayload>, "persistence" | "onError" | "onExpired" | "onLifecycle">;
  abstract forceDenyDetailed(recordId: string, reason: OperatorApprovalTerminalReason, resolver: OperatorApprovalResolver, status?: "denied" | "expired" | "cancelled", localDecision?: ExecApprovalDecision | null, requireDue?: boolean, localResolvedBy?: string | null, assertResolverCurrent?: () => void, callerGuard?: OperatorApprovalStoreGuard): Promise<ExecApprovalForceDenyResult<TPayload>>;
  protected abstract scheduleAuthorityClosure(recordId: string): void;
  /** Observes a registered decision; Gateway closure rejects the wait, not the approval. */
  awaitDecision(recordId: string): Promise<ExecApprovalDecision | null> | null;
  protected scheduleExpiry(entry: PendingEntry<TPayload>, delayMs?: number): void;
  protected expireDue(recordId: string, authority?: ExecApprovalReadAuthority): Promise<boolean>;
}
//#endregion
//#region src/gateway/exec-approval-manager.d.ts
/** Approval creation and persistence precede every local wait or delivery handoff. */
declare class ExecApprovalManager<TPayload = ExecApprovalRequestPayload> extends ExecApprovalExpiry<TPayload> {
  protected readonly options: ExecApprovalManagerOptions<TPayload>;
  constructor(options: ExecApprovalManagerOptions<TPayload>);
  get approvalKind(): OperatorApprovalKind;
  get runtimeEpoch(): string;
  create(request: TPayload, timeoutMs: number, id?: string | null): ExecApprovalRecord<TPayload>;
  /** Persist registration before exposing its separate decision promise to delivery. */
  register(record: ExecApprovalRecord<TPayload>, _timeoutMs: number): Promise<{
    decision: Promise<ExecApprovalDecision | null>;
  }>;
  protected scheduleAuthorityClosure(recordId: string): void;
  /** Persist the first verdict, then release the process-local waiter. */
  resolveDetailed(recordId: string, decision: ExecApprovalDecision, resolver: OperatorApprovalResolver, localResolvedBy?: string | null, localResolutionSource?: ExecApprovalResolutionSource, options?: ExecApprovalResolveOptions): Promise<ExecApprovalResolveResult<TPayload>>;
  /** Persist a fail-closed terminal state, then release the local waiter. */
  forceDenyDetailed(recordId: string, reason: OperatorApprovalTerminalReason, resolver: OperatorApprovalResolver, status?: "denied" | "expired" | "cancelled", localDecision?: ExecApprovalDecision | null, requireDue?: boolean, localResolvedBy?: string | null, assertResolverCurrent?: () => void, callerGuard?: OperatorApprovalStoreGuard): Promise<ExecApprovalForceDenyResult<TPayload>>;
  private recoverUnknownVerdict;
  /** Reconciles durable truth with an existing waiter without rehydrating its request. */
  reconcileDurableLookup(initialLookup: ExecApprovalDurableLookup, localResolvedBy?: string | null, authority?: ExecApprovalReadAuthority): Promise<OperatorApprovalRecord | null>;
  private persistStorageCorruptDeny;
  resolve(recordId: string, decision: ExecApprovalDecision, resolvedBy?: string | null, options?: ExecApprovalResolveOptions): Promise<boolean>;
  /**
   * Trusted auto-review resolution (identity-matched approval runtime).
   * Always allow-once; system.run replay validation treats the resulting
   * record more strictly than an operator decision (see #103515).
   */
  resolveAutoReview(recordId: string, resolvedBy?: string | null, assertCurrent?: () => void, guard?: OperatorApprovalStoreGuard): Promise<boolean>;
  expire(recordId: string, resolvedBy?: string | null): Promise<boolean>;
  /** The effect owner composes this live guard and the shared consumption CAS in its transaction. */
  prepareConsumeAllowOnce(recordId: string, consumerId?: string): ExecApprovalPreparedConsumption | null;
  consumeAllowOnce(recordId: string, consumerId?: string): Promise<boolean>;
  /** Exact accepted record liveness for owner-bound waits; never grants a decision. */
  isPending(record: ExecApprovalRecord<TPayload>): boolean;
  /** Delivery eligibility stays with the exact pending record across adapter awaits. */
  isPendingDeliveryCurrent(record: ExecApprovalRecord<TPayload>): boolean;
  /** Projects an allowed decision only while its exact runtime authority is live. */
  projectDecisionIfActive(recordId: string, decision: ExecApprovalDecision | null): ExecApprovalDecision | null;
  /** Atomically closes a live approval whose exact runtime owner is gone. */
  forceDenyIfRuntimeAuthorityClosed(recordId: string): Promise<ExecApprovalForceDenyResult<TPayload> | null>;
}
//#endregion
//#region src/plugins/runtime-degraded-state.d.ts
type PluginVerificationFailureReason = "missing-install-path" | "missing-package-dir" | "missing-package-json" | "unreadable-package-json" | "invalid-package-json" | "missing-bundle-manifest" | "invalid-bundle-manifest" | "missing-main-entry" | "missing-extension-entry" | "missing-openclaw-peer-link";
//#endregion
//#region src/infra/gateway-crash.d.ts
type GatewayCrashEvidence = {
  reason?: string;
  signal?: string;
  exitCode?: number;
  lastHeartbeatAtMs?: number;
  uptimeMs?: number;
};
type GatewayRunMetadata = {
  version?: string;
  commit?: string;
  runtime?: string;
  supervisor?: GatewayOwnerSupervisor;
  systemdInvocationId?: string;
};
type GatewayCrashRecord = GatewayRunMetadata & GatewayCrashEvidence & {
  bootId: string;
  pid: number;
  startedAtMs: number;
  detectedAtMs: number;
};
//#endregion
//#region src/agents/prepared-model-runtime.startup-status.d.ts
type PreparedModelRuntimeStartupStatus = Readonly<{
  degraded: boolean;
  pendingAgents: readonly string[];
  stage?: string;
}>;
//#endregion
//#region src/gateway/health/types.d.ts
type ProtocolHealth = Snapshot["health"];
type ProtocolPlugin = NonNullable<ProtocolHealth["plugins"]>;
type UnavailablePlugin = NonNullable<ProtocolPlugin["unavailable"]>[number];
type ChannelAccountHealthSummary = ChannelAccountSnapshot & {
  authAgeMs?: number | null;
  [key: string]: unknown;
};
type ChannelHealthSummary = ChannelAccountHealthSummary & {
  accounts?: Record<string, ChannelAccountHealthSummary>;
};
type AgentHealthSummary = NonNullable<ProtocolHealth["agents"]>[number];
type PluginHealthSummary = Omit<ProtocolPlugin, "unavailable"> & {
  unavailable?: Array<Omit<UnavailablePlugin, "diagnostic"> & {
    diagnostic: Omit<UnavailablePlugin["diagnostic"], "reason"> & {
      reason: PluginVerificationFailureReason;
    };
  }>;
};
/** Full gateway health payload consumed by `openclaw health`. */
type HealthSummary = ProtocolHealth & {
  recentCrashes?: readonly GatewayCrashRecord[];
  modelRuntime?: PreparedModelRuntimeStartupStatus;
  ok: true;
  ts: number;
  durationMs: number;
  plugins?: PluginHealthSummary;
  channels: Record<string, ChannelHealthSummary>;
  channelOrder: string[];
  channelLabels: Record<string, string>;
  heartbeatSeconds: number;
  agents: AgentHealthSummary[];
  sessions: NonNullable<ProtocolHealth["sessions"]>;
};
//#endregion
//#region src/gateway/live-text-continuity.d.ts
type LiveTextProjectionText = {
  snapshot: string;
  delta: string;
};
//#endregion
//#region src/gateway/mention-inbox-input.d.ts
type MentionCommittedInput = {
  sourceId: string;
  committedSource: {
    generation: string;
    sequence: number;
    timestamp: number;
  };
  sessionKey: string;
  agentId?: string;
  sessionId: string;
  messageId: string;
  senderProfileId: string;
  recipientProfileIds: readonly string[];
  excerpt?: string;
};
//#endregion
//#region src/gateway/mention-inbox.contracts.d.ts
/** Keep the Gateway context independent of its context-consuming Inbox implementation. */
type MentionInbox = {
  mentionable: (client: GatewayClient | null, input: UsersMentionableParams, publish: (result: Result$1<UsersMentionableResult, ErrorShape>) => undefined) => Promise<void>;
  /** @deprecated Await validateRecipientsAsync. Removed in a later release after stable deprecation. */
  validateRecipients: (client: GatewayClient | null, input: UsersMentionableParams, profileIds: readonly string[]) => Result$1<readonly string[], ErrorShape>;
  validateRecipientsAsync: (client: GatewayClient | null, input: UsersMentionableParams, profileIds: readonly string[]) => Promise<Result$1<readonly string[], ErrorShape>>;
  /** @deprecated Await listAsync and publish its current result. The synchronous adapter rejects calls; its signature is removed in a later release after stable deprecation. */
  list: (client: GatewayClient | null) => Result$1<MentionsListResult, ErrorShape>;
  /** @deprecated Await dismissAsync and publish its current result. The synchronous adapter rejects calls; its signature is removed in a later release after stable deprecation. */
  dismiss: (client: GatewayClient | null, ids: readonly string[]) => Result$1<MentionsListResult, ErrorShape>;
  listAsync: (client: GatewayClient | null, publish: (result: Result$1<MentionsListResult, ErrorShape>) => undefined) => Promise<void>;
  dismissAsync: (client: GatewayClient | null, ids: readonly string[], publish: (result: Result$1<MentionsListResult, ErrorShape>) => undefined) => Promise<void>;
  /** @deprecated Queues recording; await recordCommittedInputAsync for completion. */
  recordCommittedInput: (input: MentionCommittedInput) => void;
  /** @deprecated Await invalidateAsync. The synchronous adapter rejects calls; its signature is removed in a later release after stable deprecation. */
  invalidate: (sessionKey?: string) => void;
  recordCommittedInputAsync: (input: MentionCommittedInput) => Promise<void>;
  invalidateAsync: (sessionKey?: string) => Promise<void>;
  dispose: () => Promise<void>;
};
//#endregion
//#region src/gateway/portals/portal-http-proxy.d.ts
type PortalTarget = {
  kind: "local";
  port: number;
} | {
  kind: "worker";
  environmentId: string;
  ownerEpoch: number;
  remotePort: number;
  connect: () => Promise<Duplex>;
};
//#endregion
//#region src/gateway/portals/portal-service.d.ts
type GatewayPortalOpenParams = {
  targetPort: number;
  target?: PortalTarget;
  /** Revalidated before metadata mutation or publication after asynchronous listener startup. */
  assertCurrent?: () => void;
  /** Resource lifetime, independent of the operation or actor that created the link. */
  ownerSignal?: AbortSignal;
  /** Internal resource identity; scoped resources must not adopt a global portal's lifetime. */
  resourceOwnerKey?: string;
  /** Ownership transfers to open; unused targets are released even when it rejects or reuses a portal. */
  onClose?: () => Promise<void> | void;
  origin?: string;
  title?: string;
  description?: string;
  path?: string;
};
type GatewayPortalService = Omit<ReturnType<typeof createGatewayPortalService>, "startIngress">;
/** Creates the gateway-lifetime registry and per-portal transport listeners. */
declare function createGatewayPortalService(params: {
  httpBindHosts: readonly string[];
  tlsOptions?: TlsOptions;
  httpServers: Server[];
  ingress?: GatewayPortalIngressConfig;
  managedTailscale?: boolean;
  gatewayOrigins?: readonly string[];
}): {
  startIngress: () => Promise<void>;
  open: (input: GatewayPortalOpenParams) => Promise<{
    id: string;
    title: string;
    port: number;
    listenPort: number;
    publicUrl: string;
    exposure?: {
      kind: "loopback-only" | "non-loopback";
      browserReachability: "unverified";
    } | undefined;
    path?: string | undefined;
    description?: string | undefined;
    origin?: string | undefined;
    createdAtMs: number;
    tokenQuery: string;
    url: string;
  }>;
  list: () => {
    id: string;
    title: string;
    port: number;
    listenPort: number;
    publicUrl: string;
    exposure?: {
      kind: "loopback-only" | "non-loopback";
      browserReachability: "unverified";
    } | undefined;
    path?: string | undefined;
    description?: string | undefined;
    origin?: string | undefined;
    createdAtMs: number;
    tokenQuery?: string | undefined;
    url?: string | undefined;
  }[];
  listWorkerPortals: (environmentId: string, ownerEpoch: number, resourceOwnerKey?: string) => {
    id: string;
    title: string;
    port: number;
    listenPort: number;
    publicUrl: string;
    exposure?: {
      kind: "loopback-only" | "non-loopback";
      browserReachability: "unverified";
    } | undefined;
    path?: string | undefined;
    description?: string | undefined;
    origin?: string | undefined;
    createdAtMs: number;
    tokenQuery?: string | undefined;
    url?: string | undefined;
  }[];
  close: (id: string, assertCurrent?: () => void) => Promise<void>;
  closeWorkerPortals: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  closeAll: () => Promise<void>;
};
//#endregion
//#region src/gateway/question-session-access.types.d.ts
/** Current caller and session facts supplied by the question access owner. */
type QuestionClientAuthorization = (client: GatewayClient | null, target?: {
  agentId: string;
  canonicalKey: string;
  entry: SessionEntry;
} | null) => boolean;
type QuestionSessionCurrentRead = {
  readonly target: {
    agentId: string;
    canonicalKey: string;
    storePath: string;
    entry: {
      sessionId: string;
      lifecycleRevision?: string;
      incognito?: boolean;
    };
  } | null;
  readonly read: {
    database: {
      path: string;
    };
    result: {
      databaseIdentity?: {
        identity: string;
        birthtime?: string;
      };
    };
  };
  assertCurrent: () => void;
};
/** Original source and database generation survive until the manager retires this entry. */
type QuestionSessionAccess = {
  readonly agentId: string;
  readonly sessionKey: string;
  /** Pure original-person selection, before session reads or liveness transitions. */
  canSelect: (client: GatewayClient | null) => boolean;
  assertSourceCurrent: () => void;
  assertCurrent: (read: QuestionSessionCurrentRead) => void;
  release: () => void;
};
//#endregion
//#region src/gateway/question-manager.d.ts
type QuestionManagerRequest = {
  id?: string;
  questions: Question[];
  agentId?: string;
  sessionKey?: string;
  runId?: string;
  timeoutMs: number;
  onResolved?: ((event: QuestionResolvedEvent, observation: QuestionObservation) => void) | ((event: QuestionResolvedEvent, observation: QuestionObservation) => Promise<void>);
  /** Host-owned human decision boundary; never accepted from wire data. */
  authorizeClient?: QuestionClientAuthorization;
  sessionAccess?: QuestionSessionAccess;
  isRequesterActive?: () => boolean;
  requesterRun?: OperationalRunInstanceRef;
  /** Trusted handler binds the run; the manager owns expiry and terminal release. */
  registerHumanInputWait?: (isPending: () => boolean) => ((resolved: boolean) => void) | undefined;
};
/** Private entry identity. Never reselect a successor by its public question id. */
type QuestionObservation = {
  readonly record: QuestionRecord;
  readonly ordinary: boolean;
  readonly sessionAccess?: QuestionSessionAccess;
  readonly authorizeClient?: QuestionClientAuthorization;
  isCurrent: () => boolean;
  refreshRequester: () => void;
};
/** Process-local lifecycle owner for pending questions. */
declare class QuestionManager {
  private readonly scheduler;
  private readonly onPublicationError?;
  private readonly entries;
  private closed;
  private readonly publications;
  private readonly scheduleId;
  constructor(scheduler: GatewayScheduler, onPublicationError?: (() => void) | undefined);
  drain(): Promise<void>;
  request(params: QuestionManagerRequest): QuestionRecord;
  get(id: string): QuestionRecord | null;
  /** Observation only: unlike get(), this cannot expire or cancel and recursively broadcast. */
  observe(id: string, expectedRecord?: QuestionRecord): QuestionObservation | null;
  private observeEntry;
  private refreshRequester;
  /** Called by the Gateway's existing authority-close observer. */
  cancelClosedAuthorities(closedRun?: {
    runId: string;
    instanceId?: string;
  }): void;
  list(include?: (record: QuestionRecord) => boolean): QuestionRecord[];
  /** Re-enters only the still-pending question's original admitted root. */
  runPendingContinuation<T>(id: string, run: () => Promise<T>): Promise<T> | null;
  waitAnswer(id: string, timeoutMs?: number, includeResolutionId?: boolean): Promise<QuestionWaitAnswerResult>;
  resolve(id: string, answers: QuestionAnswers, resolvedBy?: string, options?: {
    commit?: () => void;
    resolutionId?: string;
  }): QuestionResolveResult;
  /** Async persistence keeps the v2026.8.1 SDK's ordinary resolve() synchronous. */
  resolveWithCommit(id: string, answers: QuestionAnswers, resolvedBy: string | undefined, options: {
    commit: (assertCurrent: () => void) => Promise<void>;
    resolutionId?: string;
  }): Promise<QuestionResolveResult>;
  cancel(id: string, resolvedBy?: string): QuestionResolveResult;
  private cancelEntry;
  /** Retires this Gateway's owner only after received mutations have joined. */
  close(): void;
  /** Reusable on open owners (v2026.8.1 SDK context); never reopens a closed owner. */
  reset(): void;
  private releaseEntry;
  private requireEntry;
  private requirePendingEntry;
  /** Validates answers against stored questions and returns them in canonical form. */
  private validateAnswers;
  private invalidAnswer;
  private expire;
  private finish;
}
//#endregion
//#region src/chat/canvas-render.d.ts
type CanvasSurface = "assistant_message" | "node_panel";
type CanvasSandbox = "strict" | "scripts";
type McpAppPreviewDescriptor = {
  viewId: string;
  serverName?: string;
  toolName?: string;
  uiResourceUri?: string;
  toolCallId?: string;
  originSessionKey?: string;
  resultMetaState?: "unavailable";
};
type CanvasPreview = {
  kind: "canvas";
  surface: CanvasSurface;
  render: "url";
  title?: string;
  preferredHeight?: number;
  url?: string;
  viewId?: string;
  className?: string;
  style?: string;
  sandbox?: CanvasSandbox;
  boardWidgetName?: string;
  mcpApp?: McpAppPreviewDescriptor;
};
/** Extracts a canvas preview from a JSON-shaped tool or assistant payload. */
declare function extractCanvasFromText(outputText: string | undefined): CanvasPreview | undefined;
//#endregion
//#region src/gateway/chat-display-projection.canvas.d.ts
type ChatCanvasPreview = {
  preview: NonNullable<ReturnType<typeof extractCanvasFromText>>;
  rawText: string | null;
};
type ChatCanvasBlock = ChatCanvasPreview & {
  type: "canvas";
};
//#endregion
//#region src/gateway/agent-event-assistant-text.d.ts
type AssistantTextInput = {
  text?: string;
  delta?: string;
  itemId?: string;
  occurrenceId?: string;
  replace?: boolean;
  replaceable?: boolean;
  managedMediaUrls?: string[];
};
type AssistantTextSnapshot = {
  text: string;
  scope?: {
    itemId: string;
    prefix: string;
    boundaryNewlines: number;
    separatorLength: number;
  };
};
/** Merge item snapshots without imposing a transport's display or wire limit. */
declare function mergeAssistantText(previous: AssistantTextSnapshot, input: AssistantTextInput, unkeyed: "live" | "append-only"): AssistantTextSnapshot & {
  /** Present only when this merge proves an append to its input snapshot. */
  appendedText?: string;
};
//#endregion
//#region src/gateway/live-chat-projector.d.ts
/** One run-owned display chain; replacements rebuild every syntax and visibility probe. */
declare function createLiveAssistantTextProjection(options?: {
  managedMediaUrls?: readonly string[];
  final?: boolean;
}): {
  readonly source: string;
  append: (delta: string, preparedSource?: string) => {
    text: string;
    suppress: boolean;
    delta: string | null;
  };
  replace: (text: string) => {
    text: string;
    suppress: boolean;
    delta: string | null;
  };
};
//#endregion
//#region src/gateway/server-chat-buffer.d.ts
type ChatRunBufferState = {
  rawBuffer?: string;
  rawOffset?: number;
  /** Positions are absolute; null ends retain identity facts after a source replacement. */
  assistantItems?: Map<string | symbol | undefined, {
    committed?: true;
    /** False while saved history has not taken over this live occurrence. */
    published?: boolean;
    start?: number;
    end?: number | null;
    scope?: number;
    publishThinkingReceipt?: (messageId: string, sessionKey?: string, sessionId?: string) => void;
  }>;
  assistantScope?: AssistantTextSnapshot["scope"];
  assistantScopeOffset?: number;
  assistantOccurrenceId?: string;
  managedMediaUrls?: Set<string>;
  display?: {
    projector: ReturnType<typeof createLiveAssistantTextProjection>;
    current: ReturnType<ReturnType<typeof createLiveAssistantTextProjection>["replace"]>;
    pendingRawDelta?: string | null;
    reset?: boolean;
    unsentDelta: string | null;
    sentText?: string;
  };
};
type BufferInput = Parameters<typeof mergeAssistantText>[1];
declare const updateBuffer: (record: ChatRunBufferState, incoming: BufferInput, source?: AgentAssistantSourceReceipt) => string;
//#endregion
//#region src/gateway/server-chat-progress-snapshot.d.ts
type ChatRunProgressSnapshot = {
  events: AgentEventPayload[];
  byteLength: number;
  lastSeq: number;
};
//#endregion
//#region src/gateway/server-chat-tool-recipients.d.ts
type ChatRunToolRecipientState = {
  connIds: Set<string>;
  updatedAt: number;
  finalizedAt?: number;
};
//#endregion
//#region src/gateway/server-chat-state.d.ts
type ChatRunTiming = {
  ackedAtMs: number;
  connId: string;
  dispatchStartedAtMs?: number;
  firstAssistantEventSent?: boolean;
  receivedAtMs: number;
};
type ChatRunRegistration = {
  sessionKey: string;
  agentId?: string;
  clientRunId: string;
  chatSendTiming?: ChatRunTiming;
};
type ChatRunEntry = ChatRunRegistration & {
  registeredSequence: number;
};
type ChatAbortMarker = {
  abortedAtMs: number;
  sequence: number;
};
type BufferedAgentEvent = {
  sessionKey?: string;
  agentId?: string;
  controlUiVisible?: boolean;
  isCurrent?: () => boolean;
  payload: AgentEventPayload & {
    spawnedBy?: string;
  };
};
type ChatRunPlanSnapshot = {
  steps: AgentPlanStep[];
  explanation?: string;
};
type ChatRunAgentTextState = {
  lastSentAt?: number;
  bufferedEvent?: BufferedAgentEvent;
  snapshot?: {
    text: string;
    itemId?: string;
  };
};
type PendingLiveTextFlush = {
  timer: NodeJS.Timeout;
  flush: () => void;
};
type ChatRunRecord = ChatRunBufferState & {
  lastActivityAt: number;
  registrations?: ChatRunEntry[];
  buffer?: string;
  bufferIsCurrent?: () => boolean;
  releaseBufferAuthority?: () => void;
  /** Retire queued connection snapshots when this buffering generation is cleared. */
  liveTextGroup?: AbortController;
  liveTextEpoch?: object;
  planSnapshot?: ChatRunPlanSnapshot;
  progressSnapshot?: ChatRunProgressSnapshot;
  canvasBlocks?: ChatCanvasBlock[];
  deltaSentAt?: number;
  agentText?: Partial<Record<"assistant" | "thinking" | "preamble" | "answer_candidate", ChatRunAgentTextState>>;
  abortMarker?: ChatAbortMarker;
  toolRecipient?: ChatRunToolRecipientState;
  /** Fixed-deadline trailing wake-up owned by this run's buffered state. */
  pendingTextFlushes?: Partial<Record<"chat" | "agent", PendingLiveTextFlush>>;
};
type ChatRunRegistry = {
  add: (sessionId: string, entry: ChatRunRegistration) => void;
  peek: (sessionId: string) => ChatRunEntry | undefined;
  shift: (sessionId: string) => ChatRunEntry | undefined;
  remove: (sessionId: string, clientRunId: string, sessionKey?: string) => ChatRunEntry | undefined;
};
type ChatRunState = ReturnType<typeof createChatRunState>;
/** Create the single record map used by Gateway chat-run runtime state. */
declare function createChatRunState(isConnectionActive?: (connId: string) => boolean): {
  runs: Map<string, ChatRunRecord>;
  registry: ChatRunRegistry;
  toolEventRecipients: {
    add: (runId: string, connId: string) => void;
    removeConnection: (connId: string) => void;
    get: (runId: string) => ReadonlySet<string> | undefined;
    markFinal: (runId: string) => void;
    pruneExpired: (now?: number) => void;
  };
  /** Acquire mutable state and record activity; readers use runs.get. */
  getOrCreate: (runId: string) => ChatRunRecord;
  resolveBuffer: (runId: string, options?: {
    final?: boolean;
  }) => {
    text: string;
    suppress: boolean;
  } & {
    displayText?: string;
  };
  captureFinalBuffer: (runId: string) => () => {
    text: string;
    suppress: boolean;
  } & {
    displayText?: string;
  };
  updateBuffer: (runId: string, input: Parameters<typeof updateBuffer>[1], source?: AgentAssistantSourceReceipt) => string;
  retireBuffer: (runId: string, itemIds: readonly string[]) => boolean;
  retireSource: (runId: string, source: AgentAssistantSourceReceipt) => boolean;
  takeBufferDelta: (runId: string, text: string) => {
    deltaText: string;
    replace: true;
  } | {
    replace?: undefined;
    deltaText: string;
  } | undefined;
  flushPendingText: (runId: string) => void;
  hasAbortMarker: (runId: string) => boolean;
  deleteAbortMarker: (runId: string) => void;
  recordProgressEvent: (runId: string, event: AgentEventPayload, mode?: "full" | "summary") => void;
  clearRun: (runId: string) => void;
  clear: () => void;
};
type SessionMessageSubscriberRegistry = {
  subscribe: (connId: string, sessionKey: string, opts?: {
    includeApprovals?: boolean;
    provisional?: boolean;
    mode?: "narration";
    subscriptionId?: string;
  }) => SessionMessageSubscription | undefined;
  unsubscribe: (connId: string, sessionKey: string, subscriptionId?: string) => void;
  unsubscribeAll: (connId: string) => void;
  get: (sessionKey: string) => ReadonlySet<string>;
  getApprovals: (sessionKey: string) => ReadonlySet<string>;
  getNarration: (sessionKey: string) => ReadonlySet<string>;
  onChange: (listener: (sessionKey: string, connId: string, baselineOnly?: true) => void) => () => void;
};
type SessionMessageSubscription = (() => void) & {
  commit: () => void;
};
//#endregion
//#region src/gateway/server-cron-contract.d.ts
type GatewayCronServiceContract = CronServiceContract & {
  /** Borrow the current resident jobs without loading storage. */
  getLoadedJobs(): readonly CronStoredJob[] | undefined;
  /** Selected opaque partition after a list/job read prepares the serving cron owner. */
  getStoreKey?(): string;
  /** Cancel exact current definitions under the serving scheduler's operation lock. */
  quiesceJobs(jobs: readonly {
    id: string;
    revision: string;
  }[], commitGuard: (cancel: () => void) => void | Promise<void>): Promise<void>;
  /** Remove an owned declarative job family from obsolete SQLite store partitions. */
  removeStaleJobFamily(family: {
    declarationKey: string;
    name: string;
    ownerPluginTag: string;
  }, opts?: {
    commitGuard?: () => void;
  }): Promise<number>;
  /** True once an accepted manual run wrote its terminal history row; false on timeout or abort. */
  waitForManualRun(runId: string, timeoutMs: number, signal?: AbortSignal): Promise<boolean>;
  readScratch(id: string, options?: {
    assertCurrent?: () => void;
    signal?: AbortSignal;
  }): Promise<CronJobScratchState>;
  writeScratch(id: string, params: {
    content: string | null;
    expectedRevision?: number;
    sourceSha256?: string;
    commitGuard?: () => void;
  }): Promise<CronJobScratchWriteResult>;
  /** Serialize agent-job removal with the roster commit and restore on failure. */
  removeAgentJobsTransactional<T>(agentId: string, commit: () => Promise<T>): Promise<T>;
  /** Temporarily disarm ticks without running startup recovery on resume. */
  pauseScheduling(): void;
  resumeScheduling(): void;
  /** Scheduler-owned work not represented by active cron run markers. */
  getSuspensionBlockerCount?(): number;
  /** Materialize lazy cron dependencies before a synchronous operator wake. */
  prepareWake?(): Promise<void>;
  /** Stop cron and await scheduler-owned child process teardown. */
  stopAndDrain?(): Promise<void>;
};
//#endregion
//#region src/gateway/server-instance-runtime.types.d.ts
type GatewayInstanceAgentDispatchOptions = {
  /** Host-issued source authority for independently accepted native work. */
  operatorRunAuthority?: AdmittedRunOperatorAuthority;
  agentToolCaller?: NonNullable<GatewayClient["internal"]>["agentToolCaller"];
  /** Exact process-local source reserved by a durable lifecycle owner. */
  controllerInput?: SessionControllerInput;
  /** Host-owned input semantics, never supplied by wire request parameters. */
  replyExpectation?: ReplyExpectation;
  assertAdmissionCurrent?: () => void;
  /** Live source permission retained by accepted execution, independently of its admission claim. */
  executionSource?: SessionSourceAssertion;
  /** Refresh source facts immediately before dispatch; the accepted turn owns execution. */
  prepareDispatchCurrent?: () => Promise<void>;
  allowModelOverride?: boolean;
  allowSyntheticModelOverride?: boolean;
  allowSyntheticCronRunContinuation?: boolean;
  delegatedToolPolicyHandoff?: SubagentCompletionToolHandoffRegistration;
  expectFinal?: boolean;
  /** Instance-owned dispatch always uses a synthetic client. */
  forceSyntheticClient?: boolean;
  runtimeContextFragments?: RuntimeContextFragment[];
  /** Keep runtime error payloads (timeouts, provider failures) out of the delivered reply. */
  internalDeliverySuppressErrors?: boolean;
  onAccepted?: (payload: unknown) => void;
  onStartOwner?: (owner: AgentTurnStartOwner) => void;
  onExecutionStarted?: () => void;
  onSignalAbort?: () => Promise<void> | void;
  scopes?: string[];
  signal?: AbortSignal;
  syntheticScopes?: string[];
};
type GatewayApprovalEventPublisher = {
  /** @deprecated Use publishRequestedAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
  publishRequested: (kind: ChannelApprovalKind, request: unknown) => number;
  publishRequestedAsync?: (kind: ChannelApprovalKind, request: unknown) => Promise<number>;
  publishResolved: (kind: ChannelApprovalKind, resolved: unknown) => void;
};
type GatewayLifecycleSessionMethod = "chat.history" | "chat.abort" | "sessions.delete";
type GatewayLifecycleTypingParams = {
  agentId?: string;
  runId: string;
  channel: string;
  to: string;
  accountId?: string;
  threadId?: string | number;
  isCurrent: (cfg: OpenClawConfig) => boolean;
};
type GatewayLifecycleRuntime = {
  dispatchSessionMethod: <T = unknown>(method: GatewayLifecycleSessionMethod, params: unknown, options?: {
    timeoutMs?: number;
    signal?: AbortSignal;
    assertCurrent?: () => void;
  }) => Promise<T>;
  startTyping?: (params: GatewayLifecycleTypingParams) => () => void;
  dispatchAgent: <T = unknown>(params: AgentRunRequest, timeoutMs?: number, options?: GatewayInstanceAgentDispatchOptions) => Promise<T>;
  waitForAgent: <T = unknown>(params: AgentWaitParams, timeoutMs?: number, signal?: AbortSignal) => Promise<T>;
  sendNotice: (params: {
    channel: string;
    to: string;
    accountId?: string;
    threadId?: string | number;
    text: string;
    idempotencyKey: string;
    isCurrent?: (cfg: OpenClawConfig) => boolean;
  }) => Promise<{
    /** True when delivery produced zero platform results (policy/channel suppression). */
    suppressed: boolean;
  }>;
};
//#endregion
//#region src/gateway/server-plugin-reload-status.types.d.ts
/** Pending or failed plugin replacement, as recorded by the Gateway plugin runtime generation. */
type GatewayPluginReloadStatus = Readonly<{
  phase: "reloading" | "recovering" | "failed";
  pluginIds: string[];
  deadlineAtMs?: number;
  reason?: string;
}>;
//#endregion
//#region src/gateway/server-shared.d.ts
type DedupeEntry = {
  ts: number;
  ok: boolean;
  /** Optional effectful-request fingerprint for methods with caller-supplied operation ids. */
  requestIdentity?: string;
  /** The request crossed its effect owner's acceptance boundary. */
  effectAccepted?: true;
  /** Retain source privacy for diagnostic replay after the live session binding is gone. */
  incognito?: true;
  payload?: unknown;
  error?: ErrorShape;
};
//#endregion
//#region packages/gateway-protocol/src/schema/runtime-vitals.d.ts
/** Process observations shared by health snapshots and host resource polling. */
declare const GatewayEventLoopHealthSchema: Type$1.TObject<{
  degraded: Type$1.TBoolean;
  degradedSinceMs: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
  reasons: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"event_loop_delay">, Type$1.TLiteral<"event_loop_utilization">, Type$1.TLiteral<"cpu">]>>;
  intervalMs: Type$1.TNumber;
  delayP99Ms: Type$1.TNumber;
  delayMaxMs: Type$1.TNumber;
  utilization: Type$1.TNumber;
  cpuCoreRatio: Type$1.TNumber;
  cpuBreakdown: Type$1.TOptional<Type$1.TObject<{
    mainThreadCoreRatio: Type$1.TOptional<Type$1.TNumber>;
    workerCoreRatio: Type$1.TOptional<Type$1.TNumber>;
    /** Estimated process residual after main and tracked worker counters. */
    otherThreadsCoreRatio: Type$1.TOptional<Type$1.TNumber>;
    hostUtilization: Type$1.TOptional<Type$1.TNumber>;
    hostCpuCount: Type$1.TOptional<Type$1.TInteger>;
  }>>;
}>;
//#endregion
//#region src/gateway/server/event-loop-health.d.ts
type GatewayEventLoopHealth = SchemaContract<Static<typeof GatewayEventLoopHealthSchema>> & {
  degradedSinceMs: number | null;
};
//#endregion
//#region src/infra/child-runtime-viability.d.ts
type ChildRuntimeViability = {
  execPath: string;
  available: boolean;
};
//#endregion
//#region src/gateway/server/readiness.types.d.ts
type ReadinessResult = {
  ready: boolean;
  coreReady: boolean;
  failing: string[];
  suppressed?: string[];
  uptimeMs: number;
  eventLoop?: GatewayEventLoopHealth;
  pluginReload?: GatewayPluginReloadStatus;
  agentDatabases?: readonly AgentDatabaseAdmissionRefusal[];
  stateDatabase?: {
    reason: string;
  };
};
type ReadinessChecker = (childRuntime?: ChildRuntimeViability) => ReadinessResult;
//#endregion
//#region src/gateway/session-row-delta-fields.d.ts
type SessionRowDeltaFields = {
  readonly fingerprints: ReadonlyMap<string, number | boolean | null | bigint>;
  readonly fieldCount: number;
};
type SessionRowDelta = {
  set: Record<string, unknown>;
  remove: string[];
};
/** A publication owns patches; identical recipient baselines share comparison work. */
declare function createSessionRowDeltaDiffer(): (previous: SessionRowDeltaFields, current: SessionRowDeltaFields, row: Record<string, unknown>) => SessionRowDelta;
//#endregion
//#region src/gateway/session-ancestor-references.d.ts
type DeliveredRow = {
  version: number;
  fields: SessionRowDeltaFields;
  bytes: number;
};
type DeliveredAncestor = {
  key: string;
  content: string;
  chars: number;
  revision: string;
};
type PreparedAncestor = {
  row: SessionRow;
  identity: string;
  content: string;
  chars: number;
  certified?: WeakRef<SessionRow>;
};
/** Prepare immutable viewer content once, before consulting connection delivery history. */
declare function prepareSessionAncestor(row: SessionRow): PreparedAncestor;
/** Connection-owned, bounded history of exactly the presented wire content. */
declare class ConnectionSessionRows {
  #private;
  get history(): object;
  clear(cause?: SessionEventRowsResetCause, histories?: Map<object, object>): void;
  clearAncestors(histories?: Map<object, object>): void;
  forget(key: string, histories?: Map<object, object>): void;
  /** Equal histories include both LRU orders, byte charges, certificates and wire versions. */
  prepareDelivery(row: SessionRow, ancestors: ReturnType<typeof prepareSessionAncestor>[] | undefined, revision?: `${string}-${string}-${string}-${string}-${string}`, diff?: ReturnType<typeof createSessionRowDeltaDiffer>, certifyAncestors?: boolean): {
    ancestor: {
      ancestorSessions: {
        key: string;
        rowMode?: "compact" | "dashboard" | "sidebar" | undefined;
        sharedFacts?: number[] | undefined;
        sessionId?: string | undefined;
        lifecycleRevision?: string | undefined;
        sessionModelRevision?: string | undefined;
        incognito?: true | undefined;
        kind: "direct" | "global" | "group" | "unknown";
        label?: string | undefined;
        autoLabel?: string | undefined;
        icon?: string | undefined;
        color?: string | undefined;
        channelAvatarUrl?: string | undefined;
        boardFace?: "chat" | "dashboard" | undefined;
        hasBoard?: boolean | undefined;
        boardPresentation?: "expanded" | "split" | undefined;
        displayName?: string | undefined;
        titlePending?: boolean | undefined;
        derivedTitle?: string | undefined;
        lastMessagePreview?: string | undefined;
        lastAssistantMessage?: {
          text: string;
          timestamp: number;
        } | undefined;
        channel?: string | undefined;
        classification?: string | undefined;
        agentId?: string | undefined;
        accountId?: string | undefined;
        peerKind?: string | undefined;
        isMain?: boolean | undefined;
        isBackground?: boolean | undefined;
        isDock?: boolean | undefined;
        chatType?: "channel" | "direct" | "group" | undefined;
        activitySummary?: {
          canEnsure?: boolean | undefined;
          text?: string | undefined;
          updatedAt?: number | undefined;
          state: "current" | "stale" | "unavailable" | "updating";
        } | undefined;
        updatedAt?: number | null | undefined;
        snapshotAt?: number | undefined;
        ancestorRevision?: string | undefined;
        hiddenFromInvolvingMe?: boolean | undefined;
        archived?: boolean | undefined;
        archivedAt?: number | undefined;
        archivedBy?: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        } | undefined;
        archiveReason?: "active-session-cap" | "age-retention" | "manual" | "restart-recovery" | "stale-dashboard" | undefined;
        pinned?: boolean | undefined;
        sidebarRoot?: boolean | undefined;
        pinnedAt?: number | undefined;
        snoozedUntil?: number | undefined;
        snoozedAt?: number | undefined;
        unread?: boolean | undefined;
        lastReadAt?: number | undefined;
        markedUnreadAt?: number | undefined;
        lastActivityAt?: number | undefined;
        lastInteractionAt?: number | undefined;
        status?: "done" | "failed" | "interrupted" | "killed" | "queued" | "running" | "timeout" | undefined;
        lastRunError?: string | undefined;
        suppressErrorNotice?: boolean | undefined;
        providerReview?: {
          id: string;
          runId: string;
          explanation?: string | undefined;
          continuationMessage?: string | undefined;
          canContinue: boolean;
        } | undefined;
        lastRunId?: string | undefined;
        activeLeafEntryId?: string | null | undefined;
        spawnedBy?: string | undefined;
        parentSessionKey?: string | undefined;
        parentSessionId?: string | undefined;
        controlOwnerSessionKey?: string | undefined;
        childOwnerSessionKeys?: string[] | undefined;
        childSessions?: string[] | undefined;
        forkedFromParent?: boolean | undefined;
        spawnDepth?: number | undefined;
        subagentRole?: "leaf" | "orchestrator" | undefined;
        subagentControlScope?: "children" | "none" | undefined;
        swarmGroupId?: string | undefined;
        swarm?: {
          groups: {
            groupId: string;
            createdAt: number;
            children?: {
              sessionKey: string;
              status: "done" | "failed" | "queued" | "running";
            }[] | undefined;
            queued: number;
            running: number;
            done: number;
            failed: number;
          }[];
          otherActiveGroups: number;
        } | undefined;
        deviceFolder?: {
          deviceId: string;
          path: string;
        } | undefined;
        worktree?: {
          id: string;
          branch: string;
          repoRoot: string;
        } | undefined;
        repositoryWorkspaceId?: string | undefined;
        repository?: {
          url: string;
          ref?: string | undefined;
          branch: string;
        } | undefined;
        execNode?: string | undefined;
        execCwd?: string | undefined;
        spawnedWorkspaceDir?: string | undefined;
        spawnedCwd?: string | undefined;
        projectId?: string | undefined;
        workspaceDir?: string | undefined;
        cyberAccessProgram?: "daybreak_blue" | "daybreak_red" | "standard" | undefined;
        permissionMode?: "full" | "guarded" | "read-only" | "workspace" | undefined;
        communication?: {
          send?: "always" | "ask" | "never" | undefined;
          receive?: "always" | "ask" | "never" | undefined;
        } | undefined;
        effectiveCommunication?: {
          send: "always" | "ask" | "never";
          receive: "always" | "ask" | "never";
        } | undefined;
        sandboxMode?: "off" | undefined;
        nativeRuntimeConsent?: string | undefined;
        permissionModePending?: boolean | undefined;
        sessionRoot?: string | undefined;
        createdVia?: "channel" | "cron" | "internal" | "operator" | "plugin" | "run" | "spawn" | "talk" | undefined;
        createdSurface?: "plugin-dock" | undefined;
        createdActor?: {
          type: "agent" | "human" | "system";
          id?: string | undefined;
          label?: string | undefined;
          avatarUrl?: string | undefined;
          identity?: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          } | undefined;
        } | undefined;
        owner?: {
          actor: {
            type: "agent" | "human" | "system";
            id?: string | undefined;
            label?: string | undefined;
            avatarUrl?: string | undefined;
            identity?: {
              type: "profile";
              id: string;
            } | {
              type: "agent";
              id: string;
            } | {
              type: "remote";
              pluginId: string;
              domain: string;
              idKind: string;
              id: string;
            } | {
              type: "observation";
              pluginId: string | null;
              accountId: string | null;
              senderKind: "bot" | "human" | "unknown";
              id: string;
            } | {
              type: "legacy";
              actorType: string;
              source: string | null;
              id: string;
            } | undefined;
          };
          assignedBy?: {
            type: "agent" | "human" | "system";
            id?: string | undefined;
            label?: string | undefined;
            avatarUrl?: string | undefined;
            identity?: {
              type: "profile";
              id: string;
            } | {
              type: "agent";
              id: string;
            } | {
              type: "remote";
              pluginId: string;
              domain: string;
              idKind: string;
              id: string;
            } | {
              type: "observation";
              pluginId: string | null;
              accountId: string | null;
              senderKind: "bot" | "human" | "unknown";
              id: string;
            } | {
              type: "legacy";
              actorType: string;
              source: string | null;
              id: string;
            } | undefined;
          } | undefined;
          assignedAt?: number | undefined;
        } | undefined;
        participants?: {
          identity: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          };
          label?: string | undefined;
          avatarUrl?: string | undefined;
        }[] | undefined;
        expandedParticipants?: {
          identity: {
            type: "profile";
            id: string;
          } | {
            type: "agent";
            id: string;
          } | {
            type: "remote";
            pluginId: string;
            domain: string;
            idKind: string;
            id: string;
          } | {
            type: "observation";
            pluginId: string | null;
            accountId: string | null;
            senderKind: "bot" | "human" | "unknown";
            id: string;
          } | {
            type: "legacy";
            actorType: string;
            source: string | null;
            id: string;
          };
          label?: string | undefined;
          avatarUrl?: string | undefined;
        }[] | undefined;
        participantCount?: number | undefined;
        visibility?: "draft" | "read-only" | "shared" | "suggest" | undefined;
        sharingRole?: "admin" | "member" | "owner" | "viewer" | undefined;
        sendDisabledReason?: string | null | undefined;
        createdAt?: number | undefined;
        forkSource?: {
          sessionKey: string;
          sessionId: string;
          entryId?: string | undefined;
        } | undefined;
        previousSessionId?: string | undefined;
        inputTokens?: number | undefined;
        outputTokens?: number | undefined;
        usageReport?: {
          state: "available" | "unavailable";
        } | undefined;
        totalTokens?: number | undefined;
        totalTokensFresh?: boolean | undefined;
        contextTokens?: number | undefined;
        estimatedCostUsd?: number | undefined;
        model?: string | undefined;
        modelProvider?: string | undefined;
        activeModel?: string | undefined;
        activeModelProvider?: string | undefined;
        modelOverrideSource?: "auto" | "inherited" | "user" | null | undefined;
        toolOverrides?: {
          mcpServers?: Record<string, boolean> | undefined;
          mcpToolsDeny?: Record<string, string[]> | undefined;
          skills?: Record<string, boolean> | undefined;
          webSearch?: boolean | undefined;
        } | undefined;
      }[];
      ancestorSessionRefs?: {
        key: string;
        sessionId?: string | undefined;
        agentId?: string | undefined;
        revision: string;
        snapshotAt: number;
      }[] | undefined;
      updates: Map<string, DeliveredAncestor | undefined> | undefined;
    } | undefined;
    rows: {
      wire: SessionRowWire[];
      encoded: (string | undefined)[];
      updates: Map<string, DeliveredRow | undefined>;
      count: number;
      bytes: number;
      version: number;
      generations: number;
      evictions: number;
    } | undefined;
    key: string;
    certifyAncestors: boolean;
    before: object;
    after: {};
  };
  deliver(plan: ReturnType<ConnectionSessionRows["prepareDelivery"]>): void;
}
//#endregion
//#region src/gateway/terminal/launch.d.ts
type TerminalLaunchBlock = {
  kind: "disabled";
} | {
  kind: "owner-required";
  message: string;
} | {
  kind: "unknown-agent";
  agentId: string;
} | {
  kind: "sandboxed";
  agentId: string;
  mode: "all";
};
type TerminalLaunchPlan = {
  agentId: string;
  cwd: string;
  shell: string;
  args: string[];
  initialCommand?: string[];
  cwdOverride?: string;
};
type TerminalLaunchResolution = {
  ok: true;
  plan: TerminalLaunchPlan;
} | {
  ok: false;
  block: TerminalLaunchBlock;
};
//#endregion
//#region src/infra/terminal-file-upload.d.ts
type TerminalUploadFile = {
  name: string;
  contentBase64: string;
  /** Host-only client policy, carried unchanged through the terminal staging adapter. */
  assertCommitAllowed?: () => void;
};
type TerminalUploadResult = TerminalUploadResult$1;
//#endregion
//#region src/process/terminal-pty.d.ts
/** Live PTY handle shared by gateway terminals and node-host commands. */
type TerminalPtySubscription = {
  dispose(): void;
};
type TerminalPtyHandle = {
  pid: number;
  write(data: string | Buffer): void;
  resize(cols: number, rows: number): void;
  pause(): void;
  resume(): void;
  onData(listener: (chunk: string) => void): TerminalPtySubscription | void;
  onExit(listener: (event: {
    exitCode: number;
    signal?: number;
  }) => void): TerminalPtySubscription | void;
  kill(signal?: string): void;
};
type TerminalPtySpawnParams = {
  file: string;
  args: string[];
  cwd?: string;
  env?: Record<string, string>;
  name?: string;
  cols: number;
  rows: number;
};
declare function spawnTerminalPty(params: TerminalPtySpawnParams, lifecycle?: {
  abortSignal?: AbortSignal;
  assertCurrent?: () => void;
  initiateSpawn?: SpawnInitiation;
}): Promise<TerminalPtyHandle>;
//#endregion
//#region src/gateway/terminal/backend.d.ts
type TerminalBackendExit = {
  exitCode?: number;
  signal?: number;
  error?: string;
};
interface TerminalBackend {
  write(data: string): void;
  resize(cols: number, rows: number): void;
  pause(): void;
  resume(): void;
  kill(): void;
  onData(callback: (data: string) => void): void;
  onExit(callback: (exit: TerminalBackendExit) => void): void;
}
//#endregion
//#region src/gateway/terminal/session-manager.types.d.ts
type TerminalEventSink = (connId: string, event: string, payload: unknown) => void;
type AgentTerminalOwner = {
  kind: "agent";
  agentSessionKey: string;
  agentSessionId: string;
  agentId: string;
};
type TerminalOwner = {
  kind: "conn";
  connId: string;
} | AgentTerminalOwner;
type AgentTerminalSessionDrain = {
  drained: Promise<void>;
  hasWork(): boolean;
  release(): void;
};
type TerminalSessionManagerOptions = {
  /** Host-selected restriction; never read from Gateway configuration. */
  disableGatewayLocalTerminals?: boolean;
  withOpenAdmission?: (request: TerminalOpenRequest, run: (request: TerminalOpenRequest) => Promise<TerminalOpenOutcome>) => Promise<TerminalOpenOutcome>;
  emit: TerminalEventSink;
  getBufferedAmount?: (connId: string) => number | undefined;
  spawn?: typeof spawnTerminalPty;
  maxSessions?: number;
  /** Detach grace; 0 preserves kill-on-disconnect. Gateway wiring owns its default. */
  detachGraceMs?: number;
  maxDetachedSessions?: number;
  scrollbackChars?: number;
};
type TerminalOpenRequest = {
  owner: TerminalOwner;
  /** Operator connection initially viewing an agent-owned session. */
  viewerConnId?: string;
  agentId: string;
  cwd: string;
  shell: string;
  title?: string;
  args: string[];
  cols: number;
  rows: number;
  env: Record<string, string>;
  /** Request-scoped cancellation; a late backend is killed before registration. */
  signal?: AbortSignal;
  /** The trusted caller marks node relays explicitly; omitted requests execute on the Gateway. */
  executionHost?: "gateway" | "node";
  createBackend?: () => Promise<TerminalBackend>;
  stageUpload?: (file: TerminalUploadFile) => Promise<TerminalUploadResult>;
};
type TerminalOpenOutcome = ({
  ok: true;
} & Omit<TerminalOpenResult, "confined" | "title">) | {
  ok: false;
  code: "limit" | "spawn_failed" | "closed" | "disabled";
  message: string;
};
type TerminalAgentActionOutcome = {
  ok: true;
} | {
  ok: false;
  code: "session_unavailable" | "backend_failed";
};
//#endregion
//#region src/gateway/terminal/session-types.d.ts
type TerminalSessionSummary = Omit<TerminalSessionInfo, "confined" | "owner"> & {
  owner: "conn" | `agent:${string}`;
};
type TerminalAttachSummary = Omit<TerminalSessionSummary, "attached" | "createdAtMs"> & {
  buffer: string;
  seq: number;
};
//#endregion
//#region src/gateway/terminal/session-manager.d.ts
/** Owns PTYs and indexes their connections for bounded disconnect cleanup. */
declare class TerminalSessionManager {
  private readonly sessions;
  private readonly pendingOpens;
  private readonly agentSessionDrain;
  private readonly sessionConnections;
  private readonly pendingConnections;
  private readonly emit;
  private readonly getBufferedAmount;
  private readonly spawn;
  readonly gatewayLocalTerminalBlockReason: string | undefined;
  private readonly withOpenAdmission;
  private readonly maxSessions;
  private detachGraceMs;
  private readonly maxDetachedSessions;
  private readonly scrollbackChars;
  private opening;
  private spawning;
  constructor(options: TerminalSessionManagerOptions);
  get size(): number;
  open(request: TerminalOpenRequest): Promise<TerminalOpenOutcome>;
  private openAdmitted;
  write(connId: string, sessionId: string, data: string): boolean;
  /** Writes agent input after proving exact agent-session ownership. */
  writeAgent(owner: AgentTerminalOwner, sessionId: string, data: string): TerminalAgentActionOutcome;
  resize(connId: string, sessionId: string, cols: number, rows: number): boolean;
  /** Resizes an agent-owned PTY after proving exact agent-session ownership. */
  resizeAgent(owner: AgentTerminalOwner, sessionId: string, cols: number, rows: number): TerminalAgentActionOutcome;
  private updateSession;
  /** Stages a file on the same host as an owned terminal session. */
  upload(connId: string, sessionId: string, file: TerminalUploadFile): Promise<TerminalUploadResult | undefined>;
  close(connId: string, sessionId: string): boolean;
  /** Closes an agent-owned PTY after proving session-key ownership. */
  closeAgent(owner: AgentTerminalOwner, sessionId: string): TerminalAgentActionOutcome;
  /** Exact session for Stop/archive; an agent ID includes every terminal during deletion. */
  beginAgentSessionDrain(owner: AgentTerminalOwner | string, assertCurrent?: () => void): AgentTerminalSessionDrain;
  /**
   * Rebinds a connection-owned session, or co-attaches a viewer to an
   * agent-owned session. Operator-to-operator attach remains take-over; only
   * agent-owned sessions gain shared viewers.
   */
  attach(connId: string, sessionId: string): TerminalAttachSummary | undefined;
  /** Every live session, oldest first; all admin connections see the same list. */
  list(): TerminalSessionSummary[];
  snapshot(sessionId: string): string | undefined;
  /** Raw buffer for an agent-owned session, guarded by the caller session key. */
  snapshotAgent(owner: AgentTerminalOwner, sessionId: string): string | undefined;
  listAgent(owner: AgentTerminalOwner): TerminalSessionSummary[];
  private trackPendingOpen;
  private openAbortMessage;
  private untrackPendingOpen;
  /**
   * Handles a dropped connection: detaches its sessions for later reattach
   * when a grace period is configured, otherwise kills them (legacy behavior,
   * still selected by detachedSessionTimeoutSeconds: 0).
   */
  handleDisconnect(connId: string): void;
  /** Closes live and pending sessions whose agent no longer permits a host shell. */
  closeDisallowedAgents(isAllowed: (agentId: string) => boolean): void;
  /** Parks a session ownerless with a reaper; PTY output keeps buffering. */
  private detach;
  updateDetachGraceMs(graceMs: number): void;
  private scheduleDetachedExpiry;
  private enforceDetachedCap;
  /** Tears down all sessions silently on Gateway shutdown; their sockets are closing too. */
  disposeAll(): void;
  /** Viewer-free agent PTYs may be evicted under pool pressure. */
  private idleAgentSessions;
  private removeViewer;
  /** Browser viewers and exact agent owners share the same adoption boundary. */
  private ownedSession;
  private finalize;
}
//#endregion
//#region src/gateway/server-methods/chat-startup-projection-contract.d.ts
type ChatStartupProjectionReadParams = {
  agentId: string;
  sessionKey?: string;
  sessionEntry?: ChatMetadataSessionEntry;
  readPolicy?: "current" | "ready";
};
type ChatStartupProjectionResult = {
  commandsRevision?: string;
  metadata?: Pick<ChatMetadataResult, "commands" | "swarmEnabled" | "requiredWorkerInferenceProfileId">;
  sessionModelCatalog?: ModelCatalogEntry[];
  defaultModelCatalog?: ModelCatalogEntry[];
};
//#endregion
//#region src/gateway/server-methods/shared-types.d.ts
type PreparedSessionApprovalReplay = {
  replay: SessionApprovalReplay;
  /** Check in the response frame; a publication may race promise delivery. */
  isCurrent: () => boolean;
  /** Retain publication fencing through the response, then release the replay scope. */
  release: () => void;
};
/**
 * Structural mirror of the engine's SystemAgentAssistantTurn. Kept local as a
 * leaf contract: importing the assistant module here closes a madge cycle
 * through the agents/config cluster.
 */
type SystemAgentHistoryTurn = {
  role: "user" | "assistant";
  text: string;
};
type SystemAgentReply = {
  text: string;
  action: "none" | "exit" | "open-tui" | "open-setup";
  sensitive?: boolean;
  question?: SystemAgentChatQuestion;
};
/** Minimal hosted OpenClaw contract retained by the gateway request router. */
type GatewaySystemAgentSession = {
  engine: {
    handle: (message: string, options?: {
      uiContext?: {
        page: string;
      };
    }) => Promise<SystemAgentReply>;
    answerWizard: (answer: WizardAnswer) => Promise<SystemAgentReply>;
    cancelWizard: (cancel: SystemAgentWizardCancel) => Promise<SystemAgentReply>;
    decorateRejoinReply: (reply: {
      text: string;
      action: "none";
    }) => SystemAgentReply & {
      wizardInputPending?: boolean;
      step?: WizardStep;
    };
    noteAssistantMessage: (text: string) => void;
    seedHistory: (turns: readonly SystemAgentHistoryTurn[]) => void;
    historyLength: () => number;
    historySince: (index: number) => SystemAgentHistoryTurn[];
    getPendingOperatorProposal: () => {
      operation: SystemAgentOperation;
      hash: string;
    } | null;
    resolveOperatorApproval: (decision: "allow-once" | "allow-always" | "deny" | null, proposalHash: string, beforePersistentApply?: () => void, terminalStatus?: "expired" | "cancelled") => Promise<{
      text: string;
      action: "none" | "exit" | "open-tui" | "open-setup";
      applied?: boolean;
    } | null>;
    dispose: () => Promise<void>;
  };
  welcome: string;
  /** Recorded with the welcome; external-edit notices and setup are not optional. */
  optionalWelcome?: boolean;
  /** Passive creation entry, retained so reconnects do not append duplicate history. */
  newAgentWelcome?: string;
  welcomeQuestion?: SystemAgentChatQuestion;
  /** Audit cursor captured with the pending caretaker welcome; cleared after delivery. */
  welcomeAuditSequence?: number;
  lastUsedAt: number;
  ownerKey: string;
  pendingApproval?: {
    id: string;
    proposalHash: string;
    completion: Promise<NonNullable<Awaited<ReturnType<GatewaySystemAgentSession["engine"]["resolveOperatorApproval"]>>>>;
  };
};
/** Kernel-owned services and state that can be constructed without binding sockets. */
type GatewayKernelContext = {
  deps: CliDeps;
  /** Host-bound plugin ingress; the transport owns its shared hook dispatch queue. */
  dispatchHookAgentTurn?: (pluginId: string, params: Parameters<PluginRuntimeCore["hooks"]["dispatchHookAgentTurn"]>[0]) => ReturnType<PluginRuntimeCore["hooks"]["dispatchHookAgentTurn"]>;
  configRevisionProjector: GatewayConfigRevisionProjector;
  cron: GatewayCronServiceContract;
  cronStorePath: string;
  getRuntimeConfig: () => OpenClawConfig;
  /** Instance-owned startup observation; never lends preparation or write authority. */
  agentDatabaseStartup?: {
    readonly hasPendingAgents: boolean;
    waitForAgentPreparation: (agentId: string, options?: {
      signal?: AbortSignal;
      forWrite?: boolean;
    }) => Promise<void> | undefined;
  };
  channelAdmissionAudit?: ChannelAdmissionAudit;
  /** Last serving policy committed by this Gateway, excluding tentative secret activation. */
  getCommittedRuntimeConfig?: () => OpenClawConfig;
  sessionRowProjectionOwner?: object;
  ensureSessionRowProjection?: () => Promise<void>;
  /** Live reload owner, including same-config restart work and shutdown. */
  isConfigReloadSettled: () => boolean;
  /** Prepared listener certificate pin; undefined when Gateway TLS is disabled. */
  gatewayTlsFingerprint?: string;
  sessionCompanion?: SessionCompanionService;
  sessionObserver?: SessionObserverService;
  sessionActivitySummaries?: SessionActivitySummaryService;
  /** Temporary profile-owned mentions for this exact Gateway lifetime. */
  mentionInbox?: MentionInbox;
  resolveTerminalLaunchPolicy: (agentId?: string) => TerminalLaunchResolution;
  isTerminalEnabled: () => boolean;
  execApprovalManager?: ExecApprovalManager;
  questionManager?: QuestionManager;
  scopeUpgradeCoordinator?: ScopeUpgradeCoordinator;
  /** Exact authority cancels bound approvals; legacy run ids cancel only unbound exec requests. */
  cancelRunBoundApprovals?: (target: string | AgentRunDelegatedAuthority) => Promise<number>;
  pluginApprovalManager?: ExecApprovalManager<PluginApprovalRequestPayload>;
  placementStandingGrants?: PlacementStandingGrantRuntime;
  systemAgentApprovalManager?: ExecApprovalManager<SystemAgentApprovalRequestPayload>;
  forwardPluginApprovalRequest?: (request: PluginApprovalRequest$1) => Promise<boolean>;
  forwardExecApprovalRequest?: (request: ExecApprovalRequest) => Promise<boolean>;
  forwardSystemAgentApprovalRequest?: (request: SystemAgentApprovalRequest) => Promise<boolean>;
  forwardSystemAgentApprovalResolved?: (resolved: SystemAgentApprovalResolved) => Promise<void>;
  execApprovalIosPushDelivery?: {
    handleRequested?: (request: ExecApprovalRequest, opts?: {
      isTargetVisible?: (target: {
        deviceId: string;
        scopes: readonly string[];
      }) => boolean;
    }) => Promise<boolean>;
    handleResolved?: (resolved: ExecApprovalResolved) => Promise<void>;
    handleExpired?: (request: ExecApprovalRequest) => Promise<void>;
  };
  approvalWebPushDelivery?: {
    handleRequested: <TPayload>(record: ExecApprovalRecord<TPayload>) => boolean | Promise<boolean>;
    handleResolved: (resolved: {
      id: string;
    }) => Promise<void>;
    handleExpired: (request: {
      id: string;
    }) => Promise<void>;
  };
  pluginApprovalIosPushDelivery?: {
    handleRequested?: (request: PluginApprovalRequest$1, opts?: {
      isTargetVisible?: (target: {
        deviceId: string;
        scopes: readonly string[];
      }) => boolean;
    }) => Promise<boolean>;
    handleExpired?: (request: PluginApprovalRequest$1) => Promise<void>;
  };
  listSessionPendingApprovals?: (sessionKey: string, client: GatewayClient | null) => Promise<PreparedSessionApprovalReplay>;
  loadGatewayModelCatalog: (params?: {
    agentId?: string;
    agentDir?: string;
    readOnly?: boolean;
    workspaceDir?: string;
  }) => Promise<ModelCatalogEntry[]>;
  loadGatewayModelCatalogSnapshot: (params?: {
    agentId?: string;
    agentDir?: string;
    readOnly?: boolean;
    workspaceDir?: string;
  }) => Promise<GatewayModelCatalogSnapshot>;
  readPreparedGatewayModelCatalog?: (params?: {
    agentId?: string;
    agentDir?: string;
    workspaceDir?: string;
    /** Display-only consumers can omit the eager session-row invalidation snapshot. */
    includeSessionRowPolicy?: boolean;
  }) => Promise<PreparedGatewayModelCatalog | undefined>;
  readPreparedGatewayModelCatalogBatch?: (agentIds: readonly string[], options?: {
    includeSessionRowPolicy?: boolean;
  }) => Promise<PreparedGatewayModelCatalogReadResult[]>;
  readChatMetadata: (params: ChatMetadataReadParams) => Promise<ChatMetadataResult>;
  readPreparedModelsList?: (params: PreparedModelsListRequest) => Promise<ModelsListResult | undefined>;
  readChatStartupProjection?: (params: ChatStartupProjectionReadParams) => Promise<ChatStartupProjectionResult | undefined>;
  getHealthCache: () => HealthSummary | null;
  getReadiness?: ReadinessChecker;
  logHealth: {
    error: (message: string) => void;
  };
  logGateway: SubsystemLogger;
  publishPresence: () => void;
  /** Current live transports, independent of the bounded legacy beacon cache. */
  getPresenceSnapshot: () => PresenceEntry[];
  /** Instance-local native approval subscribers; never derived from a network client. */
  approvalEvents?: GatewayApprovalEventPublisher;
  lifecycleRuntime?: GatewayLifecycleRuntime;
  sharedGatewaySessionGenerationState?: SharedGatewaySessionGenerationState;
  /** Uses the lifecycle owner's module graph for plugin and detached agent turns. */
  createAgentTurnFacade?: InternalAgentTurnFacadeFactory;
  /** Live target facts stay with the instance owner, outside tool dispatch's import graph. */
  resolveSessionRequestTargets?: (request: {
    method: string;
    requestParams: unknown;
    connId?: string;
  }) => SessionMutationTarget[] | undefined;
  enforceSharedGatewayAuthGenerationForConfigWrite?: (nextConfig: OpenClawConfig, previousConfig: OpenClawConfig) => void;
  nodeRegistry: NodeRegistry;
  agentRunSeq: Map<string, number>;
  chatRunState: ChatRunState;
  addChatRun: (sessionId: string, entry: ChatRunRegistration) => void;
  removeChatRun: (sessionId: string, clientRunId: string, sessionKey?: string) => ChatRunEntry | undefined;
  dedupe: Map<string, DedupeEntry>;
  wizardSessions: Map<string, WizardSession>;
  systemAgentSessions: Map<string, GatewaySystemAgentSession>;
  findRunningWizard: () => string | null;
  purgeWizardSession: (id: string) => void;
  wizardRunner: SetupWizardRunner;
  channelWizardRunner: ChannelSetupWizardRunner;
  unavailableGatewayMethods?: ReadonlySet<string>;
};
/** Socket-bound services and connection state supplied by the Gateway transports. */
type GatewayTransportContext = {
  portalService?: GatewayPortalService;
  getMcpAppSandboxPort?: () => number | undefined;
  ensureSandboxHostPort?: () => Promise<number>;
  broadcast: GatewayBroadcastFn;
  broadcastToConnIds: GatewayBroadcastToConnIdsFn;
  getClientConnIds?: (filter?: (client: GatewayClient) => boolean) => ReadonlySet<string>;
  nodeSendToSession: (sessionKey: string, event: string, payload: unknown, opts?: GatewayBroadcastOpts) => void;
  nodeSendToAllSubscribed: (event: string, payload: unknown) => void;
  nodeSubscribe: (nodeId: string, sessionKey: string, connId?: string) => void;
  nodeUnsubscribe: (nodeId: string, sessionKey: string, connId?: string) => void;
  nodeUnsubscribeAll: (nodeId: string) => void;
  hasConnectedTalkNode: () => Promise<boolean>;
  isConnectionActive?: (connId: string) => boolean;
  /** Server-stamped activity from an accepted request on the exact live person connection. */
  recordClientActivity?: (client: GatewayClient | null) => void;
  hasExecApprovalClients?: (excludeConnId?: string) => boolean;
  getApprovalClientConnIds?: <TPayload>(params?: {
    approvalKind?: "exec" | "plugin" | "system-agent";
    excludeConnId?: string;
    filter?: (client: GatewayClient, record?: ExecApprovalRecord<TPayload>) => boolean;
    record?: ExecApprovalRecord<TPayload>;
  }) => ReadonlySet<string>;
  disconnectClientsForDevice?: (deviceId: string, opts?: {
    role?: string;
  }) => void;
  disconnectClientsForUserProfile?: (profileId: string) => void;
  invalidateClientsForDevice?: (deviceId: string, opts?: {
    role?: string;
    reason?: string;
  }) => void;
  hasConnectedClientsForDevice?: (deviceId: string) => boolean;
  refreshConnectedUserProfile?: (profile?: {
    id: string;
    displayName: string | null;
    avatarRevision: string;
    hasAvatar: boolean;
    updatedAt: number;
  }) => void;
  disconnectClientsUsingSharedGatewayAuth?: () => void;
  terminalSessions?: TerminalSessionManager;
  subscribeSessionEvents: (connId: string) => void;
  unsubscribeSessionEvents: (connId: string) => void;
  forgetConnectionAncestors: (connId: string) => void;
  subscribeSessionMessageEvents: SessionMessageSubscriberRegistry["subscribe"];
  unsubscribeSessionMessageEvents: SessionMessageSubscriberRegistry["unsubscribe"];
  unsubscribeAllSessionEvents: (connId: string) => void;
  getSessionEventSubscriberConnIds: () => ReadonlySet<string>;
  getSessionMessageSubscriberConnIds?: (sessionKey: string) => ReadonlySet<string>;
  registerToolEventRecipient: (runId: string, connId: string) => void;
};
/** Resident-owned services bridged into request handling by the server lifecycle. */
type GatewayResidentBridgeContext = {
  getGatewayMethodRegistry?: () => GatewayMethodRegistry;
  controlUiSessionPullRequests?: ReturnType<typeof createControlUiSessionPullRequestSubscriptions>;
  sessionViewerPresence?: ReturnType<typeof createSessionViewerPresenceDeclarations>;
  applyPluginLifecycleChange?: PluginLifecycleRuntimeApply;
  refreshHealthSnapshot: (opts?: {
    probe?: boolean;
    includeSensitive?: boolean;
  }) => Promise<HealthSummary>;
  /** Durable cloud-worker lifecycle; absent from lightweight in-process contexts. */
  workerEnvironmentService?: WorkerEnvironmentServiceContract;
  /** Gateway-host desktop acquisition and observation; present only after enabled startup. */
  hostDesktopService?: HostDesktopService;
  /** Local computer provider shared with the node host, owned by this Gateway lifetime. */
  gatewayComputerService?: GatewayComputerService;
  /** Durable per-session worker placement; absent only from lightweight in-process contexts. */
  workerSessionPlacementService?: WorkerSessionPlacementReader & Partial<WorkerSessionPlacementRetirementService> & Partial<Pick<WorkerSessionPlacementStore, "withWorkspaceExclusion" | "withLocalWorkspaceReservation">>;
  /** Process-local health samples fenced to the exact active placement owner. */
  workerPlacementDiskSpaceReader?: WorkerPlacementDiskSpaceReader;
  /** Process-current paired-device runner proof for active placement projection. */
  workerPlacementRunnerAvailabilityReader?: WorkerPlacementRunnerAvailabilityReader;
  /** Process-local installation progress for the placement's session-host node. */
  workerPlacementRuntimeInstallReader?: WorkerPlacementRuntimeInstallReader;
  /** Use-time approval authority validation over the live run/worker owners. */
  validateAgentRuntimeApprovalAuthority?: AgentRuntimeApprovalAuthorityValidator;
  /** One-way local-to-worker dispatch; absent when cloud workers are disabled. */
  workerPlacementDispatchService?: WorkerPlacementDispatchContract;
  workerRepositoryWorkspaceMutationService?: ReturnType<typeof createRepositoryWorkspaceMutationService>;
  githubPublicationService?: GitHubPublicationCoordinator;
  githubOAuthService?: ReturnType<typeof createGitHubOAuthLifecycle>;
  modelAccountConnectService?: ReturnType<typeof createModelAccountConnectService>;
  getRuntimeSnapshot: (options?: ChannelRuntimeSnapshotOptions) => ChannelRuntimeSnapshot;
  getEventLoopHealth?: () => GatewayEventLoopHealth | undefined;
  getConfigReloaderHotReloadStatus?: () => GatewayHotReloadStatus | undefined;
  getPluginReloadStatus?: () => GatewayPluginReloadStatus | undefined;
  getDeferredChannelReloads?: () => readonly GatewayDeferredChannelReload[];
  startChannel: (channel: ChannelId$1, accountId?: string, opts?: StartChannelOptions) => Promise<ReadonlyMap<string, ChannelAccountStartOutcome>>;
  stopChannel: (channel: ChannelId$1, accountId?: string) => Promise<void>;
  markChannelLoggedOut: (channelId: ChannelId$1, cleared: boolean, accountId?: string) => void;
  broadcastVoiceWakeChanged: (triggers: string[]) => void;
  broadcastVoiceWakeRoutingChanged: (config: VoiceWakeRoutingConfig) => void;
};
type GatewayContextResolver = () => GatewayRequestContext | undefined;
type GatewayRequestContext = GatewayKernelContext & GatewayTransportContext & GatewayResidentBridgeContext & {
  /** Retains original execution while callers may receive an early response. */
  trackExecution: typeof trackAsyncWork;
  /** Local commands can dispatch methods without owning a Gateway server. */
  localEmbedded?: true;
  /** Live instance routing only; never authorization or wire state. */
  resolveGatewayContext?: GatewayContextResolver;
  hostLifecycle?: GatewayHostLifecycle;
  /** Entry-only access; the kernel owns closure. Absent in embedded-only contexts. */
  requestEntryLifetime?: Pick<GatewayRequestEntryLifetime, "enter" | "signal" | "retainedSignal">;
};
/** Full dispatch context for raw request frames before params are normalized. */
type GatewayRequestOptions = {
  /** Transport can forward trusted worker JSON without materializing it. */
  acceptsSerializedJson?: boolean;
  /** Transport can reuse worker-produced raw deflate with the default 15-bit window. */
  acceptsDeflatedSegments?: boolean;
  req: RequestFrame;
  client: GatewayClient | null;
  isWebchatConnect: (params: ConnectParams | null | undefined) => boolean;
  respond: RespondFn;
  context: GatewayRequestContext;
  methodRegistry?: GatewayMethodRegistryView;
  /** Shared entry/publication precondition; never retained as accepted-run authority. */
  expectedProfileBinding?: ExpectedProfileBinding;
  /** In-process source refresh before handler entry; never retained by the handler. */
  prepareDispatchCurrent?: () => Promise<void>;
  /**
   * In-process Gateway lifetime guard composed into durable session mutations.
   * @deprecated For approval persistence use api.runtime.gateway.request with host-bound authority;
   * opaque approval commit callbacks are removed after an announced ordinary stable release window.
   */
  sessionMutationCommitGuard?: () => void;
  /** In-process caller lifetime; never serialized into a Gateway request frame. */
  signal?: AbortSignal;
  /** Live transport authority; in-process only and never derived from request data. */
  hasCurrentClientAuthority?: () => boolean;
};
/** Commit-time guard captured by the pre-dispatch session participation check. */
type SessionMutationAuthorization = {
  /** Release the request's retained sharing facts after its final effect. */
  release?: () => void;
  /** Retain these facts until a detached effect settles, independently of the request. */
  retain?: () => () => void;
  /** Transfer retained facts to admitted work; request cleanup then leaves them with that owner. */
  takeRelease?: () => () => void;
  bindCreation?: (target: {
    sessionKey?: string;
    key?: string;
    agentId?: string;
  }, operation: SessionEntryCreationOperation) => void;
  /** Follow only the selected creator execution's own registry receipts. */
  followRegistration?: (target: {
    sessionKey: string;
    agentId: string;
  }, change: AgentDatabaseRegistryChange) => void;
  /** Consume fresh durable facts while their physical reader remains retained. */
  withCurrent?: <T>(consume: () => T) => Promise<T>;
  withPreparedCurrent?: <T>(facts: {
    agentId: string;
    storePath: string;
    sessionKey: string;
    entry: SessionEntry | undefined;
    readSource?: CapturedSessionEntryReadSource;
    members: readonly SessionMember[];
  }, consume: () => T, assertSourceCurrent: () => void) => T;
  talkSessionTarget?: PreparedTalkSessionTarget;
  /** Original materialized target; Stop must match producer facts, not a later row lookup. */
  admittedTarget?: Readonly<{
    agentId: string;
    sessionKey: string;
    sessionId: string;
  }>;
  assertCurrent: () => void;
  /** Prepare captured agent-store reads before a shared-state worker takes its write lock. */
  prepareWorkerGrant?: (target?: Omit<SessionSourceTransactionGrant, "assertCurrent">) => Promise<{
    assertCurrent: () => void;
    assertLifetimeCurrent: () => void;
    release: () => void | Promise<void>;
    transaction?: SessionSourceTransactionGrant;
  }>;
  /** Original host/session authority for committed input custody, without the selection precondition. */
  assertAdmittedInputCurrent?: () => void;
  /** Original host/operator authority; forwarded input owns its current session policy. */
  assertAdmittedSourceCurrent?: () => void;
  /** Fresh sharing facts for runtime custody; synchronous methods retain the released SDK contract. */
  admittedInputAuthority?: SessionPendingInputAuthority;
  /** Creation-owner notification after COMMIT; binds only this request's previously absent row. */
  recordCreatedSession?: (target: {
    entry?: SessionEntry;
    agentId: string;
    sessionKey: string;
    storePath: string;
    sessionId: string;
    lifecycleRevision?: string;
    readSource?: CapturedSessionEntryReadSource;
  }) => void;
  assertTargetCurrent: (target: {
    sessionKey: string;
    agentId?: string;
    /** Internal ensure result: may materialize a previously id-less Talk target, never replace it. */
    ensuredSessionId?: string;
  }) => void;
};
/** Normalized method invocation options passed to registered handlers. */
type GatewayRequestHandlerOptions = Omit<GatewayRequestOptions, "methodRegistry" | "expectedProfileBinding" | "prepareDispatchCurrent"> & {
  params: Record<string, unknown>;
  sessionMutationAuthorization?: SessionMutationAuthorization;
  /** Synchronously consume current chat.send authority without starting a turn. */
  withSessionTurnAuthority?: <T>(target: {
    sessionKey: string;
    agentId?: string;
    sessionId: string;
  }, consume: (entry: InternalSessionEntry) => T) => Promise<T>;
  diffTiming?: DiffReadTiming;
  markSessionSubscribePhase?: (phase: SessionSubscribePhase) => void;
  /** Host-prepared session resource authority; services explicitly retain their own borrow. */
  sessionAccessAuthority?: GatewaySessionAccessAuthority;
};
type GatewayRequestHandler = ((opts: GatewayRequestHandlerOptions) => Promise<void> | void) & {
  prepareRead?: GatewayReadPreparation;
  onReadError?: GatewayReadErrorHandler;
};
type GatewayRequestHandlers = Record<string, GatewayRequestHandler>;
type SessionEventProjection = {
  payload: unknown;
  /** Certifies a publication-owned envelope and stable row bytes; identical envelopes share encoding. */
  serializeSession?: () => string;
  /** Publication-owned UTF-8 message field, including its trailing comma. */
  serializeMessage?: () => Buffer;
  /** Producer-owned payload fragment; three segments preserve the shared message compression boundary. */
  serializePayload?: () => readonly [Buffer] | readonly [Buffer, Buffer, Buffer];
  delivered?: (client: GatewayClient) => void;
};
type SessionEventProjectionScope = {
  sessionKeys: readonly string[];
  agentId?: string;
};
/** Connection-owned receipts and run display facts, consumed within one publication. */
type SessionEventProjectionContext = {
  isCurrentProjection: (owner: object) => boolean;
  resolveAgentScope: (key: string, agentId?: string) => readonly [string | undefined, string | undefined, string | undefined] | null;
  forgetAncestors: (key?: string) => void;
  references: (client: GatewayClient) => ConnectionSessionRows;
  createRunProjector: () => VisibleActiveSessionRunProjector;
};
type PrepareSessionEventProjection = (event: string, payload: unknown, scope: SessionEventProjectionScope, context: SessionEventProjectionContext) => ((client: GatewayClient) => SessionEventProjection | undefined) | undefined;
type GatewayBroadcastStateVersion = {
  presence?: number;
  health?: number;
};
type GatewayBroadcastOpts = {
  /** Agent scope for agent-relative keys such as `global`. */
  agentId?: string;
  dropIfSlow?: boolean;
  /** Omit a redundant projection for clients that advertise this capability. */
  excludeClientCapability?: GatewayClientCap;
  /** Canonical subscription keys for session-scoped delivery. */
  sessionKeys?: readonly string[];
  /** Producer-resolved exact subscription keys for traffic attribution; never changes recipients. */
  sessionEventSubscriptionKeys?: readonly string[];
  /** Prepared facts remain valid only during this synchronous publication. */
  prepareSessionProjection?: PrepareSessionEventProjection;
  /** Target recipients were selected from subscriptions at ingress. */
  sessionSubscriptionVerified?: boolean;
  /** Question owner authorizes ordinary own-run recipients without a broad question grant. */
  questionRecipient?: (client: GatewayClient) => boolean;
  stateVersion?: GatewayBroadcastStateVersion;
  /** Private live-text ownership; omitting coalesce flushes this group's progress. */
  liveText?: {
    group: AbortSignal;
    /** Source continuity changes without revoking already queued publications. */
    sourceEpoch?: object;
    /** Accepted terminal barrier; drain current queued text before retiring its group. */
    settle?: true;
    isCurrent?: () => boolean;
    coalesce?: {
      key: string;
      merge: (previous: unknown, next: unknown) => unknown;
    };
    /** Full internal payloads become append-only only after this socket has a baseline. */
    projection?: {
      key: string;
      delta: (payload: unknown) => unknown;
      /** Upper bound for encoded full payload bytes, without encoding cumulative text. */
      snapshotBytes?: (payload: unknown, deltaPayloadBytes: number) => number;
      version?: unknown;
      snapshot?: boolean;
      /** Verify transformed snapshots against the prior publication before omitting them. */
      text?: LiveTextProjectionText;
    };
  };
};
type GatewayBroadcastFn = (event: string, payload: unknown, opts?: GatewayBroadcastOpts) => void;
type GatewayBroadcastToConnIdsFn = (event: string, payload: unknown, connIds: ReadonlySet<string>, opts?: GatewayBroadcastOpts) => void;
type SessionRuntimeScope = {
  storePath: string;
  physicalPaths?: (locator: string, agentId?: string) => readonly string[];
  resolveGatewayContext?: GatewayContextResolver;
};
type VisibleActiveSessionRunState = {
  active: boolean;
  /** Complete exact active set. Omitted when another active owner exposes only liveness. */
  runIds?: string[];
  status?: "queued";
};
type VisibleActiveSessionRunSelection = Omit<SessionRuntimeScope, "storePath"> & {
  storePath?: string;
  requestedKey: string;
  canonicalKey: string;
  sessionId?: string;
  agentId?: string;
  defaultAgentId?: string;
};
type VisibleActiveSessionRunProjector = (params: Omit<VisibleActiveSessionRunSelection, "physicalPaths">) => VisibleActiveSessionRunState;
//#endregion
//#region src/plugins/gateway-events.d.ts
type OpenClawPluginGatewayEventScope = "operator.read" | "operator.write" | "operator.admin";
type OpenClawPluginSessionsChangedEvent = {
  sessionKey: string;
  agentId?: string;
  label?: string;
  displayName?: string;
  reason?: string;
  phase?: string;
};
type OpenClawPluginGatewayEvents = {
  emit: (event: string, payload: PluginJsonValue, opts: {
    scope: OpenClawPluginGatewayEventScope;
  }) => void;
  /**
   * Native plugins can already read full session entries through the injected runtime;
   * this notice only avoids polling and does not widen session access.
   */
  onSessionsChanged: (handler: (event: OpenClawPluginSessionsChangedEvent) => void) => () => void;
};
//#endregion
//#region src/infra/gateway-ws-metrics.d.ts
type GatewayWsMetricsListener = (event: string, count: number, bytes: number, wireBytes: number | undefined,
/** Exclusive bucket counts, borrowed synchronously until the listener returns. */
buckets: Readonly<ArrayLike<number>>, bucketLabels: readonly string[], sessionEvent: Readonly<GatewayWsSessionEventAttribution> | undefined, presenceMode: GatewayWsPresenceMode | undefined) => void;
//#endregion
//#region src/infra/diagnostic-trace-propagation.d.ts
type DiagnosticTracePropagationBridge<TEvent, TMetadata> = Readonly<{
  /** Selects events that need synchronous exporter preparation. */
  shouldPrepareEvent?: (event: TEvent) => boolean;
  /** Prepares exporter-owned state before an outbound caller can resolve it. */
  prepareEvent?: (event: TEvent, metadata: TMetadata) => void;
  /** Translates a diagnostic correlation context to an exporter-owned context. */
  resolveTraceContext: (traceContext: DiagnosticTraceContext) => DiagnosticTraceContext | undefined;
}>;
//#endregion
//#region src/plugins/plugin-registration.types.d.ts
type PluginInteractiveRegistration<TContext = unknown, TChannel extends string = string, TResult = {
  handled?: boolean;
} | void> = {
  channel: TChannel;
  namespace: string;
  handler: (ctx: TContext) => Promise<TResult> | 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> | boolean | void;
type OpenClawPluginHttpRouteUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => Promise<boolean | void> | boolean | void;
type OpenClawPluginHttpRouteParams = {
  path: string;
  handler: OpenClawPluginHttpRouteHandler;
  handleUpgrade?: OpenClawPluginHttpRouteUpgradeHandler;
  auth: OpenClawPluginHttpRouteAuth;
  match?: OpenClawPluginHttpRouteMatch;
  gatewayRuntimeScopeSurface?: OpenClawPluginGatewayRuntimeScopeSurface;
  nodeCapability?: {
    surface: string;
    ttlMs?: number;
  };
  replaceExisting?: boolean;
};
type WidgetPresenterContext = Readonly<{
  messageChannel?: string;
  accountId?: string;
  deliveryContext?: Readonly<DeliveryContext>;
  nativeChannelId?: string;
  currentChannelId?: string;
  currentMessagingTarget?: string;
  /** Channel-local id of the inbound message this turn answers. */
  currentMessageId?: string;
  sessionKey?: string;
}>;
type WidgetPresenterDocument = Readonly<{
  kind: "html";
  /** Core-wrapped document for hosts that run widgets inside OpenClaw's iframe bridge. */
  html: string;
  /** Agent-authored widget code before wrapping, for hosts with their own widget runtime. */
  source: string;
  hostedUrl?: string;
}>;
type WidgetPresentationError = {
  code: "no_eligible_node";
  message: string;
} | {
  code: "node_error";
  message: string;
  nodeId?: string;
} | {
  code: "unavailable";
  message: string;
} | {
  code: "presentation_error";
  message: string;
};
type WidgetPresentationSuccess = {
  kind: "node";
  nodeId: string;
  nodeName?: string;
} | {
  kind: "message";
  receipt: MessageReceipt;
  updated?: boolean;
  /** Advisory findings for the model; the widget was still delivered. */
  notes?: readonly string[];
};
type WidgetPresenter = {
  description: string;
  availability: (context: WidgetPresenterContext) => Promise<Result$1<{
    available: true;
  }, WidgetPresentationError>>;
  present: (params: {
    document: WidgetPresenterDocument;
    title: string;
    /** Stable widget name: the explicit `name`, or one derived from the title. */
    name: string;
    /** Agent-written widget state, passed only to presenters that declare `capabilities.state`. */
    state?: string;
    context: WidgetPresenterContext;
  }) => Promise<Result$1<WidgetPresentationSuccess, WidgetPresentationError>>;
} & ({
  target: "node_panel";
  match?: never;
  capabilities?: never;
} | {
  target: "current_channel";
  match: (context: WidgetPresenterContext) => boolean;
  capabilities: Readonly<{
    sourceKinds: readonly string[];
    maxSourceBytes?: number;
    /**
     * Replaces the browser-host authoring rules in the `show_widget` description while this
     * presenter owns the current channel. Keep it bounded; it is part of the tool prompt.
     */
    authoringGuidance?: string;
    /** Accepts the `state` argument: a UTF-8 string of at most `maxBytes` the widget reads. */
    state?: Readonly<{
      maxBytes: number;
      description: string;
    }>;
  }>;
});
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<void>;
/**
 * 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 = PluginManifestCliCommand;
/** Root-command metadata that is available before a plugin registrar is activated. */
type OpenClawPluginCliRootCommandDescriptor = OpenClawPluginCliCommandDescriptor & {
  machineOutput?: (params: {
    argv: readonly string[];
    stdoutIsTTY: boolean;
  }) => boolean;
};
type OpenClawPluginCliRegistrationOptions = {
  /** Omit or pass an empty path for root commands. */
  parentPath?: readonly [];
  commands?: readonly string[];
  descriptors?: readonly OpenClawPluginCliRootCommandDescriptor[];
} | /** Backward-compatible registration shape for dynamic root or nested paths. */ {
  parentPath?: readonly string[];
  commands?: readonly string[];
  descriptors?: readonly OpenClawPluginCliCommandDescriptor[];
};
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 OpenClawPluginNodeInvokeTransportResult = {
  ok: true;
  payload?: unknown;
  payloadJSON?: string | null;
} | {
  ok: false;
  code?: string;
  message: string;
  details?: Record<string, unknown>;
};
type OpenClawPluginNodeInvokeApprovalDecision = "allow-once" | "allow-always" | "deny";
type OpenClawPluginNodeInvokePolicyContext = {
  nodeId: string;
  command: string;
  params: unknown;
  timeoutMs?: number;
  idempotencyKey?: string;
  config: OpenClawConfig;
  pluginConfig?: Record<string, unknown>;
  node?: {
    nodeId: string;
    displayName?: string;
    platform?: string;
    deviceFamily?: string;
    caps?: string[];
    commands?: string[];
  };
  client?: {
    connId?: string;
    scopes?: string[];
  } | null;
  risk?: {
    level: "ordinary" | "high";
    /** Stable, content-free family name; never include user or action arguments. */
    family: string;
  };
  approvals?: {
    request: (input: {
      title: string;
      description: string;
      scope?: ApprovalScope;
      severity?: "info" | "warning" | "critical";
      toolName?: string;
      toolCallId?: string;
      agentId?: string;
      sessionKey?: string;
      allowedDecisions?: readonly OpenClawPluginNodeInvokeApprovalDecision[];
      timeoutMs?: number;
    }) => Promise<{
      id?: string;
      decision?: OpenClawPluginNodeInvokeApprovalDecision | null;
    }>;
  };
  /** Full covers only the selected harness's declared node commands; undefined requires a human decision. */
  invokeNodeWithSessionFull?: (input: {
    workspace: OpenClawPluginNodeWorkspace;
    /** Called only after the host authorizes this exact admitted Full launch. */
    createParams: () => unknown;
  }) => Promise<OpenClawPluginNodeInvokeTransportResult | undefined>;
  invokeNode: (input?: {
    params?: unknown;
    /** Bind an approved launch to its admitted managed workspace, when present. */
    workspace?: OpenClawPluginNodeWorkspace;
    timeoutMs?: number;
    idempotencyKey?: string;
  }) => Promise<OpenClawPluginNodeInvokeTransportResult>;
};
type OpenClawPluginNodeInvokePolicyResult = Extract<OpenClawPluginNodeInvokeTransportResult, {
  ok: true;
}> | (Extract<OpenClawPluginNodeInvokeTransportResult, {
  ok: false;
}> & {
  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.commands.allow`.
   */
  defaultPlatforms?: Array<"ios" | "android" | "macos" | "windows" | "linux" | "unknown">;
  /**
   * Dangerous policy commands are filtered out of default allowlists unless
   * explicitly allowed by config.
   */
  dangerous?: boolean;
  /**
   * Explicitly permits one approval to cover later launches on the same managed placement.
   * The scope is a stable semantic capability key, never user or action arguments.
   */
  standingApproval?: {
    kind: "placement";
    scope: string;
  };
  /**
   * iOS foreground-restricted commands should be queued for foreground delivery
   * when an iOS node reports BACKGROUND_UNAVAILABLE.
   */
  foregroundRestrictedOnIos?: boolean;
  /**
   * Classify exact command arguments before the policy handler or node transport runs.
   * Throwing rejects the invocation before dispatch.
   */
  classifyRisk?: (ctx: Pick<OpenClawPluginNodeInvokePolicyContext, "command" | "params">) => NonNullable<OpenClawPluginNodeInvokePolicyContext["risk"]>;
  handle: (ctx: OpenClawPluginNodeInvokePolicyContext) => Promise<OpenClawPluginNodeInvokePolicyResult> | OpenClawPluginNodeInvokePolicyResult;
};
type OpenClawPluginSecurityAuditContext = {
  config: OpenClawConfig;
  sourceConfig: OpenClawConfig;
  env: NodeJS.ProcessEnv;
  stateDir: string;
  configPath: string;
};
type OpenClawPluginSecurityAuditCollector = (ctx: OpenClawPluginSecurityAuditContext) => SecurityAuditFinding[] | Promise<SecurityAuditFinding[]>;
type OpenClawGatewayDiscoveryAdvertiseContext = {
  machineDisplayName: string;
  gatewayPort: number;
  gatewayTlsEnabled: boolean;
  gatewayTlsFingerprintSha256?: string;
  gatewayDirectReachable: boolean;
  tailnetDns?: string;
  sshPort?: number;
  cliPath?: string;
  minimal: boolean;
};
type OpenClawGatewayDiscoveryService = {
  id: string;
  advertise: (ctx: OpenClawGatewayDiscoveryAdvertiseContext) => void | Promise<void | {
    stop?: () => void | Promise<void>;
  }>;
};
/** Context passed to long-lived plugin services. */
type OpenClawPluginServiceHealth = {
  reportFailure: (error: unknown) => void;
  clearFailure: () => void;
};
type OpenClawPluginServiceContext = {
  config: OpenClawConfig;
  workspaceDir?: string;
  stateDir: string;
  logger: PluginLogger;
  serviceHealth?: OpenClawPluginServiceHealth;
  /** Gateway-owned timed work; required by the version 2 service contract. */
  scheduler?: PluginServiceSchedulerV1;
  /** Remote device-only Control UI ingress, available only to admitted trusted services. */
  controlUiIngress?: GatewayControlUiIngressFactoryV2;
  /** Gateway-owned scheduler access, revoked when this service stops. */
  getCron?: () => (PluginHookGatewayCronService & {
    /** Only this plugin's event sources, without credentials or creator authority. */
    readEventSources?: () => Promise<CronEventSourceSnapshot[]>;
    /** Transfer a durable ingress claim into this plugin's bound Automation. */
    runEvent?: (id: string, input: Omit<CronEventRunOptions, "commitGuard"> & {
      /** Additional current source/account authority; never replaces the host guard. */
      assertCurrent: () => void;
    }) => Promise<CronEventRunResult>;
    /** Admit service-owned work through the scheduler's normal run queue. */
    enqueueRun?: (id: string, mode?: CronRunMode) => Promise<CronServiceRunResult>;
  }) | undefined;
  /** Host-authenticated MCP Events requests bound to this plugin's persisted event source. */
  mcpEvents?: {
    /** One binding lifetime, including exact finite cleanup across benign policy refresh. */
    prepareSource: (input: {
      jobId: string;
      sourceIdentity: string;
      serverName: string;
    }) => Promise<{
      accountId: string;
      principalId: string;
      assertCurrent: () => void;
      /** Refresh current policy and credential-owner facts; retired authorization never revives. */
      revalidate: () => Promise<void>;
      request: (method: "server/discover" | "events/list" | "events/subscribe", params: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>;
      /** Close subscribe admission and clean up this handle’s captured webhook identity. */
      unsubscribe: (signal: AbortSignal) => Promise<unknown>;
      dispose: () => void;
    }>;
  };
  /** Service-owned node calls for this plugin's commands; normal node policy still applies. */
  invokeNode?: (params: Omit<Parameters<PluginRuntime["nodes"]["invoke"]>[0], "scopes">) => Promise<unknown>;
  /** Service-owned binary transport for this plugin's duplex node commands. */
  openNodeDuplex?: (params: Omit<Parameters<PluginRuntime["nodes"]["openDuplex"]>[0], "scopes"> & {
    assertCurrent?: () => void;
  }) => ReturnType<PluginRuntime["nodes"]["openDuplex"]>;
  gatewayEvents?: OpenClawPluginGatewayEvents;
  startupTrace?: {
    detail?: (name: string, metrics: ReadonlyArray<readonly [string, number | string]>) => void;
    measure: <T>(name: string, run: () => T | Promise<T>) => Promise<T>;
  };
  internalDiagnostics?: {
    /** Synchronous WebSocket counters; arrays and attribution are borrowed until return. */
    onGatewayWsMetrics?: (listener: GatewayWsMetricsListener) => () => void;
    /** Synchronous worker measurements; timing fields are borrowed and must not be mutated. */
    onWorkerRequestMetrics?: (listener: WorkerRequestMetricsListener) => () => void;
    /** Identity of the hosting process, available only while this service is active. */
    getRuntimeIdentity?: () => {
      processInstanceId: string;
      buildId?: string;
    };
    /** Current owner-projected work; undefined while the Gateway projection is unavailable. */
    onGatewayWorkMetrics?: (listener: (snapshot: GatewayWorkMetricsSnapshot | undefined) => void) => () => void;
    emit: (event: DiagnosticEventInput, privateData?: DiagnosticEventPrivateData) => void;
    onEvent: (listener: (event: DiagnosticEventPayload, metadata: DiagnosticEventMetadata, privateData: DiagnosticEventPrivateData) => void, filter?: InternalDiagnosticEventInterest<DiagnosticEventPayload["type"]>,
    /** Defaults to true; false skips private payload copies and passes a frozen empty object. */
    options?: {
      includePrivateData?: boolean;
    }) => () => void;
    registerTracePropagationBridge?: (bridge: DiagnosticTracePropagationBridge<DiagnosticEventPayload, DiagnosticEventMetadata>) => () => void;
  };
};
/** Background service registered by a plugin during `register(api)`. */
type OpenClawPluginService = {
  apiVersion?: 1;
  id: string;
  /** Restart this service with committed config when one of these paths changes. */
  reload?: {
    configPrefixes: readonly string[];
  };
  start: (ctx: OpenClawPluginServiceContext) => void | Promise<void>;
  stop?: (ctx: OpenClawPluginServiceContext) => void | Promise<void>;
};
type OpenClawPluginServiceContextV2 = OpenClawPluginServiceContext & {
  scheduler: PluginServiceSchedulerV1;
};
/** A service whose host must provide scheduling bound to its lifetime. */
type OpenClawPluginServiceV2 = Omit<OpenClawPluginService, "apiVersion" | "start" | "stop"> & {
  apiVersion: 2;
  start: (ctx: OpenClawPluginServiceContextV2) => void | Promise<void>;
  stop?: (ctx: OpenClawPluginServiceContextV2) => void | Promise<void>;
};
type OpenClawPluginChannelRegistration<Plugin extends AnyChannelPlugin$2 = ChannelPlugin> = {
  plugin: Plugin;
};
/**
 * 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";
//#endregion
//#region src/decisions/provider-host.d.ts
type Options = DecisionEvaluateOptionsV2;
/** Core accounting consumes only these route-bound public billing facts. */
type PreparedDecisionBilling = {
  provider: string;
  model: string;
  billing?: ModelDecisionCapabilities["billing"];
};
/** Provider-owned admission and health. */
declare class DecisionProviderHost {
  readonly provider: DecisionProviderV1 | DecisionProviderV2;
  readonly record: PluginRecord;
  private readonly registration?;
  private retired;
  private reloadPause?;
  private health?;
  private readonly pending;
  private readonly reasons;
  private successCount;
  private totalLatencyMs;
  private inputTokens;
  private outputTokens;
  constructor(provider: DecisionProviderV1 | DecisionProviderV2, record: PluginRecord, registration?: PluginProviderRegistration | undefined);
  private generation;
  unavailable(reason: UnavailableReason): DecisionOutcome;
  /** Close only capability admission before reversible native reload preparation. */
  pauseForReload(changedConsumerIds?: ReadonlySet<string>): {
    settled: Promise<void[]>;
    assertResumable: () => void;
    resume: () => void;
  };
  /** Native service stop/disposal is irreversible; rollback must not reopen it. */
  retire(): void;
  cancelConsumer(pluginId: string): void;
  stop(): Promise<void>;
  private ready;
  inspect(config: OpenClawConfig): {
    providerId: string;
    pluginId: string;
    configured: boolean;
    credentialReady?: boolean | undefined;
    callable: boolean;
    runtimeGeneration: string;
    recentSuccessAt: number | undefined;
    activeRequests: number;
    successCount: number;
    totalLatencyMs: number;
    usage: {
      inputTokens: number;
      outputTokens: number;
    };
    reasons: {
      authentication?: number | undefined;
      "circuit-open"?: number | undefined;
      "credentials-unavailable"?: number | undefined;
      deadline?: number | undefined;
      disabled?: number | undefined;
      "invalid-response"?: number | undefined;
      "not-configured"?: number | undefined;
      overloaded?: number | undefined;
      "rate-limited"?: number | undefined;
      retiring?: number | undefined;
      transport?: number | undefined;
      "unsupported-input"?: number | undefined;
    };
  };
  evaluate(submitted: DecisionBatch, options: Options, model: string, config: OpenClawConfig, registry: PluginRegistry, consumerId?: string, isAdmissible?: () => boolean, onPreparedBilling?: (facts: PreparedDecisionBilling) => void): Promise<DecisionOutcome>;
  evaluateV2(submitted: DecisionBatchV2, options: Options, model: string, config: OpenClawConfig, registry: PluginRegistry, consumerId?: string, isAdmissible?: () => boolean, onPreparedBilling?: (facts: PreparedDecisionBilling) => void): Promise<DecisionOutcomeV2>;
  private evaluateVersion;
  private fail;
}
//#endregion
//#region src/plugins/subagent-profile.types.d.ts
/** Plugin-local native child instructions and restrictions; never an authority grant. */
type PluginSubagentProfile = {
  id: string;
  description: string;
  /** Relative to the registering plugin package. */
  instructionsFile: string;
  outputSchema?: Record<string, unknown>;
  tools?: {
    deny: string[];
  };
};
/** Host snapshot retained by the registry generation that read the package bytes. */
type RegisteredSubagentProfile = {
  pluginId: string;
  id: string;
  description: string;
  instructionsFile: string;
  instructionsSha256: string;
  instructions: string;
  outputSchema?: Record<string, unknown>;
  deny: string[];
};
//#endregion
//#region src/plugins/registry-types.d.ts
type AnyChannelPlugin$1 = AnyChannelPlugin$2;
type PluginOrigin = PluginOrigin$1;
/** Registration provenance; this shape carries no execution or resource authority. */
type PluginRegistrationOwner = {
  pluginId: string;
  pluginName?: string;
  source: string;
  rootDir?: string;
};
/** Agent tool factory registered by one plugin runtime. */
type PluginToolRegistration = PluginRegistrationOwner & {
  factory: OpenClawPluginToolFactory;
  /** Explicitly registered required-authority context, never inferred from plugin identity. */
  contextVersion?: 2;
  names: string[];
  declaredNames?: ReadonlySet<string>;
  optional: boolean;
  workspaceAccess?: boolean | "execute";
  /** Loader-owned provenance. Missing values are conservative legacy registrations. */
  origin?: PluginOrigin;
};
/** Gateway HTTP route registered by a plugin runtime. */
type PluginHttpRouteRegistration = {
  /** Retired ingress awaiting a lifecycle replacement; responds with Retry-After. */
  handoff?: true;
  /** Compatibility endpoints retained by live holders or route handoffs. */
  legacyListeners?: readonly {
    port: number;
    host?: string;
    /** Shipped listener-liveness response: exact raw path, status 200, body "ok". */
    health?: {
      path: string;
      contentType?: string;
    };
    /** Shipped Node HTTP deadlines in milliseconds; omission keeps Node defaults. */
    timeouts?: {
      headers: number;
      request: number;
      socket: number;
    };
  }[];
  /** Endpoints retained only by a handoff, without a live holder. */
  legacyListenerHandoffs?: PluginHttpRouteRegistration["legacyListeners"];
  pluginId?: string;
  path: string;
  handler: OpenClawPluginHttpRouteHandler;
  handleUpgrade?: OpenClawPluginHttpRouteUpgradeHandler;
  auth: OpenClawPluginHttpRouteAuth;
  match: OpenClawPluginHttpRouteMatch;
  gatewayRuntimeScopeSurface?: OpenClawPluginGatewayRuntimeScopeSurface;
  gatewayMethodDispatchAllowed?: boolean;
  nodeCapability?: {
    surface: string;
    ttlMs?: number;
  };
  source?: string;
};
type PluginChannelRegistration = PluginRegistrationOwner & {
  plugin: AnyChannelPlugin$1;
  /** Prepared views retain the exact transport donor in addition to their local admission. */
  borrowedRuntimeRecord?: PluginRecord;
  /** Exact record-bound runtime resolver captured when the active plugin registered the channel. */
  resolveChannelRuntime?: () => PluginRuntime["channel"];
  /** Loader-owned provenance. Missing values are conservative legacy registrations. */
  origin?: PluginOrigin;
  /** Host-owned capture of the exact verified official channel registration. */
  captureReadAuthority?: () => (() => boolean) | undefined;
};
type PluginDashboardDataBindingRegistration = PluginManifestDashboardDataBinding & {
  pluginId: string;
  capabilityId: string;
  handler: GatewayRequestHandlers[string];
};
type PluginDashboardActionVerbRegistration = PluginManifestDashboardActionVerb & {
  pluginId: string;
  capabilityId: string;
  handler: GatewayRequestHandlers[string];
};
type PluginOwnedProviderRegistration<T> = PluginRegistrationOwner & {
  provider: T;
};
type PluginAgentToolResultMiddlewareRegistration = PluginRegistrationOwner & {
  rawHandler: AgentToolResultMiddleware;
  handler: AgentToolResultMiddleware;
  runtimes: AgentToolResultMiddlewareRuntime[];
  scopes?: AgentToolResultMiddlewareScope[];
};
type PluginAgentToolResultMiddlewareOwner = {
  pluginId: string;
  runtimes: AgentToolResultMiddlewareRuntime[];
  manifest: PluginManifestRecord;
};
type PluginServiceRegistration = PluginRegistrationOwner & {
  readonly id: string;
  service: OpenClawPluginService | OpenClawPluginServiceV2;
  origin: PluginOrigin;
  trustedOfficialInstall?: boolean;
};
type PluginGatewayDiscoveryServiceRegistration = PluginRegistrationOwner & {
  readonly id: string;
  service: OpenClawGatewayDiscoveryService;
  instance?: PluginInstanceExecution;
};
type PluginNodeHostCommandRegistration = PluginRegistrationOwner & {
  command: OpenClawPluginNodeHostCommand;
};
type PluginWidgetPresenterRegistration = PluginRegistrationOwner & {
  presenter: WidgetPresenter;
};
type PluginCommandRegistration = PluginRegistrationOwner & {
  command: OpenClawPluginCommandDefinition;
  trustedOwnerStatusExposure?: true;
};
type PluginTrustedToolPolicyRegistryRegistration = PluginRegistrationOwner & {
  policy: PluginTrustedToolPolicyRegistration;
  origin?: PluginRecord["origin"];
};
type PluginSessionActionRegistryRegistration = PluginRegistrationOwner & {
  action: PluginSessionActionRegistration;
};
type PluginRecord = {
  id: string;
  nativeSessionCatalog?: PluginManifestNativeSessionCatalogSetup;
  name: string;
  packageVersion?: string;
  version?: string;
  builtWithOpenClawVersion?: string;
  packageName?: string;
  description?: string;
  format?: PluginFormat;
  bundleFormat?: PluginBundleFormat;
  bundleCapabilities?: string[];
  kind?: PluginKind | PluginKind[];
  source: string;
  rootDir?: string;
  origin: PluginOrigin;
  workspaceDir?: string;
  trustedOfficialInstall?: boolean;
  trust?: PluginTrust;
  enabled: boolean;
  explicitlyEnabled?: boolean;
  activated?: boolean;
  imported?: boolean;
  /** Families authoritatively supplied by a descriptor entry, including empty collections. */
  capabilityCatalog?: Array<keyof PluginCapabilityCatalog>;
  compat?: readonly PluginCompatCode[];
  activationSource?: PluginActivationSource;
  activationReason?: string;
  status: "loaded" | "disabled" | "error";
  error?: string;
  failedAt?: Date;
  failurePhase?: "validation" | "load" | "register";
  toolNames: string[];
  hookNames: string[];
  channelIds: string[];
  cliBackendIds: string[];
  providerIds: string[];
  syntheticAuthRefs?: string[];
  embeddingProviderIds: string[];
  speechProviderIds: string[];
  realtimeTranscriptionProviderIds: string[];
  realtimeVoiceProviderIds: string[];
  mediaUnderstandingProviderIds: string[];
  transcriptSourceProviderIds: string[];
  imageGenerationProviderIds: string[];
  videoGenerationProviderIds: string[];
  musicGenerationProviderIds: string[];
  webFetchProviderIds: string[];
  webSearchProviderIds: string[];
  migrationProviderIds: string[];
  contextEngineIds?: string[];
  declaredContextEngineIds?: readonly string[];
  /** Manifest `reload.turnHandover`: a reload hands this generation's running turns to the next one. */
  turnHandover?: boolean;
  agentHarnessIds: string[];
  cliCommands: string[];
  services: string[];
  gatewayDiscoveryServiceIds: string[];
  commands: string[];
  commandAliases?: PluginManifestRecord["commandAliases"];
  httpRoutes: number;
  hookCount: number;
  configSchema: boolean;
  configUiHints?: Record<string, PluginConfigUiHint>;
  configJsonSchema?: JsonSchemaObject;
  contracts?: PluginManifestContracts;
  dashboard?: PluginManifestDashboard;
  controlUi?: PluginManifestControlUi;
  uiCapabilities?: PluginManifestRecord["uiCapabilities"];
  mcpServers?: Record<string, PluginManifestMcpServer>;
  memorySlotSelected?: boolean;
  dependencyStatus?: PluginDependencyStatus;
};
type PluginRegistry = {
  plugins: PluginRecord[];
  tools: PluginToolRegistration[];
  hooks: HookRunnerRegistry["hooks"][number][];
  typedHooks: PluginHookRegistration[];
  channels: PluginChannelRegistration[];
  channelSetups: (PluginRegistrationOwner & {
    plugin: AnyChannelPlugin$1;
    /** Loader-owned provenance. Missing values are conservative legacy registrations. */
    origin?: PluginOrigin;
    enabled: boolean;
  })[];
  providers: PluginProviderRegistration[];
  modelCatalogProviders: PluginOwnedProviderRegistration<UnifiedModelCatalogProviderPlugin>[];
  sessionCatalogs: PluginOwnedProviderRegistration<SessionCatalogProvider>[];
  cliBackends: (PluginRegistrationOwner & {
    builtWithOpenClawVersion?: string;
    backend: CliBackendPlugin;
  })[];
  embeddingProviders: PluginOwnedProviderRegistration<EmbeddingProviderAdapter>[];
  speechProviders: PluginOwnedProviderRegistration<SpeechProviderPlugin>[];
  realtimeTranscriptionProviders: PluginOwnedProviderRegistration<RealtimeTranscriptionProviderPlugin>[];
  realtimeVoiceProviders: PluginOwnedProviderRegistration<RealtimeVoiceProviderPlugin>[];
  mediaUnderstandingProviders: PluginOwnedProviderRegistration<MediaUnderstandingProviderPlugin>[];
  transcriptSourceProviders: PluginOwnedProviderRegistration<TranscriptSourceProvider>[];
  imageGenerationProviders: PluginOwnedProviderRegistration<ImageGenerationProviderPlugin>[];
  videoGenerationProviders: PluginOwnedProviderRegistration<VideoGenerationProviderPlugin>[];
  musicGenerationProviders: PluginOwnedProviderRegistration<MusicGenerationProviderPlugin>[];
  webFetchProviders: PluginOwnedProviderRegistration<WebFetchProviderPlugin>[];
  webSearchProviders: PluginOwnedProviderRegistration<WebSearchProviderPlugin>[];
  workerProviders: Map<string, PluginOwnedProviderRegistration<WorkerProvider>>;
  storageProviders: Map<string, PluginOwnedProviderRegistration<StorageProvider>>;
  migrationProviders: PluginOwnedProviderRegistration<MigrationProviderPlugin>[];
  agentToolResultMiddlewareOwners: PluginAgentToolResultMiddlewareOwner[];
  agentToolResultMiddlewares: PluginAgentToolResultMiddlewareRegistration[];
  agentHarnesses: (PluginRegistrationOwner & {
    harness: AgentHarness;
    nativeCompaction?: AgentHarnessNativeCompaction;
  })[];
  pluginRuntimeArtifacts: Map<string, ResolvedPluginRuntimeArtifact>;
  compactionProviders: RegisteredCompactionProvider[];
  decisionProviders: Array<{
    pluginId: string;
    host: DecisionProviderHost;
  }>;
  legacyInternalHooks: {
    pluginId: string;
    name: string;
    event: string;
    handler: InternalHookHandler;
  }[];
  memoryCapabilities: MemoryPluginCapabilityRegistration[];
  memoryCorpusSupplements: MemoryCorpusSupplementRegistration[];
  memoryPromptPreparations: MemoryPromptPreparationRegistration[];
  memoryPromptSupplements: MemoryPromptSupplementRegistration[];
  sessionDiscussionProviders: Map<string, {
    pluginId: string;
    provider: SessionDiscussionProvider;
  }>;
  contextEngines: Map<string, ContextEngineRegistration>;
  gatewayHandlers: GatewayRequestHandlers;
  gatewayMethodDescriptors: GatewayMethodDescriptor[];
  dashboardDataBindings: Map<string, PluginDashboardDataBindingRegistration>;
  dashboardActionVerbs: Map<string, PluginDashboardActionVerbRegistration>;
  coreGatewayMethodNames: string[];
  httpRoutes: PluginHttpRouteRegistration[];
  widgetPresenters: PluginWidgetPresenterRegistration[];
  mcpServerConnectionResolvers: PluginMcpServerConnectionResolverRegistration[];
  cliRegistrars: (PluginRegistrationOwner & {
    register: OpenClawPluginCliRegistrar;
    parentPath: string[];
    commands: string[];
    descriptors: OpenClawPluginCliRootCommandDescriptor[];
  })[];
  reloads: Array<PluginRegistrationOwner & {
    registration: OpenClawPluginReloadRegistration;
  }>;
  nodeHostCommands: PluginNodeHostCommandRegistration[];
  nodeInvokePolicies: (PluginRegistrationOwner & {
    policy: OpenClawPluginNodeInvokePolicy;
    pluginConfig?: Record<string, unknown>;
  })[];
  gatewayAccessPolicies: Array<PluginRegistrationOwner & {
    policy: PluginGatewayAccessPolicy;
  }>;
  securityAuditCollectors: Array<PluginRegistrationOwner & {
    collector: OpenClawPluginSecurityAuditCollector;
  }>;
  services: PluginServiceRegistration[];
  gatewayDiscoveryServices: PluginGatewayDiscoveryServiceRegistration[];
  commands: PluginCommandRegistration[];
  subagentProfiles: RegisteredSubagentProfile[];
  interactiveHandlers: (PluginInteractiveHandlerRegistration & {
    pluginId: string;
    pluginName?: string;
    pluginRoot?: string;
  })[];
  sessionExtensions: Array<PluginRegistrationOwner & {
    extension: PluginSessionExtensionRegistration;
  }>;
  trustedToolPolicies: PluginTrustedToolPolicyRegistryRegistration[];
  toolMetadata: Array<PluginRegistrationOwner & {
    metadata: PluginToolMetadataRegistration;
  }>;
  controlUiDescriptors: Array<PluginRegistrationOwner & {
    descriptor: PluginControlUiDescriptor;
  }>;
  runtimeLifecycles: Array<PluginRegistrationOwner & {
    lifecycle: PluginRuntimeLifecycleRegistration;
  }>;
  agentEventSubscriptions: Array<PluginRegistrationOwner & {
    subscription: PluginAgentEventSubscriptionRegistration;
  }>;
  sessionSchedulerJobs: (PluginRegistrationOwner & {
    job: PluginSessionSchedulerJobRegistration;
    generation?: number;
  })[];
  sessionActions: PluginSessionActionRegistryRegistration[];
  conversationBindingResolvedHandlers: (PluginRegistrationOwner & {
    pluginRoot?: string;
    handler: (event: PluginConversationBindingResolvedEvent) => void | Promise<void>;
  })[];
  diagnostics: PluginDiagnostic[];
};
type PluginRegistryParams = {
  logger: PluginLogger;
  coreGatewayHandlers?: GatewayRequestHandlers;
  coreGatewayMethodNames?: readonly string[];
  runtime: PluginRuntime;
  /** Synchronous factory binding supplied by loaders or direct registry composition roots. */
  resolveCapabilityCatalogContext?: () => PluginCapabilityCatalogHostContext;
  /** Process-owner policy for registering catalogs that may fall back to HOME. */
  allowProcessHomeSessionCatalogs?: boolean;
  hostServices?: {
    /** May be a live accessor; plugin APIs must read it at call time. */
    cron?: CronServiceContract;
  };
  activateGlobalSideEffects?: boolean;
};
//#endregion
//#region src/plugins/plugin-instance-scope.d.ts
/** Runtime consumers retain capabilities, never the concrete loader implementation. */
interface PluginInstanceHandle extends PluginInvocationInstance, PluginInstanceExecution {
  readonly disposing: boolean;
  readonly acceptingCalls: boolean;
  readonly replacementPending: boolean;
  readonly hasRetainedConsumers: boolean;
  readonly owner?: PluginInstanceOwner;
  toolRegistrationComplete: boolean;
  runConsumer<T>(consume: () => T): T;
  adopt<T>(value: T): T;
  admitFactory(factory: (...args: never[]) => unknown, resultCallbacks?: "tool" | readonly PropertyKey[]): void;
  retainWork(reason?: PluginRetentionReason): PluginWorkRelease;
  retentionSnapshot(options?: {
    limit?: number;
    includeOwners?: boolean;
  }): PluginRetentionSnapshot;
  readonly retainedWorkCount: number;
  readonly ordinaryCallCount: number;
  waitForRetainedWork(signal: AbortSignal, options?: {
    includeConsumers?: boolean;
    includeCalls?: boolean;
  }): Promise<void>;
  waitForIdle(signal: AbortSignal): Promise<void>;
  reserveReplacement(operation?: PluginReplacementOperation): () => void;
  retainConsumer(invoke?: <T>(run: () => T) => T, registry?: PluginRegistry, kind?: "work" | "custody", diagnostics?: {
    reason?: PluginRetentionReason;
    owner?: PluginRetentionOwner;
  }): PluginInstanceConsumer;
  runInRegistry<T>(registry: PluginRegistry | undefined, run: () => T, options?: {
    joinDisposal?: boolean;
  }): T;
  createRegistryView(registry: PluginRegistry, invoke: <T>(run: () => T) => T): <T>(value: T) => T;
  drain(options?: {
    includeConsumers?: boolean;
    signal?: AbortSignal;
  }): Promise<PluginInstanceDisposalResult>;
  resume(): void;
}
type PluginInvocationBinding = {
  run: <T>(run: () => T) => T;
  wrap: <T>(value: T) => T;
};
type PluginInstanceOwner = {
  record: PluginRecord;
  instance?: PluginInstanceHandle;
  incarnationId?: string;
} & ({
  revoked: false;
  registry: PluginRegistry;
} | {
  revoked: true;
  registry: PluginRegistry | undefined;
});
//#endregion
//#region src/plugin-sdk/agent-core.d.ts
/** Agent-core class preconfigured with OpenClaw runtime dependencies. */
declare class Agent$1 extends Agent$2 {
  constructor(options?: AgentOptions);
}
//#endregion
//#region src/agents/agent-tools.before-tool-call.types.d.ts
type ToolOutcomeObservation = {
  toolName: string;
  argsHash: string;
  resultHash: string;
  resultContentSource?: AgentTool["resultContentSource"];
  /** Monotonic model-call order within the owning embedded run. */
  toolCallOrdinal?: number;
  terminalPresentation?: string;
  presentationOnly?: boolean;
};
type ToolOutcomeObserver = (observation: ToolOutcomeObservation) => void;
type HookContext = {
  /** Host-owned workspace attribution barrier, captured for this exact run. */
  awaitSessionDiffBaseline?: () => Promise<void>;
  watchdogAttempt?: SessionControllerWatchdogAttempt;
  /** The execution owner's live deadline, excluding lane cleanup grace. */
  getRunAbortDeadlineAtMs?: () => number | undefined;
  agentId?: string;
  config?: OpenClawConfig;
  /** Selected tool registration owner; independent of the hook requesting approval. */
  toolOwnerPluginId?: string;
  /** 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;
  /** What initiated this run, used to reject approvals on unattended surfaces. */
  trigger?: string;
  /** Device-scoped operator session allowed to review approvals initiated by this run. */
  approvalReviewerDeviceId?: string;
  trace?: DiagnosticTraceContext;
  channelId?: string;
  /** Host-derived message requester for sender-aware tool hooks. */
  requester?: PluginHookToolRequesterContext;
  /** Originating channel for approval delivery routing; mirrors exec approval turn-source fields. */
  turnSourceChannel?: string;
  turnSourceTo?: string;
  turnSourceAccountId?: string;
  turnSourceThreadId?: string | number;
  loopDetection?: ToolLoopDetectionConfig;
  onToolOutcome?: ToolOutcomeObserver;
  allocateToolOutcomeOrdinal?: (toolCallId?: string) => number;
  skillsSnapshot?: SkillSnapshot;
  skillUsagePaths?: SkillUsagePath[];
  skillCommand?: {
    commandName: string;
    skillFile?: string;
    skillName: string;
    skillSource?: SkillTelemetrySource;
    toolName?: string;
  };
  sandbox?: {
    root: string;
    bridge: SandboxFsBridge;
  };
};
type BeforeToolCallFailureDisposition = "blocked" | DiagnosticToolTerminalReason;
type PluginApprovalRequest = NonNullable<PluginHookBeforeToolCallResult["requireApproval"]>;
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;
  }>;
};
type HookBlockedReason = "plugin-before-tool-call" | "plugin-approval" | "plugin-approval-unavailable" | "tool-loop";
type HookBlockedOutcome = {
  blocked: true;
  deniedReason?: HookBlockedReason;
  reason: string;
  params?: unknown;
};
type HookOutcome = (HookBlockedOutcome & {
  kind: "veto";
  genericDecision?: true;
}) | (HookBlockedOutcome & {
  kind: "failure";
  disposition: BeforeToolCallFailureDisposition;
}) | {
  blocked: false;
  params: unknown;
  ownerDecision?: true;
  approvalResolution?: PluginApprovalResolution;
  deferredApproval?: DeferredPluginToolApproval;
  loopWarning?: ToolLoopWarning;
};
//#endregion
//#region src/agents/agent-tools.before-tool-call.state.d.ts
/** Detach before mutable execution; mutable hook/middleware inputs get their own copies. */
declare function recordAdjustedParamsForToolCall(toolCallId: string | undefined, params: unknown, runId?: string): void;
/** Consume and remove hook-adjusted params for a completed tool call. */
declare function consumeAdjustedParamsForToolCall(toolCallId: string, runId?: string): unknown;
/** Borrow execution facts without consuming later outcome bookkeeping. */
declare function peekAdjustedParamsForToolCall(toolCallId: string, runId?: string): unknown;
/** Consume whether policy prevented the target tool from starting. */
declare function consumePreExecutionBlockedToolCall(toolCallId: string, runId?: string): boolean;
//#endregion
//#region src/agents/before-tool-call-metadata.d.ts
type BeforeToolCallDiagnosticOptions = {
  emitDiagnostics: boolean;
  protectNetworkErrors?: boolean;
  approvalMode?: "request" | "report" | "deny";
};
declare function isToolWrappedWithBeforeToolCallHook(tool: AnyAgentTool): boolean;
/** Toggle diagnostic event emission on an existing before_tool_call wrapper. */
declare function setBeforeToolCallDiagnosticsEnabled(tool: AnyAgentTool, enabled: boolean): void;
//#endregion
//#region src/agents/agent-tools.before-tool-call.diagnostics.d.ts
/** Finalizes a trusted terminal summary after harness result middleware. */
declare function finalizeToolTerminalPresentation(params: {
  toolCallId: string;
  runId?: string;
  result: Awaited<ReturnType<AnyAgentTool["execute"]>>;
  isError: boolean;
  observer?: ToolOutcomeObserver;
  toolName?: string;
  toolCallOrdinal?: number;
}): void;
//#endregion
//#region src/agents/agent-tools.before-tool-call.approval.d.ts
/** Resolve a deferred plugin approval request at the later execution boundary. */
declare function requestDeferredPluginToolApproval(params: {
  deferredApproval: DeferredPluginToolApproval;
  signal?: AbortSignal;
}): Promise<HookOutcome>;
declare function cancelDeferredPluginToolApproval(deferredApproval: DeferredPluginToolApproval): void;
//#endregion
//#region src/agents/agent-tools.before-tool-call.policy.d.ts
declare function getBeforeToolCallPolicyDiagnosticState(): BeforeToolCallPolicyDiagnosticState;
declare function hasBeforeToolCallPolicy(): boolean;
declare function runBeforeToolCallHook(args: {
  toolName: string;
  params: unknown;
  toolKind?: PluginHookToolKind;
  toolInputKind?: PluginHookToolInputKind;
  toolCallId?: string;
  ctx?: HookContext;
  signal?: AbortSignal;
  approvalMode?: "request" | "report" | "deny" | "defer";
}): Promise<HookOutcome>;
//#endregion
//#region src/agents/agent-tools.before-tool-call.wrapper.d.ts
declare function getBeforeToolCallFailureDisposition(error: unknown): BeforeToolCallFailureDisposition | undefined;
/** Record that one concrete core-owned tool call may use structured replay classification. */
declare function recordStructuredReplayTrustForToolCall(toolCallId: string | undefined, tool: AnyAgentTool, runId?: string): void;
declare function buildBlockedToolResult(params: {
  reason: string;
  deniedReason?: HookBlockedReason;
  toolCallId?: string;
  runId?: string;
}): {
  content: {
    type: "text";
    text: string;
  }[];
  details: {
    status: string;
    deniedReason: HookBlockedReason;
    reason: string;
  };
};
declare function wrapToolWithBeforeToolCallHook(tool: AnyAgentTool, inputContext?: HookContext, options?: Partial<BeforeToolCallDiagnosticOptions>): AnyAgentTool;
/** Rebuild a before_tool_call wrapper while preserving the original source tool. */
declare function rewrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext, options?: Partial<BeforeToolCallDiagnosticOptions>): AnyAgentTool;
declare namespace agent_tools_before_tool_call_d_exports {
  export { BeforeToolCallFailureDisposition, BeforeToolCallPolicyDiagnosticState, DeferredPluginToolApproval, HookContext, ToolOutcomeObservation, ToolOutcomeObserver, buildBlockedToolResult, cancelDeferredPluginToolApproval, consumeAdjustedParamsForToolCall, consumePreExecutionBlockedToolCall, finalizeToolTerminalPresentation, getBeforeToolCallFailureDisposition, getBeforeToolCallPolicyDiagnosticState, hasBeforeToolCallPolicy, isToolWrappedWithBeforeToolCallHook, peekAdjustedParamsForToolCall, recordAdjustedParamsForToolCall, recordStructuredReplayTrustForToolCall, requestDeferredPluginToolApproval, rewrapToolWithBeforeToolCallHook, runBeforeToolCallHook, setBeforeToolCallDiagnosticsEnabled, wrapToolWithBeforeToolCallHook };
}
//#endregion
//#region src/agents/memory-write-provenance.d.ts
type MemoryWriteProvenanceObserver = {
  classifies: (absolutePath: string) => Promise<boolean>;
  write: (params: {
    absolutePath: string;
    contentBefore: string;
    contentAfter: string;
    commit: () => Promise<void>;
  }) => Promise<void>;
  clearAfterDelete: (absolutePath: string, contentBefore: string) => Promise<void>;
};
//#endregion
//#region src/agents/agent-tools.read.d.ts
type SkillInstructionDeliveryCache = Map<string, Promise<boolean>>;
//#endregion
//#region src/agents/bash-tools.process.d.ts
type ProcessToolDefaults = {
  hasCronTool?: boolean;
  inputWaitIdleMs?: number;
  scopeKey?: string;
  sessionKey?: string;
  agentId?: string;
  sessionStore?: string;
};
//#endregion
//#region src/agents/openclaw-tools.model-context.d.ts
type ModelAwareToolContext = {
  agentDir?: string;
  /** Lifecycle generation prepared for the active run. */
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  /** Auth profiles already loaded for prompt-time tool availability. */
  authProfileStore?: AuthProfileStore$1;
  /** Source detection prepared without loading credentials during tool selection. */
  authProfileStoreSource?: boolean;
  /** Whether the active model accepts image content natively; this does not load arbitrary files. */
  modelHasVision?: boolean;
  /** Active provider/model pair used for tool gating. */
  modelProvider?: string;
  modelId?: string;
  /** Effective context ceiling for selected-model model-visible projections. */
  modelContextWindowTokens?: number;
  /** Explicit agent ID override for cron and hook sessions. */
  requesterAgentIdOverride?: string;
};
//#endregion
//#region src/agents/tools/session-portal-target.d.ts
type SessionPortalToolTarget = {
  sessionKey: string;
  agentId: string;
  environmentId: string;
  assertCurrent(): void;
};
//#endregion
//#region src/cron/execution-context-registry.d.ts
/**
 * The session a scheduled run's board and widget tools act on, plus the
 * occurrence's assertion. Tools call `assertCurrent` before and inside each
 * effect so a reset or removed parent, or a settled run, refuses the write.
 */
type ScheduledToolTargets = Readonly<{
  boardSessionKey: string;
  assertCurrent: () => void;
  /**
   * Set when a requester holds the run's owner authority. Owner-only tools call
   * it before each effect, so a requester who stops being an owner is refused.
   */
  assertOwnerCurrent?: () => void;
  /**
   * Where a scheduled occurrence runs relative to its requester. Undefined for
   * ingress turns, which keep their existing surface.
   */
  placement?: ScheduledExecutionFacts["placement"];
  /** The job's exec target pin, from the context's tool policy. */
  execTarget?: ScheduledExecutionFacts["toolPolicy"]["execTarget"];
}>;
//#endregion
//#region src/agents/code-mode-skills.d.ts
type CodeModeSkill = {
  name: string;
  description: string;
  location: string;
  locationNote?: string;
  source: Pick<Skill, "filePath" | "readContent">;
  reader?: CodeModeSkillReader;
};
type CodeModeSkillReader = (params: {
  location: string;
  signal?: AbortSignal;
}) => Promise<string>;
//#endregion
//#region src/agents/installed-skill-catalog.d.ts
type InstalledSkill = CodeModeSkill & {
  /** Prompt-listed instructions retain the shipped Code Mode whole-read contract. */
  promptListed?: boolean;
  assertCurrent?: () => void;
  /** The owner must bound I/O before allocating the returned content. */
  readSearchContent?: (maxBytes: number, signal?: AbortSignal) => Promise<string>;
};
//#endregion
//#region src/agents/spawned-context.d.ts
type SpawnedRunMetadata = {
  spawnedBy?: string | null;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  workspaceDir?: string | null;
};
type SpawnedToolContext = DelegatedToolPolicyContext & {
  /** Host-verified current requester, used only to scope Git credit from main. */
  gitContributorProfileId?: string;
  agentGroupId?: string | null;
  agentGroupChannel?: string | null;
  agentGroupSpace?: string | null;
  agentMemberRoleIds?: string[];
  workspaceDir?: string;
  /** Effective parent-turn level, including one-shot overrides, for child inheritance. */
  requesterThinkingLevel?: ThinkLevel;
  /** Effective parent-turn model; saved preferences may describe a later turn. */
  requesterModel?: ProviderModelRef;
  /** Prepared by tool-policy resolution so building the spawn schema reads no session store; unset uses session-key shape. */
  requesterIsSubagent?: boolean;
  sessionPermissionPolicy?: PreparedSessionPermissionPolicy;
};
//#endregion
//#region src/agents/session-permission-exec-mode.d.ts
/** Pure final projection shared by local tool construction and worker dispatch. */
declare function projectEffectiveExecPolicy(params: {
  base: {
    host?: ExecTarget;
    mode?: ExecMode;
    security?: ExecSecurity;
    ask?: ExecAsk;
  };
  overrides?: {
    host?: ExecTarget;
    mode?: ExecMode;
    security?: ExecSecurity;
    ask?: ExecAsk;
  };
  permissionPolicy?: Pick<PreparedSessionPermissionPolicy, "mode">;
  scheduledExecTarget?: ScheduledToolPolicyContext["execTarget"];
}): {
  host: "auto" | ExecHost | undefined;
  mode: ExecMode | undefined;
  security: ExecSecurity | undefined;
  ask: ExecAsk | undefined;
  bypassHostApprovalFloors: boolean;
};
//#endregion
//#region src/agents/tools/question-prompt-send.d.ts
/** Publishes one prompt into the originating conversation. */
type QuestionPromptSend = (payload: ReplyPayload$1, options?: {
  signal?: AbortSignal;
}) => void | Promise<void>;
/** A run's own way to show a question prompt, plus the channel it would appear in. */
type QuestionPromptDelivery = {
  send: QuestionPromptSend;
  messageChannel?: string;
};
//#endregion
//#region src/agents/run-wait.types.d.ts
/** Normalized terminal or pending state returned by `agent.wait`. */
type AgentWaitResult = {
  status: "ok" | "timeout" | "error" | "pending";
  error?: string;
  /** Set locally when the wait RPC fails; terminal run text is never retry evidence. */
  retryableTransportError?: true;
  startedAt?: number;
  endedAt?: number;
  stopReason?: string;
  livenessState?: string;
  yielded?: boolean;
  pendingError?: boolean;
  timeoutPhase?: AgentRunTimeoutPhase;
  providerStarted?: boolean;
  terminalReply?: AgentRunTerminalReplySnapshot;
  sourceReplyDelivered?: true;
};
//#endregion
//#region src/agents/subagents/registry/subagent-registry-requester-yield.d.ts
/** A requester child whose completion is still owed to the requester session. */
type UnsettledRequesterChild = {
  runId: string;
  childSessionKey: string;
  label?: string;
  startedAt?: number;
  /**
   * Running children have not ended; completing children ended and still owe
   * delivery; paused children yielded for an incoming continuation and will
   * not complete until one arrives.
   */
  state: "running" | "completing" | "paused";
  /** True when an earlier requester yield already armed a settle wake for this child. */
  wakeArmed: boolean;
};
//#endregion
//#region src/agents/tools/sessions-yield-tool.d.ts
/**
 * A harness runtime's yield claim: true when this turn owns a pending completion,
 * or the children an earlier turn left pending that will resume the session.
 */
type SessionsYieldRuntimeClaim = boolean | {
  pendingChildren: readonly UnsettledRequesterChild[];
};
type SessionsYieldCallback = (message: string, acknowledgment?: string, messageWaitRegistered?: boolean, options?: {
  conditional: true;
}) => Promise<void> | void;
//#endregion
//#region src/agents/tools/skill-workshop-tool-factory.d.ts
/** Run-scoped Workshop authority chosen by the run owner, never by tool arguments. */
type SkillWorkshopRunOptions = {
  /** Originating session of a background review; turns on the review guard. */
  reviewOf?: string;
  libraryAuthoring?: SkillLibraryAuthoringCapability;
};
//#endregion
//#region src/agents/openclaw-tools.types.d.ts
/** Options shared by the coding-tool factory and its OpenClaw tool surface. */
type OpenClawSharedToolsOptions = {
  /** Session-owned declaration used only for tool listing, never invocation authority. */
  listingClientCaps?: string[];
  /** Creator policy retained by the scheduled session owner. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
  /** Complete model-discoverable catalog, prepared by the current host. */
  installedSkills?: readonly InstalledSkill[];
  skillsSnapshot?: SkillSnapshot;
  /**
   * Overrides the originating-channel sender for blocking questions. An actual
   * harness prompt reservation retains delivery ownership.
   */
  questionPrompt?: QuestionPromptDelivery;
  toolBindings?: Readonly<Record<string, unknown>>;
  /** Trusted runtime-only authorization for one bounded cross-conversation recall pass. */
  conversationRecall?: ConversationRecallContext;
  /** Host-resolved memory partition shared by plugin tools for this turn. */
  memoryAudience?: MemoryAudience;
  /** Stable mutation identity supplied only for a provider-owned memory flush. */
  memoryFlush?: {
    flushId: string;
  };
  /** Trusted platform-native conversation id for the active inbound turn. */
  nativeChannelId?: string;
  /** Producer-authored bare upload handles mapped to exact sandbox paths. */
  stagedMediaPaths?: ReadonlyMap<string, string>;
  /** Durable store key when it differs from the sandbox/policy session key. */
  runSessionKey?: string;
  /** Ephemeral session UUID — regenerated on /new and /reset. */
  sessionId?: string;
  /** One-shot local CLI runs release plugin-owned resources after their result. */
  oneShotCliRun?: boolean;
  runId?: string;
  computerTransport?: ComputerToolTransport | null;
  /** Current runtime directory used as the default project for follow-up suggestions. */
  cwd?: string;
  /**
   * Workspace directory to pass to spawned subagents for inheritance.
   * Defaults to workspaceDir. Use this to pass the actual agent workspace when the
   * session itself is running in a copied-workspace sandbox (`ro` or `none`) so
   * subagents inherit the real workspace path instead of the sandbox copy.
   */
  spawnWorkspaceDir?: string;
  config?: OpenClawConfig;
  /** Gateway-owned session policy follows runtime updates; explicit overrides stay pinned. */
  sessionConfigSource?: "runtime" | "pinned";
  /** Host-bound history/search scope; does not change mutation or execution identity. */
  sessionReadScopeKey?: string;
  /**
   * Wrap returned tools with the before_tool_call hook at construction time.
   * Defaults to true; callers that already enforce the hook at a later shared
   * boundary should opt out explicitly.
   */
  wrapBeforeToolCallHook?: boolean;
  /** Run-owned Workshop authority: review guard and personal library access. */
  skillWorkshop?: SkillWorkshopRunOptions;
  webFetchHostnameAllowlistRef?: {
    value?: string[];
  };
  webSearchEnabled?: boolean;
  /** Construction fact for prompt guidance; never contains credentials or diagnostics. */
  onWebSearchConfiguration?: (configured: boolean) => void;
  /** Routable target for the current conversation when it differs from the native channel ID. */
  currentMessagingTarget?: string;
  /** Dynamic audio state for runs that can accept steered input after tool creation. */
  hasCurrentInboundAudio?: () => boolean;
  /** Mutable ref to track if a reply was sent (for "first" mode). */
  hasRepliedRef?: {
    value: boolean;
  };
  /** Allow plugin tools for this tool set to late-bind the gateway subagent. */
  allowGatewaySubagentBinding?: boolean;
  runtimeToolAllowlist?: string[];
  /** Session-owned Gateway publication surface; the broker checks current identity and authority. */
  githubPublicationAvailable?: boolean;
  cronCreatorAuthorityUnavailableReason?: CronToolOptions["creatorAuthorityUnavailableReason"];
  /** Mutable model-context generation used to expire screenshot coordinate frames. */
  computerContextEpoch?: {
    value: number;
  };
  computerExecutionId?: string;
  /** Registers run-owned cleanup for tools that hold node resources. */
  registerRunCleanup?: (cleanup: (reason: string) => Promise<void>) => void;
  inboundEventKind?: InboundEventKind;
  disableMessageTool?: boolean;
  swarmCollector?: boolean;
  swarmOutputSchema?: Record<string, unknown>;
  /** Host-only observation after a canonical progress-card replacement commits. */
  onProgressCardPlanSaved?: (unfinished: boolean) => void;
  onYield?: SessionsYieldCallback;
  claimYieldCompletion?: () => SessionsYieldRuntimeClaim | Promise<SessionsYieldRuntimeClaim>;
  /** Records hot-path tool-prep stages for reply startup diagnostics. */
  recordToolPrepStage?: (name: string) => void;
};
type OpenClawToolsOptions = {
  /** Host-owned policy binding; used only by the delegation authority reader. */
  readDelegationConfig?: () => OpenClawConfig;
  /** Actual prepared sandbox passed only by the coding-tool assembly owner. */
  sandbox?: SandboxContext | null;
  abortSignal?: AbortSignal;
  pluginExecutionAuthority?: AdmittedRunOperatorAuthority;
  /** Captured installation identities, independent of prompt-facing sandbox paths. */
  pluginExecutionSkillsSnapshot?: SkillSnapshot;
  /** Host-projected default sandbox surface; cannot execute other session actions. */
  sandboxSessionRenameOnly?: boolean;
  /** Host-issued source for session-control schema projection; execution rechecks the caller. */
  sessionControlAuthority?: AdmittedRunOperatorAuthority;
  /** Host-qualified restricted preview target; never permits Gateway-local ports. */
  sessionPortalTarget?: SessionPortalToolTarget;
  sandboxBrowserBridgeUrl?: string;
  allowHostBrowserControl?: boolean;
  /** Host-prepared local exec parity for this run's managed browser requests. */
  allowLocalBrowserLoopback?: boolean;
  assertLocalBrowserLoopbackCurrent?: () => void;
  agentSessionKey?: string;
  agentChannel?: string;
  /** Prepared active-conversation support for structured human questions. */
  questionInputMode?: ReturnType<typeof resolveConversationQuestionInputMode>;
  /** Host-bound standalone request/grant authority, never supplied by tool arguments. */
  assertInvocationCurrent?: () => void;
  assertInputCommitAllowed?: () => void;
  /** Exact admitted session policy shared with terminal-input authorization. */
  execSession?: ExecSessionDefaults;
  /** Effective run-local exec overrides, including prepared permission mode. */
  execOverrides?: ExecPolicyOverrides;
  /** Host-owned execution path with final callable exec and no unverified client-side policy. */
  delegationExecAuthority?: () => "gateway-host" | undefined;
  /** Trusted operator devices allowed to review this run's terminal input. */
  approvalReviewerDeviceIds?: string[];
  /** Trusted account used for authorization; delivery keeps agentAccountId. */
  gatewayCallerAccountId?: string;
  gatewayCallerChannel?: string | null;
  /** True only for explicit server-authored local scheduled provenance. */
  gatewayCallerLocal?: boolean;
  /** True only for a validated scheduled tool policy. */
  gatewayCallerScheduled?: boolean;
  /** Sessions a scheduled run's board, widget and media tools act on, from its execution context. */
  scheduledToolTargets?: ScheduledToolTargets;
  /** Delivery target for topic/thread routing. */
  agentTo?: string;
  /** Thread/topic identifier for routing replies to the originating thread. */
  agentThreadId?: string | number;
  /** Message-only authority from a CLI grant; does not authorize plugin delivery. */
  messageToolTurnCapability?: {
    token: string;
    sessionKey: string;
  };
  /** Private factory admission for a new scheduled message invocation. */
  admitScheduledMessageInvocation?: () => OpenClawConfig;
  sandboxRoot?: string;
  /** Admitted sandbox policy owner; task and delivery ownership remain with the requester. */
  sandboxAgentId?: string;
  sandboxContainerWorkdir?: string;
  sandboxFsBridge?: SandboxFsBridge;
  sandboxReadOnlyResourceMounts?: readonly {
    hostPath: string;
    containerPath: string;
  }[];
  /** Prepared effective read authorization for exporting sandbox workspace media. */
  sandboxWorkspaceMediaReadAllowed?: boolean;
  fsPolicy?: ToolFsPolicy;
  sandboxed?: boolean;
  cronSandboxContext?: CronToolOptions["sandboxContext"];
  pluginToolAllowlist?: string[];
  pluginToolDenylist?: string[];
  /** Prepared profile authority for the gateway tool's configuration-read actions. */
  gatewayConfigReadAllowed?: boolean;
  /** Effective caller tool surface to persist on isolated cron agentTurn jobs. */
  cronCreatorToolAllowlist?: CronToolOptions["creatorToolAllowlist"];
  cronCreatorToolAllowlistCaptureRef?: CronToolOptions["creatorToolAllowlistCaptureRef"];
  resolveCronCreatorToolAuthority?: CronToolOptions["resolveCreatorToolAuthority"];
  /** Trusted normalized conversation kind for the active inbound turn. */
  currentChatType?: ChatType;
  /** Fail closed instead of posting same-channel thread-originated replies at the root. */
  sameChannelThreadRequired?: boolean;
  pairedNodeComputerUse?: PreparedPairedComputerUse;
  /** If true, nodes action="invoke" can call media-returning commands directly. */
  allowMediaInvokeCommands?: boolean;
  /** Server-owned operation-local origin for conversation-read visibility policy. */
  conversationReadOrigin?: ConversationReadInvocationOrigin;
  /** Restrict cron operations to the active cron job's self-scoped surface. */
  cronSelfRemoveOnlyJobId?: string;
  /** Process-local completion authority restricted to the current source conversation. */
  sourceReplyOnly?: boolean;
  /**
   * Re-checked immediately before a collector result is persisted. Supplied by
   * callers whose collector authority can be revoked while a tool call is
   * already in flight.
   */
  assertCollectorWriteAuthority?: () => void;
  /** If true, skip plugin tool resolution and return only shipped core tools. */
  disablePluginTools?: boolean;
  /** Override or extend the default hook context used by construction-time wrapping. */
  beforeToolCallHookContext?: HookContext;
  /** Trusted sender id from inbound context (not tool args). */
  requesterSenderId?: string | null;
  /** Prepared exec/process isolation key for this run. */
  processScopeKey?: string;
  inputProvenance?: InputProvenance;
} & OpenClawSharedToolsOptions & AgentRunClientContext & AgentRunMessageContext & SpawnedToolContext & ModelAwareToolContext;
//#endregion
//#region src/agents/tool-search-types.d.ts
type CatalogSource = "openclaw" | "mcp" | "client";
type CatalogTool = AnyAgentTool | ToolDefinition$1;
type ToolSearchCatalogToolExecutor = (params: {
  tool: CatalogTool;
  toolName: string;
  source: CatalogSource;
  sourceName?: string;
  toolCallId: string;
  parentToolCallId?: string;
  /** Exact registered-instance classification resolved by the catalog owner. */
  replaySafe?: boolean;
  input: unknown;
  signal?: AbortSignal;
  onUpdate?: AgentToolUpdateCallback;
  acceptResultBeforeProjection: (result: AgentToolResult<unknown>) => Promise<AgentToolResult<unknown>>;
}) => Promise<AgentToolResult<unknown>>;
/** Per-run/session context used by Tool Search control tools. */
type ToolSearchToolContext = {
  modelContextWindowTokens?: number;
  config?: OpenClawConfig;
  runtimeConfig?: OpenClawConfig;
  agentId?: string;
  sessionKey?: string;
  sessionId?: string;
  runId?: string;
  catalogRef?: ToolSearchCatalogRef;
  abortSignal?: AbortSignal;
  executeTool?: ToolSearchCatalogToolExecutor;
  /** Set when the run executes only these tools; swarm globals gate on `sessions_spawn`. */
  toolExecutionAllow?: readonly string[];
  codeModeSkills?: Readonly<AgentToolSurfacePresentation["skills"]>;
};
/** Catalog entry retained behind compacted Tool Search control tools. */
type ToolSearchCatalogEntry = {
  id: string;
  source: CatalogSource;
  sourceName?: string;
  mcp?: PluginToolMcpMeta;
  name: string;
  label?: string;
  description: string;
  /** Recorded when the catalog owner also exposes this tool in the native surface. */
  directVisible?: boolean;
  /** Its bare name also belongs to an eligible tool kept direct outside the catalog. */
  requiresExactId?: boolean;
  parameters?: unknown;
  outputSchema?: TSchema;
  tool: CatalogTool;
};
type ToolSearchCatalogSession = {
  entries: ToolSearchCatalogEntry[];
  counterScope: string;
  searchCount: number;
  describeCount: number;
  callCount: number;
};
type ToolSearchCatalogTelemetry = Omit<ToolSearchCatalogSession, "entries"> & {
  catalogSize: number;
  sources: Record<CatalogSource, number>;
};
type ToolSearchCatalogRef = {
  current?: ToolSearchCatalogSession;
  directOnlyToolNames?: ReadonlySet<string>;
  baselineDirectOnlyToolNames?: ReadonlySet<string>;
  closedTelemetry?: ToolSearchCatalogTelemetry;
  onDispose?: Set<() => void>;
};
//#endregion
//#region src/agents/agent-tools.options.d.ts
/** Public options for building one plugin-owned agent tool surface. */
type OpenClawCodingToolsOptions = {
  agentId?: string;
  /** Retained policy owner; execution identity remains agentId/runSessionKey. */
  policyAgentId?: string;
  exec?: ExecToolDefaults & ProcessToolDefaults;
  /** Specific ingress provider used only for transport tool availability. */
  toolPolicyMessageProvider?: string;
  messageTo?: string;
  messageThreadId?: string | number;
  sandbox?: SandboxContext | null;
  sessionKey?: string;
  requesterThinkingLevel?: ThinkLevel;
  requesterModel?: SpawnedToolContext["requesterModel"];
  /** Exact admitted run instance for lifecycle-bound subprocess capabilities. */
  operationalRunInstance?: OperationalRunInstanceRef;
  /** Host-prepared effective paired-node Computer Use surface. */
  pairedNodeComputerUse?: PreparedPairedComputerUse;
  /** Diagnostic trace context for hook/log correlation during this run. */
  trace?: DiagnosticTraceContext;
  /** What initiated this run (for trigger-specific tool restrictions). */
  trigger?: string;
  /** Stable cron job identifier populated for cron-triggered runs. */
  jobId?: string;
  /** Relative workspace path that memory-triggered writes may append to. */
  memoryFlushWritePath?: string;
  /** Provider-owned persistence surface for a tools-arm memory flush. */
  memoryFlushTools?: MemoryFlushToolRunContext;
  workspaceDir?: string;
  /** Additional containment for a trusted scheduled workspace; never weakens configured policy. */
  requireWorkspaceOnly?: true;
  sessionPermissionPolicy?: PreparedSessionPermissionPolicy;
  abortSignal?: AbortSignal;
  /** Disable hook-owned diagnostics when an outer runtime owns tool diagnostics. */
  emitBeforeToolCallDiagnostics?: boolean;
  /** Attempt-local authority to start or redirect delegated work. */
  delegationCapability?: DelegationCapability;
  /** Model API for the current provider (used for provider-native tool arbitration). */
  modelApi?: string;
  /** Resolved endpoint for provider-native tool eligibility. */
  modelBaseUrl?: string;
  /** Secret-free capability facts from the selected runtime model route. */
  modelParams?: Record<string, unknown>;
  /** Resolved runtime model compatibility hints. */
  modelCompat?: ModelCompatConfig;
  /** If false, keep OpenClaw web_search even when a provider-native search tool is active. */
  suppressManagedWebSearch?: boolean;
  /**
   * Auth mode for the current provider. We only need this for Anthropic OAuth
   * tool-name blocking quirks.
   */
  modelAuthMode?: ModelAuthMode;
  /** Normalized conversation id exposed to tool hooks. Defaults to currentChannelId. */
  hookChannelId?: string;
  /** Trusted provider role ids for the requester in this group turn. */
  memberRoleIds?: string[];
  /** True when runtimeToolAllowlist is real parent authority that child sessions inherit. */
  inheritRuntimeToolAllowlist?: boolean;
  /** Plugin-owned optional tools granted to this run (e.g. subagent toolsAlsoAllow). */
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  /** Mutable spawn capability snapshot refreshed after late-bound runtime tools are authorized. */
  inheritedToolAllowlistRef?: string[];
  /** Mutable cron creator cap ref for callers that append final runtime tools later. */
  cronCreatorToolAllowlistRef?: CronCreatorToolAllowlistEntry[];
  /** Mutable proof that the cron cap reached the final executable surface. */
  cronCreatorToolAllowlistCaptureRef?: CronToolsAllowCaptureRef;
  /** Attempt-local full skill reads that remain visible in the model context. */
  skillInstructionDeliveryCache?: SkillInstructionDeliveryCache;
  /** Keep the message tool available even when the selected profile omits it. */
  forceMessageTool?: boolean;
  /** If false, build plugin tools only while preserving the shared policy pipeline. */
  includeCoreTools?: boolean;
  /** Include Tool Search control tools when enabled for this run. */
  includeToolSearchControls?: boolean;
  /** Executes cataloged tools through the active agent run lifecycle. */
  toolSearchCatalogExecutor?: ToolSearchCatalogToolExecutor;
  /** Runtime-local Tool Search catalog ref shared with attempt compaction. */
  toolSearchCatalogRef?: ToolSearchCatalogRef;
  /** Already-admitted skill locations for mistaken tool-id recovery. */
  codeModeSkills?: ToolSearchToolContext["codeModeSkills"];
  /** Limits which tool families are materialized before the shared policy pipeline runs. */
  toolConstructionPlan?: OpenClawCodingToolConstructionPlan;
  /** Ring-zero OpenClaw tool; set only by the OpenClaw agent runner. */
  systemAgentTool?: SystemAgentToolOptions;
  /** Live observer called after wrapped tool outcomes are recorded. */
  onToolOutcome?: ToolOutcomeObserver;
  /** Reads the sticky untrusted-content flag for the current user turn. */
  isTurnTainted?: () => boolean;
  /** Supplies run-global model-call ordering for parallel tool outcomes. */
  allocateToolOutcomeOrdinal?: (toolCallId?: string) => number;
  /** Original identities for sandbox-materialized skill instruction paths. */
  skillUsagePaths?: SkillUsagePath[];
  /** Prepared conversation-scoped facts for callers that already resolved this run context. */
  conversationCapabilityProfile?: ResolvedConversationCapabilityProfile;
  /** Trusted conversation policy prepared at channel ingress. */
  conversationToolPolicy?: GroupToolPolicyConfig;
  inputProvenance?: InputProvenance;
  /** Consumed in-process completion capability; never derived from model-facing input. */
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
} & OpenClawSharedToolsOptions & Omit<ModelAwareToolContext, "requesterAgentIdOverride"> & AgentRunClientContext & AgentRunMessageContext & AgentRunChannelContext;
type InternalCodingToolsOptions = OpenClawCodingToolsOptions & {
  readDelegationConfig?: OpenClawToolsOptions["readDelegationConfig"];
  assertInvocationCurrent?: () => void;
  /** Live harness-owned local execution, independent of the Gateway tool catalog. */
  nativeHarnessExecution?: true;
  /** Host-recorded handoff to a caller whose additional execution policy is unknown. */
  unverifiedExecutionPolicy?: true;
  pluginExecutionAuthority?: AdmittedRunOperatorAuthority;
  pluginExecutionSkillsSnapshot?: SkillSnapshot;
  awaitSessionDiffBaseline?: () => Promise<void>;
  /** Execution owner's current deadline, without lane cleanup grace. */
  getRunAbortDeadlineAtMs?: () => number | undefined;
  /** Policy-approved tool names unavailable here but usable in a child's own workspace. */
  additionalInheritedToolNamesRef?: string[];
  /** The host owns continuation policy when this factory builds only part of its tool surface. */
  sessionEventSourcePolicy?: SessionEventSourcePolicy;
};
type PluginCodingToolsOptions = Omit<OpenClawCodingToolsOptions, "sessionReadScopeKey" | "onProgressCardPlanSaved" | "authProfileStoreSource" | "onWebSearchConfiguration">;
//#endregion
//#region src/agents/tool-construction-preparation.d.ts
type ToolConstructionPreparationOptions = {
  signal?: AbortSignal;
  assertCurrent?: () => void;
  env?: NodeJS.ProcessEnv;
  cwd?: string;
  reader?: SessionEntryCohortReader;
};
type CapturedToolConstruction = {
  config: OpenClawConfig | undefined;
  env: NodeJS.ProcessEnv;
  cwd: string;
  statePath: string;
  admitStateRead: () => void;
  assertCurrent: () => void;
};
type PreparedToolConstruction = Omit<CapturedToolConstruction, "statePath" | "admitStateRead"> & {
  loadExecApprovals: () => Promise<ExecApprovalsFile>;
  reader?: SessionEntryCohortReader;
};
//#endregion
//#region src/agents/agent-tools.execution-policy.d.ts
type BrowserLoopbackParams = {
  options?: InternalCodingToolsOptions;
  execApprovals?: ExecApprovalsFile;
  capabilityProfile: ResolvedConversationCapabilityProfile;
  effectiveExecPolicy: ReturnType<typeof projectEffectiveExecPolicy>;
  sandboxed: boolean;
  workspaceOnly: boolean;
  assertConfigCurrent?: () => void;
};
/** Optional policy preparation must never disable ordinary browser tools. */
declare function createLocalBrowserLoopbackPreparation(params: BrowserLoopbackParams): {
  assertCurrent: (() => void) | undefined;
  sync(): void;
  prepare(shared: PreparedToolConstruction): Promise<void>;
} | undefined;
//#endregion
//#region src/agents/channel-tools.d.ts
declare function listChannelAgentTools(params: {
  cfg?: OpenClawConfig;
}): ChannelAgentTool[];
//#endregion
//#region src/agents/apply-patch-containment-hint.d.ts
/** Which layer contained apply_patch, and therefore which operator explanation applies. */
type ApplyPatchContainmentSource = "config" | "session" | "required-root";
//#endregion
//#region src/agents/core-coding-tools.d.ts
type CoreCodingToolsOptions = {
  abortSignal?: AbortSignal;
  attachmentReadRoot?: string;
  codingRoot: string;
  containmentRoot: string;
  includeBaseCodingTools: boolean;
  shellTools: "disabled" | "patch-only" | "full";
  workspaceOnly: boolean;
  readOnly: boolean;
  sandbox?: SandboxContext;
  skillsSnapshot?: SkillSnapshot;
  skillReadResources?: SkillSnapshot["resolvedSkills"];
  skillInstructionPaths?: readonly string[];
  skillInstructionDeliveryCache?: SkillInstructionDeliveryCache;
  modelContextWindowTokens?: number;
  imageSanitization?: ImageSanitizationLimits;
  modelHasVision?: boolean;
  memoryWriteProvenance?: MemoryWriteProvenanceObserver;
  applyPatchEnabled: boolean;
  applyPatchWorkspaceOnly: boolean;
  applyPatchContainmentSource?: ApplyPatchContainmentSource;
  execDefaults: ExecToolDefaults;
  processDefaults: ProcessToolDefaults;
  recordToolPrepStage?: (name: string) => void;
};
/** Materialize only the core file and shell families selected by the runtime owner. */
declare function createCoreCodingTools(options: CoreCodingToolsOptions): AnyAgentTool[];
//#endregion
//#region src/agents/openclaw-tools.plugin-context.d.ts
type OpenClawPluginToolOptions = Pick<OpenClawToolsOptions, "agentSessionKey" | "runSessionKey" | "runId" | "inputProvenance" | "assertInvocationCurrent" | "assertInputCommitAllowed" | "agentChannel" | "agentAccountId" | "agentTo" | "currentMessagingTarget" | "currentChannelId" | "agentThreadId" | "approvalReviewerDeviceIds" | "nativeChannelId" | "messageActionTurnCapability" | "agentDir" | "workspaceDir" | "config" | "fsPolicy" | "modelProvider" | "modelId" | "modelContextWindowTokens" | "requesterSenderId" | "senderIsOwner" | "memoryAudience" | "memoryFlush" | "conversationReadOrigin" | "requesterAgentIdOverride" | "sessionId" | "conversationRecall" | "oneShotCliRun" | "sandboxBrowserBridgeUrl" | "allowHostBrowserControl" | "allowLocalBrowserLoopback" | "assertLocalBrowserLoopbackCurrent" | "sandboxed" | "allowGatewaySubagentBinding" | "toolBindings" | "sandbox" | "abortSignal" | "pluginExecutionSkillsSnapshot" | "pluginExecutionAuthority"> & {
  activeProjectKeys?: readonly string[];
  approvalReviewerDeviceId?: string;
};
//#endregion
//#region src/agents/openclaw-plugin-tools.d.ts
type ResolveOpenClawPluginToolsOptions = OpenClawPluginToolOptions & {
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  pluginToolAllowlist?: string[];
  pluginToolDenylist?: string[];
  clientCaps?: string[];
  authProfileStore?: AuthProfileStore$1;
};
type PluginToolOptions = {
  options?: ResolveOpenClawPluginToolsOptions;
  resolvedConfig?: OpenClawConfig;
  existingToolNames?: Set<string>;
};
declare function resolveOpenClawPluginToolsForOptions(params: PluginToolOptions): AnyAgentTool[];
//#endregion
//#region src/agents/agent-tools.preparation.d.ts
/** The assembly owns order; these adapters satisfy each preparation request. */
type CodingToolAssembly = Generator<OpenClawToolsOptions | {
  coreTools: Parameters<typeof createCoreCodingTools>[0];
} | {
  channelTools: Parameters<typeof listChannelAgentTools>[0];
} | {
  prepareBrowserLoopback: NonNullable<ReturnType<typeof createLocalBrowserLoopbackPreparation>>;
} | {
  pluginTools: Parameters<typeof resolveOpenClawPluginToolsForOptions>[0];
}, AnyAgentTool[], AnyAgentTool[]>;
//#endregion
//#region src/agents/prepared-tool-surface.d.ts
type CoreToolPolicyOptions = Pick<OpenClawCodingToolsOptions, "config" | "agentId" | "sessionPermissionPolicy" | "requireWorkspaceOnly" | "trigger" | "memoryFlushWritePath" | "modelProvider" | "modelId" | "modelContextWindowTokens" | "modelHasVision">;
/** Resolve once on the Gateway; placement hosts consume these secret-free facts. */
declare function prepareCoreToolPolicy(options: CoreToolPolicyOptions, execConfig?: {
  host: "auto" | "gateway" | "node" | "sandbox" | undefined;
  mode: ExecMode | undefined;
  security: ExecSecurity | undefined;
  ask: ExecAsk | undefined;
  node: string | undefined;
  configuredPathPrepend: string[] | undefined;
  pathPrepend: string[] | undefined;
  safeBins: string[] | undefined;
  strictInlineEval: boolean | undefined;
  commandHighlighting: boolean;
  safeBinTrustedDirs: string[] | undefined;
  safeBinProfiles: Record<string, SafeBinProfileFixture> | undefined;
  reviewer: {
    model?: string | {
      primary?: string | undefined;
      fallbacks?: string[] | undefined;
    } | undefined;
    thinking?: "high" | "low" | "max" | "medium" | "minimal" | "xhigh" | undefined;
    fastMode?: boolean | undefined;
    timeoutMs?: number | undefined;
  } | undefined;
  backgroundMs: number | undefined;
  timeoutSec: number | undefined;
  approvalRunningNoticeMs: number | undefined;
  cleanupMs: number | undefined;
  notifyOnExit: boolean | undefined;
  notifyOnExitEmptySuccess: boolean | undefined;
  applyPatch: {
    enabled?: boolean | undefined;
    workspaceOnly?: boolean | undefined;
    allowModels?: string[] | undefined;
  } | undefined;
}): {
  workspaceOnly: boolean;
  readOnly: boolean;
  applyPatchEnabled: boolean;
  applyPatchWorkspaceOnly: boolean;
  applyPatchContainmentSource: ApplyPatchContainmentSource;
  imageSanitization: ImageSanitizationLimits;
  modelContextWindowTokens: number | undefined;
  modelHasVision: boolean | undefined;
  memoryFlushWritePath?: string | undefined;
};
//#endregion
//#region src/agents/sandbox-tool-policy.d.ts
/** Provenance marker for wildcard allowlists created from `alsoAllow`. */
declare const IMPLICIT_ALLOW_ALL_FROM_ALSO_ALLOW: unique symbol;
//#endregion
//#region src/agents/tool-policy.d.ts
/** Tool allow/deny policy shape accepted by agent and sandbox config. */
type ToolPolicyLike = {
  allow?: string[];
  deny?: string[];
  [IMPLICIT_ALLOW_ALL_FROM_ALSO_ALLOW]?: true;
};
//#endregion
//#region src/agents/tool-policy-pipeline.d.ts
/** Provenance travels with the decision; consumers never infer it from log labels. */
type ToolPolicySource = {
  kind: "profile" | "config" | "session" | "runtime";
  path?: string;
  profile?: string;
  alsoAllowPath?: string;
};
type ToolPolicyPipelineStep = {
  policy: ToolPolicyLike | undefined;
  label: string;
  source?: ToolPolicySource;
  stripPluginOnlyAllowlist?: boolean;
  suppressUnavailableCoreToolWarning?: boolean;
  suppressUnavailableCoreToolWarningAllowlist?: string[];
  unavailableCoreToolReason?: string;
};
/** One policy application, exposed for diagnostics that need exclusion provenance. */
type ToolPolicyFilterEvent<TTool extends {
  name: string;
} = AnyAgentTool> = {
  step: ToolPolicyPipelineStep;
  policy: ToolPolicyLike;
  before: readonly TTool[];
  after: readonly TTool[];
};
//#endregion
//#region src/agents/agent-tools.assembly.d.ts
declare function assembleOpenClawCodingTools(options?: InternalCodingToolsOptions, skillReadResources?: SkillSnapshot["resolvedSkills"], onPolicyFilter?: (event: ToolPolicyFilterEvent) => void, preparedSurface?: {
  tools: AnyAgentTool[];
  policy: ReturnType<typeof prepareCoreToolPolicy>;
}, assertLoopbackConfigCurrent?: () => void): CodingToolAssembly;
//#endregion
//#region src/agents/agent-tools.async.d.ts
/** Internal preparation data stays outside the public harness factory options. */
declare function createOpenClawCodingToolsInternalAsync(options?: InternalCodingToolsOptions, skillReadResources?: SkillSnapshot["resolvedSkills"], onPolicyFilter?: (event: ToolPolicyFilterEvent) => void, preparedSurface?: {
  tools: AnyAgentTool[];
  policy: ReturnType<typeof prepareCoreToolPolicy>;
}, preparation?: ToolConstructionPreparationOptions): Promise<AnyAgentTool[]>;
/** Build the SDK tool list with a fresh, source-bound exec policy. */
declare function createOpenClawCodingToolsAsync(options?: PluginCodingToolsOptions): Promise<AnyAgentTool[]>;
//#endregion
//#region src/agents/tool-loop-detection-config.d.ts
declare function resolveToolLoopDetectionConfig(params: {
  cfg?: OpenClawConfig;
  agentId?: string;
}): ToolLoopDetectionConfig | undefined;
declare namespace agent_tools_d_exports {
  export { createOpenClawCodingTools, createOpenClawCodingToolsAsync, createOpenClawCodingToolsInternal, createOpenClawCodingToolsInternalAsync, resolveToolLoopDetectionConfig };
}
/** @deprecated Use createOpenClawCodingToolsInternalAsync for runtime construction. */
declare function createOpenClawCodingToolsInternal(...args: Parameters<typeof assembleOpenClawCodingTools>): AnyAgentTool[];
/** @deprecated Use createOpenClawCodingToolsAsync to prepare policy through the worker. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
declare function createOpenClawCodingTools(options?: PluginCodingToolsOptions): AnyAgentTool[];
//#endregion
//#region src/agents/harness/current-input-budget.d.ts
/** Returns the host note with the staged path, bounded by noteMaxChars, or undefined. */
type StageCurrentInputAttachment = (noteMaxChars: number, media: MediaFact[]) => Promise<string | undefined>;
//#endregion
//#region src/agents/embedded-agent-utils.d.ts
declare function extractEmbeddedAssistantText(msg: AssistantHistoryMessage): string;
declare function formatReasoningMessage(text: string): string;
//#endregion
//#region src/agents/embedded-agent-runner/replay-state.d.ts
type EmbeddedRunReplayState = {
  replayInvalid: boolean;
  hadPotentialSideEffects: boolean;
};
/** Serializable replay metadata stored with run results. */
type EmbeddedRunReplayMetadata = {
  hadPotentialSideEffects: boolean;
  replaySafe: boolean;
};
//#endregion
//#region src/agents/failover/provider-patterns.d.ts
type ProviderSpecificErrorContext = {
  provider?: string;
  modelId?: string;
  errorMessage: string;
  status?: number;
  code?: string;
  errorType?: string;
  providerPlugin?: PreparedProviderFailoverOwner | null;
};
type PreparedProviderFailoverOwner = {
  id: string;
  matchesContextOverflowError?: (ctx: ProviderSpecificErrorContext) => boolean | undefined;
  classifyFailoverReason?: (ctx: ProviderSpecificErrorContext) => FailoverReason | null | undefined;
};
//#endregion
//#region src/agents/embedded-agent-subscribe.types.d.ts
type SubscribeEmbeddedAgentSessionParams = Pick<EmbeddedRunAttemptParams, "runId" | "lifecycleGeneration" | "messageChannel" | "initialReplayState" | "assistantErrorTranscript" | "verboseLevel" | "toolResultFormat" | "toolProgressDetail" | "shouldEmitToolResult" | "shouldEmitToolOutput" | "sourceReplyDeliveryMode" | "messageToolFinalByDefault" | "onToolResult" | "onAgentToolResult" | "observeToolTerminal" | "trajectoryRecorder" | "onReasoningStream" | "streamReasoningInNonStreamModes" | "onReasoningEnd" | "onBlockReply" | "onBlockReplyFlush" | "blockReplyBreak" | "blockReplyChunking" | "onPartialReply" | "onAssistantMessageStart" | "onAgentEvent" | "onToolStreamBoundary" | "enforceFinalTag" | "silentExpected" | "suppressLiveStreamOutput" | "config" | "sessionPersistence" | "sessionKey" | "currentChannelId" | "currentMessagingTarget" | "currentMessageId" | "replyToMode" | "hasRepliedRef" | "agentId" | "internalEvents"> & {
  session: AgentSession;
  hookRunner?: HookRunner;
  reasoningMode?: ReasoningLevel;
  thinkingLevel?: ThinkLevel;
  /** Attempt-owned delivery proof for message-tool-only source replies. */
  hasDeliveredMessageToolOnlySourceReply?: () => boolean;
  /** Reports source delivery observed through bridged tool lifecycle events. */
  onDeliveredMessageToolOnlySourceReply?: () => void;
  /** Assistant fragment usage before queued delivery; fragments may be intermediate. */
  onModelUsage?: (usage: NormalizedUsage | undefined, identity?: Pick<AssistantMessage, "responseId" | "turnId">) => void;
  onExecutionPhase?: (info: {
    phase: "tool_execution_started";
    tool?: string;
    toolCallId?: string;
    source?: string;
  }) => void;
  /** "finishing" defers both success and error terminal ownership to the caller. */
  terminalLifecyclePhase?: "end" | "finishing";
  /** Read immediately before terminal lifecycle emission. */
  isTerminalAborted?: () => boolean | undefined;
  /** Override the terminal stop reason from the current abort owner. */
  resolveTerminalStopReason?: () => string | undefined;
  /** Same-prompt checks can retain ordinary streaming instead of buffering a draft. */
  deferTerminalDelivery?: boolean;
  /** Gate final block delivery/lifecycle after the natural answer is known. */
  onBeforeTerminalDelivery?: (event: {
    messages: AgentMessage[];
    willRetry: boolean;
    assistantEntryId?: string;
    lastAssistant?: AgentMessage;
    assistantTexts: readonly string[];
    hasAssistantVisibleText: boolean;
    isError: boolean;
    incompleteTerminalAssistant: boolean;
    hadDeterministicSideEffect: boolean;
    hasPendingContinuation: boolean;
  }) => void | Promise<void | {
    suppressTerminalDelivery?: boolean;
    continueCurrentTurn?: boolean;
  }>;
  /** Best-effort hook invoked immediately before the terminal lifecycle event is emitted. */
  onBeforeLifecycleTerminal?: () => void | Promise<void>;
  /** Prepared endpoint ownership can differ from the assistant's provider route ID. */
  providerOwner?: PreparedProviderFailoverOwner;
  compactionCountOwner?: EmbeddedRunAttemptInternalParams["compactionCountOwner"];
  onContextAccountingEvent?: EmbeddedRunAttemptInternalParams["onContextAccountingEvent"];
  currentAccountId?: string;
  /** Current transport thread resolved for this run. */
  currentThreadId?: string;
  /** Ephemeral session UUID — regenerated on /new and /reset. */
  sessionId?: string;
  /**
   * Exact raw names of OpenClaw tools registered for this run.
   */
  builtinToolNames?: ReadonlySet<string>;
  /** Exact raw names of core-owned tools registered for this run. */
  coreBuiltinToolNames?: ReadonlySet<string>;
  /** Exact registered tool names whose concrete instances are safe to replay. */
  replaySafeToolNames?: ReadonlySet<string>;
  /** Exact names of the marked Code Mode `exec` control tool(s) registered for this run. */
  codeModeExecToolNames?: ReadonlySet<string>;
  /** Exact names of tools whose author declared `canDeliverSourceReply`. */
  sourceReplyCapableToolNames?: ReadonlySet<string>;
  /** Canonical owner keys for unique plugin tools that can change durable state. */
  sideEffectToolOwners?: ReadonlyMap<string, string>;
  /**
   * Exact raw names allowed to emit local media paths for this run.
   * Includes core trusted tools plus bundled plugin tools proven from the
   * startup metadata snapshot.
   */
  trustedLocalMediaToolNames?: ReadonlySet<string>;
};
//#endregion
//#region src/agents/tool-error-summary.d.ts
type ProcessTerminalDiagnostic = {
  kind: "process";
  sessionId: string;
  reason: {
    kind: "exit";
    exitCode: number;
  } | {
    kind: "signal";
    signal: string | number;
  } | {
    kind: "timeout";
    timeoutKind?: "overall-timeout" | "no-output-timeout";
  };
};
type ToolErrorSummary = {
  toolName: string;
  executionStarted?: boolean;
  /** The call named no tool this run has, so no later call can share its tool identity. */
  unknownTool?: true;
  meta?: string;
  errorCode?: string;
  error?: string;
  validationErrorSummary?: string;
  timedOut?: boolean;
  middlewareError?: boolean;
  mutatingAction?: boolean;
  terminalDiagnostic?: ProcessTerminalDiagnostic | {
    kind: "timeout";
    timeoutMs: number;
    partialResults?: number;
  };
};
//#endregion
//#region src/agents/embedded-agent-subscribe.run-state.d.ts
/** A response-ending answer and the message index its reply payload belongs to. */
type CompletedAssistantAnswer = {
  assistant: AssistantHistoryMessage;
  messageIndex: number;
};
//#endregion
//#region src/agents/embedded-agent-subscribe.d.ts
declare function subscribeEmbeddedAgentSession(input: SubscribeEmbeddedAgentSessionParams): {
  assistantTexts: string[];
  answerSegments: {
    textEnd: number;
    messageEnd: number;
    finalMessageStart: number;
    lastAssistant: AssistantHistoryMessage;
    keptAnswer?: CompletedAssistantAnswer;
    sourceReplyDeliveryState?: ReplyDeliveryState;
  }[];
  getCurrentAttemptAssistant: () => AssistantHistoryMessage | undefined;
  getKeptAnswer: () => CompletedAssistantAnswer | undefined;
  hasSuccessfulModelResponse: () => boolean;
  getLastAssistantTextMessageIndex: () => number | undefined;
  toolMetas: ({
    toolName: string;
    toolCallId?: string;
    meta?: string;
    replaySafe?: boolean;
    isError?: boolean;
    terminate?: boolean;
    asyncStarted?: boolean;
    asyncTaskRunId?: string;
    asyncTaskId?: string;
    codeModeSuspended?: boolean;
  } & {
    parentToolCallId?: string;
    activity?: AgentItemEventData;
  })[];
  getAcceptedSessionSpawns: () => AcceptedSessionSpawn[];
  getLatestMcpAppChannelView: () => {
    viewId: string;
  } | undefined;
  getLatestMcpConnectAction: () => {
    serverName: string;
    authorizationUrl: string;
  } | undefined;
  runToolLifecycle: <T>(toolParams: {
    toolName: string;
    toolCallId: string;
    parentToolCallId?: string;
    args: unknown;
    replaySafe?: boolean;
    hideFromChannelProgress?: boolean;
    execute: (onImplementationStart: () => void) => Promise<T>;
    onTerminal?: (terminal: {
      result: unknown;
      readSanitizedResult: () => unknown;
      isError: boolean;
      executedArguments: unknown;
      effectReceipt: ToolEffectReceipt;
    }) => void | false | Promise<void | false>;
  }) => Promise<T>;
  unsubscribe: () => void;
  setTerminalLifecycleMeta: (meta: {
    replayInvalid?: boolean;
    livenessState?: EmbeddedRunLivenessState;
    stopReason?: string;
    yielded?: boolean;
    timeoutPhase?: AgentRunTimeoutPhase;
    providerStarted?: boolean;
    aborted?: boolean;
  }) => void;
  isCompacting: () => boolean;
  isCompactionInFlight: () => boolean;
  getMessagingToolSentTexts: () => string[];
  getMessagingToolSentMediaUrls: () => string[];
  getMessagingToolSentTargets: () => MessagingToolSend[];
  getMessagingToolSourceReplyPayloads: () => MessagingToolSourceReplyPayload[];
  getSourceReplyDelivered: () => true | undefined;
  getSourceReplyDeliveryState: () => ReplyDeliveryState | undefined;
  endsWithSourceProgress: () => boolean;
  getPendingToolMediaReply: () => BlockReplyPayload | null;
  getToolAutoDeliveryMediaUrls: () => string[];
  hasToolMediaBlockReply: () => boolean;
  getVisibleBlockReplyCount: () => number;
  getSuccessfulCronAdds: () => number;
  getReplayState: () => {
    replayInvalid: boolean;
    hadPotentialSideEffects: boolean;
  };
  didSendViaMessagingTool: () => boolean;
  didSendDeterministicApprovalPrompt: () => boolean;
  getLastToolError: () => {
    toolName: string;
    executionStarted?: boolean;
    unknownTool?: true;
    meta?: string;
    errorCode?: string;
    error?: string;
    validationErrorSummary?: string;
    timedOut?: boolean;
    middlewareError?: boolean;
    mutatingAction?: boolean;
    terminalDiagnostic?: ProcessTerminalDiagnostic | {
      kind: "timeout";
      timeoutMs: number;
      partialResults?: number;
    };
  } | undefined;
  getUsageTotals: () => NormalizedUsage | undefined;
  getLastAssistantUsage: () => NormalizedUsage | undefined;
  getCompactionCount: () => number;
  getLastCompactionTokensAfter: () => number | undefined;
  getAssistantTurnCount: () => number;
  waitForPendingEvents: (options?: {
    includePartialReplies?: boolean;
  }) => Promise<void>;
  flushPartialAssistantText: () => void;
  getItemLifecycle: () => {
    startedCount: number;
    completedCount: number;
    activeCount: number;
  };
  waitForCompactionRetry: () => Promise<void>;
};
//#endregion
//#region src/agents/code-mode-mcp-api.d.ts
/** Virtual TypeScript-style API file exposed to code mode. */
type CodeModeApiVirtualFile = {
  path: string;
  description?: string;
  content: string;
  bytes: number;
};
//#endregion
//#region src/agents/code-mode-json.d.ts
type CodeModeJsonSource = {
  kind: "complete";
  json: string;
} | {
  kind: "prefix";
  json: string;
  originalBytes: number;
};
type CodeModeOutputSource = {
  count: number;
  source: CodeModeJsonSource;
};
declare const EMPTY_CODE_MODE_OUTPUT: CodeModeOutputSource;
/** Capture after guest conversion, before any public projection discards source facts. */
declare function captureCodeModeValue(value: unknown, maxBytes: number, structuredMaxBytes?: number): CodeModeJsonSource;
declare function captureCodeModeOutput(output: unknown[], maxBytes: number): CodeModeOutputSource;
declare function boundCodeModeError(error: string, maxBytes: number): string;
//#endregion
//#region src/agents/code-mode-namespaces.d.ts
/** JSON-serializable descriptor value emitted to the code-mode runtime. */
type SerializedCodeModeNamespaceValue = {
  kind: "array";
  items: SerializedCodeModeNamespaceValue[];
} | {
  kind: "function";
  path: string[];
} | {
  kind: "object";
  entries: Array<[string, SerializedCodeModeNamespaceValue]>;
} | {
  kind: "value";
  value: unknown;
};
type CodeModeNamespaceDescriptor = {
  id: string;
  globalName: string;
  description?: string;
  scope: SerializedCodeModeNamespaceValue;
};
//#endregion
//#region src/agents/code-mode-worker-types.d.ts
declare const CODE_MODE_WORKER_WATCHDOG_GRACE_MS = 2000;
declare const CODE_MODE_BRIDGE_METHODS: readonly ["search", "describe", "callValue", "resultSave", "resultLoad", "resultDelete", "nodes", "yield", "namespace", "agentSpawn", "agentWait", "skillsList", "skillsSearch", "skillsRead", "sleep", "swarmNote"];
type CodeModeBridgeMethod = (typeof CODE_MODE_BRIDGE_METHODS)[number];
type CodeModeConfig = {
  timeoutMs: number;
  memoryLimitBytes: number;
  maxOutputBytes: number;
  maxPendingToolCalls: number;
  maxSnapshotBytes: number;
};
type PendingBridgeRequest = {
  id: string;
  method: CodeModeBridgeMethod;
  args: unknown[];
};
type SettledBridgeRequest = {
  id: string;
  ok: boolean;
  json: string;
};
type CodeModeWorkerInput<State> = {
  kind: "exec";
  source: string;
  prelude?: string;
  executionTimeoutMs?: number;
  config: CodeModeConfig;
  catalog: unknown[];
  apiFiles?: CodeModeApiVirtualFile[];
  namespaces: CodeModeNamespaceDescriptor[];
  swarmEnabled?: boolean;
} | {
  kind: "resume";
  continuation: State;
  config: CodeModeConfig;
  settledRequests: SettledBridgeRequest[];
  pendingRequests?: PendingBridgeRequest[];
};
type CodeModeWorkerPayload<State> = CodeModeWorkerInput<State> & {
  /** Only interactive, non-replay cells can hand full final JSON to the run store. */
  retainFinalValue?: boolean;
};
type CodeModeSettlementMode = {
  kind: "awaiting";
} | {
  kind: "draining";
  requiredRequestIds: string[];
};
/** Transient worker boundary; no heap serialization and no resumable handle. */
type CodeModeWorkerBoundary = {
  networkContentObserved?: true;
  status: "boundary";
  pendingRequests: PendingBridgeRequest[];
  canceledRequestIds: string[];
  settlementMode: CodeModeSettlementMode;
  output: CodeModeOutputSource;
  /** Engine-reported allocations for diagnostics, not RSS or admission authority. */
  memoryUsedBytes: number;
};
type CodeModeWorkerContinuation = {
  kind: "checkpoint";
} | {
  kind: "continue";
  timeoutMs: number;
  settledRequests: SettledBridgeRequest[];
  pendingRequests: PendingBridgeRequest[];
};
type CodeModeFailurePhase = "input" | "guest" | "bridge" | "host";
type CodeModeWorkerOutcome<Output, Value, State> = {
  networkContentObserved?: true;
} & ({
  status: "completed";
  value: Value;
  output: Output;
} | {
  status: "waiting";
  continuation: State;
  pendingRequests: PendingBridgeRequest[];
  canceledRequestIds: string[];
  settlementMode: CodeModeSettlementMode;
  output: Output;
} | {
  status: "failed";
  error: string;
  code: "invalid_input" | "runtime_unavailable" | "timeout" | "snapshot_limit_exceeded" | "internal_error";
  failurePhase: CodeModeFailurePhase;
  bridgeDispatchStarted: false;
  output: Output;
});
type CodeModeVmResult<State> = CodeModeWorkerOutcome<unknown[], unknown, State>;
type CodeModeWorkerThreadResult<State> = CodeModeWorkerOutcome<CodeModeOutputSource, CodeModeJsonSource, State>;
//#endregion
//#region src/agents/code-mode-node-input.d.ts
declare const codeModeNodeInitialization: unique symbol;
type CodeModeNodeInitialization = {
  [codeModeNodeInitialization]?: SharedArrayBuffer;
};
//#endregion
//#region src/agents/code-mode-executor-types.d.ts
type CodeModeExecutorId = "node" | "quickjs";
type CodeModeFailureCode = "aborted" | "invalid_input" | "runtime_unavailable" | "timeout" | "output_limit_exceeded" | "snapshot_limit_exceeded" | "internal_error";
type CodeModeExecutorStartInput = Extract<CodeModeWorkerPayload<never>, {
  kind: "exec";
}> & CodeModeNodeInitialization;
type CodeModeExecutorResumeInput = Omit<Extract<CodeModeWorkerPayload<never>, {
  kind: "resume";
}>, "continuation">;
type CodeModeExecutorInlineHost = {
  gcAttribution?: {
    runId: string;
    sessionKeyHash?: string;
  };
  onWorkerAssigned?: (workerId: string) => void;
  onFailure?: (error: unknown, phase: CodeModeFailurePhase, workerId?: string) => void;
  onNetworkContent?: () => void;
  onInputConsumed?: () => void;
  onBoundary: (boundary: CodeModeWorkerBoundary, context: {
    signal: AbortSignal;
    yieldSignal: AbortSignal;
    maxTimeoutMs: number;
  }) => Promise<CodeModeWorkerContinuation & {
    onConsumed?: () => void;
  }>;
};
type CodeModeExecutorRunOptions = {
  timeoutMs: number;
  signal?: AbortSignal;
  inlineHost?: CodeModeExecutorInlineHost;
};
/** One-shot custody of a parked execution; resuming transfers its resources to the next result. */
type CodeModeExecutorContinuation = {
  readonly executor: CodeModeExecutorId;
  readonly retainedBytes: number;
  resume: (input: CodeModeExecutorResumeInput, options: CodeModeExecutorRunOptions) => Promise<CodeModeWorkerResult>;
  /** Revokes resume and joins cleanup; failed cleanup is retryable, consumed continuations are inert. */
  dispose: () => Promise<void>;
};
type CodeModeWorkerResult = Extract<CodeModeWorkerThreadResult<CodeModeExecutorContinuation>, {
  status: "completed" | "waiting";
}> | {
  status: "failed";
  error: string;
  code: CodeModeFailureCode;
  failurePhase: CodeModeFailurePhase;
  bridgeDispatchStarted: boolean;
  networkContentObserved?: true;
  output: CodeModeOutputSource;
};
type CodeModeExecutor = {
  readonly id: CodeModeExecutorId;
  execute: (input: CodeModeExecutorStartInput, options: CodeModeExecutorRunOptions) => Promise<CodeModeWorkerResult>;
};
//#endregion
//#region src/agents/code-mode-errors.d.ts
declare class CodeModeHeadlessAbortError extends Error {
  constructor(message?: string);
}
declare class CodeModeHeadlessTimeoutError extends Error {
  constructor(message?: string);
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt-result.d.ts
type EmbeddedAttemptSubscription = ReturnType<typeof subscribeEmbeddedAgentSession>;
type EmbeddedRunAttemptWithReceiptEvidence = EmbeddedRunAttemptResult & {
  answerSegments?: EmbeddedAttemptSubscription["answerSegments"];
  keptAnswer?: CompletedAssistantAnswer;
  successfulNestedToolNames?: string[];
};
//#endregion
//#region src/auto-reply/reply/reply-media-paths.d.ts
type PreparedReplyMediaSource = {
  mediaUrl: string;
  trustedLocalMedia: boolean;
  fileName?: string;
  mimeType?: string;
};
/** Delivery facts only; contains no live reader or transcript changes. */
type PreparedReplyMedia = readonly {
  source: string;
  outcome: PreparedReplyMediaSource | {
    failure: ReplyMediaFailure;
  };
}[];
//#endregion
//#region src/agents/harness/host-capability-types.d.ts
type AgentHarnessContextMedia = {
  text?: string;
  images: ImageContent$1[];
};
type AgentHarnessContextMediaRequest = {
  message: AgentMessage;
  maxChars: number;
};
type AgentHarnessHostApprovalResult = Readonly<{
  decision: ApprovalDecision | null | undefined;
  terminalReason: ApprovalTerminalReason | null | undefined;
}>;
type AgentHarnessPreparedEnvironment = Readonly<{
  credentialScrubEnv: Readonly<Record<string, string>>;
  localIdentityEnv: Readonly<Record<string, string>>;
  /** Append to effective Git parameters only in an owned local execution environment. */
  localGitConfigParameters?: string;
  /** Local child destination facts; must not be projected into a remote or sandbox process. */
  localProcessEnv?: Readonly<Record<string, string>>;
  /** Tool lookup on an owned local process; omit for remote, socket, or sandbox placement. */
  localToolEnv?: Readonly<Record<string, string>>;
  /** Prefix intent for runtimes with an explicitly authored native shell PATH. */
  localToolPathPrepend?: readonly string[];
  /** Non-secret fact used to select the local GitHub identity overlay. */
  managedLocalIdentity: boolean;
  /** Use this host's tool surface when the runtime cannot bind credentials at process launch. */
  hostExecutionRequired?: true;
}>;
type AgentHarnessToolSurfaceOptions = Omit<NonNullable<Parameters<(typeof agent_tools_d_exports)["createOpenClawCodingToolsAsync"]>[0]>, "operationalRunInstance">;
type AgentHarnessModelExecutionBinder = (model: (ProviderModelRef & {
  cyberAccessProgram?: CyberAccessProgram;
}) | undefined) => Readonly<{
  signal: AbortSignal;
  assertCurrent: () => void;
  release: () => void;
}> | undefined;
type AgentHarnessToolSurfaceBindingOptions = Readonly<{
  cwd?: string;
  /** The selected native runtime permits local execution outside Gateway tool policy. */
  nativeLocalExecution?: true;
}>;
type AgentHarnessHostCapabilities = Readonly<{
  kind: "agent-harness-host-capability";
  version: 1;
  /** Fails closed unless this exact admitted run capability remains active. */
  assertActive: () => void;
  /** Prepare history only when a native thread must be freshly seeded, under this run's authority. */
  prepareBoundedSeed?: (request: Readonly<{
    assertCurrent: () => void;
    signal?: AbortSignal;
    /** Final delivery allowance; valid smaller values only narrow the captured host budget. */
    tokenBudget?: number;
  }>) => Promise<readonly AgentMessage[]>;
  /**
   * Freeze the host continuation count before tools or inference, using the native
   * owner's admitted Gateway-local cwd. Never pass a remote/container path.
   * Repeat calls must use the same cwd; omission preserves the harness result budget.
   */
  prepareContinuationRetryCount?: (workspace: Readonly<{
    cwd: string;
  }>) => void;
  /** Capture admitted request ancestry for descendants that outlive this foreground turn. */
  captureRequestCustody?: () => ExecRequestCustody | undefined;
  /** Native runtimes must install pre-tool admission for these pending workspace operations. */
  workspaceReadiness?: Readonly<{
    toolNames: readonly string[];
    /** Await the existing workspace owner while preserving this run's authority. */
    waitUntilReady: () => Promise<void>;
  }>;
  /** Native delegation retains the incumbent execution and requires its current authority. */
  assertNativeSubagentSpawnAllowed?: () => void;
  /** Binds the actual native model and Access selection; returns undefined only for runs without an operator source. */
  bindModelExecution?: AgentHarnessModelExecutionBinder;
  /** Retains the original source for already-admitted work beyond foreground completion. */
  retainSourceAuthority?: () => Readonly<{
    assertCurrent: () => void;
    signal?: AbortSignal;
    /** Model or Access dispatch enforcement; absence means unknown, not unrestricted. */
    modelPolicyRequired?: boolean;
    /** Opaque equality for compatible active input; never authority by itself. */
    sourceIdentity?: object;
    /** Binds later dispatches while this retained work remains active. */
    bindModelExecution?: AgentHarnessModelExecutionBinder;
    release: () => void;
  }> | undefined;
  /** Reports one completed model call's output tokens to this admitted run's live total. */
  reportOutputTokens?: (outputTokens: number) => void;
  /** Adds native provenance only to this host's exact current admitted prompt. */
  annotateCurrentUserTurn?: (annotation: UserTurnTranscriptAnnotation) => Promise<void>;
  /** Detached admitted originals before inline projection; file readers still enforce custody. */
  resolveInputAttachmentMedia?: () => Promise<readonly Readonly<MediaFact>[]>;
  /** Execution-only document paths after the harness confirms unsandboxed local placement. */
  prepareInputAttachments?: (request: {
    placement: "local-host";
    maxChars: number;
    /** Omit for the admitted input; supply the current input for steering. */
    turn?: Pick<EmbeddedRunAttemptParams, "media" | "userTurnTranscriptRecorder">;
    assertCurrent: () => void;
    signal?: AbortSignal;
  }) => Promise<string | undefined>;
  /**
   * Fits a current request over the runtime's hard per-turn text cap. The harness
   * passes its own placement-aware preparer, so the full request becomes an
   * attachment only where the runtime can read it; otherwise its middle is cut.
   */
  fitCurrentInput?: (request: {
    prompt: string;
    maxChars: number;
    stageAttachment?: StageCurrentInputAttachment;
  }) => Promise<string>;
  /** Rebuilds retained attachments under this host's captured media policy and run authority. */
  prepareContextMedia?: (request: AgentHarnessContextMediaRequest) => Promise<AgentHarnessContextMedia>;
  /** Stages reply attachments under captured policy and live run authority. */
  prepareReplyMedia?: (request: {
    /** Additional native session or transport authority, retained through publication. */
    assertCurrent?: () => void;
    signal?: AbortSignal;
  } & (({
    workspaceRoot?: string;
    readWorkspaceFile: (relativePath: string, options: {
      maxBytes: number;
      signal: AbortSignal;
    }) => Promise<Buffer>;
  } & ({
    kind: "attempt";
    attempt: EmbeddedRunAttemptWithReceiptEvidence;
  } | {
    kind: "payload";
    payload: ReplyPayload$1;
  })) | {
    /** Already-admitted provider bytes, not permission to read a host path. */
    kind: "artifact";
    buffer: Buffer;
    fileName: string;
    assertCurrent: () => void;
  })) => Promise<{
    kind: "attempt";
    preparedMedia: PreparedReplyMedia;
  } | {
    kind: "payload";
    payload: ReplyPayload$1;
  }>;
  /** Closure-bound event sink backed by the host-owned trajectory recorder. */
  trajectory?: Readonly<{
    recordEvent: (type: string, data?: Record<string, unknown>) => void;
    flush: () => Promise<void>;
  }>;
  /** Closure-bound non-secret maps prepared before harness placement. */
  preparedEnvironment?: () => AgentHarnessPreparedEnvironment;
  /** Current bounded presence hint; physical activity does not identify the message source. */
  activeComputerContext?: () => string;
  /** Applies the exact host caller binding to a plugin-built tool surface. */
  bindToolSurface: (tools: AnyAgentTool[], options?: Readonly<{
    cwd?: string;
  }>) => AnyAgentTool[];
  /** @deprecated Await createToolSurfaceAsync for worker-backed exec policy. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  createToolSurface?: (options: AgentHarnessToolSurfaceOptions, bindingOptions?: AgentHarnessToolSurfaceBindingOptions) => AnyAgentTool[];
  /** Prepares fresh exec policy, then creates and binds tools to this exact live host. */
  createToolSurfaceAsync?: (options: AgentHarnessToolSurfaceOptions, bindingOptions?: AgentHarnessToolSurfaceBindingOptions) => Promise<AnyAgentTool[]>;
  /** Core-owned byte binding for a native command approval, scoped to this admitted run. */
  prepareMutableFileApproval?: (request: {
    command: string;
    cwd?: string;
  }) => Promise<{
    ok: true;
    requiresOneShot: boolean;
    revalidate: () => Promise<{
      ok: true;
    } | {
      ok: false;
      message: string;
    }>;
  } | {
    ok: false;
    message: string;
  }>;
  /** Runs policy with host-fixed HookContext; callers provide only the native action tuple. */
  runBeforeToolCall: (request: Omit<Parameters<(typeof agent_tools_before_tool_call_d_exports)["runBeforeToolCallHook"]>[0], "approvalMode" | "ctx"> & {
    /** Native relays may defer approval for a correlated app-server callback. */
    approvalMode?: "request" | "defer";
    /** Action-local facts from the native runtime; host authority remains closure-bound. */
    nativeOperation?: Readonly<{
      cwd?: string;
    }>;
  }) => ReturnType<(typeof agent_tools_before_tool_call_d_exports)["runBeforeToolCallHook"]>;
  requestApproval: (request: {
    signal?: AbortSignal;
    title: string;
    description: string;
    /** Full action evidence for authenticated reviewer surfaces, not channel messages. */
    detail?: string;
    severity: "info" | "warning";
    toolName: string;
    toolCallId?: string;
    mcpTool?: {
      server: string;
      tool: string;
    };
    /** Persistence-only proof; loss of correlation does not cancel a one-shot approval. */
    isMcpToolApprovalActive?: () => boolean;
    allowedDecisions?: ApprovalDecision[];
    timeoutMs: number;
    transportTimeoutMs?: number;
  }) => Promise<{
    id?: string;
    decision?: ApprovalDecision | null;
  } | undefined>;
  waitForApproval: (request: {
    approvalId: string;
    timeoutMs: number;
    transportTimeoutMs?: number;
    signal?: AbortSignal;
  }) => Promise<AgentHarnessHostApprovalResult | undefined>;
}>;
//#endregion
//#region src/agents/agent-harness-completion-scope.d.ts
type AgentHarnessCompletionScope = {
  readonly requesterSessionKey: string;
  readonly requesterAgentId: string;
  readonly requesterOrigin?: DeliveryContext;
};
//#endregion
//#region src/agents/context-window-guard.d.ts
type ContextWindowSource = "model" | "modelsConfig" | "agentContextTokens" | "default";
type ContextWindowInfo = {
  tokens: number;
  referenceTokens?: number;
  source: ContextWindowSource;
};
//#endregion
//#region src/agents/embedded-agent-runner/run/types.d.ts
type EmbeddedRunAttemptBase = Omit<RunEmbeddedAgentParams, "provider" | "model" | "authProfileId" | "authProfileIdSource" | "thinkLevel" | "fastMode" | "lane" | "enqueue" | "sessionFile" | "preparedRunAdmission" | "admittedRunContext">;
type EmbeddedRunFastModeParam = Exclude<FastMode, "auto"> | (() => Exclude<FastMode, "auto"> | undefined);
/** Host-owned trajectory recorder supplied to plugin harnesses for attempt-local runtime events. */
type EmbeddedRunAttemptTrajectoryRecorder = {
  recordEvent: (type: string, data?: Record<string, unknown>) => void;
  flush: () => Promise<void>;
};
type EmbeddedRunAttemptParams = EmbeddedRunAttemptBase & {
  /** Resume an admitted turn's history without re-admitting its original input after steering. */
  replayCurrentTranscript?: true;
  /** Set only by prompt admission after validating an already-delivered input. */
  inputAlreadyDelivered?: true;
  /** Transport hooks follow the current endpoint without changing admitted request policy. */
  transportConfig?: RunEmbeddedAgentParams["config"];
  modelCallSequence?: {
    value: number;
  };
  /** Recomputed by the host for this attempt; never inherited from the requesting turn. */
  githubPublicationAvailable?: boolean;
  disableToolSearch?: true;
  /** Recovery checkpoints preserve their input until memory extraction finishes. */
  compactionForbidden?: boolean;
  sessionReadScopeKey?: string;
  admittedRunContext: NonNullable<RunEmbeddedAgentParams["admittedRunContext"]>;
  /**
   * Run-owned start timestamp captured by the embedded-run orchestrator before
   * admission. Flows onto the queue handle so recovery can project the active
   * run's authoritative start time instead of the session's subagent first-run.
   */
  startedAtMs?: number;
  /** Explicit session owner captured before fallback agent resolution. */
  contextEngineAgentId?: string;
  /** Host-resolved sandbox snapshot for plugin harness tool construction. */
  sandbox?: SandboxContext | null;
  /** Host-created authority available only after harness selection. */
  hostCapabilities?: AgentHarnessHostCapabilities;
  /** Sticky operation identity used to suppress ordinary retry and hook policy. */
  operation?: "attempt" | "settled-tool-finalization";
  /** Core-prepared fact that explicit requester/config policy restricts plugin-native tools. */
  pluginHarnessToolPolicyRestricted?: boolean;
  /** Requester policy prepared by core; turn-specific tool restrictions still apply. */
  preparedWebSearchPolicy?: {
    allowed: boolean;
    persistentAllowed: boolean;
    /** Core binds the policy to this tuple; optional for existing SDK callers. */
    modelRef?: ProviderModelRef;
    /** Exact requester reads used during preparation; absence preserves existing SDK callers. */
    requesterFacts?: SessionCapabilitySnapshot[];
  };
  /** Host-prepared policy lifetime; turn-scoped policy can still allow every native tool. */
  pluginHarnessToolPolicyScope?: "conversation" | "turn";
  /** Audited exact denies that the plugin harness must enforce against native equivalents. */
  pluginHarnessToolPolicySafeDeniedTools?: readonly string[];
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  preparedTtsPreferences?: PreparedTtsPreferences;
  /** Active file-backed artifact target resolved by the run/session target seam. */
  sessionFile: string;
  initialReplayState?: EmbeddedRunReplayState;
  /** Pluggable context engine for ingest/assemble/compact lifecycle. */
  contextEngine?: ContextEngine;
  /** Native model context window before session or operator caps are applied. */
  modelContextWindow?: number;
  /** Per-model contextTokens cap authored by the operator; absent when none was authored. */
  authoredContextTokenCap?: number;
  /** Source metadata for the resolved model context budget. */
  contextWindowInfo?: ContextWindowInfo;
  /** Resolved API key for this run when runtime auth did not replace it. */
  resolvedApiKey?: string;
  /** Auth profile resolved for this attempt's provider/model call. */
  authProfileId?: string;
  /** Source for the resolved auth profile (user-locked or automatic). */
  authProfileIdSource?: "auto" | "user";
  provider: string;
  modelId: string;
  /** Operator-requested or initial model id before any fallback resolution. */
  requestedModelId?: string | null;
  /** True when this attempt is running after a model fallback decision. */
  fallbackActive?: boolean;
  /** Concrete fallback reason that selected this attempt, when known. */
  fallbackReason?: string | null;
  /** Whether this attempt may start or redirect work to another agent/task. */
  delegationCapability?: DelegationCapability;
  /** Concrete degraded-runtime reason for this attempt, when known. */
  degradedReason?: string | null;
  /** Actual embedded harness declaration, supplied by its invocation owner. */
  supportsTurnScopedToolRestrictions?: boolean;
  /** Non-authorizing expectation; the harness must verify its current private binding. */
  expectedSessionRuntimeOwnership?: {
    model: "native";
    auth: "native" | "host";
    /** Host-prepared credentials must still target this exact native tuple at inference. */
    modelRef?: ProviderModelRef;
  };
  /** Capture a local harness implementation only for setup/verified continuations. */
  captureRuntimeArtifact?: boolean;
  /** Exact implementation that must own the attempt before it creates a native thread. */
  expectedRuntimeArtifact?: AgentHarnessRuntimeArtifactBinding;
  /** OpenClaw-owned runtime policy prepared by the orchestrator for this attempt. */
  runtimePlan?: AgentRuntimePlan;
  /** Reports terminal tool facts to the host-owned attempt outcome accumulator. */
  observeToolTerminal?: (observation: {
    toolCallId?: string;
    toolName: string;
    arguments?: unknown;
    /** Original host result or error; public fields cannot supply effect provenance. */
    result?: unknown;
    meta?: string;
    executionStarted?: boolean;
    /** Exact-instance replay classification resolved by the host tool catalog. */
    replaySafe?: boolean;
    outcome: "success" | "failure";
    failure?: Omit<ToolErrorSummary, "toolName" | "meta" | "mutatingAction">;
    /** Protocol-owned mutation facts for native tools that do not use OpenClaw definitions. */
    nativeMutation?: {
      mutatingAction: boolean;
      replaySafe: boolean;
    };
    /** Concrete plugin owner; the terminal observer derives mutation facts from executed args. */
    ownerMutation?: {
      ownerKey: string;
    };
  }) => {
    lastToolError?: ToolErrorSummary;
    executionStarted: boolean;
    executedArguments?: Record<string, unknown>;
    sideEffectEvidence: boolean;
    effectReceipt: ToolEffectReceipt;
  };
  /** Host-issued scope for harness-owned child completion. */
  agentHarnessCompletionScope?: AgentHarnessCompletionScope;
  /** Host-only originals retained across native image projection. */
  inputAttachmentMedia?: RunEmbeddedAgentParams["media"];
  /** Storage-aware trajectory recorder owned by the OpenClaw host. */
  trajectoryRecorder?: EmbeddedRunAttemptTrajectoryRecorder | null;
  /** Live observer called after wrapped tool outcomes are recorded. */
  onToolOutcome?: ToolOutcomeObserver;
  /** Reads the sticky untrusted-content flag for the current user turn. */
  isTurnTainted?: () => boolean;
  /** Shipped harness notification; core uses onAttemptDeadlineChanged for queue ownership. */
  onAttemptTimeoutArmed?: () => void;
  /** Hands the lane an authoritative deadline, never a progress-idle estimate. */
  onAttemptDeadlineChanged?: (deadline: CommandQueueTaskDeadline) => void;
  /** Signals that this attempt's timeout has fired and must unwind promptly. */
  onAttemptTimeout?: (reason: Error) => void;
  /** Signals an explicit cancellation through the active native run handle. */
  onAttemptAbort?: () => void;
  /** Called before attempt cleanup; only core decides whether to request verified context. */
  onSettledTurn?: (attempt: EmbeddedRunAttemptResult, captureContext: () => Promise<EmbeddedRunAttemptResult["settledTurnFinalizationContext"]>) => Promise<void>;
  onDeferredLifecycleOwner?: (owner: DeferredEmbeddedRunLifecycleOwner) => void;
  onDeferredLifecycleAbort?: (reason?: "user_abort" | "restart" | "superseded") => void;
  /** Host-requested runtime replacement takes effect after the current tool batch is persisted. */
  pluginRuntimeRefreshPending?: () => boolean;
  /** Registers the exact attempt owner able to stop before another model request. */
  registerPluginRuntimeRefreshConsumer?: (isCurrent: () => boolean) => void;
  /** Completed native attempt results excluded by the original admission read fence. */
  pluginRuntimeRefreshMessages?: AgentMessage[];
  /**
   * Set on a plugin-runtime refresh continuation: the logical turn's user prompt.
   * Prompt hooks see it instead of the synthetic continuation prompt, and turn-start
   * work (next-turn injections, agent_turn_prepare) is not repeated.
   */
  pluginRuntimeRefreshUserPrompt?: string;
  /** Host-owned same-turn recovery context; never a new user turn or execution authority. */
  continuation?: {
    /** Original current request, retained outside bounded historical projections. */
    prompt: string;
    /** Settled attempt snapshots, in order, including completed tool calls and results. */
    messages: AgentMessage[];
  };
  /** Run-owned permission changes survive native attempt replacement, never user cancellation. */
  permissionChange?: {
    readonly owner: object;
    readonly baseExecOverrides: Readonly<NonNullable<RunEmbeddedAgentParams["execOverrides"]>>;
    readonly notice?: string;
    request: (mode: NonNullable<RunEmbeddedAgentParams["permissionMode"]> | null) => Promise<boolean>;
    /** False means a newer permission request superseded this prepared attempt. */
    applied: () => boolean;
    recordApplied: (mode: NonNullable<RunEmbeddedAgentParams["permissionMode"]> | null) => void;
  };
  /** Supplies run-global model-call ordering for parallel tool outcomes. */
  allocateToolOutcomeOrdinal?: (toolCallId?: string) => number;
  model: Model & {
    requestTimeoutMs?: number;
  };
  authStorage: AuthStorage;
  /** Auth profile store already resolved during startup for this attempt. */
  authProfileStore: AuthProfileStore$1;
  /**
   * Full auth profile store for OpenClaw tool availability.
   * Plugin-owned harnesses may scope `authProfileStore` to model transport credentials.
   */
  toolAuthProfileStore?: AuthProfileStore$1;
  modelRegistry: ModelRegistry$1;
  thinkLevel: ThinkLevel;
  fastMode?: EmbeddedRunFastModeParam;
  /** True when this attempt is running the auto fast-mode policy. */
  fastModeAuto?: boolean;
  beforeAgentFinalizeRevisionAttempts?: number;
  maxBeforeAgentFinalizeRevisions?: number;
};
type EmbeddedRunAttemptResult = {
  /** Exact historical input acknowledged without another model turn. */
  inputAlreadyDelivered?: true;
  cyberAccessProgram?: "standard" | "daybreak_blue" | "daybreak_red";
  terminal: AgentRunAttemptTerminal;
  preparedTerminalReply?: PreparedAgentRunTerminalReply;
  /** Prepared policy that explains unavailable tools without another session read. */
  sandboxRuntime?: ReturnType<typeof resolveSandboxRuntimeStatus>;
  /** True when the runtime made the authoritative final-assistant transcript decision. */
  assistantTranscriptOwned?: boolean;
  /** Exact idempotency key for the runtime-owned final-assistant transcript row. */
  assistantTranscriptIdempotencyKey?: string;
  /** Host-private terminal identity used to close the accepted transcript turn. */
  contextEngineTerminalAnchor?: TranscriptEntryAnchor;
  preflightRecovery?: {
    route: Exclude<PreemptiveCompactionRoute, "fits">;
    /** Only "overflow" may fail the turn; "maintenance" always continues it. */
    pressure: ContextPressure;
    source?: "mid-turn";
    estimatedPromptTokens?: number;
    promptBudgetBeforeReserve?: number;
    overflowTokens?: number;
  } & ({
    handled: true;
    truncatedCount?: number;
  } | {
    handled?: false;
  });
  sessionIdUsed: string;
  sessionFileUsed?: string;
  diagnosticTrace?: DiagnosticTraceContext;
  agentHarnessId?: string;
  /** Current physical model attempt; replaced from the prepared runtime plan at the boundary. */
  modelAttempt?: AgentRuntimeModelAttempt;
  /** Native owner's selected tuple, distinct from response/billing model attribution. */
  runtimeModelSelection?: ProviderModelRef;
  /** Exact credential material fingerprint reported by a harness-owned auth boundary. */
  authBindingFingerprint?: string;
  /** Exact local implementation used by a plugin-owned harness attempt. */
  runtimeArtifact?: AgentHarnessRuntimeArtifactBinding;
  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_settlement_timeout" | "turn_completion_idle_timeout";
    turnWatchTimeoutKind?: "progress" | "completion" | "terminal";
    transport: "stdio" | "unix" | "websocket";
    threadId?: string;
    turnId?: string;
    replaySafe: boolean;
    replayBlockedReason?: "assistant_output" | "tool_activity" | "potential_side_effect" | "active_item";
    diagnostics?: {
      transportError?: string;
      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;
  /** Exact provider-response count when the harness can observe model iterations directly. */
  modelIterations?: number;
  /** Saved provider retry setting resolved by the prepared session owner. */
  providerRetryMaxRetries?: number;
  /** Explicit provider/session request timeouts retain their configured retry policy. */
  providerRequestTimeoutExplicit?: boolean;
  /** Saved retry.provider.maxRetryDelayMs from the same owner; 0 disables the cap. */
  providerRetryMaxDelayMs?: number;
  messagesSnapshot: AgentMessage[];
  pluginRuntimeRefreshMessages?: AgentMessage[];
  /** Owner-eligible settled finalization, with frozen evidence or an unavailable projection. */
  settledTurnFinalizationContext?: {
    readonly source: "openclaw-transcript";
    readonly messages: readonly AgentMessage[];
  } | {
    readonly source: "harness";
    readonly data: unknown;
  } | {
    readonly source: "unavailable";
  };
  beforeAgentFinalizeRevisionReason?: string;
  assistantTexts: string[];
  /** A registered tool was requested as structured text without a native call. */
  textToolCallAttempt?: boolean;
  /** Immutable delivery facts prepared before a remote harness releases its file reader. */
  preparedReplyMedia?: PreparedReplyMedia;
  latestMcpAppChannelView?: McpAppChannelView;
  latestMcpConnectAction?: McpConnectAction;
  lastAssistantTextMessageIndex?: number;
  toolMetas: Array<{
    toolName: string;
    toolCallId?: string;
    meta?: string;
    replaySafe?: boolean;
    isError?: boolean;
    terminate?: boolean;
    asyncStarted?: boolean;
    asyncTaskRunId?: string;
    asyncTaskId?: string;
    /** Producer-recorded: this exec result parked a Code Mode run (status "waiting"). */
    codeModeSuspended?: boolean;
  }>;
  acceptedSessionSpawns?: AcceptedSessionSpawn[];
  /** Core successfully settled this requester's explicit yield in the registry. */
  requesterContinuationSettled?: true;
  /** This attempt accepted work whose future output has a runtime-owned delivery path. */
  runtimeContinuationStarted?: boolean;
  lastAssistant: AssistantHistoryMessage | undefined;
  /**
   * Omission preserves the legacy `lastAssistant` fallback; explicit `undefined`
   * means this attempt produced no assistant response.
   */
  currentAttemptAssistant?: AssistantHistoryMessage | undefined;
  /** Completed message_end snapshot owned by this model attempt. */
  currentAttemptCompletedAssistant?: AssistantHistoryMessage | undefined;
  /** A real model response completed successfully during this attempt, before any later failure. */
  hasSuccessfulModelResponse?: boolean;
  lastToolError?: ToolErrorSummary;
  didSendViaMessagingTool: boolean;
  didDeliverSourceReplyViaMessageTool?: boolean;
  sourceReplyDelivered?: true;
  sourceReplyDeliveryState?: ReplyDeliveryState;
  didSendDeterministicApprovalPrompt?: boolean;
  messagingToolSentTexts: string[];
  messagingToolSentMediaUrls: string[];
  messagingToolSentTargets: MessagingToolSend[];
  messagingToolSourceReplyPayloads?: MessagingToolSourceReplyPayload[];
  toolMediaUrls?: string[];
  /**
   * Native artifacts produced and owned by the harness, never model-selected
   * dynamic-tool output. Core validates this as a subset of toolMediaUrls.
   */
  hostOwnedToolMediaUrls?: string[];
  toolAudioAsVoice?: boolean;
  toolTrustedLocalMedia?: boolean;
  hasToolMediaBlockReply?: boolean;
  successfulCronAdds?: number;
  cloudCodeAssistFormatError: boolean;
  /** Effective context window reported by the harness during this attempt. */
  contextTokens?: number;
  /** Whether the harness observed the window or carried prepared resolution forward. */
  contextTokensSource?: "runtime" | "runtime-configured" | "resolved";
  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<string, unknown>;
  }>;
  /** True when sessions_yield tool was called during this attempt. */
  yieldDetected?: boolean;
  /** Explicit user-facing waiting status supplied to sessions_yield. */
  yieldAcknowledgment?: string;
  /** The registry accepted this attempt's explicit incoming-message wait. */
  yieldMessageWaitRegistered?: boolean;
  /**
   * True when code mode owned this attempt's model tool surface. Absent means
   * the harness did not report engagement (treated as not engaged), which is
   * how config-enabled code mode stays visible as a no-op on harness routes.
   */
  codeModeEngaged?: boolean;
  /** Completed assistant round trips observed during this attempt. */
  assistantTurns?: number;
  /** Inner bridge call counts from this attempt's tool-search/code-mode catalog. */
  bridgeCalls?: {
    search: number;
    describe: number;
    call: number;
  };
  replayMetadata: EmbeddedRunReplayMetadata;
  /**
   * Replay metadata for this attempt before prior session state is accumulated.
   * Older harnesses may omit it and retain conservative cumulative retry gating.
   */
  currentAttemptReplayMetadata?: 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/sessions/session-initialization.d.ts
/** Creation-only authority. Copied fields never identify an initializer to the host. */
type SessionInitialization = {
  assertCurrent: () => void;
  assertRollbackCurrent: () => void;
  /** Prepares child policy data without constructing tools or acquiring run authority. */
  prepareNativeToolPolicy?: (model: SessionNativeToolModel) => Promise<Readonly<{
    webSearchAllowed: boolean;
  }>>;
};
/** Native model selection data; the creation owner fixes every authority-bearing input. */
type SessionNativeToolModel = Readonly<{
  provider: string;
  runtimeProvider?: string;
  id: string;
}>;
//#endregion
//#region src/agents/harness/types.d.ts
type AgentHarnessNativeSubagents = NativeSubagentsSnapshot;
/** Private native ownership, not execution authority or credential readiness. */
type AgentHarnessSessionRuntimeOwnership = {
  model: "native";
  auth: "native" | "host";
  /** Actual native selection, only when both facts are known from the same binding. */
  modelRef?: ProviderModelRef;
};
type AgentHarnessPreparedAuthSupport = {
  source: "profile" | "direct" | "harness" | "none";
  mode?: string;
  requirement?: ProviderModelRouteAuthRequirement;
};
type AgentHarnessSupportContext = {
  provider: string;
  modelId?: string;
  modelProvider?: {
    api?: string;
    baseUrl?: string;
    azureApiVersion?: string;
    /** Secret-free projection of request behavior a native harness must reproduce. */
    requestTransportOverrides?: ProviderRouteOverridePresence;
    /** Authored endpoints that a native runtime must reproduce. */
    endpointOverrides?: ProviderRouteOverridePresence;
    /** Provider-owned native-runtime compatibility for the prepared route. */
    runtimePolicy?: ProviderModelRouteRuntimePolicy;
    /** Secret-free auth source the native runtime must reproduce for this attempt. */
    preparedAuth?: AgentHarnessPreparedAuthSupport;
    request?: {
      auth?: {
        mode?: unknown;
      };
      proxy?: unknown;
      tls?: unknown;
      allowPrivateNetwork?: unknown;
    };
  };
  requestedRuntime: EmbeddedAgentRuntime;
  providerOwnerStatus?: "unowned" | "owned" | "ambiguous";
  providerOwnerPluginIds?: readonly string[];
};
type AgentHarnessSupport = {
  supported: true;
  priority?: number;
  reason?: string;
} | {
  supported: false;
  reason?: string;
  /** Lossless host fallback when this harness cannot reproduce the prepared request. */
  fallbackRuntime?: "openclaw";
};
type InternalEmbeddedRunAttemptParams = EmbeddedRunAttemptParams;
/** @deprecated Read `terminal` instead. Remove no earlier than the 2026.9 stable release. */
type AgentHarnessDeprecatedAttemptTerminalFields = {
  aborted?: boolean;
  externalAbort?: boolean;
  timedOut?: boolean;
  idleTimedOut?: boolean;
  timedOutDuringCompaction?: boolean;
  timedOutDuringToolExecution?: boolean;
  timedOutByRunBudget?: boolean;
  promptError?: unknown;
  promptErrorSource?: AgentRunAttemptFailureSource | null;
};
type AgentHarnessCanonicalAttemptResult = Omit<EmbeddedRunAttemptResult, "contextEngineTerminalAnchor"> & AgentHarnessDeprecatedAttemptTerminalFields;
/** @deprecated Return `terminal` instead. Remove no earlier than the 2026.9 stable release. */
type AgentHarnessLegacyAttemptResult = Omit<AgentHarnessCanonicalAttemptResult, "terminal"> & Required<Omit<AgentHarnessDeprecatedAttemptTerminalFields, "timedOutDuringToolExecution" | "timedOutByRunBudget">>;
type AgentHarnessAttemptParamsBase = Omit<InternalEmbeddedRunAttemptParams, "thinkingExplicit" | "admittedRunContext" | "disableToolSearch" | "sessionReadScopeKey" | "blindPrompt" | "assistantErrorTranscript" | "contextEngineLogicalTurnLease" | "onContextEngineTurnCandidate" | "trajectoryRecorder" | "inputAttachmentMedia" | "supportsTurnScopedToolRestrictions" | "onSettledTurn"> & {
  /** Awaited in the original attempt scope; core alone decides whether to capture. */
  onSettledTurn?: (attempt: AgentHarnessCanonicalAttemptResult, captureContext: () => Promise<AgentHarnessCanonicalAttemptResult["settledTurnFinalizationContext"]>) => Promise<void>;
};
/**
 * @deprecated Use AgentHarnessAttemptParamsV2. The optional capability keeps
 * existing harness source compatible through 2026-10-12.
 */
type AgentHarnessAttemptParams = AgentHarnessAttemptParamsBase & {
  hostCapabilities?: AgentHarnessHostCapabilities;
};
/** Current host-prepared attempt contract for agent harnesses. */
type AgentHarnessAttemptParamsV2 = AgentHarnessAttemptParamsBase & {
  hostCapabilities: AgentHarnessHostCapabilities;
};
/** Data and admitted authority needed to prepare a native session, without a model turn. */
type AgentHarnessSessionRuntimeParamsV1 = Omit<AgentHarnessAttemptParamsV2, "prompt" | "sessionFile" | "model" | "authStorage" | "modelRegistry" | "thinkLevel" | "timeoutMs"> & {
  model?: AgentHarnessAttemptParamsV2["model"];
};
/** A new operation, not an optional-authority path through the shipped attempt contract. */
type AgentHarnessSessionPreparationV1 = {
  version: 1;
  purpose: "mcp-app";
  params: AgentHarnessSessionRuntimeParamsV1;
  run: <T>(operation: () => Promise<T>) => Promise<T>;
};
type AgentHarnessAttemptResult = AgentHarnessCanonicalAttemptResult | AgentHarnessLegacyAttemptResult;
type AgentHarnessSettledTurnFinalizationAttemptParams<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams> = Omit<TAttemptParams, "hostCapabilities" | "onSettledTurn"> & {
  hostCapabilities?: never;
};
type AgentHarnessSettledTurnFinalizationParams<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams> = {
  /** Fully prepared attempt context for the isolated finalization operation. */
  attempt: AgentHarnessSettledTurnFinalizationAttemptParams<TAttemptParams>;
  /** Settled result whose completed tool transcript needs a final visible answer. */
  settledAttempt: AgentHarnessCanonicalAttemptResult;
};
type AgentHarnessSettledTurnFinalizationResult = {
  /** Completed answer projected from the isolated attempt; stored usage may lack a price. */
  assistant: AssistantHistoryMessage;
  preparedTerminalReply?: PreparedAgentRunTerminalReply;
  /** Normalized usage for the finalization model call only. */
  usage?: NormalizedUsage;
  /** True when the harness already persisted the assistant into the application transcript. */
  assistantTranscriptOwned?: boolean;
  /** Exact idempotency key for the harness-owned assistant transcript row. */
  assistantTranscriptIdempotencyKey?: string;
  /** Assistant stream generation index used to correlate final reply delivery. */
  assistantMessageIndex?: number;
  diagnosticTrace?: DiagnosticTraceContext;
};
/** @deprecated Use AgentHarnessIsolatedCompletionParamsV2. Remove after 2026-10-12. */
type AgentHarnessIsolatedCompletionParams = {
  /** Logical provider selected by the caller before harness dispatch. */
  provider: string;
  /** Logical model id selected by the caller before harness dispatch. */
  modelId: string;
  /** Exact prepared transport model; harnesses must not resolve another route. */
  model: Model;
  /** Exact prepared credential; harnesses must not rotate or substitute it. */
  auth: ResolvedProviderAuth;
  /** Non-reversible proof of the prepared credential owner when available. */
  sourceAuthFingerprint?: string;
  config: OpenClawConfig;
  agentId: string;
  agentDir: string;
  workspaceDir: string;
  systemPrompt: string;
  prompt: string;
  timeoutMs: number;
  abortSignal?: AbortSignal;
  /** Revalidate after preparation and before credential or inference I/O, including retries. */
  assertCurrent?: () => void;
  thinkLevel?: ThinkLevel;
  /** Do not recover ambiguous reasoning as visible text; an empty visible result is valid. */
  outputTextPolicy?: "strict-visible";
  /** Report inference dispatch through settlement, excluding preparation and cleanup. */
  onRequestComplete?: (durationMs: number) => void;
  /** Observe the returned assistant before cancellation/output rejection; never grants acceptance. */
  onResult?: (result: AgentHarnessIsolatedCompletionResult) => void;
  streamParams?: {
    maxTokens?: number;
    temperature?: number;
  };
};
type AgentHarnessIsolatedCompletionAuthorization = {
  /** OpenClaw resolved the exact transport model and credential before handoff. */
  owner: "host";
  model: Model;
  auth: ResolvedProviderAuth;
  /** Non-reversible proof of the prepared credential owner when available. */
  sourceAuthFingerprint?: string;
} | {
  /** The selected harness owns credential resolution for this prepared route. */
  owner: "harness";
  plan: AgentRuntimeAuthPlan;
  /** Credential snapshot restricted to the single profile selected for this call. */
  authProfileStore: AuthProfileStore$1;
};
type AgentHarnessIsolatedCompletionParamsV2 = Omit<AgentHarnessIsolatedCompletionParams, "model" | "auth" | "sourceAuthFingerprint"> & {
  authorization: AgentHarnessIsolatedCompletionAuthorization;
  /** Advisory final-output schema; harnesses without native support may ignore it. */
  outputSchema?: JsonSchemaObject;
};
type AgentHarnessIsolatedCompletionResult = {
  /** The single assistant completion. Core rejects tool-shaped or failed results. */
  assistant: AssistantMessage;
};
type AgentHarnessAuthBindingFingerprintParams = {
  authProfileId: string;
  authProfileStore: AuthProfileStore$1;
  agentDir: string;
  config?: OpenClawConfig;
};
/**
 * @deprecated Use {@link AgentHarnessSideQuestionParamsV2}. This compatibility
 * contract is retained through 2026-10-12.
 */
type AgentHarnessSideQuestionParams = {
  /** Host-bound authority for this admitted side execution; contains no public token fields. */
  hostCapabilities?: AgentHarnessHostCapabilities;
  /** Host-resolved sandbox snapshot for this side execution. */
  sandbox?: SandboxContext | null;
  /** Prepared plugin/model generation that owns this side execution. */
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  cfg: OpenClawConfig;
  agentDir: string;
  provider: string;
  model: string;
  runtimeModel?: Model<Api>;
  /** One atomic route/profile/store snapshot prepared before native dispatch. */
  preparedRuntimeAuth: {
    plan: AgentRuntimeAuthPlan;
    authProfileStore: AuthProfileStore$1;
    authStorage: AuthStorage;
    modelRegistry: ModelRegistry$1;
    /** Resolved host credential for an immutable API-key route only. */
    resolvedApiKey?: string;
  };
  question: string;
  /** Preserve tool definitions but reject all tool execution in this side question. */
  toolCalls?: "deny";
  images?: ImageContent$1[];
  sessionEntry: SessionEntry;
  sessionStore?: Record<string, SessionEntry>;
  sessionKey?: string;
  storePath?: string;
  resolvedThinkLevel?: ThinkLevel;
  resolvedReasoningLevel: ReasoningLevel;
  blockReplyChunking?: BlockReplyChunking;
  resolvedBlockStreamingBreak?: "text_end" | "message_end";
  opts?: GetReplyOptions;
  isNewSession: boolean;
  sessionId: string;
  sessionFile: string;
  sandboxSessionKey?: string;
  agentId?: string;
  workspaceDir?: string;
  messageChannel?: string;
  messageProvider?: string;
  chatType?: ChatType;
  agentAccountId?: string;
  messageTo?: string;
  messageThreadId?: string | number;
  chatId?: string;
  messageActionTurnCapability?: string;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  memberRoleIds?: string[];
  spawnedBy?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
  senderIsOwner?: boolean;
  currentChannelId?: string;
  toolsAllow?: string[];
  authProfileId?: string;
  authProfileIdSource?: "auto" | "user";
};
/** Current side-question contract for hosts that always provide closure-bound authority. */
type AgentHarnessSideQuestionParamsV2 = AgentHarnessSideQuestionParams & {
  hostCapabilities: AgentHarnessHostCapabilities;
  /** Non-authorizing native ownership captured before model and auth preparation. */
  expectedSessionRuntimeOwnership?: InternalEmbeddedRunAttemptParams["expectedSessionRuntimeOwnership"];
  /** Core-prepared search policy, bound to the side question's model and requester facts. */
  preparedWebSearchPolicy?: InternalEmbeddedRunAttemptParams["preparedWebSearchPolicy"];
};
type AgentHarnessSideQuestionResult = {
  text: string;
  /** Aggregate billed usage for the side question, including native tool-loop calls. */
  usage?: NormalizedUsage;
};
type LegacyAgentHarnessCompactParams = CompactEmbeddedAgentSessionParams;
/** Select version 2 for required host authority; the default preserves registered legacy callbacks. */
type AgentHarnessCompactParams<Version extends 1 | 2 = 1> = Version extends 2 ? LegacyAgentHarnessCompactParams & {
  hostCapabilities: Readonly<Pick<AgentHarnessHostCapabilities, "kind" | "version" | "assertActive"> & Required<Pick<AgentHarnessHostCapabilities, "retainSourceAuthority">>>;
} : LegacyAgentHarnessCompactParams;
type AgentHarnessCompactResult = EmbeddedAgentCompactResult;
type AgentHarnessNativeCompactionRequest = "after_context_engine" | "required_preflight";
type AgentHarnessNativeCompactionParams<Version extends 1 | 2 = 1> = AgentHarnessCompactParams<Version> & {
  nativeCompactionRequest: AgentHarnessNativeCompactionRequest;
};
type AgentHarnessNativeCompaction = (params: AgentHarnessNativeCompactionParams) => Promise<AgentHarnessCompactResult | undefined>;
type AgentHarnessRegistrationOptions = {
  /**
   * Registers the Codex-only native preflight bridge in host-owned registry
   * metadata. Arbitrary properties on the public harness never grant it.
   */
  nativeCompaction?: AgentHarnessNativeCompaction;
};
type AgentHarnessResetParams = {
  agentId?: string;
  sessionId?: string;
  sessionKey?: string;
  sessionFile?: string;
  reason?: "new" | "reset" | "idle" | "daily" | "compaction" | "deleted" | "unknown";
};
type AgentHarnessSessionForkFailureCode = "steer-message" | "in-progress-turn" | "drift-mismatch" | "upstream-unavailable";
type AgentHarnessSessionForkParams = {
  targetKey: string;
  /** Creator-owned isolation floor resolved by the trusted Gateway request. */
  sandbox?: "required";
  source: {
    agentId: string;
    sessionId: string;
    sessionKey: string;
    storePath: string;
    entryId: string;
  };
  upstream: {
    catalogId: string;
    hostId: string;
    kind: SessionUpstreamKind;
    threadId: string;
    ref: PluginJsonValue;
  };
};
/** Current fork contract for harnesses that can fence native side effects. */
type AgentHarnessSessionForkParamsV2 = AgentHarnessSessionForkParams & {
  /** Revalidate immediately before native side effects; this authority closes when fork settles. */
  assertCurrent: () => void;
};
type AgentHarnessSessionForkResult = {
  status: "created";
  key: string;
  editorText?: string;
} | {
  status: "failed";
  code: AgentHarnessSessionForkFailureCode;
  message: string;
};
type AgentHarnessResultClassification = "ok" | NonNullable<AgentHarnessAttemptResult["agentHarnessResultClassification"]>;
type AgentHarnessDeliveryDefaults = {
  /** Default visible-reply policy when config does not override the harness. */
  visibleReplies?: "automatic" | "message_tool";
  /**
   * @deprecated Use visibleReplies. Kept for existing harness plugins.
   */
  sourceVisibleReplies?: "automatic" | "message_tool";
};
/** Exact node authority and worker capacity required by one paired-device runtime. */
type DevicePlacementRequirement = {
  requiredNodeCommands: readonly string[];
  consumesWorkerSlot: boolean;
};
type AgentHarnessSessionDeletionParams = {
  /** Present only during the exact host initializer's guarded rollback. */
  initialization?: SessionInitialization;
  agentId: string;
  sessionKey: string;
  sessionId: string;
  lifecycleRevision?: string;
  /** Revalidate the captured registry, harness, and operation before each side effect. */
  assertCurrent: () => void;
};
/**
 * Direct, unbound commit/rollback callbacks are deprecated and will be removed
 * after an announced stable deprecation period. Use createNativeSessionBindingLifecycleV2 for
 * reversible stored bindings or createNativeSessionCommitFinalizer for
 * commit-only cleanup from openclaw/plugin-sdk/agent-harness-session-runtime.
 * Factory-produced participants remain supported by this contract.
 */
type AgentHarnessSessionDeletionMutation = {
  /**
   * @deprecated Opaque callbacks run after durable session commit. Use
   * createNativeSessionBindingLifecycleV2 for stored bindings or
   * createNativeSessionCommitFinalizer for cleanup.
   */
  commit: () => void;
  /** @deprecated Opaque callbacks no longer run before commit, so their rollback is unused. */
  rollback: () => void;
};
type AgentHarnessSessionContextResetParams = Omit<AgentHarnessSessionDeletionParams, "initialization"> & {
  /** Exact recorded predecessor may still own native context after interrupted compaction. */
  previousSessionId?: string;
};
type AgentHarnessMcpCatalogParams = {
  config: OpenClawConfig;
  agentId: string;
  sessionId: string;
  sessionKey: string;
  workspaceDir: string;
  /** OpenClaw-configured servers whose session policy this harness can enforce. */
  mcpServerNames: readonly string[];
  toolOverrides?: Pick<SessionToolOverrides, "mcpServers" | "mcpToolsDeny">;
};
type AgentHarnessModelCatalogParams = {
  config: OpenClawConfig;
  agentId: string;
  agentDir: string;
  workspaceDir: string;
  configuredModelRefs?: readonly ProviderModelRef[];
};
type AgentHarnessModelCatalogResult = readonly ModelCatalogEntry[] | {
  entries: readonly ModelCatalogEntry[];
  outcomes?: readonly ProviderCatalogOutcome[];
};
type AgentHarnessDescendantCancellationResult = {
  killed: number;
  /** Settlement failures do not erase already acknowledged sibling cancellations. */
  errors?: readonly unknown[];
  cancelledRequesters: Array<{
    agentId: string;
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
    requesterTurnRunId: string;
  }>;
};
/** Activation-only native readiness check; it does not authorize a model turn. */
type AgentHarnessSetupVerificationContext = {
  config: OpenClawConfig;
  provider: string;
  modelId: string;
  workspaceDir: string;
  signal: AbortSignal;
  /** Revalidate the setup owner after awaits and before native I/O. */
  assertCurrent: () => void;
};
type AgentHarnessContract<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams, TSideQuestionParams extends AgentHarnessSideQuestionParams = AgentHarnessSideQuestionParams> = {
  id: string;
  label: string;
  pluginId?: string;
  /**
   * Exhaustive provider ids eligible for automatic selection. Omitting this hint preserves
   * dynamic probing; an empty list marks an explicit-only harness.
   */
  autoSelection?: {
    providerIds: readonly string[];
  };
  /** Declares host-owned remote execution and its exact paired-device requirements. */
  cloudPlacement?: {
    mode: "remote-exec";
    devicePlacement?: DevicePlacementRequirement;
  };
  /** Provider-managed workspace presentation, not Gateway worker placement or readiness. */
  workspaceEnvironment?: {
    kind: "provider-hosted";
    label: string;
  };
  /**
   * Plugin ids this harness owner permits to execute its locked sessions.
   * Delegates receive work admission and execution only; session mutation stays owner-only.
   */
  delegatedExecutionPluginIds?: readonly 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[];
  /** Native context management ignores OpenClaw Responses compaction tuning, not request policy. */
  contextManagement?: "native";
  deliveryDefaults?: AgentHarnessDeliveryDefaults;
  /** Core must reject containment this runtime cannot implement before invoking it. */
  executionEnvironment?: "host-only";
  /** Certifies exact runAttempt enforcement; direct-policy-restricted channel side questions fail in core. */
  conversationToolPolicySupport?: "exact";
  /** Certifies binding the actual native model through the host before every inference dispatch. */
  nativeModelPolicySupport?: "exact";
  /**
   * Canonical OpenClaw tool names whose exact denies the harness can also enforce
   * against native equivalents. Every other deny remains fail-closed.
   */
  conversationToolPolicySafeDenyTools?: readonly string[];
  /** OpenClaw tool capabilities an indivisible native surface requires from effective profiles. */
  conversationToolPolicyNativeTools?: readonly string[];
  supports(ctx: AgentHarnessSupportContext): AgentHarnessSupport;
  /**
   * Verify a profileless, harness-owned setup candidate without a model turn.
   * Resolve only after native credentials and the selected model are usable;
   * throw on rejection. Core owns the resulting setup binding and rechecks it
   * before activation. Other inference checks still execute a bounded turn.
   */
  verifySetup?(ctx: AgentHarnessSetupVerificationContext): Promise<void>;
  /**
   * Synchronous private ownership read; no discovery, auth loading, or native connection setup.
   * @deprecated Implement resolveSessionRuntimeOwnershipAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release.
   */
  resolveSessionRuntimeOwnership?(params: {
    config?: OpenClawConfig;
    agentId?: string;
    sessionId: string;
    sessionKey?: string;
    storePath?: string;
    /** Latest predecessor of this exact physical session; valid only during this invocation. */
    readPreviousSessionId?: () => string | undefined;
    assertCurrent: () => void;
  }): AgentHarnessSessionRuntimeOwnership | undefined;
  /** Worker-backed private ownership read, without discovery or native connection setup. */
  resolveSessionRuntimeOwnershipAsync?(params: {
    version: 2;
    config?: OpenClawConfig;
    agentId?: string;
    sessionId: string;
    sessionKey?: string;
    storePath?: string;
    /** Latest predecessor of this exact physical session; valid only during this invocation. */
    readPreviousSessionId: () => Promise<string | undefined>;
    /** Revalidate the retained caller after awaited work and before returning ownership. */
    assertCurrent: () => void;
  }): Promise<AgentHarnessSessionRuntimeOwnership | undefined>;
  /** Read retained native-child observations without starting or adopting native work. */
  readNativeSubagents?(params: {
    agentId: string;
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
    storePath: string;
    assertCurrent: () => void;
  }): Promise<AgentHarnessNativeSubagents | undefined>;
  /** Lets this harness resolve forwarded profiles or its own native credentials. */
  authBootstrap?: "harness";
  /**
   * Declares whether this harness supports turn-scoped restrictive tool policies
   * (`toolsAllow: []`), such as OpenClaw's embedded agent runner. Harnesses that define
   * tools only at connection/thread boundaries (like Codex app-server) omit this or set false.
   */
  supportsTurnScopedToolRestrictions?: boolean;
  runAttempt(params: TAttemptParams): Promise<AgentHarnessAttemptResult>;
  /**
   * Produces one final answer from a settled tool transcript without exposing
   * capabilities that can repeat or extend the completed work.
   */
  finalizeSettledTurn?(params: AgentHarnessSettledTurnFinalizationParams<TAttemptParams>): Promise<AgentHarnessSettledTurnFinalizationResult>;
  /** @deprecated Implement runIsolatedCompletionV2. Remove after 2026-10-12. */
  runIsolatedCompletion?(params: AgentHarnessIsolatedCompletionParams): Promise<AgentHarnessIsolatedCompletionResult>;
  /**
   * Runs one fresh prompt-only completion with a literal zero-tool model surface.
   * The harness must fail closed when it cannot enforce that native boundary.
   * Agents API is the documented exception: its restricted sessions may retain
   * service-owned helpers. Callers requiring zero tools must use another runtime.
   */
  runIsolatedCompletionV2?(params: AgentHarnessIsolatedCompletionParamsV2): Promise<AgentHarnessIsolatedCompletionResult>;
  /** Side-effect-free engine selection, shared with this harness's isolated dispatch. */
  resolveIsolatedCompletionRuntime?(params: {
    authorizationOwner: AgentHarnessIsolatedCompletionAuthorization["owner"];
  }): "openclaw" | "self";
  runSideQuestion?(params: TSideQuestionParams): Promise<AgentHarnessSideQuestionResult>;
  classify?(result: AgentHarnessAttemptResult, ctx: TAttemptParams): AgentHarnessResultClassification | undefined;
  compact?(params: AgentHarnessCompactParams): Promise<AgentHarnessCompactResult | undefined>;
  /** Throw AgentHarnessSessionCleanupError when required cleanup must block session replacement. */
  reset?(params: AgentHarnessResetParams): Promise<void> | void;
  /** Reserve descendants before parent Stop; cancel joins native terminal and delivery custody. */
  withDescendantCancellation?<T>(this: void, params: Omit<AgentHarnessSessionDeletionParams, "initialization"> & {
    requesterTurnRunId?: string;
    acceptsRequest: (custody: ExecRequestCustody | undefined) => boolean;
  }, run: (cancel: () => Promise<AgentHarnessDescendantCancellationResult>) => Promise<T>): Promise<T>;
  /** Invalidate native context only when a same-key history cut commits; preserve compaction. */
  withSessionContextReset?<T>(this: void, params: AgentHarnessSessionContextResetParams, run: (mutation: AgentHarnessSessionDeletionMutation) => Promise<T>): Promise<T>;
  /** Prepare outside the session writer; release native resources after its commit completes. */
  withSessionDeletion?<T>(this: void, params: AgentHarnessSessionDeletionParams, run: (mutation: AgentHarnessSessionDeletionMutation) => Promise<T>): Promise<T>;
  dispose?(): Promise<void> | void;
  /**
   * @deprecated Use sessionForkV2. This legacy fork contract remains
   * source-compatible through 2026-10-12.
   */
  sessionFork?: {
    upstreamKinds: readonly SessionUpstreamKind[];
    fork(params: AgentHarnessSessionForkParams): Promise<AgentHarnessSessionForkResult>;
  };
  sessionForkV2?: {
    /** Declares fork initialization that can execute work on the Gateway host. */
    executionEnvironment?: "host-only";
    upstreamKinds: readonly SessionUpstreamKind[];
    fork(params: AgentHarnessSessionForkParamsV2): Promise<AgentHarnessSessionForkResult>;
  };
  /** Revalidate an artifact only at setup and persistent-operation boundaries. */
  runtimeArtifact?: {
    validate(binding: AgentHarnessRuntimeArtifactBinding): Promise<boolean>;
  };
  /** Recomputes the exact credential fingerprint at persistent trust boundaries. */
  authBinding?: {
    fingerprint(params: AgentHarnessAuthBindingFingerprintParams): Promise<string | undefined>;
  };
  /**
   * Contributes runtime-owned quota data without registering a text provider.
   * Provider usage hooks remain authoritative when both surfaces exist.
   */
  fetchUsageSnapshot?: (ctx: ProviderFetchUsageSnapshotContext) => Promise<ProviderUsageSnapshot | null | undefined> | ProviderUsageSnapshot | null | undefined;
  /** Lists the MCP tools owned by this session's native runtime, if it is already bound. */
  loadMcpToolCatalog?(params: AgentHarnessMcpCatalogParams): Promise<McpToolCatalog | undefined>;
  /** Borrows the existing thread-owned MCP connection for explicit user App interactions. */
  acquireMcpAppRuntime?(params: AgentHarnessMcpCatalogParams & {
    assertCurrent: () => void;
    appRequester?: McpAppRequesterIdentity;
    /** Lazy: warm sessions never acquire preparation authority. */
    prepareSession?: () => Promise<AgentHarnessSessionPreparationV1>;
  }): Promise<SessionMcpRuntimeLease | undefined>;
  /** Lists account-scoped models owned by this native runtime. */
  loadModelCatalog?(params: AgentHarnessModelCatalogParams): Promise<AgentHarnessModelCatalogResult>;
  /**
   * Narrows resolved picker tiers for this runtime. Synchronous, no I/O or discovery;
   * return a subset without mutating inputs. This does not grant execution authority.
   */
  filterModelServiceTiers?(params: {
    config: OpenClawConfig;
    agentId?: string;
    provider: string;
    modelId: string;
    serviceTiers: readonly string[];
  }): readonly string[];
  /**
   * Reads current, secret-free native account evidence for this exact catalog scope/model.
   * No I/O or discovery here. Missing/stale/disposed evidence returns undefined; this is
   * picker metadata only, never execution authorization or a host-route credential.
   * When known, authMode describes this same account observation.
   */
  readModelCatalogReadiness?(params: AgentHarnessModelCatalogParams & {
    provider: string;
    modelId: string;
  }): {
    accountType: string;
    authMode?: string;
  } | undefined;
};
/**
 * @deprecated Implement AgentHarnessV2. This registration contract remains
 * source-compatible for existing plugins through 2026-10-12.
 */
type AgentHarness = AgentHarnessContract;
/** Current harness contract for hosts that always supply versioned capabilities. */
type AgentHarnessV2 = AgentHarnessContract<AgentHarnessAttemptParamsV2, AgentHarnessSideQuestionParamsV2>;
//#endregion
//#region src/shared/plugin-inline-view.d.ts
/** The durable display record. Availability is presentation state, never stored data. */
type PluginInlineViewDescriptor = {
  pluginId: string;
  viewId: string;
  version: number;
  payload: PluginJsonValue;
  summary: string;
};
//#endregion
//#region src/plugins/inline-view.d.ts
type PluginInlineViewResult = {
  content: [{
    type: "text";
    text: string;
  }];
  details: {
    pluginInlineView: PluginInlineViewDescriptor;
  };
};
//#endregion
//#region src/plugins/plugin-api.types.d.ts
type AnyChannelPlugin = AnyChannelPlugin$2;
type ChannelPluginForGatewayVersion<Version extends 1 | 2> = Omit<ChannelPlugin, "gateway"> & {
  gateway?: Extract<NonNullable<AnyChannelPlugin["gateway"]>, {
    apiVersion?: Version;
  }>;
};
type ChannelRegistrationForGatewayVersion<Version extends 1 | 2> = ChannelPluginForGatewayVersion<Version> | OpenClawPluginChannelRegistration<ChannelPluginForGatewayVersion<Version>>;
type OpenClawPluginSessionStateApi = {
  /** Register plugin-owned session state projected into Gateway session rows. */
  registerSessionExtension: (extension: PluginSessionExtensionRegistration) => void;
};
type PluginActiveRunSteerParams = {
  sessionKey: string;
  text: string;
  /** Operator-facing note without model-only delivery instructions; defaults to text. */
  displayText?: string;
  idempotencyKey?: string;
};
type PluginActiveRunSteerResult = {
  steered: true;
  runId?: string;
} | {
  steered: false;
  reason: string;
};
type OpenClawPluginSessionWorkflowApi = {
  /** Queue one plugin-owned context injection for the next agent turn in a session. */
  enqueueNextTurnInjection: (injection: PluginNextTurnInjection) => Promise<PluginNextTurnInjectionEnqueueResult>;
  /** Steer a current run without starting a turn; shown only as a Control UI notice, never a channel reply. */
  steerActiveRun: (params: PluginActiveRunSteerParams) => Promise<PluginActiveRunSteerResult>;
  /**
   * 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.
   * Intended for bundled plugins with host channel/session integration available.
   * Calls can return `{ ok: false }` when side effects are disabled or the required
   * channel runtime is not loaded; callers must handle that result.
   */
  sendSessionAttachment: (params: PluginSessionAttachmentParams) => Promise<PluginSessionAttachmentResult>;
  /**
   * Schedule a future agent turn in a session through Cron.
   * Cron owns timing and records the run history when the turn runs.
   * Bundled plugins only; workspace plugins receive undefined.
   */
  scheduleSessionTurn: (params: PluginSessionTurnScheduleParams) => Promise<PluginSessionSchedulerJobHandle | undefined>;
  /**
   * Remove Cron-backed scheduled session turns that share a plugin-owned tag.
   * Bundled plugins only; workspace plugins receive a zero-count result.
   */
  unscheduleSessionTurnsByTag: (params: PluginSessionTurnUnscheduleByTagParams) => Promise<PluginSessionTurnUnscheduleByTagResult>;
};
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 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 OpenClawPluginLifecycleApi = Partial<PluginInstanceLifecycle> & {
  /** Register cleanup hooks for plugin-owned host state and background work. */
  registerRuntimeLifecycle: (lifecycle: PluginRuntimeLifecycleRegistration) => void;
};
/**
 * Main registration API injected into native plugin entry files.
 * @experimental All plugin APIs are experimental. Pin and test OpenClaw host versions.
 * @see https://docs.openclaw.ai/plugins/sdk-overview#api-stability
 */
type OpenClawPluginApi = {
  /** Data for an installed native view, with a portable text summary. */
  inlineView: (viewId: string, payload: PluginJsonValue, options: {
    version: number;
    summary: string;
  }) => PluginInlineViewResult;
  id: string;
  name: string;
  version?: string;
  description?: string;
  source: string;
  /** Selected runtime entrypoint, independent of setup; absent without runtime artifact selection. */
  readonly runtimeSource?: string;
  rootDir?: string;
  registrationMode: PluginRegistrationMode;
  config: OpenClawConfig;
  pluginConfig?: Record<string, unknown>;
  /**
   * 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: {
    state: OpenClawPluginSessionStateApi;
    workflow: OpenClawPluginSessionWorkflowApi;
    controls: OpenClawPluginSessionControlsApi;
  };
  /** Grouped facade for agent-event workflow seams. */
  agent: {
    /** Optional; requires contracts.subagentProfiles and native-subagent-profiles-v1. */
    registerSubagentProfile?: (profile: PluginSubagentProfile) => void;
    events: OpenClawPluginAgentEventsApi;
  };
  /** Grouped facade for run-scoped plugin scratch state. */
  runContext: {
    /** 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;
  };
  /** Grouped facade for plugin-owned lifecycle cleanup hooks. */
  lifecycle: OpenClawPluginLifecycleApi;
  registerTool: (tool: AnyAgentTool | OpenClawPluginToolFactory | OpenClawPluginToolFactory<2>, opts?: OpenClawPluginToolOptions$1) => void;
  registerHook: (events: string | string[], handler: InternalHookHandler, opts?: OpenClawPluginHookOptions) => void;
  registerHttpRoute: (params: OpenClawPluginHttpRouteParams) => void;
  /** Register a plugin-owned destination for presenting hosted widget documents. */
  registerWidgetPresenter: (presenter: WidgetPresenter) => void;
  /** Bind a declared MCP server's transport to the trusted message requester. */ registerMcpServerConnectionResolver: (resolver: OpenClawPluginMcpServerConnectionResolver) => void;
  /** Register a native messaging channel plugin (channel capability). */
  registerChannel: {
    (registration: ChannelRegistrationForGatewayVersion<1>): void;
    (registration: ChannelRegistrationForGatewayVersion<2>): void;
    (registration: OpenClawPluginChannelRegistration<AnyChannelPlugin> | AnyChannelPlugin): 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;
    profileAccess?: "independent" | "required";
    /** Require a top-level sessionKey (and optional agentId) naming an existing session. */
    sessionAccess?: GatewayMethodSessionAccess;
    shareKey?: GatewayReadSharing["shareKey"];
    shareInvalidationEvents?: readonly string[];
    shareMaxAgeMs?: number;
  }) => void;
  /** Add a plugin-owned lifetime requirement to authenticated person admission. */
  registerGatewayAccessPolicy: (policy: PluginGatewayAccessPolicy) => void;
  /** Register a sandboxed board widget source kind owned by this plugin. */
  /** Register a read-only external-session catalog with optional native adoption actions. */
  registerSessionCatalog: (provider: SessionCatalogProvider) => void;
  registerCli: (registrar: OpenClawPluginCliRegistrar, opts?: OpenClawPluginCliRegistrationOptions) => 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;
    (service: OpenClawPluginServiceV2): void;
    (service: OpenClawPluginService | OpenClawPluginServiceV2): 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 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 a cloud-worker lifecycle provider. */
  registerWorkerProvider: (provider: WorkerProvider) => void;
  registerStorageProvider: (provider: StorageProvider) => 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 descriptor or synchronous factory bound to native host operations. */
  registerSpeechProvider: (provider: SpeechProviderPlugin | ((context: PluginCapabilityCatalogHostContext) => SpeechProviderPlugin)) => void;
  /** Register a transcription descriptor or synchronous factory bound to native host operations. */
  registerRealtimeTranscriptionProvider: (provider: RealtimeTranscriptionProviderPlugin | ((context: PluginCapabilityCatalogHostContext) => RealtimeTranscriptionProviderPlugin)) => void;
  /** Register a voice descriptor or synchronous factory bound to native host operations. */
  registerRealtimeVoiceProvider: (provider: RealtimeVoiceProviderPlugin | ((context: PluginCapabilityCatalogHostContext) => 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>) => 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 versioned typed decision executor declared in the manifest. */
  registerDecisionProvider: (provider: DecisionProviderV1 | DecisionProviderV2) => void;
  /** Register a compaction provider (pluggable summarization backend). */
  registerCompactionProvider: (provider: CompactionProvider) => void;
  /** Register an agent harness implementation. */
  registerAgentHarness: (harness: AgentHarness, options?: AgentHarnessRegistrationOptions) => 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: OpenClawPluginSessionStateApi["registerSessionExtension"];
  /**
   * Queue one plugin-owned context injection for the next agent turn in a session.
   * @deprecated Use `api.session.workflow.enqueueNextTurnInjection(...)`.
   */
  enqueueNextTurnInjection: OpenClawPluginSessionWorkflowApi["enqueueNextTurnInjection"];
  /**
   * Register a trusted pre-tool policy. Installed plugins must declare the
   * policy id in `contracts.trustedToolPolicies`.
   */
  registerTrustedToolPolicy: (policy: PluginTrustedToolPolicyRegistration) => void;
  /**
   * Register display/policy metadata for a plugin-owned tool. Metadata is
   * scoped to the (pluginId, toolName) pair at projection time, so plugins
   * cannot decorate other plugins' tools or core tools through this surface.
   */
  registerToolMetadata: (metadata: PluginToolMetadataRegistration) => void;
  /**
   * Register a generic Control UI contribution descriptor.
   * @deprecated Use `api.session.controls.registerControlUiDescriptor(...)`.
   */
  registerControlUiDescriptor: OpenClawPluginSessionControlsApi["registerControlUiDescriptor"];
  /**
   * Register cleanup hooks for plugin-owned host state and background work.
   * @deprecated Use `api.lifecycle.registerRuntimeLifecycle(...)`.
   */
  registerRuntimeLifecycle: OpenClawPluginLifecycleApi["registerRuntimeLifecycle"];
  /**
   * Subscribe to sanitized agent events through the host-owned plugin lifecycle.
   * @deprecated Use `api.agent.events.registerAgentEventSubscription(...)`.
   */
  registerAgentEventSubscription: OpenClawPluginAgentEventsApi["registerAgentEventSubscription"];
  /**
   * 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: OpenClawPluginSessionWorkflowApi["registerSessionSchedulerJob"];
  /** Register the active memory capability for this memory plugin (exclusive slot). */
  registerMemoryCapability: (capability: MemoryPluginCapability) => void;
  /** Register an additive memory-adjacent prompt section (non-exclusive). */
  registerMemoryPromptSupplement: (builder: MemoryPromptSectionBuilder) => void;
  /** Register an async memory prompt preparation step (non-exclusive). */
  registerMemoryPromptPreparation: (prepare: (params: MemoryPromptSectionParams) => Promise<readonly string[]>) => void;
  /** Register an additive memory-adjacent search/read corpus supplement (non-exclusive). */
  registerMemoryCorpusSupplement: (supplement: MemoryCorpusSupplement) => void;
  resolvePath: (input: string) => string;
  /** Register a lifecycle hook handler */
  on: <K extends PluginHookName>(hookName: K, handler: PluginHookHandlerMap[K], opts?: PluginHookRegistrationOptions<K>) => void;
};
//#endregion
//#region src/plugins/plugin-config-schema.types.d.ts
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. `jsonSchema` is optional runtime schema metadata.
 */
type OpenClawPluginConfigSchema = {
  safeParse?: (value: unknown) => {
    success: boolean;
    data?: unknown;
    error?: {
      issues?: Array<{
        path: Array<string | number>;
        message: string;
      }>;
    };
  };
  parse?: (value: unknown) => unknown;
  validate?: (value: unknown) => PluginConfigValidation;
  /**
   * @deprecated Declare config presentation metadata in the plugin's
   * `openclaw.plugin.json` manifest via top-level `uiHints`. The host reads
   * manifest hints and does not consume runtime config-schema hints.
   */
  uiHints?: Record<string, PluginConfigUiHint>;
  jsonSchema?: JsonSchemaObject;
};
//#endregion
//#region src/plugins/plugin-definition.types.d.ts
/** 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;
};
//#endregion
//#region src/tts/directives.d.ts
type ParseTtsDirectiveOptions = {
  cfg?: OpenClawConfig;
  providers?: readonly SpeechProviderPlugin[];
  providerConfigs?: Record<string, SpeechProviderConfig>;
  preferredProviderId?: string;
};
/** Parse TTS directives from final message text, leaving markdown code spans unchanged. */
declare function parseTtsDirectives(text: string, policy: SpeechModelOverridePolicy, options?: ParseTtsDirectiveOptions): TtsDirectiveParseResult;
//#endregion
//#region src/agents/simple-completion-execution.d.ts
type SimpleCompletionModelOptions = {
  headers?: Record<string, string>;
  sessionId?: string;
  maxTokens?: number;
  temperature?: number;
  serviceTier?: SimpleStreamOptions["serviceTier"];
  reasoning?: ThinkLevel;
  strictReasoningTags?: boolean;
  signal?: AbortSignal;
};
type PreparedCompletionParams = {
  assertCurrent?: () => void;
  model: Model;
  auth: ResolvedProviderAuth;
  context: Parameters<typeof completeSimple>[1];
  cfg?: OpenClawConfig;
  options?: SimpleCompletionModelOptions;
};
declare function completeWithPreparedSimpleCompletionModel(params: PreparedCompletionParams): Promise<AssistantMessage>;
//#endregion
//#region src/agents/simple-completion-runtime.d.ts
type PreparedStreamCompletionModel = (Extract<PreparedSimpleCompletionModel, {
  model: Model;
}> & {
  recordServiceTierObservation?: ReturnType<NonNullable<PreparedModelRuntimeSnapshot["accountCatalog"]>["prepareServiceTierObserver"]>;
}) | Extract<PreparedSimpleCompletionModel, {
  error: string;
}>;
/** Prepares a model within the exact generation already held by its caller. */
declare function prepareSimpleCompletionModel(params: PrepareSimpleCompletionModelParams & {
  preparedModelRuntime: PreparedModelRuntimeSnapshot;
}, assertCurrent?: () => void): Promise<PreparedStreamCompletionModel>;
//#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<string, ResolvedTtsPersona>;
  summaryModel?: string;
  modelOverrides: ResolvedTtsModelOverrides;
  providerConfigs: Record<string, SpeechProviderConfig>;
  prefsPath?: string;
  maxTextLength: number;
  timeoutMs: number;
  timeoutMsSource?: "config" | "default";
  rawConfig?: TtsConfig;
  sourceConfig?: OpenClawConfig;
};
//#endregion
//#region src/tts/tts-core.d.ts
type SummarizeTextDeps = {
  completeWithPreparedSimpleCompletionModel: typeof completeWithPreparedSimpleCompletionModel;
  prepareSimpleCompletionModel: (params: PrepareSimpleCompletionModelParams) => ReturnType<typeof prepareSimpleCompletionModel>;
  requireApiKey: typeof requireApiKey;
};
type SummarizeResult = {
  summary: string;
  latencyMs: number;
  inputLength: number;
  outputLength: number;
};
declare function summarizeText(params: {
  text: string;
  targetLength: number;
  cfg: OpenClawConfig;
  config: ResolvedTtsConfig;
  timeoutMs: number;
  agentId?: string;
}, deps?: SummarizeTextDeps): Promise<SummarizeResult>;
//#endregion
//#region src/tts/tts-auto-mode.d.ts
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/plugins/provider-registry-shared.d.ts
declare function normalizeCapabilityProviderId(providerId: string | undefined): string | undefined;
//#endregion
//#region src/tts/tts-settings.d.ts
declare function setTtsMachinePrefsPathResolver(resolver?: () => string | undefined): void;
declare function resolveModelOverridePolicy(overrides: TtsModelOverrideConfig | undefined): ResolvedTtsModelOverrides;
declare function resolveTtsConfig(cfgInput: OpenClawConfig, contextOrAgentId?: string | TtsConfigResolutionContext): ResolvedTtsConfig;
/** Resolves a prepared preference path without reading the state database. */
declare function resolveTtsPrefsPath(config: ResolvedTtsConfig, preparedTtsPreferences: PreparedTtsPreferences): string;
/** @deprecated Use resolveTtsPrefsPathAsync or pass awaited prepareTtsPreferences(). Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function resolveTtsPrefsPath(config: ResolvedTtsConfig, preparedTtsPreferences?: PreparedTtsPreferences): string;
declare function resolveTtsPrefsPathAsync(config: ResolvedTtsConfig, preparedTtsPreferences?: PreparedTtsPreferences): Promise<string>;
declare function resolveTtsAutoMode(params: {
  config: ResolvedTtsConfig;
  prefsPath: string;
  sessionAuto?: string;
}): TtsAutoMode;
/** Builds the hint from an awaited preference-path preparation without state-database reads. */
declare function buildTtsSystemPromptHint(cfg: OpenClawConfig, agentId: string | undefined, options: {
  messageToolOnly?: boolean;
  preparedTtsPreferences: PreparedTtsPreferences;
}): string | undefined;
/** @deprecated Await api.runtime.tts.buildSystemPromptHintAsync. Bundled callers can pass awaited prepareTtsPreferences(). Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
declare function buildTtsSystemPromptHint(cfg: OpenClawConfig, agentId?: string, options?: {
  messageToolOnly?: boolean;
  preparedTtsPreferences?: PreparedTtsPreferences;
}): string | undefined;
/** Prepares machine preferences through their worker owner before rendering the hint. */
declare function buildTtsSystemPromptHintAsync(cfg: OpenClawConfig, agentId?: string, options?: {
  messageToolOnly?: boolean;
  preparedTtsPreferences?: PreparedTtsPreferences;
}): Promise<string | undefined>;
declare function isTtsEnabled(config: ResolvedTtsConfig, prefsPath: string, sessionAuto?: string): boolean;
declare function getTtsPersona(config: ResolvedTtsConfig, prefsPath: string): ResolvedTtsPersona | undefined;
declare function listTtsPersonas(config: ResolvedTtsConfig): ResolvedTtsPersona[];
declare function getTtsMaxLength(prefsPath: string): number;
declare function isSummarizationEnabled(prefsPath: string): boolean;
//#endregion
//#region src/tts/tts-provider-resolution.d.ts
declare function getResolvedSpeechProviderConfig(config: ResolvedTtsConfig, providerId: string, cfg?: OpenClawConfig): SpeechProviderConfig;
declare function resolveTtsProviderOrder(primary: TtsProvider, cfg?: OpenClawConfig, providers?: readonly SpeechProviderPlugin[]): TtsProvider[];
/** @deprecated Use isTtsProviderConfiguredAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
declare function isTtsProviderConfigured(config: ResolvedTtsConfig, provider: TtsProvider | SpeechProviderPlugin, cfg?: OpenClawConfig): boolean;
declare function isTtsProviderConfiguredAsync(config: ResolvedTtsConfig, provider: TtsProvider | SpeechProviderPlugin, cfg?: OpenClawConfig, onError?: (error: unknown) => void): Promise<boolean>;
//#endregion
//#region src/tts/tts-runtime-types.d.ts
type TtsProviderAttempt = {
  provider: string;
  outcome: "success" | "skipped" | "failed";
  reasonCode: "success" | "no_provider_registered" | "not_configured" | "unsupported_for_streaming" | "unsupported_for_telephony" | "timeout" | "provider_error";
  persona?: string;
  personaBinding?: "applied" | "missing" | "none";
  latencyMs?: number;
  error?: string;
};
type TtsAttemptOutcome = {
  success: boolean;
  error?: string;
  latencyMs?: number;
  provider?: string;
  persona?: string;
  fallbackFrom?: string;
  attemptedProviders?: string[];
  attempts?: TtsProviderAttempt[];
};
type TtsMediaOutcome = TtsAttemptOutcome & {
  outputFormat?: string;
};
type TtsProviderMediaOutcome = TtsMediaOutcome & {
  providerModel?: string;
  providerVoice?: string;
};
type TtsVoiceMediaOutcome = TtsProviderMediaOutcome & {
  voiceCompatible?: boolean;
  fileExtension?: string;
  target?: "audio-file" | "voice-note";
};
type TtsResult = TtsMediaOutcome & {
  audioPath?: string;
  voiceCompatible?: boolean;
  audioAsVoice?: boolean;
  target?: "audio-file" | "voice-note";
};
type TtsSynthesisResult = TtsVoiceMediaOutcome & {
  audioBuffer?: Buffer;
};
type TtsStreamResult = TtsVoiceMediaOutcome & {
  audioStream?: ReadableStream<Uint8Array>;
  release?: () => Promise<void>;
};
type TtsSynthesisStreamResult = TtsStreamResult;
type TtsTelephonyResult = TtsProviderMediaOutcome & {
  audioBuffer?: Buffer;
  sampleRate?: number;
};
type TtsStatusEntry = TtsAttemptOutcome & {
  timestamp: number;
  textLength: number;
  summarized: boolean;
};
//#endregion
//#region src/tts/tts-synthesis-support.d.ts
declare function formatTtsProviderError(provider: TtsProvider, err: unknown): string;
declare function sanitizeTtsErrorForLog(err: unknown): string;
//#endregion
//#region src/tts/tts-synthesis.d.ts
type TtsAudioPersistence = (params: {
  audioBuffer: Buffer;
  cfg: OpenClawConfig;
  fileExtension: string;
  outputFormat?: string;
}) => Promise<string>;
declare function supportsNativeVoiceNoteTts(channel: string | undefined): boolean;
declare function supportsTranscodedVoiceNoteTts(channel: string | undefined): boolean;
declare function resolveTtsSynthesisTarget(channel: string | undefined): "audio-file" | "voice-note";
declare function shouldDeliverTtsAsVoice(params: {
  channel: string | undefined;
  target: "audio-file" | "voice-note" | undefined;
  voiceCompatible: boolean | undefined;
  fileExtension?: string;
  outputFormat?: string;
}): boolean;
declare function textToSpeechCore(params: SpeechSynthesisParams$1, persistTtsAudio: TtsAudioPersistence): Promise<TtsResult>;
type SpeechSynthesisParams$1 = {
  text: string;
  cfg: OpenClawConfig;
  prefsPath?: string;
  channel?: string;
  overrides?: TtsDirectiveOverrides;
  disableFallback?: boolean;
  timeoutMs?: number;
  agentId?: string;
  accountId?: string;
};
declare function synthesizeSpeech(params: SpeechSynthesisParams$1): Promise<TtsSynthesisResult>;
//#endregion
//#region src/tts/runtime-availability.d.ts
/** Installs the process-lifecycle availability guard owned by the OpenClaw host. */
declare function setSpeechRuntimeAvailabilityGuard(guard: (() => void) | undefined): void;
//#endregion
//#region src/tts/tts-settings-writes.d.ts
declare function setTtsAutoMode(prefsPath: string, mode: TtsAutoMode): void;
declare function setTtsEnabled(prefsPath: string, enabled: boolean): void;
declare function setTtsPersona(prefsPath: string, persona: string | null | undefined): void;
declare function setTtsProvider(prefsPath: string, provider: TtsProvider): void;
declare function setTtsMaxLength(prefsPath: string, maxLength: number): void;
declare function setSummarizationEnabled(prefsPath: string, enabled: boolean): void;
//#endregion
//#region src/tts/tts-payload.d.ts
declare function getLastTtsAttempt(): TtsStatusEntry | undefined;
declare function setLastTtsAttempt(entry: TtsStatusEntry | undefined): void;
declare function listSpeechVoices(params: {
  provider: string;
  cfg?: OpenClawConfig;
  config?: ResolvedTtsConfig;
  apiKey?: string;
  baseUrl?: string;
}): Promise<SpeechVoiceOption[]>;
//#endregion
//#region src/tts/tts-request.d.ts
type PreparedTtsRequest = {
  cfg: OpenClawConfig;
  directives: TtsDirectiveParseResult;
};
/** Merge a surface TTS override and resolve its inline synthesis directives. */
declare function prepareTtsRequest(params: {
  cfg: OpenClawConfig;
  override?: TtsConfig;
  text: string;
}): Promise<PreparedTtsRequest>;
type ExplicitTtsOverrideParams = {
  cfg: OpenClawConfig;
  prefsPath?: string;
  provider?: string;
  modelId?: string;
  voiceId?: string;
  agentId?: string;
  channelId?: string;
  accountId?: string;
};
/** @deprecated Use resolveExplicitTtsOverridesAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
declare function resolveExplicitTtsOverrides(params: ExplicitTtsOverrideParams): TtsDirectiveOverrides;
declare function resolveExplicitTtsOverridesAsync(params: ExplicitTtsOverrideParams): Promise<TtsDirectiveOverrides>;
//#endregion
//#region src/tts/tts-streaming.d.ts
type SpeechSynthesisParams = Parameters<typeof synthesizeSpeech>[0];
declare function streamSpeech(params: SpeechSynthesisParams): Promise<TtsSynthesisStreamResult>;
declare function textToSpeechStream(params: SpeechSynthesisParams): Promise<TtsStreamResult>;
//#endregion
//#region src/tts/tts-telephony.d.ts
declare function textToSpeechTelephony(params: {
  text: string;
  cfg: OpenClawConfig;
  prefsPath?: string;
  overrides?: TtsDirectiveOverrides;
  timeoutMs?: number;
}): Promise<TtsTelephonyResult>;
declare namespace runtime_api_d_exports {
  export { ResolvedTtsConfig, ResolvedTtsModelOverrides, TtsDirectiveOverrides, TtsDirectiveParseResult, TtsStreamResult, TtsSynthesisResult, TtsSynthesisStreamResult, TtsTelephonyResult, buildTtsSystemPromptHint, buildTtsSystemPromptHintAsync, getLastTtsAttempt, getResolvedSpeechProviderConfig, getTtsMaxLength, getTtsPersona, getTtsProvider, getTtsProviderAsync, isSummarizationEnabled, isTtsEnabled, isTtsProviderConfigured, isTtsProviderConfiguredAsync, listSpeechVoices, listTtsPersonas, prepareTtsRequest, resolveExplicitTtsOverrides, resolveExplicitTtsOverridesAsync, resolveTtsAutoMode, resolveTtsConfig, resolveTtsPrefsPath, resolveTtsPrefsPathAsync, resolveTtsProviderOrder, setLastTtsAttempt, setSpeechRuntimeAvailabilityGuard, setSummarizationEnabled, setTtsAutoMode, setTtsEnabled, setTtsMachinePrefsPathResolver, setTtsMaxLength, setTtsPersona, setTtsProvider, streamSpeech, synthesizeSpeech, testApi, textToSpeechStream, textToSpeechTelephony };
}
/** @deprecated Use getTtsProviderAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
declare function getTtsProvider(config: ResolvedTtsConfig, prefsPath: string): TtsProvider;
declare function getTtsProviderAsync(config: ResolvedTtsConfig, prefsPath: string): Promise<TtsProvider>;
declare const testApi: {
  parseTtsDirectives: typeof parseTtsDirectives;
  resolveModelOverridePolicy: typeof resolveModelOverridePolicy;
  supportsNativeVoiceNoteTts: typeof supportsNativeVoiceNoteTts;
  supportsTranscodedVoiceNoteTts: typeof supportsTranscodedVoiceNoteTts;
  resolveTtsSynthesisTarget: typeof resolveTtsSynthesisTarget;
  shouldDeliverTtsAsVoice: typeof shouldDeliverTtsAsVoice;
  summarizeText: typeof summarizeText;
  getResolvedSpeechProviderConfig: typeof getResolvedSpeechProviderConfig;
  formatTtsProviderError: typeof formatTtsProviderError;
  sanitizeTtsErrorForLog: typeof sanitizeTtsErrorForLog;
};
//#endregion
//#region src/plugins/runtime/runtime-agent-session-catalog.d.ts
type RuntimeSessionCatalogCreateTargetParams = {
  config: OpenClawConfig;
  requestedAgentId?: string;
  provider: string;
  modelIds: readonly string[];
  agentRuntime: string;
};
/**
 * Resolve a synchronous catalog create target through the same model/runtime
 * policy used by agent turns, without making plugins import that policy graph.
 */
declare function resolveAgentCatalogCreateTarget(params: RuntimeSessionCatalogCreateTargetParams): SessionCatalogCreateTarget | undefined;
//#endregion
//#region src/agents/command/types.d.ts
type ImageContent = Pick<ImageContent$1, "type" | "data" | "mimeType">;
type AgentRunContext = {
  messageChannel?: string;
  accountId?: string;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  currentChannelId?: string;
  /** Transport-native chat/conversation ID for plugin hook identity context. */
  chatId?: string;
  /** Channel-specific sender/chat metadata for plugin hook identity context. */
  channelContext?: PluginHookChannelContext;
  currentThreadTs?: string;
  currentInboundAudio?: boolean;
  senderId?: string | null;
  replyToMode?: "off" | "first" | "all" | "batched";
  hasRepliedRef?: {
    value: boolean;
  };
};
/** Full trusted option surface for running an agent command. */
type AgentCommandOpts = {
  message: string;
  /** User-visible transcript body; defaults to message and excludes runtime-only context. */
  transcriptMessage?: string;
  /** Durable media metadata for the user-visible transcript turn. */
  transcriptMedia?: UserTurnInput["media"];
  images?: ImageContent[];
  /** Original inline/offloaded attachment order for inbound images. */
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered facts represented by attachment text in this prompt. */
  media?: MediaFact[];
  /** Optional client-provided tools (OpenResponses hosted tools). */
  clientTools?: ClientToolDefinition[];
  /** Agent id override (must exist in config). */
  agentId?: string;
  provider?: string;
  model?: string;
  /** Explicit ordered fallback chain for this run. Undefined uses normal selection policy. */
  modelFallbacksOverride?: string[];
  to?: string;
  sessionId?: string;
  sessionKey?: string;
  thinking?: string;
  thinkingOnce?: string;
  verbose?: string;
  json?: boolean;
  timeout?: string;
  deliver?: boolean;
  /** Override delivery target (separate from session routing). */
  replyTo?: string;
  /** Override delivery channel (separate from session routing). */
  replyChannel?: string;
  /** Override delivery account id (separate from session routing). */
  replyAccountId?: string;
  /** Override delivery thread/topic id (separate from session routing). */
  threadId?: string | number;
  messageChannel?: string;
  /** Tool-policy/output surface context. Defaults to messageChannel. */
  messageProvider?: string;
  channel?: string;
  /** Account ID for multi-account channel routing. */
  accountId?: string;
  runContext?: AgentRunContext;
  /** Client capabilities captured by trusted Gateway ingress. */
  clientCaps?: string[];
  /** Exact Control UI destination captured by trusted Gateway ingress. */
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  /** Tool bindings admitted by the originating Gateway request. */
  toolBindings?: Readonly<Record<string, unknown>>;
  /** Follow-up task action sink admitted by the originating Gateway client. */
  taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  /** Device-scoped operator session allowed to review approvals initiated by this run. */
  approvalReviewerDeviceId?: string;
  /** Internal trusted exec approval follow-up elevated defaults. */
  bashElevated?: ExecElevatedDefaults;
  /** Trusted span whose final cap is resolved with the selected model. */
  execApprovalContinuationPromptRange?: ExecApprovalContinuationPromptRange;
  /** Corresponding span in the undecorated transcript message. */
  execApprovalContinuationTranscriptPromptRange?: ExecApprovalContinuationPromptRange;
  /** Trusted sender identity bit for command/channel-action auth; defaults true for local CLI calls. */
  senderIsOwner?: boolean;
  /** Host-verified current requester for Git credit only; never accepted from public ingress. */
  gitContributorProfileId?: string;
  /** Whether this caller is authorized to use provider/model per-run overrides. */
  allowModelOverride?: boolean;
  /** Optional runtime tool allow-list; when set, only these tools are exposed for this run. */
  toolsAllow?: string[];
  /** Trusted owner-scoped plugin tool grant; normal policy and deny rules still apply. */
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  /** Consumed in-process subagent-completion capability; never accepted from public RPC params. */
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  /** Internal marker identifying a server-managed default cap. */
  toolsAllowIsDefault?: boolean;
  /** Trusted server-stamped authority for an explicitly capped scheduled run. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
  /** Host-authorized dashboard authoring without an originating inline renderer. */
  pinnedWidgetAuthoring?: boolean;
  /** Preserve the originating run's message-tool policy across internal continuation turns. */
  requireExplicitMessageTarget?: boolean;
  cliSessionBindingFacts?: CliSessionBindingFacts;
  /** Group/spawn metadata for subagent policy inheritance and routing context. */
  groupId?: SpawnedRunMetadata["groupId"];
  groupChannel?: SpawnedRunMetadata["groupChannel"];
  groupSpace?: SpawnedRunMetadata["groupSpace"];
  spawnedBy?: SpawnedRunMetadata["spawnedBy"];
  deliveryTargetMode?: ChannelOutboundTargetMode;
  bestEffortDeliver?: boolean;
  abortSignal?: AbortSignal;
  /** Private source-owner fence; cancellation alone does not establish current authority. */
  assertSourceCurrent?: CommandOwnerAssertion;
  /** Original operator restriction; host-only and never accepted from public ingress. */
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /** Host-captured requester identity for policy resolution across internal continuations. */
  requesterOrigin?: RequesterOrigin;
  lane?: string;
  swarmExecutionLane?: CommandLaneConfiguration;
  runId?: string;
  /** Immutable gateway lifecycle ownership captured when this run was admitted. */
  lifecycleGeneration?: string;
  /** Startup awaits returned work; incidental synchronous return values are ignored. */
  onExecutionStarted?: () => unknown;
  extraSystemPrompt?: string;
  /** Internal conversation-producer annotation, not accepted from public ingress. */
  extraSystemPromptTurnContext?: {
    start: number;
    text: string;
  };
  /** Conversation preparation owns silence guidance; required-reply enforcement is separate. */
  silentReplyPromptMode?: SilentReplyPromptMode;
  bootstrapContextMode?: "full" | "lightweight";
  bootstrapContextRunKind?: BootstrapContextRunKind;
  internalEvents?: AgentInternalEvent[];
  runtimeContextFragments?: RuntimeContextFragment[];
  inputProvenance?: InputProvenance;
  /** Internal runs can execute against a session without updating visible status/model/usage. */
  sessionEffects?: "visible" | "internal";
  /** Internal handoffs can write transcript turns without changing user-facing model/usage state. */
  preserveUserFacingSessionModelState?: boolean;
  /** Admitted private completion owns a hidden input and its processing receipt. */
  privateCompletion?: true;
  /** Input-owner obligation, captured by trusted ingress; never supplied by model output. */
  replyExpectation?: ReplyExpectation;
  /** Visible source replies must be sent through the message tool when set. */
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  /** Internal runs can omit the channel message tool entirely. */
  disableMessageTool?: boolean;
  /** Collector children fail closed instead of emitting operator approval requests. */
  swarmCollector?: boolean;
  /** Synthetic structured_output input schema for collector children. */
  swarmOutputSchema?: Record<string, unknown>;
  /** Invocation-owned Code Mode activation; limits still come from config. */
  codeModeOverride?: boolean | "auto";
  /** Host-owned: deliver only authored output; runtime error payloads stay out of the chat. */
  internalDeliverySuppressErrors?: boolean;
  /** Gateway ingress that already persisted visible activity can skip the duplicate pre-run touch. */
  skipInitialSessionTouch?: boolean;
  /** Per-call stream param overrides (best-effort). */
  streamParams?: AgentStreamParams;
  /** Resolved per-run fast mode from channel/directive handling. */
  fastMode?: FastMode;
  /** Resolved per-run auto cutoff seconds for fast mode. */
  fastModeAutoOnSeconds?: number;
  /** Explicit workspace directory override (for subagents to inherit parent workspace). */
  workspaceDir?: SpawnedRunMetadata["workspaceDir"];
  /** Explicit task working directory for this run. Bootstrap still uses workspaceDir. */
  cwd?: string;
  /** Force bundled MCP teardown when a one-shot local run completes. */
  cleanupBundleMcpOnRunEnd?: boolean;
  /** Force long-lived CLI live session teardown when a one-shot local run completes. */
  cleanupCliLiveSessionOnRunEnd?: boolean;
  /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */
  oneShotCliRun?: boolean;
  /** Record a root session this run creates as a direct chat with its local operator. */
  operatorDirectRoot?: boolean;
  /** Gateway-owned runs can late-bind plugin subagent and node runtime helpers. */
  allowGatewaySubagentBinding?: boolean;
  /** Gateway-owned exact operational instance shared with its abort controller. */
  operationalRunInstance?: OperationalRunInstanceRef;
  skillLibraryAuthoring?: SkillLibraryAuthoringCapability;
  /** Gateway-minted exact-run capability for late Codex creator-authority capture. */
  cronCreatorAuthorityCapability?: CronCreatorAuthorityCapability;
  /** Private exact-instance binding hook invoked after delegated authority admission. */
  onAdmittedRunContext?: (context: AdmittedRunContext) => void | Promise<void>;
  /** Private owner binding hook invoked only after exact admission has resolved. */
  onPostAdmittedRunContext?: (context: AdmittedRunContext) => void | Promise<void>;
  /** Gateway owns final media projection and joins transcript writes before delivery or cleanup. */
  beforeTerminalDelivery?: (reply?: {
    payloads: ReplyPayload$1[];
    sessionId: string;
    lifecycleRevision?: string;
    storePath?: string;
  }, producerError?: unknown) => Promise<void>;
  /** Exact Gateway execution outcome; terminal cleanup retains its session admission. */
  isTerminalOutcomeObserved?: () => boolean;
  /** Gateway-owned preparation of runtime-appended assistant transcript messages. */
  prepareAssistantTranscriptMessage?: AgentRunTranscriptContext["prepareAssistantTranscriptMessage"];
  /** Called when the actual run model is selected, including fallback retries. */
  onActiveModelSelected?: (ctx: {
    provider: string;
    model: string;
  }) => void | Promise<void>;
  onModelFallbackExhausted?: () => void;
  /** Called before delivery projection when the raw run contains an error payload. */
  onResultErrorPayload?: (message?: string) => void;
  /** Called when compaction rotates the active run onto a successor session. */
  onSessionIdChanged?: (sessionId: string) => void;
  /** Internal one-shot model probe mode: no tools, no workspace/chat prompt policy. */
  modelRun?: boolean;
  /** Internal prompt-mode override for trusted local/gateway callsites. */
  promptMode?: PromptMode;
  /** Internal ACP-ready session turn source. Manual spawn turns bypass only the dispatch gate. */
  acpTurnSource?: "manual_spawn";
  /** Internal handoffs can feed the model without writing the synthetic prompt to transcript. */
  suppressPromptPersistence?: boolean;
  /** Gateway/channel ingress can provide a canonical user-turn persistence owner. */
  userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
};
/** Public ingress clears the same host-owned fields its option type excludes. */
declare const AGENT_COMMAND_PUBLIC_INGRESS_DEFAULTS: {
  readonly clientCaps: undefined;
  readonly gatewayUiCommandTarget: undefined;
  readonly toolBindings: undefined;
  readonly taskSuggestionDeliveryMode: undefined;
  readonly runtimeContextFragments: undefined;
  readonly senderIsOwner: false;
  readonly gitContributorProfileId: undefined;
  readonly pinnedWidgetAuthoring: undefined;
  readonly operationalRunInstance: undefined;
  readonly assertSourceCurrent: undefined;
  readonly operatorAuthority: undefined;
  readonly requesterOrigin: undefined;
  readonly privateCompletion: undefined;
  readonly extraSystemPromptTurnContext: undefined;
  readonly replyExpectation: undefined;
  readonly skillLibraryAuthoring: undefined;
  readonly cronCreatorAuthorityCapability: undefined;
  readonly onAdmittedRunContext: undefined;
  readonly onPostAdmittedRunContext: undefined;
  readonly beforeTerminalDelivery: undefined;
  readonly isTerminalOutcomeObserved: undefined;
  readonly prepareAssistantTranscriptMessage: undefined;
  readonly internalDeliverySuppressErrors: undefined;
  readonly operatorDirectRoot: undefined;
};
type AgentCommandGatewayOnlyKey = Exclude<keyof typeof AGENT_COMMAND_PUBLIC_INGRESS_DEFAULTS, "senderIsOwner">;
/** Restricted option surface for external ingress callsites. */
type AgentCommandIngressOpts = Omit<AgentCommandOpts, AgentCommandGatewayOnlyKey | "senderIsOwner" | "allowModelOverride"> & {
  /** @deprecated Public ingress ignores owner claims; use the host-injected channel runtime. */
  senderIsOwner?: boolean;
  /** Ingress callsites must always pass explicit model-override authorization state. */
  allowModelOverride: boolean;
};
//#endregion
//#region src/agents/command/delivery-result.d.ts
type AgentCommandDeliveryStatus = {
  requested: true;
  attempted: boolean;
  status: "sent" | "suppressed" | "partial_failed" | "failed";
  /** `partial` means at least one payload was sent before a later payload failed. */
  succeeded: true | false | "partial";
  error?: true;
  errorMessage?: string;
  /** Free-form lowercase_snake reason from durable delivery or preflight validation. */
  reason?: string;
  resultCount?: number;
  sentBeforeError?: true;
  payloadOutcomes?: SerializedDurableMessagePayloadOutcome[];
};
type AgentCommandDeliveryResult = Pick<EmbeddedAgentRunResult, "didDeliverSourceReplyViaMessageTool" | "sourceReplyDelivered" | "sourceReplyDeliveryState" | "messagingToolSourceReplyPayloads" | "meta" | "didSendViaMessagingTool" | "messagingToolSentTexts" | "messagingToolSentMediaUrls" | "messagingToolSentTargets" | "acceptedSessionSpawns" | "requesterContinuationSettled" | "successfulCronAdds"> & {
  payloads: ReturnType<typeof projectOutboundPayloadPlanForJson>;
  didSendDeterministicApprovalPrompt?: true;
  deliverySucceeded?: boolean;
  deliveryStatus?: AgentCommandDeliveryStatus;
};
//#endregion
//#region src/agents/agent-command.d.ts
/** Runs an agent turn from an inbound channel/gateway ingress context. */
declare function agentCommandFromIngress(opts: AgentCommandIngressOpts, runtime?: RuntimeEnv, deps?: CliDeps): Promise<AgentCommandDeliveryResult>;
//#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/agents/embedded-agent-runner/cli-backend-dispatch-eligibility.d.ts
type EmbeddedCliBackendDispatchEligibilityParams = {
  provider?: string;
  model?: string;
  agentId?: string;
  /** Explicitly pinned auth profile for the run; decisive when it resolves. */
  authProfileId?: string;
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  preparedAuthStore?: AuthProfileStore$1;
};
/** @deprecated Use resolveEmbeddedCliBackendDispatchEligibilityAsync for worker-owned reads. */
declare function resolveEmbeddedCliBackendDispatchEligibility(params: EmbeddedCliBackendDispatchEligibilityParams): {
  provider: string;
} | undefined;
/** Reads credential metadata through its worker without materializing or refreshing secrets. */
declare function resolveEmbeddedCliBackendDispatchEligibilityAsync(params: EmbeddedCliBackendDispatchEligibilityParams): Promise<{
  provider: string;
} | undefined>;
//#endregion
//#region src/plugins/runtime/runtime-agent-workspace.d.ts
type PluginWorkspaceParams = Omit<NonNullable<Parameters<typeof ensureAgentWorkspace>[0]>, "guard"> & {
  guard?: {
    assertHost?: () => void;
  };
  /** @deprecated Runs before dispatch. Use SQL-free guard.assertHost for live commit authority. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  beforePersistentApply?: () => void;
};
declare function ensurePluginAgentWorkspace(params?: PluginWorkspaceParams): Promise<{
  dir: string;
  agentsPath?: string;
  soulPath?: string;
  identityPath?: string;
  userPath?: string;
  bootstrapPath?: string;
  bootstrapPending?: boolean;
  identityPathCreated?: boolean;
}>;
//#endregion
//#region src/auto-reply/reply/session-event-handoff.d.ts
/** Producer-owned occurrence; passive notices continue to use enqueueSystemEvent. */
declare function enqueueSessionEventForHost(text: string, options: SessionEventOptions): SessionEventReceipt;
//#endregion
//#region src/plugins/runtime/runtime-session-events.d.ts
declare const capturedTarget: unique symbol;
type SessionEventTarget = {
  readonly [capturedTarget]: true;
};
/** Capture the original destination before asynchronous plugin work. */
declare function captureSessionEventTarget(agentId: string, sessionKey: string): Promise<SessionEventTarget>;
/** Admit a bounded internal follow-up through the destination's normal session queue. */
declare function enqueueSessionEvent(text: string, options: {
  agentId: string;
  sessionKey: string;
  contextKey?: string;
  deliveryContext?: DeliveryContext;
  abortSignal?: AbortSignal;
  expectedTarget?: SessionEventTarget;
  /** Explicit fresh ingress may initialize an absent session after authorization. */
  createIfMissing?: true;
}, enqueueForHost: typeof enqueueSessionEventForHost): SessionEventReceipt;
/** Keep synchronous receipt admission behind the host's existing native runtime loader. */
declare function createSessionEventEnqueuer(enqueueForHost: typeof enqueueSessionEventForHost): (text: string, options: Parameters<typeof enqueueSessionEvent>[1]) => SessionEventReceipt;
//#endregion
//#region src/plugins/runtime/system-events.d.ts
declare const enqueueSystemEventFromSdk: (text: string, { agentId, ...options }: Parameters<typeof enqueueSystemEvent>[1] & {
  agentId?: string;
}) => boolean;
declare const enqueueSystemEventEntryFromSdk: (text: string, options: Parameters<typeof enqueueSystemEventEntry>[1]) => ReturnType<typeof enqueueSystemEventEntry>;
declare function enqueueRoutedSystemEvent(text: string, route: {
  agentId: string;
  sessionKey: string;
}, options?: Omit<Parameters<typeof enqueueSystemEvent>[1], "sessionKey">): boolean;
declare const consumeSelectedSystemEventEntriesFromSdk: typeof consumeSelectedSystemEventEntries;
declare const drainSystemEventEntriesFromSdk: typeof drainSystemEventEntries;
declare const drainSystemEventsFromSdk: typeof drainSystemEvents;
declare const hasSystemEventsFromSdk: typeof hasSystemEvents;
declare const isSystemEventContextChangedFromSdk: typeof isSystemEventContextChanged;
declare function peekSystemEventEntriesFromSdk(key: string, agentId?: string): SystemEvent[];
declare const peekSystemEventsFromSdk: typeof peekSystemEvents;
//#endregion
//#region src/plugins/runtime/native-deps.d.ts
type NativeDependencyHintParams = {
  packageName: string;
  manager?: "pnpm" | "npm" | "yarn";
  rebuildCommand?: string;
  approveBuildsCommand?: string;
  downloadCommand?: string;
};
declare function formatNativeDependencyHint(params: NativeDependencyHintParams): string;
//#endregion
//#region src/tts/tts.d.ts
declare function textToSpeech(params: Parameters<typeof textToSpeechCore>[0]): Promise<TtsResult>;
//#endregion
//#region src/video-generation/runtime-types.d.ts
type GenerateVideoParams = Omit<VideoGenerationRequest, "provider" | "model"> & {
  modelOverride?: string;
  autoProviderFallback?: boolean;
};
type GenerateVideoRuntimeResult = Omit<VideoGenerationResult, "model"> & {
  provider: string;
  model: string;
  attempts: FallbackAttempt[];
  normalization?: VideoGenerationNormalization;
  ignoredOverrides: VideoGenerationIgnoredOverride[];
};
//#endregion
//#region src/music-generation/runtime-types.d.ts
type GenerateMusicParams = Omit<MusicGenerationRequest, "provider" | "model"> & {
  modelOverride?: string;
  autoProviderFallback?: boolean;
};
type GenerateMusicRuntimeResult = Omit<MusicGenerationResult, "model"> & {
  provider: string;
  model: string;
  attempts: FallbackAttempt[];
  normalization?: MusicGenerationNormalization;
  ignoredOverrides: MusicGenerationIgnoredOverride[];
};
//#endregion
//#region src/web-search/runtime-types.d.ts
type ResolveWebSearchDefinitionParams = {
  config?: OpenClawConfig;
  agentDir?: string;
  authStore?: AuthProfileStore$1;
  sandboxed?: boolean;
  runtimeWebSearch?: RuntimeWebSearchMetadata;
  providerId?: string;
  preferRuntimeProviders?: boolean;
  preferInputConfig?: boolean;
};
type RunWebSearchParams = ResolveWebSearchDefinitionParams & {
  args: Record<string, unknown>;
  signal?: AbortSignal;
  /** Caller-owned synchronous authority check, repeated immediately before external requests. */
  assertCurrent?: () => void;
};
type RunWebSearchResult = {
  provider: string;
  result: Record<string, unknown>;
};
//#endregion
//#region src/media-understanding/runtime-types.d.ts
type RunMediaUnderstandingFileParams = {
  capability: "image" | "audio" | "video";
  filePath: string;
  mediaUrl?: string;
  cfg: OpenClawConfig;
  agentId?: string;
  agentDir?: string;
  workspaceDir?: string;
  mime?: string;
  activeModel?: ActiveMediaModel;
  prompt?: string;
  timeoutMs?: number;
  scopeContext?: {
    sessionKey?: string;
    channel?: string;
    chatType?: string;
  };
};
type RunMediaUnderstandingFileResult = {
  text: string | undefined;
  provider?: string;
  model?: string;
  output?: MediaUnderstandingOutput;
  decision?: MediaUnderstandingDecision;
};
type DescribeImageFileParams = Omit<RunMediaUnderstandingFileParams, "capability">;
type DescribeImageFileWithModelParams = Omit<RunMediaUnderstandingFileParams, "capability" | "activeModel" | "scopeContext" | "prompt"> & {
  provider: string;
  model: string;
  prompt: string;
  maxTokens?: number;
};
type PreparedImageDescriptionInput = ImagesDescriptionInput;
type PrepareImageDescriptionInputParams = Pick<DescribeImageFileWithModelParams, "filePath" | "mediaUrl" | "mime" | "cfg" | "timeoutMs">;
type DescribePreparedImageWithModelParams = Omit<DescribeImageFileWithModelParams, "filePath" | "mediaUrl" | "mime"> & {
  image: PreparedImageDescriptionInput;
};
type DescribeImageFileWithModelResult = Awaited<ReturnType<NonNullable<MediaUnderstandingProvider["describeImage"]>>>;
type ExtractStructuredWithModelParams = Omit<StructuredExtractionRequest, "input" | "agentDir" | "signal" | "timeoutMs"> & {
  /** At least one image input is required; text inputs provide supplemental context. */
  input: StructuredExtractionRequest["input"];
  agentDir?: string;
  timeoutMs?: number;
};
type DescribeVideoFileParams = Omit<DescribeImageFileParams, "mediaUrl" | "prompt" | "timeoutMs" | "scopeContext">;
type TranscribeAudioFileParams = DescribeVideoFileParams & {
  language?: string;
  prompt?: string;
};
type MediaUnderstandingRuntime = {
  resolveAudioInputBudget: (params: {
    cfg: OpenClawConfig;
  }) => Promise<{
    enabled: false;
  } | {
    enabled: true;
    maxBytes: number;
  }>;
  runMediaUnderstandingFile: (params: RunMediaUnderstandingFileParams) => Promise<RunMediaUnderstandingFileResult>;
  describeImageFile: (params: DescribeImageFileParams) => Promise<RunMediaUnderstandingFileResult>;
  prepareImageDescriptionInput: (params: PrepareImageDescriptionInputParams) => Promise<PreparedImageDescriptionInput>;
  describePreparedImageWithModel: (params: DescribePreparedImageWithModelParams) => Promise<DescribeImageFileWithModelResult>;
  describeImageFileWithModel: (params: DescribeImageFileWithModelParams) => Promise<DescribeImageFileWithModelResult>;
  extractStructuredWithModel: (params: ExtractStructuredWithModelParams) => Promise<Awaited<ReturnType<NonNullable<MediaUnderstandingProvider["extractStructured"]>>>>;
  describeVideoFile: (params: DescribeVideoFileParams) => Promise<RunMediaUnderstandingFileResult>;
  transcribeAudioFile: (params: TranscribeAudioFileParams) => Promise<RunMediaUnderstandingFileResult>;
};
//#endregion
//#region src/plugins/runtime/types-core.d.ts
type TtsRuntimeApi = typeof runtime_api_d_exports;
type RuntimeWriteConfigOptions = {
  /** Revalidate caller authority at guarded publication; accepted writes still settle. */
  assertCurrent?: () => void;
  envSnapshotForRestore?: Record<string, string | undefined>;
  expectedConfigPath?: string;
  unsetPaths?: string[][];
};
type DeepReadonly<T> = T extends ((...args: never[]) => unknown) ? T : T extends readonly (infer U)[] ? ReadonlyArray<DeepReadonly<U>> : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]>; } : T;
type RuntimeConfigAfterWrite = ConfigWriteAfterWrite;
type RuntimeConfigReplaceResult = ConfigReplaceResult;
type RuntimeProviderListParams = {
  config?: OpenClawConfig;
};
type RuntimeSessionEntry = SessionEntry;
type RuntimeSessionPluginExtensions = Record<string, Record<string, PluginJsonValue>> | undefined;
type RuntimeSessionStoreReadParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  hydrateSkillPromptRefs?: boolean;
  sessionKey: string;
  readConsistency?: "latest";
  storePath?: string;
};
type RuntimeSessionStoreEntrySummary = {
  sessionKey: string;
  entry: RuntimeSessionEntry;
};
type RuntimeCreateSessionEntryResult = {
  key: string;
  agentId: string;
  sessionId: string;
  entry: RuntimeSessionEntry;
};
type RuntimeCreateSessionEntryContext = RuntimeCreateSessionEntryResult & {
  /** Host creation authority; runtimes that cannot supply it must leave it absent. */
  initialization?: SessionInitialization;
};
type RuntimeCreateSessionEntryFinalPatch = {
  pluginExtensions: RuntimeSessionPluginExtensions;
};
/** @public Part of the PluginRuntime declaration contract. */
type PluginRuntimeThinkingPolicyRequest = {
  provider?: string | null;
  model?: string | null;
  catalog?: ThinkingCatalogEntry[];
  agentRuntime?: string | null;
};
/** @public Part of the PluginRuntime declaration contract. */
type PluginRuntimeThinkingPolicyLevel = {
  id: ThinkLevel;
  label: string;
};
/** @public Part of the PluginRuntime declaration contract. */
type PluginRuntimeThinkingPolicy = {
  levels: PluginRuntimeThinkingPolicyLevel[];
  defaultLevel?: ThinkLevel | null;
};
/** Structured logger surface injected into runtime-backed plugin helpers. */
type RuntimeLogger = {
  debug?: (message: string, meta?: Record<string, unknown>) => void;
  info: (message: string, meta?: Record<string, unknown>) => void;
  warn: (message: string, meta?: Record<string, unknown>) => void;
  error: (message: string, meta?: Record<string, unknown>) => void;
};
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 LlmCompleteCommonParams = {
  /** Model ref (e.g. "anthropic/claude-sonnet-4-6"); defaults to the target agent's configured model. */
  model?: string;
  /** Advisory output limit; runtime owners without an equivalent control may ignore it. */
  maxTokens?: number;
  /** Advisory sampling hint; runtime owners without an equivalent control may ignore it. */
  temperature?: number;
  /** Requested reasoning effort; the host normalizes it for the selected model. */
  reasoning?: ThinkLevel;
  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 LlmIsolatedAgentRuntimeCompleteParams = LlmCompleteCommonParams & {
  /** Isolated runtimes currently accept one fresh user prompt, not a replayed chat history. */
  messages: [{
    role: "user";
    content: string;
  }];
  /** Advisory final-output schema; isolated runtimes without native support may ignore it. */
  outputSchema?: JsonSchemaObject;
  execution: {
    /**
     * Fresh completion through the configured agent runtime with no supplied tools.
     * Agents API may retain service-owned helpers; it cannot guarantee zero tools.
     */
    mode: "isolated-agent-runtime";
    /** Exact credential owner. Requires host-granted plugin policy. */
    authProfileId?: string;
    timeoutMs?: number;
  };
};
type LlmCompleteParams = (LlmCompleteCommonParams & {
  messages: {
    role: "system" | "user" | "assistant";
    content: string;
  }[];
  /** Provider-native constrained-output request. Unsupported transports may ignore it. */
  responseFormat?: Record<string, unknown>;
  /** Fail before dispatch unless the exact selected credential has this host-resolved mode. */
  requiredAuthMode?: "oauth";
  execution?: undefined;
}) | LlmIsolatedAgentRuntimeCompleteParams;
type LlmCompleteResult = {
  text: string;
  provider: string;
  model: string;
  /** Concrete model identity returned by the provider, when available. */
  responseModel?: string;
  /** Provider terminal reason for direct completions, when available. */
  stopReason?: StopReason;
  agentId: string;
  usage: LlmCompleteUsage;
  execution: {
    mode: "direct-provider";
    owner: {
      kind: "provider";
      id: string;
    };
  } | {
    mode: "isolated-agent-runtime";
    owner: {
      kind: "cli" | "harness";
      id: string;
    };
  };
  audit: {
    caller: LlmCompleteCaller;
    purpose?: string;
    sessionKey?: string;
  };
};
/** Core runtime helpers exposed to trusted native plugins. */
type PluginRuntimeCore = {
  version: string;
  /** Optional host behavior guarantees; absent capabilities remain unsupported on older hosts. */
  readonly capabilities?: readonly string[];
  decisions: DecisionRuntimeV2;
  config: {
    /** Current process runtime config snapshot. Prefer config passed into the active call path. */
    current: {
      /** Independent mutable copy retaining the published config's resolution facts. */
      (options: {
        clone: true;
      }): OpenClawConfig;
      /** Keep the default last so ReturnType consumers retain the readonly snapshot. */
      (): DeepReadonly<OpenClawConfig>;
    };
    /**
     * Persist a focused config mutation. Callers must choose the post-write
     * behavior explicitly so the gateway can hot-reload, restart, or defer.
     */
    mutateConfigFile: <T = void>(params: {
      base?: ConfigMutationBase;
      baseHash?: string;
      afterWrite: RuntimeConfigAfterWrite;
      writeOptions?: RuntimeWriteConfigOptions;
      mutate: (draft: OpenClawConfig, context: {
        snapshot: ConfigFileSnapshot;
        previousHash: string | null;
      }) => Promise<T | void> | T | void;
    }) => Promise<RuntimeConfigReplaceResult & {
      result: T | undefined;
    }>;
    /**
     * Persist a full config replacement. Callers must choose the post-write
     * behavior explicitly so the gateway can hot-reload, restart, or defer.
     */
    replaceConfigFile: (params: {
      nextConfig: OpenClawConfig;
      baseHash?: string;
      afterWrite: RuntimeConfigAfterWrite;
      writeOptions?: RuntimeWriteConfigOptions;
    }) => Promise<RuntimeConfigReplaceResult>;
  };
  agent: {
    defaults: {
      model: typeof DEFAULT_MODEL;
      provider: typeof DEFAULT_PROVIDER;
    };
    resolveAgentDir: typeof resolveAgentDir;
    resolveAgentWorkspaceDir: typeof resolveAgentWorkspaceDir;
    resolveAgentIdentity: typeof resolveAgentIdentity;
    /** Resolve an allowed catalog create target through canonical agent model/runtime policy. */
    resolveSessionCatalogCreateTarget: typeof resolveAgentCatalogCreateTarget;
    resolveThinkingDefault: (params: {
      cfg: OpenClawConfig;
      provider: string;
      model: string;
      catalog?: ModelCatalogEntry[];
    }) => ThinkLevel;
    normalizeThinkingLevel: (raw?: string | null) => ThinkLevel | undefined;
    resolveThinkingPolicy: (params: PluginRuntimeThinkingPolicyRequest) => PluginRuntimeThinkingPolicy;
    /** Admit a turn for this exact trusted channel plugin and its authenticated sender. */
    runCommandFromIngress: (opts: AgentCommandIngressOpts, runtime: RuntimeEnv) => ReturnType<typeof agentCommandFromIngress>;
    runEmbeddedAgent: (params: Omit<RunEmbeddedAgentParams, "admittedRunContext" | "preparedRunAdmission"> & {
      /** @deprecated Ignored; the host derives availability. Retained until the next Plugin SDK major. */
      githubPublicationAvailable?: boolean;
    }) => Promise<EmbeddedAgentRunResult>;
    resolveAgentTimeoutMs: typeof resolveAgentTimeoutMs;
    /**
     * Shares the embedded runner's CLI-backend dispatch eligibility (route,
     * registered backend, stored credential mode) so opted-in callers can
     * budget timeouts for the run that will actually execute.
     */
    /** @deprecated Use resolveCliBackendDispatchEligibilityAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
    resolveCliBackendDispatchEligibility: typeof resolveEmbeddedCliBackendDispatchEligibility;
    resolveCliBackendDispatchEligibilityAsync: typeof resolveEmbeddedCliBackendDispatchEligibilityAsync;
    ensureAgentWorkspace: typeof ensurePluginAgentWorkspace;
    session: {
      resolveStorePath: typeof resolveSessionStorePathCore;
      createSessionEntry: (params: {
        cfg: OpenClawConfig;
        key: string;
        agentId?: string;
        label?: string;
        /** Create-only title snapshot: trimmed, capped at 500 UTF-16 units without splitting pairs; not a unique label. */
        displayName?: string;
        spawnedCwd?: string;
        sessionRoot?: string;
        permissionMode?: RuntimeSessionEntry["permissionMode"];
        /** Bind the created session's CLI execution to this paired node. */
        execNode?: string;
        /** Working directory interpreted only by execNode. */
        execCwd?: string;
        initialEntry: {
          agentHarnessId: string;
          color?: string;
          modelSelectionLocked?: true;
          pluginExtensions?: RuntimeSessionPluginExtensions;
        } | {
          cliBackendId: string;
          color?: string;
          model: string;
          cliSessionBinding: CliSessionBinding;
          modelSelectionLocked: true;
          pluginExtensions?: RuntimeSessionPluginExtensions;
          /** Registry-injected owner; plugin callers cannot select another owner. */
          pluginOwnerId?: string;
        } | {
          acpBackendId: string;
          color?: string;
          acpSessionBinding: {
            acpAgentId: string;
            agentSessionId: string;
          };
          modelSelectionLocked?: true;
          pluginExtensions?: RuntimeSessionPluginExtensions;
          /** Registry-injected owner; plugin callers cannot select another owner. */
          pluginOwnerId?: string;
        };
      } & ({
        /** Retry an interrupted initializer only when persisted trusted state matches exactly. */
        recoverMatchingInitialEntry: true;
        afterCreate: (created: RuntimeCreateSessionEntryContext) => Promise<RuntimeCreateSessionEntryFinalPatch>;
      } | {
        recoverMatchingInitialEntry?: never;
        afterCreate?: (created: RuntimeCreateSessionEntryContext) => Promise<RuntimeCreateSessionEntryFinalPatch | void>;
      })) => Promise<RuntimeCreateSessionEntryResult>;
      /** @deprecated Use getSessionEntryAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
      getSessionEntry: (params: RuntimeSessionStoreReadParams) => RuntimeSessionEntry | undefined;
      /** Worker-backed descriptive read; keep live effect authority with the owning operation. */
      getSessionEntryAsync: (params: RuntimeSessionStoreReadParams) => Promise<RuntimeSessionEntry | undefined>;
      /** Complete public entry for a visible current ID in the selected physical store. */
      getSessionEntryByIdAsync: (params: Omit<RuntimeSessionStoreReadParams, "sessionKey"> & {
        sessionId: string;
        /** Newest normalized-ID match; omitted preserves exact-ID-first listing order. */
        orderBy?: "updatedAt";
      }) => Promise<RuntimeSessionStoreEntrySummary | undefined>;
      /** @deprecated Use listSessionEntriesAsync for metadata reads. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
      listSessionEntries: (params?: Partial<Omit<RuntimeSessionStoreReadParams, "sessionKey">> & {
        readOnly?: boolean;
        /** Restrict results to exact persisted keys while retaining canonical listing validation. */
        sessionKeys?: readonly string[];
        /** Set false to skip derived participant identities and counts when reading metadata. */
        includeParticipants?: boolean;
        /** Capture the admitted store's physical identity; access policy remains caller-owned. */
        captureSource?: (assertCurrent: () => void) => void;
      }) => RuntimeSessionStoreEntrySummary[];
      /** Read-only metadata listing; saved prompts and other detached snapshots are omitted. */
      listSessionEntriesAsync: typeof listSessionEntriesAsync;
      /** Exact selected entries retained through a synchronous disclosure callback. */
      withSessionEntriesAsync: typeof withSessionEntriesAsync;
      createSessionEntryListReader: (params: {
        agentId: string;
        storePath: string;
        env?: NodeJS.ProcessEnv;
      }) => Promise<() => Promise<{
        entries: RuntimeSessionStoreEntrySummary[];
        assertCurrent: () => void;
      }>>;
      /** @deprecated Use prepareSessionEntryPatch; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
      patchSessionEntry: (params: RuntimeSessionStoreReadParams & {
        /** Synchronous final ownership check executed inside the commit transaction. */
        assertCommitAllowed?: () => void;
        fallbackEntry?: RuntimeSessionEntry;
        maintenanceConfig?: ResolvedSessionMaintenanceConfigInput;
        preserveActivity?: boolean;
        replaceEntry?: boolean;
        update: (entry: RuntimeSessionEntry, context: {
          existingEntry?: RuntimeSessionEntry;
        }) => Promise<Partial<RuntimeSessionEntry> | null> | Partial<RuntimeSessionEntry> | null;
      }) => Promise<RuntimeSessionEntry | null>;
      prepareSessionEntryPatch: typeof prepareSessionEntryPatch;
      upsertSessionEntry: (params: RuntimeSessionStoreReadParams & {
        entry: RuntimeSessionEntry;
      }) => Promise<void>;
      runWithWorkAdmission: <T>(params: {
        storePath: string;
        sessionKey: string;
        signal?: AbortSignal;
      }, run: (signal: AbortSignal) => Promise<T>) => Promise<T>;
      /** @deprecated Use prepareSessionEntryPatch; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
      updateSessionStoreEntry: (params: {
        storePath: string;
        sessionKey: string;
        update: (entry: RuntimeSessionEntry) => Promise<Partial<RuntimeSessionEntry> | null> | Partial<RuntimeSessionEntry> | null;
        skipMaintenance?: boolean;
        takeCacheOwnership?: boolean;
        requireWriteSuccess?: boolean;
      }) => Promise<RuntimeSessionEntry | null>;
    };
  };
  hooks: {
    /** Dispatch untrusted external content through an isolated, contained hook agent turn. */
    dispatchHookAgentTurn: (params: {
      name: string;
      agentId: string;
      sessionKey: string;
      message: string;
      externalContentSource: "email";
      deliver: boolean;
      model?: string;
      thinking?: ThinkLevel;
      timeoutSeconds?: number;
      idempotencyKey?: string;
    }) => Promise<{
      ok: true;
      runId: string;
    } | {
      ok: false;
      reason: string;
    }>;
  };
  system: {
    captureSessionEventTarget: typeof captureSessionEventTarget;
    enqueueSessionEvent: ReturnType<typeof createSessionEventEnqueuer>;
    enqueueSystemEvent: typeof enqueueSystemEventFromSdk;
    runCommandWithTimeout: typeof runCommandWithTimeout;
    formatNativeDependencyHint: typeof formatNativeDependencyHint;
  };
  media: {
    loadWebMedia: typeof loadWebMedia;
    detectMime: typeof detectMime;
    mediaKindFromMime: typeof mediaKindFromMime;
    isVoiceCompatibleAudio: typeof isVoiceMessageCompatibleAudio;
    getImageMetadata: typeof getImageMetadata;
    resizeToJpeg: typeof resizeToJpeg;
  };
  tts: {
    /** Await machine preference preparation before rendering; optional for older custom runtimes. */
    buildSystemPromptHintAsync?: TtsRuntimeApi["buildTtsSystemPromptHintAsync"];
    prepareTtsRequest: typeof prepareTtsRequest;
    textToSpeech: typeof textToSpeech;
    textToSpeechStream: TtsRuntimeApi["textToSpeechStream"];
    textToSpeechTelephony: TtsRuntimeApi["textToSpeechTelephony"];
    listVoices: TtsRuntimeApi["listSpeechVoices"];
  };
  mediaUnderstanding: {
    resolveAudioInputBudget: MediaUnderstandingRuntime["resolveAudioInputBudget"];
    runFile: MediaUnderstandingRuntime["runMediaUnderstandingFile"];
    describeImageFile: MediaUnderstandingRuntime["describeImageFile"];
    describeImageFileWithModel: MediaUnderstandingRuntime["describeImageFileWithModel"];
    extractStructuredWithModel: MediaUnderstandingRuntime["extractStructuredWithModel"];
    describeVideoFile: MediaUnderstandingRuntime["describeVideoFile"];
    transcribeAudioFile: MediaUnderstandingRuntime["transcribeAudioFile"];
  };
  imageGeneration: {
    generate: (params: GenerateImageParams) => Promise<GenerateImageRuntimeResult>;
    listProviders: (params?: RuntimeProviderListParams) => ImageGenerationProvider[];
  };
  videoGeneration: {
    generate: (params: GenerateVideoParams) => Promise<GenerateVideoRuntimeResult>;
    listProviders: (params?: RuntimeProviderListParams) => VideoGenerationProvider[];
  };
  musicGeneration: {
    generate: (params: GenerateMusicParams) => Promise<GenerateMusicRuntimeResult>;
    listProviders: (params?: RuntimeProviderListParams) => MusicGenerationProvider[];
  };
  webSearch: {
    /** @deprecated Await listProvidersAsync so discovery policy is prepared off-thread. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
    listProviders: (params?: RuntimeProviderListParams) => PluginWebSearchProviderEntry[];
    listProvidersAsync: (params?: RuntimeProviderListParams) => Promise<PluginWebSearchProviderEntry[]>;
    search: (params: RunWebSearchParams) => Promise<RunWebSearchResult>;
  };
  events: {
    onAgentEvent: typeof onAgentEvent;
    onSessionTranscriptUpdate: typeof onSessionTranscriptUpdate;
  };
  logging: {
    shouldLogVerbose: typeof shouldLogVerbose;
    getChildLogger: (bindings?: Record<string, unknown>, opts?: {
      level?: LogLevel;
    }) => RuntimeLogger;
  };
  state: {
    resolveStateDir: typeof resolveStateDir;
    openBlobStore: <TMetadata>(options: OpenBlobStoreOptions) => PluginBlobStoreWithReceipts<TMetadata>;
    openKeyedStore: <T>(options: OpenAsyncKeyedStoreOptions) => PluginStateKeyedStore<T>;
    /** Data-only worker store; operations retain this runtime and optional action authority. */
    openKeyedStoreV2: <T>(options: OpenAsyncKeyedStoreOptions, authority?: PluginStateActionAuthority) => PluginStateKeyedStore<T, 2>;
    /**
     * @deprecated Use openKeyedStoreV2 and await its operations. This synchronous
     * compatibility adapter is supported through 2026-12-31, then removed in the first January 2027 stable release.
     */
    openSyncKeyedStore: <T>(options: OpenKeyedStoreOptions) => PluginStateSyncKeyedStore<T>;
    openChannelIngressQueue: <TPayload, TMetadata = unknown, TCompletedMetadata = unknown>(options?: Omit<CreateChannelIngressQueueOptions, "channelId">) => ChannelIngressQueue<TPayload, TMetadata, TCompletedMetadata>;
    openChannelIngressDrain: <TPayload, TMetadata = unknown, TCompletedMetadata = unknown>(options: Omit<CreateChannelIngressDrainOptions<TPayload, TMetadata, TCompletedMetadata>, "queue"> & {
      queue?: ChannelIngressQueue<TPayload, TMetadata, TCompletedMetadata>;
      accountId?: string;
      stateDir?: string;
    }) => ChannelIngressDrain;
  };
  llm: {
    complete: (params: LlmCompleteParams) => Promise<LlmCompleteResult>;
    acquireLocalService: (target: {
      providerId: string;
      baseUrl: string;
      headers?: HeadersInit;
      reconcile?: ProviderPlugin["reconcileLocalService"];
    }, signal?: AbortSignal | null) => Promise<{
      release: () => void;
    } | undefined>;
  };
  modelConfig: {
    /** Read-only model selection; no session mutation or harness execution authority. */
    resolveDefaultModelForAgent: typeof resolveDefaultModelForAgent;
    resolveAllowedModelRef: typeof resolveAllowedModelRefCore;
    /** Read authored model/provider runtime policy without projecting runtime availability. */
    resolveModelRuntimePolicy: typeof resolveModelRuntimePolicy;
  };
  modelAuth: {
    /** Existing synchronous SDK operations, composed by the native host. */
    resolveProviderIdForAuth: typeof resolveProviderIdForAuth;
    /** @deprecated Use ensureAuthProfileStoreAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
    ensureAuthProfileStore: typeof ensureAuthProfileStore;
    ensureAuthProfileStoreAsync: typeof ensureAuthProfileStoreAsync;
    resolveAuthProfileOrder: typeof resolveAuthProfileOrder;
    listProfilesForProvider: typeof listProfilesForProvider;
    /** @deprecated Use isProviderApiKeyConfiguredAsync. Final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
    isProviderApiKeyConfigured: typeof isProviderApiKeyConfigured;
    isProviderApiKeyConfiguredAsync: typeof isProviderApiKeyConfiguredAsync;
    /** Resolve auth for a model. Only provider/model, optional cfg, and workspaceDir are used. */
    getApiKeyForModel: (params: {
      model: Model<Api>;
      cfg?: OpenClawConfig;
      workspaceDir?: string;
    }) => Promise<ResolvedProviderAuth>;
    /** Resolve request-ready auth for a model, including provider runtime exchanges. */
    getRuntimeAuthForModel: (params: {
      model: Model<Api>;
      cfg?: OpenClawConfig;
      workspaceDir?: string;
    }) => Promise<ResolvedProviderRuntimeAuth>;
    /** Resolve auth for a provider by name. Only provider, optional cfg, and workspaceDir are used. */
    resolveApiKeyForProvider: (params: {
      provider: string;
      cfg?: OpenClawConfig;
      workspaceDir?: string;
    }) => Promise<ResolvedProviderAuth>;
  };
};
//#endregion
//#region src/context-engine/types.d.ts
type AssembleResult = {
  /** Ordered messages to use as model context */
  messages: AgentMessage[];
  /** Engine estimate of assembled tokens; does not control host request admission. */
  estimatedTokens: number;
  /**
   * Controls the history included in host token-pressure diagnostics.
   * The returned `messages` remain the model context.
   *
   * - "assembled": diagnostics use the host's assembled prompt estimate.
   * - "preassembly_may_overflow": diagnostics take the maximum of the host's
   *   assembled and pre-assembly (unwindowed) history estimates. This maximum
   *   does not block a fitting outgoing request.
   *
   * Defaults to "assembled". Neither value disables host request admission
   * checks for engines that own compaction.
   */
  promptAuthority?: "assembled" | "preassembly_may_overflow";
  /** Optional context-engine-provided instructions prepended to the runtime system prompt */
  systemPromptAddition?: string;
  /**
   * Optional projection lifecycle for hosts with persistent backend threads.
   *
   * Context engines that return `thread_bootstrap` ask the host to inject the
   * assembled context once for the supplied epoch, then reuse the backend
   * thread until the epoch changes. Engines that omit this field retain the
   * legacy per-turn projection behavior.
   */
  contextProjection?: ContextEngineProjection;
};
type ContextEngineProjection = {
  /** How the assembled context should be projected into the backend runtime. */
  mode: "per_turn" | "thread_bootstrap";
  /** Stable context epoch. Changing this tells persistent backends to rotate. */
  epoch?: string;
  /** Optional diagnostic fingerprint for the projected context payload. */
  fingerprint?: string;
};
type ContextEngineOperation = "agent-run" | "manual-compact" | "subagent-spawn";
type ContextEngineRuntimeMode = "normal" | "fallback" | "degraded";
type ContextEngineSelectionSource = "configured" | "default" | "unknown";
type ContextEngineRuntimeReasonCode = "provider_timeout" | "provider_unavailable" | "rate_limited" | "context_overflow" | "runtime_unavailable" | "unknown";
type ContextEngineHostCapability = "bootstrap" | "assemble-before-prompt" | "after-turn" | "maintain" | "compact" | "runtime-llm-complete" | "thread-bootstrap-projection";
type ContextEngineHostRequirements = {
  /** Host capabilities required before the engine can safely serve this operation. */
  requiredCapabilities: ContextEngineHostCapability[];
  /** Optional engine-authored guidance appended to the host compatibility error. */
  unsupportedMessage?: string;
};
type ContextEngineRuntimeSettings = {
  schemaVersion: 1;
  runtime: {
    host: "openclaw";
    mode: ContextEngineRuntimeMode;
    harnessId: string | null;
    runtimeId: string | null;
  };
  model: {
    requested: string | null;
    resolved: string | null;
    provider: string | null;
    family: string | null;
  };
  contextEngineSelection: {
    selectedId: string | null;
    source: ContextEngineSelectionSource;
  };
  executionHost: {
    id: string | null;
    label: string | null;
  };
  limits: {
    promptTokenBudget: number | null;
    maxOutputTokens: number | null;
  };
  diagnostics: {
    fallbackReason: ContextEngineRuntimeReasonCode | null;
    degradedReason: ContextEngineRuntimeReasonCode | null;
  };
};
type CompactResult = {
  ok: boolean;
  compacted: boolean;
  reason?: string;
  result?: {
    summary?: string;
    firstKeptEntryId?: string;
    tokensBefore: number;
    tokensAfter?: number;
    details?: unknown;
    /** Session id after compaction, when the runtime rotated transcripts. */
    sessionId?: string;
    /** Typed post-compaction live session target; successor when the runtime rotated transcripts. */
    sessionTarget?: ContextEngineSessionTarget;
    /**
     * Raw session file path after compaction.
     *
     * @deprecated Use `sessionTarget`. Shipped plugin-sdk contract: released
     * third-party context engines (v2026.6.x and earlier) report rotated
     * transcripts through this field. Remove once typed session targets are
     * the only successor contract.
     */
    sessionFile?: string;
  };
};
type IngestResult = {
  /** Whether the message was ingested (false if duplicate or no-op) */
  ingested: boolean;
};
type IngestBatchResult = {
  /** Number of messages ingested from the supplied batch */
  ingestedCount: number;
};
type BootstrapResult = {
  /** Whether bootstrap ran and initialized the engine's store */
  bootstrapped: boolean;
  /** Number of historical messages imported (if applicable) */
  importedMessages?: number;
  /** Optional reason when bootstrap was skipped */
  reason?: string;
};
type ContextEngineInfo = {
  id: string;
  name: string;
  version?: string;
  acceptedHostParams?: string[];
  transcriptSemantics?: {
    currentTurnFence?: "before-current-turn-entry-v1";
    turnAdvancementIdempotency?: "atomic-idempotent-v1";
  };
  /**
   * True when the engine manages compaction instead of built-in auto-compaction.
   * The embedded host checks every outgoing provider request, including the first,
   * using matching measured current-run usage plus appended content when available,
   * or a fresh estimate of the actual system prompt, messages, and tools otherwise.
   * The engine's estimatedTokens never controls host request admission.
   */
  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<Record<ContextEngineOperation, ContextEngineHostRequirements>>;
};
type SubagentSpawnPreparation = {
  /** Roll back pre-spawn setup when subagent launch fails. */
  rollback: () => void | Promise<void>;
};
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 = Pick<NormalizedUsage, "input" | "output" | "cacheRead" | "cacheWrite" | "contextUsage" | "total">;
type ContextEnginePromptCacheObservationChangeCode = "historyRewrite" | "compaction" | "pruning" | "runtimeContextCarrier" | "aggregateToolResultTruncation" | "cacheRetention" | "model" | "streamStrategy" | "systemPrompt" | "systemPromptSuffix" | "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 ContextEngineTranscriptStorageInfo = {
  /**
   * Authoritative transcript backend for this runtime turn.
   *
   * Hosts may still pass legacy locator fields such as `sessionFile` for older
   * plugin contracts, but context engines should use this field to decide
   * whether that locator is a live transcript source.
   */
  kind: "sqlite";
};
type ContextEngineSessionTarget = {
  /** Agent that owns the session in the runtime store. */
  agentId?: string;
  /** Runtime session id to compact. */
  sessionId?: string;
  /** Stable session key used for aliases, policy, and store resolution. */
  sessionKey?: string;
  /** Session store path that scopes the SQLite-backed runtime session. */
  storePath?: string;
  /** Optional transport thread identity for session target resolution. */
  threadId?: string | number;
};
type ContextEngineRuntimeContext = Record<string, unknown> & {
  /** 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;
  /** Authoritative transcript backend for this turn. */
  transcriptStorage?: ContextEngineTranscriptStorageInfo;
  /** Storage-neutral runtime session target for compaction delegation. */
  sessionTarget?: ContextEngineSessionTarget;
  /**
   * 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<TranscriptRewriteResult>;
  /** LLM completion capability for engines that need model inference. */
  llm?: {
    complete: (params: LlmCompleteParams) => Promise<LlmCompleteResult>;
  };
};
/**
 * 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;
    /** Storage-neutral runtime session target for transcript/session SDK helpers. */
    sessionTarget?: ContextEngineSessionTarget;
    sessionFile: string;
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
  }): Promise<BootstrapResult>;
  /**
   * 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;
    /** Storage-neutral runtime session target for transcript/session SDK helpers. */
    sessionTarget?: ContextEngineSessionTarget;
    sessionFile: string;
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
    /**
     * Optional caller cancellation for maintenance work that may block.
     * Engines should reject promptly when this signal aborts.
     */
    abortSignal?: AbortSignal;
  }): Promise<ContextEngineMaintenanceResult>;
  /**
   * Ingest a single message into the engine's store.
   */
  ingest(params: {
    sessionId: string;
    sessionKey?: string;
    message: AgentMessage;
  }): Promise<IngestResult>;
  /**
   * Ingest a completed turn batch as a single unit.
   */
  ingestBatch?(params: {
    sessionId: string;
    sessionKey?: string;
    messages: AgentMessage[];
  }): Promise<IngestBatchResult>;
  /**
   * 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;
    /** Storage-neutral runtime session target for transcript/session SDK helpers. */
    sessionTarget?: ContextEngineSessionTarget;
    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;
    /** Optional model context token budget for proactive compaction. */
    tokenBudget?: number;
    /** Optional runtime-owned context for engines that need caller state. */
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
  }): Promise<void>;
  /**
   * Atomically and idempotently commit one accepted durable transcript turn.
   * Messages span the admitted user entry through the accepted terminal entry.
   * Hosts may retry the same advancement key after process or plugin failure.
   */
  commitTurn?(params: {
    advancementKey: string;
    admission: TranscriptTurnAdmission;
    terminal: TranscriptEntryAnchor;
    messages: AgentMessage[];
    sessionId: string;
    sessionKey?: string;
    sessionTarget?: ContextEngineSessionTarget;
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
  }): Promise<{
    status: "committed" | "duplicate";
  }>;
  /**
   * 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<string>;
    /** Active memory citation mode when engines want to mirror memory prompt guidance. */
    citationsMode?: MemoryCitationsMode;
    /** Current model identifier (e.g. "claude-opus-4", "gpt-4o", "qwen2.5-7b").
     *  Allows context engine plugins to adapt formatting per model. */
    model?: string;
    /** The incoming user prompt for this turn (useful for retrieval-oriented engines). */
    prompt?: string;
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
  }): Promise<AssembleResult>;
  /**
   * 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;
    /** Caller-resolved owner agent for global session aliases. */
    agentId?: string;
    /** Storage-neutral runtime session target for delegated compaction. */
    sessionTarget?: ContextEngineSessionTarget;
    tokenBudget?: number;
    /** Force compaction even below the default trigger threshold. */
    force?: boolean;
    /** Optional live token estimate from the caller's active context. */
    currentTokenCount?: number;
    /** Controls convergence target; defaults to budget. */
    compactionTarget?: "budget" | "threshold";
    customInstructions?: string;
    /** Optional runtime-owned context for engines that need caller state. */
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
    /**
     * Optional abort signal honored before and during compaction. The host
     * aborts it on run-level abort or when its compaction safety timeout
     * fires; engines should stop work and reject promptly when it aborts.
     */
    abortSignal?: AbortSignal;
    /**
     * Report meaningful compaction progress to refresh the host's idle window.
     * Requires "onProgress" in info.acceptedHostParams. The same ten-window
     * overall ceiling applies; reports after completion or abort have no effect.
     */
    onProgress?: () => void;
  }): Promise<CompactResult>;
  /**
   * 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<SubagentSpawnPreparation | undefined>;
  /**
   * Notify the context engine that a subagent lifecycle ended.
   */
  onSubagentEnded?(params: {
    childSessionKey: string;
    reason: SubagentEndReason;
  }): Promise<void>;
  /**
   * Dispose of any resources held by the engine.
   */
  dispose?(): Promise<void>;
}
//#endregion
//#region src/agents/harness/context-engine-turn-outbox.d.ts
type PendingContextEngineTurn = Readonly<{
  advancement_key: string;
  payload_json: string;
  session_id: string;
}>;
/** Persist only resolved model facts, never live capabilities or credential-bearing config. */
type ContextEngineTurnRuntimeContext = Readonly<{
  provider?: string;
  modelId?: string;
  modelContextWindow?: number;
  tokenBudget?: number;
  /** The turn's last-call usage and cache observation; plain counters only. */
  promptCache?: ContextEnginePromptCacheInfo;
}>;
type ContextEngineTurnOutboxFilter = Readonly<{
  engineId: string;
  ownerPluginId?: string;
}>;
type ContextEngineTurnOutboxWorkerOperations = {
  prepareRun: {
    input: ContextEngineTurnOutboxFilter & {
      admission?: TranscriptTurnAdmission;
      sessionId: string;
    };
    output: {
      warnings: string[];
      pending: boolean;
      admitted: boolean;
    };
  };
  listPendingSessions: {
    input: ContextEngineTurnOutboxFilter & {
      sessionId?: string;
      limit: number;
    };
    output: string[];
  };
  readNextPending: {
    input: ContextEngineTurnOutboxFilter & {
      sessionId: string;
    };
    output: PendingContextEngineTurn | undefined;
  };
  complete: {
    input: {
      advancementKey: string;
    };
    output: undefined;
  };
  recordFailure: {
    input: {
      advancementKey: string;
      message: string;
      attemptedAt: number;
    };
    output: undefined;
  };
  hasPending: {
    input: ContextEngineTurnOutboxFilter & {
      sessionId?: string;
    };
    output: boolean;
  };
  enqueueIntent: {
    input: ContextEngineTurnOutboxFilter & {
      admission: TranscriptTurnAdmission;
    };
    output: undefined;
  };
  acceptIntent: {
    input: ContextEngineTurnOutboxFilter & {
      boundary: TranscriptTurnBoundary;
      runtimeContext?: ContextEngineTurnRuntimeContext;
    };
    output: undefined;
  };
  publishClosedTurn: {
    input: ContextEngineTurnOutboxFilter & {
      boundary: TranscriptTurnBoundary;
      maxBytes: number;
      maxEvents: number;
      runtimeContext?: ContextEngineTurnRuntimeContext;
    };
    output: ClosedTranscriptTurnReadResult["kind"];
  };
  discardIntent: {
    input: ContextEngineTurnOutboxFilter & {
      admission: TranscriptTurnAdmission;
    };
    output: boolean;
  };
};
//#endregion
//#region src/infra/message-tool-run-outcome-store.kernel.d.ts
type MessageToolRunOutcomeInsert = Insertable<DB["message_tool_run_outcomes"]>;
//#endregion
//#region src/config/sessions/session-actor-memory-side-effects-contract.d.ts
type OutboxOperations = { [Key in keyof ContextEngineTurnOutboxWorkerOperations as `session.outbox.${Key}`]: ContextEngineTurnOutboxWorkerOperations[Key]; };
type SessionActorMemorySideEffectsReads = Pick<OutboxOperations, "session.outbox.listPendingSessions" | "session.outbox.readNextPending" | "session.outbox.hasPending"> & {
  "session.trajectory.read": {
    input: Omit<SqliteTrajectoryRuntimeReadScope, "agentId" | "env" | "storePath">;
    output: TrajectoryEvent[];
  };
  "session.trajectory.rows": {
    input: Omit<SqliteTrajectoryRuntimeReadScope, "agentId" | "env" | "storePath"> & {
      afterSeq?: number;
      maxEvents?: number;
      tailEvents?: number;
    };
    output: Array<{
      event: TrajectoryEvent;
      seq: number;
    }>;
  };
};
type SessionActorMemorySideEffectsWrites = Omit<OutboxOperations, keyof SessionActorMemorySideEffectsReads> & {
  "session.messageToolOutcome.record": {
    input: MessageToolRunOutcomeInsert;
    output: void;
  };
  "session.trajectory.append": {
    input: SqliteTrajectoryRuntimeAppend;
    output: void;
  };
};
//#endregion
//#region src/config/sessions/session-actor-memory-turn-contract.d.ts
type SessionActorMemoryTurnReads = {
  "session.turn.prepare": {
    input: SessionTurnPlan;
    output: ReturnType<typeof prepareSessionTurn>;
  };
};
//#endregion
//#region src/config/sessions/session-actor-memory-usage-contract.d.ts
/** Replaced as a unit; readers retain the immutable envelope and body together. */
type SessionActorMemoryUsageRollup = {
  valueJson: string;
  blob: Uint8Array;
  updatedAt: number;
};
type SessionActorMemoryUsageSnapshot = {
  sessionKey: string;
  sessionId: string;
  updatedAtMs: number;
  stats: SessionTranscriptStats;
  rollup?: Omit<SessionActorMemoryUsageRollup, "blob"> & {
    blob?: Uint8Array;
    bodyBytes?: number;
  };
  rollupDeferred?: boolean;
  deferredRollupMetadata?: {
    checkpoint: UsageCostFreshnessCheckpoint;
    scannedAt: number;
  };
  events?: Array<{
    seq: number;
    eventJson: string;
  }>;
};
type SessionActorMemoryUsageReads = {
  "session.memory.targets": {
    input: {
      selectors: MemorySessionSelectors;
    };
    output: MemorySessionTarget[];
  };
  "session.corpus.list": {
    input: {
      options: SessionTranscriptCorpusOptions;
    };
    output: SessionTranscriptCorpusEntry[];
  };
  "session.usage.snapshot": {
    input: {
      includeEvents?: boolean;
      includeRollupBodies?: boolean;
      reportBudget?: {
        remainingBytes: number;
        metadataLimit: number;
        pricingFingerprint: string;
      };
      sessionIds?: readonly string[];
    };
    output: SessionActorMemoryUsageSnapshot[];
  };
};
type SessionActorMemoryUsageWrites = {
  "session.usage.write": {
    input: {
      sessionId: string;
      rollup: SessionActorMemoryUsageRollup;
    };
    output: boolean;
  };
};
//#endregion
//#region src/config/sessions/session-actor-storage-contract.d.ts
type SessionActorStorageReads = SessionActorMemoryConversationReads & SessionActorMemoryCorpusReads & SessionActorMemoryTurnReads & SessionActorMemoryCollaborationReads & SessionActorMemorySideEffectsReads & SessionActorBoardReads & SessionActorProgressCardReads & SessionActorMemoryReportsReads & SessionActorMemoryUsageReads & SessionActorMemorySearchReads & SessionActorMemoryEntryReads & SessionActorMemoryForkReads & SessionActorMemoryHistoryReads & SessionActorMemoryMetadataReads & SessionActorMemoryPendingReads;
type SessionActorStorageWrites = SessionActorMemoryConversationWrites & SessionActorMemoryCollaborationWrites & SessionActorMemorySideEffectsWrites & SessionActorBoardWrites & SessionActorProgressCardWrites & SessionActorMemoryReportsWrites & SessionActorMemoryUsageWrites & SessionActorMemoryEntryWrites & SessionActorMemoryForkWrites & SessionActorMemoryMetadataWrites & SessionActorMemoryPendingWrites;
type SessionActorStorageChange = {
  sessionKey: string;
  before: SessionActorHotState | undefined;
  after: SessionActorHotState | undefined;
};
type SessionActorStorageOutcome<Value> = {
  kind: "committed";
  value: Value;
  changes: SessionActorStorageChange[];
  entryPatchEffects?: SessionLifecyclePatchEffects;
  failure?: {
    name: string;
    message: string;
  };
} | {
  kind: "rolled-back";
  error: {
    name: string;
    message: string;
    code?: SessionGoalOperationErrorCode | BoardValidationError["code"];
    sessionId?: string;
    operationLabel?: string;
    sessionKey?: string;
    refusal?: TranscriptAppendRefusal;
  };
};
type SessionActorStorageAuthority = SessionActorAuthority & {
  /** The host supplies CLI fork capabilities; memory entry patches travel with the command. */
  parentFork?: SessionActorMemoryParentForkCallbacks;
};
//#endregion
//#region src/config/sessions/session-pending-final-settlement.d.ts
type PendingFinalDelivery = NonNullable<InternalSessionEntry["pendingFinalDelivery"]>;
type PendingFinalDeliveryState$1 = NonNullable<PendingFinalDelivery["deliveries"]>[number]["state"];
type PendingFinalDeliverySettlementInput = {
  sessionId: string;
  intentId: string;
  deliveryId: string;
  state: PendingFinalDeliveryState$1;
  expectedStates?: readonly ("prepared" | "queued" | "unknown")[];
  /** Only the settled delivery owner may clear custody; pre-ACK receipts omit this. */
  cleanup?: {
    sessionKey: string;
    now: number;
    preserveActivity?: boolean;
  };
};
//#endregion
//#region src/config/sessions/session-actor-contract.d.ts
/** Serializable, pure bookkeeping. These reducers cannot change session identity or authority. */
type SessionActorReducer = SessionEntryBookkeepingReducer;
type SessionActorCommandContext = {
  commandId: string;
  phaseId: string;
  /** Omit to adopt the current preimage inside this command, without a preceding read. */
  expected?: SessionActorVersion;
  reducers?: readonly SessionActorReducer[];
};
/** Reuse SessionManager's prepared bytes, envelope, view limits, and admission predicates. */
type SessionActorAppend = ({
  kind: "metadata";
  input: SessionMetadataOperations["session.metadata.append"]["input"];
} | {
  kind: "message";
  input: SessionMetadataOperations["session.transcript.appendMessage"]["input"];
}) & {
  /** First-writer ownership is verified live; a run ID alone never grants it. */
  initialization?: SessionMetadataOperations["session.metadata.initialize"]["input"];
  /** Optional prepared session header, committed atomically before this append. */
  header?: SessionMetadataOperations["session.metadata.append"]["input"];
  /** Final prompt text joins its runtime-context carrier at the same durable point. */
  modelPromptProjection?: {
    anchor: TranscriptEntryAnchor;
    text: string;
  };
};
/** The original snapshot preserves canonical adopted IDs, parents, bytes, and versions. */
type SessionActorAppendCommitted = ({
  kind: "metadata";
  value: SessionMetadataOperations["session.metadata.append"]["output"];
} | {
  kind: "message";
  value: SessionMetadataOperations["session.transcript.appendMessage"]["output"];
}) & {
  initialEntry?: InitialSessionEntryCommit;
  header?: SessionMetadataOperations["session.metadata.append"]["output"];
  modelPromptProjection?: {
    result: NonNullable<SessionMessageRewriteCommitted["result"]> & {
      message: PersistedUserTurnMessage;
    };
    before: SessionTranscriptContextVersion;
    after: SessionTranscriptContextVersion;
    rows: SessionActorTranscriptRow[];
  };
};
type SessionActorPendingFinalDelivery = NonNullable<InternalSessionEntry["pendingFinalDelivery"]> & {
  intentId: string;
  deliveries: NonNullable<NonNullable<InternalSessionEntry["pendingFinalDelivery"]>["deliveries"]>;
};
type SessionActorPhaseInputs = {
  acceptInput: {
    expectedState: SessionTranscriptTurnExpectedState;
    lifecycle: SessionTranscriptTurnLifecyclePatch;
  } & ({
    pending: Extract<PendingInputMutation, {
      kind: "stage";
    }>;
    /** Admission and adoption may share a durable point only before an intervening effect. */
    turn?: SessionTurnPlan;
    /** A retry adopts canonical pending/transcript identity instead of appending twice. */
    append?: SessionActorAppend;
  } | {
    /** Transcript custody before ACK does not require a queued-input row. */
    pending?: never;
    turn: SessionTurnPlan;
    append?: never;
  });
  adoptRun: {
    sessionId: string;
    expectedState: SessionTranscriptTurnExpectedState;
    lifecycle: SessionTranscriptTurnLifecyclePatch;
    /** Explicit writer adoption; omission preserves the existing lifecycle-only command. */
    runId?: string;
    /** Consume accepted input and adopt its lifecycle at the same durable point. */
    turn?: SessionTurnPlan;
  };
  appendToolResult: {
    turn: SessionTurnPlan;
    append?: never;
  } | {
    append: SessionActorAppend;
    turn?: never;
  };
  appendTranscriptEvent: {
    sessionId: string;
    lifecycleRevision: string | null;
    writerRunId?: string;
    ownerSources?: SessionSourcePredicate[];
    eventJson: string;
    append?: never;
  } | {
    append: SessionActorAppend;
    eventJson?: never;
  };
  completeTurn: ({
    turn: SessionTurnPlan;
    bookkeeping?: never;
  } | {
    turn?: never;
    /** The assistant transcript is already durable; this command must not append it again. */
    bookkeeping: {
      sessionId: string;
      lifecycleRevision: string | null;
      writerRunId: string | undefined;
      expectedState: SessionTranscriptTurnExpectedState;
      lifecycle?: SessionTranscriptTurnLifecyclePatch;
    };
  }) & {
    completion?: Extract<PendingInputMutation, {
      kind: "complete";
    }>;
    /** Exact delivery intent and payload IDs join terminal accounting in this commit. */
    pendingFinalDelivery?: SessionActorPendingFinalDelivery;
    activitySummary?: SessionActivitySummary;
  };
  deliverySettled: {
    settlement: PendingFinalDeliverySettlementInput;
    evidence?: SessionActorDeliveryEvidence;
  };
  patch: {
    reducers: readonly SessionActorReducer[];
  };
};
type SessionActorPhase = keyof SessionActorPhaseInputs;
type SessionActorPhaseResults = {
  acceptInput: {
    inputId?: string;
    turn?: SessionTurnCommitted;
    append?: SessionActorAppendCommitted;
    adoption?: Pick<PendingInputSnapshot, "existing" | "previous" | "committed">;
    pendingInputReceipt?: PendingInputMutationReceipt;
  };
  adoptRun: SessionTurnCommitted | undefined;
  appendToolResult: SessionTurnCommitted | SessionActorAppendCommitted;
  appendTranscriptEvent: {
    anchor?: TranscriptEntryAnchor;
    projectionNeedsReconcile?: boolean;
  } | SessionActorAppendCommitted;
  completeTurn: SessionTurnCommitted | {
    kind: "bookkeeping";
  };
  deliverySettled: {
    state: PendingFinalDeliverySettlementInput["state"] | "stale";
  };
  patch: undefined;
};
type SessionActorReducerOutcome = {
  index: number;
  kind: SessionActorReducer["kind"];
  changed: boolean;
  /** Only pure best-effort usage preparation/reduction can be skipped. Writes remain atomic. */
  failure?: {
    name: string;
    message: string;
  };
};
type SessionActorReceipt = {
  kind: "session-actor-committed";
  commandId: string;
  phaseId: string;
  phase: SessionActorPhase;
  beforeVersion: SessionActorVersion;
  afterVersion: SessionActorVersion;
  transcript: {
    before: SessionTranscriptContextVersion;
    after: SessionTranscriptContextVersion;
    /** Includes idempotency adoption, not only newly inserted messages. */
    appendedMessages: SessionTurnCommitted["result"]["appendedMessages"];
    /** Complete append delta in this generation; absent when payloads are unavailable. */
    appendedEvents?: Array<{
      rawSeq: number;
      event: unknown;
      serializedBytes: number;
    }>;
    authorityReceipts?: readonly SessionTranscriptAuthorityReceipt[];
    append?: SessionActorAppendCommitted;
    projectionNeedsReconcile: boolean;
  };
  conversationPublication?: readonly ConversationPublication[];
  entryMetadata?: readonly SessionEntryMetadataReceipt[];
  pendingInputReceipt?: SessionPendingInputWorkerReceipt;
  pendingInputMutationReceipt?: PendingInputMutationReceipt;
  reducers: SessionActorReducerOutcome[];
  /** Complete postimage installed on MAIN; unchanged entries may share its frozen preimage. */
  postimage: SessionActorHotState;
};
type SessionActorOutcome<Value> = {
  kind: "committed";
  value: Value;
  receipt: SessionActorReceipt;
  /** Publication/cleanup failure cannot erase a captured durable receipt. */
  failure?: {
    name: string;
    message: string;
    /** Only the command response was lost; native settlement and publication succeeded. */
    origin?: "response";
  };
} | {
  kind: "rolled-back";
  error: {
    name: string;
    message: string;
  };
  reason?: "stale-state";
} | {
  /** No mutation ran. A caller may retry once using this authorized postimage. */
  kind: "stale-version";
  expected: SessionActorVersion;
  postimage: SessionActorHotState;
  error: {
    name: string;
    message: string;
  };
} | {
  kind: "unknown";
  target: SessionActorTarget;
  commandId: string;
  error: {
    name: string;
    message: string;
    cause?: unknown;
  };
};
type SessionActorCommitObserver<Value> = {
  /** Called once with read-only native evidence before fallible publication or cleanup. */
  committed(outcome: Extract<SessionActorOutcome<Value>, {
    kind: "committed";
  }>): void;
};
/** Private durable worker commands; the actor reconstructs outcomes from native receipts. */
type SessionActorOperations = { [Phase in SessionActorPhase as `session.actor.${Phase}`]: {
  input: SessionActorCommandContext & SessionActorPhaseInputs[Phase] & {
    target: SessionActorTarget;
    /** Command-local immutable preimage retained by the host; never grants authority. */
    entryReference?: string;
  };
  /** Native settlement owns committed data; the reply only acknowledges it. */
  output: Exclude<SessionActorOutcome<never>, {
    kind: "committed";
  }> | Pick<Extract<SessionActorOutcome<never>, {
    kind: "committed";
  }>, "kind" | "failure">;
}; } & {
  "session.actor.read": {
    input: {
      target: SessionActorTarget;
    };
    output: SessionActorHotState;
  };
};
type SessionActorCommands = { [Phase in SessionActorPhase]: (input: SessionActorCommandContext & SessionActorPhaseInputs[Phase], authority: SessionActorAuthority, observer?: SessionActorCommitObserver<SessionActorPhaseResults[Phase]>) => Promise<SessionActorOutcome<SessionActorPhaseResults[Phase]>>; };
type SessionActorStorageCommitObserver<Value> = {
  beforeCommit?(outcome: Extract<SessionActorStorageOutcome<Value>, {
    kind: "committed";
  }>): void | Promise<void>;
  /** Memory companions settle before this owner's FIFO admits later work. */
  settled?(outcome: SessionActorStorageOutcome<Value>): void | Promise<void>;
  committed?(outcome: Extract<SessionActorStorageOutcome<Value>, {
    kind: "committed";
  }>): void;
};
/** Bound at acquisition; shares the actor's accepted work, FIFO, and state owner. */
type SessionActorStorage = {
  /** Synchronous current facts for an actual effect; never reads an uninstalled working copy. */
  readCurrent<Key extends keyof SessionActorStorageReads>(query: {
    type: Key;
    input: SessionActorStorageReads[Key]["input"];
  }, authority: SessionActorStorageAuthority): SessionActorStorageReads[Key]["output"];
  /** Acquire a separately releasable handle from this already-selected owner. */
  acquire(sessionKey: string, lifetime?: SessionActorLifetime): Promise<SessionActor>;
  read<Key extends keyof SessionActorStorageReads>(query: {
    type: Key;
    input: SessionActorStorageReads[Key]["input"];
  }, authority: SessionActorStorageAuthority): Promise<SessionActorStorageReads[Key]["output"]>;
  mutate<Key extends keyof SessionActorStorageWrites>(command: {
    type: Key;
    input: SessionActorStorageWrites[Key]["input"];
  }, authority: SessionActorStorageAuthority, observer?: SessionActorStorageCommitObserver<SessionActorStorageWrites[Key]["output"]>): Promise<SessionActorStorageOutcome<SessionActorStorageWrites[Key]["output"]>>;
};
/**
 * One command is one synchronous writer transaction. No mailbox hold crosses an await.
 * Unknown outcomes fence disclosure until read() reconciles; commands are never replayed.
 * A receipt is commit evidence, not live authority for the caller's next external effect.
 */
type SessionActor = SessionActorLifetime & SessionActorCommands & {
  readonly target: SessionActorTarget;
  /** Present only when the selected backend owns the storage domain. */
  readonly storage?: SessionActorStorage;
  /** Read-only installed MAIN revision; copy before editing. Undefined means fenced/missing. Never dispatches a worker request. */
  snapshot(authority: SessionActorAuthority): SessionActorHotState | undefined;
  /** Entry-only receipts retain the same lifetime and reconciliation fence as full snapshots. */
  snapshotEntry(authority: SessionActorAuthority): SessionActorAuthorityFacts | undefined;
  read(authority: SessionActorAuthority): Promise<SessionActorHotState>;
  /** Drain retained attempts and accepted descendants; a teardown timeout is not settlement. */
  release(): Promise<void>;
  /**
   * Retain lifetime, not FIFO. Reducers ride the next command in this phase;
   * any remainder commits before the phase settles, including exceptional exits.
   */
  withPhase<T>(phaseId: string, authority: SessionActorAuthority, operation: (phase: {
    actor: SessionActor;
    patch(reducers: readonly SessionActorReducer[]): void;
  }) => Promise<T>): Promise<T>;
};
//#endregion
//#region src/sessions/session-controller.contracts.d.ts
type ReplyOperationPhase = ReplyOperationActivePhase | "completed" | "failed" | "aborted";
type ReplyOperationResult = Exclude<ReplyOperationResult$1, {
  kind: "yielded";
}>;
type ReplyTurnKind = "visible" | "queued_followup";
type ReplyOperation = {
  readonly watchdog: SessionControllerWatchdog;
  readonly personalToolParticipants?: ReplyTurnParticipants;
  readonly key: string;
  readonly sessionId: string;
  /** Captured logical owner for session activity, including raw global keys. */
  readonly agentId?: string;
  readonly turnKind: ReplyTurnKind;
  /** Gateway lifecycle that admitted this process-local owner. */
  readonly lifecycleGeneration?: string;
  readonly routeThreadId?: string | number;
  /** Transcript branch leaf from which this operation was admitted. */
  readonly originatingLeafEntryId?: string | null;
  readonly abortSignal: AbortSignal;
  readonly resetTriggered: boolean;
  /**
   * True when this operation was admitted to recover a terminal session (a
   * leftover failed/timeout/killed run). Concurrent visible turns reading the
   * same terminal store snapshot must NOT force-clear such an operation: it is a
   * sibling recovery already in flight, not the proven stale leftover.
   */
  readonly terminalRecovery: boolean;
  /**
   * Sticky fact for audio accepted into this operation after its originating turn.
   * Final delivery reads it because the original dispatch context cannot change.
   */
  readonly acceptedSteeredInboundAudio: boolean;
  /** Sticky fact: a final message-tool send already answered this turn's source. */
  readonly sourceReplyDelivered: boolean;
  /** Immutable tool authority accepted by the active backend for steered user turns. */
  readonly toolAuthorityFingerprint?: string;
  readonly requesterPrincipalKey?: string;
  /** Initial selected model; a concrete attempt must not replace user intent. */
  readonly requestedToolAuthorityRoute?: ReplyToolAuthorityRoute;
  /** Current candidate proven automatic by the fallback owner; identity marks its attempt. */
  readonly automaticFallbackRoute?: ReplyToolAuthorityRoute;
  /** Concrete provider/model route currently selected for this operation. */
  readonly toolAuthorityRoute?: ReplyToolAuthorityRoute;
  readonly phase: ReplyOperationPhase;
  readonly result: ReplyOperationResult | null;
  /** Its fenced admission ended; raw producer settlement remains independently retained. */
  readonly admissionRetired: boolean;
  /** Retire only after exact writer fences and execution authority permit a successor. */
  retireAdmissionAfterFencing(): Promise<boolean>;
  /** Frozen backend outcome; cancellation and lane settlement remain separate. */
  readonly abortFrozen: boolean;
  /** Retire exact placement authority on cleanup; never a raw writer-settlement receipt. */
  registerExecutionCleanup(cleanup: () => Promise<void>): () => void;
  /** Retain this producer until an admitted nested native body actually returns. */
  retainExecution(): () => void;
  /** Fence one exact persisted writer before terminal cleanup may release the run slot. */
  registerTerminalProducerFence(fence: () => Promise<boolean>): () => void;
  /** True after cleanup could not prove every unsettled producer durably fenced. */
  readonly terminalProducerBlocked: boolean;
  /** Set when a stale-watchdog expiry forced this operation's run_stalled result. */
  readonly staleExpiryReason?: ReplyOperationStaleReason;
  readonly startedAtMs: number;
  readonly lastActivityAtMs: number;
  /** True when this operation has owned the supplied session ID. */
  hasOwnedSessionId(sessionId: string): boolean;
  /** Capture lineage before a pending barrier outlives this operation's lane. */
  captureOwnedSessionIds(): Set<string>;
  recordActivity(): void;
  setPhase(next: ReplyOperationActivePhase): void;
  /** Mark this operation as waiting on prior same-session maintenance. */
  markWaitingForDeferredMaintenance(): void;
  /** Return a maintenance-waiting operation to queued if the run has not started. */
  markDeferredMaintenanceWaitEnded(): void;
  markWaitingForGlobalLane(): void;
  /** Return a global-lane-waiting operation to queued once capacity is granted. */
  markGlobalLaneWaitEnded(): void;
  markTerminalRecovery(): void;
  /** A steered input joined this operation; any earlier source answer predates it. */
  markSteeredInputAccepted(params: {
    inboundAudio: boolean;
  }): void;
  markSourceReplyDelivered(): void;
  /** Freeze the complete caller policy before a concrete backend attempt attaches. */
  /** @deprecated Use bindToolAuthoritySnapshotAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  bindToolAuthoritySnapshot(snapshot: ReplyToolAuthoritySnapshot): void;
  bindToolAuthoritySnapshotAsync(snapshot: ReplyToolAuthoritySnapshot): Promise<void>;
  setAutomaticFallbackRoute(route: ReplyToolAuthorityRoute | undefined): void;
  /** Project an inbound turn through the current concrete route; settled owners fail closed. */
  /** @deprecated Use projectToolAuthorityFingerprintAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  projectToolAuthorityFingerprint(overlay: ReplyToolAuthorityOverlay): string | undefined;
  projectToolAuthorityFingerprintAsync(this: void, overlay: ReplyToolAuthorityOverlay): Promise<string | undefined>;
  /** Legacy snapshots without fresh-requester projection cannot admit delegated steering. */
  projectRequesterToolAuthorityFingerprint?(requester: ReplyToolAuthorityRequester): string | undefined;
  projectRequesterToolAuthorityFingerprintAsync?(this: void, requester: ReplyToolAuthorityRequester): Promise<string | undefined>;
  /** Prepare fingerprint and projection together for the final concrete attempt route. */
  /** @deprecated Use bindToolAuthorityRouteAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
  bindToolAuthorityRoute(route: ReplyToolAuthorityRoute): string;
  bindToolAuthorityRouteAsync(route: ReplyToolAuthorityRoute): Promise<string>;
  updateSessionId(nextSessionId: string): void;
  /**
   * Native commands transfer their queued source reservation to the target session.
   * An occupied target throws ReplyRunAlreadyActiveError; unchanged keys still adopt agentId.
   */
  updateSessionKey(nextSessionKey: string, agentId?: string, mailboxClaim?: SessionControllerMailboxClaim): void;
  attachBackend(handle: ReplyBackendHandle): void;
  detachBackend(handle: ReplyBackendHandle): void;
  /** Reject later aborts after the backend has committed its terminal outcome. */
  freezeAbort(): void;
  /** Published SDK opt-in; controller failures already retain custody until complete(). */
  retainFailureUntilComplete(): void;
  /**
   * Records the backend's own yield and closes injection and tool authority; settlement then
   * records `yielded` unless a Stop or failure supersedes it first. False once the turn has ended.
   */
  yield(): boolean;
  /** Settles after the lifecycle owner's final delivery/persistence barrier. */
  readonly ownerSettlement: Promise<void>;
  complete(): void;
  /**
   * Complete the operation, clear active-run state, then run follow-up work.
   * Use when the follow-up can create another operation for this session.
   */
  completeThen(afterClear: () => void): void;
  /**
   * Clear active-run state immediately, but delay registered after-clear work
   * until delivery or another external barrier settles.
   */
  completeWithAfterClearBarrier(barrier: PromiseLike<unknown>, timeout?: number | ReplyFollowupAdmissionBarrierTimeoutPolicy): void;
  fail(code: Exclude<Extract<ReplyOperationResult, {
    kind: "failed";
  }>["code"], "aborted_by_user">, cause?: unknown): void;
  abort(reason?: unknown): boolean;
  abortByUser(): boolean;
  abortForRestart(): boolean;
  /** Watchdog-only terminal attribution; committed outcomes require cleanup, not Stop. */
  abortForStall(): boolean;
  supersede(beforeSupersede?: () => void): boolean;
};
declare const sessionControllerOperationState: unique symbol;
type SessionControllerTurnKind = ReplyTurnKind | "direct";
/** Internal observations read the same operation state as the published getters. */
type SessionControllerOperation = ReplyOperation & {
  readonly [sessionControllerOperationState]: {
    readonly phase: ReplyOperationState["phase"];
    readonly turnKind: SessionControllerTurnKind;
    retireAdmissionAfterFencing(isCurrent: () => boolean): Promise<boolean>;
    forceCleanup(isCurrent: () => boolean, cleanup?: () => Promise<void>): Promise<boolean>;
    registerTerminalProducerFence(fence: (isCurrent: () => boolean, options?: {
      persistTerminal?: true;
    }) => Promise<boolean>): () => void;
    bindAttemptToolAuthoritySnapshot(snapshot: ReplyToolAuthoritySnapshot): Promise<() => void>;
  };
};
type ReplyRunWaiter = {
  finish: (ended: boolean) => void;
  timer?: NodeJS.Timeout;
};
type ReplyRunAdmissionSource = {
  sessionId: string;
  sessionIds: Set<string>;
  operation: ReplyOperation;
  databaseIdentity?: OpenClawAgentDatabaseIdentity;
};
type ReplyRunCompletionObservation = {
  changed: boolean;
  sources: Map<OpenClawAgentDatabaseIdentity | undefined, ReplyRunAdmissionSource>;
};
type ReplyRunAdmissionBarrier = {
  settled: Promise<void>;
  source: ReplyRunAdmissionSource;
  sources: Map<OpenClawAgentDatabaseIdentity | undefined, ReplyRunAdmissionSource>;
};
/** The exact run facts owned by one reply operation. Embedded attempts extend
 * this object in place and the runner's run-id index points back to that record. */
type SessionControllerRunAttachment = {
  readonly operation: ReplyOperation;
  /** Each attach call owns a fresh identity, even when it reuses a backend handle. */
  backend?: {
    readonly handle: ReplyBackendHandle;
  };
  projectSessionActive?: boolean;
};
/** One retained scheduling owner per canonical key. Native attempts are subordinate
 * to active; waiters, fences and completion observations belong to this same entry.
 * Mailbox and mutation scheduling extend this entry, never a second keyed registry. */
type SessionControllerEntry = {
  readonly id: string;
  readonly key: string;
  target?: SessionTarget;
  aliases: Set<string>;
  logicalAliases: Set<string>;
  mailbox?: SessionControllerMailbox;
  lifecycle?: SessionControllerLifecycle;
  active?: SessionControllerOperation;
  attachment?: SessionControllerRunAttachment | EmbeddedRunAttachment;
  sourceTurnId?: string;
  waiters: Set<ReplyRunWaiter>;
  followupBarrier?: ReplyRunAdmissionBarrier;
  successorBarrier?: ReplyRunAdmissionBarrier;
  observations: Set<ReplyRunCompletionObservation>;
};
type SessionEffectInterrupt = (reason?: Error) => {
  runId: string;
} | void;
type SessionWorkRun = Readonly<{
  runId: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  controlUiVisible?: boolean;
}>;
type SessionEffectRef = {
  readonly target: SessionTarget;
  readonly operation?: ReplyOperation;
  createHandoff(): string;
  isActive(): boolean;
  release: () => void;
  readonly released: Promise<void>;
  run: <T>(run: () => Promise<T>) => Promise<T>;
};
type Effect = {
  admissionTransitions?: Map<object, (transition: SessionAdmissionTransition, isActive: SessionEffectRef["isActive"]) => void>;
  diagnostic?: LifecycleDiagnosticOperation;
  sourceInput?: SessionControllerInput;
  agent?: AgentWorkAdmissionIdentity;
  run?: SessionWorkRun;
  owner?: symbol;
  isSettling?: () => boolean;
  getAbortReason?: () => unknown;
  ref: SessionEffectRef;
  entry: SessionControllerEntry;
  phase: "queued" | "validating" | "writer" | "acquired" | "released";
  generation: string;
  interrupt?: SessionEffectInterrupt;
  interrupted?: Error;
  cancel: AbortController;
  handoffs: Set<string>;
  validated: Deferred;
};
type SessionMutationKind = "reset" | "delete" | "compaction" | "read-marker" | "background-result";
type Mutation = {
  diagnostic?: LifecycleDiagnosticOperation;
  entries: SessionControllerEntry[];
  targets: SessionTarget[];
  kind?: SessionMutationKind;
  phase: "queued" | "active" | "released";
  operations: Set<ReplyOperation>;
  ready: Deferred;
};
type SessionControllerLifecycle = {
  targets: Map<SessionTarget, number>;
  operations: Set<ReplyOperation>;
  effects: Set<Effect>;
  mutations: Mutation[];
  closures: Set<{
    reason: Error;
  }>;
  changed: Deferred;
  readonly blocksTurnAdmission: boolean;
};
type SessionControllerSourceCustody = {
  enqueued?: boolean;
  adopted?: boolean;
  adopting?: Promise<void>;
  /** Cancellation may notify abandonment before raw preparation releases source custody. */
  abandonment?: {
    completion?: Promise<void>;
    failure?: {
      error: unknown;
    };
  };
  work?: Set<Promise<unknown>>;
  settling?: Promise<void>;
  completed?: boolean;
  cancellationRetired?: boolean;
  stopHeartbeat?: () => void;
  releaseAuthority?: () => void;
  failure?: unknown;
  disposeSource?: () => void;
  /** One in-process Gateway registration may adopt a pre-reserved source. */
  rpcAdopted?: boolean;
  /** The Gateway accepted this source into its protocol run registry. */
  rpcAccepted?: boolean;
};
type SessionControllerInput = {
  readonly [inputCancellation]: AbortController;
  readonly abortSignal: AbortSignal;
  readonly instance: Readonly<{
    id: string;
  }>;
  sequence: number;
  readonly sourceTurnId?: string;
  protocolRunId?: string;
  /** Producer records transcript custody after the input owner commits it. */
  onTranscriptCommitted?: (runId: string) => void | Promise<void>;
  policy: Readonly<QueueSettings>;
  mailbox: SessionControllerMailbox;
  readonly custody: SessionControllerSourceCustody;
  readonly settlement: ReturnType<typeof createDeferredCore<void>>;
  /** Current protocol-facing session identity before an operation owns it. */
  sourceSessionId?: string;
  /** Source admission identity survives later mailbox incarnation bindings. */
  target?: SessionTarget;
  source?: FollowupRun;
  sourceAdapter?: SessionControllerSourceAdapter;
  /** Process-local requester identity reference; never serialized or accepted over RPC. */
  readonly continuationCaller?: Readonly<{
    deliveryRoute?: DeliveryContext;
    run<T>(run: () => Promise<T>): Promise<T>;
  }>;
  phase: "preparing" | "waiting" | "injecting" | "claimed" | "consumed";
  readonly injectionOrder: {
    readonly resolved: boolean;
    settled: Promise<boolean>;
    settle(consumed: boolean): void;
  };
  injectionAttempted?: true;
  injection?: {
    predecessor: Promise<boolean>;
    settled: Promise<boolean>;
    settle(accepted: boolean): void;
    admitted?: boolean;
  };
  claim?: SessionControllerMailboxClaim;
  ready?: (claim: SessionControllerMailboxClaim) => void;
  reject?: (error: unknown) => void;
  task?: (claim: SessionControllerMailboxClaim) => void;
  taskTurnKind?: SessionControllerTurnKind;
  /** The active mutation whose own body submitted this direct task. */
  mutation?: Mutation;
  withdrawalHolds: number;
  retirementRequested?: boolean;
  cancelling?: boolean;
  retirementPending?: boolean;
  payload: "unbound" | "ready" | "summary";
};
type SessionControllerMailboxClaim = {
  readonly mailbox: SessionControllerMailbox;
  inputs: readonly SessionControllerInput[];
  sources: readonly FollowupRun[];
  readonly custody: SessionControllerSourceCustody;
  readonly summary: boolean;
  readonly settlement: ReturnType<typeof createDeferredCore<void>>;
  readonly abortController: AbortController;
  operation?: ReplyOperation;
  released: boolean;
  releaseRequested?: boolean;
  retryBeforeExecution?: boolean;
};
/** All runnable inputs, including direct native producers, share this ordered owner. */
type SessionControllerMailbox = {
  readonly key: string;
  readonly owner: SessionControllerEntry;
  clearing?: boolean;
  nextSequence: number;
  entries: SessionControllerInput[];
  claim?: SessionControllerMailboxClaim;
  priority?: SessionControllerInput;
  preparing?: boolean;
  wake(): void;
  dispatch?: (claim: SessionControllerMailboxClaim) => Promise<void>;
  dispatchEnabled?: boolean;
  timer?: ReturnType<typeof setTimeout>;
  abortController: AbortController;
  readonly items: FollowupRun[];
  readonly draining: boolean;
  readonly inFlight: ReadonlySet<FollowupRun>;
  lastEnqueuedAt: number;
  mode: QueueSettings["mode"];
  debounceMs: number;
  cap: number;
  dropPolicy: "old" | "new" | "summarize";
  droppedCount: number;
  summaryLines: string[];
  summarySources: FollowupRun[];
  activeSummarySources: Set<FollowupRun>;
  summaryElisions: Array<{
    contextKey: string;
    count: number;
    sources: FollowupRun[];
    summaryLines: string[];
    sourceRefs: Map<FollowupRun, FollowupRun>;
  }>;
  lastRun?: FollowupRun["run"];
  recentSources: Map<string, {
    inputInstance: SessionControllerInput["instance"];
    expires: number;
  }>;
};
type SessionControllerSourceAdapter = {
  /** Original personal ingress, bound at admission; identity evidence, not an execution grant. */
  initiatingPersonalOperator?: AdmittedRunOperatorAuthority;
  readonly scope?: string;
  readonly authority?: {
    assertCurrent(): void;
    signal?: AbortSignal;
  };
  readonly signal?: AbortSignal;
  readonly requester?: Readonly<{
    deviceId?: string;
    connectionId?: string;
    clientId?: string;
  }>;
  /** Known routing identity before a physical target exists; never execution authority. */
  readonly preparation?: Readonly<{
    agentId?: string;
  }>;
  /** False for internal work that ordinary operator chat surfaces must preserve. */
  readonly controlUiVisible?: boolean;
  /** Initial presentation copied to the claimed operation; the adapter is not a runtime owner. */
  readonly projectSessionActive?: boolean;
  /** Side questions stay independent from main-turn session stops. */
  readonly turnKind?: "main" | "btw";
  cancel?(reason?: unknown): void;
  /** Joins accepted cancellation publication without joining raw source cleanup. */
  cancellationAcknowledgment?(): Promise<void>;
  onSettled?(): void | Promise<void>;
};
declare const inputCancellation: unique symbol;
type FollowupRun = FollowupRunPayload & {
  /** @internal Host-only fallback eligibility; false preserves a caller without a profile grant. */
  sessionPrincipalTurn?: boolean;
  run: FollowupRunPayload["run"] & {
    /** Observe admission without transferring the runner's settlement custody. */
    onOperationAdmitted?: (operation: ReplyOperation) => void;
  };
  /** @internal Exact controller reservation; scheduling and cancellation live on it. */
  controllerInput?: SessionControllerInput;
  /** @internal Exact selected mailbox sources shared by a queued collect batch. */
  controllerClaim?: SessionControllerMailboxClaim;
  /** @internal Source execution receipts retained across queued collect batches. */
  replyOperationRunStates?: ReplyOperationRunState[];
};
type ReplyOperationAdmissionSnapshot = {
  status: "owned";
} | {
  status: "accepted";
  mode: "steer" | "followup";
  reason?: "requester-mismatch" | "steering-unavailable" | "explicit-followup" | "collaborative-steering-disabled";
} | {
  status: "skipped";
  reason: "active-run" | "aborted" | "lifecycle-invalidated" | "queue-cap" | "collaborative-steering-disabled" | "question-response-indeterminate" | "question-response-refused" | "question-response-rejected";
};
type ReplyPreRunRejectionCode = "model-scope-conflict" | "model-scope-not-authorized" | "model-selection-locked" | "model-runtime-invalid" | "model-selection-rejected" | "model-selection-conflict" | "session-directive-rejected";
type ReplyOperationRunState = {
  replyCompletion?: ReplyCompletion;
  /** The source delivery owner can keep spawned completion turns private. */
  sessionEventDelivery?: false;
  admission?: ReplyOperationAdmissionSnapshot;
  /** Latest queue-owned disposition; original acceptance still records custody. */
  followupQueueDisposition?: FollowupQueueDisposition$1;
  /** The Gateway accepted this question answer or rejected its values before commitment. */
  questionInputHandled?: true;
  messageInjectionAborted?: true;
  agentTurn?: ReturnType<typeof resolveAgentTurnExecutionStatus>;
  agentTurnOwner?: ReplyOperation;
  messagingToolSentTargets?: MessagingToolSend[];
  backgroundWorkStarted?: boolean;
  preRunRejection?: ReplyPreRunRejectionCode;
  /**
   * Armed by the admitted interactive run owner. Interruption recovery consumes it once;
   * true means the session lane will answer instead.
   */
  continueStalledTurn?: (guidance?: string, owner?: ReplyOperation) => boolean;
};
declare const embeddedRunCleanupAttachment: unique symbol;
type EmbeddedAgentQueueHandle = {
  kind?: "embedded";
  [embeddedRunCleanupAttachment]?: ActiveEmbeddedRunAttachment;
  runId?: string;
  /** Exact process-local diagnostic lifecycle shared with this handle's model wrapper. */
  readonly diagnosticOwner?: DiagnosticEmbeddedRunOwner;
  /** Synchronously closes diagnostic authority before this handle is evicted. */
  readonly closeDiagnostics?: () => void;
  /** Core run start time used by live recovery projections. */
  startedAtMs?: number;
  /** Exact authority of the concrete provider/model attempt behind this handle. */
  toolAuthorityFingerprint?: string;
  /** Shared outer-run owner survives an intentional native-turn replacement. */
  permissionChangeOwner?: object;
  /** Fences prior tools, revokes their approvals, then acknowledges installed permissions. */
  applyPermissionMode?: (mode: SessionPermissionMode | null, revokeApprovals: () => void) => Promise<boolean>;
  /** Atomically consumes one plain-text answer for this run's pending user-input request. */
  claimPendingUserInputAnswer?: ReplyBackendHandle["claimPendingUserInputAnswer"];
  /** Cancels this run's pending user-input request before an image is queued as a later turn. */
  cancelPendingUserInput?: (resolvedBy: string) => Promise<boolean>;
  queueMessage: (text: string, options?: EmbeddedAgentQueueMessageOptions) => Promise<void | EmbeddedAgentQueueMessageResult>;
  messageInjection?: ReplyBackendMessageInjection;
  messageInjectionV2?: ReplyBackendMessageInjectionV2;
  isStreaming: () => boolean;
  /** Borrow current model context only while this attempt owns the session. */
  readSessionForkContext?: () => {
    model: Model;
    systemPrompt: string;
    tools: Context["tools"];
    messages: AgentMessage[];
    projectMessages?: (messages: AgentMessage[]) => AgentMessage[];
    sessionVersion?: number;
    boundary?: LlmBoundaryOptions;
    blockImages?: boolean;
  } | undefined;
  isStopped?: () => boolean;
  /** True after this handle has accepted an abort, even while cleanup retains it. */
  isAborted?: () => boolean;
  /** True only while this exact runtime owns a live wait, not unresolved host work or cleanup. */
  ownsLiveness?: () => boolean;
  /** Interrupts a current model request; its attempt still owns settlement and replay policy. */
  recoverStalledModelCall?: () => boolean;
  isAbortable?: () => boolean;
  isCompacting: () => boolean;
  supportsTranscriptCommitWait?: boolean;
  /** True only when queueMessage preserves images supplied in its options. */
  supportsQueueMessageImages?: boolean;
  /** False keeps inbound steering with the turn owner's profile; omission permits other profiles. */
  readonly supportsCrossProfileSteering?: boolean;
  cancel?: (reason?: "user_abort" | "restart" | "superseded") => void;
  abort: (reason?: "restart") => void;
  sourceReplyDeliveryMode?: ReplyBackendHandle["sourceReplyDeliveryMode"];
  terminalReplyExpectation?: ReplyExpectation;
  supportsUserReplyPromotion?: boolean;
  taskSuggestionDeliveryMode?: ReplyBackendHandle["taskSuggestionDeliveryMode"];
};
type EmbeddedAgentQueueMessageOptions = ReplyBackendQueueMessageOptions;
type EmbeddedAgentQueueMessageResult = ReplyBackendQueueMessageResult;
/** Host-private binding consumed before publishing one actual backend handle. */
type EmbeddedRunToolAuthorityBinding = (registration: {
  sessionId: string;
  sessionKey?: string;
  sessionFile?: string;
  agentId?: string;
  handle: EmbeddedAgentQueueHandle;
}) => {
  source: "reply" | "attempt";
  detached?: true;
  operation?: ReplyOperation;
  sourceTurnId?: string;
  readonly requesterPrincipalKey?: string;
  acceptsRequesterOrigin: (origin: RequesterOrigin) => boolean;
  watchdogAttempt?: SessionControllerWatchdogAttempt;
  project: (overlay: ReplyToolAuthorityOverlay) => string | undefined;
  projectAsync: (overlay: ReplyToolAuthorityOverlay) => Promise<string | undefined>;
  projectRequester?: (requester: ReplyToolAuthorityRequester) => string | undefined;
  projectRequesterAsync?: (requester: ReplyToolAuthorityRequester) => Promise<string | undefined>;
  /** Registration may precede reply-backend attachment; use requires the attached owner. */
  assertRegistrationActive: () => void;
  assertActive: () => void;
  personalToolParticipants?: ReplyTurnParticipants;
};
type EmbeddedRunRegistration = {
  handle: EmbeddedAgentQueueHandle;
  lifecycleGeneration: string;
  /** Resolves only when this exact native producer clears, including after replacement. */
  settlement: ReturnType<typeof createDeferredCore<void>>;
  /** Full generation cleanup retained after native terminal publication clears this attachment. */
  runCleanupSettlement?: Promise<void>;
  settled?: true;
  watchdogAttempt?: SessionControllerWatchdogAttempt;
  closeWatchdogWait?: () => void;
  /** Controller-owned presentation fact; retained cleanup must not reappear after context release. */
  projectSessionActive?: boolean;
  toolAuthority?: ReturnType<EmbeddedRunToolAuthorityBinding>;
  operationalRunInstance?: OperationalRunInstanceRef;
  sessionId: string;
  sessionKey?: string;
  agentId?: string;
  delegatedAuthority?: AgentRunDelegatedAuthority;
  humanInputWaits?: Set<() => boolean>;
  onHumanInputResolved?: () => void;
};
/** The controller's exact attachment for one scoped embedded attempt. */
type EmbeddedRunAttachment = EmbeddedRunRegistration & SessionControllerRunAttachment;
/** Unhosted or explicitly detached attempts have no controller operation. */
type DetachedEmbeddedRunAttachment = EmbeddedRunRegistration & {
  operation?: undefined;
  backend?: undefined;
};
type ActiveEmbeddedRunAttachment = EmbeddedRunAttachment | DetachedEmbeddedRunAttachment;
//#endregion
//#region src/agents/harness/host-private-capabilities.d.ts
type QuestionInputAuthority = {
  kind: "run" | "source-bound";
  assertCurrent: () => void;
  prepareCurrent?: () => Promise<void>;
  toolAuthorityPreparation?: ReplyToolAuthorityPreparation;
};
declare function prepareQuestionGatewayDispatch(authority?: {
  version: 2;
} & QuestionInputAuthority, inProcess?: boolean): {
  assertDispatchCurrent: (() => void) | undefined;
  prepareDispatchCurrent: (() => Promise<void>) | undefined;
};
//#endregion
//#region src/agents/tools/gateway.d.ts
type GatewayCallOptions = {
  gatewayUrl?: string;
  gatewayToken?: string;
  timeoutMs?: number;
};
/** Presentation hint from the admitted operator source; RPC admission remains authoritative. */
declare function readGatewayToolOperatorScopes(): readonly string[] | undefined;
declare function callGatewayTool<T = Record<string, unknown>>(method: string, opts: GatewayCallOptions, params?: unknown, extra?: {
  expectFinal?: boolean;
  scopes?: OperatorScope[];
  requireAgentRuntimeIdentity?: boolean;
  signal?: AbortSignal;
  onHelloOk?: CallGatewayOptions["onHelloOk"];
  dispatchAuthority?: Parameters<typeof prepareQuestionGatewayDispatch>[0];
}): Promise<T>;
//#endregion
//#region src/agents/tools/computer-tool-gateway.d.ts
type GatewayComputerStatus = {
  configured: false;
  available: false;
} | {
  configured: true;
  available: false;
  computerUse?: ComputerUseCapabilityDescriptor;
  error?: string;
} | {
  configured: true;
  available: true;
  computerUse: ComputerUseCapabilityDescriptor;
};
//#endregion
//#region src/agents/tools/computer-tool-shared.d.ts
declare const COMPUTER_ACT_COMMAND = "computer.act";
declare const SCREEN_SNAPSHOT_COMMAND = "screen.snapshot";
/** The owner binds the execution target and revalidates its authority before every dispatch. */
type ComputerToolTransport = {
  readonly computerUse?: ComputerUseCapabilityDescriptor;
  resolveNode: (query?: string, signal?: AbortSignal) => Promise<{
    nodeId: string;
    computerUse?: ComputerUseCapabilityDescriptor;
  }>;
  invoke: (params: {
    nodeId: string;
    command: typeof COMPUTER_ACT_COMMAND | typeof SCREEN_SNAPSHOT_COMMAND;
    commandParams: Record<string, unknown>;
    timeoutMs?: number;
    idempotencyKey?: string;
    signal?: AbortSignal;
  }) => Promise<unknown>;
};
//#endregion
//#region src/agents/computer-use-node-capabilities.d.ts
type PreparedPairedComputerUse = {
  actions: readonly ComputerUseV2ActionName[];
  guidanceCapabilities?: ComputerUseCapabilityDescriptor;
  gateway?: GatewayComputerStatus;
};
//#endregion
//#region src/gateway/worker-environments/computer-transport.d.ts
type WorkerComputerTransport = Omit<ComputerToolTransport, "invoke"> & {
  invoke(request: Parameters<ComputerToolTransport["invoke"]>[0], assertAuthorized?: () => void): Promise<unknown>;
};
type PreparedWorkerComputer = {
  descriptor: WorkerComputerLaunchDescriptor;
  bind(operationalRunInstance: OperationalRunInstanceRef, workerSource?: {
    authority: AgentRunDelegatedAuthority;
    assertCurrent: () => void;
  }): WorkerComputerTransport;
  close(reason: string): Promise<void>;
};
type WorkerEnvironmentComputerAuthority = {
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
  sessionKey: string;
  agentId: string;
  runId: string;
  assertCurrent(): void;
  turnClaim?: WorkerSessionTurnClaim;
};
//#endregion
//#region src/gateway/worker-environments/placement-target.d.ts
type WorkerPlacementCancellationTarget = Readonly<Pick<WorkerSessionPlacementRecord, "state" | "generation" | "environmentId" | "activeOwnerEpoch">>;
//#endregion
//#region src/gateway/worker-environments/service-contract.d.ts
/** Non-secret worker projection available to Gateway request handlers. */
type WorkerEnvironmentServiceRecord = {
  startStatus?: WorkerEnvironmentStartStatus;
  environmentId: string;
  providerId: string;
  profileId: string;
  inference?: "worker";
  leaseId: string | null;
  nodeDeviceId?: string | null;
  sharedHost: boolean | null;
  state: WorkerEnvironmentState;
  ownerEpoch: number;
  createdAtMs: number;
  idleSinceAtMs: number | null;
  destroyRequestedAtMs: number | null;
  attachedSessionIds: readonly string[];
  desktopAvailable: boolean;
  desktopApps: readonly WorkerDesktopApp["id"][];
  tunnelStatus: WorkerTunnelStatus;
  preparation?: (WorkerEnvironmentPreparation & {
    project?: {
      label?: string;
      baseCommit: string;
    };
  }) | null;
  error?: string;
};
type WorkerDesktopObserveResult = Omit<WorkerDesktopObserveResult$1, "transport"> & {
  transport: "rfb";
};
/** Request-facing lifecycle methods, kept separate from persistence and provider internals. */
type WorkerEnvironmentServiceContract = {
  observeProcesses?(input: Omit<NodeWorkerProcessInput, "gatewayNamespace" | "expectedBundleHash">, assertCurrent: () => void, signal?: AbortSignal): Promise<SessionsProcessesListResult | SessionsProcessesStopResult>;
  /** Current explicit provider attestation, never the persisted legacy default. */
  getDedicatedNodeLeaseSignal(environmentId: string): AbortSignal | undefined;
  captureSessionAttachment(identity: WorkerEnvironmentSessionIdentity): {
    binding: WorkerEnvironmentAttachment;
    assertCurrent(): void;
    touch(): Promise<void>;
  };
  getSessionAttachment(sessionId: string): WorkerEnvironmentAttachment | undefined;
  findSessionAttachment(identity: Pick<WorkerEnvironmentSessionIdentity, "agentId" | "sessionKey">): WorkerEnvironmentAttachment | undefined;
  getSessionAttachmentStatus(sessionId: string): {
    attachment: WorkerEnvironmentAttachmentRecord & {
      ownerEpoch: number;
    };
    environment: WorkerEnvironmentServiceRecord;
  } | undefined;
  assertSessionAttachment(binding: WorkerEnvironmentAttachment): void;
  touchSessionAttachment(binding: WorkerEnvironmentAttachment): Promise<void>;
  execSessionAttachment(binding: WorkerEnvironmentAttachment, command: WorkerWorkspaceCommand): Promise<NodeWorkerWorkspaceExecResult>;
  createSessionAttachment(request: WorkerEnvironmentSessionCreateRequest, authorize: () => void, signal?: AbortSignal, onReserved?: WorkerEnvironmentSessionReservationHandler): Promise<{
    attachment: WorkerEnvironmentAttachmentRecord & {
      ownerEpoch: number;
    };
    environment: WorkerEnvironmentServiceRecord;
    reused: boolean;
  }>;
  destroySessionAttachment(request: {
    sessionId: string;
    environmentId?: string;
  }, authorize: () => void): Promise<WorkerEnvironmentServiceRecord | undefined>;
  prepareAttachedComputer?: (authority: WorkerEnvironmentComputerAuthority) => Promise<PreparedWorkerComputer | undefined>;
  openNodePortal(request: {
    environmentId: string;
    ownerEpoch: number;
    remotePort: number;
  }): Promise<{
    connect: (assertCurrent?: () => void, touch?: () => Promise<void>) => Promise<import("node:stream").Duplex>;
    close: () => Promise<void>;
  }>;
  list(): WorkerEnvironmentServiceRecord[];
  readPreparedPoolSummary(): {
    maxTotal: number;
    reservedEnvironmentIds: string[];
  };
  readReadyWorkerTarget(profileId: string): number;
  get(environmentId: string): WorkerEnvironmentServiceRecord | undefined;
  inventoryVersion(): number;
  readMachineShape(environmentId: string, prepared?: WorkerEnvironmentPlacementFacts): SessionPlacementMachine | undefined;
  machineShapeVersion(): number;
  supportsExecutionMode(profileId: string, mode: WorkerPlacementExecutionMode): boolean;
  readProviderDisplayId(profileId: string): string | undefined;
  listMachineOptions(profileId: string): Promise<readonly WorkerMachineOption[] | undefined>;
  listOperatingSystems(profileId: string): Promise<readonly WorkerOperatingSystem[] | undefined>;
  prepare(request: EnvironmentsPrepareParams, authorize?: () => void): Promise<EnvironmentsPrepareResult>;
  create(profileId: string, idempotencyKey: string, machineClass?: string, executionMode?: WorkerPlacementExecutionMode, projectPath?: string, signal?: AbortSignal, os?: string, runSetupScript?: boolean): Promise<WorkerEnvironmentServiceRecord>;
  destroy(environmentId: string): Promise<WorkerEnvironmentServiceRecord>;
  /** Stop session work and return after provider acceptance; physical cleanup remains owned. */
  reclaim(environmentId: string): Promise<WorkerEnvironmentServiceRecord>;
  destroyUnattached(environmentId: string, authorize?: () => void): Promise<WorkerEnvironmentServiceRecord>;
  observeDesktop(request: {
    environmentId: string;
    control: boolean;
    requester?: DesktopObserveRequester;
  }): Promise<WorkerDesktopObserveResult>;
  launchDesktopApp(request: WorkerDesktopLaunchParams, authorize?: () => void): Promise<WorkerDesktopLaunchResult>;
  startTunnel(request: WorkerTunnelRequest): Promise<WorkerTunnelHandle>;
  stopTunnel(environmentId: string, ownerEpoch?: number): Promise<void>;
};
type WorkerPlacementDispatchRequest = WorkerSessionPlacementDispatchIdentity & {
  profileId: string;
  executionMode: WorkerPlacementExecutionMode;
  /** Initial mandatory admission cannot cancel the input it is preparing. Never exposed over RPC. */
  requiredProfile?: string;
  /** Current dispatch caller's setup authority; never inherited by a new caller. */
  runSetupScript?: boolean;
  devicePlacement?: DevicePlacementRequirement;
  idempotencyKey?: string;
  deviceId?: string;
  machineClass?: string;
  os?: string;
  inheritedProfile?: {
    providerId: string;
    profileSnapshot: WorkerProfile;
  };
};
type WorkerPlacementReclaimRequest = WorkerSessionPlacementIdentity & {
  recoverToGateway?: SessionsReclaimParams["recoverToGateway"];
};
type WorkerPlacementMoveRequest = WorkerSessionPlacementIdentity & {
  source: WorkerPlacementMoveSource;
  target: WorkerPlacementMoveTarget;
  abandonSource?: true;
};
/** Exact source eligibility may follow only transitions published by captured predecessors. */
type WorkerPlacementReclaimSourceCheck = ((predecessor?: WorkerPlacementCancellationTarget) => void) & {
  /** Host-only eligibility, without placement reads; ends when drain commits. */
  assertCurrent?: WorkerPlacementAuthorization;
};
type WorkerPlacementDispatchContract = {
  /** Server-owned placement under existing session creation/run authority, not manual dispatch. */
  withRequiredSession?: RequiredSessionPlacementAdmission;
  getPendingDeviceDispatchCount?(deviceId: string, excludeSessionId?: string): number;
  /** @deprecated Await getAdmittedDeviceSessionCountsAsync; retained through the next Plugin SDK major. */
  getAdmittedDeviceSessionCounts?(excludeSessionId?: string): ReadonlyMap<string, number>;
  getAdmittedDeviceSessionCountsAsync?(excludeSessionId?: string): Promise<ReadonlyMap<string, number>>;
  dispatch(request: WorkerPlacementDispatchRequest, onTransition?: (placement: WorkerSessionPlacementRecord) => void, authorize?: WorkerPlacementAuthorization, callerSignal?: AbortSignal): Promise<Extract<WorkerSessionPlacementRecord, {
    state: "active";
  }>>;
  move?(request: WorkerPlacementMoveRequest, onTransition?: (placement: WorkerSessionPlacementRecord) => void, authorize?: WorkerPlacementAuthorization): Promise<Extract<WorkerSessionPlacementRecord, {
    state: "local" | "active";
  }>>;
  reclaim?(request: WorkerPlacementReclaimRequest, authorize?: WorkerPlacementAuthorization, beforeDrain?: WorkerPlacementReclaimSourceCheck): Promise<Extract<WorkerSessionPlacementRecord, {
    state: "local" | "reclaimed";
  }>>;
  forceDestroyEnvironment?(environmentId: string, onCleanupError?: (error: unknown) => void, authorize?: () => void): Promise<WorkerEnvironmentServiceRecord>;
  reconcileActive?(environmentId?: string): Promise<void>;
};
//#endregion
//#region src/gateway/worker-environments/session-placement-lifecycle.d.ts
type SessionWorkerPlacementContext = {
  workerEnvironmentService?: Pick<WorkerEnvironmentServiceContract, "get">;
  workerPlacementDispatchService?: Pick<WorkerPlacementDispatchContract, "reclaim">;
  workerSessionPlacementService?: Pick<WorkerSessionPlacementStore, "getMany"> & Partial<Pick<WorkerSessionPlacementStore, "getManyAsync" | "retireSessionPlacement" | "listForReconcile" | "listAsync" | "prepareMaintenancePlacements" | "prepareSessionPlacement" | "retireSessionPlacementAsync" | "prepareRuntimeRefresh">>;
};
//#endregion
//#region src/auto-reply/reply/abort.d.ts
type FastAbortRequestParams = {
  ctx: FinalizedRuntimeMsgContext;
  cfg: OpenClawConfig;
  isCommandTargetCurrent?: SessionSourceCheck | AsyncSessionSourceCheck;
  onAbortRequest?: () => void;
};
type FastAbortResult = {
  handled: boolean;
  aborted: boolean;
  rejectionReason?: "finalizing";
  localModelMayStillBeFinishing?: true;
  stoppedSubagents?: number;
  failedSubagents?: number;
};
declare function formatAbortReplyText(stoppedSubagents?: number, rejectionReason?: "finalizing", failedSubagents?: number, localModelMayStillBeFinishing?: boolean): string;
declare function tryFastAbortFromMessage(params: FastAbortRequestParams): Promise<FastAbortResult>;
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.types.d.ts
type DispatchFromConfigResult = {
  queuedFinal: boolean;
  counts: Record<ReplyDispatchKind, number>;
  failedCounts?: Partial<Record<ReplyDispatchKind, number>>;
  settledReceipt?: ReplyDispatchReceipt;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  sendPolicyDenied?: boolean;
  observedReplyDelivery?: boolean;
  deferredToActiveRun?: "steer" | "followup";
  noVisibleReplyFallbackEligible?: boolean;
  noVisibleReplyFallbackDelivered?: boolean;
  deliberateSilentTerminalReply?: true;
  beforeAgentRunBlocked?: boolean;
  collaborativeSteeringRefused?: true;
  sessionMetadataChanges?: CommandSessionMetadataChange[];
};
type DispatchFromConfigParams = {
  ctx: FinalizedMsgContext;
  /** Full runtime config captured by the channel; reply resolution refreshes it per turn. */
  cfg: OpenClawConfig;
  dispatcher: ReplyDispatcher;
  replyOptions?: Omit<InternalGetReplyOptions, "onBlockReply" | "onPreparedBlockReply">;
  replyResolver?: InternalGetReplyFromConfig;
  onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void;
  fastAbortResolver?: typeof tryFastAbortFromMessage;
  formatAbortReplyTextResolver?: typeof formatAbortReplyText;
  /** Optional patch applied to the current runtime config before reply resolution. */
  configOverride?: OpenClawConfig;
  /** Gateway-owned worker services for archive recovery outside a request scope. */
  sessionWorkerPlacementContext?: SessionWorkerPlacementContext;
  /** @deprecated Omit this option; published model runtime is always enabled in the Gateway. */
  usePublishedModelRuntime?: boolean;
};
type DispatchReplyFromConfig$1 = (params: DispatchFromConfigParams) => Promise<DispatchFromConfigResult>;
//#endregion
//#region src/auto-reply/reply/provider-dispatcher.types.d.ts
type DispatchReplyContext = MsgContext | FinalizedMsgContext;
type DispatchReplyOptions = Omit<GetReplyOptions, "onBlockReply" | "onPreparedBlockReply"> & PluginCommandReplyOptions;
/** Buffered block dispatcher entry point used by provider reply flows. */
type DispatchReplyWithBufferedBlockDispatcher$2 = (params: {
  ctx: DispatchReplyContext;
  cfg: OpenClawConfig;
  dispatcherOptions: ReplyDispatcherWithTypingOptions;
  toolsAllow?: string[];
  replyOptions?: DispatchReplyOptions;
  replyResolver?: GetReplyFromConfig;
  dispatchReplyFromConfig?: DispatchReplyFromConfig$1;
}) => Promise<DispatchFromConfigResult>;
/** Plain dispatcher entry point used when block buffering is not needed. */
type DispatchReplyWithDispatcher$1 = (params: {
  ctx: DispatchReplyContext;
  cfg: OpenClawConfig;
  dispatcherOptions: ReplyDispatcherOptions;
  toolsAllow?: string[];
  replyOptions?: DispatchReplyOptions;
  replyResolver?: GetReplyFromConfig;
}) => Promise<DispatchFromConfigResult>;
//#endregion
//#region src/auto-reply/reply/conversation-label-generator.d.ts
type ConversationLabelParams = {
  userMessage: string;
  prompt: string;
  cfg: OpenClawConfig;
  agentId?: string;
  agentDir?: string;
  agentHarnessRuntimeOverride?: string;
  modelRef?: string;
  timeoutMs?: number;
  maxLength?: number;
  abortSignal?: AbortSignal;
  assertCurrent?: () => void;
  operatorAuthority?: AdmittedRunOperatorAuthority;
};
/** Generates a bounded human-readable label for a session, or null for empty output. */
declare function generateConversationLabel(params: ConversationLabelParams): Promise<string | null>;
//#endregion
//#region src/plugin-sdk/reply-dispatch-runtime.d.ts
type DispatchReplyWithBufferedBlockDispatcher$1 = (params: PublicReplyParams<Parameters<DispatchReplyWithBufferedBlockDispatcher$2>[0]>) => ReturnType<DispatchReplyWithBufferedBlockDispatcher$2>;
type DispatchReplyWithDispatcher = (params: PublicReplyParams<Parameters<DispatchReplyWithDispatcher$1>[0]>) => ReturnType<DispatchReplyWithDispatcher$1>;
/** Dispatches a reply with buffered block support after lazy-loading the runtime dispatcher. */
declare const dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher$1;
/** Dispatches a reply through the provider dispatcher after lazy-loading runtime code. */
declare const dispatchReplyWithDispatcher: DispatchReplyWithDispatcher;
//#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<void>;
}): Promise<ReplyDispatchReceipt | undefined>;
/** Run work with a dispatcher and always drain it before returning or throwing. */
declare function withReplyDispatcher<T>(params: {
  dispatcher: ReplyDispatcher;
  run: () => Promise<T>;
  onSettled?: () => void | Promise<void>;
  onSettledReceipt?: (receipt: ReplyDispatchReceipt | undefined) => void;
}): Promise<T>;
//#endregion
//#region src/infra/channel-activity.d.ts
/** Direction of the last observed activity for a channel/account pair. */
type ChannelDirection = "inbound" | "outbound";
type ActivityEntry = {
  inboundAt: number | null;
  outboundAt: number | null;
};
/** Records the latest inbound or outbound activity timestamp for a channel/account. */
declare function recordChannelActivity(params: {
  channel: ChannelId$1;
  accountId?: string | null;
  direction: ChannelDirection;
  at?: number;
}): void;
/** Returns the latest known inbound/outbound activity timestamps for a channel/account. */
declare function getChannelActivity(params: {
  channel: ChannelId$1;
  accountId?: string | null;
}): ActivityEntry;
//#endregion
//#region src/channels/plugins/outbound/load.d.ts
declare const loadChannelOutboundAdapter: (id: ChannelId$1) => Promise<ChannelOutboundAdapter | undefined>;
//#endregion
//#region src/channels/message-access/runtime-routes.d.ts
declare function channelIngressRoutes(...routes: Array<ChannelIngressRouteDescriptor | false | null | undefined>): ChannelIngressRouteDescriptor[];
//#endregion
//#region src/channels/message-access/runtime.d.ts
/** Evaluate policy without admitting a host participant. */
declare function createChannelIngressPolicyResolver(base: CreateChannelIngressResolverParams): ChannelIngressResolver;
declare function resolveStableChannelIngressPolicy(params: ResolveStableChannelMessageIngressParams): Promise<ResolvedChannelMessageIngress>;
declare function resolveChannelIngressPolicy(params: ResolveChannelMessageIngressParams): Promise<ResolvedChannelMessageIngress>;
//#endregion
//#region src/channels/turn/execution.d.ts
declare function runPreparedChannelTurn<TDispatchResult = DispatchedChannelTurnResult["dispatchResult"]>(params: PreparedChannelTurn<TDispatchResult>): Promise<ChannelTurnResult<TDispatchResult>>;
//#endregion
//#region src/config/markdown-tables.types.d.ts
/** Parameters for resolving markdown table rendering per config and channel. */
type ResolveMarkdownTableModeParams = {
  cfg?: Partial<OpenClawConfig>;
  channel?: string | null;
  accountId?: string | null;
  supportsBlockTables?: boolean;
};
type ResolveMarkdownTableMode = (params: ResolveMarkdownTableModeParams) => MarkdownTableMode;
//#endregion
//#region src/plugins/runtime/types-channel.d.ts
type DispatchReplyWithBufferedBlockDispatcher = DispatchReplyWithBufferedBlockDispatcher$1;
type DispatchReplyFromConfig = (params: PublicReplyParams<Parameters<DispatchReplyFromConfig$1>[0]>) => ReturnType<DispatchReplyFromConfig$1>;
type RecordInboundSession = RecordInboundSession$1;
type RuntimeThreadBindingLifecycleRecord = SessionBindingRecord | {
  boundAt: number;
  lastActivityAt: number;
  idleTimeoutMs?: number;
  maxAgeMs?: number;
};
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: typeof 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;
    resolveEnvelopeFormatOptions: typeof resolveEnvelopeFormatOptions;
  };
  routing: {
    buildAgentSessionKey: typeof buildAgentSessionKey;
    resolveAgentRoute: typeof resolveAgentRoute;
  };
  pairing: {
    buildPairingReply: typeof buildPairingReply;
    readAllowFromStore: ReadChannelAllowFromStoreForAccount;
    removeAllowFromStoreEntry: RemoveChannelAllowFromStoreEntryForAccount;
    upsertPairingRequest: UpsertChannelPairingRequestForAccount;
  };
  media: {
    readRemoteMediaBuffer: typeof readRemoteMediaBuffer;
    /** @deprecated Use `readRemoteMediaBuffer`. */
    fetchRemoteMedia: typeof fetchRemoteMedia;
    saveRemoteMedia: typeof saveRemoteMedia;
    saveResponseMedia: typeof saveResponseMedia;
    saveMediaBuffer: typeof saveMediaBuffer;
    deleteMediaBuffer: typeof deleteMediaBuffer;
  };
  activity: {
    record: typeof recordChannelActivity;
    get: typeof getChannelActivity;
  };
  session: {
    /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */
    resolveStorePath: typeof resolveSessionStorePathCore;
    /** @deprecated Await readSessionUpdatedAtAsync. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
    readSessionUpdatedAt: ReadSessionUpdatedAt;
    readSessionUpdatedAtAsync: (...params: Parameters<ReadSessionUpdatedAt>) => Promise<ReturnType<ReadSessionUpdatedAt>>;
    recordSessionMetaFromInbound: RecordSessionMetaFromInbound;
    /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */
    recordInboundSession: RecordInboundSession;
    updateLastRoute: typeof updateLastRoute;
    updateLastRouteWithAuthority: typeof updateLastRouteWithAuthority;
  };
  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: typeof isControlCommandMessage;
    shouldComputeCommandAuthorized: typeof shouldComputeCommandAuthorized;
    shouldHandleTextCommands: typeof shouldHandleTextCommands;
  };
  outbound: {
    loadAdapter: typeof loadChannelOutboundAdapter;
  };
  inbound: {
    /** Ingress policy and identity handoff bound to this channel's host instance. */
    ingress: {
      createResolver: typeof createChannelIngressPolicyResolver;
      resolve: typeof resolveChannelIngressPolicy;
      resolveStable: typeof resolveStableChannelIngressPolicy;
    };
    buildContext: typeof buildChannelInboundEventContext;
    run: typeof runChannelInboundEvent;
    /** @deprecated Prefer `run` for raw inbound events or `dispatchReply` for assembled contexts. */
    runPreparedReply: typeof runPreparedChannelTurn;
    dispatch: typeof dispatchChannelInboundTurn;
    /** Compatibility escape hatch; prefer `dispatch`, which keeps session wiring in core. */
    dispatchReply: typeof dispatchChannelInboundReply;
  };
  /** @deprecated Compatibility for shipped plugins; use `channel.inbound`. */
  turn: PluginRuntimeChannel$1["inbound"];
  threadBindings: {
    setIdleTimeoutBySessionKeyAsync: (params: Parameters<PluginRuntimeChannel$1["threadBindings"]["setIdleTimeoutBySessionKey"]>[0]) => Promise<RuntimeThreadBindingLifecycleRecord[]>;
    setMaxAgeBySessionKeyAsync: (params: Parameters<PluginRuntimeChannel$1["threadBindings"]["setMaxAgeBySessionKey"]>[0]) => Promise<RuntimeThreadBindingLifecycleRecord[]>;
    /** @deprecated Use setIdleTimeoutBySessionKeyAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
    setIdleTimeoutBySessionKey: (params: {
      channelId: string;
      targetSessionKey: string;
      accountId?: string;
      idleTimeoutMs: number;
    }) => RuntimeThreadBindingLifecycleRecord[];
    /** @deprecated Use setMaxAgeBySessionKeyAsync; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
    setMaxAgeBySessionKey: (params: {
      channelId: string;
      targetSessionKey: string;
      accountId?: string;
      maxAgeMs: number;
    }) => RuntimeThreadBindingLifecycleRecord[];
  };
  runtimeContexts: ChannelRuntimeContextRegistry;
};
//#endregion
//#region src/plugins/runtime/types-session-facts.d.ts
/** Bounded, current session facts for trusted background plugin classifiers. */
type RuntimeSessionFacts = {
  key: string;
  sessionId: string;
  lifecycleRevision?: string;
  agentId: string;
  label?: string;
  derivedTitle?: string;
  lastMessagePreview?: string;
  run: "active" | "idle" | "failed";
  observerDigest?: {
    health: SessionObserverHealth;
    headline: string;
    assessment?: string;
    revision: number;
  };
  pullRequests: Array<{
    number: number;
    state: "open" | "draft" | "merged" | "closed";
    url?: string;
    title?: string;
  }>;
  /** Unknown or stale PR state must not be interpreted as a confirmed empty list. */
  pullRequestsUnavailable?: boolean;
  pullRequestsRateLimited?: true;
  archived: boolean;
  lastActivityAt: number;
};
type RuntimeSessionFactsResult = {
  sessions: RuntimeSessionFacts[];
  warnings?: string[];
};
type RuntimeSessionFactsSelection = Pick<SessionsListParams, "configuredAgentsOnly" | "includeGlobal" | "includeUnknown" | "excludeDock" | "excludeCron" | "excludeSystem" | "archived" | "sortBy" | "activeMinutes" | "agentId" | "involvingMe" | "involvingProfileId" | "includePeople">;
type RuntimeSessionFactsSelectionResult = {
  /** Stable viewer and query identity; only reusable inside the current callback. */
  scope: string | undefined;
  /** Changes when the selected immutable facts, people, or activity deadline change. */
  revision: string;
  sessions: Array<RuntimeSessionFacts & {
    isMain?: boolean;
    unavailable?: string;
    pullRequestsStale?: true;
  }>;
  people?: SessionPerson[];
  activityExpiresAt?: number;
  retryAt?: number;
  /** Selected identities omitted by the current facts owner, distinct from failed reads. */
  missingSessionKeys?: readonly string[];
};
//#endregion
//#region src/plugins/runtime/types.d.ts
type PluginRuntimeChannel = PluginRuntimeChannel$1;
type SubagentRunParams = {
  /** Revalidate command authority at the host's run admission boundary. */
  assertCurrent?: () => void;
  sessionKey: string;
  message: string;
  /** Run with an exact empty tool surface. */
  disableTools?: boolean;
  /** Add exact tools registered by the calling plugin to the worker's normal tool surface. */
  toolsAlsoAllow?: string[];
  provider?: string;
  model?: string;
  extraSystemPrompt?: string;
  /** Use the bounded subagent prompt instead of the full conversation prompt. */
  promptMode?: "minimal";
  lane?: string;
  lightContext?: boolean;
  deliver?: boolean;
  /** Deliver the completion to the authenticated requester of the current hook invocation. */
  completionDelivery?: "current-requester";
  idempotencyKey?: string;
  cwd?: string;
};
type SubagentCompleteParams = {
  agentId: string;
  message: string;
  extraSystemPrompt?: string;
  model?: string;
  timeoutMs?: number;
  signal?: AbortSignal;
};
type PluginManagedWorktree = {
  id: string;
  path: string;
  branch: string;
};
type SubagentRunResult = {
  runId: string;
  /** Canonical accepted session identity. Optional for explicit/custom runtimes. */
  sessionKey?: string;
  runtime?: {
    harness: string;
    provider: string;
    model: string;
  };
};
type SubagentWaitParams = {
  runId: string;
  timeoutMs?: number;
};
type SubagentGetSessionMessagesParams = {
  sessionKey: string;
  limit?: number;
};
type SubagentGetSessionMessagesResult = {
  messages: unknown[];
};
type SubagentDeleteSessionParams = {
  sessionKey: string;
  deleteTranscript?: boolean;
};
type RuntimeNodeListParams = {
  connected?: boolean;
};
type RuntimeNodeListResult = {
  nodes: Array<{
    nodeId: string;
    displayName?: string;
    platform?: string;
    clientId?: string;
    remoteIp?: string;
    connected?: boolean;
    connectedAtMs?: number;
    lastSeenAtMs?: number;
    caps?: string[];
    commands?: string[];
    /** True only for the node host installed alongside this Gateway. */
    gatewayLocal?: boolean;
    /** Advertised commands currently permitted by Gateway node-command policy. */
    invocableCommands?: string[];
    nodePluginTools?: NodePluginToolDescriptor[];
  }>;
};
type RuntimeNodeInvokeParams = {
  nodeId: string;
  command: string;
  params?: unknown;
  timeoutMs?: number;
  idempotencyKey?: string;
  sessionKey?: string;
  /** Cancel the invocation and any work already dispatched to a first-party node. */
  signal?: AbortSignal;
  /** Requested Gateway scopes. Honored only for bundled or trusted official plugins. */
  scopes?: OperatorScope[];
};
/** A lifecycle-bound, complete-message binary channel for one node invocation. */
type RuntimeNodeDuplexChannel = {
  send: (message: Uint8Array) => Promise<void>;
  onMessage: (listener: (message: Uint8Array) => void | Promise<void>) => () => void;
  closed: Promise<unknown>;
  close: () => void;
};
type RuntimeGatewayRequestOptions = {
  timeoutMs?: number;
  /** Cancel this request without extending the current caller or plugin lifetime. */
  signal?: AbortSignal;
  /** Requested Gateway scopes. Honored only for bundled or trusted official plugins. */
  scopes?: OperatorScope[];
  /** Fence an in-process channel send to the exact current requester session incarnation. */
  sessionDeliveryGeneration?: {
    sessionKey: string;
    sessionId: string;
    lifecycleRevision?: string;
  };
};
/** One plugin-written agent message; see `api.runtime.gateway.appendAgentMessage`. */
type RuntimeAgentMessage = {
  sessionKey: string;
  agentId?: string;
  /** Displayed Markdown, normalized like typed chat input; mention spans are UTF-16 offsets into it. */
  text: string;
  /** Spans selecting `@label` text for people to notify; the caller cannot mention themselves. */
  mentions?: ReadonlyArray<{
    profileId: string;
    start: number;
    end: number;
  }>;
  /** Stable per message; a retry replays the same transcript row and Inbox entry. */
  idempotencyKey: string;
};
type RuntimeAgentMessageResult = {
  messageId: string;
  replayed: boolean;
};
/** Trusted in-process runtime surface injected into native plugins. */
type PluginRuntime = PluginRuntimeCore & {
  gateway: {
    /** Whether this process owns an active Gateway request context. */
    isAvailable: () => Promise<boolean>;
    /** Dispatch a Gateway method as the current trusted plugin. */
    request: <T = unknown>(method: string, params?: Record<string, unknown>, options?: RuntimeGatewayRequestOptions) => Promise<T>;
    /** Open this plugin's native panel in the requesting Control UI, preserving caller authority. */
    openPluginPanel: (params: {
      panelId: string;
      sessionKey: string;
      agentId?: string;
    }) => Promise<{
      ok: true;
    }>;
    /** Bounded redacted facts for up to 40 sessions; excludes incognito and rechecks the bound caller/lifecycle. */
    readSessionFacts: (params: {
      sessionKeys: readonly string[];
    }) => Promise<RuntimeSessionFactsResult>;
    /** Select immutable current session facts, retaining caller authority through the consumer. */
    withSessionFacts: <T>(select: RuntimeSessionFactsSelection, run: (snapshot: RuntimeSessionFactsSelectionResult) => Promise<T>) => Promise<T>;
    /**
     * Inside an authenticated RPC handler, add one agent-authored message to a session the
     * caller may write, without a model run. The caller is named as the Inbox sender.
     */
    appendAgentMessage: (params: RuntimeAgentMessage) => Promise<RuntimeAgentMessageResult>;
    /** Keyed fact invalidations; callers own unsubscribe. Broad store changes are excluded. */
    subscribeSessionChanges: (listener: (event: {
      agentId: string;
      sessionKey: string;
      factsInvalidated?: string;
    }) => void) => () => void;
    withUserProfileIdentity?: <T>(params: {
      profileId: string;
      emails: readonly string[];
      githubAccountIds?: readonly number[];
    }, run: (assertCurrent: () => void) => Promise<T>) => Promise<T>;
    /** Resolve public GitHub identity with the Gateway credential; never retry anonymously. */
    resolveGitHubAccount?: (params: {
      login: string;
      signal?: AbortSignal;
    }) => Promise<{
      accountId: number;
      login: string;
      error?: never;
    } | {
      error: {
        statusCode: number;
        message: string;
        retryAtMs?: number;
        credentialConfigured: boolean;
      };
    }>;
  };
  subagent: {
    /** Native collector children; only callable during requester-bound reply_dispatch. */
    native?: NativeSubagentRuntime;
    /** Fresh, tool-free background inference under the existing subagent model policy. */
    complete: (params: SubagentCompleteParams) => Promise<{
      text: string;
    }>;
    /** Ephemeral session-context inference on the session's model, with tool execution denied. */
    forkSession: (params: {
      sessionKey: string;
      message: string;
      signal?: AbortSignal;
      timeoutMs?: number;
    }) => Promise<{
      text: string;
      usage?: LlmCompleteUsage;
    }>;
    run: (params: SubagentRunParams) => Promise<SubagentRunResult>;
    waitForRun: (params: SubagentWaitParams) => Promise<AgentWaitResult>;
    getSessionMessages: (params: SubagentGetSessionMessagesParams) => Promise<SubagentGetSessionMessagesResult>;
    deleteSession: (params: SubagentDeleteSessionParams) => Promise<void>;
  };
  nodes: {
    list: (params?: RuntimeNodeListParams) => Promise<RuntimeNodeListResult>;
    invoke: (params: RuntimeNodeInvokeParams) => Promise<unknown>;
    /** Open a connection-scoped binary node command inside the trusted Gateway runtime. */
    openDuplex: (params: RuntimeNodeInvokeParams & {
      maxMessageBytes?: number;
      maxOutstandingDeliveryBytes?: number;
    }) => Promise<RuntimeNodeDuplexChannel>;
  };
  sandbox: {
    resolveWorkspaceAuthority: (params: {
      config: OpenClawConfig;
      agentId?: string;
      storePath?: string;
      confinedToolNames?: readonly string[];
      requiredToolNames?: readonly string[];
      modelProvider?: string;
      modelId?: string;
      sessionKey: string;
    }) => {
      sandboxed: boolean;
      workspaceAccess: "none" | "ro" | "rw";
      confinementError?: string;
    };
    prepareWorkspaceAuthority: (params: Parameters<PluginRuntime["sandbox"]["resolveWorkspaceAuthority"]>[0] & {
      workspaceDir: string;
    }) => Promise<ReturnType<PluginRuntime["sandbox"]["resolveWorkspaceAuthority"]>>;
  };
  worktrees: {
    resolveCheckoutRoot: (params: {
      path: string;
    }) => Promise<string | undefined>;
    hasSelfContainedCheckoutMetadata?: (params: {
      path: string;
    }) => Promise<boolean>;
    create: (params: {
      repoRoot: string;
      name: string;
      baseRef?: string;
      ownerKind: "workboard";
      ownerId: string;
      commitGuard?: () => void;
    }) => Promise<PluginManagedWorktree>;
    release: (params: {
      path: string;
    }) => Promise<void>;
    removeIfLossless: (params: {
      path: string;
      ownerKind: "workboard";
      ownerId: string;
    }) => Promise<boolean>;
  };
  channel: PluginRuntimeChannel;
};
type CreatePluginRuntimeOptions = {
  dispatchReplyFromConfig?: PluginRuntime["channel"]["reply"]["dispatchReplyFromConfig"];
  gateway?: PluginRuntime["gateway"];
  hooks?: PluginRuntime["hooks"];
  subagent?: PluginRuntime["subagent"];
  nodes?: PluginRuntime["nodes"];
  /** Native policy facades avoid re-evaluating SDK dependencies during registration. */
  modelAuth?: PluginRuntime["modelAuth"];
  modelConfig?: PluginRuntime["modelConfig"];
  allowGatewaySubagentBinding?: boolean;
};
//#endregion
//#region src/plugins/session-catalog.d.ts
type SessionCatalogListProviderParams = {
  /** Gateway always supplies this; optional only for pre-existing external provider types. */
  agentId?: string;
  /** False when Gateway-local scans must not inherit a root from process HOME. */
  allowProcessHomeFallback?: boolean;
  /** Trimmed, non-empty search capped at 500 UTF-16 code units by the gateway. */
  search?: string;
  limitPerHost?: number;
  hostIds?: string[];
  cursors?: Record<string, string>;
  /** Never mutate these entries; release after `list` settles or the list operation closes. */
  sessionEntries?: SessionCatalogEntrySnapshot;
  /** Lazily lists nodes once; release after `list` settles or the list operation closes. */
  listNodes?: () => ReturnType<PluginRuntime["nodes"]["list"]>;
  /** Publishes completed hosts without waiting for slower machines in the same list. */
  onHost?: (host: SessionCatalogHost) => void;
  /** True when the caller accepts retained/pending hosts and later authoritative onHost updates. */
  allowPartialResults?: boolean;
  /** Register host publication before the logical list settles; includes the onHost callback. */
  waitUntil?: (completion: Promise<void>) => void;
  /** Catalog owner retirement, independent of the requesting connection's lifetime. */
  signal?: AbortSignal;
};
type SessionCatalogReadProviderParams = Omit<SessionsCatalogReadParams, "catalogId"> & {
  /** Gateway always supplies this; optional only for pre-existing external provider types. */
  agentId?: string;
  /** False when Gateway-local reads must not inherit a root from process HOME. */
  allowProcessHomeFallback?: boolean;
};
type SessionCatalogContinueProviderParams = Omit<SessionsCatalogContinueParams, "catalogId"> & {
  /** Gateway always supplies this; optional only for pre-existing external provider types. */
  agentId?: string;
  /** False when Gateway-local continuation must not inherit a root from process HOME. */
  allowProcessHomeFallback?: boolean;
  /** Caller's gateway scopes so providers can gate high-authority continues up front. */
  clientScopes?: readonly string[];
};
type SessionCatalogArchiveProviderParams = Omit<SessionsCatalogArchiveParams, "catalogId"> & {
  /** Gateway always supplies this; optional only for pre-existing external provider types. */
  agentId?: string;
  /** False when Gateway-local archive must not inherit a root from process HOME. */
  allowProcessHomeFallback?: boolean;
};
type SessionCatalogStartTerminalProviderParams = {
  /** False when Gateway-local terminal start must not inherit process HOME. */
  allowProcessHomeFallback?: boolean;
  agentId: string;
  cwd: string;
  initialMessage?: string;
  /** Present only when the caller selected a catalog host backed by this node. */
  nodeId?: string;
  /** Selected local catalog source; node ownership is carried by nodeId. */
  hostId?: string;
};
type SessionCatalogTerminalPlan = {
  kind: "local";
  argv: string[];
  cwd?: string;
  title?: string;
  /** Bounded command-specific environment overrides. */
  env?: Record<string, string>;
  /** PATH that resolved argv[0], needed by env-based script interpreters. */
  pathEnv?: string;
} | {
  kind: "node";
  nodeId: string;
  command: string;
  paramsJSON: string;
  cwd?: string;
  title?: string;
  /** Opt in only for native CLI text input, never for a shell receiver. */
  uploadPathStyle?: TerminalUploadPathStyle;
};
type SessionCatalogCreateTarget = {
  model: string;
  /** Concrete runtime pinned onto the created session so config reloads cannot retarget it. */
  agentRuntime: string;
};
interface SessionCatalogEntrySummary {
  sessionKey: string;
  entry: SessionEntry;
}
/** Shared, logically frozen store state for one request; copy locally before mutating. */
type SessionCatalogEntrySnapshot = {
  /** Opaque immutable-entry revision, including config and selection scope. Cache only derived
   * facts by this token; release entry references when the list closes. Not live authority. */
  revision?: object;
  entriesForAgent: (agentId: string) => readonly SessionCatalogEntrySummary[];
  /** Request-wide flatten; optional for compatibility with pre-flatten plugin hosts. */
  entriesForCatalog?: () => SessionCatalogAgentEntry[];
};
type SessionCatalogAgentEntry = SessionCatalogEntrySummary & {
  agentId: string;
};
type SessionUpstreamProbe = {
  sessionKey: string;
  agentId: string;
  threadId: string;
  hostId: string;
  upstreamKind: SessionUpstreamKind;
  upstreamRef: PluginJsonValue;
  marker: PluginJsonValue | null;
  ownRecentUserTexts: string[];
};
declare function normalizeUserText(text: string): string;
declare function isExternalUserText(probe: SessionUpstreamProbe, text: string | undefined): boolean;
type SessionUpstreamActivity = {
  kind: "activity";
  sessionKey: string;
  humanTurns: number;
  nextMarker: PluginJsonValue;
  occurredAt?: number;
  dedupeId?: string;
} | {
  kind: "missing";
  sessionKey: string;
};
type SessionCatalogContinueProviderResult = {
  sessionKey: string;
  /** Plugin binding installed for this authenticated Control UI session. */
  conversationBinding?: {
    summary?: string;
    detachHint?: string;
    data?: Record<string, unknown>;
  };
  /** Publishes provider state only after the requested binding is durable. */
  afterConversationBound?: () => Promise<void>;
  /** Upstream link seed so the monitor can detect direct external activity. */
  upstream?: {
    kind: SessionUpstreamKind;
    ref: PluginJsonValue;
    marker: PluginJsonValue;
  };
};
type SessionCatalogProvider = {
  id: string;
  label: string;
  /** Gateway artifacts are shared with all operators; remote publications follow session-viewing roles. */
  audience?: "gateway-operators" | "session-viewers";
  /** Source authorization must be refreshed before reusing a previous list snapshot. */
  requiresFreshList?: true;
  /** Closed plugin-owned route contract; invalid or colliding declarations are not projected. */
  shareRoute?: SessionCatalogShareRoute;
  /** Declares that every HOME-sensitive action honors the host isolation policy. */
  supportsProcessHomeIsolation?: true;
  /** Config-derived target; the Gateway memoizes it for one runtime-config object identity. */
  resolveCreateSession?: (params: {
    /** Agent whose model/runtime policy must authorize the catalog target. */
    agentId?: string;
  }) => SessionCatalogCreateTarget | undefined;
  list: (params: SessionCatalogListProviderParams) => Promise<SessionCatalogHost[]>;
  /** Optional inert factory; each settled step leaves no foreground work running. */
  createListOperation?: (params: SessionCatalogListProviderParams) => {
    next: () => Promise<{
      done: false;
    } | {
      done: true;
      hosts: SessionCatalogHost[];
    }>;
    /** Synchronous cleanup, called once after the last active step settles. */
    close: () => void;
  };
  /** Items are newest-first by source order; nextCursor continues to older items. */
  read: (params: SessionCatalogReadProviderParams) => Promise<SessionsCatalogReadResult>;
  continueSession?: (params: SessionCatalogContinueProviderParams) => Promise<SessionCatalogContinueProviderResult>;
  /** Copy catalog history into a new ordinary Gateway-owned session. */
  copyToGatewaySession?: (params: SessionCatalogContinueProviderParams) => Promise<{
    displayName?: string;
    preferredModel?: string;
  }>;
  checkUpstreamActivity?: (probes: SessionUpstreamProbe[], policy?: {
    allowProcessHomeFallback?: boolean;
  }) => Promise<SessionUpstreamActivity[]>;
  archive?: (params: SessionCatalogArchiveProviderParams) => Promise<{
    ok: true;
  }>;
  openTerminal?: (request: {
    allowProcessHomeFallback?: boolean;
    /** Gateway always supplies this; optional only for pre-existing external provider types. */
    agentId?: string;
    hostId: string;
    threadId: string;
    sourceHomeId?: string;
  }) => Promise<SessionCatalogTerminalPlan>;
  startTerminalSession?: (request: SessionCatalogStartTerminalProviderParams) => Promise<SessionCatalogTerminalPlan>;
};
declare function listSessionCatalogEntries(params: {
  agentId?: string;
  config: OpenClawConfig;
  runtime: PluginRuntime;
  sessionEntries?: SessionCatalogEntrySnapshot;
}): SessionCatalogAgentEntry[];
declare function sessionCatalogAdoptedSourceKey(hostId: string, threadId: string): string;
declare function sessionCatalogAdoptedSessionKey(prefix: string, source: string): string;
declare function listAdoptedSessionCatalogSessions(params: {
  agentId?: string;
  config: OpenClawConfig;
  pluginId: string;
  runtime: PluginRuntime;
  sessionEntries?: SessionCatalogEntrySnapshot;
  sourceFromEntry: (entry: SessionEntry) => {
    hostId: string;
    threadId: string;
  } | undefined;
}): Map<string, string>;
declare function createSessionCatalogAdoptionCoordinator<TResult extends {
  sessionKey: string;
}>(): (params: {
  sourceKey: string;
  findExisting: () => string | undefined | Promise<string | undefined>;
  create: () => Promise<{
    sessionKey: string;
  }>;
  complete: (continued: {
    sessionKey: string;
  }) => Promise<TResult>;
}) => Promise<TResult>;
//#endregion
//#region src/agents/admitted-run-operator-authority.types.d.ts
type AdmittedRunOperatorAuthority = Readonly<{
  profileId: string;
  /** Host-captured original input; claim/occurrence owners revalidate it for continuations. */
  recoverySnapshot?: OperatorRunRecoverySnapshot;
  /** Existing immutable policy and link; accepted-input owners may retain them for recovery. */
  channelRecoverySource?: Readonly<{
    reference: UserChannelAuthorizationReference;
    modelPolicy?: PreparedOperatorModelPolicy;
  }>;
  scopes: readonly string[];
  /** Original access dependency; null is proven independent, undefined is unclassified. */
  gatewayAccessGrant?: GatewayAccessGrantRef | null;
  assertCurrent: SessionSourceAssertion;
  signal?: AbortSignal;
  /** Opaque original source identity used only to compare compatible queued input. */
  source?: object;
  /** Retains the original source independently of a foreground run or request. */
  retain?: () => () => void;
  /** Assignment and verified login from one check of the original live profile authority. */
  readCurrentRoleFacts?: (this: void) => Readonly<{
    assignedRole: string | null;
    githubLogin?: string | null;
  }>;
  /** Prepared role permissions; source-policy changes revoke the owning authority. */
  rolePolicy?: Readonly<{
    sessionAccessCap: GatewayOperatorRoleDefinition["sessions"]["others"];
    sandboxRequired: boolean;
    agents: "*" | readonly string[];
    accessPrograms?: Readonly<{
      cyber: ReadonlyArray<NonNullable<GatewayOperatorRoleDefinition["accessPrograms"]>["cyber"][number]>;
    }>;
  }>;
  modelPolicy?: PreparedOperatorModelPolicy;
  /** Committed policy changes invalidate only executions using a removed model. */
  onModelPolicyChanged?: (listener: () => void) => () => void;
}>;
//#endregion
//#region src/agents/admitted-run-context.d.ts
/** Exact context carried by one admitted execution and every retry/fallback it owns. */
type AdmittedRunContext = Readonly<{
  operationalRunInstance: OperationalRunInstanceRef;
  /** Scheduler-authored ingress authority, independent of optional audit collection. */
  admissionSource?: "operator-schedule" | "requester-schedule";
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
}>;
type PreparedAgentRunAdmission = Readonly<{
  operationalRunInstance: OperationalRunInstanceRef;
  /** Exact post-prepare owner; repeated fallback/retry returns the same object. */
  admit: (runtimeKind: ExecutionIdentityAdmissionFacts["runtime"]["kind"], runtimeInstanceId?: string) => Promise<AdmittedRunContext>;
  /** Checks latched source revocation after normal close; never grants execution authority. */
  assertSourceCurrent: () => void;
  /** Host-only source restriction available before the runtime prepares its tools. */
  readOperatorAuthority?: () => AdmittedRunOperatorAuthority | undefined;
  /** Idempotently closes the exact delegated approval lease, if admission occurred. */
  close: () => void;
}>;
//#endregion
//#region src/auto-reply/command-owner-authority.d.ts
type CommandOwnerAssertion = (() => void) & {
  readonly recoveryReference?: CommandOwnerReference | null;
};
//#endregion
//#region src/auto-reply/reply-payload.d.ts
type ReplyMediaFailureCode = "file-not-found" | "unsupported-format" | "delivery-failed" | "invalid-reference";
/** Producer-owned outcome for one attachment that could not be delivered. */
type ReplyMediaFailure = {
  code: ReplyMediaFailureCode;
  kind: "image" | "audio" | "video" | "document";
  label: string;
  mimeType?: string;
};
declare function readAskUserQuestionId(payload: Pick<ReplyPayload$1, "channelData">): string | undefined;
declare const FAST_MODE_AUTO_PROGRESS_KIND = "fast-mode-auto";
declare function isFastModeAutoProgressPayload(payload: Pick<ReplyPayload$1, "channelData">): boolean;
/** Reply policy facts that provider adapters use to resolve the final transport route. */
type ReplyDeliveryContext = {
  chatType?: "direct" | "group" | "channel" | null;
  replyToMode: ReplyToMode;
};
/** Returns normalized TTS supplement metadata only when the payload has media to carry it. */
declare function getReplyPayloadTtsSupplement(payload: Pick<ReplyPayload$1, "mediaUrl" | "mediaUrls" | "ttsSupplement">): ReplyPayloadTtsSupplement | undefined;
declare function isReplyPayloadTtsSupplement(payload: Pick<ReplyPayload$1, "mediaUrl" | "mediaUrls" | "ttsSupplement">): boolean;
/** Marks a reply payload as supplemental TTS media while preserving the original shape. */
declare function markReplyPayloadAsTtsSupplement<T extends ReplyPayload$1>(payload: T, spokenText?: string, options?: {
  visibleTextAlreadyDelivered?: boolean;
}): T;
/** Removes visible-only fields from a payload that should be delivered as TTS supplement media. */
declare function buildTtsSupplementMediaPayload(payload: ReplyPayload$1): ReplyPayload$1;
/** WeakMap-backed metadata attached to payload objects without changing wire shape. */
type SessionWriterDeliveryAuthority = {
  agentId?: string;
  /** Current facts from the original actor or its receipt-backed delivery preparation. */
  readCurrentSession?: () => {
    sessionId: string;
    lifecycleRevision?: string;
    activeWriterRunId?: string;
  } | undefined;
  expectedLifecycleRevision?: string;
  expectedSessionId: string;
  expectedWriterRunId?: string;
  sessionKey: string;
  storePath?: string;
};
/** Remove only recorded normalization decoration when appending a preview chunk. */
declare function stripReplyPayloadResponsePrefix(payload: object, text: string): string;
declare function isReplyPayloadNonTerminalToolErrorWarning(payload: object): boolean;
declare function copyReplyPayloadMetadata<T extends object>(source: object, payload: T): T;
/** Host-generated errors, warnings, status lines and run labels; never the model's answer. */
declare function isHostNoticePayload(payload: ReplyPayload$1): boolean;
/** Classifies terminal vs. supplemental reply lanes, not content, sendability, or authority. */
declare const isReplyPayloadTerminalContent: (payload: ReplyPayload$1) => boolean;
//#endregion
//#region src/auto-reply/reply/typing.d.ts
type TypingController = {
  onReplyStart: () => Promise<void>;
  startTypingLoop: () => Promise<void>;
  startTypingOnText: (text?: string) => Promise<void>;
  refreshTypingTtl: () => void;
  isActive: () => boolean;
  markRunComplete: () => void;
  markDispatchIdle: () => void;
  cleanup: () => void;
};
//#endregion
//#region src/auto-reply/get-reply-options.types.d.ts
/** An accepted visible work session and its canonical Control UI link. */
type VisibleWorkSession = {
  sessionKey: string;
  url: string;
  label?: string;
  publicRead?: boolean;
};
/** A successful runtime append, independent of optional active-path projection anchors. */
type ReplyDispatchAssistantTranscript = Pick<TranscriptEntryAnchor, "agentId" | "sessionId" | "sessionKey" | "storePath"> & {
  messageId: string;
  anchor?: TranscriptEntryAnchor;
  idempotencyKey: string;
};
type ReplyDispatchRun = {
  completionSource: "reply-dispatch";
  getResult: () => {
    assistantTranscript?: ReplyDispatchAssistantTranscript;
    terminalOutcome?: AgentRunTerminalOutcome$1;
  };
};
/** Prepared transcript boundary; current run and writer authority remain caller-owned. */
type PreparedReplyTranscriptStart = {
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
  generation: string | null;
  maxSeq: number | null;
};
/** Run-start notification after the runtime has prepared its transcript boundary. */
type PreparedAgentRunStart = {
  runId: string;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  options?: ReplyDispatchRun;
  transcriptStart: PreparedReplyTranscriptStart | null;
};
type BlockReplyContext = {
  abortSignal?: AbortSignal;
  timeoutMs?: number;
  /** Source assistant message index from the upstream stream, when available. */
  assistantMessageIndex?: number;
  /** @internal Stable durable outbound intent owned by the producing runtime. */
  deliveryIntentId?: string;
};
/** Typing indicator class for channel-owned UX policy. */
type TypingPolicy = "auto" | "user_message" | "system_event" | "internal_webchat";
/** Per-turn policy for source-message reply threading. */
type ReplyThreadingPolicy = {
  /** Override implicit reply-to-current behavior for the current turn. */
  implicitCurrentMessage?: "default" | "allow" | "deny";
};
/** Action sink available for model-proposed follow-up tasks during this turn. */
type TaskSuggestionDeliveryMode = "gateway";
/** Correlates queued reply ownership transfer with later delivery drains. */
type QueuedReplyDeliveryCorrelation = {
  /** Source-owned suppression for origin-routed replies that bypass the dispatcher.
   * A collected batch is suppressed only when all participating policies agree. */
  shouldSuppressReply?: (payload: ReplyPayload$1) => boolean;
  /** Called only after the origin transport confirms visible delivery. */
  onReplyDelivered?: (payload: ReplyPayload$1) => void;
  /** No settlement means a source retry or a separate source-owned delivery outcome. */
  begin: () => ((settlement?: {
    visibleReplySent: boolean;
    failed: boolean;
    /** True only for a successfully completed execution, not cancellation. */
    completed?: boolean;
    /** Transport retained delivery without a callback to this source; clear activity UI. */
    transportPending?: boolean;
  }) => void) | void;
};
type QueuedFollowupReplyBatch = {
  kind: "queued-followup";
  runId: string;
  originatingChannel: string | undefined;
  payloads: ReplyPayload$1[];
  completion: {
    kind: "progress";
  } | {
    kind: "completed";
    stopReason?: string;
    allowCanvasOnly?: true;
  } | {
    kind: "failed";
    error: string;
    stopReason?: string;
    errorKind?: "timeout";
  } | {
    kind: "aborted";
    stopReason?: string;
  };
};
type QueuedFollowupReplyDelivery = ((batch: QueuedFollowupReplyBatch) => Promise<void> | void) & {
  ownsCompletion?: (originatingChannel: string | undefined) => boolean;
  createSourceRetry?: () => QueuedFollowupReplyDelivery;
};
/**
 * Exclusive: each lifecycle is its own collect-admission identity.
 * Cancel-only: share collect identity via ownerKey (gateway chat.send).
 */
type TurnAdoptionAdmission = "exclusive" | "cancel-only";
/**
 * Canonical turn-ownership lifecycle (adopt / defer / abandon / settle).
 * Single surface for durable ingress, gateway cancel identity, and reply-lane transfer.
 */
type TurnAdoptionLifecycle = {
  /**
   * Admission isolation mode (closed). Exclusive isolates collect identity per
   * lifecycle; cancel-only shares via ownerKey. Never inferred from onAbandoned.
   * Durable ingress sets exclusive; gateway cancel identity sets cancel-only.
   */
  admission?: TurnAdoptionAdmission;
  /** Transcript branch leaf from which this turn was admitted. */
  originatingLeafEntryId?: string | null;
  onAdopted: () => void | Promise<void>;
  /** Return false to reject followup enqueue. */
  onDeferred?: () => boolean | void;
  /** Pre-adoption liveness while waiting for reply-lane admission or preflight compaction. */
  onDeferredHeartbeat?: () => void;
  /** Requested cadence for pre-adoption heartbeats. */
  deferredHeartbeatIntervalMs?: number;
  /** Deferred turn finished without owning the reply lane. */
  onAbandoned?: () => void | Promise<void>;
  /** Always fires when the followup ownership cycle ends (admitted or not). Gateway cleanup. */
  onSettled?: () => void | Promise<void>;
  /** Retires cancellation ownership while retaining live identity. */
  onCancellationRetired?: () => void;
  /** Stable cancellation owner for collect-mode batches. */
  ownerKey?: string;
  abortSignal?: AbortSignal;
  /** Ephemeral fact: a direct local operator turn lost fresh cron authority when queued. */
  cronCreatorAuthorityUnavailable?: "queued-local-operator";
};
/** Partial assistant payload emitted during streaming or replacement updates. */
type PartialReplyPayload = {
  /**
   * Sanitized text, which may be an enumerable memoized getter. Content materializes on first
   * read: direct-delivery consumers pay per partial, while throttled consumers pay per flush.
   */
  text?: ReplyPayload$1["text"];
  mediaUrls?: ReplyPayload$1["mediaUrls"];
  delta?: string;
  replace?: true;
};
type ReasoningStreamPayload = Pick<ReplyPayload$1, "text" | "mediaUrls" | "isReasoning" | "isReasoningSnapshot"> & {
  requiresReasoningProgressOptIn?: boolean;
};
/** Return false until the channel has accepted operator-visible progress. */
type ProgressCallbackResult = boolean | void;
/** Reply generation options shared by auto-reply, webchat, channels, and tests. */
type GetReplyOptions = {
  /** Host-issued capability for the exact findings acknowledged by the current operator. */
  providerReviewAcknowledgment?: ProviderReviewAcknowledgment;
  /** Channel-owned participant name encoding for source replies sent through message actions. */
  groupThreadReplyFormatter?: (text: string, participant: {
    agentId: string;
    name: string;
  }) => string;
  /** Override run id for agent events (defaults to random UUID). */
  runId?: string;
  /** Stable provider prompt-cache affinity key; distinct from run id/idempotency. */
  promptCacheKey?: string;
  /** Abort signal for the underlying agent run. */
  abortSignal?: AbortSignal;
  /** Ephemeral channel owner check for a targeted Stop; never serialized as authority. */
  isCommandTargetCurrent?: SessionSourceCheck | AsyncSessionSourceCheck;
  /** Optional inbound images (used for webchat attachments). */
  images?: ImageContent$1[];
  /** Original inline/offloaded attachment order for inbound images. */
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered media facts whose model-facing text projection is already present in the prompt. */
  media?: MediaFact[];
  /** Return "reply-dispatch" synchronously to accept the offered completion ownership. */
  onPreparedAgentRunStart?: (start: PreparedAgentRunStart) => unknown;
  /**
   * @deprecated Use onPreparedAgentRunStart with a prepared transcript boundary. Supported through 2026-12-31. Removal in the first January 2027 stable release.
   * Notifies when an agent run starts. Return "reply-dispatch" synchronously to accept
   * completion ownership offered in options; all other legacy callback results are ignored.
   */
  onAgentRunStart?: (runId: string, executionIdentityToken?: ExecutionIdentityAdmissionToken, options?: ReplyDispatchRun, transcriptStart?: PreparedReplyTranscriptStart | null) => unknown;
  /** Reports the terminal agent-run classification to the shared dispatch owner. */
  onAgentRunTerminalOutcome?: (outcome: "completed" | "failed") => void;
  /** Retains source-owned delivery when this turn is queued behind an active run. */
  onQueuedFollowupReplyBatch?: QueuedFollowupReplyDelivery;
  /** Reports terminal queue-cap rejection or eviction when no agent run will report an outcome. */
  onFollowupQueueDisposition?: (disposition: "queue-cap" | "queue-cap-old" | "queue-cap-new") => void;
  /**
   * Reports fresh visible children before their first turn and accepted spawns at settlement.
   * Creation reports include the key even when no public session URL is configured.
   * Awaited before child dispatch; a child may be reported again at settlement.
   */
  onVisibleWorkSessions?: (sessions: readonly VisibleWorkSession[], creation?: {
    createdSessionKey: string;
  }) => void | Promise<void>;
  /**
   * Canonical adoption lifecycle (adopted / deferred / abandoned / settled + pre-adoption abort).
   */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
  /** Shared lifecycle owner for the current user-turn transcript append. */
  userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
  /** Gateway-owned start-or-steer decision for this turn. */
  messageInjectionDisposition?: "none" | "accepted" | "rejected" | "collaborative-steering-disabled";
  /** Current user turn is already durable; replay it without appending another copy. */
  suppressNextUserMessagePersistence?: boolean;
  onReplyStart?: () => Promise<void> | void;
  /** Called when the typing controller cleans up (e.g., run ended with NO_REPLY). */
  onTypingCleanup?: () => void;
  onTypingController?: (typing: TypingController) => void;
  /** If false, send only the initial typing signal without periodic keepalive refreshes. */
  typingKeepalive?: boolean;
  /** Policy-level typing control for run classes (user/system/internal). */
  typingPolicy?: TypingPolicy;
  /** Force-disable typing indicators for this run (system/internal/cross-channel routes). */
  suppressTyping?: boolean;
  /** One-shot thinking level override for this run; does not persist to the session. */
  thinkingLevelOverride?: string;
  /** One-shot fast-mode override for this run; does not persist to the session. */
  fastModeOverride?: FastMode;
  /** One-shot auto fast-mode cutoff override in seconds; does not persist to the session. */
  fastModeAutoOnSecondsOverride?: number;
  /** Controls bootstrap workspace context injection (default: full). */
  bootstrapContextMode?: "full" | "lightweight";
  /** If true, run the model without OpenClaw tools for this turn. */
  disableTools?: boolean;
  /** Runtime tool allow-list for this turn. Empty means no tools. */
  toolsAllow?: string[];
  /**
   * @deprecated Ignored. The tool-failure warning is delivered whenever a run ends
   * without a reply and cannot be suppressed. Kept only so plugin-sdk callers that
   * still pass it keep compiling; removed in the first stable release after 2026.10.
   */
  suppressToolErrorWarnings?: boolean;
  /**
   * If true, dispatch skips default tool/progress text messages and expects the
   * channel to surface progress via its own streaming/edit UX.
   */
  suppressDefaultToolProgressMessages?: boolean;
  /** Keep automatic progress private for turns whose canonical reply expectation is optional. */
  progressRequiresReply?: boolean;
  /** Suppress standalone tool/progress text even when verbose progress is enabled. */
  suppressToolProgressMessages?: boolean;
  /** Allow channel-owned tool lifecycle feedback while text progress remains hidden. */
  allowToolLifecycleWhenProgressHidden?: boolean;
  /**
   * Called before dispatch with a live getter for whether verbose standalone
   * progress messages are active for this run. Channels that render tool or
   * commentary progress inside an ephemeral streaming draft should yield those
   * draft lines while the getter returns true, so progress is not rendered in
   * both lanes at once.
   * @deprecated Use onVerboseProgressVisibilityAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release.
   */
  onVerboseProgressVisibility?: (isActive: () => boolean) => void;
  /** Registers awaited visibility before dispatch; preferred over the deprecated callback. */
  onVerboseProgressVisibilityAsync?: (isActive: () => Promise<boolean>) => Promise<void> | void;
  /** Preserve source-event callback start order for stateful channel progress renderers. */
  preserveProgressCallbackStartOrder?: boolean;
  onPartialReply?: (payload: PartialReplyPayload) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onReasoningStream?: (payload: ReasoningStreamPayload) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onReasoningProgress?: (payload: {
    progressTokens: number;
  }) => Promise<void> | void;
  streamReasoningInNonStreamModes?: boolean;
  /** Called when a thinking/reasoning block ends. */
  onReasoningEnd?: () => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when a new assistant message starts (e.g., after tool call or thinking block). */
  onAssistantMessageStart?: () => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called synchronously when a block reply is logically emitted, before async
   * delivery drains. Useful for channels that need to rotate preview state at
   * block boundaries without waiting for transport acks. */
  onBlockReplyQueued?: (payload: ReplyPayload$1, context?: BlockReplyContext) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onBlockReply?: (payload: ReplyPayload$1, context?: BlockReplyContext) => Promise<void> | void;
  /** Receives a block whose producer has already resolved inline directives. */
  onPreparedBlockReply?: (plan: OutboundPayloadPlan, context?: BlockReplyContext) => Promise<void> | void;
  onToolResult?: (payload: ReplyPayload$1) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when a tool phase starts/updates, before summary payloads are emitted. */
  onToolStart?: (payload: {
    itemId?: string;
    toolCallId?: string;
    name?: string;
    phase?: string;
    args?: Record<string, unknown>;
    detailMode?: "explain" | "raw";
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when a concrete work item starts, updates, or completes. */
  onItemEvent?: (payload: {
    itemId?: string;
    toolCallId?: string;
    kind?: string;
    title?: string;
    name?: string;
    phase?: string;
    status?: string;
    summary?: string;
    progressText?: string;
    meta?: string;
    commandBearing?: boolean;
    approvalId?: string;
    approvalSlug?: string;
    suppressDurableProgress?: true;
    hideFromChannelProgress?: boolean;
    suppressChannelProgress?: boolean;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /**
   * Called when the utility-model narration of the in-progress turn changes.
   * Providing this callback opts the channel into progress narration; core
   * only generates narration when a utility model resolves (explicit
   * config or the provider-declared default; utilityModel: "" disables).
   * An empty text clears narration; a retained model preamble still wins before
   * the channel falls back to raw tool progress.
   */
  onNarrationUpdate?: (payload: {
    text: string;
  }) => Promise<void> | void;
  /** Channel-owned final and queued-turn boundaries for the current narrator. */
  onProgressNarratorLifecycle?: (lifecycle: {
    beginTurn: () => void;
    stopTurn: () => void;
  }) => void;
  /** False while utility-model narration has no visible progress draft. */
  isProgressDraftVisible?: () => boolean;
  /**
   * Omit exec/bash command text from narration model input, mirroring the
   * channel's `streaming.progress.commandText: "status"` display policy so
   * narration never receives more command detail than the draft shows.
   */
  narrationHideCommandText?: boolean;
  /** In progress mode, classify Claude pre-tool text; true also renders it as commentary. */
  commentaryProgressEnabled?: boolean;
  /** Bridge typed preambles to a channel-owned progress headline without commentary. */
  progressPreambleEnabled?: boolean;
  /** Deliver durable reasoning payloads to channels that own a separate reasoning lane. */
  reasoningPayloadsEnabled?: boolean;
  /** Deliver durable commentary (💬) payloads to channels that own a separate commentary lane. */
  commentaryPayloadsEnabled?: boolean;
  /** Optional turn-frozen commentary owner; visibility is live by default.
   * With the static opt-in and this callback, core freezes, evaluates once, and snapshots. */
  shouldDeliverCommentaryPayloads?: () => boolean;
  /** Called when the agent emits a structured plan update. */
  onPlanUpdate?: (payload: {
    phase?: string;
    title?: string;
    explanation?: string;
    /** Prepared literal text; unmarked explanations retain authored Markdown. */
    explanationFormat?: "plain";
    steps?: AgentPlanStep[];
    source?: string;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when an approval becomes pending or resolves. */
  onApprovalEvent?: (payload: Partial<Omit<AgentApprovalEventData, "phase" | "kind" | "status">> & {
    phase?: string;
    kind?: string;
    status?: string;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when command output streams or completes. */
  onCommandOutput?: (payload: Partial<Omit<AgentCommandOutputEventFields, "phase" | "status">> & {
    phase?: string;
    status?: string;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when a patch completes with a file summary. */
  onPatchSummary?: (payload: {
    itemId?: string;
    phase?: string;
    title?: string;
    toolCallId?: string;
    name?: string;
    added?: string[];
    modified?: string[];
    deleted?: string[];
    summary?: string;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when context auto-compaction starts (allows UX feedback during the pause). */
  onCompactionStart?: () => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when context auto-compaction ends; omitted outcome means completed for legacy callers. */
  onCompactionEnd?: (payload?: {
    completed: boolean;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when the actual model is selected (including after fallback).
   * Use this to get model/provider/thinkLevel for responsePrefix template interpolation. */
  /** Context passed to onModelSelected callback with actual model used. */
  onModelSelected?: (ctx: {
    provider: string;
    model: string;
    thinkLevel: string | undefined;
  }) => void;
  /**
   * Controls whether normal assistant replies are automatically delivered to
   * the source conversation. `message_tool_only` prefers message-tool visible
   * delivery and keeps normal final text, block output, and preview output
   * private unless dispatch explicitly marks a source reply as deliverable.
   */
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  /** Enables task-suggestion tools only when the initiating surface can action Gateway events. */
  taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  /** Starts delivery tracking when this turn later drains as a queued followup. */
  queuedDeliveryCorrelations?: QueuedReplyDeliveryCorrelation[];
  /** Called after a queued followup owns the reply lane, before its model run starts. */
  onQueuedFollowupAdmitted?: () => Promise<void> | void;
  /** Called after an admitted queued followup finishes, including failed attempts. */
  onQueuedFollowupSettled?: () => Promise<void> | void;
  /** Allow channel-owned progress UI while final/source reply delivery remains message-tool-only. */
  allowProgressCallbacksWhenSourceDeliverySuppressed?: boolean;
  /** Called when a suppressed source reply mode observes visible delivery through another path. */
  onObservedReplyDelivery?: () => Promise<void> | void;
  /** Emit tool result summaries for channel-owned progress UI even when verbose is off. */
  forceToolResultProgress?: boolean;
  disableBlockStreaming?: boolean;
  /** Timeout for block reply delivery (ms). */
  blockReplyTimeoutMs?: number;
  /** If provided, only load these skills for this session (empty = no skills). */
  skillFilter?: string[];
  /** Mutable ref to track if a reply was sent (for Slack "first" threading mode). */
  hasRepliedRef?: {
    value: boolean;
  };
  /** Override agent timeout in seconds (0 = no timeout). Threads through to resolveAgentTimeoutMs. */
  timeoutOverrideSeconds?: number;
  /** Millisecond run timeout override; takes precedence over seconds (0 = no timeout). */
  timeoutOverrideMs?: number;
};
//#endregion
//#region src/auto-reply/templating.d.ts
/** Valid message channels for routing. */
type OriginatingChannelType = string & {
  readonly __originatingChannelBrand?: never;
};
type MentionSource = "explicit_bot" | "subteam" | "mention_pattern" | "implicit_thread" | "command_bypass" | "none";
type InboundSourceModality = "text" | "voice" | "audio" | "image" | "video" | "document";
type StickerContextMetadata = {
  cachedDescription?: string;
  emoji?: string;
  setName?: string;
  description?: string;
  fileId?: string;
  fileUniqueId?: string;
  uniqueFileId?: string;
  isAnimated?: boolean;
  isVideo?: boolean;
} & Record<string, unknown>;
type ChannelStructuredContextEntry = {
  label: string;
  source?: string;
  type?: string;
  payload: unknown;
  /** Keeps this provider-owned window independent of bounded canonical transcript enrichment. */
  sessionTranscriptMode?: "preserve";
  /** Internal exact-id hints for canonical transcript/live-cache deduplication. */
  sessionTranscriptDedupeMessageIds?: string[];
  /** Internal visible-text hints for legacy assistant rows without transcript ids. */
  sessionTranscriptAssistantTextDedupeKeys?: string[];
};
type SessionTranscriptContext = {
  chatWindow?: boolean;
  historyLimit: number;
  /** A platform-selected recent window keeps its configured bound and does not merge transcript rows. */
  historyKind?: "pending" | "recent";
  beforeTimestampMs?: number;
  minTimestampMs?: number;
  senderLabels?: {
    assistant: string;
    user: string;
  };
};
/** @deprecated Use ChannelStructuredContextEntry. Removal: after 2026-09-08 (see sdk-untrusted-context-identifier-aliases). */
type UntrustedStructuredContextEntry = ChannelStructuredContextEntry;
/** Structured supplemental facts projected into prompt context by inbound finalization. */
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;
  };
  channelStructuredContext?: ChannelStructuredContextEntry[];
  /** @deprecated Use channelStructuredContext. Removal: after 2026-09-08 (see sdk-untrusted-context-identifier-aliases). */
  untrustedContext?: ChannelStructuredContextEntry[];
  groupSystemPrompt?: string;
  /** Prompt-like group metadata from user-controlled sources; never enters the system prompt. */
  untrustedGroupSystemPrompt?: string;
};
/** Canonical normalized inbound text populated once by `finalizeInboundContext`. */
type CanonicalInboundText = {
  /** Clean text used for command and directive parsing. */
  commandText: string;
  /** Prompt-facing text used for the agent turn. */
  agentText: string;
  /** Normalized visible/raw inbound text before command-specific projection. */
  rawText: string;
};
/** Raw inbound message context accepted from channels before finalization. */
type MsgContext = Partial<CanonicalInboundText> & {
  Body?: string;
  InboundEventKind?: InboundEventKind;
  /**
   * Agent prompt body (may include envelope/history/context). Prefer this for prompt shaping.
   * Should use real newlines (`\n`), not escaped `\\n`.
   */
  BodyForAgent?: string;
  /**
   * Recent chat history for context (untrusted user content). Prefer passing this
   * as structured context blocks in the user prompt rather than rendering plaintext envelopes.
   */
  InboundHistory?: HistoryEntry[];
  /** Internal facts used to merge canonical transcript turns before dispatch. */
  SessionTranscriptContext?: SessionTranscriptContext;
  /**
   * @deprecated Use CommandBody.
   *
   * Raw message body without structural context (history, sender labels).
   * Legacy alias for CommandBody. Falls back to Body if not set.
   */
  RawBody?: string;
  /**
   * Prefer for command detection; RawBody is treated as legacy alias.
   */
  CommandBody?: string;
  /**
   * Command parsing body. Prefer this over CommandBody/RawBody when set.
   * Should be the "clean" text (no history/sender context).
   */
  BodyForCommands?: string;
  CommandArgs?: CommandArgs;
  From?: string;
  To?: string;
  SessionKey?: string;
  /**
   * Resolved agent scope for canonical session keys that do not encode the agent
   * id, such as selected-agent global sessions.
   */
  AgentId?: string;
  /** Participant mention facts prepared once from the physical inbound message. */
  GroupThread?: GroupThreadMentionFacts;
  /** Effective routed DM scope, including binding overrides. */
  DmScope?: DmScope;
  /**
   * Session-like key used for runtime policy (sandbox/tool policy) when the
   * conversation key intentionally remains broader, such as a main-session DM.
   */
  RuntimePolicySessionKey?: string;
  /** Provider account id (multi-account). */
  AccountId?: string;
  ParentSessionKey?: string;
  /**
   * Session key used only for inheriting session-scoped model/provider
   * overrides. Unlike ParentSessionKey, this must not trigger transcript
   * forking or parent-session lifecycle behavior.
   */
  ModelParentSessionKey?: string;
  MessageSid?: string;
  /** Provider-specific full message id when MessageSid is a shortened alias. */
  MessageSidFull?: string;
  MessageSids?: string[];
  MessageSidFirst?: string;
  MessageSidLast?: string;
  AmbientTranscriptWatermarkKey?: string;
  AmbientTranscriptBody?: string;
  AmbientTranscriptMessageId?: string;
  AmbientTranscriptTimestampMs?: number;
  AmbientTranscriptPreviousMessageId?: string;
  AmbientTranscriptPreviousTimestampMs?: number;
  /** Per-turn reply-threading overrides. */
  ReplyThreading?: ReplyThreadingPolicy;
  /** Effective channel reply mode prepared for this turn. */
  ReplyToMode?: ReplyToMode;
  ReplyToId?: string;
  /**
   * Root message id for thread reconstruction (used by Feishu for root_id).
   * When a message is part of a thread, this is the id of the first message.
   */
  RootMessageId?: string;
  /** Provider-specific full reply-to id when ReplyToId is a shortened alias. */
  ReplyToIdFull?: string;
  ReplyToBody?: string;
  ReplyToQuoteText?: string;
  ReplyToSender?: string;
  ReplyChain?: Array<{
    messageId?: string;
    threadId?: string;
    sender?: string;
    senderId?: string;
    senderUsername?: string;
    timestamp?: number;
    body?: string;
    isQuote?: boolean;
    mediaType?: string;
    mediaPath?: string;
    mediaRef?: string;
    replyToId?: string;
    forwardedFrom?: string;
    forwardedFromId?: string;
    forwardedFromUsername?: string;
    forwardedDate?: number;
  }>;
  ReplyToIsQuote?: boolean;
  /** Forward origin from the reply target (when reply_to_message is a forwarded message). */
  ReplyToForwardedFrom?: string;
  ReplyToForwardedFromType?: string;
  ReplyToForwardedFromId?: string;
  ReplyToForwardedFromUsername?: string;
  ReplyToForwardedFromTitle?: string;
  ReplyToForwardedDate?: number;
  ForwardedFrom?: string;
  ForwardedFromType?: string;
  ForwardedFromId?: string;
  ForwardedFromUsername?: string;
  ForwardedFromTitle?: string;
  ForwardedFromSignature?: string;
  ForwardedFromChatType?: string;
  ForwardedFromMessageId?: number;
  ForwardedDate?: number;
  ThreadStarterBody?: string;
  /** Full thread history when starting a new thread session. */
  ThreadHistoryBody?: string;
  IsFirstThreadTurn?: boolean;
  ThreadLabel?: string;
  /** @deprecated Use `media?.[0]?.path`. */
  MediaPath?: string;
  /** @deprecated Use `media?.[0]?.url`. */
  MediaUrl?: string;
  /** @deprecated Use `media?.[0]?.contentType` or `.kind`. */
  MediaType?: string;
  /** @deprecated Derive the directory from `media?.[0]?.path` at the consuming boundary. */
  MediaDir?: string;
  /** @deprecated Use `media?.map((entry) => entry.path)`. */
  MediaPaths?: string[];
  /** @deprecated Use `media?.map((entry) => entry.url)`. */
  MediaUrls?: string[];
  /** @deprecated Use `media?.map((entry) => entry.contentType ?? entry.kind)`. */
  MediaTypes?: string[];
  /** Ordered current-turn media facts; array position is attachment identity. */
  media?: MediaFact[];
  /** Original message modality before transcription or other media normalization. */
  SourceModality?: InboundSourceModality;
  /** @deprecated Use each media fact's `workspaceDir`. */
  MediaWorkspaceDir?: string;
  /** Attachment indexes whose audio was already transcribed before media understanding runs. */
  /** @deprecated Use each media fact's `transcribed` field. */
  MediaTranscribedIndexes?: number[];
  /**
   * Marker: skip downstream stageSandboxMedia. chat.send RPC sets this so
   * staging runs synchronously before respond() and surfaces 5xx to the
   * client; any later failure only reaches the broadcast channel.
   */
  /** @deprecated Use each media fact's `workspaceDir` or `staged` proof. */
  MediaStaged?: boolean;
  /** Telegram sticker metadata (emoji, set name, file IDs, cached description). */
  Sticker?: StickerContextMetadata;
  /** True when current-turn sticker media is present in structured facts. */
  StickerMediaIncluded?: boolean;
  /** Skip automatic understanding for the current sticker because its cached description is used. */
  SkipStickerMediaUnderstanding?: boolean;
  OutputDir?: string;
  OutputBase?: string;
  /** Remote host for SCP when media lives on a different machine (e.g., openclaw@192.168.64.3). */
  MediaRemoteHost?: string;
  Transcript?: string;
  MediaUnderstanding?: MediaUnderstandingOutput[];
  MediaUnderstandingDecisions?: MediaUnderstandingDecision[];
  LinkUnderstanding?: string[];
  Prompt?: string;
  MaxChars?: number;
  ChatType?: string;
  /** @deprecated Channel-configured snapshot for the original external request. Use the channel policy resolver; retained until a later stable release after an announced deprecation window and explicit maintainer approval. No removal date is set. */
  ConversationToolPolicy?: GroupToolPolicyConfig;
  /** Human label for envelope headers (conversation label, not sender). */
  ConversationLabel?: string;
  GroupSubject?: string;
  /** Human label for channel-like group conversations (e.g. #general, #support). */
  GroupChannel?: string;
  GroupSpace?: string;
  /** Trusted provider role ids for the sender in this group turn. */
  MemberRoleIds?: string[];
  GroupMembers?: string;
  GroupSystemPrompt?: string;
  /**
   * Canonical inbound supplemental facts for new channel code. `finalizeInboundContext`
   * projects these to the existing flat reply/forward/thread/group prompt fields.
   */
  SupplementalContext?: SupplementalContextFacts;
  /** Channel-provided metadata that must not be treated as system instructions. */
  ChannelPromptContext?: string[];
  /** @deprecated Use ChannelPromptContext. Removal: after 2026-09-08 (see sdk-untrusted-context-identifier-aliases). */
  UntrustedContext?: string[];
  /** Structured channel metadata rendered by prompt assembly as fenced JSON. */
  ChannelStructuredContext?: ChannelStructuredContextEntry[];
  /** @deprecated Use ChannelStructuredContext. Removal: after 2026-09-08 (see sdk-untrusted-context-identifier-aliases). */
  UntrustedStructuredContext?: UntrustedStructuredContextEntry[];
  /** System-attached provenance for the current inbound message. */
  InputProvenance?: InputProvenance;
  /** Internal wake cause, independent of transport, transcript provenance, and execution authority. */
  InternalTurnSource?: "heartbeat" | "cron" | "exec" | "event" | "progress-card-refresh";
  /** Explicit owner allowlist overrides (trusted, configuration-derived). */
  OwnerAllowFrom?: Array<string | number>;
  SenderName?: string;
  SenderId?: string;
  /** Trusted in-process creation provenance; never populated from channel payloads. */
  SessionCreation?: {
    skillLibrarySelections?: SkillLibrarySelection[];
    via: SessionCreatedVia;
    actor?: SessionCreatedActor;
    sandbox?: "required";
  };
  SenderUsername?: string;
  SenderTag?: string;
  SenderE164?: string;
  SenderIsBot?: boolean;
  /** Channel-ingress fact: sender is the operator's own account (from-me). */
  SenderIsSelf?: boolean;
  Timestamp?: number;
  LocationLat?: number;
  LocationLon?: number;
  LocationAccuracy?: number;
  LocationName?: string;
  LocationAddress?: string;
  LocationSource?: string;
  LocationIsLive?: boolean;
  LocationLivePeriodSeconds?: number;
  LocationCaption?: string;
  /** Stable identity of the provider update that carried this message. */
  ProviderUpdateId?: string;
  /** Provider update kind, for example `message` or `edited_message`. */
  ProviderUpdateKind?: string;
  /** Provider-native timestamp for the original message. */
  ProviderMessageTimestamp?: number;
  /** Provider-native timestamp for an edited message update. */
  ProviderEditTimestamp?: number;
  /** Provider label. */
  Provider?: string;
  /** Provider surface label. Prefer this over `Provider` when available. */
  Surface?: string;
  /** Platform bot username when command mentions should be normalized. */
  BotUsername?: string;
  WasMentioned?: boolean;
  /** Effective channel-owned mention policy before any plugin-binding bypass. */
  GroupRequireMention?: boolean;
  /** True when this turn explicitly mentioned the current bot target. */
  ExplicitlyMentionedBot?: boolean;
  /** Provider-native explicit user mention ids present on this turn. */
  MentionedUserIds?: string[];
  /** Provider-native explicit user-group/subteam mention ids present on this turn. */
  MentionedSubteamIds?: string[];
  /** Provider-native implicit mention wake reasons present on this turn. */
  ImplicitMentionKinds?: string[];
  /** Provider-native source that caused the current mention decision. */
  MentionSource?: MentionSource;
  CommandAuthorized?: boolean;
  CommandTurn?: CommandTurnContext;
  CommandSource?: "text" | "native";
  CommandInterpretationSuppressed?: boolean;
  CommandTargetSessionKey?: string;
  /**
   * Internal flag: command handling prepared trailing prompt text for ACP dispatch.
   * Used for `/new <prompt>` and `/reset <prompt>` on ACP-bound sessions.
   */
  AcpDispatchTailAfterReset?: boolean;
  /** Gateway client scopes when the message originates from the gateway. */
  GatewayClientScopes?: string[];
  /** Gateway client capabilities when the message originates from the gateway. */
  GatewayClientCaps?: string[];
  /** Server-bound requesting browser; never sourced from message text or rendered into prompts. */
  GatewayUiCommandTarget?: GatewayUiCommandTarget;
  /** Run-scoped plugin tool bindings; never rendered into prompt text. */
  GatewayRunToolBindings?: Readonly<Record<string, unknown>>;
  /** Gateway device id allowed to review approvals initiated by this turn. */
  ApprovalReviewerDeviceId?: string;
  /** Thread identifier (Telegram topic id or Matrix thread event id). */
  MessageThreadId?: string | number;
  /** Provider-native thread target for reply delivery without making the session thread-scoped. */
  TransportThreadId?: string | number;
  /** Platform-native channel/conversation id (e.g. Slack DM channel "D…" id). */
  NativeChannelId?: string;
  /** Channel-owned local image reference; empty clears a prior avatar. Never rendered into prompts. */
  ConversationAvatar?: string;
  /** Channel-owned metadata exposed to plugin hook context, not prompt text. */
  ChannelContext?: PluginHookChannelContext;
  /** Provider-native chat/conversation id used by channel plugins that expose `chat_id`. */
  ChatId?: string;
  /** Stable provider-native direct-peer id when a DM room/user mapping must survive later writes. */
  NativeDirectUserId?: string;
  /** Telegram forum supergroup marker. */
  IsForum?: boolean;
  /** Human-readable Telegram forum topic name (cached from service messages). */
  TopicName?: string;
  /** Warning: DM has topics enabled but this message is not in a topic. */
  TopicRequiredButMissing?: boolean;
  /**
   * Originating channel for reply routing.
   * When set, replies should be routed back to this provider
   * instead of using lastChannel from the session.
   */
  OriginatingChannel?: OriginatingChannelType;
  /**
   * Originating destination for reply routing.
   * The chat/channel/user ID where the reply should be sent.
   */
  OriginatingTo?: string;
  /**
   * True when the current turn intentionally requested external delivery to
   * OriginatingChannel/OriginatingTo, rather than inheriting stale session route metadata.
   */
  ExplicitDeliverRoute?: boolean;
  /**
   * Internal proof that the channel ingress owner admitted this sender/event.
   * Correlation interceptors must fail closed when this proof is absent.
   */
  InboundAccessAuthorized?: boolean;
  /** Internal marker that channel ingress authoritatively observed route-context facts. */
  ConversationRouteContextObserved?: boolean;
  /** Canonical peer used by route selection; delivery targets may use a different namespace. */
  ConversationRoutePeerId?: string;
  /**
   * Internal flag for channels that emit message_received through a channel-specific
   * privacy gate before entering the shared reply dispatcher.
   */
  SuppressMessageReceivedHooks?: boolean;
  /**
   * Provider-specific parent conversation id for threaded contexts.
   * For Discord threads, this is the parent channel id.
   */
  ThreadParentId?: string;
  /**
   * Messages from hooks to be included in the response.
   * Used for hook confirmation messages like "Session context saved to memory".
   */
  HookMessages?: string[];
};
type FinalizedMsgContext = Omit<MsgContext, "CommandAuthorized"> & {
  /**
   * Always set by finalizeInboundContext().
   * Default-deny: missing/undefined becomes false.
   */
  CommandAuthorized: boolean;
  /**
   * Populated by finalizeInboundContext(); optional for public SDK
   * compatibility with existing plugin-constructed finalized contexts.
   */
  CommandTurn?: CommandTurnContext;
};
/** Internal inbound context; legacy media fields exist only on the shipped SDK adapter. */
type RuntimeMsgContext = Omit<MsgContext, LegacyMediaContextKey>;
type FinalizedRuntimeMsgContext = Omit<RuntimeMsgContext, "CommandAuthorized" | keyof CanonicalInboundText> & CanonicalInboundText & {
  CommandAuthorized: boolean;
  CommandTurn: CommandTurnContext;
};
type NonTemplateContextKey = "ConversationAvatar";
type TemplateContext = Omit<RuntimeMsgContext, NonTemplateContextKey> & {
  BodyStripped?: string;
  SessionId?: string;
  IsNewSession?: string;
  /** Local path for the attachment currently being processed. */
  AttachmentPath?: string;
  /** Original URL/reference for the attachment currently being processed. */
  AttachmentUrl?: string;
  /** MIME content type for the attachment currently being processed. */
  AttachmentContentType?: string;
  /** Directory containing AttachmentPath. */
  AttachmentDir?: string;
  /** Stable zero-based source fact index for the attachment currently being processed. */
  AttachmentIndex?: number;
  /** @deprecated Use AttachmentPath. */
  MediaPath?: string;
  /** @deprecated Use AttachmentUrl. */
  MediaUrl?: string;
  /** @deprecated Use AttachmentContentType. */
  MediaType?: string;
  /** @deprecated Use AttachmentDir. */
  MediaDir?: string;
};
declare function applyTemplate(str: string | undefined, ctx: TemplateContext): string;
//#endregion
//#region src/config/sessions/conversation-route-context.d.ts
type ConversationRouteContext = {
  peerId?: string;
  guildId?: string;
  teamId?: string;
  parentPeerId?: string;
  memberRoleIds?: string[];
};
//#endregion
//#region src/config/sessions/session-reset-boundary-event.d.ts
type SessionResetBoundaryReason = "new" | "reset" | "idle" | "daily" | "cron-stale";
type SessionResetBoundaryRequest = {
  context: "clear";
  reason: Extract<SessionResetBoundaryReason, "new" | "reset">;
} | {
  context: "preserve-tail";
  reason: Extract<SessionResetBoundaryReason, "reset" | "idle" | "daily" | "cron-stale">;
};
//#endregion
//#region src/config/sessions/session-accessor.lifecycle-types.d.ts
/** Reset is an append: an empty transcript needs the caller's workspace for its header. */
type SessionResetBoundaryWrite = SessionResetBoundaryRequest & {
  /** Caller-prepared identity when a lifecycle consumer must reopen this exact window. */
  boundaryId?: string;
  cwd: string;
};
type SessionLifecycleArtifactCleanupParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  storePath: string;
  archiveRemovedEntryTranscripts?: boolean;
  /** Preserve explicitly foreign plugin-owned state while retaining ownerless legacy rows. */
  pluginOwnerId?: string;
  sessionKeySegmentPrefix: string;
  transcriptContentMarker: string;
  orphanTranscriptMinAgeMs: number;
  nowMs?: number;
};
type SessionLifecycleArtifactCleanupResult = {
  removedEntries: number;
  archivedTranscriptArtifacts: number;
};
type SessionLifecycleStoreTarget = {
  canonicalKey: string;
  storeKeys: string[];
};
type SessionLifecycleArchivedTranscript = {
  /** Canonical SQLite archive identity used for idempotent derived-file publication. */
  generation: string;
  sessionId: string;
  sourcePath: string;
  archivedPath: string;
};
type ResetSessionEntryLifecycleResult = {
  archivedTranscripts: SessionLifecycleArchivedTranscript[];
  previousEntry?: InternalSessionEntry;
  previousSessionFile?: string;
  previousSessionId?: string;
  nextEntry: InternalSessionEntry;
};
type DeleteSessionEntryLifecycleResult = {
  archivedTranscripts: SessionLifecycleArchivedTranscript[];
  deleted: boolean;
  expectedEntryMismatch?: true;
  deletedEntry?: InternalSessionEntry;
  deletedSessionId?: string;
};
type DeleteSessionEntryLifecycleParams = {
  /** Captured host state source; never part of the cloneable deletion plan. */
  env?: NodeJS.ProcessEnv;
  /**
   * Revalidate caller and external lifecycle owners at each synchronous deletion boundary.
   * Must not write the deleting agent database: its Worker may hold the transaction lock.
   */
  commitGuard?: (operation?: RetainedWorkerTransactionAdmission) => void;
  /** Agent owner used to resolve backend transcript artifacts. */
  agentId?: string;
  /** Whether transcript artifacts should be archived/deleted with the entry. */
  archiveTranscript: boolean;
  /** Delete transcript rows without writing an archive artifact. */
  deleteTranscriptWithoutArchive?: boolean;
  /** Full teardown only: delete durable operations sourced from this logical session. */
  deleteDeliveryArtifacts?: boolean;
  /** Optional exact row guard checked under the storage writer lock. */
  expectedEntry?: InternalSessionEntry;
  /** Bind a cross-store handoff to the original physical source at deletion admission. */
  expectedDatabaseIdentity?: OpenClawAgentDatabaseIdentity;
  /** Compare remaining source generations with their verified cross-store handoff. */
  expectedGenerations?: readonly SqliteSessionGenerationClaim[];
  /** Guard logical-node artifacts when planning or committing entry removal. */
  expectedNodeArtifactFingerprint?: string;
  /** Optional provider-run identity guard checked under the storage writer lock. */
  expectedSessionId?: string | null;
  /** Optional owner revision guard checked under the storage writer lock. */
  expectedLifecycleRevision?: string;
  /** Optional persisted revision guard checked under the storage writer lock. */
  expectedUpdatedAt?: number;
  /** Fail when the underlying store cannot confirm a durable write. */
  requireWriteSuccess?: boolean;
  /** Explicit store target for SQLite session ownership. */
  storePath: string;
  /** Canonical key plus aliases that identify the logical entry. */
  target: SessionLifecycleStoreTarget;
};
type SessionEntryLifecycleRemovalBase = {
  sessionKey: string;
  /** Doctor repair only: address a malformed persisted key without normalizing it first. */
  exactStoredKey?: boolean;
  /** Doctor cross-store repair only: copied/archived windows may be removed with the source node. */
  deleteOwnedWindows?: boolean;
  /** Doctor cross-store repair only: delivery aliases copied under the canonical destination key. */
  deliveryCleanupKeys?: readonly string[];
  archiveRemovedTranscript?: boolean;
  /** Omit removal when the transcript changed after the caller's positive classification. */
  expectedTranscriptSnapshot?: SessionStateDeleteSnapshot;
  /** Memory cleanup rechecks message absence at the actor deletion boundary. */
  requiresMissingTranscript?: true;
  expectedSessionId?: string;
  expectedLifecycleRevision?: string;
  expectedUpdatedAt?: number;
};
type SessionEntryLifecycleRemoval = SessionEntryLifecycleRemovalBase & ({
  /** Doctor repair only: compare the rejected hot blob and its detached snapshot revision. */
  expectedRawEntryJson: string;
  expectedSnapshotRevision: number;
  expectedEntry: InternalSessionEntry;
} | {
  expectedRawEntryJson?: never;
  expectedSnapshotRevision?: never;
  expectedEntry?: InternalSessionEntry;
});
//#endregion
//#region src/config/sessions/session-accessor.types.d.ts
/**
 * Session access API for callers that need entries or transcripts without
 * depending on the persisted store layout. Callers provide stable session
 * identity, and this module resolves the current entry/transcript target while
 * preserving canonical-key, transcript-linking, and update-notification rules.
 *
 * This accessor is the permanent storage-neutral domain boundary for
 * session/transcript runtime access. Legacy JSON import remains doctor-only.
 */
type SessionAccessScope = {
  /** Agent owner used when the session key does not already encode one. */
  agentId?: string;
  /**
   * Set false only for internal read-only hot paths that will not retain or
   * mutate the returned entry.
   */
  clone?: boolean;
  /** Configured default owner for fixed-store SQLite target derivation. */
  defaultAgentId?: string;
  /** Environment override used when resolving agent-scoped store paths in tests/tools. */
  env?: NodeJS.ProcessEnv;
  /** Set false for metadata-only reads that do not need hydrated prompt refs. */
  hydrateSkillPromptRefs?: boolean;
  /** Use latest when the caller must bypass any in-process metadata snapshot. */
  readConsistency?: "latest";
  /** Canonical or alias session key for the entry being read or written. */
  sessionKey: string;
  /** Explicit store path for callers that already resolved the owning store. */
  storePath?: string;
};
type SessionEntryReadScope = SessionAccessScope & {
  /** Select only required saved snapshots; list omits all of them before decoding. */
  projection?: SessionEntryProjection;
};
type SessionEntryListScope = Partial<Omit<SessionEntryReadScope, "sessionKey" | "projection">> & {
  projection?: "full" | "list";
  /** Retain the physical source assertion independently of this synchronous read. */
  captureSource?: (assertCurrent: () => void) => void;
  /** Select exact persisted keys after validating the complete listing snapshot. */
  sessionKeys?: readonly string[];
  /** Set false for readers that do not consume derived participant identities or counts. */
  includeParticipants?: boolean;
  /** Page full cron-run entries for exact deletion guards without hydrating the store. */
  cronRetention?: {
    afterSessionKey?: string;
    limit: number;
  };
  /** Validate the complete listing, retaining full expired cron rows only for this logical owner. */
  expiredCronRuns?: {
    agentId: string;
    updatedBefore: number;
  };
};
type SessionTranscriptAccessScope = Omit<SessionAccessScope, "sessionKey"> & {
  /** Deprecated transcript locator from older file-backed call sites. */
  sessionFile?: string;
  /** Runtime session id used to resolve the transcript identity. */
  sessionId: string;
  /** Required when resolving through session metadata; optional for legacy locators. */
  sessionKey?: string;
  /** Channel thread suffix used when deriving topic transcript paths. */
  threadId?: string | number;
};
type SessionTranscriptRuntimeScope = SessionTranscriptAccessScope & {
  sessionKey: string;
};
type SessionTranscriptReadScope = Omit<SessionTranscriptRuntimeScope, "sessionKey"> & {
  /** Canonical key when the caller has a session-store identity for this read. */
  sessionKey?: string;
  /** Entry already loaded by hot callers; avoids rereading the session store. */
  sessionEntry?: Partial<Pick<InternalSessionEntry, "sessionId">>;
  /** Byte budget enforced via SQL before parsing transcript event rows. */
  maxEventBytes?: number;
};
type SessionTranscriptWriteScope = Omit<SessionTranscriptAccessScope, "sessionId"> & {
  /** Optional for appenders that resolve it from the session entry. */
  sessionId?: string;
  /** Optional run-owned fence checked inside the transcript write transaction. */
  expectedWriterRunId?: string;
  /** Optional lifecycle fence paired with sessionId for run-owned writes. */
  expectedLifecycleRevision?: string;
  /** Exact owner facts, including absent fields, checked inside the write transaction. */
  expectedOwner?: Pick<InternalSessionEntry, "lifecycleRevision" | "activeWriterRunId">;
};
type SessionEntrySummary = {
  /** Persisted key for the entry. */
  sessionKey: string;
  /** Entry value cloned from the backing store unless the caller requested borrowed reads. */
  entry: InternalSessionEntry;
};
/** Raw transcript record for non-message events; message records use appendTranscriptMessage. */
type TranscriptEvent = unknown;
type SessionTranscriptStats = {
  eventCount: number;
  lastMutationAtMs?: number;
  lastObservedMutationAtMs?: number;
  maxSeq: number;
  sizeBytes: number;
};
type SessionTranscriptEventRow = {
  event: TranscriptEvent;
  seq: number;
};
/** Count, byte, and continuation bounds for one raw transcript page. */
type SessionTranscriptRawDeltaLimits = {
  /** Opaque cursor returned by a prior page or reset result. */
  cursor?: string;
  /** Maximum serialized JSONL bytes returned by this page. */
  maxBytes?: number;
  /** Maximum number of events returned by this page. */
  maxEvents?: number;
};
type SessionTranscriptDeltaResult<TEvent, TResetReason extends string> = {
  kind: "page";
  /** Cursor positioned after the last returned event. */
  cursor: string;
  /** Ordered transcript events selected for this page. */
  events: TEvent[];
  /** True when another event remains after this page. */
  hasMore: boolean;
  /** First unread event size when it cannot fit under maxBytes. */
  requiredBytes?: number;
  /** Stored JSONL bytes represented by events. */
  serializedBytes: number;
} | {
  kind: "reset";
  /** Fresh bootstrap cursor for the current generation. */
  cursor: string;
  /** Stable discontinuity that invalidated the supplied cursor. */
  reason: TResetReason;
} | {
  kind: "missing";
};
/** Generation-aware outcome for one bounded raw transcript read. */
type SessionTranscriptRawDeltaResult = SessionTranscriptDeltaResult<SessionTranscriptEventRow, "generation_mismatch" | "invalid_cursor" | "scope_mismatch">;
/** Count, byte, and continuation bounds for one visible-message page. */
type SessionTranscriptVisibleMessageDeltaLimits = {
  /** Opaque continuation cursor; store and return it unchanged. */
  cursor?: string;
  /** Maximum serialized JSONL bytes returned by this page. */
  maxBytes?: number;
  /** Maximum number of visible messages returned by this page. */
  maxMessages?: number;
  /**
   * Where fresh cursors begin: on a cursor-less read and in `reset` results.
   * `"transcript"` (default) starts at the first active-path message;
   * `"reset-window"` starts at the latest reset's retained tail.
   */
  start?: "transcript" | "reset-window";
};
/** One active-path message row selected from the materialized projection. */
type SessionTranscriptVisibleMessageEventRow = SessionTranscriptEventRow & {
  /** Raw transcript sequence used only by the opaque continuation cursor. */
  eventSeq: number;
  /** Parent id after active-branch normalization; null for the visible root. */
  parentId: string | null;
};
/** Generation-aware outcome for one bounded visible-message read. */
type SessionTranscriptVisibleMessageDeltaResult = SessionTranscriptDeltaResult<SessionTranscriptVisibleMessageEventRow, "anchor_missing" | "anchor_moved" | "generation_mismatch" | "invalid_cursor" | "scope_mismatch" |
/** Reset-window cursors only: a newer same-session reset closed the drained window. */
"session_reset">;
type TranscriptMessageAppendOptions<TMessage> = {
  /** Detached preparation; fresh commit compares the exact transcript version before insertion. */
  preparation?: {
    prepareMessage?: (message: TMessage) => Promise<TMessage | undefined>;
    /** Owner-prepared row predicates and live lifecycle authority; opaque SQL callbacks are unsupported. */
    source?: SessionSourceAssertion;
  };
  /** Exact read snapshot required for a fresh insertion; replay keeps its original receipt. */
  expectedTranscript?: SessionTranscriptContextVersion;
  /** Rebase a stale explicit parent when the current tail still descends from it. */
  appendIntent?: "active-branch";
  /** Runtime config used for transcript header metadata. */
  config?: OpenClawConfig;
  /** Working directory recorded in a newly created transcript header. */
  cwd?: string;
  /** How duplicate message idempotency keys are detected before append. */
  idempotencyLookup?: "scan" | "scan-assistant" | "caller-checked";
  /** Reject the append when the transcript changed since the caller loaded it. */
  expectedMutationAt?: number | null;
  /** Provider/channel message payload to persist. */
  message: TMessage;
  /** Testable timestamp override for the generated transcript entry. */
  now?: number;
  /** Existing transcript event id owned by a caller with its own session tree. */
  eventId?: string;
  /** Existing parent id owned by a caller with its own session tree. */
  parentId?: string | null;
  /** @deprecated Use preparation.prepareMessage. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  prepareMessageAfterIdempotencyCheck?: (message: TMessage) => TMessage | undefined;
  /** @deprecated Use preparation.source. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  beforeFreshMessageCommit?: () => void;
  /** Allow append without parent-link migration for large legacy linear transcripts. */
  useRawWhenLinear?: boolean;
};
type TranscriptMessageAppendResult<TMessage> = {
  /** False when idempotency lookup found an existing transcript message. */
  appended: boolean;
  /** Prepared message payload as persisted or replayed from the transcript. */
  message: TMessage;
  /** Existing or newly generated transcript message id. */
  messageId: string;
  /** Parent id actually used by the durable transcript append. */
  effectiveParentId?: string | null;
  /** Authoritative immutable identity issued by the append transaction. */
  anchor?: TranscriptEntryAnchor;
};
/** Transcript update fields supplied by callers; the target is resolved here. */
type TranscriptUpdatePayload = Partial<SessionTranscriptUpdate> & Pick<InternalSessionTranscriptUpdate, "lifecycleRevision" | "assistantItemIds">;
type LatestTranscriptAssistantText = {
  id?: string;
  text: string;
  timestamp?: number;
  openclawDelivery?: AssistantMessage["openclawDelivery"];
};
type SessionTranscriptWriteLockAccessorContext = {
  publishUpdate: (update?: TranscriptUpdatePayload) => Promise<void>;
  appendMessage: <TMessage>(options: LockedTranscriptMessageAppendOptions<TMessage>) => Promise<TranscriptMessageAppendResult<TMessage> | undefined>;
  /** Appends with commit-time idempotency and returns the committed visible sequence. */
  appendMessageWithMessageSequence: <TMessage>(options: LockedTranscriptMessageAppendOptions<TMessage>) => Promise<{
    /** Unfenced imports omit ownership and retain canonical-history refresh. */
    lifecycleRevision?: string;
    messageSeq?: number;
    result: TranscriptMessageAppendResult<TMessage> | undefined;
  }>;
  /** Reads bounded indexed facts for supplied transcript mirror identities. */
  readMessageFacts: (params: {
    idempotencyKeys: readonly string[];
    /** Limit identities to the current active branch; default includes abandoned branches. */
    activeBranchOnly?: boolean;
    sourceRunId?: string;
  }) => Promise<{
    anchorsByIdempotencyKey: Map<string, TranscriptEntryAnchor>;
    existingIdempotencyKeys: Set<string>;
    messagesByIdempotencyKey: Map<string, unknown>;
    sourceEvents?: TranscriptEvent[];
  }>;
  readEvents: () => Promise<TranscriptEvent[]>;
  replaceEvents: (events: readonly TranscriptEvent[]) => Promise<void>;
};
type LockedTranscriptMessageAppendOptions<TMessage> = Omit<TranscriptMessageAppendOptions<TMessage>, "prepareMessageAfterIdempotencyCheck"> & {
  /** @deprecated Use preparation.prepareMessage. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
  prepareMessageAfterIdempotencyCheck?: (message: TMessage) => TMessage | undefined;
  /** Awaited after duplicate detection; undefined suppresses a fresh append. */
  prepareMessageAfterIdempotencyCheckAsync?: (message: TMessage) => Promise<TMessage | undefined>;
};
type SessionTranscriptTurnUpdateMode = "inline" | "file-only" | "none";
type SessionTranscriptTurnMessageAppend = TranscriptMessageAppendOptions<unknown> & {
  /** Audited preparation runs once on the host against worker-read idempotency facts. */
  workerPreparation?: Pick<TranscriptMessageAppendOptions<unknown>, "prepareMessageAfterIdempotencyCheck" | "beforeFreshMessageCommit"> & {
    /** Requires expectedSessionId and one message without transaction predicates; awaited after duplicate detection. */
    prepareMessageAfterIdempotencyCheckAsync?: (message: unknown) => Promise<unknown>;
  };
  predicate?: {
    kind: "latest-assistant-differs";
    runId: string;
    text: string;
  } | {
    kind: "active-entry";
    entryId: string;
    errorMessage: string;
  };
  /**
   * Runs inside the session writer queue before the SQLite transaction begins.
   * The commit phase revalidates session ownership and database idempotency
   * after asynchronous predicate work finishes.
   */
  shouldAppend?: (context: SessionTranscriptTurnWriteContext) => Promise<boolean> | boolean;
  /**
   * Rechecks authority after the write transaction begins. Read the newest assistant
   * only when the predicate needs it, synchronously within this callback.
   * Direct synchronous writers bypass the process queue, so prepared facts can be stale.
   */
  shouldAppendInTransaction?: (readLatestAssistantMessage: () => unknown) => boolean;
};
type SessionTranscriptTurnWriteContext = Partial<SessionTranscriptRuntimeTarget>;
type SessionTranscriptTurnPersistOptions = {
  /** Retained caller authority, with no same-database reads inside worker grants. */
  assertCurrent?: () => void;
  acceptedResultGuard?: {
    expectedWriterRunId: string | null;
    errorMessage: string;
  };
  /** Runtime config used for lock settings and header metadata. */
  config?: OpenClawConfig;
  /** Working directory recorded in a newly created transcript header. */
  cwd?: string;
  /**
   * Rejects the turn when the persisted session key no longer points at this
   * runtime session id. SQLite evaluates this guard inside the same queued
   * write as the transcript append and metadata touch.
   */
  expectedSessionId?: string;
  /** Creates this entry with the turn only if the logical session is still absent. */
  initialSessionEntry?: InternalSessionEntry;
  /** Rejects the turn when lifecycle ownership changed without rotating the session id. */
  expectedLifecycleRevision?: SessionLifecycleRevisionExpectation;
  /** Rejects the turn when another admitted run owns transcript writes. */
  expectedWriterRunId?: SessionTranscriptTurnExpectedState["expectedWriterRunId"];
  /** Rejects the turn unless the persisted row still has this exact lifecycle owner state. */
  expectedSessionState?: SessionTranscriptTurnExpectedState;
  /** Lifecycle metadata committed when the guarded turn inserts or idempotently matches a message. */
  sessionLifecyclePatch?: SessionTranscriptTurnLifecyclePatch;
  /** Closed mutation committed with the admitted turn, never as a separate client write. */
  sessionTurnMutation?: SessionTranscriptTurnMutation;
  /** Message rows to append under one transcript write lock. */
  messages: readonly SessionTranscriptTurnMessageAppend[];
  /** Exact run provenance persisted on output rows and emitted on terminal assistant updates. */
  runId?: string;
  /**
   * Accept appended or matched messages synchronously after guarded SQLite commit.
   * Explicit completion work is joined before owner drain or transcript publication.
   * The canonical result preserves replay bytes. Throws cannot roll back committed rows.
   */
  onMessageCommitted?: (result: TranscriptMessageAppendResult<unknown>, acceptCompletion: (complete: () => Promise<void>) => void,
  /** Exact guarded-turn postimage; absent for legacy, unguarded single-message writes. */
  turn?: Pick<SessionTranscriptTurnPersistResult, "sessionEntry" | "sessionTurnMutationResult">) => void;
  /** Publish each appended message inline, one file-only invalidation, or nothing. */
  updateMode?: SessionTranscriptTurnUpdateMode;
  /** Emit file-only updates even when every candidate message was skipped. */
  publishWhen?: "always" | "when-appended";
  /**
   * Touch updatedAt/sessionFile metadata after appending.
   * SQLite implementation note: transcript row append(s) plus this session
   * metadata touch should be one SQLite write transaction; publish happens
   * after that transaction commits.
   */
  touchSessionEntry?: boolean;
};
interface SessionTranscriptTurnPersistResult {
  predicateSkipped?: boolean;
  sessionTurnMutationResult?: SessionTranscriptTurnMutationResult;
  messages: TranscriptMessageAppendResult<unknown>[];
  rejectedReason?: "session-rebound";
  sessionEntry: InternalSessionEntry | undefined;
}
interface SessionTranscriptRuntimeTarget {
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
}
type ResolvedSessionTranscriptRuntimeTarget = SessionTranscriptRuntimeTarget & {
  selectedSessionId?: string | null;
  selectedLifecycleRevision?: SessionLifecycleRevisionExpectation;
};
type SessionTranscriptManualTrimResult = {
  compacted: false;
  reason: "no transcript";
} | {
  compacted: false;
  kept: number;
} | {
  compacted: true;
  kept: number;
};
/** Detached candidate row; changes persist only when returned as a replacement. */
type SessionEntryReplacementSnapshot = SessionEntrySummary;
/** Full row to replace in the transaction; missing keys are ignored. */
type SessionEntryReplacement = SessionEntrySummary;
/** Decision made before inheriting parent context into a child session. */
type SessionParentForkDecision = {
  status: "fork";
  maxTokens: number;
  parentTokens?: number;
} | {
  status: "skip";
  reason: "parent-too-large";
  maxTokens: number;
  parentTokens: number;
  message: string;
};
/** SQLite transcript identity created for a child fork. */
type ParentForkedSessionTranscript = {
  sessionFile: string;
  sessionId: string;
};
type ForkSessionFromParentTranscriptResult = {
  status: "created";
  transcript: ParentForkedSessionTranscript;
} | {
  status: "too-large";
  decision: Extract<SessionParentForkDecision, {
    status: "skip";
  }>;
} | {
  status: "missing-parent";
} | {
  status: "failed";
};
type ForkSessionEntryFromParentTargetResult = {
  status: "forked";
  fork: ParentForkedSessionTranscript;
  parentEntry: InternalSessionEntry;
  sessionEntry: InternalSessionEntry;
  decision: Extract<SessionParentForkDecision, {
    status: "fork";
  }>;
} | {
  status: "skipped";
  reason: "existing-entry" | "decision-skip";
  parentEntry?: InternalSessionEntry;
  sessionEntry: InternalSessionEntry;
  decision?: SessionParentForkDecision;
} | {
  status: "missing-entry";
} | {
  status: "missing-parent";
} | {
  status: "failed";
};
type ForkSessionEntryFromParentTargetParams = {
  agentId?: string;
  commitGuard?: () => void;
  fallbackEntry?: InternalSessionEntry;
  parentTarget: SessionLifecycleStoreTarget;
  sessionTarget: SessionLifecycleStoreTarget;
  storePath: string;
};
type SessionMessageCutMutationResult = {
  status: "created";
  key: string;
  entry: InternalSessionEntry;
  editorText?: string;
  editorAttachments?: Array<{
    mimeType: string;
    data: string;
  }>;
  editorMediaRefs?: Array<{
    path: string;
    contentType: string;
  }>;
} | {
  status: "missing-session";
} | {
  status: "missing-entry";
} | {
  status: "not-user-message";
} | {
  status: "off-active-path";
} | {
  status: "unsupported-storage";
} | {
  status: "failed";
};
type SessionMessageCutMutationParams = {
  agentId?: string;
  /** Synchronous authority check run inside the transcript commit transaction. */
  commitGuard?: () => void;
  creation?: {
    via: SessionCreatedVia;
    actor?: SessionCreatedActor;
    sandbox?: "required";
  };
  entryId: string;
  env?: NodeJS.ProcessEnv;
  sessionKey: string;
  sessionStoreKey?: string;
  storePath?: string;
  targetKey?: string;
  /** Canonical local workspace prepared by the fork lifecycle before transcript commit. */
  forkWorkspace?: Pick<InternalSessionEntry, "projectId" | "spawnedCwd" | "spawnedWorkspaceDir" | "sessionRoot">;
  /** Distinct repository owner prepared by the fork lifecycle before transcript commit. */
  repositoryWorkspaceId?: string;
};
type SessionBranchSummary = SchemaContract<SessionBranch>;
type SessionBranchSwitchMutationResult = {
  status: "created";
  key: string;
  entry: InternalSessionEntry;
} | {
  status: "missing-session";
} | {
  status: "missing-entry";
} | {
  status: "not-branch-tip";
} | {
  status: "already-active";
} | {
  status: "unsupported-storage";
} | {
  status: "failed";
};
type SessionEntryCreateWithTranscriptContext = {
  /** Current entry under the requested key before creation, if any. */
  existingEntry?: InternalSessionEntry;
  /** Exact normalized target from the same snapshot, distinct from an alias-resolved entry. */
  targetEntry?: InternalSessionEntry;
  /** Requested label's detached occupancy; excludes the exact normalized target only. */
  labelInUse: boolean;
};
//#endregion
//#region src/config/sessions/cli-history-boundary.d.ts
type CliHistoryWriter = {
  target: SessionTranscriptRuntimeTarget;
  runId: string;
  authFingerprint: string;
  lifecycleRevision?: string;
  assertCurrent: () => void;
  assertReadable: () => void | Promise<void>;
  /**
   * Fresh owner check, asked once per coverage commit; never throws. False keeps the commit's
   * rows but does not advance coverage. Absent means the owner cannot change during the run.
   */
  confirmsOwner?: () => boolean;
};
/** The serializable account facts a worker needs to advance coverage for this writer. */
type CliHistoryWriterFacts = Pick<CliHistoryWriter, "runId" | "authFingerprint" | "lifecycleRevision"> & {
  /** The host holds a live owner check the worker must ask for inside its transaction. */
  confirmOwner?: boolean;
};
/** Private proof of the account that owns every covered transcript event. */
type CliHistoryBoundary = {
  version: 1;
  sessionId: string;
  state: "unknown";
} | {
  version: 1;
  sessionId: string;
  state: "known";
  authFingerprint: string;
  generation: string | null;
  maxSeq: number | null;
  writerRunId: string;
};
//#endregion
//#region src/config/sessions/session-diff-baseline-capture.d.ts
type SessionDiffBaselineCapture = {
  version: 1;
  captureId: string;
  status: "pending" | "unavailable";
};
//#endregion
//#region src/config/sessions/pending-final-delivery-types.d.ts
type PendingFinalDeliveryState = {
  createdAt: number;
  context?: DeliveryContext;
  intentId?: string;
  /** Original admitted source; survives claim cleanup before the queued final settles. */
  sourceRunId?: string;
  deliveries?: Array<{
    id: string;
    state: "prepared" | "queued" | "delivered" | "suppressed" | "unknown";
    /** Same-route identified evidence for the complete logical member, not just its last send. */
    receipt?: {
      platformMessageId: string;
      resultCount: number;
    };
  }>;
} & ({
  kind: "replayable";
  text: string;
} | {
  kind: "transport-only";
});
/**
 * Owed user-visible notice that a final's delivery outcome stayed unknown.
 * Settled unknown custody records the debt here; the next same-route turn
 * sends it once, so an ambiguous loss never ends silently.
 */
type PendingDeliveryNoticeState = {
  createdAt: number;
  context: DeliveryContext;
  intentId: string;
  state: "owed" | "unresolved" | "acknowledged";
};
//#endregion
//#region src/config/sessions/session-model-fallback.d.ts
type AgentPatchedSessionModelFallback = {
  prevModel: string;
  prevProvider: string;
  prevModelOverride?: string;
  prevProviderOverride?: string;
  prevModelOverrideSource?: "auto" | "user" | "default";
  prevModelOverrideRouteResolution?: "resolved";
  prevModelOverrideFallbackOriginProvider?: string;
  prevModelOverrideFallbackOriginModel?: string;
  prevAuthProfileOverride?: string;
  prevAuthProfileOverrideSource?: "auto" | "user" | "user-link";
  prevAuthProfileOverrideCompactionCount?: number;
  prevContextWindow?: string;
  prevThinkingLevel?: string;
  lastValidatedPatchTs?: number;
  ts: number;
  source: "agent-patch";
};
//#endregion
//#region src/config/sessions/session-prompt-types.d.ts
type SessionSkillPromptRef = {
  version: 1;
  algorithm: "sha256";
  hash: string;
  bytes: number;
};
type SessionSkillSnapshot = {
  librarySelections?: SkillLibrarySelection[];
  prompt: string;
  /** Persisted stores may replace large duplicate prompts with a content-addressed blob ref. */
  promptRef?: SessionSkillPromptRef;
  skills: Array<{
    name: string;
    primaryEnv?: string;
    requiredEnv?: string[];
  }>;
  /** Normalized agent-level filter used to build this snapshot; undefined means unrestricted. */
  skillFilter?: string[];
  /** Effective node-exec eligibility used to select connected node-hosted skills. */
  nodeSkillsEligibility?: {
    canExec: boolean;
    node?: string;
  };
  /**
   * Runtime-only, never persisted. Carries the full parsed Skill[] (including
   * each SKILL.md body) so the embedded runner can skip a workspace skill
   * scan within a turn. Persistence projections strip it before committing
   * session state. On a cold session resume this is undefined and
   * src/skills/runtime/embedded-run-entries.ts rebuilds it from disk.
   */
  resolvedSkills?: Skill[];
  /** Runtime-only model-discoverable catalog before prompt budgeting; never persisted. */
  discoverySkills?: Skill[];
  version?: number;
};
//#endregion
//#region src/config/sessions/session-tool-overrides.d.ts
type SessionToolOverrides = SchemaContract<SessionToolOverrides$1>;
//#endregion
//#region src/config/sessions/types.d.ts
type SessionChatType = ChatType;
type PersistedSessionRunStatus = Exclude<SessionRunStatus, "running" | "queued">;
declare const SESSION_TOTAL_TOKENS_VERSION: 1;
type SessionGitHubPullRequestSource = {
  repository: string;
  repositoryId: number;
  branch: string;
  commit: string;
};
/** Original PR selection for one managed workspace; never a publication receipt or permission grant. */
type SessionGitHubPullRequestBinding = {
  url: string;
  host: string;
  number: number;
  base: SessionGitHubPullRequestSource;
  head: SessionGitHubPullRequestSource;
  /** Prepared initial PR head; absence means its first import is incomplete. */
  preparedHeadCommit?: string;
};
type SessionOrigin = {
  label?: string;
  provider?: string;
  surface?: string;
  chatType?: SessionChatType;
  from?: string;
  to?: string;
  nativeChannelId?: string;
  nativeDirectUserId?: string;
  avatar?: string;
  accountId?: string;
  threadId?: string | number;
};
/** Canonical persisted delivery ownership for one session. */
type SessionDeliveryState = {
  kind: "none";
} | {
  kind: "internal";
} | {
  kind: "external";
  route: ChannelRouteRef;
  context: DeliveryContext;
  origin: SessionOrigin;
};
/**
 * Durable transcript-repair record: an assistant final that was delivered to
 * the user but could not be appended to the canonical transcript. Kept
 * separate from `pendingFinalDelivery` so transport-replay cleanup never drops
 * the only copy of the missing assistant turn.
 */
type PendingTranscriptRepairState = {
  /** Stable identity for retry-safe transcript insertion. */
  id: string;
  text: string;
  provider?: string;
  model?: string;
  createdAt: number;
};
type FallbackNoticeState = {
  kind: "active";
  selectedModel: string;
  activeModel: string;
  reason?: string;
};
type MemoryFlushState = {
  kind: "succeeded";
  compactionCount: number;
} | {
  kind: "failed";
  compactionCount?: number;
  failureCount: number;
};
type CliSessionReseedReceipt = {
  version: 1;
  promptHash: string;
  localSessionId: string;
  userTurnDisposition: "persisted" | "omitted";
};
type SessionDiffBaseline = {
  version: 1;
  sessionId: string;
  root: string;
  files: Array<{
    path: string;
    fingerprint: string;
  }>;
  /** Some checkout entries could not be fingerprinted without exceeding diff safety caps. */
  truncated?: true;
};
type CliSessionBinding = {
  sessionId: string;
  /** Last successful assistant boundary accepted by the backend's resume contract. */
  resumeCheckpointId?: string;
  /** Resume with the backend's fork argument once, then clear before process start. */
  forkNextResume?: true;
  /** Trust an explicitly attached CLI session even when auth, prompt, or MCP fingerprints drift. */
  forceReuse?: boolean;
  authProfileId?: string;
  authEpoch?: string;
  authEpochVersion?: number;
  extraSystemPromptHash?: string;
  messageToolPolicyHash?: string;
  promptToolNamesHash?: string;
  cwdHash?: string;
  mcpConfigHash?: string;
  mcpResumeHash?: string;
  /** Identifies one synthetic history prompt and the trusted local handling of its user turn. */
  reseedReceipt?: CliSessionReseedReceipt;
  /** Last input snapshot supplied to this native session, independent of recovery authority. */
  transcriptCursor?: {
    localSessionId: string;
    entryId: string | null;
    runId: string;
    userEntryId?: string;
  };
};
type AcpSessionBinding = {
  acpBackendId: string;
  acpAgentId: string;
  agentSessionId: string;
};
type SessionContextBudgetStatus = {
  schemaVersion: 1;
  source: "pre-prompt-estimate";
  updatedAt: number;
  provider: string;
  model: string;
  route: PreemptiveCompactionRoute;
  shouldCompact: boolean;
  estimatedPromptTokens: number;
  contextTokenBudget: number;
  promptBudgetBeforeReserve: number;
  reserveTokens: number;
  effectiveReserveTokens: number;
  remainingPromptBudgetTokens: number;
  overflowTokens: number;
  toolResultReducibleChars: number;
  messageCount: number;
  unwindowedMessageCount: number;
  sessionId?: string;
};
type AmbientTranscriptWatermark = {
  sessionId: string;
  messageId: string;
  timestampMs?: number;
  updatedAt: number;
};
type SessionPluginDebugEntry = {
  pluginId: string;
  lines: string[];
};
type SessionPluginNextTurnInjection = {
  id: string;
  pluginId: string;
  pluginName?: string;
  text: string;
  idempotencyKey?: string;
  placement: "prepend_context" | "append_context";
  ttlMs?: number;
  createdAt: number;
  metadata?: PluginJsonValue;
};
type LaneExecutionState = "active" | "draining" | "suspended" | "resuming" | "circuit_open" | "failed_handoff";
interface QuotaSuspension {
  schemaVersion: 1;
  suspendedAt: number;
  reason: "quota_exhausted" | "manual" | "circuit_open";
  failedProvider: string;
  failedModel: string;
  /** Recovery briefing text injected into the next attempt when state === "resuming". */
  summary?: string;
  /** Opaque pointer to an external snapshot blob (path/key); not the briefing text itself. */
  snapshotRef?: string;
  /**
   * @deprecated Lane suspension was removed; nothing writes this anymore. Kept only to
   * hold the shipped SDK surface stable; drop at the next surface window.
   */
  laneId?: string;
  expectedResumeBy?: number;
  state: LaneExecutionState;
}
type SessionEntryCore = SessionEntryProvenance & Pick<SessionRow, "permissionMode" | "sandboxMode" | "nativeRuntimeConsent" | "sessionRoot"> & {
  /** Collaboration mode. Missing legacy values are equivalent to "shared". */
  visibility?: NonNullable<SessionRow["visibility"]>;
  /**
   * Last delivered heartbeat payload (used to suppress duplicate heartbeat notifications).
   * Stored on the main session entry.
   */
  lastHeartbeatText?: string;
  /** Timestamp (ms) when lastHeartbeatText was delivered. */
  lastHeartbeatSentAt?: number;
  /**
   * Base session key for heartbeat-created isolated sessions.
   * When present, `<base>:heartbeat` is a synthetic isolated session rather than
   * a real user/session-scoped key that merely happens to end with `:heartbeat`.
   */
  heartbeatIsolatedBaseSessionKey?: string;
  /** Legacy heartbeat task timestamps consumed and cleared only by doctor migration. */
  heartbeatTaskState?: Record<string, number>;
  /** Plugin-owned session state, grouped by plugin id then extension namespace. */
  pluginExtensions?: Record<string, Record<string, PluginJsonValue>>;
  /** Trusted session initialization is incomplete; all work admission stays blocked. */
  initializationPending?: true;
  /** Top-level SessionEntry mirror slots owned by plugin session extensions. */
  pluginExtensionSlotKeys?: Record<string, Record<string, string>>;
  /** Durable one-shot prompt additions drained before the next agent turn. */
  pluginNextTurnInjections?: Record<string, SessionPluginNextTurnInjection[]>;
  sessionId: string;
  /** Latest operator client declaration; retained across internal turns and restart. */
  clientCapabilities?: string[];
  updatedAt: number;
  /** Process-lifetime session whose entry and transcript stay in the in-memory agent database. */
  incognito?: true;
  /** Opaque owner revision used to reject stale lifecycle mutations. */
  lifecycleRevision?: string;
  /** Current provider precaution; only its acknowledged continuation may start work. */
  providerReview?: SessionProviderReview;
  /** Timestamp (ms) when the session was archived from active session lists. */
  archivedAt?: number;
  /** Actor that archived the session; cleared when the session is restored. */
  archivedBy?: SessionActor$1;
  /** Stable lifecycle cause; absent values are legacy archives and remain manually protected. */
  archiveReason?: SessionEntryArchiveReason;
  /** Timestamp (ms) when the session was pinned for quick access. */
  pinnedAt?: number;
  /** Independent sidebar placement; origin, execution ownership, and access remain unchanged. */
  sidebarRoot?: boolean;
  /** Epoch ms wake time; suppresses the active session in sidebar lists until then. */
  snoozedUntil?: number;
  /** Server-stamped epoch ms when the current snooze was set. */
  snoozedAt?: number;
  /** Timestamp (ms) when an operator client last marked the session read. */
  lastReadAt?: number;
  /** Agent-declared sidebar presence; projection drops it after expiresAt. */
  agentStatus?: SessionAgentStatus;
  /** Latest utility-model status judgment for idle session status surfaces. */
  observerDigest?: SessionObserverDigest;
  /** Versioned, reconstructible Activity recap; never authoritative task status. */
  activitySummary?: SessionActivitySummary;
  /** Timestamp (ms) when an operator explicitly marked the session unread; cleared on read. */
  markedUnreadAt?: number;
  /** Timestamp (ms) of the latest completed agent run; metadata patches do not update it. */
  lastActivityAt?: number;
  /** Parent session key that spawned this session (used for sandbox session-tool scoping). */
  spawnedBy?: string;
  /** Host-captured owner status of the spawning invocation; never inferred from child launch authority. */
  spawnedBySenderIsOwner?: boolean;
  /** Parent session id captured with the spawn authority receipt; navigation uses parentSessionId. */
  spawnedBySessionId?: string;
  /** Immutable session key authorized to receive this child's completion handoff. */
  completionOwnerSessionKey?: string;
  /** Workspace inherited by spawned sessions and reused on later turns for the same child session. */
  spawnedWorkspaceDir?: string;
  /** Task working directory inherited by spawned sessions and reused on later turns. */
  spawnedCwd?: string;
  /** Content-free fingerprints for checkout changes that predate this session generation. */
  sessionDiffBaseline?: SessionDiffBaseline;
  /** Canonical existing directory owned by the user on a paired session host. */
  deviceFolder?: {
    deviceId: string;
    path: string;
  };
  /**
   * Managed worktree bound to this session; set with spawnedCwd at worktree
   * creation and cleared together when a plain New Chat detaches the checkout.
   */
  worktree?: {
    id: string;
    branch: string;
    repoRoot: string;
    /** Durable skill workspace prepared when this session runs from a managed worktree. */
    canonicalWorkspaceDir?: string;
    githubPullRequest?: SessionGitHubPullRequestBinding;
  };
  /** Project registry id selected when this logical session node was created. */
  projectId?: string;
  /** Durable cloud repository owner; never identifies a Gateway filesystem path. */
  repositoryWorkspaceId?: string;
  /** Explicit parent session linkage for dashboard-created child sessions. */
  parentSessionKey?: string;
  /** Exact parent incarnation captured when this child was created. */
  parentSessionId?: string;
  /** Exact parent lifecycle captured for native spawn authority, including same-id resets. */
  parentSessionLifecycleRevision?: string;
  /** How this session node came to exist; written once and retained across sessionId rotations. */
  createdVia?: SessionCreatedVia;
  /** Creation-only presentation surface; stored in entry_json without a column projection. */
  createdSurface?: SessionRow["createdSurface"];
  /** Actor that caused node creation, with an optional profile, session, or sender id; written once. */
  createdActor?: SessionCreatedActor;
  /** Creation-only sandbox requirement; existing unstamped sessions always remain unstamped. */
  sandbox?: "required";
  /** Mutable responsibility, projected from SQLite; absent means createdActor owns the session. */
  owner?: SessionOwnerAssignment;
  /** Retained identities, projected from the participant table before display truncation. */
  participants?: SessionParticipant[];
  /** Raw retained identity count, including the owner, for admission-bound coverage. */
  participantCount?: number;
  /** Node creation time (ms); unlike sessionStartedAt, survives sessionId rotations. */
  createdAt?: number;
  /** Exact source generation and optional cut entry for an actual transcript-copy fork. */
  forkSource?: {
    sessionKey: string;
    sessionId: string;
    entryId?: string;
  };
  /** Session id of the prior transcript generation under this same session key. */
  previousSessionId?: string;
  /** Thread parent-seeding settled marker; also set when seeding is deliberately skipped. */
  forkedFromParent?: boolean;
  /** Subagent spawn depth (0 = main, 1 = sub-agent, 2 = sub-sub-agent). */
  spawnDepth?: number;
  /** Explicit role assigned at spawn time for subagent tool policy/control decisions. */
  subagentRole?: "orchestrator" | "leaf";
  /** Explicit control scope assigned at spawn time for subagent control decisions. */
  subagentControlScope?: "children" | "none";
  /** Spawn-time blind child: its rendered prompt omits its model, identity and workspace path. */
  blindPrompt?: true;
  /** Version of the requester tool-policy snapshot captured when this child was spawned. */
  inheritedToolPolicyVersion?: 1;
  /** Sender/channel restriction provenance retained with the inherited tool snapshot. */
  inheritedToolPolicySource?: "sender";
  /** Session-scoped tool deny entries inherited from the caller that created this session. */
  inheritedToolDeny?: string[];
  /** Session-scoped tool allow entries inherited from the caller that created this session. */
  inheritedToolAllow?: string[];
  /** Host-created native execution exception; the full inherited snapshot still owns completion. */
  delegatedToolPolicy?: {
    requesterSessionKey: string;
    targetAgentId: string;
    deny: string[];
    /** The immediate parent’s effective deny snapshot, separately from revocation fallback. */
    requesterDeny: string[];
  };
  systemSent?: boolean;
  abortedLastRun?: boolean;
  /** Quota cascade protection and state-aware failover status. */
  quotaSuspension?: QuotaSuspension;
  /** Core-owned durable goal state for this thread/session. */
  goal?: SessionGoal;
  /** Timestamp (ms) when the current sessionId first became active. */
  sessionStartedAt?: number;
  /** Stable usage lineage key for transcript-backed rollups across sessionId rotations. */
  usageFamilyKey?: string;
  /** Session ids known to belong to this usage lineage, including archived predecessors. */
  usageFamilySessionIds?: string[];
  /** Timestamp (ms) of the last user/channel interaction that should extend idle lifetime. */
  lastInteractionAt?: number;
  /** Stable first-run start time for subagent sessions, persisted after completion. */
  startedAt?: number;
  /** Latest completed run end time for subagent sessions, persisted after completion. */
  endedAt?: number;
  /** Accumulated runtime across subagent follow-up runs, persisted after completion. */
  runtimeMs?: number;
  /** Final persisted subagent run status, used after in-memory run archival. */
  status?: PersistedSessionRunStatus;
  /** Compact user-facing reason for the latest failed or timed-out run. */
  lastRunError?: string;
  /** The latest failed run is diagnostic-only, not a request for the user to retry. */
  suppressErrorNotice?: boolean;
  /**
   * Session-level stop cutoff captured when /stop is received.
   * Messages at/before this boundary are skipped to avoid replaying
   * queued pre-stop backlog.
   */
  abortCutoffMessageSid?: string;
  /** Epoch ms cutoff paired with abortCutoffMessageSid when available. */
  abortCutoffTimestamp?: number;
  chatType?: SessionChatType;
  contextWindow?: string;
  thinkingLevel?: string;
  /**
   * Exact isolated-cron continuation policy. Only hidden `:run:` session rows
   * carry this while detached generated-media work may still wake the run.
   */
  cronRunContinuation?: {
    lifecycleRevision: string;
    phase: "running" | "ready" | "continuing";
    /** True only after this row's session changes were projected to the stable cron row. */
    basePersisted?: boolean;
    ownerRunId?: string;
    /** Gateway lifecycle generation that owns a continuing claim. */
    ownerLifecycleGeneration?: string;
    /** CLI backend whose native session must exist before media work detaches. */
    cliExecutionProvider?: string;
    toolsAllow?: string[];
    toolsAllowIsDefault?: boolean;
    /** Exact server-stamped authority provenance copied from the owning cron job. */
    scheduledToolPolicy?: CronScheduledToolPolicy;
    /** Restrict-only exec pin copied from the owning cron job's cap. */
    toolsAllowExecTarget?: CronToolsAllowExecTarget;
    /** Expected pin copied with the cap so detached continuation loss fails closed. */
    toolsAllowExecTargetRequirement?: CronToolsAllowExecTargetRequirement;
    /** Store-private origin paired with an account scheduled-tool policy. */
    scheduledToolCallerOrigin?: CronScheduledToolCallerOrigin;
    cliSessionBindingFacts?: {
      extraSystemPromptStatic?: string;
      sourceReplyDeliveryMode?: "automatic" | "message_tool_only";
      requireExplicitMessageTarget?: boolean;
    };
  };
  /** Explicit requested access program; omission follows the model/project default. */
  cyberAccessProgram?: SessionRow["cyberAccessProgram"];
  fastMode?: FastMode;
  toolOverrides?: SessionToolOverrides;
  /** Swarm group for collector-mode child sessions. */
  swarmGroupId?: string;
  /** Marks non-interactive collector-mode child sessions. */
  swarmCollector?: boolean;
  /** JSON Schema exposed through the synthetic structured_output tool. */
  swarmOutputSchema?: Record<string, unknown>;
  verboseLevel?: string;
  traceLevel?: string;
  reasoningLevel?: string;
  elevatedLevel?: string;
  ttsAuto?: TtsAutoMode;
  /** Hash of the latest assistant reply that was sent through `/tts latest`. */
  lastTtsReadLatestHash?: string;
  /** Timestamp (ms) when `/tts latest` last sent audio for this session. */
  lastTtsReadLatestAt?: number;
  execHost?: string;
  execNode?: string;
  /** Working directory interpreted only by the bound exec node. */
  execCwd?: string;
  responseUsage?: "on" | "off" | "tokens" | "full";
  providerOverride?: string;
  modelOverride?: string;
  /** Last submitted selection, retained when picker edits clear runtime fields. */
  lastSubmittedModel?: {
    provider: string;
    model: string;
  };
  /** Session-scoped agent runtime/harness override selected with the model picker. */
  agentRuntimeOverride?: string;
  /**
   * Tracks whether the persisted model selection came from an explicit user
   * action (`/model`, `sessions.patch`), a temporary runtime fallback, or an
   * explicit configured-default selection that blocks parent inheritance.
   */
  modelOverrideSource?: "auto" | "user" | "default";
  /** Present only when providerOverride/modelOverride are a canonical route pair. */
  modelOverrideRouteResolution?: "resolved";
  /** Selected model that produced the current auto fallback override. */
  modelOverrideFallbackOriginProvider?: string;
  modelOverrideFallbackOriginModel?: string;
  /** One-run rollback guard for a model selected by the agent sessions tool. */
  modelFallback?: AgentPatchedSessionModelFallback;
  authProfileOverride?: string;
  authProfileOverrideSource?: "auto" | "user" | "user-link";
  authProfileOverrideCompactionCount?: number;
  /**
   * Set on explicit user-driven session model changes (for example `/model`
   * and `sessions.patch`) during an active run. The embedded runner checks
   * this flag to decide whether to throw `LiveSessionModelSwitchError`.
   * System-initiated fallbacks (rate-limit retry rotation) never set this
   * flag, so they are never mistaken for user-initiated switches.
   */
  liveModelSwitchPending?: boolean;
  groupActivation?: "mention" | "always";
  groupActivationNeedsSystemIntro?: boolean;
  sendPolicy?: "allow" | "deny";
  /** Human-selected peer messaging preferences; omitted directions inherit configuration. */
  communication?: SessionCommunicationPolicy;
  queueMode?: QueueMode;
  queueDebounceMs?: number;
  queueCap?: number;
  queueDrop?: "old" | "new" | "summarize";
  inputTokens?: number;
  outputTokens?: number;
  /** Completeness of the latest run's token and cost accounting. */
  usageReport?: {
    state: "available" | "unavailable";
  };
  totalTokens?: number;
  pendingFinalDelivery?: PendingFinalDeliveryState;
  pendingDeliveryNotice?: PendingDeliveryNoticeState;
  /**
   * Ordered durable backlog of delivered assistant finals that failed to
   * reach the canonical transcript. Session admission restores each item
   * before another turn can extend that transcript. Kept as a list so
   * independently admitted writers never overwrite an earlier reply.
   */
  pendingTranscriptRepair?: PendingTranscriptRepairState[];
  /**
   * Whether totalTokens reflects a fresh context snapshot for the latest run.
   * Undefined means legacy/unknown freshness; false forces consumers to treat
   * totalTokens as stale/unknown for context-utilization displays.
   */
  totalTokensFresh?: boolean;
  /** Version 1 records totalTokens as the current prompt/context snapshot only. */
  totalTokensVersion?: typeof SESSION_TOTAL_TOKENS_VERSION;
  estimatedCostUsd?: number;
  cacheRead?: number;
  cacheWrite?: number;
  modelProvider?: string;
  model?: string;
  /**
   * Prevents OpenClaw model changes and automatic maintenance eviction until
   * the owning harness explicitly retires the session.
   */
  modelSelectionLocked?: boolean;
  /**
   * Embedded agent harness selected for this session id.
   * Prevents config/env changes from moving an existing transcript between
   * incompatible runtime harnesses.
   */
  agentHarnessId?: string;
  fallbackNotice?: FallbackNoticeState;
  contextTokens?: number;
  /** Origin of the persisted context window; `resolved` is legacy/unverified. */
  contextTokensSource?: "runtime" | "runtime-configured" | "resolved" | "resolved-v1";
  contextBudgetStatus?: SessionContextBudgetStatus;
  compactionCount?: number;
  /** A committed lossy compaction affected this history; cleared with a new session. */
  compactionQualityDegraded?: true;
  memoryFlush?: MemoryFlushState;
  cliSessionIds?: Record<string, string>;
  cliSessionBindings?: Record<string, CliSessionBinding>;
  /** Initialization fence for seeding canonical ACP metadata; cleared after creation. */
  acpSessionBinding?: AcpSessionBinding;
  claudeCliSessionId?: string;
  label?: string;
  /** Automatic device name; never claims a custom label or overrides a generated title. */
  autoLabel?: string;
  /** Persistent sidebar emoji, named glyph, or canonical SVG image data URL. */
  icon?: string;
  /** Named sidebar tint (SESSION_COLOR_IDS); palette mirrors Claude Code /color for import. */
  color?: string;
  /** User-defined organization bucket for session lists; unrelated to chat groupId/groupChannel. */
  category?: string;
  /** Preferred Control UI face when a caller opens this session without explicit face intent. */
  boardFace?: SessionBoardFace;
  /** Shared dashboard presentation default; absence uses the built-in split view. */
  boardPresentation?: NonNullable<SessionRow["boardPresentation"]>;
  displayName?: string;
  /** Canonical delivery state. Legacy delivery fields are migrated by `openclaw doctor --fix`. */
  delivery?: SessionDeliveryState;
  groupId?: string;
  subject?: string;
  /** Display-only topic name; subject remains the group name used for routing. */
  topicName?: string;
  groupChannel?: string;
  space?: string;
  /** Last ambient room message durably appended to this transcript, keyed by channel scope. */
  ambientTranscriptWatermarks?: Record<string, AmbientTranscriptWatermark>;
  skillsSnapshot?: SessionSkillSnapshot;
  /** Explicit authorized immutable library pins; current speakers never replace this selection. */
  skillLibrarySelections?: SkillLibrarySelection[];
  systemPromptReport?: SessionSystemPromptReport;
  /**
   * Generic plugin-owned runtime debug entries shown in verbose status surfaces.
   * Each plugin owns and may overwrite only its own entry between turns.
   */
  pluginDebugEntries?: SessionPluginDebugEntry[];
  acp?: SessionAcpMeta;
};
interface SessionEntry extends SessionEntryCore {}
/** Internal durable fields excluded from public/plugin session projections. */
type SessionProfileInvolvement = {
  hidden: boolean;
  updatedAt: number;
  /** Original committed source ordering, retained when the person hides the session. */
  lastMention?: {
    generation: string;
    sequence: number;
    timestamp: number;
  };
};
type InternalSessionEntryCore = SessionEntryCore & {
  /** Atomic history-cut receipt for the exact settled local projection, cleared after adoption. */
  localWorkspaceHandoff?: {
    worktreeId: string;
    fromSessionId: string;
    toSessionId: string;
    lifecycleRevision: string | null;
    projectionRevision: number;
  };
  /** Original unbound files, private to this conversation's adopted workspace. */
  priorWorkspace?: {
    worktreeId: string;
    sessionId: string;
    workspaceDir: string;
    fileRoot: string;
    through: {
      generation: string | null;
      maxSeq: number | null;
    };
  };
  /** Personal discovery state, never participation, attribution, or sharing authority. */
  profileInvolvement?: {
    key: string;
    profiles: Record<string, SessionProfileInvolvement>;
  };
  /** Transcript-wide account provenance; native binding replacement must not replace it. */
  cliHistoryBoundary?: CliHistoryBoundary;
  /** Explicit world-readable publication, bound to one transcript generation. */
  publicShare?: {
    id: string;
    sessionId: string;
    createdAt: number;
  };
  /** Run that owns the current non-terminal Gateway lifecycle projection. */
  lifecycleRunId?: string;
  /** Exact run that produced the latest terminal Gateway lifecycle projection. */
  lastRunId?: string;
  /** Run admitted by the session lane; overwritten at admission and checked by transcript writes. */
  activeWriterRunId?: string;
  /** Canonical remote repository awaiting preparation by this exact session generation. */
  pendingProjectGitUrl?: string;
  /** Authorized worktree intent awaiting preparation by an admitted turn. */
  pendingWorktree?: PendingSessionWorktree;
  /** Suppresses repeated byte-triggered compaction after an oversized successor was observed. */
  transcriptByteCompactionLatch?: {
    activeBytes: number;
    sessionId: string;
    maxBytes: number;
  };
  /** Private per-generation ownership for the pre-runtime checkout baseline capture. */
  sessionDiffBaselineCapture?: SessionDiffBaselineCapture;
  /** Written only by committed graceful shutdown, consumed by the next startup. */
  resumeAfterRestart?: {
    queuedInputIds: string[];
    /** Original per-input limits, restored only after current source revalidation. */
    queuedInputSources?: Record<string, {
      runId: string;
      source: QueuedOperatorRecoverySource;
    }>;
    hadBackgroundExec?: true;
  };
  /** Latest authenticated source per person; private evidence revalidated before recovery. */
  operatorSources?: Record<string, OperatorRunRecoverySnapshot>;
  /** Upgrade-only cycle; remove once stable includes the restart redesign (#185730). */
  mainRestartRecovery?: {
    cycleId: string;
  };
};
interface InternalSessionEntry extends InternalSessionEntryCore {}
type GroupKeyResolution = {
  key: string;
  channel?: string;
  id?: string;
  chatType?: SessionChatType;
};
//#endregion
export { generateConversationLabel as $, SessionUpstreamKind as $A, replaceRuntimeAuthProfileStoreSnapshotsAsync as $C, resolveAgentDir as $D, ChannelIngressIdentityDescriptor as $E, PluginStateEntry as $O, ProviderAppGuidedSetupContext as $S, updateLastRoute as $T, resolveChannelSourceReplyDeliveryMode as $_, DecisionBatchResultV2 as $a, createNormalizedOutboundDeliverer as $b, DeviceBootstrapPurpose as $c, resolveTailscaleServeGatewayUrlsWithRunner as $d, migrateBaseNameToDefaultAccount as $f, matchesMentionPatterns as $g, DurableMessageBatchSendResult as $h, shouldPreemptivelyCompactBeforePrompt as $i, ChannelProgressDraftLine as $j, chunkTextWithMode as $k, createNativeApprovalForwardingFallbackSuppressorAsync as $l, sanitizeForPlainText as $m, hasBeforeToolCallPolicy as $n, isMessagingToolSendAction as $o, parseMediaContentLength as $p, InternalHookEvent as $r, isDeliveredMessageToolOnlySourceReplyResult as $s, AgentHarnessNativeCompaction as $t, buildBaseAccountStatusSnapshot as $u, resolveScopeRequireMention as $v, PluginHeartbeatPromptContributionEvent as $w, ProviderPlugin as $x, resolveThreadBindingsEnabled as $y, SessionCatalogEntrySummary as A, ChannelThreadingToolContext as AA, markAuthProfileBlockedUntil as AC, resolveChannelImplicitMentions as AD, SessionTranscriptVisibleMessageDeltaResult$1 as AE, TranscriptStopRequest as AO, ProviderReplaySessionState as AS, SessionStoreSelectedEntry as AT, PublicReplyParams as A_, assignSafeServerNames as Aa, resolveTelegramToken as Ab, AgentPromptGuidance as Ac, defineChannelPluginEntry as Ad, MemoryPromptSectionBuilder as Af, toInboundMediaFactsWithMetadata as Ag, createChannelIngressMonitor as Ah, prepareWatchedSessionsHarnessContext as Ai, compactChannelProgressDraftLine as Aj, ChannelDirectoryAdapter as Ak, resolveApprovalApprovers as Al, isPotentialTruncatedFinal as Am, CodeModeConfig as An, isAgentToolReplaySafe as Ao, renderQrTerminal as Ap, OpenClawPluginSessionsChangedEvent as Ar, AgentToolResultMiddlewareEvent as As, getTtsProvider as At, formatApprovalDisplayPath as Au, ExecSessionDefaults as Av, PluginSessionActionContext as Aw, buildJsonPluginConfigSchema as Ax, resolveDmGroupAccessWithLists as Ay, listAdoptedSessionCatalogSessions as B, ChannelMessageUnknownSendReconciliationResult as BA, loadAuthProfileStoreForRuntime as BC, resolveSystemEventDeliveryContext as BD, OAuthCredentials as BE, RealtimeVoiceBrowserSessionCreateRequest as BO, ProviderNormalizeTransportContext as BS, loadTranscriptEvents as BT, filterChannelInboundQuoteContext as B_, normalizeProviderToolSchemas as Ba, hasConfiguredAccountValue as Bb, DEFAULT_PLUGIN_NODE_CAPABILITY_TTL_MS as Bc, isLoopbackHost as Bd, createEmptyChannelResult as Bf, DurableInboundReplyDeliveryParams as Bg, bindIngressLifecycleToReplyOptions as Bh, getAgentHarnessHookRunner as Bi, resolveChannelPreviewStreamMode as Bj, ChannelResolveResult as Bk, createChannelExecApprovalProfile as Bl, defineFinalizableLivePreviewAdapter as Bm, EMPTY_CODE_MODE_OUTPUT as Bn, resolveToolResultFailureKind as Bo, runFfmpeg as Bp, PersonalGitHubSessionActionV2 as Br, assertContextEngineHostSupport as Bs, ResolvedTtsModelOverrides as Bt, buildTypedApprovalPresentation as Bu, createDangerousNameMatchingMutableAllowlistWarningCollector as Bv, PluginSessionTurnUnscheduleByTagParams as Bw, redactSensitiveText as Bx, readChannelAllowFromStoreSync as By, markReplyPayloadAsTtsSupplement as C, ChannelMessageToolSchemaContribution as CA, isProviderApiKeyConfigured as CC, InboundMentionPolicy as CD, deliveryContextFromSession as CE, SessionStoreAgentIdRequiredError as CM, WorkerProfile as CO, UsageWindow as CS, PluginConversationBindingResolvedEvent as CT, resolveGroupThreadMentionFacts as C_, createWorkspaceBootstrapFilePolicy as Ca, resolveTelegramAccount as Cb, AgentHarnessUserInputOption as Cc, ChannelOutboundSessionRouteParams as Cd, MemoryEmbeddingProviderCreateOptions as Cf, ChannelInboundMediaPayload as Cg, DraftStreamLoop as Ch, detectAndLoadAgentHarnessPromptImages as Ci, AgentApprovalEventData as Cj, WizardPrompter as Ck, formatApprovalDecisionLabel as Cl, ChannelProgressDraftRenderMode as Cm, CodeModeExecutorInlineHost as Cn, buildHarnessVisibleReplyGuidance as Co, transcribeFirstAudio as Cp, OpenClawPluginServiceContext as Cr, CodexAppServerExtensionContext as Cs, enqueueSystemEventEntryFromSdk as Ct, doesApprovalRequestSelectChannelAccount as Cu, InternalGetReplyFromConfig as Cv, PluginAgentEventEmitParams as Cw, renderPresentationForDelivery as Cx, createOpenProviderGroupPolicyWarningCollector as Cy, SessionCatalogContinueProviderParams as D, ChannelStatusIssue as DA, listUsableProviderAuthProfileIds as DC, implicitMentionKindWhen as DD, rethrowIncognitoSessionError as DE, WorkerSshIdentity as DO, ProviderReplayPolicy as DS, ApplySessionEntryPatchParams as DT, hasFinalChannelTurnDispatch as D_, resolveWritableSandboxBindHostRoots as Da, mergeTelegramAccountConfig as Db, resolveActiveSessionRunId as Dc, buildThreadAwareOutboundSessionRoute as Dd, MemoryPluginPublicArtifact as Df, formatMediaPlaceholderText as Dg, processPidFromOwnerId as Dh, materializeRequesterScopedMcpToolsForHarnessRun as Di, AgentPlanStepStatus as Dj, ChannelApprovalCapability as Dk, buildPluginApprovalPendingReplyPayload as Dl, resolveChannelProgressDraftRender as Dm, CodeModeFailureCode as Dn, SKILL_WORKSHOP_TOOL_NAME as Do, createScopedChannelMediaMaxBytesResolver as Dp, PluginInteractiveRegistration as Dr, CodexAppServerToolResultHandlerResult as Ds, peekSystemEventEntriesFromSdk as Dt, resolveApprovalRequestChannelAccountId as Du, SessionMcpRuntime as Dv, PluginRunContextGetParams as Dw, presentationPageSize as Dx, projectConfigWarningCollector as Dy, SessionCatalogArchiveProviderParams as E, ChannelSecurityDmPolicy as EA, isProviderAuthProfileConfiguredAsync as EC, ResolveInboundMentionDecisionParams as ED, sessionDeliveryRoute as EE, WorkerSshEndpoint as EO, ProviderReasoningOutputModeContext as ES, StickyModelSelectionDispatchOutcome as ET, getGroupThreadDeliverySession as E_, hasSandboxBindReadonlyHostShadows as Ea, listTelegramAccountIds as Eb, abortEmbeddedAgentRun as Ec, buildChannelOutboundSessionRoute as Ed, MemoryPluginCapability as Ef, formatInboundMediaUnavailableText as Eg, INGRESS_CLAIM_PROCESS_ID as Eh, loadCodexBundleMcpThreadConfig as Ei, AgentPlanStep as Ej, ChannelApprovalAdapter as Ek, buildApprovalResolvedReplyPayload as El, preserveReplyPayloadMediaSelection as Em, CodeModeExecutorStartInput as En, resolveMainSessionDelegationMode as Eo, createDirectTextMediaOutbound as Ep, PluginInteractiveHandlerRegistration as Er, CodexAppServerToolResultEvent as Es, isSystemEventContextChangedFromSdk as Et, resolveApprovalRequestAccountIdAsync as Eu, McpToolCatalog as Ev, PluginControlUiDescriptor as Ew, applyPresentationActionLimits as Ex, projectConfigAccountIdWarningCollector as Ey, SessionCatalogTerminalPlan as F, ChannelMessageSendMediaContext as FA, ensureAuthProfileStore as FC, ReplyDispatcher as FD, getSessionEntryByIdAsync as FE, RealtimeVoiceBridge as FO, ProviderValidateReplayTurnsContext as FS, getConversationSession as FT, ChannelInboundSupplementalResolutionOptions as F_, RuntimeToolInputSchemaProjection as Fa, resolveAccountWithDefaultFallback as Fb, PluginCommandResult as Fc, isAllowedParsedChatSender as Fd, ChannelSendRawResult as Ff, isChannelPartialDeliveryError as Fg, ChannelIngressMonitorPayloadCodec as Fh, buildEmbeddedForegroundPromptContext as Fi, formatPlanChecklistLines as Fj, ChannelDoctorSequenceResult as Fk, createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutesAsync as Fl, createMessageReceiveContext as Fm, CodeModeWorkerThreadResult as Fn, readToolOperatorHint as Fo, fillPixel as Fp, AgentTurnStartOwner as Fr, CompactEmbeddedAgentSessionParams as Fs, normalizeCapabilityProviderId as Ft, buildApprovalButtonPresentation as Fu, TelegramThreadSpec as Fv, PluginSessionExtensionProjection as Fw, PluginCapabilityCatalogContext as Fx, buildPluginBindingApprovalCustomId as Fy, PluginRuntime as G, OutboundSendDeps as GA, prepareAuthProfileProvider as GC, TrustedSubagentCompletionHandoff as GD, resolveCommandAuthorization as GE, RealtimeVoiceTool as GO, ProviderPreparedRuntimeAuth as GS, readAmbientTranscriptWatermarkAsync as GT, ChannelTurnRecordOptions as G_, applyEmbeddedAttemptToolsAllow as Ga, createAccountActionGate as Gb, normalizePluginNodeCapabilityScopedUrl as Gc, resolveGatewayBindUrl as Gd, clearAccountFieldsFromConfigSection as Gf, ClassifyChannelInboundEventParams as Gg, ChannelIngressQueueClaimRef as Gh, runAgentHarnessAfterToolCallHook as Gi, resolveChannelStreamingBlockEnabled as Gj, ChannelOutboundPayloadHint as Gk, matchesApprovalRequestFilters as Gl, verifyChannelMessageReceiveAckPolicyAdapterProofs as Gm, z$1 as Gn, captureToolAuthoredSourceReply as Go, FetchLike as Gp, prepareGitHubPublicationRequesterV2 as Gr, ExecAutoReviewer as Gs, AgentHarnessAttemptParams as Gt, parseExecApprovalCommandText as Gu, resolveSenderScopedGroupPolicy as Gv, PluginHookReplyDispatchContext as Gw, readProviderJsonResponse as Gx, formatThreadBindingDisabledError as Gy, normalizeUserText as H, MessageReceiptPart as HA, loadAuthProfileStoreForSecretsRuntime as HC, RateLimitConfig as HD, ProviderModel as HE, RealtimeVoiceProviderCapabilities as HO, ProviderPrepareExtraParamsContext as HS, patchSessionEntry as HT, finalizeChannelInboundContext as H_, finalizeAgentToolAvailability as Ha, resolveListedDefaultAccountId as Hb, PLUGIN_NODE_CAPABILITY_PATH_PREFIX as Hc, isTrustedProxyAddress as Hd, getChatChannelMeta as Hf, DEFAULT_CHANNEL_FEEDBACK_REFLECTION_COOLDOWN_MS as Hg, DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS as Hh, runAgentHarnessBeforeAgentFinalizeHook as Hi, resolveChannelProgressDraftMaxLineChars as Hj, ChannelPairingAdapter as Hk, isChannelExecApprovalClientEnabledFromConfig as Hl, verifyChannelMessageAdapterCapabilityProofs as Hm, captureCodeModeOutput as Hn, sanitizeToolResult as Ho, transcodeAudioBuffer as Hp, GitHubPublicationSessionRequestV2 as Hr, resolveRequesterToolPolicies as Hs, OpenClawPluginConfigSchema as Ht, formatExecApprovalExpiresIn as Hu, evaluateGroupRouteAccessForPolicy as Hv, PluginToolMetadataRegistration as Hw, formatErrorMessage as Hx, readChannelAllowFromStore as Hy, SessionUpstreamActivity as I, ChannelMessageSendPayloadContext as IA, ensureAuthProfileStoreAsync as IC, ReplyFollowupAdmissionBarrierTimeoutPolicy as ID, SessionEntryPatchAuthority as IE, RealtimeVoiceBridgeCallbacks as IO, ProviderAuthDoctorHintContext as IS, getConversationSessionAsync as IT, FinalizeChannelInboundContextAsyncParams as I_, RuntimeToolSchemaDiagnostic as Ia, listConfiguredAccountIds as Ib, GatewayAgentRunTaskOwner as Ic, stripChannelTargetPrefix as Id, attachChannelToResult as If, createMessageReceiptFromOutboundResults as Ig, CreateChannelIngressMonitorOptions as Ih, awaitAgentEndSideEffects as Ii, isChannelProgressDraftWorkToolName as Ij, ChannelGatewayAdapterV2 as Ik, createChannelApprovalCapability as Il, LivePreviewDeliveryResult as Im, PendingBridgeRequest as In, ToolResultFailureKind as Io, resolveOutboundAttachmentFromUrl as Ip, RequesterSettleWakeReplay as Ir, EmbeddedForegroundPromptContext as Is, TtsConfigResolutionContext as It, buildApprovalPresentationFromActionDescriptors as Iu, ChannelMutableAllowlistCandidate as Iv, PluginSessionExtensionRegistration as Iw, PluginCapabilityCatalogEntry as Ix, buildPluginBindingResolvedText as Iy, DispatchReplyWithBufferedBlockDispatcher$1 as J, meetsIdentifierAuthentication as JA, updateAuthProfileStoreWithLock as JC, AgentModelPrimaryWriteTarget as JD, ChannelIngressCommandPresetInput as JE, PluginCommandReplyOptions as JO, ProviderResolvedUsageAuth as JS, readSessionUpdatedAtAsync as JT, ChannelBotLoopProtectionFacts as J_, resolveAttemptSpawnWorkspaceDir as Ja, TelegramInlineButtons as Jb, DevicePairingApprovalOptions as Jc, prepareMemorySystemPromptAddition as Jd, applyAccountNameToChannelSection as Jf, resolveInboundSessionEnvelopeContext as Jg, OutboundMessageIdentity as Jh, LlmBoundaryTokenPressure as Ji, resolveChannelStreamingPreviewToolProgress as Jj, ChunkMode as Jk, isImplicitSameChatApprovalAuthorization as Jl, createChannelMessageAdapterFromOutbound as Jm, createOpenClawCodingTools as Jn, extractMessagingToolSourceReplyPayload as Jo, fetchRemoteMedia as Jp, resolveStoredModelOverride as Jr, projectAgentHarnessTranscriptMessageForDisplay as Js, AgentHarnessAuthBindingFingerprintParams as Jt, collectTelegramUnmentionedGroupIds as Ju, ScopeTree as Jv, PluginHookReplyPayloadSendingContext as Jw, readResponseWithLimit as Jx, resolveThreadBindingIdleTimeoutMs as Jy, channelIngressRoutes as K, resolveOutboundSendDep as KA, resolvePersistedAuthProfileOwnerAgentDirAsync as KC, RuntimePluginToolGrant as KD, resolveCommandAuthorizationAsync as KE, RealtimeVoiceToolCallEvent as KO, ProviderResolveDynamicModelContext as KS, readSessionStoreTranscriptStatsSync as KT, CommandFacts as K_, resolveEmbeddedAttemptToolConstructionPlan as Ka, TelegramButtonStyle as Kb, RespondFn as Kc, buildMemorySystemPromptAddition as Kd, deleteAccountFromConfigSection as Kf, classifyChannelInboundEvent as Kg, ChannelIngressQueueCorruptClaim as Kh, runAgentHarnessBeforeMessageWriteHook as Ki, resolveChannelStreamingChunkMode as Kj, OutboundIdentity as Kk, createChannelApprovalAuth as Kl, verifyDurableFinalCapabilityProofs as Km, extractEmbeddedAssistantText as Kn, extractMessagingToolSend as Ko, MediaFetchError as Kp, NodeSession as Kr, fingerprintResolvedAuthProfileCredential as Ks, AgentHarnessAttemptParamsV2 as Kt, resolveTelegramRuntimeGroupPolicy as Ku, ScopeNode as Kv, PluginHookReplyDispatchResult as Kw, readProviderTextResponse as Kx, formatThreadBindingSpawnDisabledError as Ky, SessionUpstreamProbe as L, ChannelMessageSendResult as LA, ensureAuthProfileStoreForLocalUpdate as LC, NormalizedUsage as LD, AmbientTranscriptWatermarkScope as LE, RealtimeVoiceBridgeCreateRequest as LO, ProviderFetchUsageSnapshotContext as LS, getSessionEntry as LT, FinalizeChannelInboundContextParams as L_, filterProviderNormalizableTools as La, createAccountListHelpers as Lb, GatewayNodeInvokeStream as Lc, stripTargetKindPrefix as Ld, attachChannelToResults as Lf, listMessageReceiptPlatformIds as Lg, ChannelIngressDrain as Lh, runAgentEndSideEffects as Li, mergeChannelProgressDraftLine as Lj, ChannelGatewayContext as Lk, splitChannelApprovalCapability as Ll, LivePreviewLifecycle as Lm, SettledBridgeRequest as Ln, formatToolExecutionErrorMessage as Lo, probeVideoDimensions as Lp, GatewayMethodDispatchResponse as Lr, AgentHarnessRuntimeArtifactBinding as Ls, resolveEffectiveTtsConfig as Lt, buildExecApprovalActionDescriptors as Lu, buildMutableAllowEntryDetector as Lv, PluginSessionSchedulerJobHandle as Lw, PluginCapabilityCatalogHostContext as Lx, parsePluginBindingApprovalCustomId as Ly, SessionCatalogProvider as M, ChannelLegacyStateMigrationPlan as MA, isProfileInCooldown as MC, ReplyDispatchBeforeDeliverOptions as MD, readRecentUserAssistantTextForSession as ME, TranscriptsStopResult as MO, ProviderSanitizeReplayHistoryContext as MS, applySessionEntryPatch as MT, BuildChannelInboundEventContextAsyncParams as M_, logAgentRuntimeToolDiagnostics as Ma, resolveTelegramTransport as Mb, AgentPromptSurfaceKind as Mc, ensureConfiguredAcpBindingReady as Md, EmbeddingInput as Mf, createChannelDeliveryAccumulator as Mg, ChannelIngressMonitorDrainOptions as Mh, setActiveEmbeddedRun as Mi, formatChannelProgressDraftLine as Mj, ChannelDoctorConfigMutation as Mk, createApproverRestrictedNativeApprovalCapability as Ml, selectLongerFinalText as Mm, CodeModeWorkerBoundary as Mn, listAgentIdsCompatibility as Mo, renderQrPngDataUrl as Mp, GatewayRequestHandlerOptions as Mr, AgentToolResultMiddlewareResult as Ms, resolveTtsConfig as Mt, ExecApprovalPendingReplyParams as Mu, resolveExecApprovalRequestAllowedDecisions as Mv, PluginSessionActionResult as Mw, emptyPluginConfigSchema as Mx, resolvePinnedMainDmOwnerFromAllowlist as My, SessionCatalogReadProviderParams as N, ChannelMessageAdapterShape as NA, resolveProfileUnusableUntilForDisplay as NC, ReplyDispatchKind as ND, isTranscriptOnlyOpenClawAssistantMessage as NE, RealtimeVoiceAudioClearReason as NO, ProviderSanitizeReplayHistoryContextV2 as NS, cleanupSessionLifecycleArtifacts as NT, BuildChannelInboundEventContextParams as N_, normalizeAgentRuntimeTools as Na, shouldRetryTelegramTransportFallback as Nb, OpenClawPluginCommandDefinition as Nc, getChatChannelMetaForSdk as Nd, RemoteEmbeddingClient as Nf, ChannelPartialDeliveryError as Ng, ChannelIngressMonitorFacts as Nh, toolPolicy as Ni, formatChannelProgressDraftLineForEntry as Nj, ChannelDoctorEmptyAllowlistAccountContext as Nk, createApproverRestrictedNativeApprovalCapabilityAsync as Nl, MessageAckPolicy as Nm, CodeModeWorkerContinuation as Nn, resolveSessionAgentIdCompatibility as No, writeQrPngTempFile as Np, GatewayRequestHandlers as Nr, AgentToolResultMiddlewareRuntime as Ns, resolveTtsPrefsPath as Nt, ExecApprovalReplyDecision as Nu, NativeSubagentCommandFactory as Nv, PluginSessionAttachmentParams as Nw, SuggestedWorkerProfile as Nx, readChannelIngressStoreAllowFromForDmPolicy as Ny, SessionCatalogContinueProviderResult as O, ChannelStructuredComponents as OA, listUsableProviderAuthProfileIdsAsync as OC, resolveInboundMentionDecision as OD, SessionTranscriptMessageEntry as OE, WorkerSshIdentityRequest as OO, ProviderReplayPolicyContext as OS, PrepareSessionEntryPatchParams as OT, hasVisibleChannelTurnDispatch as O_, splitSandboxBindSpec as Oa, resolveTelegramAccountConfig as Ob, CodexBundleMcpThreadConfig as Oc, createChannelPluginBase as Od, MemoryPluginPublicArtifactsProvider as Of, toHistoryMediaEntries as Og, createChannelIngressError as Oh, mcpStdioRuntime as Oi, buildChannelProgressDraftLine as Oj, ChannelCommandConversationContext as Ok, buildPluginApprovalResolvedReplyPayload as Ol, sendDurableMessageBatch as Om, CodeModeWorkerResult as On, buildSkillWorkshopPromptSection as Oo, resolveChannelMediaMaxBytes as Op, OpenClawPluginGatewayEventScope as Or, AgentToolResultMiddleware as Os, peekSystemEventsFromSdk as Ot, resolveApprovalRequestChannelAccountIdAsync as Ou, CommandSessionMetadataChange as Ov, PluginRunContextPatch as Ow, ProviderBuiltInModelSuppressionContext as Ox, projectWarningCollector as Oy, SessionCatalogStartTerminalProviderParams as P, ChannelMessageDurableFinalAdapter as PA, resolveProfilesUnavailableReason as PC, ReplyDispatchRuntimeInfo as PD, getSessionEntryAsync as PE, RealtimeVoiceBargeInOptions as PO, ProviderToolSchemaDiagnostic as PS, deleteSessionEntry as PT, BuiltChannelInboundEventContext as P_, RuntimeToolInputSchemaJson as Pa, makeProxyFetch as Pb, PluginCommandContext as Pc, recoverCurrentThreadSessionId as Pd, EmbeddingProvider as Pf, createChannelPartialDeliveryError as Pg, ChannelIngressMonitorLifecycle as Ph, inferToolMetaFromArgsCore as Pi, formatChannelProgressDraftText as Pj, ChannelDoctorLegacyConfigRule as Pk, createApproverRestrictedNativeApprovalCapabilityFromForwardingRoutes as Pl, MessageReceiveContext as Pm, CodeModeWorkerPayload as Pn, resolveSessionAgentIdsCompatibility as Po, encodePngRgba as Pp, GatewayRequestOptions as Pr, OpenClawAgentToolResult as Ps, resolveTtsPrefsPathAsync as Pt, ExecApprovalReplyMetadata as Pu, finalizeInboundContextForSdk as Pv, PluginSessionAttachmentResult as Pw, WorkerProfileSuggestionDiscovery as Px, resolveChannelIngressEffectiveAllowFromLists as Py, ConversationLabelParams as Q, SessionUpstreamLinkInput as QA, replaceRuntimeAuthProfileStoreSnapshots as QC, resolveAgentContextLimits as QD, ChannelIngressIdentityAlias as QE, PluginStateComparisonCondition as QO, ProviderAppGuidedSetupCandidate as QS, resolveTranscriptSessionKeyBySessionId as QT, createChannelReplyPipeline as Q_, DecisionAnswerV2 as Qa, ReplyPayload as Qb, DeviceBootstrapProfileInput as Qc, resolveTailscalePublishedHost as Qd, createSetupInputPresenceValidator as Qf, buildMentionRegexes as Qg, projectAgentActivityItem as Qh, formatPrePromptPrecheckLog as Qi, selectPlanChecklistSteps as Qj, chunkText as Qk, createNativeApprovalForwardingFallbackSuppressor as Ql, createChannelProgressWorkCounter as Qm, getBeforeToolCallPolicyDiagnosticState as Qn, isMessagingTool as Qo, getMediaDir as Qp, getPluginRuntimeGatewayRequestScope as Qr, AgentHarnessSessionSupersededError as Qs, AgentHarnessModelCatalogParams as Qt, AccountStatusSnapshot as Qu, resolveScopeKeyCaseInsensitive as Qv, PluginAgentTurnPrepareResult as Qw, PluginCapabilityCatalog as Qx, resolveThreadBindingSpawnPolicy as Qy, createSessionCatalogAdoptionCoordinator as R, ChannelMessageSendTextContext as RA, ensureAuthProfileStoreForLocalUpdateAsync as RC, normalizeUsage as RD, resolveAmbientTranscriptWatermarkKey as RE, RealtimeVoiceBridgeEvent as RO, ProviderNormalizeModelIdContext as RS, listSessionEntries as RT, FinalizeChannelInboundContextResult as R_, inspectRuntimeToolInputSchemas as Ra, describeAccountSnapshot as Rb, TrustedAgentToolCaller as Rc, resolveConfiguredAcpBindingRecord as Rd, buildChannelSendResult as Rf, resolveMessageReceiptPrimaryId as Rg, DEFAULT_INGRESS_ADOPTION_STALL_MS as Rh, runAgentEndSideEffectsAsync as Ri, normalizeAgentPlanSteps as Rj, ChannelGatewayContextV2 as Rk, createChannelNativeApprovalRuntime as Rl, createLivePreviewLifecycle as Rm, CodeModeNamespaceDescriptor as Rn, isToolResultError as Ro, parseFfprobeCodecAndSampleRate as Rp, CliDeps as Rr, EmbeddedBlockChunker as Rs, normalizeTtsAutoMode as Rt, buildExecApprovalPendingReplyPayload as Ru, coerceNativeSetting as Rv, PluginSessionSchedulerJobRegistration as Rw, PluginCapabilityCatalogHostEntry as Rx, requestPluginConversationBinding as Ry, isReplyPayloadTtsSupplement as S, ChannelMessageToolDiscovery as SA, createRealtimeTranscriptionWebSocketSession as SC, InboundMentionFacts as SD, projectSessionDeliveryFields as SE, resolveGatewayPublicOrigin as SM, WorkerMachineOption as SO, UsageProviderId as SS, PluginConversationBindingRequestResult as ST, resolveGroupThreadConfig as S_, resolveBootstrapFilesForRun as Sa, resolveDefaultTelegramAccountId as Sb, AgentHarnessUserInputAnswers as Sc, createChannelConfigUiHints as Sd, MemoryEmbeddingProviderAdapter as Sf, ChannelInboundMediaInput as Sg, takeMessageIdAfterStop as Sh, clearActiveEmbeddedRun as Si, resetAgentEventsForTest as Sj, WizardProgress as Sk, buildSystemAgentApprovalResolvedText as Sl, StickerMetadata as Sm, CodeModeExecutorId as Sn, buildCredentialSafetyPrompt as So, resolveAutoImageModel as Sp, OpenClawPluginService as Sr, NativeHookRelayRegistrationHandle as Ss, enqueueRoutedSystemEvent as St, doesApprovalRequestMatchChannelAccountAsync as Su, createTypingCallbacks as Sv, resolveFastModeForElapsed as Sw, reduceInteractiveReply as Sx, createOpenProviderConfiguredRouteWarningCollector as Sy, stripReplyPayloadResponsePrefix as T, ChannelOutboundSessionRoute as TA, isProviderAuthProfileConfigured as TC, ResolveInboundMentionDecisionNestedParams as TD, sessionDeliveryOrigin as TE, resolveSessionTranscriptsDirForAgent as TM, WorkerProviderError as TO, ProviderReasoningOutputMode as TS, ConversationRecallContext as TT, GroupThreadTurn as T_, hasSandboxBindContainerPathAliases as Ta, resolveTelegramPollActionGateState as Tb, abortAndDrainEmbeddedAgentRun as Tc, ThreadAwareOutboundSessionRouteThreadSource as Td, MemoryEmbeddingProviderRuntime as Tf, buildChannelInboundMediaPayload as Tg, createTypingKeepaliveLoop as Th, loadAgentHarnessMcpConfig as Ti, PreparedSessionSourceAssertion as Tj, ChannelAllowlistAdapter as Tk, buildApprovalPendingReplyPayload as Tl, deliverStructuredInboundReplyWithMessageSendContext as Tm, CodeModeExecutorRunOptions as Tn, buildDelegationGuidanceSection as To, resolveDefaultMediaModel as Tp, OpenClawPluginServiceV2 as Tr, CodexAppServerExtensionRuntime as Ts, hasSystemEventsFromSdk as Tt, resolveApprovalRequestAccountId as Tu, EmbeddedAgentCompactResult as Tv, PluginAgentEventSubscriptionRegistration as Tw, adaptMessagePresentationForChannel as Tx, projectAccountWarningCollector as Ty, sessionCatalogAdoptedSessionKey as U, MessageReceiptPartKind as UA, loadAuthProfileStoreWithoutExternalProfiles as UC, GatewayScheduler as UD, ProviderStreamOptions as UE, RealtimeVoiceResponseOutcome as UO, ProviderPrepareRuntimeAuthContext as US, prepareSessionEntryPatch as UT, resolveInboundSupplementalSenderAllowed as U_, getPluginToolMeta as Ua, mergeAccountConfig as Ub, buildPluginNodeCapabilityScopedHostUrl as Uc, resolveClientIp as Ud, PAIRING_APPROVED_MESSAGE as Uf, recordChannelFeedbackEvent as Ug, ChannelIngressQueue as Uh, runAgentHarnessLlmInputHook as Ui, resolveChannelProgressDraftMaxLines as Uj, ChannelOutboundAdapter as Uk, isChannelExecApprovalTargetRecipient as Ul, verifyChannelMessageLiveCapabilityAdapterProofs as Um, captureCodeModeValue as Un, extractToolResultMediaArtifact as Uo, transcodeAudioBufferToOpus as Up, GitHubPublicationRequesterPolicyV2 as Ur, ExecAutoReviewDecision as Us, OpenClawPluginApi as Ut, getExecApprovalApproverDmNoticeText as Uu, evaluateSenderGroupAccessForPolicy as Uv, PluginTrustedToolPolicyRegistration as Uw, formatUncaughtError as Ux, buildPairingReply as Uy, listSessionCatalogEntries as V, MessageReceipt as VA, loadAuthProfileStoreForRuntimeAsync as VC, AuthRateLimiter as VD, ProviderContext as VE, RealtimeVoiceGatewayControl as VO, ProviderPrepareDynamicModelContext as VS, loadTranscriptEventsSyncLegacy as VT, filterChannelInboundSupplementalContext as V_, disposeRegisteredAgentHarnesses as Va, listCombinedAccountIds as Vb, NormalizedPluginNodeCapabilityUrl as Vc, isPrivateOrLoopbackHost as Vd, createRawChannelSendResultAdapter as Vf, ChannelFeedbackReflectionResult as Vg, DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS as Vh, runAgentHarnessAgentEndHook as Vi, resolveChannelProgressDraftConfig as Vj, ChannelStatusAdapter as Vk, createChannelExecApprovalProfileAsync as Vl, deliverWithFinalizableLivePreviewAdapter as Vm, boundCodeModeError as Vn, extractToolErrorMessage as Vo, runFfprobe as Vp, GitHubPublicationClaimRequestV2 as Vr, resolveFastModeState as Vs, OpenClawPluginDefinition as Vt, buildTypedExecApprovalPendingReplyPayload as Vu, createRestrictSendersChannelSecurity as Vv, PluginSessionTurnUnscheduleByTagResult as Vw, redactToolPayloadText as Vx, upsertChannelPairingRequest as Vy, sessionCatalogAdoptedSourceKey as W, MessageReceiptSourceResult as WA, loadAuthProfileStoreWithoutExternalProfilesAsync as WC, SubagentCompletionToolHandoffRegistration as WD, CommandAuthorization as WE, RealtimeVoiceRole as WO, ProviderPrepareRuntimeAuthContextV2 as WS, readAmbientTranscriptWatermark as WT, ChannelTurnDroppedHistoryOptions as W_, getPluginToolSideEffectOwnerKey as Wa, resolveMergedAccountConfig as Wb, mintPluginNodeCapabilityToken as Wc, GatewayBindUrlResult as Wd, clearAccountEntryFields as Wf, runChannelFeedbackReflection as Wg, ChannelIngressQueueClaim as Wh, runAgentHarnessLlmOutputHook as Wi, resolveChannelStreamingBlockCoalesce as Wj, ChannelOutboundContext as Wk, ApprovalRequestFilterInput as Wl, verifyChannelMessageLiveFinalizerProofs as Wm, CodeModeApiVirtualFile as Wn, filterToolResultMediaUrls as Wo, MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS as Wp, GitHubPublicationRequesterV2 as Wr, ExecAutoReviewInput as Ws, AgentHarness as Wt, getExecApprovalReplyMetadata as Wu, normalizeAllowFromList as Wv, PluginHookInboundClaimResult as Ww, createProviderHttpError as Wx, resolvePairingIdLabel as Wy, dispatchReplyWithBufferedBlockDispatcher as X, SandboxFsBridge as XA, resolvePersistedAuthProfileOwnerAgentDir as XC, setAgentEffectiveModelPrimary as XD, ChannelIngressContextBinding as XE, PluginStateCompareIntent as XO, ProviderUsageAuthToken as XS, recordSessionMetaFromInbound as XT, ChannelReplyPipeline as X_, buildAfterTurnRuntimeContextFromUsage as Xa, OutboundReplyPayload as Xb, BOOTSTRAP_HANDOFF_OPERATOR_SCOPES as Xc, TailscaleStatusCommandRunner as Xd, createEnvPatchedAccountSetupAdapter as Xf, createChannelInboundDebouncer as Xg, recordOutboundMessageIdentity as Xh, PreemptiveCompactionDecision as Xi, resolveChannelStreamingProgressNarration as Xj, chunkMarkdownText as Xk, createNativeApprovalChannelRouteGates as Xl, deriveDurableFinalDeliveryRequirements as Xm, getBeforeToolCallFailureDisposition as Xn, projectPluginMessageDeliveryFact as Xo, saveRemoteMedia as Xp, resolveSessionModelRef as Xr, AgentHarnessPreflightError as Xs, AgentHarnessCompactResult as Xt, TelegramProbeOptions as Xu, encodeScopeSegment as Xv, PluginHookReplyPayloadSendingResult as Xw, augmentModelCatalogWithProviderPlugins as Xx, resolveThreadBindingMaxAgeMs as Xy, DispatchReplyWithDispatcher as Y, ChannelMessageActionName as YA, findPersistedAuthProfileCredential as YC, resolveAgentEffectiveModelPrimary as YD, ChannelIngressConfigInput as YE, OpenKeyedStoreOptions as YO, ProviderRuntimeAuthModel as YS, readTranscriptStatsAsync as YT, recordChannelBotPairLoopAndCheckSuppression as Y_, buildAfterTurnRuntimeContext as Ya, AskUserQuestionOptionIndices as Yb, DeviceBootstrapTokenRecord as Yc, TailscaleStatusCommandResult as Yd, applySetupAccountConfigPatch as Yf, resolveInboundSessionEnvelopeContextAsync as Yg, isRecentOutboundMessageIdentity as Yh, PREEMPTIVE_OVERFLOW_ERROR_TEXT as Yi, resolveChannelStreamingProgressCommentary as Yj, chunkByParagraph as Yk, markImplicitSameChatApprovalAuthorization as Yl, defineChannelMessageAdapter as Ym, createOpenClawCodingToolsAsync as Yn, isDeliveredMessagingToolSendToCurrentSource as Yo, readRemoteMediaBuffer as Yp, resolveStoredModelOverrideAsync as Yr, projectSettledTurnFinalizationAttemptResult as Ys, AgentHarnessCompactParams as Yt, TelegramProbe as Yu, buildChannelGroupsScopeTree as Yv, PluginHookReplyPayloadSendingEvent as Yw, fetchWithSsrFGuard as Yx, resolveThreadBindingIdleTimeoutMsForChannel as Yy, dispatchReplyWithDispatcher as Z, SessionUpstreamLink as ZA, clearRuntimeAuthProfileStoreSnapshots as ZC, resolveAgentConfig as ZD, ChannelIngressEventPresetInput as ZE, PluginStateCompareResult as ZO, ProviderAppGuidedSetup as ZS, resolveSessionStoreBackupPaths as ZT, ReplyPrefixContext as Z_, resolveAttemptFsWorkspaceOnly as Za, ReasoningReplyPayload as Zb, DeviceBootstrapProfile as Zc, resolveTailnetHostWithRunner as Zd, createPatchedAccountSetupAdapter as Zf, shouldDebounceTextInbound as Zg, isCompleteAgentPreamble as Zh, estimateRenderedLlmBoundaryTokenPressure as Zi, resolveChannelStreamingSuppressDefaultToolProgressMessages as Zj, chunkMarkdownTextWithMode as Zk, createNativeApprovalChannelRouteGatesAsync as Zl, createChannelProgressDraftCompositor as Zm, wrapToolWithBeforeToolCallHook as Zn, readEmbeddedMessageDeliveryFact as Zo, saveResponseMedia as Zp, AgentRuntimePolicyScope as Zr, AgentHarnessSessionCleanupError as Zs, AgentHarnessDeliveryDefaults as Zt, probeTelegram as Zu, resolveScopeIntroHint as Zv, PluginAgentTurnPrepareEvent as Zw, PluginLoadOptions as Zx, resolveThreadBindingMaxAgeMsForChannel as Zy, getReplyPayloadTtsSupplement as _, ChannelGroupContext as _A, getModelProviderRequestTransport as _C, ChannelIngressState as _D, SqliteSessionFileMarker as _E, resolveChannelGroupRequireMention as _M, TranscriptSourceProvider as _O, ProviderResolveWebSocketSessionPolicyContext as _S, PluginHookMessageReceivedEvent as _T, AccessGroupMembershipResolver as __, resolveSessionWriteLockOptions as _a, ResolvedTelegramAccount as _b, deliverAgentHarnessUserInputPrompt as _c, resolveEnabledConfiguredAccountId as _d, getMemoryCapabilityRegistration as _f, dispatchChannelInboundReply as _g, FinalizableDraftStreamState as _h, ToolProgressDetailMode as _i, normalizeOutboundLocation as _j, ChannelSetupWizardTextInput as _k, monitorTelegramProvider as _l, resolveTelegramForumThreadId as _m, EmbeddedRunAttemptResult as _n, ProviderDecisionOutcome as _o, pinMessageTelegram as _p, OpenClawPluginNodeInvokePolicyContext as _r, buildNativeHookRelayCommand as _s, RunMediaUnderstandingFileResult as _t, resolveApprovalRequestSessionTargetAsync as _u, ReplyDispatcherWithTypingOptions as _v, formatFastModeAutoProgressText as _w, sendPayloadWithChunkedTextAndMedia as _x, createAllowlistProviderOpenWarningCollector as _y, MsgContext as a, canBypassConfigWritePolicy as aA, ProviderPluginWizardSetup as aC, ChannelIngressRouteDescriptor as aD, resolveSendPolicy as aE, isAuthorizedTextSlashCommandTurn as aM, tryResolveDefaultAgentId as aO, ProviderBuiltInModelSuppressionResult as aS, PluginHookSkillChangedEvent as aT, resolveMentionPatternPolicy as a_, finalizeHarnessContextEngineTurn as aa, createScopedAccountReplyToModeResolver as ab, StreamingDirectiveAccumulator as ac, buildWebhookChannelStatusSummary as ad, enqueueKeyedTask as af, getTelegramTextParts as ag, createChannelRunQueue as ah, MigrationApplyResult as ai, SendableOutboundReplyParts as aj, PluginStateOperationDefinitions as ak, TelegramActionConfig as al, TelegramApiOverride as am, AgentHarnessSessionDeletionMutation as an, DecisionQuestionV2 as ao, AcpRuntimeErrorCode as ap, consumeAdjustedParamsForToolCall as ar, classifyEmbeddedAgentRunResultForModelFallback as as, SessionControllerInput as at, createChannelNativeOriginTargetResolver as au, initializeGlobalHookRunner as av, resolveApiKeyForProfile as aw, isNumericTargetId as ax, buildOpenGroupPolicyConfigureRouteAllowlistWarning as ay, isReplyPayloadNonTerminalToolErrorWarning as b, ChannelMessageActionContext as bA, ProviderRequestTransport as bC, InboundImplicitMentionKind as bD, sqliteSessionFileMarkerMatchesSession as bE, resolveToolsBySender as bM, WorkerLease as bO, ProviderWrapStreamFnContext as bS, PluginConversationBinding as bT, readAgentRunTerminalOutcome as b_, buildBootstrapContextForFiles as ba, createTelegramActionGate as bb, normalizeAgentHarnessUserInputAnswer as bc, resolveConfiguredFromRequiredCredentialStatuses as bd, registerMemoryCorpusSupplement as bf, runChannelInboundEvent as bg, createFinalizableDraftStreamControls as bh, buildWatchedSessionsHarnessContext as bi, emitAgentEvent as bj, WizardCancelledError as bk, shouldSuppressTelegramExecApprovalForwardingFallback as bl, withResolvedTelegramForumFlag as bm, CodeModeExecutor as bn, DecisionProviderContextV2 as bo, unpinMessageTelegram as bp, OpenClawPluginSecurityAuditCollector as br, NativeHookRelayProcessResponse as bs, drainSystemEventEntriesFromSdk as bt, ApprovalRequestSessionDelivery as bu, CreateTypingCallbacksParams as bv, formatFastModeSourceSuffix as bw, MediaPayloadInput as bx, createConditionalWarningCollector as by, SupplementalContextFacts as c, ConfigWriteScopeLike as cA, CODEX_APP_SERVER_AUTH_MARKER as cC, ResolveChannelMessageIngressParams as cD, resolveThreadFlag as cE, isTextSlashCommandTurn as cM, MessagingToolSourceReplyPayload as cO, ProviderModernModelPolicyContext as cS, PluginHookBeforeChannelIngressContext as cT, DirectDmPreCryptoGuardPolicy as c_, createAgentToolResultMiddlewareRunner as ca, resolveThreadBindingConversationIdFromBindingId as cb, resolveAgentExecutorController as cc, createComputedAccountStatusAdapter as cd, CompiledAllowlist as cf, normalizeForwardedContext as cg, waitUntilAbort as ch, MigrationPlan as ci, hasOutboundText as cj, SandboxToolPolicy as ck, ParsedTelegramTopicConversation as cl, buildTelegramGroupFrom as cm, AgentHarnessSessionForkParams as cn, DecisionAnswer as co, sendStickerTelegram as cp, BeforeToolCallPolicyDiagnosticState as cr, log as cs, ContextEngineOperation as ct, ChannelApprovalExplicitTargetEligibilityParams as cu, ReplyToResolution as cv, ProviderAuthAliasLookupParams as cw, resolveAskUserQuestionOptionIndex as cx, collectAllowlistProviderGroupPolicyWarnings as cy, BlockReplyContext as d, BaseTokenResolution as dA, isKnownEnvApiKeyMarker as dC, StableChannelIngressIdentityParams as dD, resolveSessionResetPolicy as dE, PluginHookChannelContext as dM, ScheduledToolPolicyContext as dO, ProviderBuildMissingAuthMessageContext as dS, PluginHookInboundClaimContext as dT, DirectDmCommandAuthorizationRuntime as d_, runAgentHarnessAfterCompactionHook as da, resolveConversationLabel as db, AgentExecutorController as dc, readAccountStatusSnapshot as dd, resolveAllowlistCandidates as df, BuiltChannelTurnContext as dg, ChannelDraftStreamingChunking as dh, MigrationSummary as di, ReplyPayload$1 as dj, ChannelSetupDmPolicy as dk, createTelegramThreadBindingManager as dl, buildTelegramRoutingTarget as dm, AgentHarnessSideQuestionParams as dn, DecisionEntry as do, editMessageReplyMarkupTelegram as dp, PluginRegistry as dr, runAgentCleanupStep as ds, RuntimeLogger as dt, ApprovalRequestSessionConversation as du, buildOutboundSessionContext as dv, hasUsableOAuthCredential as dw, resolveTextChunksWithFallback as dx, collectOpenGroupPolicyRestrictSendersWarnings as dy, resolveChunkMode as eA, ProviderAuthContext as eC, ChannelIngressIdentityField as eD, updateLastRouteWithAuthority as eE, isChannelProgressAttentionLine as eM, resolveAgentWorkspaceDir as eO, ProviderApplyConfigDefaultsContext as eS, PluginHeartbeatPromptContributionResult as eT, matchesMentionWithExplicit as e_, compactContextEngineWithSafetyTimeout as ea, resolveThreadBindingLifecycle as eb, isDeliveredMessagingToolResult as ec, buildBaseChannelStatusSummary as ed, generateSecureToken as ef, TelegramForwardedContext as eg, collectReplyMediaEntries as eh, InternalHookEventType as ei, resolveGroupSessionKey as ej, PluginStateKeyRange as ek, PAIRING_SETUP_BOOTSTRAP_PROFILE as el, canonicalizeBase64 as em, AgentHarnessNativeCompactionParams as en, DecisionBatchV2 as eo, moveSingleAccountChannelSectionToDefaultAccount as ep, runBeforeToolCallHook as er, formatToolAggregate as es, DispatchFromConfigResult as et, createNativeApprovalMessagingTargetResolvers as eu, ReplyPrefixContextBundle as ev, removeProviderAuthProfilesWithLock as ew, deliverFormattedTextWithAttachments as ex, resolveScopeToolsPolicy as ey, GetReplyOptions as f, ChannelAccountSnapshot as fA, isNonSecretApiKeyMarker as fC, AccessGroupMembershipFact as fD, isValidAgentHarnessSessionStoreEntry as fE, PluginHookChannelSenderContext as fM, isOpenClawRuntimeContextCustomMessage as fO, ProviderBuildUnknownModelHintContext as fS, PluginHookInboundClaimEvent as fT, ResolvedInboundDirectDmAccess as f_, runAgentHarnessBeforeCompactionHook as fa, ConfiguredBindingRouteResult as fb, cancelPendingAgentQuestionForSession as fc, standardDmPolicyOpenIssue as fd, resolveAllowlistMatchByCandidates as ff, ChannelInboundEventRunnerParams as fg, resolveChannelDraftStreamingChunking as fh, PluginLogger as fi, ReplyPayloadTtsSupplement as fj, ChannelSetupWizard as fk, getTelegramThreadBindingManager as fl, buildTelegramThreadParams as fm, AgentHarnessSideQuestionParamsV2 as fn, DecisionOutcome as fo, editMessageTelegram as fp, OpenClawGatewayDiscoveryAdvertiseContext as fr, buildAgentHookContextChannelFields as fs, DescribeImageFileParams as ft, ExecApprovalSessionTarget as fu, resolveAgentOutboundIdentity as fv, StorageBackend as fw, sendMediaWithLeadingCaption as fx, collectOpenGroupPolicyRouteAllowlistWarnings as fy, copyReplyPayloadMetadata as g, ChannelDirectoryEntryKind as gA, attachModelProviderRequestTransport as gC, ChannelIngressPolicyInput as gD, resolveSessionKey as gE, resolveChannelGroupPolicy as gM, SpeechProviderPlugin as gO, ProviderResolveTransportTurnStateContext as gS, PluginHookMessageContext as gT, resolveControlCommandGate as g_, resolveSessionWriteLockAcquireTimeoutMs as ga, resolveRuntimeConversationBindingRoute as gb, buildAgentHarnessUserInputAnswers as gc, formatMatchMetadata as gd, clearMemoryPluginState as gf, buildChannelTurnContext as gg, createRunStateMachine as gh, EmbeddedRunAttemptParamsV2 as gi, formatLocationText as gj, ChannelSetupWizardStatus as gk, setTelegramThreadBindingMaxAgeBySessionKeyAsync as gl, resolveTelegramForumFlag as gm, AgentHarnessV2 as gn, JsonValue as go, deleteMessageTelegram as gp, OpenClawPluginNodeInvokePolicy as gr, testing as gs, RunMediaUnderstandingFileParams as gt, resolveApprovalRequestSessionTarget as gu, ReplyDispatcherOptions as gv, FastModeAutoProgressState as gw, sendPayloadTextChunkSequence as gx, createAllowlistProviderGroupPolicyWarningCollector as gy, buildTtsSupplementMediaPayload as h, ChannelDirectoryEntry as hA, resolveEnvApiKey as hC, ChannelIngressIdentifierKind as hD, deriveSessionKey as hE, ChannelGroupPolicy as hM, RealtimeVoiceProviderPlugin as hO, ProviderReconcileLocalServiceContext as hS, PluginHookMediaFact as hT, resolveCommandAuthorizedFromAuthorizers as h_, acquireSessionWriteLock as ha, resolveConfiguredBindingRoute as hb, AgentHarnessUserInputPromptOptions as hc, collectIssuesForEnabledAccounts as hd, buildMemoryPromptSection as hf, PreparedInboundReply as hg, createArmableStallWatchdog as hh, EmbeddedRunAttemptParams$1 as hi, OutboundLocation as hj, ChannelSetupWizardCredential as hk, setTelegramThreadBindingMaxAgeBySessionKey as hl, extractTelegramForumFlag as hm, AgentHarnessSupportContext as hn, DecisionRuntimeV1 as ho, renameForumTopicTelegram as hp, OpenClawPluginHttpRouteHandler as hr, registerNativeHookRelay as hs, ExtractStructuredWithModelParams as ht, resolveApprovalRequestSessionConversation as hu, projectOutboundPayloadPlanForDelivery as hv, StorageProviderOpenParams as hw, sendPayloadMediaSequenceOrFallback as hx, composeWarningCollectors as hy, FinalizedMsgContext as i, authorizeConfigWrite as iA, ProviderDeferSyntheticProfileAuthContext as iC, ChannelIngressRouteAccess as iD, withSessionEntriesAsync as iE, createCommandTurnContext as iM, resolveSessionAgentIdsStrict as iO, ProviderAugmentModelCatalogContext as iS, PluginHookSkillArtifact as iT, ResolvedMentionPatternPolicy as i_, bootstrapHarnessContextEngine as ia, resolveThreadBindingThreadName as ib, formatToolProgressOutput as ic, buildTokenChannelStatusSummary as id, KeyedAsyncQueue as if, extractTelegramLocation as ig, createAccountStatusSink as ih, OpenClawPluginToolFactory as ii, OutboundPayloadPlan as ij, PluginStateOperation as ik, TelegramAccountConfig as il, transcribeFirstAudio$1 as im, AgentHarnessResultClassification as in, DecisionProviderV2 as io, AcpRuntimeError as ip, setBeforeToolCallDiagnosticsEnabled as ir, hasGatewayToolRoutingContext as is, ReplyOperation as it, createChannelApproverDmTargetResolverAsync as iu, getGlobalHookRunner as iv, refreshOAuthCredentialForRuntime as iw, hasReplyPayloadFinalDeliveryCapture as ix, parseOptionalDelimitedEntries as iy, SessionCatalogListProviderParams as j, ChannelToolSend as jA, clearExpiredCooldowns as jC, SessionRecentConversationText as jD, readSessionTranscriptVisibleMessageDelta as jE, TranscriptsStartResult as jO, ProviderReplaySessionStateV2 as jS, SessionStoreTranscriptEvent as jT, recordDroppedChannelTurnHistory as j_, decodeHeaderEnvPlaceholder as ja, resolveTelegramFetch as jb, AgentPromptGuidanceEntry as jc, defineSetupPluginEntry as jd, SessionDiscussionProvider as jf, createAcceptedChannelDeliveryResult as jg, ChannelIngressMonitorDeliveryResult as jh, queueAgentHarnessMessage as ji, createChannelProgressDraftGate as jj, ChannelDoctorAdapter as jk, createApproverRestrictedNativeApprovalAdapter as jl, resolveTranscriptBackedChannelFinalText as jm, CodeModeVmResult as jn, supportsModelTools as jo, renderQrPngBase64 as jp, GatewayContextResolver as jr, AgentToolResultMiddlewareOptions as js, getTtsProviderAsync as jt, resolveExecApprovalCommandDisplay as ju, resolveExecApprovalAllowedDecisions as jv, PluginSessionActionRegistration as jw, buildPluginConfigSchema as jx, resolveOpenDmAllowlistAccess as jy, SessionCatalogEntrySnapshot as k, ChannelThreadingContext as kA, resolveProviderAuthProfileApiKey as kC, ResolvedChannelImplicitMentions as kD, SessionTranscriptVisibleMessageDeltaParams as kE, TranscriptStartRequest as kO, ProviderReplaySessionEntry as kS, SessionStoreSelectedEntries as kT, resolveChannelTurnDispatchCounts as k_, resolveSandboxContext as ka, TelegramTokenResolution as kb, LoadCodexBundleMcpThreadConfigParams as kc, createChatChannelPlugin as kd, MemoryPluginRuntime as kf, toInboundMediaFacts as kg, CHANNEL_INGRESS_RETENTION_DEFAULTS as kh, prepareHarnessNativeMcpAppPreview as ki, buildChannelProgressDraftLineForEntry as kj, ChannelConfigAdapter as kk, buildTypedPluginApprovalPendingReplyPayload as kl, withDurableMessageSendContext as km, CODE_MODE_WORKER_WATCHDOG_GRACE_MS as kn, getChannelAgentToolMeta as ko, unlinkIfExists as kp, OpenClawPluginGatewayEvents as kr, AgentToolResultMiddlewareContext as ks, agentCommandFromIngress as kt, resolveApprovalRequestSessionDeliveryAsync as ku, ExecPolicyOverrides as kv, PluginRuntimeLifecycleRegistration as kw, definePluginEntry as kx, DM_GROUP_ACCESS_REASON as ky, UntrustedStructuredContextEntry as l, ConfigWriteTargetLike as lA, CUSTOM_LOCAL_AUTH_MARKER as lC, ResolveStableChannelMessageIngressParams as lD, SessionResetMode as lE, InputProvenance as lM, ToolArgumentValidationError as lO, UnifiedModelCatalogProviderContext as lS, PluginHookBeforeChannelIngressEvent as lT, DirectDmPreCryptoGuardPolicyOverrides as l_, createCodexAppServerToolResultExtensionRunner as la, recordInboundSessionMetaSafe as lb, AgentExecutorBinding as lc, createDefaultChannelRuntimeState as ld, compileAllowlist as lf, AssembledInboundReply as lg, createRuntimeDirectoryLiveAdapter as lh, MigrationProviderContext as li, resolveOutboundMediaUrls as lj, SandboxWorkspaceAccess as lk, parseTelegramTopicConversation as ll, buildTelegramGroupPeerId as lm, AgentHarnessSessionForkResult as ln, DecisionBatch as lo, sendMessageTelegram as lp, DeferredPluginToolApproval as lr, isHostScopedAgentToolActive as ls, ContextEngineProjection as lt, ChannelApprovalForwardingEligibilityParams as lu, createReplyToFanout as lv, resolveProviderIdForAuth as lw, resolveAskUserQuestionOptionIndices as lx, collectAllowlistProviderRestrictSendersWarnings as ly, FAST_MODE_AUTO_PROGRESS_KIND as m, ChannelCapabilities as mA, resolveApiKeyForProviderCore as mC, ChannelIngressEventInput as mD, canonicalizeMainSessionAlias as mE, onInternalSessionTranscriptUpdate as mM, RealtimeTranscriptionProviderPlugin as mO, ProviderFailoverErrorContext as mS, PluginHookLocation as mT, resolveInboundDirectDmAccessWithRuntime as m_, SessionWriteLockAcquireTimeoutConfig as ma, ensureConfiguredBindingRouteReady as mb, runAgentHarnessGatewayQuestion as mc, appendMatchMetadata as md, resolveCompiledAllowlistMatch as mf, InboundReplyDispatchResult as mg, StallWatchdogTimeoutMeta as mh, AgentHarnessTerminalOutcomeInput as mi, NormalizedLocation as mj, ChannelSetupWizardAllowFromEntry as mk, setTelegramThreadBindingIdleTimeoutBySessionKeyAsync as ml, describeReplyTarget as mm, AgentHarnessSupport as mn, DecisionQuestion as mo, editForumTopicTelegram as mp, OpenClawPluginCliRootCommandDescriptor as mr, invokeNativeHookRelay as ms, DescribeVideoFileParams as mt, resolveApprovalRequestOriginTargetAsync as mu, createStructuredOutboundPayloadPlan as mv, StorageProvider as mw, sendPayloadMediaSequenceAndFinalize as mx, composeAccountWarningCollectors as my, SessionEntry as n, OutboundDeliveryResult as nA, ProviderAuthMethodNonInteractiveContext as nC, ChannelIngressResolver as nD, updateSessionStoreEntry as nE, GroupThreadMentionFacts as nM, resolveDefaultAgentId as nO, ProviderResolveConfigApiKeyContext as nS, PluginNextTurnInjectionEnqueueResult as nT, BuildMentionRegexesOptions as n_, resolveCompactionTimeoutMs as na, resolveThreadBindingFarewellText as nb, projectProgressCardChannelUpdate as nc, buildProbeChannelStatusSummary as nd, createDedupeCache as nf, buildSenderLabel as ng, ChannelRunQueueParams as nh, OpenClawPluginActiveModelContext as ni, ChannelProgressDraftCompositorSnapshot as nj, PluginStateMoveEntries as nk, modelSupportsVision as nl, isVoiceMessageCompatibleAudio as nm, AgentHarnessRegistrationOptions as nn, DecisionEvaluateOptionsV2 as no, prepareScopedSetupConfig as np, finalizeToolTerminalPresentation as nr, resolveNodeIdFromList as ns, callGatewayTool as nt, shouldSuppressLocalNativeExecApprovalPrompt as nu, createReplyPrefixContext as nv, upsertAuthProfileAsync as nw, formatTextWithAttachmentLinks as nx, buildAccountScopedDmSecurityPolicy as ny, OriginatingChannelType as o, formatConfigWriteDeniedMessage as oA, resolveModelAuthMode as oC, ChannelMessageIngressCommandInput as oD, resolveChannelResetConfig as oE, isExplicitCommandTurn as oM, ReplyExpectation as oO, ProviderCatalogContext as oS, PluginHookSkillContext as oT, dispatchInboundDirectDm as o_, isActiveHarnessContextEngine as oa, createStaticReplyToModeResolver as ob, createStreamingDirectiveAccumulator as oc, collectStatusIssuesFromLastError as od, AllowlistMatch as of, hasBotMention as og, keepHttpServerTaskAlive as oh, MigrationDetection as oi, countOutboundMedia as oj, PluginStateOperationReceipt as ok, TelegramNetworkConfig as ol, TelegramReplyTarget as om, AgentHarnessSessionDeletionParams as on, DecisionRuntimeV2 as oo, createPluginRuntimeStore as op, consumePreExecutionBlockedToolCall as or, prepareAgentRuntimeAuth as os, ContextEngine as ot, createChannelNativeOriginTargetResolverAsync as ou, resetGlobalHookRunner as ov, resolveAuthProfileEligibility as ow, isReasoningReplyPayload as ox, buildOpenGroupPolicyRestrictSendersWarning as oy, PreparedAgentRunStart as p, ChannelAgentTool as pA, resolveOAuthApiKeyMarker as pC, ChannelIngressDecision as pD, clearSessionStoreCacheForTest as pE, InboundEventKind as pM, MediaUnderstandingProviderPlugin as pO, ProviderCacheTtlEligibilityContext as pS, PluginHookInboundMessageMetadata as pT, createPreCryptoDirectDmAuthorizer as p_, isReplaySafeToolCall as pa, RuntimeConversationBindingRouteResult as pb, claimPendingAgentQuestionAnswer as pc, standardNotConfiguredIssue as pd, resolveAllowlistMatchSimple as pf, ChannelInboundTurnPlan as pg, ArmableStallWatchdog as ph, AgentHarnessTerminalOutcomeClassification as pi, LocationSource as pj, ChannelSetupWizardAdapter as pk, setTelegramThreadBindingIdleTimeoutBySessionKey as pl, buildTypingThreadParams as pm, AgentHarnessSideQuestionResult as pn, DecisionProviderV1 as po, createForumTopicTelegram as pp, OpenClawGatewayDiscoveryService as pr, hasNativeHookRelayInvocation as ps, DescribeImageFileWithModelParams as pt, resolveApprovalRequestOriginTarget as pu, createOutboundPayloadPlan as pv, StorageObjectInfo as pw, sendPayloadMediaSequence as px, collectOpenProviderGroupPolicyWarnings as py, settleReplyDispatcher as q, IdentifierAuthentication as qA, saveAuthProfileStore as qC, SourceReplyDeliveryMode as qD, ChannelIngressAccessGroupMembershipResolver as qE, PLUGIN_COMMAND_DISPATCH as qO, ProviderResolveUsageAuthContext as qS, readSessionUpdatedAt as qT, InboundMediaFacts as q_, buildEmbeddedAttemptToolRunContext as qa, TelegramCallbackButton as qb, ApproveDevicePairingResult as qc, delegateCompactionToRuntime as qd, setAccountEnabledInConfigSection as qf, resolveUnmentionedGroupInboundPolicy as qg, ChannelIngressQueueRecord as qh, resolveContextEngineOwnerPluginId as qi, resolveChannelStreamingPreviewCommandText as qj, OutboundDeliveryFormattingOptions as qk, createResolvedApproverActionAuthAdapter as ql, createDurableInboundReceiveJournalFromQueue as qm, formatReasoningMessage as qn, extractMessagingToolSendResult as qo, SavedRemoteMedia as qp, listDevicePairing as qr, restorePreparedUserTurnOperationalMetaForRuntime as qs, AgentHarnessAttemptResult as qt, auditTelegramGroupMembership as qu, ScopePath as qv, PluginHookReplyPayload as qw, readResponseTextSnippet as qx, resolveThreadBindingEffectiveExpiresAt as qy, ChannelStructuredContextEntry as r, PlatformMessageNotDispatchedError as rA, ProviderAuthResult as rC, ChannelIngressResolverMessageParams as rD, upsertSessionEntry as rE, CommandTurnContext as rM, resolveSessionAgentIdStrict as rO, CliBackendPlugin as rS, PluginNextTurnInjectionRecord as rT, ResolveMentionPatternPolicyParams as r_, assembleHarnessContextEngine as ra, resolveThreadBindingIntroText as rb, TOOL_PROGRESS_OUTPUT_MAX_CHARS as rc, buildRuntimeAccountStatusSnapshot as rd, resolveGlobalDedupeCache as rf, buildSenderName as rg, ChannelRunQueueTaskContext as rh, OpenClawPluginToolContext as ri, UserTurnTranscriptRecorder as rj, PluginStateObservation as rk, findModelInCatalog as rl, MediaExecutionContext as rm, AgentHarnessResetParams as rn, DecisionOutcomeV2 as ro, ChannelSetupPromotionSurface as rp, isToolWrappedWithBeforeToolCallHook as rr, selectDefaultNodeFromList as rs, readGatewayToolOperatorScopes as rt, createChannelApproverDmTargetResolver as ru, createReplyPrefixOptions as rv, listProfilesForProvider as rw, hasOutboundReplyContent as rx, formatPairingApproveHint as ry, RuntimeMsgContext as s, ConfigWriteAuthorizationResultLike as sA, resolveModelAuthModeAsync as sC, CreateChannelIngressResolverParams as sD, resolveSessionResetType as sE, isNativeCommandTurn as sM, MessagingToolSend as sO, ProviderCatalogResult as sS, PluginHookReplyDispatchEvent as sT, dispatchInboundDirectDmWithRuntime as s_, runHarnessContextEngineMaintenance as sa, createTopLevelChannelReplyToModeResolver as sb, prepareAgentRunTerminalReply as sc, createAsyncComputedAccountStatusAdapter as sd, AllowlistMatchSource as sf, isBinaryContent as sg, runPassiveAccountLifecycle as sh, MigrationItem as si, hasOutboundMedia as sj, SandboxContext as sk, resolveTelegramPollVisibility as sl, buildGroupLabel as sm, AgentHarnessSessionForkFailureCode as sn, ProviderDecisionOutcomeV2 as so, sendPollTelegram as sp, BeforeToolCallFailureDisposition as sr, buildAgentRuntimePlan as ss, ContextEngineHostCapability as st, nativeApprovalTargetsMatch as su, PluginSubagentRequesterContext as sv, resolveAuthProfileOrder as sw, normalizeOutboundReplyPayload as sx, buildOpenGroupPolicyWarning as sy, InternalSessionEntry as t, resolveTextChunkLimit as tA, ProviderAuthMethod as tC, ChannelIngressIdentitySubjectInput as tD, updateSessionStoreAmbientTranscriptWatermark as tE, formatChannelProgressDraftDiffStat as tM, resolveDefaultAgentDir as tO, ProviderNormalizeConfigContext as tS, PluginNextTurnInjection as tT, normalizeMentionText as t_, compactWithSafetyTimeout as ta, formatThreadBindingDurationLabel as tb, resolveMessageToolSourceReplyFinal as tc, buildComputedAccountStatusSnapshot as td, generateSecureUuid as tf, TelegramTextEntity as tg, ChannelRunQueue as th, InternalHookHandler as ti, ChannelProgressDraftCompositorLine as tj, PluginStateKeyedStore as tk, normalizeDeviceBootstrapProfile as tl, estimateBase64DecodedBytes as tm, AgentHarnessNativeCompactionRequest as tn, DecisionContentV2 as to, patchScopedAccountConfig as tp, requestDeferredPluginToolApproval as tr, listNodes as ts, DispatchReplyFromConfig$1 as tt, resolveApprovalKind as tu, ReplyPrefixOptions as tv, upsertAuthProfile as tw, deliverTextOrMediaReply as tx, scopeKey as ty, applyTemplate as u, BaseProbeResult as uA, MINIMAX_OAUTH_MARKER as uC, ResolvedChannelMessageIngress as uD, evaluateSessionFreshness as uE, PluginHookChannelChatContext as uM, resolveSessionKeyBySessionIdAsync as uO, UnifiedModelCatalogProviderPlugin as uS, PluginHookBeforeChannelIngressResult as uT, createDirectDmPreCryptoGuardPolicy as u_, resolveAgentHarnessBeforePromptBuildResult as ua, recordInboundSession as ub, AgentExecutorContext as uc, createDependentCredentialStatusIssueCollector as ud, formatAllowlistMatchMeta as uf, BuildChannelTurnContextParams as ug, createRuntimeOutboundDelegates as uh, MigrationProviderPlugin as ui, resolveSendableOutboundReplyParts as uj, ChannelPlugin as uk, setTelegramRuntime as ul, buildTelegramParentPeer as um, AgentHarnessSettledTurnFinalizationResult as un, DecisionBatchResult as uo, sendLocationTelegram as up, PluginHttpRouteRegistration as ur, resolveAgentRunAbortLifecycleFields as us, ContextEngineSessionTarget as ut, ChannelApprovalPotentialRouteParams as uu, OutboundSessionContext as uv, DEFAULT_OAUTH_REFRESH_MARGIN_MS as uw, resolvePayloadMediaUrls as ux, collectOpenGroupPolicyConfiguredRouteWarnings as uy, isFastModeAutoProgressPayload as v, ChannelLogSink as vA, resolveProviderRequestHeaders as vC, ChannelIngressStateInput as vD, formatSqliteSessionFileMarker as vE, resolveChannelGroupToolsPolicy as vM, WorkerDesktopApp as vO, ProviderTransportTurnState as vS, PluginHookMessageSentEvent as vT, expandAllowFromWithAccessGroups as v_, prepareAgentWorkspaceContext as va, TelegramMediaRuntimeOptions as vb, emptyAgentHarnessUserInputAnswers as vc, projectCredentialSnapshotFields as vd, listActiveMemoryPublicArtifacts as vf, dispatchChannelInboundTurn as vg, clearFinalizableDraftMessage as vh, agentHarnessAttemptTerminal as vi, toLocationContext as vj, PromptAccountId as vk, telegramMessageActions as vl, resolveTelegramGroupAllowFromContext as vm, CodeModeHeadlessAbortError as vn, ProviderFailureReason as vo, reactMessageTelegram as vp, OpenClawPluginNodeInvokePolicyResult as vr, resolveNativeHookRelayDeferredToolApproval as vs, TranscribeAudioFileParams as vt, resolveExecApprovalSessionTarget as vu, createReplyDispatcher as vv, formatFastModeCommandOptions as vw, sendTextMediaPayload as vx, createAllowlistProviderRestrictSendersWarningCollector as vy, readAskUserQuestionId as w, ChannelMessagingAdapter as wA, isProviderApiKeyConfiguredAsync as wC, ResolveInboundMentionDecisionFlatParams as wD, sessionDeliveryChannel as wE, resolveSessionStorePathCore as wM, WorkerProvider as wO, ProviderNormalizeToolSchemasContext as wS, MessageHookMediaFact as wT, runGroupThread as w_, EmbeddedContextFile as wa, resolveTelegramMediaRuntimeOptions as wb, AgentHarnessUserInputQuestion as wc, ThreadAwareOutboundSessionRouteRecoveryContext as wd, MemoryEmbeddingProviderCreateResult as wf, MediaPlaceholderTextFact as wg, createDraftStreamLoop as wh, execPolicy as wi, AgentEventPayload as wj, WizardSelectParams as wk, formatChannelApprovalResolvedLabel as wl, deliverInboundReplyWithMessageSendContext as wm, CodeModeExecutorResumeInput as wn, buildUiPresentationPrompt as wo, resolveAutoMediaKeyProviders as wp, OpenClawPluginServiceContextV2 as wr, CodexAppServerExtensionFactory as ws, enqueueSystemEventFromSdk as wt, doesApprovalRequestSelectChannelAccountAsync as wu, InternalGetReplyOptions as wv, PluginAgentEventEmitResult as ww, ModelPickerCapabilityProfile as wx, projectAccountConfigWarningCollector as wy, isReplyPayloadTerminalContent as x, ChannelMessageActionDiscoveryContext as xA, VERSION as xC, InboundMentionDecision as xD, normalizeSessionDeliveryState as xE, resolveChannelGroups as xM, WorkerLeaseStatus as xO, ProviderUsageSnapshot as xS, PluginConversationBindingRequestParams as xT, isGroupThreadRouteExclusive as x_, resolveBootstrapContextForRun as xa, listEnabledTelegramAccounts as xb, AgentHarnessQuestionGatewayCall as xc, TelegramConfigSchema as xd, MemoryEmbeddingProvider as xf, runPreparedInboundReply as xg, createFinalizableDraftStreamControlsForState as xh, classifyAgentHarnessTerminalOutcome as xi, onAgentEvent as xj, WizardMultiSelectParams as xk, createNativeApprovalControlRegistry as xl, resolveTelegramPreviewStreamMode as xm, CodeModeExecutorContinuation as xn, normalizeQuestionTimeoutSeconds as xo, TelegramSendOpts as xp, OpenClawPluginSecurityAuditContext as xr, NativeHookRelayProvider as xs, drainSystemEventsFromSdk as xt, doesApprovalRequestMatchChannelAccount as xu, TypingCallbacks as xv, formatFastModeStatusValue as xw, buildMediaPayload as xx, createOpenGroupPolicyRestrictSendersWarningCollector as xy, isHostNoticePayload as y, ChannelMessageActionAdapter as yA, ProviderRequestCapability as yC, IngressReasonCode as yD, parseSqliteSessionFileMarker as yE, resolveChannelGroupsConfigPath as yM, WorkerDesktopEndpoint as yO, ProviderWebSocketSessionPolicy as yS, PluginHookProviderUpdate as yT, AgentRunTerminalOutcome as y_, buildAgentWorkspaceInstructionSnapshot as ya, TelegramPollActionGateState as yb, formatAgentHarnessUserInputPrompt as yc, resolveConfiguredFromCredentialStatuses as yd, registerMemoryCapability as yf, filterChannelTurnSupplementalContext as yg, createFinalizableDraftLifecycle as yh, agentHarnessStructuredInput as yi, projectAgentToolActivity as yj, promptChannelAccessConfig as yk, buildTelegramExecApprovalPendingPayload as yl, resolveTelegramThreadSpec as ym, CodeModeHeadlessTimeoutError as yn, UnavailableReason as yo, sendTypingTelegram as yp, OpenClawPluginReloadRegistration as yr, NativeHookRelayEvent as ys, consumeSelectedSystemEventEntriesFromSdk as yt, resolveExecApprovalSessionTargetAsync as yu, createReplyDispatcherWithTyping as yv, formatFastModeCurrentStatus as yw, MediaPayload as yx, createAllowlistProviderRouteAllowlistWarningCollector as yy, isExternalUserText as z, ChannelMessageUnknownSendContext as zA, findPersistedAuthProfileCredentialAsync as zC, SystemEvent as zD, resolveAuthStorePathForDisplay as zE, RealtimeVoiceBrowserSession as zO, ProviderNormalizeResolvedModelContext as zS, listSessionEntriesAsync as zT, buildChannelInboundEventContext as z_, projectRuntimeToolInputSchema as za, describeWebhookAccountSnapshot as zb, TrustedSessionCreation as zc, formatZonedTimestamp as zd, createAttachedChannelResultAdapter as zf, DurableInboundReplyDeliveryOptions as zg, createChannelIngressDrain as zh, awaitAgentHarnessAgentEndHook as zi, normalizeChannelProgressDraftLineIdentity as zj, ChannelResolveKind as zk, ExecApprovalChannelRuntime as zl, createPreviewMessageReceipt as zm, CodeModeOutputSource as zn, resolveToolExecutionErrorKind as zo, resolveFfmpegBin as zp, SessionMutationTarget as zr, CODEX_APP_SERVER_CONTEXT_ENGINE_HOST as zs, ResolvedTtsConfig as zt, buildExecApprovalPresentation as zu, collectStandardAllowlistLists as zv, PluginSessionTurnScheduleParams as zw, redactSensitiveFieldValue as zx, resolvePluginConversationBindingApproval as zy };