import { $ as MentionPatternsPolicyConfig, A as PluginInstallRecord, At as ChannelConfigSchema, B as TtsMode, C as ThinkingLevelMap, Ct as PluginManifestModelIdNormalizationProvider, D as Usage, Dt as PluginManifestSetupProvider, E as Transport, Et as PluginManifestProviderRequestProvider, F as AgentRuntimePolicyConfig, Ft as UnifiedModelCatalogKind, G as ToolLoopDetectionConfig, H as TtsProvider, I as ChannelImplicitMentionsConfig, J as MemoryCitationsMode, K as ToolProfileId, L as ResolvedTtsPersona, M as GatewayTrustedProxyConfig, Mt as ModelCatalogContextWindowOption, N as TalkProviderConfig, Nt as ModelCatalogStatus, O as McpCodexToolApprovalMode, Ot as PluginKind, P as AgentBinding, Pt as UnifiedModelCatalogEntry, Q as BroadcastStrategy, R as TtsAutoMode, S as ThinkingBudgets, St as PluginManifestMcpServer, T as ToolResultMessage, Tt as PluginManifestProviderEndpoint, U as GroupToolPolicyBySenderConfig, V as TtsModelOverrideConfig, W as GroupToolPolicyConfig, X as SecretInput, Y as SafeBinProfileFixture, Z as SecretRef, _ as Message, _t as PluginManifestContracts, a as ModelMediaInputConfig, at as IdentityConfig, b as StreamFn$1, bt as PluginManifestDashboardActionVerb, ct as SessionMaintenanceMode, d as AssistantMessage$1, dt as PluginBundleFormat, et as ContextVisibilityMode, f as AssistantMessageEvent, ft as PluginConfigUiHint, g as ImageContent$1, gt as PluginManifestChannelCommandDefaults, h as Context, ht as PluginManifest, i as ModelDefinitionConfig, it as HumanDelayConfig, j as GatewayOperatorRoleDefinition, jt as JsonSchemaObject, k as McpServerToolFilterConfig, kt as ChannelAccountKeyPolicy, l as ModelApi, lt as SessionScope, m as CompleteSimpleFn, mt as PluginFormat, n as OpenClawConfig, nt as DmScope, o as ModelProviderAuthMode, ot as MarkdownTableMode$1, p as AssistantMessageEventStreamContract, pt as PluginDiagnostic, q as ToolsConfig, r as ModelCompatConfig, rt as GroupScope, s as ModelProviderConfig, st as ReplyToMode, t as ConfigFileSnapshot, tt as DmPolicy, u as Api, ut as AccessGroupConfig, v as Model, vt as PluginManifestControlUi, w as Tool, wt as PluginManifestNativeSessionCatalogSetup, x as TextContent, xt as PluginManifestDashboardDataBinding, y as SimpleStreamOptions, yt as PluginManifestDashboard, z as TtsConfig } from "./types.openclaw-R0XDvekS.js";
import { n as ControlUiLinkReaderMetadata } from "./control-ui-link-reader-CcJBydfw.js";
import { Static, TSchema, Type as Type$1 } from "typebox";
import { z } from "zod";
import { DatabaseSync } from "node:sqlite";
import "@openclaw/fs-safe/advanced";
import { ColumnType, Selectable } from "kysely";
import { LookupAddress } from "node:dns";
import { Dispatcher } from "undici";
import { MessagePort } from "node:worker_threads";
import "execa";
import { Duplex, Readable } from "node:stream";
import { ClientOptions, WebSocket } from "ws";
import "@openclaw/fs-safe/errors";
import "@openclaw/fs-safe/root";
import "@openclaw/fs-safe/path";
import "@openclaw/fs-safe/secure-file";
import "@openclaw/fs-safe/walk";
import { Agent, IncomingMessage, ServerResponse } from "node:http";
import { Command } from "commander";
import "json5";
import "@openclaw/ai/validation";
import "@modelcontextprotocol/sdk/types.js";
import { AutocompleteItem, AutocompleteProvider, Component, EditorComponent, EditorTheme, KeyId, KeybindingsConfig, KeybindingsManager, OverlayHandle, OverlayOptions, TUI, TUI_KEYBINDINGS } from "@earendil-works/pi-tui";
import "@openclaw/ai";
import "@openclaw/ai/internal/runtime";
import "@openclaw/ai/internal/shared";
import "typebox/error";
import "minimatch";
import "@openclaw/ai/internal/tool-schema";
import "@openclaw/fs-safe/file-lock";
import "@openclaw/fs-safe";
import "@openclaw/fs-safe/secret";
import { ImageMetadata } from "rastermill";
//#region packages/memory-host-sdk/src/host/search-deadline-control.d.ts
/**
 * Per-call control channel between a memory-search deadline owner and a nested
 * phase that runs on its own budget. The canonical example is managed
 * local-service acquisition during query embedding: service readiness is owned
 * and bounded by `models.providers.<id>.localService.readyTimeoutMs`, so the
 * whole-search deadline must not consume its budget while the caller waits for
 * a cold service to become ready.
 *
 * The channel is symbol-keyed so it never serializes into tool payloads or
 * provider request bodies and stays invisible to model-facing surfaces.
 */
declare const MEMORY_SEARCH_DEADLINE_CONTROL: unique symbol;
type MemorySearchDeadlineControlAction = "pause" | "resume";
/**
 * Owned phases call `report`; deadline owners `subscribe`.
 *
 * The control owner balances concurrent owned phases: subscribers see "pause"
 * only on the 0→1 transition and "resume" only on the final 1→0 transition, so
 * overlapping owned phases cannot re-arm a budget early. Caller cancellation
 * never passes through this channel; it stays on the AbortSignal.
 */
type MemorySearchDeadlineControl = {
  report: (action: MemorySearchDeadlineControlAction) => void;
  subscribe: (listener: (action: MemorySearchDeadlineControlAction) => void) => () => void;
};
type MemorySearchDeadlineControlOptions = {
  [MEMORY_SEARCH_DEADLINE_CONTROL]?: MemorySearchDeadlineControl;
};
//#endregion
//#region packages/memory-host-sdk/src/host/types.d.ts
type MemorySource = "memory" | "sessions";
type MemoryOriginClass = "owner" | "agent" | "untrusted" | "system";
type MemorySessionKind = "interactive" | "cron" | "heartbeat" | "subagent" | "unknown";
/** Additional memory root, optionally narrowed by a root-relative glob. */
type MemoryExtraPath = string | {
  path: string;
  pattern?: string;
};
type MemoryEntryProvenance = {
  originClass: MemoryOriginClass;
  sessionKind: MemorySessionKind;
  observedAt: number;
  supersedesKey?: string;
};
/** One ranked memory search hit with optional vector/text scoring details. */
type MemorySearchResult = {
  path: string;
  startLine: number;
  endLine: number;
  score: number;
  vectorScore?: number;
  textScore?: number;
  snippet: string;
  source: MemorySource;
  importance?: number;
  triggers?: string;
  /** Semicolon-separated stable repository identities lifted from inline annotations. */
  projectKey?: string;
  /** @deprecated Use provenance.originClass. This field is not authoritative for automatic injection. */
  originClass?: string;
  citation?: string;
  provenance?: MemoryEntryProvenance;
};
/** Cached/probed embedding availability status. */
type MemoryEmbeddingProbeResult = {
  ok: boolean;
  error?: string;
  checked?: boolean;
  cached?: boolean;
  checkedAtMs?: number;
  cacheExpiresAtMs?: number;
};
/** Progress event emitted during memory sync. */
type MemorySyncProgressUpdate = {
  completed: number;
  total: number;
  label?: string;
};
type MemorySessionSyncTarget = {
  /** Owning OpenClaw agent. Omit only when the active manager scope already supplies it. */
  agentId?: string;
  /** Storage-neutral transcript/session identity. */
  sessionId: string;
  /** Optional visible session-store key for callers that already carry it. */
  sessionKey?: string;
};
type MemorySyncParams = {
  reason?: string;
  force?: boolean;
  /** Storage-neutral session transcript targets to refresh. */
  sessions?: MemorySessionSyncTarget[];
  /** Archive/support transcript files to refresh without treating paths as active session identity. */
  archiveFiles?: string[];
  progress?: (update: MemorySyncProgressUpdate) => void;
};
type MemorySearchRuntimeDebug = {
  backend: "builtin";
  configuredMode?: string;
  effectiveMode?: string;
  fallback?: string;
  embeddingBootstrap?: {
    ok: false;
    provider: string;
    reason: string;
    degradedTo: "keyword-only";
  };
};
/** Successful memory-file excerpt, optionally paginated/truncated. */
type MemoryReadSuccessResult = {
  status: "ok";
  text: string;
  path: string;
  truncated?: boolean;
  from?: number;
  lines?: number;
  nextFrom?: number;
};
/** An allowed memory path that does not exist. */
type MemoryReadNotFoundResult = {
  status: "not_found";
  text: "";
  path: string;
  truncated?: never;
  from?: never;
  lines?: never;
  nextFrom?: never;
};
type MemoryReadResult = MemoryReadSuccessResult | MemoryReadNotFoundResult;
/** Pre-status result accepted only from registered memory managers during migration. */
type LegacyMemoryReadResult = {
  status?: never;
  text: string;
  path: string;
  truncated?: boolean;
  from?: number;
  lines?: number;
  nextFrom?: number;
};
/** Aggregated memory backend status for CLI/UI diagnostics. */
type MemoryVectorIndexState = {
  state: "empty";
} | {
  state: "complete";
} | {
  state: "incomplete";
} | {
  state: "unverified";
};
type MemoryProviderStatus = {
  backend: "builtin";
  provider: string;
  model?: string;
  requestedProvider?: string;
  files?: number;
  chunks?: number;
  dirty?: boolean;
  /** Process-local failure from the newest admitted sync without a newer successful sync. */
  lastSyncError?: string;
  workspaceDir?: string;
  dbPath?: string;
  /** Explicit diagnostics for the whole shared agent database; payload sizes are not additive. */
  storage?: {
    databaseBytes: number;
    walBytes: number;
    reusableBytes: number;
    embeddingCacheBytes: number;
    embeddingCacheEntries: number;
  };
  extraPaths?: MemoryExtraPath[];
  sources?: MemorySource[];
  sourceCounts?: Array<{
    source: MemorySource;
    files: number;
    chunks: number;
    /** Stored chunk text and JSON embedding bytes, excluding cache and index overhead. */
    chunkBytes?: number;
    eligible?: number | null;
    issues?: string[];
  }>;
  cache?: {
    enabled: boolean;
    entries?: number;
    maxEntries?: number;
  };
  fts?: {
    enabled: boolean;
    available: boolean;
    error?: string;
  };
  fallback?: {
    from: string;
    reason?: string;
  };
  vector?: {
    enabled: boolean;
    index?: MemoryVectorIndexState;
    storeAvailable?: boolean;
    semanticAvailable?: boolean;
    available?: boolean;
    extensionPath?: string;
    loadError?: string;
    dims?: number;
  };
  batch?: {
    enabled: boolean;
    failures: number;
    limit: number;
    wait: boolean;
    concurrency: number;
    pollIntervalMs: number;
    timeoutMs: number;
    lastError?: string;
    lastProvider?: string;
  };
  custom?: Record<string, unknown>;
};
/** Search/read/sync/status contract implemented by memory managers. */
interface MemorySearchManager {
  search(query: string, opts?: {
    maxResults?: number;
    minScore?: number;
    sessionKey?: string;
    /**
     * Keyword/FTS scoring only: skip query embedding and vector search.
     * For reply-path recall (trigger injection) that must not add a
     * network round-trip per inbound message.
     */
    lexicalOnly?: boolean;
    /** Active repository identities used only for project-aware ranking. */
    activeProjectKeys?: string[];
    onDebug?: (debug: MemorySearchRuntimeDebug) => void;
    /**
     * Ranked memory-file keyword candidates bounded by maxResults, available before semantic retrieval completes.
     * Callers must apply the same visibility checks as for final results.
     * Null invalidates a previous snapshot before its provider/index changes.
     */
    onPartialResults?: (results: MemorySearchResult[] | null) => void;
    sources?: MemorySource[];
    /** Optional caller cancellation; managers consume it where their runtime supports cancellation. */
    signal?: AbortSignal;
  } & MemorySearchDeadlineControlOptions): Promise<MemorySearchResult[]>;
  listTriggerCandidates?(opts?: {
    limit?: number;
    activeProjectKeys?: string[];
  }): Promise<MemorySearchResult[]>;
  listCuratedProjectCandidates?(opts: {
    activeProjectKeys: string[];
    limit?: number;
  }): Promise<MemorySearchResult[]>;
  readFile(params: {
    relPath: string;
    from?: number;
    lines?: number;
  }): Promise<MemoryReadResult>;
  status(): MemoryProviderStatus;
  sync?(params?: MemorySyncParams): Promise<void>;
  getCachedEmbeddingAvailability?(): MemoryEmbeddingProbeResult | null;
  probeEmbeddingAvailability(): Promise<MemoryEmbeddingProbeResult>;
  probeVectorStoreAvailability?(): Promise<boolean>;
  probeVectorAvailability(): Promise<boolean>;
  close?(): Promise<void>;
}
//#endregion
//#region packages/llm-core/src/utils/provider-refusal.d.ts
/** Provider-authored findings; continuation is offered only after explicit user review. */
type ProviderRefusalReview = {
  explanation: string;
  continuation?: {
    message: string;
  };
  errorType?: string;
};
//#endregion
//#region src/config/zod-schema.sandbox.d.ts
declare const SandboxDockerSchema: z.ZodOptional<z.ZodObject<{
  image: z.ZodOptional<z.ZodString>;
  containerPrefix: z.ZodOptional<z.ZodString>;
  workdir: z.ZodOptional<z.ZodString>;
  readOnlyRoot: z.ZodOptional<z.ZodBoolean>;
  tmpfs: z.ZodOptional<z.ZodArray<z.ZodString>>;
  network: z.ZodOptional<z.ZodString>;
  user: z.ZodOptional<z.ZodString>;
  capDrop: z.ZodOptional<z.ZodArray<z.ZodString>>;
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
  setupCommand: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>, z.ZodTransform<string, string | string[]>>, z.ZodString>>;
  pidsLimit: z.ZodOptional<z.ZodNumber>;
  memory: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
  memorySwap: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
  cpus: z.ZodOptional<z.ZodNumber>;
  gpus: z.ZodOptional<z.ZodString>;
  ulimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodObject<{
    soft: z.ZodOptional<z.ZodNumber>;
    hard: z.ZodOptional<z.ZodNumber>;
  }, z.core.$strict>]>>>;
  seccompProfile: z.ZodOptional<z.ZodString>;
  apparmorProfile: z.ZodOptional<z.ZodString>;
  dns: z.ZodOptional<z.ZodArray<z.ZodString>>;
  extraHosts: z.ZodOptional<z.ZodArray<z.ZodString>>;
  binds: z.ZodOptional<z.ZodArray<z.ZodString>>;
  dangerouslyAllowReservedContainerTargets: z.ZodOptional<z.ZodBoolean>;
  dangerouslyAllowExternalBindSources: z.ZodOptional<z.ZodBoolean>;
  dangerouslyAllowContainerNamespaceJoin: z.ZodOptional<z.ZodBoolean>;
}, z.core.$strict>>;
//#endregion
//#region src/config/types.sandbox.d.ts
type SandboxDockerSettings = NonNullable<z.output<typeof SandboxDockerSchema>>;
//#endregion
//#region src/agents/agent-runtime-id.d.ts
type EmbeddedAgentRuntime = "openclaw" | "auto" | (string & {});
//#endregion
//#region packages/gateway-protocol/src/schema/skill-library.d.ts
declare const SkillLibraryFileSchema: Type$1.TObject<{
  path: Type$1.TString;
  content: Type$1.TString;
  encoding: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"utf8">, Type$1.TLiteral<"base64">]>>;
  executable: Type$1.TOptional<Type$1.TBoolean>;
}>;
declare const SkillLibrarySelectionSchema: Type$1.TObject<{
  skillId: Type$1.TString;
  revision: Type$1.TString;
  /** Persisted command identity: library collisions never shadow workspace names. */
  name: Type$1.TString;
  ownerProfileId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
}>;
type SkillLibraryFile = Static<typeof SkillLibraryFileSchema>;
type SkillLibrarySelection = Static<typeof SkillLibrarySelectionSchema>;
type SkillLibraryEntry = {
  skillId: string;
  slug: string;
  name: string;
  description: string;
  ownerProfileId: string | null;
  ownerLabel: string;
  authorProfileId: string;
  shared: boolean;
  enabled: boolean;
  removed: boolean;
  revision: string;
  createdAt: number;
  updatedAt: number;
  canEdit: boolean;
};
type SkillsLibraryListResult = {
  entries: SkillLibraryEntry[];
  profileId: string | null;
  multipleProfiles: boolean;
  defaultTarget: "workspace" | "personal" | "unavailable";
  canManageWorkspace: boolean;
  defaultSelectionLimit: number;
  defaultSelectionNotice?: string;
  session?: {
    sessionKey: string;
    selections: Array<SkillLibrarySelection & {
      slug: string;
      description: string;
      ownerLabel: string;
    }>;
    attachable: SkillLibraryEntry[];
  };
};
type SkillsLibraryReadResult = {
  entry: SkillLibraryEntry;
  content: string;
  files: SkillLibraryFile[];
  revisions: Array<{
    revision: string;
    createdAt: number;
  }>;
};
type SkillsLibraryReceipt = {
  state: "published" | "unchanged" | "removed";
  target: "personal" | "team";
  entry: SkillLibraryEntry;
  sessionActivation: "new-sessions";
  nextAction: string;
};
type SkillsLibraryActivateResult = {
  sessionKey: string;
  selections: SkillLibrarySelection[];
  sessionActivation: "next-turn";
};
//#endregion
//#region src/agents/sessions/source-info.d.ts
/**
 * Source metadata helpers for session resources.
 *
 * Tracks where prompts, skills, and extension-provided assets came from for diagnostics and UI.
 */
type SourceScope = "user" | "project" | "temporary";
type SourceOrigin = "package" | "top-level";
interface PathMetadata {
  source: string;
  scope: SourceScope;
  origin: SourceOrigin;
  baseDir?: string;
}
interface SourceInfo extends PathMetadata {
  path: string;
}
//#endregion
//#region src/skills/loading/skill-contract.d.ts
interface Skill {
  name: string;
  /** Human-readable title from the first Markdown H1, falling back to the identifier. */
  displayName?: string;
  description: string;
  /** Additional loading guidance rendered with the location in full and compact catalogs. */
  locationNote?: string;
  /** Prepared instructions for transferred bundles or non-filesystem locators such as node://. */
  readContent?: string;
  /** Prepared runtime identity of instruction bytes, or the complete delivered bundle tree. */
  contentHash?: string;
  filePath: string;
  baseDir: string;
  /** Discovery provenance for collision diagnostics, never read authority. */
  discoveryRoot?: {
    path: string;
    worktree: boolean;
  };
  /** Assigned by Gateway discovery, never accepted from the workspace provider. */
  fileHost?: "gateway" | "workspace";
  /** @deprecated Ignored; retained for API compatibility until the next Plugin SDK major. */
  promptVersion?: string;
  sourceInfo: SourceInfo;
  disableModelInvocation: boolean;
  source: string;
}
//#endregion
//#region src/skills/types.d.ts
type SkillInstallSpec = {
  id?: string;
  kind: "brew" | "node" | "go" | "uv" | "download";
  label?: string;
  bins?: string[];
  os?: string[];
  formula?: string;
  package?: string;
  module?: string;
  url?: string;
  sha256?: string;
  archive?: string;
  extract?: boolean;
  stripComponents?: number;
  targetDir?: string;
};
type SkillTelemetrySource = "bundled" | "unknown" | "workspace";
type SkillUsagePath = {
  /** Path visible to the tool runtime when it reads SKILL.md. */
  readPath: string;
  /** Canonical source SKILL.md path used as the lifecycle identity. */
  skillFile: string;
  skillName: string;
  skillSource: SkillTelemetrySource;
};
type ExplicitSkillSelection = {
  name: string;
  path: string;
};
type SkillEligibilityContext = {
  nodeSkills?: {
    canExec: boolean;
    node?: string;
  };
  remote?: {
    platforms: string[];
    hasBin: (bin: string) => boolean;
    hasAnyBin: (bins: string[]) => boolean;
    note?: string;
  };
};
type SkillSnapshot = {
  librarySelections?: SkillLibrarySelection[];
  prompt: string;
  /** Complete eligible sync identities, including skills hidden from the model prompt. */
  skills: Array<{
    name: string;
    /** Gateway-admitted path for explicit reads of hidden, Gateway-owned skills. */
    gatewayFilePath?: string;
    /** Config key can differ from the prompt-facing skill name. */
    skillKey?: string;
    primaryEnv?: string;
    requiredEnv?: string[];
  }>;
  /** Normalized agent-level filter used to build this snapshot; undefined means unrestricted. */
  skillFilter?: string[];
  /** Sparse per-session overlay applied after the agent-level filter. */
  skillOverrides?: Record<string, boolean>;
  /** Effective node-exec eligibility used to select connected node-hosted skills. */
  nodeSkillsEligibility?: SkillEligibilityContext["nodeSkills"];
  resolvedSkills?: Skill[];
  /** Present only when a session merges skills from distinct agent and execution roots. */
  skillRoots?: {
    agentWorkspaceDir: string;
    executionWorkspaceDir: string;
  };
  version?: number;
  promptFormatVersion?: number;
};
//#endregion
//#region src/plugins/computer-use-contract.d.ts
declare const COMPUTER_USE_V2_ACTION_NAMES: readonly ["screenshot", "left_click", "right_click", "middle_click", "double_click", "triple_click", "mouse_move", "left_click_drag", "left_mouse_down", "left_mouse_up", "scroll", "type", "key", "hold_key", "wait", "list_apps", "list_windows", "get_accessibility_tree", "get_cursor_position", "get_window_state", "launch_app", "kill_app", "bring_to_front", "set_value", "zoom", "get_browser_state", "browser_prepare", "browser_navigate", "browser_click", "browser_type", "browser_dialog", "browser_set_input_files", "browser_download", "browser_pointer", "escalate_scope", "get_recording_state", "start_recording", "stop_recording", "replay_trajectory", "invoke_menu"];
type ComputerUseV2ActionName = (typeof COMPUTER_USE_V2_ACTION_NAMES)[number];
declare const ComputerUseCapabilityDescriptorSchema: Type$1.TObject<{
  contractVersion: Type$1.TLiteral<2>;
  provider: Type$1.TObject<{
    id: Type$1.TString;
    label: Type$1.TString;
    generation: Type$1.TString;
  }>;
  actions: Type$1.TArray<Type$1.TEnum<["screenshot", "left_click", "right_click", "middle_click", "double_click", "triple_click", "mouse_move", "left_click_drag", "left_mouse_down", "left_mouse_up", "scroll", "type", "key", "hold_key", "wait", "list_apps", "list_windows", "get_accessibility_tree", "get_cursor_position", "get_window_state", "launch_app", "kill_app", "bring_to_front", "set_value", "zoom", "get_browser_state", "browser_prepare", "browser_navigate", "browser_click", "browser_type", "browser_dialog", "browser_set_input_files", "browser_download", "browser_pointer", "escalate_scope", "get_recording_state", "start_recording", "stop_recording", "replay_trajectory", "invoke_menu"]>>;
  targets: Type$1.TArray<Type$1.TEnum<["screen", "window", "element", "browser"]>>;
  deliveryModes: Type$1.TArray<Type$1.TEnum<["background", "foreground"]>>;
  observations: Type$1.TArray<Type$1.TEnum<["image", "accessibility", "browser"]>>;
  features: Type$1.TObject<{
    recording: Type$1.TBoolean;
    agentCursor: Type$1.TBoolean;
    multiDisplay: Type$1.TBoolean;
  }>;
}>;
type ComputerUseCapabilityDescriptor = Static<typeof ComputerUseCapabilityDescriptorSchema>;
//#endregion
//#region packages/model-catalog-core/src/model-catalog-refs.d.ts
type ProviderModelRef = {
  provider: string;
  model: string;
};
//#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">;
  }>]>>;
  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/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/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;
};
//#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$1 = z.infer<typeof ActivitySummarySchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/session-participant.d.ts
/** Product identity, independent of display metadata and authorization. */
declare const SessionParticipantIdentitySchema: Type$1.TUnion<[Type$1.TObject<{
  type: Type$1.TLiteral<"profile">;
  id: Type$1.TString;
}>, Type$1.TObject<{
  type: Type$1.TLiteral<"agent">;
  id: Type$1.TString;
}>, Type$1.TObject<{
  type: Type$1.TLiteral<"remote">;
  pluginId: Type$1.TString;
  domain: Type$1.TString;
  idKind: Type$1.TString;
  id: Type$1.TString;
}>, Type$1.TObject<{
  type: Type$1.TLiteral<"observation">;
  pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
  id: Type$1.TString;
}>, Type$1.TObject<{
  type: Type$1.TLiteral<"legacy">;
  actorType: Type$1.TString;
  source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  id: Type$1.TString;
}>]>;
declare const SessionParticipantSchema: Type$1.TObject<{
  identity: Type$1.TUnion<[Type$1.TObject<{
    type: Type$1.TLiteral<"profile">;
    id: Type$1.TString;
  }>, Type$1.TObject<{
    type: Type$1.TLiteral<"agent">;
    id: Type$1.TString;
  }>, Type$1.TObject<{
    type: Type$1.TLiteral<"remote">;
    pluginId: Type$1.TString;
    domain: Type$1.TString;
    idKind: Type$1.TString;
    id: Type$1.TString;
  }>, Type$1.TObject<{
    type: Type$1.TLiteral<"observation">;
    pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
    accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
    senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
    id: Type$1.TString;
  }>, Type$1.TObject<{
    type: Type$1.TLiteral<"legacy">;
    actorType: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
    id: Type$1.TString;
  }>]>;
  label: Type$1.TOptional<Type$1.TString>;
  avatarUrl: Type$1.TOptional<Type$1.TString>;
}>;
type SessionParticipantIdentity = Static<typeof SessionParticipantIdentitySchema>;
type SessionParticipant = Static<typeof SessionParticipantSchema>;
//#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
/** Kept aligned with SessionStateActorType (src/sessions/session-state-event-kinds.ts); not imported to avoid layering config/sessions onto src/sessions. */
type SessionActor = {
  type: "human" | "agent" | "system";
  id?: string;
  label?: string;
};
/** Only trusted creation owners may stamp a Gateway profile namespace. */
type SessionCreatedActor = SessionActor & ({
  type: "human";
  source: "profile" | "channel" | "unknown";
} | {
  type: "agent" | "system";
});
type SessionOwnerAssignment = {
  actor: SessionActor;
  assignedBy?: SessionActor;
  assignedAt?: number;
};
type SessionCreatedVia = "operator" | "spawn" | "channel" | "cron" | "talk" | "run" | "plugin" | "internal";
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;
};
type SessionTranscriptUpdateFields = {
  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;
};
/** Normalized transcript update emitted after a session transcript changes. */
type SessionTranscriptUpdate = Omit<SessionTranscriptUpdateFields, "sessionFile" | "lifecycleRevision" | "target"> & {
  target: Omit<SessionTranscriptUpdateTarget, "storePath">;
};
/** Internal transcript update that may identify a transcript without a file path. */
type InternalSessionTranscriptUpdate = SessionTranscriptUpdateFields;
type SessionTranscriptListener = (update: SessionTranscriptUpdate) => void;
/** Registers a listener for normalized session transcript updates. */
declare function onSessionTranscriptUpdate(listener: SessionTranscriptListener): () => void;
//#endregion
//#region packages/gateway-protocol/src/schema/sessions-goal.d.ts
declare const SessionGoalSchema: Type$1.TObject<{
  schemaVersion: Type$1.TLiteral<1>;
  id: Type$1.TString;
  objective: Type$1.TString;
  status: Type$1.TUnion<[Type$1.TLiteral<"active">, Type$1.TLiteral<"paused">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"usage_limited">, Type$1.TLiteral<"budget_limited">, Type$1.TLiteral<"complete">]>;
  createdAt: Type$1.TNumber;
  updatedAt: Type$1.TNumber;
  tokenStart: Type$1.TNumber;
  tokenStartFresh: Type$1.TOptional<Type$1.TBoolean>;
  tokensUsed: Type$1.TNumber;
  tokenBudget: Type$1.TOptional<Type$1.TNumber>;
  continuationTurns: Type$1.TNumber;
  lastStatusNote: Type$1.TOptional<Type$1.TString>;
  pausedAt: Type$1.TOptional<Type$1.TNumber>;
  blockedAt: Type$1.TOptional<Type$1.TNumber>;
  completedAt: Type$1.TOptional<Type$1.TNumber>;
  usageLimitedAt: Type$1.TOptional<Type$1.TNumber>;
  budgetLimitedAt: Type$1.TOptional<Type$1.TNumber>;
}>;
type SessionGoal = Static<typeof SessionGoalSchema>;
declare const SessionsGoalMutationResultSchema: Type$1.TObject<{
  operationId: Type$1.TString;
  action: Type$1.TUnion<[Type$1.TLiteral<"start">, Type$1.TLiteral<"edit">, Type$1.TLiteral<"pause">, Type$1.TLiteral<"resume">, Type$1.TLiteral<"complete">, Type$1.TLiteral<"block">, Type$1.TLiteral<"clear">]>;
  sessionId: Type$1.TString;
  goalId: Type$1.TString;
  goal: Type$1.TOptional<Type$1.TObject<{
    schemaVersion: Type$1.TLiteral<1>;
    id: Type$1.TString;
    objective: Type$1.TString;
    status: Type$1.TUnion<[Type$1.TLiteral<"active">, Type$1.TLiteral<"paused">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"usage_limited">, Type$1.TLiteral<"budget_limited">, Type$1.TLiteral<"complete">]>;
    createdAt: Type$1.TNumber;
    updatedAt: Type$1.TNumber;
    tokenStart: Type$1.TNumber;
    tokenStartFresh: Type$1.TOptional<Type$1.TBoolean>;
    tokensUsed: Type$1.TNumber;
    tokenBudget: Type$1.TOptional<Type$1.TNumber>;
    continuationTurns: Type$1.TNumber;
    lastStatusNote: Type$1.TOptional<Type$1.TString>;
    pausedAt: Type$1.TOptional<Type$1.TNumber>;
    blockedAt: Type$1.TOptional<Type$1.TNumber>;
    completedAt: Type$1.TOptional<Type$1.TNumber>;
    usageLimitedAt: Type$1.TOptional<Type$1.TNumber>;
    budgetLimitedAt: Type$1.TOptional<Type$1.TNumber>;
  }>>;
  runId: Type$1.TOptional<Type$1.TString>;
  replayed: Type$1.TOptional<Type$1.TLiteral<true>>;
  status: Type$1.TUnion<[Type$1.TLiteral<"started">, Type$1.TLiteral<"updated">, Type$1.TLiteral<"cleared">]>;
}>;
type SessionsGoalMutationResult = Static<typeof SessionsGoalMutationResultSchema>;
//#endregion
//#region src/config/sessions/goals-operations.types.d.ts
type SessionGoalOperationResult = Omit<SessionsGoalMutationResult, "replayed">;
type SessionTranscriptTurnMutationResult = {
  result: SessionGoalOperationResult;
  replayed: boolean;
};
//#endregion
//#region src/channels/inbound-event/kind.d.ts
/**
 * High-level inbound event class used to separate actionable user requests from room activity.
 */
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 packages/normalization-core/src/result.d.ts
/** Result of a fallible operation. Expected failures use the `ok: false` arm. */
type Result$1<TValue, TError> = {
  ok: true;
  value: TValue;
} | {
  ok: false;
  error: TError;
};
//#endregion
//#region packages/media-understanding-common/src/types.d.ts
/** Kind of media-understanding output produced for an attachment. */
type MediaUnderstandingKind = "audio.transcription" | "video.description" | "image.description";
/** Capability exposed by a media-understanding provider. */
type MediaUnderstandingCapability = "image" | "audio" | "video";
/** Normalized text output produced by media understanding. */
type MediaUnderstandingOutput = {
  kind: MediaUnderstandingKind;
  attachmentIndex: number;
  text: string;
  provider: string;
  model?: string;
  requestedBackend?: string;
  observedBackend?: string;
};
//#endregion
//#region src/agents/auth-profiles/credential-schema.d.ts
/** Provider-owned fields retained with OAuth material through storage and refresh. */
declare const oauthCredentialMetadataSchema: z.ZodObject<{
  idToken: z.ZodOptional<z.ZodString>;
  clientId: z.ZodOptional<z.ZodString>;
  authorizationScope: z.ZodOptional<z.ZodString>;
  grantedScope: z.ZodOptional<z.ZodString>;
  enterpriseUrl: z.ZodOptional<z.ZodString>;
  projectId: z.ZodOptional<z.ZodString>;
  accountId: z.ZodOptional<z.ZodString>;
  chatgptPlanType: z.ZodOptional<z.ZodString>;
  subscriptionType: z.ZodOptional<z.ZodString>;
  rateLimitTier: z.ZodOptional<z.ZodString>;
  tokenEndpoint: z.ZodOptional<z.ZodString>;
  deviceAuthorizationEndpoint: z.ZodOptional<z.ZodString>;
  issuer: z.ZodOptional<z.ZodString>;
  authFlow: z.ZodOptional<z.ZodString>;
}, z.core.$strict>;
type OAuthCredentialMetadata = z.infer<typeof oauthCredentialMetadataSchema>;
//#endregion
//#region src/agents/auth-profiles/legacy-oauth-ref.d.ts
/** Legacy OAuth ref source persisted by older credential stores. */
declare const LEGACY_OAUTH_REF_SOURCE = "openclaw-credentials";
/** Legacy OAuth ref provider persisted by older credential stores. */
declare const LEGACY_OAUTH_REF_PROVIDER = "openai-codex";
type LegacyOAuthRef = {
  source: typeof LEGACY_OAUTH_REF_SOURCE;
  provider: typeof LEGACY_OAUTH_REF_PROVIDER;
  id: string;
};
//#endregion
//#region src/agents/auth-profiles/types.d.ts
/** Provider identifier recorded on auth profile credentials. */
type OAuthProvider = string;
/** Refreshable OAuth credential fields persisted for provider auth profiles. */
type OAuthCredentials$1 = OAuthCredentialMetadata & {
  access: string;
  refresh: string;
  expires: number;
  provider?: OAuthProvider;
  email?: string;
};
/** API-key credential with optional secret reference indirection. */
type ApiKeyCredential$1 = {
  type: "api_key";
  provider: string;
  key?: string;
  keyRef?: SecretRef;
  /** Explicit opt-out for copying this profile when creating another agent. */
  copyToAgents?: boolean;
  email?: string;
  displayName?: string;
  /** Optional provider-specific metadata (e.g., account IDs, gateway IDs). */
  metadata?: Record<string, string>;
};
/** Static token credential that OpenClaw does not refresh. */
type TokenCredential$1 = {
  /**
   * Static bearer-style token (often OAuth access token / PAT).
   * Not refreshable by OpenClaw (unlike `type: "oauth"`).
   */
  type: "token";
  provider: string;
  token?: string;
  tokenRef?: SecretRef;
  /** Explicit opt-out for copying this profile when creating another agent. */
  copyToAgents?: boolean;
  /** Optional expiry timestamp (ms since epoch). */
  expires?: number;
  email?: string;
  displayName?: string;
};
/** Refreshable OAuth credential plus provider metadata and legacy references. */
type OAuthCredential$1 = OAuthCredentials$1 & {
  type: "oauth";
  provider: string;
  oauthRef?: LegacyOAuthRef;
  /**
   * OAuth refresh tokens are not portable by default. Provider-owned flows may
   * set this only when copying refresh material across agents is known safe.
   */
  copyToAgents?: boolean;
  email?: string;
  displayName?: string;
};
type SavedSetupCredential = {
  apiKeyHeader?: true;
  agentRuntimeId?: string;
  replacement: boolean;
  modelRef: string;
  /** Setup validates the connection config when retrying, outside auth hot paths. */
  configJson: string;
  authChoice?: string;
  pluginId?: string;
};
/** Credential variants supported by auth profiles. */
type AuthProfileCredential = (ApiKeyCredential$1 | TokenCredential$1 | OAuthCredential$1) & {
  /** Replacement credentials stay unavailable until their verified connection is activated. */
  setup?: SavedSetupCredential;
};
/** Closed reasons that drive cooldown, disable, and failure counters. */
type AuthProfileFailureReason = "auth" | "auth_permanent" | "format" | "overloaded" | "rate_limit" | "billing" | "timeout" | "model_not_found" | "session_expired" | "empty_response" | "no_error_details" | "unclassified" | "unknown";
/** Optional host diagnostic attached to a canonical cooldown reason. */
type AuthProfileCooldownClassification = "wham_token_expired" | "wham_account_dead";
/** Profile-wide blocked reason reported by provider usage probes. */
type AuthProfileBlockedReason = "subscription_limit";
/** Source that marked a profile as blocked. */
type AuthProfileBlockedSource = "codex_rate_limits" | "wham";
/** Per-profile usage statistics for round-robin and cooldown tracking */
type ProfileUsageStats = {
  lastUsed?: number;
  blockedUntil?: number;
  blockedReason?: AuthProfileBlockedReason;
  blockedSource?: AuthProfileBlockedSource;
  blockedModel?: string;
  blockedScope?: "model";
  cooldownUntil?: number;
  cooldownReason?: AuthProfileFailureReason;
  cooldownClassification?: AuthProfileCooldownClassification;
  cooldownModel?: string;
  disabledUntil?: number;
  disabledReason?: AuthProfileFailureReason;
  errorCount?: number;
  failureCounts?: Partial<Record<AuthProfileFailureReason, number>>;
  lastFailureAt?: number;
  /** Most recent quota probe or successful provider use. */
  lastProbeAt?: number;
};
/** Durable, non-secret auth profile selection state. */
type AuthProfileState = {
  /**
   * Optional per-agent preferred profile order overrides.
   * This lets you lock/override auth rotation for a specific agent without
   * changing the global config.
   */
  order?: Record<string, string[]>;
  lastGood?: Record<string, string>;
  /** Usage statistics per profile for round-robin rotation */
  usageStats?: Record<string, ProfileUsageStats>;
};
/** Persisted credential payload without runtime-only selection state. */
type AuthProfileSecretsStore = {
  version: number;
  profiles: Record<string, AuthProfileCredential>;
};
/** Effective in-memory auth store combining credentials, state, and overlays. */
type AuthProfileStore = AuthProfileSecretsStore & AuthProfileState & {
  /** Runtime-only provenance for credentials cloned from persisted auth stores. */
  runtimePersistedProfileIds?: string[];
  /** Runtime-only provenance for external OAuth profiles overlaid onto this store. */
  runtimeExternalProfileIds?: string[];
  /** True when the runtime external profile set was freshly resolved, even if empty. */
  runtimeExternalProfileIdsAuthoritative?: boolean;
};
/** Physical origin of a canonical credential selected into a session read view. */
type AuthProfileCredentialSource = {
  readonly databasePath: string;
  readonly provider: string;
};
/** Internal effective-store ownership metadata; never exposed through the plugin SDK. */
type RuntimeAuthProfileStore = AuthProfileStore & {
  /** Physical sources of the selected rows; retained only in session read views. */
  runtimeCredentialSources?: Record<string, AuthProfileCredentialSource>;
  /** Runtime-only built-in CLI winners; internal provenance, never exposed or persisted. */
  runtimeExternalCliProfileIds?: string[];
  runtimeLocalProfileIds?: string[];
  /** Provider orders stored by this owner; [] means no local override, even with inherited priority. */
  runtimeLocalOrderProviderIds?: string[];
  runtimeInheritsMainState?: boolean;
};
//#endregion
//#region src/media-understanding/types.d.ts
/** Agent-owned runtime handle carried opaquely through media provider requests. */
type MediaPreparedModelRuntime = Readonly<{
  agentDir: string;
  workspaceDir?: string;
  config: OpenClawConfig;
  createStores: () => unknown;
}>;
type MediaUnderstandingDecisionOutcome = "success" | "failed" | "skipped" | "disabled" | "no-attachment" | "scope-deny";
type MediaUnderstandingModelDecision = {
  provider?: string;
  model?: string;
  requestedBackend?: string;
  observedBackend?: string;
  type: "provider" | "cli";
  outcome: "success" | "skipped" | "failed";
  reason?: string;
};
type MediaUnderstandingAttachmentDecision = {
  attachmentIndex: number;
  attempts: MediaUnderstandingModelDecision[];
  chosen?: MediaUnderstandingModelDecision;
};
type MediaAttachmentDisposition = {
  kind: "handled";
} | {
  kind: "handed-to-native-vision";
} | {
  kind: "not-selected";
} | {
  kind: "capability-disabled";
} | {
  kind: "no-model";
} | {
  kind: "scope-denied";
} | {
  kind: "failed";
  reason?: string;
};
type MediaAttachmentProcessing = "completed" | "omitted";
type MediaUnderstandingDecision = {
  capability: MediaUnderstandingCapability;
  outcome: MediaUnderstandingDecisionOutcome;
  attachments: MediaUnderstandingAttachmentDecision[];
  attachmentDispositions?: Record<number, MediaAttachmentDisposition>;
  attachmentProcessing?: Record<number, MediaAttachmentProcessing>;
  nativeVisionActive?: boolean;
};
type MediaUnderstandingProviderRequestAuthOverride = {
  mode: "provider-default";
} | {
  mode: "authorization-bearer";
  token: string;
} | {
  mode: "header";
  headerName: string;
  value: string;
  prefix?: string;
};
type MediaUnderstandingProviderRequestTlsOverride = {
  ca?: string;
  cert?: string;
  key?: string;
  passphrase?: string;
  serverName?: string;
  insecureSkipVerify?: boolean;
};
type MediaUnderstandingProviderRequestProxyOverride = {
  mode: "env-proxy";
  tls?: MediaUnderstandingProviderRequestTlsOverride;
} | {
  mode: "explicit-proxy";
  url: string;
  tls?: MediaUnderstandingProviderRequestTlsOverride;
};
type MediaUnderstandingProviderRequestTransportOverrides = {
  headers?: Record<string, string>;
  auth?: MediaUnderstandingProviderRequestAuthOverride;
  proxy?: MediaUnderstandingProviderRequestProxyOverride;
  tls?: MediaUnderstandingProviderRequestTlsOverride;
  /** Runtime-only flag from trusted model-provider config; media config rejects it. */
  allowPrivateNetwork?: boolean;
};
type MediaUnderstandingProviderRequestAuth = {
  kind: "api-key";
  apiKey: string;
  source?: string;
} | {
  kind: "none";
  source: string;
};
type AudioTranscriptionRequest = {
  buffer: Buffer;
  fileName: string;
  mime?: string;
  /** Compatibility field for existing providers; prefer auth.kind/apiKey. */
  apiKey: string;
  auth?: MediaUnderstandingProviderRequestAuth;
  baseUrl?: string;
  headers?: Record<string, string>;
  request?: MediaUnderstandingProviderRequestTransportOverrides;
  model?: string;
  language?: string;
  prompt?: string;
  query?: Record<string, string | number | boolean>;
  timeoutMs: number;
  signal?: AbortSignal;
  fetchFn?: typeof fetch;
};
type AudioTranscriptionResult = {
  text: string;
  model?: string;
};
type AudioTranscriptionContext = Omit<AudioTranscriptionRequest, "apiKey" | "auth"> & {
  cfg: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  profile?: string;
  preferredProfile?: string;
};
type VideoDescriptionRequest = {
  buffer: Buffer;
  fileName: string;
  mime?: string;
  /** Compatibility field for existing providers; prefer auth.kind/apiKey. */
  apiKey: string;
  auth?: MediaUnderstandingProviderRequestAuth;
  baseUrl?: string;
  headers?: Record<string, string>;
  request?: MediaUnderstandingProviderRequestTransportOverrides;
  model?: string;
  prompt?: string;
  timeoutMs: number;
  signal?: AbortSignal;
  fetchFn?: typeof fetch;
};
type VideoDescriptionResult = {
  text: string;
  model?: string;
};
type ImageDescriptionRequest = ImagesDescriptionInput & Omit<ImagesDescriptionRequest, "images">;
type ImagesDescriptionInput = {
  buffer: Buffer;
  fileName: string;
  mime?: string;
};
type ImagesDescriptionRequest = {
  images: ImagesDescriptionInput[];
  model: string;
  provider: string;
  prompt?: string;
  maxTokens?: number;
  timeoutMs: number;
  signal?: AbortSignal;
  profile?: string;
  preferredProfile?: string;
  authStore?: AuthProfileStore;
  agentId?: string;
  agentDir: string;
  workspaceDir?: string;
  preparedModelRuntime?: MediaPreparedModelRuntime;
  cfg: OpenClawConfig;
};
type ImageDescriptionResult = {
  text: string;
  model?: string;
};
type ImagesDescriptionResult = ImageDescriptionResult;
type StructuredExtractionTextInput = {
  type: "text";
  text: string;
};
type StructuredExtractionImageInput = {
  type: "image";
  buffer: Buffer;
  fileName: string;
  mime?: string;
};
type StructuredExtractionInput = StructuredExtractionTextInput | StructuredExtractionImageInput;
type StructuredExtractionRequest = {
  /** Image-first extraction input; callers must include at least one image. */
  input: StructuredExtractionInput[];
  instructions: string;
  schemaName?: string;
  jsonSchema?: unknown;
  jsonMode?: boolean;
  timeoutMs: number;
  signal?: AbortSignal;
  profile?: string;
  preferredProfile?: string;
  authStore?: AuthProfileStore;
  agentDir: string;
  cfg: OpenClawConfig;
  model: string;
  provider: string;
};
type StructuredExtractionResult = {
  text: string;
  parsed?: unknown;
  model?: string;
  provider?: string;
  contentType?: "json" | "text";
};
type MediaUnderstandingDocumentModelDefaults = {
  textExtraction?: string;
  image?: string | false;
};
type MediaUnderstandingProviderAuthContext = {
  config?: OpenClawConfig;
  provider: string;
  providerConfig?: ModelProviderConfig;
};
type MediaUnderstandingProviderAuthResult = {
  kind: "none";
  source: string;
} | {
  kind: "api-key";
  apiKey: string;
  source: string;
  mode?: "api-key";
};
type MediaUnderstandingProviderSyntheticAuthResult = {
  apiKey: string;
  source: string;
  mode: "api-key";
};
type MediaUnderstandingProvider = {
  id: string;
  capabilities?: MediaUnderstandingCapability[];
  defaultModels?: Partial<Record<MediaUnderstandingCapability, string>>;
  autoPriority?: Partial<Record<MediaUnderstandingCapability, number>>;
  nativeDocumentInputs?: Array<"pdf">;
  documentModels?: Partial<Record<"pdf", MediaUnderstandingDocumentModelDefaults>>;
  resolveAuth?: (ctx: MediaUnderstandingProviderAuthContext) => MediaUnderstandingProviderAuthResult | null | undefined;
  /** @deprecated Use resolveAuth. */
  resolveSyntheticAuth?: (ctx: MediaUnderstandingProviderAuthContext) => MediaUnderstandingProviderSyntheticAuthResult | null | undefined;
  transcribeAudio?: (req: AudioTranscriptionRequest) => Promise<AudioTranscriptionResult>;
  /** Called after file loading. Result.error is only a rejection before audio upload;
   * upload/HTTP failures must throw and stop automatic provider selection. */
  transcribeAudioWithContext?: (req: AudioTranscriptionContext) => Promise<Result$1<AudioTranscriptionResult, unknown>>;
  describeVideo?: (req: VideoDescriptionRequest) => Promise<VideoDescriptionResult>;
  describeImage?: (req: ImageDescriptionRequest) => Promise<ImageDescriptionResult>;
  describeImages?: (req: ImagesDescriptionRequest) => Promise<ImagesDescriptionResult>;
  extractStructured?: (req: StructuredExtractionRequest) => Promise<StructuredExtractionResult>;
};
//#endregion
//#region packages/media-core/src/constants.d.ts
/** Canonical media families used by attachment facts, routing, and MIME classification. */
type MediaKind = "image" | "audio" | "video" | "document" | "sticker" | "unknown";
/** Maps a MIME type to the media family used for size limits and routing. */
declare function mediaKindFromMime(mime?: string | null): MediaKind | undefined;
//#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/media/media-facts.d.ts
/** One ordered runtime attachment; array position is its alignment identity. */
type MediaFact = {
  path?: string;
  url?: string;
  contentType?: string;
  kind?: MediaKind;
  fileName?: string;
  /** Composer attachment provenance for display; never part of model input. */
  origin?: "paste" | "file";
  sizeBytes?: number;
  durationMs?: number;
  width?: number;
  height?: number;
  transcribed?: boolean;
  messageId?: string;
  workspaceDir?: string;
  /** Internal proof that this exact fact was covered by a legacy staged projection. */
  staged?: boolean;
  hydrationSuppressed?: boolean;
};
type MediaFactInput = { [Key in keyof MediaFact]?: MediaFact[Key] | null; };
declare const LEGACY_MEDIA_CONTEXT_KEYS: readonly ["MediaPath", "MediaPaths", "MediaUrl", "MediaUrls", "MediaType", "MediaTypes", "MediaDir", "MediaTranscribedIndexes", "MediaStaged", "MediaWorkspaceDir"];
type LegacyMediaContextKey = (typeof LEGACY_MEDIA_CONTEXT_KEYS)[number];
//#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 packages/agent-core/src/types.d.ts
/**
 * Stream function used by the agent loop.
 *
 * Contract:
 * - Must not throw or return a rejected promise for request/model/runtime failures.
 * - Must return an AssistantMessageEventStream.
 * - Failures must be encoded in the returned stream via protocol events and a
 *   final AssistantMessage with stopReason "error" or "aborted" and errorMessage.
 */
type StreamFn = StreamFn$1;
/**
 * Configuration for how tool calls from a single assistant message are executed.
 *
 * - "sequential": each tool call is prepared, checked for steering, executed, and finalized before the next one starts.
 * - "parallel": tool calls are prepared sequentially, checked for steering once, then allowed tools execute concurrently.
 *   `tool_execution_end` is emitted in tool completion order after each tool is finalized,
 *   while tool-result message artifacts are emitted later in assistant source order.
 */
type ToolExecutionMode = "sequential" | "parallel";
/**
 * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.
 *
 * - "all": drain and inject every queued message at that point.
 * - "one-at-a-time": drain and inject only the oldest queued message, leaving the rest queued for later drain points.
 */
type QueueMode$1 = "all" | "one-at-a-time";
/** A single tool call content block emitted by an assistant message. */
type AgentToolCall = Extract<AssistantMessage$1["content"][number], {
  type: "toolCall";
}>;
/**
 * Result returned from `beforeToolCall`.
 *
 * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.
 * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.
 */
interface BeforeToolCallResult {
  block?: boolean;
  reason?: string;
}
/** A validated call participating in an internal whole-batch admission check. */
interface InternalToolBatchCall {
  toolCall: AgentToolCall;
  args: unknown;
  /** Resolved tool identity for OpenClaw-owned argument canonicalization. */
  tool?: AgentTool;
}
/** Typed core signal used to recover once from a critical tool loop. */
interface ToolLoopIntervention {
  kind: "critical-tool-loop";
  toolCallId: string;
  toolName: string;
  actionKey: string;
  detector: string;
  count: number;
  reason: string;
}
/** Bucketed feedback for an admitted call, not a veto or recovery attempt. */
interface ToolLoopWarning {
  kind: "tool-loop-warning";
  toolCallId: string;
  count: number;
}
/** Context for OpenClaw-owned whole-batch tool admission. */
interface InternalBeforeToolBatchContext {
  assistantMessage: AssistantMessage$1;
  calls: InternalToolBatchCall[];
  context: AgentContext;
}
/** Result of OpenClaw-owned whole-batch tool admission. */
type InternalBeforeToolBatchResult = {
  intervention: ToolLoopIntervention;
  warnings?: never;
} | {
  intervention?: never;
  warnings?: ToolLoopWarning[];
};
interface DeferredToolCallContext {
  /** The assistant message that requested the deferred tool call. */
  assistantMessage: AssistantMessage$1;
  /** The raw tool call block whose authorized tool definition is deferred. */
  toolCall: AgentToolCall;
  /** Current agent context before the deferred tool is hydrated. */
  context: AgentContext;
}
/**
 * Partial override returned from `afterToolCall`.
 *
 * Merge semantics are field-by-field:
 * - `content`: if provided, replaces the tool result content array in full
 * - `details`: if provided, replaces the tool result details value in full
 * - `isError`: if provided, replaces the tool result error flag
 * - `terminate`: if provided, replaces the early-termination hint
 *
 * Omitted fields keep the original executed tool result values.
 * There is no deep merge for `content` or `details`.
 */
interface AfterToolCallResult {
  content?: (TextContent | ImageContent$1)[];
  details?: unknown;
  isError?: boolean;
  /**
   * Hint that the agent should stop after the current tool batch.
   * Early termination only happens when every finalized tool result in the batch sets this to true.
   */
  terminate?: boolean;
}
/** Context passed to `beforeToolCall`. */
interface BeforeToolCallContext {
  /** The assistant message that requested the tool call. */
  assistantMessage: AssistantMessage$1;
  /** The raw tool call block from `assistantMessage.content`. */
  toolCall: AgentToolCall;
  /** Validated tool arguments for the target tool schema. */
  args: unknown;
  /** Current agent context at the time the tool call is prepared. */
  context: AgentContext;
}
/** Context passed to `afterToolCall`. */
interface AfterToolCallContext {
  /** The assistant message that requested the tool call. */
  assistantMessage: AssistantMessage$1;
  /** The raw tool call block from `assistantMessage.content`. */
  toolCall: AgentToolCall;
  /** Validated tool arguments for the target tool schema. */
  args: unknown;
  /** The executed tool result before unknown `afterToolCall` overrides are applied. */
  result: AgentToolResult<unknown>;
  /** Whether the executed tool result is currently treated as an error. */
  isError: boolean;
  /** Current agent context at the time the tool call is finalized. */
  context: AgentContext;
}
/**
 * Context passed to `afterToolOutcome` after every finalized tool outcome.
 *
 * Unlike `afterToolCall`, this hook also observes failures that prevented
 * execution. `args` contains validated arguments when execution reached the
 * prepared state, otherwise the raw model arguments.
 */
interface AfterToolOutcomeContext {
  /** The assistant message that requested the tool call. */
  assistantMessage: AssistantMessage$1;
  /** The tool call whose final result is being emitted. */
  toolCall: AgentToolCall;
  /** Validated arguments when available, otherwise the raw model arguments. */
  args: unknown;
  /** Final result after any executed-only `afterToolCall` override. */
  result: AgentToolResult<unknown>;
  /** Whether the finalized result is currently treated as an error. */
  isError: boolean;
  /** Whether the tool implementation started executing. */
  executionStarted: boolean;
  /** Typed pre-execution failure provenance when available. */
  errorKind?: "argument-validation";
  /** Current agent context at the time the tool outcome is finalized. */
  context: AgentContext;
}
/** Context passed to `shouldStopAfterTurn`. */
interface ShouldStopAfterTurnContext {
  /** The assistant message that completed the turn. */
  message: AssistantMessage$1;
  /** Tool result messages passed to the preceding `turn_end` event. */
  toolResults: ToolResultMessage[];
  /** Current agent context after the turn's assistant message and tool results have been appended. */
  context: AgentContext;
  /** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */
  newMessages: AgentMessage[];
}
/** Replacement runtime state used by the agent loop before starting another provider request. */
interface AgentLoopTurnUpdate {
  /** Commit accepted steering and settle this invocation without another model request. */
  stop?: boolean;
  /** Context for the next provider request. */
  context?: AgentContext;
  /** Model for the next provider request. */
  model?: Model;
  /** Thinking level for the next provider request. */
  thinkingLevel?: ThinkingLevel;
}
interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}
/** @internal Mutable one-shot budget shared by prompt retries in one Agent run. */
type ToolLoopRecoveryState = {
  criticalToolLoopSeen: boolean;
};
interface AgentLoopConfig extends SimpleStreamOptions {
  model: Model;
  /** Logical thinking level retained across model changes before provider mapping. */
  thinkingLevel?: ThinkingLevel;
  /**
   * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
   *
   * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
   * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
   * status messages) should be filtered out.
   *
   * Contract: must not throw or reject. Return a safe fallback value instead.
   * Throwing interrupts the low-level agent loop without producing a normal event sequence.
   *
   * @example
   * ```typescript
   * convertToLlm: (messages) => messages.flatMap(m => {
   *   if (m.role === "custom") {
   *     // Convert custom message to user message
   *     return [{ role: "user", content: m.content, timestamp: m.timestamp }];
   *   }
   *   if (m.role === "notification") {
   *     // Filter out UI-only messages
   *     return [];
   *   }
   *   // Pass through standard LLM messages
   *   return [m];
   * })
   * ```
   */
  convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
  /**
   * Optional transform applied to the context before `convertToLlm`.
   *
   * Use this for operations that work at the AgentMessage level:
   * - Context window management (pruning old messages)
   * - Injecting context from external sources
   *
   * Contract: must not throw or reject. Return the original messages or another
   * safe fallback value instead.
   *
   * @example
   * ```typescript
   * transformContext: async (messages) => {
   *   if (estimateTokens(messages) > MAX_TOKENS) {
   *     return pruneOldMessages(messages);
   *   }
   *   return messages;
   * }
   * ```
   */
  transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
  /**
   * Resolves an API key dynamically for each LLM call.
   *
   * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire
   * during long-running tool execution phases.
   *
   * Contract: must not throw or reject. Return undefined when no key is available.
   */
  getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
  /**
   * Called after each turn fully completes and `turn_end` has been emitted.
   *
   * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,
   * without starting another LLM call. Steering already drained at a tool checkpoint takes precedence,
   * so this hook is deferred until that steering turn completes.
   *
   * Use this to request a graceful stop after the current turn, e.g. before context gets too full.
   *
   * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.
   */
  shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
  /**
   * Called after `turn_end` and before the loop decides whether another provider request should start.
   * Return replacement context/model/thinking state to affect the next turn in this run.
   * Return undefined to keep using the current context/config.
   */
  prepareNextTurn?: (context: PrepareNextTurnContext) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;
  /**
   * Returns steering messages to inject into the conversation mid-run.
   *
   * Sequential execution checks before each tool starts, including again after
   * asynchronous preparation. Parallel execution checks once after preparation
   * and immediately before launching the prepared calls. A non-empty result
   * skips calls that have not started and is added to context before the next
   * LLM call; already-running calls continue.
   *
   * Once a check returns messages, the loop carries that exact result to the
   * next turn without polling again. This preserves queue drain ordering.
   *
   * Use this for "steering" the agent while it's working.
   *
   * Contract: must not throw or reject. Resolve to [] when no steering messages are available.
   */
  getSteeringMessages?: () => Promise<AgentMessage[]>;
  /**
   * Returns follow-up messages to process after the agent would otherwise stop.
   *
   * Called when the agent has no more tool calls and no steering messages.
   * If messages are returned, they're added to the context and the agent
   * continues with another turn.
   *
   * Use this for follow-up messages that should wait until the agent finishes.
   *
   * Contract: must not throw or reject. Return [] when no follow-up messages are available.
   */
  getFollowUpMessages?: () => Promise<AgentMessage[]>;
  /** Consumes the cancellation fact for a previously drained queue message. */
  consumeQueuedMessageCancellation?: (message: AgentMessage) => boolean;
  /**
   * Tool execution mode.
   * - "sequential": execute tool calls one by one, checking for steering before each starts
   * - "parallel": preflight tool calls sequentially, then execute allowed tools concurrently;
   *   steering is checked once immediately before prepared calls launch;
   *   emit `tool_execution_end` in tool completion order after each tool is finalized,
   *   then emit tool-result message artifacts later in assistant source order
   *
   * Default: "parallel"
   */
  toolExecution?: ToolExecutionMode;
  /**
   * Called before a tool is executed, after arguments have been validated.
   *
   * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.
   * The hook receives the agent abort signal and is responsible for honoring it.
   */
  beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
  /** @internal OpenClaw-owned batch admission. Not a plugin or session SDK hook. */
  beforeToolBatch?: (context: InternalBeforeToolBatchContext, signal?: AbortSignal) => Promise<InternalBeforeToolBatchResult | undefined>;
  /** @internal Preserves the one-shot recovery budget across Agent.continue() retries. */
  toolLoopRecoveryState?: ToolLoopRecoveryState;
  /**
   * Hydrates an already-authorized tool that was deferred out of the current
   * provider-visible tool set. Return undefined for every other unknown name so
   * the loop keeps the normal "Tool <name> not found" result. Thrown or rejected
   * failures become error tool results for the requested call.
   */
  resolveDeferredTool?: (context: DeferredToolCallContext, signal?: AbortSignal) => Promise<AgentTool | undefined> | AgentTool | undefined;
  /**
   * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.
   *
   * Return an `AfterToolCallResult` to override parts of the executed tool result:
   * - `content` replaces the full content array
   * - `details` replaces the full details payload
   * - `isError` replaces the error flag
   * - `terminate` replaces the early-termination hint
   *
   * Any omitted fields keep their original values. No deep merge is performed.
   * The hook receives the agent abort signal and is responsible for honoring it.
   */
  afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
  /**
   * Called after every tool outcome is finalized, including failures that
   * prevented execution. It runs after `afterToolCall` for executed tools.
   */
  afterToolOutcome?: (context: AfterToolOutcomeContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
}
/**
 * Thinking/reasoning level for models that support it.
 * Note: "xhigh" is only supported by selected model families. Use model thinking-level metadata
 * from openclaw/plugin-sdk/llm to detect support for a concrete model.
 */
type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
interface BashExecutionMessage {
  /** Harness role for shell command transcripts. */
  role: "bashExecution";
  /** Command line that was executed. */
  command: string;
  /** Captured command output, usually already truncated for context. */
  output: string;
  /** Process exit code when the command reached process exit. */
  exitCode: number | undefined;
  /** True when the command was interrupted before normal completion. */
  cancelled: boolean;
  /** True when output was shortened for transcript/context storage. */
  truncated: boolean;
  /** Optional path containing the complete output when truncation occurred. */
  fullOutputPath?: string;
  /** Millisecond timestamp for transcript ordering. */
  timestamp: number;
  /** Exclude this command transcript from model context while keeping it in session history. */
  excludeFromContext?: boolean;
}
interface CustomMessage<T = unknown> {
  /** Harness role for application-defined transcript content. */
  role: "custom";
  /** Application-defined discriminator for rendering or handling this message. */
  customType: string;
  /** Content replayed into model context when this message is included. */
  content: string | (TextContent | ImageContent$1)[];
  /** Whether UI surfaces should display this message. */
  display: boolean;
  /** Keep display-only application activity out of future model context. */
  excludeFromContext?: boolean;
  /** Optional application-specific metadata. */
  details?: T;
  /** Millisecond timestamp for transcript ordering. */
  timestamp: number;
}
interface BranchSummaryMessage {
  /** Harness role for summaries produced when returning from another branch. */
  role: "branchSummary";
  /** Summary text inserted back into model context. */
  summary: string;
  /** Entry id of the branch root or source leaf being summarized. */
  fromId: string;
  /** Millisecond timestamp for transcript ordering. */
  timestamp: number;
}
interface CompactionSummaryMessage {
  /** Harness role for summaries that replace compacted transcript history. */
  role: "compactionSummary";
  /** Summary text inserted back into model context. */
  summary: string;
  /** Estimated context tokens before compaction. */
  tokensBefore: number;
  /** Timestamp may be numeric in memory or string when loaded from older persisted rows. */
  timestamp: number | string;
  /** Optional estimated context tokens after compaction. */
  tokensAfter?: number;
  /** Optional first retained entry id from the compaction range. */
  firstKeptEntryId?: string;
  /** Optional implementation-specific compaction metadata. */
  details?: unknown;
}
/**
 * Extensible interface for custom app and harness messages.
 * Apps can extend via declaration merging.
 */
interface CustomAgentMessages {
  bashExecution: BashExecutionMessage;
  custom: CustomMessage;
  branchSummary: BranchSummaryMessage;
  compactionSummary: CompactionSummaryMessage;
}
/**
 * AgentMessage: Union of LLM messages + custom messages.
 * This abstraction allows apps to add custom message types while maintaining
 * type safety and compatibility with the base LLM messages.
 */
type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
/**
 * Public agent state.
 *
 * `tools` and `messages` use accessor properties so implementations can copy
 * assigned arrays before storing them.
 */
interface AgentState {
  /** System prompt sent with each model request. */
  systemPrompt: string;
  /** Active model used for future turns. */
  model: Model;
  /** Requested reasoning level for future turns. */
  thinkingLevel: ThinkingLevel;
  /** Available tools. Assigning a new array copies the top-level array. */
  set tools(tools: AgentTool[]);
  get tools(): AgentTool[];
  /** Conversation transcript. Assigning a new array copies the top-level array. */
  set messages(messages: AgentMessage[]);
  get messages(): AgentMessage[];
  /**
   * True while the agent is processing a prompt or continuation.
   *
   * This remains true until awaited `agent_end` listeners settle.
   */
  readonly isStreaming: boolean;
  /** Partial assistant message for the current streamed response, if any. */
  readonly streamingMessage?: AgentMessage;
  /** Tool call ids currently executing. */
  readonly pendingToolCalls: ReadonlySet<string>;
  /** Error message from the most recent failed or aborted assistant turn, if any. */
  readonly errorMessage?: string;
}
/** Channel-safe progress text emitted by a running tool. */
interface AgentToolProgress {
  /** Public text suitable for user-facing progress surfaces. */
  text: string;
  /** Tool progress is rendered by channel progress UIs. */
  visibility: "channel";
  /** Progress text must not contain secrets, private args, or fetched content. */
  privacy: "public";
  /** Optional stable id for progress line replacement. */
  id?: string;
}
/** Final or partial result produced by a tool. */
interface AgentToolResult<T> {
  /** Text or image content returned to the model. */
  content: (TextContent | ImageContent$1)[];
  /** Arbitrary structured details for logs or UI rendering. */
  details: T;
  /** Optional public progress hint for partial tool updates; never model content. */
  progress?: AgentToolProgress;
  /**
   * Hint that the agent should stop after the current tool batch.
   * Early termination only happens when every finalized tool result in the batch sets this to true.
   */
  terminate?: boolean;
}
/** Callback used by tools to stream partial execution updates. */
type AgentToolUpdateCallback<T = unknown> = (partialResult: AgentToolResult<T>) => void;
/** Origin class for tool output that can taint later model-authored content in the same turn. */
type ToolResultContentSource = "network";
/** Tool definition used by the agent runtime. */
interface AgentTool<TParameters extends TSchema = TSchema, TDetails = unknown> extends Tool<TParameters> {
  /** Human-readable label for UI display. */
  label: string;
  /** Optional schema for the structured `AgentToolResult.details` value. */
  outputSchema?: TSchema;
  /** Preserve lifecycle telemetry without rendering transient channel progress. */
  hideFromChannelProgress?: boolean;
  /** Tool results contain externally controlled network content. */
  resultContentSource?: ToolResultContentSource;
  /**
   * Optional compatibility shim for raw tool-call arguments before schema validation.
   * Must return an object that matches `TParameters`.
   */
  prepareArguments?: (args: unknown) => Static<TParameters>;
  /** Execute the tool call. Throw on failure instead of encoding errors in `content`. */
  execute: (toolCallId: string, params: Static<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
  /**
   * Per-tool execution mode override.
   * - "sequential": this tool must execute one at a time with other tool calls.
   * - "parallel": this tool can execute concurrently with other tool calls.
   *
   * If omitted, the default execution mode applies.
   */
  executionMode?: ToolExecutionMode;
}
/** Context snapshot passed into the low-level agent loop. */
interface AgentContext {
  /** System prompt included with the request. */
  systemPrompt: string;
  /** Transcript visible to the model. */
  messages: AgentMessage[];
  /** Tools available for this run. */
  tools?: AgentTool[];
}
/**
 * Events emitted by the Agent for UI updates.
 *
 * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`
 * listeners for that event are still part of run settlement. The agent becomes
 * idle only after those listeners finish.
 */
type AgentEvent = {
  type: "agent_start";
} | {
  type: "agent_end";
  messages: AgentMessage[];
} | {
  type: "turn_start";
} | {
  type: "turn_end";
  message: AgentMessage;
  toolResults: ToolResultMessage[];
} | {
  type: "message_start";
  message: AgentMessage;
} | {
  type: "message_update";
  message: AgentMessage;
  assistantMessageEvent: AssistantMessageEvent;
} | {
  type: "message_end";
  message: AgentMessage;
} | {
  type: "tool_execution_start";
  toolCallId: string;
  toolName: string;
  args: unknown;
  hideFromChannelProgress?: boolean;
} | {
  type: "tool_execution_update";
  toolCallId: string;
  toolName: string;
  args: unknown;
  partialResult: unknown;
  hideFromChannelProgress?: boolean;
} | {
  type: "tool_execution_end";
  toolCallId: string;
  toolName: string;
  result: unknown;
  isError: boolean;
  /** False when resolution, preparation, validation, policy, or queued steering prevented execution. */
  executionStarted?: boolean;
  /** Typed pre-execution failure provenance for safe downstream diagnostics. */
  errorKind?: "argument-validation";
  hideFromChannelProgress?: boolean;
};
//#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";
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;
});
//#endregion
//#region src/auto-reply/commands-args.types.d.ts
/** Primitive values accepted by parsed auto-reply command args. */
type CommandArgValue = string | number | boolean | bigint;
/** Named parsed auto-reply command values. */
type CommandArgValues = Record<string, CommandArgValue>;
/** Parsed command argument bundle with raw source and structured values. */
type CommandArgs = {
  raw?: string;
  values?: CommandArgValues;
};
//#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/auto-reply/reply/history.types.d.ts
/** Normalized history message used when building reply context. */
type HistoryEntry = {
  sender: string;
  body: string;
  timestamp?: number;
  messageId?: string;
  media?: HistoryMediaEntry[];
};
/** Media metadata attached to a normalized history message. */
type HistoryMediaEntry = Pick<MediaFact, "contentType" | "durationMs" | "height" | "kind" | "messageId" | "path" | "url" | "width">;
//#endregion
//#region packages/normalization-core/src/string-coerce.d.ts
type FastMode = boolean | "auto";
//#endregion
//#region packages/normalization-core/src/agent-run-terminal-outcome.d.ts
declare const AGENT_RUN_TIMEOUT_PHASES: readonly ["queue", "preflight", "provider", "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
/** Normalized terminal outcome for an agent run. */
type AgentRunTerminalOutcome = 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;
};
//#endregion
//#region src/channels/progress-draft-diffstat.d.ts
type ChannelProgressDraftDiffStat = Readonly<{
  files: number;
  added: number;
  removed: number;
}>;
//#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;
  /** Progress event family that produced this line. */
  kind: "tool" | "item" | "plan" | "approval" | "command-output" | "patch";
  /** Rendered line text before final draft truncation/prefix formatting. */
  text: string;
  /** Human-readable label for UI renderers. */
  label: string;
  /** Optional leading icon for rich or plain progress renderers. */
  icon?: string;
  /** Compact detail text separated from label/icon. */
  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;
};
//#endregion
//#region src/channels/streaming.d.ts
type AgentPlanStepStatus = "pending" | "in_progress" | "completed";
type AgentPlanStep = {
  step: string;
  status: AgentPlanStepStatus;
};
//#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/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">;
//#endregion
//#region packages/gateway-protocol/src/schema/approvals.d.ts
/** Reviewer decisions accepted by the unified approval resolver. */
declare const ApprovalDecisionSchema: Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">, Type$1.TLiteral<"deny">]>;
/** Closed reason recorded for a terminal approval transition. */
declare const ApprovalTerminalReasonSchema: Type$1.TUnion<[Type$1.TLiteral<"user">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"malformed-verdict">, Type$1.TLiteral<"no-route">, Type$1.TLiteral<"run-aborted">, Type$1.TLiteral<"gateway-restart">, Type$1.TLiteral<"storage-corrupt">]>;
/**
 * Owner-declared blast-radius facts for a pending approval. Variants are
 * named schemas so native protocol generators emit the discriminated union.
 */
declare const ApprovalScopeSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"message-send">;
  target: Type$1.TString;
  recipientCount: Type$1.TInteger;
  recipients: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  audience: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"internal">, Type$1.TLiteral<"external">]>>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"payment">;
  amount: Type$1.TString;
  currency: Type$1.TString;
  target: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"external-post">;
  target: Type$1.TString;
  visibility: Type$1.TUnion<[Type$1.TLiteral<"public">, Type$1.TLiteral<"restricted">]>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"standing-grant">;
  automation: Type$1.TString;
  command: Type$1.TString;
  expiresInDays: Type$1.TOptional<Type$1.TInteger>;
}>]>;
/** Reviewer-safe presentation discriminated by the approval owner. */
declare const ApprovalPresentationSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"exec">;
  commandText: Type$1.TString;
  commandPreview: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  warningText: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  host: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  nodeId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    kind: Type$1.TLiteral<"message-send">;
    target: Type$1.TString;
    recipientCount: Type$1.TInteger;
    recipients: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    audience: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"internal">, Type$1.TLiteral<"external">]>>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"payment">;
    amount: Type$1.TString;
    currency: Type$1.TString;
    target: Type$1.TString;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"external-post">;
    target: Type$1.TString;
    visibility: Type$1.TUnion<[Type$1.TLiteral<"public">, Type$1.TLiteral<"restricted">]>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"standing-grant">;
    automation: Type$1.TString;
    command: Type$1.TString;
    expiresInDays: Type$1.TOptional<Type$1.TInteger>;
  }>]>>;
  allowedDecisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">, Type$1.TLiteral<"deny">]>>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"plugin">;
  title: Type$1.TString;
  description: Type$1.TString;
  detail: Type$1.TOptional<Type$1.TString>;
  severity: Type$1.TUnion<[Type$1.TLiteral<"info">, Type$1.TLiteral<"warning">, Type$1.TLiteral<"critical">]>;
  pluginId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  toolName: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    kind: Type$1.TLiteral<"message-send">;
    target: Type$1.TString;
    recipientCount: Type$1.TInteger;
    recipients: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    audience: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"internal">, Type$1.TLiteral<"external">]>>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"payment">;
    amount: Type$1.TString;
    currency: Type$1.TString;
    target: Type$1.TString;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"external-post">;
    target: Type$1.TString;
    visibility: Type$1.TUnion<[Type$1.TLiteral<"public">, Type$1.TLiteral<"restricted">]>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"standing-grant">;
    automation: Type$1.TString;
    command: Type$1.TString;
    expiresInDays: Type$1.TOptional<Type$1.TInteger>;
  }>]>>;
  allowedDecisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">, Type$1.TLiteral<"deny">]>>;
  externalResolution: Type$1.TOptional<Type$1.TObject<{
    label: Type$1.TString;
    decisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">]>>;
  }>>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"system-agent">;
  title: Type$1.TString;
  description: Type$1.TString;
  proposalHash: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  allowedDecisions: Type$1.TTuple<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"deny">]>;
}>]>;
/** Authoritative pending approval set returned when a session stream subscribes. */
declare const SessionApprovalReplaySchema: Type$1.TObject<{
  sessionKey: Type$1.TString;
  updatedAtMs: Type$1.TInteger;
  approvals: Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    urlPath: Type$1.TString;
    createdAtMs: Type$1.TInteger;
    expiresAtMs: Type$1.TInteger;
    presentation: Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"exec">;
      commandText: Type$1.TString;
      commandPreview: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      warningText: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      host: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      nodeId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        kind: Type$1.TLiteral<"message-send">;
        target: Type$1.TString;
        recipientCount: Type$1.TInteger;
        recipients: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
        audience: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"internal">, Type$1.TLiteral<"external">]>>;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"payment">;
        amount: Type$1.TString;
        currency: Type$1.TString;
        target: Type$1.TString;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"external-post">;
        target: Type$1.TString;
        visibility: Type$1.TUnion<[Type$1.TLiteral<"public">, Type$1.TLiteral<"restricted">]>;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"standing-grant">;
        automation: Type$1.TString;
        command: Type$1.TString;
        expiresInDays: Type$1.TOptional<Type$1.TInteger>;
      }>]>>;
      allowedDecisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">, Type$1.TLiteral<"deny">]>>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"plugin">;
      title: Type$1.TString;
      description: Type$1.TString;
      detail: Type$1.TOptional<Type$1.TString>;
      severity: Type$1.TUnion<[Type$1.TLiteral<"info">, Type$1.TLiteral<"warning">, Type$1.TLiteral<"critical">]>;
      pluginId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      toolName: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        kind: Type$1.TLiteral<"message-send">;
        target: Type$1.TString;
        recipientCount: Type$1.TInteger;
        recipients: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
        audience: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"internal">, Type$1.TLiteral<"external">]>>;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"payment">;
        amount: Type$1.TString;
        currency: Type$1.TString;
        target: Type$1.TString;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"external-post">;
        target: Type$1.TString;
        visibility: Type$1.TUnion<[Type$1.TLiteral<"public">, Type$1.TLiteral<"restricted">]>;
      }>, Type$1.TObject<{
        kind: Type$1.TLiteral<"standing-grant">;
        automation: Type$1.TString;
        command: Type$1.TString;
        expiresInDays: Type$1.TOptional<Type$1.TInteger>;
      }>]>>;
      allowedDecisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">, Type$1.TLiteral<"deny">]>>;
      externalResolution: Type$1.TOptional<Type$1.TObject<{
        label: Type$1.TString;
        decisions: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"allow-always">]>>;
      }>>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"system-agent">;
      title: Type$1.TString;
      description: Type$1.TString;
      proposalHash: Type$1.TString;
      agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      allowedDecisions: Type$1.TTuple<[Type$1.TLiteral<"allow-once">, Type$1.TLiteral<"deny">]>;
    }>]>;
    status: Type$1.TLiteral<"pending">;
    /** Canonical raising session when projected into a session-scoped reviewer surface. */
    sourceSessionKey: Type$1.TOptional<Type$1.TString>;
  }>>;
  truncated: Type$1.TBoolean;
}>;
type ApprovalDecision = Static<typeof ApprovalDecisionSchema>;
type ApprovalTerminalReason = Static<typeof ApprovalTerminalReasonSchema>;
type ApprovalScope$1 = Static<typeof ApprovalScopeSchema>;
type ApprovalPresentation = Static<typeof ApprovalPresentationSchema>;
type SessionApprovalReplay = Static<typeof SessionApprovalReplaySchema>;
//#endregion
//#region src/infra/command-analysis/explain.d.ts
/** Compact command explanation summary shown in approval UI. */
type CommandExplanationSummary = {
  commandCount: number;
  nestedCommandCount: number;
  riskKinds: string[];
  warningLines: string[];
};
//#endregion
//#region src/infra/exec-approval-policy-snapshot.d.ts
type ExecApprovalPolicyRule = {
  pattern: string;
  argPattern?: string;
  source?: "allow-always";
};
type ExecApprovalPolicySnapshot = {
  security: "deny" | "allowlist" | "full";
  ask: "off" | "on-miss" | "always";
  askFallback: "deny" | "allowlist" | "full";
  autoAllowSkills: boolean;
  allowlistRules: readonly ExecApprovalPolicyRule[];
};
//#endregion
//#region src/infra/exec-approvals-core.d.ts
type ExecHost = "sandbox" | "gateway" | "node";
type ExecTarget = "auto" | ExecHost;
type ExecSecurity = "deny" | "allowlist" | "full";
type ExecAsk = "off" | "on-miss" | "always";
type ExecMode = "deny" | "allowlist" | "ask" | "auto" | "full";
type ExecApprovalDecision = "allow-once" | "allow-always" | "deny";
type ExecApprovalUnavailableDecision = "allow-always";
type SystemRunApprovalBinding = {
  argv: string[];
  cwd: string | null;
  agentId: string | null;
  sessionKey: string | null;
  envHash: string | null;
};
type SystemRunApprovalFileOperand = {
  argvIndex: number;
  path: string;
  sha256: string;
};
type SystemRunApprovalPlan = {
  argv: string[];
  cwd: string | null;
  commandText: string;
  commandPreview?: string | null;
  agentId: string | null;
  sessionKey: string | null;
  policySnapshot?: ExecApprovalPolicySnapshot;
  mutableFileOperand?: SystemRunApprovalFileOperand | null;
};
type ExecApprovalCommandSpan = {
  startIndex: number;
  endIndex: number;
};
/** Cron job identity recorded at approval creation for a cron isolated run. */
type ExecApprovalCronExecutionSource = {
  jobId: string;
  jobConfigRevision: string;
};
type ExecApprovalRequestPayload = {
  command: string;
  commandPreview?: string | null;
  commandArgv?: string[];
  envKeys?: string[];
  systemRunBinding?: SystemRunApprovalBinding | null;
  systemRunPlan?: SystemRunApprovalPlan | null;
  cwd?: string | null;
  nodeId?: string | null;
  host?: string | null;
  security?: string | null;
  ask?: string | null;
  warningText?: string | null;
  /** Owner-declared blast-radius facts; display-only, never authorization. */
  scope?: ApprovalScope$1 | null;
  commandAnalysis?: CommandExplanationSummary | null;
  commandSpans?: ExecApprovalCommandSpan[];
  unavailableDecisions?: readonly ExecApprovalUnavailableDecision[];
  allowedDecisions?: readonly ExecApprovalDecision[];
  agentId?: string | null;
  resolvedPath?: string | null;
  sessionKey?: string | null;
  sessionId?: string | null;
  runId?: string | null;
  toolCallId?: string | null;
  turnSourceChannel?: string | null;
  turnSourceTo?: string | null;
  turnSourceAccountId?: string | null;
  turnSourceThreadId?: string | number | null;
  /** Gateway-recorded cron source; never taken from client request params. */
  cronExecutionSource?: ExecApprovalCronExecutionSource | null;
  /** Exact operation binding prepared at creation for standing-grant minting. */
  cronOperationBinding?: string | null;
};
type ExecApprovalRequest = {
  /** Descriptive wire metadata; readers derive it from the payload when absent. */
  approvalKind?: "exec";
  id: string;
  request: ExecApprovalRequestPayload;
  createdAtMs: number;
  expiresAtMs: number;
};
type ExecApprovalResolved = {
  id: string;
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
  ts: number;
  request?: ExecApprovalRequest["request"];
};
//#endregion
//#region src/infra/approval-scope.d.ts
type ApprovalScope = Static<typeof ApprovalScopeSchema>;
//#endregion
//#region src/infra/plugin-approvals.d.ts
type PluginApprovalActionView = {
  kind?: "command" | "decision";
  label: string;
  command: string;
  decision?: ExecApprovalDecision;
  style?: "primary" | "secondary" | "success" | "danger";
};
/** Gateway-minted placement identity; plugin and RPC callers never supply this authority. */
type PluginApprovalPlacementGrantBinding = {
  pluginId: string;
  command: string;
  approvalScope: string;
  agentId: string;
  sessionKey: string;
  sessionId: string;
  nodeId: string;
  pairingGeneration: string;
  environmentId: string;
  ownerEpoch: number;
  placementGeneration: number;
  cwd: string;
};
type PluginApprovalRequestPayload = {
  pluginId?: string | null;
  title: string;
  description: string;
  detail?: string | null;
  severity?: "info" | "warning" | "critical" | null;
  /** Owner-declared blast-radius facts; display-only, never authorization. */
  scope?: ApprovalScope | null;
  toolName?: string | null;
  toolCallId?: string | null;
  /** Trusted harness-selected policy subject; distinct from display-only toolName. */
  policySubject?: {
    pluginKey: string;
    tool?: string;
  };
  /** Exact MCP persistence intent; the host separately binds live tool-call proof. */
  mcpTool?: {
    server: string;
    tool: string;
  };
  allowedDecisions?: readonly ExecApprovalDecision[] | null;
  /** Trusted in-process metadata; public Gateway callers cannot submit this field. */
  externalResolution?: {
    label: string;
    decisions?: readonly ("allow-once" | "allow-always")[];
  } | null;
  actions?: readonly PluginApprovalActionView[] | null;
  agentId?: string | null;
  sessionKey?: string | null;
  /** Host-derived source run; never accepted from plugin approval RPC params. */
  runId?: string | null;
  /** Host-derived grant binding; never accepted from plugin approval RPC params. */
  placementGrant?: PluginApprovalPlacementGrantBinding | null;
  turnSourceChannel?: string | null;
  turnSourceTo?: string | null;
  turnSourceAccountId?: string | null;
  turnSourceThreadId?: string | number | null;
};
/** Timed plugin approval request persisted while awaiting a decision. */
type PluginApprovalRequest$1 = {
  /** Descriptive wire metadata; readers derive it from the payload when absent. */
  approvalKind?: "plugin";
  id: string;
  request: PluginApprovalRequestPayload;
  createdAtMs: number;
  expiresAtMs: number;
};
type PluginApprovalResolved = {
  id: string;
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
  ts: number;
  request?: PluginApprovalRequestPayload;
};
//#endregion
//#region src/infra/system-agent-approvals.d.ts
type SystemAgentApprovalRequestPayload = {
  title: string;
  description: string;
  command: string;
  proposalHash: string;
  allowedDecisions: readonly ExecApprovalDecision[];
  agentId?: string | null;
  sessionKey?: string | null;
  sessionId: string;
  runId?: string | null;
  turnSourceChannel?: string | null;
  turnSourceTo?: string | null;
  turnSourceAccountId?: string | null;
  turnSourceThreadId?: string | number | null;
};
type SystemAgentApprovalRequest = {
  approvalKind?: "system-agent";
  id: string;
  request: SystemAgentApprovalRequestPayload;
  createdAtMs: number;
  expiresAtMs: number;
};
type SystemAgentApprovalApplicationStatus = "applied" | "not-applied";
type SystemAgentApprovalResolved = {
  id: string;
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
  ts: number;
  request?: SystemAgentApprovalRequestPayload;
  applicationStatus?: SystemAgentApprovalApplicationStatus;
  terminalStatus?: "expired" | "cancelled";
};
//#endregion
//#region src/infra/approval-types.d.ts
type ChannelApprovalKind = "exec" | "plugin" | "system-agent";
/** Backward-compatible request shape accepted from Gateway events and replay. */
type ApprovalRequestInput = ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
type ApprovalResolved = ExecApprovalResolved | PluginApprovalResolved | SystemAgentApprovalResolved;
//#endregion
//#region src/interactive/payload.d.ts
type InteractiveButtonStyle = "primary" | "secondary" | "success" | "danger";
/** Visual tone for a portable message presentation. */
type MessagePresentationTone = "info" | "success" | "warning" | "danger" | "neutral";
type QuestionPresentationAction = {
  /** Resolve one declared choice. */
  type: "question";
  questionId: string;
  optionValue: string;
} | {
  /** Switch this question to its free-text answer path. */
  type: "question";
  questionId: string;
  intent: "custom-input";
};
/** Core-owned model-picker action; channels serialize it only inside private envelopes. */
type ModelPickerAction = ({
  intent: "show-providers";
  cursor?: string;
} | {
  intent: "show-models";
  providerToken: string;
  cursor?: string;
} | {
  intent: "show-recents";
  cursor?: string;
} | {
  intent: "choose-model";
  providerToken: string;
  modelToken: string;
} | {
  intent: "choose-runtime";
  providerToken: string;
  modelToken: string;
  runtimeToken: string;
} | {
  intent: "reset";
} | {
  intent: "cancel";
}) & {
  type: "model-picker";
  version: 1;
  snapshotToken: string;
  /** Legacy command/callback payload fields are deliberately unavailable on picker actions. */
  readonly command?: never;
  readonly value?: never;
};
/** Portable typed action behind a button or select option. */
type MessagePresentationAction = {
  /** Run a core/plugin slash command through the target channel's native command path. */
  type: "command";
  command: string;
} | {
  /** Opaque callback value interpreted by the target channel/plugin. */
  type: "callback";
  value: string;
} | ModelPickerAction | {
  /** Resolve one durable operator approval without exposing transport callback data. */
  type: "approval";
  approvalId: string;
  approvalKind: ChannelApprovalKind;
  decision: "allow-once" | "allow-always" | "deny";
} | QuestionPresentationAction | {
  /** Open a normal external link. */
  type: "url";
  url: string;
} | {
  /** Launch a channel-native web app. */
  type: "web-app";
  /** External web app URL for channels that launch web apps by URL. */
  url: string;
  /** OpenClaw hosted-widget ID whose launch mechanics are owned by the channel. */
  widgetId?: string;
} | {
  /** Launch a channel-native web app. */
  type: "web-app";
  /** External web app URL for channels that launch web apps by URL. */
  url?: string;
  /** OpenClaw hosted-widget ID whose launch mechanics are owned by the channel. */
  widgetId: string;
};
/** Portable action control rendered as a button or link by channel adapters. */
type MessagePresentationButton = {
  /** User-visible button label. */
  label: string;
  /** Typed action sent when the button is pressed. */
  action?: MessagePresentationAction;
  /**
   * Legacy opaque callback value sent when the button is pressed.
   * Prefer action for new presentation controls.
   * @deprecated Use action.
   */
  value?: string;
  /** @deprecated Use an action with type "url". */
  url?: string;
  /** @deprecated Use an action with type "web-app". */
  webApp?: {
    url: string;
  };
  /**
   * @deprecated Use an action with type "web-app". Accepted for legacy JSON payloads only.
   */
  web_app?: {
    url: string;
  };
  /** Higher-priority buttons are kept first when channel limits require truncation. */
  priority?: number;
  /** Disable the button when the target channel supports disabled controls. */
  disabled?: boolean;
  /** Keep this action available after a successful interaction when the target channel supports it. */
  reusable?: boolean;
  /** Optional visual style hint; unsupported channels ignore or normalize it. */
  style?: InteractiveButtonStyle;
};
/** Portable select/menu option. */
type MessagePresentationOption = {
  /** User-visible option label. */
  label: string;
  /** Typed action sent when the option is selected. */
  action?: Extract<MessagePresentationAction, {
    type: "command" | "callback" | "model-picker";
  }>;
  /** @deprecated Use action. */
  value?: string;
};
type LegacyInteractiveReplyOption = MessagePresentationOption;
type LegacyInteractiveReplyTextBlock = {
  type: "text";
  text: string;
};
type LegacyInteractiveReplySelectBlock = {
  type: "select";
  placeholder?: string;
  options: LegacyInteractiveReplyOption[];
};
type LegacyInteractiveReplyBlock = LegacyInteractiveReplyTextBlock | MessagePresentationButtonsBlock | LegacyInteractiveReplySelectBlock;
type LegacyInteractiveReply = {
  blocks: LegacyInteractiveReplyBlock[];
};
/** @deprecated Use MessagePresentation. */
type InteractiveReply = LegacyInteractiveReply;
type MessagePresentationTextBlock = {
  type: "text";
  /** Primary markdown-ish text rendered in the message body. */
  text: string;
};
type MessagePresentationContextBlock = {
  type: "context";
  /** Lower-emphasis contextual text, or normal text on channels without context support. */
  text: string;
};
type MessagePresentationDividerBlock = {
  type: "divider";
};
type MessagePresentationButtonsBlock = {
  type: "buttons";
  /** Button row candidates; core may split or truncate them for channel limits. */
  buttons: MessagePresentationButton[];
};
type MessagePresentationSelectBlock = {
  type: "select";
  /** Optional prompt shown above or inside the select control. */
  placeholder?: string;
  /** Menu options; core may truncate them for channel limits. */
  options: MessagePresentationOption[];
};
type MessagePresentationChartSegment = {
  /** Category label shown in the chart legend. */
  label: string;
  /** Positive segment magnitude. */
  value: number;
};
type MessagePresentationChartSeries = {
  /** Unique series name shown in the chart legend. */
  name: string;
  /** One finite value for each chart category, in category order. */
  values: number[];
};
type MessagePresentationChartBlock = {
  type: "chart";
  chartType: "pie";
  /** Short chart heading. */
  title: string;
  segments: MessagePresentationChartSegment[];
} | {
  type: "chart";
  chartType: "bar" | "area" | "line";
  /** Short chart heading. */
  title: string;
  /** Ordered categories shared by every series. */
  categories: string[];
  series: MessagePresentationChartSeries[];
  xLabel?: string;
  yLabel?: string;
};
/** Scalar cell value supported by portable table presentations. */
type MessagePresentationTableCell = string | number;
/** Portable table rendered natively where supported and linearly elsewhere. */
type MessagePresentationTableBlock = {
  type: "table";
  /** Short table heading used by native renderers and fallback text. */
  caption: string;
  /** Unique ordered column labels shared by every row. */
  headers: string[];
  /** Rows whose width exactly matches the header count. */
  rows: MessagePresentationTableCell[][];
  /** Optional column whose cells should be rendered as row headers. */
  rowHeaderColumnIndex?: number;
};
type MessagePresentationBlock = MessagePresentationTextBlock | MessagePresentationContextBlock | MessagePresentationDividerBlock | MessagePresentationButtonsBlock | MessagePresentationSelectBlock | MessagePresentationChartBlock | MessagePresentationTableBlock;
type MessagePresentation = {
  /** Optional short heading rendered before blocks when the channel supports it. */
  title?: string;
  /** Optional severity/status tone for renderers that support toned presentations. */
  tone?: MessagePresentationTone;
  /** Ordered portable blocks rendered or downgraded by the target channel adapter. */
  blocks: MessagePresentationBlock[];
};
type ReplyPayloadDeliveryPin = {
  enabled: boolean;
  notify?: boolean;
  required?: boolean;
};
type ReplyPayloadDelivery = {
  pin?: boolean | ReplyPayloadDeliveryPin;
};
//#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 = {
  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;
  };
  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 = {
  text: string;
  trimmedText: string;
  /** Normalized non-empty media URLs. */
  mediaUrls: string[];
  mediaCount: number;
  hasText: boolean;
  hasMedia: boolean;
  hasContent: boolean;
};
/** Prepared payload entry that keeps source indexing plus reusable projections. */
type OutboundPayloadPlan = {
  sourceIndex: number;
  payload: ReplyPayload;
  parts: SendableOutboundReplyParts;
  hasPresentation: boolean;
  hasInteractive: boolean;
  hasChannelData: boolean;
};
//#endregion
//#region packages/gateway-protocol/src/schema/session-placement.d.ts
declare const SessionPlacementDiskSpaceSchema: Type$1.TObject<{
  status: Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"warning">, Type$1.TLiteral<"critical">]>;
  availableBytes: Type$1.TInteger;
  totalBytes: Type$1.TInteger;
  observedAtMs: Type$1.TInteger;
}>;
declare const SessionPlacementWorkerRuntimeInstallSchema: Type$1.TObject<{
  phase: Type$1.TUnion<[Type$1.TLiteral<"transferring">, Type$1.TLiteral<"installing">]>;
  transferredBytes: Type$1.TInteger;
  totalBytes: Type$1.TInteger;
  startedAtMs: Type$1.TInteger;
  updatedAtMs: Type$1.TInteger;
}>;
declare const SessionPlacementRunnerSchema: Type$1.TObject<{
  kind: Type$1.TLiteral<"device">;
  status: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"offline">]>;
  deviceId: Type$1.TOptional<Type$1.TString>;
}>;
declare const SessionPlacementMachineSchema: Type$1.TObject<{
  class: Type$1.TOptional<Type$1.TString>;
  os: Type$1.TOptional<Type$1.TString>;
  osLabel: Type$1.TOptional<Type$1.TString>;
  cpu: Type$1.TOptional<Type$1.TInteger>;
  memoryGb: Type$1.TOptional<Type$1.TInteger>;
}>;
/** Stops a worker or explicitly recovers one failed placement onto the Gateway. */
declare const SessionsReclaimParamsSchema: Type$1.TObject<{
  key: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  recoverToGateway: Type$1.TOptional<Type$1.TObject<{
    expectedGeneration: Type$1.TInteger;
  }>>;
}>;
/** Closed destination union for session placement moves. */
declare const SessionMoveTargetSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"gateway">;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"profile">;
  profileId: Type$1.TString;
  machineClass: Type$1.TOptional<Type$1.TString>;
  os: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"device">;
  deviceId: Type$1.TString;
}>]>;
type SessionPlacementDiskSpace = Static<typeof SessionPlacementDiskSpaceSchema>;
type SessionPlacementWorkerRuntimeInstall = Static<typeof SessionPlacementWorkerRuntimeInstallSchema>;
type SessionPlacementRunner = Static<typeof SessionPlacementRunnerSchema>;
type SessionPlacementMachine = Static<typeof SessionPlacementMachineSchema>;
type SessionsReclaimParams = Static<typeof SessionsReclaimParamsSchema>;
type SessionMoveTarget = Static<typeof SessionMoveTargetSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/frames.d.ts
/** Initial client hello/connect payload sent before the gateway accepts frames. */
declare const ConnectParamsSchema: Type$1.TObject<{
  minProtocol: Type$1.TInteger;
  maxProtocol: Type$1.TInteger;
  client: Type$1.TObject<{
    id: Type$1.TEnum<["openclaw-android", "openclaw-browser-copilot", "cli", "openclaw-control-ui", "fingerprint", "gateway-client", "openclaw-ios", "openclaw-linux", "openclaw-macos", "node-host", "openclaw-probe", "test", "openclaw-tui", "openclaw-watchos", "webchat", "webchat-ui", "openclaw-worker"]>;
    displayName: Type$1.TOptional<Type$1.TString>;
    version: Type$1.TString;
    buildId: Type$1.TOptional<Type$1.TString>;
    platform: Type$1.TString;
    deviceFamily: Type$1.TOptional<Type$1.TString>;
    modelIdentifier: Type$1.TOptional<Type$1.TString>;
    /** Self-reported IANA zone. Bounded because the longest real name is well under this cap. */
    timeZone: Type$1.TOptional<Type$1.TString>;
    mode: Type$1.TEnum<["backend", "cli", "node", "probe", "test", "ui", "webchat", "worker"]>;
    instanceId: Type$1.TOptional<Type$1.TString>;
  }>;
  caps: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  commands: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  /** Additive Computer Use declaration; the owning core contract validates its bounded shape. */
  computerUse: Type$1.TOptional<Type$1.TUnknown>;
  /** @deprecated Accepted for the shipped v1 node-host envelope; current hosts use runner inventory. */
  workerRuns: Type$1.TOptional<Type$1.TObject<{
    bundleHash: Type$1.TString;
    openclawVersion: Type$1.TString;
    protocolFeatures: Type$1.TArray<Type$1.TString>;
    bundlePrewarm: Type$1.TOptional<Type$1.TInteger>;
  }>>;
  permissions: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TBoolean>>;
  pathEnv: Type$1.TOptional<Type$1.TString>;
  role: Type$1.TOptional<Type$1.TString>;
  scopes: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  /** Initial catalog read scope; method authorization still owns access. */
  modelCatalog: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TString>;
    sessionKey: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TString>;
    shortId: Type$1.TString;
    slugHint: Type$1.TOptional<Type$1.TString>;
  }>]>>;
  device: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    publicKey: Type$1.TString;
    signature: Type$1.TString;
    signedAt: Type$1.TInteger;
    nonce: Type$1.TString;
  }>>;
  auth: Type$1.TOptional<Type$1.TObject<{
    token: Type$1.TOptional<Type$1.TString>;
    bootstrapToken: Type$1.TOptional<Type$1.TString>;
    deviceToken: Type$1.TOptional<Type$1.TString>;
    password: Type$1.TOptional<Type$1.TString>;
    approvalRuntimeToken: Type$1.TOptional<Type$1.TString>;
    agentRuntimeIdentityToken: Type$1.TOptional<Type$1.TString>;
  }>>;
  locale: Type$1.TOptional<Type$1.TString>;
  userAgent: Type$1.TOptional<Type$1.TString>;
}>;
/** Standard structured error shape used in response frames and connect failures. */
declare const ErrorShapeSchema: Type$1.TObject<{
  code: Type$1.TString;
  message: Type$1.TString;
  details: Type$1.TOptional<Type$1.TUnknown>;
  retryable: Type$1.TOptional<Type$1.TBoolean>;
  retryAfterMs: Type$1.TOptional<Type$1.TInteger>;
}>;
/** Client request frame envelope; `method` selects the payload validator. */
declare const RequestFrameSchema: Type$1.TObject<{
  type: Type$1.TLiteral<"req">;
  id: Type$1.TString;
  method: Type$1.TString;
  params: Type$1.TOptional<Type$1.TUnknown>;
  traceparent: Type$1.TOptional<Type$1.TString>;
  expectedProfileId: Type$1.TOptional<Type$1.TString>;
}>;
type ConnectParams = Static<typeof ConnectParamsSchema>;
type ErrorShape = Static<typeof ErrorShapeSchema>;
type RequestFrame = Static<typeof RequestFrameSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/session-github-publication.d.ts
declare const GitHubPublicationPublisherSchema: Type$1.TObject<{
  accountId: Type$1.TInteger;
  login: Type$1.TString;
  source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
}>;
declare const SessionGitHubPublishParamsSchema: Type$1.TObject<{
  sessionKey: Type$1.TOptional<Type$1.TString>;
  agentId: Type$1.TOptional<Type$1.TString>;
  idempotencyKey: Type$1.TString;
  title: Type$1.TOptional<Type$1.TString>;
  body: Type$1.TOptional<Type$1.TString>;
  selection: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    source: Type$1.TLiteral<"shared">;
    expected: Type$1.TOptional<Type$1.TObject<{
      accountId: Type$1.TInteger;
      login: Type$1.TString;
      source: Type$1.TUnion<[Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
    }>>;
  }>, Type$1.TObject<{
    source: Type$1.TLiteral<"personal">;
    generation: Type$1.TString;
    account: Type$1.TObject<{
      accountId: Type$1.TInteger;
      login: Type$1.TString;
    }>;
  }>]>>;
}>;
declare const SessionGitHubPublicationResultSchema: Type$1.TUnion<[Type$1.TObject<{
  requestId: Type$1.TString;
  publisher: Type$1.TOptional<Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
  }>>;
  effect: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"push">, Type$1.TLiteral<"pull_request">]>;
    status: Type$1.TUnion<[Type$1.TLiteral<"dispatched">, Type$1.TLiteral<"observed">]>;
    headCommit: Type$1.TOptional<Type$1.TString>;
    url: Type$1.TOptional<Type$1.TString>;
  }>>;
  status: Type$1.TLiteral<"requested">;
  message: Type$1.TString;
}>, Type$1.TObject<{
  requestId: Type$1.TString;
  publisher: Type$1.TOptional<Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
  }>>;
  effect: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"push">, Type$1.TLiteral<"pull_request">]>;
    status: Type$1.TUnion<[Type$1.TLiteral<"dispatched">, Type$1.TLiteral<"observed">]>;
    headCommit: Type$1.TOptional<Type$1.TString>;
    url: Type$1.TOptional<Type$1.TString>;
  }>>;
  status: Type$1.TLiteral<"publishing">;
  message: Type$1.TString;
}>, Type$1.TObject<{
  requestId: Type$1.TString;
  publisher: Type$1.TOptional<Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
  }>>;
  effect: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"push">, Type$1.TLiteral<"pull_request">]>;
    status: Type$1.TUnion<[Type$1.TLiteral<"dispatched">, Type$1.TLiteral<"observed">]>;
    headCommit: Type$1.TOptional<Type$1.TString>;
    url: Type$1.TOptional<Type$1.TString>;
  }>>;
  status: Type$1.TLiteral<"published">;
  url: Type$1.TString;
  repository: Type$1.TString;
  branch: Type$1.TString;
  headCommit: Type$1.TString;
}>, Type$1.TObject<{
  requestId: Type$1.TString;
  publisher: Type$1.TOptional<Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
  }>>;
  effect: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"push">, Type$1.TLiteral<"pull_request">]>;
    status: Type$1.TUnion<[Type$1.TLiteral<"dispatched">, Type$1.TLiteral<"observed">]>;
    headCommit: Type$1.TOptional<Type$1.TString>;
    url: Type$1.TOptional<Type$1.TString>;
  }>>;
  status: Type$1.TLiteral<"failed">;
  code: Type$1.TUnion<[Type$1.TLiteral<"identity_changed">, Type$1.TLiteral<"identity_unavailable">, Type$1.TLiteral<"session_changed">, Type$1.TLiteral<"workspace_changed">, Type$1.TLiteral<"not_git">, Type$1.TLiteral<"not_github">, Type$1.TLiteral<"no_changes">, Type$1.TLiteral<"push_rejected">, Type$1.TLiteral<"github_rejected">, Type$1.TLiteral<"unavailable">]>;
  message: Type$1.TString;
  nextAction: Type$1.TString;
}>, Type$1.TObject<{
  requestId: Type$1.TString;
  publisher: Type$1.TOptional<Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
    source: Type$1.TUnion<[Type$1.TLiteral<"personal">, Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
  }>>;
  effect: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TUnion<[Type$1.TLiteral<"push">, Type$1.TLiteral<"pull_request">]>;
    status: Type$1.TUnion<[Type$1.TLiteral<"dispatched">, Type$1.TLiteral<"observed">]>;
    headCommit: Type$1.TOptional<Type$1.TString>;
    url: Type$1.TOptional<Type$1.TString>;
  }>>;
  status: Type$1.TLiteral<"needs_confirmation">;
  message: Type$1.TString;
}>]>;
type GitHubPublicationPublisher = Static<typeof GitHubPublicationPublisherSchema>;
type SessionGitHubPublishParams = Static<typeof SessionGitHubPublishParamsSchema>;
type SessionGitHubPublicationResult = Static<typeof SessionGitHubPublicationResultSchema>;
//#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/schema/model-catalog.d.ts
declare const ModelChoiceSchema: Type$1.TObject<{
  available: Type$1.TOptional<Type$1.TBoolean>;
  /** Scoped manual-choice permission; separate from runtime readiness and automatic selection. */
  manualSelectionAllowed: Type$1.TOptional<Type$1.TBoolean>;
  unavailableReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"missing-auth">, Type$1.TLiteral<"auth-failed">, Type$1.TLiteral<"cooldown">]>>;
  /** Earliest known retry time in epoch milliseconds, only for unavailable models. */
  unavailableUntil: Type$1.TOptional<Type$1.TInteger>;
  contextWindow: Type$1.TOptional<Type$1.TInteger>;
  contextTokens: Type$1.TOptional<Type$1.TInteger>;
  local: Type$1.TOptional<Type$1.TBoolean>;
  contextWindows: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    label: Type$1.TString;
    contextWindow: Type$1.TInteger;
  }>>>;
  contextWindowDefault: Type$1.TOptional<Type$1.TString>;
  reasoning: Type$1.TOptional<Type$1.TBoolean>;
  thinkingLevels: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    label: Type$1.TString;
  }>>>;
  thinkingDefault: Type$1.TOptional<Type$1.TString>;
  effectiveFastMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TLiteral<"auto">]>>;
  /** Local selected-request applicability, not preference or upstream fulfillment. */
  supportsFastMode: Type$1.TOptional<Type$1.TBoolean>;
  supportsTools: Type$1.TOptional<Type$1.TBoolean>;
  input: Type$1.TOptional<Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"text">, Type$1.TLiteral<"image">, Type$1.TLiteral<"audio">, Type$1.TLiteral<"video">, Type$1.TLiteral<"document">]>>>;
  id: Type$1.TString;
  name: Type$1.TString;
  provider: Type$1.TString;
  alias: Type$1.TOptional<Type$1.TString>;
  tags: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  agentRuntime: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    fallback: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"openclaw">, Type$1.TLiteral<"none">]>>;
    cloudPlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
    cloudPlacementExecutionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"worker-turn">, Type$1.TLiteral<"remote-exec">]>>;
    devicePlacement: Type$1.TOptional<Type$1.TObject<{
      requiredNodeCommands: Type$1.TArray<Type$1.TString>;
      consumesWorkerSlot: Type$1.TBoolean;
    }>>;
    devicePlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
    source: Type$1.TUnion<[Type$1.TLiteral<"env">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"defaults">, Type$1.TLiteral<"model">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"implicit">, Type$1.TLiteral<"session">, Type$1.TLiteral<"session-key">]>;
  }>>;
  apiKeySupported: Type$1.TOptional<Type$1.TBoolean>;
  runtimeChoices: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    available: Type$1.TOptional<Type$1.TBoolean>;
    /** Scoped manual-choice permission; separate from runtime readiness and automatic selection. */
    manualSelectionAllowed: Type$1.TOptional<Type$1.TBoolean>;
    /** Earliest known retry time in epoch milliseconds, only for unavailable models. */
    unavailableUntil: Type$1.TOptional<Type$1.TInteger>;
    contextWindow: Type$1.TOptional<Type$1.TInteger>;
    contextTokens: Type$1.TOptional<Type$1.TInteger>;
    local: Type$1.TOptional<Type$1.TBoolean>;
    contextWindows: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      id: Type$1.TString;
      label: Type$1.TString;
      contextWindow: Type$1.TInteger;
    }>>>;
    contextWindowDefault: Type$1.TOptional<Type$1.TString>;
    reasoning: Type$1.TOptional<Type$1.TBoolean>;
    thinkingLevels: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      id: Type$1.TString;
      label: Type$1.TString;
    }>>>;
    thinkingDefault: Type$1.TOptional<Type$1.TString>;
    effectiveFastMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TLiteral<"auto">]>>;
    /** Local selected-request applicability, not preference or upstream fulfillment. */
    supportsFastMode: Type$1.TOptional<Type$1.TBoolean>;
    supportsTools: Type$1.TOptional<Type$1.TBoolean>;
    input: Type$1.TOptional<Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"text">, Type$1.TLiteral<"image">, Type$1.TLiteral<"audio">, Type$1.TLiteral<"video">, Type$1.TLiteral<"document">]>>>;
    agentRuntime: Type$1.TObject<{
      id: Type$1.TString;
      fallback: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"openclaw">, Type$1.TLiteral<"none">]>>;
      cloudPlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
      cloudPlacementExecutionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"worker-turn">, Type$1.TLiteral<"remote-exec">]>>;
      devicePlacement: Type$1.TOptional<Type$1.TObject<{
        requiredNodeCommands: Type$1.TArray<Type$1.TString>;
        consumesWorkerSlot: Type$1.TBoolean;
      }>>;
      devicePlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
      source: Type$1.TUnion<[Type$1.TLiteral<"env">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"defaults">, Type$1.TLiteral<"model">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"implicit">, Type$1.TLiteral<"session">, Type$1.TLiteral<"session-key">]>;
    }>;
    unavailableReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"missing-auth">, Type$1.TLiteral<"auth-failed">, Type$1.TLiteral<"cooldown">]>, Type$1.TLiteral<"unsupported-runtime">]>>;
  }>>>;
}>;
declare const ModelsListResultSchema: Type$1.TObject<{
  models: Type$1.TArray<Type$1.TObject<{
    available: Type$1.TOptional<Type$1.TBoolean>;
    /** Scoped manual-choice permission; separate from runtime readiness and automatic selection. */
    manualSelectionAllowed: Type$1.TOptional<Type$1.TBoolean>;
    unavailableReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"missing-auth">, Type$1.TLiteral<"auth-failed">, Type$1.TLiteral<"cooldown">]>>;
    /** Earliest known retry time in epoch milliseconds, only for unavailable models. */
    unavailableUntil: Type$1.TOptional<Type$1.TInteger>;
    contextWindow: Type$1.TOptional<Type$1.TInteger>;
    contextTokens: Type$1.TOptional<Type$1.TInteger>;
    local: Type$1.TOptional<Type$1.TBoolean>;
    contextWindows: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      id: Type$1.TString;
      label: Type$1.TString;
      contextWindow: Type$1.TInteger;
    }>>>;
    contextWindowDefault: Type$1.TOptional<Type$1.TString>;
    reasoning: Type$1.TOptional<Type$1.TBoolean>;
    thinkingLevels: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      id: Type$1.TString;
      label: Type$1.TString;
    }>>>;
    thinkingDefault: Type$1.TOptional<Type$1.TString>;
    effectiveFastMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TLiteral<"auto">]>>;
    /** Local selected-request applicability, not preference or upstream fulfillment. */
    supportsFastMode: Type$1.TOptional<Type$1.TBoolean>;
    supportsTools: Type$1.TOptional<Type$1.TBoolean>;
    input: Type$1.TOptional<Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"text">, Type$1.TLiteral<"image">, Type$1.TLiteral<"audio">, Type$1.TLiteral<"video">, Type$1.TLiteral<"document">]>>>;
    id: Type$1.TString;
    name: Type$1.TString;
    provider: Type$1.TString;
    alias: Type$1.TOptional<Type$1.TString>;
    tags: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    agentRuntime: Type$1.TOptional<Type$1.TObject<{
      id: Type$1.TString;
      fallback: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"openclaw">, Type$1.TLiteral<"none">]>>;
      cloudPlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
      cloudPlacementExecutionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"worker-turn">, Type$1.TLiteral<"remote-exec">]>>;
      devicePlacement: Type$1.TOptional<Type$1.TObject<{
        requiredNodeCommands: Type$1.TArray<Type$1.TString>;
        consumesWorkerSlot: Type$1.TBoolean;
      }>>;
      devicePlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
      source: Type$1.TUnion<[Type$1.TLiteral<"env">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"defaults">, Type$1.TLiteral<"model">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"implicit">, Type$1.TLiteral<"session">, Type$1.TLiteral<"session-key">]>;
    }>>;
    apiKeySupported: Type$1.TOptional<Type$1.TBoolean>;
    runtimeChoices: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      available: Type$1.TOptional<Type$1.TBoolean>;
      /** Scoped manual-choice permission; separate from runtime readiness and automatic selection. */
      manualSelectionAllowed: Type$1.TOptional<Type$1.TBoolean>;
      /** Earliest known retry time in epoch milliseconds, only for unavailable models. */
      unavailableUntil: Type$1.TOptional<Type$1.TInteger>;
      contextWindow: Type$1.TOptional<Type$1.TInteger>;
      contextTokens: Type$1.TOptional<Type$1.TInteger>;
      local: Type$1.TOptional<Type$1.TBoolean>;
      contextWindows: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        id: Type$1.TString;
        label: Type$1.TString;
        contextWindow: Type$1.TInteger;
      }>>>;
      contextWindowDefault: Type$1.TOptional<Type$1.TString>;
      reasoning: Type$1.TOptional<Type$1.TBoolean>;
      thinkingLevels: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        id: Type$1.TString;
        label: Type$1.TString;
      }>>>;
      thinkingDefault: Type$1.TOptional<Type$1.TString>;
      effectiveFastMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TLiteral<"auto">]>>;
      /** Local selected-request applicability, not preference or upstream fulfillment. */
      supportsFastMode: Type$1.TOptional<Type$1.TBoolean>;
      supportsTools: Type$1.TOptional<Type$1.TBoolean>;
      input: Type$1.TOptional<Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"text">, Type$1.TLiteral<"image">, Type$1.TLiteral<"audio">, Type$1.TLiteral<"video">, Type$1.TLiteral<"document">]>>>;
      agentRuntime: Type$1.TObject<{
        id: Type$1.TString;
        fallback: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"openclaw">, Type$1.TLiteral<"none">]>>;
        cloudPlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
        cloudPlacementExecutionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"worker-turn">, Type$1.TLiteral<"remote-exec">]>>;
        devicePlacement: Type$1.TOptional<Type$1.TObject<{
          requiredNodeCommands: Type$1.TArray<Type$1.TString>;
          consumesWorkerSlot: Type$1.TBoolean;
        }>>;
        devicePlacementSupported: Type$1.TOptional<Type$1.TBoolean>;
        source: Type$1.TUnion<[Type$1.TLiteral<"env">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"defaults">, Type$1.TLiteral<"model">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"implicit">, Type$1.TLiteral<"session">, Type$1.TLiteral<"session-key">]>;
      }>;
      unavailableReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"missing-auth">, Type$1.TLiteral<"auth-failed">, Type$1.TLiteral<"cooldown">]>, Type$1.TLiteral<"unsupported-runtime">]>>;
    }>>>;
  }>>;
  /** The Gateway owns role restrictions and the effective permitted reset target. */
  modelSelectionPolicy: Type$1.TOptional<Type$1.TObject<{
    restricted: Type$1.TLiteral<true>;
    defaultModel: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  }>>;
  /** Manifest-owned decision choices, separate from conversational model routing. */
  decisionModels: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    provider: Type$1.TString;
    name: Type$1.TString;
    pluginId: Type$1.TString;
    capabilities: Type$1.TOptional<Type$1.TObject<{
      questionTypes: Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"boolean">, Type$1.TLiteral<"choice">, Type$1.TLiteral<"score">]>>;
      maxQuestions: Type$1.TOptional<Type$1.TInteger>;
      maxChoiceAlternatives: Type$1.TOptional<Type$1.TInteger>;
      maxScoreLevels: Type$1.TOptional<Type$1.TInteger>;
      maxInputTokens: Type$1.TOptional<Type$1.TInteger>;
      inputTokenScope: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"encoded-question">, Type$1.TLiteral<"state-plus-each-criterion">]>>;
      requiresBooleanCriteria: Type$1.TOptional<Type$1.TBoolean>;
      confidence: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"provider-specific">, Type$1.TLiteral<"none">]>>;
    }>>;
  }>>>;
  defaultModels: Type$1.TOptional<Type$1.TObject<{
    /** Auto preview from agents.defaults.model, even when utility routing is explicit or disabled. */
    automaticUtilityModel: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  }>>;
  refreshFailed: Type$1.TOptional<Type$1.TBoolean>;
  pendingProviders: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  accountSelection: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    kind: Type$1.TLiteral<"automatic">;
    label: Type$1.TString;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"personal">;
    label: Type$1.TString;
    authProfileId: Type$1.TOptional<Type$1.TString>;
    source: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auto">, Type$1.TLiteral<"user">, Type$1.TLiteral<"user-link">]>>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"shared">;
    label: Type$1.TString;
    authProfileId: Type$1.TString;
    source: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auto">, Type$1.TLiteral<"user">, Type$1.TLiteral<"user-link">]>>;
  }>]>>;
  providerOutcomes: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    profileId: Type$1.TOptional<Type$1.TString>;
    status: Type$1.TUnion<[Type$1.TLiteral<"ready">, Type$1.TLiteral<"auth-rejected">, Type$1.TLiteral<"unavailable">]>;
  }>>>;
}>;
type ModelChoice = Static<typeof ModelChoiceSchema>;
type ModelsListResult = Static<typeof ModelsListResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/worker-inference.d.ts
declare const WorkerInferenceStartParamsSchema: Type$1.TObject<{
  readonly runEpoch: Type$1.TInteger;
  readonly sessionId: Type$1.TString;
  readonly runId: Type$1.TString;
  readonly turnId: Type$1.TString;
  readonly modelRef: Type$1.TObject<{
    readonly provider: Type$1.TString;
    readonly model: Type$1.TString;
  }>;
  readonly context: Type$1.TObject<{
    readonly systemPrompt: Type$1.TOptional<Type$1.TString>;
    readonly messages: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      readonly role: Type$1.TLiteral<"user">;
      readonly content: Type$1.TUnion<[Type$1.TString, Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
        readonly type: Type$1.TLiteral<"text">;
        readonly text: Type$1.TString;
        readonly textSignature: Type$1.TOptional<Type$1.TString>;
      }>, Type$1.TObject<{
        readonly type: Type$1.TLiteral<"image">;
        readonly data: Type$1.TString;
        readonly mimeType: Type$1.TString;
      }>]>>]>;
      readonly timestamp: Type$1.TInteger;
      readonly runtimeContextCarrier: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      readonly role: Type$1.TLiteral<"assistant">;
      readonly content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
        readonly type: Type$1.TLiteral<"text">;
        readonly text: Type$1.TString;
        readonly textSignature: Type$1.TOptional<Type$1.TString>;
      }>, Type$1.TObject<{
        readonly type: Type$1.TLiteral<"thinking">;
        readonly thinking: Type$1.TString;
        readonly thinkingSignature: Type$1.TOptional<Type$1.TString>;
        readonly redacted: Type$1.TOptional<Type$1.TBoolean>;
      }>, Type$1.TObject<{
        readonly type: Type$1.TLiteral<"toolCall">;
        readonly id: Type$1.TString;
        readonly name: Type$1.TString;
        readonly arguments: Type$1.TRecord<"^.*$", Type$1.TUnknown>;
        readonly thoughtSignature: Type$1.TOptional<Type$1.TString>;
        readonly executionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"sequential">, Type$1.TLiteral<"parallel">]>>;
      }>]>>;
      readonly api: Type$1.TString;
      readonly provider: Type$1.TString;
      readonly model: Type$1.TString;
      readonly responseModel: Type$1.TOptional<Type$1.TString>;
      readonly responseId: Type$1.TOptional<Type$1.TString>;
      readonly 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>;
      }>>;
      readonly usage: Type$1.TObject<{
        input: Type$1.TNumber;
        output: Type$1.TNumber;
        cacheRead: Type$1.TNumber;
        cacheWrite: Type$1.TNumber;
        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.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">>;
        }>;
      }>;
      readonly timestamp: Type$1.TInteger;
      readonly 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>>;
      }>>>;
      readonly stopReason: Type$1.TUnion<[Type$1.TLiteral<"stop">, Type$1.TLiteral<"length">, Type$1.TLiteral<"toolUse">, Type$1.TLiteral<"error">, Type$1.TLiteral<"aborted">]>;
      readonly errorMessage: Type$1.TOptional<Type$1.TString>;
      readonly errorCode: Type$1.TOptional<Type$1.TString>;
      readonly errorType: Type$1.TOptional<Type$1.TString>;
      readonly errorBody: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      readonly role: Type$1.TLiteral<"toolResult">;
      readonly toolCallId: Type$1.TString;
      readonly toolName: Type$1.TString;
      readonly content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
        readonly type: Type$1.TLiteral<"text">;
        readonly text: Type$1.TString;
        readonly textSignature: Type$1.TOptional<Type$1.TString>;
      }>, Type$1.TObject<{
        readonly type: Type$1.TLiteral<"image">;
        readonly data: Type$1.TString;
        readonly mimeType: Type$1.TString;
      }>]>>;
      readonly details: Type$1.TOptional<Type$1.TUnknown>;
      readonly isError: Type$1.TBoolean;
      readonly timestamp: Type$1.TInteger;
    }>]>>;
    readonly tools: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      readonly name: Type$1.TString;
      readonly description: Type$1.TString;
      readonly parameters: Type$1.TUnknown;
    }>>>;
  }>;
  readonly options: Type$1.TObject<{
    readonly temperature: Type$1.TOptional<Type$1.TNumber>;
    readonly maxTokens: Type$1.TOptional<Type$1.TInteger>;
    readonly reasoning: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"off">, Type$1.TLiteral<"minimal">, Type$1.TLiteral<"low">, Type$1.TLiteral<"medium">, Type$1.TLiteral<"high">, Type$1.TLiteral<"xhigh">, Type$1.TLiteral<"adaptive">, Type$1.TLiteral<"max">]>>;
    readonly thinkingBudgets: Type$1.TOptional<Type$1.TObject<{
      readonly minimal: Type$1.TOptional<Type$1.TInteger>;
      readonly low: Type$1.TOptional<Type$1.TInteger>;
      readonly medium: Type$1.TOptional<Type$1.TInteger>;
      readonly high: Type$1.TOptional<Type$1.TInteger>;
      readonly max: Type$1.TOptional<Type$1.TInteger>;
    }>>;
  }>;
}>;
declare const WorkerInferenceStartResultSchema: Type$1.TObject<{
  readonly status: Type$1.TUnion<[Type$1.TLiteral<"accepted">, Type$1.TLiteral<"replayed">]>;
}>;
declare const WorkerInferenceErrorReasonSchema: Type$1.TUnion<[Type$1.TLiteral<"model-not-approved">, Type$1.TLiteral<"invalid-context">, Type$1.TLiteral<"epoch-mismatch">, Type$1.TLiteral<"session-not-attached">, Type$1.TLiteral<"provider-error">, Type$1.TLiteral<"cancelled">]>;
declare const WorkerInferenceCancelParamsSchema: Type$1.TObject<{
  readonly runEpoch: Type$1.TInteger;
  readonly sessionId: Type$1.TString;
  readonly runId: Type$1.TString;
  readonly turnId: Type$1.TString;
}>;
declare const WorkerInferenceCancelResultSchema: Type$1.TObject<{
  readonly status: Type$1.TLiteral<"cancelled">;
}>;
declare const WorkerInferenceEventParamsSchema: Type$1.TObject<{
  readonly runEpoch: Type$1.TInteger;
  readonly sessionId: Type$1.TString;
  readonly runId: Type$1.TString;
  readonly turnId: Type$1.TString;
  readonly seq: Type$1.TInteger;
  readonly event: Type$1.TUnion<[Type$1.TObject<{
    readonly type: Type$1.TLiteral<"start">;
    readonly resolvedModel: Type$1.TObject<{
      readonly api: Type$1.TString;
      readonly provider: Type$1.TString;
      readonly model: Type$1.TString;
    }>;
    readonly timestamp: Type$1.TInteger;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"text_start">;
    readonly contentIndex: Type$1.TInteger;
    readonly contentSignature: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"text_delta">;
    readonly contentIndex: Type$1.TInteger;
    readonly delta: Type$1.TString;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"text_end">;
    readonly contentIndex: Type$1.TInteger;
    readonly contentSignature: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"thinking_start">;
    readonly contentIndex: Type$1.TInteger;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"thinking_delta">;
    readonly contentIndex: Type$1.TInteger;
    readonly delta: Type$1.TString;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"thinking_end">;
    readonly contentIndex: Type$1.TInteger;
    readonly contentSignature: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"toolcall_start">;
    readonly contentIndex: Type$1.TInteger;
    readonly id: Type$1.TString;
    readonly toolName: Type$1.TString;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"toolcall_delta">;
    readonly contentIndex: Type$1.TInteger;
    readonly delta: Type$1.TString;
  }>, Type$1.TObject<{
    readonly type: Type$1.TLiteral<"toolcall_end">;
    readonly contentIndex: Type$1.TInteger;
  }>]>;
}>;
declare const WorkerInferenceEventFrameSchema: Type$1.TObject<{
  readonly type: Type$1.TLiteral<"event">;
  readonly event: Type$1.TLiteral<"worker.inference.event">;
  readonly payload: Type$1.TObject<{
    readonly runEpoch: Type$1.TInteger;
    readonly sessionId: Type$1.TString;
    readonly runId: Type$1.TString;
    readonly turnId: Type$1.TString;
    readonly seq: Type$1.TInteger;
    readonly event: Type$1.TUnion<[Type$1.TObject<{
      readonly type: Type$1.TLiteral<"start">;
      readonly resolvedModel: Type$1.TObject<{
        readonly api: Type$1.TString;
        readonly provider: Type$1.TString;
        readonly model: Type$1.TString;
      }>;
      readonly timestamp: Type$1.TInteger;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"text_start">;
      readonly contentIndex: Type$1.TInteger;
      readonly contentSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"text_delta">;
      readonly contentIndex: Type$1.TInteger;
      readonly delta: Type$1.TString;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"text_end">;
      readonly contentIndex: Type$1.TInteger;
      readonly contentSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"thinking_start">;
      readonly contentIndex: Type$1.TInteger;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"thinking_delta">;
      readonly contentIndex: Type$1.TInteger;
      readonly delta: Type$1.TString;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"thinking_end">;
      readonly contentIndex: Type$1.TInteger;
      readonly contentSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"toolcall_start">;
      readonly contentIndex: Type$1.TInteger;
      readonly id: Type$1.TString;
      readonly toolName: Type$1.TString;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"toolcall_delta">;
      readonly contentIndex: Type$1.TInteger;
      readonly delta: Type$1.TString;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"toolcall_end">;
      readonly contentIndex: Type$1.TInteger;
    }>]>;
  }>;
}>;
declare const WorkerInferenceTerminalOutcomeSchema: Type$1.TUnion<[Type$1.TObject<{
  readonly type: Type$1.TLiteral<"done">;
  readonly message: Type$1.TObject<{
    readonly role: Type$1.TLiteral<"assistant">;
    readonly content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      readonly type: Type$1.TLiteral<"text">;
      readonly text: Type$1.TString;
      readonly textSignature: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"thinking">;
      readonly thinking: Type$1.TString;
      readonly thinkingSignature: Type$1.TOptional<Type$1.TString>;
      readonly redacted: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"toolCall">;
      readonly id: Type$1.TString;
      readonly name: Type$1.TString;
      readonly arguments: Type$1.TRecord<"^.*$", Type$1.TUnknown>;
      readonly thoughtSignature: Type$1.TOptional<Type$1.TString>;
      readonly executionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"sequential">, Type$1.TLiteral<"parallel">]>>;
    }>]>>;
    readonly api: Type$1.TString;
    readonly provider: Type$1.TString;
    readonly model: Type$1.TString;
    readonly responseModel: Type$1.TOptional<Type$1.TString>;
    readonly responseId: Type$1.TOptional<Type$1.TString>;
    readonly 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>;
    }>>;
    readonly usage: Type$1.TObject<{
      input: Type$1.TNumber;
      output: Type$1.TNumber;
      cacheRead: Type$1.TNumber;
      cacheWrite: Type$1.TNumber;
      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.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">>;
      }>;
    }>;
    readonly timestamp: Type$1.TInteger;
    readonly stopReason: Type$1.TUnion<[Type$1.TLiteral<"stop">, Type$1.TLiteral<"length">, Type$1.TLiteral<"toolUse">]>;
  }>;
}>, Type$1.TObject<{
  readonly type: Type$1.TLiteral<"error">;
  readonly reason: Type$1.TUnion<[Type$1.TLiteral<"model-not-approved">, Type$1.TLiteral<"invalid-context">, Type$1.TLiteral<"epoch-mismatch">, Type$1.TLiteral<"session-not-attached">, Type$1.TLiteral<"provider-error">, Type$1.TLiteral<"cancelled">]>;
  readonly message: Type$1.TString;
  readonly usage: Type$1.TOptional<Type$1.TObject<{
    input: Type$1.TNumber;
    output: Type$1.TNumber;
    cacheRead: Type$1.TNumber;
    cacheWrite: Type$1.TNumber;
    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.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">>;
    }>;
  }>>;
}>]>;
declare const WorkerInferenceTerminalFrameSchema: Type$1.TObject<{
  readonly type: Type$1.TLiteral<"event">;
  readonly event: Type$1.TLiteral<"worker.inference.terminal">;
  readonly payload: Type$1.TObject<{
    readonly runEpoch: Type$1.TInteger;
    readonly sessionId: Type$1.TString;
    readonly runId: Type$1.TString;
    readonly turnId: Type$1.TString;
    readonly seq: Type$1.TInteger;
    readonly outcome: Type$1.TUnion<[Type$1.TObject<{
      readonly type: Type$1.TLiteral<"done">;
      readonly message: Type$1.TObject<{
        readonly role: Type$1.TLiteral<"assistant">;
        readonly content: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
          readonly type: Type$1.TLiteral<"text">;
          readonly text: Type$1.TString;
          readonly textSignature: Type$1.TOptional<Type$1.TString>;
        }>, Type$1.TObject<{
          readonly type: Type$1.TLiteral<"thinking">;
          readonly thinking: Type$1.TString;
          readonly thinkingSignature: Type$1.TOptional<Type$1.TString>;
          readonly redacted: Type$1.TOptional<Type$1.TBoolean>;
        }>, Type$1.TObject<{
          readonly type: Type$1.TLiteral<"toolCall">;
          readonly id: Type$1.TString;
          readonly name: Type$1.TString;
          readonly arguments: Type$1.TRecord<"^.*$", Type$1.TUnknown>;
          readonly thoughtSignature: Type$1.TOptional<Type$1.TString>;
          readonly executionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"sequential">, Type$1.TLiteral<"parallel">]>>;
        }>]>>;
        readonly api: Type$1.TString;
        readonly provider: Type$1.TString;
        readonly model: Type$1.TString;
        readonly responseModel: Type$1.TOptional<Type$1.TString>;
        readonly responseId: Type$1.TOptional<Type$1.TString>;
        readonly 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>;
        }>>;
        readonly usage: Type$1.TObject<{
          input: Type$1.TNumber;
          output: Type$1.TNumber;
          cacheRead: Type$1.TNumber;
          cacheWrite: Type$1.TNumber;
          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.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">>;
          }>;
        }>;
        readonly timestamp: Type$1.TInteger;
        readonly stopReason: Type$1.TUnion<[Type$1.TLiteral<"stop">, Type$1.TLiteral<"length">, Type$1.TLiteral<"toolUse">]>;
      }>;
    }>, Type$1.TObject<{
      readonly type: Type$1.TLiteral<"error">;
      readonly reason: Type$1.TUnion<[Type$1.TLiteral<"model-not-approved">, Type$1.TLiteral<"invalid-context">, Type$1.TLiteral<"epoch-mismatch">, Type$1.TLiteral<"session-not-attached">, Type$1.TLiteral<"provider-error">, Type$1.TLiteral<"cancelled">]>;
      readonly message: Type$1.TString;
      readonly usage: Type$1.TOptional<Type$1.TObject<{
        input: Type$1.TNumber;
        output: Type$1.TNumber;
        cacheRead: Type$1.TNumber;
        cacheWrite: Type$1.TNumber;
        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.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">>;
        }>;
      }>>;
    }>]>;
  }>;
}>;
type WorkerInferenceStartParams = Static<typeof WorkerInferenceStartParamsSchema>;
type WorkerInferenceStartResult = Static<typeof WorkerInferenceStartResultSchema>;
type WorkerInferenceErrorReason = Static<typeof WorkerInferenceErrorReasonSchema>;
type WorkerInferenceCancelParams = Static<typeof WorkerInferenceCancelParamsSchema>;
type WorkerInferenceCancelResult = Static<typeof WorkerInferenceCancelResultSchema>;
type WorkerInferenceEventParams = Static<typeof WorkerInferenceEventParamsSchema>;
type WorkerInferenceEventFrame = Static<typeof WorkerInferenceEventFrameSchema>;
type WorkerInferenceTerminalOutcome = Static<typeof WorkerInferenceTerminalOutcomeSchema>;
type WorkerInferenceTerminalFrame = Static<typeof WorkerInferenceTerminalFrameSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/worker-computer.d.ts
declare const WorkerComputerParamsSchema: Type$1.TObject<{
  command: Type$1.TEnum<["screen.snapshot", "computer.act"]>;
  paramsJson: Type$1.TString;
  timeoutMs: Type$1.TOptional<Type$1.TInteger>;
  idempotencyKey: Type$1.TOptional<Type$1.TString>;
}>;
declare const WorkerComputerResultSchema: Type$1.TObject<{
  resultJson: Type$1.TString;
}>;
type WorkerComputerParams = Static<typeof WorkerComputerParamsSchema>;
type WorkerComputerResult = Static<typeof WorkerComputerResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/theme.d.ts
declare const THEME_COLOR_KEYS: readonly ["background", "foreground", "card", "card-foreground", "popover", "popover-foreground", "primary", "primary-foreground", "secondary", "secondary-foreground", "muted", "muted-foreground", "accent", "accent-foreground", "destructive", "destructive-foreground", "border", "input", "ring"];
declare const THEME_FONT_KEYS: readonly ["font-sans", "font-mono"];
declare const THEME_MASCOT_VALUES: readonly ["claw", "none"];
type ThemeMascot = (typeof THEME_MASCOT_VALUES)[number];
type ThemePalette = Record<(typeof THEME_COLOR_KEYS)[number], string> & Partial<Record<(typeof THEME_FONT_KEYS)[number], string>>;
type ThemeDefinition = {
  name: string;
  description: string;
  mascot?: ThemeMascot;
  workingPhrases?: string[];
  critters?: string[];
  avatarHat?: string;
  light?: ThemePalette;
  dark?: ThemePalette;
};
//#endregion
//#region packages/gateway-protocol/src/schema/sessions-row.d.ts
declare const SessionPermissionModeSchema: Type$1.TUnion<[Type$1.TLiteral<"read-only">, Type$1.TLiteral<"guarded">, Type$1.TLiteral<"workspace">, Type$1.TLiteral<"full">]>;
declare const SessionRunStatusSchema: Type$1.TUnion<[Type$1.TLiteral<"queued">, Type$1.TLiteral<"running">, Type$1.TLiteral<"done">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"interrupted">, Type$1.TLiteral<"killed">, Type$1.TLiteral<"timeout">]>;
declare const SessionEntryArchiveReasonSchema: Type$1.TUnion<[Type$1.TLiteral<"manual">, Type$1.TLiteral<"active-session-cap">, Type$1.TLiteral<"age-retention">, Type$1.TLiteral<"stale-dashboard">, Type$1.TLiteral<"restart-recovery">]>;
/** Stable Gateway session row fields; mutation envelopes may add null tombstones. */
declare const SessionRowSchema: Type$1.TObject<{
  key: Type$1.TString;
  sessionId: Type$1.TOptional<Type$1.TString>;
  incognito: Type$1.TOptional<Type$1.TLiteral<true>>;
  kind: Type$1.TUnion<[Type$1.TLiteral<"direct">, Type$1.TLiteral<"group">, Type$1.TLiteral<"global">, Type$1.TLiteral<"unknown">]>;
  label: Type$1.TOptional<Type$1.TString>;
  autoLabel: Type$1.TOptional<Type$1.TString>;
  icon: Type$1.TOptional<Type$1.TString>;
  /** Named sidebar tint from SESSION_COLOR_IDS; clients map names to theme hues. */
  color: Type$1.TOptional<Type$1.TString>;
  channelAvatarUrl: Type$1.TOptional<Type$1.TString>;
  boardFace: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"chat">, Type$1.TLiteral<"dashboard">]>>;
  /** Shared dashboard default; absent means split. */
  boardPresentation: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"split">, Type$1.TLiteral<"expanded">]>>;
  displayName: Type$1.TOptional<Type$1.TString>;
  derivedTitle: Type$1.TOptional<Type$1.TString>;
  lastMessagePreview: Type$1.TOptional<Type$1.TString>;
  channel: Type$1.TOptional<Type$1.TString>;
  /** Stable non-sensitive facts derived from the canonical session route. */
  classification: Type$1.TOptional<Type$1.TString>;
  agentId: Type$1.TOptional<Type$1.TString>;
  accountId: Type$1.TOptional<Type$1.TString>;
  peerKind: Type$1.TOptional<Type$1.TString>;
  isMain: Type$1.TOptional<Type$1.TBoolean>;
  isBackground: Type$1.TOptional<Type$1.TBoolean>;
  chatType: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"direct">, Type$1.TLiteral<"group">, Type$1.TLiteral<"channel">]>>;
  activitySummary: Type$1.TOptional<Type$1.TObject<{
    canEnsure: Type$1.TOptional<Type$1.TBoolean>;
    text: Type$1.TOptional<Type$1.TString>;
    updatedAt: Type$1.TOptional<Type$1.TInteger>;
    state: Type$1.TUnion<[Type$1.TLiteral<"current">, Type$1.TLiteral<"stale">, Type$1.TLiteral<"updating">, Type$1.TLiteral<"unavailable">]>;
  }>>;
  updatedAt: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
  /** Gateway sampling time, retained when a read reuses a cached projection. */
  snapshotAt: Type$1.TOptional<Type$1.TNumber>;
  /** Connection-scoped presentation identity on full event ancestor rows. */
  ancestorRevision: Type$1.TOptional<Type$1.TString>;
  /** Personal list preference for the authenticated viewer; not session visibility. */
  hiddenFromInvolvingMe: Type$1.TOptional<Type$1.TBoolean>;
  archived: Type$1.TOptional<Type$1.TBoolean>;
  archivedAt: Type$1.TOptional<Type$1.TNumber>;
  archivedBy: Type$1.TOptional<Type$1.TObject<{
    type: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"system">]>;
    id: Type$1.TOptional<Type$1.TString>;
    label: Type$1.TOptional<Type$1.TString>;
    /** Durable profile avatar route; absent for actors without a stored profile avatar. */
    avatarUrl: Type$1.TOptional<Type$1.TString>;
    /** Display identity is separate from the actor fields used by ownership policy. */
    identity: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"profile">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"agent">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"remote">;
      pluginId: Type$1.TString;
      domain: Type$1.TString;
      idKind: Type$1.TString;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"observation">;
      pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"legacy">;
      actorType: Type$1.TString;
      source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      id: Type$1.TString;
    }>]>>;
  }>>;
  archiveReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"manual">, Type$1.TLiteral<"active-session-cap">, Type$1.TLiteral<"age-retention">, Type$1.TLiteral<"stale-dashboard">, Type$1.TLiteral<"restart-recovery">]>>;
  pinned: Type$1.TOptional<Type$1.TBoolean>;
  pinnedAt: Type$1.TOptional<Type$1.TNumber>;
  unread: Type$1.TOptional<Type$1.TBoolean>;
  lastReadAt: Type$1.TOptional<Type$1.TNumber>;
  markedUnreadAt: Type$1.TOptional<Type$1.TNumber>;
  lastActivityAt: Type$1.TOptional<Type$1.TNumber>;
  lastInteractionAt: Type$1.TOptional<Type$1.TNumber>;
  status: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"queued">, Type$1.TLiteral<"running">, Type$1.TLiteral<"done">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"interrupted">, Type$1.TLiteral<"killed">, Type$1.TLiteral<"timeout">]>>;
  lastRunError: Type$1.TOptional<Type$1.TString>;
  providerReview: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    runId: Type$1.TString;
    explanation: Type$1.TOptional<Type$1.TString>;
    continuationMessage: Type$1.TOptional<Type$1.TString>;
    canContinue: Type$1.TBoolean;
  }>>;
  /** Exact run that produced the latest terminal lifecycle projection. */
  lastRunId: Type$1.TOptional<Type$1.TString>;
  restartRecoveryStatus: Type$1.TOptional<Type$1.TLiteral<"tombstoned">>;
  activeLeafEntryId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  spawnedBy: Type$1.TOptional<Type$1.TString>;
  parentSessionKey: Type$1.TOptional<Type$1.TString>;
  parentSessionId: Type$1.TOptional<Type$1.TString>;
  controlOwnerSessionKey: Type$1.TOptional<Type$1.TString>;
  childSessions: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  forkedFromParent: Type$1.TOptional<Type$1.TBoolean>;
  spawnDepth: Type$1.TOptional<Type$1.TNumber>;
  subagentRole: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"orchestrator">, Type$1.TLiteral<"leaf">]>>;
  subagentControlScope: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"children">, Type$1.TLiteral<"none">]>>;
  swarmGroupId: Type$1.TOptional<Type$1.TString>;
  /** Requester-owned execution counts; never child content or parent synthesis status. */
  swarm: Type$1.TOptional<Type$1.TObject<{
    groups: Type$1.TArray<Type$1.TObject<{
      groupId: Type$1.TString;
      createdAt: Type$1.TNumber;
      children: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        sessionKey: Type$1.TString;
        status: Type$1.TUnion<[Type$1.TLiteral<"queued">, Type$1.TLiteral<"running">, Type$1.TLiteral<"done">, Type$1.TLiteral<"failed">]>;
      }>>>;
      queued: Type$1.TInteger;
      running: Type$1.TInteger;
      done: Type$1.TInteger;
      failed: Type$1.TInteger;
    }>>;
    otherActiveGroups: Type$1.TInteger;
  }>>;
  worktree: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    branch: Type$1.TString;
    repoRoot: Type$1.TString;
  }>>;
  repositoryWorkspaceId: Type$1.TOptional<Type$1.TString>;
  repository: Type$1.TOptional<Type$1.TObject<{
    url: Type$1.TString;
    ref: Type$1.TOptional<Type$1.TString>;
    branch: Type$1.TString;
  }>>;
  execNode: Type$1.TOptional<Type$1.TString>;
  execCwd: Type$1.TOptional<Type$1.TString>;
  spawnedWorkspaceDir: Type$1.TOptional<Type$1.TString>;
  spawnedCwd: Type$1.TOptional<Type$1.TString>;
  /** Persisted project registry association, distinct from a cloud repository workspace. */
  projectId: Type$1.TOptional<Type$1.TString>;
  /** Persisted task cwd or spawned workspace; no filesystem resolution is implied. */
  workspaceDir: Type$1.TOptional<Type$1.TString>;
  permissionMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"read-only">, Type$1.TLiteral<"guarded">, Type$1.TLiteral<"workspace">, Type$1.TLiteral<"full">]>>;
  /** Authorized per-chat containment opt-out; omission follows configured sandbox policy. */
  sandboxMode: Type$1.TOptional<Type$1.TLiteral<"off">>;
  /** Administrator consent to the exact external runtime's own permissions for this incarnation. */
  nativeRuntimeConsent: Type$1.TOptional<Type$1.TString>;
  permissionModePending: Type$1.TOptional<Type$1.TBoolean>;
  sessionRoot: Type$1.TOptional<Type$1.TString>;
  createdVia: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"operator">, Type$1.TLiteral<"spawn">, Type$1.TLiteral<"channel">, Type$1.TLiteral<"cron">, Type$1.TLiteral<"talk">, Type$1.TLiteral<"run">, Type$1.TLiteral<"plugin">, Type$1.TLiteral<"internal">]>>;
  createdActor: Type$1.TOptional<Type$1.TObject<{
    type: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"system">]>;
    id: Type$1.TOptional<Type$1.TString>;
    label: Type$1.TOptional<Type$1.TString>;
    /** Durable profile avatar route; absent for actors without a stored profile avatar. */
    avatarUrl: Type$1.TOptional<Type$1.TString>;
    /** Display identity is separate from the actor fields used by ownership policy. */
    identity: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"profile">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"agent">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"remote">;
      pluginId: Type$1.TString;
      domain: Type$1.TString;
      idKind: Type$1.TString;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"observation">;
      pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"legacy">;
      actorType: Type$1.TString;
      source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      id: Type$1.TString;
    }>]>>;
  }>>;
  owner: Type$1.TOptional<Type$1.TObject<{
    actor: Type$1.TObject<{
      type: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"system">]>;
      id: Type$1.TOptional<Type$1.TString>;
      label: Type$1.TOptional<Type$1.TString>;
      /** Durable profile avatar route; absent for actors without a stored profile avatar. */
      avatarUrl: Type$1.TOptional<Type$1.TString>;
      /** Display identity is separate from the actor fields used by ownership policy. */
      identity: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        type: Type$1.TLiteral<"profile">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"agent">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"remote">;
        pluginId: Type$1.TString;
        domain: Type$1.TString;
        idKind: Type$1.TString;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"observation">;
        pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"legacy">;
        actorType: Type$1.TString;
        source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        id: Type$1.TString;
      }>]>>;
    }>;
    assignedBy: Type$1.TOptional<Type$1.TObject<{
      type: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"system">]>;
      id: Type$1.TOptional<Type$1.TString>;
      label: Type$1.TOptional<Type$1.TString>;
      /** Durable profile avatar route; absent for actors without a stored profile avatar. */
      avatarUrl: Type$1.TOptional<Type$1.TString>;
      /** Display identity is separate from the actor fields used by ownership policy. */
      identity: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        type: Type$1.TLiteral<"profile">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"agent">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"remote">;
        pluginId: Type$1.TString;
        domain: Type$1.TString;
        idKind: Type$1.TString;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"observation">;
        pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"legacy">;
        actorType: Type$1.TString;
        source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        id: Type$1.TString;
      }>]>>;
    }>>;
    assignedAt: Type$1.TOptional<Type$1.TNumber>;
  }>>;
  participants: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    identity: Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"profile">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"agent">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"remote">;
      pluginId: Type$1.TString;
      domain: Type$1.TString;
      idKind: Type$1.TString;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"observation">;
      pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"legacy">;
      actorType: Type$1.TString;
      source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      id: Type$1.TString;
    }>]>;
    label: Type$1.TOptional<Type$1.TString>;
    avatarUrl: Type$1.TOptional<Type$1.TString>;
  }>>>;
  expandedParticipants: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    identity: Type$1.TUnion<[Type$1.TObject<{
      type: Type$1.TLiteral<"profile">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"agent">;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"remote">;
      pluginId: Type$1.TString;
      domain: Type$1.TString;
      idKind: Type$1.TString;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"observation">;
      pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
      id: Type$1.TString;
    }>, Type$1.TObject<{
      type: Type$1.TLiteral<"legacy">;
      actorType: Type$1.TString;
      source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      id: Type$1.TString;
    }>]>;
    label: Type$1.TOptional<Type$1.TString>;
    avatarUrl: Type$1.TOptional<Type$1.TString>;
  }>>>;
  participantCount: Type$1.TOptional<Type$1.TInteger>;
  visibility: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"shared">, Type$1.TLiteral<"read-only">, Type$1.TLiteral<"suggest">, Type$1.TLiteral<"draft">]>>;
  sharingRole: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"admin">, Type$1.TLiteral<"owner">, Type$1.TLiteral<"member">, Type$1.TLiteral<"viewer">]>>;
  createdAt: Type$1.TOptional<Type$1.TNumber>;
  forkSource: Type$1.TOptional<Type$1.TObject<{
    sessionKey: Type$1.TString;
    sessionId: Type$1.TString;
    entryId: Type$1.TOptional<Type$1.TString>;
  }>>;
  previousSessionId: Type$1.TOptional<Type$1.TString>;
  inputTokens: Type$1.TOptional<Type$1.TNumber>;
  outputTokens: Type$1.TOptional<Type$1.TNumber>;
  totalTokens: Type$1.TOptional<Type$1.TNumber>;
  totalTokensFresh: Type$1.TOptional<Type$1.TBoolean>;
  contextTokens: Type$1.TOptional<Type$1.TNumber>;
  estimatedCostUsd: Type$1.TOptional<Type$1.TNumber>;
  model: Type$1.TOptional<Type$1.TString>;
  modelProvider: Type$1.TOptional<Type$1.TString>;
  /** Runtime model serving this session while it differs from the selected model. */
  activeModel: Type$1.TOptional<Type$1.TString>;
  activeModelProvider: Type$1.TOptional<Type$1.TString>;
  /** Effective override provenance; null means configured default, omission means not projected. */
  modelOverrideSource: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"user">, Type$1.TLiteral<"auto">, Type$1.TLiteral<"inherited">, Type$1.TNull]>>;
  toolOverrides: Type$1.TOptional<Type$1.TObject<{
    mcpServers: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TBoolean>>;
    mcpToolsDeny: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>>;
    skills: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TBoolean>>;
    webSearch: Type$1.TOptional<Type$1.TBoolean>;
  }>>;
}>;
type SessionPermissionMode = Static<typeof SessionPermissionModeSchema>;
type SessionRunStatus = Static<typeof SessionRunStatusSchema>;
type SessionRow = Static<typeof SessionRowSchema>;
type SessionEntryArchiveReason = Static<typeof SessionEntryArchiveReasonSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/sessions-activity-summary.d.ts
declare const SessionActivitySummarySchema: Type$1.TObject<{
  /** Caller-specific participation permission; operator.write is required separately. */
  canEnsure: Type$1.TOptional<Type$1.TBoolean>;
  text: Type$1.TOptional<Type$1.TString>;
  updatedAt: Type$1.TOptional<Type$1.TInteger>;
  state: Type$1.TUnion<[Type$1.TLiteral<"current">, Type$1.TLiteral<"stale">, Type$1.TLiteral<"updating">, Type$1.TLiteral<"unavailable">]>;
}>;
type SessionActivitySummary = Static<typeof SessionActivitySummarySchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/sessions-catalog.d.ts
declare const SessionCatalogShareRouteSchema: Type$1.TObject<{
  kind: Type$1.TLiteral<"thread-id-prefix">;
  routeSegment: Type$1.TString;
  hostId: Type$1.TString;
  identifierAlphabet: Type$1.TLiteral<"lowercase-hex">;
  fullLength: Type$1.TLiteral<32>;
  minPrefixLength: Type$1.TLiteral<12>;
  lookup: Type$1.TLiteral<"catalog-list-search-by-thread-id-prefix">;
  ambiguity: Type$1.TLiteral<"multiple-results-or-next-cursor">;
}>;
declare const SessionCatalogHostSchema: Type$1.TObject<{
  hostId: Type$1.TString;
  label: Type$1.TString;
  kind: Type$1.TUnion<[Type$1.TLiteral<"gateway">, Type$1.TLiteral<"node">]>;
  connected: Type$1.TBoolean;
  /** First snapshot is still loading; retain prior rows until the host publication arrives. */
  pending: Type$1.TOptional<Type$1.TBoolean>;
  nodeId: Type$1.TOptional<Type$1.TString>;
  canStartTerminal: Type$1.TOptional<Type$1.TBoolean>;
  sessions: Type$1.TArray<Type$1.TObject<{
    threadId: Type$1.TString;
    sourceHomeId: Type$1.TOptional<Type$1.TString>;
    name: Type$1.TOptional<Type$1.TString>;
    /** Named tint imported from the source CLI session (SESSION_COLOR_IDS). */
    color: Type$1.TOptional<Type$1.TString>;
    cwd: Type$1.TOptional<Type$1.TString>;
    status: Type$1.TString;
    createdAt: Type$1.TOptional<Type$1.TNumber>;
    updatedAt: Type$1.TOptional<Type$1.TNumber>;
    recencyAt: Type$1.TOptional<Type$1.TNumber>;
    source: Type$1.TOptional<Type$1.TString>;
    modelProvider: Type$1.TOptional<Type$1.TString>;
    cliVersion: Type$1.TOptional<Type$1.TString>;
    gitBranch: Type$1.TOptional<Type$1.TString>;
    customGroup: Type$1.TOptional<Type$1.TString>;
    pullRequest: Type$1.TOptional<Type$1.TObject<{
      numbers: Type$1.TArray<Type$1.TInteger>;
      state: Type$1.TUnion<[Type$1.TLiteral<"open">, Type$1.TLiteral<"draft">, Type$1.TLiteral<"merged">, Type$1.TLiteral<"closed">]>;
    }>>;
    archived: Type$1.TBoolean;
    sessionKey: Type$1.TOptional<Type$1.TString>;
    createdActor: Type$1.TOptional<Type$1.TObject<{
      type: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"agent">, Type$1.TLiteral<"system">]>;
      id: Type$1.TOptional<Type$1.TString>;
      label: Type$1.TOptional<Type$1.TString>;
      avatarUrl: Type$1.TOptional<Type$1.TString>;
      identity: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        type: Type$1.TLiteral<"profile">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"agent">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"remote">;
        pluginId: Type$1.TString;
        domain: Type$1.TString;
        idKind: Type$1.TString;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"observation">;
        pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"legacy">;
        actorType: Type$1.TString;
        source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        id: Type$1.TString;
      }>]>>;
    }>>;
    canContinue: Type$1.TBoolean;
    canArchive: Type$1.TBoolean;
    canOpenTerminal: Type$1.TOptional<Type$1.TBoolean>;
  }>>;
  nextCursor: Type$1.TOptional<Type$1.TString>;
  error: Type$1.TOptional<Type$1.TObject<{
    code: Type$1.TString;
    message: Type$1.TString;
  }>>;
}>;
declare const SessionsCatalogReadParamsSchema: Type$1.TObject<{
  catalogId: Type$1.TString;
  hostId: Type$1.TString;
  threadId: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  sourceHomeId: Type$1.TOptional<Type$1.TString>;
  limit: Type$1.TOptional<Type$1.TInteger>;
  cursor: Type$1.TOptional<Type$1.TString>;
}>;
declare const SessionsCatalogReadResultSchema: Type$1.TObject<{
  hostId: Type$1.TString;
  label: Type$1.TOptional<Type$1.TString>;
  threadId: Type$1.TString;
  items: Type$1.TArray<Type$1.TObject<{
    id: Type$1.TOptional<Type$1.TString>;
    type: Type$1.TUnion<[Type$1.TLiteral<"userMessage">, Type$1.TLiteral<"agentMessage">, Type$1.TLiteral<"reasoning">, Type$1.TLiteral<"toolCall">, Type$1.TLiteral<"toolResult">, Type$1.TLiteral<"other">]>;
    text: Type$1.TOptional<Type$1.TString>;
    timestamp: Type$1.TOptional<Type$1.TString>;
    model: Type$1.TOptional<Type$1.TString>;
    /** Source-supplied attribution, independent of the viewer and session adopter. */
    sender: Type$1.TOptional<Type$1.TObject<{
      identity: Type$1.TUnion<[Type$1.TObject<{
        type: Type$1.TLiteral<"profile">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"agent">;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"remote">;
        pluginId: Type$1.TString;
        domain: Type$1.TString;
        idKind: Type$1.TString;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"observation">;
        pluginId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        accountId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        senderKind: Type$1.TUnion<[Type$1.TLiteral<"human">, Type$1.TLiteral<"bot">, Type$1.TLiteral<"unknown">]>;
        id: Type$1.TString;
      }>, Type$1.TObject<{
        type: Type$1.TLiteral<"legacy">;
        actorType: Type$1.TString;
        source: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        id: Type$1.TString;
      }>]>;
      label: Type$1.TOptional<Type$1.TString>;
      avatarUrl: Type$1.TOptional<Type$1.TString>;
    }>>;
    truncated: Type$1.TOptional<Type$1.TBoolean>;
    raw: Type$1.TOptional<Type$1.TUnknown>;
  }>>;
  nextCursor: Type$1.TOptional<Type$1.TString>;
}>;
declare const SessionsCatalogContinueParamsSchema: Type$1.TObject<{
  catalogId: Type$1.TString;
  hostId: Type$1.TString;
  threadId: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  sourceHomeId: Type$1.TOptional<Type$1.TString>;
}>;
declare const SessionsCatalogArchiveParamsSchema: Type$1.TObject<{
  catalogId: Type$1.TString;
  hostId: Type$1.TString;
  threadId: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  sourceHomeId: Type$1.TOptional<Type$1.TString>;
  confirmNoOtherRunner: Type$1.TLiteral<true>;
}>;
type SessionCatalogShareRoute = Static<typeof SessionCatalogShareRouteSchema>;
type SessionCatalogHost = Static<typeof SessionCatalogHostSchema>;
type SessionsCatalogReadParams = Static<typeof SessionsCatalogReadParamsSchema>;
type SessionsCatalogReadResult = Static<typeof SessionsCatalogReadResultSchema>;
type SessionsCatalogContinueParams = Static<typeof SessionsCatalogContinueParamsSchema>;
type SessionsCatalogArchiveParams = Static<typeof SessionsCatalogArchiveParamsSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/agent.d.ts
/** Main agent-run request accepted by the gateway. */
declare const AgentParamsSchema: Type$1.TObject<{
  message: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  provider: Type$1.TOptional<Type$1.TString>;
  model: Type$1.TOptional<Type$1.TString>;
  to: Type$1.TOptional<Type$1.TString>;
  replyTo: Type$1.TOptional<Type$1.TString>;
  sessionId: Type$1.TOptional<Type$1.TString>;
  sessionKey: Type$1.TOptional<Type$1.TString>;
  expectedExistingSessionId: Type$1.TOptional<Type$1.TString>;
  expectedExistingSessionLifecycleRevision: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  thinking: Type$1.TOptional<Type$1.TString>;
  deliver: Type$1.TOptional<Type$1.TBoolean>;
  attachments: Type$1.TOptional<Type$1.TArray<Type$1.TUnknown>>;
  channel: Type$1.TOptional<Type$1.TString>;
  replyChannel: Type$1.TOptional<Type$1.TString>;
  accountId: Type$1.TOptional<Type$1.TString>;
  replyAccountId: Type$1.TOptional<Type$1.TString>;
  threadId: Type$1.TOptional<Type$1.TString>;
  groupId: Type$1.TOptional<Type$1.TString>;
  groupChannel: Type$1.TOptional<Type$1.TString>;
  groupSpace: Type$1.TOptional<Type$1.TString>;
  timeout: Type$1.TOptional<Type$1.TInteger>;
  bestEffortDeliver: Type$1.TOptional<Type$1.TBoolean>;
  lane: Type$1.TOptional<Type$1.TString>;
  cwd: Type$1.TOptional<Type$1.TString>;
  cleanupBundleMcpOnRunEnd: Type$1.TOptional<Type$1.TBoolean>;
  modelRun: Type$1.TOptional<Type$1.TBoolean>;
  promptMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"full">, Type$1.TLiteral<"minimal">, Type$1.TLiteral<"none">]>>;
  extraSystemPrompt: Type$1.TOptional<Type$1.TString>;
  bootstrapContextMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"full">, Type$1.TLiteral<"lightweight">]>>;
  bootstrapContextRunKind: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"default">, Type$1.TLiteral<"heartbeat">, Type$1.TLiteral<"cron">]>>;
  acpTurnSource: Type$1.TOptional<Type$1.TLiteral<"manual_spawn">>;
  internalRuntimeHandoffId: Type$1.TOptional<Type$1.TString>;
  internalExecutionIdentityRetry: Type$1.TOptional<Type$1.TBoolean>;
  /** Exact durable recovery attempt that owns any post-admission identity bind. */
  internalExecutionIdentityRecoveryAttempt: Type$1.TOptional<Type$1.TInteger>;
  execApprovalFollowupExpectedSessionId: Type$1.TOptional<Type$1.TString>;
  internalEvents: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    type: Type$1.TLiteral<"task_completion">;
    source: Type$1.TString;
    childSessionKey: Type$1.TString;
    childSessionId: Type$1.TOptional<Type$1.TString>;
    announceType: Type$1.TString;
    taskLabel: Type$1.TString;
    status: Type$1.TString;
    statusLabel: Type$1.TString;
    result: Type$1.TString;
    noVisibleResult: Type$1.TOptional<Type$1.TBoolean>;
    modelRouteChange: Type$1.TOptional<Type$1.TString>;
    attachments: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      type: Type$1.TOptional<Type$1.TString>;
      path: Type$1.TOptional<Type$1.TString>;
      url: Type$1.TOptional<Type$1.TString>;
      mediaUrl: Type$1.TOptional<Type$1.TString>;
      filePath: Type$1.TOptional<Type$1.TString>;
      mimeType: Type$1.TOptional<Type$1.TString>;
      name: Type$1.TOptional<Type$1.TString>;
      sizeBytes: Type$1.TOptional<Type$1.TNumber>;
      durationMs: Type$1.TOptional<Type$1.TNumber>;
      width: Type$1.TOptional<Type$1.TNumber>;
      height: Type$1.TOptional<Type$1.TNumber>;
    }>>>;
    mediaUrls: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    statsLine: Type$1.TOptional<Type$1.TString>;
    replyInstruction: Type$1.TString;
  }>>>;
  inputProvenance: Type$1.TOptional<Type$1.TObject<{
    kind: Type$1.TString;
    originSessionId: Type$1.TOptional<Type$1.TString>;
    sourceSessionKey: Type$1.TOptional<Type$1.TString>;
    sourceChannel: Type$1.TOptional<Type$1.TString>;
    sourceTool: Type$1.TOptional<Type$1.TString>;
    sourceRole: Type$1.TOptional<Type$1.TLiteral<"subagent">>;
    sourcePromptPrefix: Type$1.TOptional<Type$1.TString>;
    jobId: Type$1.TOptional<Type$1.TString>;
    runId: Type$1.TOptional<Type$1.TString>;
  }>>;
  suppressPromptPersistence: Type$1.TOptional<Type$1.TBoolean>;
  sessionEffects: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"visible">, Type$1.TLiteral<"internal">]>>;
  sourceReplyDeliveryMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"automatic">, Type$1.TLiteral<"message_tool_only">]>>;
  disableMessageTool: Type$1.TOptional<Type$1.TBoolean>;
  swarmCollector: Type$1.TOptional<Type$1.TBoolean>;
  swarmOutputSchema: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnknown>>;
  forceRestartSafeTools: Type$1.TOptional<Type$1.TBoolean>;
  forceCodeModeTools: Type$1.TOptional<Type$1.TBoolean>;
  voiceWakeTrigger: Type$1.TOptional<Type$1.TString>;
  idempotencyKey: Type$1.TString;
  label: Type$1.TOptional<Type$1.TString>;
}>;
/** Waits for a submitted agent run to complete or time out. */
declare const AgentWaitParamsSchema: Type$1.TObject<{
  runId: Type$1.TString;
  timeoutMs: Type$1.TOptional<Type$1.TInteger>;
}>;
type AgentWaitParams = Static<typeof AgentWaitParamsSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/agents-models-skills.d.ts
/** Proposal record result returned after non-apply proposal actions. */
declare const SkillsProposalRecordResultSchema: Type$1.TObject<{
  schema: Type$1.TLiteral<"openclaw.skill-workshop.proposal.v1">;
  id: Type$1.TString;
  kind: Type$1.TUnion<[Type$1.TLiteral<"create">, Type$1.TLiteral<"update">]>;
  status: Type$1.TUnion<[Type$1.TLiteral<"pending">, Type$1.TLiteral<"applied">, Type$1.TLiteral<"rejected">, Type$1.TLiteral<"quarantined">, Type$1.TLiteral<"stale">]>;
  title: Type$1.TString;
  description: Type$1.TString;
  createdAt: Type$1.TString;
  updatedAt: Type$1.TString;
  createdBy: Type$1.TUnion<[Type$1.TLiteral<"skill-workshop">, Type$1.TLiteral<"cli">, Type$1.TLiteral<"gateway">]>;
  origin: Type$1.TOptional<Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TString>;
    sessionKey: Type$1.TOptional<Type$1.TString>;
    runId: Type$1.TOptional<Type$1.TString>;
    messageId: Type$1.TOptional<Type$1.TString>;
  }>>;
  proposedVersion: Type$1.TString;
  draftFile: Type$1.TLiteral<"PROPOSAL.md">;
  draftHash: Type$1.TString;
  supportFiles: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    path: Type$1.TString;
    sizeBytes: Type$1.TInteger;
    hash: Type$1.TString;
    targetExisted: Type$1.TOptional<Type$1.TBoolean>;
    targetContentHash: Type$1.TOptional<Type$1.TString>;
  }>>>;
  target: Type$1.TObject<{
    skillName: Type$1.TString;
    skillKey: Type$1.TString;
    skillDir: Type$1.TString;
    skillFile: Type$1.TString;
    source: Type$1.TOptional<Type$1.TString>;
    currentContentHash: Type$1.TOptional<Type$1.TString>;
  }>;
  scan: Type$1.TObject<{
    state: Type$1.TUnion<[Type$1.TLiteral<"pending">, Type$1.TLiteral<"clean">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"quarantined">]>;
    scannedAt: Type$1.TString;
    critical: Type$1.TInteger;
    warn: Type$1.TInteger;
    info: Type$1.TInteger;
    findings: Type$1.TArray<Type$1.TObject<{
      ruleId: Type$1.TString;
      severity: Type$1.TUnion<[Type$1.TLiteral<"info">, Type$1.TLiteral<"warn">, Type$1.TLiteral<"critical">]>;
      file: Type$1.TString;
      line: Type$1.TInteger;
      message: Type$1.TString;
      evidence: Type$1.TString;
    }>>;
  }>;
  goal: Type$1.TOptional<Type$1.TString>;
  evidence: Type$1.TOptional<Type$1.TString>;
  appliedAt: Type$1.TOptional<Type$1.TString>;
  rejectedAt: Type$1.TOptional<Type$1.TString>;
  quarantinedAt: Type$1.TOptional<Type$1.TString>;
  staleAt: Type$1.TOptional<Type$1.TString>;
  statusReason: Type$1.TOptional<Type$1.TString>;
  evaluation: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    proposedVersion: Type$1.TString;
    revisionHash: Type$1.TString;
    trigger: Type$1.TUnion<[Type$1.TLiteral<"manual">, Type$1.TLiteral<"apply">]>;
    startedAt: Type$1.TString;
    completedAt: Type$1.TString;
    correlationId: Type$1.TOptional<Type$1.TString>;
    targetTreeSha256: Type$1.TOptional<Type$1.TString>;
    outcomes: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
      pluginId: Type$1.TString;
      pluginVersion: Type$1.TOptional<Type$1.TString>;
      evaluatorId: Type$1.TString;
      status: Type$1.TLiteral<"completed">;
      result: Type$1.TObject<{
        summary: Type$1.TOptional<Type$1.TString>;
        findings: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
          ruleId: Type$1.TString;
          severity: Type$1.TUnion<[Type$1.TLiteral<"info">, Type$1.TLiteral<"warn">, Type$1.TLiteral<"critical">]>;
          message: Type$1.TString;
          file: Type$1.TOptional<Type$1.TString>;
          line: Type$1.TOptional<Type$1.TInteger>;
        }>>>;
        metrics: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnion<[Type$1.TString, Type$1.TNumber, Type$1.TBoolean]>>>;
        evaluatorVersion: Type$1.TOptional<Type$1.TString>;
        mode: Type$1.TOptional<Type$1.TString>;
        decision: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"pass">, Type$1.TLiteral<"revise">, Type$1.TLiteral<"block">]>>;
        decisionReason: Type$1.TOptional<Type$1.TString>;
      }>;
    }>, Type$1.TObject<{
      pluginId: Type$1.TString;
      pluginVersion: Type$1.TOptional<Type$1.TString>;
      evaluatorId: Type$1.TString;
      status: Type$1.TLiteral<"skipped">;
    }>, Type$1.TObject<{
      pluginId: Type$1.TString;
      pluginVersion: Type$1.TOptional<Type$1.TString>;
      evaluatorId: Type$1.TString;
      status: Type$1.TLiteral<"error">;
      error: Type$1.TString;
    }>]>>;
  }>>;
}>;
declare const ToolsGitHubAuthorizeStartResultSchema: Type$1.TObject<{
  requestId: Type$1.TString;
  userCode: Type$1.TString;
  verificationUri: Type$1.TLiteral<"https://github.com/login/device">;
  expiresInMs: Type$1.TInteger;
  pollAfterMs: Type$1.TInteger;
}>;
declare const ToolsGitHubAuthorizePollResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"pending">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"slow_down">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"access_denied">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"expired">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"incorrect_device_code">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"network_error">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"failed">;
  reason: Type$1.TUnion<[Type$1.TLiteral<"identity_changed">, Type$1.TLiteral<"setup_failed">]>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"success">;
  githubStatus: Type$1.TObject<{
    agentId: Type$1.TString;
    selectedScope: Type$1.TUnion<[Type$1.TLiteral<"system">, Type$1.TLiteral<"agent">]>;
    selected: Type$1.TObject<{
      scope: Type$1.TUnion<[Type$1.TLiteral<"system">, Type$1.TLiteral<"agent">]>;
      configured: Type$1.TBoolean;
      identity: Type$1.TUnion<[Type$1.TObject<{
        source: Type$1.TUnion<[Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
        credentialKind: Type$1.TUnion<[Type$1.TLiteral<"native">, Type$1.TLiteral<"managed-pat">, Type$1.TLiteral<"managed-oauth">]>;
        credentialState: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"unavailable">, Type$1.TLiteral<"configured_unavailable">, Type$1.TLiteral<"unverified">, Type$1.TLiteral<"rate_limited">]>;
        account: Type$1.TUnion<[Type$1.TObject<{
          login: Type$1.TString;
        }>, Type$1.TNull]>;
        gitAuthor: Type$1.TObject<{
          name: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
          email: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        }>;
        evidence: Type$1.TUnion<[Type$1.TLiteral<"github-api">, Type$1.TLiteral<"none">, Type$1.TLiteral<"unverified">, Type$1.TLiteral<"rate-limited">]>;
        accessExpiresAtMs: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
        refreshState: Type$1.TUnion<[Type$1.TLiteral<"not_applicable">, Type$1.TLiteral<"available">, Type$1.TLiteral<"expired">, Type$1.TLiteral<"unavailable">, Type$1.TLiteral<"refreshing">, Type$1.TLiteral<"failed">]>;
        oauthScopes: Type$1.TArray<Type$1.TString>;
        repositoryGrants: Type$1.TLiteral<"unknown">;
      }>, Type$1.TNull]>;
    }>;
    effective: Type$1.TObject<{
      source: Type$1.TUnion<[Type$1.TLiteral<"system-detected">, Type$1.TLiteral<"system-configured">, Type$1.TLiteral<"agent-override">]>;
      credentialKind: Type$1.TUnion<[Type$1.TLiteral<"native">, Type$1.TLiteral<"managed-pat">, Type$1.TLiteral<"managed-oauth">]>;
      credentialState: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"unavailable">, Type$1.TLiteral<"configured_unavailable">, Type$1.TLiteral<"unverified">, Type$1.TLiteral<"rate_limited">]>;
      account: Type$1.TUnion<[Type$1.TObject<{
        login: Type$1.TString;
      }>, Type$1.TNull]>;
      gitAuthor: Type$1.TObject<{
        name: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
        email: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
      }>;
      evidence: Type$1.TUnion<[Type$1.TLiteral<"github-api">, Type$1.TLiteral<"none">, Type$1.TLiteral<"unverified">, Type$1.TLiteral<"rate-limited">]>;
      accessExpiresAtMs: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
      refreshState: Type$1.TUnion<[Type$1.TLiteral<"not_applicable">, Type$1.TLiteral<"available">, Type$1.TLiteral<"expired">, Type$1.TLiteral<"unavailable">, Type$1.TLiteral<"refreshing">, Type$1.TLiteral<"failed">]>;
      oauthScopes: Type$1.TArray<Type$1.TString>;
      repositoryGrants: Type$1.TLiteral<"unknown">;
    }>;
  }>;
}>]>;
type ToolsGitHubAuthorizeStartResult = Static<typeof ToolsGitHubAuthorizeStartResultSchema>;
type ToolsGitHubAuthorizePollResult = Static<typeof ToolsGitHubAuthorizePollResultSchema>;
type SkillsProposalRecordResult = Static<typeof SkillsProposalRecordResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/audit-run.d.ts
declare const DecisionReceiptV1Schema: Type$1.TObject<{
  schemaVersion: Type$1.TLiteral<1>;
  receiptId: Type$1.TString;
  contextId: Type$1.TString;
  executionId: Type$1.TString;
  runId: Type$1.TString;
  actionId: Type$1.TOptional<Type$1.TString>;
  occurredAt: Type$1.TInteger;
  action: Type$1.TObject<{
    family: Type$1.TString;
    operation: Type$1.TString;
    resourceRef: Type$1.TOptional<Type$1.TString>;
    targetRef: Type$1.TOptional<Type$1.TString>;
    summary: Type$1.TOptional<Type$1.TString>;
  }>;
  decision: Type$1.TObject<{
    outcome: Type$1.TUnion<[Type$1.TLiteral<"allowed">, Type$1.TLiteral<"denied">, Type$1.TLiteral<"not-applicable">, Type$1.TLiteral<"unknown">]>;
    reasonCode: Type$1.TString;
  }>;
  enforcement: Type$1.TObject<{
    coverageState: Type$1.TUnion<[Type$1.TLiteral<"enforced">, Type$1.TLiteral<"attribution-only">, Type$1.TLiteral<"unattributed">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"unsupported">]>;
    evaluatorRef: Type$1.TOptional<Type$1.TString>;
    policyRefs: Type$1.TArray<Type$1.TString>;
    grantRefs: Type$1.TArray<Type$1.TString>;
    contextFieldsUsed: Type$1.TArray<Type$1.TString>;
  }>;
  source: Type$1.TObject<{
    owner: Type$1.TString;
    recordRef: Type$1.TString;
    decisionBoundary: Type$1.TString;
  }>;
  missingEvidence: Type$1.TArray<Type$1.TString>;
  remediation: Type$1.TArray<Type$1.TObject<{
    code: Type$1.TString;
    text: Type$1.TString;
  }>>;
}>;
type DecisionReceiptV1 = Static<typeof DecisionReceiptV1Schema>;
//#endregion
//#region packages/gateway-protocol/src/schema/model-account-selection.d.ts
/** Configured preference only; provider failover can use a different account. */
declare const ChatAccountSelectionSchema: Type$1.TUnion<[Type$1.TObject<{
  kind: Type$1.TLiteral<"automatic">;
  label: Type$1.TString;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"personal">;
  label: Type$1.TString;
  authProfileId: Type$1.TOptional<Type$1.TString>;
  source: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auto">, Type$1.TLiteral<"user">, Type$1.TLiteral<"user-link">]>>;
}>, Type$1.TObject<{
  kind: Type$1.TLiteral<"shared">;
  label: Type$1.TString;
  authProfileId: Type$1.TString;
  source: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auto">, Type$1.TLiteral<"user">, Type$1.TLiteral<"user-link">]>>;
}>]>;
type ChatAccountSelection = Static<typeof ChatAccountSelectionSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/users.d.ts
declare const UsersListModelAccountsResultSchema: Type$1.TObject<{
  profileId: Type$1.TString;
  accounts: Type$1.TArray<Type$1.TObject<{
    authProfileId: Type$1.TString;
    provider: Type$1.TString;
    label: Type$1.TString;
    authType: Type$1.TUnion<[Type$1.TLiteral<"api_key">, Type$1.TLiteral<"oauth">, Type$1.TLiteral<"token">]>;
    selected: Type$1.TBoolean;
  }>>;
  nextCursor: Type$1.TOptional<Type$1.TString>;
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>;
declare const UsersSelectModelAccountResultSchema: Type$1.TObject<{
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>;
declare const UsersListAuthLinksResultSchema: Type$1.TObject<{
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>;
declare const UsersLinkAuthProfileResultSchema: Type$1.TObject<{
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>;
declare const UsersUnlinkAuthProfileResultSchema: Type$1.TObject<{
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>;
declare const UsersAuthConnectCatalogResultSchema: Type$1.TObject<{
  providers: Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    label: Type$1.TString;
    methods: Type$1.TArray<Type$1.TObject<{
      id: Type$1.TString;
      label: Type$1.TString;
      hint: Type$1.TOptional<Type$1.TString>;
    }>>;
  }>>;
}>;
declare const UsersAuthConnectStartResultSchema: Type$1.TObject<{
  connectId: Type$1.TString;
  expiresAtMs: Type$1.TInteger;
}>;
declare const UsersAuthConnectStatusResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"pending">;
  step: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    type: Type$1.TUnion<[Type$1.TLiteral<"note">, Type$1.TLiteral<"select">, Type$1.TLiteral<"text">, Type$1.TLiteral<"confirm">, Type$1.TLiteral<"multiselect">, Type$1.TLiteral<"progress">, Type$1.TLiteral<"action">]>;
    title: Type$1.TOptional<Type$1.TString>;
    message: Type$1.TOptional<Type$1.TString>;
    format: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"plain">]>>;
    options: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      value: Type$1.TUnknown;
      label: Type$1.TString;
      hint: Type$1.TOptional<Type$1.TString>;
    }>>>;
    initialValue: Type$1.TOptional<Type$1.TUnknown>;
    placeholder: Type$1.TOptional<Type$1.TString>;
    sensitive: Type$1.TOptional<Type$1.TBoolean>;
    executor: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"gateway">, Type$1.TLiteral<"client">]>>;
    externalUrl: Type$1.TOptional<Type$1.TString>;
    deviceCode: Type$1.TOptional<Type$1.TObject<{
      code: Type$1.TString;
      expiresInMinutes: Type$1.TOptional<Type$1.TInteger>;
      message: Type$1.TOptional<Type$1.TString>;
    }>>;
  }>>;
  error: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"connected">;
  authProfileId: Type$1.TString;
  links: Type$1.TArray<Type$1.TObject<{
    provider: Type$1.TString;
    authProfileId: Type$1.TString;
    updatedAt: Type$1.TInteger;
  }>>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"cancelled">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"expired">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"failed">;
  reason: Type$1.TUnion<[Type$1.TLiteral<"exchange">, Type$1.TLiteral<"identity">, Type$1.TLiteral<"authority">, Type$1.TLiteral<"unavailable">]>;
}>]>;
type UsersListModelAccountsResult = Static<typeof UsersListModelAccountsResultSchema>;
type UsersSelectModelAccountResult = Static<typeof UsersSelectModelAccountResultSchema>;
type UsersAuthConnectStartResult = Static<typeof UsersAuthConnectStartResultSchema>;
type UsersAuthConnectCatalogResult = Static<typeof UsersAuthConnectCatalogResultSchema>;
type UsersAuthConnectStatusResult = Static<typeof UsersAuthConnectStatusResultSchema>;
type UsersListAuthLinksResult = Static<typeof UsersListAuthLinksResultSchema>;
type UsersLinkAuthProfileResult = Static<typeof UsersLinkAuthProfileResultSchema>;
type UsersUnlinkAuthProfileResult = Static<typeof UsersUnlinkAuthProfileResultSchema>;
declare const UsersGitHubAuthorizeStartResultSchema: Type$1.TObject<{
  requestId: Type$1.TString;
  userCode: Type$1.TString;
  verificationUri: Type$1.TLiteral<"https://github.com/login/device">;
  expiresInMs: Type$1.TInteger;
  pollAfterMs: Type$1.TInteger;
}>;
declare const PersonalGitHubStatusSchema: Type$1.TObject<{
  state: Type$1.TUnion<[Type$1.TLiteral<"connected">, Type$1.TLiteral<"disconnected">, Type$1.TLiteral<"unavailable">]>;
  generation: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  account: Type$1.TUnion<[Type$1.TObject<{
    accountId: Type$1.TInteger;
    login: Type$1.TString;
  }>, Type$1.TNull]>;
  accessExpiresAtMs: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
  refreshState: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"refreshing">, Type$1.TLiteral<"expired">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"not_applicable">]>;
  pending: Type$1.TUnion<[Type$1.TObject<{
    requestId: Type$1.TString;
    userCode: Type$1.TString;
    verificationUri: Type$1.TLiteral<"https://github.com/login/device">;
    expiresInMs: Type$1.TInteger;
    pollAfterMs: Type$1.TInteger;
  }>, Type$1.TNull]>;
}>;
declare const UsersGitHubAuthorizePollResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"pending">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"slow_down">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"access_denied">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"expired">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"incorrect_device_code">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"network_error">;
  retryAfterMs: Type$1.TInteger;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"failed">;
  reason: Type$1.TUnion<[Type$1.TLiteral<"identity_changed">, Type$1.TLiteral<"setup_failed">]>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"success">;
  personal: Type$1.TObject<{
    state: Type$1.TUnion<[Type$1.TLiteral<"connected">, Type$1.TLiteral<"disconnected">, Type$1.TLiteral<"unavailable">]>;
    generation: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
    account: Type$1.TUnion<[Type$1.TObject<{
      accountId: Type$1.TInteger;
      login: Type$1.TString;
    }>, Type$1.TNull]>;
    accessExpiresAtMs: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
    refreshState: Type$1.TUnion<[Type$1.TLiteral<"available">, Type$1.TLiteral<"refreshing">, Type$1.TLiteral<"expired">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"not_applicable">]>;
    pending: Type$1.TUnion<[Type$1.TObject<{
      requestId: Type$1.TString;
      userCode: Type$1.TString;
      verificationUri: Type$1.TLiteral<"https://github.com/login/device">;
      expiresInMs: Type$1.TInteger;
      pollAfterMs: Type$1.TInteger;
    }>, Type$1.TNull]>;
  }>;
}>]>;
type PersonalGitHubStatus = Static<typeof PersonalGitHubStatusSchema>;
type UsersGitHubAuthorizeStartResult = Static<typeof UsersGitHubAuthorizeStartResultSchema>;
type UsersGitHubAuthorizePollResult = Static<typeof UsersGitHubAuthorizePollResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/openclaw.d.ts
declare const SystemAgentWizardCancelSchema: Type$1.TObject<{
  /** The visible step this action belongs to; stale controls must not affect a newer step. */
  stepId: Type$1.TString;
}>;
/**
 * Structured choice attached to a chat reply. Card-capable clients render the
 * options and send back `reply` (default: `label`) as the next message; text
 * clients ignore this and use the reply prose, which always stands alone.
 */
declare const SystemAgentChatQuestionSchema: Type$1.TObject<{
  id: Type$1.TString;
  header: Type$1.TString;
  question: Type$1.TString;
  options: Type$1.TArray<Type$1.TObject<{
    label: Type$1.TString;
    description: Type$1.TOptional<Type$1.TString>;
    recommended: Type$1.TOptional<Type$1.TBoolean>;
    /** Message text a client sends when this option is chosen; defaults to label. */
    reply: Type$1.TOptional<Type$1.TString>;
  }>>;
  /** Free-text answers are also accepted for this question. */
  isOther: Type$1.TOptional<Type$1.TBoolean>;
  /** Client-owned action for the visible skip control; omitted means send a reply. */
  skipAction: Type$1.TOptional<Type$1.TLiteral<"exit">>;
}>;
type SystemAgentWizardCancel = Static<typeof SystemAgentWizardCancelSchema>;
type SystemAgentChatQuestion = Static<typeof SystemAgentChatQuestionSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/cron.d.ts
/** Persisted cron job definition returned by scheduler list/get APIs. */
declare const CronJobSchema: Type$1.TObject<{
  id: Type$1.TString;
  declarationKey: Type$1.TOptional<Type$1.TString>;
  displayName: Type$1.TOptional<Type$1.TString>;
  owner: Type$1.TOptional<Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TString>;
    sessionKey: Type$1.TOptional<Type$1.TString>;
    accountId: Type$1.TOptional<Type$1.TString>;
  }>>;
  scheduledToolPolicy: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    version: Type$1.TLiteral<1>;
    mode: Type$1.TLiteral<"trusted">;
  }>, Type$1.TObject<{
    version: Type$1.TLiteral<1>;
    mode: Type$1.TLiteral<"account">;
    ownerSessionKey: Type$1.TString;
    ownerAccountId: Type$1.TString;
  }>]>>;
  agentId: Type$1.TOptional<Type$1.TString>;
  sessionKey: Type$1.TOptional<Type$1.TString>;
  name: Type$1.TString;
  description: Type$1.TOptional<Type$1.TString>;
  enabled: Type$1.TBoolean;
  deleteAfterRun: Type$1.TOptional<Type$1.TBoolean>;
  createdAtMs: Type$1.TInteger;
  updatedAtMs: Type$1.TInteger;
  /** Opaque Gateway-computed token for the job definition, excluding scheduler state. */
  configRevision: Type$1.TOptional<Type$1.TString>;
  schedule: Type$1.TUnion<[Type$1.TObject<{
    kind: Type$1.TLiteral<"at">;
    at: Type$1.TString;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"every">;
    everyMs: Type$1.TInteger;
    anchorMs: Type$1.TOptional<Type$1.TInteger>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"cron">;
    expr: Type$1.TString;
    tz: Type$1.TOptional<Type$1.TString>;
    staggerMs: Type$1.TOptional<Type$1.TInteger>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"on-exit">;
    command: Type$1.TString;
    cwd: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"stream">;
    command: Type$1.TArray<Type$1.TString>;
    cwd: Type$1.TOptional<Type$1.TString>;
    mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"line">, Type$1.TLiteral<"match">]>>;
    match: Type$1.TOptional<Type$1.TString>;
    batchMs: Type$1.TOptional<Type$1.TInteger>;
    maxBatchBytes: Type$1.TOptional<Type$1.TInteger>;
  }>]>;
  pacing: Type$1.TOptional<Type$1.TObject<{
    min: Type$1.TOptional<Type$1.TString>;
    max: Type$1.TOptional<Type$1.TString>;
  }>>;
  trigger: Type$1.TOptional<Type$1.TObject<{
    script: Type$1.TString;
    once: Type$1.TOptional<Type$1.TBoolean>;
  }>>;
  sessionTarget: Type$1.TUnion<[Type$1.TLiteral<"main">, Type$1.TLiteral<"isolated">, Type$1.TLiteral<"current">, Type$1.TString]>;
  wakeMode: Type$1.TUnion<[Type$1.TLiteral<"next-heartbeat">, Type$1.TLiteral<"now">]>;
  payload: Type$1.TUnion<[Type$1.TObject<{
    kind: Type$1.TLiteral<"systemEvent">;
    text: Type$1.TString;
    toolsAllow: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"agentTurn">;
    message: Type$1.TString;
    model: Type$1.TOptional<Type$1.TString>;
    fallbacks: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    thinking: Type$1.TOptional<Type$1.TString>;
    timeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
    allowUnsafeExternalContent: Type$1.TOptional<Type$1.TBoolean>;
    lightContext: Type$1.TOptional<Type$1.TBoolean>;
    toolsAllow: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"command">;
    argv: Type$1.TArray<Type$1.TString>;
    cwd: Type$1.TOptional<Type$1.TString>;
    env: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TString>>;
    input: Type$1.TOptional<Type$1.TString>;
    timeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
    noOutputTimeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
    outputMaxBytes: Type$1.TOptional<Type$1.TInteger>;
    toolsAllow: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"script">;
    script: Type$1.TString;
    timeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
    toolBudget: Type$1.TOptional<Type$1.TInteger>;
    toolsAllow: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
  }>, Type$1.TObject<{
    kind: Type$1.TLiteral<"heartbeat">;
  }>]>;
  delivery: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
    channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
    threadId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber]>>;
    accountId: Type$1.TOptional<Type$1.TString>;
    bestEffort: Type$1.TOptional<Type$1.TBoolean>;
    failureDestination: Type$1.TOptional<Type$1.TObject<{
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
      to: Type$1.TOptional<Type$1.TString>;
      accountId: Type$1.TOptional<Type$1.TString>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
    }>>;
    mode: Type$1.TLiteral<"none">;
    to: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
    threadId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber]>>;
    accountId: Type$1.TOptional<Type$1.TString>;
    bestEffort: Type$1.TOptional<Type$1.TBoolean>;
    failureDestination: Type$1.TOptional<Type$1.TObject<{
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
      to: Type$1.TOptional<Type$1.TString>;
      accountId: Type$1.TOptional<Type$1.TString>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
    }>>;
    mode: Type$1.TLiteral<"announce">;
    completionDestination: Type$1.TOptional<Type$1.TObject<{
      mode: Type$1.TLiteral<"webhook">;
      to: Type$1.TString;
    }>>;
    to: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
    threadId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber]>>;
    accountId: Type$1.TOptional<Type$1.TString>;
    bestEffort: Type$1.TOptional<Type$1.TBoolean>;
    failureDestination: Type$1.TOptional<Type$1.TObject<{
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
      to: Type$1.TOptional<Type$1.TString>;
      accountId: Type$1.TOptional<Type$1.TString>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
    }>>;
    mode: Type$1.TLiteral<"webhook">;
    to: Type$1.TString;
  }>]>>;
  failureAlert: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<false>, Type$1.TObject<{
    after: Type$1.TOptional<Type$1.TInteger>;
    channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>>;
    to: Type$1.TOptional<Type$1.TString>;
    cooldownMs: Type$1.TOptional<Type$1.TInteger>;
    includeSkipped: Type$1.TOptional<Type$1.TBoolean>;
    mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
    accountId: Type$1.TOptional<Type$1.TString>;
  }>]>>;
  state: Type$1.TObject<{
    lastFailureNotificationDelivered: Type$1.TOptional<Type$1.TBoolean>;
    lastFailureNotificationDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
    lastFailureNotificationDeliveryError: Type$1.TOptional<Type$1.TString>;
    lastFailureAlertAtMs: Type$1.TOptional<Type$1.TInteger>;
    lastTriggerEvalAtMs: Type$1.TOptional<Type$1.TInteger>;
    triggerEvalCount: Type$1.TOptional<Type$1.TInteger>;
    lastTriggerFireAtMs: Type$1.TOptional<Type$1.TInteger>;
    triggerState: Type$1.TOptional<Type$1.TUnknown>;
    streamStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"starting">, Type$1.TLiteral<"running">, Type$1.TLiteral<"restarting">, Type$1.TLiteral<"stopped">, Type$1.TLiteral<"disabled">, Type$1.TLiteral<"error">]>>;
    streamError: Type$1.TOptional<Type$1.TString>;
    streamConsecutiveFailures: Type$1.TOptional<Type$1.TInteger>;
    streamRestartExhausted: Type$1.TOptional<Type$1.TBoolean>;
    nextRunAtMs: Type$1.TOptional<Type$1.TInteger>;
    scheduleActivatedAtMs: Type$1.TOptional<Type$1.TInteger>;
    runningAtMs: Type$1.TOptional<Type$1.TInteger>;
    lastRunAtMs: Type$1.TOptional<Type$1.TInteger>;
    lastRunStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
    lastStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
    lastError: Type$1.TOptional<Type$1.TString>;
    lastDiagnostics: Type$1.TOptional<Type$1.TObject<{
      summary: Type$1.TOptional<Type$1.TString>;
      entries: Type$1.TArray<Type$1.TObject<{
        ts: Type$1.TInteger;
        source: Type$1.TUnion<[Type$1.TLiteral<"cron-preflight">, Type$1.TLiteral<"cron-setup">, Type$1.TLiteral<"model-preflight">, Type$1.TLiteral<"agent-run">, Type$1.TLiteral<"tool">, Type$1.TLiteral<"exec">, Type$1.TLiteral<"delivery">]>;
        severity: Type$1.TUnion<[Type$1.TLiteral<"info">, Type$1.TLiteral<"warn">, Type$1.TLiteral<"error">]>;
        message: Type$1.TString;
        toolName: Type$1.TOptional<Type$1.TString>;
        exitCode: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
        truncated: Type$1.TOptional<Type$1.TBoolean>;
      }>>;
    }>>;
    lastDiagnosticSummary: Type$1.TOptional<Type$1.TString>;
    lastErrorReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"auth_permanent">, Type$1.TLiteral<"format">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"overloaded">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"server_error">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"tls_certificate">, Type$1.TLiteral<"context_overflow">, Type$1.TLiteral<"model_not_found">, Type$1.TLiteral<"session_expired">, Type$1.TLiteral<"empty_response">, Type$1.TLiteral<"no_error_details">, Type$1.TLiteral<"unclassified">, Type$1.TLiteral<"unknown">]>>;
    lastDurationMs: Type$1.TOptional<Type$1.TInteger>;
    consecutiveErrors: Type$1.TOptional<Type$1.TInteger>;
    scheduleErrorCount: Type$1.TOptional<Type$1.TInteger>;
    autoDisabled: Type$1.TOptional<Type$1.TObject<{
      reason: Type$1.TUnion<[Type$1.TLiteral<"consecutive-failures">, Type$1.TLiteral<"schedule-errors">]>;
      atMs: Type$1.TInteger;
      consecutiveErrors: Type$1.TInteger;
    }>>;
    consecutiveSkipped: Type$1.TOptional<Type$1.TInteger>;
    lastDelivered: Type$1.TOptional<Type$1.TBoolean>;
    lastDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
    lastDeliveryError: Type$1.TOptional<Type$1.TString>;
    deliverySuppressionReason: Type$1.TOptional<Type$1.TString>;
    streamSourceIdentity: Type$1.TOptional<Type$1.TString>;
    streamDroppedBatches: Type$1.TOptional<Type$1.TInteger>;
    streamCoalescedBatches: Type$1.TOptional<Type$1.TInteger>;
    streamLastStartedAtMs: Type$1.TOptional<Type$1.TInteger>;
    streamLastExitAtMs: Type$1.TOptional<Type$1.TInteger>;
  }>;
  nextRunAtMs: Type$1.TOptional<Type$1.TInteger>;
  lastRunAtMs: Type$1.TOptional<Type$1.TInteger>;
  lastRunStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
  lastRunError: Type$1.TOptional<Type$1.TString>;
  lastDelivered: Type$1.TOptional<Type$1.TBoolean>;
  lastDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
  lastDeliveryError: Type$1.TOptional<Type$1.TString>;
  deliverySuppressionReason: Type$1.TOptional<Type$1.TString>;
  lastFailureNotificationDelivered: Type$1.TOptional<Type$1.TBoolean>;
  lastFailureNotificationDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
  lastFailureNotificationDeliveryError: Type$1.TOptional<Type$1.TString>;
}>;
/** Updates a cron job by id or legacy jobId alias. */
declare const CronUpdateParamsSchema: Type$1.TUnion<[Type$1.TObject<{
  id: Type$1.TString;
} & {
  readonly patch: Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    sessionKey: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    description: Type$1.TOptional<Type$1.TString>;
    enabled: Type$1.TOptional<Type$1.TBoolean>;
    deleteAfterRun: Type$1.TOptional<Type$1.TBoolean>;
    name: Type$1.TOptional<Type$1.TString>;
    displayName: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    schedule: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"at">;
      at: Type$1.TString;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"every">;
      everyMs: Type$1.TInteger;
      anchorMs: Type$1.TOptional<Type$1.TInteger>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"cron">;
      expr: Type$1.TString;
      tz: Type$1.TOptional<Type$1.TString>;
      staggerMs: Type$1.TOptional<Type$1.TInteger>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"on-exit">;
      command: Type$1.TString;
      cwd: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"stream">;
      command: Type$1.TArray<Type$1.TString>;
      cwd: Type$1.TOptional<Type$1.TString>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"line">, Type$1.TLiteral<"match">]>>;
      match: Type$1.TOptional<Type$1.TString>;
      batchMs: Type$1.TOptional<Type$1.TInteger>;
      maxBatchBytes: Type$1.TOptional<Type$1.TInteger>;
    }>]>>;
    pacing: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      min: Type$1.TOptional<Type$1.TString>;
      max: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TNull]>>;
    trigger: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      script: Type$1.TString;
      once: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TNull]>>;
    sessionTarget: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"main">, Type$1.TLiteral<"isolated">, Type$1.TLiteral<"current">, Type$1.TString]>>;
    wakeMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"next-heartbeat">, Type$1.TLiteral<"now">]>>;
    payload: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"systemEvent">;
      text: Type$1.TOptional<Type$1.TString>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"agentTurn">;
      message: Type$1.TOptional<Type$1.TString>;
      model: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      fallbacks: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      thinking: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      allowUnsafeExternalContent: Type$1.TOptional<Type$1.TBoolean>;
      lightContext: Type$1.TOptional<Type$1.TBoolean>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"command">;
      argv: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
      cwd: Type$1.TOptional<Type$1.TString>;
      env: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TString>>;
      input: Type$1.TOptional<Type$1.TString>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      noOutputTimeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
      outputMaxBytes: Type$1.TOptional<Type$1.TInteger>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"script">;
      script: Type$1.TOptional<Type$1.TString>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      toolBudget: Type$1.TOptional<Type$1.TInteger>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>]>>;
    delivery: Type$1.TOptional<Type$1.TObject<{
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
      threadId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber, Type$1.TNull]>>;
      accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      bestEffort: Type$1.TOptional<Type$1.TBoolean>;
      failureDestination: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
        to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
        accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
        mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">, Type$1.TNull]>>;
      }>, Type$1.TNull]>>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"none">, Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
      completionDestination: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        mode: Type$1.TLiteral<"webhook">;
        to: Type$1.TString;
      }>, Type$1.TNull]>>;
      to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    }>>;
    failureAlert: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<false>, Type$1.TObject<{
      after: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
      to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      cooldownMs: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
      includeSkipped: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TNull]>>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">, Type$1.TNull]>>;
      accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    }>, Type$1.TNull]>>;
    state: Type$1.TOptional<Type$1.TObject<{
      lastFailureNotificationDelivered: Type$1.TOptional<Type$1.TBoolean>;
      lastFailureNotificationDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
      lastFailureNotificationDeliveryError: Type$1.TOptional<Type$1.TString>;
      lastFailureAlertAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastTriggerEvalAtMs: Type$1.TOptional<Type$1.TInteger>;
      triggerEvalCount: Type$1.TOptional<Type$1.TInteger>;
      lastTriggerFireAtMs: Type$1.TOptional<Type$1.TInteger>;
      triggerState: Type$1.TOptional<Type$1.TUnknown>;
      streamStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"starting">, Type$1.TLiteral<"running">, Type$1.TLiteral<"restarting">, Type$1.TLiteral<"stopped">, Type$1.TLiteral<"disabled">, Type$1.TLiteral<"error">]>>;
      streamError: Type$1.TOptional<Type$1.TString>;
      streamConsecutiveFailures: Type$1.TOptional<Type$1.TInteger>;
      streamRestartExhausted: Type$1.TOptional<Type$1.TBoolean>;
      nextRunAtMs: Type$1.TOptional<Type$1.TInteger>;
      runningAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastRunAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastRunStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
      lastStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
      lastError: Type$1.TOptional<Type$1.TString>;
      lastErrorReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"auth_permanent">, Type$1.TLiteral<"format">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"overloaded">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"server_error">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"tls_certificate">, Type$1.TLiteral<"context_overflow">, Type$1.TLiteral<"model_not_found">, Type$1.TLiteral<"session_expired">, Type$1.TLiteral<"empty_response">, Type$1.TLiteral<"no_error_details">, Type$1.TLiteral<"unclassified">, Type$1.TLiteral<"unknown">]>>;
      lastDurationMs: Type$1.TOptional<Type$1.TInteger>;
      consecutiveErrors: Type$1.TOptional<Type$1.TInteger>;
      consecutiveSkipped: Type$1.TOptional<Type$1.TInteger>;
      lastDelivered: Type$1.TOptional<Type$1.TBoolean>;
      lastDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
      lastDeliveryError: Type$1.TOptional<Type$1.TString>;
      streamDroppedBatches: Type$1.TOptional<Type$1.TInteger>;
      streamCoalescedBatches: Type$1.TOptional<Type$1.TInteger>;
      streamLastStartedAtMs: Type$1.TOptional<Type$1.TInteger>;
      streamLastExitAtMs: Type$1.TOptional<Type$1.TInteger>;
    }>>;
  }>;
  /** Rejects the patch when the current definition does not match the caller's token. */
  readonly expectedConfigRevision: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  jobId: Type$1.TString;
} & {
  readonly patch: Type$1.TObject<{
    agentId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    sessionKey: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    description: Type$1.TOptional<Type$1.TString>;
    enabled: Type$1.TOptional<Type$1.TBoolean>;
    deleteAfterRun: Type$1.TOptional<Type$1.TBoolean>;
    name: Type$1.TOptional<Type$1.TString>;
    displayName: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    schedule: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"at">;
      at: Type$1.TString;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"every">;
      everyMs: Type$1.TInteger;
      anchorMs: Type$1.TOptional<Type$1.TInteger>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"cron">;
      expr: Type$1.TString;
      tz: Type$1.TOptional<Type$1.TString>;
      staggerMs: Type$1.TOptional<Type$1.TInteger>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"on-exit">;
      command: Type$1.TString;
      cwd: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"stream">;
      command: Type$1.TArray<Type$1.TString>;
      cwd: Type$1.TOptional<Type$1.TString>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"line">, Type$1.TLiteral<"match">]>>;
      match: Type$1.TOptional<Type$1.TString>;
      batchMs: Type$1.TOptional<Type$1.TInteger>;
      maxBatchBytes: Type$1.TOptional<Type$1.TInteger>;
    }>]>>;
    pacing: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      min: Type$1.TOptional<Type$1.TString>;
      max: Type$1.TOptional<Type$1.TString>;
    }>, Type$1.TNull]>>;
    trigger: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      script: Type$1.TString;
      once: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TNull]>>;
    sessionTarget: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"main">, Type$1.TLiteral<"isolated">, Type$1.TLiteral<"current">, Type$1.TString]>>;
    wakeMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"next-heartbeat">, Type$1.TLiteral<"now">]>>;
    payload: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"systemEvent">;
      text: Type$1.TOptional<Type$1.TString>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"agentTurn">;
      message: Type$1.TOptional<Type$1.TString>;
      model: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      fallbacks: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      thinking: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      allowUnsafeExternalContent: Type$1.TOptional<Type$1.TBoolean>;
      lightContext: Type$1.TOptional<Type$1.TBoolean>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"command">;
      argv: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
      cwd: Type$1.TOptional<Type$1.TString>;
      env: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TString>>;
      input: Type$1.TOptional<Type$1.TString>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      noOutputTimeoutSeconds: Type$1.TOptional<Type$1.TNumber>;
      outputMaxBytes: Type$1.TOptional<Type$1.TInteger>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"script">;
      script: Type$1.TOptional<Type$1.TString>;
      timeoutSeconds: Type$1.TOptional<Type$1.TUnion<[Type$1.TNumber, Type$1.TNull]>>;
      toolBudget: Type$1.TOptional<Type$1.TInteger>;
      toolsAllow: Type$1.TOptional<Type$1.TUnion<[Type$1.TArray<Type$1.TString>, Type$1.TNull]>>;
      toolsAllowIsDefault: Type$1.TOptional<Type$1.TBoolean>;
    }>]>>;
    delivery: Type$1.TOptional<Type$1.TObject<{
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
      threadId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNumber, Type$1.TNull]>>;
      accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      bestEffort: Type$1.TOptional<Type$1.TBoolean>;
      failureDestination: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
        to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
        accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
        mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">, Type$1.TNull]>>;
      }>, Type$1.TNull]>>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"none">, Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">]>>;
      completionDestination: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        mode: Type$1.TLiteral<"webhook">;
        to: Type$1.TString;
      }>, Type$1.TNull]>>;
      to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    }>>;
    failureAlert: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<false>, Type$1.TObject<{
      after: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
      channel: Type$1.TOptional<Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"last">, Type$1.TString]>, Type$1.TNull]>>;
      to: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
      cooldownMs: Type$1.TOptional<Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>>;
      includeSkipped: Type$1.TOptional<Type$1.TUnion<[Type$1.TBoolean, Type$1.TNull]>>;
      mode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"announce">, Type$1.TLiteral<"webhook">, Type$1.TNull]>>;
      accountId: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
    }>, Type$1.TNull]>>;
    state: Type$1.TOptional<Type$1.TObject<{
      lastFailureNotificationDelivered: Type$1.TOptional<Type$1.TBoolean>;
      lastFailureNotificationDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
      lastFailureNotificationDeliveryError: Type$1.TOptional<Type$1.TString>;
      lastFailureAlertAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastTriggerEvalAtMs: Type$1.TOptional<Type$1.TInteger>;
      triggerEvalCount: Type$1.TOptional<Type$1.TInteger>;
      lastTriggerFireAtMs: Type$1.TOptional<Type$1.TInteger>;
      triggerState: Type$1.TOptional<Type$1.TUnknown>;
      streamStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"starting">, Type$1.TLiteral<"running">, Type$1.TLiteral<"restarting">, Type$1.TLiteral<"stopped">, Type$1.TLiteral<"disabled">, Type$1.TLiteral<"error">]>>;
      streamError: Type$1.TOptional<Type$1.TString>;
      streamConsecutiveFailures: Type$1.TOptional<Type$1.TInteger>;
      streamRestartExhausted: Type$1.TOptional<Type$1.TBoolean>;
      nextRunAtMs: Type$1.TOptional<Type$1.TInteger>;
      runningAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastRunAtMs: Type$1.TOptional<Type$1.TInteger>;
      lastRunStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
      lastStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"error">, Type$1.TLiteral<"skipped">]>>;
      lastError: Type$1.TOptional<Type$1.TString>;
      lastErrorReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"auth_permanent">, Type$1.TLiteral<"format">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"overloaded">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"server_error">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"tls_certificate">, Type$1.TLiteral<"context_overflow">, Type$1.TLiteral<"model_not_found">, Type$1.TLiteral<"session_expired">, Type$1.TLiteral<"empty_response">, Type$1.TLiteral<"no_error_details">, Type$1.TLiteral<"unclassified">, Type$1.TLiteral<"unknown">]>>;
      lastDurationMs: Type$1.TOptional<Type$1.TInteger>;
      consecutiveErrors: Type$1.TOptional<Type$1.TInteger>;
      consecutiveSkipped: Type$1.TOptional<Type$1.TInteger>;
      lastDelivered: Type$1.TOptional<Type$1.TBoolean>;
      lastDeliveryStatus: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"delivered">, Type$1.TLiteral<"not-delivered">, Type$1.TLiteral<"unknown">, Type$1.TLiteral<"not-requested">]>>;
      lastDeliveryError: Type$1.TOptional<Type$1.TString>;
      streamDroppedBatches: Type$1.TOptional<Type$1.TInteger>;
      streamCoalescedBatches: Type$1.TOptional<Type$1.TInteger>;
      streamLastStartedAtMs: Type$1.TOptional<Type$1.TInteger>;
      streamLastExitAtMs: Type$1.TOptional<Type$1.TInteger>;
    }>>;
  }>;
  /** Rejects the patch when the current definition does not match the caller's token. */
  readonly expectedConfigRevision: Type$1.TOptional<Type$1.TString>;
}>]>;
//#endregion
//#region packages/gateway-protocol/src/schema/cron.types.d.ts
type CronJob$1 = Static<typeof CronJobSchema>;
type CronUpdateParams = Static<typeof CronUpdateParamsSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/environments.d.ts
/** Operational desktop state reported by the current native node connection. */
declare const DesktopAvailabilitySchema: Type$1.TObject<{
  state: Type$1.TUnion<[Type$1.TLiteral<"locked">, Type$1.TLiteral<"unlocked">, Type$1.TLiteral<"unknown">]>;
}>;
type DesktopAvailability = Static<typeof DesktopAvailabilitySchema>;
/** Durable lifecycle states for plugin-provisioned worker environments. */
declare const WorkerEnvironmentStateSchema: Type$1.TUnion<[Type$1.TLiteral<"requested">, Type$1.TLiteral<"provisioning">, Type$1.TLiteral<"bootstrapping">, Type$1.TLiteral<"ready">, Type$1.TLiteral<"attached">, Type$1.TLiteral<"idle">, Type$1.TLiteral<"draining">, Type$1.TLiteral<"destroying">, Type$1.TLiteral<"destroyed">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"orphaned">]>;
/** Process-local SSH tunnel connectivity for a worker environment. */
declare const WorkerTunnelStatusSchema: Type$1.TUnion<[Type$1.TLiteral<"stopped">, Type$1.TLiteral<"connecting">, Type$1.TLiteral<"connected">, Type$1.TLiteral<"reconnecting">]>;
type WorkerEnvironmentState = Static<typeof WorkerEnvironmentStateSchema>;
type WorkerTunnelStatus = Static<typeof WorkerTunnelStatusSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/devices.d.ts
/** Returns the terminal scope-upgrade state to the identity-bound waiter. */
declare const ScopeUpgradeResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"approved">;
  requestId: Type$1.TString;
  deviceToken: Type$1.TString;
  scopes: Type$1.TArray<Type$1.TString>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"rejected">;
  requestId: Type$1.TString;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"expired">;
  requestId: Type$1.TString;
}>]>;
type ScopeUpgradeResult = Static<typeof ScopeUpgradeResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/desktop.d.ts
declare const DesktopObserveResultSchema: Type$1.TObject<{
  transport: Type$1.TString;
  wsPath: Type$1.TString;
  expiresAtMs: Type$1.TInteger;
  control: Type$1.TBoolean;
  audio: Type$1.TOptional<Type$1.TObject<{
    wsPath: Type$1.TString;
    encoding: Type$1.TLiteral<"pcm-s16le">;
    sampleRate: Type$1.TLiteral<48000>;
    channels: Type$1.TLiteral<2>;
  }>>;
  audioUnavailableReason: Type$1.TOptional<Type$1.TLiteral<"setup-unavailable">>;
  canResize: Type$1.TOptional<Type$1.TBoolean>;
  vncPassword: Type$1.TOptional<Type$1.TString>;
  auth: Type$1.TOptional<Type$1.TString>;
  preauthenticated: Type$1.TOptional<Type$1.TBoolean>;
}>;
type DesktopObserveResult = Static<typeof DesktopObserveResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/human-mentions.d.ts
/** Explicit selections bound to UTF-16 offsets in the submitted message text. */
declare const HumanMentionSchema: Type$1.TObject<{
  profileId: Type$1.TString;
  start: Type$1.TInteger;
  end: Type$1.TInteger;
}>;
declare const UsersMentionableParamsSchema: Type$1.TUnion<[Type$1.TObject<{
  sessionKey: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  query: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  agentId: Type$1.TString;
  visibility: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"shared">, Type$1.TLiteral<"read-only">, Type$1.TLiteral<"suggest">, Type$1.TLiteral<"draft">]>>;
  query: Type$1.TOptional<Type$1.TString>;
}>]>;
declare const UsersMentionableResultSchema: Type$1.TObject<{
  users: Type$1.TArray<Type$1.TObject<{
    profileId: Type$1.TString;
    displayName: Type$1.TString;
    avatarUrl: Type$1.TOptional<Type$1.TString>;
    online: Type$1.TBoolean;
  }>>;
  truncated: Type$1.TBoolean;
}>;
declare const MentionsListResultSchema: Type$1.TObject<{
  gatewayInstanceId: Type$1.TString;
  revision: Type$1.TInteger;
  items: Type$1.TArray<Type$1.TObject<{
    id: Type$1.TString;
    senderProfileId: Type$1.TString;
    senderLabel: Type$1.TString;
    senderAvatarUrl: Type$1.TOptional<Type$1.TString>;
    sessionKey: Type$1.TString;
    agentId: Type$1.TString;
    sessionTitle: Type$1.TString;
    messageId: Type$1.TString;
    createdAt: Type$1.TInteger;
    expiresAt: Type$1.TInteger;
    excerpt: Type$1.TOptional<Type$1.TString>;
  }>>;
}>;
type HumanMention = Static<typeof HumanMentionSchema>;
type UsersMentionableParams = Static<typeof UsersMentionableParamsSchema>;
type UsersMentionableResult = Static<typeof UsersMentionableResultSchema>;
type MentionsListResult = Static<typeof MentionsListResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/logs-chat.d.ts
declare const AgentActivityItemSchema: Type$1.TObject<{
  itemId: Type$1.TString;
  phase: Type$1.TUnion<[Type$1.TLiteral<"start">, Type$1.TLiteral<"update">, Type$1.TLiteral<"end">]>;
  kind: Type$1.TString;
  title: Type$1.TString;
  status: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"running">, Type$1.TLiteral<"completed">, Type$1.TLiteral<"failed">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"skipped">]>>;
  name: Type$1.TOptional<Type$1.TString>;
  meta: Type$1.TOptional<Type$1.TString>;
  commandBearing: Type$1.TOptional<Type$1.TBoolean>;
  toolCallId: Type$1.TOptional<Type$1.TString>;
  startedAt: Type$1.TOptional<Type$1.TNumber>;
  endedAt: Type$1.TOptional<Type$1.TNumber>;
  error: Type$1.TOptional<Type$1.TString>;
  summary: Type$1.TOptional<Type$1.TString>;
  progressText: Type$1.TOptional<Type$1.TString>;
  suppressChannelProgress: Type$1.TOptional<Type$1.TBoolean>;
  hideFromChannelProgress: Type$1.TOptional<Type$1.TBoolean>;
  approvalId: Type$1.TOptional<Type$1.TString>;
  approvalSlug: Type$1.TOptional<Type$1.TString>;
}>;
type AgentActivityItem = Static<typeof AgentActivityItemSchema>;
declare const QUEUE_MODES: readonly ["steer", "followup", "collect", "interrupt"];
type QueueMode = (typeof QUEUE_MODES)[number];
//#endregion
//#region packages/gateway-protocol/src/schema/nodes.d.ts
declare const NodeHostStatsPayloadSchema: Type$1.TRefine<Type$1.TObject<{
  cpuCount: Type$1.TInteger;
  loadAverage: Type$1.TOptional<Type$1.TTuple<[Type$1.TNumber, Type$1.TNumber, Type$1.TNumber]>>;
  memoryTotalBytes: Type$1.TInteger;
  memoryFreeBytes: Type$1.TInteger;
  diskTotalBytes: Type$1.TOptional<Type$1.TInteger>;
  diskAvailableBytes: Type$1.TOptional<Type$1.TInteger>;
}>>;
/** Agent-visible tool descriptor advertised by a connected node. */
declare const NodePluginToolDescriptorSchema: Type$1.TObject<{
  pluginId: Type$1.TString;
  name: Type$1.TString;
  description: Type$1.TString;
  parameters: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnknown>>;
  command: Type$1.TOptional<Type$1.TString>;
  mcp: Type$1.TOptional<Type$1.TObject<{
    server: Type$1.TString;
    tool: Type$1.TString;
  }>>;
}>;
type NodePluginToolDescriptor = Static<typeof NodePluginToolDescriptorSchema>;
/** Agent-visible skill descriptor advertised by a connected node. */
declare const NodeSkillDescriptorSchema: Type$1.TObject<{
  name: Type$1.TString;
  description: Type$1.TString;
  content: Type$1.TString;
}>;
type NodeSkillDescriptor = Static<typeof NodeSkillDescriptorSchema>;
type NodeHostStatsPayload = Static<typeof NodeHostStatsPayloadSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/questions.d.ts
/** Canonical normalized question shown to an operator. */
declare const QuestionSchema: Type$1.TObject<{
  questionId: Type$1.TString;
  header: Type$1.TString;
  question: Type$1.TString;
  url: Type$1.TOptional<Type$1.TString>;
  options: Type$1.TArray<Type$1.TObject<{
    label: Type$1.TString;
    description: Type$1.TOptional<Type$1.TString>;
  }>>;
  multiSelect: Type$1.TOptional<Type$1.TBoolean>;
  isOther: Type$1.TOptional<Type$1.TBoolean>;
  isSecret: Type$1.TOptional<Type$1.TBoolean>;
  secretStore: Type$1.TOptional<Type$1.TObject<{
    name: Type$1.TString;
    kind: Type$1.TUnion<[Type$1.TLiteral<"secret">, Type$1.TLiteral<"env">]>;
    allowedHosts: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    reason: Type$1.TOptional<Type$1.TString>;
  }>>;
  secretStoreExisting: Type$1.TOptional<Type$1.TObject<{
    updatedAtMs: Type$1.TInteger;
    updatedBy: Type$1.TOptional<Type$1.TString>;
  }>>;
}>;
declare const QuestionAnswersSchema: Type$1.TObject<{
  answers: Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>;
}>;
/**
 * One pending or recently resolved transient question request. Flat object with
 * optional terminal fields (exec-approval record precedent): native protocol
 * codegen cannot emit per-status object unions, and the manager owns the
 * status/answers invariant (answers present only when status is "answered").
 */
declare const QuestionRecordSchema: Type$1.TObject<{
  id: Type$1.TString;
  questions: Type$1.TArray<Type$1.TObject<{
    questionId: Type$1.TString;
    header: Type$1.TString;
    question: Type$1.TString;
    url: Type$1.TOptional<Type$1.TString>;
    options: Type$1.TArray<Type$1.TObject<{
      label: Type$1.TString;
      description: Type$1.TOptional<Type$1.TString>;
    }>>;
    multiSelect: Type$1.TOptional<Type$1.TBoolean>;
    isOther: Type$1.TOptional<Type$1.TBoolean>;
    isSecret: Type$1.TOptional<Type$1.TBoolean>;
    secretStore: Type$1.TOptional<Type$1.TObject<{
      name: Type$1.TString;
      kind: Type$1.TUnion<[Type$1.TLiteral<"secret">, Type$1.TLiteral<"env">]>;
      allowedHosts: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
      reason: Type$1.TOptional<Type$1.TString>;
    }>>;
    secretStoreExisting: Type$1.TOptional<Type$1.TObject<{
      updatedAtMs: Type$1.TInteger;
      updatedBy: Type$1.TOptional<Type$1.TString>;
    }>>;
  }>>;
  agentId: Type$1.TOptional<Type$1.TString>;
  sessionKey: Type$1.TOptional<Type$1.TString>;
  runId: Type$1.TOptional<Type$1.TString>;
  createdAtMs: Type$1.TInteger;
  expiresAtMs: Type$1.TInteger;
  status: Type$1.TUnion<[Type$1.TLiteral<"pending">, Type$1.TLiteral<"answered">, Type$1.TLiteral<"cancelled">, Type$1.TLiteral<"expired">]>;
  answers: Type$1.TOptional<Type$1.TObject<{
    answers: Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>;
  }>>;
  resolvedBy: Type$1.TOptional<Type$1.TString>;
}>;
declare const QuestionWaitAnswerResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"pending">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"answered">;
  answers: Type$1.TObject<{
    answers: Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>;
  }>;
  resolutionId: Type$1.TOptional<Type$1.TString>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"cancelled">;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"expired">;
}>]>;
declare const QuestionResolveResultSchema: Type$1.TUnion<[Type$1.TObject<{
  status: Type$1.TLiteral<"answered">;
  answers: Type$1.TObject<{
    answers: Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>;
  }>;
}>, Type$1.TObject<{
  status: Type$1.TLiteral<"cancelled">;
}>]>;
declare const QuestionResolvedEventSchema: Type$1.TUnion<[Type$1.TObject<{
  id: Type$1.TString;
  status: Type$1.TLiteral<"answered">;
  answers: Type$1.TObject<{
    answers: Type$1.TRecord<"^.*$", Type$1.TArray<Type$1.TString>>;
  }>;
}>, Type$1.TObject<{
  id: Type$1.TString;
  status: Type$1.TLiteral<"cancelled">;
}>, Type$1.TObject<{
  id: Type$1.TString;
  status: Type$1.TLiteral<"expired">;
}>]>;
type Question = Static<typeof QuestionSchema>;
type QuestionAnswers = Static<typeof QuestionAnswersSchema>;
type QuestionRecord = Static<typeof QuestionRecordSchema>;
type QuestionWaitAnswerResult = Static<typeof QuestionWaitAnswerResultSchema>;
type QuestionResolveResult = Static<typeof QuestionResolveResultSchema>;
type QuestionResolvedEvent = Static<typeof QuestionResolvedEventSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/sessions.d.ts
/** Live session status judgment broadcast to subscribed operator clients. */
declare const SessionObserverDigestSchema: Type$1.TObject<{
  sessionKey: Type$1.TString;
  agentId: Type$1.TOptional<Type$1.TString>;
  sessionId: Type$1.TOptional<Type$1.TString>;
  lifecycleRevision: Type$1.TOptional<Type$1.TString>;
  runId: Type$1.TOptional<Type$1.TString>;
  revision: Type$1.TInteger;
  updatedAt: Type$1.TInteger;
  headline: Type$1.TString;
  assessment: Type$1.TOptional<Type$1.TString>;
  health: Type$1.TUnion<[Type$1.TLiteral<"on-track">, Type$1.TLiteral<"grinding">, Type$1.TLiteral<"stuck">, Type$1.TLiteral<"waiting-on-user">, Type$1.TLiteral<"wrapping-up">, Type$1.TLiteral<"done">, Type$1.TLiteral<"failed">]>;
  planProgress: Type$1.TOptional<Type$1.TObject<{
    completed: Type$1.TInteger;
    total: Type$1.TInteger;
  }>>;
}>;
/** One bounded question/answer exchange in the ephemeral session companion. */
declare const SessionCompanionExchangeSchema: Type$1.TObject<{
  question: Type$1.TString;
  answer: Type$1.TString;
  ts: Type$1.TInteger;
}>;
/** Current bounded exchanges for one session companion thread. */
declare const SessionsCompanionStateResultSchema: Type$1.TObject<{
  exchanges: Type$1.TArray<Type$1.TObject<{
    question: Type$1.TString;
    answer: Type$1.TString;
    ts: Type$1.TInteger;
  }>>;
}>;
type SessionObserverDigest = Static<typeof SessionObserverDigestSchema>;
type SessionCompanionExchange = Static<typeof SessionCompanionExchangeSchema>;
type SessionsCompanionStateResult = Static<typeof SessionsCompanionStateResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/snapshot.d.ts
/**
 * Gateway state snapshot schemas.
 *
 * Snapshots are sent during hello and later event streams; they summarize node
 * presence, health, session defaults, and version counters for clients.
 */
/** One gateway-visible presence record for a node/client/runtime. */
declare const PresenceEntrySchema: Type$1.TObject<{
  /** Gateway-assigned id for this connection; changes after reconnect. */
  connectionId: Type$1.TOptional<Type$1.TString>;
  host: Type$1.TOptional<Type$1.TString>;
  clientId: Type$1.TOptional<Type$1.TString>;
  ip: Type$1.TOptional<Type$1.TString>;
  version: Type$1.TOptional<Type$1.TString>;
  platform: Type$1.TOptional<Type$1.TString>;
  deviceFamily: Type$1.TOptional<Type$1.TString>;
  modelIdentifier: Type$1.TOptional<Type$1.TString>;
  timeZone: Type$1.TOptional<Type$1.TString>;
  mode: Type$1.TOptional<Type$1.TString>;
  lastInputSeconds: Type$1.TOptional<Type$1.TInteger>;
  reason: Type$1.TOptional<Type$1.TString>;
  tags: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  text: Type$1.TOptional<Type$1.TString>;
  /** Heartbeat freshness, not online duration or user activity. */
  ts: Type$1.TInteger;
  /** Server timestamps for the person's continuous online interval and last accepted activity. */
  onlineSince: Type$1.TOptional<Type$1.TInteger>;
  lastActivityAt: Type$1.TOptional<Type$1.TInteger>;
  /** Latest accepted OpenClaw interaction on this connection, independent of person timing. */
  connectionLastActivityAt: Type$1.TOptional<Type$1.TInteger>;
  deviceId: Type$1.TOptional<Type$1.TString>;
  roles: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  scopes: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  instanceId: Type$1.TOptional<Type$1.TString>;
  user: Type$1.TOptional<Type$1.TObject<{
    /** Canonical profile id when resolved, otherwise authenticated identity; grouping also uses identity qualification. */
    id: Type$1.TString;
    identity: Type$1.TOptional<Type$1.TObject<{
      type: Type$1.TLiteral<"profile">;
      id: Type$1.TString;
    }>>;
    email: Type$1.TOptional<Type$1.TString>;
    name: Type$1.TOptional<Type$1.TString>;
    avatarUrl: Type$1.TOptional<Type$1.TString>;
  }>>;
  /** Sessions this connection declares it is viewing, independent of transport subscriptions. Sorted lexicographically. */
  watchedSessions: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
}>;
/** Initial and incremental gateway state snapshot payload. */
declare const SnapshotSchema: Type$1.TObject<{
  suspension: Type$1.TOptional<Type$1.TObject<{
    phase: Type$1.TUnion<[Type$1.TLiteral<"accepting">, Type$1.TLiteral<"preparing">, Type$1.TLiteral<"draining">, Type$1.TLiteral<"prepared">]>;
  }>>;
  presence: Type$1.TArray<Type$1.TObject<{
    /** Gateway-assigned id for this connection; changes after reconnect. */
    connectionId: Type$1.TOptional<Type$1.TString>;
    host: Type$1.TOptional<Type$1.TString>;
    clientId: Type$1.TOptional<Type$1.TString>;
    ip: Type$1.TOptional<Type$1.TString>;
    version: Type$1.TOptional<Type$1.TString>;
    platform: Type$1.TOptional<Type$1.TString>;
    deviceFamily: Type$1.TOptional<Type$1.TString>;
    modelIdentifier: Type$1.TOptional<Type$1.TString>;
    timeZone: Type$1.TOptional<Type$1.TString>;
    mode: Type$1.TOptional<Type$1.TString>;
    lastInputSeconds: Type$1.TOptional<Type$1.TInteger>;
    reason: Type$1.TOptional<Type$1.TString>;
    tags: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    text: Type$1.TOptional<Type$1.TString>;
    /** Heartbeat freshness, not online duration or user activity. */
    ts: Type$1.TInteger;
    /** Server timestamps for the person's continuous online interval and last accepted activity. */
    onlineSince: Type$1.TOptional<Type$1.TInteger>;
    lastActivityAt: Type$1.TOptional<Type$1.TInteger>;
    /** Latest accepted OpenClaw interaction on this connection, independent of person timing. */
    connectionLastActivityAt: Type$1.TOptional<Type$1.TInteger>;
    deviceId: Type$1.TOptional<Type$1.TString>;
    roles: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    scopes: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    instanceId: Type$1.TOptional<Type$1.TString>;
    user: Type$1.TOptional<Type$1.TObject<{
      /** Canonical profile id when resolved, otherwise authenticated identity; grouping also uses identity qualification. */
      id: Type$1.TString;
      identity: Type$1.TOptional<Type$1.TObject<{
        type: Type$1.TLiteral<"profile">;
        id: Type$1.TString;
      }>>;
      email: Type$1.TOptional<Type$1.TString>;
      name: Type$1.TOptional<Type$1.TString>;
      avatarUrl: Type$1.TOptional<Type$1.TString>;
    }>>;
    /** Sessions this connection declares it is viewing, independent of transport subscriptions. Sorted lexicographically. */
    watchedSessions: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  }>>;
  health: Type$1.TObject<{
    ok: Type$1.TOptional<Type$1.TLiteral<true>>;
    ts: Type$1.TOptional<Type$1.TInteger>;
    durationMs: Type$1.TOptional<Type$1.TInteger>;
    eventLoop: Type$1.TOptional<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>;
        otherThreadsCoreRatio: Type$1.TOptional<Type$1.TNumber>;
        hostUtilization: Type$1.TOptional<Type$1.TNumber>;
        hostCpuCount: Type$1.TOptional<Type$1.TInteger>;
      }>>;
    }>>;
    plugins: Type$1.TOptional<Type$1.TObject<{
      loaded: Type$1.TArray<Type$1.TString>;
      errors: Type$1.TArray<Type$1.TObject<{
        id: Type$1.TString;
        origin: Type$1.TString;
        activated: Type$1.TBoolean;
        activationSource: Type$1.TOptional<Type$1.TString>;
        activationReason: Type$1.TOptional<Type$1.TString>;
        failurePhase: Type$1.TOptional<Type$1.TString>;
        error: Type$1.TString;
      }>>;
      unavailable: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        id: Type$1.TString;
        state: Type$1.TLiteral<"configured-unavailable">;
        diagnostic: Type$1.TObject<{
          kind: Type$1.TLiteral<"plugin-verification">;
          reason: Type$1.TString;
          detail: Type$1.TString;
        }>;
      }>>>;
    }>>;
    contextEngines: Type$1.TOptional<Type$1.TObject<{
      quarantined: Type$1.TArray<Type$1.TObject<{
        engineId: Type$1.TString;
        owner: Type$1.TOptional<Type$1.TString>;
        operation: Type$1.TString;
        reason: Type$1.TString;
        failedAt: Type$1.TInteger;
      }>>;
    }>>;
    deliveryQueues: Type$1.TOptional<Type$1.TObject<{
      failed: Type$1.TArray<Type$1.TObject<{
        queueName: Type$1.TString;
        count: Type$1.TInteger;
        oldestFailedAt: Type$1.TOptional<Type$1.TInteger>;
      }>>;
      ingressFailed: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        channelId: Type$1.TString;
        accountId: Type$1.TString;
        count: Type$1.TInteger;
        oldestFailedAt: Type$1.TOptional<Type$1.TInteger>;
      }>>>;
      ingressPressure: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
        channelId: Type$1.TString;
        accountId: Type$1.TString;
        laneCount: Type$1.TInteger;
        pendingCount: Type$1.TInteger;
        claimedCount: Type$1.TInteger;
        blockedCount: Type$1.TInteger;
        oldestReceivedAt: Type$1.TInteger;
      }>>>;
    }>>;
    modelPricing: Type$1.TOptional<Type$1.TObject<{
      state: Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"degraded">, Type$1.TLiteral<"disabled">]>;
      sources: Type$1.TArray<Type$1.TObject<{
        source: Type$1.TUnion<[Type$1.TLiteral<"openrouter">, Type$1.TLiteral<"litellm">, Type$1.TLiteral<"bootstrap">, Type$1.TLiteral<"refresh">]>;
        state: Type$1.TUnion<[Type$1.TLiteral<"ok">, Type$1.TLiteral<"degraded">]>;
        lastFailureAt: Type$1.TOptional<Type$1.TInteger>;
        detail: Type$1.TOptional<Type$1.TString>;
      }>>;
      lastFailureAt: Type$1.TOptional<Type$1.TInteger>;
      detail: Type$1.TOptional<Type$1.TString>;
    }>>;
    configReload: Type$1.TOptional<Type$1.TObject<{
      hotReloadStatus: Type$1.TUnion<[Type$1.TLiteral<"active">, Type$1.TLiteral<"disabled">]>;
    }>>;
    childRuntime: Type$1.TOptional<Type$1.TObject<{
      execPath: Type$1.TString;
      available: Type$1.TBoolean;
    }>>;
    channels: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TUnknown>>;
    channelOrder: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    channelLabels: Type$1.TOptional<Type$1.TRecord<"^.*$", Type$1.TString>>;
    heartbeatSeconds: Type$1.TOptional<Type$1.TInteger>;
    defaultAgentId: Type$1.TOptional<Type$1.TString>;
    agents: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      agentId: Type$1.TString;
      name: Type$1.TOptional<Type$1.TString>;
      isDefault: Type$1.TBoolean;
      heartbeat: Type$1.TObject<{
        enabled: Type$1.TBoolean;
        every: Type$1.TString;
        everyMs: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
        prompt: Type$1.TString;
        target: Type$1.TString;
        model: Type$1.TOptional<Type$1.TString>;
        session: Type$1.TOptional<Type$1.TString>;
        ackMaxChars: Type$1.TInteger;
      }>;
      sessions: Type$1.TObject<{
        path: Type$1.TString;
        count: Type$1.TInteger;
        recent: Type$1.TArray<Type$1.TObject<{
          key: Type$1.TString;
          updatedAt: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
          age: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
        }>>;
      }>;
    }>>>;
    sessions: Type$1.TOptional<Type$1.TObject<{
      path: Type$1.TString;
      count: Type$1.TInteger;
      recent: Type$1.TArray<Type$1.TObject<{
        key: Type$1.TString;
        updatedAt: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
        age: Type$1.TUnion<[Type$1.TInteger, Type$1.TNull]>;
      }>>;
    }>>;
  }>;
  stateVersion: Type$1.TObject<{
    presence: Type$1.TInteger;
    health: Type$1.TInteger;
  }>;
  uptimeMs: Type$1.TInteger;
  /** Resolved source-config revision accepted by the active Gateway runtime. */
  appliedConfigHash: Type$1.TOptional<Type$1.TUnion<[Type$1.TString, Type$1.TNull]>>;
  configPath: Type$1.TOptional<Type$1.TString>;
  stateDir: Type$1.TOptional<Type$1.TString>;
  sessionDefaults: Type$1.TOptional<Type$1.TObject<{
    defaultAgentId: Type$1.TString;
    modelConfigured: Type$1.TOptional<Type$1.TBoolean>;
    ownership: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"sole">, Type$1.TLiteral<"legacy">, Type$1.TLiteral<"explicit">]>>;
    selectionRequired: Type$1.TOptional<Type$1.TBoolean>;
    mainKey: Type$1.TString;
    mainSessionKey: Type$1.TString;
    scope: Type$1.TOptional<Type$1.TString>;
  }>>;
  /** Credential-free browser sign-in endpoint advertised to authenticated operators. */
  controlUiIdentityUrl: Type$1.TOptional<Type$1.TString>;
  authMode: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"none">, Type$1.TLiteral<"token">, Type$1.TLiteral<"password">, Type$1.TLiteral<"trusted-proxy">]>>;
  updateAvailable: Type$1.TOptional<Type$1.TObject<{
    currentVersion: Type$1.TString;
    latestVersion: Type$1.TString;
    channel: Type$1.TString;
    currentSha: Type$1.TOptional<Type$1.TString>;
    upstreamRef: Type$1.TOptional<Type$1.TString>;
    upstreamSha: Type$1.TOptional<Type$1.TString>;
    repositoryUrl: Type$1.TOptional<Type$1.TString>;
    commitsBehind: Type$1.TOptional<Type$1.TInteger>;
    commits: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      sha: Type$1.TString;
      subject: Type$1.TString;
    }>>>;
  }>>;
  updateSchedule: Type$1.TOptional<Type$1.TObject<{
    channel: Type$1.TString;
    autoEnabled: Type$1.TBoolean;
    install: Type$1.TOptional<Type$1.TObject<{
      kind: Type$1.TUnion<[Type$1.TLiteral<"package">, Type$1.TLiteral<"git">, Type$1.TLiteral<"unknown">]>;
      git: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
        currentSha: Type$1.TOptional<Type$1.TString>;
        upstreamSha: Type$1.TOptional<Type$1.TString>;
        repositoryUrl: Type$1.TOptional<Type$1.TString>;
        commitAtMs: Type$1.TOptional<Type$1.TInteger>;
        installedAtMs: Type$1.TOptional<Type$1.TInteger>;
        status: Type$1.TLiteral<"current">;
      }>, Type$1.TObject<{
        currentSha: Type$1.TOptional<Type$1.TString>;
        upstreamSha: Type$1.TOptional<Type$1.TString>;
        repositoryUrl: Type$1.TOptional<Type$1.TString>;
        commitAtMs: Type$1.TOptional<Type$1.TInteger>;
        installedAtMs: Type$1.TOptional<Type$1.TInteger>;
        status: Type$1.TLiteral<"behind">;
        commitsBehind: Type$1.TInteger;
      }>, Type$1.TObject<{
        currentSha: Type$1.TOptional<Type$1.TString>;
        upstreamSha: Type$1.TOptional<Type$1.TString>;
        repositoryUrl: Type$1.TOptional<Type$1.TString>;
        commitAtMs: Type$1.TOptional<Type$1.TInteger>;
        installedAtMs: Type$1.TOptional<Type$1.TInteger>;
        status: Type$1.TLiteral<"ahead">;
        commitsAhead: Type$1.TInteger;
      }>, Type$1.TObject<{
        currentSha: Type$1.TOptional<Type$1.TString>;
        upstreamSha: Type$1.TOptional<Type$1.TString>;
        repositoryUrl: Type$1.TOptional<Type$1.TString>;
        commitAtMs: Type$1.TOptional<Type$1.TInteger>;
        installedAtMs: Type$1.TOptional<Type$1.TInteger>;
        status: Type$1.TLiteral<"diverged">;
        commitsAhead: Type$1.TInteger;
        commitsBehind: Type$1.TInteger;
      }>, Type$1.TObject<{
        currentSha: Type$1.TOptional<Type$1.TString>;
        upstreamSha: Type$1.TOptional<Type$1.TString>;
        repositoryUrl: Type$1.TOptional<Type$1.TString>;
        commitAtMs: Type$1.TOptional<Type$1.TInteger>;
        installedAtMs: Type$1.TOptional<Type$1.TInteger>;
        status: Type$1.TLiteral<"unavailable">;
        reason: Type$1.TUnion<[Type$1.TLiteral<"fetch-failed">, Type$1.TLiteral<"no-upstream">, Type$1.TLiteral<"no-upstream-sha">, Type$1.TLiteral<"comparison-failed">, Type$1.TLiteral<"git-unavailable">]>;
      }>]>>;
    }>>;
    target: Type$1.TOptional<Type$1.TUnion<[Type$1.TObject<{
      kind: Type$1.TLiteral<"package">;
      version: Type$1.TString;
    }>, Type$1.TObject<{
      kind: Type$1.TLiteral<"git">;
      upstreamRef: Type$1.TString;
      upstreamSha: Type$1.TString;
      commitsBehind: Type$1.TInteger;
    }>]>>;
    campaign: Type$1.TOptional<Type$1.TObject<{
      id: Type$1.TString;
      state: Type$1.TUnion<[Type$1.TLiteral<"waiting-for-idle">, Type$1.TLiteral<"countdown">, Type$1.TLiteral<"applying">]>;
      announcedAtMs: Type$1.TInteger;
      applyAtMs: Type$1.TOptional<Type$1.TInteger>;
      holdUntilMs: Type$1.TOptional<Type$1.TInteger>;
      forceAtMs: Type$1.TInteger;
      updatedAtMs: Type$1.TInteger;
    }>>;
  }>>;
}>;
type Snapshot = Static<typeof SnapshotSchema>;
type PresenceEntry = Static<typeof PresenceEntrySchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/terminal.d.ts
/** Absolute temporary path pasted into the active terminal after upload. */
declare const TerminalUploadResultSchema: Type$1.TObject<{
  path: Type$1.TString;
  size: Type$1.TInteger;
  /** Explicit path insertion contract for a native CLI rather than a shell. */
  uploadPathStyle: Type$1.TOptional<Type$1.TLiteral<"native">>;
}>;
type TerminalUploadResult$1 = Static<typeof TerminalUploadResultSchema>;
type TerminalUploadPathStyle = NonNullable<TerminalUploadResult$1["uploadPathStyle"]>;
//#endregion
//#region packages/gateway-protocol/src/schema/portals.d.ts
declare const PortalSummarySchema: Type$1.TObject<{
  id: Type$1.TString;
  title: Type$1.TString;
  port: Type$1.TInteger;
  listenPort: Type$1.TInteger;
  publicUrl: Type$1.TString;
  path: Type$1.TOptional<Type$1.TString>;
  description: Type$1.TOptional<Type$1.TString>;
  origin: Type$1.TOptional<Type$1.TString>;
  createdAtMs: Type$1.TInteger;
  tokenQuery: Type$1.TOptional<Type$1.TString>;
  url: Type$1.TOptional<Type$1.TString>;
}>;
declare const PortalOpenResultSchema: Type$1.TObject<{
  id: Type$1.TString;
  title: Type$1.TString;
  port: Type$1.TInteger;
  listenPort: Type$1.TInteger;
  publicUrl: Type$1.TString;
  path: Type$1.TOptional<Type$1.TString>;
  description: Type$1.TOptional<Type$1.TString>;
  origin: Type$1.TOptional<Type$1.TString>;
  createdAtMs: Type$1.TInteger;
  tokenQuery: Type$1.TString;
  url: Type$1.TString;
}>;
type PortalSummary = Static<typeof PortalSummarySchema>;
type PortalOpenResult = Static<typeof PortalOpenResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/wizard.d.ts
/** Client answer payload for the current wizard step. */
declare const WizardAnswerSchema: Type$1.TObject<{
  stepId: Type$1.TString;
  value: Type$1.TOptional<Type$1.TUnknown>;
}>;
/** UI contract for one wizard step rendered by gateway clients. */
declare const WizardStepSchema: Type$1.TObject<{
  id: Type$1.TString;
  type: Type$1.TUnion<[Type$1.TLiteral<"note">, Type$1.TLiteral<"select">, Type$1.TLiteral<"text">, Type$1.TLiteral<"confirm">, Type$1.TLiteral<"multiselect">, Type$1.TLiteral<"progress">, Type$1.TLiteral<"action">]>;
  title: Type$1.TOptional<Type$1.TString>;
  message: Type$1.TOptional<Type$1.TString>;
  format: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"plain">]>>;
  options: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    value: Type$1.TUnknown;
    label: Type$1.TString;
    hint: Type$1.TOptional<Type$1.TString>;
  }>>>;
  initialValue: Type$1.TOptional<Type$1.TUnknown>;
  placeholder: Type$1.TOptional<Type$1.TString>;
  sensitive: Type$1.TOptional<Type$1.TBoolean>;
  executor: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"gateway">, Type$1.TLiteral<"client">]>>;
  externalUrl: Type$1.TOptional<Type$1.TString>;
  deviceCode: Type$1.TOptional<Type$1.TObject<{
    code: Type$1.TString;
    expiresInMinutes: Type$1.TOptional<Type$1.TInteger>;
    message: Type$1.TOptional<Type$1.TString>;
  }>>;
}>;
/** Result after advancing a wizard session. */
declare const WizardNextResultSchema: Type$1.TObject<{
  done: Type$1.TBoolean;
  step: Type$1.TOptional<Type$1.TObject<{
    id: Type$1.TString;
    type: Type$1.TUnion<[Type$1.TLiteral<"note">, Type$1.TLiteral<"select">, Type$1.TLiteral<"text">, Type$1.TLiteral<"confirm">, Type$1.TLiteral<"multiselect">, Type$1.TLiteral<"progress">, Type$1.TLiteral<"action">]>;
    title: Type$1.TOptional<Type$1.TString>;
    message: Type$1.TOptional<Type$1.TString>;
    format: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"plain">]>>;
    options: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      value: Type$1.TUnknown;
      label: Type$1.TString;
      hint: Type$1.TOptional<Type$1.TString>;
    }>>>;
    initialValue: Type$1.TOptional<Type$1.TUnknown>;
    placeholder: Type$1.TOptional<Type$1.TString>;
    sensitive: Type$1.TOptional<Type$1.TBoolean>;
    executor: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"gateway">, Type$1.TLiteral<"client">]>>;
    externalUrl: Type$1.TOptional<Type$1.TString>;
    deviceCode: Type$1.TOptional<Type$1.TObject<{
      code: Type$1.TString;
      expiresInMinutes: Type$1.TOptional<Type$1.TInteger>;
      message: Type$1.TOptional<Type$1.TString>;
    }>>;
  }>>;
  status: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"running">, Type$1.TLiteral<"done">, Type$1.TLiteral<"cancelled">, Type$1.TLiteral<"error">]>>;
  error: Type$1.TOptional<Type$1.TString>;
  channels: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  accounts: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
    channel: Type$1.TString;
    accountId: Type$1.TString;
  }>>>;
  preparedModelRef: Type$1.TOptional<Type$1.TString>;
  modelActivation: Type$1.TOptional<Type$1.TObject<{
    modelRef: Type$1.TString;
    modelTarget: Type$1.TOptional<Type$1.TLiteral<"utility">>;
    gatewayRestartRequired: Type$1.TOptional<Type$1.TLiteral<true>>;
  }>>;
  activationRejection: Type$1.TOptional<Type$1.TObject<{
    disposition: Type$1.TLiteral<"rejected-before-promotion">;
    status: Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"format">, Type$1.TLiteral<"unavailable">, Type$1.TLiteral<"unknown">]>;
  }>>;
}>;
type WizardAnswer = Static<typeof WizardAnswerSchema>;
type WizardStep$1 = Static<typeof WizardStepSchema>;
type WizardNextResult$1 = Static<typeof WizardNextResultSchema>;
//#endregion
//#region packages/gateway-protocol/src/schema/worker-protocol-primitives.d.ts
declare const WorkerIdentifierSchema: Type$1.TString;
declare const WorkerAdmissionFailureReasonSchema: Type$1.TUnion<[Type$1.TLiteral<"invalid-credential">, Type$1.TLiteral<"credential-expired">, Type$1.TLiteral<"environment-mismatch">, Type$1.TLiteral<"environment-unavailable">, Type$1.TLiteral<"bundle-mismatch">, Type$1.TLiteral<"version-mismatch">, Type$1.TLiteral<"session-mismatch">, Type$1.TLiteral<"placement-mismatch">, Type$1.TLiteral<"owner-epoch-mismatch">, Type$1.TLiteral<"rpc-set-mismatch">, Type$1.TLiteral<"protocol-features-mismatch">]>;
declare const WorkerProtocolCloseReasonSchema: Type$1.TUnion<[Type$1.TUnion<[Type$1.TLiteral<"invalid-credential">, Type$1.TLiteral<"credential-expired">, Type$1.TLiteral<"environment-mismatch">, Type$1.TLiteral<"environment-unavailable">, Type$1.TLiteral<"bundle-mismatch">, Type$1.TLiteral<"version-mismatch">, Type$1.TLiteral<"session-mismatch">, Type$1.TLiteral<"placement-mismatch">, Type$1.TLiteral<"owner-epoch-mismatch">, Type$1.TLiteral<"rpc-set-mismatch">, Type$1.TLiteral<"protocol-features-mismatch">]>, Type$1.TLiteral<"admission-rejected">, Type$1.TLiteral<"invalid-handshake">, Type$1.TLiteral<"protocol-mismatch">, Type$1.TLiteral<"gateway-unavailable">, Type$1.TLiteral<"invalid-frame">, Type$1.TLiteral<"slow-consumer">, Type$1.TLiteral<"method-not-allowed">, Type$1.TLiteral<"invalid-heartbeat">, Type$1.TLiteral<"credential-replaced">, Type$1.TLiteral<"gateway-shutdown">]>;
declare const LiveIntegerSchema: Type$1.TInteger;
declare const LiveSequenceSchema: Type$1.TInteger;
//#endregion
//#region packages/gateway-protocol/src/schema/worker-admission.d.ts
/** Build identity presented by a worker before the gateway admits it. */
declare const WorkerAdmissionHandshakeSchema: Type$1.TObject<{
  bundleHash: Type$1.TString;
  openclawVersion: Type$1.TString;
  protocolFeatures: Type$1.TArray<Type$1.TString>;
  bundlePrewarm: Type$1.TOptional<Type$1.TInteger>;
}>;
/** Dedicated first-frame payload accepted only on the worker ingress. */
declare const WorkerConnectParamsSchema: Type$1.TObject<{
  minProtocol: Type$1.TInteger;
  maxProtocol: Type$1.TInteger;
  client: Type$1.TObject<{
    id: Type$1.TLiteral<"openclaw-worker">;
    version: Type$1.TString;
    platform: Type$1.TString;
    mode: Type$1.TLiteral<"worker">;
  }>;
  role: Type$1.TLiteral<"worker">;
  admission: Type$1.TUnion<[Type$1.TObject<{
    environmentId: Type$1.TString;
    credential: Type$1.TString;
    ownerEpoch: Type$1.TInteger;
    rpcSetVersion: Type$1.TInteger;
    handshake: Type$1.TObject<{
      bundleHash: Type$1.TString;
      openclawVersion: Type$1.TString;
      protocolFeatures: Type$1.TArray<Type$1.TString>;
      bundlePrewarm: Type$1.TOptional<Type$1.TInteger>;
    }>;
    sessionId: Type$1.TNull;
    runId: Type$1.TNull;
  }>, Type$1.TObject<{
    environmentId: Type$1.TString;
    credential: Type$1.TString;
    ownerEpoch: Type$1.TInteger;
    rpcSetVersion: Type$1.TInteger;
    handshake: Type$1.TObject<{
      bundleHash: Type$1.TString;
      openclawVersion: Type$1.TString;
      protocolFeatures: Type$1.TArray<Type$1.TString>;
      bundlePrewarm: Type$1.TOptional<Type$1.TInteger>;
    }>;
    sessionId: Type$1.TString;
    runId: Type$1.TString;
  }>]>;
}>;
declare const WorkerSessionsSpawnParamsSchema: Type$1.TObject<{
  toolCallId: Type$1.TString;
  task: Type$1.TString;
  label: Type$1.TOptional<Type$1.TString>;
  agentId: Type$1.TOptional<Type$1.TString>;
  model: Type$1.TOptional<Type$1.TString>;
  runTimeoutSeconds: Type$1.TOptional<Type$1.TInteger>;
}>;
declare const WorkerSessionsSendParamsSchema: Type$1.TObject<{
  toolCallId: Type$1.TString;
  sessionKey: Type$1.TString;
  message: Type$1.TString;
  timeoutSeconds: Type$1.TOptional<Type$1.TInteger>;
}>;
declare const WorkerPortalParamsSchema: Type$1.TObject<{
  toolCallId: Type$1.TString;
  action: Type$1.TUnion<[Type$1.TLiteral<"open">, Type$1.TLiteral<"list">, Type$1.TLiteral<"close">]>;
  port: Type$1.TOptional<Type$1.TInteger>;
  title: Type$1.TOptional<Type$1.TString>;
  description: Type$1.TOptional<Type$1.TString>;
  path: Type$1.TOptional<Type$1.TString>;
  id: Type$1.TOptional<Type$1.TString>;
}>;
declare const WorkerPresenceParamsSchema: Type$1.TObject<{
  action: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"list">, Type$1.TLiteral<"person">, Type$1.TLiteral<"device">]>>;
  person: Type$1.TOptional<Type$1.TString>;
  deviceId: Type$1.TOptional<Type$1.TString>;
  include: Type$1.TOptional<Type$1.TArray<Type$1.TUnion<[Type$1.TLiteral<"devices">, Type$1.TLiteral<"network">, Type$1.TLiteral<"location">]>>>;
  limit: Type$1.TOptional<Type$1.TInteger>;
  toolCallId: Type$1.TString;
}>;
declare const WorkerSessionToolResultSchema: Type$1.TObject<{
  resultJson: Type$1.TString;
}>;
declare const WorkerTranscriptCommitParamsSchema: Type$1.TObject<{
  runEpoch: Type$1.TInteger;
  seq: Type$1.TInteger;
  baseLeafId: Type$1.TUnion<[Type$1.TString, Type$1.TNull]>;
  messages: Type$1.TArray<Type$1.TUnion<[Type$1.TObject<{
    role: Type$1.TLiteral<"user">;
    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;
    }>]>>;
    timestamp: Type$1.TInteger;
  }>, 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.TUnion<[Type$1.TLiteral<"sequential">, Type$1.TLiteral<"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>;
    }>>;
    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>>;
    }>>>;
    usage: Type$1.TObject<{
      input: Type$1.TNumber;
      output: Type$1.TNumber;
      cacheRead: Type$1.TNumber;
      cacheWrite: Type$1.TNumber;
      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.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">>;
      }>;
    }>;
    stopReason: Type$1.TUnion<[Type$1.TLiteral<"stop">, Type$1.TLiteral<"length">, Type$1.TLiteral<"toolUse">, Type$1.TLiteral<"error">, Type$1.TLiteral<"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>;
    timestamp: Type$1.TInteger;
  }>, 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;
  }>]>>;
}>;
declare const WorkerTranscriptCommitResultSchema: Type$1.TObject<{
  entryIds: Type$1.TArray<Type$1.TString>;
  newLeafId: Type$1.TString;
}>;
declare const WorkerTranscriptCommitErrorReasonSchema: Type$1.TUnion<[Type$1.TLiteral<"stale-base-leaf">, Type$1.TLiteral<"epoch-mismatch">, Type$1.TLiteral<"invalid-batch">, Type$1.TLiteral<"session-not-attached">]>;
declare const WorkerLiveEventSchema: Type$1.TUnion<[Type$1.TObject<{
  readonly kind: Type$1.TLiteral<"assistant">;
  readonly payload: Type$1.TObject<{
    readonly text: Type$1.TString;
    readonly delta: Type$1.TString;
    readonly replace: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly mediaUrls: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
    readonly phase: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"commentary">, Type$1.TLiteral<"final_answer">]>>;
    readonly itemId: Type$1.TOptional<Type$1.TString>;
  }>;
}>, Type$1.TObject<{
  readonly kind: Type$1.TLiteral<"thinking">;
  readonly payload: Type$1.TObject<{
    readonly text: Type$1.TString;
    readonly delta: Type$1.TString;
  }>;
}>, Type$1.TObject<{
  readonly kind: Type$1.TLiteral<"tool">;
  readonly payload: Type$1.TUnion<[Type$1.TObject<{
    readonly name: Type$1.TString;
    readonly toolCallId: Type$1.TString;
    readonly hideFromChannelProgress: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"start">;
    readonly args: Type$1.TUnknown;
  }>, Type$1.TObject<{
    readonly name: Type$1.TString;
    readonly toolCallId: Type$1.TString;
    readonly hideFromChannelProgress: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"update">;
    readonly partialResult: Type$1.TUnknown;
  }>, Type$1.TObject<{
    readonly name: Type$1.TString;
    readonly toolCallId: Type$1.TString;
    readonly hideFromChannelProgress: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"result">;
    readonly meta: Type$1.TOptional<Type$1.TString>;
    readonly isError: Type$1.TBoolean;
    readonly result: Type$1.TUnknown;
    readonly toolErrorSummary: Type$1.TOptional<Type$1.TString>;
  }>]>;
}>, Type$1.TObject<{
  readonly kind: Type$1.TLiteral<"approval">;
  readonly payload: Type$1.TUnion<[Type$1.TObject<{
    readonly kind: Type$1.TUnion<[Type$1.TLiteral<"exec">, Type$1.TLiteral<"plugin">, Type$1.TLiteral<"unknown">]>;
    readonly title: Type$1.TString;
    readonly itemId: Type$1.TOptional<Type$1.TString>;
    readonly toolCallId: Type$1.TOptional<Type$1.TString>;
    readonly approvalId: Type$1.TOptional<Type$1.TString>;
    readonly approvalSlug: Type$1.TOptional<Type$1.TString>;
    readonly command: Type$1.TOptional<Type$1.TString>;
    readonly host: Type$1.TOptional<Type$1.TString>;
    readonly reason: Type$1.TOptional<Type$1.TString>;
    readonly scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"turn">, Type$1.TLiteral<"session">]>>;
    readonly message: Type$1.TOptional<Type$1.TString>;
    readonly phase: Type$1.TLiteral<"requested">;
    readonly status: Type$1.TUnion<[Type$1.TLiteral<"pending">, Type$1.TLiteral<"unavailable">]>;
  }>, Type$1.TObject<{
    readonly kind: Type$1.TUnion<[Type$1.TLiteral<"exec">, Type$1.TLiteral<"plugin">, Type$1.TLiteral<"unknown">]>;
    readonly title: Type$1.TString;
    readonly itemId: Type$1.TOptional<Type$1.TString>;
    readonly toolCallId: Type$1.TOptional<Type$1.TString>;
    readonly approvalId: Type$1.TOptional<Type$1.TString>;
    readonly approvalSlug: Type$1.TOptional<Type$1.TString>;
    readonly command: Type$1.TOptional<Type$1.TString>;
    readonly host: Type$1.TOptional<Type$1.TString>;
    readonly reason: Type$1.TOptional<Type$1.TString>;
    readonly scope: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"turn">, Type$1.TLiteral<"session">]>>;
    readonly message: Type$1.TOptional<Type$1.TString>;
    readonly phase: Type$1.TLiteral<"resolved">;
    readonly status: Type$1.TUnion<[Type$1.TLiteral<"approved">, Type$1.TLiteral<"denied">, Type$1.TLiteral<"failed">]>;
  }>]>;
}>, Type$1.TObject<{
  readonly kind: Type$1.TLiteral<"lifecycle">;
  readonly payload: Type$1.TUnion<[Type$1.TObject<{
    readonly phase: Type$1.TLiteral<"start">;
    readonly startedAt: Type$1.TInteger;
  }>, Type$1.TObject<{
    readonly selectedProvider: Type$1.TString;
    readonly selectedModel: Type$1.TString;
    readonly activeProvider: Type$1.TString;
    readonly activeModel: Type$1.TString;
    readonly phase: Type$1.TLiteral<"fallback">;
    readonly reasonSummary: Type$1.TString;
    readonly attemptSummaries: Type$1.TArray<Type$1.TString>;
    readonly attempts: Type$1.TArray<Type$1.TObject<{
      readonly provider: Type$1.TString;
      readonly model: Type$1.TString;
      readonly error: Type$1.TString;
      readonly reason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"auth_permanent">, Type$1.TLiteral<"format">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"overloaded">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"server_error">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"tls_certificate">, Type$1.TLiteral<"context_overflow">, Type$1.TLiteral<"model_not_found">, Type$1.TLiteral<"session_expired">, Type$1.TLiteral<"empty_response">, Type$1.TLiteral<"no_error_details">, Type$1.TLiteral<"unclassified">, Type$1.TLiteral<"unknown">]>>;
      readonly authMode: Type$1.TOptional<Type$1.TString>;
      readonly status: Type$1.TOptional<Type$1.TInteger>;
      readonly code: Type$1.TOptional<Type$1.TString>;
    }>>;
  }>, Type$1.TObject<{
    readonly selectedProvider: Type$1.TString;
    readonly selectedModel: Type$1.TString;
    readonly activeProvider: Type$1.TString;
    readonly activeModel: Type$1.TString;
    readonly phase: Type$1.TLiteral<"fallback_cleared">;
    readonly previousActiveModel: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    readonly phase: Type$1.TLiteral<"fallback_step">;
    readonly fallbackStepType: Type$1.TLiteral<"fallback_step">;
    readonly fallbackStepFromModel: Type$1.TString;
    readonly fallbackStepToModel: Type$1.TOptional<Type$1.TString>;
    readonly fallbackStepFromFailureReason: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"auth">, Type$1.TLiteral<"auth_permanent">, Type$1.TLiteral<"format">, Type$1.TLiteral<"rate_limit">, Type$1.TLiteral<"overloaded">, Type$1.TLiteral<"billing">, Type$1.TLiteral<"server_error">, Type$1.TLiteral<"timeout">, Type$1.TLiteral<"tls_certificate">, Type$1.TLiteral<"context_overflow">, Type$1.TLiteral<"model_not_found">, Type$1.TLiteral<"session_expired">, Type$1.TLiteral<"empty_response">, Type$1.TLiteral<"no_error_details">, Type$1.TLiteral<"unclassified">, Type$1.TLiteral<"unknown">]>>;
    readonly fallbackStepFromFailureDetail: Type$1.TOptional<Type$1.TString>;
    readonly fallbackStepChainPosition: Type$1.TOptional<Type$1.TInteger>;
    readonly fallbackStepFinalOutcome: Type$1.TUnion<[Type$1.TLiteral<"next_fallback">, Type$1.TLiteral<"succeeded">, Type$1.TLiteral<"chain_exhausted">]>;
  }>, Type$1.TUnion<[Type$1.TObject<{
    readonly startedAt: Type$1.TOptional<Type$1.TInteger>;
    readonly endedAt: Type$1.TInteger;
    readonly stopReason: Type$1.TOptional<Type$1.TString>;
    readonly yielded: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly timeoutPhase: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"queue">, Type$1.TLiteral<"preflight">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"post_turn">, Type$1.TLiteral<"gateway_draining">]>>;
    readonly providerStarted: Type$1.TOptional<Type$1.TBoolean>;
    readonly aborted: Type$1.TOptional<Type$1.TBoolean>;
    readonly toolErrorSummary: Type$1.TOptional<Type$1.TString>;
    readonly livenessState: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"working">, Type$1.TLiteral<"paused">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"abandoned">]>>;
    readonly replayInvalid: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"finishing">;
    readonly error: Type$1.TOptional<Type$1.TString>;
  }>, Type$1.TObject<{
    readonly startedAt: Type$1.TOptional<Type$1.TInteger>;
    readonly endedAt: Type$1.TInteger;
    readonly stopReason: Type$1.TOptional<Type$1.TString>;
    readonly yielded: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly timeoutPhase: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"queue">, Type$1.TLiteral<"preflight">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"post_turn">, Type$1.TLiteral<"gateway_draining">]>>;
    readonly providerStarted: Type$1.TOptional<Type$1.TBoolean>;
    readonly aborted: Type$1.TOptional<Type$1.TBoolean>;
    readonly toolErrorSummary: Type$1.TOptional<Type$1.TString>;
    readonly livenessState: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"working">, Type$1.TLiteral<"paused">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"abandoned">]>>;
    readonly replayInvalid: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"end">;
  }>, Type$1.TObject<{
    readonly startedAt: Type$1.TOptional<Type$1.TInteger>;
    readonly endedAt: Type$1.TInteger;
    readonly stopReason: Type$1.TOptional<Type$1.TString>;
    readonly yielded: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly timeoutPhase: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"queue">, Type$1.TLiteral<"preflight">, Type$1.TLiteral<"provider">, Type$1.TLiteral<"post_turn">, Type$1.TLiteral<"gateway_draining">]>>;
    readonly providerStarted: Type$1.TOptional<Type$1.TBoolean>;
    readonly aborted: Type$1.TOptional<Type$1.TBoolean>;
    readonly toolErrorSummary: Type$1.TOptional<Type$1.TString>;
    readonly livenessState: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"working">, Type$1.TLiteral<"paused">, Type$1.TLiteral<"blocked">, Type$1.TLiteral<"abandoned">]>>;
    readonly replayInvalid: Type$1.TOptional<Type$1.TLiteral<true>>;
    readonly phase: Type$1.TLiteral<"error">;
    readonly error: Type$1.TString;
    readonly fallbackExhaustedFailure: Type$1.TOptional<Type$1.TLiteral<true>>;
  }>]>]>;
}>]>;
declare const WorkerLiveEventParamsSchema: Type$1.TObject<{
  readonly runEpoch: typeof LiveIntegerSchema;
  readonly lastAckedSeq: typeof LiveIntegerSchema;
  readonly seq: typeof LiveSequenceSchema;
  readonly runId: typeof WorkerIdentifierSchema;
  readonly event: typeof WorkerLiveEventSchema;
}>;
declare const WorkerLiveEventResultSchema: Type$1.TObject<{
  readonly ackedSeq: Type$1.TInteger;
}>;
declare const WorkerLiveEventErrorDetailsSchema: Type$1.TUnion<[Type$1.TObject<{
  readonly reason: Type$1.TUnion<[Type$1.TLiteral<"epoch-mismatch">, Type$1.TLiteral<"session-not-attached">, Type$1.TLiteral<"invalid-event">, Type$1.TLiteral<"capacity-exceeded">]>;
}>, Type$1.TObject<{
  readonly reason: Type$1.TLiteral<"resync-required">;
  readonly ackedSeq: Type$1.TInteger;
  readonly expectedSeq: Type$1.TInteger;
}>]>;
type WorkerAdmissionHandshake = Static<typeof WorkerAdmissionHandshakeSchema>;
type WorkerConnectParams = Static<typeof WorkerConnectParamsSchema>;
type WorkerAdmissionFailureReason = Static<typeof WorkerAdmissionFailureReasonSchema>;
type WorkerProtocolCloseReason = Static<typeof WorkerProtocolCloseReasonSchema>;
type WorkerSessionsSpawnParams = Static<typeof WorkerSessionsSpawnParamsSchema>;
type WorkerSessionsSendParams = Static<typeof WorkerSessionsSendParamsSchema>;
type WorkerPortalParams = Static<typeof WorkerPortalParamsSchema>;
type WorkerPresenceParams = Static<typeof WorkerPresenceParamsSchema>;
type WorkerSessionToolResult = Static<typeof WorkerSessionToolResultSchema>;
type WorkerTranscriptCommitParams = Static<typeof WorkerTranscriptCommitParamsSchema>;
type WorkerTranscriptCommitResult = Static<typeof WorkerTranscriptCommitResultSchema>;
type WorkerTranscriptCommitErrorReason = Static<typeof WorkerTranscriptCommitErrorReasonSchema>;
type WorkerLiveEventParams = Static<typeof WorkerLiveEventParamsSchema>;
type WorkerLiveEventResult = Static<typeof WorkerLiveEventResultSchema>;
type WorkerLiveEventErrorDetails = Static<typeof WorkerLiveEventErrorDetailsSchema>;
//#endregion
//#region packages/gateway-protocol/src/client-info.d.ts
/** Canonical client ids accepted in gateway hello/connect payloads. */
declare const GATEWAY_CLIENT_IDS: {
  readonly WEBCHAT_UI: "webchat-ui";
  readonly CONTROL_UI: "openclaw-control-ui";
  readonly BROWSER_COPILOT: "openclaw-browser-copilot";
  readonly TUI: "openclaw-tui";
  readonly WEBCHAT: "webchat";
  readonly CLI: "cli";
  readonly GATEWAY_CLIENT: "gateway-client";
  readonly MACOS_APP: "openclaw-macos";
  readonly LINUX_APP: "openclaw-linux";
  readonly IOS_APP: "openclaw-ios";
  readonly WATCHOS_APP: "openclaw-watchos";
  readonly ANDROID_APP: "openclaw-android";
  readonly NODE_HOST: "node-host";
  readonly WORKER: "openclaw-worker";
  readonly TEST: "test";
  readonly FINGERPRINT: "fingerprint";
  readonly PROBE: "openclaw-probe";
};
/** Stable gateway client ids used on the wire during hello/connect handshakes. */
type GatewayClientId = (typeof GATEWAY_CLIENT_IDS)[keyof typeof GATEWAY_CLIENT_IDS];
/** Compatibility alias for internal callers that still use "name" terminology. */
type GatewayClientName = GatewayClientId;
/** Coarse modes let policy group clients without matching every product id. */
declare const GATEWAY_CLIENT_MODES: {
  readonly WEBCHAT: "webchat";
  readonly CLI: "cli";
  readonly UI: "ui";
  readonly BACKEND: "backend";
  readonly NODE: "node";
  readonly WORKER: "worker";
  readonly PROBE: "probe";
  readonly TEST: "test";
};
/** Coarse client category used for gateway policy and diagnostics. */
type GatewayClientMode = (typeof GATEWAY_CLIENT_MODES)[keyof typeof GATEWAY_CLIENT_MODES];
/** Client metadata sent during gateway connection setup. */
type GatewayClientInfo = {
  /** Stable product/client identifier from `GATEWAY_CLIENT_IDS`. */
  id: GatewayClientId;
  /** Human-readable label for diagnostics; not used for policy decisions. */
  displayName?: string;
  /** Client app or package version reported by the connecting process. */
  version: string;
  /** Exact immutable artifact identity when the client can report one. */
  buildId?: string;
  /** Runtime platform string, such as `darwin`, `ios`, `android`, or `web`. */
  platform: string;
  /** Optional device family used by native clients for display and routing hints. */
  deviceFamily?: string;
  /** Native hardware/model identifier when available. */
  modelIdentifier?: string;
  /** Self-reported IANA time zone, such as `Europe/Vienna`, for presence display. */
  timeZone?: string;
  /** Coarse category from `GATEWAY_CLIENT_MODES` for policy and diagnostics. */
  mode: GatewayClientMode;
  /** Per-installation or per-process id used to distinguish same-product clients. */
  instanceId?: string;
};
/** Capability flags a client may advertise during the gateway handshake. */
declare const GATEWAY_CLIENT_CAPS: {
  readonly AGENT_KIND: "agent-kind";
  readonly APPROVALS: "approvals";
  readonly CHAT_ONLY_ASSISTANT_TEXT: "chat-only-assistant-text";
  readonly EXEC_APPROVALS: "exec-approvals";
  readonly INLINE_WIDGETS: "inline-widgets";
  readonly MODEL_CATALOG_SNAPSHOT: "model-catalog-snapshot";
  readonly MODEL_SELECTION_POLICY: "model-selection-policy";
  readonly RUN_TOOL_BINDINGS: "run-tool-bindings";
  readonly SESSION_SCOPED_EVENTS: "session-scoped-events";
  readonly SKILL_CURATOR_LIVE_INVENTORY: "skill-curator-live-inventory";
  readonly PLUGIN_APPROVALS: "plugin-approvals";
  readonly TASK_SUGGESTIONS: "task-suggestions";
  readonly TERMINAL_OFFSET_SEQ: "terminal-offset-seq";
  readonly TERMINAL_SESSION_METADATA: "terminal-session-metadata";
  readonly TERMINAL_UPLOAD_PATH_STYLE: "terminal-upload-path-style";
  readonly TOOL_EVENTS: "tool-events";
  readonly UI_COMMANDS: "ui-commands";
  readonly USAGE_REFRESHING: "usage-refreshing";
};
/** Optional capability advertised by clients during gateway handshake. */
type GatewayClientCap = (typeof GATEWAY_CLIENT_CAPS)[keyof typeof GATEWAY_CLIENT_CAPS];
//#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;
} & 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/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/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
/** Deferred outbound delivery intent attached to a session or task. */
type DeliveryIntentRef = {
  /** 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";
};
/** 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?: DeliveryIntentRef;
};
//#endregion
//#region src/config/sessions/restart-recovery-types.d.ts
/** Exact task and requester generation captured by the admitted host completion turn. */
type HarnessCompletionRecovery = {
  taskId: string;
  /** Terminal outcome captured when this completion input was admitted. */
  taskStatus: "succeeded" | "failed";
  taskRunId: string;
  sourceRunId: string;
  requesterSessionKey: string;
  requesterAgentId: string;
  sessionId: string;
  /** Absence is an expected absent revision, not a wildcard. */
  lifecycleRevision?: string;
};
type RestartRecoveryBeforeAgentReplyState = "admitted" | "pending" | "continue" | "handled-silent" | "handled-reply" | "handled-unrecoverable";
type RestartRecoveryTerminalDeliveryEvidenceResult = {
  /** The terminal result was captured even when it contained no visible or delivery evidence. */
  captured?: true;
  payloads?: Array<{
    mediaUrls?: string[];
    visible?: boolean;
  }>;
  payloadsTruncated?: true;
  deliveryStatus?: {
    status: "failed" | "partial_failed" | "sent" | "suppressed";
    resultCount?: number;
    errorMessage?: string;
    payloadOutcomes?: Array<{
      index: number;
      status: "failed" | "sent" | "suppressed";
      sentBeforeError?: boolean;
    }>;
  };
  messagingToolSentTargets?: Array<{
    provider?: string;
    accountId?: string;
    to?: string;
    threadId?: string;
    threadImplicit?: boolean;
    threadSuppressed?: boolean;
    mediaUrls?: string[];
    visible?: boolean;
    /** Explicit false remains progress-only after a restart. */
    sourceReplyFinal?: boolean;
  }>;
  messagingToolSentTargetsTruncated?: true;
  /** Aggregate committed sends were not all represented by route-checkable target records. */
  messagingToolAggregateEvidenceUnaccounted?: true;
  /** The terminal run reported a committed effect that makes fresh replay unsafe. */
  restartUnsafeSideEffectsDetected?: true;
};
type RestartRecoveryTerminalDeliveryEvidence = RestartRecoveryTerminalDeliveryEvidenceResult & {
  runId: string;
  harnessCompletion?: HarnessCompletionRecovery;
  deliveryContext?: DeliveryContext;
  /** Identified queue completion retained before its exact harness task settles. */
  durableFinalReceipt?: {
    intentId: string;
    deliveryId: string;
    platformMessageId: string;
  };
  /** Actual completion run; a resumed run can differ from its queued source. */
  transcriptRunId?: string;
};
/** Durable ownership and idempotency state for gateway restart recovery. */
type SessionRestartRecoveryState = {
  restartRecoveryBeforeAgentReplyState?: RestartRecoveryBeforeAgentReplyState;
  /** Durable pre/post boundary around the terminal external send. */
  restartRecoveryDeliveryReceiptState?: "terminal-pending" | "delivered-terminal";
  /** Exact agent tool call whose terminal external send owns the receipt. */
  restartRecoveryDeliveryToolCallId?: string;
  restartRecoveryDeliveryContext?: DeliveryContext;
  /** Exact host-owned media allowlist for a generated-media recovery run. */
  restartRecoveryDeliveryMediaUrls?: string[];
  /** Keeps the message tool absent while a generated-media recovery run is resumed. */
  restartRecoveryDisableMessageTool?: true;
  /** Suppresses visible text when a recovery attempt repairs only missing media. */
  restartRecoverySuppressTextDelivery?: true;
  restartRecoveryDeliveryRequestFingerprint?: string;
  restartRecoveryDeliveryRunId?: string;
  restartRecoveryDeliverySourceRunId?: string;
  restartRecoveryHarnessCompletion?: HarnessCompletionRecovery;
  restartRecoveryRequesterAccountId?: string;
  restartRecoveryRequesterSenderId?: string;
  restartRecoverySameChannelThreadRequired?: true;
  restartRecoverySourceIngress?: "channel" | "control-ui" | "internal";
  restartRecoverySourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  restartRecoveryTerminalDeliveryEvidence?: RestartRecoveryTerminalDeliveryEvidence[];
  restartRecoveryTerminalRunIds?: string[];
};
//#endregion
//#region src/config/sessions/session-transcript-turn-lifecycle.types.d.ts
/** Authoritative lifecycle snapshot required for an atomic transcript admission. */
type SessionTranscriptTurnExpectedState = {
  /** Rejects a run-owned turn after another admitted run takes writer ownership. */
  expectedWriterRunId?: string;
  abortedLastRun: boolean | undefined;
  /** Fences recovery-only transcript writes against concurrent ownership changes. */
  mainRestartRecoveryCycleId: string | undefined;
  mainRestartRecoveryRevision: number | undefined;
  restartRecoveryBeforeAgentReplyState: SessionRestartRecoveryState["restartRecoveryBeforeAgentReplyState"];
  restartRecoveryDeliveryReceiptState: SessionRestartRecoveryState["restartRecoveryDeliveryReceiptState"];
  restartRecoveryDeliveryToolCallId: SessionRestartRecoveryState["restartRecoveryDeliveryToolCallId"];
  restartRecoveryDeliveryRequestFingerprint: SessionRestartRecoveryState["restartRecoveryDeliveryRequestFingerprint"];
  restartRecoveryDeliveryRunId: SessionRestartRecoveryState["restartRecoveryDeliveryRunId"];
  restartRecoveryDeliverySourceRunId: SessionRestartRecoveryState["restartRecoveryDeliverySourceRunId"];
  restartRecoveryRequesterAccountId: SessionRestartRecoveryState["restartRecoveryRequesterAccountId"];
  restartRecoveryRequesterSenderId: SessionRestartRecoveryState["restartRecoveryRequesterSenderId"];
  restartRecoverySameChannelThreadRequired: SessionRestartRecoveryState["restartRecoverySameChannelThreadRequired"];
  restartRecoverySourceIngress: SessionRestartRecoveryState["restartRecoverySourceIngress"];
  restartRecoverySourceReplyDeliveryMode: SessionRestartRecoveryState["restartRecoverySourceReplyDeliveryMode"];
  restartRecoveryTerminalRunIds: SessionRestartRecoveryState["restartRecoveryTerminalRunIds"];
  status: PersistedSessionRunStatus | undefined;
};
/** Lifecycle fields committed with an accepted transcript turn. */
type SessionTranscriptTurnLifecyclePatch = {
  abortedLastRun?: boolean;
  endedAt?: number;
  lifecycleRunId?: InternalSessionEntry["lifecycleRunId"];
  lastRunId?: InternalSessionEntry["lastRunId"];
  lastRunError?: InternalSessionEntry["lastRunError"];
  pendingFinalDelivery?: InternalSessionEntry["pendingFinalDelivery"];
  mainRestartRecovery?: InternalSessionEntry["mainRestartRecovery"];
  restartRecoveryBeforeAgentReplyState?: SessionRestartRecoveryState["restartRecoveryBeforeAgentReplyState"];
  restartRecoveryDeliveryReceiptState?: SessionRestartRecoveryState["restartRecoveryDeliveryReceiptState"];
  restartRecoveryDeliveryToolCallId?: SessionRestartRecoveryState["restartRecoveryDeliveryToolCallId"];
  restartRecoveryDeliveryContext?: SessionRestartRecoveryState["restartRecoveryDeliveryContext"];
  restartRecoveryDeliveryRequestFingerprint?: SessionRestartRecoveryState["restartRecoveryDeliveryRequestFingerprint"];
  restartRecoveryDeliveryRunId?: SessionRestartRecoveryState["restartRecoveryDeliveryRunId"];
  restartRecoveryDeliverySourceRunId?: SessionRestartRecoveryState["restartRecoveryDeliverySourceRunId"];
  restartRecoveryRequesterAccountId?: SessionRestartRecoveryState["restartRecoveryRequesterAccountId"];
  restartRecoveryRequesterSenderId?: SessionRestartRecoveryState["restartRecoveryRequesterSenderId"];
  restartRecoverySameChannelThreadRequired?: SessionRestartRecoveryState["restartRecoverySameChannelThreadRequired"];
  restartRecoverySourceIngress?: SessionRestartRecoveryState["restartRecoverySourceIngress"];
  restartRecoverySourceReplyDeliveryMode?: SessionRestartRecoveryState["restartRecoverySourceReplyDeliveryMode"];
  restartRecoveryForceSafeTools?: InternalSessionEntry["restartRecoveryForceSafeTools"];
  restartRecoveryRuns?: InternalSessionEntry["restartRecoveryRuns"];
  /** Durable tombstones merged with the fresh row inside the SQLite write transaction. */
  restartRecoveryTerminalRunIds?: SessionRestartRecoveryState["restartRecoveryTerminalRunIds"];
  runtimeMs?: number;
  startedAt?: number;
  status?: PersistedSessionRunStatus;
  updatedAt?: number;
};
//#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[];
  };
};
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;
  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$1;
  sessionKey: string;
  sessionEntry: SessionEntry$1 | undefined;
  sessionStore?: Record<string, SessionEntry$1>;
  storePath?: string;
  agentId: string;
  threadId?: string | number;
  cwd?: string;
  config?: unknown;
  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$1 | undefined;
  messageId: string;
  message: PersistedUserTurnMessage;
  admission: UserTurnTranscriptAdmissionReceipt;
};
type UserTurnTranscriptTargetResolver = UserTurnTranscriptTarget | (() => UserTurnTranscriptTarget | undefined | Promise<UserTurnTranscriptTarget | undefined>);
type UserTurnTranscriptRecorder = {
  readonly message: PersistedUserTurnMessage | undefined;
  resolveMessage: () => Promise<PersistedUserTurnMessage | undefined>;
  /** Committed input, accepted pending custody, and blocked notices are exempt. */
  assertOriginalInputCommit?: () => void;
  /** Durable input custody leaves the active transcript unchanged until execution owns it. */
  stageApproved?: (options: {
    runId: string;
    assertCurrent: () => void;
    assertAdmittedCurrent?: () => void;
    assertCompletionCurrent?: () => void;
  }) => Promise<boolean>;
  getProcessingCompletion?: () => AgentRunTerminalOutcome | undefined;
  completeProcessing?: (outcome: AgentRunTerminalOutcome) => AgentRunTerminalOutcome | undefined;
  getPendingInputMessage?: () => PersistedUserTurnMessage | undefined;
  isPendingInputConsumed?: () => boolean;
  withPendingInput?: <T>(run: () => T) => T;
  finishPendingInput?: (disposition: "cancelled" | "interrupted") => 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;
  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?: {
    target?: UserTurnTranscriptTargetResolver;
    updateMode?: UserTurnTranscriptUpdateMode;
    cwd?: string;
    expectedSessionId?: string;
    expectedSessionState?: SessionTranscriptTurnExpectedState;
    sessionLifecyclePatch?: SessionTranscriptTurnLifecyclePatch;
    /** Allow a later explicit persistence attempt when this attempt appends nothing. */
    retryIfUnpersisted?: boolean;
  }) => Promise<UserTurnTranscriptPersistResult | undefined>;
  persistBlocked: (message: PersistedUserTurnMessage, params?: {
    target?: UserTurnTranscriptTargetResolver;
    updateMode?: UserTurnTranscriptUpdateMode;
    cwd?: string;
  }) => Promise<UserTurnTranscriptPersistResult | undefined>;
  persistFallback: (params?: {
    target?: UserTurnTranscriptTargetResolver;
    updateMode?: UserTurnTranscriptUpdateMode;
    cwd?: string;
  }) => Promise<UserTurnTranscriptPersistResult | 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;
}>;
//#endregion
//#region src/channels/progress-continuation.d.ts
/** Positive platform evidence plus data-only presentation state, never a transport callback. */
type ProgressContinuationReceipt = {
  channel: string;
  accountId?: string;
  to: string;
  threadId?: string | number;
  messageId: string;
  text: string;
  snapshot: ChannelProgressDraftCompositorSnapshot;
};
type ProgressContinuationCapability = {
  adopt: (this: void, receipt: ProgressContinuationReceipt) => Promise<boolean>;
  close: () => void;
};
//#endregion
//#region src/plugins/gateway-access-policy.types.d.ts
type GatewayAccessGrantRef = Readonly<{
  pluginId: string;
  grantId: string;
}>;
/** Additional access held by an authenticated person, independent of a transport. */
type PluginGatewayAccessAuthority = Readonly<{
  /** Stable UUID for one uninterrupted grant, if the policy supports durable requests. */
  grantId?: string;
  assertCurrent: () => void;
  signal: AbortSignal;
}>;
type GatewayAccessPolicyContext = {
  config: OpenClawConfig;
  /** The person's effective operator role explicitly names this policy's plugin. */
  requiredByRole: boolean;
  profile: {
    profileId: string;
    emails: readonly string[];
    assignedRole: string | null;
  };
};
type PluginGatewayAccessPolicy = {
  /** Return no authority when inapplicable; an explicit role binding still requires authority. */
  authorize: (context: GatewayAccessPolicyContext) => PluginGatewayAccessAuthority | undefined;
  /**
   * Check the original grant even if the current role is exempt. Return undefined
   * only for a definitively ended grant; throw while its state is unavailable.
   */
  resume?: (context: GatewayAccessPolicyContext & {
    grantId: string;
  }) => PluginGatewayAccessAuthority | undefined;
};
//#endregion
//#region src/runtime.d.ts
type RuntimeExitOptions = {
  /** Route ANSI terminal-reset bytes away from structured stdout when needed. */
  resetStream?: NodeJS.WriteStream;
};
type RuntimeEnv = {
  log: (...args: unknown[]) => void;
  error: (...args: unknown[]) => void;
  /**
   * Exit the process after restoring terminal state.
   * Pass `resetStream` to route the ANSI reset sequence to a specific
   * stream (e.g. stderr) when structured output on stdout must stay clean.
   */
  exit: (code: number, opts?: RuntimeExitOptions) => void;
};
//#endregion
//#region src/logging/levels.d.ts
declare const ALLOWED_LOG_LEVELS: readonly ["silent", "fatal", "error", "warn", "info", "debug", "trace"];
type LogLevel = (typeof ALLOWED_LOG_LEVELS)[number];
//#endregion
//#region src/logging/subsystem.d.ts
type SubsystemLogger = {
  subsystem: string;
  isEnabled: (level: LogLevel, target?: "any" | "console" | "file") => boolean;
  trace: (message: string, meta?: Record<string, unknown>) => void;
  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;
  fatal: (message: string, meta?: Record<string, unknown>) => void;
  raw: (message: string) => void;
  child: (name: string) => SubsystemLogger;
};
//#endregion
//#region src/infra/sqlite-reader-lifecycle.d.ts
type SqliteReaderOwner = {
  operation: string;
  ownerKind: "main" | "worker";
  actorId?: number;
};
type SqliteReaderDiagnostic = SqliteReaderOwner & {
  kind: "iterator";
  connectionId: number;
  threadId: number;
  ageMs: number;
  idleMs: number;
};
type SqliteReaderDiagnostics = {
  scope: "current-thread";
  blockingOwner: "unknown";
  nativeStatements: "unobserved";
  threadId: number;
  observedAtMs: number;
  connectionCount: number;
  readerCount: number;
  connections: Array<SqliteReaderOwner & {
    connectionId: number;
    threadId: number;
    ageMs: number;
    transactionOpen: boolean;
    trackedReaders: number;
  }>;
  activeReaders: SqliteReaderDiagnostic[];
};
//#endregion
//#region src/infra/sqlite-wal-checkpoint.d.ts
type SqliteWalCheckpointMode = "PASSIVE" | "FULL" | "RESTART" | "TRUNCATE";
type SqliteWalHealth = {
  state: "complete" | "blocked" | "error";
  observedAtMs: number;
  walBytes: number | null;
  databaseBytes: number | null;
  logFrames: number | null;
  checkpointedFrames: number | null;
  lastCompletedAtMs: number | null;
  consecutiveBlocked: number;
  warning: boolean;
  error?: string;
  activeReaders?: SqliteReaderDiagnostic[];
  readerDiagnostics?: Array<Omit<SqliteReaderDiagnostics, "activeReaders">>;
};
type SqliteWalCheckpointSnapshot = {
  health: SqliteWalHealth;
  observedAtNs: bigint;
};
//#endregion
//#region src/infra/sqlite-wal-reclamation.d.ts
type SqliteWalReclamationOptions = {
  maxPages?: number;
  checkpointMode?: SqliteWalCheckpointMode;
  beforeMutation?: () => void;
  onCommit?: () => void;
  afterCommit?: () => void;
};
type SqliteWalReclamationResult = {
  checkpointCompleted: boolean;
  checkpoint?: SqliteWalCheckpointSnapshot;
  freePagesBefore: number | null;
  remainingFreePages: number | null;
  checkpointCalls: number;
  checkpointIncomplete: number;
  checkpointMs: number;
  checkpointMaxMs: number;
  queryMs: number;
  vacuumMs: number;
  vacuumPasses: number;
  vacuumPagesRequested: number;
};
//#endregion
//#region src/infra/sqlite-wal-write-admission.d.ts
type SqliteWalPeriodicRequest = {
  maxPages: number;
  checkpointMode: SqliteWalCheckpointMode;
  checkpoint?: SqliteWalCheckpointSnapshot;
};
type SqliteWalPeriodicResult = {
  reclaimedPages: number;
  checkpoint?: SqliteWalCheckpointSnapshot;
};
//#endregion
//#region src/infra/sqlite-wal.d.ts
type SqliteWalMaintenance = {
  /** Last maintenance observation; reading it never checkpoints or probes storage. */
  readonly health?: SqliteWalHealth;
  checkpoint: () => boolean;
  maintainPeriodic?: (request: SqliteWalPeriodicRequest, admit?: (stage: "transaction" | "commit") => void) => SqliteWalPeriodicResult;
  reclaimFreePages: (options?: SqliteWalReclamationOptions) => SqliteWalReclamationResult;
  /** Inspect this retained WAL connection, independently of checkpoint completion elsewhere. */
  inspectIdle?: () => "healthy" | "retire";
  close: (options?: {
    checkpointMode?: SqliteWalCheckpointMode;
  }) => boolean;
};
//#endregion
//#region src/infra/sqlite-worker-identity.d.ts
type DatabasePathIdentity = Readonly<{
  key: string;
  canonicalPath: string;
  birthtime?: string;
}>;
//#endregion
//#region src/state/openclaw-state-db-contract.d.ts
/** Open shared SQLite database handle plus WAL maintenance lifecycle. */
type OpenClawStateDatabase = {
  db: DatabaseSync;
  path: string;
  walMaintenance: SqliteWalMaintenance;
};
/** Options for resolving or overriding the shared state database path. */
type OpenClawStateDatabaseOptions = {
  env?: NodeJS.ProcessEnv;
  path?: string;
  database?: OpenClawStateDatabase;
  readOnly?: boolean;
  /** Additional known agent stores can only make first-use classification more conservative. */
  initializationAgentPaths?: readonly string[];
};
//#endregion
//#region src/state/openclaw-state-db-async-lifecycle.d.ts
type OpenClawStateDatabaseReadAdmission = {
  readonly databasePath: string;
  /** Stable across first creation and aliases; coordinates work but grants no authority. */
  readonly coordinationKey: string;
  readonly identity: DatabasePathIdentity;
  assertCurrent: () => void;
};
type MaintenanceResource = {
  phase: "agent-resources" | "agent-handles" | "shared-leases" | "shared-resources" | "shared-references" | "shared-handles";
  close: () => void | Promise<void>;
};
type AgentSchemaMigration = {
  agentId: string;
  path: string;
  foundVersion: number;
  supportedVersion: number;
};
type OpenClawDatabaseMaintenanceScope = {
  readonly ownsSchemaMaintenance: boolean;
  assertOwnerCurrent(this: void, access?: "read"): void;
  assertDatabaseAccess(this: void, databasePath: string): void;
  assertAdmission(this: void): void;
  assertReadAdmission(this: void): void;
  addAgentSchemaMigrationCheck(check: (migration: AgentSchemaMigration) => void): void;
  assertAgentSchemaMigration(migration: AgentSchemaMigration): void;
  run<T>(operation: () => T): T;
  track<T>(operation: Promise<T>): Promise<T>;
  own(resource: object, phase: MaintenanceResource["phase"], close: MaintenanceResource["close"]): void;
  close(): Promise<void>;
};
//#endregion
//#region src/infra/sqlite-worker-state-context.d.ts
/** Resolved host facts for the canonical shared-state owner, never authority. */
type SqliteWorkerStateContext = {
  environment: NodeJS.ProcessEnv & {
    OPENCLAW_STATE_DIR: string;
    OPENCLAW_SUPERVISOR_MODE?: "external";
  };
  /** Selected config inputs for native shared-state initialization, not command environment. */
  initializationEnvironment?: NodeJS.ProcessEnv;
  /** Known agent paths preserve deletion-history uncertainty during native initialization. */
  initializationAgentPaths?: readonly string[];
  existingSchemaPath?: string;
};
//#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;
  /** 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/state/openclaw-state-db-cache.d.ts
declare const { touch: touchStateDatabase, retain: retainOpenClawStateDatabaseForIdle }: {
  touch: (database: OpenClawStateDatabase) => void;
  retain(this: void, database: OpenClawStateDatabase): () => void;
};
declare const { register: registerStateDatabaseWalAdmission, readHealth: readOpenClawStateWalHealth }: {
  register(this: void, database: OpenClawStateDatabase, identity: DatabasePathIdentity, admission: OpenClawStateDatabaseReadAdmission, env: NodeJS.ProcessEnv): void;
  readHealth(this: void): SqliteWalHealth | undefined;
};
/** Retain one exact canonical native owner; only the final reference retires its handle. */
declare const { retain: retainOpenClawStateDatabase, borrowForRead: borrowOpenClawStateDatabaseForAsyncRead, retainForIndependentRead: retainOpenClawStateDatabaseForIndependentRead }: {
  retain: (database: OpenClawStateDatabase) => {
    release(): void;
  };
  retainForIndependentRead(this: void, pathname: string, ownership?: "cached-read"): {
    assertCurrent: () => void;
    observe(): void;
    release(): void;
  } | undefined;
  borrowForRead(this: void, pathname: string, ownership?: "cached-read"): {
    assertCurrent: () => void;
    observe(): void;
    release(): void;
    database: OpenClawStateDatabase;
  } | undefined;
};
//#endregion
//#region src/state/openclaw-state-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 WorkerEnvironments {
  attached_session_ids_json: Generated<string>;
  bootstrap_bundle_hash: string | null;
  bootstrap_install_kind: string | null;
  bootstrap_openclaw_version: string | null;
  bootstrap_protocol_features_json: string | null;
  created_at_ms: number;
  desktop_json: string | null;
  destroy_requested_at_ms: number | null;
  environment_id: string;
  idle_since_at_ms: number | null;
  last_activated_at_ms: number | null;
  last_error: string | null;
  lease_id: string | null;
  node_device_id: string | null;
  node_setup_id: string | null;
  owner_epoch: Generated<number>;
  preparation_consumed_at_ms: number | null;
  preparation_demand_at_ms: number | null;
  preparation_expires_at_ms: number | null;
  preparation_key: string | null;
  preparation_purpose: string | null;
  profile_id: string;
  profile_snapshot_json: string;
  provider_id: string;
  provision_operation_id: string;
  shared_host: number | null;
  ssh_host: string | null;
  ssh_host_key: string | null;
  ssh_key_ref_json: string | null;
  ssh_port: number | null;
  ssh_user: string | null;
  state: string;
  state_changed_at_ms: number;
  teardown_terminal_state: string | null;
  updated_at_ms: number;
}
//#endregion
//#region src/state/user-channel-identities.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-owner-authority.d.ts
type CommandOwnerAssertion = (() => void) & {
  readonly recoveryReference?: CommandOwnerReference | null;
};
//#endregion
//#region src/auto-reply/reply/reply-dispatch-outcome.types.d.ts
type ReplyDispatchDeliveryOutcome = "delivered" | "delivered-not-visible" | "channel-transform" | "cancelled" | "failed-before-deliver" | "recovery-owned" | "failed-deliver";
//#endregion
//#region src/auto-reply/reply-payload.d.ts
type ReplyMediaFailureCode = "file-not-found" | "unsupported-format" | "delivery-failed";
/** Producer-owned outcome for one attachment that could not be delivered. */
type ReplyMediaFailure = {
  code: ReplyMediaFailureCode;
  kind: "image" | "audio" | "video" | "document";
  label: string;
  mimeType?: string;
};
/** Reply policy facts that provider adapters use to resolve the final transport route. */
type ReplyDeliveryContext = {
  chatType?: "direct" | "group" | "channel" | null;
  replyToMode: ReplyToMode;
};
/** WeakMap-backed metadata attached to payload objects without changing wire shape. */
type SessionWriterDeliveryAuthority = {
  agentId?: string;
  /** Captured admitted completion authority, retained by the durable queue. */
  harnessCompletion?: HarnessCompletionRecovery;
  expectedLifecycleRevision?: string;
  expectedSessionId: string;
  expectedWriterRunId?: string;
  sessionKey: string;
  storePath?: string;
};
//#endregion
//#region src/auto-reply/reply/typing.d.ts
/** Controller for channel typing indicator lifecycle during a reply run. */
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;
};
/** 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;
  };
};
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;
};
/** Context passed to onModelSelected callback with actual model used. */
type ModelSelectedContext = {
  provider: string;
  model: string;
  thinkLevel: string | undefined;
};
/** Typing indicator class for channel-owned UX policy. */
type TypingPolicy = "auto" | "user_message" | "system_event" | "internal_webchat" | "heartbeat";
/** 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 = {
  begin: () => (() => void) | void;
};
/**
 * 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;
  /** Always fires when the followup ownership cycle ends (admitted or not). Gateway cleanup. */
  onSettled?: () => 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["text"];
  mediaUrls?: ReplyPayload["mediaUrls"];
  delta?: string;
  replace?: true;
};
type ReasoningStreamPayload$2 = Pick<ReplyPayload, "text" | "mediaUrls" | "isReasoning" | "isReasoningSnapshot"> & {
  requiresReasoningProgressOptIn?: boolean;
};
type ReasoningProgressPayload = {
  progressTokens: number;
};
/** 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?: () => boolean;
  /** 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[];
  /**
   * 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) => unknown;
  /** Reports the terminal agent-run classification to the shared dispatch owner. */
  onAgentRunTerminalOutcome?: (outcome: "completed" | "failed") => void;
  /** Reports visible work sessions this agent run spawned, in acceptance order. */
  onVisibleWorkSessions?: (sessions: readonly VisibleWorkSession[]) => 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";
  /** 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;
  isHeartbeat?: boolean;
  /** Policy-level typing control for run classes (user/system/internal/heartbeat). */
  typingPolicy?: TypingPolicy;
  /** Force-disable typing indicators for this run (system/internal/cross-channel routes). */
  suppressTyping?: boolean;
  /** Resolved heartbeat model override (provider/model string from merged per-agent config). */
  heartbeatModelOverride?: string;
  /** 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[];
  /** If true, include the heartbeat response tool for structured heartbeat outcomes. */
  enableHeartbeatTool?: boolean;
  /** If true, keep the heartbeat response tool available even under narrow tool profiles. */
  forceHeartbeatTool?: boolean;
  /**
   * @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;
  /** 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.
   */
  onVerboseProgressVisibility?: (isActive: () => boolean) => void;
  /** Preserve source-event callback start order for stateful channel progress renderers. */
  preserveProgressCallbackStartOrder?: boolean;
  onPartialReply?: (payload: PartialReplyPayload) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onReasoningStream?: (payload: ReasoningStreamPayload$2) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onReasoningProgress?: (payload: ReasoningProgressPayload) => 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, context?: BlockReplyContext) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  onBlockReply?: (payload: ReplyPayload, 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) => 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: {
    phase?: string;
    kind?: string;
    status?: string;
    title?: string;
    itemId?: string;
    toolCallId?: string;
    approvalId?: string;
    approvalSlug?: string;
    command?: string;
    host?: string;
    reason?: string;
    scope?: "turn" | "session";
    message?: string;
  }) => Promise<ProgressCallbackResult> | ProgressCallbackResult;
  /** Called when command output streams or completes. */
  onCommandOutput?: (payload: {
    itemId?: string;
    phase?: string;
    title?: string;
    toolCallId?: string;
    name?: string;
    output?: string;
    status?: string;
    exitCode?: number | null;
    durationMs?: number;
    cwd?: 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. */
  onModelSelected?: (ctx: ModelSelectedContext) => 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;
  /** Trusted channel-configured policy for this admitted conversation turn. */
  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" | "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 conversation image reference; never rendered into prompt text. */
  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;
};
type RuntimeMediaContextKey = "MediaPath" | "MediaUrl" | "MediaType" | "MediaDir" | "MediaPaths" | "MediaUrls" | "MediaTypes" | "MediaWorkspaceDir" | "MediaTranscribedIndexes" | "MediaStaged";
/** Internal inbound context; legacy media fields exist only on the shipped SDK adapter. */
type RuntimeMsgContext = Omit<MsgContext, RuntimeMediaContextKey>;
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;
};
//#endregion
//#region src/state/openclaw-agent-db-contract.d.ts
/** Open per-agent SQLite database handle plus lifecycle maintenance. */
type OpenClawAgentDatabase = {
  agentId: string;
  db: DatabaseSync;
  path: string;
  walMaintenance: SqliteWalMaintenance;
};
/** Options for resolving and opening one agent database. */
type OpenClawAgentDatabaseOptions = OpenClawStateDatabaseOptions & {
  agentId: string;
};
//#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.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 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;
};
/** Raw transcript record for non-message events; message records use appendTranscriptMessage. */
type TranscriptEvent = unknown;
type TranscriptMessageAppendOptions<TMessage> = {
  /** Rebase a stale explicit parent when the current tail still descends from it. */
  appendIntent?: "active-branch";
  /** Runtime config used for message redaction and 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;
  /** Optional finalizer that runs after duplicate detection but before persistence. */
  prepareMessageAfterIdempotencyCheck?: (message: TMessage) => TMessage | undefined;
  /** Synchronous assertion after replay, custody, preparation, and redaction, before insertion. */
  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;
  /** Redacted 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;
};
interface SessionTranscriptRuntimeTarget {
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
}
//#endregion
//#region src/config/sessions/cli-history-boundary.d.ts
/** 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 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/channels/chat-type.d.ts
/**
 * Normalized conversation kind shared by channel routing, sessions, and SDK helpers.
 */
type ChatType = "direct" | "group" | "channel";
//#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/shared/session-types.d.ts
/** Per-session Control UI face preference carried by session list rows. */
type SessionBoardFace = "chat" | "dashboard";
//#endregion
//#region src/config/sessions/main-session-recovery.types.d.ts
type MainRestartRecoveryState = {
  /** Stable identity for one interrupted episode; prevents clear-and-rewedge ABA matches. */
  cycleId: string;
  /** Monotonic identity for observations within the current recovery cycle. */
  revision: number;
  /** Attempts charged when their reservation is persisted, before dispatch. */
  chargedAttempts: number;
  /** Last attempt observed starting a backend turn; later startup failures get a fresh budget. */
  startedAttempt?: number;
  /** Private safe token for one recovered outer turn; raw identity refs never enter session state. */
  executionIdentity?: {
    tokenVersion: 1;
    contextId: string;
    executionId: string;
    runId: string;
    createdAt: number;
  };
  reservation?: {
    runId: string;
    attempt: number;
    lifecycleGeneration: string;
  };
  foregroundClaims?: {
    lifecycleGeneration: string;
    tokens: string[];
    /** Run identity for claims that have crossed the actual agent-run boundary. */
    runIdsByClaimId?: Record<string, string>;
  };
  tombstone?: {
    reason: string;
    /** Durable successor returned when an explicit rollover request is retried. */
    recoveredSessionId?: string;
    recoveredSessionKey?: string;
  };
};
//#endregion
//#region src/config/sessions/pending-final-delivery-types.d.ts
type PendingFinalDeliveryState = {
  createdAt: number;
  context?: DeliveryContext;
  intentId?: string;
  deliveries?: Array<{
    id: string;
    state: "prepared" | "queued" | "delivered" | "suppressed" | "unknown";
  }>;
} & ({
  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[];
  version?: number;
};
//#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;
    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;
      summaryChars: number;
      summaryHash?: string;
      schemaChars: number;
      schemaHash?: string;
      propertiesCount?: number | null;
    }>;
  };
};
//#endregion
//#region src/config/sessions/session-tool-overrides.d.ts
type SessionToolOverrides = {
  mcpServers?: Record<string, boolean>;
  mcpToolsDeny?: Record<string, string[]>;
  skills?: Record<string, boolean>;
  webSearch?: boolean;
};
//#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/config/sessions/types.d.ts
type SessionChatType = ChatType;
type PersistedSessionRunStatus = SessionRunStatus;
declare const SESSION_TOTAL_TOKENS_VERSION: 1;
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;
};
type AcpSessionBinding = {
  acpBackendId: string;
  acpAgentId: string;
  agentSessionId: string;
};
type SessionContextBudgetStatusRoute = "fits" | "compact_only" | "truncate_tool_results_only" | "compact_then_truncate";
type SessionContextBudgetStatus = {
  schemaVersion: 1;
  source: "pre-prompt-estimate";
  updatedAt: number;
  provider: string;
  model: string;
  route: SessionContextBudgetStatusRoute;
  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 SessionPluginJsonValue = string | number | boolean | null | SessionPluginJsonValue[] | {
  [key: string]: SessionPluginJsonValue;
};
type SessionPluginNextTurnInjection = {
  id: string;
  pluginId: string;
  pluginName?: string;
  text: string;
  idempotencyKey?: string;
  placement: "prepend_context" | "append_context";
  ttlMs?: number;
  createdAt: number;
  metadata?: SessionPluginJsonValue;
};
type SubagentRecoveryState = {
  /** Consecutive accepted automatic orphan-recovery resumes in the rapid re-wedge window. */
  automaticAttempts?: number;
  /** Timestamp (ms) of the latest accepted automatic orphan-recovery resume. */
  lastAttemptAt?: number;
  /** Registry run id that triggered the latest automatic orphan-recovery resume. */
  lastRunId?: string;
  /** Visible execution retained while the recovered run uses an internal transcript. */
  sessionLifecycleRunId?: string;
  /** Timestamp (ms) when automatic recovery was tombstoned for this session. */
  wedgedAt?: number;
  /** Human-readable reason automatic recovery was tombstoned. */
  wedgedReason?: string;
};
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 RestartRecoveryRun = {
  runId: string;
  lifecycleGeneration: string;
};
type SessionEntryCore = SessionRestartRecoveryState & 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, SessionPluginJsonValue>>;
  /** 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;
  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;
  /** 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;
  /** 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$1;
  /** 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;
  /** 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;
  /**
   * 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;
  };
  /** 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;
  /** How this session node came to exist; written once and retained across sessionId rotations. */
  createdVia?: SessionCreatedVia;
  /** 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";
  /** Version of the requester tool-policy snapshot captured when this child was spawned. */
  inheritedToolPolicyVersion?: 1;
  /** 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[];
  systemSent?: boolean;
  abortedLastRun?: boolean;
  /** Interrupted run generations whose late lifecycle events must be ignored. */
  restartRecoveryRuns?: RestartRecoveryRun[];
  /** Keeps automatic restart recovery limited to replay-safe tools until the run terminates. */
  restartRecoveryForceSafeTools?: true;
  /** Durable guard state for automatic subagent orphan recovery. */
  subagentRecovery?: SubagentRecoveryState;
  /** 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;
  /**
   * 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;
    };
  };
  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;
  /** 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";
  queueMode?: QueueMode;
  queueDebounceMs?: number;
  queueCap?: number;
  queueDrop?: "old" | "new" | "summarize";
  inputTokens?: number;
  outputTokens?: number;
  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;
  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$1 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 & {
  /** 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;
  mainRestartRecovery?: MainRestartRecoveryState;
};
interface InternalSessionEntry extends InternalSessionEntryCore {}
type GroupKeyResolution = {
  key: string;
  channel?: string;
  id?: string;
  chatType?: SessionChatType;
};
//#endregion
//#region src/sessions/provider-review.d.ts
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 src/auto-reply/thinking.shared.d.ts
/** Canonical thinking level values accepted by chat commands and session state. */
declare const ALL_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "adaptive", "max", "ultra"];
type ThinkLevel = (typeof ALL_THINKING_LEVELS)[number];
type VerboseLevel = "off" | "on" | "full";
type ReasoningLevel = "off" | "on" | "stream";
/** Prepared model catalog fields reused while choosing and dispatching a queued runtime. */
type ThinkingCatalogEntry = {
  provider: string;
  id: string;
  nativeRuntime?: string;
  api?: string;
  baseUrl?: string;
  contextWindow?: number;
  contextTokens?: number;
  reasoning?: boolean;
  configuredReasoning?: boolean;
  /** Concrete runtime owner of thinking policy; internal and never project to clients. */
  thinkingPolicyProvider?: string;
  thinkingLevelMap?: ThinkingLevelMap;
  input?: readonly ("text" | "image" | "audio" | "video" | "document")[];
  params?: Record<string, unknown>;
  compat?: {
    thinkingFormat?: string;
    supportsReasoningEffort?: boolean;
    supportedReasoningEfforts?: readonly string[] | null;
    reasoningEffortMap?: Record<string, string>;
  } | null;
};
//#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;
}>;
declare namespace admitted_run_context_d_exports {
  export { AdmittedRunContext, AdmittedRunOperatorAuthority, OperationalRunInstanceRef, PreparedAgentRunAdmission, assertAdmittedRunOperatorAuthority, assertOperatorModelAllowed, bindOperatorModelExecution, closeAdmittedRunDelegatedAuthority, createAdmittedRunOperatorAuthority, createExecutionIdentityRecoveryAdmission, createOperationalRunInstanceRef, getAdmittedRunDelegatedAuthority, getAdmittedRunSource, prepareAgentRunAdmission, prepareSystemAgentRunAdmission, readAdmittedRunOperatorAuthority, readPreparedRunOperatorAuthority, readRunOperatorAuthority, resolveAdmittedRunActiveAssertion, resolvePreparedRunAdmission, retainAdmittedRunBeforeToolCallRecovery };
}
/** Operational lifecycle correlation. This is never identity or authorization evidence. */
type OperationalRunInstanceRef = Readonly<{
  instanceId: string;
  runId: string;
}>;
/** 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 AdmittedRunOperatorAuthority = Readonly<{
  profileId: string;
  scopes: readonly string[];
  /** Original access dependency; null is proven independent, undefined is unclassified. */
  gatewayAccessGrant?: GatewayAccessGrantRef | null;
  assertCurrent: () => void;
  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;
  /** Live assignment from the original prepared profile lease. */
  readCurrentRoleAssignment?: (this: void) => string | null;
  /** Prepared role permissions; source-policy changes revoke the owning authority. */
  rolePolicy?: Readonly<{
    sessionAccessCap: GatewayOperatorRoleDefinition["sessions"]["others"];
    sandboxRequired: boolean;
    agents: "*" | readonly string[];
  }>;
  modelPolicy?: PreparedOperatorModelPolicy;
  /** Committed policy changes invalidate only executions using a removed model. */
  onModelPolicyChanged?: (listener: () => void) => () => void;
}>;
/** Host-only construction; public reply options cannot manufacture a source capability. */
declare function createAdmittedRunOperatorAuthority(source: AdmittedRunOperatorAuthority): AdmittedRunOperatorAuthority;
declare function assertAdmittedRunOperatorAuthority(authority: unknown): asserts authority is AdmittedRunOperatorAuthority;
/** Selection never grants authority; callers must pass the original host-issued source. */
declare function assertOperatorModelAllowed(authority: AdmittedRunOperatorAuthority | undefined, model: ProviderModelRef | undefined): void;
/** Keeps one selected model current without revoking other work from the same source. */
declare function bindOperatorModelExecution(authority: AdmittedRunOperatorAuthority | undefined, model: ProviderModelRef | undefined, mapAuthorizationError?: (error: unknown) => Error): Readonly<{
  signal: AbortSignal;
  assertCurrent: () => void;
  release: () => void;
}> | undefined;
/** Prepared and admitted paths share the same source throughout retries and detached work. */
declare function readRunOperatorAuthority(params: {
  preparedRunAdmission?: PreparedAgentRunAdmission;
  admittedRunContext?: AdmittedRunContext;
}): AdmittedRunOperatorAuthority | undefined;
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;
}>;
/** Reads the immutable outer-run authority without reviving a closed claim. */
declare function getAdmittedRunDelegatedAuthority(context: AdmittedRunContext): AgentRunDelegatedAuthority | undefined;
/** Captures the operator's source lifetime from a live run, including for detached children. */
declare function readAdmittedRunOperatorAuthority(context: AdmittedRunContext | undefined): AdmittedRunOperatorAuthority | undefined;
/** Reads the same source ceiling used by admission without minting run authority. */
declare function readPreparedRunOperatorAuthority(prepared: PreparedAgentRunAdmission | undefined): AdmittedRunOperatorAuthority | undefined;
/** Reads the original admission source only through its exact live authority. */
declare function getAdmittedRunSource(authority: AgentRunDelegatedAuthority | undefined): AdmittedRunContext["admissionSource"];
/** Captures an exact admitted-run assertion for work that may cross an await boundary. */
declare function resolveAdmittedRunActiveAssertion(context: AdmittedRunContext, signal?: AbortSignal): (() => void) | undefined;
/** Idempotently compare-releases the authority captured by this admission. */
declare function closeAdmittedRunDelegatedAuthority(context: AdmittedRunContext): boolean;
type AdmittedRunBeforeToolCallRecovery = Readonly<{
  assertActive: () => void;
  release: () => void;
}>;
/** Recovery-only lease for the already-created native pre-tool policy callback. */
declare function retainAdmittedRunBeforeToolCallRecovery(context: AdmittedRunContext): AdmittedRunBeforeToolCallRecovery | undefined;
type ExecutionIdentityRecoveryAdmission = Readonly<{
  /** Recovery retries never manufacture replacement identity when exact evidence is absent. */
  retryOnly: boolean;
  consume: (runId: string) => Readonly<{
    accepted: boolean;
    token?: ExecutionIdentityAdmissionToken;
  }>;
}>;
/** Creates a one-shot recovery admission owned by the durable recovery resolver. */
declare function createExecutionIdentityRecoveryAdmission(params: {
  retryOnly: boolean;
  token?: ExecutionIdentityAdmissionToken;
  expectedOperationalRunId?: string;
}): ExecutionIdentityRecoveryAdmission;
declare function createOperationalRunInstanceRef(runId: string): OperationalRunInstanceRef;
/** Prepares a system-owned run without selecting its eventual execution runtime early. */
declare function prepareSystemAgentRunAdmission(cfg: OpenClawConfig, runId: string, agentId: string, boundary: string, assertSourceCurrent?: () => void, operatorAuthority?: AdmittedRunOperatorAuthority): PreparedAgentRunAdmission;
/**
 * Freezes ingress facts before preparation while deferring allocation/capture until the
 * authoritative runtime owner is selected immediately before execution.
 */
declare function prepareAgentRunAdmission(params: {
  cfg: OpenClawConfig;
  admissionSource?: AdmittedRunContext["admissionSource"];
  facts: Omit<ExecutionIdentityAdmissionFacts, "runtime">;
  operationalRunInstance: OperationalRunInstanceRef;
  recovery?: ExecutionIdentityRecoveryAdmission;
  onAdmitted?: (context: AdmittedRunContext) => void | Promise<void>;
  assertSourceCurrent?: () => void;
  operatorAuthority?: AdmittedRunOperatorAuthority;
}): PreparedAgentRunAdmission;
/** Resolves a host-only continuation or validates an already-admitted internal caller. */
declare function resolvePreparedRunAdmission(params: {
  runId: string;
  runtimeKind: ExecutionIdentityAdmissionFacts["runtime"]["kind"];
  runtimeInstanceId?: string;
  admittedRunContext?: AdmittedRunContext;
  preparedRunAdmission?: PreparedAgentRunAdmission;
}): Promise<AdmittedRunContext>;
//#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;
  completionOwnerSessionKey?: string;
  resolvedModel?: ProviderModelRef;
  inheritedPermissionMode?: SessionPermissionMode;
  inheritedToolPolicy: {
    version: 1;
    allow: string[];
    deny: string[];
  };
  spawnModelAutoSelection?: AgentRuntimeSpawnModelAutoSelection;
};
//#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/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/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_NAMES: readonly ["send", "broadcast", "poll", "poll-vote", "react", "reactions", "read", "edit", "unsend", "reply", "sendWithEffect", "renameGroup", "setGroupIcon", "addParticipant", "removeParticipant", "leaveGroup", "sendAttachment", "delete", "pin", "unpin", "list-pins", "permissions", "thread-create", "thread-list", "thread-reply", "search", "sticker", "sticker-search", "member-info", "role-info", "emoji-list", "emoji-upload", "sticker-upload", "role-add", "role-remove", "channel-info", "channel-list", "channel-create", "conversation-open", "channel-edit", "channel-delete", "channel-move", "category-create", "category-edit", "category-delete", "topic-create", "topic-edit", "voice-status", "event-list", "event-create", "timeout", "kick", "ban", "set-profile", "set-presence", "download-file", "upload-file"];
/**
 * Message action name union derived from the canonical action list.
 */
type ChannelMessageActionName = (typeof CHANNEL_MESSAGE_ACTION_NAMES)[number];
//#endregion
//#region src/media/load-options.d.ts
/** Host callback used to read an already-authorized outbound media file. */
type OutboundMediaReadFile = (filePath: string) => Promise<Buffer>;
/** Host-provided file access used when a runtime can read outbound media from local disk. */
type OutboundMediaAccess = {
  localRoots?: readonly string[];
  readFile?: OutboundMediaReadFile;
  /** Agent workspace directory for resolving relative media paths. */
  workspaceDir?: string;
};
//#endregion
//#region src/channels/message-access/identifier-authentication.d.ts
/** Ordered strength of one identifier-authentication claim. */
type IdentifierAuthentication = "verified" | "asserted" | "unverified" | "mutable";
//#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;
};
//#endregion
//#region src/polls.d.ts
type PollInput = {
  question: string;
  options: string[];
  maxSelections?: number;
  /**
   * Poll duration in seconds.
   * Channel-specific limits apply in each owning plugin.
   */
  durationSeconds?: number;
  /**
   * Poll duration in hours.
   * Used by channels that model duration in hours.
   */
  durationHours?: number;
};
//#endregion
//#region src/channels/message/types.d.ts
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"];
/** Durable final delivery capability key understood by message-channel adapters. */
type DurableFinalDeliveryCapability = (typeof durableFinalDeliveryCapabilities)[number];
/** Capability map used by adapters to declare which final-send guarantees they support. */
type DurableFinalDeliveryRequirementMap = Partial<Record<DurableFinalDeliveryCapability, boolean>>;
/** Raw platform result shape normalized into a message receipt. */
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>;
};
/** Logical part kind for multi-part rendered messages. */
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[];
};
/** Render-plan item category used before adapter-specific send execution. */
type RenderedMessageBatchPlanKind = "text" | "media" | "voice" | "presentation" | "interactive" | "channelData" | "empty";
/** Render plan for a single reply payload after text/media/presentation splitting. */
type RenderedMessageBatchPlanItem = {
  index: number;
  kinds: readonly RenderedMessageBatchPlanKind[];
  text?: string;
  mediaUrls: readonly string[];
  audioAsVoice?: boolean;
  presentationBlockCount?: number;
  hasInteractive?: boolean;
  hasChannelData?: boolean;
};
/** Aggregate render plan for a batch of reply payloads. */
type RenderedMessageBatchPlan = {
  payloadCount: number;
  textCount: number;
  mediaCount: number;
  voiceCount: number;
  presentationCount: number;
  interactiveCount: number;
  channelDataCount: number;
  items: readonly RenderedMessageBatchPlanItem[];
};
/** Common text-send context shared by text, media, payload, and poll adapter calls. */
type ChannelMessageSendTextContext<TConfig = OpenClawConfig> = {
  cfg: TConfig;
  to: string;
  text: 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;
};
/** Media send context with validated access hooks and media presentation hints. */
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;
};
/** Rich reply payload send context used when adapters can consume structured payloads. */
type ChannelMessageSendPayloadContext<TConfig = OpenClawConfig> = Omit<ChannelMessageSendMediaContext<TConfig>, "mediaUrl"> & {
  payload: ReplyPayload;
  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;
};
/** Adapter send result normalized to a receipt plus optional legacy message id. */
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];
/** Send-attempt context tagged with the adapter method core is about to call. */
type ChannelMessageSendAttemptContext<TConfig = OpenClawConfig> = (ChannelMessageSendTextContext<TConfig> & {
  kind: "text";
}) | (ChannelMessageSendMediaContext<TConfig> & {
  kind: "media";
}) | (ChannelMessageSendPayloadContext<TConfig> & {
  kind: "payload";
}) | (ChannelMessageSendPollContext<TConfig> & {
  kind: "poll";
});
/** Lifecycle context emitted after an adapter send succeeds but before commit finishes. */
type ChannelMessageSendSuccessContext<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = ChannelMessageSendAttemptContext<TConfig> & {
  result: TSendResult;
  attemptToken?: unknown;
};
/** Lifecycle context emitted after an adapter send throws or rejects. */
type ChannelMessageSendFailureContext<TConfig = OpenClawConfig> = ChannelMessageSendAttemptContext<TConfig> & {
  error: unknown;
  attemptToken?: unknown;
};
/** Lifecycle context emitted when a successful send is being durably committed. */
type ChannelMessageSendCommitContext<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = ChannelMessageSendSuccessContext<TConfig, TSendResult>;
/** Durable queue context used to reconcile a send whose platform state is 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[];
  renderedBatchPlan?: RenderedMessageBatchPlan;
  replyToId?: string | null;
  replyToMode?: ReplyToMode;
  threadId?: string | number | null;
  silent?: boolean;
};
/** Adapter verdict for whether an unknown queued send reached the platform. */
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;
};
/** Minimal context available at deferred-delivery admission boundaries. */
type ChannelMessageDeferredDeliveryAdmissionContext<TConfig = OpenClawConfig> = {
  cfg: TConfig;
  channel: string;
  to: string;
  accountId?: string | null;
  phase: "live" | "recovery";
};
/** Optional hooks around adapter send attempts, platform success/failure, and commit. */
type ChannelMessageSendLifecycleAdapter<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = {
  beforeSendAttempt?: (ctx: ChannelMessageSendAttemptContext<TConfig>) => unknown;
  afterSendSuccess?: (ctx: ChannelMessageSendSuccessContext<TConfig, TSendResult>) => Promise<void> | void;
  afterSendFailure?: (ctx: ChannelMessageSendFailureContext<TConfig>) => Promise<void> | void;
  afterCommit?: (ctx: ChannelMessageSendCommitContext<TConfig, TSendResult>) => Promise<void> | void;
};
/** Adapter methods a message channel can implement for outbound text/media/payload/poll sends. */
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>;
};
/** Durable final-delivery extension for queue reconciliation and capability declaration. */
type ChannelMessageDurableFinalAdapter = {
  capabilities?: DurableFinalDeliveryRequirementMap;
  /** Opt into provider reconciliation for ordinary single-payload queued sends. */
  automaticUnknownSendReconciliation?: 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;
};
/** Live-message feature key declared by adapters that support preview or streaming behavior. */
type ChannelMessageLiveCapability = (typeof channelMessageLiveCapabilities)[number];
/** Canonical ordered list of live-message feature keys. */
declare const channelMessageLiveCapabilities: readonly ["draftPreview", "previewFinalization", "progressUpdates", "nativeStreaming", "quietFinalization"];
/** Capability keys for turning a preview into a final platform message. */
declare const livePreviewFinalizerCapabilities: readonly ["finalEdit", "normalFallback", "discardPending", "previewReceipt", "retainOnAmbiguousFailure"];
/** Finalizer capability key understood by live-message adapters. */
type LivePreviewFinalizerCapability = (typeof livePreviewFinalizerCapabilities)[number];
/** Capability map for preview finalization behavior. */
type LivePreviewFinalizerCapabilityMap = Partial<Record<LivePreviewFinalizerCapability, boolean>>;
/** Adapter shape for finalizing live previews. */
type ChannelMessageLiveFinalizerAdapterShape = {
  capabilities?: LivePreviewFinalizerCapabilityMap;
};
/** Adapter shape for live preview and streaming message features. */
type ChannelMessageLiveAdapterShape = {
  capabilities?: Partial<Record<ChannelMessageLiveCapability, boolean>>;
  finalizer?: ChannelMessageLiveFinalizerAdapterShape;
};
/** Receive acknowledgement timing policy for durable inbound message records. */
type ChannelMessageReceiveAckPolicy = (typeof channelMessageReceiveAckPolicies)[number];
/** Canonical ordered list of receive acknowledgement policies. */
declare const channelMessageReceiveAckPolicies: readonly ["after_receive_record", "after_agent_dispatch", "after_durable_send", "manual"];
/** Adapter receive shape for default and supported inbound acknowledgement policies. */
type ChannelMessageReceiveAdapterShape = {
  defaultAckPolicy?: ChannelMessageReceiveAckPolicy;
  supportedAckPolicies?: readonly ChannelMessageReceiveAckPolicy[];
};
/** Full message adapter shape composed from send, durable-final, live, and receive facets. */
type ChannelMessageAdapterShape<TConfig = OpenClawConfig, TSendResult extends ChannelMessageSendResult = ChannelMessageSendResult> = {
  id?: string;
  durableFinal?: ChannelMessageDurableFinalAdapter;
  send?: ChannelMessageSendAdapter<TConfig, TSendResult>;
  live?: ChannelMessageLiveAdapterShape;
  receive?: ChannelMessageReceiveAdapterShape;
};
//#endregion
//#region src/channels/ids.d.ts
/**
 * Canonical chat channel id used by core routing, plugin config, and channel catalogs.
 */
type ChatChannelId = string;
//#endregion
//#region src/channels/plugins/channel-id.types.d.ts
/**
 * Channel id accepted by plugin helpers, covering built-in chat ids and external plugin ids.
 */
type ChannelId$1 = ChatChannelId | (string & {});
//#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/setup-input.d.ts
type ChannelSetupEnvelope = {
  name?: string;
  token?: string;
  tokenFile?: string;
  useEnv?: boolean;
  defaultTo?: string;
  allowFrom?: string[];
};
/**
 * Compatibility fields with known published readers in the 2026-07-22 registry sweep.
 * Each field is deleted as soon as no published plugin reads it; no version boundary is needed.
 */
type DeprecatedChannelSetupFields = {
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  privateKey?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  secret?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  botToken?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  appToken?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  signingSecret?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  mode?: "socket" | "http" | "relay";
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  cliPath?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  authDir?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  httpUrl?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  httpPort?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  webhookPath?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  webhookUrl?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  userId?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  accessToken?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  password?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  deviceName?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  url?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  baseUrl?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  code?: string;
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  groupChannels?: string[];
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  dmAllowlist?: string[];
  /** @deprecated Declare this field in the owning plugin's setup input type: https://docs.openclaw.ai/plugins/sdk-setup#channel-owned-setup-input-fields. Removed once no published plugin reads it. */
  autoDiscoverChannels?: boolean;
};
/** Generic setup envelope used by CLI, onboarding, and channel-owned setup adapters. */
type ChannelSetupInput = ChannelSetupEnvelope & DeprecatedChannelSetupFields;
//#endregion
//#region src/channels/plugins/types.core.d.ts
type ChannelExposure = {
  configured?: boolean;
  setup?: boolean;
  docs?: boolean;
};
type ChannelOutboundTargetMode = "explicit" | "implicit" | "heartbeat";
/** Agent tool registered by a channel plugin. */
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 ChannelMessageToolMediaSourceParams = readonly string[] | Partial<Record<ChannelMessageActionName, readonly string[]>>;
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?: ChannelMessageToolMediaSourceParams | null;
};
type ChannelStatusIssue = {
  channel: ChannelId$1;
  accountId: string;
  kind: "intent" | "permissions" | "config" | "auth" | "runtime";
  message: string;
  fix?: string;
};
type ChannelAccountState = "linked" | "not linked" | "configured" | "not configured" | "enabled" | "disabled";
type ChannelHeartbeatDeps = {
  webAuthExists?: () => Promise<boolean>;
  hasActiveWebListener?: (accountId?: string) => boolean;
};
/** User-facing metadata used in docs, pickers, and setup surfaces. */
type ChannelMeta = {
  id: ChannelId$1;
  label: string;
  selectionLabel: string;
  docsPath: string;
  docsLabel?: string;
  blurb: string;
  order?: number;
  aliases?: readonly string[];
  selectionDocsPrefix?: string;
  selectionDocsOmitLabel?: boolean;
  selectionExtras?: readonly string[];
  detailLabel?: string;
  systemImage?: string;
  markdownCapable?: boolean;
  exposure?: ChannelExposure;
  quickstartAllowFrom?: boolean;
  forceAccountBinding?: boolean;
  preferSessionLookupForAnnounceTarget?: boolean;
  preferOver?: readonly string[];
};
/** Snapshot row returned by channel status and lifecycle surfaces. */
type ChannelAccountSnapshot = {
  accountId: string;
  name?: string;
  enabled?: boolean;
  configured?: boolean;
  statusState?: string;
  linked?: boolean;
  running?: boolean;
  connected?: boolean;
  restartPending?: boolean;
  reconnectAttempts?: number;
  lastConnectedAt?: number | null;
  lastDisconnect?: string | {
    at: number;
    status?: number;
    error?: string;
    loggedOut?: boolean;
  } | null;
  lastMessageAt?: number | null;
  lastEventAt?: number | null;
  lastTransportActivityAt?: number | null;
  stateReason?: string;
  lastError?: string | null;
  /**
   * 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;
  lastStartAt?: number | null;
  lastStopAt?: number | null;
  lastInboundAt?: number | null;
  lastOutboundAt?: number | null;
  busy?: boolean;
  activeRuns?: number;
  lastRunActivityAt?: number | null;
  activeRunStartedAt?: number | null;
  mode?: string;
  dmPolicy?: string;
  allowFrom?: string[];
  tokenSource?: string;
  botTokenSource?: string;
  appTokenSource?: string;
  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;
  baseUrl?: string;
  allowUnmentionedGroups?: boolean;
  cliPath?: string | null;
  dbPath?: string | null;
  port?: number | null;
  probe?: unknown;
  lastProbeAt?: number | null;
  audit?: unknown;
  application?: unknown;
  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;
};
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";
};
/** Static capability flags advertised by a channel plugin. */
type ChannelCapabilities = {
  chatTypes: Array<ChatType | "thread">;
  polls?: boolean;
  reactions?: boolean;
  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 ChannelCrossContextPresentationFactory = (params: {
  originLabel: string;
  message: string;
  cfg: OpenClawConfig;
  accountId?: string | null;
}) => MessagePresentation;
type ChannelReplyTransport = {
  replyToId?: string | null;
  /** Mark a channel-inferred target so outbound delivery can consume first-mode replies. */
  replyToIdSource?: "implicit";
  threadId?: string | number | null;
};
type ChannelFocusedBindingContext = {
  conversationId: string;
  parentConversationId?: string;
  placement: "current" | "child";
  labelNoun: string;
};
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: "direct" | "group" | "channel";
  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";
  matchesToolContextTarget?: (params: {
    target: string;
    toolContext: ChannelThreadingToolContext;
  }) => boolean;
  resolveReplyToMode?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    chatType?: string | null;
  }) => "off" | "first" | "all" | "batched";
  /**
   * 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;
  }) => ChannelReplyTransport | null;
  resolveFocusedBinding?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    context: ChannelThreadingContext;
  }) => ChannelFocusedBindingContext | 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?: "off" | "first" | "all" | "batched";
  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[];
  /** Re-resolve the current owner when channel behavior exceeds generic bindings. */
  resolveConversationRouteOwner?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    conversation: {
      kind: "direct" | "group" | "channel";
      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;
  /** 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$1;
  normalizeExplicitSessionKey?: (params: {
    sessionKey: string;
    ctx: MsgContext;
  }) => string | undefined;
  deriveLegacySessionChatType?: (sessionKey: string) => "direct" | "group" | "channel" | 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?: ChannelCrossContextPresentationFactory;
  transformReplyPayload?: (params: {
    payload: ReplyPayload;
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => ReplyPayload | null;
  hasStructuredReplyPayload?: (params: {
    payload: ReplyPayload;
  }) => 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;
  }) => ChannelOutboundSessionRoute | Promise<ChannelOutboundSessionRoute | null> | null;
};
type ChannelAgentPromptAdapter = {
  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;
  /** 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;
};
type ChannelMessagePreparedSendPayloadContext = {
  ctx: ChannelMessageActionContext;
  to: string;
  payload: ReplyPayload;
  replyToId?: string | null;
  /** Preserve caller intent when plugins translate reply ids into durable payloads. */
  replyToIdSource?: "explicit" | "implicit";
  threadId?: string | number | null;
};
/** 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;
  /** 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: ChannelMessagePreparedSendPayloadContext) => ReplyPayload | null | undefined | Promise<ReplyPayload | 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" | "onPlatformSendDispatch" | "assertDirectAdapterHandoff"> & {
  content?: string;
  /** Trusted originating turn context for channel-owned delivery correlation. */
  sessionKey?: string;
  inboundEventKind?: InboundEventKind;
};
//#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/channels/plugins/approval-native.types.d.ts
/**
 * Native channel surface that can receive approval prompts.
 */
type ChannelApprovalNativeSurface = "origin" | "approver-dm";
/**
 * Native channel destination for an approval prompt.
 */
type ChannelApprovalNativeTarget = {
  to: string;
  threadId?: string | number | null;
};
/**
 * Preferred native delivery surface for approval prompts.
 */
type ChannelApprovalNativeDeliveryPreference = ChannelApprovalNativeSurface | "both";
/**
 * Approval request shapes supported by native channel approval delivery.
 */
type ChannelApprovalNativeRequest = ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
/**
 * Capabilities returned by native channel approval delivery inspection.
 */
type ChannelApprovalNativeDeliveryCapabilities = {
  enabled: boolean;
  preferredSurface: ChannelApprovalNativeDeliveryPreference;
  supportsOriginSurface: boolean;
  supportsApproverDmSurface: boolean;
  notifyOriginWhenDmOnly?: boolean;
};
type ChannelApprovalNativeContext = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  approvalKind: ChannelApprovalKind;
  request: ChannelApprovalNativeRequest;
};
/**
 * Adapter implemented by channel plugins that support native approval delivery.
 */
type ChannelApprovalNativeAdapter = {
  describeDeliveryCapabilities: (params: ChannelApprovalNativeContext) => ChannelApprovalNativeDeliveryCapabilities;
  resolveOriginTarget?: (params: ChannelApprovalNativeContext) => ChannelApprovalNativeTarget | null | Promise<ChannelApprovalNativeTarget | null>;
  resolveApproverDmTargets?: (params: ChannelApprovalNativeContext) => ChannelApprovalNativeTarget[] | Promise<ChannelApprovalNativeTarget[]>;
};
//#endregion
//#region src/infra/approval-native-delivery.d.ts
/** One native approval delivery target selected by the channel adapter plan. */
type ChannelApprovalNativePlannedTarget = {
  surface: ChannelApprovalNativeSurface;
  target: ChannelApprovalNativeTarget;
  reason: "preferred" | "fallback";
};
//#endregion
//#region src/infra/approval-native-runtime-types.d.ts
/** Prepared delivery target plus the stable key used to avoid duplicate native messages. */
type PreparedChannelNativeApprovalTarget<TPreparedTarget> = {
  dedupeKey: string;
  target: TPreparedTarget;
};
//#endregion
//#region src/infra/approval-view-model.types.d.ts
type ApprovalPhase = "pending" | "resolved" | "expired";
/** Button or command action shown with a pending approval prompt. */
type ApprovalActionView = {
  kind?: "command" | "decision";
  decision: ExecApprovalDecision;
  label: string;
  style: NonNullable<MessagePresentationButton["style"]>;
  action?: MessagePresentationAction;
  /** Copyable command fallback for non-interactive surfaces. */
  command: string;
};
/** Label/value metadata row rendered with an approval prompt. */
type ApprovalMetadataView = {
  label: string;
  value: string;
};
type ApprovalViewBase = {
  approvalId: string;
  approvalKind: ChannelApprovalKind;
  phase: ApprovalPhase;
  title: string;
  description?: string | null;
  metadata: ApprovalMetadataView[];
};
/** Shared presentation fields for exec approval views across all phases. */
type ExecApprovalViewBase = ApprovalViewBase & {
  approvalKind: "exec";
  ask?: string | null;
  agentId?: string | null;
  warningText?: string | null;
  commandAnalysis?: CommandExplanationSummary | null;
  commandText: string;
  commandPreview?: string | null;
  cwd?: string | null;
  envKeys?: readonly string[];
  host?: string | null;
  nodeId?: string | null;
  scope?: ApprovalScope | null;
  sessionKey?: string | null;
};
/** Pending exec approval view, including executable reply actions. */
type ExecApprovalPendingView = ExecApprovalViewBase & {
  phase: "pending";
  actions: ApprovalActionView[];
  expiresAtMs: number;
};
/** Resolved exec approval view with the recorded decision. */
type ExecApprovalResolvedView = ExecApprovalViewBase & {
  phase: "resolved";
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
};
/** Expired exec approval view without reply actions. */
type ExecApprovalExpiredView = ExecApprovalViewBase & {
  phase: "expired";
};
/** Shared presentation fields for plugin approval views across all phases. */
type PluginApprovalViewBase = ApprovalViewBase & {
  approvalKind: "plugin";
  agentId?: string | null;
  pluginId?: string | null;
  scope?: ApprovalScope | null;
  toolName?: string | null;
  severity: "info" | "warning" | "critical";
};
/** Pending plugin approval view, including executable reply actions. */
type PluginApprovalPendingView = PluginApprovalViewBase & {
  phase: "pending";
  actions: ApprovalActionView[];
  expiresAtMs: number;
};
/** Resolved plugin approval view with the recorded decision. */
type PluginApprovalResolvedView = PluginApprovalViewBase & {
  phase: "resolved";
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
};
/** Expired plugin approval view without reply actions. */
type PluginApprovalExpiredView = PluginApprovalViewBase & {
  phase: "expired";
};
/** Shared presentation fields for OpenClaw system change approvals. */
type SystemAgentApprovalViewBase = ApprovalViewBase & {
  approvalKind: "system-agent";
  agentId?: string | null;
  scope?: null;
  commandText: string;
  commandPreview?: string | null;
  ask?: string | null;
  cwd?: string | null;
  envKeys?: readonly string[];
  host?: string | null;
  nodeId?: string | null;
  sessionKey?: string | null;
  operationSummary: string;
};
/** Pending system change approval view, including executable reply actions. */
type SystemAgentApprovalPendingView = SystemAgentApprovalViewBase & {
  phase: "pending";
  actions: ApprovalActionView[];
  expiresAtMs: number;
};
/** Resolved system change approval view with the recorded decision. */
type SystemAgentApprovalResolvedView = SystemAgentApprovalViewBase & {
  phase: "resolved";
  decision: ExecApprovalDecision;
  resolvedBy?: string | null;
  applicationStatus?: SystemAgentApprovalApplicationStatus;
  terminalStatus?: "expired" | "cancelled";
};
/** Expired system change approval view without reply actions. */
type SystemAgentApprovalExpiredView = SystemAgentApprovalViewBase & {
  phase: "expired";
};
/** Any pending approval view that still accepts a user decision. */
type PendingApprovalView = ExecApprovalPendingView | PluginApprovalPendingView | SystemAgentApprovalPendingView;
/** Any approval view after a decision was recorded. */
type ResolvedApprovalView = ExecApprovalResolvedView | PluginApprovalResolvedView | SystemAgentApprovalResolvedView;
/** Any approval view after it can no longer be acted on. */
type ExpiredApprovalView = ExecApprovalExpiredView | PluginApprovalExpiredView | SystemAgentApprovalExpiredView;
//#endregion
//#region src/infra/approval-handler-runtime-types.d.ts
/** Backward-compatible approval request accepted by public plugin callbacks. */
type ApprovalRequest = ApprovalRequestInput;
/** Shared context passed to channel-native approval hooks. */
type ChannelApprovalCapabilityHandlerContext = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  gatewayUrl?: string;
  context?: unknown;
};
/** Result instruction for updating, deleting, clearing, or leaving a delivered approval entry. */
type ChannelApprovalNativeFinalAction<TPayload> = {
  kind: "update";
  payload: TPayload;
} | {
  kind: "delete";
} | {
  kind: "clear-actions";
} | {
  kind: "leave";
};
/** Availability gate for deciding whether a channel-native approval runtime can handle work. */
type ChannelApprovalNativeAvailabilityAdapter = {
  isConfigured: (params: ChannelApprovalCapabilityHandlerContext) => boolean;
  shouldHandle: (params: ChannelApprovalCapabilityHandlerContext & {
    request: ApprovalRequest;
    /** Payload-derived owner; channel adapters must not infer ownership from the id. */
    approvalKind: ChannelApprovalKind;
  }) => boolean;
};
type ChannelApprovalNativePresentationAdapterForView<TPendingPayload = unknown, TFinalPayload = unknown, TPendingEntry = unknown, TPendingView extends PendingApprovalView = PendingApprovalView, TResolvedView extends ResolvedApprovalView = ResolvedApprovalView, TExpiredView extends ExpiredApprovalView = ExpiredApprovalView> = {
  buildPendingPayload: (params: ChannelApprovalCapabilityHandlerContext & {
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    nowMs: number;
    view: TPendingView;
  }) => TPendingPayload | Promise<TPendingPayload>;
  buildResolvedResult: (params: ChannelApprovalCapabilityHandlerContext & {
    request: ApprovalRequest;
    resolved: ApprovalResolved;
    view: TResolvedView;
    entry: TPendingEntry;
  }) => ChannelApprovalNativeFinalAction<TFinalPayload> | Promise<ChannelApprovalNativeFinalAction<TFinalPayload>>;
  buildExpiredResult: (params: ChannelApprovalCapabilityHandlerContext & {
    request: ApprovalRequest;
    view: TExpiredView;
    entry: TPendingEntry;
  }) => ChannelApprovalNativeFinalAction<TFinalPayload> | Promise<ChannelApprovalNativeFinalAction<TFinalPayload>>;
};
/** Builds channel-native payloads for pending, resolved, and expired approval views. */
type ChannelApprovalNativePresentationAdapter<TPendingPayload = unknown, TFinalPayload = unknown> = ChannelApprovalNativePresentationAdapterForView<TPendingPayload, TFinalPayload>;
type ChannelApprovalNativeTransportAdapterForView<TPreparedTarget = unknown, TPendingEntry = unknown, TPendingPayload = unknown, TFinalPayload = unknown, TPendingView extends PendingApprovalView = PendingApprovalView> = {
  prepareTarget: (params: ChannelApprovalCapabilityHandlerContext & {
    plannedTarget: ChannelApprovalNativePlannedTarget;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
  }) => PreparedChannelNativeApprovalTarget<TPreparedTarget> | null | Promise<PreparedChannelNativeApprovalTarget<TPreparedTarget> | null>;
  deliverPending: (params: ChannelApprovalCapabilityHandlerContext & {
    plannedTarget: ChannelApprovalNativePlannedTarget;
    preparedTarget: TPreparedTarget;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
  }) => TPendingEntry | null | Promise<TPendingEntry | null>;
  updateEntry?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    payload: TFinalPayload;
    phase: "resolved" | "expired";
  }) => Promise<void>;
  deleteEntry?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    phase: "resolved" | "expired";
  }) => Promise<void>;
};
/** Transport hooks for preparing, delivering, updating, and deleting native approval entries. */
type ChannelApprovalNativeTransportAdapter<TPreparedTarget = unknown, TPendingEntry = unknown, TPendingPayload = unknown, TFinalPayload = unknown> = ChannelApprovalNativeTransportAdapterForView<TPreparedTarget, TPendingEntry, TPendingPayload, TFinalPayload>;
type ChannelApprovalNativeInteractionAdapterForView<TPendingEntry = unknown, TBinding = unknown, TPendingPayload = unknown, TPendingView extends PendingApprovalView = PendingApprovalView> = {
  bindPending?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
  }) => TBinding | null | Promise<TBinding | null>;
  unbindPending?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    binding: TBinding;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
  }) => Promise<void> | void;
  clearPendingActions?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    phase: "resolved" | "expired";
  }) => Promise<void>;
  cancelDelivered?: (params: ChannelApprovalCapabilityHandlerContext & {
    entry: TPendingEntry;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
  }) => Promise<void> | void;
};
/** Optional hooks for binding and clearing interactive approval controls. */
type ChannelApprovalNativeInteractionAdapter<TPendingEntry = unknown, TBinding = unknown> = ChannelApprovalNativeInteractionAdapterForView<TPendingEntry, TBinding>;
type ChannelApprovalNativeObserveAdapterForView<TPreparedTarget = unknown, TPendingPayload = unknown, TPendingEntry = unknown, TPendingView extends PendingApprovalView = PendingApprovalView> = {
  onDeliveryError?: (params: ChannelApprovalCapabilityHandlerContext & {
    error: unknown;
    plannedTarget: ChannelApprovalNativePlannedTarget;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
  }) => void;
  onDuplicateSkipped?: (params: ChannelApprovalCapabilityHandlerContext & {
    plannedTarget: ChannelApprovalNativePlannedTarget;
    preparedTarget: PreparedChannelNativeApprovalTarget<TPreparedTarget>;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
  }) => void;
  onDelivered?: (params: ChannelApprovalCapabilityHandlerContext & {
    plannedTarget: ChannelApprovalNativePlannedTarget;
    preparedTarget: PreparedChannelNativeApprovalTarget<TPreparedTarget>;
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    view: TPendingView;
    pendingPayload: TPendingPayload;
    entry: TPendingEntry;
  }) => void;
  /** Runs after every terminal entry for one approval has been finalized. */
  onFinalized?: (params: ChannelApprovalCapabilityHandlerContext & {
    request: ApprovalRequest;
    approvalKind: ChannelApprovalKind;
    phase: "resolved" | "expired";
  }) => void;
};
/** Optional observer hooks for delivery errors, duplicates, and successful deliveries. */
type ChannelApprovalNativeObserveAdapter<TPreparedTarget = unknown, TPendingPayload = unknown, TPendingEntry = unknown> = ChannelApprovalNativeObserveAdapterForView<TPreparedTarget, TPendingPayload, TPendingEntry>;
/** Runtime adapter consumed by core after a plugin's strongly typed spec has been erased. */
type ChannelApprovalNativeRuntimeAdapter<TPendingPayload = unknown, TPreparedTarget = unknown, TPendingEntry = unknown, TBinding = unknown, TFinalPayload = unknown> = {
  eventKinds?: readonly ChannelApprovalKind[];
  /**
   * Trusted legacy ownership override retained for compatibility.
   * @deprecated Omit this so core derives approval ownership from the request payload.
   */
  resolveApprovalKind?: (request: ApprovalRequest) => ChannelApprovalKind;
  availability: ChannelApprovalNativeAvailabilityAdapter;
  presentation: ChannelApprovalNativePresentationAdapter<TPendingPayload, TFinalPayload>;
  transport: ChannelApprovalNativeTransportAdapter<TPreparedTarget, TPendingEntry, TPendingPayload, TFinalPayload>;
  interactions?: ChannelApprovalNativeInteractionAdapter<TPendingEntry, TBinding>;
  observe?: ChannelApprovalNativeObserveAdapter;
};
//#endregion
//#region src/routing/resolve-route.d.ts
type RoutePeer = {
  kind: ChatType;
  id: string;
};
type ResolveAgentRouteInput = {
  cfg: OpenClawConfig;
  channel: string;
  /** Known owner when no configured binding matches this route. */
  defaultAgentId?: string;
  accountId?: string | null;
  peer?: RoutePeer | null;
  dmScope?: DmScope;
  groupScope?: GroupScope;
  /** Parent peer for threads — used for binding inheritance when peer doesn't match directly. */
  parentPeer?: RoutePeer | null;
  guildId?: string | null;
  teamId?: string | null;
  /** Discord member role IDs — used for role-based agent routing. */
  memberRoleIds?: string[];
};
type ResolvedAgentRoute = {
  agentId: string;
  channel: string;
  accountId: string;
  /** Effective direct-message scope after a matching binding override. */
  dmScope?: DmScope;
  groupScope?: GroupScope;
  /** Internal session key used for persistence + concurrency. */
  sessionKey: string;
  /** Convenience alias for direct-chat collapse. */
  mainSessionKey: string;
  /** Which session should receive inbound last-route updates. */
  lastRoutePolicy: "main" | "session";
  /** Match description for debugging/logging. */
  matchedBy: "binding.peer" | "binding.peer.parent" | "binding.peer.wildcard" | "binding.guild+roles" | "binding.guild" | "binding.team" | "binding.account" | "binding.channel" | "default";
};
declare function buildAgentSessionKey(params: {
  agentId: string;
  mainKey?: string;
  channel: string;
  accountId?: string | null;
  peer?: RoutePeer | null;
  /** DM session scope. */
  dmScope?: DmScope;
  groupScope?: GroupScope;
  identityLinks?: Record<string, string[]>;
}): string;
declare function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentRoute;
//#endregion
//#region src/channels/plugins/setup-adapter.types.d.ts
type ChannelSetupAdapter<Input extends {
  name?: string;
} = ChannelSetupInput> = {
  /** Prepared plugin-owned policy for setup outside a published Gateway metadata generation. */
  accountKeyPolicy?: ChannelAccountKeyPolicy;
  /** Keep root config as an independent identity when the host adds named accounts. */
  configPromotion?: "preserve-root";
  resolveAccountId?: (params: {
    cfg: OpenClawConfig;
    accountId?: string;
    input?: Input;
  }) => string;
  prepareAccountConfigInput?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: Input;
    runtime: RuntimeEnv;
  }) => Promise<Input> | Input;
  resolveBindingAccountId?: (params: {
    cfg: OpenClawConfig;
    agentId: string;
    accountId?: string;
  }) => string | undefined;
  applyAccountName?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    name?: string;
  }) => OpenClawConfig;
  applyAccountConfig: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: Input;
  }) => OpenClawConfig;
  afterAccountConfigWritten?: (params: {
    previousCfg: OpenClawConfig;
    cfg: OpenClawConfig;
    accountId: string;
    input: Input;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
  validateInput?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: Input;
  }) => string | null;
  singleAccountKeysToMove?: readonly string[];
  namedAccountPromotionKeys?: readonly string[];
  resolveSingleAccountPromotionTarget?: (params: {
    channel: Record<string, unknown>;
  }) => string | undefined;
};
//#endregion
//#region src/channels/plugins/setup-contract.d.ts
type ChannelSetupCliOption = {
  flags: string;
  negatedFlags?: string;
  description: string;
  defaultValue?: boolean | string;
};
type ChannelSetupStringField = {
  kind: "string";
  sensitive?: boolean;
  cli: ChannelSetupCliOption;
};
type ChannelSetupBooleanField = {
  kind: "boolean";
  cli: ChannelSetupCliOption;
  envVars?: readonly string[];
  envVarMode?: "all" | "any";
};
type ChannelSetupIntegerField = {
  kind: "integer";
  cli: ChannelSetupCliOption;
};
type ChannelSetupStringListField = {
  kind: "string-list";
  sensitive?: boolean;
  cli: ChannelSetupCliOption;
};
type ChannelSetupChoiceField<Choices extends readonly string[] = readonly string[]> = {
  kind: "choice";
  choices: Choices;
  cli: ChannelSetupCliOption;
};
type ChannelSetupField = ChannelSetupStringField | ChannelSetupBooleanField | ChannelSetupIntegerField | ChannelSetupStringListField | ChannelSetupChoiceField;
type ChannelSetupFieldMetadataFor<Field extends ChannelSetupField> = Field extends ChannelSetupField ? Field & {
  key: string;
} : never;
type ChannelSetupFieldMetadata = ChannelSetupFieldMetadataFor<ChannelSetupField>;
type ChannelSetupMetadata = {
  fields: readonly ChannelSetupFieldMetadata[];
};
type ChannelSetupParseResult = {
  ok: true;
  value: unknown;
} | {
  ok: false;
  error: string;
};
type ChannelOwnedSetupContract = {
  kind: "channel-owned";
  accountKeyPolicy?: ChannelSetupAdapter["accountKeyPolicy"];
  configPromotion?: ChannelSetupAdapter["configPromotion"];
  metadata: ChannelSetupMetadata;
  parseInput: (input: unknown) => ChannelSetupParseResult;
  resolveAccountId?: (params: {
    cfg: OpenClawConfig;
    accountId?: string;
    input?: unknown;
  }) => string;
  prepareAccountConfigInput?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: unknown;
    runtime: RuntimeEnv;
  }) => Promise<object> | object;
  resolveBindingAccountId?: ChannelSetupAdapter<{
    name?: string;
  }>["resolveBindingAccountId"];
  applyAccountName?: ChannelSetupAdapter<{
    name?: string;
  }>["applyAccountName"];
  applyAccountConfig: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: unknown;
  }) => OpenClawConfig;
  afterAccountConfigWritten?: (params: {
    previousCfg: OpenClawConfig;
    cfg: OpenClawConfig;
    accountId: string;
    input: unknown;
    runtime: RuntimeEnv;
  }) => Promise<void> | void;
  validateInput?: (params: {
    cfg: OpenClawConfig;
    accountId: string;
    input: unknown;
  }) => string | null;
  singleAccountKeysToMove?: readonly string[];
  namedAccountPromotionKeys?: readonly string[];
  resolveSingleAccountPromotionTarget?: ChannelSetupAdapter<{
    name?: string;
  }>["resolveSingleAccountPromotionTarget"];
};
//#endregion
//#region src/compat/legacy-names.d.ts
declare const MANIFEST_KEY: "openclaw";
//#endregion
//#region src/plugins/package-manifest.types.d.ts
/** package.json OpenClaw metadata used for plugin setup and catalog discovery. */
type PluginPackageChannel = {
  id?: string;
  label?: string;
  selectionLabel?: string;
  detailLabel?: string;
  docsPath?: string;
  docsLabel?: string;
  blurb?: string;
  order?: number;
  aliases?: readonly string[];
  preferOver?: readonly string[];
  systemImage?: string;
  selectionDocsPrefix?: string;
  selectionDocsOmitLabel?: boolean;
  selectionExtras?: readonly string[];
  markdownCapable?: boolean;
  /** Closed manifest flags for approval behavior available before the channel runtime loads. */
  approvalFlags?: readonly "native"[];
  exposure?: {
    configured?: boolean;
    setup?: boolean;
    docs?: boolean;
  };
  quickstartAllowFrom?: boolean;
  forceAccountBinding?: boolean;
  preferSessionLookupForAnnounceTarget?: boolean;
  commands?: PluginManifestChannelCommandDefaults;
  configuredState?: {
    specifier?: string;
    exportName?: string;
    env?: {
      allOf?: readonly string[];
      anyOf?: readonly string[];
    };
  };
  persistedAuthState?: {
    specifier?: string;
    exportName?: string;
    backingStore?: "plugin-state";
  };
  doctorCapabilities?: PluginPackageChannelDoctorCapabilities;
  /** Typed, serializable setup fields available before plugin runtime load. */
  setup?: ChannelSetupMetadata;
  /** @deprecated Use setup.fields. */
  cliAddOptions?: readonly PluginPackageChannelCliOption[];
};
type PluginPackageChannelDoctorCapabilities = {
  dmAllowFromMode?: "topOnly" | "topOrNested" | "nestedOnly";
  /** Whether dmPolicy="open" requires an explicit "*" in allowFrom. Defaults to true. */
  openDmRequiresAllowFromWildcard?: boolean;
  groupModel?: "sender" | "route" | "hybrid";
  groupAllowFromFallbackToAllowFrom?: boolean;
  warnOnEmptyGroupSenderAllowlist?: boolean;
};
type PluginPackageChannelCliOption = {
  flags: string;
  negatedFlags?: string;
  description: string;
  defaultValue?: boolean | string;
  valueType?: "int" | "list";
};
type PluginPackageInstall = {
  clawhubSpec?: string;
  npmSpec?: string;
  localPath?: string;
  defaultChoice?: "clawhub" | "npm" | "local";
  minHostVersion?: string;
  expectedIntegrity?: string;
  allowInvalidConfigRecovery?: boolean;
  requiredPlatformPackages?: string[];
};
type OpenClawPackageSetupFeatures = {
  configPromotion?: boolean | "preserve-root";
  /**
   * @deprecated Declare doctorContract.stateMigrations in openclaw.plugin.json instead.
   * Removal plan: remove the setup-entry adapter after the 2027.1 external-plugin migration window.
   */
  legacyStateMigrations?: boolean;
  legacySessionSurfaces?: boolean;
};
type OpenClawPackageCompat = {
  pluginApi?: string;
  minGatewayVersion?: string;
};
type OpenClawPackageBuild = {
  bundledDist?: boolean;
  openclawVersion?: string;
  pluginSdkVersion?: string;
};
type OpenClawPackageManifest = {
  extensions?: string[];
  runtimeExtensions?: string[];
  setupEntry?: string;
  runtimeSetupEntry?: string;
  controlUi?: string;
  setupFeatures?: OpenClawPackageSetupFeatures;
  plugin?: {
    id?: string;
    label?: string;
  };
  channel?: PluginPackageChannel;
  compat?: OpenClawPackageCompat;
  install?: PluginPackageInstall;
  build?: OpenClawPackageBuild;
};
type PackageManifest = {
  name?: string;
  version?: string;
  description?: string;
  dependencies?: Record<string, string>;
  optionalDependencies?: Record<string, string>;
} & Partial<Record<typeof MANIFEST_KEY, OpenClawPackageManifest>>;
//#endregion
//#region src/plugins/plugin-origin.types.d.ts
/** Origin class for plugin discovery and runtime trust decisions. */
type PluginOrigin$1 = "bundled" | "global" | "workspace" | "config";
//#endregion
//#region src/plugins/status-dependencies.types.d.ts
/** Dependency name-to-version map from a plugin package manifest. */
type PluginDependencySpecMap = Record<string, string>;
/** Installation status for one plugin dependency. */
type PluginDependencyEntry = {
  name: string;
  spec: string;
  installed: boolean;
  optional: boolean;
  resolvedPath?: string;
};
/** Aggregate installation status for required and optional plugin dependencies. */
type PluginDependencyStatus = {
  hasDependencies: boolean;
  installed: boolean;
  requiredInstalled: boolean;
  optionalInstalled: boolean;
  missing: string[];
  missingOptional: string[];
  dependencies: PluginDependencyEntry[];
  optionalDependencies: PluginDependencyEntry[];
};
//#endregion
//#region src/plugins/discovery.types.d.ts
/** One potential plugin root discovered before manifest validation and registry normalization. */
type PluginCandidate = {
  idHint: string;
  /** Discovery-owned identity for one entry in a multi-entry package pack. */
  effectivePluginId?: string;
  diagnosticIdHint?: string;
  source: string;
  setupSource?: string;
  rootDir: string;
  origin: PluginOrigin$1;
  /** Retains explicit load-path precedence when physical aliases merge their provenance. */
  configSelected?: true;
  /** An intentional source overlay must not execute its packaged peer. */
  sourcePreferred?: true;
  format?: PluginFormat;
  bundleFormat?: PluginBundleFormat;
  workspaceDir?: string;
  packageName?: string;
  packageVersion?: string;
  packageDescription?: string;
  packageDir?: string;
  packageManifest?: OpenClawPackageManifest;
  packageDependencies?: PluginDependencySpecMap;
  packageOptionalDependencies?: PluginDependencySpecMap;
  bundledManifestId?: string;
  bundledManifest?: PluginManifest;
  bundledManifestPath?: string;
  requiredPluginIds?: string[];
  requiredPluginSource?: string;
  rawPackageManifest?: PackageManifest;
};
/** Discovery candidates plus warnings/errors emitted while scanning roots. */
type PluginDiscoveryResult = {
  candidates: PluginCandidate[];
  diagnostics: PluginDiagnostic[];
};
//#endregion
//#region src/plugins/plugin-trust.d.ts
/** Captured beside the trust decision; consumers never rediscover installation facts. */
type PluginTrust = {
  reason: "bundled" | "trusted-official" | "record-missing" | "owner-ambiguous" | "origin-path" | "install-path-mismatch" | "provenance-missing" | "provenance-invalid";
  registryPath: string | null;
  origin: PluginOrigin$1 | "unknown";
  installSource?: PluginInstallRecord["source"];
  installSpec?: string;
};
//#endregion
//#region src/plugins/manifest-registry.types.d.ts
type PluginManifestRecordStatic = Omit<PluginManifest, "capabilityCatalogEntry" | "channels" | "cliBackends" | "configSchema" | "enabledByDefaultOnPlatforms" | "providerCatalogEntry" | "providers" | "requiresPlugins" | "skills" | "uiHints">;
type PluginThemeArtwork = {
  hats?: Record<string, {
    svg: string;
  }>;
  critters?: Record<string, {
    svg: string;
    title?: string;
    crossMs?: number;
  }>;
};
type PluginManifestRecord = PluginManifestRecordStatic & {
  /** Validated palettes and artwork captured by the immutable metadata generation. */
  themeDefinitions?: Array<{
    id: string;
    definition: ThemeDefinition;
    artwork?: PluginThemeArtwork;
  }>;
  /** Process-local source selection, never persisted in the installed index. */
  sourcePreferred?: true;
  iconPath?: string;
  activityIconPath?: string;
  toolActivityIconPaths?: Record<string, string>;
  packageName?: string;
  packageVersion?: string;
  packageDescription?: string;
  enabledByDefaultOnPlatforms?: string[];
  format?: PluginFormat;
  bundleFormat?: PluginBundleFormat;
  bundleCapabilities?: string[];
  channels: string[];
  providers: string[];
  providerDiscoverySource?: string;
  /** Undefined is undeclared; null retains a rejected declaration without enabling full-entry fallback. */
  capabilityCatalogSource?: string | null;
  cliBackends: string[];
  packageManifest?: OpenClawPackageManifest;
  packageDependencies?: PluginDependencySpecMap;
  packageOptionalDependencies?: PluginDependencySpecMap;
  packageChannel?: PluginPackageChannel;
  packageInstall?: PluginPackageInstall;
  trustedOfficialInstall?: boolean;
  trust?: PluginTrust;
  skills: string[];
  settingsFiles?: string[];
  hooks: string[];
  origin: PluginOrigin$1;
  workspaceDir?: string;
  rootDir: string;
  source: string;
  setupSource?: string;
  manifestPath: string;
  schemaCacheKey?: string;
  configSchema?: Record<string, unknown>;
  configUiHints?: Record<string, PluginConfigUiHint>;
  channelCatalogMeta?: {
    id: string;
    label?: string;
    blurb?: string;
    preferOver?: readonly string[];
    commands?: PluginManifestChannelCommandDefaults;
  };
};
type PluginManifestRegistry = {
  plugins: PluginManifestRecord[];
  diagnostics: PluginDiagnostic[];
};
//#endregion
//#region src/secrets/resolve-types.d.ts
/** Shared per-runtime cache for resolved SecretRefs and file provider payloads. */
type SecretRefResolveCache = {
  /** In-flight or completed resolution promise keyed by `secretRefKey(ref)`. */
  resolvedByRefKey?: Map<string, Promise<unknown>>;
  /** In-flight or completed parsed file-provider payload keyed by provider alias. */
  filePayloadByProvider?: Map<string, Promise<unknown>>;
};
//#endregion
//#region src/secrets/runtime-degraded-state.d.ts
type SecretOwnerKind = "account" | "capability" | "gateway" | "provider" | "route" | "unknown";
type SecretAssignmentDisposition = "fail-closed" | "isolate";
//#endregion
//#region src/secrets/runtime-shared.d.ts
type SecretResolverWarningCode = "SECRETS_REF_OVERRIDES_PLAINTEXT" | "SECRETS_REF_IGNORED_INACTIVE_SURFACE" | "SECRETS_OWNER_UNAVAILABLE" | "WEB_SEARCH_PROVIDER_INVALID_AUTODETECT" | "WEB_SEARCH_AUTODETECT_SELECTED" | "WEB_SEARCH_KEY_UNRESOLVED_FALLBACK_USED" | "WEB_SEARCH_KEY_UNRESOLVED_NO_FALLBACK" | "WEB_FETCH_PROVIDER_INVALID_AUTODETECT" | "WEB_FETCH_AUTODETECT_SELECTED" | "WEB_FETCH_PROVIDER_KEY_UNRESOLVED_FALLBACK_USED" | "WEB_FETCH_PROVIDER_KEY_UNRESOLVED_NO_FALLBACK";
type SecretResolverWarning = {
  code: SecretResolverWarningCode;
  path: string;
  message: string;
};
type SecretAssignment = {
  ref: SecretRef;
  path: string;
  expected: "string" | "string-or-object";
  ownerKind: SecretOwnerKind;
  ownerId: string;
  requiredForGateway: boolean;
  disposition: SecretAssignmentDisposition;
  /** Digest of the complete owner config captured before secret materialization. */
  ownerContractDigest?: string;
  apply: (value: unknown) => void;
  /** Applies the canonical unavailable state when this owner must start cold. */
  applyUnavailable?: () => void;
};
type ResolverContext = {
  sourceConfig: OpenClawConfig;
  env: NodeJS.ProcessEnv;
  cache: SecretRefResolveCache;
  manifestRegistry?: Pick<PluginManifestRegistry, "plugins">;
  warnings: SecretResolverWarning[];
  warningKeys: Set<string>;
  assignments: SecretAssignment[];
};
type SecretDefaults = NonNullable<OpenClawConfig["secrets"]>["defaults"];
//#endregion
//#region src/secrets/target-registry-types.d.ts
/** Config document that owns a registered secret-bearing target. */
type SecretTargetConfigFile = "openclaw.json" | "auth-profile-store";
/** Storage shape used by a target: inline SecretInput or a sibling `*Ref` field. */
type SecretTargetShape = "secret_input" | "sibling_ref";
/** Resolved value shape accepted by runtime and apply validation. */
type SecretTargetExpected = "string" | "string-or-object";
/** Auth profile families that have separate secret target coverage. */
type AuthProfileType = "api_key" | "token";
/**
 * Registry metadata for one configurable secret-bearing value.
 */
type SecretTargetRegistryEntry = {
  /** Stable id used by plans, audits, docs, and targeted discovery filters. */
  id: string;
  /** Plan/configure target family; aliases keep CLI-facing names additive. */
  targetType: string;
  targetTypeAliases?: string[];
  /** Config document where the value is discovered or rewritten. */
  configFile: SecretTargetConfigFile;
  /** Dot-path pattern for the secret-bearing value; `*` captures path segments. */
  pathPattern: string;
  /** Structured pattern segments preserve literal plugin IDs containing dots. */
  pathPatternSegments?: string[];
  /** Optional sibling SecretRef path materialized from the same captures as `pathPattern`. */
  refPathPattern?: string;
  /** Whether the registered value stores a SecretInput directly or via a sibling ref field. */
  secretShape: SecretTargetShape;
  /** Runtime value shape accepted after SecretRef resolution. */
  expectedResolvedValue: SecretTargetExpected;
  /** Enables `openclaw secrets apply` targeting for this entry. */
  includeInPlan: boolean;
  /** Enables interactive/non-interactive configure candidate generation. */
  includeInConfigure: boolean;
  /** Enables plaintext/unresolved-ref audit scanning. */
  includeInAudit: boolean;
  /** Captured path segment that names the owning provider, when applicable. */
  providerIdPathSegmentIndex?: number;
  /** Captured path segment that names the owning account/profile, when applicable. */
  accountIdPathSegmentIndex?: number;
  /** Auth-profile family for auth-profiles.json entries. */
  authProfileType?: AuthProfileType;
  /** Enables provider-shadowing diagnostics for provider-auth surfaces with fallback order. */
  trackProviderShadowing?: boolean;
};
//#endregion
//#region src/security/audit.types.d.ts
/** Severity levels emitted by security audit checks. */
type SecurityAuditSeverity = "info" | "warn" | "critical";
/** One actionable or informational security audit finding. */
type SecurityAuditFinding = {
  checkId: string;
  severity: SecurityAuditSeverity;
  title: string;
  detail: string;
  remediation?: string;
};
//#endregion
//#region src/channels/plugins/channel-runtime-surface.types.d.ts
type ChannelRuntimeContextKey = {
  channelId: string;
  accountId?: string | null;
  capability: string;
};
type ChannelRuntimeContextEvent = {
  type: "registered" | "unregistered";
  key: {
    channelId: string;
    accountId?: string;
    capability: string;
  };
  context?: unknown;
};
type ChannelRuntimeContextRegistry = {
  register: (params: ChannelRuntimeContextKey & {
    context: unknown;
    abortSignal?: AbortSignal;
  }) => {
    dispose: () => void;
  };
  get: <T = unknown>(params: ChannelRuntimeContextKey) => T | undefined;
  watch: (params: {
    channelId?: string;
    accountId?: string | null;
    capability?: string;
    onEvent: (event: ChannelRuntimeContextEvent) => void;
  }) => () => void;
};
/**
 * Minimal channel-runtime surface exported through the public plugin SDK.
 *
 * Gateway startup supplies the full plugin channel runtime, but external callers
 * may still type context-only helpers against this compatibility surface.
 */
type ChannelRuntimeSurface = {
  runtimeContexts: ChannelRuntimeContextRegistry;
  [key: string]: unknown;
};
//#endregion
//#region src/channels/plugins/config-write-policy-shared.d.ts
/**
 * Channel/account scope used to evaluate config write policy.
 */
type ConfigWriteScopeLike<TChannelId extends string = string> = {
  channelId?: TChannelId | null;
  accountId?: string | null;
};
/**
 * Target affected by a config write command.
 */
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>[];
};
//#endregion
//#region src/channels/plugins/config-writes.d.ts
/**
 * Target affected by a channel config write.
 */
type ConfigWriteTarget = ConfigWriteTargetLike;
//#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?: {
    kind: "chat" | "channel" | "room" | "conversation";
    id: string;
  };
  timestamp?: number;
  toJid?: string;
  pollId?: string;
  receipt?: MessageReceipt;
  meta?: Record<string, unknown>;
};
/** 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 = "platform_send" | "queue" | "unknown";
type OutboundPayloadDeliveryKind = "text" | "media" | "other";
/** Per-payload delivery status emitted to callers and channel send summaries. */
type OutboundPayloadDeliveryOutcome = {
  index: number;
  status: "sent";
  results: OutboundDeliveryResult[];
  /** 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[];
    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[];
/**
 * Unified chunking function that dispatches based on mode.
 */
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$1;
  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 = {
  name?: string;
  avatarUrl?: string;
  emoji?: string;
  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;
};
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;
  cfg: OpenClawConfig;
  accountId?: string | null;
};
type ChannelOutboundNormalizePayloadBatchParams = Omit<ChannelOutboundNormalizePayloadParams, "payload"> & {
  payloads: readonly {
    index: number;
    payload: ReplyPayload;
  }[];
};
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;
    cfg?: OpenClawConfig;
    accountId?: string;
  }) => string;
  pollMaxOptions?: number;
  supportsPollDurationSeconds?: boolean;
  supportsAnonymousPolls?: boolean;
  normalizePayload?: (params: ChannelOutboundNormalizePayloadParams) => ReplyPayload | null;
  /** Normalize an ordered batch in place. Return one entry per input; null suppresses that send. */
  normalizePayloadBatch?: (params: ChannelOutboundNormalizePayloadBatchParams) => ReadonlyArray<ReplyPayload | 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;
  }) => boolean;
  resolveEffectiveTextChunkLimit?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    fallbackLimit?: number;
    formatting?: OutboundDeliveryFormattingOptions;
  }) => number | undefined;
  shouldSuppressLocalPayloadPrompt?: (params: ChannelOutboundNormalizePayloadParams & {
    hint?: ChannelOutboundPayloadHint;
  }) => boolean;
  beforeDeliverPayload?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    payload: ReplyPayload;
    hint?: ChannelOutboundPayloadHint;
  }) => Promise<void> | void;
  afterDeliverPayload?: (params: {
    cfg: OpenClawConfig;
    target: ChannelOutboundTargetRef;
    payload: ReplyPayload;
    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;
    presentation: MessagePresentation;
    /** Normalized original for readable fallbacks; native rendering uses presentation. */
    sourcePresentation?: MessagePresentation;
    ctx: ChannelOutboundPayloadContext;
  }) => Promise<ReplyPayload | null> | ReplyPayload | 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, "channelData" | "delivery" | "presentation"> | null | Promise<Pick<ReplyPayload, "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. Retained through the next Plugin SDK major. */
  setIdleTimeoutBySessionKey?: (params: {
    targetSessionKey: string;
    accountId?: string | null;
    idleTimeoutMs: number;
  }) => Array<{
    boundAt: number;
    lastActivityAt: number;
    idleTimeoutMs?: number;
    maxAgeMs?: number;
  }>;
  /** @deprecated Use setMaxAgeBySessionKeyAsync. Retained through the next Plugin SDK major. */
  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 = {
  channel: string;
  to: string;
  accountId?: string | null;
  threadId?: string | number | null;
  source?: "session" | "target";
};
type ChannelCapabilitiesDisplayTone = "default" | "muted" | "success" | "warn" | "error";
type ChannelCapabilitiesDisplayLine = {
  text: string;
  tone?: ChannelCapabilitiesDisplayTone;
};
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;
  resolveAllowFrom?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
  }) => 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 = {
  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;
  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 ChannelLogoutResult = {
  cleared: boolean;
  loggedOut?: boolean;
  [key: string]: unknown;
};
type ChannelLoginWithQrStartResult = {
  qrDataUrl?: string;
  message: string;
  connected?: boolean;
  sessionKey?: string;
};
type ChannelLoginWithQrWaitResult = {
  connected: boolean;
  message: string;
  qrDataUrl?: string;
};
type ChannelLogoutContext<ResolvedAccount = unknown> = {
  cfg: OpenClawConfig;
  accountId: string;
  account: ResolvedAccount;
  runtime: RuntimeEnv;
  log?: ChannelLogSink;
};
type ChannelGatewayAdapter<ResolvedAccount = unknown> = {
  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;
    force?: boolean;
    timeoutMs?: number;
    verbose?: boolean;
  }) => Promise<ChannelLoginWithQrStartResult>;
  loginWithQrWait?: (params: {
    accountId?: string;
    sessionKey?: string;
    timeoutMs?: number;
    currentQrDataUrl?: string;
  }) => Promise<ChannelLoginWithQrWaitResult>;
  logoutAccount?: (ctx: ChannelLogoutContext<ResolvedAccount>) => Promise<ChannelLogoutResult>;
};
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 ChannelDirectorySelfParams = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  runtime: RuntimeEnv;
};
type ChannelDirectoryListParams = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  query?: string | null;
  limit?: number | null;
  runtime: RuntimeEnv;
};
type ChannelDirectoryListGroupMembersParams = {
  cfg: OpenClawConfig;
  accountId?: string | null;
  groupId: string;
  limit?: number | null;
  runtime: RuntimeEnv;
};
type ChannelDirectoryAdapter = {
  self?: (params: ChannelDirectorySelfParams) => 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: ChannelDirectoryListGroupMembersParams) => 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["channelData"] | null;
  buildModelsMenuChannelData?: (params: {
    providers: Array<{
      id: string;
      count: number;
    }>;
  }) => ReplyPayload["channelData"] | null;
  buildModelsProviderChannelData?: NonNullable<ChannelCommandAdapter["buildModelsMenuChannelData"]>;
  buildModelsAddProviderChannelData?: (params: {
    providers: Array<{
      id: string;
    }>;
  }) => ReplyPayload["channelData"] | null;
  buildModelsListChannelData?: (params: {
    provider: string;
    models: readonly string[];
    currentModel?: string;
    currentPage: number;
    totalPages: number;
    pageSize?: number;
    modelNames?: ReadonlyMap<string, string>;
  }) => ReplyPayload["channelData"] | null;
  buildModelBrowseChannelData?: () => ReplyPayload["channelData"] | null;
};
type ChannelDoctorConfigMutation = {
  config: OpenClawConfig;
  changes: string[];
  warnings?: string[];
};
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;
  request: ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
};
type ChannelApprovalDeliveryAdapter = {
  hasConfiguredDmRoute?: (params: {
    cfg: OpenClawConfig;
  }) => 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;
};
type ChannelApproveCommandBehavior = {
  kind: "allow";
} | {
  kind: "ignore";
} | {
  kind: "reply";
  text: string;
};
type ChannelApprovalRenderHandlers<Request, Resolved> = {
  buildPendingPayload?: (params: {
    cfg: OpenClawConfig;
    request: Request;
    target: ChannelApprovalForwardTarget;
    nowMs: number;
  }) => ReplyPayload | null;
  buildResolvedPayload?: (params: {
    cfg: OpenClawConfig;
    resolved: Resolved;
    target: ChannelApprovalForwardTarget;
  }) => ReplyPayload | null;
};
type ChannelApprovalRenderAdapter = {
  exec?: ChannelApprovalRenderHandlers<ExecApprovalRequest, ExecApprovalResolved>;
  plugin?: ChannelApprovalRenderHandlers<PluginApprovalRequest$1, PluginApprovalResolved>;
};
type ChannelApprovalAdapter = {
  delivery?: ChannelApprovalDeliveryAdapter;
  nativeRuntime?: ChannelApprovalNativeRuntimeAdapter;
  render?: ChannelApprovalRenderAdapter;
  native?: ChannelApprovalNativeAdapter;
  describeExecApprovalSetup?: (params: {
    channel: string;
    channelLabel: string;
    accountId?: string;
  }) => string | null | undefined;
  describePluginApprovalSetup?: (params: {
    channel: string;
    channelLabel: string;
    accountId?: string;
  }) => string | null | undefined;
};
type ChannelApprovalCapability = ChannelApprovalAdapter & {
  /** Confirms that this channel enforces configured plugin reviewer lists for routing and decisions. */
  supportsScopedPluginApprovalApprovers?: true;
  authorizeActorAction?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    senderId?: string | null;
    action: "approve";
    approvalKind: ChannelApprovalKind;
    request?: ExecApprovalRequest | PluginApprovalRequest$1 | SystemAgentApprovalRequest;
  }) => {
    authorized: boolean;
    reason?: string;
  };
  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;
  /** Exec-native client availability for the initiating surface; distinct from same-chat auth. */
  getExecInitiatingSurfaceState?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    action: "approve";
  }) => ChannelActionAvailabilityState;
  resolveApproveCommandBehavior?: (params: {
    cfg: OpenClawConfig;
    accountId?: string | null;
    senderId?: string | null;
    approvalKind: ChannelApprovalKind;
  }) => ChannelApproveCommandBehavior | 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> = {
  applyConfigFixes?: (params: {
    cfg: OpenClawConfig;
    env: NodeJS.ProcessEnv;
  }) => ChannelDoctorConfigMutation | Promise<ChannelDoctorConfigMutation>;
  resolveDmPolicy?: (ctx: ChannelSecurityContext<ResolvedAccount>) => 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/gateway/operator-scopes.d.ts
declare const KNOWN_OPERATOR_SCOPE_VALUES: readonly ["operator.admin", "operator.read", "operator.write", "operator.sessions.read", "operator.sessions.write", "operator.approvals", "operator.questions", "operator.pairing", "operator.talk", "operator.talk.secrets"];
/** Operator privileges advertised by gateway auth and checked by method policy. */
type OperatorScope = (typeof KNOWN_OPERATOR_SCOPE_VALUES)[number];
//#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;
};
//#endregion
//#region src/channels/plugins/setup-group-access.d.ts
/**
 * Group access policy selected during channel setup.
 */
type ChannelAccessPolicy = "allowlist" | "open" | "disabled";
//#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;
};
/** Optional explanatory note shown when its owning step is reached. */
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>;
};
/** Declarative secret/input step for a channel account credential. */
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>;
};
/** Declarative text step that can depend on resolved credentials. */
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;
};
/** Channel-specific resolver for user-entered allowlist targets. */
type ChannelSetupWizardAllowFrom = {
  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>;
};
/** Declarative group/DM access policy step used by interactive setup. */
type ChannelSetupWizardGroupAccess = {
  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;
};
type ChannelSetupWizardHookContext = ChannelSetupWizardStepContext & {
  runtime: ChannelSetupConfigureContext["runtime"];
  prompter: WizardPrompter;
  options?: ChannelSetupConfigureContext["options"];
};
type ChannelSetupWizardHookResult = {
  cfg?: OpenClawConfig;
  credentialValues?: ChannelSetupWizardCredentialValues;
} | void;
/** Optional pre-step hook for deriving helper config or credential values. */
type ChannelSetupWizardPrepare = (params: ChannelSetupWizardHookContext) => ChannelSetupWizardHookResult | Promise<ChannelSetupWizardHookResult>;
/** Optional post-step hook for final validation, writes, or post prompts. */
type ChannelSetupWizardFinalize = (params: ChannelSetupWizardHookContext & {
  forceAllowFrom: boolean;
}) => ChannelSetupWizardHookResult | Promise<ChannelSetupWizardHookResult>;
/** Full declarative setup wizard consumed by the generic setup adapter. */
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;
  prepare?: ChannelSetupWizardPrepare;
  stepOrder?: "credentials-first" | "text-first";
  credentials: ChannelSetupWizardCredential[];
  textInputs?: ChannelSetupWizardTextInput[];
  finalize?: ChannelSetupWizardFinalize;
  completionNote?: ChannelSetupWizardNote;
  dmPolicy?: ChannelSetupDmPolicy;
  allowFrom?: ChannelSetupWizardAllowFrom;
  groupAccess?: ChannelSetupWizardGroupAccess;
  disable?: (cfg: OpenClawConfig) => OpenClawConfig;
  onAccountRecorded?: ChannelSetupWizardAdapter["onAccountRecorded"];
};
/** Runtime options for selecting and configuring one or more channels. */
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 ChannelSetupStatus = {
  channel: ChannelId$1;
  configured: boolean;
  statusLines: string[];
  selectionHint?: string;
  quickstartScore?: number;
};
/** Shared context for status checks before channel selection. */
type ChannelSetupStatusContext = {
  cfg: OpenClawConfig;
  options?: SetupChannelsOptions;
  accountOverrides: Partial<Record<ChannelId$1, string>>;
};
/** Shared context for applying setup changes for a selected channel. */
type ChannelSetupConfigureContext = ChannelSetupStatusContext & {
  runtime: RuntimeEnv;
  prompter: WizardPrompter;
  shouldPromptAccountIds: boolean;
  forceAllowFrom: boolean;
};
/** Context passed after setup has written config to disk. */
type ChannelOnboardingPostWriteContext = ChannelSetupWizardAccountContext & {
  previousCfg: OpenClawConfig;
  runtime: RuntimeEnv;
};
/** 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 ChannelSetupInteractiveContext = ChannelSetupConfigureContext & {
  configured: boolean;
  label: string;
};
/** Optional direct-message policy contract exposed by setup adapters. */
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>;
};
/** Imperative adapter consumed by onboarding and setup flows. */
type ChannelSetupWizardAdapter = {
  channel: ChannelId$1;
  getStatus: (ctx: ChannelSetupStatusContext) => Promise<ChannelSetupStatus>;
  configure: (ctx: ChannelSetupConfigureContext) => Promise<ChannelSetupResult>;
  configureInteractive?: (ctx: ChannelSetupInteractiveContext) => Promise<ChannelSetupConfiguredResult>;
  configureWhenConfigured?: NonNullable<ChannelSetupWizardAdapter["configureInteractive"]>;
  afterConfigWritten?: (ctx: ChannelOnboardingPostWriteContext) => 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$1<ResolvedAccount = any, Probe = unknown, Audit = unknown> = 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?: 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[];
};
//#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/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;
  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/worker-environments/placement-state.d.ts
declare const WORKER_SESSION_PLACEMENT_STATES: readonly ["local", "requested", "provisioning", "syncing", "starting", "active", "draining", "reconciling", "reclaimed", "failed"];
type WorkerSessionPlacementState = (typeof WORKER_SESSION_PLACEMENT_STATES)[number];
//#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: WorkerSessionPlacementState;
  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 = {
  owner: "local";
  claimId: string;
  runId: string;
  generation: number;
  ownerEpoch: null;
} | {
  owner: "worker";
  claimId: string;
  runId: string;
  generation: number;
  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 = {
  environmentId: null;
  activeOwnerEpoch: null;
  workspaceBaseManifestRef: null;
  remoteWorkspaceDir: null;
  workerBundleHash: null;
  lastTranscriptAckCursor: null;
  lastLiveEventAckCursor: null;
  recoveryError: null;
  terminalReason: null;
  terminalAtMs: 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 WorkerSessionPlacementState]: PlacementRecordsByState[State] & {
  state: State;
}; }[WorkerSessionPlacementState];
type WorkerSessionPlacementTransitionPatch = {
  environmentId?: string | null;
  activeOwnerEpoch?: number | null;
  workspaceBaseManifestRef?: string | null;
  remoteWorkspaceDir?: string | null;
  workerBundleHash?: string | null;
  lastTranscriptAckCursor?: number | null;
  lastLiveEventAckCursor?: number | null;
  recoveryError?: string | null;
  terminalReason?: string | null;
};
//#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/agents/tools/computer-tool-gateway.d.ts
type GatewayComputerStatus$1 = {
  configured: false;
  available: false;
} | {
  configured: true;
  available: false;
  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/shared/node-host-stats.d.ts
type NodeHostStats = NodeHostStatsPayload & {
  updatedAtMs: number;
};
//#endregion
//#region src/shared/node-list-types.d.ts
type NodeWorkerBundleStatus = {
  status: "installed";
  version: string;
} | {
  status: "missing";
};
//#endregion
//#region src/agents/computer-use-node-capabilities.d.ts
type PreparedPairedComputerUse = {
  actions: readonly ComputerUseV2ActionName[];
  guidanceCapabilities?: ComputerUseCapabilityDescriptor;
  gateway?: GatewayComputerStatus$1;
};
//#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/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/infra/outbound/session-binding.types.d.ts
/**
 * Runtime destination a conversation binding points at.
 */
type BindingTargetKind = "subagent" | "session";
/**
 * Lifecycle state for a registered session binding.
 */
type BindingStatus = "active" | "ending" | "ended";
/**
 * Channel/account/conversation tuple used to resolve a bound delivery route.
 */
type ConversationRef = {
  channel: string;
  accountId: string;
  conversationId: string;
  parentConversationId?: string;
};
/**
 * Persistable record that connects one conversation to one target session.
 */
type SessionBindingRecord = {
  bindingId: string;
  targetSessionKey: string;
  targetKind: BindingTargetKind;
  conversation: ConversationRef;
  status: BindingStatus;
  boundAt: number;
  expiresAt?: number;
  metadata?: Record<string, unknown>;
};
//#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 packages/media-generation-core/src/normalization.d.ts
/** Primitive value types reported in media generation normalization metadata. */
type MediaNormalizationValue = string | number | boolean;
/** Requested/applied value pair plus provenance for a normalized media option. */
type MediaNormalizationEntry<TValue extends MediaNormalizationValue> = {
  requested?: TValue;
  applied?: TValue;
  derivedFrom?: string;
  supportedValues?: readonly TValue[];
};
//#endregion
//#region src/infra/net/ssrf.d.ts
type LookupFn = (hostname: string, options: {
  all: true;
}) => Promise<LookupAddress[]>;
type SsrFPolicy = {
  allowPrivateNetwork?: boolean;
  dangerouslyAllowPrivateNetwork?: boolean;
  allowRfc2544BenchmarkRange?: boolean;
  /**
   * Exempt addresses in `fc00::/7` (IPv6 Unique Local Address block, RFC 4193)
   * from the SSRF private-IP block. Companion to
   * `allowRfc2544BenchmarkRange` for fake-ip proxy stacks (sing-box, Clash,
   * Surge) that resolve foreign domains to ULA addresses alongside the IPv4
   * 198.18.0.0/15 range. See #74351.
   */
  allowIpv6UniqueLocalRange?: boolean;
  allowedHostnames?: string[];
  /**
   * Exact HTTP origins that may promote only the current request hostname into
   * `allowedHostnames`. Evaluated per URL inside the redirect loop.
   */
  allowedOrigins?: string[];
  hostnameAllowlist?: string[];
  /** Deny exact hosts or wildcard subdomains; "*.example.com" excludes the apex. */
  blockedHostnames?: string[];
};
type PinnedHostnameOverride = {
  hostname: string;
  addresses: string[];
};
type PinnedDispatcherPolicy = {
  mode: "direct";
  connect?: Record<string, unknown>;
  pinnedHostname?: PinnedHostnameOverride;
} | {
  mode: "env-proxy";
  connect?: Record<string, unknown>;
  proxyTls?: Record<string, unknown>;
  pinnedHostname?: PinnedHostnameOverride;
} | {
  mode: "explicit-proxy";
  proxyUrl: string;
  allowPrivateProxy?: boolean;
  proxyTls?: Record<string, unknown>;
  pinnedHostname?: PinnedHostnameOverride;
};
//#endregion
//#region src/image-generation/types.d.ts
/** Non-empty binary image asset returned by an image-generation provider. */
type GeneratedImageAsset = {
  buffer: Buffer;
  mimeType: string;
  fileName?: string;
  revisedPrompt?: string;
  metadata?: Record<string, unknown>;
};
type ImageGenerationResolution = "1K" | "2K" | "4K";
type ImageGenerationQuality = "low" | "medium" | "high" | "xhigh" | "max" | "auto";
type ImageGenerationOutputFormat = "png" | "jpeg" | "webp";
type ImageGenerationBackground = "transparent" | "opaque" | "auto";
type ImageGenerationOpenAIBackground = ImageGenerationBackground;
type ImageGenerationOpenAIModeration = "low" | "auto";
type ImageGenerationOpenAIOptions = {
  background?: ImageGenerationOpenAIBackground;
  moderation?: ImageGenerationOpenAIModeration;
  outputCompression?: number;
  user?: string;
};
type ImageGenerationProviderOptions = Record<string, unknown> & {
  openai?: ImageGenerationOpenAIOptions;
};
type ImageGenerationIgnoredOverrideKey = "size" | "aspectRatio" | "resolution" | "quality" | "outputFormat" | "background";
type ImageGenerationIgnoredOverride = {
  key: ImageGenerationIgnoredOverrideKey;
  value: string;
};
type ImageGenerationSourceImage = {
  buffer: Buffer;
  mimeType: string;
  fileName?: string;
  metadata?: Record<string, unknown>;
};
type ImageGenerationProviderConfiguredContext = {
  cfg?: OpenClawConfig;
  agentDir?: string;
};
/** Runtime request passed to an image-generation provider implementation. */
type ImageGenerationRequest = {
  provider: string;
  model: string;
  prompt: string;
  cfg: OpenClawConfig;
  agentDir?: string;
  authStore?: AuthProfileStore;
  timeoutMs?: number;
  count?: number;
  size?: string;
  aspectRatio?: string;
  resolution?: ImageGenerationResolution;
  quality?: ImageGenerationQuality;
  outputFormat?: ImageGenerationOutputFormat;
  background?: ImageGenerationBackground;
  inputImages?: ImageGenerationSourceImage[];
  providerOptions?: ImageGenerationProviderOptions;
  ssrfPolicy?: SsrFPolicy;
};
type ImageGenerationResult = {
  images: GeneratedImageAsset[];
  model?: string;
  metadata?: Record<string, unknown>;
};
type ImageGenerationModeCapabilities = {
  maxCount?: number;
  supportsSize?: boolean;
  supportsAspectRatio?: boolean;
  supportsResolution?: boolean;
};
type ImageGenerationEditCapabilities = ImageGenerationModeCapabilities & {
  enabled: boolean;
  maxInputImages?: number;
  maxInputImagesByModel?: Readonly<Record<string, number>>;
  maxInputImagesByModelPrefix?: Readonly<Record<string, number>>;
};
type ImageGenerationGeometryCapabilities = {
  sizes?: string[];
  sizesByModel?: Record<string, string[]>;
  aspectRatios?: string[];
  aspectRatiosByModel?: Record<string, string[]>;
  resolutions?: ImageGenerationResolution[];
  resolutionsByModel?: Record<string, ImageGenerationResolution[]>;
};
type ImageGenerationOutputCapabilities = {
  qualities?: ImageGenerationQuality[];
  qualitiesByModel?: Record<string, ImageGenerationQuality[]>;
  formats?: ImageGenerationOutputFormat[];
  formatsByModel?: Record<string, ImageGenerationOutputFormat[]>;
  backgrounds?: ImageGenerationBackground[];
  backgroundsByModel?: Record<string, ImageGenerationBackground[]>;
};
type ImageGenerationNormalization = {
  size?: MediaNormalizationEntry<string>;
  aspectRatio?: MediaNormalizationEntry<string>;
  resolution?: MediaNormalizationEntry<ImageGenerationResolution>;
};
type ImageGenerationProviderCapabilities = {
  generate: ImageGenerationModeCapabilities;
  edit: ImageGenerationEditCapabilities;
  geometry?: ImageGenerationGeometryCapabilities;
  output?: ImageGenerationOutputCapabilities;
};
type ImageGenerationProvider = {
  id: string;
  aliases?: string[];
  label?: string;
  defaultModel?: string;
  /** Default provider operation timeout in milliseconds when caller/config omit timeoutMs. */
  defaultTimeoutMs?: number;
  models?: string[];
  capabilities: ImageGenerationProviderCapabilities;
  isConfigured?: (ctx: ImageGenerationProviderConfiguredContext) => boolean;
  generateImage: (req: ImageGenerationRequest) => Promise<ImageGenerationResult>;
};
//#endregion
//#region src/music-generation/types.d.ts
/**
 * Public music generation provider contracts.
 *
 * Providers implement these request/result/capability shapes so the core
 * runtime can normalize prompts, options, assets, and fallback diagnostics.
 */
/** Audio output formats currently understood by music generation providers. */
type MusicGenerationOutputFormat = "mp3" | "wav";
/** Non-empty in-memory audio asset returned from a music generation provider. */
type GeneratedMusicAsset = {
  buffer: Buffer;
  mimeType: string;
  fileName?: string;
  metadata?: Record<string, unknown>;
};
/** Optional source image passed to image-conditioned music edit models. */
type MusicGenerationSourceImage = {
  url?: string;
  buffer?: Buffer;
  mimeType?: string;
  fileName?: string;
  metadata?: Record<string, unknown>;
};
type MusicGenerationProviderConfiguredContext = {
  cfg?: OpenClawConfig;
  agentDir?: string;
};
/** Provider request after runtime fallback and override normalization. */
type MusicGenerationRequest = {
  provider: string;
  model: string;
  prompt: string;
  cfg: OpenClawConfig;
  agentDir?: string;
  authStore?: AuthProfileStore;
  timeoutMs?: number;
  lyrics?: string;
  instrumental?: boolean;
  durationSeconds?: number;
  format?: MusicGenerationOutputFormat;
  inputImages?: MusicGenerationSourceImage[];
};
/** Provider result before runtime fallback metadata is attached. */
type MusicGenerationResult = {
  tracks: GeneratedMusicAsset[];
  model?: string;
  lyrics?: string[];
  metadata?: Record<string, unknown>;
};
/** Caller override dropped because the selected provider/model does not support it. */
type MusicGenerationIgnoredOverride = {
  key: "lyrics" | "instrumental" | "durationSeconds" | "format";
  value: string | boolean | number;
};
/** Capability block for prompt-only music generation. */
type MusicGenerationModeCapabilities = {
  maxTracks?: number;
  maxDurationSeconds?: number;
  supportsLyrics?: boolean;
  supportsLyricsByModel?: Readonly<Record<string, boolean>>;
  supportsInstrumental?: boolean;
  supportsInstrumentalByModel?: Readonly<Record<string, boolean>>;
  supportsDuration?: boolean;
  supportsFormat?: boolean;
  supportedFormats?: readonly MusicGenerationOutputFormat[];
  supportedFormatsByModel?: Readonly<Record<string, readonly MusicGenerationOutputFormat[]>>;
};
/** Capability block for image-conditioned music generation. */
type MusicGenerationEditCapabilities = MusicGenerationModeCapabilities & {
  enabled: boolean;
  maxInputImages?: number;
};
/** Provider capability declaration, including optional mode-specific overrides. */
type MusicGenerationProviderCapabilities = MusicGenerationModeCapabilities & {
  maxInputImages?: number;
  generate?: MusicGenerationModeCapabilities;
  edit?: MusicGenerationEditCapabilities;
};
/** Normalization metadata attached to runtime results. */
type MusicGenerationNormalization = {
  durationSeconds?: MediaNormalizationEntry<number>;
};
/** Provider implementation contract consumed by the music generation runtime. */
type MusicGenerationProvider = {
  id: string;
  aliases?: string[];
  label?: string;
  defaultModel?: string;
  models?: string[];
  capabilities: MusicGenerationProviderCapabilities;
  isConfigured?: (ctx: MusicGenerationProviderConfiguredContext) => boolean;
  generateMusic: (req: MusicGenerationRequest) => Promise<MusicGenerationResult>;
};
//#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;
};
/** 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/talk-events.d.ts
/**
 * Canonical event names emitted by Talk sessions across realtime and STT/TTS flows.
 */
declare const TALK_EVENT_TYPES: readonly ["session.started", "session.ready", "session.closed", "session.error", "session.replaced", "turn.started", "turn.ended", "turn.cancelled", "capture.started", "capture.stopped", "capture.cancelled", "capture.once", "input.audio.delta", "input.audio.committed", "transcript.delta", "transcript.done", "output.text.delta", "output.text.done", "output.audio.started", "output.audio.delta", "output.audio.done", "tool.call", "tool.progress", "tool.result", "tool.error", "usage.metrics", "latency.metrics", "health.changed"];
type TalkEventType = (typeof TALK_EVENT_TYPES)[number];
type TalkMode = "realtime" | "stt-tts" | "transcription";
type TalkTransport = "webrtc" | "provider-websocket" | "gateway-relay" | "managed-room";
type TalkBrain = "agent-consult" | "direct-tools" | "none";
//#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;
};
type RealtimeVoiceBrowserAudioContract = {
  inputEncoding: "pcm16" | "g711_ulaw";
  inputSampleRateHz: number;
  outputEncoding: "pcm16" | "g711_ulaw";
  outputSampleRateHz: number;
};
type RealtimeVoiceBrowserSessionBase = {
  provider: RealtimeVoiceProviderId;
  model?: string;
  voice?: string;
  expiresAt?: number;
};
type RealtimeVoiceBrowserWebRtcSdpSession = RealtimeVoiceBrowserSessionBase & {
  transport: "webrtc";
  clientSecret: string;
  offerUrl?: string;
  offerHeaders?: Record<string, string>;
  offerResponseMaxBytes?: number;
};
type RealtimeVoiceBrowserJsonPcmWebSocketSession = RealtimeVoiceBrowserSessionBase & {
  transport: "provider-websocket";
  protocol: string;
  clientSecret: string;
  websocketUrl: string;
  audio: RealtimeVoiceBrowserAudioContract;
  initialMessage?: unknown;
};
type RealtimeVoiceBrowserGatewayRelaySession = RealtimeVoiceBrowserSessionBase & {
  transport: "gateway-relay";
  relaySessionId: string;
  audio: RealtimeVoiceBrowserAudioContract;
};
type RealtimeVoiceBrowserManagedRoomSession = RealtimeVoiceBrowserSessionBase & {
  transport: "managed-room";
  roomUrl: string;
  token?: string;
};
type RealtimeVoiceBrowserSession = RealtimeVoiceBrowserWebRtcSdpSession | RealtimeVoiceBrowserJsonPcmWebSocketSession | RealtimeVoiceBrowserGatewayRelaySession | RealtimeVoiceBrowserManagedRoomSession;
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
/**
 * Public contracts for transcript source providers.
 *
 * Providers can stream live utterances, import post-hoc transcript text, expose
 * status, and stop active sessions using shared session/source descriptors.
 */
/** Supported source families for transcript providers. */
type TranscriptSourceKind = "live-audio" | "live-caption" | "posthoc-transcript" | "recording-stt";
/** Provider-specific locator for a live, recorded, or imported transcript source. */
type TranscriptSourceLocator = {
  providerId: string;
  kind?: TranscriptSourceKind;
  accountId?: string;
  guildId?: string;
  channelId?: string;
  meetingUrl?: string;
  threadTs?: string;
  fileId?: string;
  [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 = {
  id?: string;
  sessionId?: string;
  startedAt?: string;
  endedAt?: string;
  speaker?: TranscriptParticipant;
  text: string;
  final?: boolean;
  metadata?: Record<string, unknown>;
};
/** Durable transcript session metadata. */
type TranscriptSessionDescriptor = {
  sessionId: string;
  title?: string;
  source: TranscriptSourceLocator;
  startedAt: string;
  stoppedAt?: string;
  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$2 = {
  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 = {
  enabled: boolean;
  allowText: boolean;
  allowProvider: boolean;
  allowVoice: boolean;
  allowModelId: boolean;
  allowVoiceSettings: boolean;
  allowNormalization: boolean;
  allowSeed: boolean;
};
/** Parsed directive overrides grouped by provider. */
type TtsDirectiveOverrides = {
  ttsText?: string;
  provider?: SpeechProviderId;
  providerOverrides?: Record<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 = {
  audioStream: ReadableStream<Uint8Array>;
  outputFormat: string;
  fileExtension: string;
  voiceCompatible: boolean;
  release?: () => Promise<void>;
};
/** Telephony synthesis request for provider output that needs a fixed sample rate. */
type SpeechTelephonySynthesisRequest = {
  text: string;
  cfg: OpenClawConfig;
  providerConfig: SpeechProviderConfig;
  providerOverrides?: SpeechProviderOverrides;
  timeoutMs: number;
};
/** Telephony synthesis result with sample-rate metadata for call transports. */
type SpeechTelephonySynthesisResult = {
  audioBuffer: Buffer;
  outputFormat: string;
  sampleRate: number;
};
/** Provider hook input for applying persona/config before synthesis. */
type SpeechProviderPrepareSynthesisContext = {
  text: string;
  cfg: OpenClawConfig;
  providerConfig: SpeechProviderConfig;
  providerOverrides?: SpeechProviderOverrides;
  persona?: ResolvedTtsPersona;
  personaProviderConfig?: SpeechProviderConfig;
  target: SpeechSynthesisTarget;
  timeoutMs: number;
};
/** Optional provider-prepared synthesis overrides. */
type SpeechProviderPreparedSynthesis = {
  text?: string;
  providerConfig?: SpeechProviderConfig;
  providerOverrides?: SpeechProviderOverrides;
};
/** Voice metadata returned by provider list-voices hooks. */
type SpeechVoiceOption = {
  id: string;
  name?: string;
  category?: string;
  description?: string;
  locale?: string;
  gender?: string;
  personalities?: string[];
};
/** Provider voice-listing request with optional direct auth/URL overrides. */
type SpeechListVoicesRequest = {
  cfg?: OpenClawConfig;
  providerConfig?: SpeechProviderConfig;
  apiKey?: string;
  baseUrl?: string;
  /** 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/video-generation/types.d.ts
/** Video asset returned by a provider after generation or transformation. */
type GeneratedVideoAsset = {
  /** Non-empty raw video bytes; may accompany url as a delivery fallback. */
  buffer?: Buffer;
  /** Provider-hosted URL returned instead of bytes or alongside them as a delivery fallback.
   * When buffer is absent, callers can forward or download without materializing the video. */
  url?: string;
  mimeType: string;
  fileName?: string;
  metadata?: Record<string, unknown>;
};
/** Resolution label accepted by video generation providers. */
type VideoGenerationResolution = "360P" | "480P" | "540P" | "720P" | "768P" | "1080P" | (string & {});
/**
 * Canonical semantic role hints for reference assets (first/last frame,
 * reference image/video/audio). Providers may accept additional role strings;
 * the asset.role type accepts both canonical values and arbitrary strings.
 */
type VideoGenerationAssetRole = "first_frame" | "last_frame" | "reference_image" | "reference_video" | "reference_audio";
/** Source media asset supplied to image/video/audio-to-video providers. */
type VideoGenerationSourceAsset = {
  url?: string;
  buffer?: Buffer;
  mimeType?: string;
  fileName?: string;
  /**
   * Optional semantic role hint forwarded to the provider. Canonical values
   * come from `VideoGenerationAssetRole`; plain strings are accepted for
   * provider-specific extensions.
   */
  role?: VideoGenerationAssetRole | (string & {});
  metadata?: Record<string, unknown>;
};
/** Context passed when checking whether a video provider is configured. */
type VideoGenerationProviderConfiguredContext = {
  cfg?: OpenClawConfig;
  agentDir?: string;
};
/** Context passed when resolving model-specific video generation capabilities. */
type VideoGenerationModelCapabilitiesContext = {
  provider: string;
  model: string;
  cfg: OpenClawConfig;
  agentDir?: string;
  authStore?: AuthProfileStore;
  timeoutMs?: number;
};
/** Normalized request object passed to a selected video generation provider. */
type VideoGenerationRequest = {
  provider: string;
  model: string;
  prompt: string;
  cfg: OpenClawConfig;
  agentDir?: string;
  authStore?: AuthProfileStore;
  timeoutMs?: number;
  size?: string;
  aspectRatio?: string;
  resolution?: VideoGenerationResolution;
  durationSeconds?: number;
  audio?: boolean;
  watermark?: boolean;
  inputImages?: VideoGenerationSourceAsset[];
  inputVideos?: VideoGenerationSourceAsset[];
  /** Reference audio assets (e.g. background music) forwarded to the provider. */
  inputAudios?: VideoGenerationSourceAsset[];
  /** Arbitrary provider-specific parameters forwarded as-is (e.g. seed, draft, camerafixed). */
  providerOptions?: Record<string, unknown>;
};
/** Provider video generation response returned to the runtime. */
type VideoGenerationResult = {
  videos: GeneratedVideoAsset[];
  model?: string;
  metadata?: Record<string, unknown>;
};
/** Supported high-level video generation operation modes. */
type VideoGenerationMode = "generate" | "imageToVideo" | "videoToVideo";
/**
 * Primitive type tag for a declared `providerOptions` key. Keep narrow —
 * plugins that need richer shapes should leave them out of the typed contract
 * and interpret the forwarded opaque value inside their own provider code.
 */
type VideoGenerationProviderOptionType = "number" | "boolean" | "string";
/** Capability limits and supported options for one video generation mode. */
type VideoGenerationModeCapabilities = {
  maxVideos?: number;
  maxInputImages?: number;
  maxInputImagesByModel?: Readonly<Record<string, number>>;
  maxInputVideos?: number;
  maxInputVideosByModel?: Readonly<Record<string, number>>;
  /** Max number of reference audio assets the provider accepts (e.g. background music, voice reference). */
  maxInputAudios?: number;
  maxInputAudiosByModel?: Readonly<Record<string, number>>;
  maxDurationSeconds?: number;
  supportedDurationSeconds?: readonly number[];
  supportedDurationSecondsByModel?: Readonly<Record<string, readonly number[]>>;
  sizes?: readonly string[];
  aspectRatios?: readonly string[];
  resolutions?: readonly VideoGenerationResolution[];
  supportsSize?: boolean;
  supportsAspectRatio?: boolean;
  supportsResolution?: boolean;
  supportsAudio?: boolean;
  supportsWatermark?: boolean;
  /**
   * Declared typed schema for `VideoGenerationRequest.providerOptions`. Keys
   * listed here are accepted and validated against the declared primitive
   * type before forwarding; unknown keys or type mismatches skip the
   * candidate provider at runtime so mis-typed or provider-specific options
   * never silently reach the wrong provider.
   */
  providerOptions?: Readonly<Record<string, VideoGenerationProviderOptionType>>;
};
/** Capability block for transform modes that may be independently enabled. */
type VideoGenerationTransformCapabilities = VideoGenerationModeCapabilities & {
  enabled: boolean;
};
/** Full provider capability map including base and transform mode overrides. */
type VideoGenerationProviderCapabilities = VideoGenerationModeCapabilities & {
  generate?: VideoGenerationModeCapabilities;
  imageToVideo?: VideoGenerationTransformCapabilities;
  videoToVideo?: VideoGenerationTransformCapabilities;
};
/** Static catalog metadata that overrides provider defaults for one video model. */
type VideoGenerationCatalogModelEntry = {
  capabilities?: VideoGenerationProviderCapabilities;
  modes?: readonly VideoGenerationMode[];
};
/** Video generation provider contract implemented by provider plugins. */
type VideoGenerationProvider = {
  id: string;
  aliases?: string[];
  label?: string;
  defaultModel?: string;
  /** Default provider operation timeout in milliseconds when caller/config omit timeoutMs. */
  defaultTimeoutMs?: number;
  models?: string[];
  capabilities: VideoGenerationProviderCapabilities;
  catalogByModel?: Readonly<Record<string, VideoGenerationCatalogModelEntry>>;
  isConfigured?: (ctx: VideoGenerationProviderConfiguredContext) => boolean;
  resolveModelCapabilities?: (ctx: VideoGenerationModelCapabilitiesContext) => VideoGenerationProviderCapabilities | undefined | Promise<VideoGenerationProviderCapabilities | undefined>;
  generateVideo: (req: VideoGenerationRequest) => Promise<VideoGenerationResult>;
};
type VideoGenerationIgnoredOverride = {
  key: "size" | "aspectRatio" | "resolution" | "audio" | "watermark";
  value: string | boolean;
};
type VideoGenerationNormalization = {
  size?: MediaNormalizationEntry<string>;
  aspectRatio?: MediaNormalizationEntry<string>;
  resolution?: MediaNormalizationEntry<VideoGenerationResolution>;
  durationSeconds?: MediaNormalizationEntry<number>;
};
//#endregion
//#region src/plugins/host-hook-json.d.ts
/** Bounded JSON value shape accepted from plugin hooks. */
type PluginJsonValue = string | number | boolean | null | PluginJsonValue[] | {
  [key: string]: PluginJsonValue;
};
//#endregion
//#region src/plugins/capability-provider.types.d.ts
/** JSON-compatible provider settings for one configured worker profile. */
type WorkerProfile = Readonly<Record<string, PluginJsonValue>>;
/** Provider-authored picker metadata for one machine class or exact machine type. */
type WorkerMachineOption = Readonly<{
  id: string;
  label: string;
  os?: string;
  cpu?: number;
  memoryGb?: number;
  default?: boolean;
}>;
/** Provider-owned operating system choices for one configured worker profile. */
type WorkerOperatingSystem = Readonly<{
  id: string;
  label: string;
  default?: boolean;
  /** Why this advertised target cannot currently be selected, including a repair hint. */
  disabledReason?: string;
}>;
/** 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[];
};
/** Placement execution modes a worker provider can carry. */
type WorkerExecutionMode = "worker-turn" | "remote-exec";
/** 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;
  };
  /** Runtime/enrollment closure, including shutdown; provision's separate signal identifies explicit Stop. */
  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";
};
/** Cloud-worker lifecycle capability shared by plugin and internal providers. */
type WorkerProvider$1 = {
  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;
  } | 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;
    /** Cancel this attempt; settle its active commands before rejecting. Cleanup proves release 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;
      };
      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) => string, signal: AbortSignal) => Promise<string>;
        upload: (localPath: string, remotePath: string, signal: AbortSignal) => Promise<void>;
      }) => Promise<{
        seedKey: string;
        cacheHit: boolean;
        /** New completed setup must enter the reusable image before enrollment. */
        captureRequired?: true;
        preparedWorkspace?: {
          preparationKey: string;
          cacheKey: string;
          workspaceDir: string;
          homeDir: string;
          sourceManifestRef: string;
          preparedManifestRef: string;
        };
      }>;
    };
  }) => Promise<WorkerLease>;
  /**
   * 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$1["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;
  }) => 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>;
  /** Idempotent; resolves only after the provider can prove teardown. */
  destroy: (lease: {
    leaseId: string;
    profile: WorkerProfile;
  }) => Promise<void>;
  /** Maximum core wait for teardown, including provider-owned checkpointing and cleanup. */
  resolveDestroyTimeoutMs?: (profile: WorkerProfile) => number;
};
/** Speech capability registered by a plugin. */
type SpeechProviderPlugin$1 = {
  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>;
  isConfigured: (ctx: SpeechProviderConfiguredContext) => boolean;
  synthesize: (req: SpeechSynthesisRequest) => Promise<SpeechSynthesisResult>;
  streamSynthesize?: (req: SpeechSynthesisStreamRequest) => Promise<SpeechSynthesisStreamResult>;
  synthesizeTelephony?: (req: SpeechTelephonySynthesisRequest) => Promise<SpeechTelephonySynthesisResult>;
  listVoices?: (req: SpeechListVoicesRequest) => Promise<SpeechVoiceOption[]>;
};
/** Realtime transcription capability registered by a plugin. */
type RealtimeTranscriptionProviderPlugin$1 = {
  id: RealtimeTranscriptionProviderId;
  label: string;
  aliases?: string[];
  defaultModel?: string;
  models?: readonly string[];
  autoSelectOrder?: number;
  resolveConfig?: (ctx: RealtimeTranscriptionProviderResolveConfigContext) => RealtimeTranscriptionProviderConfig;
  isConfigured: (ctx: RealtimeTranscriptionProviderConfiguredContext) => boolean;
  createSession: (req: RealtimeTranscriptionSessionCreateRequest) => RealtimeTranscriptionSession;
};
/** Transcript source capability registered by a channel or meeting plugin. */
type TranscriptSourceProvider$1 = TranscriptSourceProvider$2;
/** Realtime voice capability registered by a plugin. */
type RealtimeVoiceProviderPlugin$1 = {
  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;
  resolveConfig?: (ctx: RealtimeVoiceProviderResolveConfigContext) => RealtimeVoiceProviderConfig;
  isConfigured: (ctx: RealtimeVoiceProviderConfiguredContext) => boolean;
  createBridge: (req: RealtimeVoiceBridgeCreateRequest) => RealtimeVoiceBridge;
  createBrowserSession?: (req: RealtimeVoiceBrowserSessionCreateRequest) => Promise<RealtimeVoiceBrowserSession>;
};
type MediaUnderstandingProviderPlugin$1 = MediaUnderstandingProvider;
type ImageGenerationProviderPlugin$1 = ImageGenerationProvider;
type VideoGenerationProviderPlugin$1 = VideoGenerationProvider;
type MusicGenerationProviderPlugin$1 = MusicGenerationProvider;
//#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: () => void;
};
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.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">;
type WorkerSessionPlacementProjection = {
  placements: ReadonlyMap<string, WorkerSessionPlacementRecord>;
  moves: ReadonlyMap<string, WorkerPlacementMoveIntent>;
  pendingResults: ReadonlyMap<string, WorkerWorkspacePendingResult>;
  workspaceJournalOwnerSessionIds: ReadonlySet<string>;
  workspaceResultReconcilingSessionIds: ReadonlySet<string>;
  workspaceRecoveryPendingSessionIds: ReadonlySet<string>;
  environments: ReadonlyMap<string, WorkerEnvironmentPlacementFacts>;
};
type WorkerPlacementRecoveryCandidate = {
  sessionId: string;
  environmentId: string | null;
  state?: WorkerSessionPlacementState;
  moveSourceEnvironmentId?: string;
};
//#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[];
};
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(): WorkerWorkspaceReconciliationJournal | undefined;
  begin(journal: WorkerWorkspaceReconciliationJournal): void;
  commit(manifestRef: string): void;
  abort(): void;
};
//#endregion
//#region src/infra/startup-maintenance-required.d.ts
declare const maintenanceReasons: {
  readonly "state-migrations": "state migration";
  readonly "newer-schema": "a newer OpenClaw build";
  readonly "agent-media": "offline media migration";
  readonly "agent-databases-composite-primary-key": "state database schema migration";
  readonly "audit-events-v2": "state database schema migration";
  readonly "legacy-workshop-review-index": "state database schema migration";
  readonly "legacy-cron-run-logs": "cron run history migration";
  readonly "legacy-workspace": "workspace setup state migration";
  readonly "legacy-session-store": "session store migration";
};
declare class StartupMaintenanceRequiredError extends Error {
  readonly kind: keyof typeof maintenanceReasons;
  readonly code = "gateway.maintenance_required";
  constructor(kind: keyof typeof maintenanceReasons, message: string, options?: ErrorOptions);
  get reason(): string;
}
//#endregion
//#region src/plugin-state/plugin-blob-store.types.d.ts
type PluginBlobEntryInfo<TMetadata> = {
  key: string;
  metadata: TMetadata;
  sizeBytes: number;
  createdAt: number;
  expiresAt?: number;
};
type PluginBlobEntry<TMetadata> = PluginBlobEntryInfo<TMetadata> & {
  bytes: Uint8Array;
};
type PluginBlobStore<TMetadata> = {
  register(key: string, bytes: Uint8Array, metadata: TMetadata, opts?: {
    ttlMs?: number;
  }): Promise<void>;
  registerIfAbsent(key: string, bytes: Uint8Array, metadata: TMetadata, opts?: {
    ttlMs?: number;
  }): Promise<boolean>;
  lookup(key: string): Promise<PluginBlobEntry<TMetadata> | undefined>;
  entries(): Promise<PluginBlobEntryInfo<TMetadata>[]>;
  delete(key: string): Promise<boolean>;
  deleteExpiredKey(key: string): Promise<PluginBlobEntryInfo<TMetadata> | undefined>;
  deleteExpired(): Promise<PluginBlobEntryInfo<TMetadata>[]>;
  clear(): Promise<void>;
};
type PluginBlobOverflowPolicy = "evict-oldest" | "reject-new";
type OpenBlobStoreOptions = {
  namespace: string;
  maxEntries: number;
  maxBytesPerEntry: number;
  maxBytesPerNamespace: number;
  overflowPolicy?: PluginBlobOverflowPolicy;
  defaultTtlMs?: number;
};
type PluginBlobStoreErrorCode = "PLUGIN_BLOB_OPEN_FAILED" | "PLUGIN_BLOB_WRITE_FAILED" | "PLUGIN_BLOB_READ_FAILED" | "PLUGIN_BLOB_CORRUPT" | "PLUGIN_BLOB_LIMIT_EXCEEDED" | "PLUGIN_BLOB_INVALID_INPUT";
type PluginBlobStoreOperation = "open" | "register" | "lookup" | "delete" | "entries" | "clear" | "sweep";
declare class PluginBlobStoreError extends Error {
  readonly code: PluginBlobStoreErrorCode;
  readonly operation: PluginBlobStoreOperation;
  readonly path?: string;
  constructor(message: string, options: {
    code: PluginBlobStoreErrorCode;
    operation: PluginBlobStoreOperation;
    path?: string;
    cause?: unknown;
  });
}
//#endregion
//#region src/state/openclaw-state-db-schema-migration-required.d.ts
type OpenClawStateDatabaseSchemaMigrationRequiredKind = "agent-databases-composite-primary-key" | "audit-events-v2" | "legacy-cron-run-logs" | "legacy-workshop-review-index";
declare class OpenClawStateDatabaseSchemaMigrationRequiredError extends StartupMaintenanceRequiredError {
  readonly kind: OpenClawStateDatabaseSchemaMigrationRequiredKind;
  readonly pathname: string;
  constructor(kind: OpenClawStateDatabaseSchemaMigrationRequiredKind, pathname: string);
}
//#endregion
//#region src/state/openclaw-state-lease-error.d.ts
declare const leaseErrorCodes: readonly ["OPENCLAW_STATE_LEASE_INVALID_INPUT", "OPENCLAW_STATE_LEASE_HELD", "OPENCLAW_STATE_LEASE_ABORTED", "OPENCLAW_STATE_LEASE_LOST", "OPENCLAW_STATE_LEASE_STORAGE_FAILED"];
type OpenClawStateLeaseErrorCode = (typeof leaseErrorCodes)[number];
//#endregion
//#region src/state/session-metadata-unavailable-error.d.ts
declare class SessionMetadataUnavailableError extends Error {
  readonly reason: "schema-missing" | "table-missing";
  readonly missingTables: readonly string[];
  constructor(reason: "schema-missing" | "table-missing", options?: ErrorOptions, missingTables?: readonly string[]);
}
//#endregion
//#region src/state/openclaw-state-worker-error-identity.d.ts
type MaintenanceKind = ConstructorParameters<typeof StartupMaintenanceRequiredError>[0];
type StateMigrationKind = ConstructorParameters<typeof OpenClawStateDatabaseSchemaMigrationRequiredError>[0];
type ErrorIdentity = {
  type: "worker-session-already-attached";
  sessionId: string;
  environmentId: string;
} | {
  type: "workspace-alias-repointed";
  aliasPath: string;
  storedWorkspacePath: string;
  currentWorkspacePath: string;
} | {
  type: "error" | "aggregate" | "ownership" | "newer-schema" | "coordinator" | "range-error" | "syntax-error" | "type-error" | "skill-upload-request" | "mcp-oauth-corruption";
} | {
  type: "state-owner-contention";
  databasePath: string;
} | {
  type: "ownership-metadata";
  databasePath: string;
} | {
  type: "external-ownership";
  databasePath: string;
  managerId: string;
} | {
  type: "state-lease";
  leaseCode: OpenClawStateLeaseErrorCode;
} | {
  type: "plugin-blob";
  blobCode: PluginBlobStoreError["code"];
  operation: PluginBlobStoreError["operation"];
  path?: string;
} | {
  type: "maintenance";
  kind: MaintenanceKind;
} | {
  type: "state-migration";
  kind: StateMigrationKind;
  pathname: string;
} | {
  type: "session-metadata";
  reason: SessionMetadataUnavailableError["reason"];
  missingTables: readonly string[];
} | {
  type: "agent-media-migration";
  pathname: string;
  schemaVersion: number;
};
//#endregion
//#region src/state/openclaw-state-worker-error.d.ts
type ErrorValue = {
  ref: number;
} | {
  value: string | number | boolean | null;
} | {
  undefined: true;
};
type ErrorNode = ErrorIdentity & {
  name: string;
  message: string;
  code?: string | number;
  errcode?: number;
  errno?: number;
  nativeOpen?: true;
  stateDatabasePath?: string;
  cause?: ErrorValue;
  errors?: ErrorValue[];
};
/** A closed error graph; references preserve shared causes and cyclic aggregates. */
type OpenClawStateWorkerErrorPayload = {
  version: 1;
  root: number;
  nodes: ErrorNode[];
};
//#endregion
//#region src/gateway/worker-environments/placement-turn-claims.worker-contract.d.ts
type PlacementTurnClaimReceipt = {
  placement?: WorkerSessionPlacementRecord;
  claim?: WorkerSessionTurnClaim;
};
type PlacementTurnClaimWorkerOperations = {
  "placementTurns.claim": {
    input: {
      claim: WorkerTurnClaimInput;
      nowMs?: number;
    };
    output: PlacementTurnClaimReceipt;
  };
  "placementTurns.release": {
    input: {
      claim: WorkerSessionTurnClaim;
      nowMs?: number;
    };
    output: PlacementTurnClaimReceipt;
  };
  "placementTurns.releaseIfOwned": {
    input: {
      claim: WorkerSessionTurnClaim;
      nowMs?: number;
    };
    output: PlacementTurnClaimReceipt;
  };
  "placementTurns.recoverWorkspace": {
    input: {
      claim: WorkerSessionTurnClaim;
      gatewayInstanceId: string;
      nowMs?: number;
    };
    output: PlacementTurnClaimReceipt;
  };
  "placementTurns.handoffRuntimeRefreshResult": {
    input: {
      claim: WorkerSessionTurnClaim;
      expectedGeneration: number;
      gatewayInstanceId: string;
      nowMs: number;
    };
    output: PlacementTurnClaimReceipt;
  };
};
//#endregion
//#region src/gateway/worker-environments/placement-turn-authority.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/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/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/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-worker-contract.d.ts
type WorkerEnvironmentPruneObservation = Selectable<WorkerEnvironments>;
/** 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: {
    approved: WorkerEnvironmentPruneObservation[];
  }): 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: WorkerEnvironmentRecord;
  }>;
  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/placement-store.d.ts
declare const RETIRABLE_PLACEMENT_STATES: readonly ["local", "requested", "reclaimed", "failed"];
type WorkerSessionPlacementRetirement = {
  sessionId: string;
  expectedState: (typeof RETIRABLE_PLACEMENT_STATES)[number];
  expectedGeneration: number;
};
declare function createWorkerSessionPlacementStore(options?: {
  database?: OpenClawStateDatabase;
  now?: () => number;
}): {
  getWorkspaceReconciliationPlacement(owner: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }): (WorkerSessionPlacementIdentity & {
    generation: number;
    executionMode: WorkerPlacementExecutionMode;
    turnClaim: PersistedTurnClaim | null;
    createdAtMs: number;
    updatedAtMs: number;
    stateChangedAtMs: number;
    workspaceResultConflict?: WorkerWorkspaceResultConflict;
  } & Omit<Omit<Omit<{
    environmentId: null;
    activeOwnerEpoch: null;
    workspaceBaseManifestRef: null;
    remoteWorkspaceDir: null;
    workerBundleHash: null;
    lastTranscriptAckCursor: null;
    lastLiveEventAckCursor: null;
    recoveryError: null;
    terminalReason: null;
    terminalAtMs: 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<{
    environmentId: null;
    activeOwnerEpoch: null;
    workspaceBaseManifestRef: null;
    remoteWorkspaceDir: null;
    workerBundleHash: null;
    lastTranscriptAckCursor: null;
    lastLiveEventAckCursor: null;
    recoveryError: null;
    terminalReason: null;
    terminalAtMs: 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(): {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }[];
  pruneOrphanedWorkspaceReconciliations(options: {
    retainFailedOwner: (recoveryError: string) => boolean;
  }): {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }[];
  loadWorkspaceReconciliation(owner: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }, options?: {
    allowFailedOwner?: boolean;
  }): WorkerWorkspaceReconciliationJournal | undefined;
  beginWorkspaceReconciliation(owner: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }, journal: WorkerWorkspaceReconciliationJournal): void;
  abortWorkspaceReconciliation(owner: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    placementGeneration: number;
  }, options?: {
    force?: boolean;
  }): void;
  workspaceResultInstanceId(): string;
  validateWorkspaceResultClaim(claim: WorkerSessionTurnClaim): boolean;
  listPendingWorkspaceResults(sessionId?: string): WorkerWorkspacePendingResult[];
  markWorkspaceResultPending(claim: WorkerSessionTurnClaim): void;
  recordStagedWorkspaceResult(claim: WorkerSessionTurnClaim, stagedResultRef: string, repositoryWorkspaceId?: string): void;
  acceptWorkspaceResult(claim: WorkerSessionTurnClaim): void;
  handoffWorkspaceResultRecovery(claim: WorkerSessionTurnClaim): void;
  abandonWorkspaceResult(pending: WorkerWorkspacePendingResult): void;
  getPlacementMove(sessionId: string): WorkerPlacementMoveIntent | undefined;
  beginPlacementMove(input: {
    sessionId: string;
    source: WorkerPlacementMoveSource;
    target: WorkerPlacementMoveTarget;
    abandonSource?: true;
  }): {
    intent: WorkerPlacementMoveIntent;
    placement: WorkerSessionPlacementRecord;
    joined: boolean;
  };
  recordPlacementMoveError(input: {
    operationId: string;
    sessionId: string;
    error: string;
  }): boolean;
  cancelPlacementMove(input: {
    operationId: string;
    sessionId: string;
  }): void;
  completePlacementMoveSourceToLocal(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
  }): WorkerSessionPlacementRecord;
  completeAbandonedPlacementMoveSourceToLocal(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
    expectedRecoveryError: string;
  }): WorkerSessionPlacementRecord;
  completePlacementMoveToWorker(input: {
    operationId: string;
    sessionId: string;
    expectedGeneration: number;
    environmentId: string;
    ownerEpoch: number;
  }): WorkerSessionPlacementRecord;
  authorizeWorkerTurnTools(claim: WorkerSessionTurnClaim, toolNames: readonly string[]): void;
  isWorkerTurnToolAuthorized(claim: WorkerSessionTurnClaim, toolName: string): boolean;
  closeWorkerTurnToolAdmission(claim: WorkerSessionTurnClaim): void;
  closeWorkerTurnToolState(claim: WorkerSessionTurnClaim): Promise<void>;
  beginWorkerSessionToolOperation(params: {
    claim: WorkerSessionTurnClaim;
    toolName: "sessions_spawn" | "sessions_send";
    toolCallId: string;
    requestDigest: string;
    childSessionKey?: string;
  }): {
    kind: "execute";
    operationSeed: string;
    childSessionKey?: string;
  } | {
    kind: "in-progress";
  } | {
    kind: "completed";
    resultJson: string;
  } | {
    kind: "unknown";
  } | {
    kind: "capacity";
  } | {
    kind: "conflict";
  } | {
    kind: "unauthorized";
  };
  bindWorkerSessionToolOperationChild(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  } & {
    childSessionKey: string;
  }): boolean;
  completeWorkerSessionToolOperation(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  } & {
    resultJson: string;
    failed?: boolean;
  }): boolean;
  abandonWorkerSessionToolOperation(params: {
    sourceSessionId: string;
    sourceClaimId: string;
    toolCallId: string;
    requestDigest: string;
  }): boolean;
  recoverWorkerSessionToolOperationsAfterRestart(): number;
  failWorkspaceResultAndReleaseTurn(pending: WorkerWorkspacePendingResult, error: unknown): WorkerSessionPlacementRecord;
  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>;
  claimReclaimWorkspaceResult(input: WorkerTurnClaimInput, beforePublish?: (claim: WorkerSessionTurnClaim) => void): WorkerSessionTurnClaim;
  claimWorkspaceMutationResult(input: Omit<WorkerTurnClaimInput, "runId">): WorkerSessionTurnClaim;
  completeWorkspaceResultAndReleaseTurn(claim: WorkerSessionTurnClaim): WorkerSessionPlacementRecord;
  cancelWorkspaceResultAndReleaseTurn(claim: WorkerSessionTurnClaim, options?: {
    reason: "node-disconnect";
  }): WorkerSessionPlacementRecord;
  clearLocalTurnClaimsAfterRestart(): number;
  waitForTurnClaimRelease(sessionIdInput: string, waitOptions: {
    timeoutMs?: number;
    signal?: AbortSignal;
  }): Promise<void>;
  validateTurnClaim(claim: WorkerSessionTurnClaim): boolean;
  updateAckCursors(input: {
    claim: WorkerSessionTurnClaim;
    transcript?: number;
    liveEvent?: number;
  }): WorkerSessionPlacementRecord;
  updateWorkspaceBaseManifest(input: {
    claim: WorkerSessionTurnClaim;
    manifestRef: string;
  }): WorkerSessionPlacementRecord;
  retainInterruptedTurnWorkspace(claim: Parameters<(claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord>[0], assertCurrent: () => void): Promise<void>;
  handoffRuntimeRefreshResult(input: Omit<PlacementTurnClaimWorkerOperations["placementTurns.handoffRuntimeRefreshResult"]["input"], "nowMs">, assertCurrent?: () => void): Promise<WorkerSessionPlacementRecord>;
  claimTurn(input: Parameters<(input: WorkerTurnClaimInput) => WorkerSessionTurnClaim>[0], assertCurrent?: () => void): Promise<WorkerSessionTurnClaim>;
  releaseTurn(claim: Parameters<(claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord>[0], assertCurrent?: () => void): Promise<WorkerSessionPlacementRecord>;
  releaseTurnIfOwned(claim: Parameters<(claim: WorkerSessionTurnClaim) => WorkerSessionPlacementRecord>[0]): Promise<void>;
  registerTurnClaimClosedHandler(handler: (claim: WorkerSessionTurnClaim) => void): () => void;
  get(sessionId: string): WorkerSessionPlacementRecord | undefined;
  prepareTurnClaimAuthority(claim: WorkerSessionTurnClaim): Promise<PlacementTurnClaimAuthority>;
  prepareRuntimeRefresh(sessionIdInput: string): Promise<{
    assertCurrent(this: void): void;
    release(this: void): void;
    placement: WorkerSessionPlacementRecord | undefined;
    move: WorkerPlacementMoveIntent | undefined;
    pendingResult: WorkerWorkspacePendingResult | undefined;
  }>;
  readProjection(sessionIds: readonly string[], readOptions?: {
    current?: boolean;
  }): Promise<WorkerSessionPlacementProjection>;
  readRecoveryCandidates(): Promise<WorkerPlacementRecoveryCandidate[]>;
  getMany(sessionIds: readonly string[]): ReadonlyMap<string, WorkerSessionPlacementRecord>;
  getWorkspaceResultReconcilingSessionIds(sessionIds: readonly string[]): ReadonlySet<string>;
  retireSessionPlacement(input: WorkerSessionPlacementRetirement): void;
  recordWorkspaceResultConflict(claim: WorkerSessionTurnClaim, conflict: WorkerWorkspaceResultConflict | undefined): void;
  bindPreparedEnvironment(input: PreparedEnvironmentSelection): WorkerSessionPlacementRecord | undefined;
  startDispatch(input: WorkerSessionPlacementDispatchIdentity, dispatchOptions?: {
    assertCurrent?: () => void;
  }): Promise<WorkerSessionPlacementRecord>;
  transition(input: {
    sessionId: string;
    from: WorkerSessionPlacementState;
    to: WorkerSessionPlacementState;
    expectedGeneration: number;
    patch?: WorkerSessionPlacementTransitionPatch;
  }): WorkerSessionPlacementRecord;
  startDrain(input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration: number;
    workspaceBaseManifestRef?: string;
  }): WorkerSessionPlacementRecord;
  startWorkspaceResultDrain(claim: WorkerSessionTurnClaim): WorkerSessionPlacementRecord;
  startReconcile(input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration: number;
    forceLocalClaim?: true;
  }): WorkerSessionPlacementRecord;
  fail(input: {
    sessionId: string;
    recoveryError: string;
    expectedGeneration?: number;
  }): WorkerSessionPlacementRecord;
  adoptActive(input: {
    sessionId: string;
    environmentId: string;
    ownerEpoch: number;
    expectedGeneration?: number;
  }): WorkerSessionPlacementRecord;
  listForReconcile(sessionKey?: string): WorkerSessionPlacementRecord[];
  list(): WorkerSessionPlacementRecord[];
  readChangeSnapshot(profileIds?: readonly string[]): Promise<WorkerSessionPlacementChangeSnapshot[]>;
};
type WorkerSessionPlacementStore = ReturnType<typeof createWorkerSessionPlacementStore>;
type WorkerSessionPlacementRetirementService = Pick<WorkerSessionPlacementStore, "retireSessionPlacement">;
//#endregion
//#region src/process/exec-output.d.ts
type CommandOutputCaptureMode = "head" | "tail" | "discard";
type CommandOutputStream = "stdout" | "stderr";
type CommandOutputCaptureOption = CommandOutputCaptureMode | {
  stdout?: CommandOutputCaptureMode;
  stderr?: CommandOutputCaptureMode;
};
type CommandOutputLimitOption = boolean | {
  stdout?: boolean;
  stderr?: boolean;
  combined?: boolean;
};
type CommandOutputErrorOption = boolean | {
  stdout?: boolean;
  stderr?: boolean;
};
type PreserveOutputLine = (line: string, stream: CommandOutputStream) => boolean;
//#endregion
//#region src/process/exec-result.d.ts
type SpawnResult = {
  pid?: number;
  stdout: string;
  stderr: string;
  stdoutTruncatedBytes?: number;
  stderrTruncatedBytes?: number;
  preservedStdoutLines?: string[];
  preservedStderrLines?: string[];
  code: number | null;
  signal: NodeJS.Signals | null;
  killed: boolean;
  /** The runner accepted cancellation and requested termination, independent of the OS signal. */
  killIssuedByAbort?: boolean;
  /** Completion of this invocation's cleanup; never an escaped-descendant inventory. */
  cleanup?: "normal" | "cooperative" | "forced" | "uncertain";
  termination: "exit" | "timeout" | "no-output-timeout" | "signal";
  noOutputTimedOut?: boolean;
  outputLimitExceeded?: boolean;
  outputErrorStream?: "stdout" | "stderr";
};
//#endregion
//#region src/process/exec-runner.d.ts
type CommandOptions = {
  timeoutMs?: number;
  cwd?: string;
  input?: string | Uint8Array;
  /** Borrow a caller-owned descriptor as stdin without buffering or piping its bytes. */
  stdinFileDescriptor?: number;
  /** Synchronous admission with the spawned PID and argv, before input is released. */
  beforeInput?: (pid: number, argv?: readonly string[]) => void;
  baseEnv?: NodeJS.ProcessEnv;
  env?: NodeJS.ProcessEnv;
  windowsVerbatimArguments?: boolean;
  noOutputTimeoutMs?: number;
  signal?: AbortSignal;
  maxOutputBytes?: number | {
    stdout?: number;
    stderr?: number;
  };
  maxCombinedOutputBytes?: number;
  outputCapture?: CommandOutputCaptureOption;
  /** Observe raw output without owning child lifecycle. Return false to stop the command. */
  onOutputChunk?: (chunk: Buffer, stream: CommandOutputStream) => boolean | void;
  /** Accept a successful exit when only the selected diagnostic output stream failed. */
  tolerateOutputError?: {
    stdout?: boolean;
    stderr?: boolean;
  };
  /** Terminate when the selected output stream emits an error. */
  terminateOnOutputError?: CommandOutputErrorOption;
  terminateOnOutputLimit?: CommandOutputLimitOption;
  maxPreservedOutputLines?: number;
  preserveOutputLine?: PreserveOutputLine;
  killProcessTree?: boolean;
  /** Join owned descendants even after a successful root exits. */
  requireProcessTreeExtinction?: boolean;
  /** Initial signal for direct-child and graceful process-group cancellation. */
  killSignal?: NodeJS.Signals | number;
  /** Grace between graceful termination and the force-kill fallback. */
  killGraceMs?: number;
};
declare function runCommandWithTimeout(argv: string[], optionsOrTimeout: number | CommandOptions): Promise<SpawnResult>;
//#endregion
//#region src/worker/tool-authority.d.ts
/** Gateway-proxied tools exposed through the closed worker protocol. */
declare const WORKER_SESSION_TOOL_NAMES: readonly ["skill_workshop", "sessions_spawn", "sessions_send", "portal", "presence"];
declare const WORKER_TOOL_NAMES: readonly ["read", "write", "edit", "apply_patch", "exec", "process", "browser", "computer", "skill_workshop", "sessions_spawn", "sessions_send", "portal", "presence"];
type WorkerSessionToolName = (typeof WORKER_SESSION_TOOL_NAMES)[number];
type WorkerToolName = (typeof WORKER_TOOL_NAMES)[number];
type WorkerExecAuthority = {
  security: ExecSecurity;
  ask: ExecAsk;
  /** No host-specific approvals or default safe bins may be reconstructed remotely. */
  safeBins?: [];
} & ({
  host: Exclude<ExecHost, "node">;
  node?: never;
} | {
  host: "node";
  node?: string;
});
type WorkerToolAuthority = {
  allowedToolNames: WorkerToolName[];
  /**
   * Effective exec policy resolved at the Gateway. Optional for protocol compatibility only;
   * consumers must treat an absent value as denied rather than re-deriving it worker-side.
   */
  exec?: WorkerExecAuthority;
};
//#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.ZodCustom<{
    multipleProfiles: boolean;
  }, {
    multipleProfiles: boolean;
  }>>;
  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<{
    readonly provider: string;
    readonly model: string;
  }, {
    readonly provider: string;
    readonly model: string;
  }>;
  inferenceOptions: z.ZodCustom<{
    readonly temperature?: number | undefined;
    readonly maxTokens?: number | undefined;
    readonly reasoning?: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh" | undefined;
    readonly thinkingBudgets?: {
      readonly minimal?: number | undefined;
      readonly low?: number | undefined;
      readonly medium?: number | undefined;
      readonly high?: number | undefined;
      readonly max?: number | undefined;
    } | undefined;
  }, {
    readonly temperature?: number | undefined;
    readonly maxTokens?: number | undefined;
    readonly reasoning?: "adaptive" | "high" | "low" | "max" | "medium" | "minimal" | "off" | "xhigh" | undefined;
    readonly thinkingBudgets?: {
      readonly minimal?: number | undefined;
      readonly low?: number | undefined;
      readonly medium?: number | undefined;
      readonly high?: number | undefined;
      readonly max?: number | undefined;
    } | undefined;
  }>;
  systemPrompt: z.ZodOptional<z.ZodString>;
  initialMessages: z.ZodCustom<({
    role: "user";
    content: ({
      type: "text";
      text: string;
      textSignature?: string | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
    })[];
    timestamp: number;
  } | {
    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;
    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;
    usage: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      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: "aborted" | "error" | "length" | "stop" | "toolUse";
    errorMessage?: string | undefined;
    errorCode?: string | undefined;
    errorType?: string | undefined;
    errorBody?: string | undefined;
    timestamp: number;
  } | {
    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;
  } | {
    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;
    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;
    usage: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      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: "aborted" | "error" | "length" | "stop" | "toolUse";
    errorMessage?: string | undefined;
    errorCode?: string | undefined;
    errorType?: string | undefined;
    errorBody?: string | undefined;
    timestamp: number;
  } | {
    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;
  })[]>;
  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.ZodPipe<z.ZodCustom<("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[], ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[]>, z.ZodTransform<("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[], ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[]>>;
    exec: z.ZodOptional<z.ZodUnion<readonly [z.ZodPipe<z.ZodUnknown, z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodObject<{
      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<{
      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<{
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
    } | {
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node: string;
    }, {
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node?: string | undefined;
    }>>]>>;
  }, z.core.$strip>>, z.ZodTransform<WorkerToolAuthority, {
    allowedToolNames: ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[];
    exec?: {
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "gateway" | "sandbox";
    } | {
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
    } | {
      security: "allowlist" | "deny" | "full";
      ask: "always" | "off" | "on-miss";
      safeBins?: [] | undefined;
      host: "node";
      node: string;
    } | 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 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>;
}, 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;
  referenceManifestRef: z.ZodString;
  publicationBaseCommit: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>]>;
type NodeWorkerWorkspaceTransferInput = z.infer<typeof NodeWorkerWorkspaceTransferInputSchema>;
//#endregion
//#region src/gateway/worker-environments/workspace-hash-memo.d.ts
declare const { workspaceStatIdentity, selectWorkerWorkspaceHashMemoEntries }: {
  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/infra/git-read-operations.d.ts
type GitCheckoutContext = {
  owner: string;
  repo: string;
  branch: string | null;
  root?: string;
  defaultBranch?: 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;
};
type WorkerRepositoryCheckpointPayload = {
  stagingRoot: string;
  baseManifestRaw: string;
  currentManifestRaw: string;
  baseManifestRef: string;
  currentManifestRef: string;
  publicationStagingRoot?: string;
  publicationDigest?: 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">;
};
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;
  } | WorkerRepositoryWorkspaceSource;
};
type WorkerWorkspaceSyncResult = {
  mode: "git" | "plain";
  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;
  };
};
type WorkerWorkspaceReconcileRequest = {
  remoteWorkspaceDir: string;
  baseManifestRef: string;
  source: {
    kind: "local";
    path: string;
    journal: WorkerWorkspaceReconciliationJournalAdapter;
    assertCurrent?: () => void;
    stagedResult: WorkerLocalWorkspaceReconcileRequest["stagedResult"];
  } | {
    kind: "repository";
    authorize?: () => 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 = {
  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 WorkerTurnTunnelHandle = Omit<WorkerWorkspaceTunnelHandle, "launchTurn" | "measureLaunchTurn" | "readLaunchToolNames"> & {
  measureLaunchTurn(plan: WorkerLaunchPlan, claim: WorkerSessionTurnClaim): number;
  /** Worker tool names the destination's installed supervisor admits in launch descriptors. */
  readLaunchToolNames(): Promise<readonly WorkerToolName[]>;
  launchTurn(request: WorkerTurnLaunchRequest): Promise<SpawnResult>;
};
type WorkerTunnelHandle = WorkerWorkspaceTunnelHandle | WorkerTurnTunnelHandle;
//#endregion
//#region src/agents/tools/common.d.ts
type AgentToolWithMeta<TParameters extends TSchema, TResult> = AgentTool<TParameters, TResult> & {
  displaySummary?: string;
  /** Keep this tool model-visible; hidden catalog bridges cannot preserve its result contract. */
  catalogMode?: "direct-only";
  /** Gateway client capabilities required before this tool can be assembled. */
  requiredClientCaps?: string[];
  /** Tool-owned execution and transport wait budget, before any harness completion grace. */
  getExecutionTimeoutMs?: (args: unknown) => number | undefined;
  prepareBeforeToolCallParams?: (params: unknown, ctx: {
    toolCallId?: string;
    hookContext?: unknown;
    signal?: AbortSignal;
  }) => unknown;
  finalizeBeforeToolCallParams?: (params: unknown, preparedParams: unknown) => unknown;
};
type ErasedAgentToolExecute = {
  execute(this: void, toolCallId: string, params: unknown, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback): Promise<AgentToolResult<unknown>>;
};
type AnyAgentTool = Omit<AgentToolWithMeta<TSchema, unknown>, "execute"> & ErasedAgentToolExecute;
//#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$1;
  /** 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$1>, consume: () => T) => T;
}
/** Runtime dependency subset required by streaming agent loops. */
type AgentCoreStreamRuntimeDeps = Pick<AgentCoreRuntimeDeps, "streamSimple" | "runStream">;
//#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;
  /** 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 before the next unstarted tool or model turn. */
  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 readonly listeners;
  private readonly steeringQueue;
  private readonly followUpQueue;
  private readonly toolLoopRecoveryState;
  convertToLlm: NonNullable<AgentOptions["convertToLlm"]>;
  transformContext?: NonNullable<AgentOptions["transformContext"]>;
  runtime?: AgentCoreStreamRuntimeDeps;
  streamFn: StreamFn;
  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, 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. Running tools finish, while sequential
   * tail calls or a parallel batch that has not launched yet are skipped.
   */
  steer(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 still contains pending messages. */
  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 the current transcript. The last message must be a user or tool-result message. */
  continue(): Promise<void>;
  private normalizePromptInput;
  private runPromptMessages;
  private runContinuation;
  private createContextSnapshot;
  private createLoopConfig;
  private runWithLifecycle;
  private handleRunFailure;
  private finishRun;
  /**
   * 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 `finishRun()` clears runtime-owned state.
   */
  private processEvents;
}
//#endregion
//#region src/plugins/plugin-instance.types.d.ts
/** Disposal and admission shared by instance resources and registry handles. */
type PluginInstanceLifecycle = {
  readonly signal: AbortSignal;
  onDispose: (dispose: () => void | Promise<void>) => () => void;
};
/** 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[];
  /** Errors seen only in host cleanup, eligible for its named-hook reporting. */
  hostCleanupErrors?: 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>): Promise<PluginInstanceDisposalResult>;
}
/** Captured code custody survives retiring a runtime until recovery consumes or releases it. */
type PluginModuleLoaderRecovery = {
  bind(instance: PluginModuleLoaderOwner): void;
  dispose(): 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): void;
  captureModuleLoaderRecovery(): PluginModuleLoaderRecovery;
}
/** Current-call helpers retain the instance itself, not a registry or plugin-id lookup. */
interface PluginInvocationInstance extends PluginModuleLoaderOwner {
  readonly slots: Map<string | symbol, {
    runtime: unknown;
  }>;
  wrap<T>(value: T): T;
}
//#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: "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/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/infra/gateway-scheduler.d.ts
type GatewaySchedulerClock = {
  now: () => number;
  monotonicNow: () => number;
  arm: (run: () => void | Promise<void>, delayMs: number) => () => void;
};
type GatewayScheduledJob = {
  cancel: () => void;
  stop: () => Promise<void>;
};
/** 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 timerGeneration;
  private closed;
  private readonly controller;
  constructor(options?: {
    clock?: GatewaySchedulerClock;
  });
  get signal(): AbortSignal;
  now(): number;
  get nextWakeAtMs(): number | null;
  schedule(params: {
    id: string;
    everyMs?: number;
    /** Keep both pending clock deadlines when a stale read would postpone the wake. */
    mode?: "replace" | "earliest";
    run: () => void | Promise<unknown>;
  } & ({
    atMs: number;
  } | {
    delayMs: number;
  })): GatewayScheduledJob;
  beginClose(): void;
  stop(): Promise<void>;
  private remaining;
  private arm;
  private wake;
  private run;
}
//#endregion
//#region src/infra/heartbeat-wake-contracts.d.ts
type HeartbeatRunResult = {
  status: "ran";
  durationMs: number;
} | {
  status: "skipped";
  reason: string;
  retryAtMs?: number;
} | {
  status: "failed";
  reason: string;
};
type HeartbeatWakeIntent = "scheduled" | "task" | "event" | "immediate" | "manual";
type HeartbeatWakeSource = "interval" | "manual" | "exec-event" | "notifications-event" | "cron" | "hook" | "background-task" | "background-task-blocked" | "acp-spawn" | "session-state" | "cli-watchdog" | "restart-sentinel" | "retry" | "other";
type HeartbeatWakeOverride = {
  target?: string;
  to?: string | undefined;
  accountId?: string | undefined;
};
/** Cron-owned periodic work carried directly into a guarded heartbeat turn. */
type HeartbeatScheduledTask = {
  jobId: string;
  name: string;
  prompt: string;
};
type HeartbeatWakeRequest = {
  source: HeartbeatWakeSource;
  intent: HeartbeatWakeIntent;
  reason?: string;
  agentId?: string;
  sessionKey?: string;
  sessionStorePath?: string | null;
  heartbeat?: HeartbeatWakeOverride;
  /** Persisted cron monitor cadence carried with a scheduled heartbeat tick. */
  scheduledEveryMs?: number;
  tasks?: readonly HeartbeatScheduledTask[];
  /** Internal marker for work retained after a spacing/cooldown deferral. */
  retainedWork?: boolean;
};
//#endregion
//#region src/infra/session-event-wake.d.ts
type SessionEventWakeResult = HeartbeatRunResult;
type SessionEventWakeRequest = HeartbeatWakeRequest;
type WakeHandler = (request: SessionEventWakeRequest, signal: AbortSignal) => Promise<SessionEventWakeResult>;
type SessionEventWakeWaitOptions = {
  abortSignal?: AbortSignal;
  /** Called when the queue starts an attempt for this waiter. */
  onAttemptStarted?: () => void;
  /** Called whenever this waiter enters the queue, including retained retries. */
  onQueued?: () => void;
  /** Detach this waiter while the queue retains the wake at its retry deadline. */
  stopWaitingOnRetry?: (result: Extract<SessionEventWakeResult, {
    status: "skipped";
  }>, retryAtMs: number) => boolean;
};
type RequestOptions = Omit<SessionEventWakeRequest, "retainedWork"> & {
  coalesceMs?: number;
};
declare const { setSessionEventWakeHandler, requestSessionEventWake, requestSessionEventWakeAndWait, getSessionEventWakeAbortSignal, markSessionEventWakeWorkStarted, deferSessionEventWakePoll, isSessionEventWakePollDeferred, areSessionEventWakesEnabled, setSessionEventWakesEnabled }: {
  setSessionEventWakeHandler: (next: WakeHandler | null) => () => void;
  requestSessionEventWake: (options: RequestOptions) => void;
  requestSessionEventWakeAndWait: (options: RequestOptions, lifecycle?: SessionEventWakeWaitOptions) => Promise<SessionEventWakeResult>;
  getSessionEventWakeAbortSignal: () => AbortSignal | undefined;
  markSessionEventWakeWorkStarted: () => void;
  deferSessionEventWakePoll: () => boolean;
  isSessionEventWakePollDeferred: () => boolean;
  areSessionEventWakesEnabled: () => boolean;
  setSessionEventWakesEnabled: (value: boolean) => void;
};
//#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/agents/embedded-agent-runner/execution-phase.d.ts
/**
 * Ordered execution milestones reported by the embedded runner while a turn starts up.
 *
 * Keep labels stable: external status surfaces and diagnostics consume the formatted values.
 */
declare const EMBEDDED_AGENT_EXECUTION_PHASE_LABELS: {
  readonly runner_entered: "runner-entered";
  readonly workspace: "workspace";
  readonly runtime_plugins: "runtime-plugins";
  readonly before_agent_reply: "before-agent-reply";
  readonly model_resolution: "model-resolution";
  readonly auth: "auth";
  readonly context_engine: "context-engine";
  readonly attempt_dispatch: "attempt-dispatch";
  readonly context_assembled: "context-assembled";
  readonly turn_accepted: "turn-accepted";
  readonly process_spawned: "process-spawned";
  readonly tool_execution_started: "tool-execution-started";
  readonly assistant_output_started: "assistant-output-started";
  readonly model_call_started: "model-call-started";
};
type EmbeddedAgentExecutionPhase = keyof typeof EMBEDDED_AGENT_EXECUTION_PHASE_LABELS;
//#endregion
//#region src/agents/failover/signal.d.ts
/** Persisted and wire-visible failover reason codes. Spellings are frozen. */
declare const FAILOVER_REASONS: readonly ["auth", "auth_permanent", "format", "rate_limit", "overloaded", "billing", "server_error", "timeout", "tls_certificate", "context_overflow", "model_not_found", "session_expired", "empty_response", "no_error_details", "unclassified", "unknown"];
type FailoverReason = (typeof FAILOVER_REASONS)[number];
//#endregion
//#region src/cron/types-shared.d.ts
/** Optional dynamic-cadence bounds for one cron job. */
type CronPacing = {
  min?: string;
  max?: 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;
  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 = "next-heartbeat" | "now";
/** 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;
  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">> & {
  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 = "ok" | "error" | "skipped";
/** 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" | "heartbeat";
}> | (Extract<CronJob$1["payload"], {
  kind: "agentTurn";
}> & CronExternalContent) | ({
  kind: "heartbeat";
} & CronPayloadToolAllow);
/** Partial payload update shape used by cron patch/edit flows. */
type CronPayloadPatch = Exclude<CronPayloadPatchWire, {
  kind: "agentTurn";
}> | (Extract<CronPayloadPatchWire, {
  kind: "agentTurn";
}> & CronExternalContent) | ({
  kind: "heartbeat";
} & CronPayloadToolAllowPatch);
type CronPayloadToolAllow = {
  /** Restricts agentTurn execution, or the trigger runtime for other payload kinds. */
  toolsAllow?: string[];
  /** Server-managed marker for auto-stamped defaults; explicit restrictions omit it. */
  toolsAllowIsDefault?: boolean;
};
type CronPayloadToolAllowPatch = {
  toolsAllow?: string[] | null;
  toolsAllowIsDefault?: boolean;
};
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;
  /** 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. */
  failureAlertIncident?: {
    signature?: string;
    scope: "run" | "trigger";
  };
  /** 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 = {
  script: string;
  once?: boolean;
};
/** 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;
  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 = CronJob & {
  /** Immutable revisions inherited from the authorized creator session, never human mutation authority. */
  skillLibrarySelections?: SessionEntry$1["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, "autoDisabled" | "scheduleActivatedAtMs" | "streamSourceIdentity" | "runningReceiptId" | "runningScheduleChangeId">>;
/** Create input accepted by cron APIs before id/timestamps/state are assigned. */
type CronJobCreate = Omit<CronJob, "id" | "createdAtMs" | "updatedAtMs" | "state" | "scheduledToolPolicy"> & {
  /** 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" | "pacing" | "trigger">> & {
  displayName?: string | null;
  pacing?: CronPacing | null;
  trigger?: CronTrigger | null;
  payload?: CronPayloadPatch;
  delivery?: CronDeliveryPatch;
  failureAlert?: CronFailureAlertPatch | false | null;
  state?: CronJobStateInput;
};
//#endregion
//#region src/cron/service/list-page-types.d.ts
/** Enabled-state filter accepted by paginated cron listing. */
type CronJobsEnabledFilter = "all" | "enabled" | "disabled";
/** Schedule-kind filter accepted by paginated cron listing. */
type CronJobsScheduleKindFilter = "all" | "at" | "every" | "cron" | "on-exit" | "stream";
/** Last-run status filter, including jobs that have not produced a status yet. */
type CronJobsLastRunStatusFilter = "all" | CronRunStatus | "unknown";
/** Condition-trigger filter accepted by paginated cron listing. */
type CronJobsTriggerFilter = "all" | "conditional" | "unconditional";
/** Stable sort keys supported by paginated cron listing. */
type CronJobsSortBy = "nextRunAtMs" | "updatedAtMs" | "name";
/** Sort direction for paginated cron listing. */
type CronSortDir = "asc" | "desc";
/** Input contract for filtered, sorted, offset-based cron job pages. */
type CronListPageOptions = {
  includeDisabled?: boolean;
  limit?: number;
  offset?: number;
  query?: string;
  enabled?: CronJobsEnabledFilter;
  scheduleKind?: CronJobsScheduleKindFilter;
  lastRunStatus?: CronJobsLastRunStatusFilter;
  trigger?: CronJobsTriggerFilter;
  sortBy?: CronJobsSortBy;
  sortDir?: CronSortDir;
  agentId?: string;
};
/** Offset-page result returned by cron listPage callers. */
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
/** 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;
  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;
/** Caller-specific declaration-key visibility and explicit enablement metadata. */
type CronAddOptions = {
  /** Selected revisions captured from a validated caller session, never public input. */
  skillLibrarySelections?: CronStoredJob["skillLibrarySelections"];
  matchesExisting?: (job: CronJob) => boolean;
  enabledExplicit?: boolean;
  /** Gateway/doctor-owned heartbeat jobs require this opt-in at service 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 guard consumed immediately before mutation. */
  commitGuard?: () => void;
  /** One-use fresh capture; callback presence means fresh even when it returns undefined. */
  captureRuntimeAuthority?: () => CronRuntimeAuthority | undefined;
};
type CronUpdateInput = CronJobPatch;
/** Authenticated caller provenance used only when a tool policy is explicitly adopted. */
type CronUpdateOptions = Pick<CronAddOptions, "toolsAllowProvenance" | "toolsAllowExecTarget" | "commitGuard" | "captureRuntimeAuthority"> & {
  /** Null forbids policy adoption; undefined retains in-process operator defaults. */
  scheduledToolPolicy?: CronScheduledToolPolicy | null;
};
type CronCommitGuardOptions = {
  /** Synchronous Gateway-owned guard consumed at the mutation owner. */
  commitGuard?: () => void;
};
/** 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/cron/service-contract.d.ts
type CronWakeResult = {
  ok: true;
} | {
  ok: false;
  reason?: "unwakeable-session-key";
};
/** Result shape for direct/queued cron runs. */
type CronServiceRunResult = CronRunResult;
type CronServiceRunOptions = {
  payload?: CronPayload;
  /** 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 {
  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?: {
    systemOwned?: boolean;
  } & CronCommitGuardOptions): Promise<CronRemoveResult>;
  run(id: string, mode?: CronRunMode, opts?: CronServiceRunOptions): Promise<CronServiceRunResult>;
  enqueueRun(id: string, mode?: CronRunMode, opts?: CronCommitGuardOptions): Promise<CronServiceRunResult>;
  getJob(id: string): CronJob | undefined;
  readJob(id: string): Promise<CronJob | undefined>;
  getDefaultAgentId(): string | undefined;
  wake(opts: {
    mode: CronWakeMode;
    text: string;
    sessionKey?: string;
    agentId?: string;
  }): CronWakeResult;
}
//#endregion
//#region src/gateway/live-text-continuity.d.ts
type LiveTextProjectionText = {
  snapshot: string;
  delta: string;
};
//#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[];
};
//#endregion
//#region src/plugins/runtime/subagent-requester-context.d.ts
type PluginSubagentRequesterContext = Readonly<{
  sessionKey: string;
  origin: Readonly<DeliveryContext>;
}>;
//#endregion
//#region src/gateway/auth-resolve.d.ts
/** Authentication modes after config, override, and credential inputs are combined. */
type ResolvedGatewayAuthMode = "none" | "token" | "password" | "trusted-proxy";
/** Records which input selected the effective Gateway auth mode. */
type ResolvedGatewayAuthModeSource = "override" | "config" | "password" | "token" | "default";
/** Fully resolved Gateway auth policy before startup validates required secrets. */
type ResolvedGatewayAuth = {
  mode: ResolvedGatewayAuthMode;
  modeSource?: ResolvedGatewayAuthModeSource;
  token?: string;
  password?: string;
  allowTailscale: boolean;
  trustedProxy?: GatewayTrustedProxyConfig;
};
//#endregion
//#region src/gateway/ingress-attribution.d.ts
type VerifiedTailscaleIngressIdentity = {
  login: string;
  name: string;
  profilePic?: string;
};
//#endregion
//#region src/gateway/auth.d.ts
/** Normalized outcome for gateway shared-secret, Tailscale, device, and proxy auth. */
type GatewayAuthResult = {
  ok: boolean;
  method?: "none" | "token" | "password" | "tailscale" | "device-token" | "bootstrap-token" | "trusted-proxy";
  user?: string;
  /** Full verified Tailscale identity; present only after header + WhoIs agreement. */
  tailscaleIdentity?: VerifiedTailscaleIdentity;
  reason?: string;
  /** Present when the request was blocked by the rate limiter. */
  rateLimited?: boolean;
  /** Milliseconds the client should wait before retrying (when rate-limited). */
  retryAfterMs?: number;
};
type VerifiedTailscaleIdentity = VerifiedTailscaleIngressIdentity;
//#endregion
//#region src/gateway/server/client-identity-types.d.ts
/** Server-attested identity facts shared by RPC and transport client records. */
type GatewayWsBrowserOrigin = {
  requestHost?: string;
  origin?: string;
  isLocalClient?: boolean;
};
type PreparedSessionProfile = {
  profileId: string;
  aliases: ReadonlySet<string>;
  role: string | null;
};
//#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 = {
  profileId: string;
  updatedAt: number;
};
type AuthenticatedGitHubIdentitySync = () => Promise<AuthenticatedGitHubIdentitySyncResult>;
//#endregion
//#region src/gateway/operator-access-policy.types.d.ts
type GatewayOperatorAccessAuthority = PluginGatewayAccessAuthority & {
  readonly gatewayAccessGrant?: GatewayAccessGrantRef;
};
//#endregion
//#region src/gateway/operator-role-actor.d.ts
/** Host-minted role authority; never accepted from Gateway wire params.
    Leaf contract: both ws-types and server-methods/shared-types embed it in
    client `internal` state, so it must not import either hub. */
type GatewayOperatorRoleActor = {
  kind: "system";
} | {
  kind: "operator";
  profileId: string;
};
//#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
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;
  }>;
};
//#endregion
//#region src/gateway/server-methods/session-creation-provenance.d.ts
type TrustedSessionCreation = {
  skillLibrarySelections?: SkillLibrarySelection[];
  via: SessionCreatedVia;
  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;
  /** Host-verified human requester; never accepted from model-authored parameters. */
  requesterProfileId?: string;
  /** Immutable completion recipient for a spawn-owned visible session. */
  completionOwnerSessionKey?: string;
  /** Prepared parent selection; never accepted from public creation parameters. */
  resolvedModel?: ProviderModelRef;
  /** Effective host-prepared permission mode, not a public permission-change request. */
  inheritedPermissionMode?: SessionPermissionMode;
  /** Effective caller tool-policy snapshot for an in-process visible spawn. */
  inheritedToolPolicy?: {
    version: 1;
    allow: string[];
    deny: string[];
  };
  /** Config-selected model provenance from the trusted spawning tool. */
  spawnModelAutoSelection?: AgentRuntimeSpawnModelAutoSelection;
};
//#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;
  /** 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;
};
/** Per-connection client metadata captured after the gateway handshake. */
type GatewayClient = {
  connect: ConnectParams;
  authPolicy?: GatewayAuthPolicy;
  /** Transport-owned revocation marker; retained callers have no authority after invalidation. */
  invalidated?: boolean;
  /** Host-owned transport retirement notification; does not cancel ordinary admitted RPCs. */
  connectionSignal?: AbortSignal;
  /** Server-attested browser origin captured during the WebSocket handshake. */
  browserOrigin?: GatewayWsBrowserOrigin;
  connId?: string;
  presenceKey?: string;
  clientIp?: string;
  /** Client id verified against the server-approved device pairing record. */
  pairedClientId?: string;
  authenticatedUserId?: string;
  /** Verified Tailscale provider identity; generic proxy identities must not infer this. */
  authenticatedUserIsTailscaleProvider?: boolean;
  authenticatedGitHubIdentitySync?: AuthenticatedGitHubIdentitySync;
  /** Prepared at identity admission and profile publication, before session reads or events. */
  preparedSessionProfile?: PreparedSessionProfile;
  authenticatedUserProfile?: {
    profileId: string;
    displayName: string | null;
    avatarRevision?: string;
    hasAvatar: boolean;
    updatedAt: number;
  };
  pluginSurfaceUrls?: Record<string, string>;
  pluginNodeCapabilitySurfaces?: Record<string, PluginNodeCapabilitySurface>;
  pluginNodeCapabilities?: Record<string, {
    capability: string;
    expiresAtMs: number;
  }>;
  isDeviceTokenAuth?: boolean;
  internal?: {
    /** Handshake-attested direct-local transport; never accepted from wire params. */
    isLocalClient?: true;
    /** Authenticated operator transport ingress; never accepted from wire params. */
    authenticatedOperator?: 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;
    /** Marks the server-constructed client used by trusted in-process dispatch. */
    syntheticClient?: true;
    /** Host-owned role authority retained separately from an autonomous run principal. */
    operatorRoleActor?: GatewayOperatorRoleActor;
    /** Original source restriction carried only by trusted in-process run admission. */
    operatorRunAuthority?: AdmittedRunOperatorAuthority;
    /** Closure-bound access captured by the authenticated ingress, never wire data. */
    operatorAccessAuthority?: GatewayOperatorAccessAuthority | null;
    /** 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;
    cronRunContinuation?: boolean;
    agentRuntimeIdentity?: AgentRuntimeIdentity;
    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;
    /** Host-owned exact media set for a scoped automatic recovery delivery. */
    internalDeliveryMediaUrls?: string[];
    runtimeContextFragments?: RuntimeContextFragment[];
    internalDeliverySuppressText?: 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/server-broadcast-types.d.ts
type GatewayBroadcastStateVersion = {
  presence?: number;
  health?: number;
};
/** Options for gateway websocket broadcasts. */
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[];
  /** 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;
    };
  };
};
/** Broadcast function signature for all connected clients. */
type GatewayBroadcastFn = (event: string, payload: unknown, opts?: GatewayBroadcastOpts) => void;
/** Broadcast function signature for targeted connection ids. */
type GatewayBroadcastToConnIdsFn = (event: string, payload: unknown, connIds: ReadonlySet<string>, opts?: GatewayBroadcastOpts) => void;
//#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/diagnostic-event-listener-presence.d.ts
/** Process-wide listener counts used to avoid telemetry work without consumers. */
type InternalDiagnosticEventInterest<EventType extends string = string> = Readonly<{
  include?: readonly EventType[];
  exclude?: readonly EventType[];
  /** Restricts trusted events only; untrusted events still use include/exclude. */
  includeTrusted?: readonly EventType[];
}>;
//#endregion
//#region src/infra/diagnostic-process-types.d.ts
type DiagnosticMemoryUsage = {
  rssBytes: number;
  heapTotalBytes: number;
  heapUsedBytes: number;
  externalBytes: number;
  arrayBuffersBytes: number;
  workerCount?: number;
  workerHeapSampledCount?: number;
  workerHeapTotalBytes?: number;
  workerHeapUsedBytes?: number;
  workerExternalBytes?: number;
  workerArrayBuffersBytes?: number;
  workerArrayBuffersSampledCount?: number;
  /** Coverage concerns direct Workers only; nested isolates are not in the parent registry. */
  workerMemoryScope?: "direct";
  workerMemoryCoverage?: "complete" | "partial" | "unavailable";
  workerMemoryMissing?: {
    script: string;
    threadId: number;
    reason: "pending" | "stale" | "unavailable";
  }[];
  /** Live, fresh isolate samples; script is an allowlisted basename or "other". */
  workerHeaps?: {
    script: string;
    heapUsed: number;
    heapTotal: number;
    threadId?: number;
    external?: number;
    /** Missing for native-only samplers; zero is a measured value. Included in external. */
    arrayBuffers?: number;
    sampleAgeMs?: number;
  }[];
  /** Cumulative process-owned counts; script and reason come from fixed allowlists. */
  workerLifecycle?: {
    script: string;
    started: number;
    retired: {
      reason: string;
      count: number;
    }[];
  }[];
};
type DiagnosticChildProcessSpawnFields = {
  type: "diagnostic.child_process.spawn";
  family: string;
  count: number;
  intervalMs: number;
};
//#endregion
//#region src/infra/diagnostic-run-types.d.ts
type DiagnosticRunScopeFields = {
  runId: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  provider?: string;
  model?: string;
  trigger?: string;
  channel?: string;
};
type DiagnosticAgentCommentaryFields = DiagnosticRunScopeFields & {
  type: "agent.commentary";
  harnessId: string;
  pluginId?: string;
  itemId?: string;
  sourceSequence: number;
  sourceTimestampMs: number;
  textLength: number;
  contentCaptured: boolean;
  contentTruncated: boolean;
};
//#endregion
//#region src/infra/diagnostic-trace-context.d.ts
type DiagnosticTraceContext = {
  /** W3C trace id, 32 lowercase hex chars. */
  readonly traceId: string;
  /** Current span id, 16 lowercase hex chars. */
  readonly spanId?: string;
  /** Parent span id, 16 lowercase hex chars. */
  readonly parentSpanId?: string;
  /** W3C trace flags, 2 lowercase hex chars. Defaults to sampled. */
  readonly traceFlags?: string;
};
//#endregion
//#region src/infra/diagnostic-events.d.ts
type DiagnosticSessionState = "idle" | "processing" | "waiting";
type DiagnosticBaseEvent = {
  ts: number;
  seq: number;
  trace?: DiagnosticTraceContext;
};
/** Payload-free facts from authenticated Gateway WebSocket request owners. */
type DiagnosticGatewayRpcEvent = DiagnosticBaseEvent & {
  type: "gateway.rpc";
  /** Canonical core method name, or a fixed other/unknown bucket. */
  method: string;
} & ({
  phase: "received";
} | {
  phase: "response";
  outcome: "ok" | "error" | "unavailable" | "suppressed";
  durationMs: number;
} | {
  phase: "handler";
  outcome: "returned" | "threw";
  durationMs: number;
  admissionMs: number;
} | {
  phase: "dispatch";
  outcome: "returned" | "threw" | "rejected" | "cancelled";
  durationMs: number;
  queueWaitMs?: number;
  response: "none" | "sent" | "unavailable" | "suppressed";
});
type DiagnosticUsageEvent = DiagnosticBaseEvent & {
  type: "model.usage";
  sessionKey?: string;
  sessionId?: string;
  channel?: string;
  agentId?: string;
  provider?: string;
  model?: string;
  usage: {
    input?: number;
    output?: number;
    cacheRead?: number;
    cacheWrite?: number;
    promptTokens?: number;
    total?: number;
  };
  lastCallUsage?: {
    input?: number;
    output?: number;
    cacheRead?: number;
    cacheWrite?: number;
    total?: number;
  };
  context?: {
    limit?: number;
    used?: number;
  };
  costUsd?: number;
  durationMs?: number;
};
type DiagnosticFailoverEvent = DiagnosticBaseEvent & {
  type: "model.failover";
  sessionId?: string;
  sessionKey?: string;
  lane?: string;
  fromProvider?: string;
  fromModel?: string;
  toProvider?: string;
  toModel?: string;
  reason: string;
  cascadeDepth?: number;
  suspended?: boolean;
};
type DiagnosticSecurityEventActor = {
  kind: "operator" | "node" | "agent" | "plugin" | "channel_sender" | "system";
  idHash?: string;
  deviceIdHash?: string;
  channel?: string;
  role?: string;
  scopes?: string[];
};
type DiagnosticSecurityEventTarget = {
  kind: "gateway" | "device" | "node" | "tool" | "plugin" | "secret_ref" | "channel" | "config" | "session";
  idHash?: string;
  name?: string;
  owner?: string;
};
type DiagnosticSecurityEventPolicy = {
  id?: string;
  decision?: "allow" | "deny" | "ask" | "auto" | "full" | "not_applicable";
  reason?: string;
};
type DiagnosticSecurityEventControl = {
  id?: string;
  family?: "auth" | "authorization" | "approval" | "sandbox" | "secret" | "supply_chain";
};
type DiagnosticSecurityEvent = DiagnosticBaseEvent & {
  type: "security.event";
  eventId: string;
  category: "auth" | "approval" | "tool" | "plugin" | "secret" | "channel" | "config" | "audit" | "telemetry";
  action: string;
  outcome: "success" | "failure" | "denied" | "error";
  severity: "info" | "low" | "medium" | "high" | "critical";
  actor?: DiagnosticSecurityEventActor;
  target?: DiagnosticSecurityEventTarget;
  policy?: DiagnosticSecurityEventPolicy;
  control?: DiagnosticSecurityEventControl;
  reason?: string;
  attributes?: Record<string, string | number | boolean>;
};
type DiagnosticWebhookReceivedEvent = DiagnosticBaseEvent & {
  type: "webhook.received";
  channel: string;
  updateType?: string;
  chatId?: number | string;
};
type DiagnosticWebhookProcessedEvent = DiagnosticBaseEvent & {
  type: "webhook.processed";
  channel: string;
  updateType?: string;
  chatId?: number | string;
  durationMs?: number;
};
type DiagnosticWebhookErrorEvent = DiagnosticBaseEvent & {
  type: "webhook.error";
  channel: string;
  updateType?: string;
  chatId?: number | string;
  error: string;
};
type DiagnosticMessageQueuedEvent = DiagnosticBaseEvent & {
  type: "message.queued";
  sessionKey?: string;
  sessionId?: string;
  channel?: string;
  source: string;
  queueDepth?: number;
};
type DiagnosticMessageReceivedEvent = DiagnosticBaseEvent & {
  type: "message.received";
  sessionKey?: string;
  sessionId?: string;
  channel?: string;
  messageId?: number | string;
  chatId?: number | string;
  source: string;
};
type DiagnosticMessageDispatchStartedEvent = DiagnosticBaseEvent & {
  type: "message.dispatch.started";
  sessionKey?: string;
  sessionId?: string;
  channel?: string;
  source: string;
};
type DiagnosticMessageDispatchCompletedEvent = DiagnosticBaseEvent & {
  type: "message.dispatch.completed";
  sessionKey?: string;
  sessionId?: string;
  channel?: string;
  source: string;
  durationMs: number;
  outcome: "completed" | "skipped" | "error";
  reason?: string;
  error?: string;
};
type DiagnosticMessageProcessedEvent = DiagnosticBaseEvent & {
  type: "message.processed";
  channel: string;
  messageId?: number | string;
  chatId?: number | string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  durationMs?: number;
  outcome: "completed" | "skipped" | "error";
  reason?: string;
  error?: string;
};
type DiagnosticMessageDeliveryKind = "text" | "media" | "edit" | "reaction" | "other";
type DiagnosticMessageDeliveryBaseEvent = DiagnosticBaseEvent & {
  channel: string;
  sessionKey?: string;
  deliveryKind: DiagnosticMessageDeliveryKind;
};
type DiagnosticMessageDeliveryStartedEvent = DiagnosticMessageDeliveryBaseEvent & {
  type: "message.delivery.started";
};
type DiagnosticMessageDeliveryCompletedEvent = DiagnosticMessageDeliveryBaseEvent & {
  type: "message.delivery.completed";
  durationMs: number;
  resultCount: number;
};
type DiagnosticMessageDeliveryErrorEvent = DiagnosticMessageDeliveryBaseEvent & {
  type: "message.delivery.error";
  durationMs: number;
  errorCategory: string;
};
type DiagnosticTalkEvent = DiagnosticBaseEvent & {
  type: "talk.event";
  sessionId?: string;
  turnId?: string;
  captureId?: string;
  talkEventType: TalkEventType;
  mode: TalkMode;
  transport: TalkTransport;
  brain: TalkBrain;
  provider?: string;
  final?: boolean;
  durationMs?: number;
  byteLength?: number;
};
type DiagnosticSessionStateEvent = DiagnosticBaseEvent & {
  type: "session.state";
  sessionKey?: string;
  sessionId?: string;
  prevState?: DiagnosticSessionState;
  state: DiagnosticSessionState;
  reason?: string;
  queueDepth?: number;
};
type DiagnosticSessionActiveWorkKind = "embedded_run" | "model_call" | "tool_call";
type DiagnosticSessionAttentionClassification = "long_running" | "blocked_tool_call" | "stalled_agent_run" | "stale_session_state";
type DiagnosticSessionAttentionBaseEvent = DiagnosticBaseEvent & {
  sessionKey?: string;
  sessionId?: string;
  state: DiagnosticSessionState;
  ageMs: number;
  queueDepth?: number;
  reason?: string;
  classification: DiagnosticSessionAttentionClassification;
  activeWorkKind?: DiagnosticSessionActiveWorkKind;
  lastProgressAgeMs?: number;
  lastProgressReason?: string;
  activeToolName?: string;
  activeToolCallId?: string;
  activeToolAgeMs?: number;
  repeatedRequestNoProgressAgeMs?: number;
  terminalProgressStale?: boolean;
};
type DiagnosticSessionLongRunningEvent = DiagnosticSessionAttentionBaseEvent & {
  type: "session.long_running";
  classification: "long_running";
};
type DiagnosticSessionStalledEvent = DiagnosticSessionAttentionBaseEvent & {
  type: "session.stalled";
  classification: "blocked_tool_call" | "stalled_agent_run";
};
type DiagnosticSessionStuckEvent = DiagnosticSessionAttentionBaseEvent & {
  type: "session.stuck";
  classification: "stale_session_state";
};
type DiagnosticSessionRecoveryStatus = "aborted" | "released" | "skipped" | "noop" | "failed";
type DiagnosticSessionRecoveryBaseEvent = DiagnosticBaseEvent & {
  sessionKey?: string;
  sessionId?: string;
  state: DiagnosticSessionState;
  stateGeneration?: number;
  ageMs: number;
  queueDepth?: number;
  reason?: string;
  activeWorkKind?: DiagnosticSessionActiveWorkKind;
  allowActiveAbort?: boolean;
};
type DiagnosticSessionRecoveryRequestedEvent = DiagnosticSessionRecoveryBaseEvent & {
  type: "session.recovery.requested";
};
type DiagnosticSessionRecoveryCompletedEvent = DiagnosticSessionRecoveryBaseEvent & {
  type: "session.recovery.completed";
  status: DiagnosticSessionRecoveryStatus;
  action: string;
  outcomeReason?: string;
  released?: number;
  stale?: boolean;
};
type DiagnosticSessionTurnCreatedEvent = DiagnosticBaseEvent & {
  type: "session.turn.created";
  runId: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  channel?: string;
  trigger: "user" | "heartbeat";
};
type DiagnosticLaneEnqueueEvent = DiagnosticBaseEvent & {
  type: "queue.lane.enqueue";
  lane: string;
  queueSize: number;
};
type DiagnosticLaneDequeueEvent = DiagnosticBaseEvent & {
  type: "queue.lane.dequeue";
  lane: string;
  queueSize: number;
  waitMs: number;
};
type DiagnosticRunAttemptEvent = DiagnosticBaseEvent & {
  type: "run.attempt";
  sessionKey?: string;
  sessionId?: string;
  runId: string;
  attempt: number;
};
type DiagnosticRunProgressEvent = DiagnosticBaseEvent & {
  type: "run.progress";
  sessionKey?: string;
  sessionId?: string;
  runId?: string;
  reason: string;
};
/**
 * Session-correlated embedded-runner execution milestone. Emitted for every
 * phase transition so external status surfaces can render turn startup
 * without a control-UI subscription. `phase` is the closed
 * EmbeddedAgentExecutionPhase contract (type-only import keeps this module
 * runtime-independent of the agents layer).
 */
type DiagnosticRunExecutionPhaseEvent = DiagnosticBaseEvent & {
  type: "run.execution_phase";
  sessionKey?: string;
  sessionId: string;
  runId: string;
  phase: EmbeddedAgentExecutionPhase;
  provider?: string;
  model?: string;
  backend?: string;
  source?: string;
  tool?: string;
  toolCallId?: string;
  itemId?: string;
  firstModelCallStarted?: boolean;
};
type DiagnosticGatewayEventLoopSampleEvent = DiagnosticBaseEvent & {
  type: "gateway.event_loop.sample";
  intervalMs: number;
  delayMaxMs: number;
};
type DiagnosticGcEvent = DiagnosticBaseEvent & {
  type: "diagnostic.gc";
  durationMs: number;
};
type DiagnosticHeartbeatEvent = DiagnosticBaseEvent & {
  type: "diagnostic.heartbeat";
  webhooks: {
    received: number;
    processed: number;
    errors: number;
  };
  active: number;
  waiting: number;
  queued: number;
};
type DiagnosticLivenessWarningReason = "event_loop_delay" | "event_loop_utilization" | "cpu";
type DiagnosticPhaseDetails = Record<string, string | number | boolean>;
type DiagnosticPhaseSnapshot = {
  name: string;
  startedAt: number;
  endedAt?: number;
  durationMs?: number;
  cpuUserMs?: number;
  cpuSystemMs?: number;
  cpuTotalMs?: number;
  cpuCoreRatio?: number;
  details?: DiagnosticPhaseDetails;
};
type DiagnosticLivenessWarningEvent = DiagnosticBaseEvent & {
  type: "diagnostic.liveness.warning";
  reasons: DiagnosticLivenessWarningReason[];
  intervalMs: number;
  degradedSinceMs?: number;
  eventLoopDelayP99Ms?: number;
  eventLoopDelayMaxMs?: number;
  eventLoopUtilization?: number;
  cpuUserMs?: number;
  cpuSystemMs?: number;
  cpuTotalMs?: number;
  cpuCoreRatio?: number;
  active: number;
  waiting: number;
  queued: number;
  phase?: string;
  recentPhases?: DiagnosticPhaseSnapshot[];
  activeWorkLabels?: string[];
  waitingWorkLabels?: string[];
  queuedWorkLabels?: string[];
};
type DiagnosticPhaseCompletedEvent = DiagnosticBaseEvent & DiagnosticPhaseSnapshot & {
  type: "diagnostic.phase.completed";
};
type DiagnosticToolLoopEvent = DiagnosticBaseEvent & {
  type: "tool.loop";
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  toolName: string;
  level: "warning" | "critical";
  action: "warn" | "block";
  detector: "generic_repeat" | "argument_churn" | "unknown_tool_repeat" | "known_poll_no_progress" | "global_circuit_breaker" | "ping_pong";
  count: number;
  message: string;
  pairedToolName?: string;
};
type DiagnosticToolParamsSummary = {
  kind: "object";
} | {
  kind: "array";
  length: number;
} | {
  kind: "string";
  length: number;
} | {
  kind: "number" | "boolean" | "null" | "undefined" | "other";
};
type DiagnosticToolSource = "channel" | "core" | "mcp" | "plugin";
type DiagnosticToolTerminalReason = "failed" | "cancelled" | "timed_out";
type DiagnosticToolExecutionBaseEvent = DiagnosticBaseEvent & {
  runId?: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  /** Authoritative lifecycle time from the tool runtime, when it exposes one. */
  sourceTimestampMs?: number;
  toolName: string;
  toolSource?: DiagnosticToolSource;
  toolOwner?: string;
  toolCallId?: string;
  paramsSummary?: DiagnosticToolParamsSummary;
  /** Deterministic mutation classification computed before tool execution. */
  mutatingAction?: boolean;
};
type DiagnosticToolExecutionStartedEvent = DiagnosticToolExecutionBaseEvent & {
  type: "tool.execution.started";
};
type DiagnosticToolExecutionCompletedEvent = DiagnosticToolExecutionBaseEvent & {
  type: "tool.execution.completed";
  durationMs: number;
};
type DiagnosticToolExecutionErrorEvent = DiagnosticToolExecutionBaseEvent & {
  type: "tool.execution.error";
  durationMs: number;
  errorCategory: string;
  errorCode?: string;
  terminalReason?: DiagnosticToolTerminalReason;
};
type DiagnosticToolExecutionBlockedEvent = DiagnosticToolExecutionBaseEvent & {
  type: "tool.execution.blocked";
  deniedReason: string;
  reason: string;
};
type DiagnosticSkillTelemetrySource = "bundled" | "unknown" | "workspace";
type DiagnosticSkillActivation = "command" | "read";
type DiagnosticSkillUsedEvent = DiagnosticBaseEvent & {
  type: "skill.used";
  runId?: string;
  sessionKey?: string;
  sessionId?: string;
  agentId?: string;
  skillName: string;
  skillSource: DiagnosticSkillTelemetrySource;
  activation: DiagnosticSkillActivation;
  toolName?: string;
  toolCallId?: string;
};
type DiagnosticExecProcessCompletedEvent = DiagnosticBaseEvent & {
  type: "exec.process.completed";
  sessionKey?: string;
  target: "host" | "sandbox";
  mode: "child" | "pty";
  outcome: "completed" | "failed";
  durationMs: number;
  commandLength: number;
  exitCode?: number;
  exitSignal?: string;
  timedOut?: boolean;
  failureKind?: "shell-command-not-found" | "shell-not-executable" | "overall-timeout" | "no-output-timeout" | "signal" | "aborted" | "runtime-error";
};
type DiagnosticExecApprovalFollowupSuppressedEvent = DiagnosticBaseEvent & {
  type: "exec.approval.followup_suppressed";
  approvalId: string;
  reason: "session_rebound";
  phase: "direct_delivery" | "gateway_preflight";
};
type DiagnosticRunBaseEvent = DiagnosticBaseEvent & DiagnosticRunScopeFields;
type DiagnosticRunStartedEvent = DiagnosticRunBaseEvent & {
  type: "run.started";
};
type DiagnosticRunCompletedEvent = DiagnosticRunBaseEvent & {
  type: "run.completed";
  durationMs: number;
  outcome: "completed" | "aborted" | "blocked" | "error";
  errorCategory?: string;
  blockedBy?: string;
};
type DiagnosticHarnessRunPhase = "prepare" | "start" | "send" | "resolve" | "cleanup";
type DiagnosticHarnessRunOutcome = "completed" | "aborted" | "timed_out" | "error";
type DiagnosticHarnessRunBaseEvent = DiagnosticBaseEvent & DiagnosticRunScopeFields & {
  harnessId: string;
  pluginId?: string;
};
type DiagnosticHarnessRunStartedEvent = DiagnosticHarnessRunBaseEvent & {
  type: "harness.run.started";
};
type DiagnosticAgentCommentaryEvent = DiagnosticBaseEvent & DiagnosticAgentCommentaryFields;
type DiagnosticHarnessRunCompletedEvent = DiagnosticHarnessRunBaseEvent & {
  type: "harness.run.completed";
  durationMs: number;
  outcome: DiagnosticHarnessRunOutcome;
  resultClassification?: "empty" | "reasoning-only" | "planning-only";
  yieldDetected?: boolean;
  itemLifecycle?: {
    startedCount: number;
    completedCount: number;
    activeCount: number;
  };
};
type DiagnosticHarnessRunErrorEvent = DiagnosticHarnessRunBaseEvent & {
  type: "harness.run.error";
  durationMs: number;
  phase: DiagnosticHarnessRunPhase;
  errorCategory: string;
  cleanupFailed?: boolean;
};
type DiagnosticModelCallBaseEvent = DiagnosticBaseEvent & {
  runId: string;
  agentId?: string;
  callId: string;
  sessionKey?: string;
  sessionId?: string;
  provider: string;
  model: string;
  api?: string;
  transport?: string;
  /** Defaults to request for emitters created before turn-level CLI diagnostics. */
  observationUnit?: "request" | "turn";
  contextTokenBudget?: number;
  contextWindowSource?: "model" | "modelsConfig" | "agentContextTokens" | "default";
  contextWindowReferenceTokens?: number;
  upstreamRequestIdHash?: string;
  promptStats?: DiagnosticModelCallPromptStats;
};
type DiagnosticModelCallStartedEvent = DiagnosticModelCallBaseEvent & {
  type: "model.call.started";
};
type DiagnosticModelCallCompletedEvent = DiagnosticModelCallBaseEvent & {
  type: "model.call.completed";
  durationMs: number;
  requestPayloadBytes?: number;
  responseStreamBytes?: number;
  timeToFirstByteMs?: number;
  usage?: DiagnosticModelCallUsage;
};
type DiagnosticModelCallErrorEvent = DiagnosticModelCallBaseEvent & {
  type: "model.call.error";
  durationMs: number;
  errorCategory: string;
  failureKind?: "aborted" | "connection_closed" | "connection_reset" | "terminated" | "timeout";
  memory?: DiagnosticMemoryUsage;
  requestPayloadBytes?: number;
  responseStreamBytes?: number;
  timeToFirstByteMs?: number;
  usage?: DiagnosticModelCallUsage;
};
type DiagnosticModelCallPromptStats = Readonly<{
  inputMessagesCount?: number;
  inputMessagesChars?: number;
  systemPromptChars?: number;
  toolDefinitionsCount?: number;
  toolDefinitionsChars?: number;
  totalChars?: number;
}>;
type DiagnosticModelCallUsage = Readonly<{
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  reasoningTokens?: number;
  promptTokens?: number;
  total?: number;
}>;
type DiagnosticContextAssembledEvent = DiagnosticBaseEvent & {
  type: "context.assembled";
  runId: string;
  sessionKey?: string;
  sessionId?: string;
  provider: string;
  model: string;
  channel?: string;
  trigger?: string;
  messageCount: number;
  historyTextChars: number;
  historyImageBlocks: number;
  maxMessageTextChars: number;
  systemPromptChars: number;
  promptChars: number;
  promptImages: number;
  contextTokenBudget?: number;
  reserveTokens?: number;
};
type DiagnosticMemorySampleEvent = DiagnosticBaseEvent & {
  type: "diagnostic.memory.sample";
  memory: DiagnosticMemoryUsage;
  uptimeMs?: number;
};
type DiagnosticMemoryPressureEvent = DiagnosticBaseEvent & {
  type: "diagnostic.memory.pressure";
  level: "warning" | "critical";
  reason: "rss_threshold" | "heap_threshold" | "rss_growth";
  memory: DiagnosticMemoryUsage;
  thresholdBytes?: number;
  rssGrowthBytes?: number;
  windowMs?: number;
};
type DiagnosticPayloadLargeEvent = DiagnosticBaseEvent & {
  type: "payload.large";
  surface: string;
  action: "rejected" | "truncated" | "chunked";
  bytes?: number;
  limitBytes?: number;
  count?: number;
  channel?: string;
  pluginId?: string;
  reason?: string;
};
type DiagnosticLogRecordEvent = DiagnosticBaseEvent & {
  type: "log.record";
  level: string;
  message: string;
  loggerName?: string;
  loggerParents?: string[];
  attributes?: Record<string, string | number | boolean>;
  code?: {
    line?: number;
    functionName?: string;
  };
};
type DiagnosticTelemetryExporterEvent = DiagnosticBaseEvent & {
  type: "telemetry.exporter";
  exporter: string;
  signal: "traces" | "metrics" | "logs";
  status: "started" | "failure" | "dropped";
  reason?: "configured" | "emit_failed" | "handler_failed" | "queue_full" | "shutdown_failed" | "start_failed" | "unsupported_protocol";
  errorCategory?: string;
};
type DiagnosticAsyncQueueDroppedEvent = DiagnosticBaseEvent & {
  type: "diagnostic.async_queue.dropped";
  droppedEvents: number;
  droppedTrustedEvents?: number;
  droppedUntrustedEvents?: number;
  droppedPriorityEvents?: number;
  queueLength: number;
  maxQueueLength: number;
  drainBatchSize: number;
};
type DiagnosticEventPayload = DiagnosticGatewayRpcEvent | DiagnosticUsageEvent | DiagnosticWebhookReceivedEvent | DiagnosticWebhookProcessedEvent | DiagnosticWebhookErrorEvent | DiagnosticMessageQueuedEvent | DiagnosticMessageReceivedEvent | DiagnosticMessageDispatchStartedEvent | DiagnosticMessageDispatchCompletedEvent | DiagnosticMessageProcessedEvent | DiagnosticMessageDeliveryStartedEvent | DiagnosticMessageDeliveryCompletedEvent | DiagnosticMessageDeliveryErrorEvent | DiagnosticTalkEvent | DiagnosticSessionStateEvent | DiagnosticSessionLongRunningEvent | DiagnosticSessionStalledEvent | DiagnosticSessionStuckEvent | DiagnosticSessionRecoveryRequestedEvent | DiagnosticSessionRecoveryCompletedEvent | DiagnosticSessionTurnCreatedEvent | DiagnosticLaneEnqueueEvent | DiagnosticLaneDequeueEvent | DiagnosticRunAttemptEvent | DiagnosticRunProgressEvent | DiagnosticRunExecutionPhaseEvent | DiagnosticGatewayEventLoopSampleEvent | DiagnosticGcEvent | DiagnosticHeartbeatEvent | DiagnosticLivenessWarningEvent | DiagnosticPhaseCompletedEvent | DiagnosticToolLoopEvent | DiagnosticToolExecutionStartedEvent | DiagnosticToolExecutionCompletedEvent | DiagnosticToolExecutionErrorEvent | DiagnosticToolExecutionBlockedEvent | DiagnosticSkillUsedEvent | DiagnosticExecProcessCompletedEvent | DiagnosticExecApprovalFollowupSuppressedEvent | DiagnosticRunStartedEvent | DiagnosticRunCompletedEvent | DiagnosticHarnessRunStartedEvent | DiagnosticAgentCommentaryEvent | DiagnosticHarnessRunCompletedEvent | DiagnosticHarnessRunErrorEvent | DiagnosticModelCallStartedEvent | DiagnosticModelCallCompletedEvent | DiagnosticModelCallErrorEvent | DiagnosticContextAssembledEvent | DiagnosticMemorySampleEvent | DiagnosticMemoryPressureEvent | (DiagnosticBaseEvent & DiagnosticChildProcessSpawnFields) | DiagnosticPayloadLargeEvent | DiagnosticLogRecordEvent | DiagnosticSecurityEvent | DiagnosticTelemetryExporterEvent | DiagnosticAsyncQueueDroppedEvent | DiagnosticFailoverEvent;
type DiagnosticNonSecurityEventPayload = Exclude<DiagnosticEventPayload, DiagnosticSecurityEvent>;
type DiagnosticEventInput = DiagnosticNonSecurityEventPayload extends (infer Event) ? Event extends DiagnosticEventPayload ? Omit<Event, "seq" | "ts"> : never : never;
type DiagnosticEventMetadata = Readonly<{
  internal?: boolean;
  trustedTraceContext?: boolean;
  trusted: boolean;
}>;
type DiagnosticModelCallContent = Readonly<{
  inputMessages?: unknown;
  outputMessages?: unknown;
  systemPrompt?: string;
  toolDefinitions?: unknown;
}>;
type DiagnosticToolCallContent = Readonly<{
  toolInput?: unknown;
  toolOutput?: unknown;
}>;
type DiagnosticSkillUsagePrivateData = Readonly<{
  skillFile: string;
}>;
type DiagnosticEventPrivateData = Readonly<{
  /** Raw failure text for trusted diagnostics exporters; never part of the public event payload. */
  errorMessage?: string;
  modelContent?: DiagnosticModelCallContent;
  skillUsage?: DiagnosticSkillUsagePrivateData;
  toolContent?: DiagnosticToolCallContent;
}>;
//#endregion
//#region src/infra/diagnostic-trace-propagation.d.ts
type DiagnosticTracePropagationBridge$1<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/logger-types.d.ts
/** Logger passed into plugin registration, services, and CLI surfaces. */
type PluginLogger$1 = {
  debug?: (message: string) => void;
  info: (message: string) => void;
  warn: (message: string) => void;
  error: (message: string) => void;
};
//#endregion
//#region src/plugins/types.node-host.d.ts
type OpenClawPluginNodeHostCommandAvailabilityContext = {
  /** Node-local configuration used to build this host's Gateway declaration. */
  config: OpenClawConfig;
  /** Node-host process environment. */
  env: NodeJS.ProcessEnv;
};
type OpenClawPluginNodeHostCommandIo = {
  emitChunk(chunk: string): Promise<void>;
  onInput(callback: (payloadJSON: string) => void): void;
  /** Complete binary messages; available when the node host dispatches a duplex command. */
  frames?: {
    send(message: Uint8Array): Promise<void>;
    onMessage(listener: (message: Uint8Array) => void | Promise<void>): () => void;
  };
  signal: AbortSignal;
};
type OpenClawPluginNodeWorkspace = {
  workspaceDir: string;
  environmentId: string;
  sessionId: string;
  ownerEpoch: number;
  sessionKey: string;
};
type OpenClawPluginNodeHostCommandContext = {
  /** Emit one node-owned event through the active Gateway connection. */
  sendNodeEvent(event: string, payload: unknown): Promise<unknown>;
  /** Agent session that owns this invocation, when the caller supplied one. */
  sessionKey?: string;
  /** Aborts when the Gateway cancels this specific node-host invocation. */
  signal?: AbortSignal;
  /** Prepare local exec policy; call the returned guard synchronously immediately before spawn. */
  prepareExecAuthorization?: (source: "human-approved" | "session-full") => () => void;
  /** @deprecated Use acquireManagedWorkspaceAsync; retained for synchronous plugin compatibility. */
  acquireManagedWorkspace?: (request: OpenClawPluginNodeWorkspace) => {
    workspaceDir: string;
    /** Stable HOME owned and validated by this exact prepared workspace binding. */
    homeDir?: string;
    release: () => void;
  };
  /** Protect an exact node-owned workspace after durable worker-backed binding validation. */
  acquireManagedWorkspaceAsync?: (request: OpenClawPluginNodeWorkspace) => Promise<{
    workspaceDir: string;
    homeDir?: string;
    release: () => void;
  }>;
};
type OpenClawPluginNodeHostCommandBase = {
  command: string;
  cap?: string;
  dangerous?: boolean;
  /** Settle node-local startup before the initial capability declaration; registration stays synchronous. */
  prepare?: (context: OpenClawPluginNodeHostCommandAvailabilityContext) => Promise<void> | void;
  /** Return false to omit this command and capability from the node declaration. */
  isAvailable?: (context: OpenClawPluginNodeHostCommandAvailabilityContext) => boolean;
  /** Watch availability; node shutdown awaits the returned cleanup callback. */
  watchAvailability?: (context: OpenClawPluginNodeHostCommandAvailabilityContext, onChange: () => void) => (() => void | Promise<void>) | void;
  /** Release command-owned state when the active Gateway connection closes. */
  onDisconnect?: () => Promise<void> | void;
  /** Return false only when retained work and cleanup are idle; an absent hook defers auto-update. */
  hasActiveWork?: () => boolean;
  /** Optional Computer Use declaration published with this command's node manifest. */
  computerUse?: (context: OpenClawPluginNodeHostCommandAvailabilityContext) => unknown;
  agentTool?: {
    name: string;
    description: string;
    parameters?: Record<string, unknown>;
    /** Platforms where this tool is allowlisted by default; omit for explicit config only. */
    defaultPlatforms?: Array<"ios" | "android" | "macos" | "windows" | "linux" | "unknown">;
    mcp?: {
      server: string;
      tool: string;
    };
  };
};
type OpenClawPluginNodeHostCommand = OpenClawPluginNodeHostCommandBase & {
  duplex?: boolean | "optional";
  handle: (paramsJSON?: string | null, io?: OpenClawPluginNodeHostCommandIo, context?: OpenClawPluginNodeHostCommandContext) => Promise<string>;
};
//#endregion
//#region src/plugins/plugin-registration.types.d.ts
type DiagnosticTracePropagationBridge = DiagnosticTracePropagationBridge$1<DiagnosticEventPayload, DiagnosticEventMetadata>;
type PluginInteractiveHandlerResult = {
  handled?: boolean;
} | void;
type PluginInteractiveRegistration<TContext = unknown, TChannel extends string = string, TResult = PluginInteractiveHandlerResult> = {
  channel: TChannel;
  namespace: string;
  handler: (ctx: TContext) => Promise<TResult> | TResult;
};
type PluginInteractiveHandlerRegistration$1 = PluginInteractiveRegistration;
type OpenClawPluginHttpRouteAuth = "gateway" | "plugin";
type OpenClawPluginHttpRouteMatch$1 = "exact" | "prefix";
type OpenClawPluginGatewayRuntimeScopeSurface = "write-default" | "trusted-operator";
type OpenClawPluginHttpRouteHandler$1 = (req: IncomingMessage, res: ServerResponse) => Promise<boolean | void> | boolean | void;
type OpenClawPluginHttpRouteUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => Promise<boolean | void> | boolean | void;
type OpenClawPluginHostedMediaResolver$1 = (mediaUrl: string) => string | null | undefined | Promise<string | null | undefined>;
type WidgetPresenterContext = Readonly<{
  messageChannel?: string;
  accountId?: string;
  deliveryContext?: Readonly<DeliveryContext>;
  nativeChannelId?: string;
  currentChannelId?: string;
  currentMessagingTarget?: string;
  sessionKey?: string;
}>;
type WidgetPresenterDocument = Readonly<{
  kind: "html";
  html: 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;
};
type WidgetPresenterBase = {
  description: string;
  availability: (context: WidgetPresenterContext) => Promise<Result$1<{
    available: true;
  }, WidgetPresentationError>>;
  present: (params: {
    document: WidgetPresenterDocument;
    title: string;
    context: WidgetPresenterContext;
  }) => Promise<Result$1<WidgetPresentationSuccess, WidgetPresentationError>>;
};
type WidgetPresenter = WidgetPresenterBase & ({
  target: "node_panel";
  match?: never;
  capabilities?: never;
} | {
  target: "current_channel";
  match: (context: WidgetPresenterContext) => boolean;
  capabilities: Readonly<{
    sourceKinds: readonly string[];
    maxSourceBytes?: number;
  }>;
});
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$1;
};
type OpenClawPluginCliRegistrar$1 = (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 = {
  name: string;
  description: string;
  hasSubcommands: boolean;
};
/** Root-command metadata that is available before a plugin registrar is activated. */
type OpenClawPluginCliRootCommandDescriptor$1 = OpenClawPluginCliCommandDescriptor & {
  machineOutput?: (params: {
    argv: readonly string[];
    stdoutIsTTY: boolean;
  }) => boolean;
};
type OpenClawPluginReloadRegistration$1 = {
  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 OpenClawPluginNodeInvokePolicyApprovalRuntime = {
  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;
  }>;
};
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?: OpenClawPluginNodeInvokePolicyApprovalRuntime;
  /** 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 = {
  ok: true;
  payload?: unknown;
  payloadJSON?: string | null;
} | {
  ok: false;
  message: string;
  code?: string;
  details?: Record<string, unknown>;
  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$1 = (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$1 = {
  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$1;
  serviceHealth?: OpenClawPluginServiceHealth;
  /** Gateway-owned scheduler access, revoked when this service stops. */
  getCron?: () => (PluginHookGatewayCronService & {
    /** Admit service-owned work through the scheduler's normal run queue. */
    enqueueRun?: (id: string, mode?: CronRunMode) => Promise<CronServiceRunResult>;
  }) | undefined;
  /** 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?: {
    /** Identity of the hosting process, available only while this service is active. */
    getRuntimeIdentity?: () => {
      processInstanceId: string;
      buildId?: string;
    };
    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) => () => void;
  };
};
/** Background service registered by a plugin during `register(api)`. */
type OpenClawPluginService$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>;
};
//#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$1[];
  realtimeTranscriptionProviders?: readonly RealtimeTranscriptionProviderPlugin$1[];
  realtimeVoiceProviders?: readonly RealtimeVoiceProviderPlugin$1[];
};
//#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. */
  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;
  }): 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;
    readonly rubricVersion: string;
    readonly timeoutMs: number;
    readonly signal: AbortSignal;
  }): Promise<DecisionOutcome>;
}
//#endregion
//#region src/decisions/provider-host.d.ts
type Options = Parameters<DecisionRuntimeV1["evaluate"]>[1];
/** Provider-owned admission and health. */
declare class DecisionProviderHost {
  readonly provider: DecisionProviderV1;
  readonly record: PluginRecord;
  private retired;
  private reloadPause?;
  private health?;
  private readonly pending;
  private readonly reasons;
  private successCount;
  private totalLatencyMs;
  private inputTokens;
  private outputTokens;
  constructor(provider: DecisionProviderV1, record: PluginRecord);
  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;
    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): Promise<DecisionOutcome>;
  private evaluateRequest;
  private fail;
}
//#endregion
//#region src/plugins/compat/registry-records.d.ts
declare const PLUGIN_COMPAT_RECORDS: readonly [{
  readonly code: "channel-webhook-listener-config-inputs";
  readonly status: "deprecated";
  readonly owner: "config";
  readonly introduced: "2026-09-26";
  readonly deprecated: "2026-09-26";
  readonly warningStarts: "2026-09-26";
  readonly removalGate: "next-plugin-sdk-major";
  readonly replacement: "Use legacyWebhook for canonical listener config. Doctor migrates stored webhookPort/webhookHost and webhook.port inputs; deprecated optional TypeScript properties preserve config producer source compatibility until an approved SDK major removal.";
  readonly docsPath: "/gateway/doctor/config-migrations#channel-webhook-listeners";
  readonly surfaces: readonly ["TelegramAccountConfig.webhookPort", "TelegramAccountConfig.webhookHost", "FeishuConfig.webhookPort", "FeishuConfig.webhookHost", "FeishuAccountConfig.webhookPort", "FeishuAccountConfig.webhookHost", "MSTeamsWebhookConfig.port", "NextcloudTalkAccountConfig.webhookPort", "NextcloudTalkAccountConfig.webhookHost"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations and plugin-owned Doctor migration"];
  readonly tests: readonly ["extensions/telegram/src/doctor.test.ts", "extensions/feishu/src/doctor-contract.test.ts", "extensions/msteams/config-doctor-api.test.ts", "extensions/nextcloud-talk/src/doctor-contract.test.ts"];
}, {
  readonly code: "conversation-binding-sync-mutations";
  readonly status: "deprecated";
  readonly owner: "channel";
  readonly introduced: "2026-09-20";
  readonly deprecated: "2026-09-20";
  readonly warningStarts: "2026-09-20";
  readonly removalGate: "next-plugin-sdk-major";
  readonly replacement: "Await getSessionBindingService().inspectByConversationAsync, resolveByConversationAsync, touchAsync, resolveRuntimeConversationBindingRouteAsync, and the Async-suffixed thread-binding lifecycle setters. Project prepared inspection facts with inspectRuntimeConversationBindingRoute. Async dispatch retains an explicit synchronous fallback for legacy external adapters; remaining bind/unbind and other storage operations are separate migration work.";
  readonly docsPath: "/plugins/sdk-runtime/channel#awaited-conversation-binding-mutations";
  readonly surfaces: readonly ["SessionBindingService.touch", "SessionBindingService.resolveByConversation", "SessionBindingAdapter.touch", "SessionBindingAdapter.resolveByConversation", "resolveRuntimeConversationBindingRoute", "ChannelConversationBindingSupport.setIdleTimeoutBySessionKey", "ChannelConversationBindingSupport.setMaxAgeBySessionKey", "api.runtime.channel.threadBindings.setIdleTimeoutBySessionKey", "api.runtime.channel.threadBindings.setMaxAgeBySessionKey"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on synchronous methods; resolver migration is recorded here and in docs while its broad barrel remains deprecated; no runtime warnings"];
  readonly tests: readonly ["src/infra/outbound/session-binding-service.test.ts", "src/channels/plugins/binding-routing.test.ts", "src/channels/plugins/conversation-bindings.test.ts"];
  readonly releaseNote: "Plugins can expose explicitly awaited binding mutations and pure ownership inspection; synchronous public methods remain supported while callers and persistence owners migrate.";
}, ...({
  code: "plugin-sdk-agent-config-primitives-subpath" | "plugin-sdk-channel-lifecycle-subpath" | "plugin-sdk-channel-logging-subpath" | "plugin-sdk-channel-message-subpath" | "plugin-sdk-channel-reply-pipeline-subpath" | "plugin-sdk-channel-secret-runtime-subpath" | "plugin-sdk-channel-streaming-subpath" | "plugin-sdk-config-runtime-subpath" | "plugin-sdk-group-access-subpath" | "plugin-sdk-inbound-reply-dispatch-subpath" | "plugin-sdk-infra-runtime-subpath" | "plugin-sdk-matrix-subpath" | "plugin-sdk-text-runtime-subpath" | "plugin-sdk-zod-subpath";
  owner: "channel" | "config" | "sdk";
  introduced: string;
  replacement: "`api.pluginConfig`, `openclaw/plugin-sdk/config-mutation`, `openclaw/plugin-sdk/runtime-config-snapshot`, and `openclaw/plugin-sdk/config-contracts`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-config-schema`" | "`openclaw/plugin-sdk/channel-inbound` and `openclaw/plugin-sdk/channel-outbound`" | "`openclaw/plugin-sdk/channel-ingress-runtime`" | "`openclaw/plugin-sdk/channel-outbound`" | "`openclaw/plugin-sdk/channel-outbound` and `openclaw/plugin-sdk/channel-inbound`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-outbound`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-secret-basic-runtime` and `openclaw/plugin-sdk/channel-secret-tts-runtime`" | "`openclaw/plugin-sdk/logging-core`, `openclaw/plugin-sdk/text-chunking`, `openclaw/plugin-sdk/text-utility-runtime`, and `openclaw/plugin-sdk/string-coerce-runtime`" | "`openclaw/plugin-sdk/run-command`" | "focused subpaths including `openclaw/plugin-sdk/delivery-queue-runtime`, `openclaw/plugin-sdk/diagnostic-runtime`, `openclaw/plugin-sdk/error-runtime`, `openclaw/plugin-sdk/exec-approvals-runtime`, `openclaw/plugin-sdk/fetch-runtime`, and `openclaw/plugin-sdk/ssrf-runtime`; retain until supported external plugin migration is verified and system-event snapshot inspection and consumption have a modern public replacement" | "the direct `zod` package import";
  docsPath: string;
  surfaces: string[];
  tests: string[];
  status: "removed";
  diagnostics: string[];
  releaseNote: "The deprecated `agent-config-primitives` Plugin SDK subpath was removed; plugins now use maintained config-schema primitives." | "The deprecated `channel-logging` Plugin SDK subpath was removed; channel logging helpers now come from the inbound and outbound channel surfaces." | "The deprecated `channel-secret-runtime` Plugin SDK subpath was removed; plugins now use the focused basic and TTS secret-runtime subpaths." | "The deprecated `channel-streaming` Plugin SDK subpath was removed; plugins now import channel streaming helpers from `channel-outbound`." | "The deprecated `group-access` Plugin SDK subpath was removed; plugins now resolve message admission through `channel-ingress-runtime`." | "The deprecated `matrix` Plugin SDK facade was removed; command execution now uses the generic `run-command` subpath." | "The deprecated `text-runtime` Plugin SDK facade was removed; plugins now import logging, chunking, text utility, and string coercion helpers from their focused subpaths." | "The deprecated `zod` Plugin SDK re-export was removed; plugins now import `zod` directly.";
} | {
  code: "plugin-sdk-agent-config-primitives-subpath" | "plugin-sdk-channel-lifecycle-subpath" | "plugin-sdk-channel-logging-subpath" | "plugin-sdk-channel-message-subpath" | "plugin-sdk-channel-reply-pipeline-subpath" | "plugin-sdk-channel-secret-runtime-subpath" | "plugin-sdk-channel-streaming-subpath" | "plugin-sdk-config-runtime-subpath" | "plugin-sdk-group-access-subpath" | "plugin-sdk-inbound-reply-dispatch-subpath" | "plugin-sdk-infra-runtime-subpath" | "plugin-sdk-matrix-subpath" | "plugin-sdk-text-runtime-subpath" | "plugin-sdk-zod-subpath";
  owner: "channel" | "config" | "sdk";
  introduced: string;
  replacement: "`api.pluginConfig`, `openclaw/plugin-sdk/config-mutation`, `openclaw/plugin-sdk/runtime-config-snapshot`, and `openclaw/plugin-sdk/config-contracts`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-config-schema`" | "`openclaw/plugin-sdk/channel-inbound` and `openclaw/plugin-sdk/channel-outbound`" | "`openclaw/plugin-sdk/channel-ingress-runtime`" | "`openclaw/plugin-sdk/channel-outbound`" | "`openclaw/plugin-sdk/channel-outbound` and `openclaw/plugin-sdk/channel-inbound`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-outbound`; retain until supported external plugin migration is verified" | "`openclaw/plugin-sdk/channel-secret-basic-runtime` and `openclaw/plugin-sdk/channel-secret-tts-runtime`" | "`openclaw/plugin-sdk/logging-core`, `openclaw/plugin-sdk/text-chunking`, `openclaw/plugin-sdk/text-utility-runtime`, and `openclaw/plugin-sdk/string-coerce-runtime`" | "`openclaw/plugin-sdk/run-command`" | "focused subpaths including `openclaw/plugin-sdk/delivery-queue-runtime`, `openclaw/plugin-sdk/diagnostic-runtime`, `openclaw/plugin-sdk/error-runtime`, `openclaw/plugin-sdk/exec-approvals-runtime`, `openclaw/plugin-sdk/fetch-runtime`, and `openclaw/plugin-sdk/ssrf-runtime`; retain until supported external plugin migration is verified and system-event snapshot inspection and consumption have a modern public replacement" | "the direct `zod` package import";
  docsPath: string;
  surfaces: string[];
  tests: string[];
  status: "deprecated" | "removal-pending";
  deprecated: string;
  warningStarts: string;
  removeAfter: "2026-10-01" | undefined;
  removalGate: "next-plugin-sdk-major" | undefined;
  diagnostics: string[];
} | {
  status: "removal-pending";
  removeAfter: "2026-09-30";
  replacement: "`api.registerMediaUnderstandingProvider(...)` with provider-owned request helpers and types from `openclaw/plugin-sdk/plugin-entry`; retain the public subpath through the 2026-09-30 window while official plugin consumers migrate";
  docsPath: "/plugins/architecture";
  code: "plugin-sdk-media-understanding-public-demotion" | "plugin-sdk-memory-host-core-public-demotion" | "plugin-sdk-plugin-config-runtime-public-demotion" | "plugin-sdk-tool-plugin-public-demotion";
  owner: "sdk";
  introduced: string;
  deprecated: string;
  warningStarts: string;
  surfaces: string[];
  diagnostics: string[];
  tests: string[];
} | {
  status: "removal-pending";
  removeAfter: "2026-09-30";
  replacement: "host-prepared memory prompts via `openclaw/plugin-sdk/core` and memory capability registration through the injected plugin API; retain the facade through the 2026-09-30 window and until a focused public-artifact read seam exists";
  docsPath: "/plugins/architecture-internals#context-engine-plugins";
  code: "plugin-sdk-media-understanding-public-demotion" | "plugin-sdk-memory-host-core-public-demotion" | "plugin-sdk-plugin-config-runtime-public-demotion" | "plugin-sdk-tool-plugin-public-demotion";
  owner: "sdk";
  introduced: string;
  deprecated: string;
  warningStarts: string;
  surfaces: string[];
  diagnostics: string[];
  tests: string[];
} | {
  status: "removal-pending";
  removeAfter: "2026-12-01";
  replacement: "`api.pluginConfig`, runtime tool context config, and focused `config-contracts`, `runtime-config-snapshot`, or `config-mutation` subpaths; retain the public subpath through the 2026-12-01 window while official plugin consumers migrate";
  docsPath: "/plugins/sdk-runtime";
  code: "plugin-sdk-media-understanding-public-demotion" | "plugin-sdk-memory-host-core-public-demotion" | "plugin-sdk-plugin-config-runtime-public-demotion" | "plugin-sdk-tool-plugin-public-demotion";
  owner: "sdk";
  introduced: string;
  deprecated: string;
  warningStarts: string;
  surfaces: string[];
  diagnostics: string[];
  tests: string[];
} | {
  status: "deprecated";
  replacement: "retain the public subpath until plugin authoring has a nonexecuting static metadata replacement for `defineToolPlugin`; `getToolPluginMetadata` currently reads metadata only from an already-executed entry";
  docsPath: "/plugins/tool-plugins";
  code: "plugin-sdk-media-understanding-public-demotion" | "plugin-sdk-memory-host-core-public-demotion" | "plugin-sdk-plugin-config-runtime-public-demotion" | "plugin-sdk-tool-plugin-public-demotion";
  owner: "sdk";
  introduced: string;
  deprecated: string;
  warningStarts: string;
  surfaces: string[];
  diagnostics: string[];
  tests: string[];
})[], {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-sdk-channel-setup-input-fields";
  readonly owner: "channel";
  readonly replacement: "plugin-local setup input intersections that declare each owning channel field; retain each field until a new published-plugin artifact sweep finds no reader";
  readonly docsPath: "/plugins/sdk-migration#published-channel-setup-compatibility";
  readonly surfaces: readonly ["ChannelSetupInput.privateKey", "ChannelSetupInput.secret", "ChannelSetupInput.botToken", "ChannelSetupInput.appToken", "ChannelSetupInput.signingSecret", "ChannelSetupInput.mode", "ChannelSetupInput.cliPath", "ChannelSetupInput.authDir", "ChannelSetupInput.httpUrl", "ChannelSetupInput.httpPort", "ChannelSetupInput.webhookPath", "ChannelSetupInput.webhookUrl", "ChannelSetupInput.userId", "ChannelSetupInput.accessToken", "ChannelSetupInput.password", "ChannelSetupInput.deviceName", "ChannelSetupInput.url", "ChannelSetupInput.baseUrl", "ChannelSetupInput.code", "ChannelSetupInput.groupChannels", "ChannelSetupInput.dmAllowlist", "ChannelSetupInput.autoDiscoverChannels"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on the reader-backed ChannelSetupInput compatibility tier", "published-plugin artifact reader sweep required before field removal"];
  readonly tests: readonly ["src/plugin-sdk/channel-setup.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "ChannelSetupInput keeps its reader-backed channel fields through the dated migration window while plugins move them into plugin-local input types.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-sdk-broad-runtime-barrels";
  readonly owner: "sdk";
  readonly replacement: "focused plugin SDK subpaths for each runtime capability; retain until bundled and published plugins no longer import any of the seven broad barrels";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["openclaw/plugin-sdk/agent-runtime", "openclaw/plugin-sdk/agent-runtime loadModelCatalog params.useCache", "openclaw/plugin-sdk/agent-runtime loadModelCatalog params.cacheOnly", "openclaw/plugin-sdk/agent-runtime loadModelCatalog params.metadataSnapshot", "openclaw/plugin-sdk/agent-runtime loadModelCatalog", "openclaw/plugin-sdk/cli-runtime", "openclaw/plugin-sdk/conversation-runtime", "openclaw/plugin-sdk/hook-runtime", "openclaw/plugin-sdk/media-runtime", "openclaw/plugin-sdk/media-runtime buildAgentMediaPayload", "openclaw/plugin-sdk/plugin-runtime", "openclaw/plugin-sdk/security-runtime"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on broad plugin SDK barrels", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/plugins/contracts/plugin-sdk-subpaths.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Broad agent, CLI, conversation, hook, media, plugin, and security runtime barrels remain available while bundled and external plugins migrate to focused subpaths.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-sdk-provider-owned-helper-shims";
  readonly owner: "provider";
  readonly replacement: "provider-local auth, model, replay, OAuth, and stream helper APIs; retain until every helper is migrated in official providers and absent from published plugins";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["openclaw/plugin-sdk/provider-stream GOOGLE_THINKING_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream KILOCODE_THINKING_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream MOONSHOT_THINKING_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream MINIMAX_FAST_MODE_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream OPENAI_RESPONSES_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream OPENROUTER_THINKING_STREAM_HOOKS", "openclaw/plugin-sdk/provider-stream TOOL_STREAM_DEFAULT_ON_HOOKS", "openclaw/plugin-sdk/provider-stream-shared defaultToolStreamExtraParams", "openclaw/plugin-sdk/provider-stream-shared stripTrailingAnthropicAssistantPrefillWhenThinking", "openclaw/plugin-sdk/provider-stream-shared createAnthropicThinkingPrefillPayloadWrapper", "openclaw/plugin-sdk/provider-stream-shared OpenAICompatibleThinkingLevel", "openclaw/plugin-sdk/provider-stream-shared isOpenAICompatibleThinkingEnabled", "openclaw/plugin-sdk/provider-stream-shared DeepSeekV4ThinkingLevel", "openclaw/plugin-sdk/provider-stream-shared DeepSeekV4ReasoningEffort", "openclaw/plugin-sdk/provider-stream-shared createDeepSeekV4OpenAICompatibleThinkingWrapper", "openclaw/plugin-sdk/provider-stream-shared createThinkingOnlyFinalTextWrapper", "openclaw/plugin-sdk/provider-stream-shared createGoogleThinkingPayloadWrapper", "openclaw/plugin-sdk/provider-stream-shared createGoogleThinkingStreamWrapper", "openclaw/plugin-sdk/provider-model-shared isProxyReasoningUnsupportedModelHint", "openclaw/plugin-sdk/provider-model-shared OPENAI_COMPATIBLE_REPLAY_HOOKS", "openclaw/plugin-sdk/provider-model-shared ANTHROPIC_BY_MODEL_REPLAY_HOOKS", "openclaw/plugin-sdk/provider-model-shared NATIVE_ANTHROPIC_REPLAY_HOOKS", "openclaw/plugin-sdk/provider-model-shared PASSTHROUGH_GEMINI_REPLAY_HOOKS", "openclaw/plugin-sdk/provider-auth DEFAULT_COPILOT_API_BASE_URL", "openclaw/plugin-sdk/provider-auth deriveCopilotApiBaseUrlFromToken", "openclaw/plugin-sdk/provider-auth resolveCopilotApiToken", "openclaw/plugin-sdk/provider-auth-copilot-cache CachedCopilotToken", "openclaw/plugin-sdk/oauth-utils toFormUrlEncoded", "openclaw/plugin-sdk/oauth-utils generatePkceVerifierChallenge", "openclaw/plugin-sdk/provider-oauth-runtime OAuthProvider", "openclaw/plugin-sdk/provider-oauth-runtime OAuthProviderInfo"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations naming provider-local replacements", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/plugins/contracts/plugin-sdk-subpaths.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Provider-specific auth, model, replay, OAuth, and stream shortcuts remain as deprecated SDK shims while providers move to their local APIs.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "message-presentation-legacy-bridges";
  readonly owner: "channel";
  readonly replacement: "MessagePresentation values and channel presentation renderers; retain until reply producers and official channel packages no longer emit or read legacy interactive replies";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["InteractiveReplyButton.value", "InteractiveReplyButton.url", "InteractiveReplyButton.webApp", "InteractiveReplyButton.web_app", "InteractiveReplyOption.value", "InteractiveReplyButton", "InteractiveReplyOption", "InteractiveReplyBlock", "InteractiveReply", "normalizeInteractiveReply", "hasInteractiveReplyBlocks", "presentationToInteractiveReply", "presentationToInteractiveControlsReply", "interactiveReplyToPresentation", "resolveInteractiveTextFallback", "src/auto-reply ReplyPayload.interactive", "openclaw/plugin-sdk/reply-payload ReplyPayload.interactive", "reduceInteractiveReply", "@openclaw/discord buildDiscordInteractiveComponents", "@openclaw/slack buildSlackInteractiveBlocks", "@openclaw/telegram buildTelegramInteractiveButtons"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations naming MessagePresentation replacements", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/interactive/payload.test.ts", "src/plugin-sdk/reply-payload.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Legacy interactive reply values and channel-specific rendering bridges remain available while producers migrate to MessagePresentation.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-sdk-focused-compat-aliases";
  readonly owner: "sdk";
  readonly replacement: "the focused replacement named by each TypeScript @deprecated annotation; retain until every enumerated alias has zero bundled and published readers";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["openclaw/plugin-sdk/acp-runtime __testing", "openclaw/plugin-sdk/approval-reaction-runtime", "openclaw/plugin-sdk/channel-inbound BuildChannelTurnContextParams", "openclaw/plugin-sdk/channel-inbound BuiltChannelTurnContext", "openclaw/plugin-sdk/channel-inbound buildChannelTurnContext", "openclaw/plugin-sdk/channel-inbound finalizeChannelInboundContext", "openclaw/plugin-sdk/channel-inbound filterChannelTurnSupplementalContext", "openclaw/plugin-sdk/channel-send-result ChannelSendRawResult", "openclaw/plugin-sdk/command-auth", "openclaw/plugin-sdk/command-auth ResolveSenderCommandAuthorizationParams", "openclaw/plugin-sdk/command-auth resolveCommandAuthorizedFromAuthorizers", "openclaw/plugin-sdk/command-auth CommandAuthorizationRuntime", "openclaw/plugin-sdk/command-auth ResolveSenderCommandAuthorizationWithRuntimeParams", "openclaw/plugin-sdk/command-auth resolveDirectDmAuthorizationOutcome", "openclaw/plugin-sdk/command-auth resolveSenderCommandAuthorizationWithRuntime", "openclaw/plugin-sdk/command-auth resolveSenderCommandAuthorization", "openclaw/plugin-sdk/keyed-async-queue KeyedAsyncQueue.getTailMapForTesting", "openclaw/plugin-sdk/persistent-dedupe PersistentDedupeLegacyPathOptions.lockOptions", "openclaw/plugin-sdk/retry-runtime createTelegramRetryRunner", "openclaw/plugin-sdk/ssrf-policy SsrfPolicyOptions.allowPrivateNetwork", "openclaw/plugin-sdk/ssrf-policy ssrfPolicyFromAllowPrivateNetwork", "openclaw/plugin-sdk/tts-runtime TtsSynthesisStreamResult", "openclaw/plugin-sdk/tts-runtime TtsRuntimeFacade._test"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations naming focused replacements", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/plugin-sdk/channel-inbound.test.ts", "src/plugin-sdk/command-auth.test.ts", "src/plugin-sdk/ssrf-policy.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Focused SDK compatibility aliases remain available through a dated window while callers adopt their annotated replacements.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "agent-harness-terminal-result-aliases";
  readonly owner: "agent-runtime";
  readonly replacement: "AgentHarnessAttemptResult.terminal and AgentHarnessDeliveryDefaults.visibleReplies; retain until harness migration verifies that legacy terminal fields and sourceVisibleReplies are unread";
  readonly docsPath: "/plugins/sdk-agent-harness";
  readonly surfaces: readonly ["AgentHarnessAttemptResult.aborted", "AgentHarnessAttemptResult.externalAbort", "AgentHarnessAttemptResult.timedOut", "AgentHarnessAttemptResult.idleTimedOut", "AgentHarnessAttemptResult.timedOutDuringCompaction", "AgentHarnessAttemptResult.timedOutDuringToolExecution", "AgentHarnessAttemptResult.timedOutByRunBudget", "AgentHarnessAttemptResult.promptError", "AgentHarnessAttemptResult.promptErrorSource", "AgentHarnessDeliveryDefaults.sourceVisibleReplies"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on agent harness result and delivery defaults", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/agents/harness/settled-turn-finalization-result.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Agent harness result booleans and sourceVisibleReplies remain available while harnesses migrate to terminal outcomes and visibleReplies.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "official-plugin-export-aliases";
  readonly owner: "channel";
  readonly replacement: "the canonical testing export, MessagePresentation renderers, and host-owned timeout/runtime behavior; retain until minimum supported official plugin packages no longer import these aliases";
  readonly docsPath: "/plugins/compatibility#current-compatibility-areas";
  readonly surfaces: readonly ["@openclaw/google-meet __testing", "@openclaw/discord buildDiscordInteractiveComponents", "@openclaw/discord normalizeDiscordListenerTimeoutMs", "@openclaw/discord normalizeDiscordInboundWorkerTimeoutMs", "@openclaw/discord isAbortError", "@openclaw/discord runDiscordTaskWithTimeout", "@openclaw/slack buildSlackInteractiveBlocks"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on published official-plugin exports", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["extensions/google-meet/index.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Published Google Meet testing, channel presentation, and Discord timeout aliases remain available while consumers move to their canonical exports and host-owned behavior.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "memory-host-compatibility-aliases";
  readonly owner: "sdk";
  readonly replacement: "canonical memory cache/FTS tables and getRuntimeConfig or caller-provided config; retain until memory integrations are verified to use canonical tables and prepared runtime config without these aliases";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["@openclaw/memory-host-sdk ensureMemoryIndexSchema.embeddingCacheTable", "@openclaw/memory-host-sdk ensureMemoryIndexSchema.ftsTable", "@openclaw/memory-host-sdk/runtime-core loadConfig", "@openclaw/memory-host-sdk/host/openclaw-runtime loadConfig"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on memory-host SDK compatibility fields", "plugin boundary report memory-host SDK summary"];
  readonly tests: readonly ["packages/memory-host-sdk/src/host/memory-schema.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Memory-host cache-table overrides and runtime config reload aliases remain available while callers migrate to canonical tables and prepared config.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-runtime-api-compat-aliases";
  readonly owner: "plugin-execution";
  readonly replacement: "the namespaced plugin API and focused runtime methods named per surface; retain until all enumerated flat API and runtime aliases have no readers";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["OpenClawPluginApi.registerSessionExtension", "OpenClawPluginApi.enqueueNextTurnInjection", "OpenClawPluginApi.registerControlUiDescriptor", "OpenClawPluginApi.registerRuntimeLifecycle", "OpenClawPluginApi.registerAgentEventSubscription", "OpenClawPluginApi.emitAgentEvent", "OpenClawPluginApi.setRunContext", "OpenClawPluginApi.getRunContext", "OpenClawPluginApi.clearRunContext", "OpenClawPluginApi.registerSessionSchedulerJob", "OpenClawPluginApi.registerSessionAction", "OpenClawPluginApi.sendSessionAttachment", "OpenClawPluginApi.scheduleSessionTurn", "OpenClawPluginApi.unscheduleSessionTurnsByTag", "PluginHookContext.senderExternalId", "PluginAttachmentChannelHints.telegram", "PluginAttachmentChannelHints.slack", "AgentPromptSurfaceKind pi_main", "PluginRuntime.channel.reply.createReplyDispatcherWithTyping", "PluginRuntime.channel.reply.resolveHumanDelayConfig", "PluginRuntime.channel.reply.dispatchReplyFromConfig", "PluginRuntime.channel.reply.finalizeInboundContext", "PluginRuntime.channel.media.fetchRemoteMedia", "PluginRuntime.channel.session.resolveStorePath", "PluginRuntime.channel.session.recordInboundSession", "PluginRuntime.channel.inbound.runPreparedReply", "PluginRuntime.channel.turn", "PluginRuntime.system.requestHeartbeatNow"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on plugin API and runtime aliases", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/plugins/captured-registration.test.ts", "src/plugins/runtime/index.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Flat plugin registration and broad runtime aliases remain available while plugins migrate to namespaced APIs and focused runtime methods.";
}, {
  readonly status: "removal-pending";
  readonly introduced: "2026-07-25";
  readonly deprecated: "2026-07-25";
  readonly warningStarts: "2026-07-25";
  readonly removeAfter: "2026-10-01";
  readonly code: "plugin-provider-manifest-compat-aliases";
  readonly owner: "provider";
  readonly replacement: "manifest-owned plugin kind/setup metadata and model catalog registration; retain until providers no longer publish runtime kind or legacy catalog hooks";
  readonly docsPath: "/plugins/sdk-migration#compatibility-policy";
  readonly surfaces: readonly ["DefinePluginEntryOptions.kind", "SingleProviderPluginOptions.kind", "OpenClawPluginDefinition.kind", "PluginPackageChannel.cliAddOptions", "ProviderPlugin.catalog", "ProviderPlugin.staticCatalog", "ProviderPlugin.suppressBuiltInModel", "ProviderPlugin.augmentModelCatalog", "ProviderBuiltInModelSuppressionContext"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations on plugin manifest and provider catalog aliases", "plugin boundary report compatibility inventory"];
  readonly tests: readonly ["src/plugins/contracts/package-manifest.contract.test.ts", "src/plugins/contracts/provider-catalog-deprecation.contract.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Runtime plugin kind/setup metadata and provider catalog hooks remain available while plugins migrate ownership into manifests and catalog registrations.";
}, {
  readonly code: "media-legacy-projection";
  readonly status: "removal-pending";
  readonly owner: "sdk";
  readonly introduced: "2026-07-24";
  readonly deprecated: "2026-07-24";
  readonly warningStarts: "2026-07-24";
  readonly removeAfter: "2026-10-01";
  readonly replacement: "ordered `MsgContext.media` / `InboundMediaFacts[]`; typed hook `media` and `originalMedia`; `Attachment*` template variables; and `openclaw/plugin-sdk/media-local-roots`; retain until a clean published-plugin artifact sweep verifies that the legacy media surfaces have no readers";
  readonly docsPath: "/plugins/sdk-migration#media-legacy-projection";
  readonly surfaces: readonly ["MsgContext MediaPath/MediaUrl/MediaType and plural/staging fields", "openclaw/plugin-sdk/agent-media-payload", "ChannelInboundMediaPayload and buildChannelInboundMediaPayload", "MediaPayload and buildMediaPayload", "message hook mediaPath/mediaUrl/mediaType and plural/original metadata aliases", "MediaPath/MediaUrl/MediaType/MediaDir template variables"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations naming the facts-first replacement", "plugin boundary report compatibility inventory with the approved removeAfter date", "SDK, hook, and media template migration documentation"];
  readonly tests: readonly ["src/sessions/user-turn-transcript.media.test.ts", "src/hooks/message-hook-mappers.test.ts", "src/media-understanding/runner.cli-audio.test.ts", "src/plugins/compat/registry.test.ts", "src/plugins/contracts/plugin-sdk-subpaths.test.ts"];
  readonly releaseNote: "Legacy parallel media projections remain available as deprecated compatibility while plugins move to ordered facts, typed hook media, Attachment templates, and the focused media-local-roots SDK.";
}, {
  readonly code: "node-workspace-sync-acquisition";
  readonly status: "deprecated";
  readonly owner: "sdk";
  readonly introduced: "2026-08-21";
  readonly deprecated: "2026-09-15";
  readonly warningStarts: "2026-09-15";
  readonly removalGate: "next-plugin-sdk-major";
  readonly replacement: "Await context.acquireManagedWorkspaceAsync(request) and release the returned lease in finally. Retain synchronous acquisition for supported external plugins until explicit breaking-release approval.";
  readonly docsPath: "/plugins/sdk-migration/how-to-migrate#managed-node-workspace-acquisition";
  readonly surfaces: readonly ["OpenClawPluginNodeHostCommandContext.acquireManagedWorkspace"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotation and migration documentation; no runtime warnings"];
  readonly tests: readonly ["src/node-host/invoke-workspace.test.ts", "src/node-host/node-worker-workspace-retention.test.ts", "extensions/codex/src/node-exec-server.test.ts"];
  readonly releaseNote: "Node-host plugins can await managed workspace acquisition while existing synchronous callers retain their immediate lease contract.";
}, {
  readonly code: "plugin-state-sync-keyed-store";
  readonly status: "deprecated";
  readonly owner: "sdk";
  readonly introduced: "2026-05-29";
  readonly deprecated: "2026-09-11";
  readonly warningStarts: "2026-09-11";
  readonly removalGate: "next-plugin-sdk-major";
  readonly replacement: "`api.runtime.state.openKeyedStore` and `PluginStateKeyedStore`; await operations while keeping transactional callbacks synchronous. Retain the sync adapter until a supported external-plugin migration and explicit breaking-release approval.";
  readonly docsPath: "/plugins/sdk-runtime/state-and-system#synchronous-keyed-store-migration";
  readonly surfaces: readonly ["api.runtime.state.openSyncKeyedStore", "PluginStateSyncKeyedStore", "createPluginStateSyncKeyedStore", "PluginStateKeyedStore.update", "PluginStateKeyedStore.deleteIf"];
  readonly diagnostics: readonly ["TypeScript @deprecated annotations and state-store migration documentation", "plugin compatibility inventory; no new runtime warnings"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts", "src/plugin-state/plugin-state-store.test.ts", "src/plugin-state/plugin-state-store.runtime.test.ts", "test/type-contracts/plugin-state-store-runtime.ts", "src/plugins/loader.runtime-registry.test.ts"];
  readonly releaseNote: "Synchronous plugin keyed stores remain supported through the next Plugin SDK major while plugins migrate to awaited keyed-store operations; trust eligibility and transactional callbacks are unchanged.";
}, {
  readonly code: "memory-read-result-statusless-success";
  readonly status: "deprecated";
  readonly owner: "sdk";
  readonly introduced: "2026-04-28";
  readonly deprecated: "2026-08-19";
  readonly warningStarts: "2026-08-19";
  readonly removalGate: "next-plugin-sdk-major";
  readonly replacement: '`MemoryReadResult` with explicit `status: "ok" | "not_found"`';
  readonly docsPath: "/plugins/sdk-migration#memory-read-missing-results";
  readonly surfaces: readonly ["statusless external memory manager read results"];
  readonly diagnostics: readonly ["host memory-manager acquisition adapter"];
  readonly tests: readonly ["src/plugins/memory-runtime.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "External memory managers must return explicit not-found status for absence; statusless results retain legacy successful-read semantics through the next Plugin SDK major.";
}, {
  readonly code: "context-engine-legacy-host-param-default";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-07-29";
  readonly replacement: "`ContextEngineInfo.acceptedHostParams` for restricted projection; omitted declarations receive full host params";
  readonly docsPath: "/concepts/context-engine#the-contextengine-interface";
  readonly surfaces: readonly ["ContextEngineInfo.acceptedHostParams and undeclared-engine default projection"];
  readonly diagnostics: readonly ["plugin compatibility registry and context engine guide"];
  readonly tests: readonly ["src/context-engine/host-param-projection.test.ts"];
  readonly releaseNote: "The undeclared context-engine host-parameter compatibility default was removed; engines without `acceptedHostParams` now receive all current host fields.";
}, {
  readonly code: "removed-global-api-provider-publication";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-05-27";
  readonly replacement: "provider plugins via `api.registerProvider(...)`; host/runtime code registers against its lifecycle-owned `ApiRegistry`";
  readonly docsPath: "/plugins/sdk-migration#process-global-api-provider-publication";
  readonly surfaces: readonly ["openclaw/plugin-sdk/llm registerApiProvider", "openclaw/plugin-sdk/llm unregisterApiProviders"];
  readonly diagnostics: readonly ["plugin SDK compatibility registry and migration guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "The process-global API-provider publication facade was removed; provider plugins now publish through their lifecycle-owned registration, and host runtimes register directly on their prepared ApiRegistry.";
}, {
  readonly code: "legacy-deactivate-hook-alias";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-05-16";
  readonly replacement: "`gateway_stop` hook";
  readonly docsPath: "/plugins/sdk-migration#deactivate-hook-alias";
  readonly surfaces: readonly ["api.on(\"deactivate\", ...)", "plugin typed hook registration"];
  readonly diagnostics: readonly ["plugin compatibility registry and migration guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: 'The deprecated `api.on("deactivate", ...)` hook alias was removed; plugins must register cleanup with `gateway_stop`.';
}, {
  readonly code: "legacy-subagent-spawning-hook";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-05-30";
  readonly replacement: "`subagent_spawned` for post-launch observation; core session-binding adapters for thread routing";
  readonly docsPath: "/plugins/hooks#upcoming-deprecations";
  readonly surfaces: readonly ["api.on(\"subagent_spawning\", ...)", "PluginHookSubagentSpawningEvent", "PluginHookSubagentSpawningResult", "SubagentLifecycleHookRunner.runSubagentSpawning"];
  readonly diagnostics: readonly ["plugin compatibility registry and migration guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: '`api.on("subagent_spawning", ...)` was removed; core now owns thread-bound subagent routing, and `subagent_spawned` remains available for observation.';
}, {
  readonly code: "hook-only-plugin-shape";
  readonly status: "active";
  readonly owner: "sdk";
  readonly introduced: "2026-04-24";
  readonly replacement: "explicit capability registration";
  readonly docsPath: "/plugins/sdk-migration";
  readonly surfaces: readonly ["plugin shape inspection", "plugins inspect", "status diagnostics"];
  readonly diagnostics: readonly ["plugin compatibility notice"];
  readonly tests: readonly ["src/plugins/status.test.ts", "src/plugins/contracts/shape.contract.test.ts"];
}, {
  readonly code: "deprecated-memory-embedding-provider-api";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-05-21";
  readonly replacement: "`api.registerEmbeddingProvider(...)` and `contracts.embeddingProviders`";
  readonly docsPath: "/plugins/sdk-migration#memory-embedding-provider-api";
  readonly surfaces: readonly ["api.registerMemoryEmbeddingProvider(...)", "contracts.memoryEmbeddingProviders", "openclaw/plugin-sdk/memory-core-host-engine-embeddings registerMemoryEmbeddingProvider", "plugin compatibility registry and migration guide"];
  readonly diagnostics: readonly ["plugin compatibility registry and migration guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Memory-specific embedding provider registration was removed; plugins now use the generic embedding provider contract.";
}, {
  readonly code: "deprecated-session-store-beta5-api";
  readonly status: "removal-pending";
  readonly owner: "sdk";
  readonly introduced: "2026-05-21";
  readonly deprecated: "2026-07-12";
  readonly warningStarts: "2026-07-12";
  readonly removeAfter: "2026-10-12";
  readonly replacement: "`getSessionEntry(...)`, `listSessionEntries(...)`, and row-level session mutations; retain on the 2026.9.33 extended-stable line, which does not remove shipped SDK exports";
  readonly docsPath: "/plugins/sdk-migration#removed-session-and-transcript-file-apis";
  readonly surfaces: readonly ["openclaw/plugin-sdk/session-store-runtime loadSessionStore", "openclaw/plugin-sdk/session-store-runtime updateSessionStore", "openclaw/plugin-sdk/session-store-runtime resolveSessionFilePath", "openclaw/plugin-sdk/session-store-runtime resolveSessionStoreEntry", "openclaw package root loadSessionStore", "openclaw package root saveSessionStore"];
  readonly diagnostics: readonly ["plugin SDK deprecation"];
  readonly tests: readonly ["src/plugin-sdk/session-store-runtime.test.ts", "src/index.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "The beta.5 session-store import set and package-root whole-store aliases remain available while official plugins and package consumers migrate to row-level session access.";
}, {
  readonly code: "plugin-sdk-session-agent-resolution-aliases";
  readonly status: "deprecated";
  readonly owner: "sdk";
  readonly introduced: "2026-08-29";
  readonly deprecated: "2026-08-29";
  readonly warningStarts: "2026-08-29";
  readonly removeAfter: "2026-11-29";
  readonly replacement: "`resolveSessionAgentIdsStrict` and `resolveSessionAgentIdStrict` with an explicit agent, agent-scoped session key, prepared fallback, or persisted owner";
  readonly docsPath: "/plugins/compatibility#session-agent-resolution-aliases";
  readonly surfaces: readonly ["openclaw/plugin-sdk/agent-scope-runtime resolveSessionAgentIds and resolveSessionAgentId", "openclaw/plugin-sdk/agent-runtime session-agent resolver aliases", "openclaw/plugin-sdk/agent-harness-runtime session-agent resolver aliases", "openclaw/plugin-sdk/memory-core-host-runtime-core session-agent resolver alias", "openclaw/plugin-sdk/memory-host-core session-agent resolver alias"];
  readonly diagnostics: readonly ["TypeScript deprecated SDK alias annotations", "plugin compatibility registry"];
  readonly tests: readonly ["src/plugin-sdk/agent-scope-runtime.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Legacy Plugin SDK session-agent resolver names preserve ambient system-agent fallback while published plugins migrate to strict owner-required aliases.";
}, {
  readonly code: "agent-harness-credential-prompt-string-argument";
  readonly status: "deprecated";
  readonly owner: "sdk";
  readonly introduced: "2026-08-08";
  readonly deprecated: "2026-09-09";
  readonly warningStarts: "2026-09-09";
  readonly removeAfter: "2026-11-30";
  readonly replacement: "options object `{ controlToolsAvailable }`";
  readonly docsPath: "/plugins/sdk-migration/removed-surfaces#credential-prompt-builder";
  readonly surfaces: readonly ["openclaw/plugin-sdk/agent-harness-runtime buildCredentialSafetyPrompt string argument"];
  readonly diagnostics: readonly ["JSDoc parameter deprecation", "plugin compatibility registry"];
  readonly tests: readonly ["src/agents/credential-safety-prompt.test.ts"];
  readonly releaseNote: "The credential prompt helper remains available with private login-code handoff and capability-aware terminal setup guidance; its ignored legacy string argument is supported through 2026-11-30.";
}, {
  readonly code: "removed-session-transcript-file-api";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-07-01";
  readonly replacement: "session identity (`sessionKey`/`sessionId`), `SessionTranscriptUpdate.target`, and Gateway/runtime session helpers";
  readonly docsPath: "/plugins/sdk-migration#removed-session-and-transcript-file-apis";
  readonly surfaces: readonly ["saveSessionStore", "resolveSessionTranscriptPathInDir", "resolveAndPersistSessionFile", "readLatestAssistantTextFromSessionTranscript", "SessionTranscriptUpdate.sessionFile", "sessionFiles", "transcriptPath", "sessionFile", "plugins inspect compatibility notices"];
  readonly diagnostics: readonly ["plugin compatibility notice"];
  readonly tests: readonly ["src/plugins/status.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Session/transcript file APIs were removed with the SQLite session storage flip; plugins now use session identity and Gateway/runtime session helpers.";
}, {
  readonly code: "hook.before_tool_call.terminal-block-approval";
  readonly status: "active";
  readonly owner: "agent-runtime";
  readonly introduced: "2026-04-29";
  readonly docsPath: "/plugins/hooks";
  readonly surfaces: readonly ["before_tool_call block result", "before_tool_call approval result"];
  readonly diagnostics: readonly ["hook runner contract probe"];
  readonly tests: readonly ["src/plugins/hooks.security.test.ts", "src/agents/agent-tools.before-tool-call.e2e.test.ts"];
}, {
  readonly code: "hook.llm-observer.privacy-payload";
  readonly status: "active";
  readonly owner: "agent-runtime";
  readonly introduced: "2026-04-29";
  readonly docsPath: "/plugins/hooks";
  readonly surfaces: readonly ["llm_input", "llm_output", "agent_end", "allowConversationAccess"];
  readonly diagnostics: readonly ["conversation access hook contract probe"];
  readonly tests: readonly ["src/agents/cli-runner.reliability.test.ts", "src/config/schema.help.quality.test.ts"];
}, {
  readonly code: "api.capture.runtime-registrars";
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-29";
  readonly docsPath: "/plugins/architecture-internals";
  readonly surfaces: readonly ["createCapturedPluginRegistration", "capturePluginRegistration", "OpenClawPluginApi"];
  readonly diagnostics: readonly ["runtime registration capture contract probe"];
  readonly tests: readonly ["src/plugins/captured-registration.test.ts"];
}, {
  readonly code: "channel.runtime.envelope-config-metadata";
  readonly status: "active";
  readonly owner: "channel";
  readonly introduced: "2026-04-29";
  readonly docsPath: "/plugins/sdk-channel-plugins";
  readonly surfaces: readonly ["api.registerChannel", "channel setup metadata", "channel message envelope"];
  readonly diagnostics: readonly ["channel runtime contract probe"];
  readonly tests: readonly ["src/plugin-sdk/channel-entry-contract.test.ts", "src/plugins/captured-registration.test.ts"];
}, {
  readonly code: "whatsapp-web-inbound-flat-message-aliases";
  readonly status: "removed";
  readonly owner: "channel";
  readonly introduced: "2026-05-30";
  readonly replacement: "WhatsApp `WebInboundCallbackMessage` nested contexts: `event`, `payload`, `quote`, `group`, and `platform`";
  readonly docsPath: "/plugins/compatibility";
  readonly surfaces: readonly ["@openclaw/whatsapp WebInboundMessage flat fields", "WhatsApp monitorWebInbox onMessage callback", "WhatsApp monitorWebChannel listenerFactory injected messages"];
  readonly diagnostics: readonly ["plugin compatibility registry and compatibility guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "WhatsApp WebInboundMessage flat fields were removed; callbacks now receive only nested inbound contexts.";
}, {
  readonly code: "whatsapp-web-inbound-admission-top-level-fields";
  readonly status: "removed";
  readonly owner: "channel";
  readonly introduced: "2026-06-14";
  readonly replacement: "WhatsApp `WebInboundMessage.admission` fields: `conversation.id`, `accountId`, `ingress.decision`, and `conversation.kind`";
  readonly docsPath: "/plugins/compatibility";
  readonly surfaces: readonly ["@openclaw/whatsapp WebInboundMessage top-level admission fields", "WhatsApp monitorWebInbox onMessage callback", "WhatsApp monitorWebChannel listenerFactory injected messages"];
  readonly diagnostics: readonly ["plugin compatibility registry and compatibility guide"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "WhatsApp WebInboundMessage top-level admission fields were removed; callbacks now read the canonical admission envelope.";
}, {
  readonly code: "sdk-untrusted-context-identifier-aliases";
  readonly status: "removal-pending";
  readonly owner: "sdk";
  readonly introduced: "2026-07-22";
  readonly deprecated: "2026-07-22";
  readonly warningStarts: "2026-07-22";
  readonly removeAfter: "2026-09-08";
  readonly replacement: "`MsgContext.ChannelPromptContext`, `MsgContext.ChannelStructuredContext`, `ChannelStructuredContextEntry`, `SupplementalContextFacts.channelStructuredContext`, and `buildChannelMetadata`; retain the aliases until migration of published plugin readers is verified and explicit breaking-release approval is granted";
  readonly docsPath: "/plugins/compatibility";
  readonly surfaces: readonly ["openclaw/plugin-sdk reply-runtime MsgContext.UntrustedContext and UntrustedStructuredContext", "openclaw/plugin-sdk reply-runtime UntrustedStructuredContextEntry", "openclaw/plugin-sdk channel-inbound SupplementalContextFacts.untrustedContext", "openclaw/plugin-sdk security-runtime buildUntrustedChannelMetadata"];
  readonly diagnostics: readonly ["TypeScript deprecated SDK alias annotations"];
  readonly tests: readonly ["src/auto-reply/reply/inbound-context.test.ts"];
  readonly releaseNote: "Untrusted-named prompt-context SDK identifiers remain wired as deprecated aliases of the channel-named fields while plugins migrate.";
}, {
  readonly code: "bundled-channel-sdk-compat-facades";
  readonly status: "active";
  readonly owner: "sdk";
  readonly introduced: "2026-04-28";
  readonly replacement: "generic channel SDK subpaths or plugin-local `api.ts` / `runtime-api.ts` barrels for new plugins";
  readonly docsPath: "/plugins/sdk-overview";
  readonly surfaces: readonly ["openclaw/plugin-sdk/discord component message helpers", "openclaw/plugin-sdk/telegram-account resolveTelegramAccount"];
  readonly diagnostics: readonly ["plugin SDK compatibility registry"];
  readonly tests: readonly ["src/plugin-sdk/discord.test.ts", "src/plugin-sdk/telegram-account.test.ts", "src/plugins/contracts/plugin-sdk-package-contract-guardrails.test.ts"];
}, {
  readonly code: "channel-explicit-target-parser";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-04-28";
  readonly replacement: "`messaging.targetResolver` for target normalization and `messaging.resolveOutboundSessionRoute` for session/thread identity";
  readonly docsPath: "/plugins/sdk-migration";
  readonly surfaces: readonly ["ChannelMessagingAdapter.parseExplicitTarget", "openclaw/plugin-sdk/channel-route ChannelRouteExplicitTarget", "openclaw/plugin-sdk/channel-route ChannelRouteExplicitTargetParser", "openclaw/plugin-sdk/channel-route resolveChannelRouteTargetWithParser"];
  readonly diagnostics: readonly ["plugin SDK compatibility warning"];
  readonly tests: readonly ["src/channels/plugins/contracts/test-helpers/surface-contract-suite.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "The deprecated channel explicit-target parser was removed; plugins must normalize targets with `messaging.targetResolver` and project session identity with `messaging.resolveOutboundSessionRoute`.";
}, {
  readonly code: "channel-messaging-targets-subpath";
  readonly status: "removed";
  readonly owner: "sdk";
  readonly introduced: "2026-04-28";
  readonly replacement: "`openclaw/plugin-sdk/channel-targets`";
  readonly docsPath: "/plugins/sdk-migration";
  readonly surfaces: readonly ["openclaw/plugin-sdk/messaging-targets"];
  readonly diagnostics: readonly ["plugin SDK compatibility warning"];
  readonly tests: readonly ["src/plugins/compat/registry.test.ts", "src/plugins/contracts/plugin-sdk-subpaths.test.ts"];
  readonly releaseNote: "The deprecated `openclaw/plugin-sdk/messaging-targets` subpath was removed; import target helpers from `openclaw/plugin-sdk/channel-targets`.";
}, {
  readonly code: "bundled-plugin-allowlist";
  readonly status: "active";
  readonly owner: "config";
  readonly introduced: "2026-04-24";
  readonly replacement: "manifest-owned plugin enablement and scoped load plans";
  readonly docsPath: "/plugins/architecture";
  readonly surfaces: readonly ["plugins.allow", "bundled provider startup", "plugins status"];
  readonly diagnostics: readonly ["plugin status report"];
  readonly tests: readonly ["src/plugins/status.test.ts", "src/plugins/config-state.test.ts"];
}, {
  readonly code: "bundled-plugin-enablement";
  readonly status: "active";
  readonly owner: "config";
  readonly introduced: "2026-04-24";
  readonly replacement: "manifest-owned plugin defaults and scoped load plans";
  readonly docsPath: "/plugins/architecture";
  readonly surfaces: readonly ["plugins.entries", "bundled provider startup", "plugins status"];
  readonly diagnostics: readonly ["plugin status report"];
  readonly tests: readonly ["src/plugins/status.test.ts", "src/plugins/config-state.test.ts"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-agent-harness-hint";
  readonly replacement: "top-level `cliBackends[]` for CLI aliases and future `agentRuntime` ownership metadata";
  readonly surfaces: readonly ["activation.onAgentHarnesses", "activation planner"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-provider-hint";
  readonly replacement: "`providers[]` manifest ownership";
  readonly surfaces: readonly ["activation.onProviders", "activation planner"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-channel-hint";
  readonly replacement: "`channels[]` manifest ownership";
  readonly surfaces: readonly ["activation.onChannels", "activation planner"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-command-hint";
  readonly replacement: "`commandAliases` or command contribution metadata";
  readonly surfaces: readonly ["activation.onCommands", "activation planner"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-route-hint";
  readonly replacement: "HTTP route contribution metadata";
  readonly surfaces: readonly ["activation.onRoutes", "activation planner"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly code: "activation-config-path-hint";
  readonly introduced: "2026-04-27";
  readonly replacement: "manifest contribution ownership for root config surfaces";
  readonly surfaces: readonly ["activation.onConfigPaths", "startup plugin selection"];
  readonly tests: readonly ["src/plugins/channel-plugin-ids.test.ts"];
}, {
  readonly status: "active";
  readonly owner: "plugin-execution";
  readonly introduced: "2026-04-24";
  readonly docsPath: "/plugins/manifest";
  readonly diagnostics: readonly ["activation plan compat reason"];
  readonly tests: readonly ["src/plugins/activation-planner.test.ts"];
  readonly code: "activation-capability-hint";
  readonly replacement: "manifest contribution ownership";
  readonly surfaces: readonly ["activation.onCapabilities", "activation planner"];
}, {
  readonly code: "agent-harness-sdk-alias";
  readonly status: "deprecated";
  readonly owner: "agent-runtime";
  readonly introduced: "2026-04-24";
  readonly deprecated: "2026-04-25";
  readonly warningStarts: "2026-04-25";
  readonly replacement: "none yet; retain until a harness subpath ships and external migration is proven";
  readonly docsPath: "/plugins/sdk-agent-harness";
  readonly surfaces: readonly ["openclaw/plugin-sdk/agent-harness", "openclaw/plugin-sdk/agent-harness-runtime"];
  readonly diagnostics: readonly ["plugin SDK compatibility warning"];
  readonly tests: readonly ["src/plugins/contracts/plugin-sdk-subpaths.test.ts"];
}, {
  readonly code: "embedded-pi-agent-sdk-aliases";
  readonly status: "removed";
  readonly owner: "agent-runtime";
  readonly introduced: "2026-05-21";
  readonly replacement: "`runEmbeddedAgent` and `EmbeddedAgent*` SDK/runtime names";
  readonly docsPath: "/plugins/sdk-runtime";
  readonly surfaces: readonly ["api.runtime.agent.runEmbeddedPiAgent", "openclaw/extension-api runEmbeddedPiAgent", "openclaw/plugin-sdk/agent-harness-runtime EmbeddedPi* aliases"];
  readonly diagnostics: readonly ["plugin SDK compatibility registry"];
  readonly tests: readonly ["src/plugins/runtime/index.test.ts", "src/plugins/contracts/plugin-sdk-subpaths.test.ts"];
  readonly releaseNote: "The legacy `runEmbeddedPiAgent` and `EmbeddedPi*` plugin aliases were removed; plugins must use the neutral embedded-agent names.";
}, {
  readonly code: "plugin-sdk-shipped-channel-setup-exports";
  readonly status: "deprecated";
  readonly owner: "channel";
  readonly introduced: "2026-07-23";
  readonly deprecated: "2026-07-23";
  readonly warningStarts: "2026-07-23";
  readonly replacement: "retain until supported published packages migrate to plugin-owned config schemas plus generic `openclaw/plugin-sdk/channel-config-schema` and `openclaw/plugin-sdk/setup-runtime` primitives";
  readonly docsPath: "/plugins/sdk-migration#published-channel-setup-compatibility";
  readonly surfaces: readonly ["openclaw/plugin-sdk/bundled-channel-config-schema SlackConfigSchema", "openclaw/plugin-sdk/bundled-channel-config-schema DiscordConfigSchema", "openclaw/plugin-sdk/bundled-channel-config-schema SignalConfigSchema", "openclaw/plugin-sdk/bundled-channel-config-schema MSTeamsConfigSchema", "openclaw/plugin-sdk/setup-runtime createLegacyCompatChannelDmPolicy", "openclaw/plugin-sdk/setup-runtime promptLegacyChannelAllowFromForAccount"];
  readonly diagnostics: readonly ["repository deprecated API usage guard for core and bundled plugins; no external runtime import warning"];
  readonly tests: readonly ["src/plugin-sdk/shipped-channel-compat.test.ts", "src/plugins/compat/registry.test.ts"];
  readonly releaseNote: "Published OpenClaw channel packages through 2026.7.1 remain loadable while they migrate to plugin-owned config and setup helpers.";
}, {
  readonly code: "generated-bundled-channel-config-fallback";
  readonly status: "active";
  readonly owner: "channel";
  readonly introduced: "2026-04-24";
  readonly replacement: "manifest registry `channelConfigs` metadata";
  readonly docsPath: "/plugins/manifest";
  readonly surfaces: readonly ["generated bundled channel config metadata", "channel config validation"];
  readonly diagnostics: readonly ["channel config metadata fallback"];
  readonly tests: readonly ["src/plugins/contracts/config-footprint-guardrails.test.ts"];
}, {
  readonly code: "setup-runtime-fallback";
  readonly status: "active";
  readonly owner: "setup";
  readonly introduced: "2026-04-24";
  readonly replacement: "`setup.requiresRuntime: false` with complete setup descriptors";
  readonly docsPath: "/plugins/manifest/setup-and-auth#setup-reference";
  readonly surfaces: readonly ["setup-api runtime fallback", "setup.requiresRuntime omitted"];
  readonly diagnostics: readonly ["setup registry runtime diagnostic"];
  readonly tests: readonly ["src/plugins/setup-registry.test.ts", "src/plugins/setup-registry.runtime.test.ts"];
}];
//#endregion
//#region src/plugins/compat/registry.d.ts
type PluginCompatCode = (typeof PLUGIN_COMPAT_RECORDS)[number]["code"];
//#endregion
//#region src/infra/npm-registry-spec.d.ts
/**
 * Parsed registry-only npm spec accepted by plugin install flows.
 * Selectors are limited to exact versions and dist-tags; URL/git/file specs
 * are rejected before they can execute on the gateway host.
 */
type ParsedRegistryNpmSpec = {
  name: string;
  raw: string;
  selector?: string;
  selectorKind: "none" | "exact-version" | "tag";
  selectorIsPrerelease: boolean;
};
//#endregion
//#region src/plugins/install-source-info.types.d.ts
/** Warning emitted while describing plugin package install source metadata. */
type PluginInstallSourceWarning = "invalid-clawhub-spec" | "invalid-npm-spec" | "invalid-default-choice" | "default-choice-missing-source" | "clawhub-spec-floating" | "npm-integrity-without-source" | "npm-spec-floating" | "npm-spec-missing-integrity" | "npm-spec-package-name-mismatch";
/** Pinning state for npm plugin install metadata. */
type PluginInstallNpmPinState = "exact-with-integrity" | "exact-without-integrity" | "floating-with-integrity" | "floating-without-integrity";
/** Parsed npm install source metadata for a plugin package. */
type PluginInstallNpmSourceInfo = {
  spec: string;
  packageName: string;
  expectedPackageName?: string;
  selector?: string;
  selectorKind: ParsedRegistryNpmSpec["selectorKind"];
  exactVersion: boolean;
  expectedIntegrity?: string;
  pinState: PluginInstallNpmPinState;
};
/** Parsed ClawHub install source metadata for a plugin package. */
type PluginInstallClawHubSourceInfo = {
  spec: string;
  packageName: string;
  version?: string;
  exactVersion: boolean;
};
/** Parsed plugin install sources plus validation warnings. */
type PluginInstallSourceInfo = {
  defaultChoice?: PluginPackageInstall["defaultChoice"];
  clawhub?: PluginInstallClawHubSourceInfo;
  npm?: PluginInstallNpmSourceInfo;
  local?: {
    path: string;
  };
  warnings: readonly PluginInstallSourceWarning[];
};
//#endregion
//#region src/plugins/installed-plugin-index-hash.d.ts
/** File metadata signature used to skip unchanged installed plugin files. */
type InstalledPluginFileSignature = {
  size: number;
  mtimeMs: number;
  ctimeMs?: number;
};
//#endregion
//#region src/plugins/plugin-source-admission.types.d.ts
type PluginNativeArtifactFact = {
  sourceIdentity: string;
  contentHash: string;
  sizeBytes: number;
  capturedPath: string;
  namespace: string;
  capturedIdentity: string;
};
type PluginNativeNamespaceFact = {
  sourceDirectory: string;
  capturedRoot: string;
  managed: boolean;
  /** Original immutable npm directory, retained by the install-generation owner. */
  referenceRoot?: string;
  members: Record<string, {
    source: string;
    sourceIdentity: string;
    capturedIdentity: string;
    boundaryChecked: boolean;
    contentHash?: string;
    sizeBytes?: number;
  }>;
};
type PluginSourceAdmissionReceipt = {
  signature: string;
  sourceDigest: string;
  nativeArtifacts: Record<string, PluginNativeArtifactFact>;
  nativeNamespaces: Record<string, PluginNativeNamespaceFact>;
};
//#endregion
//#region src/plugins/installed-plugin-index-types.d.ts
/** Schema version for installed plugin index files. */
declare const INSTALLED_PLUGIN_INDEX_VERSION = 1;
declare const INSTALLED_PLUGIN_INDEX_MIGRATION_VERSION = 1;
type InstalledPluginIndexRefreshReason = "missing" | "stale-manifest" | "stale-package" | "source-changed" | "policy-changed" | "migration" | "host-contract-changed" | "compat-registry-changed" | "manual";
type InstalledPluginStartupInfo = {
  sidecar: boolean;
  memory: boolean;
  agentHarnesses: readonly string[];
  /**
   * Manifest activation.onConfigPaths copied into the installed index for
   * pre-manifest startup scoping. Missing on older persisted index files.
   */
  configPaths?: readonly string[];
};
type InstalledPluginContributionInfo = {
  channels: readonly string[];
  channelConfigs: readonly string[];
  providers: readonly string[];
  modelCatalogProviders: readonly string[];
  modelSupportPrefixes: readonly string[];
  modelSupportPatterns: readonly string[];
  autoEnableProviderIds: readonly string[];
  commandAliases: readonly string[];
  contracts: Readonly<Record<string, readonly string[]>>;
};
type InstalledPluginInstallRecordInfo = PluginInstallRecord;
type InstalledPluginPackageChannelInfo = PluginPackageChannel;
/** One manifest-backed plugin entry in the generated installed plugin index. */
type InstalledPluginIndexRecord = {
  pluginId: string;
  packageName?: string;
  packageVersion?: string;
  /**
   * Legacy embedded install record accepted when reading earlier index files.
   * New index writes keep install records in InstalledPluginIndex.installRecords.
   */
  installRecord?: InstalledPluginInstallRecordInfo;
  /** Hash of the top-level installRecords entry; used to detect source-changed invalidation. */
  installRecordHash?: string;
  /** Native source admissions survive process restarts while the install owner is unchanged. */
  sourceAdmissions?: Record<string, PluginSourceAdmissionReceipt>;
  /**
   * Package-authored openclaw.install metadata. This describes catalog/package
   * install intent and must not be treated as the durable install record.
   */
  packageInstall?: PluginInstallSourceInfo;
  packageChannel?: InstalledPluginPackageChannelInfo;
  packageBuild?: OpenClawPackageBuild;
  manifestPath: string;
  manifestHash: string;
  /** Hash of the doctor-contract artifact selected by the runtime resolver. */
  doctorContractHash?: string;
  doctorContractFile?: InstalledPluginFileSignature;
  manifestFile?: InstalledPluginFileSignature;
  format?: PluginManifestRecord["format"];
  bundleFormat?: PluginManifestRecord["bundleFormat"];
  source?: string;
  setupSource?: string;
  packageJson?: {
    path: string;
    hash: string;
    fileSignature?: InstalledPluginFileSignature;
  };
  rootDir: string;
  origin: PluginManifestRecord["origin"];
  enabled: boolean;
  enabledByDefault?: boolean;
  enabledByDefaultOnPlatforms?: readonly string[];
  syntheticAuthRefs?: readonly string[];
  startup: InstalledPluginStartupInfo;
  contributions?: InstalledPluginContributionInfo;
  compat: readonly PluginCompatCode[];
};
/** Full installed-index payload used by control-plane plugin registry loading. */
type InstalledPluginIndex = {
  version: typeof INSTALLED_PLUGIN_INDEX_VERSION;
  warning?: string;
  hostContractVersion: string;
  compatRegistryVersion: string;
  migrationVersion: typeof INSTALLED_PLUGIN_INDEX_MIGRATION_VERSION;
  policyHash: string;
  generatedAtMs: number;
  /** Selected workspace used to build this index. Missing for omitted and legacy scopes. */
  workspaceDir?: string;
  refreshReason?: InstalledPluginIndexRefreshReason;
  installRecords: Readonly<Record<string, InstalledPluginInstallRecordInfo>>;
  plugins: readonly InstalledPluginIndexRecord[];
  diagnostics: readonly PluginDiagnostic[];
};
//#endregion
//#region src/plugins/plugin-registry-snapshot.types.d.ts
/** Source class for plugin registry snapshots used by diagnostics and cache decisions. */
type PluginRegistrySnapshotSource = "provided" | "persisted" | "derived";
/** Which registry facts differ for one plugin; the sources alone can be identical. */
type PluginRegistryDifferenceFacet = "record" | "install" | "diagnostics";
type PluginRegistryDifference = {
  pluginId: string;
  changed: readonly PluginRegistryDifferenceFacet[];
  persistedSource: string | null;
  derivedSource: string | null;
};
type PluginRegistrySnapshotDiagnostic = {
  level: "info" | "warn";
  code: "persisted-registry-missing" | "persisted-registry-stale-policy" | "persisted-registry-stale-source";
  message: string;
  differences?: readonly PluginRegistryDifference[];
};
//#endregion
//#region src/plugins/provider-owner-index.d.ts
type DeclaredProviderOwnerIndex = ReadonlyMap<string, ReadonlySet<string>>;
//#endregion
//#region src/plugins/plugin-metadata-snapshot.types.d.ts
type PluginProviderAuthAliasCandidate = {
  plugin: PluginManifestRecord;
  target: string;
  baseUrls?: readonly string[];
  /** First eligible declaration owns public map order, even if a later candidate wins. */
  order: number;
};
type PluginProviderAuthContribution = {
  plugin: PluginManifestRecord;
  envProviders: readonly PluginManifestSetupProvider[];
  evidenceProviders: readonly PluginManifestSetupProvider[];
  fallbackProviderRefs: readonly string[];
};
type PluginMetadataSnapshotOwnerMaps = {
  channels: ReadonlyMap<string, readonly string[]>;
  channelAccountKeyPolicies?: ReadonlyMap<string, ChannelAccountKeyPolicy>;
  channelConfigs: ReadonlyMap<string, readonly string[]>;
  providers: ReadonlyMap<string, readonly string[]>;
  modelCatalogProviders: ReadonlyMap<string, readonly string[]>;
  cliBackends: ReadonlyMap<string, readonly string[]>;
  setupProviders: ReadonlyMap<string, readonly string[]>;
  commandAliases: ReadonlyMap<string, readonly string[]>;
  contracts: ReadonlyMap<string, readonly string[]>;
  /** Empty views must not fall through to process-current model normalization policies. */
  modelIdNormalizationPolicies: ReadonlyMap<string, PluginManifestModelIdNormalizationProvider>;
  providerAuthContributions: readonly PluginProviderAuthContribution[];
  providerAuthAliases?: ReadonlyMap<string, readonly PluginProviderAuthAliasCandidate[]>;
  providerEndpoints?: readonly PluginManifestProviderEndpoint[];
  providerRequests?: ReadonlyMap<string, PluginManifestProviderRequestProvider>;
};
type PluginMetadataSnapshotMetrics = {
  registrySnapshotMs: number;
  manifestRegistryMs: number;
  ownerMapsMs: number;
  totalMs: number;
  indexPluginCount: number;
  manifestPluginCount: number;
};
type PluginMetadataSnapshot = {
  policyHash: string;
  configFingerprint?: string;
  pluginIds?: readonly string[];
  registrySource?: PluginRegistrySnapshotSource;
  workspaceDir?: string;
  index: InstalledPluginIndex;
  /** The original workspace-scoped index described by registrySource, before runtime unions. */
  registryIndex: InstalledPluginIndex;
  registryDiagnostics: readonly PluginRegistrySnapshotDiagnostic[];
  manifestRegistry: PluginManifestRegistry;
  /** Independently validated bundled owners, including packages shadowed by active plugins. */
  bundledManifestRegistry?: PluginManifestRegistry;
  plugins: readonly PluginManifestRecord[];
  diagnostics: readonly PluginDiagnostic[];
  byPluginId: ReadonlyMap<string, PluginManifestRecord>;
  normalizePluginId: (pluginId: string) => string;
  owners: PluginMetadataSnapshotOwnerMaps;
  /** Strict first-winner literal/setup ownership, separate from public alias maps. */
  declaredProviderOwners: DeclaredProviderOwnerIndex;
  metrics: PluginMetadataSnapshotMetrics;
  discovery?: PluginDiscoveryResult;
};
type PluginMetadataRegistryView = Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "discovery" | "workspaceDir"> & Partial<Pick<PluginMetadataSnapshot, "declaredProviderOwners">>;
//#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
type ResolveAuthProfileOrderParams = {
  cfg?: OpenClawConfig;
  store: AuthProfileStore;
  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 ordered so availability remains unknown. */
  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
/** External CLI auth discovery mode used while loading auth profile stores. */
type ExternalCliAuthDiscovery = {
  mode: "none";
  allowKeychainPrompt?: false;
  config?: OpenClawConfig;
} | {
  mode: "existing";
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
} | {
  mode: "scoped";
  allowKeychainPrompt?: boolean;
  config?: OpenClawConfig;
  providerIds?: Iterable<string>;
  profileIds?: Iterable<string>;
};
//#endregion
//#region src/agents/auth-profiles/path-resolve.d.ts
type SharedAuthStoreOwnership = {
  location: "legacy-main";
} | {
  location: "state-db";
};
/** Pure producer facts; capturing a supplied runtime snapshot must not open SQLite. */
type AuthProfileOwnerScope = {
  stateDir: string;
  sharedMainDir: string;
};
//#endregion
//#region src/agents/auth-profiles/profile-list.d.ts
/** Lists auth profile ids whose credential provider matches the requested provider. */
declare function listProfilesForProvider(store: AuthProfileStore, provider: string): string[];
//#endregion
//#region src/plugins/provider-auth-types.d.ts
/** Provider secret input modes: inline plaintext or external secret reference. */
type SecretInputMode = "plaintext" | "ref";
//#endregion
//#region src/plugins/provider-external-auth.types.d.ts
type ProviderAuthOptionBag = {
  token?: string;
  tokenProvider?: string;
  secretInputMode?: SecretInputMode;
  [key: string]: unknown;
};
/** Context for resolving synthetic provider credentials from config. */
type ProviderResolveSyntheticAuthContext = {
  config?: OpenClawConfig;
  provider: string;
  providerConfig?: ModelProviderConfig;
};
/** Synthetic provider credential returned by plugin auth helpers. */
type ProviderSyntheticAuthResult = {
  apiKey: string;
  source: string;
  mode: Exclude<ModelProviderAuthMode, "aws-sdk">;
  expiresAt?: number;
  /** Native presence authorizes only this runtime, never a provider bearer request. */
  nativeAuth?: {
    runtime: string;
    mode: "api-key" | "oauth" | "token";
  };
};
/** Context for resolving external provider auth profiles. */
type ProviderResolveExternalAuthProfilesContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  store: AuthProfileStore;
};
/** External auth profile credential resolved for a provider. */
type ProviderExternalAuthProfile = {
  profileId: string;
  credential: OAuthCredential$1;
  persistence?: "runtime-only" | "persisted";
};
/** Internal synchronous resolver shared by provider hooks and auth-store overlays. */
type ProviderExternalAuthProfileResolver = (params: {
  config?: OpenClawConfig;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  context: ProviderResolveExternalAuthProfilesContext;
}) => ProviderExternalAuthProfile[];
//#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/state/openclaw-agent-db-validation-cache.d.ts
type OpenClawAgentDatabaseValidation = {
  agentId: string;
  identity: string;
  /** 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;
};
//#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) => T | Promise<T>) => Promise<T>;
//#endregion
//#region src/state/openclaw-agent-db.d.ts
declare const { withOpenClawAgentDatabaseAsync, withOpenClawAgentDatabaseAdmission }: {
  withOpenClawAgentDatabaseAsync: <T>(inputOptions: OpenClawAgentDatabaseOptions, 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/agents/auth-profiles/sqlite.d.ts
type AuthProfileDatabase = OpenClawAgentDatabase | OpenClawStateDatabase;
/** Internal prepared ownership, carried through commit publication and compensation. */
type AuthProfileStoreOwner = {
  databasePath: string;
  sharedDatabasePath: string;
  location: SharedAuthStoreOwnership["location"];
};
type PreparedAuthProfileStoreOwner = AuthProfileStoreOwner & {
  env: NodeJS.ProcessEnv;
};
//#endregion
//#region src/agents/auth-profiles/runtime-read.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;
  /** 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 | null;
};
//#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/store.d.ts
/** Find a persisted credential in the scoped store, falling back to the main store. */
declare function findPersistedAuthProfileCredential(params: {
  agentDir?: string;
  profileId: string;
}): AuthProfileStore["profiles"][string] | undefined;
//#endregion
//#region src/agents/auth-profiles/store-runtime.d.ts
declare const { createAuthProfileStoreReadScope, updateAuthProfileStoreWithLock, loadAuthProfileStore, loadAuthProfileStoreForRuntime, loadAuthProfileStoreForRuntimeAsync, loadAuthProfileStoreForSecretsRuntime, loadAuthProfileStoreWithoutExternalProfiles, ensureAuthProfileStore, ensureAuthProfileStoreWithoutExternalProfiles, ensureAuthProfileStoreForLocalUpdate, saveAuthProfileStore, saveAuthProfileStoreWithPreparedOwner, saveAuthProfileStoreIfPersistenceSnapshotMatches }: Readonly<{
  createAuthProfileStoreReadScope: (agentDir: string, config: OpenClawConfig | undefined) => {
    agentDir: string;
    store: AuthProfileStore;
    read: () => AuthProfileStore;
    getRuntimeSnapshots: () => RuntimeAuthProfileStore[];
    assertCredentialReady: (source: AuthProfileCredentialSource, baseUrl?: string) => void;
    assertProviderReady: (provider?: string, baseUrl?: string) => void;
  };
  updateAuthProfileStoreWithLock: (params: {
    agentDir?: string;
    profileId?: string;
    sharedStoreWrite?: boolean;
    stateDir?: string;
    saveOptions?: {
      filterExternalAuthProfiles?: boolean;
      preserveOrderProfileIds?: Iterable<string>;
      preserveStateProfileIds?: Iterable<string>;
      pruneOrderProfileIds?: Iterable<string>;
      sharedStoreWrite?: boolean;
      syncExternalCli?: boolean;
    };
    updater: (store: AuthProfileStore, owner?: PreparedAuthProfileStoreOwner) => boolean;
  }) => Promise<AuthProfileStore | null>;
  loadAuthProfileStore: () => AuthProfileStore;
  loadAuthProfileStoreForRuntime: (agentDir?: string, options?: LoadAuthProfileStoreOptions, env?: NodeJS.ProcessEnv) => AuthProfileStore;
  loadAuthProfileStoreForRuntimeAsync: (agentDir?: string, options?: Omit<LoadAuthProfileStoreOptions, "database" | "onReadOwner" | "syncExternalCli">) => Promise<AuthProfileStore>;
  loadAuthProfileStoreForSecretsRuntime: (agentDir?: string, options?: Pick<LoadAuthProfileStoreOptions, "config" | "profileId" | "externalCli" | "externalCliProviderIds" | "externalCliProfileIds" | "inheritedAuthDir">) => AuthProfileStore;
  loadAuthProfileStoreWithoutExternalProfiles: (agentDir?: string, loadOptions?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir" | "profileId">) => AuthProfileStore;
  ensureAuthProfileStore: (agentDir?: string, options?: {
    migrationProvider?: string;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    config?: OpenClawConfig;
    externalCli?: ExternalCliAuthDiscovery;
    externalCliProviderIds?: Iterable<string>;
    externalCliProfileIds?: Iterable<string>;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
  }) => AuthProfileStore;
  ensureAuthProfileStoreWithoutExternalProfiles: (agentDir?: string, options?: {
    migrationProvider?: string;
    config?: OpenClawConfig;
    profileId?: string;
    allowKeychainPrompt?: boolean;
    inheritedAuthDir?: string;
    readOnly?: boolean;
    syncExternalCli?: boolean;
  }) => AuthProfileStore;
  ensureAuthProfileStoreForLocalUpdate: (agentDir?: string) => AuthProfileStore;
  saveAuthProfileStore: (store: AuthProfileStore, agentDir?: string, options?: {
    filterExternalAuthProfiles?: boolean;
    preserveOrderProfileIds?: Iterable<string>;
    preserveStateProfileIds?: Iterable<string>;
    pruneOrderProfileIds?: Iterable<string>;
    sharedStoreWrite?: boolean;
    syncExternalCli?: boolean;
  }, database?: AuthProfileDatabase) => void;
  saveAuthProfileStoreWithPreparedOwner: (store: AuthProfileStore, agentDir: string | undefined, options: {
    filterExternalAuthProfiles?: boolean;
    preserveOrderProfileIds?: Iterable<string>;
    preserveStateProfileIds?: Iterable<string>;
    pruneOrderProfileIds?: Iterable<string>;
    sharedStoreWrite?: boolean;
    syncExternalCli?: boolean;
  } | undefined, database: AuthProfileDatabase, owner: AuthProfileStoreOwner | PreparedAuthProfileStoreOwner) => void;
  saveAuthProfileStoreIfPersistenceSnapshotMatches: (params: {
    store: AuthProfileStore;
    snapshot: {
      owner: PreparedAuthProfileStoreOwner;
      credentialsRaw: unknown;
      stateRaw: unknown;
      runtimeCaptured: boolean;
      runtimeRevision?: number;
      runtimeRevisionAtSaveEdge?: number;
      runtimeRevisionBeforePublication?: number;
      runtimeEntry?: OwnedRuntimeAuthProfileStoreSnapshotEntry;
      derivedRuntimeStores?: Array<OwnedRuntimeAuthProfileStoreSnapshotEntry & {
        runtimeRevision: number;
      }>;
      derivedRuntimeRevisionsAtSaveEdge?: Array<{
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }>;
      derivedRuntimeRevisionsBeforePublication?: Array<{
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }>;
    };
    agentDir?: string;
    options?: {
      filterExternalAuthProfiles?: boolean;
      preserveOrderProfileIds?: Iterable<string>;
      preserveStateProfileIds?: Iterable<string>;
      pruneOrderProfileIds?: Iterable<string>;
      sharedStoreWrite?: boolean;
      syncExternalCli?: boolean;
    };
    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?: Array<{
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }>;
      derivedRuntimeRevisionsBeforePublication?: Array<{
        databasePath: string;
        agentDir: string;
        runtimeRevision: number;
      }>;
    };
    publishRuntimeSnapshots: () => boolean;
  };
  findPersistedAuthProfileCredential: typeof findPersistedAuthProfileCredential;
}>;
//#endregion
//#region src/plugins/provider-auth-availability.d.ts
declare const { isProviderApiKeyConfigured, listUsableProviderAuthProfileIds, isProviderAuthProfileConfigured, resolveProviderAuthProfileApiKey }: Readonly<{
  isProviderApiKeyConfigured: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    acceptsApiKey?: (apiKey: string) => boolean;
  }) => boolean;
  listUsableProviderAuthProfileIds: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => {
    agentDir: string;
    profileIds: string[];
  };
  isProviderAuthProfileConfigured: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => boolean;
  resolveProviderAuthProfileApiKey: (params: {
    provider: string;
    cfg?: OpenClawConfig;
    agentDir?: string;
    profileTypes?: readonly AuthProfileCredential["type"][];
    capability?: string;
    allowKeychainPrompt?: boolean;
    includeExternalCliAuth?: boolean;
  }) => Promise<string | undefined>;
}>;
//#endregion
//#region src/agents/agent-scope-config.d.ts
declare function resolveAgentWorkspaceDir(cfg: OpenClawConfig, agentId: string, env?: NodeJS.ProcessEnv): string;
declare function resolveAgentDir(cfg: OpenClawConfig, agentId: string, env?: NodeJS.ProcessEnv): string;
//#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/agents/provider-attribution.d.ts
/** Transport family used when resolving provider-specific request policy. */
type ProviderRequestTransport = "stream" | "websocket" | "http" | "media-understanding";
/** Capability family used when endpoint rules differ by media or LLM request type. */
type ProviderRequestCapability = "llm" | "audio" | "image" | "video" | "other";
//#endregion
//#region src/agents/provider-request-config.d.ts
type RequestApi = Api | ModelDefinitionConfig["api"];
/** Auth override accepted from sanitized provider/model request config. */
type ProviderRequestAuthOverride = {
  mode: "provider-default";
} | {
  mode: "authorization-bearer";
  token: string;
} | {
  mode: "header";
  headerName: string;
  value: string;
  prefix?: string;
};
/** TLS override accepted from sanitized provider/model request config. */
type ProviderRequestTlsOverride = {
  ca?: string;
  cert?: string;
  key?: string;
  passphrase?: string;
  serverName?: string;
  insecureSkipVerify?: boolean;
};
/** Proxy override accepted from sanitized provider/model request config. */
type ProviderRequestProxyOverride = {
  mode: "env-proxy";
  tls?: ProviderRequestTlsOverride;
} | {
  mode: "explicit-proxy";
  url: string;
  tls?: ProviderRequestTlsOverride;
};
/** Transport override block shared by provider and model request config. */
type ProviderRequestTransportOverrides = {
  headers?: Record<string, string>;
  auth?: ProviderRequestAuthOverride;
  proxy?: ProviderRequestProxyOverride;
  tls?: ProviderRequestTlsOverride;
};
/** Model-scoped transport overrides, including private-network policy. */
type ModelProviderRequestTransportOverrides$1 = ProviderRequestTransportOverrides & {
  allowPrivateNetwork?: boolean;
};
type ProviderRequestHeaderPrecedence = "caller-wins" | "defaults-win";
/** Resolves final headers for one provider request route. */
declare function resolveProviderRequestHeaders(params: {
  provider: string;
  api?: RequestApi;
  baseUrl?: string;
  capability?: ProviderRequestCapability;
  transport?: ProviderRequestTransport;
  callerHeaders?: Record<string, string>;
  defaultHeaders?: Record<string, string>;
  precedence?: ProviderRequestHeaderPrecedence;
  request?: ProviderRequestTransportOverrides;
}): Record<string, string> | undefined;
//#endregion
//#region src/agents/model-auth-runtime-shared.d.ts
/** Resolved credential material and provenance for one provider request. */
type ResolvedProviderAuth = {
  apiKey?: string;
  profileId?: string;
  source: string;
  mode: "api-key" | "oauth" | "token" | "aws-sdk";
  /** Provider-owned OAuth grant family; distinct from credential renewal mode. */
  authFlow?: string;
};
/** Require a normalized API key or throw a provider-auth error. */
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-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;
  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;
  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-model.d.ts
type ModelAuthMode = "api-key" | "oauth" | "token" | "mixed" | "aws-sdk" | "unknown";
//#endregion
//#region src/proxy-capture/env.d.ts
type DebugProxySettings = {
  enabled: boolean;
  required: boolean;
  proxyUrl?: string;
  /** @deprecated Capture storage now lives in the shared state database. */
  dbPath: string;
  /** @deprecated Capture payloads now live in the shared state database. */
  blobDir: string;
  certDir: string;
  sessionId: string;
  sourceProcess: string;
};
declare function resolveDebugProxySettings(env?: NodeJS.ProcessEnv): DebugProxySettings;
declare function createDebugProxyWebSocketAgent(settings: DebugProxySettings): Agent | undefined;
declare function resolveEffectiveDebugProxyUrl(configuredProxyUrl?: string): string | undefined;
//#endregion
//#region src/proxy-capture/types.d.ts
type CaptureProtocol = "http" | "https" | "sse" | "ws" | "wss" | "connect";
type CaptureDirection = "outbound" | "inbound" | "local";
type CaptureEventKind = "connect" | "tls-handshake" | "request" | "response" | "ws-open" | "ws-frame" | "ws-close" | "error" | "retry-link";
type CaptureSessionRecord = {
  id: string;
  startedAt: number;
  endedAt?: number;
  mode: string;
  sourceScope: "openclaw";
  sourceProcess: string;
  proxyUrl?: string;
  /** @deprecated Capture storage now lives in the shared state database. */
  dbPath?: string;
  /** @deprecated Capture payloads now live in the shared state database. */
  blobDir?: string;
};
type CaptureBlobRecord = {
  blobId: string;
  path: string;
  encoding: "gzip";
  sizeBytes: number;
  sha256: string;
  contentType?: string;
};
type SharedCaptureBlobRecord = Omit<CaptureBlobRecord, "path"> & {
  path?: never;
};
type CaptureEventRecord = {
  sessionId: string;
  ts: number;
  sourceScope: "openclaw";
  sourceProcess: string;
  protocol: CaptureProtocol;
  direction: CaptureDirection;
  kind: CaptureEventKind;
  flowId: string;
  method?: string;
  host?: string;
  path?: string;
  status?: number;
  closeCode?: number;
  contentType?: string;
  headersJson?: string;
  dataText?: string;
  dataBlobId?: string;
  dataSha256?: string;
  errorText?: string;
  metaJson?: string;
};
type CaptureQueryPreset = "double-sends" | "retry-storms" | "cache-busting" | "ws-duplicate-frames" | "missing-ack" | "error-bursts";
type CaptureQueryRow = Record<string, string | number | null>;
type CaptureSessionSummary = {
  id: string;
  startedAt: number;
  endedAt?: number;
  mode: string;
  sourceProcess: string;
  proxyUrl?: string;
  eventCount: number;
};
type CaptureObservedDimension = {
  value: string;
  count: number;
};
type CaptureSessionCoverageSummary = {
  sessionId: string;
  totalEvents: number;
  unlabeledEventCount: number;
  providers: CaptureObservedDimension[];
  apis: CaptureObservedDimension[];
  models: CaptureObservedDimension[];
  hosts: CaptureObservedDimension[];
  localPeers: CaptureObservedDimension[];
};
//#endregion
//#region src/proxy-capture/store.kernel.d.ts
type DebugProxyCaptureKernelOptions = {
  db: DatabaseSync;
  dbPath: string;
  blobDir: string;
  pathBased?: {
    blobDir: string;
  };
  runWrite: <T>(operation: () => T) => T;
};
declare class DebugProxyCaptureKernel {
  readonly db: DatabaseSync;
  readonly dbPath: string;
  readonly blobDir: string;
  private readonly capturePathBased?;
  private readonly runWrite;
  constructor(options: DebugProxyCaptureKernelOptions);
  upsertSession(session: CaptureSessionRecord): void;
  endSession(sessionId: string, endedAt?: number): void;
  persistPayload(data: Buffer, contentType?: string): CaptureBlobRecord | SharedCaptureBlobRecord;
  recordEvent(event: CaptureEventRecord): void;
  private insertEvent;
  listSessions(limit?: number): CaptureSessionSummary[];
  getSessionEvents(sessionId: string, limit?: number): Array<Record<string, unknown>>;
  summarizeSessionCoverage(sessionId: string): CaptureSessionCoverageSummary;
  readBlob(blobId: string): string | null;
  queryPreset(preset: CaptureQueryPreset, sessionId?: string): CaptureQueryRow[];
  purgeAll(): {
    sessions: number;
    events: number;
    blobs: number;
  };
  deleteSessions(sessionIds: string[]): {
    sessions: number;
    events: number;
    blobs: number;
  };
  private deletePathBasedSessions;
  private countCaptureRows;
  private readSessionDeletionRows;
  private deleteSessionMetadata;
  private findRemainingBlobReferences;
}
declare function persistEventPayload(store: {
  persistPayload(data: Buffer, contentType?: string): CaptureBlobRecord | SharedCaptureBlobRecord;
}, params: {
  data?: Buffer | string | null;
  contentType?: string;
  previewLimit?: number;
}): {
  dataText?: string;
  dataBlobId?: string;
  dataSha256?: string;
};
//#endregion
//#region src/proxy-capture/store.sqlite.d.ts
type DebugProxyCaptureStoreOptions = {
  env?: NodeJS.ProcessEnv;
};
declare class DebugProxyCaptureStoreImpl extends DebugProxyCaptureKernel {
  private readonly pathBased?;
  private readonly releaseIdleReference?;
  private closed;
  private closing;
  constructor(optionsOrDbPath?: DebugProxyCaptureStoreOptions | string, legacyBlobDir?: string);
  close(): void;
  get isClosed(): boolean;
}
/** @deprecated Use AsyncDebugProxyCaptureStore for worker-backed shared-state access. */
type DebugProxyCaptureStore = Omit<DebugProxyCaptureStoreImpl, "persistPayload"> & {
  persistPayload(data: Buffer, contentType?: string): CaptureBlobRecord | SharedCaptureBlobRecord;
};
type LegacyDebugProxyCaptureStore = Omit<DebugProxyCaptureStoreImpl, "persistPayload"> & {
  persistPayload(data: Buffer, contentType?: string): CaptureBlobRecord;
};
type SharedDebugProxyCaptureStore = Omit<DebugProxyCaptureStoreImpl, "persistPayload"> & {
  persistPayload(data: Buffer, contentType?: string): SharedCaptureBlobRecord;
};
type DebugProxyCaptureStoreConstructor = {
  new (dbPath: string, blobDir: string): LegacyDebugProxyCaptureStore;
  new (options?: DebugProxyCaptureStoreOptions): SharedDebugProxyCaptureStore;
};
/** @deprecated Acquire shared-state storage with acquireDebugProxyCaptureStoreAsync. */
declare const DebugProxyCaptureStore: DebugProxyCaptureStoreConstructor;
/** @deprecated Use acquireDebugProxyCaptureStoreAsync for shared-state access. */
declare function getDebugProxyCaptureStore(dbPath: string, blobDir: string): LegacyDebugProxyCaptureStore;
/** @deprecated Use acquireDebugProxyCaptureStoreAsync for shared-state access. */
declare function getDebugProxyCaptureStore(options?: DebugProxyCaptureStoreOptions): SharedDebugProxyCaptureStore;
/** @deprecated Await each async capture lease's release instead. */
declare function closeDebugProxyCaptureStore(): void;
/** @deprecated Use acquireDebugProxyCaptureStoreAsync for shared-state access. */
declare function acquireDebugProxyCaptureStore(dbPath: string, blobDir: string): {
  store: LegacyDebugProxyCaptureStore;
  release: () => void;
};
/** @deprecated Use acquireDebugProxyCaptureStoreAsync for shared-state access. */
declare function acquireDebugProxyCaptureStore(options?: DebugProxyCaptureStoreOptions): {
  store: SharedDebugProxyCaptureStore;
  release: () => void;
};
declare function safeJsonString(value: unknown): string | undefined;
//#endregion
//#region src/proxy-capture/runtime-owner.d.ts
type DebugProxyCaptureStoreLike = Pick<ReturnType<typeof getDebugProxyCaptureStore>, "upsertSession" | "endSession" | "recordEvent"> & Partial<Pick<ReturnType<typeof getDebugProxyCaptureStore>, "close" | "isClosed">>;
type DebugProxyCaptureRuntimeDeps = {
  getStore?: () => DebugProxyCaptureStoreLike;
  closeStore?: () => void;
  persistEventPayload?: (store: DebugProxyCaptureStoreLike, payload: Parameters<typeof persistEventPayload>[1]) => ReturnType<typeof persistEventPayload>;
  safeJsonString?: typeof safeJsonString;
  fetchTarget?: typeof globalThis;
};
type DebugProxyCaptureAsyncRuntimeDeps = Pick<DebugProxyCaptureRuntimeDeps, "safeJsonString" | "fetchTarget">;
declare function isDebugProxyGlobalFetchPatchInstalled(): boolean;
/** @deprecated Use finalizeDebugProxyCaptureAsync to drain asynchronous capture work. */
declare function finalizeDebugProxyCapture(resolved?: DebugProxySettings, deps?: DebugProxyCaptureRuntimeDeps): void;
declare function finalizeDebugProxyCaptureAsync(resolved?: DebugProxySettings, deps?: DebugProxyCaptureRuntimeDeps): Promise<void>;
//#endregion
//#region src/infra/fetch-headers.d.ts
type HeadersLike = {
  entries: () => IterableIterator<[string, string]>;
  get: (name: string) => string | null;
  [Symbol.iterator]: () => IterableIterator<[string, string]>;
};
//#endregion
//#region src/proxy-capture/runtime-response-body.d.ts
type HttpCaptureParams = {
  url: string;
  method: string;
  requestHeaders?: HeadersLike | Record<string, string> | undefined;
  requestBody?: BodyInit | Buffer | string | null;
  response: Response;
  signal?: AbortSignal;
  transport?: "http" | "sse";
  flowId?: string;
  meta?: Record<string, unknown>;
};
//#endregion
//#region src/proxy-capture/runtime.d.ts
/** @deprecated Use initializeDebugProxyCaptureAsync for worker-backed capture. */
declare function initializeDebugProxyCapture(mode: string, resolved?: DebugProxySettings, deps?: DebugProxyCaptureRuntimeDeps): void;
/** @deprecated Use captureHttpExchangeAsync and await capture finalization at shutdown. */
declare function captureHttpExchange(params: HttpCaptureParams, resolved?: DebugProxySettings, deps?: DebugProxyCaptureRuntimeDeps): void;
type WsCaptureParams = {
  url: string;
  direction: "outbound" | "inbound" | "local";
  kind: "ws-open" | "ws-frame" | "ws-close" | "error";
  flowId: string;
  payload?: string | Buffer;
  closeCode?: number;
  errorText?: string;
  meta?: Record<string, unknown>;
};
/** @deprecated Use captureWsEventAsync and await capture finalization at shutdown. */
declare function captureWsEvent(params: WsCaptureParams, resolved?: DebugProxySettings, deps?: DebugProxyCaptureRuntimeDeps): void;
declare function captureWsEventAsync(params: WsCaptureParams, resolved?: DebugProxySettings, deps?: DebugProxyCaptureAsyncRuntimeDeps): Promise<void>;
declare function captureHttpExchangeAsync(params: HttpCaptureParams, resolved?: DebugProxySettings, deps?: DebugProxyCaptureAsyncRuntimeDeps): Promise<void>;
declare function initializeDebugProxyCaptureAsync(mode: string, resolved?: DebugProxySettings, deps?: DebugProxyCaptureAsyncRuntimeDeps): Promise<void>;
//#endregion
//#region src/infra/net/pinned-dispatcher-pool.d.ts
type PinnedDispatcherLease = {
  dispatcher: Dispatcher;
  reused: boolean;
  release: () => Promise<void>;
};
type PinnedDispatcherPoolOptions = {
  maxEntries: number;
  idleTtlMs: number;
};
/**
 * 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 readonly ownedEntries;
  private readonly maxEntries;
  private readonly idleTtlMs;
  private closed;
  constructor(options: PinnedDispatcherPoolOptions);
  acquire(params: {
    key: string;
    groupKey: 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;
  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;
  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;
};
//#endregion
//#region src/agents/provider-http-errors.d.ts
/** Shared timeout and byte-limit options for provider response consumption. */
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;
};
/** Options for bounded provider error-body normalization. */
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>;
/** Error type carrying normalized provider status, request id, code, type, and body metadata. */
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: {
    status: number;
    code?: string;
    type?: string;
    body?: string;
    requestId?: string;
    retryAfterMs?: number;
  });
}
/** Creates a normalized provider HTTP error from a failed response. */
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;
//#endregion
//#region src/globals.d.ts
declare function shouldLogVerbose(): boolean;
type ThemeFormatter = (value: string) => string;
declare const warn: ThemeFormatter;
//#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;
};
/**
 * 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?: () => {
    pattern: ResolvedRedactPattern;
    /** Prepend one complete, newline-bounded source block; true means older input cannot matter. */
    prepend: () => {
      consume: (text: string) => void;
      finish: () => boolean;
    };
  };
};
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[];
  sensitiveFieldPatterns?: readonly RedactPattern[];
};
declare function redactSensitiveText(text: 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 = {
  isProviderApiKeyConfigured: typeof isProviderApiKeyConfigured;
  isProviderAuthProfileConfigured: typeof isProviderAuthProfileConfigured;
  resolveAgentDir: typeof resolveAgentDir;
  createRealtimeTranscriptionWebSocketSession: typeof createRealtimeTranscriptionWebSocketSession;
  resolveProviderRequestHeaders: typeof resolveProviderRequestHeaders;
  resolveProviderAuthProfileApiKey: typeof resolveProviderAuthProfileApiKey;
  resolveApiKeyForProvider: typeof resolveApiKeyForProviderCore;
  /** @deprecated Use the host context's captureWsEventAsync; retained for shipped plugins. */
  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;
};
/** Native hosts supply asynchronous capture while preserving the legacy plugin context. */
type PluginCapabilityCatalogHostContext = PluginCapabilityCatalogContext & {
  captureWsEventAsync: typeof captureWsEventAsync;
};
//#endregion
//#region src/gateway/methods/descriptor.d.ts
/** Scope marker for methods that only authenticated node clients may call. */
declare const NODE_GATEWAY_METHOD_SCOPE: "node";
/** Scope marker for methods whose handler derives the required operator scope at runtime. */
declare const DYNAMIC_GATEWAY_METHOD_SCOPE: "dynamic";
/** Authorization scope attached to a gateway method descriptor. */
type GatewayMethodScope = OperatorScope | typeof NODE_GATEWAY_METHOD_SCOPE | typeof DYNAMIC_GATEWAY_METHOD_SCOPE;
/** Owner metadata used to keep core, plugin, channel, and auxiliary methods distinguishable. */
type GatewayMethodOwner = {
  kind: "core";
  area: string;
} | {
  kind: "plugin";
  pluginId: string;
} | {
  kind: "channel";
  channelId: string;
} | {
  kind: "aux";
  area: string;
};
/** Startup availability flag exposed to clients as retryable startup-unavailable errors. */
type GatewayMethodStartupAvailability = "available" | "unavailable-until-sidecars";
type 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;
/** Complete metadata for one dispatchable gateway method. */
type GatewayMethodDescriptor = {
  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;
};
/** Read-only method registry view used by request dispatch and method listing. */
type GatewayMethodRegistryView = {
  /** Opaque registry handle carried into request scope by the gateway composition root. */
  pluginRegistry?: object;
  getHandler: (name: string) => GatewayMethodHandler | undefined;
  listMethods: () => string[];
  listAdvertisedMethods: () => string[];
  getScope: (name: string) => GatewayMethodScope | undefined;
  getSessionAccess?: (name: string) => GatewayMethodSessionAccess | undefined;
  isStartupUnavailable: (name: string) => boolean;
  isObservation: (name: string) => boolean;
  isControlPlaneWrite: (name: string) => boolean;
  requiresAuthenticatedProfile: (name: string) => boolean;
  descriptors: () => readonly GatewayMethodDescriptor[];
};
//#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">): 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/mutation-types.d.ts
/** Selects whether a mutation starts from runtime or source config shape. */
type ConfigMutationBase = "runtime" | "source";
//#endregion
//#region src/config/runtime-snapshot.d.ts
type ConfigWriteAfterWrite = {
  mode: "auto";
} | {
  mode: "restart";
  reason: string;
} | {
  mode: "none";
  reason: string;
};
type ConfigWriteFollowUp = (Exclude<ConfigWriteAfterWrite, {
  mode: "restart";
}> & {
  requiresRestart: false;
}) | (Extract<ConfigWriteAfterWrite, {
  mode: "restart";
}> & {
  requiresRestart: true;
});
//#endregion
//#region src/config/mutate.d.ts
type ConfigReplaceResult = {
  path: string;
  previousHash: string | null;
  snapshot: ConfigFileSnapshot;
  nextConfig: OpenClawConfig;
  persistedHash: string | null;
  persistedSourceConfig?: OpenClawConfig;
  afterWrite: ConfigWriteAfterWrite;
  followUp: ConfigWriteFollowUp;
};
//#endregion
//#region src/config/state-dir.d.ts
/**
 * State directory for mutable data (sessions, logs, caches).
 * Can be overridden via OPENCLAW_STATE_DIR.
 * Default: ~/.openclaw
 */
declare function resolveStateDir(env?: NodeJS.ProcessEnv, homedir?: () => string): string;
//#endregion
//#region src/config/implicit-mentions.d.ts
type ResolvedChannelImplicitMentions = Required<ChannelImplicitMentionsConfig>;
//#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 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 = {
  opaqueEntryId: string;
  kind: ChannelIngressIdentifierKind;
  wildcard?: boolean;
  authentication?: IdentifierAuthentication;
  /** @deprecated Use `authentication: "mutable"`. Remove in the next Plugin SDK major. */
  dangerous?: boolean;
  sensitivity?: "normal" | "pii";
};
/** 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?: RedactedIngressMatchedPair[];
};
type RedactedIngressMatchedPair = {
  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: "dm" | "group" | "route" | "command";
    accountId: string;
  }): InternalChannelIngressNormalizeResult | Promise<InternalChannelIngressNormalizeResult>;
  matchSubject(params: {
    subject: NormalizedIngressSubject;
    entries: readonly NormalizedIngressEntry[];
    context: "dm" | "group" | "route" | "command";
  }): 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?: RedactedIdentifierAuthenticationResult;
};
type RedactedIdentifierAuthenticationResult = {
  evaluated: boolean;
  threshold: IdentifierAuthentication;
  affectedMatch: boolean;
  rejectedEntryIds: string[];
};
type RedactedIdentifierAuthenticationDecision = {
  evaluated: boolean;
  affectedMatch: boolean;
};
type RedactedIngressAllowlistFacts = {
  configured: boolean;
  matched: boolean;
  reasonCode: IngressReasonCode;
  matchedEntryIds: string[];
  invalidEntryCount: number;
  disabledEntryCount: number;
  accessGroups: ResolvedIngressAllowlist["accessGroups"];
};
type RouteGateState = "not-configured" | "matched" | "not-matched" | "disabled" | "lookup-failed";
/** How a matched route affects sender allowlist evaluation. */
type RouteSenderPolicy = "inherit" | "replace" | "deny-when-empty";
/** Source list used when a route sender policy contributes sender entries. */
type RouteSenderAllowlistSource = "effective-dm" | "effective-group";
type RouteGateFacts = {
  id: string;
  kind: "route" | "routeSender" | "membership" | "ownerAllowlist" | "nestedAllowlist";
  gate: RouteGateState;
  effect: "allow" | "block-dispatch" | "ignore";
  precedence: number;
  senderPolicy: RouteSenderPolicy;
  senderAllowFrom?: Array<string | number>;
  senderAllowFromSource?: RouteSenderAllowlistSource;
  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: "direct" | "group" | "channel";
    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: "pairing" | "allowlist" | "open" | "disabled";
  groupPolicy: "allowlist" | "open" | "disabled";
  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 IngressGatePhase = "route" | "sender" | "command" | "event" | "activation";
type IngressGateKind = "route" | "routeSender" | "dmSender" | "groupSender" | "membership" | "ownerAllowlist" | "nestedAllowlist" | "command" | "event" | "mention";
type IngressGateEffect = "allow" | "block-dispatch" | "block-command" | "skip" | "observe" | "ignore";
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: IngressGatePhase;
  kind: IngressGateKind;
  effect: IngressGateEffect;
  allowed: boolean;
  reasonCode: IngressReasonCode;
  match?: RedactedIngressMatch;
  allowlist?: RedactedIngressAllowlistFacts;
  identifierAuthentication?: RedactedIdentifierAuthenticationDecision;
  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: "direct" | "group" | "channel";
  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
/** Describes one identity field used for stable ids or platform-specific aliases. */
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;
  /** Normalizes configured allowlist entries for this identity field. */
  normalizeEntry?: (value: string) => string | null | undefined;
  /** Normalizes inbound subject values for this identity field. */
  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";
};
/** Named alias field such as email, phone, UUID, room id, or platform user id. */
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: "dm" | "group" | "route" | "command";
  }) => boolean | undefined;
  /** Generates stable redacted entry ids for diagnostics. */
  resolveEntryId?: (params: {
    entry: string;
    entryIndex: number;
    fieldKey: string;
    fieldIndex: number;
  }) => string;
};
/** Convenience input for defining a stable identity descriptor with optional aliases. */
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"];
};
/** Raw sender identity passed by a plugin for one inbound event. */
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>;
};
/** Minimal config subset consumed by the ingress resolver. */
type ChannelIngressConfigInput = {
  /** Static or dynamic access group definitions referenced by allowlist entries. */
  accessGroups?: ChannelIngressStateInput["accessGroups"];
} | null;
/** Command gate input for control-command authorization. */
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;
};
/** Preset form for command gates accepted by `createChannelIngressResolver`. */
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;
};
/** Preset form for event gates accepted by `createChannelIngressResolver`. */
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"];
  /** Whether this route policy is configured. */
  configured?: boolean;
  /** Whether the inbound event matched this route. */
  matched?: boolean;
  /** Whether this route admits the inbound event. */
  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"];
  /** Route-specific sender allowlist entries. */
  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>;
/** Complete input for resolving one inbound channel message or event. */
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 descriptor that normalizes sender and allowlist material. */
  identity: ChannelIngressIdentityDescriptor;
  /** Inbound sender identity for this event. */
  subject: ChannelIngressIdentitySubjectInput;
  /** Conversation classification and id. */
  conversation: ChannelIngressStateInput["conversation"];
  /** Event auth mode and pairing/origin-subject facts. */
  event: ChannelIngressEventInput;
  /** Exact finalized host context this result may enter; omit for decision-only checks. */
  contextBinding?: ChannelIngressContextBinding;
  /** Sender, command, event, route, and activation policy. */
  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[];
  /** Resolver for dynamic access groups. */
  resolveAccessGroupMembership?: ChannelIngressAccessGroupMembershipResolver;
  /** Concrete sender entry appended to effective allowlists when an access group matched. */
  accessGroupMatchedAllowFromEntry?: string | number | null;
  /** Records whether a provider-specific missing-config fallback was applied. */
  providerMissingFallbackApplied?: boolean;
  /** Mention or activation facts for activation gates. */
  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"];
  /** Default group allowlist fallback behavior. */
  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"];
};
/** Per-message input for a resolver created by `createChannelIngressResolver`. */
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?: ChannelIngressEventInput | ChannelIngressEventPresetInput;
  /** DM policy override for this event. */
  dmPolicy?: ChannelIngressPolicyInput["dmPolicy"];
  /** Group policy override for this event. */
  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?: ChannelMessageIngressCommandInput | ChannelIngressCommandPresetInput | false;
};
/** Reusable high-level ingress resolver for message, command, and event surfaces. */
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>;
};
/** One-shot helper input using a simple stable identity descriptor. */
type ResolveStableChannelMessageIngressParams = Omit<CreateChannelIngressResolverParams, "identity"> & ChannelIngressResolverMessageParams & {
  identity?: StableChannelIngressIdentityParams;
};
/** Sender/conversation projection consumed by channel handlers. */
type ChannelIngressSenderAccess = {
  /** True when the sender gate admits the event. */
  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[];
  /** Whether provider-specific fallback behavior was applied. */
  providerMissingFallbackApplied: boolean;
};
/** Command projection consumed by channel command/control handlers. */
type ChannelIngressCommandAccess = {
  /** True when a command gate was requested for this event. */
  requested: boolean;
  /** True when the command gate authorizes this sender. */
  authorized: boolean;
  /** True when an unauthorized control command should be blocked. */
  shouldBlockControlCommand: boolean;
  /** Command gate reason when present, otherwise decisive ingress reason. */
  reasonCode: IngressReasonCode;
  /** Command gate from the access graph, when one ran. */
  gate?: AccessGraphGate;
};
/** Route projection consumed by room/thread/topic handlers. */
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;
};
/** Activation/mention projection consumed by group handlers. */
type ChannelIngressActivationAccess = {
  /** True when an activation gate ran. */
  ran: boolean;
  /** True when activation admits the event. */
  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;
};
/** Full ingress result returned by runtime resolvers. */
type ResolvedChannelMessageIngress = {
  /** Redacted normalized state used as input to the decision engine. */
  state: ChannelIngressState;
  /** Ordered access graph plus final admission decision. */
  ingress: ChannelIngressDecision;
  /** Sender/conversation projection. */
  senderAccess: ChannelIngressSenderAccess;
  /** Route projection. */
  routeAccess: ChannelIngressRouteAccess;
  /** Command projection. */
  commandAccess: ChannelIngressCommandAccess;
  /** Activation/mention projection. */
  activationAccess: ChannelIngressActivationAccess;
};
//#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/agents/utility-model.d.ts
/**
 * The utility model ref to use for the agent, or undefined when utility
 * routing is disabled or no default exists. Callers with a session-specific
 * selection pass both primary fields so automatic routing keeps that session's
 * provider and auth owner.
 */
declare function resolveUtilityModelRefForAgent(params: {
  cfg: OpenClawConfig;
  agentId: string;
  /** Pass when the caller already resolved the primary provider. */
  primaryProvider?: string;
  /** Pass with primaryProvider to carry a session-specific auth profile. */
  primaryModelRef?: string;
  metadataSnapshot?: Pick<PluginMetadataSnapshot, "plugins">;
}): string | undefined;
//#endregion
//#region src/gateway/chat-attachments.d.ts
type ChatAttachment = {
  type?: string;
  mimeType?: string;
  fileName?: string;
  origin?: MediaFact["origin"];
  content?: unknown;
  sizeBytes?: number;
  durationMs?: number;
  width?: number;
  height?: number;
};
//#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;
  }) => string | undefined;
  read: (params: {
    agentId: string;
    sessionKey: string;
    signal?: AbortSignal;
  }) => Promise<SessionCompanionContextReadResult>;
};
//#endregion
//#region src/infra/agent-events.d.ts
/** Stream name for agent events delivered to gateway listeners and plugin host hooks. */
type AgentEventStream = "lifecycle" | "tool" | "assistant" | "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>;
  /** 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;
};
/** Subscribes to sequenced agent events; returns an unsubscribe callback. */
declare function onAgentEvent(listener: (evt: AgentEventPayload) => void): () => void;
//#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 = {
  handleEvent: (event: SessionObserverEvent) => void;
  setConnectionVisibility: (connId: string, visible: boolean) => void;
  removeConnection: (connId: string) => void;
  getCompanionSnapshot: (sessionKey: string, agentId?: string) => SessionObserverCompanionSnapshot;
  dispose: () => void;
};
//#endregion
//#region src/gateway/session-companion-prompt.d.ts
type SessionCompanionPromptMessage = {
  role: "user" | "assistant";
  content: string;
  ts: number;
};
//#endregion
//#region src/gateway/session-companion-ask.d.ts
type SessionCompanionRunParams = {
  cfg: OpenClawConfig;
  agentId: string;
  modelRef: string;
  sessionKey: string;
  workspaceDir: string;
  systemPrompt: string;
  messages: SessionCompanionPromptMessage[];
  images?: ImageContent$1[];
  operatorAuthority?: AdmittedRunOperatorAuthority;
  assertSourceCurrent?: () => void;
  assertInputCurrent?: () => void;
  signal: AbortSignal;
};
type SessionCompanionAskDeps = {
  getConfig: () => OpenClawConfig;
  sessionObserver: {
    getCompanionSnapshot: (sessionKey: string, agentId?: string) => SessionObserverCompanionSnapshot;
  };
  resolveUtilityModelRef?: typeof resolveUtilityModelRefForAgent;
  contextReader: SessionCompanionContextReader;
  run?: (params: SessionCompanionRunParams) => Promise<string>;
  now?: () => number;
};
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[];
    connId: string;
    operatorAuthority?: AdmittedRunOperatorAuthority;
    assertSourceCurrent?: () => void;
    assertInputCurrent?: () => void;
    signal?: AbortSignal;
  }) => Promise<{
    answer: string;
    ts: number;
  }>;
  cancel(sessionKey: string, agentId: string, cancellation: Extract<SessionCompanionCancellationKind, "backing-session-revoked" | "explicit-reset">): void;
  dispose(): void;
};
//#endregion
//#region src/gateway/session-companion.d.ts
type SessionCompanionTarget = {
  sessionKey: string;
  agentId: string;
};
type SessionCompanionService = {
  ask: ReturnType<typeof createSessionCompanionAskRuntime>["ask"];
  state: (target: SessionCompanionTarget) => SessionsCompanionStateResult;
  reset: (target: SessionCompanionTarget) => void;
  dispose: () => void;
};
//#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;
  /** Inbound message context whose stable metadata is derived and persisted. */
  ctx: MsgContext;
  /** Group routing resolution for group-owned session keys. */
  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;
};
type UpdateSessionLastRouteParams = Omit<RecordInboundSessionMetaParams, "ctx"> & {
  /** Account owning the delivery route when the channel is multi-account. */
  accountId?: string;
  /** Delivery channel id persisted as the last route channel. */
  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;
  /** Canonical channel route persisted as the session route slot. */
  route?: ChannelRouteRef;
  /** Thread/topic id for the delivery route, when the transport has one. */
  threadId?: string | number;
  /** Delivery target persisted as the last route recipient. */
  to?: string;
};
/** Runtime hook for reading a session store entry timestamp. */
type ReadSessionUpdatedAt = (params: {
  storePath: string;
  sessionKey: string;
}) => number | undefined;
type RecordSessionMetaFromInbound = (params: RecordInboundSessionMetaParams) => Promise<SessionEntry$1 | null>;
type UpdateLastRoute = (params: UpdateSessionLastRouteParams) => Promise<SessionEntry$1 | null>;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-contract.d.ts
type SessionTranscriptContextVersion = {
  generation: string | null;
  rawSeq: number | null;
  updatedAt: number | null;
};
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;
};
type TranscriptAppendRefusal = {
  actualSessionIdHash: string;
  agentIdHash: string;
  code: "session-rebound";
  expectedSessionIdHash: string;
  sessionKeyHash: string;
} | {
  agentIdHash: string;
  code: "session-entry-missing";
  expectedSessionIdHash: string;
  sessionKeyHash: string;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-scope.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 ResolvedTranscriptReadScope = ResolvedSqliteReadScope & {
  sessionId: string;
};
//#endregion
//#region src/agents/sessions/session-manager-types.d.ts
interface SessionHeader {
  type: "session";
  version?: number;
  id: string;
  timestamp: string;
  cwd: string;
  parentSession?: 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";
}
interface SessionMessageEntry extends SessionEntryBase {
  type: "message";
  message: AgentMessage;
}
interface ThinkingLevelChangeEntry extends SessionEntryBase {
  type: "thinking_level_change";
  thinkingLevel: string;
}
interface ModelChangeEntry extends SessionEntryBase {
  type: "model_change";
  provider: string;
  modelId: string;
}
interface CompactionEntry<T = unknown> extends SessionEntryBase {
  type: "compaction";
  __openclaw?: {
    runId?: string;
    itemId?: string;
  };
  summary: string;
  firstKeptEntryId: string;
  tokensBefore: number;
  /** Context estimate after compaction, retained with its ordinary transcript marker. */
  tokensAfter?: number;
  /** Extension-specific data, such as artifact indexes or version markers. */
  details?: T;
  /** True for extension-generated compaction entries. */
  fromHook?: boolean;
}
type ResetReason = "new" | "reset" | "idle" | "daily" | "cron-stale";
interface ResetEntry extends SessionEntryBase {
  type: "reset";
  reason: ResetReason;
  firstKeptEntryId?: string;
}
interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
  type: "branch_summary";
  fromId: string;
  summary: string;
  /** Extension-specific data that is not sent to the model. */
  details?: T;
  /** True for extension-generated branch summaries. */
  fromHook?: boolean;
}
/** Extension state that is persisted but excluded from model context. */
interface CustomEntry<T = unknown> extends SessionEntryBase {
  type: "custom";
  customType: string;
  data?: T;
}
interface LabelEntry extends SessionEntryBase {
  type: "label";
  targetId: string;
  label: string | undefined;
}
interface SessionInfoEntry extends SessionEntryBase {
  type: "session_info";
  name?: string;
}
/** Extension message that participates in model context. */
interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
  type: "custom_message";
  customType: string;
  content: string | (TextContent | ImageContent$1)[];
  details?: T;
  display: boolean;
}
type SessionEntry = SessionMessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | ResetEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry;
type FileEntry = SessionHeader | SessionEntry;
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;
  children: SessionTreeNode[];
  label?: string;
  labelTimestamp?: string;
}
interface SessionContext {
  messages: AgentMessage[];
  thinkingLevel: string;
  model: {
    provider: string;
    modelId: string;
  } | null;
}
type PreservedOpaqueFileEntry = {
  index: number;
  record: unknown;
};
type SessionLeafControl = {
  type: "leaf";
  id: string;
  parentId: string | null;
  timestamp: string;
  targetId: string | null;
  appendParentId?: string | null;
  appendMode?: "side";
};
//#endregion
//#region src/config/sessions/transcript-target-binding.d.ts
type StorageEnvironment = Readonly<SqliteWorkerStateContext["environment"]>;
type SessionTranscriptTargetBinding = SessionTranscriptRuntimeTarget & {
  env?: StorageEnvironment;
};
//#endregion
//#region src/config/sessions/transcript-write-context.d.ts
type SessionTranscriptWriterFence = Readonly<{
  expectedLifecycleRevision: string | undefined;
  expectedWriterRunId: string;
}>;
//#endregion
//#region src/config/sessions/session-accessor.sqlite-initial-entry.d.ts
type InitialSessionEntryCommit = {
  owned: boolean;
  fence?: SessionTranscriptWriterFence;
  identity?: {
    previous: Map<string, InternalSessionEntry>;
    current: Map<string, InternalSessionEntry>;
  };
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-read.d.ts
/** Pair loaded bytes with the watermark that also fences opaque navigation edits. */
declare function loadTranscriptReadSnapshotSync(scope: SessionTranscriptReadScope, options?: {
  readOnly?: boolean;
  resolvedScope?: ResolvedTranscriptReadScope;
}): {
  events: TranscriptEvent[];
  version: SessionTranscriptContextVersion;
};
//#endregion
//#region src/config/sessions/transcript-payload.d.ts
type TranscriptPayloadRecord = {
  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-transcript-message-append.d.ts
type PreparedTranscriptMessageAppend<TMessage> = {
  messageJson: string;
  persistedMessage: TMessage;
  physicalPayload?: PreparedTranscriptPayload;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-transcript-write-snapshot.d.ts
type TranscriptWriteSnapshot<T> = {
  result: T;
  lifecycleRevision?: string;
  before: SessionTranscriptContextVersion;
  after: SessionTranscriptContextVersion;
};
type TranscriptWriteViewGuard = {
  assertCurrent: () => void;
  onPendingTransaction: (database: DatabaseSync) => void;
};
//#endregion
//#region src/config/sessions/session-accessor.sqlite-transcript-write.d.ts
type TranscriptMessageWriteSnapshot<TMessage> = TranscriptWriteSnapshot<TranscriptMessageAppendResult<TMessage> | undefined> & {
  visibleTail: {
    entryId: string | null;
    generation: string | null;
  };
};
type TranscriptEventAppendResult = {
  appended: false;
} | {
  appended: true;
  effectiveParentId?: string | null;
};
declare function appendTranscriptEventSnapshotSync(scope: SessionTranscriptWriteScope, event: TranscriptEvent, options?: TranscriptEventAppendOptions, projection?: {
  scheduleProjectionReconcile: false;
  onProjectionReconcileNeeded: () => void;
}, view?: TranscriptWriteViewGuard): Result$1<TranscriptWriteSnapshot<TranscriptEventAppendResult>, TranscriptAppendRefusal>;
declare function appendTranscriptMessageSnapshotSync<TMessage>(scope: SessionTranscriptWriteScope, options: TranscriptMessageAppendOptions<TMessage>, preparedMessage?: PreparedTranscriptMessageAppend<TMessage>, workerOptions?: {
  messageAlreadyRedacted?: true;
  scheduleProjectionReconcile?: boolean;
  onProjectionReconcileNeeded?: () => void;
}, view?: TranscriptWriteViewGuard): Result$1<TranscriptMessageWriteSnapshot<TMessage>, TranscriptAppendRefusal>;
//#endregion
//#region packages/agent-core/src/harness/types.d.ts
interface FileOperations {
  read: Set<string>;
  written: Set<string>;
  edited: Set<string>;
}
//#endregion
//#region packages/agent-core/src/harness/compaction/compaction.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;
}
/** 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;
  /** Estimated context tokens before compaction. */
  tokensBefore: number;
  /** Optional implementation-specific details stored with the compaction entry. */
  details?: T;
}
/** Compaction thresholds and retention settings. */
interface CompactionSettings$1 {
  /** 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;
}
/** Prepared inputs for a compaction run. */
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[];
  /** Whether compaction splits a turn. */
  isSplitTurn: boolean;
  /** Bounded request that the run owner will resume after compaction. */
  latestUnresolvedUserRequest?: string;
  /** Estimated context tokens before compaction. */
  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 used to prepare compaction. */
  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 last line was partially truncated (only for tail truncation edge case) */
  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-model-context.d.ts
type SessionModelContextLimits = {
  maxBytes: number;
  maxEvents: number;
  /** Detached model views may omit result bodies; evidence and fork readers remain strict. */
  toolResultOverflow?: "omit";
};
//#endregion
//#region src/agents/agent-scope.d.ts
type ModelFallbackAvailability = {
  kind: "active";
  models: string[];
  source: "explicit" | "inherited";
} | {
  kind: "none_configured";
  source: "explicit" | "inherited";
} | {
  kind: "disabled_by_model_override";
} | {
  kind: "disabled_by_model_selection_lock";
};
//#endregion
//#region src/config/sessions/paths.d.ts
/** 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/sessions/session-accessor.sqlite-active-context.d.ts
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[];
  serializedBytes: number;
  totalEvents: number;
  transcriptMutationAt: number | null;
  truncated: boolean;
};
//#endregion
//#region src/agents/sessions/session-manager-view-types.d.ts
type SessionManagerPersistenceTarget = SessionTranscriptTargetBinding;
type SessionManagerBoundedContextLimits = {
  maxBytes: number;
  maxEvents: number;
};
type PreparedSessionTranscriptReload = PreparedSessionTranscriptHydration;
type SessionManagerBoundedContext = Pick<SessionTranscriptBoundedActiveContext, "activeLeafEntryId" | "version" | "opaqueParents" | "parents" | "firstKeptRanges" | "persistedSuffixStartSeq" | "boundaryCount" | "transcriptMutationAt"> & {
  limits: SessionManagerBoundedContextLimits;
};
//#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;
type CurrentTurnReplayWitness = {
  anchor: TranscriptEntryAnchor;
  version: SessionTranscriptContextVersion;
};
//#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["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;
  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
declare class SessionManagerCore extends SessionEntryNavigation<SessionEntry> {
  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 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, transcriptMutationAt?: number | null, version?: SessionTranscriptContextVersion);
  /** @deprecated Runtime callers should await setSessionTargetAsync. */
  setSessionTarget(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;
  /** 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 setLoadedSessionTarget(target: SessionManagerPersistenceTarget | undefined, entries: readonly unknown[], bounded?: Pick<SessionTranscriptBoundedActiveContext, "activeLeafEntryId" | "version" | "opaqueParents" | "parents" | "firstKeptRanges">, 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(copy?: boolean): {
    sessionId: string;
    transcriptVersion: SessionTranscriptContextVersion | undefined;
    persistenceHeaderPending: boolean;
    migrated: boolean;
    fileEntries: FileEntry[];
    opaqueFileEntries: PreservedOpaqueFileEntry[];
    byId: Map<string, SessionEntry>;
    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>;
    boundedContextIncomplete: boolean;
    boundedContextLimits: SessionManagerBoundedContextLimits | undefined;
    persistedBoundaryCount: number | undefined;
    persistedSuffixStartSeq: number | undefined;
    transcriptMutationAt: number | null | undefined;
    leafId: string | null;
    appendParentId: string | null;
    appendMode: "side" | undefined;
    pendingDeliberateAppend: boolean;
  };
  /** @deprecated Runtime callers should await reloadPersistedTranscriptAsync. */
  reloadPersistedTranscript(): 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;
  }): void;
  newSession(options?: NewSessionOptions): string | undefined;
  private initializeSession;
  protected buildIndex(): void;
  protected normalizeEntryParent(entry: SessionEntry): SessionEntry;
  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[];
  getLabel(id: string): string | undefined;
  getBoundaryCount(): number;
  getHeader(): SessionHeader | null;
  getEntries(): SessionEntry[];
  getTree(): SessionTreeNode[];
  getLeafId(): string | null;
  getLeafEntry(): SessionEntry | undefined;
  getEntry(id: string): SessionEntry | undefined;
  getAppendParentId(): string | null;
  getAppendMode(): "side" | undefined;
  protected getPersistedFileEntries(leafAppendParentId?: string | null, leafAppendMode?: "side"): unknown[];
  getPersistedEntries(): unknown[];
  clearPreservedOpaqueFileEntries(): void;
  protected invalidateTranscriptView(error: Error): void;
  protected assertTranscriptViewAvailable(): void;
  getBranch(fromId?: string): SessionEntry[];
  isPersisted(): boolean;
  getCwd(): string;
  getSessionId(): string;
  getSessionTarget(): SessionManagerPersistenceTarget | undefined;
}
//#endregion
//#region src/agents/sessions/session-manager-metadata.worker.d.ts
type MetadataTarget = Omit<SessionTranscriptWriteScope, "env"> & SessionTranscriptRuntimeTarget;
type SessionMetadataOperations = {
  "session.transcript.appendMessage": {
    input: {
      scope: MetadataTarget;
      message: CustomMessage;
      cwd: string;
    };
    output: {
      snapshot: ReturnType<typeof appendTranscriptMessageSnapshotSync<CustomMessage>>;
      projectionNeedsReconcile: boolean;
    };
  };
  "session.metadata.initialize": {
    input: {
      scope: MetadataTarget;
      entry: InternalSessionEntry;
      initialWriterRunId?: string;
    };
    output: InitialSessionEntryCommit;
  };
  "session.metadata.append": {
    input: {
      scope: MetadataTarget;
      event: SessionHeader | ModelChangeEntry | ThinkingLevelChangeEntry | SessionMessageEntry;
      message?: {
        prepared: PreparedTranscriptMessageAppend<SessionMessageEntry["message"]>;
        cwd: string;
        validateTurn: boolean;
        idempotencyLookup?: "scan" | "scan-assistant" | "caller-checked";
      };
      options: Pick<NonNullable<Parameters<typeof appendTranscriptEventSnapshotSync>[2]>, "appendIntent" | "expectedMutationAt">;
      view?: {
        loadedVersion?: SessionTranscriptContextVersion;
        limits?: SessionManagerBoundedContextLimits;
        admission?: UserTurnTranscriptAdmissionReceipt;
      };
    };
    output: {
      snapshot: Result$1<TranscriptWriteSnapshot<TranscriptEventAppendResult | TranscriptMessageAppendResult<SessionMessageEntry["message"]> | undefined>, TranscriptAppendRefusal>;
      projectionNeedsReconcile: boolean;
      reload?: Result$1<PreparedSessionTranscriptReload, 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/agents/sessions/session-manager-write-admission.d.ts
type SessionManagerWriteAdmission = {
  database: OpenClawAgentDatabase;
  options: OpenClawAgentDatabaseOptions;
};
//#endregion
//#region src/agents/sessions/session-manager-persistence.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;
};
type PersistRecordOptions = AppendPersistenceOptions & {
  /** Retry fence captured from the durable snapshot that passed validation. */
  expectedMutationAt?: number | null;
};
declare class SessionManagerPersistence extends SessionManagerCore {
  #private;
  protected retainTranscriptWriter(): void;
  protected assertTranscriptWriteActive(): void;
  protected hasNewerPublishedTranscriptView(version: SessionTranscriptContextVersion): boolean;
  protected persistWorkerRecord(entry: ModelChangeEntry | ThinkingLevelChangeEntry | SessionMessageEntry, appendIntent: "active-branch" | undefined, writeAdmission: SessionManagerWriteAdmission, message?: NonNullable<SessionMetadataWorkerOperations["session.metadata.append"]["input"]["message"]>): Promise<PersistWorkerRecordResult>;
  protected persistRecord(entry: unknown, options?: PersistRecordOptions, preparedMessage?: PreparedTranscriptMessageAppend<AgentMessage>): PersistRecordResult;
  persist(entry: SessionEntry, options?: PersistRecordOptions): PersistRecordResult;
  private persistSqliteRecord;
}
//#endregion
//#region src/agents/sessions/session-manager-suffix-persistence.d.ts
declare class SessionManagerSuffixPersistence extends SessionManagerPersistence {
  removeTrailingEntries(predicate: (entry: SessionEntry) => boolean, options?: {
    preserveTrailing?: (entry: SessionEntry) => boolean;
  }): number;
}
//#endregion
//#region src/agents/sessions/session-manager-entries.d.ts
declare class SessionManagerEntries extends SessionManagerSuffixPersistence {
  protected appendEntry<T extends SessionEntry>(entry: T, options?: AppendPersistenceOptions): {
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  protected adoptWorkerCommittedEntry<T extends SessionEntry>(entry: T, committed: PersistWorkerRecordResult, admittedUserId?: string): {
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
    viewWasSuperseded?: true;
  };
  protected adoptPersistedEntry<T extends SessionEntry>(canonicalEntry: T, persistenceResult: PersistRecordResult, admittedUserId?: string, preparedReload?: PreparedSessionTranscriptReload): {
    entry: T;
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  private createTranscriptMutationConflictError;
  resolveCurrentTurnEntryId(isInterruptedTail?: (entry: SessionEntry) => boolean, options?: {
    includeOmittedCustomMessages?: boolean;
  }): string | null;
  [sessionManagerPrepareCurrentTurnReplay](isInterruptedTail: (entry: SessionEntry) => boolean, matchesUser: (entry: SessionEntry | undefined) => boolean, signal?: AbortSignal): Promise<CurrentTurnReplayWitness | undefined>;
  appendMessage(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): string;
  appendMessageAsync(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): Promise<string | undefined>;
  appendMessageWithTranscriptAnchorAsync(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): Promise<ReturnType<SessionManagerEntries["appendMessageWithTranscriptAnchor"]> & {
    viewWasSuperseded?: true;
  }>;
  appendMessageWithTranscriptAnchor(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): {
    entryId: string;
    message: SessionMessageEntry["message"];
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  appendCompaction(summary: string, firstKeptEntryId: string, tokensBefore: number, details?: unknown, fromHook?: boolean, metadata?: CompactionEntry["__openclaw"], tokensAfter?: number): string;
  appendResetBoundary(reason: ResetReason, firstKeptEntryId?: string): string;
  appendCustomEntry(customType: string, data?: unknown): string;
  appendSessionInfo(name: string): string;
  appendCustomMessageEntry(customType: string, content: string | (TextContent | ImageContent$1)[], display: boolean, details?: unknown): string;
  appendLeafControl(params: {
    targetId: string | null;
    appendParentId: string | null;
    appendMode?: "side";
  }): SessionLeafControl;
  appendLabelChange(targetId: string, label: string | undefined): string;
  buildSessionContext(): SessionContext;
  branch(branchFromId: string): void;
  resetLeaf(): void;
  branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string;
}
//#endregion
//#region src/agents/sessions/session-manager-metadata.d.ts
declare class SessionManagerMetadata extends SessionManagerEntries {
  private appendMetadataEntry;
  private publishMetadataCommit;
  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 {
  private collectBranchedSessionPath;
  createBranchedSession(leafId: string): Promise<string | undefined>;
}
//#endregion
//#region src/agents/sessions/session-manager.d.ts
declare class SessionManager extends SessionManagerBranching {
  private constructor();
  [sessionManagerReadInitialContext](): Promise<SessionContext>;
  /** No buffered writes remain here; asynchronous metadata methods own their settlement. */
  flushPendingPersistence(): void;
  appendMessage(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): string;
  appendMessageWithTranscriptAnchor(message: Message | CustomMessage | BashExecutionMessage, options?: AppendPersistenceOptions): {
    entryId: string;
    message: SessionMessageEntry["message"];
    anchor?: TranscriptEntryAnchor;
    lifecycleRevision?: string;
    appended: boolean;
  };
  /** Prepare off-store; publish the suffix and adopt memory at the same outer commit edge. */
  prepareTranscriptRewrite(): {
    sessionManager: SessionManager;
    commit: (rewrittenEntryIds: ReadonlyMap<string, string>) => void;
  };
  /** Opens an existing store off-thread; empty transcripts keep lazy header initialization. */
  static openAsync(target: SessionTranscriptRuntimeTarget, cwdOverride?: string, contextLimits?: SessionManagerBoundedContextLimits, signal?: AbortSignal): Promise<SessionManager>;
  /** @deprecated Runtime callers should await openAsync. */
  static open(target: SessionTranscriptRuntimeTarget, cwdOverride?: string, contextLimits?: SessionManagerBoundedContextLimits): SessionManager;
  /** @deprecated Runtime callers should await openBoundedAsync. */
  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 openBoundedAsync(target: SessionTranscriptRuntimeTarget, options: SessionManagerBoundedContextLimits & {
    cwd?: string;
    onTruncated?: () => void;
    signal?: AbortSignal;
  }): Promise<SessionManager>;
  /** Detach the prepared bounded branch without retaining database custody. */
  static openDetachedBoundedAsync(target: SessionTranscriptRuntimeTarget, options: Parameters<typeof SessionManager.openBoundedAsync>[1]): Promise<SessionManager>;
  /** @deprecated Runtime callers should await openDetachedBoundedAsync. */
  static openDetachedBounded(target: SessionTranscriptRuntimeTarget, options: Parameters<typeof SessionManager.openBounded>[1]): SessionManager;
  /** Detached model view: selected payloads plus lightweight ancestry, never raw replay evidence. */
  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>;
  private static fromSelectedEntries;
  /** Synchronously consumes full-fidelity context; its iterator closes with the read snapshot. */
  static readSessionContext<T>(target: SessionTranscriptRuntimeTarget, read: (messages: Iterable<AgentMessage>, header: unknown) => T, options?: {
    admission?: UserTurnTranscriptAdmissionReceipt;
  }): T;
  /**
   * @deprecated Retained for the v2026.9.5 plugin SDK contract.
   * Removal requires a versioned SDK replacement and plugin migration window.
   */
  static appendMessageToTranscript(target: SessionTranscriptRuntimeTarget, message: Message | CustomMessage | BashExecutionMessage, options?: Pick<AppendPersistenceOptions, "config">): string;
  static inMemory(cwd?: string): SessionManager;
  static fromEntries(entries: readonly unknown[], cwdOverride?: string): SessionManager;
}
type ReadonlySessionManager = Pick<SessionManager, "getCwd" | "getSessionId" | "getSessionTarget" | "getLeafId" | "getAppendParentId" | "getAppendMode" | "getLeafEntry" | "getEntry" | "getLabel" | "getBranch" | "getHeader" | "getEntries" | "getTree" | "getSessionName">;
//#endregion
//#region src/config/sessions/transcript.d.ts
type SessionTranscriptDeliveryMirror = {
  kind: "channel-final";
  sourceMessageId?: string;
} | {
  kind: "channel-final-suppressed";
  reason: "stale-foreground";
  sourceMessageId?: string;
};
//#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$1;
}
/** 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 SessionUpstreamJsonValue = null | boolean | number | string | SessionUpstreamJsonValue[] | {
  [key: string]: SessionUpstreamJsonValue;
};
type SessionUpstreamKind = "claude-cli" | "codex-app-server" | "opencode-cli" | "pi-cli";
type SessionUpstreamProbe = {
  sessionKey: string;
  agentId: string;
  threadId: string;
  hostId: string;
  upstreamKind: SessionUpstreamKind;
  upstreamRef: SessionUpstreamJsonValue;
  marker: SessionUpstreamJsonValue | null;
  ownRecentUserTexts: string[];
};
type SessionUpstreamActivity = {
  kind: "activity";
  sessionKey: string;
  humanTurns: number;
  nextMarker: SessionUpstreamJsonValue;
  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: SessionUpstreamJsonValue;
    marker: SessionUpstreamJsonValue;
  };
};
type SessionCatalogProvider = {
  id: string;
  label: string;
  /** Gateway artifacts are shared with all operators; remote publications follow session-viewing roles. */
  audience?: "gateway-operators" | "session-viewers";
  /** 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>;
};
//#endregion
//#region src/agents/usage.d.ts
type ContextUsage$1 = NonNullable<Usage["contextUsage"]>;
/** Normalized token counts used by runtime accounting. */
type NormalizedUsage = {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  cacheWrite1h?: number;
  contextUsage?: ContextUsage$1;
  reasoningTokens?: number;
  total?: number;
  cost?: Pick<Usage["cost"], "total" | "totalOrigin"> & Partial<Pick<Usage["cost"], "input" | "output" | "cacheRead" | "cacheWrite">>;
};
//#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>(payload: T) => T;
  /** @internal Transfer this waiting reply's existing progress card to its current task owner. */
  adoptProgressContinuation?: ProgressContinuationCapability["adopt"];
};
type ReplyDispatchBeforeDeliver = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo) => Promise<ReplyPayload | null> | ReplyPayload | 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) => NormalizeReplyOutcome<ReplyPayload>;
  sendToolResult: (payload: ReplyPayload) => boolean;
  sendBlockReply: (payload: ReplyPayload) => boolean;
  sendFinalReply: (payload: ReplyPayload) => 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 Remove in the next Plugin SDK major; retains admission-time counts. */
  getQueuedCounts: () => Record<ReplyDispatchKind, number>;
  /** @deprecated Remove in the next Plugin SDK major; derived from settled receipts. */
  getCancelledCounts?: () => Record<ReplyDispatchKind, number>;
  /** @deprecated Remove in the next Plugin SDK major; derived from settled 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/config/sessions/transcript-assistant-delivery.d.ts
/** Turn-owned display preparation; source text precedes transcript-only hook rewrites. */
type PrepareAssistantTranscriptMessage = (message: AssistantMessage$1, sourceText: string | undefined) => AssistantMessage$1;
//#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;
};
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;
  /** Session messages prepared for this run. */
  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;
};
//#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;
    /**
     * @deprecated Unresolved approvals always deny; retained for plugin API
     * compatibility. The field will be removed after one deprecation release train.
     */
    timeoutBehavior?: "allow" | "deny";
    /** 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/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;
} | {
  status: "error";
  message: string;
};
/** Event emitted after a pending conversation binding request is resolved. */
type PluginConversationBindingResolvedEvent$1 = {
  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
/** 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;
};
//#endregion
//#region src/plugins/hook-skill.types.d.ts
type PluginHookSkillProposalKind = "create" | "update";
type PluginHookSkillBundleFile = {
  path: string;
  content: string;
  encoding: "utf8" | "base64";
  sha256: string;
  sizeBytes: number;
};
type PluginHookSkillBundleSnapshot = {
  skillMd: PluginHookSkillBundleFile;
  files: PluginHookSkillBundleFile[];
  treeSha256: string;
};
type PluginHookSkillProposalEvaluateEvent = {
  /** Caller-supplied correlation metadata; not authenticated identity or authorization proof. */
  correlationId?: string;
  proposal: {
    id: string;
    kind: PluginHookSkillProposalKind;
    revision: string;
    revisionSha256: string;
    targetCurrentSha256?: string;
  };
  skill: {
    name: string;
    skillKey: string;
    description: string;
    source?: string;
  };
  candidate: PluginHookSkillBundleSnapshot;
  baseline?: PluginHookSkillBundleSnapshot;
  reason: "created" | "revised" | "manual" | "apply";
};
type PluginHookSkillEvaluationFinding = {
  ruleId: string;
  severity: "info" | "warn" | "critical";
  message: string;
  file?: string;
  line?: number;
};
type PluginHookSkillProposalEvaluateResult = {
  summary?: string;
  findings?: PluginHookSkillEvaluationFinding[];
  metrics?: Record<string, string | number | boolean>;
  /** Version of the underlying evaluator or ruleset, separate from the plugin package. */
  evaluatorVersion?: string;
  /** Bounded evaluator mode label such as `static`, `llm`, or `baseline-comparison`. */
  mode?: string;
  decision?: "pass" | "revise" | "block";
  decisionReason?: string;
};
type PluginHookSkillProposalEvaluationAttribution = {
  evaluatorId: string;
  pluginId: string;
  pluginVersion?: string;
};
type PluginHookSkillProposalEvaluationOutcome = (PluginHookSkillProposalEvaluationAttribution & {
  status: "completed";
  result: PluginHookSkillProposalEvaluateResult;
}) | (PluginHookSkillProposalEvaluationAttribution & {
  status: "skipped";
}) | (PluginHookSkillProposalEvaluationAttribution & {
  status: "error";
  error: string;
});
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;
  proposal?: {
    id: string;
    revision: string;
    revisionSha256: string;
  };
};
type PluginHookSkillProposalChangedEvent = {
  eventId: string;
  sequence: number;
  action: "created" | "revised" | "evaluation_completed" | "applied" | "rejected" | "quarantined" | "stale";
  occurredAt: string;
  correlationId?: string;
  proposal: {
    id: string;
    kind: PluginHookSkillProposalKind;
    status: "pending" | "applied" | "rejected" | "quarantined" | "stale";
    revision: string;
    revisionSha256: string;
    skillName: string;
    skillKey: string;
    skillFile: string;
    source?: string;
  };
  evaluations?: readonly PluginHookSkillProposalEvaluationOutcome[];
};
type PluginHookSkillContext = {
  workspaceDir: string;
  agentId?: 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;
};
/** Event passed to plugins before an agent turn is prepared. */
type PluginAgentTurnPrepareEvent = {
  prompt: string;
  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 = {
  prependContext?: string;
  appendContext?: string;
};
//#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/hook-types.d.ts
declare const PLUGIN_HOOK_NAMES: readonly ["before_model_resolve", "agent_turn_prepare", "before_prompt_build", "before_agent_reply", "model_call_started", "model_call_ended", "llm_input", "llm_output", "before_agent_finalize", "agent_end", "before_compaction", "after_compaction", "before_reset", "inbound_claim", "channel_pairing_requested", "message_received", "message_sending", "reply_payload_sending", "message_sent", "before_tool_call", "after_tool_call", "tool_result_persist", "before_message_write", "session_start", "session_end", "subagent_delivery_target", "subagent_spawned", "subagent_progress", "subagent_ended", "gateway_start", "gateway_stop", "heartbeat_prompt_contribution", "cron_reconciled", "cron_changed", "skill_proposal_evaluate", "skill_proposal_changed", "skill_changed", "before_dispatch", "reply_dispatch", "before_install", "before_agent_run", "resolve_exec_env"];
type PluginHookName = (typeof PLUGIN_HOOK_NAMES)[number];
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 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 PluginHookContextWindow = {
  /** Resolved effective context-token budget after model/config/agent caps. */
  contextTokenBudget?: number;
  /** Source that supplied the resolved context-token budget. */
  contextWindowSource?: PluginHookContextWindowSource;
  /** Native/configured reference window when a lower cap wins. */
  contextWindowReferenceTokens?: number;
};
type PluginHookUsage = Pick<NormalizedUsage, "input" | "output" | "cacheRead" | "cacheWrite" | "total">;
type PluginHookAgentContext = PluginHookContextWindow & {
  runId?: string;
  jobId?: string;
  trace?: DiagnosticTraceContext;
  agentId?: string;
  sessionKey?: string;
  sessionId?: string;
  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. Absent when the producer did not
   * supply a classification; absence does not establish human origin.
   */
  inputProvenance?: InputProvenance;
  /**
   * @deprecated Core does not populate cross-app sender ids. Channel plugins
   * should expose channel-specific identities by augmenting `channelContext.sender`.
   */
  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;
  /**
   * Present for before_prompt_build only. Checks this handler's result-acceptance lifetime,
   * not tool authorization or eventual model consumption. Underlying work is not cancelled.
   */
  readonly hookInvocation?: Readonly<{
    assertActive(): void;
  }>;
};
type PluginHookContextWindowSource = "model" | "modelsConfig" | "agentContextTokens" | "default";
type PluginHookBeforeAgentReplyEvent = {
  cleanedBody: string;
};
type PluginHookBeforeAgentReplyResult = {
  handled: boolean;
  reply?: ReplyPayload;
  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;
};
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 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;
  shouldSendToolSummaries: boolean;
  shouldSendFullToolDetails: boolean;
  sendPolicy: "allow" | "deny";
  isTailDispatch?: boolean;
};
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;
  onAgentRunStart?: GetReplyOptions["onAgentRunStart"];
  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, "trustedLocalMedia">;
type PluginHookReplyPayloadSendingContext = PluginHookMessageContext;
type PluginHookReplyPayloadSendingResult = {
  payload?: PluginHookReplyPayload;
  cancel?: boolean;
  reason?: string;
};
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;
};
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 PluginHookSessionContext = {
  agentId?: string;
  sessionId: string;
  sessionKey?: string;
};
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 PluginInstallRequestKind = "skill-install" | "plugin-dir" | "plugin-archive" | "plugin-file" | "plugin-npm" | "plugin-git";
type PluginInstallSourcePathKind = "file" | "directory";
type PluginInstallFinding = {
  ruleId: string;
  severity: "info" | "warn" | "critical";
  file: string;
  line: number;
  message: string;
};
type PluginHookBeforeInstallRequest = {
  kind: PluginInstallRequestKind;
  mode: "install" | "update";
  requestedSpecifier?: string;
};
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: PluginInstallRequestKind;
  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;
};
/** Event payload for the before_agent_run gate hook. */
type PluginHookBeforeAgentRunEvent = {
  /** The user's message that triggered this run. */
  prompt: string;
  /** 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;
};
/** 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 AsyncPluginHook<Event, Context, Result = void> = (event: Event, ctx: Context) => Promise<Result | void> | Result | void;
type PluginHookHandlerMap = {
  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>;
  message_received: AsyncPluginHook<PluginHookMessageReceivedEvent, PluginHookMessageContext>;
  message_sending: AsyncPluginHook<PluginHookMessageSendingEvent, PluginHookMessageContext, PluginHookMessageSendingResult>;
  message_sent: AsyncPluginHook<PluginHookMessageSentEvent, PluginHookMessageContext>;
  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_proposal_evaluate: AsyncPluginHook<PluginHookSkillProposalEvaluateEvent, PluginHookSkillContext, PluginHookSkillProposalEvaluateResult>;
  skill_proposal_changed: AsyncPluginHook<PluginHookSkillProposalChangedEvent, PluginHookSkillContext>;
  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$1<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;
  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 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. */
  surface: "session" | "tool" | "run" | "settings" | "tab" | "widget" | "link-reader";
  /** 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;
};
type PluginSessionActionContext = {
  pluginId: string;
  actionId: string;
  sessionKey?: string;
  agentId?: string;
  payload?: PluginJsonValue;
  client?: {
    connId?: string;
    scopes: string[];
  };
};
type PluginSessionActionResult = {
  ok?: true;
  result?: PluginJsonValue;
  reply?: PluginJsonValue;
  continueAgent?: boolean;
} | {
  ok: false;
  error: string;
  code?: string;
  details?: PluginJsonValue;
};
type PluginSessionActionRegistration = {
  id: string;
  description?: string;
  schema?: PluginJsonValue;
  requiredScopes?: OperatorScope[];
  handler: (ctx: PluginSessionActionContext) => PluginSessionActionResult | void | Promise<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[];
  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 PluginSessionSchedulerJobRegistration = {
  id: string;
  sessionKey: string;
  kind: string;
  description?: string;
  cleanup?: (ctx: {
    reason: PluginHostCleanupReason;
    sessionKey: string;
    jobId: string;
  }) => void | Promise<void>;
};
//#endregion
//#region src/shared/fast-mode.d.ts
type FastModeAutoProgressState = {
  offAnnounced: boolean;
  resetAnnounced: boolean;
};
//#endregion
//#region src/plugins/provider-catalog-outcome.d.ts
type ProviderCatalogOutcome = {
  provider: string;
  /** Auth profile tested by discovery; omission means provider-wide auth. */
  profileId?: string;
  /** Limits an auth rejection to catalog discovery rather than model execution. */
  rejectionScope?: "catalog";
  status: "ready" | "auth-rejected" | "unavailable";
  /** Optional successful discovery order for models already present in the catalog. */
  modelOrder?: readonly string[];
};
//#endregion
//#region src/agents/model-catalog.types.d.ts
/** Input modalities a catalog entry can advertise. */
type ModelInputType = "text" | "image" | "audio" | "video" | "document";
type ModelContextWindowOption = {
  id: string;
  label: string;
  contextWindow: number;
};
/** Normalized model metadata exposed by the agent model catalog. */
type ModelCatalogEntry = {
  /** Native catalog owner, not a physical provider route or transferable readiness fact. */
  nativeRuntime?: string;
  id: string;
  name: string;
  provider: string;
  /** Provider-owned strongest-first picker order; internal and never projected to clients. */
  providerOrder?: number;
  alias?: string;
  api?: ModelApi;
  /** Private transport provenance for route matching; never project directly to clients. */
  baseUrl?: string;
  contextWindow?: number;
  contextWindows?: ModelContextWindowOption[];
  contextWindowDefault?: string;
  contextTokens?: number;
  reasoning?: boolean;
  /** Config-authored reasoning override; internal provenance, never project to clients. */
  configuredReasoning?: boolean;
  /** Concrete runtime owner of thinking policy; internal and never project to clients. */
  thinkingPolicyProvider?: string;
  /** Provider-owned effort support for this exact physical model route. */
  thinkingLevelMap?: ThinkingLevelMap;
  input?: ModelInputType[];
  params?: Record<string, unknown>;
  compat?: ModelCompatConfig;
  mediaInput?: ModelMediaInputConfig;
  status?: ModelCatalogStatus;
  statusReason?: string;
  replaces?: string[];
  replacedBy?: string;
};
/** Logical catalog rows plus the physical variants used for route selection. */
type ModelCatalogSnapshot = {
  entries: ModelCatalogEntry[];
  routeVariants: ModelCatalogEntry[];
  /** Provider-owned outcome of each live catalog request in this generation. */
  providerOutcomes?: readonly ProviderCatalogOutcome[];
  /** Native discovery facts belong to their harness, independently of API-provider auth. */
  nativeProviderOutcomes?: Readonly<Record<string, readonly ProviderCatalogOutcome[]>>;
  /** Untagged harness observations, before API donor enrichment; each runtime owns its scope. */
  nativeHostRows?: Readonly<Record<string, readonly ModelCatalogEntry[]>>;
  /** The current acquisition failed while this published inventory remained available. */
  refreshFailed?: boolean;
  /** Provider discovery is in progress; existing rows remain usable. */
  pendingProviders?: readonly string[];
  /** Static provider-hook rows captured alongside the full lifecycle generation. */
  staticEntries?: ModelCatalogEntry[];
  /**
   * `false` only when this snapshot came from a degraded load (discovery threw,
   * static or empty fallback). Absent/`true` means authoritative — consumers that
   * destroy durable state (e.g. resetting a pinned model override) must treat only
   * an explicit `false` as degraded, so unrelated hand-built snapshots stay safe.
   */
  authoritative?: boolean;
};
//#endregion
//#region src/plugins/provider-thinking.types.d.ts
/**
 * Provider-owned thinking policy input.
 *
 * Used by shared `/think`, ACP controls, and directive parsing to ask a
 * provider whether a model supports special reasoning UX such as adaptive,
 * xhigh, max, or a binary on/off toggle.
 */
type ProviderThinkingPolicyContext = {
  provider: string;
  modelId: string;
};
type ProviderThinkingModelCompat = {
  thinkingFormat?: string;
  supportsReasoningEffort?: boolean;
  supportedReasoningEfforts?: readonly string[] | null;
  reasoningEffortMap?: Record<string, string>;
};
/**
 * Provider-owned default thinking policy input.
 *
 * `reasoning` is the merged catalog hint for the selected model when one is
 * available. Providers can use it to keep "reasoning model => low" behavior
 * without re-reading the catalog themselves.
 *
 * `compat` carries model-level request contract facts for the selected model
 * when available. Providers can use it to expose model-specific thinking
 * profiles only when the configured payload style supports them.
 */
type ProviderDefaultThinkingPolicyContext = ProviderThinkingPolicyContext & {
  /** Effective agent runtime selected for this model, when known. */
  agentRuntime?: string | null;
  /** API adapter id from the selected catalog route, when known. */
  api?: string | null;
  /** Base URL from the selected catalog route, when known. */
  baseUrl?: string | null;
  reasoning?: boolean;
  /** Thinking-to-wire mapping from the selected model route. */
  thinkingLevelMap?: ThinkingLevelMap;
  params?: Record<string, unknown>;
  compat?: ProviderThinkingModelCompat | null;
};
type ProviderThinkingLevelId = ThinkLevel;
type ProviderThinkingLevel = {
  id: ProviderThinkingLevelId;
  /**
   * Optional display label. Use this when the stored value differs from the
   * provider-facing UX, for example binary providers storing `low` but showing
   * `on`.
   */
  label?: string;
  /**
   * Relative strength used when downgrading a stored level that the selected
   * model no longer supports.
   */
  rank?: number;
};
type ProviderThinkingProfile = {
  levels: ProviderThinkingLevel[] | ReadonlyArray<ProviderThinkingLevel>;
  defaultLevel?: ProviderThinkingLevelId | null;
  /**
   * Some bundled providers have model-specific thinking contracts that are more
   * current than cached generic catalog metadata. Keep this opt-in so
   * `reasoning: false` remains authoritative for ordinary catalog entries.
   */
  preserveWhenCatalogReasoningFalse?: boolean;
};
/** Prepared provider policy ownership, without the broader Gateway registry contract. */
type ProviderThinkingRegistry = {
  providers: ReadonlyArray<{
    provider: {
      id: string;
      aliases?: string[];
      hookAliases?: string[];
      resolveThinkingProfile?: (context: ProviderDefaultThinkingPolicyContext) => ProviderThinkingProfile | null | undefined;
    };
  }>;
};
//#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/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;
};
//#endregion
//#region src/config/sessions/session-transcript-worker.types.d.ts
type PreparedSessionTranscriptHydration = {
  kind: "full";
  snapshot: ReturnType<typeof loadTranscriptReadSnapshotSync>;
} | {
  kind: "bounded";
  snapshot: SessionTranscriptBoundedActiveContext;
};
//#endregion
//#region src/gateway/session-activity-summary-state.d.ts
type ActivitySummaryTarget = {
  key: string;
  agentId: 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/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/plugins/embedding-provider-runtime-types.d.ts
/** One text chunk submitted through a provider-owned asynchronous embedding batch. */
type EmbeddingBatchChunk = {
  text: string;
};
/** Host-controlled execution parameters for an asynchronous embedding batch. */
type EmbeddingBatchOptions = {
  agentId: string;
  chunks: EmbeddingBatchChunk[];
  wait: boolean;
  concurrency: number;
  pollIntervalMs: number;
  timeoutMs: number;
  debug: (message: string, data?: Record<string, unknown>) => void;
};
/** Provider-owned asynchronous batching capability, independent of host runtime metadata. */
type EmbeddingProviderBatchRuntime = {
  /** Returns one vector per chunk in input order, or null to use host fallback. */
  batchEmbed: (options: EmbeddingBatchOptions) => Promise<number[][] | null>;
  /** Only true enables batching across dirty files; false or omission retains per-file batches. */
  sourceWideBatchEmbed?: boolean;
};
//#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;
  }>;
};
/** Per-call options passed to embedding provider calls. */
type EmbeddingProviderCallOptions = {
  signal?: AbortSignal;
  inputType?: "query" | "document" | "semantic" | "classification" | "clustering";
} & MemorySearchDeadlineControlOptions;
/** Runtime metadata returned with a created embedding provider. */
type EmbeddingProviderRuntime = {
  id: string;
  cacheKeyData?: Record<string, unknown>;
  /** Prior persisted model/cache identities that are equivalent to the current identity. */
  indexIdentityAliases?: Array<{
    model: string;
    cacheKeyData: Record<string, unknown>;
  }>;
  inlineQueryTimeoutMs?: number;
  inlineBatchTimeoutMs?: 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;
  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;
  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 src/plugins/sdk-alias.d.ts
type PluginSdkResolutionPreference = "auto" | "dist" | "src";
//#endregion
//#region src/plugins/plugin-runtime-artifact-selection.d.ts
type PluginRuntimeArtifact = {
  source: string;
  rootDir: string;
};
//#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$1;
  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;
  };
  pluginSdkResolution?: PluginSdkResolutionPreference;
  cache?: boolean;
  mode?: "full" | "validate" | "cli-metadata";
  onlyPluginIds?: 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;
  manifestRegistry?: PluginManifestRegistry;
  discovery?: PluginDiscoveryResult;
};
//#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/infra/provider-usage.types.d.ts
/** One quota window reported by a provider usage endpoint. */
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;
};
/** Aggregate model activity for the provider history window. */
type ProviderUsageModelBreakdown = Omit<ProviderUsageCostDaily, "date" | "amount"> & {
  name: string;
};
/** Aggregate provider billing category for the history window. */
type ProviderUsageCostBreakdown = {
  name: string;
  amount: number;
};
/** Provider-reported cost history and attribution for one bounded UTC window. */
type ProviderUsageCostHistory = {
  unit: string;
  periodDays: number;
  scope?: string;
  daily: ProviderUsageCostDaily[];
  models: ProviderUsageModelBreakdown[];
  categories: ProviderUsageCostBreakdown[];
};
type ProviderUsageSnapshot = {
  provider: UsageProviderId;
  displayName: string;
  windows: UsageWindow[];
  billing?: ProviderUsageBilling[];
  costHistory?: ProviderUsageCostHistory;
  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/plugin-sdk/provider-model-types.d.ts
/** Private selected-request facts; omission means the host cannot establish applicability. */
type ProviderFastModePolicyContext = {
  provider: string;
  modelId: string;
  api?: string;
  baseUrl?: string;
  authMode?: string;
  runtimeId?: string;
  modelParams?: Record<string, unknown>;
  params?: Record<string, unknown>;
  requestCapabilities: {
    endpointClass: string;
    allowsAnthropicServiceTier: boolean;
  };
};
/** A concrete provider route. Order expresses provider default, never credential precedence. */
type ProviderModelRouteAuthRequirement = "api-key" | "subscription";
type ProviderRouteOverridePresence = "none" | "present";
type ProviderModelRouteRuntimePolicy = {
  /** Agent runtime ids that can reproduce this route without losing transport behavior. */
  compatibleIds: readonly string[];
};
/** Provider-owned default for one resolved inference route; never an authored config setting. */
type ProviderToolSearchPolicyContext = {
  provider: string;
  modelId: string;
  api: string;
  baseUrl?: string;
};
//#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$1 {
  /** 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$1): 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/system-prompt.types.d.ts
type PromptMode = "full" | "minimal" | "none";
type SilentReplyPromptMode = "generic" | "none";
//#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 ProviderAuthKind = "oauth" | "api_key" | "token" | "device_code" | "custom";
type ProviderAuthSecretStorage = {
  /** 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 ProviderAuthProfile = {
  profileId: string;
  credential: AuthProfileCredential;
  /** Request host-owned SecretRef materialization at the final persistence boundary. */
  secretStorage?: ProviderAuthSecretStorage;
};
/** 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.
   */
  configPatch?: Partial<OpenClawConfig>;
  defaultModel?: string;
  notes?: string[];
  /**
   * Opt in to replace `agents.defaults.models` wholesale with the patch map.
   * Default behavior merges the map so other providers' entries survive.
   * Set only from migrations that intentionally rename/remove model keys.
   */
  replaceDefaultModels?: boolean;
};
/** Interactive auth context passed to provider login/setup methods. */
type ProviderAuthContext = {
  config: OpenClawConfig;
  /** 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;
    }>;
  };
};
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;
};
type ProviderAuthMethodNonInteractiveValidationContext = Omit<ProviderAuthMethodNonInteractiveContext, "toApiKeyCredential">;
/** 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: ProviderAuthKind;
  /** 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: ProviderAuthMethodNonInteractiveValidationContext) => 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?: Array<"text-inference" | "image-generation" | "music-generation">;
  /**
   * Optional model-allowlist prompt policy applied after this auth choice is
   * selected in configure/onboarding flows.
   *
   * Keep this UI-facing and static. Provider logic that needs runtime state
   * should stay in `run`/`runNonInteractive`.
   */
  modelAllowlist?: {
    allowedKeys?: string[];
    initialSelections?: string[];
    loadCatalog?: boolean;
    message?: string;
  };
  /**
   * Optional default-model prompt policy for this auth/setup choice.
   *
   * Use this when selecting the auth choice should still force a model picker
   * even if the choice was preseeded via CLI/configure, or when "keep current"
   * would skip required provider-owned post-selection work.
   */
  modelSelection?: {
    promptWhenAuthChoiceProvided?: boolean;
    allowKeepCurrent?: boolean;
  };
};
/** Optional model-picker metadata shown in interactive provider selection flows. */
type ProviderPluginWizardModelPicker = {
  label?: string;
  hint?: string;
  methodId?: string;
};
/** UI metadata that lets provider plugins appear in onboarding and configure flows. */
type ProviderPluginWizard = {
  setup?: ProviderPluginWizardSetup;
  modelPicker?: ProviderPluginWizardModelPicker;
};
type ProviderOAuthProfileIdRepair = {
  /**
   * Legacy OAuth profile id to migrate away from.
   *
   * When omitted, OpenClaw falls back to `<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" | "heartbeat" | "manual" | "memory" | "overflow" | "user";
};
type ProviderTransformSystemPromptContext = ProviderSystemPromptContributionContext & {
  systemPrompt: string;
};
//#endregion
//#region src/plugins/provider-catalog.types.d.ts
type ProviderCatalogOrder = "simple" | "profile" | "paired" | "late";
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;
  }) => {
    apiKey: string | undefined;
    discoveryApiKey?: string;
    mode: "api_key" | "aws-sdk" | "oauth" | "token" | "none";
    source: "env" | "profile" | "none";
    profileId?: string;
    /** Credential preparation exhausted its candidates; not an unconfigured provider. */
    preparationFailed?: boolean;
    authFlow?: string;
  };
};
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>;
};
type UnifiedModelCatalogProviderContext = ProviderCatalogContext & {
  includeLive?: boolean;
  timeoutMs?: number;
};
type UnifiedModelCatalogProviderPlugin$1 = {
  provider: string;
  kinds: readonly UnifiedModelCatalogKind[];
  staticCatalog?: (ctx: UnifiedModelCatalogProviderContext) => readonly UnifiedModelCatalogEntry[] | Promise<readonly UnifiedModelCatalogEntry[] | null | undefined> | null | undefined;
  liveCatalog?: (ctx: UnifiedModelCatalogProviderContext) => readonly UnifiedModelCatalogEntry[] | Promise<readonly UnifiedModelCatalogEntry[] | null | undefined> | null | undefined;
};
/**
 * Built-in model suppression hook context.
 *
 * @deprecated Use manifest `modelCatalog.suppressions`. Runtime suppression
 * hooks are no longer called by model resolution.
 */
type ProviderBuiltInModelSuppressionContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  modelId: string;
  baseUrl?: string;
};
type ProviderBuiltInModelSuppressionResult = {
  suppress: boolean;
  errorMessage?: string;
};
/**
 * Provider-owned "modern model" policy input.
 *
 * Live smoke/model-profile selection uses this to keep provider-specific
 * inclusion/exclusion rules out of core.
 */
type ProviderModernModelPolicyContext = {
  provider: string;
  modelId: string;
};
/**
 * Final catalog augmentation hook.
 *
 * Runs after OpenClaw loads the discovered model catalog and merges configured
 * opt-in providers. Use this for forward-compat rows or vendor-owned synthetic
 * entries that should appear in `models list` and model pickers even when the
 * upstream registry has not caught up yet.
 */
type ProviderAugmentModelCatalogContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  resolveProviderApiKey?: ProviderCatalogContext["resolveProviderApiKey"];
  entries: ModelCatalogEntry[];
};
//#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-runtime-model.types.d.ts
/**
 * Fully-resolved runtime model shape used after provider/plugin-owned
 * discovery, overrides, and compat normalization.
 */
type ProviderRuntimeModel = Omit<Model, "compat"> & {
  compat?: ModelCompatConfig;
  contextWindows?: ModelCatalogContextWindowOption[];
  contextWindowDefault?: string;
  contextTokens?: number;
  /** Host-resolved provenance for the top-level wire output cap. */
  maxTokensSource?: "configured" | "discovered";
  params?: Record<string, unknown>;
  requestTimeoutMs?: number;
  /** Provider/host-prepared tool discovery preference for this attempt; never persisted. */
  toolSearchMode?: "tools" | false;
  /** Provider-prepared default for embedded compaction; explicit compaction config wins. */
  compactionThinkingDefault?: NonNullable<ProviderThinkingProfile["defaultLevel"]>;
  mediaInput?: ModelMediaInputConfig;
};
//#endregion
//#region src/plugins/provider-replay.types.d.ts
type ProviderReplaySanitizeMode = "full" | "images-only";
type ProviderReplayToolCallIdMode = "strict" | "strict9";
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?: ProviderReplaySanitizeMode;
  sanitizeToolCallIds?: boolean;
  toolCallIdMode?: ProviderReplayToolCallIdMode;
  duplicateToolCallIdStyle?: "openai";
  preserveNativeAnthropicToolUseIds?: boolean;
  preserveSignatures?: boolean;
  /** Keep per-turn runtime context in place to preserve signed thinking prefixes. */
  appendOnlyRuntimeContext?: boolean;
  sanitizeThoughtSignatures?: {
    allowBase64Only?: boolean;
    includeCamelCase?: boolean;
  };
  dropThinkingBlocks?: boolean;
  dropReasoningFromHistory?: boolean;
  repairToolUseResultPairing?: boolean;
  applyAssistantFirstOrderingFix?: boolean;
  validateGeminiTurns?: boolean;
  validateAnthropicTurns?: boolean;
  allowSyntheticToolResults?: boolean;
};
/**
 * Provider-owned replay/compaction policy input.
 *
 * Use this when transcript replay rules depend on provider/model transport
 * behavior and should stay with the provider plugin instead of core tables.
 */
type ProviderReplayPolicyContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  provider: string;
  modelId?: string;
  modelApi?: string | null;
  model?: ProviderRuntimeModel;
};
type ProviderReplaySessionEntry = {
  customType: string;
  data?: unknown;
};
type ProviderReplaySessionState = {
  getCustomEntries(): ProviderReplaySessionEntry[];
  appendCustomEntry(customType: string, data: unknown): void;
};
/**
 * Provider-owned replay-history sanitization input.
 *
 * Runs after core applies generic transcript cleanup so plugins can make
 * provider-specific replay rewrites without owning the whole compaction flow.
 */
type ProviderSanitizeReplayHistoryContext = ProviderReplayPolicyContext & {
  sessionId: string;
  messages: AgentMessage[];
  allowedToolNames?: Iterable<string>;
  sessionState?: ProviderReplaySessionState;
};
/**
 * Provider-owned final replay-turn validation input.
 *
 * Use this for providers that require strict turn ordering or additional
 * replay-time transcript validation beyond generic sanitation.
 */
type ProviderValidateReplayTurnsContext = ProviderReplayPolicyContext & {
  sessionId?: string;
  messages: AgentMessage[];
  sessionState?: ProviderReplaySessionState;
};
/**
 * Provider-owned tool-schema normalization input.
 *
 * Runs before tool registration for replay/compaction/inference so providers
 * can rewrite schema keywords that their transport family does not support.
 */
type ProviderNormalizeToolSchemasContext = ProviderReplayPolicyContext & {
  tools: AnyAgentTool[];
};
type ProviderToolSchemaDiagnostic = {
  toolName: string;
  toolIndex?: number;
  violations: string[];
};
/**
 * Provider-owned reasoning output mode input.
 *
 * Use this when a provider requires a specific reasoning-output contract, such
 * as text tags instead of native structured reasoning fields.
 */
type ProviderReasoningOutputModeContext = ProviderReplayPolicyContext;
//#endregion
//#region src/llm/model-registry.d.ts
/** Registry abstraction used by model pickers and provider availability checks. */
type ModelRegistry$1 = {
  getAll(): Model[];
  getAvailable(): Model[];
  find(provider: string, modelId: string): Model | undefined;
  hasConfiguredAuth(model: Model): boolean;
};
//#endregion
//#region src/plugins/provider-runtime.types.d.ts
type ModelProviderRequestTransportOverrides = ModelProviderRequestTransportOverrides$1;
type ProviderRuntimeProviderConfig = {
  baseUrl?: string;
  api?: ModelProviderConfig["api"];
  auth?: ModelProviderConfig["auth"];
  models?: ModelProviderConfig["models"];
  headers?: unknown;
};
/**
 * Sync hook for provider-owned model ids that are not present in the local
 * registry/catalog yet.
 *
 * Use this for pass-through providers or provider-specific forward-compat
 * behavior. The hook should be cheap and side-effect free; async refreshes
 * belong in `prepareDynamicModel`.
 */
type ProviderResolveDynamicModelContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  agentRuntimeId?: string;
  provider: string;
  modelId: string;
  modelRegistry: ModelRegistry$1;
  providerConfig?: ProviderRuntimeProviderConfig;
  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 = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  model: ProviderRuntimeModel;
};
/**
 * Provider-owned model-id normalization before config/runtime lookup.
 *
 * Use this for provider-specific alias cleanup that should stay with the
 * plugin rather than in core string tables.
 */
type ProviderNormalizeModelIdContext = {
  provider: string;
  modelId: string;
};
/**
 * Provider-owned transport normalization for arbitrary provider/model config.
 *
 * Use this when transport cleanup depends on API/baseUrl rather than the
 * owning provider id, for example custom providers that still target a
 * plugin-owned transport family.
 */
type ProviderNormalizeTransportContext = {
  config?: OpenClawConfig;
  workspaceDir?: string;
  provider: string;
  modelId?: string;
  api?: string | null;
  baseUrl?: string;
};
/**
 * Runtime auth input for providers that need an extra exchange step before
 * inference. The incoming `apiKey` is the raw credential resolved from auth
 * profiles/env/config. The returned value should be the actual token/key to use
 * for the request.
 */
type ProviderPrepareRuntimeAuthContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  modelId: string;
  model: ProviderRuntimeModel;
  apiKey: string;
  authMode: string;
  profileId?: string;
};
/**
 * Result of `prepareRuntimeAuth`.
 *
 * `apiKey` is required and becomes the runtime credential stored in auth
 * storage. `baseUrl` is optional and lets providers like GitHub Copilot swap to
 * an entitlement-specific endpoint at request time. `expiresAt` enables generic
 * background refresh in long-running turns.
 */
type ProviderPreparedRuntimeAuth = {
  apiKey: string;
  baseUrl?: string;
  request?: ModelProviderRequestTransportOverrides;
  expiresAt?: number;
};
/**
 * Usage/billing auth input for providers that expose quota/usage endpoints.
 *
 * This hook is intentionally separate from `prepareRuntimeAuth`: usage
 * snapshots often need a different credential source than live inference
 * requests, and they run outside the embedded runner.
 *
 * The helper methods cover the common OpenClaw auth resolution paths:
 *
 * - `resolveApiKeyFromConfigAndStore`: env/config/plain token/api_key profiles
 * - `resolveOAuthToken`: oauth/token profiles resolved through the auth store,
 *   optionally for an explicit provider override
 *
 * Plugins can still do extra provider-specific work on top (for example parse a
 * token blob, read a legacy credential file, or pick between aliases).
 */
type ProviderResolveUsageAuthContext = {
  /** Cancel provider-owned work when the usage collection deadline expires. */
  signal?: AbortSignal;
  config: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  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 = {
  /** Custom transports must preserve this signal; fetchFn already includes it. */
  signal?: AbortSignal;
  config: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  env: NodeJS.ProcessEnv;
  provider: string;
  token: string;
  authFlow?: string;
  accountId?: string;
  authProfileId?: 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;
  timeoutMs: number;
  fetchFn: typeof fetch;
};
/**
 * Provider-owned auth-doctor hint input.
 *
 * Called when OAuth refresh fails and OpenClaw wants a provider-specific repair
 * hint to append to the generic re-auth message. Use this for legacy profile-id
 * migrations or other provider-owned auth-store cleanup guidance.
 */
type ProviderAuthDoctorHintContext = {
  config?: OpenClawConfig;
  store: AuthProfileStore;
  provider: string;
  profileId?: string;
};
/**
 * Provider-owned extra-param normalization before OpenClaw builds its generic
 * stream option wrapper.
 *
 * Use this to set provider defaults or rewrite provider-specific config keys
 * into the merged `extraParams` object. Return the full next extraParams object.
 */
/** Provider-facing effort after OpenClaw lowers orchestration-only modes. */
type ProviderTransportThinkingLevel = Exclude<ThinkLevel, "ultra">;
type ProviderPrepareExtraParamsContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  agentId?: string;
  /** Selected credential facts; excludes credential material. */
  auth?: {
    mode: string;
    authFlow?: string;
  };
  nativeWebSearchAllowedByToolPolicy?: boolean;
  provider: string;
  modelId: string;
  model?: ProviderRuntimeModel;
  extraParams?: Record<string, unknown>;
  thinkingLevel?: ProviderTransportThinkingLevel;
};
type ProviderExtraParamsForTransportContext = Omit<ProviderPrepareExtraParamsContext, "extraParams"> & {
  model?: ProviderRuntimeModel;
  transport?: "sse" | "websocket" | "websocket-cached" | "auto";
  extraParams: Record<string, unknown>;
};
type ProviderExtraParamsForTransportResult = {
  patch?: Record<string, unknown> | null;
};
type ProviderResolvePromptOverlayContext = ProviderSystemPromptContributionContext & {
  baseOverlay?: ProviderSystemPromptContribution;
};
type ProviderFollowupFallbackRouteContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  payload: ReplyPayload;
  originatingChannel?: string;
  originatingTo?: string;
  originRoutable: boolean;
  dispatcherAvailable: boolean;
};
type ProviderFollowupFallbackRouteResult = {
  route?: "origin" | "dispatcher" | "drop";
  reason?: string;
};
type ProviderResolveAuthProfileIdContext = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  preferredProfileId?: string;
  lockedProfileId?: string;
  profileOrder: string[];
  authStore: AuthProfileStore;
};
//#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 = {
  config?: OpenClawConfig;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  model: ProviderRuntimeModel;
};
/**
 * Provider-owned stream wrapper hook after OpenClaw applies its generic
 * transport-independent wrappers.
 *
 * Use this for provider-specific payload/header/model mutations that still run
 * through the normal `shared model runtime` stream path.
 */
type ProviderWrapStreamFnContext = ProviderPrepareExtraParamsContext & {
  model?: ProviderRuntimeModel;
  /** Wire-format API before simple completion projects an internal transport alias. */
  sourceApi?: ProviderRuntimeModel["api"];
  streamFn?: StreamFn;
};
/** 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 = {
  provider: string;
  modelId: string;
  model?: ProviderRuntimeModel;
  sessionId?: string;
  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/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[];
  /**
   * 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;
  /**
   * 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;
  /**
   * 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 | 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 | 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 | 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>;
  /**
   * 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) => 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 downgrades stale stored
   * values by profile rank.
   */
  resolveThinkingProfile?: (ctx: ProviderDefaultThinkingPolicyContext) => ProviderThinkingProfile | null | undefined;
  /** Whether Fast can affect this selected request; undefined retains existing unknown behavior. */
  resolveFastModeSupport?: (ctx: ProviderFastModePolicyContext) => boolean | 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$1) => 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.
   */
  refreshOAuth?: (cred: OAuthCredential$1) => 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/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/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;
  private readonly consumerKind;
  constructor(registry: PluginRegistry, instances: Iterable<PluginInstanceHandle>, options?: {
    retained?: boolean;
    parent?: PluginInvocationScope;
    kind?: "work" | "custody";
  });
  private consumer;
  private assertOpen;
  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 readonly retire;
  constructor(retire: (registry: PluginRegistry | undefined, rollbackInstances: ReadonlySet<object>) => Promise<void>);
  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;
  /** 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/plugins/types.mcp-connection.d.ts
/** Plugin-owned MCP server connection resolver contracts. */
/**
 * 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;
};
/** 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>;
};
/**
 * 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 packages/retry/src/index.d.ts
type RetryConfig = {
  attempts?: number;
  minDelayMs?: number;
  maxDelayMs?: number;
  /** Fractional symmetric spread or full jitter. */
  jitter?: number | "full";
};
type RetryDelayContext = {
  attempt: number;
  maxAttempts: number;
  err: unknown;
  label?: string;
};
type RetryInfo = RetryDelayContext & {
  delayMs: number;
};
type RetryOptions = RetryConfig & {
  label?: string;
  shouldRetry?: (err: unknown, attempt: number) => boolean;
  retryAfterMs?: (err: unknown) => number | undefined;
  retryAfterMaxDelayMs?: number;
  delayMs?: number | ((context: RetryDelayContext) => number);
  onRetry?: (info: RetryInfo) => unknown;
  random?: () => number;
  sleep?: (ms: number) => Promise<void>;
};
//#endregion
//#region packages/memory-host-sdk/src/host/embedding-inputs.d.ts
/** Text part passed through embedding providers that support structured input. */
type EmbeddingInputTextPart = {
  type: "text";
  text: string;
};
/** Inline binary payload encoded for providers with multimodal embedding support. */
type EmbeddingInputInlineDataPart = {
  type: "inline-data";
  mimeType: string;
  data: string;
};
/** Single structured embedding input part. */
type EmbeddingInputPart = EmbeddingInputTextPart | EmbeddingInputInlineDataPart;
/** Provider-facing input while preserving the plain text fallback. */
type EmbeddingInput = {
  text: string;
  parts?: EmbeddingInputPart[];
};
//#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 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;
};
type MemoryPromptSectionBuilder = (params: MemoryPromptSectionParams) => string[];
type MemoryPromptSectionPreparer = (params: MemoryPromptSectionParams) => Promise<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;
};
type MemoryFlushPlan = {
  softThresholdTokens: number;
  forceFlushTranscriptBytes: number;
  reserveTokensFloor: number;
  model?: string;
  prompt: string;
  systemPrompt: string;
  relativePath: string;
};
type MemoryFlushPlanResolver = (params: {
  cfg?: OpenClawConfig;
  nowMs?: number;
  contextWindowTokens?: number;
}) => MemoryFlushPlan | null;
type RegisteredMemorySearchManager = Omit<MemorySearchManager, "readFile"> & {
  readFile(params: Parameters<MemorySearchManager["readFile"]>[0]): Promise<LegacyMemoryReadResult | MemoryReadResult>;
};
type MemoryRuntimeBackendConfig = {
  backend: "builtin";
};
type MemoryPluginRuntime = {
  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[];
  }): 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>;
};
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;
  runtime?: MemoryPluginRuntime;
  publicArtifacts?: MemoryPluginPublicArtifactsProvider;
  /** Local deterministic recall tool required by provider-owned direct lookup. */
  deterministicRecallToolName?: string;
  /** Whether recall may read protected same-agent private session transcripts. */
  supportsPrivateTranscriptRecall?: boolean;
};
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 SessionDiscussionState = "none" | "available" | "open";
type SessionDiscussionInfo = {
  state: SessionDiscussionState;
  embedUrl?: string;
  openUrl?: string;
};
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/hooks/internal-hook-types.d.ts
type InternalHookEventType = "command" | "session" | "agent" | "gateway" | "message";
interface InternalHookEvent {
  /** The type of event (command, session, agent, gateway, etc.) */
  type: InternalHookEventType;
  /** The specific action within the type (e.g., 'new', 'reset', 'stop') */
  action: string;
  /** The session key this event relates to */
  sessionKey: string;
  /** Additional context specific to the event */
  context: Record<string, unknown>;
  /** Timestamp when the event occurred */
  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/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 AgentToolResultMiddlewareScope = {
  matcher?: PluginToolMatcher;
  runtimes: AgentToolResultMiddlewareRuntime[];
};
//#endregion
//#region src/plugins/board-widget-content-kind.types.d.ts
/** Plugin-owned source kind rendered through the board's sandboxed document host. */
type PluginBoardWidgetContentKind = {
  /** Agent-facing kind, for example `diagram`. Must be globally unique. */
  kind: string;
  /** Short label shown in dashboard chrome. */
  label: string;
  /** Capability-scoped static resources used by the composed document. */
  resources: {
    surface: string;
    paths: string[];
    /**
     * Public static renderer bytes served without Gateway credentials.
     * Declaring this reader reserves every path globally across content kinds,
     * including registrations without a public reader.
     * Public paths must be canonical URL pathnames and cannot use `/mcp-app-sandbox`.
     */
    readPublicResource?: (path: string) => Promise<{
      body: Uint8Array;
      contentType: string;
    } | undefined>;
  };
  /** Reject malformed or unsupported source before it reaches persistent storage. */
  validateSource: (source: string) => void;
  /** Build the untrusted document body; core adds the canonical bridge and CSP shell. */
  composeDocument: (params: {
    source: string;
    title: string;
    resourceUrls: Readonly<Record<string, string>>;
    promptGranted: boolean;
  }) => string;
};
//#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/plugins/migration-provider.types.d.ts
type MigrationItemStatus = "planned" | "migrated" | "skipped" | "warning" | "conflict" | "error";
type MigrationItemKind = "auth" | "config" | "secret" | "memory" | "skill" | "workspace" | "session" | "file" | "archive" | "manual";
type MigrationItemAction = "copy" | "create" | "update" | "merge" | "append" | "archive" | "skip" | "manual";
type MigrationApplyPhase = "before-promotion" | "after-promotion";
/** Provider guarantee required before onboarding defers non-rollbackable effects. */
type MigrationDeferredApplyContract = {
  retrySafe: true;
};
type MigrationItem = {
  id: string;
  kind: MigrationItemKind | (string & {});
  action: MigrationItemAction | (string & {});
  status: MigrationItemStatus;
  source?: string;
  target?: string;
  message?: string;
  reason?: string;
  sensitive?: boolean;
  /** Onboarding may defer non-rollbackable effects only for retry-safe providers. */
  applyPhase?: MigrationApplyPhase;
  /** 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$1;
  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$1 = {
  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>;
};
//#endregion
//#region src/plugins/plugin-command.types.d.ts
type ChannelId = ChannelId$1;
type PluginCommandSessionTarget = {
  agentId: string;
  sessionId: string;
  sessionKey: string;
  storePath: string;
};
type PluginCommandDiagnosticsSession = {
  /** Stable host session key when available. */
  sessionKey?: string;
  /** Ephemeral OpenClaw session id when available. */
  sessionId?: string;
  /** Canonical SQLite identity for active transcript access. */
  sessionTarget?: PluginCommandSessionTarget;
  /**
   * Deprecated transcript locator for this 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;
  /** Embedded agent harness selected for this session. */
  agentHarnessId?: string;
  /** Channel/provider for this session when available. */
  channel?: string;
  /** Provider channel id when available. */
  channelId?: ChannelId;
  /** Account id for multi-account channels when available. */
  accountId?: string;
  /** Thread/topic id when available. */
  messageThreadId?: string | number;
  /** Parent conversation id for thread-capable channels when available. */
  threadParentId?: string;
};
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?: PluginCommandSessionTarget;
  /**
   * 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?: {
    llm?: Pick<PluginRuntimeCore["llm"], "complete">;
    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 & {
  /** 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;
type OpenClawPluginCommandDefinition$1 = {
  /** 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[];
  /** 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/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/agents/tool-fs-policy.types.d.ts
type PreparedSessionPermissionPolicy = Readonly<{
  root: string;
  mode: SessionPermissionMode;
}>;
/** Filesystem policy for agent tools that can touch local paths. */
type ToolFsPolicy = {
  workspaceOnly: boolean;
  root?: string;
  /** Host-owned roots that read-only tools may consume outside the workspace. */
  readOnlyRoots?: 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 = {
  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;
  os?: string[];
  requires?: {
    bins?: string[];
    anyBins?: string[];
    env?: string[];
    config?: string[];
  };
  install?: HookInstallSpec[];
};
type HookInvocationPolicy = {
  enabled: boolean;
};
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?: HookInvocationPolicy;
};
//#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>;
};
/** 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;
  /** Ephemeral session UUID - regenerated on /new and /reset. Use for per-conversation isolation. */
  sessionId?: string;
  /** 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;
  };
  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;
  /** 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;
  /**
   * 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;
} : OpenClawPluginToolContextBase;
/** A version 2 descriptor explicitly opts into owner-authorized continuations. */
type OpenClawPluginToolFactory$1<Version extends 1 | 2 = 1> = Version extends 2 ? {
  contextVersion: 2;
  create: (ctx: OpenClawPluginToolContext<2>) => ReturnType<OpenClawPluginToolFactory$1>;
} : (ctx: OpenClawPluginToolContext) => AnyAgentTool | AnyAgentTool[] | null | undefined;
//#endregion
//#region src/secrets/runtime-web-tools.types.d.ts
/** Diagnostic codes emitted while selecting runtime web search/fetch providers. */
type RuntimeWebDiagnosticCode = "WEB_SEARCH_PROVIDER_INVALID_AUTODETECT" | "WEB_SEARCH_AUTODETECT_SELECTED" | "WEB_SEARCH_KEY_UNRESOLVED_FALLBACK_USED" | "WEB_SEARCH_KEY_UNRESOLVED_NO_FALLBACK" | "WEB_FETCH_PROVIDER_INVALID_AUTODETECT" | "WEB_FETCH_AUTODETECT_SELECTED" | "WEB_FETCH_PROVIDER_KEY_UNRESOLVED_FALLBACK_USED" | "WEB_FETCH_PROVIDER_KEY_UNRESOLVED_NO_FALLBACK";
/** User-facing diagnostic attached to runtime web-tool metadata. */
type RuntimeWebDiagnostic = {
  code: RuntimeWebDiagnosticCode;
  message: string;
  path?: string;
};
/** Runtime selection metadata for the web search tool. */
type RuntimeWebSearchMetadata = {
  /** Provider explicitly configured in source config, before auto-detect fallback. */
  providerConfigured?: string;
  providerSource: "configured" | "auto-detect" | "none";
  /** Provider that runtime calls should use after config validation and credential lookup. */
  selectedProvider?: string;
  /** Source that supplied the selected provider credential, or why it is unavailable. */
  selectedProviderKeySource?: "config" | "secretRef" | "env" | "missing";
  /** Perplexity transport chosen from provider config or runtime default. */
  perplexityTransport?: "search_api" | "chat_completions";
  diagnostics: RuntimeWebDiagnostic[];
};
/** Runtime selection metadata for the web fetch tool. */
type RuntimeWebFetchMetadata = {
  /** Provider explicitly configured in source config, before auto-detect fallback. */
  providerConfigured?: string;
  providerSource: "configured" | "auto-detect" | "none";
  /** Provider that runtime calls should use after config validation and credential lookup. */
  selectedProvider?: string;
  /** Source that supplied the selected provider credential, or why it is unavailable. */
  selectedProviderKeySource?: "config" | "secretRef" | "env" | "missing";
  diagnostics: RuntimeWebDiagnostic[];
};
//#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 WebProviderConfiguredCredentialFallback = {
  path: string;
  value: unknown;
};
type WebSearchRuntimeMetadataContext = {
  config?: OpenClawConfig;
  searchConfig?: Record<string, unknown>;
  runtimeMetadata?: RuntimeWebSearchMetadata;
  resolvedCredential?: {
    value?: string;
    source: WebSearchCredentialResolutionSource;
    fallbackEnvVar?: string;
  };
};
type WebSearchProviderSetupContext = {
  config: OpenClawConfig;
  runtime: RuntimeEnv;
  prompter: WizardPrompter;
  quickstartDefaults?: boolean;
  secretInputMode?: SecretInputMode;
};
type WebFetchCredentialResolutionSource = "config" | "secretRef" | "env" | "missing";
type WebFetchRuntimeMetadataContext = {
  config?: OpenClawConfig;
  fetchConfig?: Record<string, unknown>;
  runtimeMetadata?: RuntimeWebFetchMetadata;
  resolvedCredential?: {
    value?: string;
    source: WebFetchCredentialResolutionSource;
    fallbackEnvVar?: string;
  };
};
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) => WebProviderConfiguredCredentialFallback | undefined;
  applySelectionConfig?: (config: OpenClawConfig) => OpenClawConfig;
};
type WebSearchProviderPlugin$1 = 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: WebSearchRuntimeMetadataContext) => Partial<RuntimeWebSearchMetadata> | Promise<Partial<RuntimeWebSearchMetadata>>;
  createTool: (ctx: WebSearchProviderContext) => WebSearchProviderToolDefinition | null;
};
type PluginWebSearchProviderEntry = WebSearchProviderPlugin$1 & {
  pluginId: string;
};
type WebFetchProviderPlugin$1 = WebProviderPluginBase & {
  resolveRuntimeMetadata?: (ctx: WebFetchRuntimeMetadataContext) => Partial<RuntimeWebFetchMetadata> | Promise<Partial<RuntimeWebFetchMetadata>>;
  createTool: (ctx: WebFetchProviderContext) => WebFetchProviderToolDefinition | null;
};
//#endregion
//#region src/plugins/plugin-api.types.d.ts
type PluginTextTransformRegistration$1 = PluginTextTransforms;
//#endregion
//#region src/process/supervisor/types.d.ts
type TerminationReason = "manual-cancel" | "overall-timeout" | "no-output-timeout" | "spawn-error" | "signal" | "exit";
//#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
/** Catalog metadata for one configured MCP server. */
type McpServerCatalog = {
  serverName: string;
  safeServerName?: string;
  launchSummary: string;
  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;
  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;
};
/** Complete tool catalog for a session-scoped MCP runtime. */
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[];
};
type McpToolCatalogDiagnostic = {
  serverName: string;
  safeServerName: string;
  launchSummary: string;
  message: string;
};
//#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
/** Resolved sandbox path with host, relative, and container views. */
type SandboxResolvedPath = {
  hostPath?: string;
  relativePath: string;
  containerPath: string;
};
/** Minimal file stat shape returned by sandbox fs bridge implementations. */
type SandboxFsStat = {
  type: "file" | "directory" | "other";
  size: number;
  mtimeMs: number;
};
/** Filesystem operations exposed across the sandbox boundary. */
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 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;
  }): 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;
    signal?: AbortSignal;
  }): Promise<SandboxFsStat | null>;
};
//#endregion
//#region src/agents/sandbox/backend-handle.types.d.ts
/**
 * Backend-neutral sandbox runtime handles used by Docker, SSH, and future sandbox providers.
 */
type SandboxBackendId = string;
/** Shell exec specification prepared by a sandbox backend for process launch. */
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;
/** Parameters for backend-managed shell commands used by fs bridges and probes. */
type SandboxBackendCommandParams = {
  script: string;
  args?: string[];
  stdin?: Buffer | string;
  allowFailure?: boolean;
  signal?: AbortSignal;
};
/** Buffered command result returned by sandbox backend shell helpers. */
type SandboxBackendCommandResult = {
  stdout: Buffer;
  stderr: Buffer;
  code: number;
};
/** Runtime context passed to backend-provided filesystem bridge factories. */
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>;
  };
};
/** Live sandbox backend handle for command execution, cleanup, and optional fs bridge creation. */
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;
  }): 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/agents/sandbox/types.docker.d.ts
type RequiredDockerConfigKeys = "image" | "containerPrefix" | "workdir" | "readOnlyRoot" | "tmpfs" | "network" | "capDrop";
type SandboxDockerConfig = Omit<SandboxDockerSettings, RequiredDockerConfigKeys> & Required<Pick<SandboxDockerSettings, RequiredDockerConfigKeys>>;
//#endregion
//#region src/agents/sandbox/types.d.ts
type SandboxToolPolicy = {
  allow?: string[];
  deny?: string[];
};
type SandboxWorkspaceAccess = "none" | "ro" | "rw";
type SandboxBrowserContext = {
  bridgeUrl: string;
  noVncUrl?: string;
  containerName: string;
};
type SandboxContext = {
  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;
  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/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/subagents/announce/subagent-announce-handoff.d.ts
type SubagentSettleToolPolicyBatch = {
  sourceSessionKeys: readonly string[];
  /** The settle owner retains batch, requester-incarnation, and revocation authority. */
  isCurrent: () => boolean;
};
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/subagents/spawn/subagent-session-store.d.ts
type PersistedSessionCapabilityEntry = Pick<SessionEntry$1, "sessionId" | "spawnDepth" | "subagentRole" | "subagentControlScope" | "spawnedBy" | "completionOwnerSessionKey" | "inheritedToolPolicyVersion" | "inheritedToolAllow" | "inheritedToolDeny">;
type SessionCapabilityEntry = { [Key in keyof PersistedSessionCapabilityEntry]?: unknown; };
/** 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;
};
//#endregion
//#region src/agents/conversation-capability-profile.d.ts
type ConversationCapabilityScope = "direct" | "shared" | "unknown";
type ConversationCapabilityProfileParams = {
  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;
  agentDir?: string;
  agentAccountId?: string | null;
  messageProvider?: string | null;
  messageChannel?: string | null;
  chatType?: string;
  messageTo?: string | null;
  messageThreadId?: string | number | null;
  conversationToolPolicy?: GroupToolPolicyConfig;
  currentChannelId?: string | null;
  currentMessagingTarget?: string | null;
  currentThreadTs?: string | null;
  currentMessageId?: string | number | null;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  memberRoleIds?: readonly string[];
  spawnedBy?: string | null;
  senderId?: string | null;
  senderName?: string | null;
  senderUsername?: string | null;
  senderE164?: string | null;
  senderIsOwner?: boolean;
  modelProvider?: string;
  modelId?: string;
  modelApi?: string;
  modelContextWindowTokens?: number;
  modelHasVision?: boolean;
  workspaceDir?: string;
  cwd?: string;
  spawnWorkspaceDir?: string;
  isCanonicalWorkspace?: boolean;
  promptMode?: PromptMode;
  skillsSnapshot?: SkillSnapshot;
  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;
};
declare function resolveConversationCapabilityProfile(params: ConversationCapabilityProfileParams): {
  agentId: string | undefined;
  serviceIdentity: {
    agentId: string | undefined;
    agentDir: string | undefined;
    accountId: string | null | undefined;
    runId: string | undefined;
    sessionId: string | undefined;
  };
  model: {
    provider: string | undefined;
    id: string | undefined;
    api: string | undefined;
    contextWindowTokens: number | undefined;
    hasVision: boolean | undefined;
  };
  conversation: {
    scope: ConversationCapabilityScope;
    chatType: ChatType | undefined;
    sessionKey: string | undefined;
    policySessionKey: string | undefined;
    runSessionKey: string | undefined;
    sessionId: string | undefined;
    messageProvider: string | null | undefined;
    messageChannel: string | null | undefined;
    messageTo: string | null | undefined;
    messageThreadId: string | number | null | undefined;
    currentChannelId: string | null | undefined;
    currentMessagingTarget: string | null | undefined;
    currentThreadTs: string | null | undefined;
    currentMessageId: string | number | null | undefined;
    groupId: string | null | undefined;
    groupChannel: string | null | undefined;
    groupSpace: string | null | undefined;
    memberRoleIds: readonly string[] | undefined;
    spawnedBy: string | null | undefined;
  };
  sender: {
    id: string | null | undefined;
    name: string | null | undefined;
    username: string | null | undefined;
    e164: string | null | undefined;
    isOwner: boolean | undefined;
  };
  workspace: {
    workspaceDir: string | undefined;
    cwd: string | undefined;
    spawnWorkspaceDir: string | undefined;
    workspaceRoot: string;
    runtimeRoot: string;
    spawnWorkspaceRoot: string | undefined;
    instructionRoot: string | undefined;
    isCanonicalWorkspace: boolean | undefined;
  };
  instructions: {
    agentDir: string | undefined;
    workspaceDir: string | undefined;
    promptMode: PromptMode | undefined;
    isCanonicalWorkspace: boolean | undefined;
  };
  skills: {
    snapshot: SkillSnapshot | undefined;
  };
  policy: {
    agentId: string | undefined;
    sessionKey: string | undefined;
    subagentSessionKey: string | undefined;
    trustedGroup: {
      groupId: string | null | undefined;
      dropped: boolean;
    };
    profile: "coding" | "full" | "messaging" | "minimal" | undefined;
    providerProfile: ToolProfileId | undefined;
    sources: Partial<Record<"agent" | "agentProvider" | "global" | "globalProvider" | "profile" | "providerProfile", {
      kind: "profile" | "config" | "session" | "runtime";
      path?: string;
      profile?: string;
      alsoAllowPath?: string;
    }>>;
    profiles: {
      profile: "coding" | "full" | "messaging" | "minimal";
      source: string;
      active: boolean;
    }[];
    gatewayConfigReadAllowed: boolean;
    profilePolicy: {
      allow?: string[];
      deny?: string[];
    } | undefined;
    providerProfilePolicy: {
      allow?: string[];
      deny?: string[];
    } | undefined;
    profileAlsoAllow: string[] | undefined;
    providerProfileAlsoAllow: string[] | undefined;
    globalPolicy: SandboxToolPolicy | undefined;
    globalProviderPolicy: SandboxToolPolicy | undefined;
    agentPolicy: SandboxToolPolicy | undefined;
    agentProviderPolicy: SandboxToolPolicy | undefined;
    groupPolicy: SandboxToolPolicy | undefined;
    senderPolicy: SandboxToolPolicy | undefined;
    sandboxPolicy: SandboxToolPolicy | undefined;
    subagentPolicy: SandboxToolPolicy | undefined;
    inheritedToolPolicy: SandboxToolPolicy | undefined;
    delegated: boolean;
    requesterPolicySource: "completion-handoff" | "current-request" | "persisted-child";
    runtimeToolPolicyForInheritance: {
      allow: string[];
    } | undefined;
    inheritancePolicies: (SandboxToolPolicy | {
      allow: string[];
    } | undefined)[];
    explicitToolAllowlist: string[];
    explicitToolOverrideAllowlist: string[];
    explicitToolDenylist: string[];
    runtimePluginToolGrant: RuntimePluginToolGrant | undefined;
  };
};
type ResolvedConversationCapabilityProfile = ReturnType<typeof resolveConversationCapabilityProfile>;
//#endregion
//#region src/agents/run-trigger.d.ts
type EmbeddedRunTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user";
//#endregion
//#region src/agents/reply-completion.d.ts
type ReplyExpectation = "required" | "optional";
type ReplyDeliveryState = "delivered" | "pending" | "missing";
type ReplyDeliveryObserver = (minimumAssistantMessageIndex?: number) => Promise<ReplyDeliveryState>;
type ReplyCompletionEvidence = "ready" | "delivered" | "pending" | "blocked" | "empty";
/** Model output cannot waive a required reply. Only the input owner selects expectation. */
type ReplyCompletion = {
  readonly expectation: "required";
  readonly outcome: Exclude<ReplyCompletionEvidence, "empty"> | "missing";
} | {
  readonly expectation: "optional";
  readonly outcome: Exclude<ReplyCompletionEvidence, "empty"> | "silent";
};
declare namespace reply_run_finalization_lease_d_exports {
  export { ReplyOperationStaleReason$1 as ReplyOperationStaleReason, beginReplyOperationFinalizationWork, createReplyRunFinalizationLease, createReplyRunSettleTimer, formatReplyOperationResult, resetReplyRunSettleTimersForTesting };
}
type ReplyOperationStaleReason$1 = "terminal_unreleased" | "finalization_stalled" | "no_activity" | "stuck_recovery";
declare function formatReplyOperationResult(result: {
  kind: "completed";
} | {
  kind: string;
  code: string;
} | null): string;
type FinalizationLease = {
  begin(): void;
  beginWork(timeoutMs: number): () => void;
  clear(): void;
  recordActivity(): void;
};
type ReplyRunSettleTimer = {
  clear(): void;
  renew(timeoutMs: number): void;
  scheduleOnce(timeoutMs: number): void;
};
declare function createReplyRunSettleTimer(params: {
  canExpire: () => boolean;
  onExpire: () => void;
}): ReplyRunSettleTimer;
declare function createReplyRunFinalizationLease(params: {
  owner: object;
  canExpire: () => boolean;
  onActivity: () => void;
  onExpire: () => void;
  onFinalizationProgress: () => void;
}): FinalizationLease;
declare function beginReplyOperationFinalizationWork(owner: object, timeoutMs: number): () => void;
declare function resetReplyRunSettleTimersForTesting(): void;
//#endregion
//#region src/auto-reply/reply/reply-run-registry.contracts.d.ts
type ReplyRunKey = string;
type ReplyBackendKind = "embedded" | "cli";
type ReplyBackendCancelReason = "user_abort" | "restart" | "superseded";
type ReplyTurnKind = "visible" | "heartbeat" | "queued_followup";
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;
  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;
  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<{
  operatorAuthority?: AdmittedRunOperatorAuthority;
  permissionMode?: SessionEntry$1["permissionMode"];
  toolOverrides?: SessionEntry$1["toolOverrides"];
  originatingChannel?: OriginatingChannelType;
  messageProvider?: string;
  chatType?: ChatType;
  agentAccountId?: string;
  conversationToolPolicy?: GroupToolPolicyConfig;
  groupId?: string;
  groupChannel?: string;
  groupSpace?: string;
  memberRoleIds?: string[];
  spawnedBy?: string;
  senderId?: string;
  senderName?: string;
  senderUsername?: string;
  senderE164?: string;
  senderIsOwner: boolean;
  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>>;
}>;
type ReplyTurnParticipantInput = Pick<ReplyToolAuthorityOverlay, "operatorAuthority" | "senderId" | "senderName" | "gatewayUiCommandTarget">;
type ReplyToolAuthoritySnapshot = Readonly<{
  personalToolOwner?: ReplyTurnParticipantInput;
  /** Selection admitted before runtime fallback or hooks choose a concrete model. */
  requestedRoute?: ReplyToolAuthorityRoute;
  fingerprint(route?: ReplyToolAuthorityRoute): string;
  project: (overlay: ReplyToolAuthorityOverlay, route: ReplyToolAuthorityRoute) => string;
}>;
type ReplyTurnParticipant = Readonly<{
  profileId: string;
  senderId: string;
  name: string;
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  assertCurrent: () => void;
}>;
type ReplyTurnParticipants = {
  accept(participant: ReplyTurnParticipantInput): void;
  resolve(this: void, user?: string): 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 ReplyBackendMessageInjectionV2 = {
  readonly version: 2;
  isAvailable(): boolean;
  queueMessage(text: string, options: ReplyBackendQueueMessageOptions | undefined, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<void | ReplyBackendQueueMessageResult>;
  claimPendingUserInputAnswer?(text: string, options: ReplyBackendQueueMessageOptions | undefined, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<boolean>;
  cancelPendingUserInput?(resolvedBy: string, assertCurrent: () => void, authorityKind: "run" | "source-bound"): Promise<boolean>;
};
type ReplyBackendHandle = {
  readonly kind: ReplyBackendKind;
  readonly runId?: string;
  /** Exact authority of this concrete backend attempt, after fallback selection. */
  readonly toolAuthorityFingerprint?: string;
  readonly sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  readonly terminalReplyExpectation?: ReplyExpectation;
  readonly taskSuggestionDeliveryMode?: TaskSuggestionDeliveryMode;
  /** True only when queueMessage preserves images supplied in its options. */
  readonly supportsQueueMessageImages?: 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;
  isAbortable?: () => boolean;
  /** @deprecated Compatibility for shipped embedded handles. Use messageInjection. */
  queueMessage?: (text: string, options?: ReplyBackendQueueMessageOptions) => Promise<void | ReplyBackendQueueMessageResult>;
  /**
   * Compatibility-only hook so legacy "abort compacting runs" paths can still
   * find embedded runs that are compacting during the main run phase.
   */
  isCompacting?: () => boolean;
};
type ReplyOperationPhase = "queued" | "waiting_for_deferred_maintenance" | "waiting_for_global_lane" | "preflight_compacting" | "memory_flushing" | "running" | "completed" | "failed" | "aborted";
type ReplyOperationFailureCode = "gateway_draining" | "command_lane_cleared" | "aborted_by_user" | "session_corruption_reset" | "run_stalled" | "run_failed";
type ReplyOperationAbortCode = "aborted_by_user" | "aborted_for_restart" | "aborted_for_supersession";
type ReplyOperationResult = {
  kind: "completed";
} | {
  kind: "failed";
  code: ReplyOperationFailureCode;
  cause?: unknown;
} | {
  kind: "aborted";
  code: ReplyOperationAbortCode;
};
type ReplyOperation = {
  readonly personalToolParticipants?: ReplyTurnParticipants;
  readonly key: ReplyRunKey;
  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;
  /** Immutable tool authority accepted by the active backend for steered user turns. */
  readonly toolAuthorityFingerprint?: 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;
  /** 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: "queued" | "waiting_for_deferred_maintenance" | "waiting_for_global_lane" | "preflight_compacting" | "memory_flushing" | "running"): 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;
  /** Mark this operation as waiting for process-global run capacity. */
  markWaitingForGlobalLane(): void;
  /** Return a global-lane-waiting operation to queued once capacity is granted. */
  markGlobalLaneWaitEnded(): void;
  /** Mark this operation as an in-flight terminal-session recovery. */
  markTerminalRecovery(): void;
  markAcceptedSteeredInboundAudio(): void;
  /** Freeze the complete caller policy before a concrete backend attempt attaches. */
  bindToolAuthoritySnapshot(snapshot: ReplyToolAuthoritySnapshot): void;
  setAutomaticFallbackRoute(route: ReplyToolAuthorityRoute | undefined): void;
  /** Project an inbound turn through the current concrete route; settled owners fail closed. */
  projectToolAuthorityFingerprint(overlay: ReplyToolAuthorityOverlay): string | undefined;
  /** Prepare fingerprint and projection together for the final concrete attempt route. */
  bindToolAuthorityRoute(route: ReplyToolAuthorityRoute): string;
  updateSessionId(nextSessionId: string): void;
  /**
   * Move this queued operation to another session key's run slot. Native command
   * turns admit under the slash SOURCE key; when the command continues into a full
   * agent turn it must own the TARGET session's slot so concurrent target inbounds
   * queue/steer instead of double-admitting. Throws ReplyRunAlreadyActiveError when
   * the target slot is owned. Capture the selected agent even when a raw key stays unchanged.
   */
  updateSessionKey(nextSessionKey: string, agentId?: string): void;
  attachBackend(handle: ReplyBackendHandle): void;
  detachBackend(handle: ReplyBackendHandle): void;
  /** Reject later aborts after the backend has committed its terminal outcome. */
  freezeAbort(): void;
  /**
   * Keep a failed operation active until complete() releases the session lane.
   * Dispatch uses this while a user-visible failure payload still needs delivery.
   */
  retainFailureUntilComplete(): void;
  /** 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 ReplyOperation for this session.
   */
  completeThen(afterClear: () => void): void;
  /**
   * Clear active-run state immediately, but delay registered after-clear work
   * until delivery or another external barrier settles.
   */
  completeWithAfterClearBarrier(barrier: PromiseLike<unknown>, timeout?: number | ReplyFollowupAdmissionBarrierTimeoutPolicy): void;
  fail(code: Exclude<ReplyOperationFailureCode, "aborted_by_user">, cause?: unknown): void;
  abortByUser(): boolean;
  abortForRestart(): boolean;
  supersede(beforeSupersede?: () => void): boolean;
};
type ReplyOperationStaleReason = ReplyOperationStaleReason$1;
//#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";
//#endregion
//#region src/process/command-queue.types.d.ts
/**
 * Public enqueue knobs shared by command-lane callers and narrower injection
 * points that should not import the full queue implementation.
 */
type CommandQueueTaskDeadline = {
  kind: "bounded";
  deadlineAtMs: number;
} | {
  kind: "unlimited";
};
type CommandQueueEnqueueOptions = {
  /** Enqueue-time provenance for diagnostics only; never used for admission. */
  taskIdentity?: Readonly<{
    taskKind: string;
    sessionKey?: string;
    runId?: string;
    requesterSessionKey?: string;
  }>;
  /** 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";
};
/** Minimal queue function contract used by code that only needs to schedule work. */
type CommandQueueEnqueueFn = <T>(task: () => Promise<T>, opts?: CommandQueueEnqueueOptions) => Promise<T>;
//#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;
  assertWorkspaceCurrent?: () => void;
  bind: (context: AdmittedRunContext) => void;
  invoke: (params: SkillLibraryAuthoringInput) => Promise<SkillsLibraryReceipt | SkillsLibraryReadResult | SkillsLibraryActivateResult | SkillsLibraryListResult>;
};
//#endregion
//#region src/skills/workshop/types.d.ts
type ProtocolSkillProposalRecord = SkillsProposalRecordResult;
type SkillProposalOrigin = NonNullable<ProtocolSkillProposalRecord["origin"]>;
type SkillWorkshopPreparedPatch = {
  skillFile: string;
  contentHash: string;
  oldString: string;
};
/** Run-scoped budget shared by every workshop tool instance created across runner retries. */
type SkillWorkshopProposalMutationBudget = {
  remaining: number;
  /** Run-local identity set used to keep idea counts distinct. */
  mutatedProposalIds?: Set<string>;
  /** Content hash per live skill read this run; autonomous updates require a matching receipt. */
  readSkillHashes?: Map<string, string>;
  /** Single-use exact-span patch authority prepared from authoritative live content. */
  preparedSkillPatches?: Map<string, SkillWorkshopPreparedPatch>;
};
/** Exact proposal revision an operator reviewed before requesting an agent-authored revision. */
type SkillWorkshopProposalRevisionConstraint = {
  readonly agentId: string;
  readonly workspaceDir: string;
  readonly proposalId: string;
  readonly expectedRevisionHash: string;
};
type SkillWorkshopRunOptions = {
  libraryAuthoring?: SkillLibraryAuthoringCapability;
  env?: NodeJS.ProcessEnv;
  proposalOnly?: boolean;
  updateProposals?: boolean;
  autonomousCapture?: boolean;
  origin?: SkillProposalOrigin;
  proposalMutationBudget?: SkillWorkshopProposalMutationBudget;
  proposalRevision?: SkillWorkshopProposalRevisionConstraint;
};
//#endregion
//#region src/agents/sessions/event-bus.d.ts
/** Minimal publish/subscribe interface used by session components. */
interface EventBus {
  emit(channel: string, data: unknown): void;
  on(channel: string, handler: (data: unknown) => void): () => void;
}
//#endregion
//#region src/llm/stream.d.ts
declare function completeSimple<TApi extends Api>(model: Model<TApi>, context: Context, options?: SimpleStreamOptions, assertCurrent?: () => void): Promise<AssistantMessage$1>;
//#endregion
//#region src/agents/modes/interactive/theme/theme.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>;
type ThemeColor = Exclude<keyof ThemeJson["colors"], ThemeBg>;
type ThemeBg = "selectedBg" | "userMessageBg" | "customMessageBg" | "toolPendingBg" | "toolSuccessBg" | "toolErrorBg";
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/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/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;
  /** Working directory */
  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<Exclude<keyof typeof KEYBINDINGS, keyof typeof TUI_KEYBINDINGS>, true>;
declare module "@earendil-works/pi-tui" {
  interface Keybindings extends AppKeybindings {}
}
/** Complete keybinding definition map consumed by the TUI keybinding manager. */
declare const KEYBINDINGS: {
  readonly "tui.editor.cursorUp": {
    readonly defaultKeys: "up";
    readonly description: "Move cursor up";
  };
  readonly "tui.editor.cursorDown": {
    readonly defaultKeys: "down";
    readonly description: "Move cursor down";
  };
  readonly "tui.editor.historyPrevious": {
    readonly defaultKeys: [];
    readonly description: "Select previous prompt history entry";
  };
  readonly "tui.editor.historyNext": {
    readonly defaultKeys: [];
    readonly description: "Select next prompt history entry";
  };
  readonly "tui.editor.cursorLeft": {
    readonly defaultKeys: ["left", "ctrl+b"];
    readonly description: "Move cursor left";
  };
  readonly "tui.editor.cursorRight": {
    readonly defaultKeys: ["right", "ctrl+f"];
    readonly description: "Move cursor right";
  };
  readonly "tui.editor.cursorWordLeft": {
    readonly defaultKeys: ["alt+left", "ctrl+left", "alt+b"];
    readonly description: "Move cursor word left";
  };
  readonly "tui.editor.cursorWordRight": {
    readonly defaultKeys: ["alt+right", "ctrl+right", "alt+f"];
    readonly description: "Move cursor word right";
  };
  readonly "tui.editor.cursorLineStart": {
    readonly defaultKeys: ["home", "ctrl+home", "ctrl+a"];
    readonly description: "Move to line start";
  };
  readonly "tui.editor.cursorLineEnd": {
    readonly defaultKeys: ["end", "ctrl+end", "ctrl+e"];
    readonly description: "Move to line end";
  };
  readonly "tui.editor.jumpForward": {
    readonly defaultKeys: "ctrl+]";
    readonly description: "Jump forward to character";
  };
  readonly "tui.editor.jumpBackward": {
    readonly defaultKeys: "ctrl+alt+]";
    readonly description: "Jump backward to character";
  };
  readonly "tui.editor.pageUp": {
    readonly defaultKeys: ["pageUp", "ctrl+pageUp"];
    readonly description: "Page up";
  };
  readonly "tui.editor.pageDown": {
    readonly defaultKeys: ["pageDown", "ctrl+pageDown"];
    readonly description: "Page down";
  };
  readonly "tui.editor.deleteCharBackward": {
    readonly defaultKeys: "backspace";
    readonly description: "Delete character backward";
  };
  readonly "tui.editor.deleteCharForward": {
    readonly defaultKeys: ["delete", "ctrl+d"];
    readonly description: "Delete character forward";
  };
  readonly "tui.editor.deleteWordBackward": {
    readonly defaultKeys: ["ctrl+w", "alt+backspace"];
    readonly description: "Delete word backward";
  };
  readonly "tui.editor.deleteWordForward": {
    readonly defaultKeys: ["alt+d", "alt+delete"];
    readonly description: "Delete word forward";
  };
  readonly "tui.editor.deleteToLineStart": {
    readonly defaultKeys: "ctrl+u";
    readonly description: "Delete to line start";
  };
  readonly "tui.editor.deleteToLineEnd": {
    readonly defaultKeys: "ctrl+k";
    readonly description: "Delete to line end";
  };
  readonly "tui.editor.yank": {
    readonly defaultKeys: "ctrl+y";
    readonly description: "Yank";
  };
  readonly "tui.editor.yankPop": {
    readonly defaultKeys: "alt+y";
    readonly description: "Yank pop";
  };
  readonly "tui.editor.undo": {
    readonly defaultKeys: "ctrl+-";
    readonly description: "Undo";
  };
  readonly "tui.input.newLine": {
    readonly defaultKeys: ["shift+enter", "ctrl+j"];
    readonly description: "Insert newline";
  };
  readonly "tui.input.submit": {
    readonly defaultKeys: "enter";
    readonly description: "Submit input";
  };
  readonly "tui.input.tab": {
    readonly defaultKeys: "tab";
    readonly description: "Tab / autocomplete";
  };
  readonly "tui.input.copy": {
    readonly defaultKeys: "ctrl+c";
    readonly description: "Copy selection";
  };
  readonly "tui.select.up": {
    readonly defaultKeys: "up";
    readonly description: "Move selection up";
  };
  readonly "tui.select.down": {
    readonly defaultKeys: "down";
    readonly description: "Move selection down";
  };
  readonly "tui.select.pageUp": {
    readonly defaultKeys: "pageUp";
    readonly description: "Selection page up";
  };
  readonly "tui.select.pageDown": {
    readonly defaultKeys: "pageDown";
    readonly description: "Selection page down";
  };
  readonly "tui.select.confirm": {
    readonly defaultKeys: "enter";
    readonly description: "Confirm selection";
  };
  readonly "tui.select.cancel": {
    readonly defaultKeys: ["escape", "ctrl+c"];
    readonly description: "Cancel selection";
  };
  readonly "tui.altScreen.pageUp": {
    readonly defaultKeys: "pageUp";
    readonly description: "Scroll viewport up one page";
  };
  readonly "tui.altScreen.pageDown": {
    readonly defaultKeys: "pageDown";
    readonly description: "Scroll viewport down one page";
  };
  readonly "tui.altScreen.halfPageUp": {
    readonly defaultKeys: [];
    readonly description: "Scroll viewport up half a page";
  };
  readonly "tui.altScreen.halfPageDown": {
    readonly defaultKeys: [];
    readonly description: "Scroll viewport down half a page";
  };
  readonly "tui.altScreen.lineUp": {
    readonly defaultKeys: [];
    readonly description: "Scroll viewport up one line";
  };
  readonly "tui.altScreen.lineDown": {
    readonly defaultKeys: [];
    readonly description: "Scroll viewport down one line";
  };
  readonly "tui.altScreen.previousPrompt": {
    readonly defaultKeys: ["ctrl+shift+up", "ctrl+up"];
    readonly description: "Jump to previous semantic prompt";
  };
  readonly "tui.altScreen.nextPrompt": {
    readonly defaultKeys: ["ctrl+shift+down", "ctrl+down"];
    readonly description: "Jump to next semantic prompt";
  };
  readonly "tui.altScreen.search": {
    readonly defaultKeys: "ctrl+shift+f";
    readonly description: "Search the primary scroll view";
  };
  readonly "tui.altScreen.searchNext": {
    readonly defaultKeys: ["enter", "ctrl+g"];
    readonly description: "Select the next search match";
  };
  readonly "tui.altScreen.searchPrevious": {
    readonly defaultKeys: ["shift+enter", "ctrl+shift+g"];
    readonly description: "Select the previous search match";
  };
  readonly "tui.altScreen.searchClose": {
    readonly defaultKeys: "escape";
    readonly description: "Close transcript search";
  };
  readonly "tui.altScreen.top": {
    readonly defaultKeys: "home";
    readonly description: "Scroll viewport to top";
  };
  readonly "tui.altScreen.bottom": {
    readonly defaultKeys: "end";
    readonly description: "Scroll viewport to bottom";
  };
  readonly "app.interrupt": {
    readonly defaultKeys: "escape";
    readonly description: "Cancel or abort";
  };
  readonly "app.clear": {
    readonly defaultKeys: "ctrl+c";
    readonly description: "Clear editor";
  };
  readonly "app.exit": {
    readonly defaultKeys: "ctrl+d";
    readonly description: "Exit when editor is empty";
  };
  readonly "app.suspend": {
    readonly defaultKeys: "ctrl+z" | never[];
    readonly description: "Suspend to background";
  };
  readonly "app.thinking.cycle": {
    readonly defaultKeys: "shift+tab";
    readonly description: "Cycle thinking level";
  };
  readonly "app.model.cycleForward": {
    readonly defaultKeys: "ctrl+p";
    readonly description: "Cycle to next model";
  };
  readonly "app.model.cycleBackward": {
    readonly defaultKeys: "shift+ctrl+p";
    readonly description: "Cycle to previous model";
  };
  readonly "app.model.select": {
    readonly defaultKeys: "ctrl+l";
    readonly description: "Open model selector";
  };
  readonly "app.tools.expand": {
    readonly defaultKeys: "ctrl+o";
    readonly description: "Toggle tool output";
  };
  readonly "app.thinking.toggle": {
    readonly defaultKeys: "ctrl+t";
    readonly description: "Toggle thinking blocks";
  };
  readonly "app.session.toggleNamedFilter": {
    readonly defaultKeys: "ctrl+n";
    readonly description: "Toggle named session filter";
  };
  readonly "app.editor.external": {
    readonly defaultKeys: "ctrl+g";
    readonly description: "Open external editor";
  };
  readonly "app.message.followUp": {
    readonly defaultKeys: "alt+enter";
    readonly description: "Queue follow-up message";
  };
  readonly "app.message.dequeue": {
    readonly defaultKeys: "alt+up";
    readonly description: "Restore queued messages";
  };
  readonly "app.clipboard.pasteImage": {
    readonly defaultKeys: "alt+v" | "ctrl+v";
    readonly description: "Paste image from clipboard";
  };
  readonly "app.session.new": {
    readonly defaultKeys: [];
    readonly description: "Start a new session";
  };
  readonly "app.session.tree": {
    readonly defaultKeys: [];
    readonly description: "Open session tree";
  };
  readonly "app.session.fork": {
    readonly defaultKeys: [];
    readonly description: "Fork current session";
  };
  readonly "app.session.resume": {
    readonly defaultKeys: [];
    readonly description: "Resume a session";
  };
  readonly "app.tree.foldOrUp": {
    readonly defaultKeys: ["ctrl+left", "alt+left"];
    readonly description: "Fold tree branch or move up";
  };
  readonly "app.tree.unfoldOrDown": {
    readonly defaultKeys: ["ctrl+right", "alt+right"];
    readonly description: "Unfold tree branch or move down";
  };
  readonly "app.tree.editLabel": {
    readonly defaultKeys: "shift+l";
    readonly description: "Edit tree label";
  };
  readonly "app.tree.toggleLabelTimestamp": {
    readonly defaultKeys: "shift+t";
    readonly description: "Toggle tree label timestamps";
  };
  readonly "app.session.togglePath": {
    readonly defaultKeys: "ctrl+p";
    readonly description: "Toggle session path display";
  };
  readonly "app.session.toggleSort": {
    readonly defaultKeys: "ctrl+s";
    readonly description: "Toggle session sort mode";
  };
  readonly "app.session.rename": {
    readonly defaultKeys: "ctrl+r";
    readonly description: "Rename session";
  };
  readonly "app.session.delete": {
    readonly defaultKeys: "ctrl+d";
    readonly description: "Delete session";
  };
  readonly "app.session.deleteNoninvasive": {
    readonly defaultKeys: "ctrl+backspace";
    readonly description: "Delete session when query is empty";
  };
  readonly "app.models.save": {
    readonly defaultKeys: "ctrl+s";
    readonly description: "Save model selection";
  };
  readonly "app.models.enableAll": {
    readonly defaultKeys: "ctrl+a";
    readonly description: "Enable all models";
  };
  readonly "app.models.clearAll": {
    readonly defaultKeys: "ctrl+x";
    readonly description: "Clear all models";
  };
  readonly "app.models.toggleProvider": {
    readonly defaultKeys: "ctrl+p";
    readonly description: "Toggle all models for provider";
  };
  readonly "app.models.reorderUp": {
    readonly defaultKeys: "alt+up";
    readonly description: "Move model up in order";
  };
  readonly "app.models.reorderDown": {
    readonly defaultKeys: "alt+down";
    readonly description: "Move model down in order";
  };
  readonly "app.tree.filter.default": {
    readonly defaultKeys: "ctrl+d";
    readonly description: "Tree filter: default view";
  };
  readonly "app.tree.filter.noTools": {
    readonly defaultKeys: "ctrl+t";
    readonly description: "Tree filter: hide tool results";
  };
  readonly "app.tree.filter.userOnly": {
    readonly defaultKeys: "ctrl+u";
    readonly description: "Tree filter: user messages only";
  };
  readonly "app.tree.filter.labeledOnly": {
    readonly defaultKeys: "ctrl+l";
    readonly description: "Tree filter: labeled entries only";
  };
  readonly "app.tree.filter.all": {
    readonly defaultKeys: "ctrl+a";
    readonly description: "Tree filter: show all entries";
  };
  readonly "app.tree.filter.cycleForward": {
    readonly defaultKeys: "ctrl+o";
    readonly description: "Tree filter: cycle forward";
  };
  readonly "app.tree.filter.cycleBackward": {
    readonly defaultKeys: "shift+ctrl+o";
    readonly description: "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);
  /** 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/agents/plugin-model-catalog.d.ts
type PersistedPluginModelCatalog = {
  pluginId: string;
  contents: string;
};
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/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;
  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.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 {
  private data;
  private credentialSources;
  private runtimeOverrides;
  private fallbackResolver?;
  private loadError;
  private errors;
  private storage;
  private constructor();
  static forAgent(agentDir?: string, config?: OpenClawConfig): AuthStorage;
  /**
   * @deprecated Use AuthStorage.forAgent(agentDir). The path-taking compatibility
   * form is eligible for removal after 2026-10-01 and a clean published-plugin
   * reader sweep; it no longer reads or writes JSON.
   */
  static create(authPath?: string): AuthStorage;
  static fromStorage(storage: AuthStorageBackend): AuthStorage;
  static inMemory(data?: AuthStorageData): AuthStorage;
  /**
   * Set a runtime API key override (not persisted to disk).
   * Used for CLI --api-key flag.
   */
  setRuntimeApiKey(provider: string, apiKey: string): void;
  /**
   * Remove a runtime API key override.
   */
  removeRuntimeApiKey(provider: string): void;
  /**
   * Set a fallback resolver for API keys not found in auth.json or env vars.
   * Used for custom provider keys from models.json.
   */
  setFallbackResolver(resolver: (provider: string) => string | undefined): void;
  private recordError;
  private getCanonicalLoadError;
  private parseStorageData;
  private setData;
  /**
   * Reload credentials from storage.
   */
  reload(): void;
  private persistProviderChange;
  /**
   * Get credential for a provider.
   */
  get(provider: string): AuthCredential | undefined;
  /**
   * Set credential for a provider.
   */
  set(provider: string, credential: AuthCredential): void;
  /**
   * Remove credential for a provider.
   */
  remove(provider: string): void;
  /**
   * List all providers with credentials.
   */
  list(): string[];
  /**
   * Check if credentials exist for a provider in auth.json.
   */
  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 to an OAuth provider.
   */
  login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks$1): Promise<void>;
  /**
   * Logout from a provider.
   */
  logout(provider: string): 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 auth.json
   * 3. OAuth token from auth.json (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;
  /**
   * Get all OAuth providers registered for this auth/session runtime.
   */
  getOAuthProviders(): OAuthProviderInterface[];
}
//#endregion
//#region src/agents/sessions/model-registry-schema.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 ProviderAuthMode = Static<typeof ProviderAuthModeSchema>;
//#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;
  /** Optional streamSimple handler for custom APIs. */
  streamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStreamContract;
  /** Custom headers to include in requests. */
  headers?: Record<string, string>;
  /** If true, adds Authorization: Bearer header with the resolved API key. */
  authHeader?: boolean;
}
/** Configuration for a model within a provider. */
interface ProviderModelConfig {
  /** Model ID (e.g., "claude-sonnet-4-20250514"). */
  id: string;
  /** Display name (e.g., "Claude 4 Sonnet"). */
  name: string;
  /** API type override for this model. */
  api?: Api;
  /** API endpoint URL override for this model. */
  baseUrl?: string;
  /** Whether the model supports extended thinking. */
  reasoning: boolean;
  /** Maps OpenClaw thinking levels to provider/model-specific values; null marks a level unsupported. */
  thinkingLevelMap?: Model["thinkingLevelMap"];
  /** Supported input types. */
  input: ("text" | "image")[];
  /** Cost per token (for tracking, can be 0). */
  cost: {
    input: number;
    output: number;
    cacheRead: number;
    cacheWrite: number;
  };
  /** Maximum context window size in tokens. */
  contextWindow: number;
  /** Maximum output tokens. */
  maxTokens: number;
  /** Custom headers for this model. */
  headers?: Record<string, string>;
  /** OpenAI compatibility settings. */
  compat?: Model["compat"];
}
//#endregion
//#region src/agents/sessions/model-registry.d.ts
type ResolvedRequestAuth = {
  ok: true;
  apiKey?: string;
  headers?: Record<string, string>;
} | {
  ok: false;
  error: string;
};
type ModelRegistryOptions = {
  config?: OpenClawConfig;
  includePluginCatalogs?: boolean;
  modelsJsonContents?: string | null;
  pluginCatalogs?: readonly PersistedPluginModelCatalog[];
  staticProviderConfigs?: Readonly<Record<string, ModelProviderConfig>>;
  pluginMetadataSnapshot?: PluginModelCatalogMetadataSnapshot;
  sourceSnapshot?: ModelRegistry;
  workspaceDir?: string;
};
/**
 * Model registry - loads and manages models, resolves API keys via AuthStorage.
 */
declare class ModelRegistry {
  private models;
  private config;
  private providerRequestConfigs;
  private modelRequestHeaders;
  private registeredProviders;
  private loadError;
  readonly authStorage: AuthStorage;
  private modelsJsonPath;
  private modelsJsonContents;
  private pluginCatalogs;
  private staticProviderConfigs;
  private pluginMetadataSnapshot;
  private includePluginCatalogs;
  private baseCatalogSnapshot;
  private sourceSnapshot;
  private constructor();
  private captureCatalogSnapshot;
  private restoreSourceCatalog;
  static create(authStorage: AuthStorage, modelsJsonPath?: string, options?: ModelRegistryOptions): ModelRegistry;
  static inMemory(authStorage: AuthStorage): ModelRegistry;
  /** Creates a request-isolated registry from this lifecycle-owned catalog snapshot. */
  fork(authStorage: AuthStorage, publishedModels?: ReadonlyMap<string, readonly Model[]>): ModelRegistry;
  /**
   * Reload models from disk (models.json).
   */
  refresh(): void;
  /** 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 mergeProviderSources;
  private loadCapturedPluginCatalogs;
  private loadCustomModels;
  private validateConfig;
  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 getModelRequestKey;
  private storeProviderRequestConfig;
  private storeModelHeaders;
  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>;
  /**
   * Check if a model is using OAuth credentials (subscription).
   */
  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.
   */
  unregisterProvider(providerName: string): void;
  /**
   * Upsert a provider config into registeredProviders.
   * If the provider is already registered, defined values in the incoming config
   * override existing ones; undefined values are preserved from the stored config.
   * If the provider is not registered, the incoming config is stored as-is.
   */
  private upsertRegisteredProvider;
  private validateProviderConfig;
  private applyProviderConfig;
}
/**
 * Input type for registerProvider API.
 */
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/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.d.ts
interface BuildSystemPromptOptions {
  /** Custom system prompt (replaces default). */
  customPrompt?: string;
  /** Tools to include in prompt. Default: [read, bash, edit, write] */
  selectedTools?: string[];
  /** Optional one-line tool snippets keyed by tool name. */
  toolSnippets?: Record<string, string>;
  /** Additional guideline bullets appended to the default system prompt guidelines. */
  promptGuidelines?: string[];
  /** Text to append to system prompt. */
  appendSystemPrompt?: string;
  /** Working directory. */
  cwd: string;
  /** Pre-loaded context files. */
  contextFiles?: Array<{
    path: string;
    content: string;
  }>;
  /** Pre-loaded skills. */
  skills?: Skill[];
}
//#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.TInteger;
    totalBytes: 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 OAuthLoginCallbacks extends OAuthLoginCallbacks$1 {}
/** Options for extension UI dialogs. */
interface ExtensionUIDialogOptions {
  /** AbortSignal to programmatically dismiss the dialog. */
  signal?: AbortSignal;
  /** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */
  timeout?: number;
}
/** Placement for extension widgets. */
type WidgetPlacement = "aboveEditor" | "belowEditor";
/** Options for extension widgets. */
interface ExtensionWidgetOptions {
  /** Where the widget is rendered. Defaults to "aboveEditor". */
  placement?: WidgetPlacement;
}
/** Raw terminal input listener for extensions. */
type TerminalInputHandler = (data: string) => {
  consume?: boolean;
  data?: string;
} | undefined;
/** 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;
}
/** Wrap the current autocomplete provider with additional behavior. */
type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;
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 {
  /** Show a selector and return the user's choice. */
  select(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
  /** Show a confirmation dialog. */
  confirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;
  /** Show a text input dialog. */
  input(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
  /** Show a notification to the user. */
  notify(message: string, type?: "info" | "warning" | "error"): void;
  /** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */
  onTerminalInput(handler: TerminalInputHandler): () => 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;
  /** Set the text in the core input editor. */
  setEditorText(text: string): void;
  /** Get the current text from the core input editor. */
  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: AutocompleteProviderFactory): 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;
  /** Get the current theme for styling. */
  readonly theme: Theme;
  /** Get all available themes with their names and file paths. */
  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;
  /** Set the current theme by name or Theme object. */
  setTheme(theme: string | Theme): {
    success: boolean;
    error?: string;
  };
  /** Get current tool output expansion state. */
  getToolsExpanded(): boolean;
  /** Set tool output expansion state. */
  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;
}
/**
 * Context passed to extension event handlers.
 */
interface ExtensionContext {
  /** UI methods for user interaction */
  ui: ExtensionUIContext;
  /** Whether UI is available (false in print/RPC mode) */
  hasUI: boolean;
  /** Current working directory */
  cwd: string;
  /** Session manager (read-only) */
  sessionManager: ReadonlySessionManager;
  /** Model registry for API key resolution */
  modelRegistry: ModelRegistry;
  /** Current model (may be undefined) */
  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 the current agent operation */
  abort(): void;
  /** Whether there are queued messages waiting */
  hasPendingMessages(): boolean;
  /** Gracefully shut down OpenClaw and exit. Available in all contexts. */
  shutdown(): void;
  /** Get current context usage for the active model. */
  getContextUsage(): ContextUsage | undefined;
  /** Trigger compaction without awaiting completion. */
  compact(options?: CompactOptions): void;
  /** Get the current effective system prompt. */
  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>;
}
/** Rendering options for tool results */
interface ToolRenderResultOptions {
  /** Whether the result view is expanded */
  expanded: boolean;
  /** Whether this is a partial/streaming result */
  isPartial: boolean;
}
/** Context passed to tool renderers. */
interface ToolRenderContext<TState = unknown, TArgs = unknown> {
  /** 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;
  /** Working directory for this tool execution. */
  cwd: string;
  /** Whether the tool execution has started. */
  executionStarted: boolean;
  /** Whether the tool call arguments are complete. */
  argsComplete: boolean;
  /** Whether the tool result is partial/streaming. */
  isPartial: boolean;
  /** Whether the result view is expanded. */
  expanded: boolean;
  /** Whether inline images are currently shown in the TUI. */
  showImages: boolean;
  /** Whether the current result is an error. */
  isError: boolean;
}
type BivariantCallback<TArgs extends unknown[], TResult> = {
  bivarianceHack(...args: TArgs): TResult;
}["bivarianceHack"];
/**
 * Tool definition for registerTool().
 */
interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown> {
  /** Tool name (used in LLM tool calls) */
  name: string;
  /** Human-readable label for UI */
  label: string;
  /** Preserve lifecycle telemetry without rendering transient channel progress. */
  hideFromChannelProgress?: boolean;
  /** Tool results contain externally controlled network content. */
  resultContentSource?: AgentTool["resultContentSource"];
  /** Description for LLM */
  description: string;
  /** 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[];
  /** Parameter schema (TypeBox) */
  parameters: TParams;
  /** Exact schema for the structured value returned in AgentToolResult.details. */
  outputSchema?: TSchema;
  /** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */
  renderShell?: "default" | "self";
  /** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */
  prepareArguments?: (args: unknown) => Static<TParams>;
  /**
   * Per-tool execution mode override.
   * - "sequential": this tool must execute one at a time with other tool calls.
   * - "parallel": this tool can execute concurrently with other tool calls.
   *
   * If omitted, the default execution mode applies.
   */
  executionMode?: ToolExecutionMode;
  /** Execute the tool. */
  execute(toolCallId: string, params: Static<TParams>, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<TDetails> | undefined, ctx: ExtensionContext): Promise<AgentToolResult<TDetails>>;
  /** Custom rendering for tool call display */
  renderCall?: BivariantCallback<[args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>], Component>;
  /** Custom rendering for tool result display */
  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";
}
/** Result from resources_discover event handler */
interface ResourcesDiscoverResult {
  skillPaths?: string[];
  promptPaths?: string[];
  themePaths?: string[];
}
/** Fired when a session is started, loaded, or reloaded */
interface SessionStartEvent {
  type: "session_start";
  /** Why this session start happened. */
  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[];
  customInstructions?: string;
  signal: AbortSignal;
  /** Prepared reasoning level for extension-owned summarization. */
  thinkingLevel?: ThinkingLevel;
  /** Prepared provider stream for extension-owned summarization. */
  streamFn?: StreamFn;
}
/** 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;
}
/** Preparation data for tree navigation */
interface TreePreparation {
  targetId: string;
  oldLeafId: string | null;
  commonAncestorId: string | null;
  entriesToSummarize: SessionEntry[];
  userWantsSummary: boolean;
  /** Custom instructions for summarization */
  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;
}
type SessionEvent = SessionStartEvent | SessionBeforeSwitchEvent | SessionBeforeForkEvent | SessionBeforeCompactEvent | SessionCompactEvent | SessionShutdownEvent | SessionBeforeTreeEvent | SessionTreeEvent;
/** 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 attached to the user prompt, if any. */
  images?: ImageContent$1[];
  /** The fully assembled system prompt string. */
  systemPrompt: string;
  /** Structured options used to build the system prompt. Extensions can inspect this without re-discovering resources. */
  systemPromptOptions: BuildSystemPromptOptions;
}
/** Fired when an agent loop starts */
interface AgentStartEvent {
  type: "agent_start";
}
/** Fired when an agent loop ends */
interface AgentEndEvent {
  type: "agent_end";
  messages: AgentMessage[];
}
/** Fired once the session has no automatic retry, compaction, or queued continuation left. */
interface AgentSettledEvent {
  type: "agent_settled";
}
/** Fired at the start of each turn */
interface TurnStartEvent {
  type: "turn_start";
  turnIndex: number;
  timestamp: number;
}
/** Fired at the end of each turn */
interface TurnEndEvent {
  type: "turn_end";
  turnIndex: number;
  message: AgentMessage;
  toolResults: ToolResultMessage[];
}
/** Fired when a message starts (user, assistant, or toolResult) */
interface MessageStartEvent {
  type: "message_start";
  message: AgentMessage;
}
/** Fired during assistant message streaming with token-by-token updates */
interface MessageUpdateEvent {
  type: "message_update";
  message: AgentMessage;
  assistantMessageEvent: AssistantMessageEvent;
}
/** Fired when a message ends */
interface MessageEndEvent {
  type: "message_end";
  message: AgentMessage;
}
/** Fired when a tool starts executing */
interface ToolExecutionStartEvent {
  type: "tool_execution_start";
  toolCallId: string;
  toolName: string;
  args: unknown;
}
/** Fired during tool execution with partial/streaming output */
interface ToolExecutionUpdateEvent {
  type: "tool_execution_update";
  toolCallId: string;
  toolName: string;
  args: unknown;
  partialResult: unknown;
}
/** Fired when a tool finishes executing */
interface ToolExecutionEndEvent {
  type: "tool_execution_end";
  toolCallId: string;
  toolName: string;
  result: unknown;
  isError: boolean;
}
type ModelSelectSource = "set" | "cycle" | "restore";
/** Fired when a new model is selected */
interface ModelSelectEvent {
  type: "model_select";
  model: Model;
  previousModel: Model | undefined;
  source: ModelSelectSource;
}
/** Fired when a new thinking level is selected */
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";
  /** The command to execute */
  command: string;
  /** True if !! prefix was used (excluded from LLM context) */
  excludeFromContext: boolean;
  /** Current working directory */
  cwd: string;
}
/** Source of user input */
type InputSource = "interactive" | "rpc" | "extension";
/** Fired when user input is received, before agent processing */
interface InputEvent {
  type: "input";
  /** The input text */
  text: string;
  /** Attached images, if any */
  images?: ImageContent$1[];
  /** Where the input came from */
  source: InputSource;
}
/** Result from input event handler */
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;
}
type BashToolCallEvent = ToolCallEventBase<"bash", BashToolInput>;
type ReadToolCallEvent = ToolCallEventBase<"read", ReadToolInput>;
type EditToolCallEvent = ToolCallEventBase<"edit", EditToolInput>;
type WriteToolCallEvent = ToolCallEventBase<"write", WriteToolInput>;
type GrepToolCallEvent = ToolCallEventBase<"grep", GrepToolInput>;
type FindToolCallEvent = ToolCallEventBase<"find", FindToolInput>;
type LsToolCallEvent = ToolCallEventBase<"ls", LsToolInput>;
type CustomToolCallEvent = ToolCallEventBase<string, Record<string, unknown>>;
/**
 * 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 = BashToolCallEvent | ReadToolCallEvent | EditToolCallEvent | WriteToolCallEvent | GrepToolCallEvent | FindToolCallEvent | LsToolCallEvent | CustomToolCallEvent;
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;
}
type BashToolResultEvent = ToolResultEventBase<"bash", BashToolDetails | undefined>;
type ReadToolResultEvent = ToolResultEventBase<"read", ReadToolDetails | undefined>;
type EditToolResultEvent = ToolResultEventBase<"edit", EditToolDetails | undefined>;
type WriteToolResultEvent = ToolResultEventBase<"write", undefined>;
type GrepToolResultEvent = ToolResultEventBase<"grep", GrepToolDetails | undefined>;
type FindToolResultEvent = ToolResultEventBase<"find", FindToolDetails | undefined>;
type LsToolResultEvent = ToolResultEventBase<"ls", LsToolDetails | undefined>;
type CustomToolResultEvent = ToolResultEventBase<string, unknown>;
/** Fired after a tool executes. Can modify result. */
type ToolResultEvent = BashToolResultEvent | ReadToolResultEvent | EditToolResultEvent | WriteToolResultEvent | GrepToolResultEvent | FindToolResultEvent | LsToolResultEvent | CustomToolResultEvent;
/** Union of all event types */
type ExtensionEvent = ResourcesDiscoverEvent | SessionEvent | 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;
}
/** Result from user_bash event handler */
interface UserBashEventResult {
  /** Custom operations to use for execution */
  operations?: BashOperations;
  /** Full replacement: extension handled execution, use this result */
  result?: BashResult;
}
interface ToolResultEventResult {
  content?: (TextContent | ImageContent$1)[];
  details?: unknown;
  isError?: boolean;
  terminate?: boolean;
}
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;
}
/** Handler function type for events */
type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;
/**
 * ExtensionAPI passed to extension factory functions.
 */
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;
  /** Register a tool that the LLM can call. */
  registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(tool: ToolDefinition<TParams, TDetails, TState>): void;
  /** Register a custom command. */
  registerCommand(name: string, options: Omit<RegisteredCommand, "name" | "sourceInfo">): void;
  /** Register a keyboard shortcut. */
  registerShortcut(shortcut: KeyId, options: {
    description?: string;
    handler: (ctx: ExtensionContext) => Promise<void> | void;
  }): void;
  /** Register a CLI flag. */
  registerFlag(name: string, options: {
    description?: string;
    type: "boolean" | "string";
    default?: boolean | string;
  }): void;
  /** Get the value of a registered CLI flag. */
  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;
  /** Append a custom entry to the session for state persistence (not sent to LLM). */
  appendEntry(customType: string, data?: unknown): void;
  /** Set the session display name (shown in session selector). */
  setSessionName(name: string): void;
  /** Get the current session name, if set. */
  getSessionName(): string | undefined;
  /** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */
  setLabel(entryId: string, label: string | undefined): void;
  /** Execute a shell command. */
  exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
  /** Get the list of currently active tool names. */
  getActiveTools(): string[];
  /** Get all configured tools with parameter schema and source metadata. */
  getAllTools(): ToolInfo[];
  /** Set the active tools by name. */
  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>;
  /** Get current thinking level. */
  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;
}
/** Configuration for registering a provider via api.registerProvider(). */
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?: {
    /** Display name for the provider in login UI. */
    name: string;
    /** Run the login flow, return credentials to persist. */
    login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
    /** Refresh expired credentials, return updated credentials to persist. */
    refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;
    /** Convert credentials to API key string for the provider. */
    getApiKey(credentials: OAuthCredentials): string;
    /** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */
    modifyModels?(models: Model[], credentials: OAuthCredentials): Model[];
  };
}
interface RegisteredTool {
  definition: ToolDefinition;
  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 HandlerFn = (...args: unknown[]) => Promise<unknown>;
type RefreshToolsHandler = () => void;
/** Tool info with name, description, parameter schema, and source metadata */
type ToolInfo = Pick<ToolDefinition, "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.
 */
interface ExtensionActions extends Pick<ExtensionAPI, "sendMessage" | "sendUserMessage" | "appendEntry" | "setSessionName" | "getSessionName" | "setLabel" | "getActiveTools" | "getAllTools" | "setActiveTools" | "getCommands" | "setModel" | "getThinkingLevel" | "setThinkingLevel"> {
  refreshTools: RefreshToolsHandler;
}
/** 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().
 */
interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}
/** Loaded extension with all registered items. */
interface Extension {
  path: string;
  resolvedPath: string;
  sourceInfo: SourceInfo;
  handlers: Map<string, HandlerFn[]>;
  tools: Map<string, RegisteredTool>;
  messageRenderers: Map<string, MessageRenderer>;
  commands: Map<string, RegisteredCommand>;
  flags: Map<string, ExtensionFlag>;
  shortcuts: Map<KeyId, ExtensionShortcut>;
}
/** Result of loading extensions. */
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
/** Combined result from all before_agent_start handlers */
interface BeforeAgentStartCombinedResult {
  messages?: NonNullable<BeforeAgentStartEventResult["message"]>[];
  systemPrompt?: 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);
  bindCore(actions: ExtensionActions, contextActions: ExtensionContextActions, providerActions?: {
    registerProvider?: (name: string, config: ProviderConfig) => void;
    unregisterProvider?: (name: string) => void;
  }): void;
  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[];
  /** Get a tool definition by name. Returns undefined if not found. */
  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 isSessionBeforeEvent;
  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<{
    skillPaths: Array<{
      path: string;
      extensionPath: string;
    }>;
    promptPaths: Array<{
      path: string;
      extensionPath: string;
    }>;
    themePaths: Array<{
      path: string;
      extensionPath: string;
    }>;
  }>;
  /** 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
/**
 * Represents a prompt template loaded from a markdown file
 */
interface PromptTemplate {
  name: string;
  description: string;
  argumentHint?: string;
  content: string;
  sourceInfo: SourceInfo;
  filePath: string;
}
//#endregion
//#region src/agents/sessions/settings-storage.d.ts
interface CompactionSettings {
  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 {
  minimal?: number;
  low?: number;
  medium?: number;
  high?: number;
  max?: number;
}
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;
}
type SettingsScope = "global" | "project";
interface SettingsStorage {
  /** Pure scope reads; existing custom backends may serve reads through withLock. */
  readSettingsScope?(scope: SettingsScope): string | undefined;
  withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;
}
interface SettingsError {
  scope: SettingsScope;
  error: Error;
}
//#endregion
//#region src/agents/sessions/settings-manager.d.ts
declare class SettingsManager {
  private storage;
  private scopes;
  private settings;
  private runtimeOverrides;
  private writeQueue;
  private errors;
  private constructor();
  /** Create a SettingsManager that loads from files */
  static create(cwd: string, agentDir?: string): SettingsManager;
  /** Create a SettingsManager from an arbitrary storage backend */
  static fromStorage(storage: SettingsStorage): SettingsManager;
  /** Create an in-memory SettingsManager (no file I/O) */
  static inMemory(settings?: Partial<Settings>): SettingsManager;
  private static loadScope;
  private static createScopeState;
  /** Migrate old settings format to new format */
  private static migrateSettings;
  getGlobalSettings(): Settings;
  getProjectSettings(): Settings;
  private recomputeSettings;
  reload(): Promise<void>;
  /** Apply non-persisted overrides on top of global/project settings. */
  applyOverrides(overrides: Partial<Settings>): void;
  private markModified;
  private recordError;
  private enqueueWrite;
  private persistScopedSettings;
  private save;
  private setScopedSetting;
  private setGlobalNestedSetting;
  flush(): Promise<void>;
  drainErrors(): SettingsError[];
  getLastChangelogVersion(): string | undefined;
  setLastChangelogVersion(version: string): void;
  getSessionDir(): string | undefined;
  getDefaultProvider(): string | undefined;
  getDefaultModel(): string | undefined;
  setDefaultProvider(provider: string): void;
  setDefaultModel(modelId: string): void;
  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;
  getTheme(): string | undefined;
  setTheme(theme: string): void;
  getDefaultThinkingLevel(): Settings["defaultThinkingLevel"];
  setDefaultThinkingLevel(level: NonNullable<Settings["defaultThinkingLevel"]>): void;
  getTransport(): TransportSetting;
  setTransport(transport: TransportSetting): void;
  getCompactionEnabled(): boolean;
  setCompactionEnabled(enabled: boolean): void;
  getCompactionReserveTokens(): number;
  getCompactionKeepRecentTokens(): number;
  getCompactionSettings(): {
    enabled: boolean;
    reserveTokens: number;
    keepRecentTokens: number;
  };
  getBranchSummarySettings(): {
    reserveTokens: number;
    skipPrompt: boolean;
  };
  getBranchSummarySkipPrompt(): boolean;
  getRetryEnabled(): boolean;
  setRetryEnabled(enabled: boolean): void;
  getRetrySettings(): {
    enabled: boolean;
    maxRetries: number;
    baseDelayMs: number;
  };
  getHttpIdleTimeoutMs(): number;
  setHttpIdleTimeoutMs(timeoutMs: number): void;
  getProviderRetrySettings(): {
    timeoutMs?: number;
    maxRetries?: number;
    maxRetryDelayMs: number;
  };
  getHideThinkingBlock(): boolean;
  setHideThinkingBlock(hide: boolean): void;
  getShellPath(): string | undefined;
  setShellPath(path: string | undefined): void;
  getQuietStartup(): boolean;
  setQuietStartup(quiet: boolean): void;
  getShellCommandPrefix(): string | undefined;
  setShellCommandPrefix(prefix: string | undefined): void;
  getNpmCommand(): string[] | undefined;
  setNpmCommand(command: string[] | undefined): void;
  getCollapseChangelog(): boolean;
  setCollapseChangelog(collapse: boolean): void;
  getEnableInstallTelemetry(): boolean;
  setEnableInstallTelemetry(enabled: boolean): void;
  getPackages(): PackageSource[];
  setPackages(packages: PackageSource[]): void;
  setProjectPackages(packages: PackageSource[]): void;
  getExtensionPaths(): string[];
  setExtensionPaths(paths: string[]): void;
  setProjectExtensionPaths(paths: string[]): void;
  getSkillPaths(): string[];
  setSkillPaths(paths: string[]): void;
  setProjectSkillPaths(paths: string[]): void;
  getPromptTemplatePaths(): string[];
  setPromptTemplatePaths(paths: string[]): void;
  setProjectPromptTemplatePaths(paths: string[]): void;
  getThemePaths(): string[];
  setThemePaths(paths: string[]): void;
  setProjectThemePaths(paths: string[]): void;
  getEnableSkillCommands(): boolean;
  setEnableSkillCommands(enabled: boolean): void;
  getThinkingBudgets(): ThinkingBudgetsSettings | undefined;
  getShowImages(): boolean;
  setShowImages(show: boolean): void;
  getImageWidthCells(): number;
  setImageWidthCells(width: number): void;
  getClearOnShrink(): boolean;
  setClearOnShrink(enabled: boolean): void;
  getShowTerminalProgress(): boolean;
  setShowTerminalProgress(enabled: boolean): void;
  getImageAutoResize(): boolean;
  setImageAutoResize(enabled: boolean): void;
  getBlockImages(): boolean;
  setBlockImages(blocked: boolean): void;
  getEnabledModels(): string[] | undefined;
  setEnabledModels(patterns: string[] | undefined): void;
  getDoubleEscapeAction(): "fork" | "tree" | "none";
  setDoubleEscapeAction(action: "fork" | "tree" | "none"): void;
  getTreeFilterMode(): "default" | "no-tools" | "user-only" | "labeled-only" | "all";
  setTreeFilterMode(mode: "default" | "no-tools" | "user-only" | "labeled-only" | "all"): void;
  getShowHardwareCursor(): boolean;
  setShowHardwareCursor(enabled: boolean): void;
  getEditorPaddingX(): number;
  setEditorPaddingX(padding: number): void;
  getAutocompleteMaxVisible(): number;
  setAutocompleteMaxVisible(maxVisible: number): void;
  getCodeBlockIndent(): string;
  getWarnings(): WarningSettings;
  setWarnings(warnings: WarningSettings): void;
}
//#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[];
  };
  getAgentsFiles(): {
    agentsFiles: Array<{
      path: string;
      content: string;
    }>;
  };
  getSystemPrompt(): string | undefined;
  getAppendSystemPrompt(): string[];
  extendResources(paths: ResourceExtensionPaths): void;
  reload(): Promise<void>;
}
//#endregion
//#region src/agents/sessions/agent-session-types.d.ts
type AgentSessionCompactionOutcome = {
  status: "completed";
  tokensBefore: number;
  tokensAfter: number;
  willRetry: boolean;
} | {
  status: "skipped";
  reason: string;
} | {
  status: "failed";
  reason: string;
} | {
  status: "aborted";
};
type AgentSessionCompactionEndEvent = {
  type: "compaction_end";
  itemId?: string;
  reason: "manual" | "threshold" | "overflow";
  outcome: AgentSessionCompactionOutcome;
};
type AgentSessionEvent = Exclude<AgentEvent, {
  type: "agent_end";
}> | {
  type: "agent_end";
  messages: AgentMessage[];
  willRetry: boolean;
  assistantEntryId?: string;
} | {
  type: "queue_update";
  steering: readonly string[];
  followUp: readonly string[];
} | {
  type: "agent_settled";
} | {
  type: "agent_handoff";
} | {
  type: "compaction_start";
  reason: "manual" | "threshold" | "overflow";
  itemId?: string;
} | {
  type: "session_info_changed";
  name: string | undefined;
} | {
  type: "thinking_level_changed";
  level: ThinkingLevel;
} | AgentSessionCompactionEndEvent | {
  type: "auto_retry_start";
  attempt: number;
  maxAttempts: number;
  delayMs: number;
  errorMessage: string;
} | {
  type: "auto_retry_end";
  success: boolean;
  attempt: number;
  finalError?: string;
};
type AgentSessionEventListener = (event: AgentSessionEvent) => unknown;
type AgentSessionWriteSettlementRunner = <T>(run: () => Promise<T> | T) => Promise<T>;
interface AgentSessionConfig {
  agent: Agent$1;
  sessionManager: SessionManager;
  settingsManager: SettingsManager;
  cwd: string;
  /** Resource loader for skills, prompts, themes, context files, and system prompt. */
  resourceLoader: ResourceLoader;
  /** SDK custom tools registered outside extensions. */
  customTools?: ToolDefinition[];
  /** Model registry for API key resolution and model discovery. */
  modelRegistry: ModelRegistry;
  /** Initial active built-in tool names. Defaults to read, bash, edit, and write. */
  initialActiveToolNames?: string[];
  /** Optional tool allowlist. */
  allowedToolNames?: string[];
  /** Exclude built-in shell and filesystem tools from the registry. */
  disableBuiltInTools?: boolean;
  /** Override base tools for custom runtimes. */
  baseToolsOverride?: Record<string, AgentTool>;
  /** Mutable reference used by Agent to access the current extension runner. */
  extensionRunnerRef?: {
    current?: ExtensionRunner;
  };
  /** Session start metadata emitted when extensions bind to this runtime. */
  sessionStartEvent?: SessionStartEvent;
  /** Settlement boundary for session writes and write-capable hooks. */
  withSessionWriteSettlement?: AgentSessionWriteSettlementRunner;
  /** Owner of reactive context-overflow recovery. Defaults to the session. */
  contextOverflowRecoveryOwner?: "session" | "caller";
  /** 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;
  /** Image attachments. */
  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/compaction/request-budget.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;
  pendingUserEntryId?: string;
}>;
//#endregion
//#region src/agents/sessions/agent-session-base.d.ts
interface ToolDefinitionEntry {
  definition: ToolDefinition;
  sourceInfo: SourceInfo;
}
type ActiveToolPromptMetadata = {
  validToolNames: string[];
  toolSnippets: Record<string, string>;
  promptGuidelines: string[];
};
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 branchSummaryAbortController: AbortController | undefined;
  private extensionModifiedToolResultIds;
  protected retryAbortController: AbortController | undefined;
  protected retryCount: number;
  protected currentExtensionRunner: ExtensionRunner;
  private turnIndex;
  protected sessionResourceLoader: ResourceLoader;
  protected customTools: ToolDefinition[];
  protected baseToolDefinitions: Map<string, ToolDefinition>;
  protected cwd: string;
  protected extensionRunnerRef?: {
    current?: ExtensionRunner;
  };
  protected initialActiveToolNames?: string[];
  protected allowedToolNames?: Set<string>;
  protected disableBuiltInTools: boolean;
  protected baseToolsOverride?: Record<string, AgentTool>;
  protected sessionStartEvent: SessionStartEvent;
  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;
  protected toolRegistry: Map<string, AgentTool>;
  protected toolDefinitions: Map<string, ToolDefinitionEntry>;
  protected toolPromptSnippets: Map<string, string>;
  protected toolPromptGuidelines: Map<string, string[]>;
  protected baseSystemPrompt: string;
  protected baseSystemPromptOptions: BuildSystemPromptOptions;
  protected exactBaseSystemPrompt: string | undefined;
  protected systemPromptOverride: string | undefined;
  constructor(config: AgentSessionConfig);
  /** Model registry for API key resolution and model discovery */
  get modelRegistry(): ModelRegistry;
  protected getRequiredRequestAuth(model: Model): Promise<{
    apiKey: string;
    headers?: Record<string, string>;
  }>;
  protected getCompactionRequestAuth(model: Model): Promise<{
    apiKey?: string;
    headers?: Record<string, string>;
  }>;
  protected runWithSessionWriteSettlement<T>(run: () => Promise<T> | T): Promise<T>;
  private eventMayWriteSession;
  /**
   * Install tool hooks once on the Agent instance.
   *
   * The callbacks read `this.currentExtensionRunner` at execution time, so extension reload swaps in the
   * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
   * registered tool execution to the extension context. Tool call and tool result interception now
   * happens here instead of in wrappers.
   */
  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: AssistantMessage$1 | undefined;
  private lastAssistantEntryId;
  protected lastRunEndedForTurnHandoff: boolean;
  /** Internal handler for agent events - shared by subscribe and reconnect */
  protected handleAgentEvent: (event: AgentEvent, signal?: AbortSignal) => Promise<void>;
  private handleAgentEventUnlocked;
  private willRetryAfterAgentEnd;
  /** Find the last assistant message in agent state (including aborted ones) */
  protected findLastAssistantMessage(): AssistantMessage$1 | undefined;
  /** Emit extension events based on agent events */
  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;
  /** Full agent state */
  get state(): AgentState;
  /** Current model (may be undefined if not yet selected) */
  get model(): Model | undefined;
  /** Current thinking level */
  get thinkingLevel(): ThinkingLevel;
  /** Whether agent is currently streaming a response */
  get isStreaming(): boolean;
  /** Current effective system prompt (includes any per-turn extension modifications) */
  get systemPrompt(): string;
  /** Current retry attempt (0 if not retrying) */
  get retryAttempt(): number;
  /**
   * Get the names of currently active tools.
   * Returns the names of tools currently set on the agent.
   */
  getActiveToolNames(): string[];
  /**
   * Get all configured tools with name, description, parameter schema, and source metadata.
   */
  getAllTools(): ToolInfo[];
  getToolDefinition(name: string): ToolDefinition | undefined;
  /**
   * Set active tools by name.
   * Only tools in the registry can be enabled. Unknown tool names are ignored.
   * Also rebuilds the system prompt to reflect the new tool set.
   * Changes take effect on the next agent turn.
   */
  setActiveToolsByName(toolNames: string[]): void;
  /** Set an exact base prompt owned by the current runtime. */
  setBaseSystemPrompt(systemPrompt: string): void;
  /** Whether compaction or branch summarization is currently running */
  get isCompacting(): boolean;
  /** All messages including custom types like BashExecutionMessage */
  get messages(): AgentMessage[];
  /** Current steering mode */
  get steeringMode(): "all" | "one-at-a-time";
  /** Current follow-up mode */
  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;
  /** Current session ID */
  get sessionId(): string;
  /** Current session display name, if set */
  get sessionName(): string | undefined;
  /** File-based prompt templates */
  get promptTemplates(): ReadonlyArray<PromptTemplate>;
  protected normalizePromptSnippet(text: string | undefined): string | undefined;
  protected normalizePromptGuidelines(guidelines: string[] | undefined): string[];
  protected collectActiveToolPromptMetadata(toolNames: string[]): ActiveToolPromptMetadata;
  protected rebuildSystemPrompt(toolNames: string[]): string;
  protected abstract isRetryableError(message: AssistantMessage$1): boolean;
  protected abstract prepareRetry(message: AssistantMessage$1): Promise<boolean>;
  protected abstract checkCompaction(assistantMessage: AssistantMessage$1, skipAbortedCheck?: boolean, requestBudget?: CompactionRequestBudget): Promise<boolean>;
  abstract abortRetry(): void;
  abstract abortCompaction(): void;
  abstract abortBranchSummary(): void;
}
//#endregion
//#region src/agents/sessions/agent-session-prompting.d.ts
/** @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;
  [agentSessionSetPromptPreparation](prepare: (() => Promise<void | (() => void)>) | 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>;
  /**
   * Try to execute an extension command. Returns true if command was found and executed.
   */
  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 images Optional image attachments to include with the message
   * @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): 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.
   * @param images Optional image attachments to include with the message
   * @throws Error if text is an extension command
   */
  followUp(text: string, images?: ImageContent$1[]): Promise<void>;
  /**
   * Internal: Queue a steering message (already expanded, no extension command check).
   */
  private queueSteer;
  /**
   * Internal: Queue a follow-up message (already expanded, no extension command check).
   */
  private queueFollowUp;
  /**
   * Throw an error if the text is an extension command.
   */
  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 message Custom message with customType, content, display, details
   * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
   * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
   */
  sendCustomMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
    triggerTurn?: boolean;
    deliverAs?: "steer" | "followUp" | "nextTurn";
  }): Promise<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.
   *
   * @param content User message content (string or content array)
   * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
   */
  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.
   * @returns Object with steering and followUp arrays
   */
  clearQueue(): {
    steering: string[];
    followUp: string[];
  };
  /** Number of pending messages (includes both steering and follow-up) */
  get pendingMessageCount(): number;
  /** Get pending steering messages (read-only) */
  getSteeringMessages(): readonly string[];
  /** Get pending follow-up messages (read-only) */
  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-models.d.ts
declare abstract class AgentSessionModels 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;
  /**
   * Get available thinking levels for current model.
   * The provider will clamp to what the specific model supports internally.
   */
  getAvailableThinkingLevels(): ThinkingLevel[];
  /**
   * Check if current model supports thinking/reasoning.
   */
  supportsThinking(): boolean;
  private getThinkingLevelForModelSwitch;
  /**
   * Set steering message mode.
   * Saves to settings.
   */
  setSteeringMode(mode: "all" | "one-at-a-time"): void;
  /**
   * Set follow-up message mode.
   * Saves to settings.
   */
  setFollowUpMode(mode: "all" | "one-at-a-time"): void;
}
//#endregion
//#region src/agents/sessions/agent-session-inspection.d.ts
declare abstract class AgentSessionInspection extends AgentSessionModels {
  /**
   * Set a display name for the current session.
   */
  setSessionName(name: string): void;
  getContextUsage(): ContextUsage | undefined;
  /**
   * Export the current session branch to a JSONL file.
   * Writes the session header followed by all entries on the current branch path.
   * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
   * @returns The resolved output file path.
   */
  exportToJsonl(outputPath?: string): string;
  /**
   * Get text content of last assistant message.
   * Useful for /copy command.
   * @returns Text content, or undefined if no assistant message exists
   */
  getLastAssistantText(): string | undefined;
}
//#endregion
//#region src/agents/sessions/agent-session-compaction.d.ts
type CompactionRequestState = "unresolved";
type SummaryOutputPolicy = "none" | "retry-invalid-once";
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 {
  private onContextReplaced?;
  private assertContextReplacementActive?;
  [agentSessionSetContextReplacementHook](callback: ((tokensAfter: number, tokensBefore: number) => void) | undefined, assertActive?: () => void): void;
  /**
   * Manually compact the session context.
   * Aborts current agent operation first.
   * @param customInstructions Optional instructions for the compaction summary
   */
  compact(customInstructions?: string): Promise<CompactionResult>;
  [agentSessionAutomaticCompaction](customInstructions?: string, requestState?: CompactionRequestState, summaryOutputPolicy?: SummaryOutputPolicy, constraints?: CompactionRequestConstraints): Promise<SettledCompactionWorkOutcome>;
  private compactWithSessionWriteSettlement;
  /**
   * Cancel in-progress compaction (manual or auto).
   */
  abortCompaction(): void;
  /**
   * Cancel in-progress branch summarization.
   */
  abortBranchSummary(): void;
  private runCompactionWork;
  /**
   * Check if compaction is needed and run it.
   * Called after agent_end and before prompt submission.
   *
   * Two cases:
   * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
   * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
   *
   * @param assistantMessage The assistant message to check
   * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
   */
  protected checkCompaction(assistantMessage: AssistantMessage$1, skipAbortedCheck?: boolean, requestBudget?: CompactionRequestBudget): Promise<boolean>;
  /**
   * Internal: Run auto-compaction with events.
   */
  private runAutoCompaction;
  /**
   * Toggle auto-compaction setting.
   */
  setAutoCompactionEnabled(enabled: boolean): void;
  /** Whether auto-compaction is enabled */
  get autoCompactionEnabled(): boolean;
}
//#endregion
//#region src/agents/sessions/agent-session-extensions.d.ts
declare abstract class AgentSessionExtensions extends AgentSessionCompaction {
  bindExtensions(bindings: ExtensionBindings): Promise<void>;
  private extendResourcesFromExtensions;
  private buildExtensionResourcePaths;
  private getExtensionSourceLabel;
  private applyExtensionBindings;
  private refreshCurrentModelFromRegistry;
  private bindExtensionCore;
  /** Replace a runtime-owned tool surface without restarting its active agent loop. */
  replaceCustomTools(customTools: ToolDefinition[], activeToolNames: string[]): void;
  private refreshToolRegistry;
  protected buildRuntime(options: {
    activeToolNames?: string[];
    flagValues?: Map<string, boolean | string>;
    includeAllExtensionTools?: boolean;
  }): void;
  reload(): Promise<void>;
}
//#endregion
//#region src/agents/sessions/agent-session-execution.d.ts
declare abstract class AgentSessionExecution extends AgentSessionExtensions {
  /**
   * Check if an error is retryable (overloaded, rate limit, server errors).
   * Context overflow errors are NOT retryable (handled by compaction instead).
   */
  protected isRetryableError(message: AssistantMessage$1): boolean;
  /**
   * Prepare a retryable error for continuation with exponential backoff.
   * @returns true if the caller should continue the agent, false otherwise
   */
  protected prepareRetry(message: AssistantMessage$1): Promise<boolean>;
  /**
   * Cancel in-progress retry.
   */
  abortRetry(): void;
  /** Whether auto-retry is currently in progress */
  get isRetrying(): boolean;
  /** Whether auto-retry is enabled */
  get autoRetryEnabled(): boolean;
  /**
   * Toggle auto-retry setting.
   */
  setAutoRetryEnabled(enabled: boolean): void;
}
//#endregion
//#region src/agents/sessions/agent-session-tree.d.ts
declare abstract class AgentSessionTree extends AgentSessionExecution {
  /**
   * Navigate to a different node in the session tree.
   * Unlike fork() which creates a new session file, this stays in the same file.
   *
   * @param targetId The entry ID to navigate to
   * @param options.summarize Whether user wants to summarize abandoned branch
   * @param options.customInstructions Custom instructions for summarizer
   * @param options.replaceInstructions If true, customInstructions replaces the default prompt
   * @param options.label Label to attach to the branch summary entry
   * @returns Result with editorText (if user message) and cancelled status
   */
  navigateTree(targetId: string, options?: {
    summarize?: boolean;
    customInstructions?: string;
    replaceInstructions?: boolean;
    label?: string;
  }): Promise<{
    editorText?: string;
    cancelled: boolean;
    aborted?: boolean;
    summaryEntry?: BranchSummaryEntry;
  }>;
  /**
   * Get all user messages from session for fork selector.
   */
  getUserMessagesForForking(): Array<{
    entryId: string;
    text: string;
  }>;
  createReplacedSessionContext(): ReplacedSessionContext;
  /**
   * Check if extensions have handlers for a specific event type.
   */
  hasExtensionHandlers(eventType: string): boolean;
  /**
   * Get the extension runner (for setting UI context and error handlers).
   */
  get extensionRunner(): ExtensionRunner;
}
//#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 AgentSessionTree {
  constructor(config: AgentSessionConfig);
}
//#endregion
//#region src/agents/assistant-error-transcript.d.ts
type AssistantMessage = Extract<AgentMessage, {
  role: "assistant";
}>;
type TranscriptTarget = NonNullable<ReturnType<SessionManager["getSessionTarget"]>>;
/** Holds attempt failures until the logical run decides whether recovery succeeded. */
declare function createAssistantErrorTranscript(params: {
  runId: string;
  config?: OpenClawConfig;
}): {
  clear: () => void;
  bindStream(source: AgentMessage, replaceStream: (visible: boolean) => void): void;
  snapshot(): {
    message: AssistantMessage;
    source: AgentMessage;
    target: TranscriptTarget;
    assertActive: () => void;
    replaceStream?: (visible: boolean) => void;
  } | undefined;
  restore(snapshot: {
    message: AssistantMessage;
    source: AgentMessage;
    target: TranscriptTarget;
    assertActive: () => void;
    replaceStream?: (visible: boolean) => void;
  } | undefined): void;
  record(message: AssistantMessage, target: TranscriptTarget, source?: AgentMessage): AssistantMessage | undefined;
  settle(failed: boolean): Promise<void>;
};
type AssistantErrorTranscript = ReturnType<typeof createAssistantErrorTranscript>;
//#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;
  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/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/agents/bash-tools.shared.d.ts
/** Sandbox metadata needed to map host workspaces into container exec calls. */
type BashSandboxWorkdirMount = {
  hostPath: string;
  containerPath: string;
};
type BashSandboxConfig = {
  containerName: string;
  workspaceDir: string;
  containerWorkdir: string;
  workdirValidation?: SandboxBackendWorkdirValidation;
  validateWorkdir?: SandboxBackendWorkdirValidator;
  discardPreparedWorkdir?: (workdir: string) => void;
  workdirRoots?: readonly string[];
  /** Approved read-only skill mounts that may be selected as an exec workdir. */
  readOnlyWorkspaceSkillMounts?: readonly BashSandboxWorkdirMount[];
  env?: Record<string, string>;
  prepareProcessCleanup?: SandboxBackendHandle["prepareProcessCleanup"];
  buildExecSpec?: (params: {
    command: string;
    workdir?: string;
    env: Record<string, string>;
    usePty: boolean;
  }) => Promise<SandboxBackendExecSpec>;
  finalizeExec?: (params: {
    status: "completed" | "failed";
    exitCode: number | null;
    timedOut: boolean;
    token?: unknown;
  }) => Promise<void>;
};
//#endregion
//#region src/auto-reply/heartbeat-tool-response.d.ts
/** Allowed heartbeat response outcomes. */
declare const HEARTBEAT_TOOL_OUTCOMES: readonly ["no_change", "progress", "done", "blocked", "needs_attention"];
type HeartbeatToolOutcome = (typeof HEARTBEAT_TOOL_OUTCOMES)[number];
/** Allowed heartbeat notification priorities. */
declare const HEARTBEAT_TOOL_PRIORITIES: readonly ["low", "normal", "high"];
type HeartbeatToolPriority = (typeof HEARTBEAT_TOOL_PRIORITIES)[number];
/** Normalized response emitted by the heartbeat response tool. */
type HeartbeatToolResponse = {
  outcome: HeartbeatToolOutcome;
  notify: boolean;
  summary: string;
  notificationText?: string;
  reason?: string;
  priority?: HeartbeatToolPriority;
  nextCheck?: string;
  /** Complete replacement for the current heartbeat monitor's private scratch. */
  scratch?: string;
};
//#endregion
//#region src/agents/accepted-session-spawn.d.ts
type AcceptedSessionSpawn = {
  runId: string;
  childSessionKey: string;
  sessionUrl?: string;
  label?: string;
  /** True only when this child owns a terminal completion for its requester. */
  expectsCompletionMessage?: boolean;
};
//#endregion
//#region src/agents/agent-run-terminal-receipt.d.ts
type AgentRunTerminalModelRef = {
  provider: string;
  model: string;
};
type AgentRunTerminalReceipt = {
  runId: string;
  sessionId: string;
  turnId: string;
  requested: AgentRunTerminalModelRef;
  effective: AgentRunTerminalModelRef & {
    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/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, "audioAsVoice" | "attachments" | "channelData" | "interactive" | "mediaUrl" | "mediaUrls" | "presentation" | "text" | "trustedLocalMedia"> & {
  idempotencyKey?: string;
  transcriptOwner?: true;
  /** Current-source progress (`false`) or completed reply (`true`). */
  sourceReplyFinal?: boolean;
};
//#endregion
//#region src/agents/mcp-connect-action.d.ts
type McpConnectAction = {
  serverName: string;
  authorizationUrl: string;
};
//#endregion
//#region src/agents/mcp-ui-resource.d.ts
type McpAppChannelView = {
  viewId: string;
};
//#endregion
//#region src/agents/model-fallback.types.d.ts
type ModelCandidate = {
  provider: string;
  model: string;
};
type ModelFallbackRouteResolution = "raw" | "resolved";
type FallbackAttempt = ModelCandidate & {
  error: string;
  reason?: FailoverReason;
  authMode?: string;
  status?: number;
  code?: string;
};
/** Original route plus the outer fallback stage that admitted one real attempt. */
type ModelFallbackAttemptProvenance = {
  requestedProvider: string;
  requestedModel: string;
  stage: "initial" | "fallback";
  /** A user switch invalidates automatic routing for the original selection for this cycle. */
  selectionChanged?: boolean;
  fallbackReason?: FailoverReason;
};
//#endregion
//#region src/plugins/manifest-model-id-normalization.d.ts
/** Caller-owned declarations or facts from an already selected metadata snapshot. */
type ManifestModelIdNormalizationSource = readonly Pick<PluginManifestRecord, "modelIdNormalization">[] | {
  owners: Pick<PluginMetadataSnapshot["owners"], "modelIdNormalizationPolicies">;
};
//#endregion
//#region src/agents/model-ref-shared.d.ts
type ModelManifestNormalizationContext = {
  manifestPlugins?: ManifestModelIdNormalizationSource;
};
//#endregion
//#region src/agents/workspace.d.ts
declare function ensureAgentWorkspace(params?: {
  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. */
  beforePersistentApply?: () => void;
  /**
   * 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";
}): Promise<{
  dir: string;
  agentsPath?: string;
  soulPath?: string;
  identityPath?: string;
  userPath?: string;
  bootstrapPath?: string;
  bootstrapPending?: boolean;
  identityPathCreated?: 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/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;
  }) => 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$1 | undefined;
}>;
//#endregion
//#region src/agents/model-fallback-attempt.d.ts
type ModelFallbackResultClassification = {
  message: string;
  reason?: FailoverReason;
  status?: number;
  code?: string;
  rawError?: string;
  preserveResultOnExhaustion?: boolean;
  preserveResultPriority?: number;
} | {
  error: unknown;
} | null | undefined;
//#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/types.d.ts
/** Runtime transport selected for one model attempt. */
type AgentRuntimeTransport = "sse" | "websocket" | "websocket-cached" | "auto";
/** Thinking levels accepted by runtime-plan extra-param preparation. */
type AgentRuntimeThinkLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max";
/** System prompt rendering mode selected for one attempt. */
type AgentRuntimePromptMode = "full" | "minimal" | "none";
/** Trigger source that can alter provider system prompt contributions. */
type AgentRuntimePromptTrigger = "cron" | "heartbeat" | "manual" | "memory" | "overflow" | "user";
/** Provider model descriptor consumed by runtime-plan hooks. */
type AgentRuntimeModel = {
  id?: string;
  name?: string;
  api?: string;
  provider?: string;
  baseUrl?: string;
  reasoning?: boolean;
  input?: readonly string[];
  cost?: {
    input: number;
    output: number;
    cacheRead: number;
    cacheWrite: number;
  };
  contextWindow?: number;
  maxTokens?: number;
  contextTokens?: number;
  compat?: unknown;
};
/** Text replacement rule used by provider input/output transforms. */
type AgentRuntimeTextReplacement = {
  from: string | RegExp;
  to: string;
};
/** Provider text transforms applied around model calls. */
type AgentRuntimeTextTransforms = {
  input?: AgentRuntimeTextReplacement[];
  output?: AgentRuntimeTextReplacement[];
};
/** Resolved provider runtime handle forwarded to plugin-owned hooks. */
type AgentRuntimeProviderHandle = {
  provider: string;
  modelId?: string | null;
  config?: unknown;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  applyAutoEnable?: boolean;
};
type PreparedAgentRuntimeProviderHandle = AgentRuntimeProviderHandle & {
  modelId: string | null;
  prepared: true;
};
/** Stable section IDs for provider system prompt overrides. */
type AgentRuntimeSystemPromptSectionId = "interaction_style" | "tool_call_style" | "execution_bias";
/** Provider-owned system prompt contribution and section overrides. */
type AgentRuntimeSystemPromptContribution = {
  stablePrefix?: string;
  dynamicSuffix?: string;
  sectionOverrides?: Partial<Record<AgentRuntimeSystemPromptSectionId, string>>;
};
/** Context passed when resolving provider system prompt contributions. */
type AgentRuntimeSystemPromptContributionContext = {
  config?: unknown;
  agentDir?: string;
  workspaceDir?: string;
  provider: string;
  modelId: string;
  promptMode: AgentRuntimePromptMode;
  runtimeChannel?: string;
  runtimeCapabilities?: string[];
  agentId?: string;
  trigger?: AgentRuntimePromptTrigger;
};
/** Provider fallback route decision for follow-up delivery. */
type AgentRuntimeFollowupFallbackRouteResult = {
  route?: "origin" | "dispatcher" | "drop";
  reason?: string;
};
/** Tool-call id sanitizer mode for provider transcript policy. */
type AgentRuntimeToolCallIdMode = "strict" | "strict9";
/** Provider transcript sanitation, repair, and validation policy. */
type AgentRuntimeTranscriptPolicy = {
  sanitizeMode: "full" | "images-only";
  sanitizeToolCallIds: boolean;
  toolCallIdMode?: AgentRuntimeToolCallIdMode;
  duplicateToolCallIdStyle?: "openai";
  preserveNativeAnthropicToolUseIds: boolean;
  repairToolUseResultPairing: boolean;
  preserveSignatures: boolean;
  sanitizeThoughtSignatures?: {
    allowBase64Only?: boolean;
    includeCamelCase?: boolean;
  };
  dropThinkingBlocks: boolean;
  dropReasoningFromHistory?: boolean;
  applyGoogleTurnOrdering: boolean;
  validateGeminiTurns: boolean;
  validateAnthropicTurns: boolean;
  allowSyntheticToolResults: boolean;
};
/** Runtime hook that classifies run results for model fallback. */
type AgentRuntimeOutcomeClassifier = (params: {
  provider: string;
  model: string;
  result: unknown;
  hasDirectlySentBlockReply?: boolean;
  hasBlockReplyPipelineOutput?: boolean;
}) => ModelFallbackResultClassification;
/** Resolved provider/model/harness/transport reference for an attempt. */
type AgentRuntimeResolvedRef = {
  provider: string;
  modelId: string;
  modelApi?: string;
  harnessId?: string;
  transport?: AgentRuntimeTransport;
};
/** Concrete provider-owned route selected for one runtime attempt. */
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;
};
/** Common native-runtime support proven across every route left to the harness. */
type AgentRuntimeAuthDeferredRouteSupport = {
  requestTransportOverrides: ProviderRouteOverridePresence;
  runtimePolicy: ProviderModelRouteRuntimePolicy;
};
/** Auth forwarding decision for one runtime attempt. */
type AgentRuntimeCredentialSource = ProviderModelAuthSourceClassification | {
  kind: "none";
};
/** 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. */
  deferredRouteSupport?: AgentRuntimeAuthDeferredRouteSupport;
  /** Redacted source selected for this concrete physical attempt. */
  credentialSource?: AgentRuntimeCredentialSource;
};
/** Prompt transforms and provider contribution hooks for one runtime attempt. */
type AgentRuntimePromptPlan = {
  provider: string;
  modelId: string;
  textTransforms?: AgentRuntimeTextTransforms;
  resolveSystemPromptContribution(context: AgentRuntimeSystemPromptContributionContext): AgentRuntimeSystemPromptContribution | undefined;
  transformSystemPrompt(context: AgentRuntimeSystemPromptContributionContext & {
    systemPrompt: string;
  }): string;
};
/** Prepared plugin metadata snapshot kept opaque to runtime-plan consumers. */
type AgentRuntimePreparedMetadataSnapshot = object;
/** Prepared metadata loader used by tool planning without eager manifest reads. */
type PreparedOpenClawToolPlanning = {
  metadataSnapshot?: AgentRuntimePreparedMetadataSnapshot;
};
type AgentRuntimeModelOverrides = {
  workspaceDir?: string;
  modelApi?: string;
  model?: AgentRuntimeModel;
};
/** Tool normalization and diagnostics hooks for one runtime attempt. */
type AgentRuntimeToolPlan = {
  preparedPlanning?: PreparedOpenClawToolPlanning;
  normalize<TSchemaType extends TSchema = TSchema, TResult = unknown>(tools: AgentTool<TSchemaType, TResult>[], params?: AgentRuntimeModelOverrides): AgentTool<TSchemaType, TResult>[];
  logDiagnostics(tools: AgentTool[], params?: AgentRuntimeModelOverrides): void;
};
/** Delivery behavior hooks for one runtime attempt. */
type AgentRuntimeDeliveryPlan = {
  isSilentPayload(payload: Pick<ReplyPayload, "text" | "mediaUrl" | "mediaUrls" | "presentation" | "interactive" | "channelData">): boolean;
  resolveFollowupRoute(params: {
    payload: ReplyPayload;
    originatingChannel?: string;
    originatingTo?: string;
    originRoutable: boolean;
    dispatcherAvailable: boolean;
  }): AgentRuntimeFollowupFallbackRouteResult | undefined;
};
/** Extra transport parameter plan for one runtime attempt. */
type AgentRuntimeTransportPlan = {
  extraParams: Record<string, unknown>;
  resolveExtraParams(params?: {
    extraParamsOverride?: Record<string, unknown>;
    thinkingLevel?: AgentRuntimeThinkLevel;
    agentId?: string;
    workspaceDir?: string;
    model?: AgentRuntimeModel;
    resolvedTransport?: AgentRuntimeTransport;
  }): Record<string, unknown>;
};
/** Complete prepared runtime plan consumed by embedded-agent attempts. */
type AgentRuntimePlan = {
  resolvedRef: AgentRuntimeResolvedRef;
  providerRuntimeHandle?: PreparedAgentRuntimeProviderHandle;
  auth: AgentRuntimeAuthPlan;
  prompt: AgentRuntimePromptPlan;
  tools: AgentRuntimeToolPlan;
  transcript: {
    policy: AgentRuntimeTranscriptPolicy;
    resolvePolicy(params?: AgentRuntimeModelOverrides): AgentRuntimeTranscriptPolicy;
  };
  delivery: AgentRuntimeDeliveryPlan;
  outcome: {
    classifyRunResult: AgentRuntimeOutcomeClassifier;
  };
  transport: AgentRuntimeTransportPlan;
  observability: AgentRuntimeResolvedRef & {
    resolvedRef: string;
    authProfileId?: 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 EmbeddedAgentUsage = Omit<NormalizedUsage, "contextUsage">;
type EmbeddedAgentMeta = {
  sessionId: string;
  sessionFile?: string;
  provider: string;
  model: string;
  contextTokens?: number;
  contextTokensSource?: "runtime" | "runtime-configured" | "resolved";
  agentHarnessId?: string;
  /** Sanitized provider-policy refusal attached to this physical attempt. */
  providerRefusal?: {
    provider?: string;
    category?: string;
    review?: ProviderRefusalReview;
    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;
  usage?: EmbeddedAgentUsage;
  /** Terminal cumulative usage reserved for turn-level diagnostics. */
  diagnosticUsage?: EmbeddedAgentUsage;
  /**
   * 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 ExecutionTrace = {
  winnerProvider?: string;
  winnerModel?: string;
  attempts?: TraceAttempt[];
  fallbackUsed?: boolean;
  runner?: "embedded" | "cli";
  providerPolicyRetry?: {
    category: "cyber";
    provider: string;
    model: string;
  };
};
type RequestShapingTrace = {
  authMode?: string;
  thinking?: string;
  reasoning?: string;
  verbose?: string;
  trace?: string;
  fallbackEligible?: boolean;
  blockStreaming?: string;
};
type PromptSegmentTrace = {
  key: string;
  chars: number;
};
type ToolSummaryTrace = {
  calls: number;
  tools: string[];
  failures?: number;
  /** Latest tool failure not cleared by same-tool success, independent of reply presentation. */
  unresolvedError?: {
    toolName: string;
  };
  totalToolTimeMs?: number;
};
type CompletionTrace = {
  finishReason?: string;
  stopReason?: string;
  refusal?: boolean;
};
type ContextManagementTrace = {
  sessionCompactions?: number;
  lastTurnCompactions?: number;
  preflightCompactionApplied?: boolean;
  postCompactionContextInjected?: boolean;
};
type EmbeddedRunLivenessState = "working" | "paused" | "blocked" | "abandoned";
type EmbeddedRunFailureSignal = {
  kind: "execution_denied";
  source: "tool";
  toolName?: string;
  code: "SYSTEM_RUN_DENIED" | "INVALID_REQUEST";
  message: string;
  fatalForCron: true;
};
type 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;
  replayInvalid?: boolean;
  livenessState?: EmbeddedRunLivenessState;
  timeoutPhase?: AgentRunTimeoutPhase;
  providerStarted?: boolean;
  /** 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";
  terminalReplyKind?: "silent-empty";
  /** An exact, successfully settled tool batch intentionally completed the turn without a reply. */
  intentionalTerminalCompletion?: "tool-batch";
  terminalReply?: AgentRunTerminalReplySnapshot;
  yielded?: boolean;
  /** Explicit user-facing waiting status supplied to sessions_yield. */
  yieldAcknowledgment?: string;
  /** A visible parent delegated its otherwise-empty result to completion children. */
  continuationPending?: true;
  error?: {
    kind: "context_overflow" | "compaction_failure" | "compaction_replay_refresh_required" | "role_ordering" | "image_size" | "retry_limit" | "incomplete_turn" | "hook_block";
    message: string;
    /** True only when model fallback can retry this terminal error without repeating side effects. */
    fallbackSafe?: boolean;
    /** True when the payload includes a trusted structured terminal tool summary. */
    terminalPresentation?: boolean;
  };
  failureSignal?: EmbeddedRunFailureSignal;
  /** 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?: ExecutionTrace;
  requestShaping?: RequestShapingTrace;
  promptSegments?: PromptSegmentTrace[];
  toolSummary?: ToolSummaryTrace;
  completion?: CompletionTrace;
  contextManagement?: ContextManagementTrace;
};
type EmbeddedAgentRunResult = {
  latestMcpAppChannelView?: McpAppChannelView;
  latestMcpConnectAction?: McpConnectAction;
  payloads?: Array<{
    text?: string;
    mediaUrl?: string;
    mediaUrls?: string[];
    replyToId?: string;
    isError?: boolean;
    isReasoning?: boolean;
    /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
    isCommentary?: boolean;
    audioAsVoice?: boolean;
    trustedLocalMedia?: boolean;
    channelData?: Record<string, unknown>;
  }>;
  meta: EmbeddedAgentRunMeta;
  diagnosticTrace?: DiagnosticTraceContext;
  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;
  heartbeatToolResponse?: HeartbeatToolResponse;
  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/agents/exec-auto-reviewer.d.ts
/** Config for the optional model-backed exec reviewer. */
type ExecReviewerConfig = NonNullable<NonNullable<ToolsConfig["exec"]>["reviewer"]>;
//#endregion
//#region src/agents/github-tool-identity.d.ts
type PreparedGitHubToolEnvironment = Readonly<{
  credentialScrubEnv: Readonly<Record<string, string>>;
  localIdentityEnv: Readonly<Record<string, string>>;
  excludedStoreNames: readonly string[];
  /** A local process must retain the host-selected profile and author identity. */
  managedLocalIdentity: boolean;
}>;
//#endregion
//#region src/agents/bash-tools.exec-types.d.ts
/** Runtime defaults passed into exec/process tool factories. */
type ExecToolDefaults = {
  hasCronTool?: boolean;
  host?: ExecTarget;
  mode?: ExecMode;
  bypassHostApprovalFloors?: boolean;
  security?: ExecSecurity;
  ask?: ExecAsk;
  trigger?: string;
  node?: string;
  /** Default working directory for node-host execution only. */
  nodeCwd?: 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;
  autoReviewer?: ExecAutoReviewer;
  /** Reads current attempt context only when a command needs review. */
  reviewTranscript?: () => ExecAutoReviewTranscript | undefined;
  agentId?: 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;
  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/process/lanes.d.ts
type CommandLaneConfiguration = {
  readonly lane: string;
  readonly maxConcurrent: number;
};
//#endregion
//#region src/agents/bootstrap-mode.d.ts
type BootstrapContextRunKind = "default" | "heartbeat" | "cron";
//#endregion
//#region src/agents/embedded-agent-payloads.d.ts
/**
 * Channel-facing reply payload emitted by embedded agents. Keep this type
 * small: channel adapters decide how to render text, media, and reply targets.
 */
type BlockReplyPayload = {
  text?: string;
  mediaUrls?: string[];
  attachments?: ReplyMediaAttachment[];
  audioAsVoice?: boolean;
  trustedLocalMedia?: boolean;
  sensitiveMedia?: boolean;
  isReasoning?: boolean;
  /** Marks pre-tool commentary (💬) — a display lane, suppressed unless the channel opts in. */
  isCommentary?: boolean;
  replyToId?: string;
  replyToTag?: boolean;
  replyToCurrent?: boolean;
  /** Portable controls attached to a harness-owned blocking prompt. */
  presentation?: MessagePresentation;
  /** Runtime-authored text is the fallback for the portable presentation. */
  presentationTextMode?: "fallback";
  /** Channel-specific routing metadata for runtime-owned interactions. */
  channelData?: Record<string, unknown>;
};
//#endregion
//#region src/context-engine/host-compat.d.ts
type ContextEngineHostSupport = {
  id: string;
  label: string;
  capabilities: readonly ContextEngineHostCapability[];
};
//#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;
  selectForHost: (params: {
    host: ContextEngineHostSupport;
    operation: ContextEngineOperation;
    requiresDurableCommit: boolean;
  }) => EffectiveContextEngineRef;
  degradeBeforeStart: (reason: string) => EffectiveContextEngineRef;
  begin: () => EffectiveContextEngineRef;
  deferDisposalUntil: (promise: Promise<unknown>) => void;
  dispose: () => Promise<void>;
};
//#endregion
//#region src/agents/harness/context-engine-turn-outbox.d.ts
/** Persist only resolved model facts, never live capabilities or credential-bearing config. */
type ContextEngineTurnRuntimeContext = Readonly<{
  provider?: string;
  modelId?: string;
  modelContextWindow?: number;
  tokenBudget?: number;
}>;
//#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;
  isHeartbeat?: boolean;
  runtimeContext?: ContextEngineTurnRuntimeContext;
};
//#endregion
//#region src/agents/command/shared-types.d.ts
/** Best-effort provider stream parameter overrides for an agent command. */
type AgentStreamParams = {
  /** Provider stream params override (best-effort). */
  temperature?: number;
  topP?: number;
  maxTokens?: number;
  /** Stop sequences forwarded to the provider (best-effort). */
  stop?: string[];
  /** Provider fast-mode override (best-effort). */
  fastMode?: boolean;
  responseFormat?: Record<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 = {
  /** Profile selected from the session's assigned human owner or authenticated human creator, never its latest sender. */
  bootstrapUserProfileId?: string;
  /** Capabilities declared by the gateway client that originated this run. */
  clientCaps?: string[];
  gatewayUiCommandTarget?: GatewayUiCommandTarget;
  /** Host-admitted dashboard authoring without an originating inline renderer. */
  pinnedWidgetAuthoring?: boolean;
};
type AgentRunMessageContext = {
  agentAccountId?: string;
  /** Opaque host-issued capability for current-turn channel message actions. */
  messageActionTurnCapability?: string;
  /** Trusted sender identity bit for command/channel-action auth. */
  senderIsOwner?: boolean;
  /** Current channel ID for auto-threading (Slack). */
  currentChannelId?: string;
  /** Current thread timestamp for auto-threading (Slack). */
  currentThreadTs?: string;
  /** Current inbound message id for action fallbacks (e.g. Telegram react). */
  currentMessageId?: string | number;
  /** True when the current inbound turn carried audio media. */
  currentInboundAudio?: boolean;
  /** Reply-to mode for Slack auto-threading. */
  replyToMode?: "off" | "first" | "all" | "batched";
  /** 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;
  /** Require explicit message tool targets (no implicit last-route sends). */
  requireExplicitMessageTarget?: boolean;
};
type AgentRunChannelContext = {
  /** Canonical transport channel when it differs from the tool-policy provider. */
  messageChannel?: string;
  messageProvider?: string;
  chatType?: ChatType;
  /** Channel-specific identity metadata surfaced to plugin hooks. */
  channelContext?: PluginHookChannelContext;
  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;
  /** Device-scoped operator session allowed to review approvals initiated by this run. */
  approvalReviewerDeviceId?: string;
};
type AgentRunModelOptions = {
  /** 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;
  thinkLevel?: ThinkLevel;
  fastMode?: FastMode;
  /** Stable outer-run start time for auto fast-mode cutoff across retries/fallbacks. */
  fastModeStartedAtMs?: number;
  /** Effective auto fast-mode cutoff for this run, in seconds. */
  fastModeAutoOnSeconds?: number;
  /** Shared notification state for nested harnesses that can observe the same tool boundary. */
  fastModeAutoProgressState?: FastModeAutoProgressState;
  /** True when the outer model fallback loop has reached its final candidate. */
  isFinalFallbackAttempt?: boolean;
  authProfileId?: string;
};
type AgentRunInputContext = {
  workspaceDir: string;
  /** Canonical agent workspace used for bootstrap files when execution runs elsewhere. */
  bootstrapWorkspaceDir?: string;
  agentDir?: string;
  /** Task working directory for tool/runtime execution. Defaults to workspaceDir. */
  cwd?: 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;
  toolOverrides?: SessionToolOverrides;
  prompt: string;
  /** User-visible prompt body to submit and persist; runtime context travels separately. */
  transcriptPrompt?: string;
  currentInboundEventKind?: InboundEventKind;
  inputProvenance?: InputProvenance;
  extraSystemPrompt?: string;
  images?: ImageContent$1[];
  imageOrder?: PromptImageOrderEntry[];
  /** Ordered facts represented by attachment text in the current prompt. */
  media?: MediaFact[];
  skillsSnapshot?: SkillSnapshot;
  ownerNumbers?: string[];
  /** Seen bootstrap truncation warning signatures for this session (once mode dedupe). */
  bootstrapPromptWarningSignaturesSeen?: string[];
  /** Last shown bootstrap truncation warning signature for this session. */
  bootstrapPromptWarningSignature?: string;
  /** Run kind hint for context mode behavior. */
  bootstrapContextRunKind?: BootstrapContextRunKind;
};
type AgentRunTranscriptContext = {
  /** Caller-owned in-memory transcript for ephemeral helper runs. */
  sessionManager?: SessionManager;
  sessionId: string;
  sessionKey?: string;
  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;
  suppressNextUserMessagePersistence?: boolean;
  onUserMessagePersisted?: (message: Extract<AgentMessage, {
    role: "user";
  }>) => void;
};
type AgentRunLifecycle = {
  providerReviewAcknowledgment?: ProviderReviewAcknowledgment;
  /** Already-admitted internal execution; mutually exclusive with preparedRunAdmission. */
  admittedRunContext?: AdmittedRunContext;
  /** Host-only post-prepare continuation, removed before plugin invocation. */
  preparedRunAdmission?: PreparedAgentRunAdmission;
  agentId?: string;
  timeoutMs: number;
  /** Explicit timeout override; equality with the configured default does not imply inheritance. */
  runTimeoutOverrideMs?: number;
  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;
  /** Trusted server-stamped authority for an explicitly capped scheduled run. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
  /** 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;
};
//#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/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;
  /** 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;
};
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;
  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/agents/embedded-agent-block-chunker.d.ts
/**
 * Splits streamed embedded-agent replies into Markdown-safe message chunks.
 */
type BlockReplyChunking = {
  minChars: number;
  maxChars: number;
  breakPreference?: "paragraph" | "newline" | "sentence";
  /** When true, prefer \n\n paragraph boundaries once minChars has been satisfied. */
  flushOnParagraph?: boolean;
};
//#endregion
//#region src/agents/embedded-agent-subscribe.shared-types.d.ts
/** Rendering mode for completed tool results in subscribed replies. */
type ToolResultFormat = "markdown" | "plain";
/** Detail level for in-flight tool progress messages. */
type ToolProgressDetailMode = "explain" | "raw";
type EmbeddedAgentEvent = {
  stream: string;
  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/exec-defaults.d.ts
/** Session-scoped exec fields that may be carried across an isolated runtime boundary. */
type ExecSessionDefaults = Pick<SessionEntry$1, "execHost" | "execNode" | "execCwd" | "permissionMode" | "sandbox">;
//#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/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;
}>;
//#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/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 ResolvedToolPromptFinalizer = (params: {
  prompt: string;
  messageToolAvailable: boolean;
}) => string;
type ReasoningStreamPayload$1 = Pick<ReplyPayload, "text" | "mediaUrls" | "isReasoning" | "isReasoningSnapshot"> & {
  requiresReasoningProgressOptIn?: boolean;
};
type RunEmbeddedAgentParams = {
  /** 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;
  /** 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;
  /** What initiated this agent run: "user", "heartbeat", "cron", "memory", "overflow", or "manual". */
  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;
  /** 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;
  /** Trusted channel-configured policy for the admitted conversation turn. */
  conversationToolPolicy?: GroupToolPolicyConfig;
  /** Trusted provider role ids for the requester in this group turn. */
  memberRoleIds?: string[];
  /** 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>;
  /** Restrict this reconstructed run to restart-safe tools. */
  forceRestartSafeTools?: boolean;
  /** Preserve Code Mode controls for a replay-safe restart recovery turn. */
  forceCodeModeTools?: boolean;
  /** 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;
  /** Disable trajectory persistence for auxiliary runs with no durable session owner. */
  disableTrajectory?: boolean;
  /** Restrict Skill Workshop to a bounded pending-proposal budget for an internal review run. */
  skillWorkshopProposalOnly?: boolean;
  /** Mark proposals created by this internal review as autonomous captures. */
  skillWorkshopAutonomousCapture?: boolean;
  skillWorkshopUpdateProposals?: boolean;
  /** Preserve the foreground run as proposal provenance for an internal review run. */
  skillWorkshopOrigin?: SkillProposalOrigin;
  /** Run-scoped mutation budget shared across internal runner attempts. */
  skillWorkshopProposalMutationBudget?: SkillWorkshopProposalMutationBudget;
  /** Optional state environment for isolated Skill Workshop proposal persistence. */
  skillWorkshopProposalEnv?: NodeJS.ProcessEnv;
  /** Bind an operator-requested revision turn to the exact proposal revision they reviewed. */
  skillWorkshopProposalRevision?: SkillWorkshopRunOptions["proposalRevision"];
  skillLibraryAuthoring?: SkillWorkshopRunOptions["libraryAuthoring"];
  /** Explicit system prompt mode override for trusted callers. */
  promptMode?: PromptMode;
  /** Keep the message tool available even when a narrow profile would omit it. */
  forceMessageTool?: boolean;
  /** Include the heartbeat response tool for structured heartbeat outcomes. */
  enableHeartbeatTool?: boolean;
  /** Keep the heartbeat response tool available even when a narrow profile would omit it. */
  forceHeartbeatTool?: boolean;
  /** Allow runtime plugins for this run to late-bind the gateway subagent. */
  allowGatewaySubagentBinding?: boolean;
  /** @deprecated Use sessionTarget plus sessionId/sessionKey/agentId for runtime identity. */
  sessionFile?: string;
  /** Require file tools to stay within the task workspace without changing exec policy. */
  requireWorkspaceOnly?: true;
  /** Refuse an enabled sandbox that would redirect a review away from its workspace. */
  requireWritableSandbox?: true;
  permissionMode?: SessionEntry$1["permissionMode"];
  sessionRoot?: string;
  /** 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;
  /** Locks the selected model against hooks and fallbacks; does not imply native model ownership. */
  modelSelectionLocked?: boolean;
  /** 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;
  authProfileIdSource?: "auto" | "user";
  /** Disable fallback from the user-selected auth profile for a verification run. */
  allowAuthProfileFallback?: boolean;
  verboseLevel?: VerboseLevel;
  reasoningLevel?: ReasoningLevel;
  toolResultFormat?: ToolResultFormat;
  toolProgressDetail?: ToolProgressDetailMode;
  /** 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[];
  /** Owner-scoped plugin tool grant; normal policy and deny rules still apply. */
  runtimePluginToolGrant?: RuntimePluginToolGrant;
  /** Consumed in-process subagent-completion capability; never derived from public input. */
  trustedInternalHandoff?: TrustedSubagentCompletionHandoff;
  /** 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;
  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;
  }) => unknown;
  onExecutionPhase?: (info: {
    phase: EmbeddedAgentExecutionPhase;
    provider?: string;
    model?: string;
    backend?: string;
    source?: string;
    tool?: string;
    toolCallId?: string;
    itemId?: string;
    firstModelCallStarted?: boolean;
  }) => void;
  onLaneWait?: (info: {
    waitMs: number;
    queuedAhead: number;
    waiting?: boolean;
  }) => void;
  onRunProgress?: (info: {
    reason: string;
    provider?: string;
    model?: string;
    backend?: string;
  }) => void;
  onSessionIdChanged?: (sessionId: string) => void;
  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$1) => void | Promise<void>;
  streamReasoningInNonStreamModes?: boolean;
  onReasoningEnd?: () => void | Promise<void>;
  onToolResult?: (payload: ReplyPayload) => 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;
  silentReplyPromptMode?: SilentReplyPromptMode;
  internalEvents?: AgentInternalEvent[];
  streamParams?: AgentStreamParams;
  enforceFinalTag?: boolean;
  silentExpected?: boolean;
  /** 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;
  /**
   * Host-owned reply requirement for this input, independent of model output.
   * Confirmed source delivery and pending custody prevent duplicate recovery.
   */
  terminalReplyExpectation?: ReplyExpectation;
  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;
  suppressTranscriptOnlyAssistantPersistence?: boolean;
  assistantErrorTranscript?: AssistantErrorTranscript;
  /** Keep an internal continuation prompt from being replaced by the original prepared turn. */
  skipPreparedUserTurnMessage?: boolean;
  onUserMessagePersistenceInvalidated?: () => void;
} & AgentRunClientContext & AgentRunMessageContext & AgentRunChannelContext & AgentRunModelOptions & AgentRunInputContext & AgentRunTranscriptContext & AgentRunLifecycle;
//#endregion
//#region src/agents/embedded-agent-runner/compact.types.d.ts
type CompactEmbeddedAgentSessionParams = Pick<RunEmbeddedAgentParams, "requireWorkspaceOnly" | "requireWritableSandbox" | "sessionTarget" | "sessionId" | "sessionKey" | "agentId" | "sandboxSessionKey" | "sandboxAgentId" | "messageChannel" | "messageProvider" | "clientCaps" | "pinnedWidgetAuthoring" | "chatType" | "agentAccountId" | "conversationRoutePeerId" | "conversationToolPolicy" | "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;
  /** 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$1;
  /** 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";
  /**
   * 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;
  onCompactionHookMessages?: (payload: {
    phase: "before" | "after";
    messages: string[];
    sessionId: string;
    sessionKey: string;
  }) => void | Promise<void>;
};
//#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$1 = {
  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$1;
  baseParams: unknown;
  overrideParams?: unknown;
};
type BeforeToolCallPolicyDiagnosticState = {
  hasBeforeToolCallHook: boolean;
  trustedToolPolicies: Array<{
    id: string;
    pluginId: string;
    pluginName?: string;
  }>;
};
type HookBlockedReason = "client-voice-confirmation" | "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
/** Consume and remove hook-adjusted params for a completed tool call. */
declare function consumeAdjustedParamsForToolCall(toolCallId: string, runId?: string): unknown;
/** Snapshot hook-adjusted params 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";
};
/** Return true when a tool already carries the before_tool_call wrapper state. */
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>;
/** Notify plugin approval callbacks that a deferred approval was cancelled. */
declare function cancelDeferredPluginToolApproval(deferredApproval: DeferredPluginToolApproval): void;
//#endregion
//#region src/agents/agent-tools.before-tool-call.policy.d.ts
declare function getBeforeToolCallPolicyDiagnosticState(): BeforeToolCallPolicyDiagnosticState;
/** Return true when any before_tool_call policy could affect tool execution. */
declare function hasBeforeToolCallPolicy(): boolean;
declare function runBeforeToolCallHook(args: {
  toolName: string;
  params: unknown;
  toolKind?: PluginHookToolKind;
  toolInputKind?: PluginHookToolInputKind;
  toolCallId?: string;
  ctx?: HookContext$1;
  signal?: AbortSignal;
  approvalMode?: "request" | "report" | "deny" | "defer";
}): Promise<HookOutcome>;
//#endregion
//#region src/agents/agent-tools.before-tool-call.wrapper.d.ts
/** Return the closed terminal disposition carried by a before-tool failure. */
declare function getBeforeToolCallFailureDisposition(error: unknown): BeforeToolCallFailureDisposition | undefined;
/** Remember hook-adjusted params for later adapter-side execution. */
declare function recordAdjustedParamsForToolCall(toolCallId: string | undefined, params: unknown, runId?: string): void;
/** 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 isPreExecutionBlockedToolResult(result: unknown): boolean;
/** Build the standard terminal result for vetoed tool calls. */
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, ctx?: HookContext$1, options?: Partial<BeforeToolCallDiagnosticOptions>): AnyAgentTool;
/** Rebuild a before_tool_call wrapper while preserving the original source tool. */
declare function rewrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext$1, options?: Partial<BeforeToolCallDiagnosticOptions>): AnyAgentTool;
declare namespace agent_tools_before_tool_call_d_exports {
  export { BeforeToolCallFailureDisposition, BeforeToolCallPolicyDiagnosticState, DeferredPluginToolApproval, HookContext$1 as HookContext, ToolOutcomeObservation, ToolOutcomeObserver, buildBlockedToolResult, cancelDeferredPluginToolApproval, consumeAdjustedParamsForToolCall, consumePreExecutionBlockedToolCall, finalizeToolTerminalPresentation, getBeforeToolCallFailureDisposition, getBeforeToolCallPolicyDiagnosticState, hasBeforeToolCallPolicy, isPreExecutionBlockedToolResult, isToolWrappedWithBeforeToolCallHook, peekAdjustedParamsForToolCall, recordAdjustedParamsForToolCall, recordStructuredReplayTrustForToolCall, requestDeferredPluginToolApproval, rewrapToolWithBeforeToolCallHook, runBeforeToolCallHook, setBeforeToolCallDiagnosticsEnabled, wrapToolWithBeforeToolCallHook };
}
//#endregion
//#region src/shared/silent-reply-policy.d.ts
type SilentReplyConversationType = "direct" | "group" | "internal";
//#endregion
//#region src/infra/outbound/payloads.d.ts
/** Runtime-ready outbound payload after text/media/rich-content normalization. */
type NormalizedOutboundPayload = {
  text: string;
  mediaUrls: string[];
  audioAsVoice?: boolean;
  presentation?: MessagePresentation;
  presentationTextMode?: ReplyPayload["presentationTextMode"];
  delivery?: ReplyPayloadDelivery;
  interactive?: LegacyInteractiveReply;
  channelData?: Record<string, unknown>;
  location?: ReplyPayload["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;
};
/** JSON-safe outbound payload projection used for envelopes and diagnostics. */
type OutboundPayloadJson = {
  text: string;
  isError?: boolean;
  mediaUrl: string | null;
  mediaUrls?: string[];
  audioAsVoice?: boolean;
  presentation?: MessagePresentation;
  presentationTextMode?: ReplyPayload["presentationTextMode"];
  delivery?: ReplyPayloadDelivery;
  interactive?: LegacyInteractiveReply;
  channelData?: Record<string, unknown>;
  location?: ReplyPayload["location"];
};
/** Projects a payload plan into JSON-safe envelope/debug payloads. */
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/infra/delivery-queue-sqlite.types.d.ts
type DeliveryQueueCompletionRetention = "permanent" | Readonly<{
  idPrefix: string;
  maxAgeMs: number;
  maxEntries: number;
}>;
//#endregion
//#region src/infra/delivery-queue-state-context.d.ts
type DeliveryQueueStateContext = {
  stateDir: string;
  workerContext: OpenClawStateWorkerContext;
  supervisorMode?: "external";
};
//#endregion
//#region src/infra/outbound/delivery-completion.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;
};
//#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/mirror.d.ts
/**
 * Transcript append data emitted after an outbound send completes.
 */
type OutboundMirror = {
  sessionKey: string;
  agentId?: string;
  text?: string;
  mediaUrls?: string[];
  idempotencyKey?: string;
  expectedSessionId?: string;
  deliveryMirror?: SessionTranscriptDeliveryMirror;
};
/**
 * Delivery-layer mirror data with optional group/channel correlation metadata.
 */
type DeliveryMirror = OutboundMirror & {
  /** Whether this message is being sent in a group/channel context */
  isGroup?: boolean;
  /** Group or channel identifier for correlation with received events */
  groupId?: string;
};
//#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/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.
   */
  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;
};
//#endregion
//#region src/infra/outbound/outbound-audit.d.ts
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;
};
//#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;
  replyHookChanged: boolean;
  messageHookChanged: boolean;
  preparedMediaCount: number;
};
type PreparedOutboundSuppressedEntry = {
  sourceIndex: number;
  status: "suppressed";
  reason: OutboundPayloadDeliverySuppressionReason;
  hookEffect?: {
    cancelReason?: string;
    metadata?: Record<string, unknown>;
  };
};
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/delivery-queue-types.d.ts
type QueuedRenderedMessageBatchPlan = RenderedMessageBatchPlan;
type QueuedReplyPayloadSendingHook = {
  kind: ReplyDispatchKind;
  channel?: string;
  sessionKey?: string;
  runId?: string;
  context: PluginHookReplyPayloadSendingContext;
};
type QueuedDeliveryPayload = {
  sessionGeneration?: SessionDeliveryGeneration;
  channel: string;
  to: string;
  accountId?: string;
  queuePolicy?: "required" | "best_effort";
  requireUnknownSendReconciliation?: boolean;
  requiresProducerClaim?: boolean;
  preparedBatch?: PreparedOutboundBatch;
  payloads?: ReplyPayload[];
  renderedBatchPlan?: QueuedRenderedMessageBatchPlan;
  threadId?: string | number | null;
  reply?: OutboundReplyFacts;
  formatting?: OutboundDeliveryFormattingOptions;
  identity?: OutboundIdentity;
  bestEffort?: boolean;
  gifPlayback?: boolean;
  forceDocument?: boolean;
  silent?: boolean;
  mirror?: DeliveryMirror;
  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"> & {
  preparedBatch: PreparedOutboundBatch;
  id: string;
  enqueuedAt: number;
  retryCount: number;
  attemptCount: number;
  availableAt?: number;
  producerClaimId?: string;
  lastAttemptAt?: number;
  lastError?: string;
  platformSendAttemptId?: string;
  platformSendStartedAt?: number;
  effectiveReplyToId?: string | null;
  recoveryState?: "producer_claimed" | "send_attempt_started" | "unknown_after_send" | "settlement_pending";
  settlement?: DeliveryFailureSettlement;
  retainOnFailure?: true;
};
//#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): Promise<void>;
  retire(): Promise<void>;
};
type QueuedDeliveryOwner = ReturnType<typeof createQueuedDeliveryOwner>;
//#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$1[];
};
/** 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/hooks.d.ts
type HookRunnerLogger = {
  debug?: (message: string) => void;
  warn: (message: string) => void;
  error: (message: string) => void;
};
type HookFailurePolicy = "fail-open" | "fail-closed";
type VoidHookRunOptions = {
  unrefTimeout?: boolean;
};
type HookRunnerOptions = {
  logger?: HookRunnerLogger;
  /** If true, errors in hooks will be caught and logged instead of thrown */
  catchErrors?: boolean;
  /**
   * Optional per-hook failure policy.
   * Defaults to fail-open unless explicitly overridden for a hook name.
   */
  failurePolicyByHook?: Partial<Record<PluginHookName, HookFailurePolicy>>;
  /**
   * Optional timeout for void/observation hooks. A timed-out hook is logged and
   * the runner continues, but the plugin's underlying work is not cancelled.
   */
  voidHookTimeoutMsByHook?: Partial<Record<PluginHookName, number>>;
  /**
   * Optional timeout for modifying hooks. A timed-out hook is logged and skipped,
   * but the plugin's underlying work is not cancelled.
   */
  modifyingHookTimeoutMsByHook?: Partial<Record<PluginHookName, number>>;
};
type HookEvent<K extends PluginHookName> = Parameters<PluginHookHandlerMap[K]>[0];
type HookContext<K extends PluginHookName> = Parameters<PluginHookHandlerMap[K]>[1];
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>;
  runBeforeAgentReply: (event: PluginHookBeforeAgentReplyEvent, ctx: PluginHookAgentContext) => Promise<PluginHookBeforeAgentReplyResult | undefined>;
  runModelCallStarted: (event: {
    contextTokenBudget?: number;
    contextWindowSource?: PluginHookContextWindowSource;
    contextWindowReferenceTokens?: number;
  } & {
    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: PluginHookBeforeAgentFinalizeEvent, ctx: PluginHookAgentContext) => Promise<PluginHookBeforeAgentFinalizeResult | undefined>;
  runAgentEnd: (event: PluginHookAgentEndEvent, ctx: PluginHookAgentContext, 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>;
  runBeforeAgentRun: (event: PluginHookBeforeAgentRunEvent, ctx: PluginHookAgentContext) => Promise<GateHookResult<InputGateDecision> | undefined>;
  runInboundClaim: (event: PluginHookInboundClaimEvent, ctx: PluginHookInboundClaimContext) => 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) => Promise<PluginHookReplyDispatchResult | undefined>;
  runReplyPayloadSending: (event: PluginHookReplyPayloadSendingEvent, ctx: PluginHookMessageContext) => Promise<PluginHookReplyPayloadSendingResult | undefined>;
  runMessageSending: (event: HookEvent<"message_sending">, ctx: HookContext<"message_sending">) => Promise<PluginHookMessageSendingResult | 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: PluginHookAfterToolCallEvent, ctx: PluginHookToolContext) => Promise<void>;
  runToolResultPersist: (event: PluginHookToolResultPersistEvent, ctx: PluginHookToolResultPersistContext) => PluginHookToolResultPersistResult | undefined;
  runBeforeMessageWrite: (event: PluginHookBeforeMessageWriteEvent, ctx: {
    agentId?: string;
    sessionKey?: string;
  }) => PluginHookBeforeMessageWriteResult | undefined;
  runSessionStart: (event: PluginHookSessionStartEvent, ctx: {
    agentId?: string;
    sessionId: string;
    sessionKey?: string;
  }) => Promise<void>;
  runSessionEnd: (event: PluginHookSessionEndEvent, ctx: {
    agentId?: string;
    sessionId: string;
    sessionKey?: string;
  }) => 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<PluginHeartbeatPromptContributionResult | undefined>;
  runCronReconciled: (event: PluginHookCronReconciledEvent, ctx: PluginHookCronReconciledContext) => Promise<void>;
  runCronChanged: (event: PluginHookCronChangedEvent, ctx: PluginHookGatewayContext) => Promise<void>;
  runSkillProposalEvaluate: (event: PluginHookSkillProposalEvaluateEvent, ctx: PluginHookSkillContext) => Promise<PluginHookSkillProposalEvaluationOutcome[]>;
  runSkillProposalChanged: (event: PluginHookSkillProposalChangedEvent, ctx: PluginHookSkillContext) => 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<Parameters<PluginHookHandlerMap[K]>[1]>) => boolean;
  getHookCount: (hookName: PluginHookName) => number;
};
type HookRunner = ReturnType<typeof createHookRunner>;
//#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/deliver-contracts.d.ts
type ConversationDeliveryAttemptAuthority = Omit<Extract<DurableDeliveryCompletion, {
  kind: "conversation";
}>, "kind">;
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 DeliverOutboundPayloadsCoreParams = {
  cfg: OpenClawConfig;
  channel: string;
  to: string;
  accountId?: string;
  payloads: ReplyPayload[];
  /** 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;
  formatting?: OutboundDeliveryFormattingOptions;
  threadId?: string | number | null;
  identity?: OutboundIdentity;
  deps?: OutboundSendDeps;
  mediaAccess?: OutboundMediaAccess;
  gifPlayback?: boolean;
  forceDocument?: boolean;
  replyPayloadSendingHook?: QueuedReplyPayloadSendingHook;
  abortSignal?: AbortSignal;
  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 Runs after each identified platform result, before further fallible work. */
  onDeliveryResult?: (result: OutboundDeliveryResult) => Promise<void> | 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 Opaque durable intent id forwarded to provider reconciliation hooks. */
  deliveryQueueId?: string;
  /** @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 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 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 Caller preflight explicitly required provider unknown-send reconciliation. */
  requireUnknownSendReconciliation?: boolean;
  /** @internal Revalidate caller authority before direct adapter code can run. */
  onDirectAdapterHandoff?: () => Promise<void>;
  /** @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>;
  /** Session/agent context used for hooks and media local-root scoping. */
  session?: OutboundSessionContext;
  mirror?: DeliveryMirror;
  silent?: boolean;
  gatewayClientScopes?: readonly string[];
  conversationReadOrigin?: "delegated" | "direct-operator";
};
/**
 * @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?: QueuedRenderedMessageBatchPlan;
  onDeliveryIntent?: (intent: OutboundDeliveryIntent) => void;
};
//#endregion
//#region src/channels/message/send.d.ts
type DurableMessageSuppressionReason = OutboundPayloadDeliverySuppressionReason | "no_visible_result";
type DurableMessageFailureStage = "platform_send" | "queue" | "unknown";
type SerializedDurableMessagePayloadOutcome = {
  index: number;
  status: "sent";
  resultCount: number;
} | {
  index: number;
  status: "suppressed";
  reason: DurableMessageSuppressionReason;
  hookEffect?: {
    cancelReason?: string;
    metadata?: Record<string, unknown>;
  };
} | {
  index: number;
  status: "failed";
  error: string;
  sentBeforeError: boolean;
  stage: DurableMessageFailureStage;
};
//#endregion
//#region src/agents/core-tool-factory-descriptors.d.ts
type OpenClawCodingToolConstructionPlan = {
  includeBaseCodingTools: boolean;
  includeShellTools: boolean;
  includeChannelTools: boolean;
  includeOpenClawTools: boolean;
  includePluginTools: boolean;
};
//#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;
  /** Trusted requester OAuth sign-in bootstrap; exempt from per-call MCP approval. */
  oauthConnectBootstrap?: true;
  codexApproval?: {
    mode?: McpCodexToolApprovalMode;
    annotations?: McpCodexToolAnnotations;
  };
  node?: {
    id: string;
    displayName?: string;
  };
};
//#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/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/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;
  result: Awaited<ReturnType<typeof runProviderStaticCatalog>>;
  providerConfigs: Readonly<Record<string, ModelProviderConfig>>;
}>;
type PreparedProviderStaticCatalog = Readonly<{
  /** Provider handles captured for this config/workspace generation. */
  providers?: readonly ProviderPlugin[];
  entries: readonly PreparedProviderStaticCatalogEntry[];
}>;
declare function runProviderStaticCatalog(params: {
  provider: ProviderPlugin;
  signal?: AbortSignal;
}): Promise<ProviderCatalogResult> | undefined;
//#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/embedded-agent-runner/model.inline-provider.d.ts
/**
 * Normalizes inline `models.providers` config into runtime model entries.
 */
type InlineModelEntry = Omit<ModelDefinitionConfig, "api" | "contextWindow"> & {
  api?: Api;
  contextWindow?: number;
  provider: string;
  baseUrl?: string;
  headers?: Record<string, string>;
};
//#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;
  observationConfig: OpenClawConfig;
  authModes: PreparedAgentCredentialModes;
  authStore?: AuthProfileStore;
  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;
  modelCatalog: ModelCatalogSnapshot;
}>;
//#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[];
  changedOnly?: 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<{
  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 = Readonly<{
  catalogOwner: PublishedModelCatalogOwnerCandidate["catalogOwner"];
  agentId?: string;
  agentDir: string;
  inheritedAuthDir?: string;
  workspaceDir?: 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[];
  config: OpenClawConfig;
  /** Native observations retain preparation identity across model-neutral config publications. */
  observationConfig: OpenClawConfig;
  isCurrent: () => boolean;
  /** Secret-free usable auth modes captured by this exact lifecycle generation. */
  authModes: PreparedAgentCredentialModes;
  metadataSnapshot: PluginMetadataSnapshot;
  messageToolCatalog?: PreparedMessageToolCatalog;
  mediaCapabilityProviders?: ReturnType<typeof prepareMediaCapabilityProviders>;
  /** Borrows an inspected source; raw prepared hosts retain their existing external ownership. */
  acquireMediaCapabilityProviders?: () => PreparedMediaCapabilityProviderAcquisition;
  /** Registry value owned by this generation; omitted from read-only builds. */
  pluginRegistry?: PluginRegistry;
  allowGatewaySubagentBinding: boolean;
  /**
   * Configured model projection used by turn admission and synchronous callers.
   * Full inventory discovery is deliberately outside the startup publication boundary.
   */
  modelCatalog: ModelCatalogSnapshot;
  /** 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;
  /** 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 the selected runtime's native facts before host model resolution. */
  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: () => 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;
};
//#endregion
//#region src/plugins/provider-external-auth.d.ts
declare const { resolveExternalAuthProfilesWithPlugins }: Readonly<{
  resolveExternalAuthProfilesWithPlugins: (params: Parameters<ProviderExternalAuthProfileResolver>[0]) => ReturnType<ProviderExternalAuthProfileResolver>;
}>;
//#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;
  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 & {
  modelId?: string | null;
  pluginMetadataSnapshot?: PluginMetadataRegistryView;
  context: ProviderNormalizeResolvedModelContext;
}): ProviderRuntimeModel | undefined;
declare function applyProviderResolvedTransportWithPlugin(params: ProviderRuntimeLookup & {
  modelId?: string | null;
  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/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 CommonModelResolutionOptions = {
  assertCurrent?: () => void;
  authStorage?: AuthStorage;
  modelRegistry?: ModelRegistry;
  agentId?: string;
  runtimeHooks?: ProviderRuntimeHooks;
  skipProviderRuntimeHooks?: boolean;
  workspaceDir?: string;
  authProfileId?: string;
  authProfileMode?: AuthProfileCredential["type"] | "aws-sdk";
  preferredProfile?: string;
};
type AsyncModelResolutionOptions = CommonModelResolutionOptions & {
  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;
  modelRegistry: ModelRegistry;
} & ({
  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 PreparedSimpleCompletionModel = {
  model: Model;
  auth: ResolvedProviderAuth;
  /** Non-reversible owner proof captured from the same auth snapshot. */
  sourceAuthFingerprint?: string;
} | {
  error: string;
  auth?: ResolvedProviderAuth;
};
//#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$1>;
//#endregion
//#region src/agents/simple-completion-runtime.d.ts
type AllowedMissingApiKeyMode = ResolvedProviderAuth["mode"];
type PrepareSimpleCompletionModelParams = {
  cfg: OpenClawConfig | undefined;
  agentId?: string;
  provider: string;
  modelId: string;
  modelIdSource?: "input" | "selected";
  agentDir?: string;
  profileId?: string;
  preferredProfile?: string;
  allowMissingApiKeyModes?: ReadonlyArray<AllowedMissingApiKeyMode>;
  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;
};
/** Prepares a model within the exact generation already held by its caller. */
declare function prepareSimpleCompletionModel(params: PrepareSimpleCompletionModelParams & {
  preparedModelRuntime: PreparedModelRuntimeSnapshot;
}, assertCurrent?: () => void): Promise<PreparedSimpleCompletionModel>;
//#endregion
//#region src/gateway/agent-event-assistant-text.d.ts
type AssistantTextInput = {
  text?: string;
  delta?: string;
  itemId?: string;
  replace?: boolean;
  replaceable?: boolean;
  managedMediaUrls?: string[];
};
type AssistantTextSnapshot = {
  text: string;
  scope?: {
    itemId: string;
    prefix: string;
    boundaryNewlines: number;
    separatorLength: number;
  };
};
type AssistantTextMerge = AssistantTextSnapshot & {
  /** Present only when this merge proves an append to its input snapshot. */
  appendedText?: string;
};
/** Merge item snapshots without imposing a transport's display or wire limit. */
declare function mergeAssistantText(previous: AssistantTextSnapshot, input: AssistantTextInput, unkeyed: "live" | "append-only"): AssistantTextMerge;
//#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, _toolName?: string): 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/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;
    delta: string | null;
    suppress: boolean;
    pendingLeadFragment: boolean;
  };
  replace: (text: string) => {
    text: string;
    delta: string | null;
    suppress: boolean;
    pendingLeadFragment: boolean;
  };
};
//#endregion
//#region src/gateway/server-chat-progress-snapshot.d.ts
type ChatRunProgressSnapshot = {
  events: AgentEventPayload[];
  byteLength: number;
  lastSeq: 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 ChatRunToolRecipientState = {
  connIds: Set<string>;
  updatedAt: number;
  finalizedAt?: number;
};
type PendingLiveTextFlush = {
  timer: NodeJS.Timeout;
  flush: () => void;
};
type LiveDisplayState = {
  projector: ReturnType<typeof createLiveAssistantTextProjection>;
  current: ReturnType<ReturnType<typeof createLiveAssistantTextProjection>["replace"]>;
  pendingRawDelta?: string | null;
  reset?: boolean;
  unsentDelta: string | null;
  sentText?: string;
};
type ChatRunRecord = {
  lastActivityAt: number;
  registrations?: ChatRunEntry[];
  rawBuffer?: string;
  buffer?: string;
  bufferIsCurrent?: () => boolean;
  /** Retire queued connection snapshots when this buffering generation is cleared. */
  liveTextGroup?: AbortController;
  liveTextEpoch?: object;
  display?: LiveDisplayState;
  planSnapshot?: ChatRunPlanSnapshot;
  progressSnapshot?: ChatRunProgressSnapshot;
  canvasBlocks?: ChatCanvasBlock[];
  deltaSentAt?: number;
  assistantScope?: AssistantTextSnapshot["scope"];
  managedMediaUrls?: Set<string>;
  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 = {
  runs: Map<string, ChatRunRecord>;
  registry: ChatRunRegistry;
  toolEventRecipients: ToolEventRecipientRegistry;
  /** Acquire mutable state and record activity; readers use runs.get. */
  getOrCreate: (runId: string) => ChatRunRecord;
  resolveBuffer: (runId: string, options?: {
    final?: boolean;
  }) => {
    text: string;
    suppress: boolean;
  };
  updateBuffer: (runId: string, input: Parameters<typeof mergeAssistantText>[1]) => string;
  takeBufferDelta: (runId: string, text: string) => {
    deltaText: string;
    replace?: true;
  } | 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 ToolEventRecipientRegistry = {
  add: (runId: string, connId: string) => void;
  get: (runId: string) => ReadonlySet<string> | undefined;
  markFinal: (runId: string) => void;
  pruneExpired: (now?: number) => 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) => void) => () => void;
};
type SessionMessageSubscription = (() => void) & {
  commit: () => void;
};
//#endregion
//#region src/agents/model-selection-config.d.ts
declare function resolveDefaultModelForAgent(params: {
  cfg: OpenClawConfig;
  agentId?: string;
  allowManifestNormalization?: boolean;
  allowPluginNormalization?: boolean;
} & ModelManifestNormalizationContext): ProviderModelRef;
//#endregion
//#region src/agents/model-selection-shared.d.ts
type ModelAliasIndex = {
  byAlias: Map<string, {
    alias: string;
    ref: ProviderModelRef;
  }>;
  byProviderAlias?: Map<string, {
    alias: string;
    ref: ProviderModelRef;
  }>;
  byKey: Map<string, string[]>;
  disabledKeys?: Set<string>;
};
type AllowedModelSet = {
  allowAny: boolean;
  allowedCatalog: ModelCatalogEntry[];
  allowedKeys: Set<string>;
  allows: (ref: ProviderModelRef) => boolean;
};
/** Build explicit model override authorization without widening it for automatic fallbacks. */
declare function buildAllowedModelSet(params: {
  cfg: OpenClawConfig;
  catalog: ModelCatalogEntry[];
  defaultProvider: string;
  defaultModel?: string | ProviderModelRef;
  agentId?: string;
} & ModelManifestNormalizationContext): AllowedModelSet;
/** Status of a candidate model against catalog and configured allowlist state. */
type ModelRefStatus = {
  key: string;
  inCatalog: boolean;
  allowAny: boolean;
  allowed: boolean;
};
type ResolveAllowedModelRefResult = {
  ref: ProviderModelRef;
  key: string;
} | {
  error: string;
};
declare function getModelRefStatus(params: Parameters<typeof buildAllowedModelSet>[0] & {
  ref: ProviderModelRef;
}): ModelRefStatus;
/** Resolve a requested model string only if it is allowed by the supplied status check. */
declare function resolveAllowedModelRefFromAliasIndex(params: {
  cfg: OpenClawConfig;
  raw: string;
  defaultProvider: string;
  agentId?: string;
  aliasIndex: ModelAliasIndex;
  getStatus: (ref: ProviderModelRef) => ModelRefStatus;
} & ModelManifestNormalizationContext): ResolveAllowedModelRefResult;
//#endregion
//#region src/agents/model-selection-resolve.d.ts
/** Resolves a raw model string into an allowed model ref or an explanatory error. */
declare function resolveAllowedModelRefCore(params: Omit<Parameters<typeof getModelRefStatus>[0], "ref"> & {
  raw: string;
}): ReturnType<typeof resolveAllowedModelRefFromAliasIndex>;
//#endregion
//#region src/gateway/worker-environments/placement-projector.d.ts
type WorkerSessionPlacementReader = {
  getMany(sessionIds: readonly string[]): ReadonlyMap<string, WorkerSessionPlacementRecord>;
  getWorkspaceResultReconcilingSessionIds?(sessionIds: readonly string[]): ReadonlySet<string>;
  listPendingWorkspaceResults?(sessionId?: string): WorkerWorkspacePendingResult[];
  /** Runtime consumers may cancel work when the exact captured turn claim closes. */
  registerTurnClaimClosedHandler?: (handler: (claim: WorkerSessionTurnClaim) => void) => () => void;
};
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/session-activity-summaries.d.ts
type SessionActivitySummaryService = {
  ensure: (target: ActivitySummaryTarget) => SessionActivitySummary;
  handleEvent: (event: SessionObserverEvent) => void;
  handleTranscript: (event: InternalSessionTranscriptUpdate) => void;
  handleLifecycle: (event: SessionLifecycleEvent) => void;
  dispose: () => Promise<void>;
};
//#endregion
//#region src/gateway/chat-abort-diagnostics.d.ts
type ChatAbortDiagnosticReason = "rpc" | "stop" | "timeout" | "restart" | "archive" | "delete" | "authority-revoked" | "superseded" | "aborted";
//#endregion
//#region src/gateway/chat-queued-turns.d.ts
type QueuedChatTurnEntry = {
  controller: AbortController;
  sessionId: string;
  sessionKey: string;
  /** False once collect-mode transfers cancellation to the aggregate owner. */
  abortable?: boolean;
  abortListener?: () => void;
  agentId?: string;
  ownerConnId?: string;
  ownerDeviceId?: string;
  abortDiagnosticReason?: ChatAbortDiagnosticReason;
  /** Hold this source's adoption while its explicit withdrawal is committed. */
  holdPendingInputWithdrawal?: () => (() => void) | undefined;
};
//#endregion
//#region src/commands/daemon-runtime.d.ts
type GatewayDaemonRuntime = "bun" | "node";
//#endregion
//#region src/commands/onboard-types.d.ts
type OnboardMode = "local" | "remote";
/**
 * Auth choices are plugin-owned contract ids plus a few legacy aliases that
 * are normalized elsewhere (for example `oauth` -> `setup-token`).
 */
type BuiltInAuthChoice =
/** @deprecated Use `setup-token`. */
"oauth" | "setup-token" | "token" | "apiKey" | "custom-api-key" | "skip";
type AuthChoice = BuiltInAuthChoice | (string & {});
type GatewayAuthChoice = "token" | "password";
type ResetScope = "config" | "config+creds+sessions" | "full";
type GatewayBind = "loopback" | "lan" | "auto" | "custom" | "tailnet";
type TailscaleMode = "off" | "serve" | "funnel";
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;
  lmstudioApiKey?: string;
  customModelId?: string;
  customProviderId?: string;
  customCompatibility?: "openai" | "openai-responses" | "anthropic";
  customImageInput?: boolean;
  gatewayPort?: number;
  gatewayBind?: GatewayBind;
  gatewayAuth?: GatewayAuthChoice;
  gatewayToken?: string;
  gatewayTokenRefEnv?: string;
  gatewayPassword?: string;
  tailscale?: TailscaleMode;
  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 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;
//#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;
};
type ControlUiSessionPullRequests = {
  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";
};
//#endregion
//#region src/gateway/control-ui-session-pr-read.d.ts
type ControlUiSessionPrTarget = {
  params: {
    sessionKey: string;
    agentId: string;
  };
  identity: string;
  readSource: {
    agentId: string;
    path: string;
  };
  source: string | GitCheckoutContext | null;
  assertCurrent?: () => void;
};
type ControlUiSessionPrReadContext = {
  target: ControlUiSessionPrTarget;
  sourceIdentity: string;
  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 LoadSessionPullRequests = (params: ControlUiSessionPullRequestsParams, cacheSignal: AbortSignal | undefined, read: ControlUiSessionPrReadContext) => Promise<ControlUiSessionPullRequests>;
type SubscriptionDeps = {
  broadcastToConnIds: GatewayBroadcastToConnIdsFn;
  prepareRead: (connId: string, session: Pick<ControlUiSessionPullRequestsParams, "sessionKey" | "agentId">) => Promise<ControlUiSessionPrRead | undefined>;
  isConnectionActive?: (connId: string) => boolean;
  load?: LoadSessionPullRequests;
  scheduler: GatewayScheduler;
};
type ControlUiSessionPullRequestSubscriptions = {
  replace: (connId: string, sessionKeys: readonly string[], refreshSessionKeys?: ReadonlySet<string>, onAdmitted?: () => void) => Promise<void>;
  unsubscribe: (connId: string) => void;
  pollNow: () => Promise<void>;
  stop: () => Promise<void>;
};
/**
 * 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): ControlUiSessionPullRequestSubscriptions;
//#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;
};
//#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;
  /**
   * 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.
   */
  send(frame: string, callback?: (error?: Error) => void): void;
  send(frame: Buffer, options: {
    binary: false;
  }, callback?: (error?: Error) => void): 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";
/**
 * Runtime WebSocket client state tracked by the gateway server.
 */
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;
  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;
  /** 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;
  /** 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?: PreparedSessionProfile;
  authenticatedUserProfile?: {
    profileId: string;
    displayName: string | null;
    avatarRevision: string;
    hasAvatar: boolean;
    updatedAt: number;
  };
  clientIp?: string;
  /** Server-attested inputs for rechecking browser-origin policy after config publication. */
  browserOrigin?: GatewayWsBrowserOrigin;
  internal?: {
    /** 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;
    /** Additional access captured at authenticated admission; independent of socket lifetime. */
    operatorAccessAuthority?: GatewayOperatorAccessAuthority | null;
  };
  invalidatedReason?: string;
};
//#endregion
//#region src/gateway/server/client-registry.d.ts
declare class GatewayClientRegistry extends Set<GatewayWsClient> {
  #private;
  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;
};
type SessionViewerPresenceDeclarations = {
  replace: (connId: string, sessionKeys: readonly string[]) => readonly string[];
  unsubscribe: (connId: string) => void;
  stop: () => void;
};
/** Owns one replace-set per websocket connection until empty declaration or disconnect. */
declare function createSessionViewerPresenceDeclarations(deps: SessionViewerPresenceDeclarationsDeps): SessionViewerPresenceDeclarations;
//#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>>;
  /** Canonical install owners whose committed contents may already be running. */
  expectedInstallHashes?: Readonly<Record<string, string>>;
  /** Private invoker authority; never part of the published runtime receipt. */
  assertInvokerOwned?: () => void;
}) => Promise<PluginRuntimeApplication>;
//#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/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 DesktopComputerLease = {
  env: NodeJS.ProcessEnv;
  isCurrent(): boolean;
  release(): void;
};
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/observe-requester.d.ts
type DesktopObserveRequester = {
  connId?: string;
  /** Display identity from authenticated Gateway metadata, never wire-supplied client labels. */
  operatorName?: string;
  signal?: AbortSignal;
  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(deps?: {
  lingerMs?: number;
}): {
  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 = {
  observe(params: {
    control: boolean;
    requester?: DesktopObserveRequester;
    credentials?: {
      username?: string;
      password?: string;
    };
  }): Promise<{
    transport: "rfb";
    wsPath: string;
    expiresAtMs: number;
    control: boolean;
    auth: "vnc-password" | "ard-account";
    vncPassword?: string;
    audio?: DesktopObserveResult["audio"];
    audioUnavailableReason?: DesktopObserveResult["audioUnavailableReason"];
    preauthenticated?: boolean;
  }>;
  acquireComputer(params: {
    onStop(): Promise<void>;
  }): Promise<DesktopComputerLease>;
  status(): Promise<HostDesktopStatus>;
  reconcileRuntimePolicy(): Promise<void>;
};
//#endregion
//#region src/gateway/desktop/computer-protocol.d.ts
declare const command: z.ZodEnum<{
  "computer.act": "computer.act";
  "screen.snapshot": "screen.snapshot";
}>;
type ComputerHostCommand = z.infer<typeof command>;
//#endregion
//#region src/gateway/desktop/computer-service.d.ts
type GatewayComputerStatus = {
  configured: boolean;
  available: boolean;
  computerUse?: ComputerUseCapabilityDescriptor;
  error?: string;
};
type ComputerInvokeRequest = {
  command: ComputerHostCommand;
  params: Record<string, unknown>;
  generation: string;
  owner: string;
  signal?: AbortSignal;
  ownerSignal?: AbortSignal;
  assertCurrent(): void;
  timeoutMs?: number;
  idempotencyKey: string;
};
type GatewayComputerService = {
  status(): Promise<GatewayComputerStatus>;
  invoke(request: ComputerInvokeRequest): Promise<unknown>;
  reconcileRuntimePolicy(): Promise<void>;
  close(): Promise<void>;
  revokeRunAuthority(authority: AgentRunDelegatedAuthority): void;
  preparePluginReload: (params: {
    changedPluginIds: ReadonlySet<string>;
  }) => {
    drain: () => Promise<void>;
    resume: () => 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/bundle.d.ts
type WorkerBundleArtifact = ExpectedWorkerBuild & {
  install: "bundle";
  tarballBytes: number;
  tarballSha256: string;
  tarballPath: string;
};
type WorkerNpmArtifact = ExpectedWorkerBuild & {
  install: "npm";
  packageIntegrity: string;
  packageSpec: string;
};
type WorkerInstallationArtifact = WorkerBundleArtifact | WorkerNpmArtifact;
//#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/placement-turn-claim-events.d.ts
type WorkerTurnExecutionIdentity = Readonly<{
  agentId: string;
  delegatedAuthority: AgentRunDelegatedAuthority;
  executionIdentityToken?: ExecutionIdentityAdmissionToken;
  operationalRunInstance: OperationalRunInstanceRef;
  operatorAuthority?: AdmittedRunOperatorAuthority;
  /** Original presence reader, retained on the Gateway without a worker-writable claim. */
  assertPresenceSourceCurrent?: () => void;
  receiptAuthority: () => void;
  sessionKey: string;
  sessionTarget: Readonly<BoundAgentRunSessionTarget>;
  turnClaim: WorkerSessionTurnClaim;
}>;
type WorkerTurnTranscriptSource = Pick<WorkerTurnExecutionIdentity, "sessionTarget" | "receiptAuthority">;
type WorkerTurnExecutionIdentityCapability = WorkerTurnTranscriptSource & Readonly<{
  run<T>(callback: (identity: WorkerTurnExecutionIdentity) => Promise<T> | T): Promise<T>;
}>;
//#endregion
//#region src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.d.ts
type DeferredEmbeddedRunLifecycleOwner = {
  beginRetryWait: (deadlineAtMs: number, signal: AbortSignal) => ((completed?: boolean) => void) | undefined;
  complete: () => Promise<void>;
  discard: () => 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;
} | {
  kind: "presentation-only";
})>;
type RunEmbeddedAgentInternalParams = RunEmbeddedAgentParams & {
  /** Fail-closed caller input admission against the actual prepared model, before dispatch. */
  assertModelInput?: (model: Pick<Model, "input">) => void;
  /** Reset deferred terminal facts when the host admits a new attempt, before preparation. */
  onAttemptStart?: () => 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";
  /** 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;
  pluginRuntimeRefreshMessages?: EmbeddedRunAttemptParams["pluginRuntimeRefreshMessages"];
  /** 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) => ((completed?: boolean) => void) | undefined;
};
type EmbeddedRunAttemptInternalParams = EmbeddedRunAttemptParams & Pick<RunEmbeddedAgentInternalParams, "onContextAccountingEvent" | "onCompactionRequestBudget"> & {
  compactionCountOwner?: "subscription" | "caller";
  /** Current-run committed plan facts; retained across attempts, never loaded from history. */
  completionCheck?: EmbeddedRunCompletionCheck;
};
//#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;
  maxPendingBytes?: 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, ownerEpoch: number) => 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;
  }): void;
  prepareWorkspaceResultOwnerRevocation(binding: WorkerPlacementBinding, error: Error): void;
  registerTurnClaimClosedHandler(handler: (claim: WorkerSessionTurnClaim) => void): () => void;
};
//#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.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>>;
  bundleStatus: z.ZodOptional<z.ZodLiteral<1>>;
  portalStream: z.ZodOptional<z.ZodLiteral<1>>;
  environmentSession: z.ZodOptional<z.ZodLiteral<1>>;
  statusWait: z.ZodOptional<z.ZodLiteral<1>>;
  preparedWorkspace: z.ZodOptional<z.ZodLiteral<1>>;
  capturedExecPolicy: z.ZodOptional<z.ZodLiteral<true>>;
  launchToolNames: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<readonly ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[], string[]>>>;
  idleRetention: z.ZodOptional<z.ZodLiteral<true>>;
}, 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;
  bundleStatus?: 1 | undefined;
  portalStream?: 1 | undefined;
  environmentSession?: 1 | undefined;
  statusWait?: 1 | undefined;
  preparedWorkspace?: 1 | undefined;
  capturedExecPolicy?: true | undefined;
  launchToolNames?: readonly ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[] | undefined;
  idleRetention?: true | undefined;
}, {
  enabled: false;
  reason?: string | undefined;
} | {
  enabled: true;
  capacity: {
    total: number;
    available: number;
    reclaimableIdle?: number | undefined;
  };
  bundlePrewarm?: 1 | undefined;
  bundleRetention?: 1 | undefined;
  bundleStatus?: 1 | undefined;
  portalStream?: 1 | undefined;
  environmentSession?: 1 | undefined;
  statusWait?: 1 | undefined;
  preparedWorkspace?: 1 | undefined;
  capturedExecPolicy?: true | undefined;
  launchToolNames?: readonly ("apply_patch" | "browser" | "computer" | "edit" | "exec" | "portal" | "presence" | "process" | "read" | "sessions_send" | "sessions_spawn" | "skill_workshop" | "write")[] | undefined;
  idleRetention?: true | undefined;
}>>;
type NodeWorkerHostDeclaration = z.infer<typeof WorkerHost>;
//#endregion
//#region src/gateway/node-invoke.types.d.ts
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;
  /** Receives the id and armed hard deadline after a successful dispatch. */
  onDispatchReady?: (invokeId: string, deadlineAtMs?: number) => void;
  /** 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;
  } | null;
};
//#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 src/gateway/node-registry.invoke-stream.d.ts
type NodeInvokeProgressParams = {
  invokeId: string;
  nodeId: string;
  connId: string | undefined;
  seq: number;
  chunk: string;
};
type NodeInvokeResultParams = {
  id: string;
  nodeId: string;
  connId: string | undefined;
  ok: boolean;
  payload?: unknown;
  payloadJSON?: string | null;
  error?: {
    code?: string;
    message?: string;
  } | null;
};
//#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;
    isDispatchAuthorized: () => boolean;
    onDispatchReady?: (invokeId: string) => void;
  }): Promise<NodeInvokeResult>;
};
//#endregion
//#region src/gateway/worker-environments/node-worker-bundle-installer.d.ts
type GatewayNodeWorkerBundleInstall = (params: {
  deviceId: string;
  environmentId: string;
  artifact: Extract<WorkerInstallationArtifact, {
    install: "bundle";
  }>;
  prewarm: boolean;
  reason: "provision" | "refresh";
  signal?: AbortSignal;
  assertCurrent?: () => void;
  onProgress?: () => void;
}) => Promise<NodeWorkerBundleInstallResult>;
//#endregion
//#region src/gateway/worker-environments/repository-project-source.d.ts
declare const RepositoryProject: 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";
            claw: "claw";
            operator: "operator";
          }>;
          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.ZodLiteral<"system-configured">;
        profileId: z.ZodString;
        accountId: z.ZodNumber;
      }, z.core.$strict>, z.ZodObject<{
        source: z.ZodLiteral<"agent-override">;
        profileId: z.ZodString;
        accountId: z.ZodNumber;
      }, z.core.$strict>], "source">;
    }, z.core.$strict>;
  }, z.core.$strict>;
}, z.core.$strip>;
type RepositoryWorkerProjectSnapshot = z.infer<typeof RepositoryProject>;
//#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/preparation-identity.d.ts
declare const 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>;
type WorkerPreparationArtifacts = z.infer<typeof Artifacts>;
type WorkerProviderPreparedIntent = {
  providerId: string;
  profileSnapshot: WorkerProfile;
  preparationKey?: string;
};
//#endregion
//#region src/gateway/worker-environments/project-preparation.d.ts
type ProjectPreparation = NonNullable<NonNullable<Parameters<WorkerProvider$1["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;
  };
  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$1 | 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$1;
    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;
    assertCurrent: () => void;
  }>;
  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/transcript-commit-store.d.ts
type WorkerTranscriptCommitOutcome = {
  ok: true;
  result: WorkerTranscriptCommitResult;
} | {
  ok: false;
  reason: WorkerTranscriptCommitErrorReason;
};
//#endregion
//#region packages/gateway-protocol/src/schema/worker-skill-workshop.d.ts
declare const WorkerSkillWorkshopParamsSchema: Type$1.TObject<{
  toolCallId: Type$1.TString;
  arguments: Type$1.TObject<{
    action: Type$1.TEnum<["list", "read", "create", "update", "share", "unshare", "transfer", "activate", "remove", "rollback"]>;
    target: Type$1.TOptional<Type$1.TLiteral<"personal">>;
    skill_id: Type$1.TOptional<Type$1.TString>;
    expected_revision: Type$1.TOptional<Type$1.TString>;
    revision: Type$1.TOptional<Type$1.TString>;
    name: Type$1.TOptional<Type$1.TString>;
    proposal_content: Type$1.TOptional<Type$1.TString>;
    artifact_path: Type$1.TOptional<Type$1.TString>;
    files: Type$1.TOptional<Type$1.TArray<Type$1.TObject<{
      path: Type$1.TString;
      encoding: Type$1.TOptional<Type$1.TUnion<[Type$1.TLiteral<"utf8">, Type$1.TLiteral<"base64">]>>;
      executable: Type$1.TOptional<Type$1.TBoolean>;
      content: Type$1.TString;
    }>>>;
    delete_files: Type$1.TOptional<Type$1.TArray<Type$1.TString>>;
  }>;
}>;
type WorkerSkillWorkshopParams = Static<typeof WorkerSkillWorkshopParamsSchema>;
//#endregion
//#region src/gateway/worker-environments/worker-session-tool-result.d.ts
type WorkerSessionToolRequest = {
  identity: WorkerConnectionIdentity;
  signal?: AbortSignal;
} & ({
  toolName: "sessions_spawn";
  request: WorkerSessionsSpawnParams;
} | {
  toolName: "sessions_send";
  request: WorkerSessionsSendParams;
} | {
  toolName: "portal";
  request: WorkerPortalParams;
} | {
  toolName: "presence";
  request: WorkerPresenceParams;
} | {
  toolName: "skill_workshop";
  request: WorkerSkillWorkshopParams;
});
type WorkerSessionToolExecutor = (request: WorkerSessionToolRequest) => Promise<WorkerSessionToolResult>;
//#endregion
//#region src/gateway/worker-environments/inference-store.kernel.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;
};
/** The shared-state worker supplies the already-admitted transaction connection. */
declare function createWorkerInferenceStoreKernel(options: {
  db: DatabaseSync;
  now: () => number;
  retention?: Partial<WorkerInferenceRetentionPolicy>;
}): {
  begin: (rawInput: WorkerInferenceTurnInput) => WorkerInferenceTurnBeginResult;
  cancelPending: (params: {
    environmentId: string;
    sessionId: string;
    runEpoch: number;
    runId: string;
    turnId: string;
    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;
  env?: NodeJS.ProcessEnv;
  now?: () => number;
  retention?: Partial<WorkerInferenceRetentionPolicy>;
}): {
  begin: (input: Parameters<Kernel["begin"]>[0], assertCurrent?: () => void) => Promise<{
    kind: "claimed";
  } | {
    kind: "recover";
  } | {
    kind: "replay";
    outcome: WorkerInferenceTerminalOutcome;
  } | {
    kind: "rejected";
    reason: "conflict";
  }>;
  complete: (input: Parameters<Kernel["complete"]>[0], assertCurrent?: () => void) => Promise<{
    readonly type: "done";
    readonly message: {
      readonly role: "assistant";
      readonly content: ({
        readonly type: "text";
        readonly text: string;
        readonly textSignature?: string | undefined;
      } | {
        readonly type: "thinking";
        readonly thinking: string;
        readonly thinkingSignature?: string | undefined;
        readonly redacted?: boolean | undefined;
      } | {
        readonly type: "toolCall";
        readonly id: string;
        readonly name: string;
        readonly arguments: Record<string, unknown>;
        readonly thoughtSignature?: string | undefined;
        readonly executionMode?: "parallel" | "sequential" | undefined;
      })[];
      readonly api: string;
      readonly provider: string;
      readonly model: string;
      readonly responseModel?: string | undefined;
      readonly responseId?: string | undefined;
      readonly 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;
      readonly usage: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        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;
        };
      };
      readonly timestamp: number;
      readonly stopReason: "length" | "stop" | "toolUse";
    };
  } | {
    readonly type: "error";
    readonly reason: "cancelled" | "epoch-mismatch" | "invalid-context" | "model-not-approved" | "provider-error" | "session-not-attached";
    readonly message: string;
    readonly usage?: {
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
      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;
  }>;
  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 WorkerInferenceFenceReason = Extract<WorkerInferenceErrorReason, "epoch-mismatch" | "session-not-attached">;
type WorkerInferenceSink = {
  connectionId: string;
  send(frame: WorkerInferenceEventFrame | WorkerInferenceTerminalFrame): void;
};
type WorkerInferenceExecutor = (params: {
  identity: WorkerConnectionIdentity;
  request: WorkerInferenceStartParams;
  signal: AbortSignal;
  emit: (event: WorkerInferenceEventParams["event"]) => void;
  isCurrent(): boolean;
  sessionTarget: BoundAgentRunSessionTarget;
  config?: OpenClawConfig;
}) => Promise<WorkerInferenceTerminalOutcome>;
type RevalidateInference = () => WorkerInferenceFenceReason | 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;
  getConfig?: () => OpenClawConfig;
  requestMaxBytes?: number;
  streamMaxBytes?: number;
};
//#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/infra/device-pairing-read.types.d.ts
type DevicePairingBinding = {
  identity: string;
  generation?: string;
};
//#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-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-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-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;
};
//#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 NodeEventPayloadPreparation = (connId: string) => {
  payloadJSON: SerializedEventPayload | null;
  onSent?: () => void;
} | undefined;
type PairingBoundNodeSession = NodeSession & {
  pairingIdentity: string;
};
/** Connectivity probe result for a registered node. */
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>;
};
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;
};
/** Registry of currently connected Gateway nodes. */
declare class NodeRegistry {
  private readonly options;
  private nodesById;
  private nodesByConn;
  private eventTransportsByConn;
  private pendingInvokes;
  private invokeStreams;
  private authorizedSystemRunEvents;
  private pairingGenerationEventChains;
  private committedConfig;
  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;
  /** List connected node sessions. */
  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 projectPairingLeaseResolutions;
  private invalidateSessionForPairingChange;
  /** Immediately retires one exact transport after its persisted pairing authority changes. */
  invalidateConnectionForPairingChange(connId: string, reason?: string): boolean;
  /** Return a connected node session by node id. */
  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;
  private rememberAuthorizedSystemRunEvent;
  private forgetAuthorizedSystemRunEvent;
  private authorizedSystemRunEventExpiresAt;
  private matchAuthorizedSystemRunEvent;
  private allowsLegacyMacRunIdFallback;
  private pruneAuthorizedSystemRunEvents;
  private authorizedSystemRunEventKey;
  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 sendEventRawForPairingGenerationNow;
  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(deps?: {
  ttlMs?: number;
  now?: () => number;
}): {
  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;
  onDispatchReady?: () => void;
};
type NodeWorkerLaunchAdapterOptions = {
  getTransport: () => NodeWorkerSupervisorTransport | undefined;
  now?: () => number;
  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
  rpcTimeoutMs?: number;
  pollIntervalMs?: number;
  cancellationTimeoutMs?: number;
};
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 = {
  manifest: WorkerWorkspaceManifest;
  manifestRef: string;
  rawManifest: string;
  root: string;
  /** Sparse checkpoint payloads contain only these paths from the complete manifest. */
  blobPaths?: ReadonlySet<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;
};
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-service.d.ts
type DownloadCapability = {
  direction: "download";
  token: string;
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
  generation: number;
  manifestRef: string;
  expiresAtMs: number;
  isAuthorized?: () => boolean;
  signal?: AbortSignal;
};
type UploadOperation = {
  direction: "upload";
  token: string;
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
  generation: number;
  baseManifestRef: string;
  expiresAtMs: number;
  state: "ready" | "receiving" | "completed";
  isAuthorized?: () => boolean;
  uploaded?: NodeWorkspaceTransferUpload;
  abortController: AbortController;
  receiving?: {
    result: Promise<{
      manifestRef: string;
    }>;
    signal: AbortSignal;
  };
  disposal?: Promise<void>;
};
type TransferContext = {
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
  generation: number;
  localPath?: string;
  temporaryRoot: string;
  currentManifestRef: string;
  snapshots: Map<string, NodeWorkspaceTransferSnapshot>;
  baseCommit: string | null;
  pack?: Promise<string>;
  downloads: Map<string, DownloadCapability>;
  upload?: UploadOperation;
  abortController: AbortController;
  stopWatchingOwnerSignal?: () => void;
  isAuthorized: () => boolean;
};
type TransferAuthorization = {
  context: TransferContext;
  capability: DownloadCapability | UploadOperation;
  route: NodeWorkspaceTransferHttpRoute;
};
type TransferPreparation = Pick<TransferContext, "environmentId" | "ownerEpoch" | "sessionId" | "generation" | "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): 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-workspace-actions.d.ts
type NodeWorkerWorkspaceBinding = {
  source: {
    kind: "local";
    path: string;
  } | {
    kind: "repository";
    baseCommit: string;
    baseManifestRef: string;
  };
  manifestRef: string;
  remoteWorkspaceDir: string;
  sessionKey?: string;
};
//#endregion
//#region src/gateway/worker-environments/node-worker-tunnel.d.ts
type NodeWorkerWorkspaceBindingResolver = (binding: {
  environmentId: string;
  ownerEpoch: number;
  sessionId: string;
}) => Promise<NodeWorkerWorkspaceBinding | undefined>;
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;
};
/** Owns node-channel handles without treating the persistent machine as a disposable lease. */
declare function createNodeWorkerTunnelManager(options: NodeWorkerTunnelManagerOptions): {
  runSessionCommand(binding: {
    environmentId: string;
    ownerEpoch: number;
    sessionId: string;
    sessionKey: string;
  }, command: WorkerWorkspaceCommand): Promise<NodeWorkerWorkspaceExecResult>;
  bindWorkspaceBindingResolver(resolver: NodeWorkerWorkspaceBindingResolver): void;
  start(request: NodeWorkerTunnelStartRequest): Promise<WorkerTurnTunnelHandle>;
  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">;
//#endregion
//#region src/gateway/worker-environments/inference-control-internal.d.ts
type WorkerInferenceSessionDrain = {
  drained: Promise<void>;
  hasWork(): boolean;
  release(): void;
};
type AcceptedWorkerInferenceSessionDrain = WorkerInferenceSessionDrain & {
  start(): void;
};
type WorkerInferenceCancellation = {
  readonly runIds: readonly string[];
  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, reason?: WorkerInferenceErrorReason) => Promise<void>;
  cancelClaim: (claim: WorkerSessionTurnClaim) => Promise<void>;
  cancelSession: (sessionId: string, runId?: string) => Promise<string[]>;
  captureSessionCancellation: (sessionId: string, runId?: string) => WorkerInferenceCancellation;
  reserveSessionDrain: (sessionId: string) => {
    assertReserved(): void;
    accept(): AcceptedWorkerInferenceSessionDrain;
    release(): void;
  };
  hasSession: (sessionId: string, runId?: string) => boolean;
  resolveSessionTargetForRunId: (runId: string) => BoundAgentRunSessionTarget | undefined;
  stop: () => 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/transcript-commit.d.ts
type WorkerTranscriptCommitApplication = (params: {
  identity: WorkerConnectionIdentity;
  request: WorkerTranscriptCommitParams;
  sessionTarget: BoundAgentRunSessionTarget;
  assertCurrent: () => undefined;
}) => Promise<WorkerTranscriptCommitOutcome>;
//#endregion
//#region src/gateway/worker-environments/worker-turn-rpc.d.ts
type WorkerTranscriptCommitServiceResult = WorkerTranscriptCommitOutcome | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerLiveEventServiceResult = WorkerLiveEventApplicationResult | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerInferenceStartServiceResult = WorkerInferenceStartApplicationResult | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerInferenceCancelServiceResult = WorkerInferenceCancelApplicationResult | {
  ok: false;
  closeReason: WorkerProtocolCloseReason;
};
type WorkerTurnRpcOptions = {
  store: WorkerEnvironmentStore;
  prepareInstallation: (install: WorkerInstallationArtifact["install"]) => Promise<WorkerInstallationArtifact>;
  applyTranscriptCommit?: WorkerTranscriptCommitApplication;
  liveEvents?: Pick<WorkerLiveEventReceiver, "apply">;
  placementStore?: WorkerSessionPlacementGate;
  executeComputer?: WorkerComputerExecutor;
  executeSessionTool?: WorkerSessionToolExecutor;
  inference: ReturnType<typeof createWorkerInferenceManager>;
  isStopping: () => boolean;
  now: () => number;
  withLock: <T>(environmentId: string, task: () => Promise<T>) => Promise<T>;
};
declare function createWorkerTurnRpc(options: WorkerTurnRpcOptions): {
  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) => "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, request: WorkerLiveEventParams) => Promise<WorkerLiveEventServiceResult>;
  executeSessionTool: (identity: WorkerConnectionIdentity, toolName: WorkerSessionToolName, request: WorkerSessionToolRequest["request"], signal?: AbortSignal) => Promise<{
    ok: true;
    result: WorkerSessionToolResult;
  } | {
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: false;
    reason: WorkerProtocolCloseReason;
  }>;
  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<WorkerInferenceStartServiceResult>;
  cancelInference: (identity: WorkerConnectionIdentity, request: WorkerInferenceCancelParams) => Promise<WorkerInferenceCancelServiceResult>;
  cancelInferenceForSession: (params: {
    sessionId: string;
    runId?: string;
  }) => Promise<string[]>;
  hasInferenceForSession: (sessionId: string, runId?: string) => boolean;
  clear: () => void;
};
//#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;
};
type WorkerEnvironmentServiceOptions = WorkerProviderLifecycleInputOptions & WorkerEnvironmentSessionAttachmentOptions & {
  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;
  closeNodeBootstrapArtifacts?: () => Promise<void>;
  stopNodeWorkerBundleTransfers?: () => void | Promise<void>;
  maintainProviders?: (signal: AbortSignal) => Promise<void>;
  scheduler: GatewayScheduler;
  reconcileIntervalMs?: number;
  bootstrapCallTimeoutMs?: number;
  workerCredentialTtlMs?: number;
  generateWorkerCredential?: (bytes: number) => string;
  now?: () => number;
  logger?: {
    warn: (message: string) => void;
  };
  applyTranscriptCommit?: WorkerTranscriptCommitApplication;
  liveEvents?: Pick<WorkerLiveEventReceiver, "apply" | "clear" | "clearEnvironment" | "rotateCredential">;
  executeInference: WorkerInferenceExecutor;
  inferenceStore?: WorkerInferenceStore;
  placementStore?: WorkerSessionPlacementGate;
  executeSessionTool?: Parameters<typeof createWorkerTurnRpc>[0]["executeSessionTool"];
};
type WorkerEnvironmentReconcileCore = (signal?: AbortSignal, retainProviderSettlement?: (settled: Promise<void>) => void) => Promise<void>;
type WorkerEnvironmentReconcileGuard = (environmentId: string, reconcileCore: WorkerEnvironmentReconcileCore) => Promise<void>;
//#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;
      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;
      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;
    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;
    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;
      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;
      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>;
  }>;
  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;
    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;
    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;
    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;
    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?: {
    inherited?: {
      providerId: string;
      profileSnapshot: WorkerProfile;
    };
    machineClass?: string;
    os?: string;
    executionMode?: WorkerExecutionMode;
    projectPath?: string;
    projectCommit?: string;
    repository?: {
      agentId: string;
      url: string;
      ref?: string;
      baseCommit?: string;
    };
    projectRepository?: RepositoryWorkerProjectSnapshot;
    runSetupScript?: boolean;
    signal?: AbortSignal;
    setupAuthorized?: boolean;
  }) => 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;
    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;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  })[];
  schedulePreparedRefill: (environmentId?: string) => undefined;
  inventoryVersion: () => number;
  machineShapeVersion: () => number;
  subscribeMachineShapeChanged: (listener: (profileId: string) => void) => () => 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;
  readProviderDisplayId: (profileId: string) => string | undefined;
  listMachineOptions: (profileId: string) => Promise<readonly Readonly<{
    id: string;
    label: string;
    os?: string;
    cpu?: number;
    memoryGb?: number;
    default?: boolean;
  }>[] | undefined>;
  listOperatingSystems: (profileId: string) => Promise<readonly Readonly<{
    id: string;
    label: string;
    default?: boolean;
    disabledReason?: string;
  }>[] | 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;
  }>;
  createWithRequest: ({ profileId, idempotencyKey, inheritedProfile, admittedIntent, machineClass, executionMode, projectPath, signal, os, runSetupScript }: 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;
    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;
    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;
    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;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  destroy: (environmentId: string, abandonment?: WorkerEnvironmentAbandonment, forceAbandon?: () => Promise<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;
    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;
    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;
    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;
    error?: string | undefined;
    desktopAvailable: boolean;
    desktopApps: ("browser" | "terminal")[];
    tunnelStatus: "connected" | "connecting" | "reconnecting" | "stopped";
  }>;
  destroyUnattached: (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;
    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;
    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";
  }) => Promise<WorkerDesktopLaunchResult>;
  reconcileDesktopPolicy: () => 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";
  }>;
  fenceWorkerTurnForRecovery: (claim: WorkerSessionTurnClaim) => void;
  validateWorkerConnection: (identity: WorkerConnectionIdentity) => "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<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | WorkerTranscriptCommitOutcome>;
  pushLiveEvent: (identity: WorkerConnectionIdentity, request: WorkerLiveEventParams) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | WorkerLiveEventApplicationResult>;
  executeSessionTool: (identity: WorkerConnectionIdentity, toolName: WorkerSessionToolName, request: WorkerSessionToolRequest["request"], signal?: AbortSignal) => Promise<{
    ok: true;
    result: WorkerSessionToolResult;
  } | {
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: false;
    reason: WorkerProtocolCloseReason;
  }>;
  executeComputer: (identity: WorkerConnectionIdentity, request: WorkerComputerParams, signal?: AbortSignal) => Promise<{
    ok: true;
    result: WorkerComputerResult;
  } | {
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | {
    ok: false;
    reason: WorkerProtocolCloseReason;
    message?: string;
  }>;
  prepareComputer: ((claim: WorkerSessionTurnClaim) => Promise<PreparedWorkerComputer | undefined>) | undefined;
  startInference: (identity: WorkerConnectionIdentity, request: WorkerInferenceStartParams, sink: WorkerInferenceSink) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | WorkerInferenceStartApplicationResult>;
  cancelInference: (identity: WorkerConnectionIdentity, request: WorkerInferenceCancelParams) => Promise<{
    ok: false;
    closeReason: WorkerProtocolCloseReason;
  } | WorkerInferenceCancelApplicationResult>;
  cancelInferenceForSession: (params: {
    sessionId: string;
    runId?: string;
  }) => Promise<string[]>;
  hasInferenceForSession: (sessionId: string, runId?: string) => boolean;
  resolveSshIdentity: (environmentId: string) => Promise<WorkerSshIdentity>;
  attachSession: (request: WorkerCredentialBinding & {
    sessionId: string;
    placementBinding?: PreparedEnvironmentPlacementBinding;
  }) => Promise<MintedWorkerCredential>;
  takeMintedCredential: (binding: WorkerCredentialBinding) => MintedWorkerCredential | undefined;
  acquireTurnCredential: (claim: WorkerSessionTurnClaim) => Promise<MintedWorkerCredential>;
  acknowledgeCredentialDelivery: (grant: MintedWorkerCredential) => Promise<boolean>;
  startTunnel: (request: WorkerTunnelRequest) => Promise<WorkerTunnelHandle>;
  stopTunnel: (environmentId: string, ownerEpoch?: number) => Promise<void>;
  stopNodeEnrollmentWaits: (() => void) | undefined;
  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/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/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: "repository";
  repository: SessionRepositoryWorkspaceRecord;
};
//#endregion
//#region src/gateway/worker-environments/workspace-operation-coordinator.d.ts
type WorkerWorkspaceOperationCoordinator = {
  run<T>(environmentId: string, operation: () => Promise<T>): 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;
    mutate: (assertCurrent: () => void) => Promise<{
      changed: boolean;
      value: T;
    }>;
  }): Promise<T>;
};
//#endregion
//#region src/gateway/github-publication-availability.d.ts
type PublicationSessionIdentity = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  lifecycleRevision?: string | null;
};
//#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-requester.d.ts
type GitHubPublicationRequesterPolicy = Readonly<{
  snapshot: GitHubPublicationRequesterSnapshot;
  assertCurrent: () => void;
}>;
type GitHubPublicationRequester = GitHubPublicationRequesterPolicy & Readonly<{
  /** An accepted row keeps its own policy while the current invocation retains its fences. */
  assertInvocationCurrent: () => void;
}>;
//#endregion
//#region src/infra/kysely-sync-cache-state.d.ts
declare const { kyselyByDatabase, queryErrorHandlerByDatabase }: {
  kyselyByDatabase: WeakMap<DatabaseSync, unknown>;
  queryErrorHandlerByDatabase: WeakMap<DatabaseSync, (error: unknown) => void>;
};
//#endregion
//#region src/gateway/github-publication-coordinator-methods.d.ts
type GitHubPublicationClaimRequest = {
  claim: WorkerSessionTurnClaim;
  sessionKey: string;
  agentId: string;
  idempotencyKey: string;
  title?: string;
  body?: string;
  requester: GitHubPublicationRequester;
  expectedPublisher?: GitHubPublicationPublisher;
};
type GitHubPublicationSessionRequest = SessionGitHubPublishParams & {
  agentId: string;
  expectedRunId?: string;
  requester: GitHubPublicationRequester;
};
//#endregion
//#region src/gateway/github-personal-oauth.d.ts
type PersonalGitHubAction = {
  owner: string;
  assertCurrent: () => void;
};
//#endregion
//#region src/gateway/github-personal-publication.d.ts
type PersonalGitHubSessionAction = PersonalGitHubAction & {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  lifecycleRevision: string | null;
};
//#endregion
//#region src/gateway/github-publication.d.ts
type GitHubPublicationCoordinator = ReturnType<typeof createGitHubPublicationCoordinator>;
declare function createGitHubPublicationCoordinator(params: {
  placements: WorkerSessionPlacementStore;
  getCommittedRuntimeConfig: () => OpenClawConfig;
}): {
  requestForClaim: (request: GitHubPublicationClaimRequest) => 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>;
  deferClaimPreparation(claim: WorkerSessionTurnClaim): void;
  requestForSession(input: Parameters<(input: GitHubPublicationSessionRequest) => Promise<SessionGitHubPublicationResult>>[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;
  }>;
  requestPersonalForSession(input: {
    sessionKey?: string | undefined;
    agentId?: string | undefined;
    idempotencyKey: string;
    title?: string | undefined;
    body?: string | 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<{
    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;
  }>;
  sharedStatus(session: PublicationSessionIdentity, requestId: string): {
    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;
  } | undefined;
  latestShared(session: PublicationSessionIdentity, idempotencyKey?: string | undefined): {
    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;
  personalStatus(action: PersonalGitHubAction, session: {
    sessionKey: string;
    agentId: string;
    sessionId: string;
    lifecycleRevision?: string | null;
  }, requestId: string): {
    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: {
    sessionKey: string;
    agentId: string;
    sessionId: string;
    lifecycleRevision?: string | 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>;
  confirmPersonal(input: {
    sessionKey: string;
    agentId?: string | undefined;
    requestId: string;
    generation: string;
    account: {
      accountId: number;
      login: string;
    };
    requestDigest: string;
  }, action: PersonalGitHubSessionAction): 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(): Promise<void>;
  deferOrphanedRequests(): void;
  listUnreportedResults(): {
    sessionId: string;
    sessionKey: string;
    agentId: string;
    result: SessionGitHubPublicationResult;
  }[];
  read(requestId: 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: "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;
  markReported(requestId: string): void;
};
//#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-oauth-lifecycle.d.ts
declare function createGitHubOAuthLifecycle(params: {
  getConfig: () => OpenClawConfig;
  getPersistedConfig?: () => OpenClawConfig;
  warn: (message: string) => void;
  scheduler: GatewayScheduler;
}): {
  personal: {
    status: (action: PersonalGitHubAction) => Promise<PersonalGitHubStatus>;
    revalidateStatus: (action: PersonalGitHubAction, prepared: PersonalGitHubStatus) => PersonalGitHubStatus;
    startAuthorization(action: PersonalGitHubAction): Promise<UsersGitHubAuthorizeStartResult>;
    pollAuthorization(action: PersonalGitHubAction, requestId: string): Promise<UsersGitHubAuthorizePollResult>;
    cancelAuthorization(action: PersonalGitHubAction, requestId: string): boolean;
    disconnect(action: PersonalGitHubAction): 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>;
  cancelAuthorization: (requestId: string) => boolean;
  status: (agentId: string, selectedScope: GitHubIdentityScope) => Promise<{
    agentId: string;
    selectedScope: "agent" | "system";
    selected: {
      scope: "agent" | "system";
      configured: boolean;
      identity: {
        source: "agent-override" | "system-configured" | "system-detected";
        credentialKind: "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: {
      source: "agent-override" | "system-configured" | "system-detected";
      credentialKind: "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";
    };
  }>;
  retireProfile: (profileId: string) => void;
  refreshEffectiveIdentity: (agentId: string) => Promise<void>;
  maintain: () => Promise<void>;
  start: () => void;
  stop: () => Promise<void>;
};
//#endregion
//#region src/gateway/model-account-authority.d.ts
/** In-process account authority shared by connect and selection owners; never serialized. */
type ModelAccountConnectAction = {
  owner: string;
  assertCurrent: () => void;
};
type UserModelAccountSelection = ModelAccountConnectAction & {
  authProfileId: string;
};
//#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;
}): {
  listLinks(action: ModelAccountConnectAction): UsersListAuthLinksResult;
  link(action: ModelAccountConnectAction, authProfileId: string): UsersLinkAuthProfileResult;
  unlink(action: ModelAccountConnectAction, provider: string): UsersUnlinkAuthProfileResult;
  list(action: ModelAccountConnectAction, cursor?: string): UsersListModelAccountsResult;
  catalog(action: ModelAccountConnectAction): UsersAuthConnectCatalogResult;
  select(action: ModelAccountConnectAction, authProfileId: string): UsersSelectModelAccountResult;
  start(action: ModelAccountConnectAction, provider: string, methodId: string): Promise<UsersAuthConnectStartResult>;
  status(action: ModelAccountConnectAction, connectId: string): UsersAuthConnectStatusResult;
  answer(action: ModelAccountConnectAction, connectId: string, stepId: string, value?: unknown): Promise<UsersAuthConnectStatusResult>;
  cancel(action: ModelAccountConnectAction, connectId: string): 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/infra/gateway-suspend-coordinator.d.ts
/** Private identity of one live process-owning host iteration, never a wire token. */
type GatewaySuspendHandoffOwner = {
  isCurrent: () => boolean;
};
//#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;
};
/** Snapshot of channel runtime state keyed by channel and account id. */
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 = {
  preserveRestartAttempts?: boolean;
  preserveManualStop?: boolean;
  /** Reload leaves snapshot-cold accounts stopped without bypassing credential-file reinspection. */
  skipUnavailableAccounts?: boolean;
  deferAccountStartUntil?: Promise<void>;
  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 active;
  private sealed;
  readonly signal: AbortSignal;
  enter(options: RequestEntryOptions): GatewayRequestEntry;
  beginClose(): void;
  waitForPendingEntries(): Promise<void>;
  sealAndJoin(): Promise<void>;
}
//#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;
}>;
//#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/cli/outbound-send-mapping.d.ts
type CliOutboundSendSource = {
  [channelId: string]: unknown;
};
//#endregion
//#region src/cli/deps.types.d.ts
/** CLI dependency bag currently used by outbound send command plumbing. */
type CliDeps = CliOutboundSendSource;
//#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 = {
  ok: boolean;
  payload?: unknown;
  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<{
    type?: string;
    mimeType?: string;
    fileName?: string;
    content?: unknown;
  }>;
  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;
    expiresAtMs: number;
  } | undefined;
  abort: () => boolean;
};
/** A live frozen settle cohort may identify an already accepted legacy source. */
type RequesterSettleWakeReplay = {
  sourceSessionKeys: readonly string[];
  assertCurrent: () => void;
};
type InternalAgentTurnDispatchOptions = {
  /** Internal completion delivery owns its hidden input and durable processing receipt. */
  privateCompletion?: true;
  settleWakeReplay?: RequesterSettleWakeReplay;
  assertAdmissionCurrent?: () => void;
  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) => Promise<T>;
};
type InternalAgentTurnFacadeFactory = (principal: InternalAgentTurnPrincipalOptions) => InternalAgentTurnFacade | Promise<InternalAgentTurnFacade>;
//#endregion
//#region src/gateway/chat-abort.types.d.ts
type ChatTerminalProducer = {
  sessionId: string;
  sessionKey: string;
  handoff: (settle: (producerCompleted: Promise<void>) => Promise<void>) => boolean;
};
type ChatAbortControllerEntry = {
  controller: AbortController;
  /** Captures this run's canonical producer before cancellation releases its live slot. */
  resolveTerminalProducer?: () => ChatTerminalProducer | undefined;
  sessionId: string;
  sessionKey: string;
  lifecycleGeneration?: string;
  /** Exact operational instance created by this controller registration. */
  operationalRunInstance?: OperationalRunInstanceRef;
  /** Exact approval lease captured when this controller's execution was admitted. */
  agentRunDelegatedAuthority?: AgentRunDelegatedAuthority;
  agentId?: string;
  startedAtMs: number;
  /** False until lane admission reaches the execution boundary. */
  executionStarted?: boolean;
  expiresAtMs: number;
  ownerConnId?: string;
  ownerDeviceId?: string;
  providerId?: string;
  authProviderId?: string;
  abortStopReason?: string;
  /** Owner-recorded diagnostic cause; does not change terminal lifecycle semantics. */
  abortDiagnosticReason?: ChatAbortDiagnosticReason;
  /** Latest argument-free validation diagnostic for operator-initiated aborts. */
  toolErrorSummary?: string;
  /**
   * False for backend/internal agent runs that may share a session key but must
   * not be projected into operator chat surfaces.
   */
  controlUiVisible?: boolean;
  /**
   * Controls only the sessions.list active-run projection. Terminal lifecycle
   * clears this before chat.send settles, while the entry stays as the retry
   * idempotency guard until normal cleanup removes it.
   */
  projectSessionActive?: boolean;
  /** True after the terminal session-store update has completed. */
  projectSessionTerminalPersisted?: boolean;
  /** A terminal lifecycle event was observed and is awaiting persistence. */
  projectSessionTerminalPending?: boolean;
  /** Store timestamp expected from the observed terminal lifecycle event. */
  projectSessionTerminalObservedAt?: number;
  /** In-flight terminal session-store update used by restart shutdown. */
  projectSessionTerminalPersistence?: Promise<void>;
  /** Caller completion requested cleanup before terminal lifecycle persistence settled. */
  registrationCleanupRequested?: boolean;
  /** Bounded private timeout settlement while the aborted producer unwinds. */
  pendingTimeoutCompletion?: {
    expiresAtMs: number;
    settle: () => void;
  };
  /** False after the owning reply run commits a terminal outcome. */
  isAbortable?: (entry: ChatAbortControllerEntry) => boolean;
  /** Runs once when this registration is actually removed. */
  onRemoved?: () => void;
  /**
   * Which RPC owns this registration. Absent (undefined) is treated as
   * `"chat-send"` so pre-existing callers that constructed entries without
   * a kind keep their behavior. Consumers that need "chat.send specifically
   * is active" must check `kind !== "agent"`, not just `.has(runId)`.
   */
  kind?: "chat-send" | "agent";
  /** Side questions stay independent from main-turn TUI session stops. */
  turnKind?: "main" | "btw";
};
//#endregion
//#region src/gateway/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;
};
/** Coordinates live device scope-upgrade waiters with the durable pairing store. */
declare class ScopeUpgradeCoordinator {
  private readonly scheduler;
  private readonly entries;
  private readonly work;
  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<ScopeUpgradeResult | null>;
  private waitForResult;
  private readDurableResult;
  private retainTerminal;
}
//#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 PlacementStandingGrantRuntime = {
  resolveBinding: (input: PlacementGrantResolutionInput) => PlacementStandingGrantMintSpec | null;
  retain: (grant: PlacementStandingGrantMintSpec & {
    approvalId: string;
    nowMs: number;
    expiresAtMs: number | null;
  }) => boolean;
  validate: (binding: PlacementStandingGrantMintSpec) => ConsumePlacementStandingGrantResult;
  consume: (binding: PlacementStandingGrantMintSpec) => 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/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 = "user" | "timeout" | "malformed-verdict" | "no-route" | "run-aborted" | "gateway-restart" | "storage-corrupt";
type OperatorApprovalResolverKind = "device" | "channel" | "runtime" | "system";
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;
};
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";
};
/** Opaque v2026.9.4 SDK guards require a native commit boundary. */
type OperatorApprovalStoreGuard = {
  family: "worker" | "native-compatibility";
  assertCurrent: () => void;
};
//#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"];
  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>;
  /** Keep publication identity with the waiter, including durable storage-repair outcomes. */
  protected recordLifecyclePublication(event: OperatorApprovalLifecycleEvent, hasPublisher: boolean): void;
  protected wasTerminalPublished(record: OperatorApprovalRecord): 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<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 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>;
  }>;
  private scheduleAuthorityClosure;
  /** 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>;
  consumeAllowOnce(recordId: string, consumerId?: string): Promise<boolean>;
  /** Observes a registered decision; Gateway closure rejects the wait, not the approval. */
  awaitDecision(recordId: string): Promise<ExecApprovalDecision | null> | null;
  /** 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/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];
/** Health snapshot for one configured channel account. */
type ChannelAccountHealthSummary = ChannelAccountSnapshot & {
  authAgeMs?: number | null;
  [key: string]: unknown;
};
/** Channel-level health summary with optional per-account details. */
type ChannelHealthSummary = ChannelAccountHealthSummary & {
  accounts?: Record<string, ChannelAccountHealthSummary>;
};
type AgentHealthSummary = NonNullable<ProtocolHealth["agents"]>[number];
/** Plugin registry health summary. */
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 & {
  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/mention-inbox.types.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;
};
/** 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>;
  validateRecipients: (client: GatewayClient | null, input: UsersMentionableParams, profileIds: readonly string[]) => Result$1<readonly string[], ErrorShape>;
  list: (client: GatewayClient | null) => Result$1<MentionsListResult, ErrorShape>;
  dismiss: (client: GatewayClient | null, ids: readonly string[]) => Result$1<MentionsListResult, ErrorShape>;
  recordCommittedInput: (input: MentionCommittedInput) => void;
  invalidate: (sessionKey?: string) => void;
  dispose: () => 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 = {
  open: (params: GatewayPortalOpenParams) => Promise<PortalOpenResult>;
  list: () => PortalSummary[];
  listWorkerPortals: (environmentId: string, ownerEpoch: number, resourceOwnerKey?: string) => PortalSummary[];
  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
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>);
  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;
  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;
  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 requireEntry;
  private requirePendingEntry;
  /** Validates answers against stored questions and returns them in canonical form. */
  private validateAnswers;
  private invalidAnswer;
  private notFound;
  private expire;
  private finish;
}
//#endregion
//#region src/cron/scratch-store.d.ts
type CronJobScratch = {
  content: string;
  revision: number;
  sourceSha256?: string;
  updatedAtMs: number;
};
/**
 * Present scratch content plus the persisted revision. An unset scratch keeps a
 * tombstone row so `currentRevision` stays monotonic across unset/recreate and
 * stale compare-and-swap writers cannot resurrect old 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/gateway/server-cron-contract.d.ts
type GatewayCronServiceContract = CronServiceContract & {
  /** Cancel exact current definitions under the serving scheduler's operation lock. */
  quiesceJobs(jobs: readonly {
    id: string;
    revision: string;
  }[], commitGuard: () => 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>;
  readScratch(id: string): 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 = {
  assertAdmissionCurrent?: () => void;
  allowModelOverride?: boolean;
  allowSyntheticModelOverride?: boolean;
  allowSyntheticCronRunContinuation?: boolean;
  delegatedToolPolicyHandoff?: SubagentCompletionToolHandoffRegistration;
  expectFinal?: boolean;
  /** Instance-owned dispatch always uses a synthetic client. */
  forceSyntheticClient?: boolean;
  internalDeliveryMediaUrls?: string[];
  runtimeContextFragments?: RuntimeContextFragment[];
  internalDeliverySuppressText?: boolean;
  onAccepted?: (payload: unknown) => void;
  onStartOwner?: (owner: AgentTurnStartOwner) => void;
  onExecutionStarted?: () => void;
  onSignalAbort?: () => Promise<void> | void;
  scopes?: string[];
  signal?: AbortSignal;
  syntheticScopes?: string[];
};
type GatewayApprovalEventPublisher = {
  publishRequested: (kind: ChannelApprovalKind, request: unknown) => number;
  publishResolved: (kind: ChannelApprovalKind, resolved: unknown) => void;
};
type GatewayRecoverySessionMethod = "chat.history" | "chat.abort" | "sessions.delete";
type GatewayRecoveryTypingParams = {
  agentId?: string;
  runId: string;
  channel: string;
  to: string;
  accountId?: string;
  threadId?: string | number;
  isCurrent: (cfg: OpenClawConfig) => boolean;
};
type GatewayRecoveryRuntime = {
  dispatchSessionMethod: <T = unknown>(method: GatewayRecoverySessionMethod, params: unknown, options?: {
    timeoutMs?: number;
    signal?: AbortSignal;
    assertCurrent?: () => void;
  }) => Promise<T>;
  startRecoveryTyping?: (params: GatewayRecoveryTypingParams) => () => void;
  dispatchAgent: <T = unknown>(params: AgentRunRequest, timeoutMs?: number, options?: GatewayInstanceAgentDispatchOptions) => Promise<T>;
  waitForAgent: <T = unknown>(params: AgentWaitParams, timeoutMs?: number, signal?: AbortSignal) => Promise<T>;
  sendRecoveryNotice: (params: {
    channel: string;
    to: string;
    accountId?: string;
    threadId?: string | number;
    text: string;
    idempotencyKey: string;
  } & ({
    /** Main-session announcements cannot outlive their process-local owner. */
    liveOnly: true;
    isCurrent: (cfg: OpenClawConfig) => boolean;
  } | {
    /** Existing callers retain durable retry and deduplication by default. */
    liveOnly?: false;
    isCurrent?: (cfg: OpenClawConfig) => boolean;
  })) => Promise<{
    /** True when delivery produced zero platform results (policy/channel suppression). */
    suppressed: boolean;
  }>;
};
//#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;
  /** Retain source privacy for diagnostic replay after the live session binding is gone. */
  incognito?: true;
  payload?: unknown;
  error?: ErrorShape;
};
//#endregion
//#region src/gateway/server/event-loop-health.d.ts
type GatewayEventLoopHealthReason = "event_loop_delay" | "event_loop_utilization" | "cpu";
type GatewayEventLoopHealth = {
  degraded: boolean;
  degradedSinceMs: number | null;
  reasons: GatewayEventLoopHealthReason[];
  intervalMs: number;
  delayP99Ms: number;
  delayMaxMs: number;
  utilization: number;
  cpuCoreRatio: number;
  cpuBreakdown?: {
    mainThreadCoreRatio?: number;
    workerCoreRatio?: number;
    otherThreadsCoreRatio?: number;
    hostUtilization?: number;
    hostCpuCount?: number;
  };
};
//#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;
}): 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 = {
  emit: TerminalEventSink;
  getBufferedAmount?: (connId: string) => number | undefined;
  spawn?: typeof spawnTerminalPty;
  maxSessions?: number;
  env?: NodeJS.ProcessEnv;
  /** 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;
  createBackend?: () => Promise<TerminalBackend>;
  stageUpload?: (file: TerminalUploadFile) => Promise<TerminalUploadResult>;
};
type TerminalOpenOutcome = {
  ok: true;
  sessionId: string;
  agentId: string;
  cwd: string;
  shell: string;
} | {
  ok: false;
  code: "limit" | "spawn_failed" | "closed";
  message: string;
};
type TerminalAgentActionOutcome = {
  ok: true;
} | {
  ok: false;
  code: "session_unavailable" | "backend_failed";
};
//#endregion
//#region src/gateway/terminal/session-types.d.ts
type TerminalSessionSummary = {
  sessionId: string;
  agentId: string;
  shell: string;
  title?: string;
  cwd: string;
  attached: boolean;
  owner: "conn" | `agent:${string}`;
  createdAtMs: number;
};
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 connections;
  private readonly emit;
  private readonly getBufferedAmount;
  private readonly spawn;
  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>;
  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;
  private writeSession;
  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 resizeSession;
  /** 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;
  /** Fences and closes one durable agent-session incarnation through archive commit. */
  beginAgentSessionDrain(owner: AgentTerminalOwner): 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 hasAgentSessionWork;
  private resolveAgentSessionDrainIfIdle;
  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; concurrent opens claim distinct victims. */
  private claimLongestIdleAgentSession;
  private removeViewer;
  private interactiveSession;
  /** Agents may operate only PTYs created by their exact trusted session key. */
  private agentOwnedSession;
  private finalize;
}
//#endregion
//#region src/gateway/server-methods/chat-metadata-contract.d.ts
declare const chatMetadataSessionFields: readonly ["sessionId", "lifecycleRevision", "sessionStartedAt", "acp", "agentHarnessId", "agentRuntimeOverride", "modelSelectionLocked", "pluginOwnerId", "providerOverride", "modelOverride", "modelOverrideRouteResolution", "modelOverrideFallbackOriginProvider", "modelOverrideFallbackOriginModel", "authProfileOverride", "authProfileOverrideSource", "authProfileOverrideCompactionCount"];
type ChatMetadataSessionEntry = Partial<Pick<SessionEntry$1, (typeof chatMetadataSessionFields)[number]>>;
type ChatMetadataReadParams = {
  agentId: string;
  sessionKey?: string;
  storePath?: string;
  requesterProfileId?: string;
  sessionEntry?: ChatMetadataSessionEntry;
  /** Saved reads retain their selected row and physical store until response settlement. */
  isCurrent?: () => boolean;
  assertCurrent?: () => void;
  release?: () => void;
  draftAccountSelection?: UserModelAccountSelection;
};
type ChatMetadataResult = {
  commands?: unknown[];
  models?: ModelChoice[];
  modelSelectionPolicy?: ModelsListResult["modelSelectionPolicy"];
  swarmEnabled: boolean;
  runtimeSelectionLocked?: boolean;
  accountSelection?: ChatAccountSelection;
};
//#endregion
//#region src/gateway/server-methods/chat-startup-projection-contract.d.ts
type ChatStartupProjectionReadParams = {
  agentId: string;
  /** Startup reads this after metadata preparation yields; the profile owner tracks merges. */
  readRequesterProfileId?: () => string | undefined;
  sessionKey?: string;
  sessionEntry?: ChatMetadataSessionEntry;
  readPolicy?: "current" | "ready";
};
type ChatStartupProjectionResult = {
  metadata?: ChatMetadataResult;
  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;
  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;
  }) => Promise<PreparedGatewayModelCatalog | undefined>;
  readPreparedGatewayModelCatalogBatch?: (agentIds: readonly string[]) => Promise<PreparedGatewayModelCatalogReadResult[]>;
  readChatMetadata: (params: ChatMetadataReadParams) => Promise<ChatMetadataResult>;
  readChatStartupProjection?: (params: ChatStartupProjectionReadParams) => Promise<ChatStartupProjectionResult | undefined>;
  getHealthCache: () => HealthSummary | null;
  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;
  recoveryRuntime?: GatewayRecoveryRuntime;
  /** Uses the lifecycle owner's module graph for plugin and detached agent turns. */
  createAgentTurnFacade?: InternalAgentTurnFacadeFactory;
  enforceSharedGatewayAuthGenerationForConfigWrite?: (nextConfig: OpenClawConfig, previousConfig: OpenClawConfig) => void;
  nodeRegistry: NodeRegistry;
  agentRunSeq: Map<string, number>;
  chatAbortControllers: Map<string, ChatAbortControllerEntry>;
  /** Cancel identities for turns waiting in the followup/collect queue. */
  chatQueuedTurns: Map<string, QueuedChatTurnEntry>;
  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: (opts: OnboardOptions, runtime: RuntimeEnv, prompter: WizardPrompter) => Promise<void>;
  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>;
  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>;
  /** 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;
  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;
};
/** Complete runtime context available to gateway request handlers. */
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">;
};
/** Full dispatch context for raw request frames before params are normalized. */
type GatewayRequestOptions = {
  /** Transport can forward trusted worker JSON without materializing it. */
  acceptsSerializedJson?: 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 Gateway lifetime guard composed into durable session mutations. */
  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 = {
  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;
  /** Original host/session authority for committed input custody, without the selection precondition. */
  assertAdmittedInputCurrent?: () => void;
  /** Creation-owner notification after COMMIT; binds only this request's previously absent row. */
  recordCreatedSession?: (target: {
    agentId: string;
    sessionKey: string;
    storePath: string;
    sessionId: string;
    lifecycleRevision?: string;
  }) => 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"> & {
  params: Record<string, unknown>;
  sessionMutationAuthorization?: SessionMutationAuthorization;
  /** Host-prepared session resource authority; services explicitly retain their own borrow. */
  sessionAccessAuthority?: GatewaySessionAccessAuthority;
};
/** Single gateway method implementation. */
type GatewayRequestHandler = (opts: GatewayRequestHandlerOptions) => Promise<void> | void;
/** Registry fragment keyed by gateway protocol method name. */
type GatewayRequestHandlers = Record<string, GatewayRequestHandler>;
//#endregion
//#region src/plugins/config-activation-shared.d.ts
type PluginActivationSource = "disabled" | "explicit" | "auto" | "default";
//#endregion
//#region src/plugins/registry-types.d.ts
type ChannelPlugin = ChannelPlugin$1;
type CliBackendPlugin$1 = CliBackendPlugin;
type ImageGenerationProviderPlugin = ImageGenerationProviderPlugin$1;
type MediaUnderstandingProviderPlugin = MediaUnderstandingProviderPlugin$1;
type TranscriptSourceProvider = TranscriptSourceProvider$1;
type MusicGenerationProviderPlugin = MusicGenerationProviderPlugin$1;
type OpenClawPluginCliRootCommandDescriptor = OpenClawPluginCliRootCommandDescriptor$1;
type OpenClawPluginCliRegistrar = OpenClawPluginCliRegistrar$1;
type OpenClawPluginCommandDefinition = OpenClawPluginCommandDefinition$1;
type PluginInteractiveHandlerRegistration = PluginInteractiveHandlerRegistration$1;
type OpenClawGatewayDiscoveryService = OpenClawGatewayDiscoveryService$1;
type OpenClawPluginHttpRouteHandler = OpenClawPluginHttpRouteHandler$1;
type OpenClawPluginHttpRouteMatch = OpenClawPluginHttpRouteMatch$1;
type OpenClawPluginHostedMediaResolver = OpenClawPluginHostedMediaResolver$1;
type OpenClawPluginReloadRegistration = OpenClawPluginReloadRegistration$1;
type OpenClawPluginSecurityAuditCollector = OpenClawPluginSecurityAuditCollector$1;
type OpenClawPluginService = OpenClawPluginService$1;
type OpenClawPluginToolFactory = OpenClawPluginToolFactory$1;
type PluginConversationBindingResolvedEvent = PluginConversationBindingResolvedEvent$1;
type TypedPluginHookRegistration = PluginHookRegistration$1;
type PluginLogger = PluginLogger$1;
type PluginOrigin = PluginOrigin$1;
type PluginTextTransformRegistration = PluginTextTransformRegistration$1;
type MigrationProviderPlugin = MigrationProviderPlugin$1;
type RealtimeTranscriptionProviderPlugin = RealtimeTranscriptionProviderPlugin$1;
type RealtimeVoiceProviderPlugin = RealtimeVoiceProviderPlugin$1;
type SpeechProviderPlugin = SpeechProviderPlugin$1;
type VideoGenerationProviderPlugin = VideoGenerationProviderPlugin$1;
type WebFetchProviderPlugin = WebFetchProviderPlugin$1;
type WebSearchProviderPlugin = WebSearchProviderPlugin$1;
type WorkerProvider = WorkerProvider$1;
type UnifiedModelCatalogProviderPlugin = UnifiedModelCatalogProviderPlugin$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;
  /** Loader-owned provenance. Missing values are conservative legacy registrations. */
  origin?: PluginOrigin;
};
type PluginCliRegistration = PluginRegistrationOwner & {
  register: OpenClawPluginCliRegistrar;
  parentPath: string[];
  commands: string[];
  descriptors: OpenClawPluginCliRootCommandDescriptor[];
};
/** 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 PluginHostedMediaResolverRegistration = PluginRegistrationOwner & {
  resolver: OpenClawPluginHostedMediaResolver;
};
type PluginChannelRegistration = PluginRegistrationOwner & {
  plugin: ChannelPlugin;
  /** 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 PluginChannelSetupRegistration = PluginRegistrationOwner & {
  plugin: ChannelPlugin;
  /** Loader-owned provenance. Missing values are conservative legacy registrations. */
  origin?: PluginOrigin;
  enabled: boolean;
};
type PluginDashboardDataBindingRegistration = PluginManifestDashboardDataBinding & {
  pluginId: string;
  capabilityId: string;
  handler: GatewayRequestHandlers[string];
};
type PluginDashboardActionVerbRegistration = PluginManifestDashboardActionVerb & {
  pluginId: string;
  capabilityId: string;
  handler: GatewayRequestHandlers[string];
};
type PluginBoardWidgetContentKindRegistration = {
  pluginId: string;
  pluginKind: string;
  definition: PluginBoardWidgetContentKind;
};
type PluginCliBackendRegistration = PluginRegistrationOwner & {
  builtWithOpenClawVersion?: string;
  backend: CliBackendPlugin$1;
};
type PluginTextTransformsRegistration = PluginRegistrationOwner & {
  transforms: PluginTextTransformRegistration;
};
type PluginOwnedProviderRegistration<T> = PluginRegistrationOwner & {
  provider: T;
};
type PluginCodexAppServerExtensionFactoryRegistration = PluginRegistrationOwner & {
  rawFactory: CodexAppServerExtensionFactory;
  factory: CodexAppServerExtensionFactory;
};
type PluginAgentToolResultMiddlewareRegistration = PluginRegistrationOwner & {
  rawHandler: AgentToolResultMiddleware;
  handler: AgentToolResultMiddleware;
  runtimes: AgentToolResultMiddlewareRuntime[];
  scopes?: AgentToolResultMiddlewareScope[];
};
type PluginAgentToolResultMiddlewareOwner = {
  pluginId: string;
  runtimes: AgentToolResultMiddlewareRuntime[];
  manifest: PluginManifestRecord;
};
type PluginAgentHarnessRegistration = PluginRegistrationOwner & {
  harness: AgentHarness;
  nativeCompaction?: AgentHarnessNativeCompaction;
};
type PluginHookRegistration = {
  pluginId: string;
  entry: HookEntry;
  events: string[];
  source: string;
  rootDir?: string;
};
type PluginServiceRegistration = PluginRegistrationOwner & {
  readonly id: string;
  service: OpenClawPluginService;
  origin: PluginOrigin;
  trustedOfficialInstall?: boolean;
};
type PluginGatewayDiscoveryServiceRegistration = PluginRegistrationOwner & {
  readonly id: string;
  service: OpenClawGatewayDiscoveryService;
  instance?: PluginInstanceExecution;
};
type PluginReloadRegistration = PluginRegistrationOwner & {
  registration: OpenClawPluginReloadRegistration;
};
type PluginNodeHostCommandRegistration = PluginRegistrationOwner & {
  command: OpenClawPluginNodeHostCommand;
};
type PluginNodeInvokePolicyRegistration = PluginRegistrationOwner & {
  policy: OpenClawPluginNodeInvokePolicy;
  pluginConfig?: Record<string, unknown>;
};
type PluginGatewayAccessPolicyRegistration = PluginRegistrationOwner & {
  policy: PluginGatewayAccessPolicy;
};
type PluginWidgetPresenterRegistration = PluginRegistrationOwner & {
  presenter: WidgetPresenter;
};
type PluginSecurityAuditCollectorRegistration = PluginRegistrationOwner & {
  collector: OpenClawPluginSecurityAuditCollector;
};
type PluginCommandRegistration = PluginRegistrationOwner & {
  command: OpenClawPluginCommandDefinition;
  trustedOwnerStatusExposure?: true;
};
type PluginLegacyInternalHookRegistration = {
  pluginId: string;
  name: string;
  event: string;
  handler: InternalHookHandler;
};
type PluginSessionDiscussionRegistration = {
  pluginId: string;
  provider: SessionDiscussionProvider;
};
type PluginInteractiveHandlerRegistryRegistration = PluginInteractiveHandlerRegistration & {
  pluginId: string;
  pluginName?: string;
  pluginRoot?: string;
};
type PluginSessionExtensionRegistryRegistration = PluginRegistrationOwner & {
  extension: PluginSessionExtensionRegistration;
};
type PluginTrustedToolPolicyRegistryRegistration = PluginRegistrationOwner & {
  policy: PluginTrustedToolPolicyRegistration;
  origin?: PluginRecord["origin"];
};
type PluginToolMetadataRegistryRegistration = PluginRegistrationOwner & {
  metadata: PluginToolMetadataRegistration;
};
type PluginControlUiDescriptorRegistryRegistration = PluginRegistrationOwner & {
  descriptor: PluginControlUiDescriptor;
};
type PluginRuntimeLifecycleRegistryRegistration = PluginRegistrationOwner & {
  lifecycle: PluginRuntimeLifecycleRegistration;
};
type PluginAgentEventSubscriptionRegistryRegistration = PluginRegistrationOwner & {
  subscription: PluginAgentEventSubscriptionRegistration;
};
type PluginSessionSchedulerJobRegistryRegistration = PluginRegistrationOwner & {
  job: PluginSessionSchedulerJobRegistration;
  generation?: number;
};
type PluginSessionActionRegistryRegistration = PluginRegistrationOwner & {
  action: PluginSessionActionRegistration;
};
type PluginConversationBindingResolvedHandlerRegistration = PluginRegistrationOwner & {
  pluginRoot?: string;
  handler: (event: PluginConversationBindingResolvedEvent) => void | Promise<void>;
};
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[];
  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: PluginHookRegistration[];
  typedHooks: TypedPluginHookRegistration[];
  channels: PluginChannelRegistration[];
  channelSetups: PluginChannelSetupRegistration[];
  providers: PluginProviderRegistration[];
  modelCatalogProviders: PluginOwnedProviderRegistration<UnifiedModelCatalogProviderPlugin>[];
  sessionCatalogs: PluginOwnedProviderRegistration<SessionCatalogProvider>[];
  cliBackends: PluginCliBackendRegistration[];
  textTransforms: PluginTextTransformsRegistration[];
  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>>;
  migrationProviders: PluginOwnedProviderRegistration<MigrationProviderPlugin>[];
  codexAppServerExtensionFactories: PluginCodexAppServerExtensionFactoryRegistration[];
  agentToolResultMiddlewareOwners: PluginAgentToolResultMiddlewareOwner[];
  agentToolResultMiddlewares: PluginAgentToolResultMiddlewareRegistration[];
  agentHarnesses: PluginAgentHarnessRegistration[];
  pluginRuntimeArtifacts: Map<string, ResolvedPluginRuntimeArtifact>;
  compactionProviders: RegisteredCompactionProvider[];
  decisionProviders: Array<{
    pluginId: string;
    host: DecisionProviderHost;
  }>;
  legacyInternalHooks: PluginLegacyInternalHookRegistration[];
  memoryCapabilities: MemoryPluginCapabilityRegistration[];
  memoryCorpusSupplements: MemoryCorpusSupplementRegistration[];
  memoryPromptPreparations: MemoryPromptPreparationRegistration[];
  memoryPromptSupplements: MemoryPromptSupplementRegistration[];
  sessionDiscussionProviders: Map<string, PluginSessionDiscussionRegistration>;
  contextEngines: Map<string, ContextEngineRegistration>;
  gatewayHandlers: GatewayRequestHandlers;
  gatewayMethodDescriptors: GatewayMethodDescriptor[];
  dashboardDataBindings: Map<string, PluginDashboardDataBindingRegistration>;
  dashboardActionVerbs: Map<string, PluginDashboardActionVerbRegistration>;
  boardWidgetContentKinds: Map<string, PluginBoardWidgetContentKindRegistration>;
  coreGatewayMethodNames: string[];
  httpRoutes: PluginHttpRouteRegistration[];
  hostedMediaResolvers: PluginHostedMediaResolverRegistration[];
  widgetPresenters: PluginWidgetPresenterRegistration[];
  mcpServerConnectionResolvers: PluginMcpServerConnectionResolverRegistration[];
  cliRegistrars: PluginCliRegistration[];
  reloads: PluginReloadRegistration[];
  nodeHostCommands: PluginNodeHostCommandRegistration[];
  nodeInvokePolicies: PluginNodeInvokePolicyRegistration[];
  gatewayAccessPolicies: PluginGatewayAccessPolicyRegistration[];
  securityAuditCollectors: PluginSecurityAuditCollectorRegistration[];
  services: PluginServiceRegistration[];
  gatewayDiscoveryServices: PluginGatewayDiscoveryServiceRegistration[];
  commands: PluginCommandRegistration[];
  interactiveHandlers: PluginInteractiveHandlerRegistryRegistration[];
  sessionExtensions: PluginSessionExtensionRegistryRegistration[];
  trustedToolPolicies: PluginTrustedToolPolicyRegistryRegistration[];
  toolMetadata: PluginToolMetadataRegistryRegistration[];
  controlUiDescriptors: PluginControlUiDescriptorRegistryRegistration[];
  runtimeLifecycles: PluginRuntimeLifecycleRegistryRegistration[];
  agentEventSubscriptions: PluginAgentEventSubscriptionRegistryRegistration[];
  sessionSchedulerJobs: PluginSessionSchedulerJobRegistryRegistration[];
  sessionActions: PluginSessionActionRegistryRegistration[];
  conversationBindingResolvedHandlers: PluginConversationBindingResolvedHandlerRegistration[];
  diagnostics: PluginDiagnostic[];
};
type PluginRegistryParams = {
  logger: PluginLogger;
  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 hasActiveCall: boolean;
  readonly acceptingCalls: boolean;
  readonly hasRetainedConsumers: boolean;
  readonly owner?: PluginInstanceOwner;
  toolRegistrationComplete: boolean;
  runConsumer<T>(consume: () => T): T;
  adopt<T>(value: T): T;
  retainWork(): () => void;
  readonly retainedWorkCount: number;
  waitForRetainedWork(signal: AbortSignal, includeConsumers?: boolean): Promise<void>;
  reserveReplacement(): () => void;
  retainConsumer(invoke?: <T>(run: () => T) => T, registry?: PluginRegistry, kind?: "work" | "custody"): PluginInstanceConsumer;
  runInRegistry<T>(registry: PluginRegistry, 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;
  registry: PluginRegistry;
  revoked: boolean;
  instance?: PluginInstanceHandle;
};
//#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/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/service-contract.d.ts
/** Non-secret worker projection available to Gateway request handlers. */
type WorkerEnvironmentServiceRecord = {
  environmentId: string;
  providerId: string;
  profileId: string;
  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 = {
  transport: "rfb";
  wsPath: string;
  expiresAtMs: number;
  control: boolean;
  /** Provider permission to request resizing, not negotiated RFB support. */
  canResize?: boolean;
  vncPassword?: string;
};
type WorkerDesktopLaunchResult = {
  app: WorkerDesktopApp["id"];
  status: "ready";
};
/** Request-facing lifecycle methods, kept separate from persistence and provider internals. */
type WorkerEnvironmentServiceContract = {
  /** 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: {
    profileId: string;
    projectPath: string;
  }, authorize?: () => void): Promise<{
    environmentId: string;
    preparationKey: string;
    reused: boolean;
  }>;
  create(profileId: string, idempotencyKey: string, machineClass?: string, executionMode?: WorkerPlacementExecutionMode, projectPath?: string, signal?: AbortSignal, os?: string, runSetupScript?: boolean): Promise<WorkerEnvironmentServiceRecord>;
  destroy(environmentId: string): Promise<WorkerEnvironmentServiceRecord>;
  destroyUnattached(environmentId: string): Promise<WorkerEnvironmentServiceRecord>;
  observeDesktop(request: {
    environmentId: string;
    control: boolean;
    requester?: DesktopObserveRequester;
  }): Promise<WorkerDesktopObserveResult>;
  launchDesktopApp(request: {
    environmentId: string;
    app: WorkerDesktopApp["id"];
  }): Promise<WorkerDesktopLaunchResult>;
  startTunnel(request: WorkerTunnelRequest): Promise<WorkerTunnelHandle>;
  stopTunnel(environmentId: string, ownerEpoch?: number): Promise<void>;
};
type WorkerPlacementDispatchRequest = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  profileId: string;
  executionMode: WorkerPlacementExecutionMode;
  expectedPlacement?: Pick<WorkerSessionPlacementRecord, "state" | "generation" | "environmentId" | "activeOwnerEpoch">;
  /** 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 = {
  sessionId: string;
  sessionKey: string;
  agentId: string;
  recoverToGateway?: SessionsReclaimParams["recoverToGateway"];
};
type WorkerPlacementMoveRequest = Pick<WorkerPlacementReclaimRequest, "sessionId" | "sessionKey" | "agentId"> & {
  source: WorkerPlacementMoveSource;
  target: WorkerPlacementMoveTarget;
  abandonSource?: true;
};
/** Closure-bound request authority; in-process only and never part of durable placement intent. */
type WorkerPlacementAuthorization = () => void;
type WorkerPlacementCancellationTarget = Readonly<Pick<WorkerSessionPlacementRecord, "state" | "generation" | "environmentId" | "activeOwnerEpoch">>;
/** Exact source eligibility may follow only transitions published by captured predecessors. */
type WorkerPlacementReclaimSourceCheck = (predecessor?: WorkerPlacementCancellationTarget) => void;
type WorkerPlacementDispatchContract = {
  getPendingDeviceDispatchCount?(deviceId: string, excludeSessionId?: string): number;
  getAdmittedDeviceSessionCounts?(excludeSessionId?: string): 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): 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, "retireSessionPlacement" | "listForReconcile">>;
};
//#endregion
//#region src/auto-reply/reply/abort.d.ts
type FastAbortRequestParams = {
  ctx: FinalizedRuntimeMsgContext;
  cfg: OpenClawConfig;
  isCommandTargetCurrent?: () => boolean;
};
type FastAbortResult = {
  handled: boolean;
  aborted: boolean;
  rejectionReason?: "finalizing";
  stoppedSubagents?: number;
  failedSubagents?: number;
};
declare function formatAbortReplyText(stoppedSubagents?: number, rejectionReason?: "finalizing", failedSubagents?: number): string;
declare function tryFastAbortFromMessage(params: FastAbortRequestParams): Promise<FastAbortResult>;
//#endregion
//#region src/auto-reply/reply/abort.runtime-types.d.ts
type TryFastAbortFromMessage = typeof tryFastAbortFromMessage;
type FormatAbortReplyText = typeof formatAbortReplyText;
//#endregion
//#region src/auto-reply/reply/command-session-metadata.d.ts
type CommandSessionMetadataChange = {
  sessionKey: string;
  agentId?: string;
  reason: "command-metadata";
};
//#endregion
//#region src/media-understanding/extracted-file-images.d.ts
type ExtractedFileImage = ImageContent$1 & {
  attachmentIndex: number;
};
//#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$1["groupActivation"];
};
//#endregion
//#region src/agents/bash-tools.process.d.ts
/** Defaults injected by tests, agent scopes, and scoped process registries. */
type ProcessToolDefaults = {
  hasCronTool?: boolean;
  inputWaitIdleMs?: number;
  scopeKey?: string;
};
//#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/cli-runner/types.d.ts
type CliSessionBindingFacts = {
  extraSystemPromptStatic?: string;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  requireExplicitMessageTarget?: boolean;
};
//#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/reply-operation-run-state.d.ts
type ReplyOperationAdmissionSnapshot = {
  status: "owned";
} | {
  status: "accepted";
  mode: "steer" | "followup";
} | {
  status: "skipped";
  reason: "active-run" | "aborted" | "lifecycle-invalidated" | "queue-cap" | "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;
  heartbeat?: {
    prepareReply: (replyResult: ReplyPayload | ReplyPayload[] | undefined, runState: ReplyOperationRunState) => Promise<{
      reply?: ReplyPayload;
      settle?: (outcome: ReplyDispatchDeliveryOutcome) => Promise<void>;
    }>;
  };
  admission?: ReplyOperationAdmissionSnapshot;
  /** 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;
};
declare const REPLY_OPERATION_RUN_STATE: unique symbol;
type ReplyOptionsWithOperationRunState = {
  [REPLY_OPERATION_RUN_STATE]?: ReplyOperationRunState;
};
//#endregion
//#region src/auto-reply/reply/queue/types.d.ts
type FollowupQueueDisposition = "queue-cap" | "queue-cap-old" | "queue-cap-new";
type QueuedFollowupReplyBatch = {
  kind: "queued-followup";
  runId: string;
  originatingChannel: string | undefined;
  payloads: ReplyPayload[];
  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;
};
//#endregion
//#region src/shared/keyed-fifo-lease.d.ts
type KeyedFifoLease = {
  wait(signal?: AbortSignal): Promise<boolean>;
  release(): void;
};
//#endregion
//#region src/auto-reply/reply/reply-admission-ticket.d.ts
declare const REPLY_ADMISSION_TICKET: unique symbol;
type ReplyAdmissionTicket = KeyedFifoLease;
type ReplyOptionsWithAdmissionTicket = {
  [REPLY_ADMISSION_TICKET]?: ReplyAdmissionTicket;
};
//#endregion
//#region src/auto-reply/reply/get-reply.types.d.ts
type ReplySessionBinding = {
  sessionKey?: string;
  sessionId: string;
  lifecycleRevision?: string;
  storePath?: string;
};
type PendingContinuationSettlement = {
  settle: (statusDelivered: boolean) => Promise<void>;
};
type ReplyRunVerbosity = {
  verboseLevelOverride?: VerboseLevel;
  resolvedVerboseLevel: VerboseLevel;
};
type InternalReplySessionOptions = {
  /** Host-minted original operator authority; never restored from session metadata. */
  operatorAuthority?: AdmittedRunOperatorAuthority;
  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;
  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$1, "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;
  /** 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;
  /** Retire the run's bundle MCP runtime at settlement. Set by one-shot isolated runs (isolated heartbeats) whose session ID is never reused. */
  cleanupBundleMcpOnRunEnd?: boolean;
  /** Defers the child-completion wake until the visible waiting status is delivered. */
  onPendingContinuation?: (settlement?: PendingContinuationSettlement) => void;
  onSessionPrepared?: (binding: ReplySessionBinding) => void;
  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"];
  /** Receives terminal queue-cap outcomes without widening the public reply API. */
  onFollowupQueueDisposition?: (disposition: FollowupQueueDisposition) => void;
  /** Delivers queued replies only through their originating Gateway admission. */
  onQueuedFollowupReplyBatch?: QueuedFollowupReplyDelivery;
  /** Overrides persisted queue mode for this reply only. */
  queueModeOverride?: QueueMode;
  /** Dispatch-owned operation used to defer hooks until durable run admission. */
  replyOperation?: ReplyOperation;
  skillOverrides?: SessionToolOverrides["skills"];
  /** Gateway-private optimistic-concurrency constraint for an operator-requested proposal revision. */
  skillWorkshopProposalRevision?: SkillWorkshopProposalRevisionConstraint;
  skillLibraryAuthoring?: SkillLibraryAuthoringCapability;
};
type InternalGetReplyOptions = GetReplyOptions & PluginCommandReplyOptions & InternalReplySessionOptions & ReplyOptionsWithOperationRunState & ReplyOptionsWithAdmissionTicket;
/** Reply resolver signature used by dispatchers and tests for dependency injection. */
type GetReplyFromConfig = (ctx: MsgContext, opts?: GetReplyOptions, configOverride?: OpenClawConfig) => Promise<ReplyPayload | ReplyPayload[] | undefined>;
type InternalGetReplyFromConfig = (ctx: MsgContext, opts?: InternalGetReplyOptions, configOverride?: OpenClawConfig) => Promise<ReplyPayload | ReplyPayload[] | undefined>;
//#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;
  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?: TryFastAbortFromMessage;
  formatAbortReplyTextResolver?: 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 Always enabled in the Gateway; remove in the next Plugin SDK major. */
  usePublishedModelRuntime?: boolean;
};
type DispatchReplyFromConfig = (params: DispatchFromConfigParams) => Promise<DispatchFromConfigResult>;
//#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;
};
//#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 ReplyDispatchErrorHandler = (err: unknown, info: ReplyDispatchRuntimeInfo) => Promise<void> | void;
type ReplyDispatchSkipHandler = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo & {
  reason: NormalizeReplySkipReason;
}) => void;
type ReplyDispatchCancelHandler = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo) => Promise<void> | void;
type ReplyDispatchDeliverer = (payload: ReplyPayload, info: ReplyDispatchRuntimeInfo) => Promise<unknown>;
type ReplyDispatcherOptions = {
  deliver: ReplyDispatchDeliverer;
  /**
   * 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>;
  silentReplyContext?: {
    cfg?: OpenClawConfig;
    sessionKey?: string;
    surface?: string;
    conversationType?: SilentReplyConversationType;
  };
  responsePrefix?: string;
  transformReplyPayload?: (payload: ReplyPayload) => ReplyPayload | null;
  /** Static context for response prefix template interpolation. */
  responsePrefixContext?: ResponsePrefixContext;
  /** Dynamic context provider for response prefix template interpolation.
   * Called at normalization time, after model selection is complete. */
  responsePrefixContextProvider?: () => ResponsePrefixContext;
  onHeartbeatStrip?: () => void;
  onIdle?: () => Promise<void> | void;
  onError?: ReplyDispatchErrorHandler;
  /** Let ingress retry proven-unsent work only when outbound recovery holds no delivery. */
  propagateRetryableNoSendFailure?: boolean;
  onSkip?: ReplyDispatchSkipHandler;
  /** Human-like delay between block replies for natural rhythm. */
  humanDelay?: HumanDelayConfig;
  beforeDeliver?: ReplyDispatchBeforeDeliver;
  /** Owner-declared deadline for the constructor before-delivery callback. */
  beforeDeliverOptions?: ReplyDispatchBeforeDeliverOptions;
  onBeforeDeliverCancelled?: ReplyDispatchCancelHandler;
  /** Observe each queued payload settling, including cancellation and delivery failure. */
  onDeliverySettled?: (info: ReplyDispatchRuntimeInfo) => void;
  /** Resolve an owner activity policy for holding queued follow-ups behind delivery. */
  resolveFollowupAdmissionBarrierTimeoutPolicy?: (context: {
    queuedCounts: Readonly<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/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$1 = (params: {
  ctx: DispatchReplyContext;
  cfg: OpenClawConfig;
  dispatcherOptions: ReplyDispatcherWithTypingOptions;
  toolsAllow?: string[];
  replyOptions?: DispatchReplyOptions;
  replyResolver?: GetReplyFromConfig;
  dispatchReplyFromConfig?: DispatchReplyFromConfig;
}) => Promise<DispatchFromConfigResult>;
//#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;
  };
};
/** Function contract for recording inbound channel session state. */
type RecordInboundSession$1 = (params: {
  storePath: string;
  sessionKey: string;
  ctx: MsgContext;
  groupResolution?: GroupKeyResolution | null;
  createIfMissing?: boolean;
  updateLastRoute?: InboundLastRouteUpdate;
  onRecordError: (err: unknown) => void;
  trackSessionMetaTask?: (task: Promise<unknown>) => void;
}) => Promise<void>;
//#endregion
//#region src/auto-reply/commands-registry.types.d.ts
/** Extra context used when normalizing slash command text. */
type CommandNormalizeOptions = {
  botUsername?: string;
  /** Keeps complete directive/task arguments, including whitespace and later lines. */
  preserveArguments?: boolean;
  /** Strip an explicit command target only while channel bot identity is unavailable. */
  targetedCommandMode?: "pre-identity";
};
/** Inputs for deciding whether text slash commands should run on a surface. */
type ShouldHandleTextCommandsParams = {
  cfg: OpenClawConfig;
  surface: string;
  commandSource?: "text" | "native";
};
//#endregion
//#region src/auto-reply/command-detection.d.ts
/** Returns true when text starts with a configured control command alias. */
declare function hasControlCommand(text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions): boolean;
/** Returns true for exact control commands or abort triggers after metadata stripping. */
declare function isControlCommandMessage(text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions): boolean;
/** Returns true when a message may need command authorization metadata. */
declare function shouldComputeCommandAuthorized(text?: string, cfg?: OpenClawConfig, options?: CommandNormalizeOptions): boolean;
//#endregion
//#region packages/markdown-core/src/types.d.ts
/** Table rendering modes used when markdown tables need plaintext-safe output. */
type MarkdownTableMode = "off" | "bullets" | "code" | "block";
//#endregion
//#region packages/markdown-core/src/tables.d.ts
/** Convert only parsed table ranges; unrelated Markdown retains its original source bytes. */
declare function convertMarkdownTables(markdown: string, mode: MarkdownTableMode): string;
//#endregion
//#region src/agents/identity.d.ts
/** Resolve the configured identity block for one agent. */
declare function resolveAgentIdentity(cfg: OpenClawConfig, agentId: string): IdentityConfig | undefined;
/** Resolve message and response prefix values together for channel delivery. */
declare function resolveEffectiveMessagesConfig(cfg: OpenClawConfig, agentId: string, opts?: {
  hasAllowFrom?: boolean;
  fallbackMessagePrefix?: string;
  channel?: string;
  accountId?: string;
}): {
  messagePrefix: string;
  responsePrefix?: string;
};
/** Resolve per-agent human-delay settings over global agent defaults. */
declare function resolveHumanDelayConfig(cfg: OpenClawConfig, agentId: string): HumanDelayConfig | undefined;
//#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/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;
//#endregion
//#region src/auto-reply/envelope.d.ts
type AgentEnvelopeParams = {
  channel: string;
  from?: string;
  timestamp?: number | Date;
  host?: string;
  ip?: string;
  body: string;
  previousTimestamp?: number | Date;
  envelope?: EnvelopeFormatOptions;
};
/** User/config-facing controls for timestamp rendering in prompt envelopes. */
type EnvelopeFormatOptions = {
  /**
   * "local" (default), "utc", "user", or an explicit IANA timezone string.
   */
  timezone?: string;
  /**
   * Include absolute timestamps in the envelope (default: true).
   */
  includeTimestamp?: boolean;
  /**
   * Include elapsed time suffix when previousTimestamp is provided (default: true).
   */
  includeElapsed?: boolean;
  /**
   * Optional user timezone used when timezone="user".
   */
  userTimezone?: string;
};
/** Resolves envelope formatting defaults from agent config. */
declare function resolveEnvelopeFormatOptions(cfg?: OpenClawConfig): EnvelopeFormatOptions;
/** Formats the generic bracketed envelope prepended to agent-visible messages. */
declare function formatAgentEnvelope(params: AgentEnvelopeParams): string;
//#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-messages.d.ts
declare function buildPairingReply(params: {
  channel: PairingChannel;
  idLine: string;
  code: string;
}): string;
//#endregion
//#region src/media/store.d.ts
/** Media-store file metadata returned after bytes are persisted under a safe media ID. */
type SavedMedia = {
  id: string;
  path: string;
  size: number;
  contentType?: string;
};
/** Saves an in-memory media buffer under a UUID-backed media ID. */
declare function saveMediaBuffer(buffer: Buffer, contentType?: string, subdir?: string, maxBytes?: number, originalFilename?: string, detectionFilePathHint?: string, options?: {
  assertCommitAllowed?: () => void;
}): Promise<SavedMedia>;
//#endregion
//#region src/media/fetch.d.ts
/** Remote media bytes plus metadata before they are persisted to the media store. */
type FetchMediaResult = {
  buffer: Buffer;
  contentType?: string;
  fileName?: string;
};
/** Saved media record enriched with the best remote filename candidate. */
type SavedRemoteMedia = SavedMedia & {
  fileName?: string;
};
/** Retry policy applied around the complete guarded fetch and body read/save operation. */
type MediaFetchRetryOptions = RetryOptions;
/** Fetch-compatible injection point used by tests and guarded network callers. */
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;
};
/** Options for validating and saving an existing Response body into the media store. */
type SaveResponseMediaOptions = {
  sourceUrl?: string;
  filePathHint?: string;
  maxBytes?: number;
  readIdleTimeoutMs?: number;
  fallbackContentType?: string;
  subdir?: string;
  originalFilename?: string;
};
/** Options for guarded URL fetches that are saved directly into the media store. */
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>;
/** Fetches media through SSRF guards and returns the bounded response body as a buffer. */
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/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/ack-reactions.d.ts
type AckReactionScope = "all" | "direct" | "group-all" | "group-mentions" | "off" | "none";
/** Sent ack reaction state plus the cleanup hook callers can run after reply delivery. */
type AckReactionHandle = {
  ackReactionPromise: Promise<boolean>;
  ackReactionValue: string;
  remove: () => Promise<void>;
};
/**
 * Inputs for the reusable direct/group/mention gate shared by channel plugins.
 *
 * `effectiveWasMentioned` should already include any channel-specific mention
 * normalization. `shouldBypassMention` is only for an earlier channel gate that
 * proved the active conversation, such as a group activation state.
 */
type AckReactionGateParams = {
  scope: AckReactionScope | undefined;
  inboundEventKind?: "user_request" | "room_event";
  isDirect: boolean;
  isGroup: boolean;
  isMentionableGroup: boolean;
  canDetectMention: boolean;
  effectiveWasMentioned: boolean;
  shouldBypassMention?: boolean;
};
/** Resolves the generic ack reaction gate without sending or removing reactions. */
declare function shouldAckReaction(params: AckReactionGateParams): boolean;
/** Starts sending an ack reaction and returns the success-tracking cleanup handle. */
declare function createAckReactionHandle(params: {
  ackReactionValue: string;
  send: () => Promise<void>;
  remove: () => Promise<void>;
  onSendError?: (err: unknown) => void;
}): AckReactionHandle | null;
/** Schedules removal of a previously sent ack reaction after reply delivery. */
declare function removeAckReactionAfterReply(params: {
  removeAfterReply: boolean;
  ackReactionPromise: Promise<boolean> | null;
  ackReactionValue: string | null;
  remove: () => Promise<void>;
  onError?: (err: unknown) => void;
}): void;
/** Convenience wrapper that removes an ack reaction handle after reply delivery. */
declare function removeAckReactionHandleAfterReply(params: {
  removeAfterReply: boolean;
  ackReaction: AckReactionHandle | null | undefined;
  onError?: (err: unknown) => void;
}): void;
//#endregion
//#region src/config/channel-groups.d.ts
type ChannelGroupConfig = {
  requireMention?: boolean;
  requireMentionInBotThreads?: boolean;
  ingest?: boolean;
  tools?: GroupToolPolicyConfig;
  toolsBySender?: GroupToolPolicyBySenderConfig;
};
//#endregion
//#region src/config/group-policy.d.ts
type ChannelGroupPolicy = {
  allowlistEnabled: boolean;
  allowed: boolean;
  groupConfig?: ChannelGroupConfig;
  defaultConfig?: ChannelGroupConfig;
};
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;
//#endregion
//#region src/auto-reply/inbound-debounce.d.ts
/** Resolve effective inbound debounce milliseconds from explicit, channel, and global config. */
declare function resolveInboundDebounceMs(params: {
  cfg: OpenClawConfig;
  channel: string;
  overrideMs?: number;
}): number;
/** A flush releases its debounce lane at admission while completion remains drainable. */
type InboundDebounceFlush = {
  admission: Promise<void>;
  completion: Promise<void>;
};
type InboundDebounceAdmissionLifecycleInput = {
  abortSignal?: AbortSignal;
  onAdopted?: () => void | Promise<void>;
  onDeferred?: () => boolean | void;
  onDeferredHeartbeat?: () => void;
  deferredHeartbeatIntervalMs?: number;
  onAdoptionFinalizing?: () => void;
  onFailed?: (error: unknown) => void | Promise<void>;
  onAbandoned?: () => void | Promise<void>;
};
/** Lifecycle shape passed to a channel dispatch so it can signal session-lane admission. */
type InboundDebounceAdmissionLifecycle = {
  abortSignal: AbortSignal;
  onAdopted: () => Promise<void>;
  onDeferred: () => boolean | void;
  onDeferredHeartbeat?: () => void;
  deferredHeartbeatIntervalMs?: number;
  onAdoptionFinalizing: () => void;
  onFailed?: (error: unknown) => Promise<void>;
  onAbandoned: () => Promise<void>;
};
/**
 * Start one flush and bind its admission signal to the turn lifecycle.
 * Completion also releases admission for gated work that never enters a session lane.
 */
declare function createInboundDebounceFlush(params: {
  lifecycle?: InboundDebounceAdmissionLifecycleInput;
  dispatch: (lifecycle: InboundDebounceAdmissionLifecycle) => Promise<void>;
}): InboundDebounceFlush;
/** Options for creating a keyed inbound debouncer. */
type InboundDebounceCreateParams<T> = {
  debounceMs: number;
  maxTrackedKeys?: number;
  maxWaitMs?: number | ((item: T) => number | undefined);
  buildKey: (item: T) => string | null | undefined;
  shouldDebounce?: (item: T) => boolean;
  resolveDebounceMs?: (item: T, pending?: readonly T[]) => number | undefined;
  canAppend?: (item: T, pending: readonly T[]) => boolean;
  serializeImmediate?: boolean;
  onFlush: (items: T[], createFlush: typeof createInboundDebounceFlush) => InboundDebounceFlush;
  onError?: (err: unknown, items: T[]) => void;
  onCancel?: (items: T[]) => void;
};
/** Create a keyed debouncer with flush/cancel controls and same-key serialization. */
declare function createInboundDebouncer<T>(params: InboundDebounceCreateParams<T>): {
  enqueue: (item: T) => Promise<void>;
  shouldBuffer: (item: T) => boolean;
  flushKey: (key: string) => Promise<void>;
  cancelKey: (key: string) => boolean;
  drain: () => Promise<void>;
};
//#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;
//#endregion
//#region src/channels/message-access/runtime.d.ts
/** Evaluate policy without admitting a host participant. */
declare function createChannelIngressPolicyResolver(base: CreateChannelIngressResolverParams): ChannelIngressResolver;
/**
 * Resolve one inbound event using a simple stable subject identity descriptor.
 */
declare function resolveStableChannelIngressPolicy(params: ResolveStableChannelMessageIngressParams): Promise<ResolvedChannelMessageIngress>;
/**
 * Resolve sender, route, command, event, and activation gates for one inbound
 * channel event.
 */
declare function resolveChannelIngressPolicy(params: ResolveChannelMessageIngressParams): Promise<ResolvedChannelMessageIngress>;
//#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;
};
/**
 * Reply option subset consumed by channel reply dispatchers.
 */
type ReplyPrefixOptions = Pick<ReplyPrefixContextBundle, "responsePrefix" | "responsePrefixContextProvider" | "onModelSelected">;
/**
 * Creates response-prefix options and a live context provider for the selected model.
 */
declare function createReplyPrefixContext(params: {
  cfg: OpenClawConfig;
  agentId: string;
  channel?: string;
  accountId?: string;
}): ReplyPrefixContextBundle;
/**
 * Creates the reply-prefix options object expected by `getReply` call sites.
 */
declare function createReplyPrefixOptions(params: Parameters<typeof createReplyPrefixContext>[0]): ReplyPrefixOptions;
//#endregion
//#region src/channels/message/reply-pipeline.d.ts
/** Parameters for building a channel reply pipeline with prefix, typing, and payload transforms. */
type CreateChannelReplyPipelineParams = {
  /** Full config used for reply prefix and channel plugin transform resolution. */
  cfg: Parameters<typeof createReplyPrefixOptions>[0]["cfg"];
  /** Agent id used in reply prefix context. */
  agentId: string;
  /** Optional channel id for prefix context and plugin transform lookup. */
  channel?: string;
  /** Optional channel account id for prefix context and plugin transform lookup. */
  accountId?: string;
  /** Typing callback factory input. */
  typing?: CreateTypingCallbacksParams;
  /** Prebuilt typing callbacks that take precedence over `typing`. */
  typingCallbacks?: TypingCallbacks;
  /** Explicit payload transform; avoids channel plugin lookup when provided. */
  transformReplyPayload?: (payload: ReplyPayload) => ReplyPayload | null;
};
//#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;
};
//#endregion
//#region src/channels/turn/bot-loop-protection.d.ts
/** Facts used to detect repeated bot-to-bot channel reply loops. */
type ChannelBotLoopProtectionFacts = {
  scopeId: string;
  conversationId: string;
  senderId: string;
  receiverId: string;
  eventId?: string;
  config?: PairLoopGuardConfig;
  defaultsConfig?: PairLoopGuardConfig;
  defaultEnabled: boolean;
  nowMs?: number;
};
//#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;
};
/** Durable delivery queue intent recorded when a reply is deferred. */
type ChannelDeliveryIntent = {
  id: string;
  kind: "outbound_queue";
  queuePolicy: OutboundDeliveryQueuePolicy;
};
/** Result returned after delivering one channel reply payload. */
type ChannelDeliveryResult = 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
/** Admission decision for an inbound channel event before agent dispatch. */
type ChannelTurnAdmission = {
  kind: "dispatch";
  reason?: string;
} | {
  kind: "observeOnly";
  reason: string;
} | {
  kind: "handled";
  reason: string;
} | {
  kind: "drop";
  reason: string;
  recordHistory?: boolean;
};
/** Coarse event classification used to decide whether an event can start an agent turn. */
type ChannelEventClass = {
  kind: "message" | "command" | "interaction" | "reaction" | "lifecycle" | "unknown";
  canStartAgentTurn: boolean;
  requiresImmediateAck?: boolean;
};
/** Normalized inbound event text and raw payload after channel-specific ingestion. */
type NormalizedTurnInput = {
  id: string;
  timestamp?: number;
  rawText: string;
  textForAgent?: string;
  textForCommands?: string;
  raw?: unknown;
};
/** Sender identity facts projected into channel access, routing, and prompt context. */
type SenderFacts = {
  id?: string;
  name?: string;
  username?: string;
  tag?: string;
  roles?: string[];
  isBot?: boolean;
  isSelf?: boolean;
  displayLabel?: string;
};
/** Conversation identity and threading facts for a channel turn. */
type ConversationFacts = {
  kind: "direct" | "group" | "channel";
  id: string;
  label?: string;
  spaceId?: string;
  parentId?: string;
  threadId?: string;
  nativeChannelId?: string;
  avatar?: string;
  routePeer?: {
    kind: "direct" | "group" | "channel";
    id: string;
  };
};
/** Session routing facts derived before dispatch. */
type RouteFacts = {
  agentId: string;
  dmScope?: DmScope;
  accountId?: string;
  routeSessionKey: string;
  dispatchSessionKey?: string;
  persistedSessionKey?: string;
  parentSessionKey?: string;
  modelParentSessionKey?: string;
  mainSessionKey?: string;
  createIfMissing?: boolean;
};
/** Reply target and source-delivery facts for a channel turn. */
type ReplyPlanFacts = {
  to: string;
  originatingTo?: string;
  nativeChannelId?: string;
  replyTarget?: string;
  deliveryTarget?: string;
  replyToId?: string;
  replyToIdFull?: string;
  messageThreadId?: string | number;
  threadParentId?: string;
  sourceReplyDeliveryMode?: "thread" | "reply" | "channel" | "direct" | "none";
};
/** Message text/history facts passed into templating and dispatch. */
type MessageFacts = {
  inboundEventKind?: InboundEventKind;
  body?: string;
  rawBody: string;
  bodyForAgent?: string;
  commandBody?: string;
  envelopeFrom?: string;
  senderLabel?: string;
  preview?: string;
  inboundHistory?: HistoryEntry[];
  sourceModality?: InboundSourceModality;
};
/** Parsed command facts for command-like channel turns. */
type CommandFacts = {
  kind: CommandTurnKind;
  body?: string;
  name?: string;
  authorized?: boolean;
};
/** Inbound media facts supplied to the agent context. */
type InboundMediaFacts = Omit<MediaFact, "staged" | "workspaceDir">;
type MaybePromise$1<T> = T | Promise<T>;
/** Adapter preflight output assembled before turn resolution. */
type PreflightFacts = {
  admission?: ChannelTurnAdmission;
  command?: CommandFacts;
  message?: Partial<MessageFacts>;
  media?: readonly InboundMediaFacts[] | (() => MaybePromise$1<readonly InboundMediaFacts[] | readonly HistoryMediaEntry[] | null | undefined>);
  supplemental?: SupplementalContextFacts;
  history?: ChannelTurnDroppedHistoryOptions;
};
/** Delivery metadata for one reply payload dispatch. */
type ChannelDeliveryInfo = ReplyDispatchRuntimeInfo;
type ChannelCoreManagedDeliveryInfo = Omit<ChannelDeliveryInfo, "assertPlatformSendAuthorized" | "bindPendingFinalDelivery" | "onPlatformSendDispatch">;
type ChannelProviderOwnedDeliveryInfo = ChannelDeliveryInfo & {
  assertPlatformSendAuthorized: () => void;
  onPlatformSendDispatch: () => Promise<void>;
};
/** Durable outbound delivery options available to channel turn delivery adapters. */
type ChannelTurnDurableDeliveryOptions = Pick<DeliverOutboundPayloadsParams, "deps" | "formatting" | "identity" | "mediaAccess" | "replyToMode" | "silent" | "threadId"> & {
  to?: string | null;
  replyToId?: string | null;
  requiredCapabilities?: DurableFinalDeliveryRequirements;
};
type ChannelDeliveryAdapterBase = {
  /** Return null when channel policy intentionally suppresses this logical payload. */
  preparePayload?: (payload: ReplyPayload, info: ChannelDeliveryInfo) => MaybePromise$1<ReplyPayload | null>;
  onDelivered?: (payload: ReplyPayload, 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, 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, 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, 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;
/** Options for recording inbound session route state around a turn. */
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;
};
/** Options for finalizing visible conversation history after dispatch. */
type ChannelTurnHistoryFinalizeOptions = {
  isGroup?: boolean;
  historyKey?: string;
  historyMap?: Map<string, HistoryEntry[]>;
  limit?: number;
};
/** Options for recording history when an inbound event is dropped before dispatch. */
type ChannelTurnDroppedHistoryOptions = {
  key: string;
  limit: number;
  historyMap: Map<string, HistoryEntry[]>;
  recordOnDrop?: boolean;
  mediaLimit?: number;
  shouldRecord?: () => boolean;
};
/** Dispatcher options excluding delivery hooks owned by the channel turn adapter. */
type ChannelTurnDispatcherOptions = Omit<ReplyDispatcherWithTypingOptions, "deliver" | "deliverPrepared" | "onError">;
/** Reply options plus the opaque native command ownership decision carried by channel turns. */
type ChannelTurnReplyOptions = Omit<GetReplyOptions, "onBlockReply" | "onPreparedBlockReply"> & PluginCommandReplyOptions;
/** Reply pipeline options excluding cfg/agent/channel identity supplied by the turn. */
type ChannelTurnReplyPipelineOptions = Omit<CreateChannelReplyPipelineParams, "cfg" | "agentId" | "channel" | "accountId">;
type ChannelTurnContext = {
  channel: string;
  accountId?: string;
  routeSessionKey: string;
  storePath: string;
  ctxPayload: FinalizedMsgContext;
  recordInboundSession: RecordInboundSession$1;
  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;
};
/** Fully assembled channel turn ready to build the dispatch runner. */
type AssembledChannelTurn = ChannelTurnContext & {
  cfg: OpenClawConfig;
  agentId: string;
  dispatchReplyWithBufferedBlockDispatcher: DispatchReplyWithBufferedBlockDispatcher$1;
  delivery: ChannelEventDeliveryAdapter;
  replyPipeline?: ChannelTurnReplyPipelineOptions;
  dispatcherOptions?: ChannelTurnDispatcherOptions;
  toolsAllow?: string[];
  replyOptions?: ChannelTurnReplyOptions;
  replyResolver?: GetReplyFromConfig;
  /** Instance-bound reply dispatcher supplied by the owning plugin runtime. */
  dispatchReplyFromConfig?: DispatchReplyFromConfig;
  sessionInitRetry?: {
    delaysMs: readonly number[];
    signal?: AbortSignal;
    sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
  };
  /** Canonical adoption lifecycle threaded into replyOptions. */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
};
type PreparedChannelTurnDispatchSkipReason = "botLoopProtection" | "observeOnly" | "outboundEcho";
/** Lifecycle ownership declared alongside an already-prepared dispatch runner. */
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: PreparedChannelTurnDispatchSkipReason) => void | Promise<void>;
};
/** Channel turn with dispatch runner already prepared. */
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 ChannelTurnRoute = {
  agentId: string;
  dmScope?: DmScope;
  sessionKey: string;
};
type RoutedChannelTurn<T> = Omit<T, "routeSessionKey" | "storePath" | "recordInboundSession"> & {
  route: ChannelTurnRoute;
};
type InboundPreparedChannelTurn<TDispatchResult = DispatchFromConfigResult> = PreparedChannelTurn<TDispatchResult> & {
  runDispatchLifecycle: PreparedChannelTurnDispatchLifecycle;
};
type ChannelTurnPlan<TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = RoutedChannelTurn<Omit<AssembledChannelTurn, "agentId" | "delivery" | "dispatchReplyWithBufferedBlockDispatcher"> & {
  delivery: TDelivery;
}>;
type PreparedChannelTurnPlan<TDispatchResult = DispatchFromConfigResult> = RoutedChannelTurn<InboundPreparedChannelTurn<TDispatchResult>> & {
  cfg: OpenClawConfig;
};
/** Resolved turn shape returned by adapters before final run/dispatch handling. */
type ChannelTurnResolved<TDispatchResult = DispatchFromConfigResult, TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = ChannelTurnPlan<TDelivery> | PreparedChannelTurnPlan<TDispatchResult> | AssembledChannelTurn | InboundPreparedChannelTurn<TDispatchResult>;
/** Ordered lifecycle stage names emitted to channel turn log hooks. */
type ChannelTurnStage = "ingest" | "classify" | "preflight" | "resolve" | "authorize" | "assemble" | "record" | "dispatch" | "finalize";
/** Structured channel turn log event. */
type ChannelTurnLogEvent = {
  stage: ChannelTurnStage;
  event: "start" | "done" | "drop" | "handled" | "error" | "warning";
  channel: string;
  accountId?: string;
  messageId?: string;
  sessionKey?: string;
  admission?: ChannelTurnAdmission["kind"];
  reason?: string;
  error?: unknown;
};
/** Final result for a channel turn, dispatched or admitted without dispatch. */
type ChannelTurnResult<TDispatchResult = DispatchFromConfigResult> = DispatchedChannelTurnResult<TDispatchResult> | {
  admission: ChannelTurnAdmission;
  dispatched: false;
  ctxPayload?: MsgContext;
  routeSessionKey?: string;
};
/** Successful dispatch result for a channel turn. */
type DispatchedChannelTurnResult<TDispatchResult = DispatchFromConfigResult> = {
  admission: Extract<ChannelTurnAdmission, {
    kind: "dispatch" | "observeOnly";
  }>;
  dispatched: true;
  ctxPayload: MsgContext;
  routeSessionKey: string;
  dispatchResult: TDispatchResult;
};
/** Adapter contract for ingesting, classifying, resolving, and finalizing raw channel events. */
type ChannelTurnAdapter<TRaw, TDispatchResult = DispatchFromConfigResult, TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = {
  ingest: (raw: TRaw) => MaybePromise$1<NormalizedTurnInput | null>;
  classify?: (input: NormalizedTurnInput) => MaybePromise$1<ChannelEventClass>;
  preflight?: (input: NormalizedTurnInput, eventClass: ChannelEventClass) => MaybePromise$1<PreflightFacts | ChannelTurnAdmission | null | undefined>;
  resolveTurn: (input: NormalizedTurnInput, eventClass: ChannelEventClass, preflight: PreflightFacts) => MaybePromise$1<ChannelTurnResolved<TDispatchResult, TDelivery>>;
  onFinalize?: (result: ChannelTurnResult<TDispatchResult>) => Promise<void> | void;
};
/** Parameters for running one raw channel event through the turn kernel. */
type RunChannelTurnParams<TRaw, TDispatchResult = DispatchFromConfigResult, TDelivery extends ChannelTurnDeliveryAdapter = ChannelCoreManagedTurnDeliveryAdapter> = {
  channel: string;
  accountId?: string;
  raw: TRaw;
  adapter: ChannelTurnAdapter<TRaw, TDispatchResult, TDelivery>;
  log?: (event: ChannelTurnLogEvent) => void;
  /** Canonical adoption lifecycle for this turn. */
  turnAdoptionLifecycle?: TurnAdoptionLifecycle;
};
//#endregion
//#region src/channels/inbound-event/context.d.ts
type MaybePromise<T> = T | Promise<T>;
type ChannelInboundSupplementalMediaResolver = () => MaybePromise<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">;
  /** Channel-configured policy resolved at the trusted ingress boundary. */
  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;
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 runChannelTurn<TRaw, TDispatchResult = DispatchedChannelTurnResult["dispatchResult"]>(params: RunChannelTurnParams<TRaw, TDispatchResult, ChannelProviderOwnedMessageSendingDeliveryAdapter>): Promise<ChannelTurnResult<TDispatchResult>>;
declare function runChannelTurn<TRaw, TDispatchResult = DispatchedChannelTurnResult["dispatchResult"]>(params: RunChannelTurnParams<TRaw, TDispatchResult>): Promise<ChannelTurnResult<TDispatchResult>>;
//#endregion
//#region src/channels/turn/execution.d.ts
declare function runPreparedChannelTurn<TDispatchResult = DispatchedChannelTurnResult["dispatchResult"]>(params: PreparedChannelTurn<TDispatchResult>): Promise<ChannelTurnResult<TDispatchResult>>;
//#endregion
//#region src/channels/turn/lifecycle.d.ts
declare function dispatchAssembledChannelTurn(params: AssembledChannelTurn): Promise<ChannelTurnResult>;
declare function dispatchRoutedChannelTurn(params: ChannelTurnPlan<ChannelTurnDeliveryAdapter>): Promise<ChannelTurnResult>;
declare function dispatchRoutedChannelTurn(params: ChannelTurnPlan<ChannelProviderOwnedMessageSendingDeliveryAdapter>): Promise<ChannelTurnResult>;
declare function dispatchRoutedChannelTurn(params: ChannelTurnPlan): Promise<ChannelTurnResult>;
//#endregion
//#region src/auto-reply/command-detection.runtime-types.d.ts
/** Runtime-injected predicate for deciding whether visible text is an OpenClaw command. */
type IsControlCommandMessage = typeof isControlCommandMessage;
/** Runtime-injected predicate for deciding whether command authorization must be computed. */
type ShouldComputeCommandAuthorized = typeof shouldComputeCommandAuthorized;
//#endregion
//#region src/auto-reply/commands-text-routing.d.ts
/** Decides whether text slash commands remain active for the current surface/config pair. */
declare function shouldHandleTextCommands(params: ShouldHandleTextCommandsParams): boolean;
//#endregion
//#region src/auto-reply/commands-registry.runtime-types.d.ts
/** Runtime-injected policy hook for whether text slash commands should be honored. */
type ShouldHandleTextCommands = typeof shouldHandleTextCommands;
//#endregion
//#region src/channels/mention-pattern-policy.d.ts
/**
 * Inputs for resolving whether mention-pattern matching is enabled in a conversation.
 */
type ResolveMentionPatternPolicyParams = {
  cfg?: OpenClawConfig;
  provider?: string;
  conversationId?: string | null;
  providerPolicy?: MentionPatternsPolicyConfig;
  agentId?: string;
};
//#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/reply-dispatcher.runtime-types.d.ts
/** Type of the lazy reply dispatcher factory used by runtime dispatch paths. */
type CreateReplyDispatcherWithTyping = typeof createReplyDispatcherWithTyping;
//#endregion
//#region src/channels/plugins/outbound/load.d.ts
declare const loadChannelOutboundAdapter: (id: ChannelId$1) => Promise<ChannelOutboundAdapter | undefined>;
//#endregion
//#region src/channels/plugins/outbound/load.types.d.ts
type LoadChannelOutboundAdapter = typeof loadChannelOutboundAdapter;
//#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$1;
//#endregion
//#region src/plugins/runtime/types-channel.d.ts
type DispatchReplyWithBufferedBlockDispatcher = DispatchReplyWithBufferedBlockDispatcher$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: 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;
  };
  activity: {
    record: typeof recordChannelActivity;
    get: typeof getChannelActivity;
  };
  session: {
    /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */
    resolveStorePath: typeof resolveSessionStorePathCore;
    readSessionUpdatedAt: ReadSessionUpdatedAt;
    recordSessionMetaFromInbound: RecordSessionMetaFromInbound;
    /** @deprecated Prefer channel turn helpers that record inbound sessions as part of dispatch. */
    recordInboundSession: RecordInboundSession;
    updateLastRoute: UpdateLastRoute;
  };
  mentions: {
    buildMentionRegexes: BuildMentionRegexes;
    matchesMentionPatterns: MatchesMentionPatterns;
    matchesMentionWithExplicit: MatchesMentionWithExplicit;
    implicitMentionKindWhen: typeof implicitMentionKindWhen;
    resolveInboundMentionDecision: typeof resolveInboundMentionDecision;
  };
  reactions: {
    createAckReactionHandle: typeof createAckReactionHandle;
    shouldAckReaction: typeof shouldAckReaction;
    removeAckReactionAfterReply: typeof removeAckReactionAfterReply;
    removeAckReactionHandleAfterReply: typeof removeAckReactionHandleAfterReply;
  };
  groups: {
    resolveGroupPolicy: typeof resolveChannelGroupPolicy;
    resolveRequireMention: typeof resolveChannelGroupRequireMention;
  };
  debounce: {
    createInboundDebouncer: typeof createInboundDebouncer;
    resolveInboundDebounceMs: typeof resolveInboundDebounceMs;
  };
  commands: {
    resolveCommandAuthorizedFromAuthorizers: typeof resolveCommandAuthorizedFromAuthorizers;
    isControlCommandMessage: IsControlCommandMessage;
    shouldComputeCommandAuthorized: ShouldComputeCommandAuthorized;
    shouldHandleTextCommands: ShouldHandleTextCommands;
  };
  outbound: {
    loadAdapter: LoadChannelOutboundAdapter;
  };
  inbound: {
    /** 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 runChannelTurn;
    /** @deprecated Prefer `run` for raw inbound events or `dispatchReply` for assembled contexts. */
    runPreparedReply: typeof runPreparedChannelTurn;
    dispatch: typeof dispatchRoutedChannelTurn;
    /** Compatibility escape hatch; prefer `dispatch`, which keeps session wiring in core. */
    dispatchReply: typeof dispatchAssembledChannelTurn;
  };
  /** @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. Retained through the next Plugin SDK major. */
    setIdleTimeoutBySessionKey: (params: {
      channelId: string;
      targetSessionKey: string;
      accountId?: string;
      idleTimeoutMs: number;
    }) => RuntimeThreadBindingLifecycleRecord[];
    /** @deprecated Use setMaxAgeBySessionKeyAsync. Retained through the next Plugin SDK major. */
    setMaxAgeBySessionKey: (params: {
      channelId: string;
      targetSessionKey: string;
      accountId?: string;
      maxAgeMs: number;
    }) => RuntimeThreadBindingLifecycleRecord[];
  };
  runtimeContexts: ChannelRuntimeContextRegistry;
};
//#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/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;
  /** Requested Gateway scopes. Honored only for bundled or trusted official plugins. */
  scopes?: OperatorScope[];
};
/** 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>;
  };
  subagent: {
    /** Fresh, tool-free background inference under the existing subagent model policy. */
    complete: (params: SubagentCompleteParams) => Promise<{
      text: string;
    }>;
    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;
      confinedToolNames?: readonly string[];
      requiredToolNames?: readonly string[];
      modelProvider?: string;
      modelId?: string;
      sessionKey: string;
    }) => {
      sandboxed: boolean;
      workspaceAccess: "none" | "ro" | "rw";
      confinementError?: string;
    };
    prepareWorkspaceAuthority: (params: {
      config: OpenClawConfig;
      agentId?: string;
      confinedToolNames?: readonly string[];
      requiredToolNames?: readonly string[];
      modelProvider?: string;
      modelId?: string;
      sessionKey: string;
      workspaceDir: string;
    }) => Promise<{
      sandboxed: boolean;
      workspaceAccess: "none" | "ro" | "rw";
      confinementError?: string;
    }>;
  };
  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/providers.runtime.d.ts
declare const { isPluginProvidersLoadInFlight, resolvePluginProviderRegistryCore, resolvePluginProvidersCore }: Readonly<{
  isPluginProvidersLoadInFlight: (params: Parameters<(params: Parameters<(params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  }) => ReturnType<(registry: PluginRegistry, base: ReturnType<(params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  } & {
    env: NodeJS.ProcessEnv;
  }, manifestRegistry?: PluginLoadOptions["manifestRegistry"], declaredProviderOwners?: DeclaredProviderOwnerIndex, retained?: boolean) => {
    pluginIds: string[] | undefined;
    workspaceDir: string | undefined;
    manifestRegistry: PluginManifestRegistry | undefined;
    onlyPluginIds: string[] | undefined;
    providerRefs: readonly string[] | undefined;
    projectedPluginIds: string[] | undefined;
    declaredProviderOwners: DeclaredProviderOwnerIndex;
    providerOwners: {
      provider: string;
      ownerPluginIds: string[];
      providerPluginIds: string[];
      runtimePluginIds: string[];
    }[];
    providerRegistrationPluginIds: Set<string> | undefined;
    runtimeRegistrationPluginIds: Set<string> | undefined;
    unownedProviderRefs: readonly string[];
    explicitOwnerPluginIds: string[];
  }>, onlyPluginIds?: readonly string[]) => {
    registry: PluginRegistry;
    workspaceDir: string | undefined;
    onlyPluginIds: readonly string[] | undefined;
    isProviderOwnerEligible: (pluginId: string, provider: string) => boolean;
  }> | undefined>[0], onSelectedRegistry?: (registry: PluginRegistry) => ((provider: ProviderPlugin, pluginId: string) => ProviderPlugin) | undefined) => ProviderPlugin[]>[0]) => boolean;
  resolvePluginProviderRegistryCore: (params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  }) => ReturnType<(registry: PluginRegistry, base: ReturnType<(params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  } & {
    env: NodeJS.ProcessEnv;
  }, manifestRegistry?: PluginLoadOptions["manifestRegistry"], declaredProviderOwners?: DeclaredProviderOwnerIndex, retained?: boolean) => {
    pluginIds: string[] | undefined;
    workspaceDir: string | undefined;
    manifestRegistry: PluginManifestRegistry | undefined;
    onlyPluginIds: string[] | undefined;
    providerRefs: readonly string[] | undefined;
    projectedPluginIds: string[] | undefined;
    declaredProviderOwners: DeclaredProviderOwnerIndex;
    providerOwners: {
      provider: string;
      ownerPluginIds: string[];
      providerPluginIds: string[];
      runtimePluginIds: string[];
    }[];
    providerRegistrationPluginIds: Set<string> | undefined;
    runtimeRegistrationPluginIds: Set<string> | undefined;
    unownedProviderRefs: readonly string[];
    explicitOwnerPluginIds: string[];
  }>, onlyPluginIds?: readonly string[]) => {
    registry: PluginRegistry;
    workspaceDir: string | undefined;
    onlyPluginIds: readonly string[] | undefined;
    isProviderOwnerEligible: (pluginId: string, provider: string) => boolean;
  }> | undefined;
  resolvePluginProvidersCore: (params: Parameters<(params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  }) => ReturnType<(registry: PluginRegistry, base: ReturnType<(params: {
    config?: PluginLoadOptions["config"];
    workspaceDir?: string;
    env?: PluginLoadOptions["env"];
    bundledProviderVitestCompat?: boolean;
    onlyPluginIds?: string[];
    providerRefs?: readonly string[];
    modelRefs?: readonly string[];
    activate?: boolean;
    cache?: boolean;
    applyAutoEnable?: boolean;
    pluginSdkResolution?: PluginLoadOptions["pluginSdkResolution"];
    mode?: "runtime" | "setup";
    includeUntrustedWorkspacePlugins?: boolean;
    pluginMetadataSnapshot?: PluginMetadataRegistryView;
    skipIfLoadInFlight?: boolean;
    registryScope?: "exact" | "loaded";
  } & {
    env: NodeJS.ProcessEnv;
  }, manifestRegistry?: PluginLoadOptions["manifestRegistry"], declaredProviderOwners?: DeclaredProviderOwnerIndex, retained?: boolean) => {
    pluginIds: string[] | undefined;
    workspaceDir: string | undefined;
    manifestRegistry: PluginManifestRegistry | undefined;
    onlyPluginIds: string[] | undefined;
    providerRefs: readonly string[] | undefined;
    projectedPluginIds: string[] | undefined;
    declaredProviderOwners: DeclaredProviderOwnerIndex;
    providerOwners: {
      provider: string;
      ownerPluginIds: string[];
      providerPluginIds: string[];
      runtimePluginIds: string[];
    }[];
    providerRegistrationPluginIds: Set<string> | undefined;
    runtimeRegistrationPluginIds: Set<string> | undefined;
    unownedProviderRefs: readonly string[];
    explicitOwnerPluginIds: string[];
  }>, onlyPluginIds?: readonly string[]) => {
    registry: PluginRegistry;
    workspaceDir: string | undefined;
    onlyPluginIds: readonly string[] | undefined;
    isProviderOwnerEligible: (pluginId: string, provider: string) => boolean;
  }> | undefined>[0], onSelectedRegistry?: (registry: PluginRegistry) => ((provider: ProviderPlugin, pluginId: string) => ProviderPlugin) | undefined) => ProviderPlugin[];
}>;
//#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/agents/agent-tools.read.d.ts
type SkillInstructionDeliveryCache = Map<string, Promise<boolean>>;
//#endregion
//#region src/agents/delegation-capability.d.ts
type DelegationCapability = "full" | "report_only";
//#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 = {
  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;
  sessionPermissionPolicy?: PreparedSessionPermissionPolicy;
  inheritedToolAllowlist?: string[];
  inheritedToolDenylist?: string[];
};
//#endregion
//#region src/agents/tools/question-prompt-send.d.ts
/** Publishes one prompt into the originating conversation. */
type QuestionPromptSend = (payload: ReplyPayload, 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/openclaw-tools.types.d.ts
/** Options shared by the coding-tool factory and its OpenClaw tool surface. */
type OpenClawSharedToolsOptions = {
  /**
   * 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;
  /** 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;
  /** Internal review-run restrictions and proposal provenance. */
  skillWorkshop?: SkillWorkshopRunOptions;
  webFetchHostnameAllowlistRef?: {
    value?: string[];
  };
  webSearchEnabled?: boolean;
  /** 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[];
  /** Host-prepared proof that this exact session can request Gateway publication. */
  githubPublicationAvailable?: boolean;
  cronCreatorAuthorityUnavailableReason?: CronToolOptions["creatorAuthorityUnavailableReason"];
  /** Mutable model-context generation used to expire screenshot coordinate frames. */
  computerContextEpoch?: {
    value: number;
  };
  /** Registers run-owned cleanup for tools that hold node resources. */
  registerRunCleanup?: (cleanup: (reason: string) => Promise<void>) => void;
  inboundEventKind?: InboundEventKind;
  /** If true, omit the message tool from the tool list. */
  disableMessageTool?: boolean;
  swarmCollector?: boolean;
  swarmOutputSchema?: Record<string, unknown>;
  /** If true, include the heartbeat response tool for structured heartbeat outcomes. */
  enableHeartbeatTool?: boolean;
  /** Host-only observation after a canonical progress-card replacement commits. */
  onProgressCardPlanSaved?: (unfinished: boolean) => void;
  onYield?: (message: string, acknowledgment?: string) => Promise<void> | void;
  claimYieldCompletion?: () => boolean | Promise<boolean>;
  /** Records hot-path tool-prep stages for reply startup diagnostics. */
  recordToolPrepStage?: (name: string) => void;
};
//#endregion
//#region src/agents/code-mode-skills.d.ts
type CodeModeSkill = {
  name: string;
  description: string;
  location: string;
  source: Pick<Skill, "filePath" | "readContent">;
  reader?: CodeModeSkillReader;
};
type CodeModeSkillReader = (params: {
  location: string;
  signal?: AbortSignal;
}) => Promise<string>;
//#endregion
//#region src/agents/tool-search-types.d.ts
type CatalogSource = "openclaw" | "mcp" | "client";
type CatalogTool = AnyAgentTool | ToolDefinition;
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 = {
  config?: OpenClawConfig;
  runtimeConfig?: OpenClawConfig;
  agentId?: string;
  sessionKey?: string;
  sessionId?: string;
  runId?: string;
  catalogRef?: ToolSearchCatalogRef;
  abortSignal?: AbortSignal;
  executeTool?: ToolSearchCatalogToolExecutor;
  forceRestartSafeTools?: boolean;
  /** Set when the run executes only these tools; swarm globals gate on `sessions_spawn`. */
  toolExecutionAllow?: readonly string[];
  codeModeSkills?: readonly CodeModeSkill[];
};
/** 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;
  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;
  onChange?: () => void;
  disposeObserver?: () => void;
  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;
  agentDir?: string;
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  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;
  /**
   * Provider of the currently selected model (used for provider-specific tool quirks).
   * Example: "anthropic", "openai", "google", "openai".
   */
  modelProvider?: string;
  /** Model id for the current provider (used for model-specific tool gating). */
  modelId?: string;
  /** 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;
  /** Model context window in tokens (used to scale read-tool output budget). */
  modelContextWindowTokens?: number;
  /** 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;
  /** If true, the model has native vision capability */
  modelHasVision?: boolean;
  /** 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;
  /** Keep the heartbeat response tool available even when the selected profile omits it. */
  forceHeartbeatTool?: 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;
  /** Auth profiles already loaded for this run; used for prompt-time tool availability. */
  authProfileStore?: AuthProfileStore;
  /** 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;
  /** Runtime-only resolved skill paths that the read tool may load under workspaceOnly. */
  skillsSnapshot?: SkillSnapshot;
  /** 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;
  /** Trusted server-stamped authority for an explicitly capped scheduled run. */
  scheduledToolPolicy?: ScheduledToolPolicyContext;
} & OpenClawSharedToolsOptions & AgentRunClientContext & AgentRunMessageContext & AgentRunChannelContext;
//#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;
};
/** One named policy layer in the effective runtime tool policy pipeline. */
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/tool-loop-detection-config.d.ts
/** Resolves effective tool loop-detection config by overlaying agent settings on globals. */
declare function resolveToolLoopDetectionConfig(params: {
  cfg?: OpenClawConfig;
  agentId?: string;
}): ToolLoopDetectionConfig | undefined;
declare namespace agent_tools_d_exports {
  export { createOpenClawCodingTools, createOpenClawCodingToolsInternal, resolveToolLoopDetectionConfig };
}
/** Internal preparation data stays outside the public harness factory options. */
declare function createOpenClawCodingToolsInternal(options?: OpenClawCodingToolsOptions, skillReadResources?: SkillSnapshot["resolvedSkills"], onPolicyFilter?: (event: ToolPolicyFilterEvent) => void): AnyAgentTool[];
/** Build the SDK tool list without exposing core-only read scope or completion observations. */
declare function createOpenClawCodingTools(options?: Omit<OpenClawCodingToolsOptions, "sessionReadScopeKey" | "onProgressCardPlanSaved">): AnyAgentTool[];
//#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-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;
  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-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/embedded-agent-subscribe.types.d.ts
type ReasoningStreamPayload = Pick<ReplyPayload, "text" | "mediaUrls" | "isReasoning" | "isReasoningSnapshot"> & {
  requiresReasoningProgressOptIn?: boolean;
};
type SubscribeEmbeddedAgentSessionParams = {
  session: AgentSession;
  runId: string;
  /** Immutable gateway lifecycle ownership for this execution. */
  lifecycleGeneration?: string;
  /** Originating message channel used for subsystem log attribution. */
  messageChannel?: string;
  initialReplayState?: EmbeddedRunReplayState;
  assistantErrorTranscript?: EmbeddedRunAttemptParams["assistantErrorTranscript"];
  hookRunner?: HookRunner;
  verboseLevel?: VerboseLevel;
  reasoningMode?: ReasoningLevel;
  thinkingLevel?: ThinkLevel;
  toolResultFormat?: ToolResultFormat;
  toolProgressDetail?: ToolProgressDetailMode;
  shouldEmitToolResult?: () => boolean;
  shouldEmitToolOutput?: () => boolean;
  sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
  /** Attempt-owned delivery proof for message-tool-only source replies. */
  hasDeliveredMessageToolOnlySourceReply?: () => boolean;
  /** Reports source delivery observed through bridged tool lifecycle events. */
  onDeliveredMessageToolOnlySourceReply?: () => void;
  onToolResult?: (payload: ReplyPayload) => void | Promise<void>;
  onAgentToolResult?: (event: {
    toolName: string;
    result: unknown;
    isError: boolean;
  }) => void;
  observeToolTerminal?: EmbeddedRunAttemptParams["observeToolTerminal"];
  /** Attempt-scoped trajectory recorder for runtime tool audit events. */
  trajectoryRecorder?: EmbeddedRunAttemptParams["trajectoryRecorder"];
  onReasoningStream?: (payload: ReasoningStreamPayload) => void | Promise<void>;
  /** Expands window reasoning beyond "stream" mode for callers with their own display gate. */
  streamReasoningInNonStreamModes?: boolean;
  /** Called when a thinking/reasoning block ends (</think> tag processed). */
  onReasoningEnd?: () => void | Promise<void>;
  onBlockReply?: (payload: BlockReplyPayload, context?: BlockReplyContext) => void | Promise<void>;
  /** Flush pending block replies and identify the boundary that requested it. */
  onBlockReplyFlush?: (context: BlockReplyFlushContext) => void | Promise<void>;
  blockReplyBreak?: "text_end" | "message_end";
  blockReplyChunking?: BlockReplyChunking;
  onPartialReply?: (payload: PartialReplyPayload) => boolean | void | Promise<boolean | void>;
  onAssistantMessageStart?: () => void | Promise<void>;
  /** Assistant fragment usage before queued delivery; fragments may be intermediate. */
  onModelUsage?: (usage: NormalizedUsage | undefined) => void;
  onExecutionPhase?: (info: {
    phase: "tool_execution_started";
    tool?: string;
    toolCallId?: string;
    source?: string;
  }) => void;
  onAgentEvent?: (evt: EmbeddedAgentEvent) => void | Promise<void>;
  onToolStreamBoundary?: () => void | Promise<void>;
  onHeartbeatToolResponse?: (response: HeartbeatToolResponse) => void | Promise<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>;
  enforceFinalTag?: boolean;
  silentExpected?: boolean;
  /**
   * Skip per-chunk live visible-text parsing in handleMessageUpdate. Set for runs
   * with no live stream consumer — notably subagents, whose result is read back
   * from the final message_end path. Suppressing intermediate passes does not
   * change final output.
   */
  suppressLiveStreamOutput?: boolean;
  config?: OpenClawConfig;
  /** Prepared endpoint ownership can differ from the assistant's provider route ID. */
  providerOwner?: PreparedProviderFailoverOwner;
  compactionCountOwner?: EmbeddedRunAttemptInternalParams["compactionCountOwner"];
  onContextAccountingEvent?: EmbeddedRunAttemptInternalParams["onContextAccountingEvent"];
  sessionPersistence?: EmbeddedRunAttemptParams["sessionPersistence"];
  sessionKey?: string;
  /** Current transport channel resolved for this run. */
  currentChannelId?: string;
  /** Routable target for the current conversation when it differs from the native channel ID. */
  currentMessagingTarget?: string;
  currentAccountId?: string;
  /** Current transport thread resolved for this run. */
  currentThreadId?: string;
  /** Current inbound message id used to distinguish child replies from explicit roots. */
  currentMessageId?: string | number;
  /** Reply mode used by transport auto-threading. */
  replyToMode?: "off" | "first" | "all" | "batched";
  /** Shared one-shot reply state used by first/batched modes. */
  hasRepliedRef?: {
    value: boolean;
  };
  /** Ephemeral session UUID — regenerated on /new and /reset. */
  sessionId?: string;
  /** Agent identity for hook context — resolved from session config in attempt.ts. */
  agentId?: 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>;
  /** 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>;
  internalEvents?: AgentInternalEvent[];
};
//#endregion
//#region src/agents/embedded-agent-subscribe.d.ts
declare function subscribeEmbeddedAgentSession(params: SubscribeEmbeddedAgentSessionParams): {
  assistantTexts: string[];
  answerSegments: {
    textEnd: number;
    messageEnd: number;
    finalMessageStart: number;
    lastAssistant: AssistantMessage$1;
  }[];
  getCurrentAttemptAssistant: () => AssistantMessage$1 | undefined;
  hasSuccessfulModelResponse: () => boolean;
  getLastAssistantTextMessageIndex: () => number | undefined;
  toolMetas: {
    toolName?: string;
    toolCallId?: string;
    parentToolCallId?: string;
    activity?: AgentItemEventData;
    meta?: string;
    replaySafe?: boolean;
    isError?: boolean;
    terminate?: boolean;
    asyncStarted?: boolean;
    asyncTaskRunId?: string;
    asyncTaskId?: string;
    codeModeSuspended?: boolean;
  }[];
  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;
      isError: boolean;
      executedArguments: unknown;
      effectReceipt: ToolEffectReceipt;
    }) => void | Promise<void>;
  }) => 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;
  getHeartbeatToolResponse: () => {
    outcome: "blocked" | "done" | "needs_attention" | "no_change" | "progress";
    notify: boolean;
    summary: string;
    notificationText?: string;
    reason?: string;
    priority?: "high" | "low" | "normal";
    nextCheck?: string;
    scratch?: string;
  } | undefined;
  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;
    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/embedded-agent-runner/run/attempt-result.d.ts
type EmbeddedAttemptSubscription = ReturnType<typeof subscribeEmbeddedAgentSession>;
type EmbeddedRunAttemptWithReceiptEvidence = EmbeddedRunAttemptResult & {
  answerSegments?: EmbeddedAttemptSubscription["answerSegments"];
  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 AgentHarnessHostApprovalResult = Readonly<{
  decision: ApprovalDecision | null | undefined;
  terminalReason: ApprovalTerminalReason | null | undefined;
}>;
type AgentHarnessPreparedEnvironment = Readonly<{
  credentialScrubEnv: Readonly<Record<string, string>>;
  localIdentityEnv: Readonly<Record<string, 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;
}>;
type AgentHarnessToolSurfaceOptions = Omit<NonNullable<Parameters<(typeof agent_tools_d_exports)["createOpenClawCodingTools"]>[0]>, "operationalRunInstance">;
type AgentHarnessModelExecutionBinder = (model: ProviderModelRef | undefined) => Readonly<{
  signal: AbortSignal;
  assertCurrent: () => void;
  release: () => void;
}> | undefined;
type AgentHarnessHostCapabilities = Readonly<{
  kind: "agent-harness-host-capability";
  version: 1;
  /** Fails closed unless this exact admitted run capability remains active. */
  assertActive: () => void;
  /** Binds the actual native model; 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;
    /** Live preflight fact; absence means unknown, not an unrestricted source. */
    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>;
  /** 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>;
  /** Rebuilds retained attachments under this host's captured media policy and run authority. */
  prepareContextMedia?: (request: {
    message: AgentMessage;
    maxChars: number;
  }) => Promise<{
    text?: string;
    images: ImageContent$1[];
  }>;
  /** 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;
  })) | {
    /** 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;
  }>;
  /** 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[];
  /** Creates and binds core tools without exposing admitted-run correlation to the plugin. */
  createToolSurface?: (options: AgentHarnessToolSurfaceOptions, bindingOptions?: Readonly<{
    cwd?: string;
  }>) => 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/embedded-agent-runner/run/types.d.ts
type EmbeddedRunAttemptBase = Omit<RunEmbeddedAgentParams, "provider" | "model" | "authProfileId" | "authProfileIdSource" | "thinkLevel" | "fastMode" | "lane" | "enqueue" | "sessionFile" | "preparedRunAdmission" | "admittedRunContext">;
type EmbeddedRunFastModeParam = boolean | (() => boolean | undefined);
type EmbeddedRunAttemptOperation = "attempt" | "settled-tool-finalization";
type EmbeddedRunAttemptToolTerminalObservation = {
  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;
  };
};
type EmbeddedRunAttemptToolTerminalResolution = {
  lastToolError?: ToolErrorSummary;
  executionStarted: boolean;
  executedArguments?: Record<string, unknown>;
  sideEffectEvidence: boolean;
  effectReceipt: ToolEffectReceipt;
};
type EmbeddedRunAttemptToolTerminalObserver = (observation: EmbeddedRunAttemptToolTerminalObservation) => EmbeddedRunAttemptToolTerminalResolution;
/** 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 & {
  /** Recomputed by the host for this attempt; never inherited from the requesting turn. */
  githubPublicationAvailable?: boolean;
  disableToolSearch?: true;
  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?: EmbeddedRunAttemptOperation;
  /** Core-prepared fact that explicit requester/config policy restricts plugin-native tools. */
  pluginHarnessToolPolicyRestricted?: boolean;
  /** Audited exact denies that the plugin harness must enforce against native equivalents. */
  pluginHarnessToolPolicySafeDeniedTools?: readonly string[];
  preparedModelRuntime?: PreparedModelRuntimeSnapshot;
  /** Active file-backed artifact target resolved by the run/session target seam. */
  sessionFile: string;
  initialReplayState?: EmbeddedRunReplayState;
  /** Pluggable context engine for ingest/assemble/compact lifecycle. */
  contextEngine?: ContextEngine;
  /** Resolved model context window in tokens for assemble/compact budgeting. */
  contextTokenBudget?: number;
  /** 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;
  /** Final prepared harness for this attempt; not evidence of native session/model ownership. */
  agentHarnessId?: string;
  /** 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?: EmbeddedRunAttemptToolTerminalObserver;
  /** 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;
  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[];
  /** 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;
  authStorage: AuthStorage;
  /** Auth profile store already resolved during startup for this attempt. */
  authProfileStore: AuthProfileStore;
  /**
   * Full auth profile store for OpenClaw tool availability.
   * Plugin-owned harnesses may scope `authProfileStore` to model transport credentials.
   */
  toolAuthProfileStore?: AuthProfileStore;
  modelRegistry: ModelRegistry;
  thinkLevel: ThinkLevel;
  fastMode?: EmbeddedRunFastModeParam;
  /** True when this attempt is running the auto fast-mode policy. */
  fastModeAuto?: boolean;
  beforeAgentFinalizeRevisionAttempts?: number;
  maxBeforeAgentFinalizeRevisions?: number;
};
type EmbeddedRunAttemptResult = {
  terminal: AgentRunAttemptTerminal;
  /** 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">;
    source?: "mid-turn";
    estimatedPromptTokens?: number;
    promptBudgetBeforeReserve?: number;
    overflowTokens?: number;
    handled: true;
    truncatedCount?: number;
  } | {
    route: Exclude<PreemptiveCompactionRoute, "fits">;
    source?: "mid-turn";
    estimatedPromptTokens?: number;
    promptBudgetBeforeReserve?: number;
    overflowTokens?: 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;
  /** 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[];
  /** 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: AssistantMessage$1 | undefined;
  /**
   * Omission preserves the legacy `lastAssistant` fallback; explicit `undefined`
   * means this attempt produced no assistant response.
   */
  currentAttemptAssistant?: AssistantMessage$1 | undefined;
  /** Completed message_end snapshot owned by this model attempt. */
  currentAttemptCompletedAssistant?: AssistantMessage$1 | 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[];
  heartbeatToolResponse?: HeartbeatToolResponse;
  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;
  /**
   * 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
/** 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, "admittedRunContext" | "disableToolSearch" | "sessionReadScopeKey" | "assistantErrorTranscript" | "contextEngineLogicalTurnLease" | "onContextEngineTurnCandidate" | "trajectoryRecorder" | "inputAttachmentMedia">;
/**
 * @deprecated Use AgentHarnessAttemptParamsV2. The optional capability keeps
 * existing harness source compatible through 2026-10-12.
 */
type AgentHarnessAttemptParams = AgentHarnessAttemptParamsBase & {
  hostCapabilities?: AgentHarnessHostCapabilities;
};
type AgentHarnessAttemptResult = AgentHarnessCanonicalAttemptResult | AgentHarnessLegacyAttemptResult;
type AgentHarnessSettledTurnFinalizationAttemptParams<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams> = Omit<TAttemptParams, "hostCapabilities"> & {
  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 = {
  /** The single completed assistant answer produced by the isolated operation. */
  assistant: AssistantMessage$1;
  /** 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";
  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;
};
type AgentHarnessIsolatedCompletionParamsV2 = Omit<AgentHarnessIsolatedCompletionParams, "model" | "auth" | "sourceAuthFingerprint"> & {
  authorization: AgentHarnessIsolatedCompletionAuthorization;
};
type AgentHarnessIsolatedCompletionResult = {
  /** The single assistant completion. Core rejects tool-shaped or failed results. */
  assistant: AssistantMessage$1;
};
type AgentHarnessAuthBindingFingerprintParams = {
  authProfileId: string;
  authProfileStore: AuthProfileStore;
  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;
    authStorage: AuthStorage;
    modelRegistry: ModelRegistry;
    /** Resolved host credential for an immutable API-key route only. */
    resolvedApiKey?: string;
  };
  question: string;
  images?: ImageContent$1[];
  sessionEntry: SessionEntry$1;
  sessionStore?: Record<string, SessionEntry$1>;
  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";
};
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 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: SessionUpstreamJsonValue;
  };
};
/** 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 AgentHarnessRunCapability<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams> = {
  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;
  };
  /**
   * 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[];
  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;
  /** Synchronous private ownership read; no discovery, auth loading, or native connection setup. */
  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;
  /** Lets this harness resolve forwarded profiles or its own native credentials. */
  authBootstrap?: "harness";
  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>;
};
type AgentHarnessSideQuestionCapability<TSideQuestionParams extends AgentHarnessSideQuestionParams = AgentHarnessSideQuestionParams> = {
  runSideQuestion?(params: TSideQuestionParams): Promise<AgentHarnessSideQuestionResult>;
};
type AgentHarnessClassificationCapability<TAttemptParams extends AgentHarnessAttemptParams = AgentHarnessAttemptParams> = {
  classify?(result: AgentHarnessAttemptResult, ctx: TAttemptParams): AgentHarnessResultClassification | undefined;
};
type AgentHarnessCompactionCapability = {
  compact?(params: AgentHarnessCompactParams): Promise<AgentHarnessCompactResult | undefined>;
};
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;
};
type AgentHarnessSessionDeletionMutation = {
  /** Synchronously remove only the prepared owner's state at the session commit edge. */
  commit: () => void;
  /** Restore only that removal when the authoritative session transaction rolls back. */
  rollback: () => void;
};
type AgentHarnessSessionContextResetParams = Omit<AgentHarnessSessionDeletionParams, "initialization"> & {
  /** Exact recorded predecessor may still own native context after interrupted compaction. */
  previousSessionId?: string;
};
type AgentHarnessSessionLifecycleCapability = {
  reset?(params: AgentHarnessResetParams): Promise<void> | void;
  /** 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;
};
type AgentHarnessSessionForkCapability = {
  /**
   * @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>;
  };
};
type AgentHarnessRuntimeArtifactCapability = {
  /** Revalidate an artifact only at setup and persistent-operation boundaries. */
  runtimeArtifact?: {
    validate(binding: AgentHarnessRuntimeArtifactBinding): Promise<boolean>;
  };
};
type AgentHarnessAuthBindingCapability = {
  /** Recomputes the exact credential fingerprint at persistent trust boundaries. */
  authBinding?: {
    fingerprint(params: AgentHarnessAuthBindingFingerprintParams): Promise<string | undefined>;
  };
};
type AgentHarnessProviderUsageCapability = {
  /**
   * 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;
};
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 AgentHarnessMcpCatalogCapability = {
  /** Lists the MCP tools owned by this session's native runtime, if it is already bound. */
  loadMcpToolCatalog?(params: AgentHarnessMcpCatalogParams): Promise<McpToolCatalog | undefined>;
};
type AgentHarnessModelCatalogParams = {
  config: OpenClawConfig;
  agentId: string;
  agentDir: string;
  workspaceDir: string;
  configuredModelRefs?: readonly ProviderModelRef[];
};
type AgentHarnessModelCatalogResult = readonly ModelCatalogEntry[] | {
  entries: readonly ModelCatalogEntry[];
  outcomes?: readonly ProviderCatalogOutcome[];
};
type AgentHarnessModelCatalogCapability = {
  /** Lists account-scoped models owned by this native runtime. */
  loadModelCatalog?(params: AgentHarnessModelCatalogParams): Promise<AgentHarnessModelCatalogResult>;
  /**
   * 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;
};
type AgentHarnessSharedCapabilities = AgentHarnessCompactionCapability & AgentHarnessRuntimeArtifactCapability & AgentHarnessAuthBindingCapability & AgentHarnessProviderUsageCapability & AgentHarnessModelCatalogCapability & AgentHarnessMcpCatalogCapability & AgentHarnessSessionForkCapability & AgentHarnessSessionLifecycleCapability;
/**
 * @deprecated Implement AgentHarnessV2. This registration contract remains
 * source-compatible for existing plugins through 2026-10-12.
 */
type AgentHarness = AgentHarnessRunCapability & AgentHarnessSideQuestionCapability & AgentHarnessClassificationCapability & AgentHarnessSharedCapabilities;
//#endregion
//#region src/tts/directives.d.ts
type ParseTtsDirectiveOptions = {
  cfg?: OpenClawConfig;
  providers?: readonly SpeechProviderPlugin$1[];
  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/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;
};
/** Summarize long text before synthesis using the configured summary model. */
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-config.d.ts
/** Routing context used to layer global, agent, channel, and account TTS config. */
type TtsConfigResolutionContext = {
  agentId?: string;
  channelId?: string;
  accountId?: string;
};
//#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;
declare function resolveTtsPrefsPath(config: ResolvedTtsConfig): string;
declare function resolveTtsAutoMode(params: {
  config: ResolvedTtsConfig;
  prefsPath: string;
  sessionAuto?: string;
}): TtsAutoMode;
declare function buildTtsSystemPromptHint(cfg: OpenClawConfig, agentId?: string, options?: {
  messageToolOnly?: boolean;
}): 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$1[]): TtsProvider[];
declare function isTtsProviderConfigured(config: ResolvedTtsConfig, provider: TtsProvider | SpeechProviderPlugin$1, cfg?: OpenClawConfig): boolean;
//#endregion
//#region src/tts/tts-runtime-types.d.ts
type TtsAttemptReasonCode = "success" | "no_provider_registered" | "not_configured" | "unsupported_for_streaming" | "unsupported_for_telephony" | "timeout" | "provider_error";
type TtsProviderAttempt = {
  provider: string;
  outcome: "success" | "skipped" | "failed";
  reasonCode: TtsAttemptReasonCode;
  persona?: string;
  personaBinding?: "applied" | "missing" | "none";
  latencyMs?: number;
  error?: string;
};
type 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
/** Host-owned availability guard shared by every speech runtime entrypoint. */
/** 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>;
declare function resolveExplicitTtsOverrides(params: {
  cfg: OpenClawConfig;
  prefsPath?: string;
  provider?: string;
  modelId?: string;
  voiceId?: string;
  agentId?: string;
  channelId?: string;
  accountId?: string;
}): 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, getLastTtsAttempt, getResolvedSpeechProviderConfig, getTtsMaxLength, getTtsPersona, getTtsProvider, isSummarizationEnabled, isTtsEnabled, isTtsProviderConfigured, listSpeechVoices, listTtsPersonas, prepareTtsRequest, resolveExplicitTtsOverrides, resolveTtsAutoMode, resolveTtsConfig, resolveTtsPrefsPath, resolveTtsProviderOrder, setLastTtsAttempt, setSpeechRuntimeAvailabilityGuard, setSummarizationEnabled, setTtsAutoMode, setTtsEnabled, setTtsMachinePrefsPathResolver, setTtsMaxLength, setTtsPersona, setTtsProvider, streamSpeech, synthesizeSpeech, testApi, textToSpeechStream, textToSpeechTelephony };
}
declare function getTtsProvider(config: ResolvedTtsConfig, prefsPath: string): 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/tts/tts.d.ts
declare function textToSpeech(params: Parameters<typeof textToSpeechCore>[0]): Promise<TtsResult>;
//#endregion
//#region src/agents/defaults.d.ts
declare const DEFAULT_PROVIDER = "openai";
declare const DEFAULT_MODEL = "gpt-6-astra";
//#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/main-session-recovery/main-session-recovery-types.d.ts
type MainSessionRecoveryOwnerClaim = {
  cycleId: string;
  lifecycleGeneration: string;
  claimId: string;
  sessionId: string;
  sessionKey: string;
  runId?: string;
};
//#endregion
//#region src/agents/main-session-recovery/main-session-recovery-store.d.ts
type MainSessionRecoveryStoreTarget = {
  agentId?: string;
  sessionKey: string;
  storePath: string;
};
type MainSessionRecoveryOwnerLease = MainSessionRecoveryOwnerClaim & MainSessionRecoveryStoreTarget;
//#endregion
//#region src/agents/command/types.d.ts
type ImageContent = Pick<ImageContent$1, "type" | "data" | "mimeType">;
/** Channel/account/thread context carried into an agent run. */
type AgentRunContext = {
  messageChannel?: string;
  accountId?: string;
  groupId?: string | null;
  groupChannel?: string | null;
  groupSpace?: string | null;
  currentChannelId?: string;
  /** Transport-native chat/conversation ID for plugin hook identity context. */
  chatId?: string;
  /** Channel-specific sender/chat metadata for plugin hook identity context. */
  channelContext?: PluginHookChannelContext;
  currentThreadTs?: string;
  currentInboundAudio?: boolean;
  senderId?: string | null;
  replyToMode?: "off" | "first" | "all" | "batched";
  hasRepliedRef?: {
    value: boolean;
  };
};
/** Full trusted option surface for running an agent command. */
type AgentCommandOpts = {
  message: string;
  /** User-visible transcript body; defaults to message and excludes runtime-only context. */
  transcriptMessage?: string;
  /** Durable media metadata for the user-visible transcript turn. */
  transcriptMedia?: UserTurnInput["media"];
  /** Optional image attachments for multimodal messages. */
  images?: ImageContent[];
  /** 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;
  /** Per-run provider override. */
  provider?: string;
  /** Per-run model override. */
  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;
  /** Message channel context. */
  messageChannel?: string;
  /** Tool-policy/output surface context. Defaults to messageChannel. */
  messageProvider?: string;
  /** Delivery channel. */
  channel?: string;
  /** Account ID for multi-account channel routing. */
  accountId?: string;
  /** Context for embedded run routing (channel/account/thread). */
  runContext?: AgentRunContext;
  /** 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;
  /** 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;
  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;
  /** Bootstrap workspace context injection mode for this run. */
  bootstrapContextMode?: "full" | "lightweight";
  /** Run kind hint for bootstrap context behavior. */
  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 owes an internal result regardless of its channel origin. */
  privateCompletion?: true;
  /** 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>;
  /** Restrict this reconstructed run to restart-safe tools. */
  forceRestartSafeTools?: boolean;
  forceCodeModeTools?: boolean;
  /** Invocation-owned Code Mode activation; limits still come from config. */
  codeModeOverride?: boolean | "auto";
  /** Host-owned exact media set for a scoped automatic recovery delivery. */
  internalDeliveryMediaUrls?: string[];
  internalDeliverySuppressText?: boolean;
  /** Gateway ingress that already persisted visible activity can skip the duplicate pre-run touch. */
  skipInitialSessionTouch?: boolean;
  /** Per-call stream param overrides (best-effort). */
  streamParams?: AgentStreamParams;
  /** Resolved per-run fast mode from channel/directive handling. */
  fastMode?: FastMode;
  /** Resolved per-run auto cutoff seconds for fast mode. */
  fastModeAutoOnSeconds?: number;
  /** Explicit workspace directory override (for subagents to inherit parent workspace). */
  workspaceDir?: SpawnedRunMetadata["workspaceDir"];
  /** Explicit task working directory for this run. Bootstrap still uses workspaceDir. */
  cwd?: string;
  /** Force bundled MCP teardown when a one-shot local run completes. */
  cleanupBundleMcpOnRunEnd?: boolean;
  /** Force long-lived CLI live session teardown when a one-shot local run completes. */
  cleanupCliLiveSessionOnRunEnd?: boolean;
  /** Mark explicit one-shot local CLI runs so plugin tools can release resources promptly. */
  oneShotCliRun?: boolean;
  /** Gateway-owned runs can late-bind plugin subagent and node runtime helpers. */
  allowGatewaySubagentBinding?: boolean;
  /** Opaque foreground fence transferred by Gateway after atomic session admission. */
  mainRestartRecoveryOwnerLease?: MainSessionRecoveryOwnerLease;
  /** Gateway already consumed this automatic recovery run's durable reservation. */
  mainRestartRecoveryAdmitted?: boolean;
  /** Exact durable recovery attempt allowed to bind post-admission execution identity. */
  mainRestartRecoveryAttempt?: number;
  /** Private recovery correlation; public ingress callers cannot author identity evidence. */
  executionIdentityAdmission?: ReturnType<(typeof admitted_run_context_d_exports)["createExecutionIdentityRecoveryAdmission"]>;
  /** 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 joins terminal transcript writes before delivery or failed-command cleanup. */
  beforeTerminalDelivery?: () => Promise<void>;
  /** Called when the actual run model is selected, including fallback retries. */
  onActiveModelSelected?: (ctx: {
    provider: string;
    model: string;
  }) => void | Promise<void>;
  /** Called when every candidate in the run's model fallback chain failed. */
  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;
};
type AgentCommandGatewayOnlyKey = "clientCaps" | "gatewayUiCommandTarget" | "toolBindings" | "taskSuggestionDeliveryMode" | "runtimeContextFragments" | "mainRestartRecoveryOwnerLease" | "mainRestartRecoveryAdmitted" | "mainRestartRecoveryAttempt" | "pinnedWidgetAuthoring" | "executionIdentityAdmission" | "operationalRunInstance" | "operatorAuthority" | "privateCompletion" | "assertSourceCurrent" | "skillLibraryAuthoring" | "cronCreatorAuthorityCapability" | "onAdmittedRunContext" | "onPostAdmittedRunContext" | "beforeTerminalDelivery";
/** 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"> & {
  payloads: ReturnType<typeof projectOutboundPayloadPlanForJson>;
  meta: EmbeddedAgentRunMeta;
  didSendViaMessagingTool?: boolean;
  messagingToolSentTexts?: string[];
  messagingToolSentMediaUrls?: string[];
  messagingToolSentTargets?: MessagingToolSend[];
  didSendDeterministicApprovalPrompt?: true;
  acceptedSessionSpawns?: NonNullable<EmbeddedAgentRunResult["acceptedSessionSpawns"]>;
  requesterContinuationSettled?: true;
  successfulCronAdds?: number;
  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;
};
/**
 * Decides whether an opted-in embedded run would execute through the CLI
 * backend. Resolution stays on stored credential metadata — no credential
 * materialization, refresh locks, or network calls on this per-turn path.
 */
declare function resolveEmbeddedCliBackendDispatchEligibility(params: EmbeddedCliBackendDispatchEligibilityParams): {
  provider: string;
} | undefined;
declare namespace system_events_d_exports {
  export { SystemEvent, consumeSelectedSystemEventEntries, drainSystemEventEntries, drainSystemEvents, enqueueSystemEvent, enqueueSystemEventEntry, enqueueSystemEventWithReceipt, hasSystemEvents, isSystemEventContextChanged, peekSystemEventEntries, peekSystemEvents, resetSystemEventsForTest, resolveSystemEventDeliveryContext };
}
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;
  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;
};
type ReceiptOptions = {
  allowDuplicate?: 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;
/** Enqueues one occurrence and returns one-use removal ownership for its UUID. */
declare function enqueueSystemEventWithReceipt(text: string, options: SystemEventOptions, receiptOptions?: ReceiptOptions): (() => boolean) | null;
declare function drainSystemEventEntries(sessionKey: string): SystemEvent[];
declare function consumeSelectedSystemEventEntries(sessionKey: string, consumedEntries: readonly SystemEvent[]): SystemEvent[];
declare function drainSystemEvents(sessionKey: string): string[];
declare function peekSystemEventEntries(sessionKey: string): SystemEvent[];
declare function peekSystemEvents(sessionKey: string): string[];
declare function hasSystemEvents(sessionKey: string): boolean;
declare function resolveSystemEventDeliveryContext(events: readonly SystemEvent[]): DeliveryContext | undefined;
declare function resetSystemEventsForTest(): void;
//#endregion
//#region src/plugins/runtime/system-events.d.ts
declare const enqueueSystemEventFromSdk: (text: string, { agentId, ...options }: Parameters<typeof enqueueSystemEvent>[1] & {
  agentId?: string;
}) => boolean;
//#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/media/image-ops.d.ts
/** JPEG resize request passed through the media-runtime/plugin SDK surface. */
type ResizeToJpegParams = {
  buffer: Buffer;
  maxSide: number;
  quality: number;
  withoutEnlargement?: boolean;
};
/** Fully probes display dimensions through Rastermill when header-only metadata is insufficient. */
declare function getImageMetadata(buffer: Buffer): Promise<ImageMetadata | null>;
/** Resizes or encodes image bytes as JPEG through the shared image processor. */
declare function resizeToJpeg(params: ResizeToJpegParams): Promise<Buffer>;
//#endregion
//#region src/media/web-media.d.ts
/** Loaded media bytes plus resolved MIME kind and filename metadata for outbound/plugin callers. */
type WebMediaResult = {
  buffer: Buffer;
  contentType?: string;
  kind: MediaKind | undefined;
  fileName?: string;
  /** Source bytes came from a generated-HTML trust boundary. */
  trustedGeneratedHtmlSource?: boolean;
};
type WebMediaOptions = {
  maxBytes?: number;
  optimizeImages?: boolean;
  imageCompression?: ImageCompressionPolicy;
  ssrfPolicy?: SsrFPolicy;
  proxyUrl?: string;
  fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
  requestInit?: RequestInit;
  readIdleTimeoutMs?: number;
  trustExplicitProxyDns?: boolean;
  workspaceDir?: string;
  /** Allowed root directories for local path reads. "any" is deprecated; prefer sandboxValidated + readFile. */
  localRoots?: readonly string[] | "any";
  /** Channel inbound attachment root patterns checked with inbound path policy semantics. */
  inboundRoots?: readonly string[];
  /** Caller already validated the local path (sandbox/other guards); requires readFile override. */
  sandboxValidated?: boolean;
  readFile?: OutboundMediaReadFile;
  /** Host-local fs-policy read piggyback; rejects plaintext-like document sends. */
  hostReadCapability?: boolean;
};
/** Compression preference used to tune image size/quality search grids. */
type ImageQualityPreference = "auto" | "efficient" | "balanced" | "high";
/** Per-model image compression constraints merged into outbound media policy. */
type ImageCompressionModelPolicy = {
  maxBytes?: number;
  maxPixels?: number;
  maxSidePx?: number;
  preferredSidePx?: number;
};
/** Image compression policy for model/tool callers that need bounded media payloads. */
type ImageCompressionPolicy = {
  quality?: ImageQualityPreference;
  models?: ImageCompressionModelPolicy[];
  imageCount?: number;
};
/** Loads local, remote, hosted, or media-store media and optimizes images by default. */
declare function loadWebMedia(mediaUrl: string, maxBytesOrOptions?: number | WebMediaOptions, options?: {
  ssrfPolicy?: SsrFPolicy;
  localRoots?: readonly string[] | "any";
}): Promise<WebMediaResult>;
//#endregion
//#region packages/media-core/src/mime.d.ts
/** Detects the best MIME type from bytes, file path, and header metadata. */
declare function detectMime(opts: {
  buffer?: Buffer;
  headerMime?: string | null;
  additionalMimeHints?: readonly (string | null | undefined)[];
  filePath?: string;
}): Promise<string | undefined>;
//#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 src/image-generation/runtime-types.d.ts
type GenerateImageParams = Omit<ImageGenerationRequest, "provider" | "model"> & {
  modelOverride?: string;
  /** Resolution inferred from reference images; omitted for incompatible fallback models. */
  inferredResolution?: ImageGenerationResolution;
  autoProviderFallback?: boolean;
};
type GenerateImageRuntimeResult = Omit<ImageGenerationResult, "model"> & {
  provider: string;
  model: string;
  attempts: FallbackAttempt[];
  appliedResolution?: ImageGenerationResolution;
  normalization?: ImageGenerationNormalization;
  ignoredOverrides: ImageGenerationIgnoredOverride[];
};
//#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
/** Parameters accepted by the core music generation runtime. */
type GenerateMusicParams = Omit<MusicGenerationRequest, "provider" | "model"> & {
  modelOverride?: string;
  autoProviderFallback?: boolean;
};
/** Result returned after a successful runtime provider attempt. */
type GenerateMusicRuntimeResult = Omit<MusicGenerationResult, "model"> & {
  provider: string;
  model: string;
  attempts: FallbackAttempt[];
  normalization?: MusicGenerationNormalization;
  ignoredOverrides: MusicGenerationIgnoredOverride[];
};
//#endregion
//#region src/web-search/runtime-types.d.ts
/** Provider/tool resolution inputs for web_search. */
type ResolveWebSearchDefinitionParams = {
  config?: OpenClawConfig;
  agentDir?: string;
  sandboxed?: boolean;
  runtimeWebSearch?: RuntimeWebSearchMetadata;
  providerId?: string;
  preferRuntimeProviders?: boolean;
  preferInputConfig?: boolean;
};
/** Inputs for executing a web_search request through the selected provider. */
type RunWebSearchParams = ResolveWebSearchDefinitionParams & {
  args: Record<string, unknown>;
  signal?: AbortSignal;
  /** Caller-owned synchronous authority check, repeated immediately before external requests. */
  assertCurrent?: () => void;
};
/** Normalized execution result that records which provider answered. */
type RunWebSearchResult = {
  provider: string;
  result: Record<string, unknown>;
};
//#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>;
};
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> = {
  /** Prepares a mutation observation through canonical writable admission; may create state. */
  observe?: (key: string) => Promise<PluginStateObservation<T>>;
  /** Compares the observed row before applying prepared data; only explicit conflicts may retry. */
  compareAndApply?: (key: string, comparison: string, intent: PluginStateCompareIntent<T>) => 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 This callback blocks the main thread. Use data-only operations when they preserve
   * the complete atomic change. Retained through the next Plugin SDK major.
   */
  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 This callback blocks the main thread. Use deleteIfEqual for scalar comparisons;
   * other atomic predicates remain supported through the next Plugin SDK major.
   */
  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;
  }): 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">> : PluginStateKeyedStoreBase<T> & {
  /** Bind current action authority through read completion and final write admission. */
  withCurrent?: (authority: {
    assertCurrent: () => void;
  }) => PluginStateKeyedStore<T, 2>;
};
/**
 * Synchronous plugin-state compatibility contract.
 * @deprecated Use PluginStateKeyedStore from api.runtime.state.openKeyedStore
 * and await its operations. Retained through the next Plugin SDK major.
 */
type PluginStateSyncKeyedStore<T> = {
  register(key: string, value: T, opts?: {
    ttlMs?: number;
  }): void;
  registerIfAbsent(key: string, value: T, opts?: {
    ttlMs?: number;
  }): boolean;
  /** Expiry options are consumed after the synchronous updater returns. */
  update?: (key: string, updateValue: (current: T | undefined) => T | undefined, opts?: {
    ttlMs?: number;
  }) => boolean;
  /** Atomically deletes an existing entry when its current value matches. */
  deleteIf?: (key: string, predicate: (current: T) => boolean) => boolean;
  lookup(key: string): T | undefined;
  /** Positional outcomes for at most 10,000 keys; missing/expired values are undefined. */
  lookupMany?: (keys: readonly string[]) => Array<Result$1<T | undefined, PluginStateStoreError>>;
  consume(key: string): T | undefined;
  delete(key: string): boolean;
  entries(): PluginStateEntry<T>[];
  /** Counts live stored rows without decoding values; absent on older hosts and adapters. */
  count?: () => number;
  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;
type PluginStateStoreErrorCode = "PLUGIN_STATE_SQLITE_UNAVAILABLE" | "PLUGIN_STATE_OPEN_FAILED" | "PLUGIN_STATE_WRITE_FAILED" | "PLUGIN_STATE_READ_FAILED" | "PLUGIN_STATE_CORRUPT" | "PLUGIN_STATE_LIMIT_EXCEEDED" | "PLUGIN_STATE_INVALID_INPUT";
type PluginStateStoreOperation = "load-sqlite" | "open" | "ensure-schema" | "register" | "lookup" | "consume" | "delete" | "entries" | "count" | "clear" | "sweep" | "probe" | "close";
type PluginStateStoreErrorOptions = {
  code: PluginStateStoreErrorCode;
  operation: PluginStateStoreOperation;
  path?: string;
  cause?: unknown;
  owner?: {
    pid: number;
    threadId: number;
    version: string;
  };
};
/** Typed error thrown for plugin-state validation and sqlite failures. */
declare class PluginStateStoreError extends Error {
  readonly code: PluginStateStoreErrorCode;
  readonly operation: PluginStateStoreOperation;
  readonly path?: string;
  readonly owner: {
    pid: number;
    threadId: number;
    version: string;
  };
  constructor(message: string, options: PluginStateStoreErrorOptions);
  toJSON(): Record<string, unknown>;
}
//#endregion
//#region src/channels/message/ingress-queue.types.d.ts
/** Pending or retryable inbound channel event stored in the durable ingress queue. */
type ChannelIngressQueueRecord<TPayload, TMetadata = unknown> = {
  id: string;
  channelId: string;
  accountId: string;
  queueName: string;
  payload: TPayload;
  metadata?: TMetadata;
  receivedAt: number;
  updatedAt: number;
  laneKey?: string;
  attempts: number;
  lastAttemptAt?: number;
  lastError?: string;
};
/** Pending ingress event currently claimed by a worker. */
type ChannelIngressQueueClaim<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 = {
  id: string;
  channelId: string;
  accountId: string;
  queueName: string;
  laneKey?: string;
  reason: "corrupt_payload";
  claim: {
    token: string;
    ownerId: string;
    claimedAt: number;
  };
};
/** Completed ingress event tombstone retained for duplicate detection. */
type ChannelIngressQueueCompletedRecord<TCompletedMetadata = unknown> = {
  id: string;
  channelId: string;
  accountId: string;
  queueName: string;
  completedAt: number;
  metadata?: TCompletedMetadata;
};
/** Retention options for pending, completed, and failed ingress queue rows. */
type ChannelIngressQueuePruneOptions = {
  pendingTtlMs?: number;
  completedTtlMs?: number;
  failedTtlMs?: number;
  pendingMaxEntries?: number;
  completedMaxEntries?: number;
  failedMaxEntries?: number;
  protectIds?: Iterable<string>;
  now?: number;
};
/** Failed ingress event tombstone retained for duplicate detection. */
type ChannelIngressQueueFailedRecord = {
  id: string;
  channelId: string;
  accountId: string;
  queueName: 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;
};
/** Outcome of asking a channel/account queue to re-enqueue one failed event. */
type ChannelIngressQueueResubmitResult<TPayload, TMetadata = unknown, TCompletedMetadata = unknown> = {
  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>;
};
/** Result of enqueueing a possibly duplicate ingress event id. */
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;
};
/** Durable FIFO-ish ingress queue with claims, duplicate detection, and retention pruning. */
type ChannelIngressQueue<TPayload, TMetadata = unknown, TCompletedMetadata = unknown> = {
  enqueue(id: string, payload: TPayload, options?: {
    metadata?: TMetadata;
    receivedAt?: number;
    laneKey?: string;
  }): 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;
  }): 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<ChannelIngressQueueResubmitResult<TPayload, TMetadata, TCompletedMetadata>>;
  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>;
};
/** Construction options for a channel/account-scoped ingress queue. */
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";
};
//#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;
  /**
   * 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>;
};
//#endregion
//#region src/channels/message/ingress-drain-state.d.ts
type ChannelIngressDrainDispatchResult = {
  kind: "completed";
} | {
  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-retry-policy.d.ts
type IngressRetryPolicyConfig = {
  maxAttempts?: number;
  deadLetterMinAgeMs?: number;
  baseMs?: number;
  maxMs?: number;
};
type IngressNonRetryableFailure = {
  reason: string;
  message: string;
};
//#endregion
//#region src/channels/message/ingress-drain.d.ts
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;
  /** 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;
};
//#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;
  };
});
/** Config surface that supplied a resolved model runtime policy. */
type ModelRuntimePolicySource = "model" | "provider";
/** Runtime policy plus the config surface that supplied it. */
type ResolvedModelRuntimePolicy = {
  policy?: AgentRuntimePolicyConfig;
  source?: ModelRuntimePolicySource;
  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 packages/media-understanding-common/src/active-model.d.ts
/** Provider/model pair selected for one media-understanding request. */
type ActiveMediaModel = {
  provider: string;
  model?: string;
};
//#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?: MediaUnderstandingScopeContext;
};
type MediaUnderstandingScopeContext = {
  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 = {
  filePath: string;
  mediaUrl?: string;
  cfg: OpenClawConfig;
  agentId?: string;
  agentDir?: string;
  workspaceDir?: string;
  mime?: string;
  provider: string;
  model: string;
  prompt: string;
  maxTokens?: number;
  timeoutMs?: number;
};
type PreparedImageDescriptionInput = {
  buffer: Buffer;
  fileName: string;
  mime?: string;
};
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 = {
  /** At least one image input is required; text inputs provide supplemental context. */
  input: StructuredExtractionInput[];
  instructions: string;
  schemaName?: string;
  jsonSchema?: unknown;
  jsonMode?: boolean;
  cfg: OpenClawConfig;
  agentDir?: string;
  provider: string;
  model: string;
  profile?: string;
  preferredProfile?: string;
  authStore?: AuthProfileStore;
  timeoutMs?: number;
};
type ExtractStructuredWithModelResult = Awaited<ReturnType<NonNullable<MediaUnderstandingProvider["extractStructured"]>>>;
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<ExtractStructuredWithModelResult>;
  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 ListSpeechVoices = TtsRuntimeApi["listSpeechVoices"];
type PrepareTtsRequest = TtsRuntimeApi["prepareTtsRequest"];
type TextToSpeech = typeof textToSpeech;
type TextToSpeechStream = TtsRuntimeApi["textToSpeechStream"];
type TextToSpeechTelephony = TtsRuntimeApi["textToSpeechTelephony"];
type RuntimeRequestHeartbeatOptions = Parameters<typeof requestSessionEventWake>[0];
type RuntimeRequestHeartbeatNowOptions = Omit<RuntimeRequestHeartbeatOptions, "source" | "intent"> & Partial<Pick<RuntimeRequestHeartbeatOptions, "source" | "intent">>;
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 RuntimeConfigMutationContext = {
  snapshot: ConfigFileSnapshot;
  previousHash: string | null;
};
type RuntimeMutateConfigFileParams<T = void> = {
  base?: ConfigMutationBase;
  baseHash?: string;
  afterWrite: RuntimeConfigAfterWrite;
  writeOptions?: RuntimeWriteConfigOptions;
  mutate: (draft: OpenClawConfig, context: RuntimeConfigMutationContext) => Promise<T | void> | T | void;
};
type RuntimeReplaceConfigFileParams = {
  nextConfig: OpenClawConfig;
  baseHash?: string;
  afterWrite: RuntimeConfigAfterWrite;
  writeOptions?: RuntimeWriteConfigOptions;
};
type RuntimeSessionEntry = SessionEntry$1;
type RuntimeSessionPluginExtensions = Record<string, Record<string, SessionPluginJsonValue>> | undefined;
type RuntimeSessionStoreReadParams = {
  agentId?: string;
  env?: NodeJS.ProcessEnv;
  hydrateSkillPromptRefs?: boolean;
  sessionKey: string;
  readConsistency?: "latest";
  storePath?: string;
};
type RuntimeSessionStoreListParams = Partial<Omit<RuntimeSessionStoreReadParams, "sessionKey">> & {
  readOnly?: boolean;
};
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;
};
type RuntimeCreateSessionEntryBaseParams = {
  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;
  };
};
type RuntimeCreateSessionEntryParams = RuntimeCreateSessionEntryBaseParams & ({
  /** 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>;
});
type RuntimeSessionStoreEntryPatchParams = 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;
};
type RuntimeUpsertSessionEntryParams = RuntimeSessionStoreReadParams & {
  entry: RuntimeSessionEntry;
};
type RuntimeSessionWorkAdmissionParams = {
  storePath: string;
  sessionKey: string;
  signal?: AbortSignal;
};
type RuntimeSessionStoreEntryUpdateParams = {
  storePath: string;
  sessionKey: string;
  update: (entry: RuntimeSessionEntry) => Promise<Partial<RuntimeSessionEntry> | null> | Partial<RuntimeSessionEntry> | null;
  skipMaintenance?: boolean;
  takeCacheOwnership?: boolean;
  requireWriteSuccess?: boolean;
};
/** @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 RunHeartbeatOnceOptions = {
  reason?: string;
  agentId?: string;
  sessionKey?: string;
  /** Override heartbeat config (e.g. `{ target: "last" }` to deliver to the last active channel). */
  heartbeat?: {
    target?: string;
  };
};
type LlmCompleteMessage = {
  role: "system" | "user" | "assistant";
  content: string;
};
type LlmCompleteCaller = {
  kind: "plugin" | "context-engine" | "host" | "unknown";
  id?: string;
  name?: string;
};
type LlmCompleteUsage = {
  inputTokens?: number;
  outputTokens?: number;
  cacheReadTokens?: number;
  cacheWriteTokens?: number;
  totalTokens?: number;
  costUsd?: number;
};
type 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 LlmDirectCompleteParams = LlmCompleteCommonParams & {
  messages: LlmCompleteMessage[];
  /** 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;
};
type LlmIsolatedAgentRuntimeCompleteParams = LlmCompleteCommonParams & {
  /** Isolated runtimes currently accept one fresh user prompt, not a replayed chat history. */
  messages: [{
    role: "user";
    content: string;
  }];
  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 = LlmDirectCompleteParams | LlmIsolatedAgentRuntimeCompleteParams;
type LlmCompleteExecution = {
  mode: "direct-provider";
  owner: {
    kind: "provider";
    id: string;
  };
} | {
  mode: "isolated-agent-runtime";
  owner: {
    kind: "cli" | "harness";
    id: string;
  };
};
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?: "stop" | "length" | "toolUse" | "error" | "aborted";
  agentId: string;
  usage: LlmCompleteUsage;
  execution: LlmCompleteExecution;
  audit: {
    caller: LlmCompleteCaller;
    purpose?: string;
    sessionKey?: string;
  };
};
type RuntimeRunEmbeddedAgentParams = Omit<RunEmbeddedAgentParams, "admittedRunContext" | "preparedRunAdmission"> & {
  /** @deprecated Ignored; the host derives availability. Retained until the next Plugin SDK major. */
  githubPublicationAvailable?: boolean;
};
type RuntimeRunEmbeddedAgent = (params: RuntimeRunEmbeddedAgentParams) => Promise<EmbeddedAgentRunResult>;
/** Core runtime helpers exposed to trusted native plugins. */
type PluginRuntimeCore = {
  version: string;
  decisions: DecisionRuntimeV1;
  config: {
    /** Current process runtime config snapshot. Prefer config passed into the active call path. */
    current: () => 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: RuntimeMutateConfigFileParams<T>) => 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: RuntimeReplaceConfigFileParams) => 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: RuntimeRunEmbeddedAgent;
    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.
     */
    resolveCliBackendDispatchEligibility: typeof resolveEmbeddedCliBackendDispatchEligibility;
    ensureAgentWorkspace: typeof ensureAgentWorkspace;
    session: {
      resolveStorePath: typeof resolveSessionStorePathCore;
      createSessionEntry: (params: RuntimeCreateSessionEntryParams) => Promise<RuntimeCreateSessionEntryResult>;
      getSessionEntry: (params: RuntimeSessionStoreReadParams) => RuntimeSessionEntry | undefined;
      listSessionEntries: (params?: RuntimeSessionStoreListParams) => RuntimeSessionStoreEntrySummary[];
      patchSessionEntry: (params: RuntimeSessionStoreEntryPatchParams) => Promise<RuntimeSessionEntry | null>;
      upsertSessionEntry: (params: RuntimeUpsertSessionEntryParams) => Promise<void>;
      runWithWorkAdmission: <T>(params: RuntimeSessionWorkAdmissionParams, run: (signal: AbortSignal) => Promise<T>) => Promise<T>;
      updateSessionStoreEntry: (params: RuntimeSessionStoreEntryUpdateParams) => 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: {
    enqueueSystemEvent: typeof enqueueSystemEventFromSdk;
    requestHeartbeat: typeof requestSessionEventWake;
    /**
     * @deprecated Use `requestHeartbeat({ source, intent, reason })` so wake producers declare
     * scheduler intent explicitly.
     */
    requestHeartbeatNow: (opts?: RuntimeRequestHeartbeatNowOptions) => void;
    /**
     * Run a single heartbeat cycle immediately (bypassing the coalesce timer).
     * Accepts an optional `heartbeat` config override so callers can choose
     * an explicit destination or opt into internal-only `target: "none"` runs.
     */
    runHeartbeatOnce: (opts?: RunHeartbeatOnceOptions) => Promise<HeartbeatRunResult>;
    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: {
    prepareTtsRequest: PrepareTtsRequest;
    textToSpeech: TextToSpeech;
    textToSpeechStream: TextToSpeechStream;
    textToSpeechTelephony: TextToSpeechTelephony;
    listVoices: 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: {
    listProviders: (params?: RuntimeProviderListParams) => 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) => PluginBlobStore<TMetadata>;
    openKeyedStore: <T>(options: OpenAsyncKeyedStoreOptions) => PluginStateKeyedStore<T>;
    /**
     * @deprecated Use openKeyedStore and await its operations. The synchronous
     * compatibility adapter remains through the next Plugin SDK major.
     */
    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;
    ensureAuthProfileStore: typeof ensureAuthProfileStore;
    resolveAuthProfileOrder: typeof resolveAuthProfileOrder;
    listProfilesForProvider: typeof listProfilesForProvider;
    isProviderApiKeyConfigured: typeof isProviderApiKeyConfigured;
    /** 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[];
  /** Estimated total tokens in assembled context */
  estimatedTokens: number;
  /**
   * Controls which token estimate the runner treats as authoritative for
   * preemptive overflow prechecks. The returned `messages` are always the
   * prompt sent to the model; this only affects the precheck's token comparison.
   *
   * - "assembled": the generic precheck uses only the assembled prompt's estimate
   *   unless the engine owns compaction; owning engines manage prompt admission.
   * - "preassembly_may_overflow": the precheck takes the maximum of the
   *   assembled estimate and the pre-assembly (unwindowed) session-history
   *   estimate. Engines opt into this when their assembled view can hide an
   *   overflow that would still affect the underlying transcript. This opt-in
   *   keeps the generic precheck active even for engines that own compaction.
   *
   * Defaults to "assembled".
   */
  promptAuthority?: "assembled" | "preassembly_may_overflow";
  /** Optional context-engine-provided instructions prepended to the runtime system prompt */
  systemPromptAddition?: string;
  /**
   * Optional projection lifecycle for hosts with persistent backend threads.
   *
   * Context engines that return `thread_bootstrap` ask the host to inject the
   * assembled context once for the supplied epoch, then reuse the backend
   * thread until the epoch changes. Engines that omit this field retain the
   * legacy per-turn projection behavior.
   */
  contextProjection?: ContextEngineProjection;
};
type ContextEngineProjection = {
  /** How the assembled context should be projected into the backend runtime. */
  mode: "per_turn" | "thread_bootstrap";
  /** Stable context epoch. Changing this tells persistent backends to rotate. */
  epoch?: string;
  /** Optional diagnostic fingerprint for the projected context payload. */
  fingerprint?: string;
};
type ContextEngineOperation = "agent-run" | "manual-compact" | "subagent-spawn";
type ContextEngineRuntimeMode = "normal" | "fallback" | "degraded";
type ContextEngineSelectionSource = "configured" | "default" | "unknown";
type ContextEngineRuntimeReasonCode = "provider_timeout" | "provider_unavailable" | "rate_limited" | "context_overflow" | "runtime_unavailable" | "unknown";
type ContextEngineHostCapability = "bootstrap" | "assemble-before-prompt" | "after-turn" | "maintain" | "compact" | "runtime-llm-complete" | "thread-bootstrap-projection";
type ContextEngineHostRequirements = {
  /** Host capabilities required before the engine can safely serve this operation. */
  requiredCapabilities: ContextEngineHostCapability[];
  /** Optional engine-authored guidance appended to the host compatibility error. */
  unsupportedMessage?: string;
};
type ContextEngineRuntimeSettings = {
  schemaVersion: 1;
  runtime: {
    host: "openclaw";
    mode: ContextEngineRuntimeMode;
    harnessId: string | null;
    runtimeId: string | null;
  };
  model: {
    requested: string | null;
    resolved: string | null;
    provider: string | null;
    family: string | null;
  };
  contextEngineSelection: {
    selectedId: string | null;
    source: ContextEngineSelectionSource;
  };
  executionHost: {
    id: string | null;
    label: string | null;
  };
  limits: {
    promptTokenBudget: number | null;
    maxOutputTokens: number | null;
  };
  diagnostics: {
    fallbackReason: ContextEngineRuntimeReasonCode | null;
    degradedReason: ContextEngineRuntimeReasonCode | null;
  };
};
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 its own compaction lifecycle. */
  ownsCompaction?: boolean;
  /**
   * Controls how turn-triggered maintenance should be executed.
   *
   * Engines remain compatible by default unless the host explicitly opts into
   * background turn maintenance.
   */
  turnMaintenanceMode?: "foreground" | "background";
  /**
   * Host capability requirements for operations where using an unsupported
   * runtime would silently degrade or corrupt the engine's behavior.
   */
  hostRequirements?: Partial<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 = {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  contextUsage?: {
    state: "available";
    promptTokens: number;
    totalTokens: number;
  } | {
    state: "unavailable";
  };
  total?: number;
};
type ContextEnginePromptCacheObservationChangeCode = "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;
    /** True when the message belongs to a heartbeat run. */
    isHeartbeat?: boolean;
  }): Promise<IngestResult>;
  /**
   * Ingest a completed turn batch as a single unit.
   */
  ingestBatch?(params: {
    sessionId: string;
    sessionKey?: string;
    messages: AgentMessage[];
    /** True when the batch belongs to a heartbeat run. */
    isHeartbeat?: boolean;
  }): Promise<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;
    /** True when this turn belongs to a heartbeat run. */
    isHeartbeat?: boolean;
    /** Optional model context token budget for proactive compaction. */
    tokenBudget?: number;
    /** Optional runtime-owned context for engines that need caller state. */
    runtimeSettings?: ContextEngineRuntimeSettings;
    runtimeContext?: ContextEngineRuntimeContext;
  }): Promise<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;
    isHeartbeat?: boolean;
  }): 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;
  }): 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/plugins/cli-backend.types.d.ts
type CliBackendNoOutputWatchdog = {
  /** Fraction of overall timeout used when fixed timeout is not set. */
  noOutputTimeoutRatio?: number;
  /** Lower bound for computed watchdog timeout. */
  minMs?: number;
  /** Upper bound for computed watchdog timeout. */
  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";
  /** Output parsing mode when resuming a CLI session. */
  resumeOutput?: "json" | "text" | "jsonl";
  /** JSONL event dialect for CLIs with provider-specific stream formats. */
  jsonlDialect?: "claude-stream-json" | "gemini-stream-json";
  /** Long-lived CLI process mode. */
  liveSession?: "claude-stdio";
  /** Prompt input mode (default: arg). */
  input?: "arg" | "stdin";
  /** Max prompt length for arg mode (if exceeded, stdin is used). */
  maxPromptArgChars?: number;
  /** Extra env vars injected for this CLI. */
  env?: Record<string, string>;
  /** Env vars to remove before launching this CLI. */
  clearEnv?: string[];
  /** Flag used to pass model id (e.g. --model). */
  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;
  /** When to pass session ids. */
  sessionMode?: "always" | "existing" | "none";
  /** JSON fields to read session id from (in order). */
  sessionIdFields?: string[];
  /** Flag used to pass system prompt. */
  systemPromptArg?: string;
  /** Flag used to pass a system prompt file. */
  systemPromptFileArg?: string;
  /** Config override flag used to pass a system prompt file (e.g. -c). */
  systemPromptFileConfigArg?: string;
  /** Config override key used to pass a system prompt file. */
  systemPromptFileConfigKey?: string;
  /** System prompt behavior (append vs replace). */
  systemPromptMode?: "append" | "replace";
  /** When to send system prompt. */
  systemPromptWhen?: "first" | "always" | "never";
  /** Flag used to pass image paths. */
  imageArg?: string;
  /** How to pass multiple images. */
  imageMode?: "repeat" | "list";
  /** Where staged image files should live before handing them to the CLI. */
  imagePathScope?: "temp" | "workspace";
  /** Serialize runs for this CLI. */
  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";
  /** Runtime reliability tuning for this backend's process lifecycle. */
  reliability?: {
    /** No-output watchdog tuning (fresh vs resumed runs). */
    watchdog?: {
      /** Fresh/new sessions (non-resume). */
      fresh?: CliBackendNoOutputWatchdog;
      /** Resume sessions. */
      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 = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive" | "max";
type CliBackendExecutionMode = "agent" | "side-question";
/** Exact backend-native plus canonical OpenClaw tool surface for one CLI run. */
type CliBackendToolAvailability = {
  native: 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;
};
/** 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;
  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;
  /** 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 = {
  config?: OpenClawConfig;
  workspaceDir: string;
  provider: string;
  modelId: string;
  authProfileId?: string;
  thinkingLevel?: CliBackendThinkingLevel;
  /** Effective fast mode at spawn, after queue admission and backend preparation. */
  fastMode?: boolean;
  executionMode?: CliBackendExecutionMode;
  toolAvailability?: CliBackendToolAvailability;
  useResume: boolean;
  baseArgs: readonly string[];
};
type CliBackendResolveExecutionArgs = (ctx: CliBackendResolveExecutionArgsContext) => readonly string[] | null | undefined;
type CliBackendResolveModelIdContext = {
  modelId: string;
  contextWindow?: string;
};
type CliBackendJsonlUsage = {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  total?: number;
};
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;
  /**
   * Optional config normalizer applied to the registered adapter.
   */
  normalizeConfig?: (config: CliBackendConfig, context?: CliBackendNormalizeConfigContext) => CliBackendConfig;
  /**
   * Backend-owned final system-prompt transform.
   *
   * Use this for tiny CLI-specific compatibility rewrites without replacing
   * the generic CLI runner or prompt builder.
   */
  transformSystemPrompt?: (ctx: {
    config?: OpenClawConfig;
    workspaceDir?: string;
    provider: string;
    modelId: string;
    modelDisplay: string;
    agentId?: string;
    systemPrompt: string;
  }) => string | null | undefined;
  /**
   * Backend-owned bidirectional text replacements.
   *
   * `input` applies to the system prompt and user prompt passed to the CLI.
   * `output` applies to parsed/streamed assistant text from the CLI.
   */
  textTransforms?: PluginTextTransforms;
  /**
   * Preferred auth-profile id when the caller did not explicitly lock one.
   *
   * Use this when the backend should consume a canonical OpenClaw auth profile
   * rather than ambient host auth by default.
   */
  defaultAuthProfileId?: string;
  /**
   * Session/auth epoch source policy.
   *
   * `combined` keeps the legacy "host credential + auth profile" fingerprint.
   * `profile-only` treats the selected OpenClaw auth profile as the sole auth
   * owner for session invalidation when one is present.
   */
  authEpochMode?: CliBackendAuthEpochMode;
  /**
   * 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;
  /**
   * Exact-tool execution suppresses ambient instruction files, skills, hooks,
   * and plugins so the host-prepared instruction snapshot remains authoritative.
   * Required for rooted runs; omission keeps those runs unavailable.
   */
  isolatesInstructionsWithExactTools?: true;
  /**
   * 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[];
  /**
   * 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;
  /**
   * 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;
  /**
   * 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;
};
/** Plugin-owned CLI backend defaults used by the text-only CLI runner. */
type CliBackendPlugin = CliBackendPluginBase & CliBackendNativeCompactionContract;
//#endregion
export { MessageReceipt as $, CaptureQueryRow as A, resolveAgentDir as B, isDebugProxyGlobalFetchPatchInstalled as C, getDebugProxyCaptureStore as D, closeDebugProxyCaptureStore as E, createDebugProxyWebSocketAgent as F, RealtimeVoiceBrowserSession as G, RealtimeTranscriptionProviderPlugin$1 as H, resolveDebugProxySettings as I, RealtimeVoiceProviderCapabilities as J, RealtimeVoiceBrowserSessionCreateRequest as K, resolveEffectiveDebugProxyUrl as L, CaptureSessionRecord as M, CaptureSessionSummary as N, CaptureEventRecord as O, SharedCaptureBlobRecord as P, ChannelMessageSendTextContext as Q, resolveProviderRequestHeaders as R, finalizeDebugProxyCaptureAsync as S, acquireDebugProxyCaptureStore as T, RealtimeVoiceProviderPlugin$1 as U, PluginLogger$1 as V, RealtimeVoiceBridge as W, ChannelPlugin$1 as X, ImageGenerationProvider as Y, ChannelOutboundAdapter as Z, captureWsEvent as _, ProviderWrapStreamFnContext as a, initializeDebugProxyCaptureAsync as b, OAuthCredentials as c, createProviderHttpError as d, StreamFn as et, readProviderJsonResponse as f, captureHttpExchangeAsync as g, captureHttpExchange as h, ProviderPlugin as i, CaptureSessionCoverageSummary as j, CaptureQueryPreset as k, redactSensitiveText as l, fetchWithSsrFGuard as m, PluginStateSyncKeyedStore as n, AuthProfileCredential as nt, ProviderResolveDynamicModelContext as o, readProviderTextResponse as p, RealtimeVoiceGatewayControl as q, PluginRuntime as r, ProviderAuthContext as s, CliBackendPlugin as t, MediaUnderstandingProvider as tt, formatErrorMessage as u, captureWsEventAsync as v, DebugProxyCaptureStore as w, finalizeDebugProxyCapture as x, initializeDebugProxyCapture as y, createRealtimeTranscriptionWebSocketSession as z };