import { AcpMcpServer } from '@agentproto/acp'; import { SandboxMode } from '@agentproto/command-sandbox'; import { Grant } from '@agentproto/policy'; import { SandboxExecOpts, SandboxExecResult } from '@agentproto/sandbox'; import { z } from 'zod'; import { CatalogProvider } from '@agentproto/model-catalog'; import { ReauthHint } from '@agentproto/auth'; /** * `agent_start({ browser: "headless" })` — an isolated headless Chrome for * one spawned agent, mounted as a per-session stdio MCP server * (`chrome-devtools-mcp --headless --isolated`, see * `@agentproto/plugin-local-browser`'s `buildHeadlessBrowserMcpEntry`). * * The server is a child of the adapter process, so it inherits the session's * `commandSandbox` confinement and normally dies with the adapter (stdin EOF, * and Chrome exits when its pipe closes). On `session:exited`, * `sweepSessionBrowser` does two things: * - kills anything still carrying the session's `--agentproto-session=` * Chrome marker, in case an adapter never exited or never closed its MCP * children; * - deletes the session's profile dir, `$TMPDIR/agentproto-browser/`. * The profile is caller-owned rather than `--isolated`, because `--isolated` * only cleans up on a graceful `browser.close()`; observed live, a killed * session left its puppeteer temp profile behind. */ /** `agent_start.browser`. `false` (the default) mounts nothing. */ type SpawnBrowserMode = "headless" | false; interface HeadlessBrowserMount { entry: AcpMcpServer; /** Read grants the adapter's `commandSandbox` needs for the MCP server + * Chrome (threaded as `additionalReadPaths`). */ readPaths: string[]; } interface ResolveHeadlessBrowserInput { sessionId: string; cwd: string; /** The spawn's explicit `commandSandbox`; `undefined` falls back to the * workspace's `adapterSpawn` config, like the driver does. */ commandSandbox?: SandboxMode; } type ResolveHeadlessBrowser = (input: ResolveHeadlessBrowserInput) => Promise; /** * AIP-46 delegation gate, observe first. * * The spawn authority for a nested spawn is the CALLING session's bound * agent `delegatesTo` (a closed allowlist, deny by default), resolved from * the caller's trusted identity. This module owns the pure decision, the * mode type, and the process-wide observer that counts what the gate would * refuse before an operator turns enforcement on. * * The observer is a module-level singleton on purpose: `spawnAgentSession` * is reached from agent-tools, http-server, session-tools and cron, which * share no object. Counters live in memory (a restart resets them); the * `console.warn` line for a would-deny pair is the durable record. */ type DelegationGateMode = "off" | "observe" | "enforce"; /** What the gate concluded for one spawn. */ type DelegationVerdict = "allowed" | "would_deny" | "undeclared" | "unbound" | "no_caller"; interface DelegationReport { mode: DelegationGateMode; /** ISO time this process started counting (resets on a restart: counters are in memory). */ since: string; counts: Record; /** would_deny pairs, most frequent first, at most 50: caller agent -> child agent. */ wouldDeny: Array<{ callerAgent: string; childAgent: string; count: number; lastAt: string; }>; /** unbound/undeclared callers by agent slug (or "(none)"), at most 50, most frequent first. */ undeclaredAgents: Array<{ agent: string; count: number; }>; } /** * Canonical context-continuity policy for long-running agent sessions. * * Provides a deterministic, testable policy engine with safe defaults and a * clear override order: global defaults → per-harness defaults → * per-model defaults → session override. The policy drives warnings, * opportunistic compaction, fresh continuation, and hard-stop decisions at * turn boundaries so sessions never silently run into the model context * limit. */ /** * `manual` suppresses every automatic *nudge* (warn/compact/continue-fresh — * see `contextContinuityNextAction`) so the session is left alone until the * caller acts. It does NOT suppress the floor (`hard-stop` state): that is an * unconditional safety net, independent of mode — its purpose is to stop a * session from silently running past the model's real context window * (further prompts would be truncated/rejected by the provider, or corrupt * the conversation) even when nothing is watching. * * The floor is a trigger, not an exit: the runtime first compacts the session * itself (checkpoint, then `/compact`), continues it fresh when that did not * free the window, and only ends it when neither is possible — always * announcing the outcome (`session:context-rescue`). A session that wants to * opt out of the floor should set `hardStopAtPct` above what it will ever * reach, not rely on mode. */ type ContextContinuityMode = "manual" | "ask" | "auto"; interface ContextContinuityThresholds { /** Percentage at which the UI first warns that context is filling. */ warnAtPct: number; /** Percentage at which an opportunistic compact may be attempted. */ compactAtPct: number; /** Percentage at which a fresh continuation session is created. */ continueFreshAtPct: number; /** Percentage above which no new prompt may be admitted. */ hardStopAtPct: number; } interface ContextContinuityCheckpointSections { goal: boolean; plan: boolean; decisions: boolean; changedFiles: boolean; gitStatus: boolean; tests: boolean; errors: boolean; risks: boolean; nextStep: boolean; config: boolean; } /** * User-supplied policy fragment. Every field optional; missing values are * filled from the next precedence layer or from safe defaults. */ interface ContextContinuityPolicy extends Partial, Partial { mode?: ContextContinuityMode; /** * Absolute token threshold for autocompact: when an IDLE session's * context reaches this many tokens, the daemon compacts it (the same * `/compact` path as `session_compact`) and, when a mission is in * progress, injects a short resume prompt. * * Window-independent by design: the percent ladder above never fires on * a 1M-token context (558k of 1M is "55% full", the warn band), so a * session can grow without ever compacting. An absolute count does not * care how big the window is. * * Clamped into `[1000, 600000]`; `0` disables autocompact. Unset = the * default: `max(150k, warnAtPct% of the window)`, so a 1M window compacts * at 550k, not 150k (see `resolveAutoCompactTokens`). */ autoCompactAtTokens?: number; /** Optional display label for UIs. */ label?: string; /** Suggest a cross-harness handoff (`session:handoff-suggested`) once the * provider-reported remaining quota of the session's auth profile falls to * or below this number. Same unit as the `remaining` figure * `usage_rollup` shows per profile (Anthropic's unified rate-limit * header — a count, not a percentage: the header carries no limit to * divide by). Unset = disabled. Suggestion only, never a switch. */ handoffAtQuotaRemaining?: number; /** When true, a context-losing compaction prompt (`/compact`, `/compress`) * is admitted only from the operator (a source-less prompt: HTTP, CLI, * UI). One attributed to a session (`agent:` — `agent_prompt`, * `session_compact`, including the session itself) is refused. For a * session whose compaction needs a human's agreement (the Orchestrator * brain), so it can't be bypassed by a prompt-level self-compact. Unset * = false. */ compactRequiresOperator?: boolean; /** When true, a `/compact` or `/compress` prompt asks the live session for * a handoff turn (its own goal/decisions/risks) before the checkpoint is * built, then the harness's native compaction runs on the same session. * Unset = false: the checkpoint is extracted from the transcript alone, * with no billed model turn before compaction. The context-rescue path * (`runtime:context-rescue`) never asks. Unchanged explicit handoffs * (`session_checkpoint`, `session_continue_fresh`) still ask. */ compactHandoffTurn?: boolean; } /** * The AIP-46 name of the context-settings block. `contextContinuity` is the * legacy spelling of the same block (AIP-70 section 4 alias). */ type ContextSettings = ContextContinuityPolicy; /** * Layer context settings, lowest layer first. Each setting is its own axis * (AIP-46 §Session context rule 4): the highest layer that sets a key wins * for that key, and the other keys of a lower layer stay in force. An * undefined layer and a key whose value is undefined are skipped. Returns * undefined when no layer is given, so callers keep their "no policy" case. */ declare function layerContextSettings(...layers: ReadonlyArray): ContextSettings | undefined; /** * Fully-resolved, validated policy. This is the shape stored on a session * descriptor and returned by status queries. */ interface ResolvedContextContinuityPolicy extends ContextContinuityThresholds, Required { mode: ContextContinuityMode; /** See {@link ContextContinuityPolicy.autoCompactAtTokens} (clamped). * Optional so a policy persisted before autocompact existed still * deserialises; absent = the window-scaled default. */ autoCompactAtTokens?: number; /** Effective label (falls back to mode when absent). */ label: string; /** See {@link ContextContinuityPolicy.handoffAtQuotaRemaining}. */ handoffAtQuotaRemaining?: number; /** See {@link ContextContinuityPolicy.compactRequiresOperator}. */ compactRequiresOperator?: boolean; /** See {@link ContextContinuityPolicy.compactHandoffTurn}. */ compactHandoffTurn?: boolean; } /** * AIP-46 stdio mount gate, observe first. * * A spawn may mount MCP servers (`agent_start.mcpServers`). A `stdio` * entry names an arbitrary command the agent CLI launches, so it is * command execution outside `.agentproto/allowed-commands.json` unless * something evaluates it. This module owns the pure decision, the mode * type, and the process-wide observer that counts what the gate would * refuse before an operator turns enforcement on. * * Only the entries the REQUEST names are evaluated: presets, AGENT.md, * bundles, config and the daemon's own injected mounts are operator or * author configuration, not a request. A spawn with no trusted caller * (root spawn, continue-fresh, restart, migrate, cron, retries) is * authorised by the host itself and never gated. A sandboxed spawn runs * the `stdio` server inside the box, so the host allowlist does not apply. * * The observer is a module-level singleton on purpose: `spawnAgentSession` * is reached from agent-tools, http-server, session-tools and cron, which * share no object. Counters live in memory (a restart resets them); the * `console.warn` line for a would-deny command is the durable record. * Args, env and the full `ref` path never reach the log or the report. */ type StdioMountGateMode = "off" | "observe" | "enforce"; /** * `turnRetry` spawn option — the policy SHAPE only (zod schema, type, * defaults, tolerant parser). Kept free of any `sessions.ts` import so the * descriptor, the `agent_start` schema, the HTTP body parser, and the user * preset store can all share it without an import cycle. The behaviour lives * in `turn-retry.ts`. * * OFF by default for interactive supervisor sessions and ON by default for * executor / sandbox spawns: a spawn without `turnRetry` gets the DEFAULT * policy below (see {@link defaultTurnRetryForSpawn}), while a supervisor * turn that fails on a 429/5xx, or stalls silently while the provider * retries internally, just stops. DISTINCT from `restartPolicy`, * which revives a DEAD process; `turnRetry` re-prompts a LIVE session whose * last turn failed for a transient provider reason. */ /** Turn-failure classes `turnRetry.on` can opt into. */ declare const TURN_RETRY_CLASSES: readonly ["rate-limit", "upstream-5xx", "no-output-stall", "usage-limit"]; type TurnRetryClass = (typeof TURN_RETRY_CLASSES)[number]; /** What a matching failure does. `retry` (the default) re-prompts the same * live session after backoff; `migrate` moves a SANDBOX session to a fresh * box (new IP) and re-prompts it there — see `turn-retry.ts`. */ declare const TURN_RETRY_ACTIONS: readonly ["retry", "migrate"]; type TurnRetryAction = (typeof TURN_RETRY_ACTIONS)[number]; interface TurnRetryPolicy { /** Which transient failure classes trigger a retry: * - `rate-limit` — HTTP 429 / "rate limit" / "too many requests"; * - `upstream-5xx` — HTTP 5xx / "overloaded" / "bad gateway" / "endpoint unavailable" / * "at capacity; retry shortly" / a network-level failure (EPROTO "TLS * handshake failed", ECONNRESET, ETIMEDOUT, EPIPE, EAI_AGAIN, "socket * hang up") …; * - `no-output-stall` — the stall watchdog flagged a turn that produced * nothing since its prompt (`NO_OUTPUT_STALL_TURN_ERROR`, the opencode * silent-429 loop). That turn is still running, so the retry interrupts * it before re-prompting; * - `usage-limit`: a provider usage cap ("Free usage limit reached", * "usage limit exceeded"). Opt-in only (never in the default set): a cap * does not recover with backoff, so there is NO same-config retry. The * session moves straight to `rotate` / `fallback` (or, with * `action: "migrate"`, a fresh box = a new IP, the fix for a per-IP cap) * and gives up when none of those is available. */ on: TurnRetryClass[]; /** What a matching failure does: `retry` re-prompts the same live session * after backoff; `migrate` moves a sandbox session to a fresh box (new IP) * and re-prompts it there. Default `retry` — fully backward compatible. */ action: TurnRetryAction; /** Consecutive retries allowed without a clean turn in between. */ maxRetries: number; /** Box migrations allowed without a clean turn in between (action `migrate` * only). Independent of `maxRetries`: once the cap is spent the failure * falls back to a normal retry / give-up. Non-negative — `0` means the * migrate action never migrates. Default {@link TURN_MIGRATE_DEFAULTS}. */ maxMigrations: number; /** First retry's backoff delay (ms), before `factor` compounds it. */ baseDelayMs: number; /** Exponential backoff multiplier per consecutive retry. */ factor: number; /** Backoff ceiling (ms). Also caps a provider `retry-after` hint. */ maxDelayMs: number; /** Retry even when the failed turn already made a tool call that may have * side effects (anything not provably read-only, see * `read-only-tool-call.ts`). Default * false: such a turn is NOT retried, because the continuation could * repeat a write/exec the agent already did. */ retryAfterToolCalls?: boolean; /** Ordered fallback models. When a retry fires for a class in `rotateOn`, * the session is switched (live, before the continuation prompt) to the * first target that is not cooling down and passes the eligibility checks. * v1 switches the model on the session's CURRENT profile only: a target * naming a different `profileRef` is skipped. Absent ⇒ never rotate. */ rotate?: TurnRetryRotateTarget[]; /** Classes that rotate (must be a subset of what `on` retries). Default * `rate-limit` + `no-output-stall` (+ `usage-limit` when `on` lists it); add * `upstream-5xx` to rotate on those too. */ rotateOn?: TurnRetryClass[]; /** How long a rate-limited model is skipped, daemon-wide, when the error * carries no retry-after hint (ms). Default {@link TURN_ROTATE_DEFAULTS}. */ cooldownMs?: number; /** Ordered config overlays tried after same-config retries are exhausted. * Each overlay is merged over the session's BASE (spawn) config; the first * eligible one is applied with the least disruptive transition. `rotate` * is the model-only special case. Absent ⇒ no fallback chain. */ fallback?: TurnRetryFallbackOverlay[]; } /** One overlay of `turnRetry.fallback`. Omitted axes keep the base value. */ interface TurnRetryFallbackOverlay { model?: string; access?: { profileRef: string; }; harness?: string; } /** One fallback target of `turnRetry.rotate`. */ interface TurnRetryRotateTarget { model: string; /** Billing profile the target must run under. v1: must equal the session's * current profile (or be omitted = "the current profile"). */ profileRef?: string; } /** Input shape (agent_start / user preset): only `on` is required; the * numeric knobs default to {@link TURN_RETRY_DEFAULTS}, `action` to `retry` * and `maxMigrations` to {@link TURN_MIGRATE_DEFAULTS}. Opt-OUT stays an * explicit choice: `null`, or an object whose `on` list is empty, resolves * to a session that never retries (the spawn-time default is skipped for * an explicit `turnRetry`, even a disabling one). */ declare const turnRetryObjectSchema: z.ZodObject<{ on: z.ZodArray>; action: z.ZodOptional>; maxRetries: z.ZodOptional; baseDelayMs: z.ZodOptional; factor: z.ZodOptional; maxDelayMs: z.ZodOptional; maxMigrations: z.ZodOptional; retryAfterToolCalls: z.ZodOptional; rotate: z.ZodOptional; }, z.core.$strip>>>; rotateOn: z.ZodOptional>>; cooldownMs: z.ZodOptional; fallback: z.ZodOptional; access: z.ZodOptional>; harness: z.ZodOptional; }, z.core.$strip>>>; }, z.core.$strip>; type TurnRetryPolicyInput = z.infer; type TurnRetryInput = TurnRetryPolicyInput | null; /** * BOX LOGIN BRIDGE (phase 1: codex + opencode) — pure derivation of the login * file a HOST hands to a sandbox BOX. * * A box boots with a fresh filesystem, so a FILE-BASED ("external") login the * host verifies fail-loud (`verifyLocalLoginPresent`) is simply absent there: * the box re-verifies its OWN `~/.codex/auth.json` / `~/.local/share/opencode/ * auth.json` and refuses to spawn. This module builds the REDACTED copy the * host uploads before `host.start()`, and NOTHING else — no I/O, no recipe * reads (the raw JSON is a parameter), so every rule here is unit-testable * against plain strings. * * The rules, in order: * 1. **Keep-list** — only the adapter-declared dotted paths survive * (`boxLogin.keep`), so a copy never carries the host's other accounts, * API keys, or provider entries the spawn does not bill through. * 2. **UNCONDITIONAL deny** — a refresh-like key never carries material into * the box, even when the keep-list names it: an exact-kept refresh key * survives as an EMPTY STRING (codex's parser requires the field to * exist; `""` parses and the CLI then fails loud), and everything else * refresh-shaped is dropped — including from kept SUBTREES, so * `keep: ["tokens"]` still yields no refresh material. * 3. **Home-relative destination** — the box path is derived from the * recipe's own `~/…` file (or an explicit `file`), validated to be * home-relative: absolute paths and `..` segments are rejected rather * than written outside the box's home. * 4. **Expiry** — `expiresPath` is parsed (epoch seconds/ms or a date * string); an already-expired login is refused so a dead copy is never * mistaken for a working one. * 5. **Digest** — sha256 of the exact body, the change gate the refresh path * compares against before re-uploading. * * A failed result DEGRADES to today's behaviour (no copy written ⇒ the box's * own fail-loud verify runs) — never a silent unauthenticated spawn. No result * ever contains a token: messages name the FILE only. */ /** The adapter's `authSubscription.boxLogin` declaration — which recipe holds * the host's login, which method selects its surface, and what survives into * the copy. Carried across the driver manifest → runtime descriptor boundary * by SHAPE (each package owns its own copy — see the driver's mirror in * `AgentCliAuthSubscription`). */ interface BoxLoginDecl { /** Provision-recipe id whose source is the login file (`"codex"`, * `"opencode"`, …). Also the source of the destination path when * {@link file} is absent. */ recipe: string; /** Recipe method selecting the SURFACE for a multi-login adapter * (opencode: `anthropic-oauth` / `openai-oauth`). Falls back to the * recipe's default (first) method. */ methodId?: string; /** Dotted paths of the raw JSON that survive into the copy — the whole * allowlist; everything else is dropped. A path naming a deny-listed key * (or leading to a subtree that contains one) still loses that key. */ keep: string[]; /** Dotted path of the login's expiry inside the raw JSON (epoch seconds, * epoch millis, or a date string). Absent ⇒ no expiry gate. */ expiresPath?: string; /** Home-relative destination inside the box (`.codex/auth.json`). Absent ⇒ * derived from the recipe method's own `file` source. */ file?: string; } /** * The adapter's own conversation store, checkpointed with the box. * * A sandbox session's adapter conversation lives INSIDE the box, under the * box daemon's per-session isolated adapter-config dir * (`~/.agentproto/adapter-config/` — claude-code's * `projects//.jsonl`, an OS-confined codex's `CODEX_HOME` * rollouts, an engaged-credential opencode's isolated `opencode.db`, the * session's imported skills, …). The git checkpoint (`sandbox-delivery.ts`) * carries the WORK; this module carries the CONVERSATION. Without it, a * restart that moves to a fresh box re-clones the code but the adapter * starts blank — the store died with the old box. * * Two halves, mirroring `sandbox-tar-checkpoint.ts`: * - {@link archiveAdapterStore} — checkpoint time (box still alive): pack * the session's isolated config dir in the box, pull the archive to the * host next to `checkpoint.json`. Never throws; the outcome is a record * (`saved`/`skipped`/`failed`) stamped onto the checkpoint record. * - {@link restoreAdapterStore} — fresh-box restart: upload the saved * archive and extract it at the same (home-relative) path BEFORE the new * box's adapter starts, so the box daemon's resume can find the * conversation again. * * Only THIS session's store is archived: the isolated config dir is keyed by * the session's own box-side id (`SessionDescriptor.adapterSessionId` on a * sandbox row is exactly that id — the proxy's `sessionId` is the box * daemon's remote session id). Adapters that ignore the isolated dir and keep * a shared global store (hermes' `~/.hermes/state.db`, a non-confined * codex's `~/.codex`, …) have nothing per-session to ship — their store is * simply absent here, and a restart falls back to the digest handoff as * before. */ type AdapterStoreStatus = "saved" | "skipped" | "failed"; /** Checkpoint-record entry for the archived conversation store. */ interface AdapterStoreRecord { status: AdapterStoreStatus; /** Host path of the downloaded archive — present iff `saved`. */ path?: string; adapter?: string; /** The box-side session id the store is keyed by (a sandbox row's * `adapterSessionId` is exactly this id). */ adapterSessionId?: string; bytes?: number; detail?: string; } /** * Get a sandbox session's work out of the box before the box is torn down. * * Runs from the sandbox proxy's `close()`, after the box's agent session is * killed and before the box is stopped or paused, and also as a periodic * CHECKPOINT while the session is alive (`mode: "checkpoint"`: on a timer, at * each turn end, and once more when the box daemon stops answering) — a box * can die outside `close()` (an OOM-killed daemon, an expired VM), and work * that only ever left the box at teardown died with it. For a session that * has a work branch (`wt/`, cut by `sandbox-workspace-remote`): * * 1. probe how many commits the branch is ahead of its recorded base, and * snapshot any UNCOMMITTED work as a commit object (built through a * throwaway index: the agent's index, worktree and branch are never * touched) parked at {@link SNAPSHOT_REF}; * 2. push the branch to `origin` when it is ahead, and force-push the * snapshot to `agentproto-checkpoint/` when there is one; * 3. when a push did not land (or could not be tried), `git bundle` the * `base..tip` range and pull it to the host as a safety net; * 4. when the checkout is clean (no snapshot this run) and the work branch * is safe on the remote, delete the now-stale `agentproto-checkpoint/ * ` so it does not pile up on the remote forever. * * A checkpoint additionally carries the adapter's CONVERSATION store: the * box-side pack/download in `sandbox-adapter-store.ts` archives the session's * isolated adapter-config dir next to `checkpoint.json` as * `adapter-store.tar.gz` (recorded on {@link SandboxDeliveryRecord.adapterStore}), * so a restart that moves to a fresh box can put the conversation back * (`session-restart-core.ts`'s `spawnOnFreshBox`) instead of starting the * adapter blank. A store failure never fails the checkpoint. * * A fresh box checking the same branch out again (`sandbox-workspace-remote`) * picks the pushed branch up and re-applies the checkpoint snapshot as * uncommitted changes, so a restart on a new box resumes where the dead one * stopped. * * Every outcome is reported, never thrown: teardown must not be blocked by a * delivery problem, and the record is what tells a human where the work is. * No token is handled here — pushes rely on the credential helper set up at * clone time. */ interface SandboxDeliveryTarget { checkoutDir: string; /** `wt/` */ branch: string; /** Commit the branch was cut from. */ baseSha: string; } type DeliveryPushStatus = "pushed" | "skipped" | "failed"; type DeliveryBundleStatus = "saved" | "skipped" | "failed"; interface SandboxDeliveryRecord { at: string; branch: string; baseSha: string; /** Commits on the branch beyond the base; absent when the probe failed. */ ahead?: number; /** Uncommitted paths in the checkout. Delivered only through * {@link checkpoint} — absent there, they stayed in the box. */ uncommittedFiles?: number; /** `"checkpoint"` for a periodic snapshot taken while the session runs; * absent for the teardown delivery. */ mode?: "checkpoint"; push: { status: DeliveryPushStatus; detail?: string; }; /** Snapshot of the uncommitted work, force-pushed to * `agentproto-checkpoint/`. Absent when the checkout was clean. */ checkpoint?: { status: DeliveryPushStatus; ref: string; sha?: string; detail?: string; }; /** Best-effort deletion of the checkpoint branch, once the checkout was * clean and the work branch was safe on the remote — see * {@link buildCheckpointDeleteCommand}. Never blocks teardown. */ checkpointCleanup?: { status: "deleted" | "absent" | "failed"; ref: string; detail?: string; }; /** Identity of the delivered state (HEAD, snapshot tree, ahead count): a * checkpoint whose key matches the previous fully-delivered one skips the * pushes. Absent when the probe failed. */ key?: string; /** True when a checkpoint found nothing new since the last delivered one. */ unchanged?: boolean; bundle: { status: DeliveryBundleStatus; path?: string; bytes?: number; detail?: string; }; /** Checkpoint-mode only: the adapter's conversation store, archived next * to the record as `adapter-store.tar.gz` so a fresh-box restart can * restore it (see `sandbox-adapter-store.ts`). Absent on teardown * deliveries and on a checkpoint taken without an * {@link RunSandboxDeliveryInput.adapterStore} input. */ adapterStore?: AdapterStoreRecord; /** Teardown-only: outcome of the `Agentproto-Session:` provenance stamp * on the work branch (see {@link buildProvenanceStampCommand}). Absent * when no stamp was attempted (no session id, checkpoint mode, nothing * ahead, or the uncommitted-work snapshot already carries the trailer , * `"skipped"` then). Attribution only: never part of * {@link isFullyDelivered}. */ provenanceStamp?: { status: "stamped" | "failed" | "skipped"; detail?: string; }; /** Turn count this checkpoint/delivery was taken after, when the caller * knew one (`sandbox-agent-session-proxy.ts`'s `turnsSent`) — also baked * into the snapshot commit message. Absent when no turn context was * given (a bare periodic tick, or a call outside the proxy). */ turn?: number; } /** * `defaults.sandbox.checkpoint` / `agent_start({ sandboxCheckpoint })` — the * daemon-config/per-spawn knob replacing the single * `AGENTPROTO_SANDBOX_CHECKPOINT_INTERVAL_MS` env var with a composable * object. See {@link resolveSandboxCheckpointConfig} for the global → * per-spawn precedence. */ interface SandboxCheckpointConfig { /** Master switch. Default true. */ enabled?: boolean; /** Which triggers take a checkpoint. `"turn-end"` wires the per-turn hook * (a snapshot after each turn the proxy completes); absent, turns end * uncheckpointed. `"interval"` wires the PERIODIC timer — every * {@link SandboxCheckpointConfig.intervalMs} of the session's life a * snapshot is taken DURING a turn too, so a turn longer than the box * lifetime is not lost with it (a time-based trigger, as opposed to * `turn-end`'s event-based one). `"turn-end"` ALSO wires the timer (the * pre-`"interval"` behaviour — an explicit `["turn-end", "teardown"]` * keeps mid-turn checkpointing across an upgrade); `"interval"` is for a * timer WITHOUT the per-turn hook. `"teardown"` makes the teardown * delivery SNAPSHOT uncommitted work (not just count it, {@link * buildProbeCommand}'s `snapshotUncommitted`); absent, teardown still * pushes the branch but leaves uncommitted work in the box * uncounted-for-rescue, matching the pre-checkpoint behaviour. * Default all three. */ on?: Array<"turn-end" | "teardown" | "interval">; /** Remote branch namespace the snapshot is force-pushed to * (``). Default {@link CHECKPOINT_BRANCH_PREFIX} — * changing this only affects a FUTURE checkpoint; see * {@link checkpointBranchOf}. */ refPrefix?: string; /** Periodic-checkpoint timer interval (replaces * `AGENTPROTO_SANDBOX_CHECKPOINT_INTERVAL_MS`). Default * {@link DEFAULT_CHECKPOINT_INTERVAL_MS}. */ minIntervalMs?: number; /** Preferred spelling of {@link SandboxCheckpointConfig.minIntervalMs} — * the periodic-checkpoint timer interval; wins over it when both are * set (they exist because the periodic dial predates the `on: ["interval"]` * trigger that names it properly). Same default. */ intervalMs?: number; /** Per-checkpoint wall-clock budget (`runSandboxDelivery`'s `deadlineMs`). * Default {@link DEFAULT_CHECKPOINT_DEADLINE_MS}. */ timeoutMs?: number; } /** * Turn retry: re-prompt a LIVE session whose last turn failed for a * transient provider reason, opt-in via `agent_start.turnRetry`. * * The gap it closes (observed on free OpenCode Zen models, 2026-10-11): when * a provider answers 429/5xx mid-turn, the session just stops — either the * harness ends the turn in-band with an error (`lastTurnErrorMessage` set, * session idle), or opencode swallows the 429 into a silent internal retry * loop and the stall watchdog only marks it (`markStalled` → * `NO_OUTPUT_STALL_TURN_ERROR`). `restartPolicy` does not help: the process * is alive, nothing crashed. * * Shape mirrors `restart-scheduler.ts`: pure halves (`classifyTurnError`, * `decideTurnRetry`, `computeTurnRetryDelayMs`) plus an event-driven * controller (`createTurnRetryController`) that only talks to the registry * through a narrow structural slice. The controller: * - on `session:turn-end` with `reason:"error"` → classify the error and, * when eligible, schedule a continuation prompt after backoff; * - on `session:stalled` whose row carries the no-output marker → schedule * an interrupt + continuation prompt after backoff (the stuck turn is * still running, so `enqueuePrompt({interrupt:true})` cuts it first); * - on a clean `session:turn-end` → reset the retry counter; * - on `session:stall-cleared` / `session:exited` / any newer turn-end → * drop a pending retry; `policy:failed` halts retries for the session. * * A retry reports `sent` only once its continuation prompt has PASSED * admission (`enqueuePrompt` rejects a concurrent prompt, a killed session, * a failed resume): a rejected admission rolls the booked attempt back — it * costs nothing against `maxRetries` — and emits `cancelled` instead, with the * same `[turn-retry]` transcript notice every other transition carries. * * Rotation (`turnRetry.rotate`): instead of re-prompting the model that was * just throttled, the controller first switches the live session to the next * fallback target (`registry.setModel` — the `agent_set_model` path), then * sends the continuation. A rate-limited / silently-stalled model is recorded * in a DAEMON-WIDE cooldown map (the free-tier limit is per model per IP, so * it binds every session), and rotation skips cooling models. A free session * only ever rotates onto free ids. With no eligible target the retry falls * back to today's same-model behaviour and says so in the `[turn-retry]` * notice. v1 switches the model on the session's current profile only. * * Migration (`turnRetry.action: "migrate"`): a matching failure on a SANDBOX * session moves the session to a fresh box — a new IP, the same workspace * branch, the transcript carried over — via the injected `migrateSession` * orchestration (PR 2's `session_migrate`, called in-process, not over MCP), * then re-prompts "continue" on the migrated session. A non-sandbox session * and a spent `maxMigrations` cap both fall back to a normal retry, with a * `[turn-retry]` notice explaining why; a migration that fails leaves the old * session untouched and falls back to a normal retry as well — or reports * exhaustion and gives up, when the retry budget is already spent too. * * Usage cap (`usage-limit`, opt-in via `turnRetry.on`): a provider usage cap * (OpenCode's free tier is capped per source IP) does not recover with * backoff, so there is no same-config retry. The session goes straight to * `rotate`, then `fallback`; with `action: "migrate"` on a sandbox session it * first moves to a fresh box (a new IP is the fix for a per-IP cap). On a * sandbox session `rotate` and the model overlay of `fallback` both use the * restart transition (the box has no live model switch). With none of those * available it gives up, exactly as a session that never opted in. An opted-in * usage cap is held to the same tool-call gate as every other class: a turn * that already made a side-effecting call is not continued unless * `retryAfterToolCalls`. Without the opt-in a usage cap still walks the * `fallback` chain, as before. * The capped model is recorded in the same daemon-wide cooldown map a * rate-limited one is. * * NEVER retries: an interrupted turn (user Stop, `interrupt:true` prompt), a * killed / exited / errored session (kill, `maxCostUsd` cost-cap kill — the * process-death path belongs to `restartPolicy`), a session with a failed * governance policy (the windowed `costBudget` trips one), an auth error * (401/403, a bad key: the account is broken, not spent), a provider usage cap * or empty wallet (402, "insufficient balance": both `usage-limit`) unless `usage-limit` is opted * into (and then never on the same config), or a turn that already made a * tool call outside the read-only allowlist (unless `retryAfterToolCalls`). * * Pending retries are in-memory timers: a daemon restart drops them (and the * controller clears any stale `nextTurnRetryAt` at startup). A turn cut by a * daemon restart is the continue-interrupted path's job, not this one's. */ /** Classes a turn error can fall into. The retryable ones (`TurnRetryClass`) * act only when listed in `turnRetry.on`; `auth` and `other` never do. */ type TurnErrorClass = TurnRetryClass | "auth" | "usage-limit" | "other"; /** * Sandbox preflight probes: cheap checks that run against a freshly booted * box BEFORE the agent starts, so a placement that cannot work is discovered * in seconds instead of mid-run. * * Motivating failure: OpenCode's free tier is capped per SOURCE IP, and fleet * boxes can share one egress IP, so a box booted on an exhausted address * answers its first model call with "Free usage limit reached" and the run * dies. Asking the box to answer one line first turns that into a typed * spawn failure (`sandbox_preflight_failed`) a caller can act on. * * A probe is an `id` plus a `run(ctx)` that reaches the box through the same * exec seam `sandbox_exec` uses (`BootedSandbox.exec`). It answers one of: * - `ok` the box passes this check; * - `ko` the box demonstrably cannot do the thing (carries the * {@link TurnErrorClass} from `classifyTurnError`, so a probe and * a live turn speak the same classes); * - `unknown` the probe could not decide (timeout, missing binary, provider * without exec, unclassified failure). NEVER treated as `ko`: * a probe that cannot run must not veto a placement. * * Probes live in a registry keyed by id, so a new criterion is an addition, * not an edit. {@link runSandboxPreflight} runs a list of ids in order and * stops at the first `ko`; the spawn path (`bootSandboxAgentSession`) tears * the box down on that and fails with {@link preflightFailedResult}. The * outcome list and the failure details are plain data on purpose: a placement * ladder can run the same probes, read the same `outcomes`, and move to the * next rung on `sandbox_preflight_failed` without reshaping any of this. */ type PreflightVerdict = "ok" | "ko" | "unknown"; /** What a probe reports about one box. */ interface PreflightResult { verdict: PreflightVerdict; /** Set on `ko`: the class `classifyTurnError` gave the failure text. */ errorClass?: TurnErrorClass; /** One human-readable line (bounded); never a secret. */ detail: string; durationMs: number; } /** What a probe may touch. Everything is optional-by-capability except `exec`. */ interface PreflightContext { /** Run one command in the box: `BootedSandbox.exec`, i.e. what `sandbox_exec` calls. */ exec: (opts: SandboxExecOpts) => Promise; /** The adapter slug the session will run (`opencode`, `claude-code`, ...). */ adapter: string; /** The model the session will use, when the spawn named one. */ model?: string; /** A directory that exists in the box (the provider's home), when known. */ cwd?: string; /** Public source address the box egresses from, when the provider brokers one. */ egressIp?: string; /** Wall-clock budget for this probe; the runner enforces it too. */ timeoutMs: number; } /** * When a probe can run, relative to the agent's own `agent_start`. * * - `prelaunch` runs before the agent starts, through `host.exec`, and needs * no credentials (a package is installed, an address is not capped for * everyone). It always runs, authed spawn or not. * - `postlaunch` needs the session's credentials, which reach the box only * through its own `agent_start`, so it can only run through the started * session (see the seam comment in `session-spawn.ts`). */ type PreflightPhase = "prelaunch" | "postlaunch"; interface PreflightProbe { id: string; description: string; /** Hard budget in ms when the caller does not override it. */ defaultTimeoutMs: number; /** When the probe can run; defaults to `prelaunch`. */ phase?: PreflightPhase; run(ctx: PreflightContext): Promise>; } interface PreflightRegistry { register(probe: PreflightProbe): void; get(id: string): PreflightProbe | undefined; list(): PreflightProbe[]; } /** * A probe declared in config (`defaults.sandbox.preflight.probes`): run one * shell command in the box and turn its result into a yes/no. Nothing in it is * specific to a harness or provider, so any "does this box have X" check is a * config entry, not code. */ interface CommandProbeSpec { id: string; description?: string; command: string; /** Exit code that means yes. Default 0. */ okExitCode?: number; /** Regex the stdout must match to count as yes. */ okStdoutMatches?: string; /** Output patterns that are a definite no, each with the class a caller (and the egress cooldown ledger) sees. */ koWhen?: Array<{ match: string; errorClass?: "usage-limit" | "rate-limit" | "auth" | "other"; }>; /** What a result that is neither yes nor a `koWhen` hit means: `unknown` (default, never vetoes) or `ko`. */ failAs?: "ko" | "unknown"; timeoutMs?: number; /** When the probe can run; defaults to `prelaunch`. See {@link PreflightPhase}. */ phase?: PreflightPhase; /** * @deprecated Use `phase` instead. `true` maps to `prelaunch`, `false` maps * to `postlaunch`; when absent a config probe defaults to `prelaunch`. */ runsWithSpawnAuth?: boolean; } /** * AIP-46 auth-profile gate, observe first. * * A spawn may name an auth profile (`access.profileRef` / `access.profileRefs`). * The spawn authority is the CALLING session's own profile set: its recorded * `accessProfile.profileRef` plus the operator-configured * `defaults.spawn.sharedProfiles`. This module owns the pure decision, the * mode type, and the process-wide observer that counts what the gate would * refuse before an operator turns enforcement on. * * The observer is a module-level singleton on purpose: `spawnAgentSession` * is reached from agent-tools, http-server, session-tools and cron, which * share no object. Counters live in memory (a restart resets them); the * `console.warn` line for a would-deny pair is the durable record. */ type ProfileGateMode = "off" | "observe" | "enforce"; /** What the gate concluded for one spawn. */ type ProfileVerdict = "allowed" | "would_deny" | "unnamed" | "no_caller" | "caller_unknown" | "external"; interface ProfileReport { mode: ProfileGateMode; /** ISO time this process started counting (resets on a restart: counters are in memory). */ since: string; counts: Record; /** would_deny pairs, most frequent first, at most 50: caller profile -> requested profile. */ wouldDeny: Array<{ callerProfile: string; requestedProfile: string; count: number; lastAt: string; }>; } /** * Deferred/lazy MCP tool loading (harness-parity item 3). * * Motivation: a root `/mcp` session sees every tool the daemon registers — * today that's 60+ tools across families (agent_*, session_*, policy_*, * routine_*, workflow_*, terminal_*, command_*, file_*, directory_*, * browser_*, tunnel_*, mcp_*, inbound_watcher_*) — all with full schemas, * loaded upfront, whether or not the session ever touches most of them. * * NB: imported third-party MCP servers (`mcp_import`) do NOT have this * problem — they're already proxied behind `mcp_imported_tool_list` / * `mcp_imported_call` (session-tools.ts), a search-then-call pattern that * never mounts an upstream server's tools directly. This module addresses * the daemon's OWN gateway tools, the part of the surface still eager. * * ## Why this does NOT use the SDK's enable()/disable() * * `@modelcontextprotocol/sdk` 1.29.0's `server.tool(...)` returns a * `RegisteredTool` with `.enable()`/`.disable()`, `tools/list` filters on * `.enabled`, and the server auto-advertises `tools: { listChanged: true }` * — a real, SDK-supported dynamic-registration mechanism. An earlier draft * of this module used exactly that: register tools disabled, `.enable()` * them from `tool_search`. * * It does not work here. `http-server.ts` documents (and a live daemon * run confirmed): "MCP transport: stateless mode for v1 — each request is * independent" — a FRESH `McpServer` is built via `mcpServerFactory()` for * EVERY request, including `tools/call`. An `.enable()` mutation made * during a `tool_search` call lives only on that call's own throwaway * server instance; the very next `tools/call` for the newly-"enabled" * tool gets a brand-new instance where it's disabled again, and fails * with `Tool X disabled`. Confirmed by running exactly that sequence * against a live gateway — the mutation never survives past the request * that made it, so a real orchestrator would search successfully, read * a schema, then have the follow-up call rejected. Worse than doing * nothing: it looks like it works, right up until the second call. * * ## What this does instead * * Every tool stays fully registered AND enabled (`tools/call` always * works for any tool name, deferred or not — the daemon is stateless * regardless, so there is no session-scoped "have they earned the right * to call this" state to enforce even if it were desirable). "Deferred" * only means: excluded from the `tools/list` response, so a session * doesn't pay the schema-loading token tax for tools it never asked * about. The `tools/list` handler is overridden directly on the * underlying low-level `Server` (`mcpServer.server.setRequestHandler` — * the SDK's own documented escape hatch: "For advanced usage ... use the * underlying Server instance") to return only the `alwaysOn` set plus * `tool_search` itself; this is a pure per-request read, so it's * naturally correct under statelessness — there's no history to lose. * `tool_search` matches a keyword (or `select:name1,name2` for exact * names) against a catalog of every OTHER registered tool and returns * full JSON Schema for the hits directly in its own result text — the * one channel that reliably survives the stateless boundary, since it's * read from the SAME call that produced it. * * Opt-in and backward-compatible by construction: nothing calls this * unless a host explicitly wires `deferredTools` into `createGateway` — * see `index.ts`. Every existing daemon keeps registering (and exposing) * everything eagerly, exactly as before. * * Both SDK registration entry points are intercepted — `server.tool(...)` * AND `server.registerTool(...)` (the config-object overload; e.g. * mcp-apps-adapter.ts's `agentproto_sessions` panel tool uses the latter, * and would silently skip the catalog if only one were patched). * * Tools registered on the server BEFORE it's wrapped — e.g. `self_inspect`, * added inside `@agentproto/mcp-server`'s `createMcpServer()` — are * automatically excluded from `tools/list` too: the override only lists * names present in `registry` (built from tools that passed through the * proxy), so anything registered earlier is simply absent from that set, * with no extra bookkeeping needed. They stay fully callable, same as * every other tool here — the override only ever touches what `tools/list` * shows. */ /** * `~/.agentproto/config.json`'s `defaults.mcp.deferredTools` shape — * `false`/absent (the default) keeps every daemon boot eager, byte-identical * to pre-existing behaviour. `true` turns deferred tools on gateway-wide * using the daemon's own default always-on set (see `DEFAULT_ALWAYS_ON_TOOLS` * in index.ts). `{ alwaysOn }` turns it on with a custom always-on set * instead of the default one. */ type DeferredToolsConfig = boolean | { alwaysOn: string[]; }; /** * Convert the config-file value (tri-state: off / on-with-default / * on-with-custom-set) into the shape `CreateGatewayOptions.deferredTools` * expects. Pure — no fs, easy to unit test independent of `loadConfig`. * `undefined`/`false` ⇒ `undefined` (omit the key entirely, so * `createGateway` never wraps `withDeferredTools` — today's eager * behaviour). `true` ⇒ `{}` (deferred, `alwaysOn` left for the gateway's * own `DEFAULT_ALWAYS_ON_TOOLS` fallback). `{ alwaysOn }` ⇒ passed through * verbatim. */ declare function resolveDeferredToolsGatewayOption(config: DeferredToolsConfig | undefined): { alwaysOn?: readonly string[]; } | undefined; /** * Pure resolver for `~/.agentproto/config.json`'s `defaults` block — * computes the effective `skills` + `options` + `auth` for an `agent_start` * spawn before adapter-specific normalization. No fs, no adapter I/O, so * it's unit-testable in isolation from `session-spawn.ts` (which owns the * fs read + the adapter-manifest lookup). * * Precedence (lowest → highest): global `defaults` < `defaults.adapters. * ` < the explicit `agent_start` call. * - `options`: shallow-merged maps, later (higher-precedence) keys win. * - `skills`: global ∪ per-adapter when the caller didn't pass `skills` * at all; an explicit `skills` (even `[]`) REPLACES the union rather * than merging into it — a deliberate exact set, mirroring how an * explicit `mcpServers: []` opts out of the hermes default in * `session-spawn.ts`. * - `auth`: surfaces the RAW billing-auth material (requested mode, both * candidate credentials, per-spawn provider pin, and the `explicit` * signal) so the descriptor-aware resolver ({@link resolveAuthSpec}, * which also needs the adapter's provider/subscription descriptor + * providers.json) can decide the final mode, env var, scrub set, and * credential source. Credentials are named in config or the provider * store — never read from the ambient shell env. */ /** * `defaults.mcp` block — daemon-wide MCP gateway policy, distinct from the * per-adapter spawn defaults above (it's read once at daemon boot, not * per-spawn — see `serve.ts`'s `createGateway({ deferredTools })` call). */ interface McpDefaultsConfig { /** Gateway-wide deferred/lazy `tools/list` loading (harness-parity item * 3 — see `deferred-tools.ts`). Default false/absent: every daemon boot * stays eager, byte-identical to pre-existing behaviour — turning this * on is a deliberate operator opt-in. Independent of the per-role * default (`RoleProfile.deferredTools`, on for `executor`), the * harness defaults (`nativeToolSearch` ⇒ eager; * `deferredToolDiscovery` absent/false ⇒ eager) and the per-spawn * `agent_start.deferredTools` override, and independent of the * per-mount `?deferred=1|0` query override on `/mcp` — this is only * the BOOT-TIME default for connections that specify neither. */ deferredTools?: DeferredToolsConfig; /** Gateway-wide MCP surface profile (see `tool-profiles.ts`), e.g. * `"core"`, `"core,apps"`, `"admin"`. Absent ⇒ `full` (every tool, the * pre-profile behaviour). A per-mount `?profile=` query wins over this * boot-time default. */ profile?: string; } /** * Deterministic billing-auth config for one adapter slug (today, only * claude-code interprets it — see `AgentCliStartOptions.auth` in * `@agentproto/driver-agent-cli`). EXPLICIT credential selection, not * scrub-by-absence: `token`/`apiKey` are the actual secret values, named * here (or supplied per-spawn) rather than inherited from the launching * shell. Never logged; only a fingerprint (see {@link credentialFingerprint}) * is ever surfaced back to a caller. */ interface DefaultsAdapterAuthConfig { /** `"subscription"` or `"api-key"`. Omitted ⇒ the resolver picks by * ordered preference (subscription first for adapters that support it — * see {@link resolveAuthSpec}), never a hardcoded default. */ mode?: "subscription" | "api-key"; /** The subscription bearer token for `"subscription"` mode — minted via * `claude setup-token` (bills the Max/Pro subscription, not API credits), * SET to the adapter's `authSubscription.setEnv`. */ token?: string; /** Opt-in SELF-REFRESHING subscription source (Mode 3). When set to * `"claude-code-oauth"` and no static `token` is supplied per-spawn, the * subscription bearer is read FRESH on every spawn from the local Claude * Code login (macOS Keychain `Claude Code-credentials` → jsonPath * `claudeAiOauth.accessToken`, falling back to `~/.claude/.credentials.json`) * via the `claude-code-oauth` provision recipe — because Claude Code keeps * that item refreshed, agentproto gets a fresh token each spawn. Absent ⇒ * today's static-bearer behavior (Mode 2). Only `"claude-code-oauth"` is * understood; any other value fails LOUD (never a silent fallthrough). See * {@link resolveSubscriptionCredential} for the precedence with `token`. */ source?: string; /** Explicit API key for `"api-key"` mode, SET to `providerEnvVar(provider)`. * Wins over the `providers.json` store key for the same provider. */ apiKey?: string; /** Per-spawn provider PIN — overrides the adapter's fixed provider and the * model-derived provider (the sharp edge for by-model routers whose config * routes a catalog-"anthropic" model elsewhere). A `CatalogProvider` id. */ provider?: CatalogProvider; /** Sub-account scoping a host resolved for a pinned profile and forwards * to a sandbox box (which has neither the profile nor its provider): the * env var the `apiKey` is set into instead of the provider's conventional * one. Per-spawn only; never read from config defaults. */ credentialEnv?: string; /** Extra env set beside the credential (the provider's scoping config). * Layered over — not clobbering — a JSON config the adapter's own mode * already carries under the same key. Per-spawn only. */ extraEnv?: Record; /** `false` opts out of the adapter's login-less credential data home. */ isolateDataHome?: boolean; /** BOX-LOGIN BRIDGE marker: the host already uploaded a redacted copy of * this file-based login INTO the box (`box-login-bridge.ts`), so the box * must not fail-fast on a missing credential — the file beside the spawn * IS the credential. Per-spawn only, stamped by the host just before * `host.start()`; never read from config defaults. Absent ⇒ today's * fail-loud behavior, unchanged. */ loginFile?: boolean; } interface DefaultsAdapterConfig { skills?: string[]; options?: Record; auth?: DefaultsAdapterAuthConfig; contextContinuity?: ContextContinuityPolicy; /** AIP-46 name of the block; same keys as contextContinuity, which stays an * alias. Within one layer, a key set here wins over the same key in * contextContinuity. */ contextSettings?: ContextSettings; /** Capability bundle ids (`bundle_list`) auto-attached to spawns of this * adapter — unioned with the global `defaults.bundles`. See * {@link resolveBundleDefaults}. */ bundles?: string[]; /** Explicitly mount the daemon's own scoped `/mcp` for spawns of this * adapter -- mainly useful for sandbox spawns or after an `mcpServers: []` * opt-out, since the universal on-host default now covers all adapters. * Overridden per-spawn by `agent_start.daemonMount`. */ daemonMount?: boolean; /** Context profile (`full` | `lean` | an adapter-declared id) applied to * spawns of this adapter that name none themselves. `"full"` opts an * adapter out of a built-in default (see {@link BUILTIN_EXECUTOR_CONTEXT_PROFILE}). * Overridden per-spawn by `agent_start.contextProfile`. */ contextProfile?: string; } /** Shape of `config.json`'s top-level `defaults` block. */ interface SpawnDefaultsConfig { skills?: string[]; options?: Record; /** Per-harness defaults, keyed by harness slug (canonical). Read through * {@link harnessDefaultsFor} / {@link harnessDefaultsMap}, never directly: * they merge in the deprecated `adapters` block. */ harnesses?: Record; /** @deprecated Old name of {@link SpawnDefaultsConfig.harnesses}, still * read (a field set under `harnesses` wins) with a deprecation warning; * removed in the next major of @agentproto/runtime. */ adapters?: Record; /** Capability bundle ids auto-attached to every spawn — see * {@link DefaultsAdapterConfig.bundles} for the per-adapter union partner. */ bundles?: string[]; /** Browser integration (TARGET-STATE: Bureau owns the browser). */ browser?: { /** How much of the built-in browser surface the daemon registers: * `"off"` keeps only `fetch_page` (a plain HTTP read); `"proxy"` (the * default) forwards the daemon browser tools to the `proxyImport` * Bureau server. `"on"` is the retired chrome-live mode, still accepted * and read as `"proxy"` with a warning. Read in the per-`/mcp`-session * registration pass, so a change applies on the next MCP session. */ builtin?: "off" | "proxy" | "on"; /** Alias of the imported MCP that is a Bureau server; the daemon browser * tools forward to it, `"bureau"` when unset. A set value also makes the * built-in `browser` bundle mount that import. */ proxyImport?: string; }; contextContinuity?: ContextContinuityPolicy; /** AIP-46 name of the block; same keys as contextContinuity, which stays an * alias. Within one layer, a key set here wins over the same key in * contextContinuity. */ contextSettings?: ContextSettings; /** Depth cutoff for the role-derived default (see `resolveRole` in * `role.ts`) applied when an `agent_start` call omits `role`: * `depth < cutoff` → supervisor, `depth >= cutoff` → executor. * Default 1 (root spawns keep today's unrestricted behaviour; any * spawn made THROUGH an orchestrator defaults to executor). Tune * this up (e.g. to a large number) to restore the old permissive * behaviour for existing deep spawns wholesale. * @deprecated removed in `@agentproto/runtime` 6.0.0 (with `role`); * still honoured as the depth boundary between `defaults.spawn. * defaultAgent.root` and `.nested`. */ defaultRoleDepthCutoff?: number; /** Trust-boundary cap on pack-carried roles (see `role-registry.ts`'s * `loadRoleRegistry`): a role pack whose `toolPolicy.delegation` is * `"allow"` at a level ABOVE this cap has it forced to `"deny"` — * the pack can still declare the intent, the daemon just refuses to * grant it. Lets an operator install third-party role packs without * trusting every one of them to self-grant delegation. Undefined * (default) ⇒ no cap, any pack-declared level may carry * `delegation: "allow"` (back-compat: #214 had no such knob). */ maxGrantableDelegation?: number; /** Default per-session Langfuse tracing opt-in when an `agent_start` call * omits `trace`. Default false — sessions trace only when they opt in or * this is on. See `filterSessionObserver` / `SpawnAgentInput.trace`. */ langfuseTracing?: boolean; /** Wake an idle agent session when one of its background tasks settles * (see `SessionsRegistryOptions.backgroundTaskWake`). On by default; * `{ enabled: false }` opts out. `graceMs` is how long the daemon waits * for the agent to wake ITSELF (Claude Code does) before prompting it. */ backgroundTaskWake?: { enabled?: boolean; graceMs?: number; }; /** Redactor slug applied to traced session content before it's sent to * Langfuse (see `@agentproto/processor`'s registry). Default "secrets" * (deny-list by key + value-scan for secret shapes). */ traceRedactor?: string; /** Default `interrupt` applied when an `agent_prompt` / `message_parent` * call leaves `interrupt` UNSET. `false` (the default) preserves today's * behaviour — a mid-turn target queues the prompt behind its in-flight * turn. `true` flips the unset default to cut: a mid-turn target has its * turn cancelled and is redirected onto the new prompt immediately. An * EXPLICIT `interrupt` on the call (true OR false) always wins over this * default. */ agentPromptInterrupt?: boolean; /** Installed-app hosting defaults (AIP-53). */ apps?: { /** Tunnel provider slug used for a `services[].expose` (AIP-53 * Exposure). Host config, never the app's. Unset: `cloudflare-provisioned` * when its creds are registered, else `cloudflare-managed` when * registered, else `cloudflare-quick` (reported as not stable). */ exposeProvider?: string; /** Which installed-app `exposes.tools` the /mcp gateway registers. Default "read". */ exposedTools?: "off" | "read" | "all"; }; /** Inter-session messaging policy (AIP-46 §Session messages). */ messaging?: { /** Let `message_send` / `message_reply` reach a sibling session (same * parent). Default false - only child↔parent. */ allowSiblings?: boolean; /** Let `message_send` / `message_reply` reach any session of the SAME * workspace, even without a tree edge. Default true. */ allowSameWorkspace?: boolean; /** Groups of workspace slugs. Two sessions may message each other * without a tree edge when both workspace slugs sit in the SAME group * (e.g. `[["demo-app", "app-orchestrator"]]`). Default []: * no cross-workspace link. Independent of `allowSameWorkspace`. */ peerGroups?: string[][]; /** Explicit AIP-38 `session:message`, `session:prompt` and * `session:control` grants. A matching allow admits a message pair or a * drive call the legacy gate refuses; a matching deny wins. Default []: * nothing changes. */ grants?: Grant[]; /** `defaults.messaging.peerBinding` - "slug" (default): peers by recorded * workspace slug (existing behaviour). "verified": peers only when both * cwds resolve to the same registered workspace (`findWorkspaceByPath`). * The tree is never affected; decisions report `peerVerified`. */ peerBinding?: "slug" | "verified"; /** Whether a SESSION sender may use urgency `interrupt` (cancel the * recipient's in-flight turn). Default "deny": downgraded to `steer` * and reported as such. Human (HTTP/CLI) senders always may. */ agentInterrupt?: "allow" | "deny"; /** Minutes a prompt may sit queued behind a running turn before the * sender is told it is stuck (typed notice) and it is flagged `stale` * in `pendingPrompts`. Default 5. */ pendingPromptStaleMinutes?: number; /** `defaults.messaging.anonymousSend` - "label" (default): anonymous and * unverified senders reach any live session, labelled and capped at * steer. "block": unverified session senders keep the refusal. */ anonymousSend?: "block" | "label"; /** `defaults.messaging.labelAddressing` - "tree" (default): a label a * supervisor gives a child is a family name (parent + siblings only); * "open": any session may address any label; "operator": only * operator-stamped labels. */ labelAddressing?: "open" | "tree" | "operator"; }; /** Caller identity (ts#2165 step 5). */ identity?: { /** `defaults.identity.sessionTokens` - "shadow" (default): a per-session * token is minted at spawn and callers are classified (`GET /identity`) * without refusing anything. "enforce": minted the same way, and an * invalid token, a mismatching claim or a claim without token naming a * token-delivered session is refused. "off": no token, no observation. */ sessionTokens?: "off" | "shadow" | "enforce"; /** `defaults.identity.requireProof` - actions a caller must be proven to * invoke. Empty (default): nothing is refused. Only `"session:spawn"` is * evaluated. Ignored while `sessionTokens` is `"off"` (rule 8). */ requireProof?: Array<"session:spawn">; }; /** Hooks projected into a harness's own settings (`native-hooks-defaults.ts`). */ nativeHooks?: { /** `defaults.nativeHooks.preCompactCheckpoint` - "on": a local claude-code * spawn gets a synchronous PreCompact (auto) hook that writes a daemon * checkpoint before the harness compacts. "off" (default): no hook. */ preCompactCheckpoint?: "off" | "on"; /** `defaults.nativeHooks.command` - the agentproto CLI the hook runs. * Unset means the serving CLI by absolute path. */ command?: string; }; /** Action hook reactions (AIP-71). */ reactions?: { /** Completed sessions of these workspace slugs are ingested into the * workspace brain by the durable brain-ingest reaction instead of the * legacy exit subscriber. Default []: every workspace stays with the * legacy subscriber. */ brainIngest?: { workspaces?: string[]; /** File-size ceiling for a session's `events.jsonl` before the brain * refuses to materialize it. Default 32 MB. Applies to both the * legacy exit subscriber and the brain-ingest reaction (they share * the reader). */ maxTranscriptBytes?: number; /** Running ceiling on accumulated message text while the brain reader * parses a transcript. Default 8 MB. */ maxTranscriptTextBytes?: number; /** Ceiling on the files one brain's in-memory fallback search index * holds (the on-disk index has none); above it results are flagged * partial. Default 100,000. */ maxIndexDocs?: number; }; /** Debounced clerk passes for these workspace slugs are dispatched by the * durable clerk reaction instead of the legacy dispatch. Default []: * every workspace stays on the legacy dispatch. */ clerk?: { workspaces?: string[]; }; }; /** PR provenance footer policy (the daemon reconciler and the * `command_execute` stamper). */ prProvenance?: { footer?: { /** `owner/name` repos whose pull requests never receive or refresh an * agentproto provenance footer. Read per stamp, so a change takes * effect without a daemon restart. Default []: stamp every repo. */ skipRepos?: string[]; }; }; /** Task-ledger policy. */ tasks?: { /** Sessions that keep operator rights on the task ledger while still * being attributed under their own id (owner / `sessions[]` / * `createdBy`). Entries follow `allowPromptFrom`'s rules: an exact * session id, `label:`, or `label:*` against * the immutable `operatorLabel` (never the mutable `label`). Default * []: a root `/mcp` caller attributed by `?callerSessionId=` is a * plain session caller. */ operatorDelegates?: string[]; }; /** Daemon-wide MCP gateway policy. See {@link McpDefaultsConfig}. */ mcp?: McpDefaultsConfig; /** Spawn-shape defaults applied when neither the `agent_start` call, its * role nor its user preset says otherwise. */ spawn?: { /** Default `agent_start.browser` (`"headless"` | `false`). Default off. */ browser?: SpawnBrowserMode; /** Which agent a spawn that names none binds: `root` below the depth * cutoff (default `supervisor`), `nested` at or above it (default * `executor`). A role name, built-in or pack-carried. */ defaultAgent?: { root?: string; nested?: string; }; /** AIP-46 delegation gate for nested spawns: `off` skips evaluation, * `observe` (default) counts what it would refuse without changing a * decision, `enforce` refuses a child the caller's agent does not * declare in `delegatesTo`. */ delegationGate?: DelegationGateMode; /** AIP-46 auth-profile gate for spawns that name an access profile: * `off` skips evaluation, `observe` (default) counts what it would * refuse without changing a decision, `enforce` refuses a profile * outside the caller's set. */ profileGate?: ProfileGateMode; /** Command-allowlist gate for stdio MCP servers a spawn mounts: `off` * skips evaluation, `observe` (default) counts what it would refuse * without changing a decision, `enforce` refuses a mount whose command * the workspace allowlist does not admit. */ stdioMountGate?: StdioMountGateMode; /** Profile ids any session may name at spawn, in addition to its own * recorded profile. Default []. */ sharedProfiles?: string[]; }; /** Daemon-wide sandbox safety-net policy. */ sandbox?: { /** Checkpoint-per-turn safety net for a sandbox session with a * workspace-remote delivery target — see * `sandbox-delivery.ts`'s `SandboxCheckpointConfig`/ * `resolveSandboxCheckpointConfig`. Overridden per-spawn by * `agent_start.sandboxCheckpoint`. */ checkpoint?: SandboxCheckpointConfig; /** Config-declared preflight probes (one shell command in the box, read as * yes/no), referenced by id from `agent_start.preflight` or a placement * rung. See `sandbox-preflight.ts`'s `CommandProbeSpec`. */ preflight?: { probes?: CommandProbeSpec[]; }; }; } interface ResolveSpawnDefaultsInput { /** Explicit-call `skills`. Undefined ⇒ caller expressed no preference, * fall through to the config union. Provided ⇒ replaces it outright. */ skills?: string[]; /** Explicit-call AIP-45 `options` map — wins per-key over both the * global and per-adapter config defaults. */ options?: Record; /** Explicit-call `agent_start.auth` override. `mode` wins over * `defaults.adapters..auth.mode`; the credential field matching the * RESOLVED mode wins over the matching config field. Undefined ⇒ falls * through entirely to the per-adapter config default. */ auth?: DefaultsAdapterAuthConfig; /** Explicit-call context-continuity policy — wins over global and * per-adapter config defaults, key by key. */ contextContinuity?: ContextContinuityPolicy; /** Explicit-call AIP-46 name of the same block: layers per setting over * the adapter and daemon blocks, and wins over contextContinuity key by * key. */ contextSettings?: ContextSettings; } interface ResolvedSpawnDefaults { skills: string[]; options: Record; /** RAW billing-auth material (config precedence applied) — fed to the * descriptor-aware {@link resolveAuthSpec}, which owns the final mode / * env / scrub / credential-source decision. Both candidate credentials * are surfaced (NOT collapsed to one), since the ordered-mode selection * needs to know which are available before it picks the mode. */ auth: ResolvedSpawnAuthMaterial; contextContinuity?: ContextContinuityPolicy; } interface ResolvedSpawnAuthMaterial { /** Operator-requested mode (per-spawn > per-adapter config), or undefined * ⇒ let the resolver pick by ordered preference. */ requestedMode?: "subscription" | "api-key"; /** True when the operator explicitly configured `auth` (per-spawn OR in * `defaults.adapters..auth`). The ONLY way to tell "set mode, no * key" (fail-fast) from "set nothing" (ambient) — both give no credential. * DECISION 5. */ explicit: boolean; /** True when the `auth` block came from CONFIG (`defaults.adapters..auth`) * rather than the per-spawn `agent_start.auth` request. A sandboxed spawn * bills on the BOX daemon, which has neither the host's config nor its * keychain — the host uses this to know it must resolve the configured * wallet credential itself and forward it (see `session-spawn.ts`'s * `resolveHostAuth`). A per-spawn `auth` keeps its own raw-forward path * and never forces host adapter resolution. */ explicitConfig: boolean; /** Subscription bearer token (per-spawn > config), if configured. STATIC * material only — the self-refreshing {@link subscriptionSource} is resolved * separately (and impurely) by the caller. */ subscriptionCredential?: string; /** Opt-in self-refreshing subscription source (per-spawn > config), if * configured — e.g. `"claude-code-oauth"`. Surfaced RAW; the impure caller * resolves it to a fresh token via {@link resolveSubscriptionCredential}. */ subscriptionSource?: string; /** Explicit API key (per-spawn > config), if configured — distinct from the * providers.json store key the resolver fetches separately. */ apiKeyCredential?: string; /** Per-spawn provider pin, if given. */ provider?: CatalogProvider; /** Forwarded sub-account scoping — see {@link DefaultsAdapterAuthConfig.credentialEnv}. */ credentialEnvOverride?: string; extraEnv?: Record; isolateDataHome?: boolean; /** Per-spawn BOX-LOGIN BRIDGE marker — see * {@link DefaultsAdapterAuthConfig.loginFile}. Never from config: a static * `loginFile` in `~/.agentproto/config.json` would outlive the copy it * describes. */ loginFile?: boolean; } /** * One harness's defaults: `defaults.harnesses.` layered over the * deprecated `defaults.adapters.`, field by field (a field set under * `harnesses` wins; `auth` and the other blocks are replaced whole, not * deep-merged). `undefined` when neither key names the slug. */ declare function harnessDefaultsFor(defaults: Pick | undefined, slug: string): DefaultsAdapterConfig | undefined; /** Every harness's merged defaults (see {@link harnessDefaultsFor}). */ declare function harnessDefaultsMap(defaults: Pick | undefined): Record; declare function resolveSpawnDefaults(defaults: SpawnDefaultsConfig | undefined, adapterSlug: string, input: ResolveSpawnDefaultsInput): ResolvedSpawnDefaults; /** * Derive a SAFE, non-secret fingerprint for a resolved auth credential — * NEVER the raw value — for recording on the session descriptor / surfacing * in `agentproto sessions --watch` and `agent_sessions_list` (the * "verifiability" requirement: answer "what was used" without exposing the * secret). Format: ` · …` when the shape is known * (e.g. `subscription · sk-ant-oat…3f9c`), else ` · …`. * * The shape marker is matched from a PUBLIC key-prefix table (longest-match), * not derived from `mode` — see {@link CREDENTIAL_FINGERPRINT_PREFIXES}. Only * the matched prefix + the last 4 characters are ever surfaced, never the * middle (mirrors GitHub's `ghp_…abcd` style). */ declare function credentialFingerprint(mode: "subscription" | "api-key", credential: string): string; /** * One subscription (OAuth/bearer) surface — mirrors the driver's * `AgentCliAuthSubscription`. `external: true` (codex/gemini/mastracode/ * opencode) ⇒ file-based: the CLI reads its own local-login file, so * `setEnv` is absent and the runtime injects NO bearer — it only scrubs the * conflicting api-key vars. */ interface AuthSubscriptionSurface { /** Env var SET to the resolved subscription credential — absent for an * {@link external} surface. */ setEnv?: string; external?: boolean; conflictEnv?: string[]; unsetEnvAdd?: string[]; /** Provider scope for a multi-provider adapter's surface — pi's * `ANTHROPIC_OAUTH_TOKEN` is an anthropic-only door; mastracode/opencode's * file-based ChatGPT login is an openai-only door alongside their * anthropic one. When set, this surface only MATCHES a spawn whose * resolved provider equals this id (see {@link subscriptionSurfaceFor}). * Omitted for a fixed-provider adapter (claude-code, codex) — their * descriptor-level `provider` already pins it. */ provider?: string; /** BOX-LOGIN BRIDGE declaration — see `box-login-bridge.ts`. Only valid on * an {@link external} surface (the schema enforces that): how the host * re-creates a REDACTED copy of this file-based login inside a sandbox * box, which boots with neither the host's login file nor its keychain. * `keep` is the allowlist; refresh-like keys are dropped unconditionally * even when keep-listed. */ boxLogin?: BoxLoginDecl; } /** * The adapter's billing-auth capability, projected from its AIP-45 manifest * (`provider` / `authEnforce` / `authSubscription`) by the host resolver. The * runtime reads THIS, never the manifest directly — keeping the LLM-catalog * coupling in the runtime and the driver mechanical. */ interface AdapterAuthDescriptor { /** FIXED provider for a single-provider adapter; omitted for by-model * routers (provider then derives from the requested model). */ provider?: CatalogProvider; /** Enforcement policy — `"always"` engages every spawn (claude-code's * #312 fail-fast); `"when-configured"` (default) only when `explicit`. */ authEnforce?: "always" | "when-configured"; /** Subscription (OAuth/bearer) support. Presence ⇒ the adapter supports * `"subscription"` mode. A SINGLE surface for a fixed/single-provider * subscription, or an ARRAY of surfaces for an adapter with more than one * native OAuth login (mastracode/opencode: both an anthropic- and an * openai-scoped file-based login) — see {@link subscriptionSurfaceFor}, * which resolves the matching surface for a spawn's resolved provider. */ authSubscription?: AuthSubscriptionSurface | AuthSubscriptionSurface[]; /** True when the adapter's api-key auth is derived from the requested * model rather than a fixed provider (e.g. `pi`, `opencode`). When set, * the adapter supports `"api-key"` on the model-derived direct endpoint, * and `spawnEligibilityManifest` includes it for direct routes. */ modelDerivedApiKey?: boolean; /** How THIS adapter receives a GATEWAY-routed bearer credential — see * `AgentCliDefinition.gatewayAuth` (the manifest field this is projected * from). Distinct from a gateway preset's `keyEnv` (the providers-store * lookup key) and from `authSubscription.setEnv` (this adapter's own * native bearer). When a gateway route resolves, `resolveAuthSpec` injects * the credential into `gatewayAuth.setEnv` instead of the preset's * `keyEnv` — e.g. claude-code/claude-sdk read `ANTHROPIC_AUTH_TOKEN`. * Omit when the adapter reads the preset's own `keyEnv` directly (hermes). */ gatewayAuth?: { setEnv: string; }; /** Model id → the BILLING provider THIS adapter itself declares for it * (`AgentCliModelEntry.provider`, projected from `models.allowed`) — * authoritative for a model-derived-api-key adapter (`pi`, `opencode`), * whose `provider` above is absent so the eligibility projection would * otherwise fall through to the GLOBAL catalog's own (possibly different) * routing for the same model id. Consulted by `spawnEligibilityManifest` * BEFORE the catalog fallback; absent/no-match ⇒ catalog derivation, * unchanged. */ modelProviders?: Readonly>; } /** The fully-resolved spec the driver applies mechanically. Structurally * matches `@agentproto/driver-agent-cli`'s `ResolvedAuthSpec` (each package * owns its own copy; the object flows across the boundary by shape). */ interface ResolvedAuthSpec { mode: "subscription" | "api-key"; credential?: string; setEnv: string; unsetEnv: string[]; explicit: boolean; enforce: "always" | "when-configured"; /** True when NEITHER subscription nor api-key had any credential * available and `mode` above is therefore an arbitrary fallback pick — * never true when `mode` came from an explicit request or an actually- * available credential. Optional (undefined ⇒ false) so existing * callers/fixtures that predate this field keep working unchanged. * Exists so a fail-fast message can enumerate BOTH auth paths instead of * presenting the fallback mode as though the user configured it — the * root cause of a zero-credential user being told to buy a subscription * they never asked for. */ neitherConfigured?: boolean; /** File-based subscription (see `AdapterAuthDescriptor.authSubscription. * external`): the CLI reads its OWN local-login file, so the driver injects * NO credential — it only applies {@link unsetEnv} and does NOT fail-fast on * a missing `credential`. Money-safe: no bearer ever reaches an env var. */ externalCredential?: boolean; /** Non-authenticating hint: true when `providers.json` HAS a key for the * resolved provider that is currently being ignored because auth isn't * explicitly configured (no `defaults.adapters..auth` block — the * `explicit` gate above, PR #321). NEVER used to authenticate — set by * the caller (session-spawn.ts) as a read-only peek, purely so the * fail-fast message can say "you already have a key, it's just not * wired in" instead of staying silent about it. `resolveAuthSpec` itself * never sets this (it does no I/O). */ ignoredApiKeyInStore?: boolean; /** When a gateway preset or custom route was matched, the `base_url` to * inject into adapter options so the client hits the gateway endpoint. */ baseUrl?: string; /** Extra env the driver sets when it injects the credential (a pinned * sub-account: the provider's scoping config next to its token). */ extraEnv?: Record; /** `false` opts out of the adapter's isolated, login-less credential data * home for this spawn (a sub-account provider that needs the adapter's own * login). Omitted ⇒ the adapter's declaration applies. */ isolateDataHome?: boolean; /** BOX-LOGIN BRIDGE marker forwarded from the box's `agent_start.auth`: * the host uploaded the login file this external subscription reads, so * the driver's missing-credential fail-fast is satisfied by that FILE * rather than by an injected bearer (which an external surface never has). * Carries no token — the file already sits on the box's filesystem. */ loginFile?: boolean; } /** Where the resolved credential came from — the observable billing axis * (DECISION 10②), never inferred. `"claude-code-oauth"` is the Mode-3 * self-refreshing source: the subscription bearer was read fresh from the * local Claude Code login via the `claude-code-oauth` provision recipe. * `"cli-local-login"` is the file-based (external) subscription: the CLI * (codex/gemini) reads its OWN local-login file — the runtime injected no * bearer, it only verified the login is present and scrubbed api-key vars. */ type CredentialSource = "explicit-config" | "providers-store" | "claude-code-oauth" | "subaccount" | "cli-local-login" | "none"; /** * The OBSERVABLE echo (DECISION 9③ / 10②) — recorded on the session * descriptor so a verifier checks the RESOLUTION, never the model's * self-report. Never carries the raw credential (only its fingerprint). */ interface AuthEcho { /** Billing endpoint / provider recorded for observability. Kept as `string` * (not the catalog enum) so gateway preset ids (e.g. "moonshot", * "openai-direct") that are not `CatalogProvider` values can still be * echoed on the session descriptor. */ provider: string; authMode: "subscription" | "api-key"; credentialSource: CredentialSource; setEnv: string; fingerprint?: string; } /** * Thrown when the operator requested a billing mode the adapter can't serve — * today only `"subscription"` on an adapter with no `authSubscription`. A * LOUD, distinct failure (DECISION 4②), never a silent downgrade to api-key. */ declare class AuthResolutionError extends Error { readonly code = "unsupported_auth_mode"; constructor(message: string); } interface ResolveAuthSpecInput { descriptor: AdapterAuthDescriptor; /** `input.model ?? adapter default model` — for model-derived provider. */ model?: string; /** Per-spawn provider pin (`input.auth.provider`). */ requestedProvider?: CatalogProvider; /** Operator-requested mode; undefined ⇒ ordered preference. */ requestedMode?: "subscription" | "api-key"; /** Operator explicitly configured `auth` (DECISION 5). */ explicit: boolean; /** Subscription bearer credential, if configured (or resolved fresh by the * caller from a self-refreshing source). */ subscriptionCredential?: string; /** Observable ORIGIN label for `subscriptionCredential`, when it did not come * from a plain static config token — today only `"claude-code-oauth"` (the * caller resolved it fresh from the local Claude Code login). Purely a label * for the echo; NEVER affects mode/credential selection. Omitted ⇒ the * subscription credential (if any) is treated as `"explicit-config"`. */ subscriptionCredentialSource?: CredentialSource; /** File-based subscription only: the caller (impure) verified the CLI's OWN * local-login file is present (e.g. `~/.codex/auth.json` has a subscription * token) and fails LOUD before reaching here if not. Makes an `external` * `authSubscription` count as an available subscription for ordered-mode * selection — the login file IS the credential, even though the runtime * injects no bearer. Ignored for a non-external (bearer) authSubscription. */ externalSubscriptionVerified?: boolean; /** Explicit api-key credential from config, if configured. */ apiKeyConfigCredential?: string; /** api-key credential from `providers.json` (fetched by the caller). */ apiKeyStoreCredential?: string; /** Origin label for `apiKeyConfigCredential` when a source-backed profile * resolved it (a sub-account provider's scoped token); omitted ⇒ `"explicit-config"`. */ apiKeyCredentialSource?: CredentialSource; /** Env var the api-key credential is set into INSTEAD of the provider's * conventional key env (the provider's own var is then scrubbed). */ credentialEnvOverride?: string; /** Passed through to {@link ResolvedAuthSpec.extraEnv}. */ extraEnv?: Record; /** Passed through to {@link ResolvedAuthSpec.isolateDataHome}. */ isolateDataHome?: boolean; /** Passed through to {@link ResolvedAuthSpec.loginFile} — the box-login * bridge marker the box's own `agent_start.auth` carried (per-spawn only; * never derived here). */ loginFile?: boolean; /** Explicit gateway route from `SessionConfig.route.gateway`. When this * matches a `ProviderPreset` or a registered custom route, the route's * `baseUrl`/`keyEnv`/`scrubEnv` drive resolution instead of the model- * derived or fixed provider. */ routeGateway?: string; } declare function resolveAuthSpec(input: ResolveAuthSpecInput): { spec: ResolvedAuthSpec; echo: AuthEcho; } | undefined; /** The only `auth.source` value understood today (Mode 3): read the * subscription bearer fresh from the local Claude Code login via the * `claude-code-oauth` provision recipe. */ declare const CLAUDE_CODE_OAUTH_SOURCE = "claude-code-oauth"; /** * Raised when `auth.source` is configured but cannot yield a credential — an * unknown source value (`unsupported_auth_source`) or the recipe resolving to * nothing / not-logged-in (`auth_source_unresolved`). A LOUD, actionable * failure surfaced as a spawn error, NEVER a silent fallthrough to a static or * ambient credential (mirrors {@link AuthResolutionError}'s discipline). */ declare class SubscriptionSourceError extends Error { readonly code: "unsupported_auth_source" | "auth_source_unresolved"; /** Set when logging in again fixes it: the exact `agentproto auth reauth ...` * command, mirrored in the message and surfaced as `details.reauth`. */ readonly reauth?: ReauthHint; constructor(code: "unsupported_auth_source" | "auth_source_unresolved", message: string, reauth?: ReauthHint); } interface ResolveSubscriptionCredentialInput { /** Per-spawn explicit static token (`input.auth.token`) — wins over source. */ explicitToken?: string; /** Effective opt-in source (`input.auth.source ?? config auth.source`). */ source?: string; /** Config static token (`defaults.adapters..auth.token`) — the * lowest-precedence fallback, used only when NEITHER an explicit per-spawn * token nor a source applies. */ fallbackStaticToken?: string; } interface SubscriptionCredentialResolution { /** Resolved subscription bearer, or undefined ⇒ nothing configured (the * driver's fail-fast `missing_auth_credential` still owns that case). */ credential?: string; /** Observable origin of {@link credential} for the echo. */ source?: CredentialSource; } /** * Resolve the subscription (oauth-bearer) credential + its observable origin, * placing the self-refreshing `source` (Mode 3) BETWEEN the two static tokens * (SPEC §2): * a. explicit per-spawn `input.auth.token` (static) — wins over everything. * b. else `source: "claude-code-oauth"` → resolve FRESH via the injected * recipe resolver (Keychain / credentials file) ⇒ origin * `"claude-code-oauth"`. * c. else config.json static `auth.token` ⇒ origin `"explicit-config"`. * d. else nothing (⇒ driver fail-fast `missing_auth_credential`, unchanged). * * The recipe I/O is INJECTED (`resolveSourceToken`) so this stays pure and * unit-testable without touching the real Keychain — the impure resolver lives * in `claude-code-oauth-source.ts`. Fails LOUD ({@link SubscriptionSourceError}) * on an unknown source or an empty recipe; never a silent fallthrough. Only * touches the subscription path — api-key mode never reaches here. */ declare function resolveSubscriptionCredential(input: ResolveSubscriptionCredentialInput, resolveSourceToken: (source: string) => Promise): Promise; /** Manifest-declared AIP-45 option id + type, the minimum an adapter * resolver needs to expose for `normalizeSkillsOption` below. Mirrors * `AgentCliOption`'s `id`/`type` fields without importing * `@agentproto/driver-agent-cli` into the runtime package. */ interface DeclaredAdapterOption { id: string; type: "boolean" | "integer" | "string" | "enum"; } /** * Fold the resolved `skills` list into `options.skills` using whatever * shape the adapter's manifest declares for that option id (today, only * `type: "string"` exists for a skills-shaped option — e.g. hermes' * comma-joined `--skills a,b`). Adapters with no declared `skills` option * (e.g. claude-code, which auto-discovers from `~/.claude/skills`) are a * documented no-op — the effective skills list has nowhere to go, so it's * dropped rather than guessing a flag the manifest didn't declare. * * An `options.skills` already present (from config defaults or the * explicit call) is respected as-is and never overwritten here. */ declare function normalizeSkillsOption(skills: string[], options: Record, declaredOptions: readonly DeclaredAdapterOption[] | undefined): Record; export { type AdapterAuthDescriptor as A, resolveDeferredToolsGatewayOption as B, type ContextContinuityPolicy as C, type DeclaredAdapterOption as D, resolveSpawnDefaults as E, resolveSubscriptionCredential as F, type ResolveHeadlessBrowser as G, type SandboxCheckpointConfig as H, type StdioMountGateMode as I, type TurnRetryPolicy as J, type ResolvedContextContinuityPolicy as K, type SandboxDeliveryRecord as L, type SandboxDeliveryTarget as M, type PreflightRegistry as P, type ResolvedAuthSpec as R, type SpawnDefaultsConfig as S, type TurnRetryInput as T, type SpawnBrowserMode as a, type CredentialSource as b, type AuthEcho as c, AuthResolutionError as d, CLAUDE_CODE_OAUTH_SOURCE as e, type ContextSettings as f, type DefaultsAdapterAuthConfig as g, type DefaultsAdapterConfig as h, type DeferredToolsConfig as i, type DelegationGateMode as j, type DelegationReport as k, type DelegationVerdict as l, type ProfileGateMode as m, type ProfileReport as n, type ProfileVerdict as o, type ResolveSubscriptionCredentialInput as p, type ResolvedSpawnAuthMaterial as q, type ResolvedSpawnDefaults as r, type SubscriptionCredentialResolution as s, SubscriptionSourceError as t, credentialFingerprint as u, harnessDefaultsFor as v, harnessDefaultsMap as w, layerContextSettings as x, normalizeSkillsOption as y, resolveAuthSpec as z };