import { LLMPricingTier } from '@agentproto/model-catalog/llm'; import { AcpMcpServer, AgentPromptField, AgentPromptAnswers, AcpPermissionResolution, AgentPromptQuestion } from '@agentproto/acp'; import { S as SessionConfig, R as RouteSpec, P as Posture, E as EffortLevel, C as ContextProfile, d as CatalogModelsQuery, e as CatalogModelsResponse, a as CanonicalPosture, A as AuthMethod } from './catalog-models-CSvq5qBI.js'; import { AuthProfile, CostBudget } from '@agentproto/auth'; import { parseAnthropicUnifiedRateLimitHeaders } from '@agentproto/quota'; import { z } from 'zod'; import * as _agentproto_delivery from '@agentproto/delivery'; import { DeliveryApplyConfig } from '@agentproto/delivery'; import { SessionMode, SessionConfigOption } from '@agentproto/acp/client'; import { ChildProcess } from 'node:child_process'; import { Grant, GrantInput, GrantRequest } from '@agentproto/policy'; import { AdapterHandle, SetupField, AdapterResolver, AdapterLister, CredsStore, HarnessCapabilities, HookCapabilityView } from '@agentproto/provider-kit'; import { SandboxProvider, SandboxSpec, SandboxProviderChoice } from '@agentproto/sandbox'; import { ImportedSkillsConfig, ResolvedSessionSkill } from './skill-imports.js'; import { RoutineFrontmatter } from '@agentproto/routine'; import { HookEventRef } from '@agentproto/lifecycle'; import * as _agentproto_memory from '@agentproto/memory'; import { MemoryStore } from '@agentproto/memory'; import { SandboxMode } from '@agentproto/command-sandbox'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { ConversationStore } from './conversations.js'; import { b as RuntimeEvents, a as HeartbeatRunner } from './heartbeat-BIvuS0Hv.js'; import { p as SessionFollowStore, m as AgentprotoConfig, $ as WorktreeIsolationMode, ai as SpawnAttachMode, aj as SpawnDedupeMode } from './config-Bvuv9HOv.js'; import { a as SpawnBrowserMode, T as TurnRetryInput, S as SpawnDefaultsConfig, G as ResolveHeadlessBrowser, g as DefaultsAdapterAuthConfig, C as ContextContinuityPolicy, f as ContextSettings, H as SandboxCheckpointConfig, R as ResolvedAuthSpec, D as DeclaredAdapterOption, A as AdapterAuthDescriptor, j as DelegationGateMode, m as ProfileGateMode, I as StdioMountGateMode, J as TurnRetryPolicy, K as ResolvedContextContinuityPolicy, L as SandboxDeliveryRecord, M as SandboxDeliveryTarget } from './spawn-defaults-B0Yi8_MN.js'; import { ClerkHookConfig } from '@agentproto/clerk'; import { AllowlistEntry } from './command-allowlist.js'; import { IncomingMessage, ServerResponse } from 'node:http'; import { BrainManager, ExportedSessionLike } from '@agentproto/workspace-brain'; import { SentinelStore, SentinelProviderHandle, CancelTombstoneStore, SentinelDeliveryStatus, SentinelInboundDeps, SentinelRoutingDeps, SentinelPublicUrl } from '@agentproto/sentinel'; import { PairingRegistry } from '@agentproto/pairing-host'; import { FrameSink } from '@agentproto/acp/tunnel'; import { DaemonIdentity } from '@agentproto/secrets/identity'; import { ArtifactEntry } from '@agentproto/workflow-runtime'; import { WorkflowStage, WorkflowRun, RunEventEnvelope } from '@agentproto/run'; import { a as AppRegistry } from './app-registry-DtUAlxkN.js'; import { ReadResourceResult } from '@modelcontextprotocol/sdk/types.js'; import { D as DiscoveredMcp } from './mcp-discovery-CLihUe93.js'; import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; import { BundlesFile } from './bundles.js'; import { ImportedMcpsConfig } from './mcp-imports.js'; /** * Per-session usage snapshot — the single place that decides a session's * `costUsd` and where that number came from. * * Two cost sources feed a session: * - an adapter's own usage reader (`readUsage`, e.g. hermes reads its * state.db) or an ACP `usage_update` that carries a `cost` block — these * are authoritative, tagged `source: "adapter"`. * - raw input/output token counts with NO adapter cost (ACP adapters like * claude-code / mastracode that report tokens but not dollars) — here we * price them ourselves against agentproto's in-repo LLM pricing catalog, * tagged `source: "computed"`. * * When tokens exist but the model is absent from the catalog we NEVER * fabricate a price: `costUsd` is left undefined and the snapshot is tagged * `source: "no-pricing"`. A session with neither cost nor tokens is * `source: "none"`. * * This module is pure (the catalog lookup is injected) so the decision tree is * unit-testable without building the whole model catalog. */ /** How a session's usage is billed: flat-rate `subscription`, pay-per-token * `api-key`, a `free` model, or `unknown` (not determined). */ type UsageBilling = "subscription" | "api-key" | "free" | "unknown"; /** Where a session's `costUsd` came from — see the module doc. */ type UsageSource = "adapter" | "computed" | "no-pricing" | "none"; /** Per-token USD prices for a model (per 1M tokens), the subset of the * catalog's `LLMPricing` this module needs. */ interface TokenPricing { inputPer1M: number; outputPer1M: number; /** Multiplier on `inputPer1M` for cache-read tokens (Anthropic: ~0.1). * Absent = 1 (no discount), same default as the catalog. */ cacheReadMultiplier?: number; /** Multiplier on `inputPer1M` for cache-creation tokens (Anthropic: * ~1.25). Absent = 1. */ cacheWriteMultiplier?: number; /** Prompt-length price tiers (catalog `LLMPricing.tiers`). */ tiers?: readonly LLMPricingTier[]; } /** * Token-detail and activity fields shared by every usage shape below. All * optional and never zero-filled: absent means "this source doesn't report * it", a present 0 is a measured zero. * * - `cacheReadTokens` / `cacheWriteTokens`: prompt-cache reads / cache * creation, cumulative. Kept OUT of `tokensIn` (which is uncached input * only when a cache split is known). * - `reasoningTokens`: thinking/reasoning tokens, cumulative. A subset of * `tokensOut` for providers that bill them as output (Anthropic). * - `turns`: completed turns (the descriptor's `turnsCompleted`). * - `toolCalls`: tool calls the daemon observed, cumulative. * - `durationMs`: wall time spent inside turns, cumulative. */ interface UsageDetail { cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; turns?: number; toolCalls?: number; durationMs?: number; } /** Copy only the present (`number`) `UsageDetail` fields of `src`. */ declare function pickUsageDetail(src: UsageDetail): UsageDetail; /** Pluggable pricing accessor — defaults to the in-repo catalog's * `resolvePricing`, overridable in tests. Returns undefined for an * unknown model (the caller then tags `no-pricing`). */ type PricingResolver = (model: string) => TokenPricing | undefined; /** * What an adapter's usage reader (`readUsage`: hermes state.db, opencode.db, * the claude-code transcript JSONL) returns. Every field is cumulative for * the session and optional; `null` from the reader means "nothing found". */ interface UsageReadResult { model?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; /** Billing mode, when the reader can tell (native-TUI terminals). */ billing?: UsageBilling; } /** Where a reader should look for the session's native store — the spawn's * cwd and isolated provider config dir (`CLAUDE_CONFIG_DIR` for * claude-code). Readers that key only on the session id ignore it. */ interface UsageReadContext { cwd?: string; configDir?: string; } /** Raw signals gathered over a turn, handed to `deriveSessionUsage`. */ interface UsageComputeInput extends UsageDetail { /** Requested model id — needed to look up per-token prices. */ model?: string; /** Cost the adapter reported directly (readUsage or usage_update.cost). * Present → authoritative, wins over token-based computation. */ adapterCostUsd?: number; tokensIn?: number; tokensOut?: number; contextSize?: number; contextUsed?: number; } /** The resolved usage snapshot — the shape `session_usage` returns and the * durable `usage_snapshot` transcript record carries. Cost/token fields are * omitted when absent so a missing value never reads as a measured zero. */ interface SessionUsage extends UsageDetail { model?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; contextSize?: number; contextUsed?: number; source: UsageSource; /** Billing mode of the usage (see {@link UsageBilling}); absent = not * determined (agent-cli sessions today). `costUsd` stays the value at API * price; `paidCostUsd` is what the account actually pays. */ billing?: UsageBilling; paidCostUsd?: number; } /** * Decide a session's usage snapshot + cost source from the raw signals. * * Priority: an adapter-reported cost wins; else price the tokens against the * catalog; else `none`. Never fabricates a price for an unpriced model. */ declare function deriveSessionUsage(input: UsageComputeInput, resolve?: PricingResolver): SessionUsage; /** Descriptor-shaped fields `projectSessionUsage` reads. */ interface UsageDescriptorFields extends Omit { model?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; contextSize?: number; contextUsed?: number; usageSource?: UsageSource; billing?: UsageBilling; paidCostUsd?: number; /** Surfaced as `turns`. */ turnsCompleted?: number; } /** * Project a session descriptor's persisted usage fields into the * `session_usage` response shape. Omits absent fields; defaults an * unstamped `usageSource` to `"none"`. */ declare function projectSessionUsage(desc: UsageDescriptorFields): SessionUsage; /** * Usage capture for native-TUI terminal sessions (`kind: "terminal"` PTYs * that run a provider's own CLI: `claude`, `codex`, `opencode`, `hermes`). * * An agent-cli session gets its tokens and cost from ACP `usage_update` * frames or the adapter's `readUsage` hook. A PTY has no ACP stream, so * nothing reached the descriptor. But every one of these TUIs journals its * own usage on disk, and the daemon already links the PTY to that native * conversation (`adapterSessionId`, see the conversation-terminal link * probe). This module is the glue: a per-harness reader keyed by that id, * normalised to `UsageReadResult`, plus a billing classification. * * Two money figures, never mixed: * - `costUsd` = VALUE at API list price (catalog price x tokens, or the * harness's own cost when it reports a non-zero one). What the usage * would cost on pay-per-token. * - `paidCostUsd` = what the account actually pays for it. Equals * `costUsd` for metered (API key) billing; 0 on a flat-rate * subscription (the marginal cost; the monthly fee is not per session) * and for free models; absent when the billing mode is unknown. * * Per-harness status: claude-code, codex, opencode and hermes are read. * copilot and mistral-vibe write no per-session token journal we can * attribute to one PTY, and are not classified as conversation terminals * yet (no `CONVERSATION_STORES` entry), so they stay un-captured. */ /** A harness usage reader for one native conversation id. */ type TerminalUsageReader = (adapterSessionId: string, ctx: UsageReadContext) => Promise; /** * Cumulative usage from a Codex rollout's text. Codex writes * `event_msg/token_count` lines whose `info.total_token_usage` is already * cumulative for the conversation, so the LAST one wins (no summing). * OpenAI semantics: `input_tokens` INCLUDES `cached_input_tokens`; the * runtime's `tokensIn` is uncached input only (see `UsageDetail`), so it is * split here. `reasoning_output_tokens` is a subset of `output_tokens`. The * model is the latest `turn_context.model`. */ declare function parseCodexRolloutUsage(text: string): UsageReadResult | null; /** Best-effort cumulative usage of a Codex conversation. Never throws. */ declare function readCodexRolloutUsage(sessionId: string, ctx?: UsageReadContext): Promise; /** Billing of a native `claude`: `ANTHROPIC_API_KEY` in the environment * means pay-per-token; otherwise a logged-in Claude account * (`oauthAccount` in `~/.claude.json`) is a subscription. Neither = * unknown. */ declare function detectClaudeBilling(env?: NodeJS.ProcessEnv, home?: string): UsageBilling; /** Billing of a native `codex`: `auth.json` `auth_mode` is `chatgpt` * (ChatGPT plan, flat rate) or `apikey`. */ declare function detectCodexBilling(codexHome?: string): UsageBilling; /** Billing of an opencode model ref `provider/model`: the Go plan is a flat * subscription, Zen is a pay-per-token wallet, a `-free` model is free. */ declare function opencodeBilling(model: string | undefined): UsageBilling; /** What the account pays for `costUsd` of value under `billing`. */ declare function paidCostFor(billing: UsageBilling | undefined, costUsd: number | undefined): number | undefined; /** Harness readers handed in by the CLI (they live in adapter packages the * runtime does not depend on). Codex is read in-runtime. */ interface TerminalUsageSources { "claude-code"?: TerminalUsageReader; opencode?: TerminalUsageReader; hermes?: TerminalUsageReader; } /** The slug → reader table the session manager consumes. */ declare function createTerminalUsageReaders(sources: TerminalUsageSources): Record; /** * Activity ledger v1 — the PURE projection core. * * "Activity" is a unified read-model over the daemon's existing "what is * happening" silos: completion policies (supervisor), in-flight session * turns, workflow steps, and opened PRs. It is a **projection, not a * registry** — the owning subsystems keep their state machines untouched and * this module only MAPS their already-exposed state onto one shared record * shape. Nothing here is stored; re-running a mapper over the same owner * state yields byte-identical records (deterministic ids), which is what * makes re-projection idempotent and the ledger safely deletable. * * The active/pending discriminator is mechanical, never judged: * - **active** — the daemon is consuming compute for this activity NOW * (a live child process, an in-flight LLM turn, a running gate command). * The next transition is caused by work the daemon itself executes. * - **pending** — nothing is executing; the activity holds only * subscriptions. The next transition needs an EXTERNAL signal: another * session's turn-end, a human `policy_ack`/`permissions_respond`, a * forge result, a freed cap slot, a timer. `waitingOn` names that signal * and is required exactly when `state === "pending"` (enforced by the * {@link ActivityRecord} union). * * Pure by construction — no daemon imports, no I/O, no clock reads (callers * pass `now` where staleness is derived). Each mapper takes a STRUCTURAL * input slice (the `pr-provenance.ts` `FooterSession` pattern): the real * `PolicyRunState` / `SessionDescriptor` / `WorkflowRun` satisfy the slices * structurally, and tests fake them without casts. The * side-effecting projector (bus subscription, diffing, `activity:changed` * emission) lives in `activities.ts`. */ declare const ACTIVITY_STATES: readonly ["active", "pending", "done", "failed", "cancelled"]; type ActivityState = (typeof ACTIVITY_STATES)[number]; declare const ACTIVITY_KINDS: readonly ["turn", "policy", "gate", "commit", "workflow-step", "pr", "cron-run"]; type ActivityKind = (typeof ACTIVITY_KINDS)[number]; declare const ACTIVITY_SOURCES: readonly ["supervisor", "workflow", "session", "code-host", "cron"]; type ActivitySource = (typeof ACTIVITY_SOURCES)[number]; /** * What a `pending` activity is blocked on — the external signal whose * arrival causes the next transition. `refs` are the ids to poke: session * ids for `session-turn`, the policyId for `human-ack`/`cap-slot`, the PR * url for `forge`. */ interface ActivityWaitingOn { kind: "session-turn" | "human-ack" | "cap-slot" | "stage-barrier" | "forge" | "timer"; refs: string[]; /** Optional human sentence naming the blocker. */ detail?: string; } /** * Everything an {@link ActivityRecord} carries besides its state. Split out * so the record union can enforce "waitingOn REQUIRED iff pending" at the * type level rather than by doc-comment. */ interface ActivityRecordBase { /** * DETERMINISTIC, source-derived id — `policy:plc_x`, `turn:sess_y:3`, * `pr:sess_y:412` — NOT a uuid. Determinism is what makes re-projection * idempotent: the same owner state always maps to the same id, so the * projector's diff cache is disposable. */ id: string; kind: ActivityKind; /** Subject session (fan-in policies additionally carry the group). */ sessionId?: string; sessionIds?: string[]; /** Structural parent: a gate/commit activity points at its policy. */ parentActivityId?: string; /** FK into the owner: policyId, `runId#step`, PR url. */ sourceRef: string; source: ActivitySource; /** One human sentence. */ title: string; startedAt: string; endedAt?: string; error?: string; /** * Staleness FLAG (from the session's `lastActivityAt`), surfaced so a UI * can show "active but silent for 12min". Never auto-transitions the * state — an activity the owner says is active stays active. */ staleSince?: string; /** * The declared-intent Task this activity is advancing, when one links — * derived at read time by {@link linkTasks} from the Task ledger's edges * (a `turn`'s session owns a task; a `policy`'s id is a task's verify * gate). Absent when nothing links, and never a write path: Task stays the * source of truth for INTENT, Activity the projection for EXECUTION. */ taskId?: string; } /** * One activity. `active ⇄ pending` oscillates freely (honest for a policy's * watching→gating→nudging→watching→awaiting-ack life); `done`/`failed`/ * `cancelled` are terminal. The union shape makes `waitingOn` REQUIRED on a * pending record and absent on every other state. */ type ActivityRecord = (ActivityRecordBase & { state: "pending"; waitingOn: ActivityWaitingOn; }) | (ActivityRecordBase & { state: Exclude; waitingOn?: undefined; }); /** Terminal (immutable) activity states. */ declare function isTerminalActivityState(state: ActivityState): boolean; /** * Structural slice of a Task ledger row the join reads — the `TaskRecord` * satisfies it. Kept structural so this module stays free of a * `./task-ledger.js` import (and thus pure/standalone). */ interface ActivityTaskSlice { taskId: string; status: string; /** The session currently on the task (absent = unclaimed). */ owner?: string; /** How done was reached; only a Tier-1 `gate` carries the `policyId` the * join reads. `kind` is required so the full `TaskVerification` union (whose * `self-report`/`human` variants have no `policyId`) still satisfies this. */ verification?: { kind: string; policyId?: string; }; } /** * Structural slice of `supervisor.ts`'s `PolicyRunState` — the same rows * `policy_list` returns. The full state satisfies this. */ interface ActivityPolicySlice { policyId: string; /** Representative session id (fan-in group[0]). */ sessionId: string; /** * The full fan-in group being watched. OPTIONAL because supervisor state * persisted before fan-in (WP6) predates this field — legacy rows on disk * carry only `sessionId`, and the type must not lie about that. */ sessionIds?: readonly string[]; /** * Group members that have NOT yet finished their turn. OPTIONAL for the * same reason as `sessionIds`: pre-fan-in persisted supervisor state omits * it. */ pending?: readonly string[]; status: "watching" | "queued" | "gating" | "acting" | "nudging" | "awaiting-ack" | "done" | "blocked" | "cancelled"; startedAt: string; endedAt?: string; lastGate?: { exitCode: number; at: string; }; commitPlan?: { paths: readonly string[]; message: string; }; commitSha?: string; error?: string; } /** * Project one completion policy onto its `policy` activity, plus a child * `gate` activity once a gate has run (or is running) and a child `commit` * activity once a commit plan exists. Discriminator mapping (mechanical): * gating/acting/nudging → active (the daemon is running the gate / action / * nudge itself); watching → pending on the watched sessions' turns; queued → * pending on a freed cap slot; awaiting-ack → pending on a human * `policy_ack`. done → done, blocked → failed, cancelled → cancelled. */ declare function policyToActivities(policy: ActivityPolicySlice): ActivityRecord[]; /** * Structural slice of `SessionDescriptor` the turn mapper reads. The full * descriptor satisfies this (see `FooterSession` for the pattern). */ interface ActivityTurnSession { id: string; title?: string; label?: string; kind?: string; status?: string; startedAt: string; busy?: boolean; awaitingInput?: boolean; awaitingPermission?: boolean; turnsCompleted?: number; killedMidTurn?: boolean; lastActivityAt?: string; } /** * Project a session's CURRENT turn (never its history) onto at most one * `turn` activity. Turn ordinals are 1-based off `turnsCompleted`, so the * same conversational beat keeps one id across its whole life: turn n is * `turn::` while busy (`turnsCompleted` is still n-1), and the id * stays `turn::` once it completes (`turnsCompleted` becomes n) — * the record transitions active → done in place. Discriminator: busy → * active; awaiting-input / a held permission → pending `human-ack`; a * terminal session settles the in-flight turn (killedMidTurn → cancelled / * failed) or the last completed one (→ done). An idle session that never * ran a turn projects nothing. */ declare function turnToActivities(session: ActivityTurnSession, opts?: { now?: string; }): ActivityRecord[]; /** Structural slice of a run's step state — shared by `workflow-runner.ts`'s * `WorkflowStageState.steps`. */ interface ActivityRunStepSlice { index: number; label: string; status: "pending" | "running" | "done" | "failed" | "skipped" | "cancelled"; sessionId?: string; startedAt?: string; endedAt?: string; error?: string; } /** Structural slice of `workflow-runner.ts`'s `WorkflowStageState`. */ interface ActivityWorkflowStageSlice { index: number; label?: string; status: "pending" | "running" | "done" | "failed" | "skipped" | "cancelled"; steps: readonly ActivityRunStepSlice[]; } /** Structural slice of a `WorkflowRun` (`workflow_list` rows). */ interface ActivityWorkflowRunSlice { runId: string; status: string; startedAt: string; endedAt?: string; stages: readonly ActivityWorkflowStageSlice[]; } /** * Project one workflow run's steps (stage-barrier semantics): running → * active; a `pending` step waits on the stage barrier — the unfinished * steps of EARLIER stages are the sessions whose turn-ends open it; * done/failed → terminal; skipped/cancelled → cancelled; a step still * pending inside a terminal run settles as cancelled. */ declare function workflowToActivities(run: ActivityWorkflowRunSlice): ActivityRecord[]; /** * Structural slice of `SessionDescriptor` the PR mapper reads — * `openedPrs` rows are `sessions.ts`'s `OpenedPullRequest`. */ interface ActivityPrSession { id: string; openedPrs?: readonly { number: number; url: string; openedAt: string; }[]; } /** * A PR's state as the forge last reported it. `merged`/`closed` are * immutable verdicts (a merged PR never un-merges), `open` just means "not * settled yet". The projector (`activities.ts`) resolves these through its * injected `resolvePrState` port and threads them into {@link prToActivities} * as a lookup — the mapper itself never fetches. */ type PrResolvedState = "open" | "merged" | "closed"; /** * Project a session's opened PRs. A `pr` activity is `pending` on the forge * until a resolved state says otherwise: `merged` → `done`, `closed` → * `cancelled` (terminal). The resolved state arrives via the pure * `resolvedPrState` lookup (threaded like `now` is for staleSince) — the * actual forge round-trip lives behind the projector's injected * `resolvePrState` port, because it reuses `@agentproto/worktree`'s forge * access, a dependency the runtime deliberately does not take. No polling * here. */ declare function prToActivities(session: ActivityPrSession, opts?: { resolvedPrState?: (url: string) => PrResolvedState | undefined; /** The forge's real merge time (ISO) for a merged PR, when known. */ resolvedPrMergedAt?: (url: string) => string | undefined; }): ActivityRecord[]; /** Filter for `activities_list` / `GET /activities`. */ interface ActivityListFilter { /** Match the record's `sessionId` or any member of its `sessionIds`. */ sessionId?: string; state?: ActivityState; kind?: ActivityKind; source?: ActivitySource; /** Include done/failed/cancelled records. Default false — an explicit * terminal `state` filter implies inclusion on its own. */ includeTerminal?: boolean; } /** Apply an {@link ActivityListFilter}. Pure; narrowing only. */ declare function filterActivities(records: readonly ActivityRecord[], filter?: ActivityListFilter): ActivityRecord[]; /** The `{ active, pending }` counts the query surfaces return. */ declare function activityCounts(records: readonly ActivityRecord[]): { active: number; pending: number; }; /** * ReactionRunner: durable execution of action hook reactions over the receipt * store. * * The runner owns no durable state of its own. Every decision is taken from a * receipt transition, and the store is the only thing that persists. A live * event creates a `pending` receipt, the `running` transition is durable before * any target runs, and boot reconciliation replays only the receipts whose * target declares itself idempotent. * * Containment matches the workspace brain subscriber: a bus handler never * throws into the bus, a failed store write never starts a target, and boot * reconciliation resolves even when a trigger check throws. */ interface ReactionBindingHealth { bindingId: string; event: string; counts: { pending: number; running: number; done: number; failed: number; dead: number; }; /** Age in ms (now minus createdAt) of the oldest receipt that is pending or failed; undefined when none. */ oldestQueuedAgeMs?: number; /** completedAt minus startedAt over the retained done receipts of this binding; undefined when there are none. */ latencyMs?: { count: number; p50: number; p95: number; max: number; }; /** Highest reactionDepth over the retained receipts of this binding. */ maxDepth: number; /** Sum of (attempt - 1) over the retained receipts with attempt >= 1. */ retries: number; /** Dead receipts grouped by their lastError (the dead reason, for example recursion_cap, max_attempts, stale_trigger, age_out). */ deadReasons: Record; lastError?: string; /** Events this binding's shouldHandle rejected since the process started (memory only, resets at boot). */ skipped: number; } interface ReactionHealth { generatedAt: number; started: boolean; maxReactionDepth: number; maxConcurrent: number; bindings: ReactionBindingHealth[]; /** Retained receipts whose binding is not live any more (a routine disabled or deleted), grouped by binding id. */ orphans: Array<{ bindingId: string; counts: { pending: number; running: number; done: number; failed: number; dead: number; }; }>; totals: { receipts: number; pending: number; running: number; done: number; failed: number; dead: number; }; } /** * `agent_start`'s input shape, extracted so every caller that lowers to an * `agent_start` call validates against the SAME definition: the MCP tool * itself (agent-tools.ts), a cron `kind:"agent"` action * (orchestration-tools.ts / cron-scheduler.ts) and an AIP-41 routine * `target.agent` (routine-registrar.ts). A new field added here works in all * three with no extra code. * * Field descriptions here are deliberately short — the contract, not the * manual. Full detail (edge cases, cross-field interactions, examples) lives * in `docs/mcp-tools/agent_start.md`, one `##` section per field, fetched on * demand via `tool_help {name:"agent_start", topic:""}`. */ /** * `agent_start` minus the fields meaningless for a detached fire (a cron job * or routine has no caller to block on, so `wait` is dropped). This is what a * cron `kind:"agent"` action and a routine `target.agent` accept. */ declare const detachedAgentStartSchema: z.ZodObject<{ label: z.ZodOptional; route: z.ZodOptional>, unknown>>; model: z.ZodOptional; mode: z.ZodOptional; mcpServers: z.ZodOptional | undefined; credentialRef?: string | undefined; args?: string[] | undefined; env?: Record | undefined; }[], unknown, z.core.$ZodTypeInternals<{ name: string; transport: "http" | "stdio" | "sse"; ref?: string | undefined; headers?: Record | undefined; credentialRef?: string | undefined; args?: string[] | undefined; env?: Record | undefined; }[], unknown>>, unknown>>; origin: z.ZodOptional; role: z.ZodOptional; auth: z.ZodOptional>, unknown>>; prompt: z.ZodOptional | Record[], unknown, z.core.$ZodTypeInternals | Record[], unknown>>>; agent: z.ZodOptional; adapter: z.ZodOptional; parent: z.ZodOptional; parentSessionId: z.ZodOptional; agentId: z.ZodOptional; cwd: z.ZodOptional; options: z.ZodOptional, unknown, z.core.$ZodTypeInternals, unknown>>, unknown>>; resumeSessionId: z.ZodOptional; sandboxCheckpoint: z.ZodOptional>, unknown>>; workspaceSlug: z.ZodOptional; restartPolicy: z.ZodOptional>, unknown>>; turnRetry: z.ZodOptional>; 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>, z.ZodNull]>, unknown>>; modelPolicy: z.ZodOptional>, unknown>>; keepAlive: z.ZodOptional>; allowPromptFrom: z.ZodOptional>; labelAddressing: z.ZodOptional>; operator: z.ZodOptional; operatorDigest: z.ZodOptional; harness: z.ZodOptional; effort: z.ZodOptional; posture: z.ZodOptional; contextProfile: z.ZodOptional; skills: z.ZodOptional, unknown>>; bundles: z.ZodOptional, unknown>>; notifyParentOnCrash: z.ZodOptional>; permissionHold: z.ZodOptional>; commandSandbox: z.ZodOptional>; contextContinuity: z.ZodOptional>, unknown>>; succeeds: z.ZodOptional; preflight: z.ZodOptional, unknown>>; placement: z.ZodOptional | undefined; }; model?: string | undefined; access?: { profileRef?: string | undefined; profileRefs?: string[] | undefined; } | undefined; preflight?: string[] | undefined; turnRetry?: { on: ("rate-limit" | "upstream-5xx" | "no-output-stall" | "usage-limit" | "quota-exhausted")[]; action?: "retry" | "migrate" | undefined; maxRetries?: number | undefined; baseDelayMs?: number | undefined; factor?: number | undefined; maxDelayMs?: number | undefined; maxMigrations?: number | undefined; retryAfterToolCalls?: boolean | undefined; rotate?: { model: string; profileRef?: string | undefined; }[] | undefined; rotateOn?: ("rate-limit" | "upstream-5xx" | "no-output-stall" | "usage-limit" | "quota-exhausted")[] | undefined; cooldownMs?: number | undefined; fallback?: { model?: string | undefined; access?: { profileRef: string; } | undefined; harness?: string | undefined; }[] | undefined; } | null | undefined; agentStartTimeoutMs?: number | undefined; }[]; }, unknown, z.core.$ZodTypeInternals<{ ladder: { sandbox: string | { provider: string; config: { [x: string]: any; installHarnesses?: string[] | undefined; }; mounts: any[]; read_only: boolean; reuse?: string | undefined; schema?: "sandbox/v1" | undefined; id?: string | undefined; version?: string | undefined; limits?: { timeout_ms?: number | undefined; memory_mb?: number | undefined; cpu_ms?: number | undefined; cpus?: number | undefined; } | undefined; env?: { passthrough: string[]; auth?: any; autoPassthrough?: boolean | undefined; } | undefined; network?: { egress: string[]; egressIp: string; } | undefined; join?: { tokenEnv: string; } | undefined; identity?: any; policy?: any; lifecycle?: { pause_after_idle?: string | undefined; destroy_on?: string | undefined; } | undefined; extraPorts?: number[] | undefined; metadata?: Record | undefined; }; model?: string | undefined; access?: { profileRef?: string | undefined; profileRefs?: string[] | undefined; } | undefined; preflight?: string[] | undefined; turnRetry?: { on: ("rate-limit" | "upstream-5xx" | "no-output-stall" | "usage-limit" | "quota-exhausted")[]; action?: "retry" | "migrate" | undefined; maxRetries?: number | undefined; baseDelayMs?: number | undefined; factor?: number | undefined; maxDelayMs?: number | undefined; maxMigrations?: number | undefined; retryAfterToolCalls?: boolean | undefined; rotate?: { model: string; profileRef?: string | undefined; }[] | undefined; rotateOn?: ("rate-limit" | "upstream-5xx" | "no-output-stall" | "usage-limit" | "quota-exhausted")[] | undefined; cooldownMs?: number | undefined; fallback?: { model?: string | undefined; access?: { profileRef: string; } | undefined; harness?: string | undefined; }[] | undefined; } | null | undefined; agentStartTimeoutMs?: number | undefined; }[]; }, unknown>>, unknown>>; appServe: z.ZodOptional>, unknown>>; full: z.ZodOptional; access: z.ZodOptional>, unknown>>; costBudget: z.ZodOptional>, unknown>>; sentinel: z.ZodOptional>; fields: z.ZodOptional>; browser: z.ZodOptional>>; attach: z.ZodOptional>, unknown>>; cloud: z.ZodOptional; boardId: z.ZodOptional; sandbox: z.ZodOptional | undefined; }, unknown, z.core.$ZodTypeInternals | undefined; }, unknown>>, unknown>>; worktree: z.ZodOptional>, unknown>>; inference: z.ZodOptional>, unknown>>; orchestrator: z.ZodOptional>, unknown>>; maxCostUsd: z.ZodOptional>; contextSettings: z.ZodOptional>, unknown>>; agentPath: z.ZodOptional; deferredTools: z.ZodOptional; presetId: z.ZodOptional; idempotencyKey: z.ZodOptional; dedupe: z.ZodOptional>; allowSharedCwd: z.ZodOptional>; daemonMount: z.ZodOptional>; notifyUrl: z.ZodOptional; notifySecret: z.ZodOptional; hooks: z.ZodOptional>, unknown>>; promptAppend: z.ZodOptional; trace: z.ZodOptional; resumeFrom: z.ZodOptional>, unknown>>; deviceBridge: z.ZodOptional>; }, z.core.$strip>; type DetachedAgentStartInput = z.infer; type CronCreator = { kind: "operator"; } | { kind: "system"; } | { kind: "external"; id: string; } | { kind: "session"; sessionId: string; proof: "proven" | "claimed"; }; /** * Daemon-native cron scheduler — persisted, survives restarts, * fires shell-command, agent-spawn, or session-reprompt jobs on a * 5-field cron schedule. * * Design decisions (see PLAN.md for rationale): * * ONE TICK LOOP (not one setInterval per job): a single 20-second interval * scans all active jobs, fires any whose `nextRunAt` has passed, recomputes * `nextRunAt`, and deactivates one-shot jobs after firing. Avoids timer * leaks/drift as jobs accumulate. * * COMMAND ALLOWLIST: `command` action jobs go through the same * `loadAllowlist` / basename check that `command_execute` uses — one * enforcement path, not two. * * SKIPPED FIRES: if the daemon was down past a fire time, the skipped * executions are NOT backfilled. Recurring jobs resume from "now"; * one-shot jobs that were missed while the daemon was down are fired * immediately on the next tick after restart. * * PERSISTENCE: `~/.agentproto/cron-jobs.json` and its `.runs.json` ledger, * each saved by atomic write-tmp+rename. The ledger retains the last 50 * completed fires per job. `nextRunAt` is recomputed from now on load when * a past fire time is detected. * * OUTCOME + HEALTH: an agent-spawning action is no longer judged at spawn. * After the spawn, the scheduler follows the session's FIRST turn via the * injected `observeTurn` (production: `cron-turn-observer.ts`, over * `monitorSessionWait`) and records a real `outcome` (`produced` / `empty` / * `errored` / `timeout`) with output tokens and duration. N consecutive * non-productive runs (default 2, per-job `maxConsecutiveFailures`) pause the * job with a `pausedReason`. The spawn lease is released before the * observation; a separate `observing` lease stops a re-fire while a previous * run is still being followed. * * EVENTS: `cron:fired`, `cron:succeeded`, `cron:failed`, `cron:unhealthy` * emitted on the shared SessionEventBus so outcomes are visible via * session_events_poll / session_monitor — no separate notification path. */ /** How loudly a job's SUCCESS is heard by its followers. Absent means * `always` (the pre-existing behaviour). `onFailure` downgrades a successful * `kind:"command"` run to an fyi digest; a failing command still crashes and * wakes. */ type CronNotify = "always" | "onFailure"; type CronAction = { kind: "command"; command: string; args?: string[]; cwd?: string; timeoutMs?: number; } | ({ kind: "agent"; } & DetachedAgentStartInput) | { kind: "prompt-session"; /** * Id of the session to re-prompt. Mutually exclusive with `agent`. * A persisted job carrying a plain `sessionId` keeps working exactly * as before — the id is followed to its successor / revived in place, * as it always was. */ sessionId?: string; /** * Agent-label target: the job re-prompts whichever LIVE session * carries this label, resolved at FIRE time (never at create time), so * the job survives the target session being relaunched under a new id * (a restart / continue-fresh keeps the label, the id changes). * Mutually exclusive with `sessionId`. */ agent?: string; prompt: string; } | { kind: "tool"; /** Registered MCP tool name, e.g. "worktree_gc", "agent_start". */ tool: string; inputs?: Record; }; interface CronJob { id: string; label?: string; /** 5-field cron expression in local time (minute hour day-of-month month day-of-week). */ schedule: string; /** IANA tz database name the schedule is interpreted in. Defaults to host local time. */ timezone?: string; /** When false, the job fires once then deactivates (one-shot). Default true. */ recurring: boolean; action: CronAction; /** How loudly this job's success is heard: absent means `always`. Only a * `kind:"command"` job's successful exit uses it. */ notify?: CronNotify; createdAt: string; /** When false, the job will not fire. */ active: boolean; /** A one-shot job has fired and will not fire again unless explicitly resumed. */ finished?: boolean; nextRunAt?: string; lastRunAt?: string; lastResult?: { ok: boolean; summary: string; }; /** * Real outcome of the LAST completed run (see {@link CronRunOutcome}), * maintained alongside the ledger so `cron_list` can report health without * reading run history. Absent on jobs created before this field existed. */ lastOutcome?: CronRunOutcome; /** * Consecutive non-productive runs since the last `produced` one. Reset to 0 * by a produced run (and on an explicit resume). Absent means 0. */ consecutiveFailures?: number; /** * Set when the health check auto-paused the job; cleared when an operator * resumes it. Free-text so the reason survives a daemon restart. */ pausedReason?: string; /** * Health threshold: pause after this many consecutive non-productive runs. * Defaults to {@link DEFAULT_MAX_CONSECUTIVE_FAILURES} (2). */ maxConsecutiveFailures?: number; /** * Per-job bound (ms) on how long to follow a spawned session's first turn * before recording `timeout`. Defaults to the scheduler's * `observeTimeoutMs` (30 min). */ runTimeoutMs?: number; /** * Session id the job belongs to — the creating session's * `?callerSessionId=` (a cron job a live agent re-arms for itself). The * scheduler deactivates (or relinks to the successor of) a job whose owner * is retired/gone on the next tick, so a dead owner's re-arms die with it. * Absent for operator/root-created jobs, which live until deleted or * (if set) `expiresAt`. */ ownedBy?: string; /** * ISO timestamp after which the job stops firing (deactivated on the next * tick). Defaulted to `now + DEFAULT_OWNED_JOB_TTL_MS` when `ownedBy` is set * and this is omitted, so an owned job can never outlive its owner forever; * absent for unowned jobs (which never expire). */ expiresAt?: string; /** * Who created the job and how well that creator was proven (AIP-46 * §Session principals), recorded once at creation and never changed by * `update`, a pause, a resume or a re-arm. Distinct from {@link ownedBy}, * which governs the job's lifetime and moves to a successor session. * Absent on jobs persisted before this field existed ("not recorded"). * Not yet used to restrict what a fired job may do. */ createdBy?: CronCreator; } /** Real outcome of a single cron run, as recorded in the ledger. */ type CronRunOutcome = "produced" | "empty" | "errored" | "timeout"; interface CronRun { runId: string; jobId: string; startedAt: string; endedAt: string; ok: boolean; sessionId?: string; result: string; error?: string; /** * Real outcome, when the run was observed to completion (or classified from * a known action status). Optional so ledger entries written before this * field existed still parse. */ outcome?: CronRunOutcome; /** Output tokens the spawned session produced, when reported. */ tokensOut?: number; /** Wall-clock duration of the observed run, when known. */ durationMs?: number; } interface CronUpdate { label?: string | null; schedule?: string; timezone?: string | null; recurring?: boolean; active?: boolean; action?: CronAction; /** Set/replace; `null` clears it (back to `always`). */ notify?: CronNotify | null; maxConsecutiveFailures?: number; runTimeoutMs?: number; /** Set/replace the expiry; `null` clears it (the job never expires). */ expiresAt?: string | null; } interface CronRunsPage { runs: CronRun[]; nextCursor?: string; } interface CronScheduler { /** * Create and persist a new cron job. Validates the schedule expression and, * for an agent-spawning action, that its host adapter resolves * (`assertCronAdapterResolvable`) — rejects if either is invalid. Returns * the created job. */ create(input: { label?: string; schedule: string; /** IANA tz database name. Defaults to host local time when omitted. */ timezone?: string; recurring?: boolean; action: CronAction; /** Omitted means `always`. See {@link CronJob.notify}. */ notify?: CronNotify; maxConsecutiveFailures?: number; runTimeoutMs?: number; /** Creating session id — see {@link CronJob.ownedBy}. Defaults the job's * `expiresAt` to `now + DEFAULT_OWNED_JOB_TTL_MS` unless one is given. */ ownedBy?: string; /** ISO expiry — see {@link CronJob.expiresAt}. */ expiresAt?: string; /** The creating principal — see {@link CronJob.createdBy}. */ createdBy?: CronCreator; }): Promise; list(): CronJob[]; get(id: string): CronJob | undefined; /** * Re-point every `prompt-session` job that named `fromSessionId` at * `toSessionId`: the cron RE-ARM a session restart needs. A restart * retires the old row and continues the same conversation under a NEW id, * so a job still naming the old id would fail its next tick with "session * not found" instead of following the conversation. * * Agent-LABEL targets (`action.agent`) are left alone on purpose: they * are resolved at FIRE time against whichever live session carries the * label, so they already survive a restart. * * Returns the ids of the jobs that were re-armed (empty when none * matched). The change is persisted with the rest of the job file. */ rearmSessionTarget(fromSessionId: string, toSessionId: string): string[]; update(id: string, patch: CronUpdate): Promise; runs(input?: { jobId?: string; limit?: number; cursor?: string; }): CronRunsPage; /** * Permanently remove a job. Throws if not found. */ delete(id: string): void; /** * Manually fire a job immediately, bypassing its schedule. * Returns the job's lastResult once the action completes. */ run(id: string): Promise; /** Clean up: stop the tick interval. */ shutdown(): void; } /** Dotted payload path to a primitive. Semantics: every entry must match, exact equality, AND of all entries. */ type EventFilter = Readonly>; type EventBindingSource = { kind: "routine"; routineId: string; } | { kind: "agent-on"; agentId: string; event: string; index: number; }; interface ResolvedEventBinding { /** routine: `routine:`; agent `on`: `/on//` (PLAN decision 15). */ bindingId: string; /** The parsed event ref; `event.event` is the canonical name (aliases resolved). */ event: HookEventRef; filter?: EventFilter; /** The AIP-41 target arm as authored (`action` | `workflow` | `tool` | `agent`), or `{ action, inputs? }` for an `on` entry. Not dispatched here. */ target: RoutineFrontmatter["target"]; source: EventBindingSource; /** Stable 16 hex chars: sha256 of the key-sorted JSON of { event: event.event, filter, target }. Same input, same revision, across processes. It hashes the config content only; the binding identity is `bindingId`. */ configRevision: string; } /** * AIP-41 routine runtime bridge — the piece that was missing before this * file existed: nothing read `.routines//ROUTINE.md` and turned it into a * live scheduled job. See `packages/routine/README.md` "Runtime bridge" * section for the full design writeup. * * `reconcile()` scans `/.routines//ROUTINE.md`, validates each * with `@agentproto/routine`'s `parseRoutineManifest`, and for every * `enabled:true` + `schedule.kind:"cron"` routine registers (or updates) a * `CronScheduler` job tagged `label:"routine:"`. `trigger()` fires a * routine's target immediately — bypassing both its schedule and its * `enabled` flag, same as `cron_run` bypasses an existing job's schedule — * without requiring a registered job to exist. * * Every target kind (tool / agent / workflow) resolves to the SAME * `{ tool, inputs }` pair before it ever reaches `CronScheduler` or * `dispatchTool` — one execution path, not three. `target.action` (AIP-39) * is validated but not dispatchable: no action resolver exists in this * runtime yet. */ interface ReconcileResult { /** Routine ids that now have a live cron job registered. */ registered: string[]; /** Routine ids parsed but not registered (disabled, or a non-cron schedule) with why. */ skipped: Array<{ id: string; reason: string; }>; /** Cron jobs removed because their routine vanished, was disabled, or was superseded by a changed one. */ removed: string[]; /** Files that failed to parse/validate or register — collected, not fatal to the rest of the scan. */ errors: Array<{ file: string; error: string; }>; /** Bindings resolved from enabled event routines; the reaction runner fires them. */ eventBindings?: ResolvedEventBinding[]; /** What the reaction wiring made live and refused for this pass, when a hook is installed. */ reactions?: { active: string[]; refused: Array<{ bindingId: string; error: string; }>; }; } interface RoutineRegistrar { /** * Scan, validate, and reconcile cron jobs for every routine found. Safe to * call repeatedly. A routine whose job the scheduler refuses (e.g. an * unresolvable `target.agent.harness`) lands in `errors`, never aborting * the rest of the pass. */ reconcile(): Promise; /** * Re-parse one routine by id and fire its target immediately via * `dispatchTool` — bypasses the schedule AND the `enabled` flag, and * does not require `reconcile()` to have run first. */ trigger(routineId: string): Promise<{ ok: boolean; summary: string; }>; /** Routine frontmatters known from the last `reconcile()` (parse errors excluded). */ list(): RoutineFrontmatter[]; /** Event bindings resolved by the last `reconcile()` (empty before the first call). */ eventBindings(): ResolvedEventBinding[]; } /** * Approvals — the daemon's human-approval primitive, on AIP-7 signatures. * * An `ApprovalRequest` pins an exact payload (sha256 of its canonical JSON) * behind a human decision. Only a declared human channel (`web_click`, * `ui_card`, `telegram`) may decide it — never a model-callable MCP tool. * An approve writes an AIP-7 `signature` on the pinned payload bytes and * appends a hash-chained audit event; a deny appends an audit event with no * signature. See AIP-7 (https://agentproto.dev/docs/aip-7) for the * accepted specification. */ declare const APPROVAL_STATUSES: readonly ["pending", "approved", "denied", "expired", "consumed"]; type ApprovalStatus = (typeof APPROVAL_STATUSES)[number]; declare const APPROVAL_CHANNELS: readonly ["web_click", "ui_card", "telegram"]; type ApprovalChannel = (typeof APPROVAL_CHANNELS)[number]; type ApprovalDecision = "approve" | "deny"; /** Who asked. A spawned session, or the operator (root `/mcp`, HTTP twins). */ type ApprovalRequester = { sessionId: string; } | { operator: true; }; /** Who to re-prompt when the approval is decided: the session that opened * it, or an agent label (resolved at decision time, like a cron's `agent` * target, so a relaunched agent still hears the answer). */ interface ApprovalWakeTarget { sessionId?: string; agent?: string; } /** `reach` on a request: `false` keeps the REACH router silent for this * approval, an object sets the message urgency. `now` is accepted from * producer code (`POST /approvals`) only, never from the model-callable * `approval_request` tool. Stored on the record; ignored when the daemon * has no `reach.routes`. */ type ApprovalReachOption = false | { urgency: "now" | "normal" | "digest"; }; interface ApprovalDecisionRecord { decision: "approved" | "denied"; channel: ApprovalChannel; decidedAt: string; /** Workspace-relative path to the AIP-7 signature.json — present only * on an approve (a deny writes an audit event, never a signature). */ signaturePath?: string; /** The verified Telegram user id of the human who decided, when the * decision came through an approval link (`POST * /approvals/:id/decision/telegram` under a link-session token). Absent * for every other decision, including the bot bridge's. */ telegramUserId?: string; } interface ApprovalRecord { id: string; kind: string; title: string; /** JSON-ready preview for a UI to render, supplied verbatim by the * requester. Opaque to the engine. */ preview: unknown; /** sha256 (hex) of the canonical JSON of the payload written to * `/payload.json` at request time. */ payloadHash: string; status: ApprovalStatus; requestedBy: ApprovalRequester; /** Opt-in: re-prompt this session or agent when a human decides. */ wake?: ApprovalWakeTarget; taskId?: string; appId?: string; /** Human channels allowed to decide this approval. */ channels: readonly ApprovalChannel[]; requestedAt: string; expiresAt?: string; /** As requested; absent when the request did not say. */ reach?: ApprovalReachOption; decision?: ApprovalDecisionRecord; consumedAt?: string; } /** A decision a subscriber still has to deliver to the system that asked for * it (the Bureau bridge's W2 relay). Persisted next to the approval record as * `/relay-outbox.json`, so a daemon restart or an outage on the other side * does not lose the human's answer. Holds NO header values or credentials: the * target comes from `payload.json` and the connection is re-resolved at send. */ interface RelayOutboxEntry { approvalId: string; decision: "approved" | "denied"; /** Failed delivery attempts so far. */ attempts: number; queuedAt: string; } /** A Telegram card the bridge has sent and not yet closed. Persisted next to * the approval record as `/telegram-card.json`, so a tap on a card sent * before a daemon restart still decides, and a decision made while the daemon * was down still strips the old message's buttons. `token` is the opaque * random callback token; no bot token, chat id or user id is stored. * `parseMode` says how `text` must be sent back when the card is closed; a * card written before the HTML cards has none and is plain text. */ interface TelegramCardEntry { token: string; approvalId: string; messageId: number; text: string; parseMode?: "HTML"; } /** One REACH attempt for an approval, kept append-only in `/reach.json`. * A receipt plus the key it was for and what triggered it (`route` for the * `approval:requested` pass, `watchdog` for the floor). No URL, secret, chat * id or user id is ever stored. */ interface ReachReceiptEntry { dedupeKey: string; adapterId: string; kind: string; status: "delivered" | "deferred" | "deduped" | "undelivered" | "failed"; until?: string; reason?: string; at: string; trigger: "route" | "watchdog"; } /** * The approvals engine — the daemon's human-approval primitive (AIP-7 * signatures as the mechanism). * * Every mutation here is atomic in the sense the Orchestrator M1 gate uses the * word: the status check + in-memory mutation + sync persistence happen * with NO `await` between them, so a second concurrent call always * observes the first call's write. The AIP-7 signature write * (`signArtifact`) and its audit event are async and run AFTER that * synchronous transition — a decide can never race itself, only the * signature can arrive slightly after the status flip a `wait()` caller * already observed pending→approved. * * Nothing exported here can decide, mint a ticket, or sign — `decideWeb` * is reachable only from the HTTP route `POST /approvals/:id/decision`, * `decideTelegram` only from `POST /approvals/:id/decision/telegram` (gated * by a bot-bridge shared secret instead of an Origin — a webhook callback * has no browser Origin to check; or by an approval link bound to that one * id and an allow-listed Telegram user), `mintCardTicket`/`decideByCard` only * from the app-only `approval_card_list` / `approval_card_decide` tools. The MCP * tools facing an agent (`approvals/tools.ts`) expose only `request` / * `get` / `wait` / `consume`. * * No task-board coupling here — that lands in a later lane (E1b). A * request's `taskId` is recorded verbatim and rides the `approval:*` * events for a future subscriber; this engine never reads or writes a * task ledger. */ interface ApprovalRequestInput { kind: string; title: string; preview: unknown; payload: unknown; taskId?: string; appId?: string; /** Restrict to a subset of the enabled channels. Omit for "every * channel this daemon has enabled" (see {@link ApprovalsEngineOptions.webOrigins}). */ channels?: readonly ApprovalChannel[]; expiresAt?: string; /** Re-prompt this session or agent label when a human decides. */ wake?: ApprovalWakeTarget; /** REACH opt-out or urgency, stored on the record as given. */ reach?: ApprovalReachOption; } interface ApprovalListFilter { status?: ApprovalStatus; } interface ApprovalDecideEvidence { ipAddress: string; userAgent: string; /** The decider's verified Telegram user id (approval link only). Stored * on the decision record and carried by `approval:decided`. */ telegramUserId?: string; } interface ApprovalsEngine { enabledChannels: readonly ApprovalChannel[]; request(input: ApprovalRequestInput, requester: ApprovalRequester): ApprovalRecord; get(id: string): ApprovalRecord | undefined; /** The pinned payload's parsed JSON, read from `/payload.json`. This is * the restart-safe source for a subscriber that acts on a decision: * `undefined` when the file is missing or unparsable. */ getPayload(id: string): unknown | undefined; list(filter?: ApprovalListFilter): ApprovalRecord[]; /** Persist a decision a subscriber still has to deliver, next to the * approval record. Overwrites an earlier entry for the same approval. */ putRelayOutbox(entry: RelayOutboxEntry): void; /** Drop the entry once the decision is delivered or can never be. */ removeRelayOutbox(id: string): void; /** Every persisted undelivered decision, read from disk. */ listRelayOutbox(): RelayOutboxEntry[]; /** Record that the decision reached the system that asked for it, so the * boot sweep does not relay it again. */ markRelayed(id: string): void; /** Whether {@link markRelayed} was called for this approval. */ isRelayed(id: string): boolean; /** Persist an open Telegram card next to the approval record, so a tap on it * still works after a daemon restart. Overwrites an earlier card. */ putTelegramCard(card: TelegramCardEntry): void; /** Drop the card once its message is closed, whatever the channel. */ removeTelegramCard(id: string): void; /** Every persisted open Telegram card, read from disk. */ listTelegramCards(): TelegramCardEntry[]; /** Every REACH attempt for this approval (`/reach.json`), oldest first. */ listReachReceipts(id: string): ReachReceiptEntry[]; /** Append one REACH attempt next to the approval record. */ appendReachReceipt(id: string, entry: ReachReceiptEntry): void; /** Resolves once the approval leaves `pending` (approved/denied/expired), * or after `timeoutMs` with whatever the current record is (still * pending, most likely). Resolves immediately if already decided. */ wait(id: string, timeoutMs: number): Promise; decideWeb(id: string, decision: ApprovalDecision, evidence: ApprovalDecideEvidence): Promise; decideTelegram(id: string, decision: ApprovalDecision, evidence: ApprovalDecideEvidence): Promise; mintCardTicket(id: string): { ticket: string; expiresAt: string; }; decideByCard(id: string, decision: ApprovalDecision, ticket: string, evidence: ApprovalDecideEvidence): Promise; consume(id: string, requester: ApprovalRequester, payload: unknown): ApprovalRecord; dispose(): void; } interface HeapReport { at: string; memory: NodeJS.MemoryUsage; /** `heapUsed` sampled right after the last major (mark-compact) GC, and * when. Absent until the first major GC of this process. */ afterMajorGc?: { heapUsed: number; at: string; }; majorGcs: number; /** `process.getActiveResourcesInfo()` grouped by type (Timeout, TCPWRAP, * FSReqCallback, ...): a timer or socket that leaks shows up here. */ handles: Record; /** Per-probe sizes, keyed by probe name. */ structures: Record | { error: string; }>; } type HeapSnapshotResult = { ok: true; path: string; heapUsed: number; freeBytes: number; durationMs: number; warning: string; } | { ok: false; error: "insufficient_memory"; message: string; heapUsed: number; freeBytes: number; requiredBytes: number; } | { ok: false; error: "snapshot_failed"; message: string; }; /** * `GET /sessions/:id/screencast.jpg` for an id that is not a chrome-live * browser descriptor: a Bureau `browser_screenshot` (JPEG) of the newest open * tab owned by session `:id`. Called as a raw imported tool, that result is a * JSON object `{ base64, format, width, height }` (not an MCP `image` block), * handed over as `structuredContent`, as a `text` block holding the JSON, or * both; `parseImage` reads all of those plus the `image` block. The bytes * field is `base64` (the driver layer calls it `data`; both are read). No * recording is started or needed, so any session that owns an open tab can be * watched with no cooperation from the agent. * * Every Bureau call is made AS the path id (the imported-tool call takes a * caller session id, forwarded in `x-agentproto-caller-session`), so Bureau's * own tab ownership decides what is visible: a caller only ever gets the * viewport of a tab opened for that session. The route is read-only; nothing * here clicks, types or reaches another tab. The HTTP gate (bearer, or a link * token whose `sessionId` / `browserSessionId` claim equals the path id) * decides who may ask. * * Each frame is a real CDP capture of the user's browser, so it is rate * limited: a per-session frame cache (a frame under FRAME_FRESH_MS old is * served as is), one shared in-flight capture per session, and at most * MAX_CONCURRENT_CAPTURES captures in flight for the whole reader. The frame * cache is keyed by session id only, in memory, capped and expiring. */ type SessionScreencastMissReason = "not_wired" | "no_tab" | "bureau_error" | "bad_result"; type SessionScreencastOutcome = { ok: true; bytes: Buffer; mimeType: string; } | { ok: false; reason: SessionScreencastMissReason; }; interface SessionScreencastReader { read(sessionId: string): Promise; } /** * The daemon live relay of a session's browser tab (session-chat live * contract, T3): `GET /sessions/:id/live.mjpeg` and * `GET|HEAD /sessions/:id/live/:streamId/replay.mp4`. * * `live.mjpeg` picks the tab exactly like the screencast reader * (session-screencast.ts): the newest open tab Bureau lists as owned by `:id`, * moving on to the next one when Bureau refuses a tab (`target_gone`). It then * calls Bureau `browser_live_view` AS `:id` with `reuse: true`, so a stream the * agent's own widget is already watching is shared, not replaced, takes the * result's `urls.loopback`, refuses anything that is not * `http://127.0.0.1:/s/`, and pipes that MJPEG body verbatim. * The relay never calls `browser_live_stop`: the stream belongs to the tab. * A client disconnect aborts the upstream request. * * Bureau's token URLs never leave this module: no response body, header or * log line carries them. Every miss is the same 404 body, logged with a * reason only. The last {@link REMEMBERED_STREAMS} streams relayed per * session are remembered in memory (`streamId` -> replay URL, 24 h) so the * replay route can relay the kept video of a stream that ended, with the * client's `range` header passed through. * * Who may ask is the HTTP gate's call (bearer, or a link token whose * `sessionId` / `browserSessionId` claim equals `:id`, app-link-gate.ts). */ interface SessionLiveRelay { /** Answer `GET /sessions/:id/live.mjpeg`. Always ends `res`. */ serveLive(req: IncomingMessage, res: ServerResponse, sessionId: string): Promise; /** Answer `GET|HEAD /sessions/:id/live/:streamId/replay.mp4`. Always ends `res`. */ serveReplay(req: IncomingMessage, res: ServerResponse, sessionId: string, streamId: string): Promise; /** Relayed connections open right now (tests, diagnostics). */ activeCount(sessionId?: string): number; } /** * Per-call resolver for the `config.json` `defaults` knobs that gate * inter-session messaging: `defaults.agentPromptInterrupt`, * `defaults.messaging.allowSiblings`, `defaults.messaging.allowSameWorkspace`, * `defaults.messaging.peerGroups`, `defaults.messaging.agentInterrupt`. * * These used to be read ONCE at gateway boot (`index.ts`'s `configDefaults`, * captured before the `/mcp` and `/mcp/orchestrator` server factories were * built) and then closed over as static booleans/enums for the lifetime of * the daemon — so a `config_set` change never took effect without a * restart, unlike every other spawn-time `defaults.*` key (which * `session-spawn.ts` already re-reads per spawn). Both MCP gateways rebuild * their `McpServer` from scratch on EVERY request (the SDK's stateless * pattern — see `serveMcp` in `http-server.ts`), so calling this resolver * inside each factory, instead of reusing a boot-time snapshot, is all * "hot" requires: the very next `agent_prompt` / `message_parent` / * `message_send` / `message_reply` call already runs through a fresh * `McpServer` build. * * Mirrors the read-per-call discipline of `spawn-attach.ts` / * `spawn-dedupe.ts` / `worktree-isolation.ts` — no caching: `loadConfig` is * a small file read and is already called this often elsewhere. */ interface ResolvedMessagingDefaults { /** `defaults.agentPromptInterrupt` — the unset-default for `interrupt` on * `agent_prompt` / `message_parent`. Default false. */ agentPromptInterrupt: boolean; /** `defaults.messaging.allowSiblings` - lets `message_send` / * `message_reply` reach a sibling (same parent). Default false. */ allowSiblings: boolean; /** `defaults.messaging.allowSameWorkspace` - lets `message_send` / * `message_reply` reach any session of the SAME workspace, even without * a tree edge. Default true. */ allowSameWorkspace: boolean; /** `defaults.messaging.peerGroups` - groups of workspace slugs. Two * sessions may message each other without a tree edge when both * workspace slugs sit in the SAME group. Default [] (no * cross-workspace link). Independent of `allowSameWorkspace`. */ peerGroups: string[][]; /** `defaults.messaging.grants` - explicit AIP-38 `session:message` * grants. A matching allow admits a pair the tree and the switches * refuse; a matching deny wins. Default [] (nothing changes). */ grants: Grant[]; /** `defaults.messaging.peerBinding` - "slug" (default): peers by recorded * workspace slug; "verified": both cwds must resolve to the same * registered workspace. */ peerBinding: "slug" | "verified"; /** `defaults.messaging.agentInterrupt` — whether a SESSION sender's * `interrupt` may cancel the recipient's turn. Default "deny". */ agentInterrupt: "allow" | "deny"; /** `defaults.messaging.pendingPromptStaleMinutes` — minutes a queued prompt * may wait before its sender is told it is stuck. Default 5. */ pendingPromptStaleMinutes: number; /** Top-level `delivery.apply` (the K6 funnel), read with the messaging * knobs so a `message.*` type opted in takes effect on the next send. * Absent = off. */ deliveryApply?: DeliveryApplyConfig; /** `defaults.messaging.anonymousSend` - "label" (default): an anonymous or * unverified sender may message any live session, labelled unverified and * capped at steer. "block": an unverified session sender outside the usual * relations is refused (`forbidden_recipient`). */ anonymousSend: "block" | "label"; /** `defaults.messaging.labelAddressing` - "tree" (default): a label given by a * supervisor to 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"; } /** * Size ceilings for the workspace-brain ingest reader. * * The brain ingests a whole session by materializing `events.jsonl` into one * `ExportedMessage[]` (see `transcript-export.ts`), then chunks it. A * multi-hundred-MB transcript therefore becomes one very large array in a * single burst, which is the heap-growth suspect this cap exists to bound. * * Two ceilings, because they catch different explosions: * - `maxTranscriptBytes` is checked against the FILE size before a line is * parsed, so an oversized capture is refused without reading it at all. * - `maxTranscriptTextBytes` is a running ceiling on accumulated message * text while parsing: a small JSONL can still expand into a large * transcript (repetitive delta records, escaped strings, command output). * * A third ceiling bounds the QUERY side, for the in-memory fallback only: * `maxIndexDocs` caps how many files a brain's `files` provider holds in its * in-process BM25 index when it cannot use the on-disk FTS5 index (no * `node:sqlite` with FTS5). Above it that index keeps the most recently * modified files and results are flagged `partial`. The on-disk index has no * ceiling, and search is never refused. * * All are defaults, overridable under `defaults.reactions.brainIngest` in * `~/.agentproto/config.json`. Explicit operator exports (session transcript, * conversation read/export, checkpoints) do NOT pass these limits — only the * brain reader does. */ /** 32 MB. A normal long agent session is a few MB of JSONL; 32 MB is well * above that and still bounded. */ declare const DEFAULT_BRAIN_MAX_TRANSCRIPT_BYTES: number; /** 8 MB of extracted message text. The brain chunks the transcript at 3.5 KB * per source (`DEFAULT_CHUNK_MAX_BYTES`), so even a few MB is hundreds of * sources; past 8 MB the ingested-and-queryable value no longer justifies the * memory burst. */ declare const DEFAULT_BRAIN_MAX_TRANSCRIPT_TEXT_BYTES: number; interface BrainIngestLimitConfig { /** File-size ceiling for `events.jsonl`, in bytes. */ readonly maxTranscriptBytes?: number; /** Running ceiling on accumulated message text, in bytes. */ readonly maxTranscriptTextBytes?: number; /** Ceiling on the files one brain's in-memory fallback index holds. */ readonly maxIndexDocs?: number; } interface BrainIngestLimits { readonly maxTranscriptBytes: number; readonly maxTranscriptTextBytes: number; readonly maxIndexDocs: number; } /** Resolve configured ceilings, falling back per-field to the defaults for * anything absent, non-positive, or non-finite. */ declare function resolveBrainIngestLimits(config?: BrainIngestLimitConfig): BrainIngestLimits; /** * Runtime-side glue for the per-workspace brain: a shared registry of * {@link BrainManager}s (one per workspace bucket) plus the two bridges that * connect the pure `@agentproto/workspace-brain` engine to this daemon's real * conversation stores: * * - `readSessionForBrain` — a session id → exported transcript, via the same * ladder as `conversation-read.ts`: the provider-native store first * (`CONVERSATION_STORES`), then the universal `events.jsonl` capture * (`exportDaemonEventsSession`). `null` when neither has anything. * - `resolveWorkspace` — a session id → the workspace bucket it was recorded * under (via the persisted `conversations.jsonl` index). * * The registry itself is keyed by bucket slug and creates each `BrainManager` * lazily, so a workspace that never produces a session pays nothing until its * first exit does. * * A workspace's knowledge backends are configured per-workspace by a * `knowledge.json` file at `/knowledge.json` (see * {@link loadKnowledgeConfigForWorkspace}). No file → the brain's default * single `files` provider (identical to pre-config behavior); an invalid * file → warn + fall back to that default; never throws either way. */ /** The shared registry handed to both the subscriber and the MCP tools. */ interface WorkspaceBrains { /** Get (creating lazily) the brain manager for a workspace bucket slug. */ getBrain(workspace: string): BrainManager; /** Map a session id to the workspace bucket it was recorded under. */ resolveWorkspace(sessionId: string): Promise; /** Resolve an explicit workspace slug (or caller slug) to a safe bucket * slug — "default" when unregistered/absent (membership rule). */ resolveWorkspaceSlug(workspace?: string, callerSlug?: string): string; } /** Resolve a session id to its exported transcript, native first then daemon * events — `null` (never throws) when neither store has anything readable. * This is the uncapped, public operator-facing reader; the brain uses * {@link readSessionForBrainWithLimits} so it never materializes an * oversized transcript. */ declare function readSessionForBrain(sessionId: string): Promise; interface CreateWorkspaceBrainsOptions { /** Ingest ceilings for the transcript reader, plus the per-brain index * ceiling. Defaults to {@link resolveBrainIngestLimits} values (32 MB file / * 8 MB text / 100,000 indexed files). */ readonly limits?: BrainIngestLimits; } declare function createWorkspaceBrains(opts?: CreateWorkspaceBrainsOptions): WorkspaceBrains; /** * Shared types for pluggable tunnel providers. * * Extracted here so both `RemoteController` (single-gateway tunnel) and * `TunnelRegistry` (multi-tunnel general surface) can share the same * provider contract without creating a circular dep. * * The tunnel family is the FIRST consumer of `@agentproto/provider-kit`: * {@link TunnelProviderHandle} extends the kit's generic `AdapterHandle` * (slug/name/version/description/requiresSetup/check) with the * tunnel-specific `capabilities` + the existing `start`/`stop` lifecycle. */ interface ProviderStartOptions { /** Local target the tunnel forwards to. */ target: { host: string; port: number; }; /** Workspace path — for log / state files. */ workspace: string; /** Called whenever the provider has a status update worth logging. */ onLog?: (line: string) => void; /** * The tunnel's stable identity + desired hostnames, for providers that * own remote state (e.g. `cloudflare-managed`). Ignored by the others. */ tunnel?: TunnelIdentity; /** Health updates from providers that monitor themselves. */ onHealth?: (health: TunnelHealth) => void; } /** Stable identity of a registry tunnel, as seen by a stateful provider. */ interface TunnelIdentity { /** Survives daemon restarts — the registry passes `name ?? id`. */ key: string; /** Hostnames routed to the tunnel, primary first. */ hostnames: string[]; /** * Provider-side tunnel id stored on the descriptor, when one exists. Lets a * provider tell a never-provisioned local record from one with remote state. */ tunnelId?: string; /** * Hostname root asked of a provisioning service (`cloudflare-provisioned`), * e.g. `agentproto.cloud`. Unset = the service's default for the caller. */ root?: string; } type TunnelHealthState = "active" | "degraded" | "error"; /** Live health of a self-monitoring tunnel (surfaced in `tunnel_status`). */ interface TunnelHealth { state: TunnelHealthState; reason?: string; checkedAt: string; /** Per-hostname probe result (all hostnames during a swap overlap). */ hostnames?: Array<{ hostname: string; ok: boolean; reason?: string; }>; } interface ProviderStartResult { publicUrl: string; pid: number | null; /** Provider-side tunnel id, when the provider created/looked one up. */ tunnelId?: string; /** * Hostnames actually routed, primary first — set when the provider (or a * remote provisioner) decides them rather than the caller. */ hostnames?: string[]; } /** * A pluggable tunnel provider. * * `start` returns the public URL once the upstream tunnel is ready. * `stop` is idempotent — calling it twice or on an already-dead child * must not throw. * * Providers that own remote state may also implement the optional * `destroy` (delete everything they created) and `addHostname` / * `removeHostname` (hostname swap with overlap). All three work whether or * not the tunnel is currently running. */ interface RemoteProvider { readonly id: string; start(opts: ProviderStartOptions): Promise; stop(): Promise; destroy?(tunnel: TunnelIdentity): Promise; addHostname?(tunnel: TunnelIdentity, hostname: string): Promise; removeHostname?(tunnel: TunnelIdentity, hostname: string): Promise; } /** * Thrown by `RemoteProvider.start()` when `stop()` landed while the start * was still in flight and the provider already cleaned up its own process. * This is an abort, not a failure: the registry settles the tunnel as * `stopped` (so `autostart` relaunches it on the next boot) rather than * `error`. Matched with `instanceof`, never by message. */ declare class TunnelStartAbortedError extends Error { constructor(message?: string); } /** * Slug-keyed tunnel provider registry — the single source of truth that both * halves of the tunnel family consult: * * - the adapter-kit listing path (`list_tunnel_adapters` / `setup_tunnel_provider`) * - the lifecycle path (`TunnelRegistry`: create / restore / start / stop) * * Before this module those two halves spoke different languages — the * lifecycle engine only knew the short discriminators `"quick"`/`"named"` and * had no ngrok case at all, while the adapter half spoke slugs. They never * reconciled, so ngrok was listable-but-not-creatable. Routing everything * through one registry collapses that: a built-in OR a third-party * `@agentproto/adapter-` / `@agentproto/harness-` / * `@/agentproto-adapter-` / * `@/agentproto-harness-` provider * resolves the same way and works end to end. */ /** Per-slug credentials, as stored by the creds store / setup tool. */ type TunnelCreds = Record; /** * TunnelRegistry — multi-tunnel public-URL manager. * * Manages a named set of cloudflared (or future provider) tunnels, * each forwarding a local port to a public URL. Independent from * RemoteController which handles the single "expose this gateway" * use-case with bearer-token gating. This registry is for the general * "create a public endpoint for any local port" surface. * * Lifecycle: * create(input) → spawns provider, waits for URL, stores descriptor * list() → TunnelDescriptor[] * get(id) → TunnelDescriptor | undefined * stop(id) → SIGTERM provider, mark stopped * shutdown() → stop all active tunnels (called on daemon exit) * * Persistence: `~/.agentproto/tunnels.json` — descriptors survive * daemon restarts; active entries are marked "stopped" on next boot * since their child processes are gone (same GHOST pattern as * sessions.ts). */ type TunnelStatus = "starting" | "active" | "stopped" | "error"; /** * Provider identifier — an open set of slugs (built-in `cloudflare-quick` / * `cloudflare-named` / `ngrok`, legacy short names `quick` / `named`, or any * third-party `@scope/agentproto-adapter-`). Normalized to a canonical * slug only at resolve time, so persisted descriptors keep their original * value and need no migration. */ type TunnelProvider = string; interface TunnelDescriptor { id: string; /** Optional user-friendly slug. Accepts id-or-name in stop/status calls. */ name?: string; /** Free-text label surfaced in list / CLI table. */ label?: string; provider: TunnelProvider; targetHost: string; targetPort: number; publicUrl: string; status: TunnelStatus; pid: number | null; createdAt: string; stoppedAt?: string; lastError?: string; /** * When true, the tunnel is relaunched on daemon boot (see * `restoreOnBoot`). Only meaningful for `named` tunnels — a relaunched * `quick` tunnel gets a fresh random URL, so autostart for it merely * keeps *a* tunnel up, not a stable URL. */ autostart?: boolean; /** Stable public hostname routed to this tunnel. */ hostname?: string; /** Cloudflare tunnel id or name (the `run` target). */ tunnelId?: string; /** Path to the tunnel credentials JSON (defaults under ~/.cloudflared). */ credentialsFile?: string; /** * Every hostname routed to the tunnel, primary (`hostname`) first. More * than one only during a hostname swap's overlap window — the old one * stays live until `removeHostname` retires it. */ hostnames?: string[]; /** * Live health from a self-monitoring provider: `active` (public hostname * answers from the app), `degraded` (edge 5xx / unreachable / cloudflared * restarting) or `error` (cloudflared crash-looping), with a `reason`. * Unset while stopped and for providers that don't monitor themselves. */ health?: TunnelHealth; /** * `"private"` (default, including on descriptors persisted before this * field existed) puts a signed-link guard in front of the target before * handing it to the provider — `publicUrl` alone is a dead end without a * valid `?t=` token or cookie. `"public"` is the explicit opt-out: the * provider forwards straight to the target, exactly like every tunnel * before this field existed. */ access?: "private" | "public"; /** The raw `ttl` the tunnel was created with (e.g. "24h"), echoed back — * informational only; `expiresAt` is the enforced value. Unset for * `access: "public"` (no guard, no expiry). */ ttl?: string; /** ISO timestamp the current signed link stops working at. Unset for * `access: "public"`. Refreshed by `revoke()`. */ expiresAt?: string; /** * The link to actually hand to a human: `publicUrl` with the current * guard token baked in (`?t=…`) for `access: "private"`, or identical to * `publicUrl` for `access: "public"`. Always read this, never * `publicUrl` alone, when you need something a browser can open. */ url?: string; /** * Caller-chosen stable identity (the provider contract's `key`), set only through * {@link TunnelRegistry.ensureKeyed}. When present it is the key handed to * stateful providers instead of `name-`, so a re-ensure or a * daemon boot reuses the SAME remote tunnel. At most one descriptor per key. */ key?: string; /** Keyed tunnels only: who the tunnel belongs to, so its owner finds it * again without parsing the (derived, lossy) key. */ owner?: TunnelOwner; /** Keyed tunnels only: the hostname the caller requested (normalized), kept * apart from `hostname` because a provider may assign another name. */ hostnameRequest?: string; /** * `cloudflare-provisioned` only: the hostname root asked of the * provisioning service (e.g. `agentproto.cloud`), normalized. Unset = the * service picks (the API key's root, else its default). Replayed on every * start so a restart stays on the same root. */ root?: string; /** Set only for `access: "public"` — surfaced back to the caller (and * logged) since skipping the guard is the one choice here with real * blast radius if picked by habit instead of intent. */ warning?: string; } /** The app service a keyed tunnel was created for (AIP-53 `expose`). */ interface TunnelOwner { appId: string; service: string; } interface CreateTunnelInput { targetPort: number; provider?: TunnelProvider; name?: string; label?: string; targetHost?: string; /** Relaunch this tunnel on daemon boot. See `TunnelDescriptor.autostart`. */ autostart?: boolean; /** Stable public hostname (e.g. app.example.com). */ hostname?: string; /** Cloudflare tunnel id or name to `run`. */ tunnelId?: string; /** Path to the credentials JSON (defaults to ~/.cloudflared/.json). */ credentialsFile?: string; /** * Explicit opt-out of the access guard — the tunnel forwards straight to * the target, exactly like every tunnel before the guard existed. Default * false: every tunnel is private-by-default (signed link, TTL, instant * revoke) unless this is set. */ public?: boolean; /** TTL for the signed link, e.g. "1h" / "24h" / "7d" (default "24h", see * `parseTtlMs`). Ignored when `public` is set — a public tunnel has no * guard and so no expiry of its own. */ ttl?: string; /** Stable identity, see {@link TunnelDescriptor.key}. Use `ensureKeyed`; * `create` refuses a key that is already registered. */ key?: string; /** Keyed tunnels only, see {@link TunnelDescriptor.owner}. */ owner?: TunnelOwner; /** `cloudflare-provisioned` only, see {@link TunnelDescriptor.root}. */ root?: string; } interface TunnelRegistryOptions { /** Absolute path for persistence file. Defaults to ~/.agentproto/tunnels.json */ persistPath?: string; /** Absolute path to workspace — used as scratch dir for provider config files. */ workspace?: string; /** Hook for surfacing provider log lines. */ onLog?: (line: string) => void; /** * Read stored credentials for a provider slug. Lets the lifecycle build a * provider that keeps its secrets in the creds store (e.g. ngrok's authtoken, * or any third-party provider) rather than on the descriptor. Injected by the * daemon (index.ts); descriptor-carried config (named's hostname/tunnelId) * still takes precedence. */ readCreds?: (slug: string) => Promise; /** * The daemon's own gateway. A `public` tunnel (no access guard) to this * port is refused while `isProtected()` is false: the gateway only * demands its bearer on non-local requests in bearer mode * (`remote_enable` / static `auth`), so such a tunnel would publish * sessions, MCP and commands to anyone with the URL. */ gatewayGuard?: { port: number; isProtected: () => boolean; }; } declare class TunnelRegistry { private readonly tunnels; private readonly persistPath; private readonly workspace; private readonly onLog; private readonly readCreds; private readonly gatewayGuard; private persistTimer; private closed; /** Per-key in-flight chain for `ensureKeyed`: two concurrent ensures of the * same key must never both miss and create two tunnels. */ private readonly keyLocks; constructor(opts?: TunnelRegistryOptions); create(input: CreateTunnelInput): Promise; /** * Idempotent create on a stable `key` (the provider contract's `create` semantics): returns * the descriptor already registered under `key` when it is running with the * same target, access and hostname request; restarts it in place (same * descriptor, same provider key, so the same remote tunnel) when it is * stopped, errored or its config changed; and only creates a new one when * no descriptor holds the key. A provider change deletes the old tunnel * first. Never leaves two descriptors with one key. Not autostart: the * owner of the key re-ensures it on boot. */ ensureKeyed(input: CreateTunnelInput & { key: string; }): Promise; private ensureKeyedNow; /** The descriptor registered under a stable `key`, if any. */ findByKey(key: string): TunnelDescriptor | undefined; /** * Drive an entry's provider through start and fold the result back into * its descriptor. On failure the descriptor is marked `error` and the * error re-thrown (callers that want best-effort — e.g. boot restore — * catch it). Shared by `create` and `restoreOnBoot`. */ private startEntry; private markStopped; /** * Relaunch every `autostart` tunnel that isn't currently running. Called * once on daemon boot — `loadFromDisk` has already ghosted formerly-live * entries to `stopped` and given autostart ones a real provider. Quick * tunnels are skipped (a relaunch yields a fresh random URL, defeating * the point); named tunnels come back on their stable hostname. * * Best-effort: a provider that fails to start leaves its descriptor in * `error` and the others still come up. */ restoreOnBoot(): Promise; list(): TunnelDescriptor[]; get(id: string): TunnelDescriptor | undefined; findByIdOrName(idOrName: string): TunnelDescriptor | undefined; stop(idOrName: string): Promise; /** * Stop the tunnel AND delete what its provider created remotely (for * `cloudflare-managed`: the CNAMEs, then the tunnel itself), then forget * the descriptor. Providers without remote state are just stopped and * forgotten. Returns false when no such tunnel exists. If the remote * delete fails the descriptor is kept (`lastError` set) so it can be * retried — nothing is orphaned silently. */ delete(idOrName: string): Promise; /** * Hostname swap, step 1: route `hostname` to the same tunnel (ingress + * DNS) and make it the primary, while every hostname already routed keeps * working. Consumers move over at their own pace; retire the old one with * {@link removeHostname}. Works whether the tunnel is running or stopped. */ addHostname(idOrName: string, hostnameRaw: string): Promise; /** * Hostname swap, step 2: stop routing `hostname` (ingress + the engine's * own CNAME). Refuses to remove the last hostname — use `delete`. */ removeHostname(idOrName: string, hostnameRaw: string): Promise; /** * Instantly invalidate every link/cookie issued for this tunnel so far, * without tearing the tunnel itself down — rotates the guard's signing * secret and mints a fresh token on a fresh TTL window, then folds the new * `url`/`expiresAt` back into the descriptor. Unlike `stop`, the tunnel * stays active: this is for "that link leaked, kill it" or "mint me a * fresh one for TTL renewal", not for tearing the whole thing down. * * Throws for a tunnel with no guard (`access: "public"`, or not found) — * there is nothing to revoke, and silently returning false here would * read as "revoked" when it very much was not. */ revoke(idOrName: string): TunnelDescriptor; shutdown(): Promise; protected pickProviderForTest(_provider: TunnelProvider, desc: TunnelDescriptor): Promise; /** * Build the creds passed to a provider: stored creds (ngrok authtoken, * third-party secrets) merged with descriptor-carried config (named's * hostname/tunnelId/credentialsFile), descriptor taking precedence. */ protected credsForDescriptor(desc: TunnelDescriptor): Promise; private assertGatewayNotExposed; private requireEntry; /** The live provider when it supports `op`, else a freshly-built one * (stopped/restored entries carry a stub). */ private providerFor; private findEntryByKey; private findEntryByIdOrName; private schedulePersist; private persistNow; private loadFromDisk; } /** * MCP surface + shared create/remove logic for session-follow: * `session_follow` (upsert), `session_unfollow`, `session_follows` (list). * * `upsertSessionFollow` / `removeSessionFollow` / `followView` are exported * so `http-server.ts`'s `POST|GET|DELETE /follows` routes share the exact same * validation as the MCP tools — same pattern as `sentinel-tools.ts`. * * `session_follow`'s `follower` defaults to the calling session (the trusted * `?callerSessionId=` of the `/mcp` connection), like `sentinel_watch`. */ interface SessionFollowDeps { store: SessionFollowStore; /** True when the registry still knows this session id. */ hasSession: (sessionId: string) => boolean; /** Default follower when the input omits it (MCP caller's own session). */ defaultFollower?: string; } /** * LlmEndpointRegistry — supervised-sidecar manager for the * `@agentproto/inference-endpoint` proxy gateway. * * The daemon spawns the llm-endpoint bin as a CHILD PROCESS (never an * in-process import — the runtime package has zero dependency on * @agentproto/inference-endpoint, exactly like it never imports cloudflared). * This is the single-sidecar analog of {@link TunnelRegistry}: one endpoint, * one port, an in-memory descriptor that tracks pid / port / status / * startedAt, and a start / stop / status lifecycle exposed over MCP. * * Lifecycle (mirrors RemoteController's singleton style — created fresh each * boot, state in memory; the child dies with the daemon so there is nothing * to reconcile on restart): * start(input) → assemble env, spawn `node serve`, health-probe to * readiness, store descriptor. Idempotent: a call while the * endpoint is already running+healthy returns the existing * descriptor without spawning (like `start_browser`). * status() → descriptor + live `GET /v1/models` health probe. * stop() → SIGTERM the child, mark stopped (mirrors tunnel stop). * shutdown() → stop the child on daemon exit. * * Env on spawn (see {@link assembleLlmEndpointEnv}): the provider API keys * via `injectProviderKeysIntoEnv` (the same store llm-endpoint's own cli.ts * reads), `LLM_ENDPOINT_PORT` (default 18090), and `LLM_ENDPOINT_ACCESS_TOKENS` * when configured. Explicit env passed to `start` always wins. */ type LlmEndpointStatus = "starting" | "running" | "stopped" | "error"; /** The `llm_endpoint_status` MCP contract — see {@link LlmEndpointRegistry.status}. */ interface LlmEndpointStatusReport { running: boolean; pid: number | null; port: number | null; baseUrl: string | null; healthy: boolean; startedAt: string | null; status: LlmEndpointStatus | "never-started"; /** Who is actually serving this endpoint. `"daemon"` — this registry's own * spawn (or nothing at all). `"external"` — a healthy process on the same * port that this registry did NOT spawn (e.g. a launchd KeepAlive * sidecar); `pid` is unknown (always `null`) and `injectedProviders`, if * present, was DERIVED by probing `/v1/models` rather than read off our * own key-injection bookkeeping. */ owner: "daemon" | "external"; /** Whether upstream links persisted via `llm_endpoint_set_upstream_link` * are actually applied to the process answering this port. Always * `false` for `owner:"external"` — this registry never spawned it, so it * never injected `LLM_ENDPOINT_PROFILE_`; the operator must * configure the external service's own env directly. */ linksApplied: boolean; lastError?: string; injectedProviders?: string[]; linkedProviders?: string[]; /** `@agentproto/inference-endpoint`'s own package version, read from the * resolved bin's `package.json` — best-effort, present only for * `owner:"daemon"` (the version of the code this registry would spawn / * did spawn). Undefined when unresolvable, or for `owner:"external"` * (an adopted process exposes no version of its own to probe). */ version?: string; } interface LlmEndpointDescriptor { pid: number | null; port: number; baseUrl: string; status: LlmEndpointStatus; startedAt: string; stoppedAt?: string; lastError?: string; /** Provider names whose keys were injected into the child's env (never values). */ injectedProviders?: string[]; /** Upstream names mapped to an auth-profile link (`LLM_ENDPOINT_PROFILE_

`) * in the child's env. Profile IDS, not secrets — but only the provider names * are surfaced here, mirroring `injectedProviders`. */ linkedProviders?: string[]; /** * Only populated on the value returned by {@link LlmEndpointRegistry.start} * (never stored on the in-memory descriptor): `true` when the call reused an * already-running/starting child instead of spawning — so the caller can * tell a fresh `start` (new port/tokens applied) from a no-op idempotent hit * (old descriptor returned, nothing new applied). Mirrors `start_browser`. */ wasAlreadyRunning?: boolean; } interface StartLlmEndpointInput { /** Port for the proxy. Defaults to LLM_ENDPOINT_PORT env, then 18090. */ port?: number; /** Value for `LLM_ENDPOINT_ACCESS_TOKENS` (comma/space-separated token list). */ accessTokens?: string; /** Extra env for the spawn. Explicit env always wins over injected keys/port. */ env?: Record; /** Override the bin path (else resolved / `LLM_ENDPOINT_BIN`). */ binPath?: string; } /** * A spawned endpoint child. The registry keeps this as its live process and * drives it through `stop()`. Extracted as an interface so the spawn is a * test seam (mirrors TunnelRegistry's `pickProviderForTest`): tests override * {@link LlmEndpointRegistry.launch} to return a mock without a real process. */ interface EndpointProcess { readonly pid: number | null; /** SIGTERM (+ SIGKILL backstop). Idempotent — safe on an already-dead child. */ stop(): Promise; } interface LaunchOptions { binPath: string; env: NodeJS.ProcessEnv; port: number; /** Absolute path for the child's stdout+stderr log file. */ logPath: string; onLog?: (line: string) => void; /** Invoked once if the child exits (before an explicit stop). */ onExit?: (info: { code: number | null; signal: string | null; }) => void; } interface LlmEndpointRegistryOptions { /** Scratch dir for the child's log file. Defaults to ~/.agentproto. */ workspace?: string; onLog?: (line: string) => void; /** Bin path override (else auto-resolved / `LLM_ENDPOINT_BIN`). */ binPath?: string; /** * Env-key injector — defaults to `injectProviderKeysIntoEnv`. Injected so * env assembly is unit-testable without touching the on-disk providers store. */ injectKeys?: (env: NodeJS.ProcessEnv) => Promise; /** * Per-upstream link injector — defaults to `injectLlmEndpointLinksIntoEnv`. * Injected (like `injectKeys`) so env assembly is unit-testable without * touching the on-disk links store. */ injectLinks?: (env: NodeJS.ProcessEnv) => Promise; /** This daemon's own loopback base URL + per-boot bearer, injected into * EVERY spawn (including a crash-restart, which calls `start()` with no * args) as `LLM_ENDPOINT_DAEMON_URL` / `LLM_ENDPOINT_DAEMON_TOKEN` — see * `assembleLlmEndpointEnv`'s `daemonCallback` doc comment. Constructor- * level (not a per-`start()` `env` override) precisely so it survives a * restart the caller didn't supply args for. */ daemonCallback?: { baseUrl: string; token: string; }; /** Max time `start` waits for the freshly-spawned child to answer health. */ readyTimeoutMs?: number; /** Poll interval for the readiness/health wait. */ pollIntervalMs?: number; /** Health-probe timeout for a single `GET /v1/models` request. */ healthProbeTimeoutMs?: number; /** * Crash-restart policy for an unexpected exit of an already-`running` * (i.e. previously healthy) child — never for a crash during the initial * startup window (that's surfaced synchronously as a thrown `start()` * error, the caller's to handle) and never for a `stop()`-driven exit. * Exponential backoff capped by a rolling-window retry limit — mirrors * the `restartPolicy` shape documented for agent-cli sessions (`on`, * `maxRetries`, `windowMs`, `baseDelayMs`, `factor`, `maxDelayMs`) in * spirit, not by reusing that exact type. Set `maxRetries: 0` to disable * (today's behavior — stay `error` until something calls `start()` again). */ crashRestart?: { /** Max restart attempts within `windowMs` before giving up and staying * `error`. Default 5. `0` disables crash-restart entirely. */ maxRetries?: number; /** Rolling window over which `maxRetries` is counted. Default 5 minutes. */ windowMs?: number; /** Delay before the first restart attempt. Default 1s. */ baseDelayMs?: number; /** Multiplier applied to the delay after each attempt. Default 2. */ factor?: number; /** Upper bound on the computed delay. Default 30s. */ maxDelayMs?: number; }; } declare class LlmEndpointRegistry { private desc; private proc; private exited; /** * In-flight `start` promise. Set synchronously at the very top of `start` * before any `await`, cleared in its `finally`. Guarantees no two * `launch()` calls are ever in flight for one registry: concurrent callers * (and re-entrant idempotent hits) join this same promise instead of racing * past the null-check and spawning a second, orphan-prone child. */ private starting; private readonly workspace; private readonly onLog; private readonly binPath; private readonly injectKeys; private readonly injectLinks; private readonly daemonCallback; private readonly readyTimeoutMs; private readonly pollIntervalMs; private readonly healthProbeTimeoutMs; private readonly crashRestartMaxRetries; private readonly crashRestartWindowMs; private readonly crashRestartBaseDelayMs; private readonly crashRestartFactor; private readonly crashRestartMaxDelayMs; /** Timestamps (ms) of recent crash-restart attempts, pruned to the * rolling window on each unexpected exit. */ private restartAttempts; private restartTimer; /** Memoized result of {@link resolveVersionBestEffort} — `null` once a * resolution attempt fails, so a permanently-unresolvable bin doesn't * re-read the filesystem on every `status()` call. */ private cachedVersion; constructor(opts?: LlmEndpointRegistryOptions); /** * Ensure the proxy is running. Idempotent: if it is already running and a * live health probe passes (or still `starting`), returns the existing * descriptor without spawning a second child (mirrors `start_browser`'s * wasAlreadyRunning). * * Concurrency-safe: a start already in flight is joined rather than * duplicated, so two concurrent calls can never both spawn — a second child * would race for the port and one would be orphaned, outliving daemon * shutdown with the injected credentials still in its env. */ start(input?: StartLlmEndpointInput): Promise; private startInternal; /** Current descriptor (in-memory), or undefined if never started. */ get(): LlmEndpointDescriptor | undefined; /** * Descriptor + a live health probe. Shape matches the MCP `llm_endpoint_status` * contract: {running, pid, port, baseUrl, healthy, startedAt}. * * D5: `running:false` together with `healthy:true` must never both be * reported — that self-contradiction is exactly what happened when a * launchd-owned (or otherwise externally-spawned) llm-endpoint already * held the port: OUR spawn attempt lost the race (EADDRINUSE), recorded * `status:"error"` (⇒ `running:false`), while the live health probe below * runs regardless of `status` and answers `true` against the OTHER, * perfectly healthy process. Rather than reporting our own failed spawn as * the whole truth, ADOPT: when we're not running but the port answers * healthy, report `running:true, owner:"external"` (pid unknown — it isn't * ours), and derive the served provider list by probing `/v1/models` * itself (our own `injectedProviders` bookkeeping is about keys WE * injected, which is meaningless for a process we never spawned). */ status(): Promise; /** SIGTERM the child and mark the descriptor stopped. Idempotent. */ stop(): Promise; /** Called on daemon exit — stop the child if it's live. */ shutdown(): Promise; /** * Schedule a restart after an unexpected exit of a previously-`running` * child. Exponential backoff (`baseDelayMs * factor^attempt`, capped at * `maxDelayMs`), bounded by `maxRetries` attempts within the rolling * `windowMs` window — once exceeded, gives up and stays `error` until an * operator (or the lazy self-heal in `spawnAgentSession`) calls `start()` * again. The scheduled retry itself goes through the public `start()`, * so it's subject to the same in-flight dedup as any other caller. */ private scheduleCrashRestart; /** * Best-effort `@agentproto/inference-endpoint` package version, read from the * resolved bin's `package.json` (memoized — a permanently-unresolvable * bin, e.g. never built, shouldn't re-hit the filesystem on every * `status()` call). Returns `undefined` rather than throwing so a missing * bin never turns `status()` itself into a failure. */ private resolveVersionBestEffort; private stopInternal; /** Spawn `node serve` with stdout+stderr redirected to a file. */ protected launch(opts: LaunchOptions): Promise; /** Probe `GET /v1/models` — true on a 2xx. */ protected probeHealth(baseUrl: string): Promise; /** * Fetch `GET /v1/models` and extract the distinct `owned_by` * provider names from its OpenAI-style `{data:[{owned_by}]}` body — the * provider list for a process this registry did NOT spawn (D5 adoption), * so `injectedProviders` (the field the UI already reads) can still name * what an externally-owned endpoint is actually serving. Best-effort: * returns `[]` on any request/parse failure or shape mismatch rather than * throwing — the caller already knows `probeHealth` succeeded; this is * enrichment, not another readiness gate. */ protected probeModels(baseUrl: string): Promise; } /** * RemoteController — owns the gateway's "publish to the internet" state. * * One singleton per gateway. Holds: * - the current tunnel provider's child process (cloudflared, …) * - the bearer token gating /mcp once the tunnel is up * - persisted state in `/.agentproto/remote.json` * * The controller is the *only* component that mutates auth at runtime. * The HTTP server reads auth via a getter (see `AuthSource` in * http-server.ts), so flipping `enable() / disable()` here takes effect * on the next request — no restart, no race. * * ## Provider model * * Each provider implements `RemoteProvider` (start / stop / status). * v1 ships only `quick` (Cloudflare Quick Tunnel — no API key, no DNS, * ephemeral `*.trycloudflare.com` URL). Named CF Tunnel and Tailscale * land as additional implementations. * * ## Token model * * On enable we generate a 32-byte random bearer token, return it once * to the caller, and persist only its sha256 hash to disk. Same model * as a Stripe API key — losing the plaintext means rotating, not * recovering. This keeps `.agentproto/remote.json` safe to commit by * accident (it leaks the URL, not the credential). * * ## Security note * * The CF API token (when used by named-tunnel provider) is *never* * accepted as MCP tool input. The controller reads it from * `~/.config/agentproto/cloudflare.json` or `$CLOUDFLARE_API_TOKEN`. * Otherwise a remote agent could exfiltrate it through `remote_enable`. */ interface EnableInput { provider?: "quick"; /** * Local port to expose. Defaults to the gateway's own port — i.e. * "publish this MCP server." Pass any other port to expose a * different local service (Supabase 54371, a Vite dev server, …) * without spinning up a separate tunnel manager. */ targetPort?: number; /** * Host the tunnel forwards to. Defaults to `127.0.0.1`. Setting it * to `localhost` resolves through DNS (IPv6 first on most systems); * keep `127.0.0.1` unless the target is explicitly IPv6-bound. */ targetHost?: string; /** * Opt in to the legacy tunnel phone link (`EnableResult.phoneUrl`). * Default `false`: phones pair through rendezvous (`agentproto pair * offer`), which is end-to-end encrypted and does not expose the gateway * to Cloudflare. Set this only for a browser that cannot run the pair * page's service worker: the resulting link points at the whole gateway * via a bearer in a URL fragment, and Cloudflare terminates TLS for it. */ phoneLink?: boolean; } interface EnableResult { publicUrl: string; /** * Bearer token issued by this gateway. Only meaningful when the * tunnel exposes the gateway itself (default). For arbitrary-target * tunnels (`targetPort != gateway.port`) the daemon does not gate * the proxied service, and this is omitted. */ bearerToken?: string; /** * `/mcp`. Only emitted when exposing the gateway. */ mcpEndpoint?: string; /** * Paste-ready `.mcp.json` snippet. Only emitted when exposing the * gateway. */ mcpConfigSnippet?: string; /** * The opt-in tunnel phone link (`EnableInput.phoneLink: true`): the token * rides in a URL *fragment* (`#token=`), never a `?` query string, since * fragments never reach a server (no Referer, no access/proxy log, no CDN * cache key): `/apps/@agentik/session-chat/ui#token=`. * * Omitted unless the caller opted in AND this daemon exposes the gateway * AND the `@agentik/session-chat` app is installed with a UI. Phones pair * through rendezvous by default (`agentproto pair offer`); this link is a * fallback for a browser without service workers, and it exposes the * whole gateway through Cloudflare, which can read the traffic. */ phoneUrl?: string; provider: "quick"; target: { host: string; port: number; }; exposesGateway: boolean; /** * Present ONLY for passthrough tunnels (`exposesGateway === false`): * the daemon does not gate that traffic, so the public URL reaches the * upstream service with no auth from the daemon. A machine-readable flag * so UIs/agents can surface the exposure instead of it being buried in * the tool's prose description. */ warning?: string; } interface RemoteStatus { enabled: boolean; provider?: "quick"; publicUrl?: string; pid?: number | null; createdAt?: string; target?: { host: string; port: number; }; exposesGateway?: boolean; /** Last error from the provider, if any (since last enable). */ lastError?: string; } interface RemoteControllerOptions { workspace: string; port: number; /** Hook for surfacing provider logs through RuntimeEvents. */ onLog?: (line: string) => void; /** * Whether the `@agentik/session-chat` app is installed with a `ui` block * on THIS daemon, deciding whether an opted-in `enable({ phoneLink: true * })` emits `EnableResult.phoneUrl`. Resolved at call time (matches * `index.ts`'s own `isSessionChatInstalled`), so installing the app after * boot is picked up without a restart. Omitted ⇒ never a `phoneUrl`. */ isSessionChatInstalled?: () => boolean; } declare class RemoteController { private state; private bearerToken; private provider; private lastError; private readonly opts; constructor(opts: RemoteControllerOptions); /** * Auth getter handed to startHttpServer. The HTTP server calls this * on every request so flipping enable/disable is effective without * a restart. */ readonly readAuth: () => AuthOptions; status(): RemoteStatus; enable(input: EnableInput): Promise; disable(): Promise<{ disabled: boolean; }>; /** * Stop the provider on gateway shutdown. Does NOT clear persisted * state — that survives across restarts so the user can `remote_status` * after rebooting and see "stale state, run remote_enable to refresh". * (Stale-recovery semantics land in v2; today we just leave the file.) */ shutdown(): Promise; } /** * Daemon-side HOST registry (DEVICES-PLAN PR-C) — the "client" half of * pair/v2, living on the daemon so it's reachable over both an HTTP route * and an MCP tool, not just CLI-local bookkeeping (`client-pairings.ts` / * `pair-transport.ts` are that CLI-local equivalent today). * * Where `pairing-registry.ts` is what a daemon uses to let OTHER machines * pair with and remote-control IT, `host-registry.ts` is what a daemon uses * to register and drive OTHER daemons — reverse pairing. `add()` accepts a * HOST-scoped offer (`agentproto pair offer --host`, offer-url.ts's * `scope`), runs the pair/v2 client handshake, and persists the resulting * pair root; `forwardHttp()` dials on demand, reconnecting over the current * (then previous) epoch token exactly like `pair-transport.ts`'s * `openPairChannel`, forwards one HTTP request over the resulting tunnel * client, and closes. There is no standing connection here — unlike * `PairingRegistry`, a `HostRegistry` never autoconnects or keeps a * reconnect loop parked at the broker; every reach-out is a fresh dial. * That also means shutdown needs no teardown: there is nothing standing to * tear down. * * ## The scope gate * * `add()` REFUSES (throws) any offer whose parsed `scope !== "host"` before * ever dialing anything. This is the default-deny gate PR-C exists to add: * an ordinary "remote-control me" offer (today's `pair offer`, no `--host`) * must not silently become a host registration, even though the underlying * wire capability is identical either way (see offer-url.ts's "Offer scope" * and pairing-registry.ts's `OfferEntry.scope` doc comment for why the * offering daemon's OWN server-side record — not the URL's plaintext * `scope` param — is what's authoritative about what it granted). There is * deliberately no override flag. * * Persisted to `hosts.json` (`~/.agentproto/hosts.json` by default) with the * same atomic-write discipline as `pairings.json` (mkdir, write to a * pid-keyed tmp file at 0600, chmod, rename) and the same lazy-load-on- * first-use pattern. * * ## Online tracking * * `isOnline(fingerprint)` is true while a `forwardHttp()` call for that * fingerprint is in flight (a reference count, incremented on dial and * decremented in a `finally`), OR within `onlineGraceMs` of the last time a * dial to it actually succeeded (an `add()` handshake, a `forwardHttp`, or a * background snapshot poll). There is no live probe backing `list()` — that * would make `devices list` slow/flaky over N hosts — so a host answering * every ~15s snapshot poll stays online, and one that stops answering * decays to offline after the grace window. Every contact attempt stamps * `lastProbeAt`; a failed one records `lastError` (cleared by the next success). * * ## Proactive session snapshots * * A join-token-added host (an ephemeral CI runner) lives ~3 minutes, far * shorter than anyone watches it. So from the moment such a host joins, this * registry polls it (`snapshotIntervalMs`, faster while one of its sessions * is running) for its session list plus a capped output tail per session and * keeps the result in memory. Once the host is offline, `getSessionsSnapshot` * serves that — `stale: true` with the capture time. After * `snapshotMaxFailures` consecutive unreachable polls the loop backs off * exponentially (up to `probeBackoffMaxMs`) and keeps the last good capture; * `start()` resumes the loop for every join-added host after a daemon * restart, and background probes share a `probeConcurrency` cap. * `snapshotNow()` lets a departing host trigger one last * capture (see `join-token-registry.ts`'s goodbye hello). * * ## Ended hosts * * A join-added host is an ephemeral CI box, so it is marked `ended` when its * goodbye arrives (`markEnded`) or when it has been unreachable for * `endedTtlMs` (2 h), and deleted `endedRetentionMs` (7 d) after that. * `sweep()` runs that pass (the daemon calls it on a timer; `list()` runs it * too). Ended hosts are still returned by `list()` — hiding them from the * default `device_list` is `device-registry.ts`'s job. A manually added host * is never ended or deleted; `list()` only flags it `stale`. */ /** `hosts.json` format. */ declare const HOSTS_VERSION: 1; /** One-line remediation logged once per failure streak once the threshold * is crossed. Deliberately NOT a protocol change — the pairing itself is * fine; a fresh host-scoped offer re-binds it. */ declare const HOST_HANDSHAKE_REMEDIATION_HINT: string; /** One persisted host — a daemon this daemon can drive. */ interface HostRecord { /** The target daemon's identity fingerprint (32 hex). */ fingerprint: string; /** Human-facing label; defaults to the fingerprint. */ name: string; /** Target daemon's static X25519 public key, standard base64 SPKI DER — * pinned at `add()` time. */ daemonX25519Pub: string; /** Target daemon's static Ed25519 public key, standard base64 SPKI DER — * pinned at `add()` time. */ daemonEd25519Pub: string; /** Rendezvous endpoint to reach the host through. */ rendezvousUrl: string; /** Long-term shared secret (base64), from which epoch routing tokens * derive — same derivation as `PairingRecord.pairRoot`. */ pairRoot: string; /** ISO-8601 first-add timestamp. */ createdAt: string; /** ISO-8601 of the most recent successful contact (join, dial, background poll). */ lastSeen: string; /** ISO-8601 of the most recent contact attempt, successful or not. Not * persisted on every attempt — it rides along with the next write. */ lastProbeAt?: string; /** Why the most recent contact attempt failed; cleared by the next success. */ lastError?: string; /** A join-added host that is gone: it said goodbye, or was unreachable for * longer than `endedTtlMs`. Ended hosts are no longer polled, read offline, * and are deleted `endedRetentionMs` after `endedAt`. Never set on a * manually added host. */ ended?: true; /** ISO-8601 of when the host ended (for a TTL end: when the TTL lapsed, not * when the sweep noticed). */ endedAt?: string; endReason?: "goodbye" | "ttl"; /** Computed by `list()`, never persisted: a manually added host that has * been unreachable for longer than `endedTtlMs`. Stale hosts stay listed * and are never deleted — only join-added hosts are. */ stale?: true; /** Set on a host added under the retired pair/v1 protocol. Present for * parity with `PairingRecord`/`ClientPairing`; pair/v1 offers are refused * by `parseOfferUrl` before `add()` ever sees them, so this is currently * unreachable — kept so a future downgrade path has somewhere to flag it. */ legacy?: true; /** Self-reported by the host at add-time (SANDBOX-VISIBILITY-JOIN) — e.g. a * sandbox provider slug, a provider-side sandbox id, and free-form labels * (PR number, run URL, …). Never verified beyond "the host said so"; purely * descriptive for `device_list`/`devices sessions`. */ provider?: string; sandboxId?: string; labels?: Record; /** * How this host got here (SANDBOX-VISIBILITY-JOIN #3) — `"join"` for a * box that dialed in via `AGENTPROTO_JOIN`/`join-token-registry.ts`, * `"manual"` for the human `pair offer --host` + `devices add` ceremony. * Absent on a record persisted before this field existed; treated as * `"manual"` (never auto-pruned) rather than assumed ephemeral. Only * `"join"` hosts are eligible for the ended/retention sweep — a human's * own paired machine must never silently disappear just because it hasn't * been dialed in a week. */ addedVia?: "join" | "manual"; } /** Optional self-reported metadata `add()` attaches to the resulting * `HostRecord` (see `HostRecord.provider`/`sandboxId`/`labels`). */ interface HostJoinMeta { provider?: string; sandboxId?: string; labels?: Record; /** Set by `join-token-registry.ts`'s `handleJoined()` — never by a manual * `device_add`/`devices add` call — so `add()` can tell a join-token box * apart from a human's own paired host (see `HostRecord.addedVia`). */ joined?: true; } interface HostRegistryDeps { /** Dial a rendezvous WS and adapt it to a `FrameSink`. Same shape as * `PairingRegistryDeps.dial` — the CLI's `daemonDialRendezvous` satisfies * it directly. Rejects if the dial fails or `signal` aborts. */ dial: (wsUrl: string, signal: AbortSignal) => Promise; /** Path to `hosts.json`. Defaults to `~/.agentproto/hosts.json`. */ hostsPath?: string; /** Injectable clock (ms). Defaults to Date.now. */ now?: () => number; /** Diagnostic log sink. */ log?: (line: string) => void; /** Rendezvous dial ceiling per attempt. Default 15s. */ dialTimeoutMs?: number; /** Handshake ceiling per attempt. Default 15s. */ handshakeTimeoutMs?: number; /** * A join-added host (`HostRecord.addedVia === "join"`) unreachable for this * long (ms since `lastSeen`) is marked `ended`. Default 2 h; `0` disables. * Manually added hosts are never ended — `list()` only flags them `stale`. */ endedTtlMs?: number; /** * An ended host is deleted this long (ms) after `endedAt`. Default 7 days; * `0` keeps ended hosts forever. Only join-added hosts are ever deleted. */ endedRetentionMs?: number; /** Cadence (ms) of the proactive session snapshot poll for a join-added * host. Default 15s; `0` disables the poll (and `snapshotNow` becomes a * no-op that returns false). */ snapshotIntervalMs?: number; /** Faster cadence used while a snapshotted session is running. Default 5s. */ snapshotActiveIntervalMs?: number; /** Consecutive unreachable polls before the poll starts backing off. Default 3. */ snapshotMaxFailures?: number; /** A host stays `online` for this long after a successful dial. Default 2 min. */ onlineGraceMs?: number; /** Consecutive-failure poll backoff ceiling (ms). Default 5 min. */ probeBackoffMaxMs?: number; /** Max background probes in flight across all hosts. Default 4. */ probeConcurrency?: number; /** Min gap between disk writes for a `lastSeen`-only change. Default 30s. */ lastSeenPersistIntervalMs?: number; } interface ForwardHttpRequest { method: string; path: string; headers?: Record; body?: Uint8Array; } interface ForwardHttpResponse { status: number; headers: Record; body: Uint8Array; /** Set when this response was served from the last-known-good `/sessions*` * cache instead of a live forward (SANDBOX-VISIBILITY-JOIN #3) — see * {@link HostRegistry.getSessionsSnapshot}. Absent on every live * response, including `forwardHttp` itself, which never sets it — only * the cache fallback in `device-registry.ts` does. */ stale?: true; /** ISO-8601 capture time of a `stale` response. */ capturedAt?: string; } /** Streaming counterpart of {@link ForwardHttpResponse} — `body` is a Web * `ReadableStream` the caller drains directly (SSE chat/completions, most * notably) instead of a fully-buffered `Uint8Array`. See * {@link HostRegistry.forwardHttpStream}. */ interface ForwardHttpStreamResponse { status: number; headers: Record; body: ReadableStream; } interface HostRegistry { /** * Accept an offer URL and register the target daemon as a driveable host. * REFUSES (throws a plain `Error`) unless the parsed offer has * `scope === "host"` — no dial is attempted in that case. Otherwise: dials * the offer's rendezvous, runs the pair/v2 client handshake, verifies the * derived peer fingerprint matches the offer's `id` (defence in depth, * mirrors `pair-transport.ts`'s `acceptOffer`), derives the pair root, and * persists a `HostRecord` (upserted by fingerprint — re-adding replaces). */ add(offerUrl: string, name?: string, meta?: HostJoinMeta): Promise<{ fingerprint: string; name: string; rendezvousUrl: string; }>; /** All persisted hosts (copies). Loads `hosts.json` on first call. */ list(): Promise; /** Rename a host (fingerprint or current name). Returns false when nothing * matched; throws on an empty `newName`. */ rename(idOrName: string, newName: string): Promise; /** Drop a host by fingerprint or name. Returns false when nothing matched. */ revoke(idOrName: string): Promise; /** Is a `forwardHttp` call for this fingerprint in flight right now? */ isOnline(fingerprint: string): boolean; /** * On-demand: dial the host, run the client handshake against the current * epoch's tokens (falling back to the previous epoch, bridging clock * skew — same two-attempt shape as `pair-transport.ts`'s * `openPairChannel`), forward one HTTP request over the resulting tunnel * client, then close. Throws with a re-pair hint if every attempt hangs up * on the hello (likely a pair/v1 peer). */ forwardHttp(idOrName: string, req: ForwardHttpRequest): Promise; /** * Same dial/handshake/retry shape as {@link forwardHttp}, but for a * streamed response (SSE, NDJSON, long-poll) — the daemon-inference proxy's * `/v1/chat/completions` most notably, which must relay tokens as they * arrive rather than buffering the whole completion first. Unlike * `forwardHttp`, the tunnel client is kept open (and `isOnline` stays true) * until the returned `body` stream is fully drained, errors, or is * cancelled — only then does it close and the online count drop. */ forwardHttpStream(idOrName: string, req: ForwardHttpRequest): Promise; /** * The last-known-good response for a GET `/sessions` or * `/sessions/:id/output...` request against this host, captured the last * time {@link forwardHttp} actually reached it — or `undefined` if this * host has never answered that exact path, or isn't known at all. Always * `stale: true` (a live hit never goes through this method — callers * should try {@link forwardHttp} first and only fall back to this on * failure, which is exactly what `device-registry.ts`'s `forwardHttp` * wrapper does). In-memory only — see host-registry.ts's module doc for * why that's an acceptable trade here. */ getSessionsSnapshot(idOrName: string, path: string): ForwardHttpResponse | undefined; /** * Capture this host's session list + output tails right now (the same * capture the background poll takes). Resolves true when the host was * reached. Never throws; false for an unknown host, an unreachable one, or * when snapshots are disabled. */ snapshotNow(idOrName: string): Promise; /** * Mark a join-added host ended right now (its CI job said goodbye). Stops * its poll. Returns false for an unknown host or a manually added one, * which is never ended. Idempotent. */ markEnded(idOrName: string, reason?: "goodbye" | "ttl"): Promise; /** * Run the lifecycle sweep now: mark join-added hosts ended past `endedTtlMs`, * delete those ended past `endedRetentionMs`, persist if anything changed. * Cheap (one pass over the in-memory map); `list()` runs the same pass. */ sweep(): Promise; /** * Load `hosts.json` and resume the background poll for every join-added * host, so a daemon restart doesn't leave still-running CI boxes frozen at * their join-time `lastSeen`. Idempotent; call once at boot. */ start(): Promise; /** * Sizes of the registry's in-memory state, for the daemon's `[heap]` log * line: entry counts, plus the bytes held by the cached snapshot and * `/sessions*` bodies. Cheap (no I/O). Optional so test doubles need not * implement it. */ memoryStats?(): Record; } declare function createHostRegistry(deps: HostRegistryDeps): HostRegistry; /** Read-only snapshot of `hosts.json` (the read-only twin of * `readPairingsSnapshot`): for callers that just want the persisted * records — e.g. `agentproto doctor`'s devices check flagging a host * channel that persistently fails its handshake (BOOTSTRAP P3 item 4). * No dial, no rendezvous, no `loadIdentity` deps. Never throws — a * missing or malformed file yields `[]`. */ declare function readHostsSnapshot(path?: string): Promise; /** * Daemon-side JOIN TOKEN registry (SANDBOX-VISIBILITY-JOIN, stacked on * DEVICES-PLAN PR-C's `host-registry.ts`). * * `host-registry.ts`'s `add()` requires a HUMAN to relay a host-scoped offer * URL from the box to this daemon (`agentproto pair offer --host` on the box, * `agentproto devices add ` here) — fine for a laptop, impossible for an * unattended CI sandbox with no one watching its logs to copy a one-time, * 10-minute-TTL secret. A join token flips who initiates: this daemon mints a * long-lived, revocable, reusable credential ahead of time (stored as a * GitHub secret, say); a box started with `AGENTPROTO_JOIN=` dials * in — over the SAME rendezvous/pair-v2 primitives, no protocol change — and * this daemon adds it as a host automatically. * * ## Why this isn't just a long-lived `host-registry.ts` offer * * pair/v2 deliberately gives a CLIENT no persistent identity key (see * `pairing-registry.ts`'s "Reconnect authentication" doc) — only the * DAEMON/offerer side has stable keys a peer can pin and re-dial later. * `HostRegistry.forwardHttp` needs exactly those stable keys to reach a host * on demand, so the box MUST end up as the offerer of its own host-scoped * offer (a normal, single-use `pair offer --host`) with THIS daemon * `add()`-ing it — `host-registry.ts` is not touched by this module at all. * * What the join token replaces is only the relay step: this daemon parks a * STANDING accept loop (`side=daemon`, exactly like a `pair offer`'s park, * except never single-use) on a route deterministically derived from the * token's own secret. A box holding the token dials that route as the * CLIENT — the role a browser/CLI plays consuming a normal offer — and its * sealed hello's `clientName` carries a small JSON envelope: the box's own * self-minted host-scoped offer URL (freshly created, in-process, via its * own `PairingRegistry.createOffer({scope:"host"})` — see * `packages/cli/src/commands/serve.ts`'s `AGENTPROTO_JOIN` boot wiring) plus * a self-reported name/provider/sandboxId/labels. On receipt, this daemon * just calls `HostRegistry.add(offerUrl, name, meta)` — the exact call a * human would type — closes the bootstrap channel, and re-parks for the next * box. No new wire messages, no new crypto: two ordinary pair/v2 handshakes * back to back, the first only ever used to carry one string. * * ## Reuse and revocation * * Unlike an `OfferEntry` (`pairing-registry.ts`), a join token's * `{route, auth}` never rotates and is never "spent" — `useCount`/`maxUses`/ * `expiresAt`/`revokedAt` (all checked inside `verifyAuthToken`, which may be * async) gate reuse instead. This is the same trust shape as an existing * epoch reconnect token (valid, unrotated, for its whole day) stretched over * a longer, explicit, revocable window — not a new security primitive. * * ## A known limitation * * One token parks on exactly one fixed route, so exactly one box can be * mid-handshake on it at a time; a second box dialing in the same instant * either waits for the loop to re-park (typical: the ceremony is a single * short-TTL round trip) or, in the worst case, times out and retries with * backoff. Fine for the sequential-CI-review case this exists for; a fleet * of concurrently-joining boxes would want multiple parked slots per token, * deferred (see PR body). * * Persisted to `~/.agentproto/join-tokens.json`, same atomic-write + lazy- * load discipline as `hosts.json`/`pairings.json`. The raw `secret` — not a * hash — is stored, exactly like `pairings.json` stores `pairRoot` in the * clear: it is crypto material this daemon must re-derive `{route, auth}` * from on every boot, not a password to be hashed. */ /** `join-tokens.json` format. */ declare const JOIN_TOKENS_VERSION: 1; /** One persisted join token. `secret` is the crypto material a box's * `AGENTPROTO_JOIN` value carries too — never log or echo it once minted. */ interface JoinTokenRecord { /** Short random id (CLI/MCP target), distinct from `secret`. */ id: string; /** Human-facing label (e.g. "ci-reviewer"). */ name: string; /** One-time-offer-shaped secret (base64url) — re-derives `{route, auth}` * via `deriveOfferTokens`. Never rotates for this token's lifetime. */ secret: string; /** Rendezvous endpoint boxes dial through. */ rendezvousUrl: string; /** ISO-8601 mint time. */ createdAt: string; /** ISO-8601 expiry — always set (`create()` defaults `ttlMs`). */ expiresAt: string; /** Reuse ceiling. Absent = unlimited (until `expiresAt`/revoke). */ maxUses?: number; /** Successful joins so far. */ useCount: number; /** ISO-8601 of the most recent successful join. */ lastUsedAt?: string; /** ISO-8601 revoke time. Present ⇒ inactive; kept for `list()` history. */ revokedAt?: string; /** * A joined box's `useCount` bumps unconditionally (it only reflects that * the AUTH TOKEN was valid), but turning that join into a visible device * is a SEPARATE, later step — `deps.addHost` dialing back into the box's * self-minted offer, a second full pair/v2 round trip. That step can fail * (the box's 60s-TTL self-offer expiring before the home daemon gets to * it, the box already tearing down, a broker hiccup) without `useCount` * ever reflecting it — which is exactly how PR #1536's run 36438398607 * went unnoticed: `useCount: 2`, one visible device, no error anywhere a * human would look. Set on the most recent failed `addHost` call, cleared * on the next SUCCESSFUL one, so `join_token_list` always shows whether * the box currently backing `useCount` actually made it into `device_list`. */ lastJoinError?: string; /** ISO-8601 of `lastJoinError`. */ lastJoinErrorAt?: string; } interface CreateJoinTokenInput { name: string; /** Time-to-live in ms. Default 90 days. */ ttlMs?: number; /** Reuse ceiling. Absent = unlimited. */ maxUses?: number; /** Rendezvous URL override; falls back to the configured default. */ rendezvousUrl?: string; } interface CreatedJoinToken { id: string; name: string; /** The `AGENTPROTO_JOIN` value — an `agentproto://pair?…&scope=host` URL. * Shown ONCE; `list()` never returns it. */ token: string; rendezvousUrl: string; expiresAt: string; } interface JoinTokenRegistryDeps { /** Lazily load (create on first use) the daemon identity — same contract * as `PairingRegistryDeps.loadIdentity`. */ loadIdentity: () => Promise; /** Path to `join-tokens.json`. Defaults to `~/.agentproto/join-tokens.json`. */ joinTokensPath?: string; /** Configured rendezvous URL default — same three-state contract as * `PairingRegistryDeps.defaultRendezvousUrl` (absent → hosted default; * `""` → explicit opt-out, fails closed without `--rendezvous`). */ defaultRendezvousUrl?: string; /** Dial a rendezvous WS and adapt it to a `FrameSink`. Same shape as * `PairingRegistryDeps.dial`/`HostRegistryDeps.dial`. */ dial: (wsUrl: string, signal: AbortSignal) => Promise; /** Called once per successful join, with the box's self-minted host offer * URL and self-reported name/meta — normally `hostRegistry.add`. Errors * are logged and swallowed: a bad/unreachable offer from one join must not * crash the standing accept loop. */ addHost: (offerUrl: string, name?: string, meta?: HostJoinMeta) => Promise; /** Called when a joined box says goodbye just before it exits (see * `JoinHello.goodbye`), with its daemon fingerprint — normally * `hostRegistry.snapshotNow`, so the box's final session output is captured * while it can still answer. The box waits for this to settle (bounded on * its side), so it should not hang. Errors are logged and swallowed. */ flushHost?: (fingerprint: string) => Promise; /** Called after the goodbye's final capture (even if it failed), with the * same fingerprint — normally `hostRegistry.markEnded`, so a departed CI * box stops reading as a live host immediately. Errors are logged and * swallowed. */ endHost?: (fingerprint: string) => Promise; /** Injectable clock (ms). Defaults to Date.now. */ now?: () => number; /** Diagnostic log sink. */ log?: (line: string) => void; /** Handshake ceiling per attempt. Default 110s (mirrors PairingRegistry's * park timeout, kept just under the broker's own). */ handshakeTimeoutMs?: number; /** Reconnect backoff floor / ceiling (ms) after a failed dial. Defaults 1s/30s. */ reconnectMinMs?: number; reconnectMaxMs?: number; } interface JoinTokenRegistry { /** Mint a token and start its standing accept loop. */ create(input: CreateJoinTokenInput): Promise; /** All persisted tokens (copies), `secret` stripped. Loads on first call. */ list(): Promise[]>; /** Revoke by id or name — stops its accept loop. Returns false if nothing * matched or it was already revoked. */ revoke(idOrName: string): Promise; /** Start standing accept loops for every active persisted token. Call once * at boot, after the gateway/hostRegistry are wired. */ startAutoconnect(): Promise; /** Tear down every accept loop. */ shutdown(): Promise; } declare function createJoinTokenRegistry(deps: JoinTokenRegistryDeps): JoinTokenRegistry; /** * Shared types for pluggable sandbox providers. * * The sandbox family is a `@agentproto/provider-kit` consumer, same shape as * the tunnel family (`remote-providers/types.ts`): {@link SandboxProviderHandle} * extends the kit's generic `AdapterHandle` (slug/name/version/description/ * requiresSetup/check) with the AIP-36 capability namespace and the concrete * `@agentproto/sandbox` `SandboxProvider` (`boot()`) the handle wraps. */ /** * Declared capabilities of a sandbox provider — pure metadata, surfaced in * `list_sandbox_providers`. Never carries secrets. Namespace mirrors AIP-36 * SANDBOX.md (`network.egress`, `mounts`, `lifecycle.pause_after_idle`, * `read_only`, `limits.timeout_ms`). */ interface SandboxProviderCapabilities { /** Sandbox can be given a network egress allowlist (AIP-36 `network.egress`). */ networkEgress: boolean; /** Sandbox supports mounting external filesystems (AIP-36 `mounts`). */ mounts: boolean; /** Sandbox can be paused (not just killed) between turns (AIP-36 `lifecycle.pause_after_idle`). */ lifecyclePause: boolean; /** Sandbox can be started read-only (AIP-36 `read_only`). */ readOnly: boolean; /** Sandbox's own `BootedSandbox` handle exposes `exec()` — the seam the * `sandbox_exec` MCP tool shells through. Metadata only; the tool itself * checks the live handle's `exec` presence. */ exec?: boolean; /** Hard cap on `limits.timeout_ms`, when the provider enforces one. */ maxTimeoutMs?: number; /** * Descriptive metadata only — no runtime behaviour reads this yet. * Marks a provider whose booted box is ADVERTISED as shareable by several * agentproto sessions (e.g. the `computer` provider, whose daemon runs * exactly one self-hosted microVM). Providers whose boot contract assumes * a single-tenant surface leave this false. No reader in the registry or * reuse path consumes this flag today. */ sharedSessions?: boolean; } /** * A sandbox provider as an adapter-kit handle. Rides on the kit's generic * {@link AdapterHandle} and adds the sandbox-specific `capabilities` plus * the `@agentproto/sandbox` `SandboxProvider` the handle wraps — the thing * `createSandboxAgentSessionHost` actually boots. */ interface SandboxProviderHandle extends AdapterHandle { readonly provider: SandboxProvider; readonly capabilities: SandboxProviderCapabilities; /** * Credential fields this provider accepts via `setup_sandbox_provider` * (e.g. e2b's `apiKey`). Omit (or empty) when the provider needs no * credentials (e.g. `local`). */ readonly setupFields?: readonly SetupField[]; /** * The directory INSIDE the box a spawned agent session should default to * when the caller passed no explicit `cwd` — e.g. e2b/Box's login home * `/home/user`. Absent for a same-machine passthrough provider (`local`), * where the HOST's own resolved cwd is already a valid path in the box * (they're the same filesystem) and forwarding it as-is is correct. * Presence of this field is also the signal `bootSandboxAgentSession` * uses to reject an explicit HOST-only path (e.g. `/Volumes/...`) instead * of forwarding it into a box where it can never resolve. */ readonly defaultCwd?: string; /** * When true, `bootSandboxAgentSession` omits `cwd` from the box's own * `agent_start` call entirely (rather than forwarding the HOST's resolved * cwd) whenever the caller passed no explicit `agent_start.cwd` — letting * the box's own `agent_start` apply ITS normal default-cwd resolution, * exactly like an ordinary non-sandboxed local spawn. For a `device:` * target the "box" is another user's own machine with its own filesystem * layout (its default workspace), so forwarding the driving daemon's * host-shaped `cwd` (e.g. `/Volumes/...`) would almost always ENOENT * there. Distinct from `defaultCwd`: that field substitutes a KNOWN * in-box path (e2b/Box's `/home/user`); this one substitutes NOTHING, * deferring entirely to the remote's own resolution. An explicit * `agent_start.cwd` is still forwarded as-is regardless of this flag. */ readonly omitCwdWhenImplicit?: boolean; } /** * Slug-keyed sandbox provider registry — the sandbox family's counterpart to * `remote-providers/registry.ts`. `local` resolves in-process; everything * else is a dynamic import of `@agentproto/sandbox-` (e.g. * `@agentproto/sandbox-e2b`), wrapped with this registry's own capability/ * setup metadata because those packages export a bare `@agentproto/sandbox` * `SandboxProvider` (just `boot()`) rather than a self-describing * adapter-kit handle the way the tunnel family's third-party packages do. * * `modal` and `daytona` are catalog placeholders — AIP-36 day-1 provider * ids with no published `@agentproto/sandbox-` package yet, so they * always resolve to `null` (status "supported") until one ships. Their * repeated import misses (and every other third-party import here) go * through the shared bounded probe in `../provider-probes.ts`, which proves * them missing synchronously instead of loading them on every MCP request. */ /** Per-slug credentials, as stored by the creds store / setup tool. */ type SandboxCreds = Record; /** * Sandbox family on top of `@agentproto/provider-kit` — mirrors * `tunnel-adapters.ts`. This module is the entire bridge between the * generic kit and `@agentproto/sandbox`'s `SandboxProvider` concept: it * contributes nothing the kit already owns (catalog/status/creds/ledger/ * list/MCP-tool plumbing); it only supplies the sandbox-family `TInfo` * (`SandboxAdapterInfo`), the static `SANDBOX_CATALOG`, and the resolver * that maps a catalog slug to a concrete {@link SandboxProviderHandle} * (`./sandbox-providers/registry.js`). * * Built on `makeProviderFamily` (`@agentproto/provider-kit`), which owns the * creds store, the setup ledger, the catalog listing, the resolver, the * setup schema and the `list_sandbox_providers` / `setup_sandbox_provider` * tools. `legacySetup` keeps the setup semantics this module had before it * moved onto the factory (optional-unless-`required:true`, replace-not-merge, * store errors propagate). * * This is pure additive plumbing (introspection + setup) — it does NOT wire * a `sandbox` field into `agent_start`. That lands in a follow-up PR; the * `resolveSandboxProvider`/`listSandboxProviders` overrides below exist now * so that later wiring can inject the same resolver/lister this module * builds by default, mirroring `resolveAgentAdapter`/`listAgentAdapters`. * * Security: `toSandboxInfo` exposes only `capabilities` — never a cred * value (Appendix B). The setup tool's fields are marked SENSITIVE and the * result NEVER echoes any field value back. */ /** * Family descriptor (`TInfo`). Pure metadata surfaced in * `list_sandbox_providers`. The kit's `AdapterEntry` already carries * slug/name/description/status/version, so the only sandbox-specific field * is the declared capability set. NEVER carries a cred value. */ interface SandboxAdapterInfo { capabilities: SandboxProviderCapabilities; } /** Resolve a sandbox provider slug to a handle, or null when unavailable. */ type SandboxProviderResolver = AdapterResolver; /** List every sandbox provider with its live status + capabilities. */ type SandboxProviderLister = AdapterLister; /** Slugs of the concrete box-owning providers, in catalog order. `local` is a * same-filesystem passthrough with no control plane to enumerate, and `auto` * is a selector rather than an owner, so neither is ever swept or listed by * default. Placeholders still resolve to null and are reported as not * scanned by the caller. */ declare const DEFAULT_SANDBOX_PROVIDER_SLUGS: readonly string[]; /** Providers a bare `sandbox_gc` sweeps. Only the `computer` controller * scopes its boxes to this daemon's tenant, so only it can be swept by * default: a shared account (e2b) holds boxes from other daemons, machines, * CI and tools, and every one of those would look like an orphan here. * `sandbox_list` still defaults to every concrete provider because reading * is safe; sweeping is not. */ declare const DEFAULT_SANDBOX_GC_PROVIDER_SLUGS: readonly string[]; /** Build the sandbox-family creds store (per-slug, 0600). */ declare function makeSandboxCredsStore(home?: string): CredsStore; /** * Resolve a catalog slug to a concrete handle via the provider registry, * `local` in-process, `e2b`/`modal`/`daytona` dynamic-imported. Reads * stored creds first so `e2b` (and any future catalog entry) resolves * configured when possible; unconfigured slugs resolve to a descriptor-only * handle (listing never calls `start()`/`check()`). An unknown slug * resolves to `null` ("supported but not installed"). */ declare function makeSandboxResolver(credsStore: CredsStore, opts?: { /** Injectable for tests: a one-shot importer that bypasses the shared * probe cache. Left unset (production), third-party imports run through * `provider-probes.ts`: bounded, coalesced, and synchronously * preflighted so an unpublished placeholder (`modal`/`daytona`) never * enters Node's async loader. */ importPackage?: (packageName: string) => Promise>; }): SandboxProviderResolver; /** * Fire-and-forget webhook notifier for session lifecycle events. * * Each session can register its own `notifyUrl` (via `agent_start`), with an * optional `notifySecret` (`whsec_...`). A global URL can be set via * `AGENTPROTO_NOTIFY_URL` env var (+ optional `AGENTPROTO_NOTIFY_SECRET`) or * `~/.agentproto/notify.json` `{url, secret?}` (env wins). Both are POSTed * when an event fires — the union of per-session + global URLs, deduplicated * by URL (a URL registered both ways is posted once; the per-session secret * wins over the global one on conflict). * * Signing (opt-in, backward compatible): when a target has a secret, the * POST carries Standard Webhooks headers (`webhook-id` / `webhook-timestamp` * / `webhook-signature`, see `webhook-egress/signing.ts`) — HMAC-SHA256 over * `id.timestamp.body`, the same contract sentinel/MCP Events already use for * egress. A target with no secret is posted exactly as before: unauthenticated, * `Content-Type` only. Existing callers that never set `notifySecret` or a * `secret` in notify.json see zero behavior change. * * Retry policy: one retry after 2 s on network error. No retry on 4xx/5xx. * Timeout: 10 s per attempt. All errors are swallowed — the notifier never * throws into the session's hot path. * * Of the daemon-scoped `cron:*` events, ONLY `cron:unhealthy` is relayed (to * the global URL — cron events carry no sessionId). `cron:fired` / * `cron:succeeded` / `cron:failed` stay filtered: relaying every fire would * spam whatever the operator's global URL feeds (e.g. a Telegram relay) on a * schedule that can be every 20 minutes. */ interface WebhookNotifier { /** Register a per-session URL (called from agent_start), with an optional * `whsec_...` secret to sign its deliveries. */ register(sessionId: string, url: string, secret?: string): void; unregister(sessionId: string): void; /** Handler to wire into SessionEventBus.onAny. Fire-and-forget. */ onSessionEvent(ev: SessionEvent): void; } /** * In-process workflow runner — executes an ordered list of WorkflowStage[], * each stage containing one or more parallel WorkflowStep[], with an * explicit barrier between stages. * * As of the engine-unification refactor, the internals delegate to * `runWorkflow` from @agentproto/workflow-runtime via a translation layer: * each stage becomes a `ParallelStep` with one `AgentStep` branch per step; * stages are chained as a flat `steps[]`. The public API — * `WorkflowRunner.start()` / `status()` / `cancel()` — is preserved * unchanged. * * Persistence: one file per run under ~/.agentproto/workflow-runs/ (see * workflow-run-store.ts) — only DIRTY runs are written, asynchronously * (write-tmp + rename), and step outputs over a ceiling are stored as a * preview + pointer with the full value in a per-run artifact file. A legacy * ~/.agentproto/workflow-runs.json is split into that layout once at boot * (kept as `.bak`). Active runs stay resident; finished ones are summaries, * lazy-loaded on `status()`. * * On load, any run with status "running" or * "awaiting-input" is immediately marked "failed" with reason * "interrupted by daemon restart" — EXCEPT a run parked at a * `kind: "suspend"` step (status "awaiting-input" with a durable * `awaitingSuspend` record), which stays suspended and is re-registered so * a matching `resumeSuspend` still lands (AIP-15 conformance rule 7) — and a * run parked at an approval, kept as a slim envelope until it is decided or * its approval expires (`approvalTtlMs`). * * Persistence opt-in: disabled by default (persist defaults to false when * no persistPath is supplied) so unit tests never touch ~/.agentproto/. */ interface WorkflowRunner { start(input: { workflowId: string; stages: WorkflowStage[]; workspaceSlug?: string; cwd?: string; notifyUrl?: string; /** Enable journal caching for this run; cacheable steps replay unchanged outputs. */ cacheKey?: string; /** App provenance — the installed app this run belongs to. Omit to let * the runner resolve it from the registry (workflow id owned by exactly * one installed app). */ appId?: string; /** The app_run this run belongs to, when started through an app. */ appRunId?: string; /** Ledger `item` stamped on every ledger event this run appends. */ item?: string; /** Session to notify (inbox item) on success / failure / approval. */ callerSessionId?: string; /** * Supervising session every step session nests under. Recorded as each * spawned step session's `parentSessionId`, so a review/fix run reads as * ONE supervisor with children instead of a set of anonymous depth-0 * roots. Descriptor-only lineage - it never relaxes a depth/role guard. */ supervisorSessionId?: string; }): Promise; startFromFile(input: { path: string; input?: unknown; cwd?: string; workspaceSlug?: string; cacheKey?: string; /** App provenance — same resolution as `start`. */ appId?: string; appRunId?: string; item?: string; /** Session to notify (inbox item) on success / failure / approval. */ callerSessionId?: string; /** Supervising session step sessions nest under - see `start`'s doc. */ supervisorSessionId?: string; }): Promise; /** The run record. A run that is no longer resident (older terminal runs) * is lazy-loaded from its per-run file. Step outputs over the ceiling are * {@link BoundedOutputRef}s (preview + pointer); `resolveOutputs: true` * returns a COPY with each pointer replaced by the full value read back * from its artifact file (values over {@link MAX_READ_ARTIFACT_BYTES} * keep their pointer — fetch those through `readArtifact`). */ status(runId: string, opts?: { resolveOutputs?: boolean; }): WorkflowRun | undefined; /** Every known run. Active runs and the newest terminal ones are the live * records; older terminal runs are SUMMARIES (stages and steps, but no * step outputs / final output / input) — use `status(runId)` for detail. */ list(): WorkflowRun[]; /** Resolves once every change made so far is on disk. Persistence is * asynchronous and dirty-run-only; await this where a test or a shutdown * path needs durability. */ flush(): Promise; /** Stop this runner and drain persistence: clears its trailing-flush and * lease-heartbeat timers, unsubscribes its bus listeners, removes its * process-exit drain, awaits every queued write, and removes lease * sidecars. After it resolves, nothing more is written by this runner and * further writes are dropped, so call it only when no run is actively * executing (a shutdown path should stop or await those runs first). * Concurrent calls share one disposal promise. Production daemons that * live for the process lifetime need not call it; tests that delete a * persist directory MUST. */ dispose(): Promise; /** AIP-58 §5/§9 `run.events` — events with `seq > sinceSeq`, in order. * `undefined` when `runId` is unknown; an empty array is a known run * with nothing new to report. Reads straight from the on-disk log, so it * works for a run from a prior daemon process too. */ events(runId: string, sinceSeq?: number): RunEventEnvelope[] | undefined; /** AIP-58 §2 owner-liveness sweep: marks every `running` run whose lease * has expired (`now - lease.heartbeatAt > leaseTtlMs`, no live renewal — * see `WorkflowRun.lease`) `failed { code: "orphaned" }`. A conservative * TTL, not a restart check (that's `loadRuns`'s job) — this is what * catches an owner that died WITHOUT the daemon itself restarting. * `now` defaults to the real clock; a caller (or a test) MAY pass a fixed * one instead of waiting on a real timer. Callable directly (tests) or on * a caller-owned interval (the daemon composition root); this runner * does not schedule it on its own. */ sweep(now?: Date): { orphaned: string[]; expiredApprovals?: string[]; }; resolve(runId: string, stageIndex: number, stepIndex: number, response: string): void; /** Resolve a `kind: "approval"` step's parked human decision (the * "awaiting-approval" inbox). `who` records who decided (e.g. "jeremy"); * `approvalId`, when given, must match the parked request. */ resolveApproval(runId: string, input: { approvalId?: string; approved: boolean; who: string; note?: string; }): { ok: true; } | { ok: false; error: "run_not_found" | "not_awaiting_approval" | "approval_id_mismatch"; message: string; }; /** Resolve a parked `kind: "suspend"` step OR an AIP-58 §3(a) * `run.requestInput` suspend (AIP-15 rule 7 / AIP-58 §3). Works both for * a live run and for a run re-registered after a daemon restart (in * which case the recorded decision lands but the run's execution cannot * resume). `stepId`, when given, must match the parked step. When the * parked record carries a `schema` (the §3(a) case), `payload` MUST * validate against it BEFORE the transition happens — an invalid * payload is rejected and the run stays suspended. */ resumeSuspend(runId: string, input: { stepId?: string; payload?: unknown; }): { ok: true; } | { ok: false; error: "run_not_found" | "not_awaiting_suspend" | "step_id_mismatch" | "invalid_payload"; message: string; }; /** * AIP-58 §9 `run.requestInput`, called by the executing step's OWN * session (via the `run_request_input` MCP tool) — records the signal * against whichever run/step spawned `sessionId`, resolved from this * runner's own spawn bookkeeping. Does not end the turn. A session not * owned by any running workflow step is a tool error with no side * effect. */ recordInputRequest(sessionId: string, req: { prompt: string; schema?: Record; }): { ok: true; runId: string; stepId: string; } | { ok: false; error: "session_not_in_workflow_step"; }; cancel(runId: string): void; /** * AIP-58 §6 Journal `run.retry` — given a `failed`/`cancelled` runId, * starts a NEW run (fresh runId, its own AIP-58 §4 workspace seeded with * a copy of the original's `scratch/` + `artifacts/` — including any fix * made there after the failure — `retryOf` pointing at the original) * that replays every step the original run * already completed from its own journal — no re-execution, no re-spawn — * and re-executes only from the first step that never succeeded onward. * "The original run's journal is the source": this works whether or not * the caller ever passed a `cacheKey` to the original `start`/ * `startFromFile` call — every run journals its own steps internally, * ALWAYS (`internalJournal` below), independent of and in addition to * whatever the caller's own `cacheKey`/`cacheable` opted into (a run * started WITH a `cacheKey` keeps that cache's existing semantics * unchanged; its successful writes are additionally relayed into the * internal journal — see `teeIntoInternalJournal`). A step whose resolved * input changed (an explicit `input` override here, or an upstream step * producing different output because ITS input changed) naturally misses * the journal and re-executes — no separate invalidation logic; it's the * same resolved-input-hash comparison a cache hit always does * (`@agentproto/workflow-runtime`'s `readStepCache`). * * Refused (`not_retryable`) unless the original run's status is `failed` * or `cancelled` — a `done` (succeeded) run has nothing left to retry, an * in-flight run has no failure to retry FROM. Refused (`run_not_found`) * for an unknown runId, and (`not_retryable`) — never a thrown error — * for a run that predates this field (no `path`/`startStages` recorded — * a leftover pre-P5 record) or whose original source can no longer be * reloaded (e.g. the WORKFLOW.md file has since moved or no longer * compiles): reloading/recompiling is wrapped so a broken source is * always a documented refusal, never an unhandled rejection out of this * method. */ retry(runId: string, input?: { input?: unknown; }): Promise<{ ok: true; run: WorkflowRun; } | { ok: false; error: "run_not_found" | "not_retryable"; message: string; }>; /** * AIP-58 §4/§9 `run.publish { runId, artifactKey, to? }` — copy a * SUCCEEDED run's recorded artifact out of its own workspace to a * caller-visible destination. MUST be refused unless the run's `status` * is already `"succeeded"` (§4 "Publish is a separate, explicit, * post-success operation" — never implicit at run end, so two runs * racing to publish to the same shared path is always an explicit, * attributable act, not an accident of finishing order). `to`, when * omitted, defaults to the artifact's declared `outputsFiles..path` * (interpolated); relative destinations resolve against the run's own * `cwd` (F25's app-root default) — the "outer" workspace AIP-16 calls the * sync target. Fires `run.published` on success. */ publish(runId: string, input: { artifactKey: string; to?: string; }): Promise<{ ok: true; publishedPath: string; } | { ok: false; error: "run_not_found" | "not_succeeded" | "artifact_not_found" | "no_destination"; message: string; }>; /** * AIP-58 §4 "fetchable" — read a recorded artifact's file content back. * Capped at {@link MAX_READ_ARTIFACT_BYTES}; a larger file still resolves * (with `truncated: true`) rather than failing outright, so a caller can * at least confirm the artifact exists and inspect its start. */ readArtifact(runId: string, key: string): Promise<{ ok: true; entry: ArtifactEntry; content: Buffer; truncated: boolean; } | { ok: false; error: "run_not_found" | "artifact_not_found" | "file_missing"; message: string; }>; } /** * Tool-subset guard — the single mechanism that scopes which MCP tools * a `register*` pass actually exposes on a server. * * `withToolSubset(server, subset)` returns a Proxy where * `server.tool(name, …)` is a no-op when `name ∉ subset`; every other * call delegates to the underlying server unchanged. The orchestrator * sub-gateway (ADR §4.2 / WP2) wraps its per-request server with this * before running the normal `registerSessionTools` / * `registerOrchestrationTools` passes, so a scoped child orchestrator * only ever sees the curated allowlist (spawn / prompt / wait / poll / * output / list / kill) — never `command_execute`, fs, remote, import, * or terminal tools. * * Backward-compatible by construction: callers that don't pass a subset * use the raw server and register everything, exactly as before. */ /** The per-request `?denyTools=` / `?allowTools=` lists of a `/mcp` mount. */ interface ToolLists { readonly denyTools?: ReadonlySet | undefined; readonly allowTools?: ReadonlySet | undefined; } /** * `defaults.apps.exposedTools`: the operator kill-switch for installed apps' * `exposes.tools` on the /mcp gateway. Read per request, like * `resolveMcpConfig`, so a `config_set` applies to the next call. * * "read" (default) access: read for every caller; write/approve only for a * caller whose AGENT.md opted in * "off" nothing is registered * "all" every declared tool, for every caller * * Besides an AGENT.md opt-in, a write/approve tool reaches a caller through * its app's `requires.apps[].tools`: a session run from one of the consumer * app's own AGENT.md files is granted the listed provider tools, while the * provider is installed at a satisfying version ({@link exposedToolGrantsFor}). */ type ExposedToolsMode = "off" | "read" | "all"; /** Who is calling an exposed tool: the session, its AGENT.md opt-in, and its app grants. */ interface ExposedToolCaller { readonly sessionId?: string | undefined; readonly optIn?: readonly string[] | undefined; /** {@link exposedToolGrantKey} keys from {@link exposedToolGrantsFor}. */ readonly grants?: ReadonlySet | undefined; /** The session's tool deny grants (`SessionDescriptor.toolDenyGrants`). The * gateway applies them through its wrapped server; a surface that runs an * exposed tool without registering it applies them itself. */ readonly denyGrants?: readonly Grant[] | undefined; } /** * MCP tools that install and run `@agentproto/app` apps — a bundle of * one or more AIP-42 agents plus the AIP-15 workflows they run, emitted * under `

/.agentproto/` by `defineApp().emit(dir)`. * * Tools: * app_install loadAppHandle(dir) → validate → persist an installed-app record * app_list installed apps + a runs summary * app_run spawn a session per selected agent (each agent resolves its * own adapter/harness; model is pass-through, optional * `sequence` runs agents one-at-a-time under one appRunId) * app_status fan out an app_run's sessions + the app's workflow runs * app_stop kill an app_run's sessions * * `app_install` moves workflow-step tool-id validation from STEP-DISPATCH * time (where it used to surface, deep into a run — see * `output/phase-a-findings.md` A2: `unknown daemon tool "apply_patch"`) to * install time, listing every missing id at once instead of failing one * step at a time. */ interface AppToolCallDeps { dispatchTool?: (name: string, args: Record) => Promise; /** `callerSessionId` is the calling session, forwarded to the imported MCP * server (Bureau binds tab ownership to it). */ callImportedTool?: (alias: string, tool: string, args: Record, callerSessionId?: string) => Promise; /** Who is calling: the session (forwarded to an imported tool), its AGENT.md * opt-in and its app's `requires.apps` grants. A `write`/`approve` exposed * tool on the HTTP twin needs a caller session plus an opt-in or a grant * (or mode `all`), like on the gateway. */ caller?: ExposedToolCaller; /** `defaults.apps.exposedTools`, resolved by the caller. Set only by the HTTP * twin of `app_tool_call`: it then also accepts an installed app's * `exposes.tools` ids that are not in `ui.tools` (what `agentproto mcp-app` * forwards), under the kill-switch's access limit. Absent = `ui.tools` only. */ exposedToolsMode?: ExposedToolsMode; /** The request's `?denyTools=` / `?allowTools=`, same wire contract as * `/mcp`: an exposed tool they filter out is refused, like the gateway's * wrapped server never registers it. */ toolLists?: ToolLists; /** The daemon's pending-permission inbox lookup (the same source * `permissions_list` reads, `SessionsRegistry.listPendingPermissions`), * used by `LINK_OWNERSHIP_CHECKS` to check a `permissions_respond` under a * link token. Absent = that check fails closed. */ findPendingPermission?: (id: string) => { sessionId: string; } | undefined; } /** Stable marker in the error `performInstall` returns when it refuses to * re-point an installed app into a linked git worktree (see * `PerformInstallOptions.allowWorktreeRepoint`). Callers that install * implicitly (`agentproto maintain` / `steward`) match on it to keep the * installed copy and carry on. */ declare const APP_INSTALL_WORKTREE_REPOINT_REFUSED = "worktree-repoint-refused"; /** * Telegram bot credential store + MCP tools. * * Uses @agentproto/provider-kit's makeCredsStore so tokens live at * ~/.agentproto/telegram-bot-creds/.json with mode 0600. The value * is never echoed by any tool; status reads only report whether a token * exists and a one-way fingerprint/last4 identity. */ interface TelegramBotCreds { token: string; } interface TelegramBotCredsStore { read(alias: string): Promise; write(alias: string, creds: TelegramBotCreds): Promise; exists(alias: string): Promise; } /** Narrow view of the manifest fields this ingress reads. Every field is * optional: an app whose manifest predates them accepts nothing and exposes * nothing (never "everything"). */ interface A2aAppHandleLike { accepts?: { tasks?: boolean; }; exposes?: { agents?: readonly string[]; workflows?: readonly string[]; }; /** The app's bundled workflows (id + file path), used to start an exposed * workflow skill. Absent when the manifest bundles none. */ workflows?: readonly { id: string; path: string; }[]; } /** * A2A push notification delivery (`a2a-task-http.ts`'s config store half is * in a2a-tasks.ts). One background watcher per task, started the moment a * push config exists for a still-running task: it consumes `watchTask` (the * same poll loop the SSE streams use — never a copy) and POSTs every yielded * `StreamResponse` member to every config of the task that exists at that * moment (the store is re-read per event, so a deleted config stops * receiving at once). Delivery is best-effort: a failed POST is logged and * retried per the rules below, never thrown, and never stops the watcher. * * Watchers live in memory only: after a daemon restart, tasks that were * still being watched are not resumed (their configs persist; a later * config create on the same task starts a fresh watcher). */ /** Per-POST knobs, injectable so tests run fast. */ interface A2aPushDeps { /** `fetch` used for every webhook POST. Defaults to the global `fetch`. */ fetchImpl?: typeof fetch; /** Poll cadence of the shared task watcher. Defaults to 1000 ms. */ pollMs?: number; /** Hard cap on one watcher (same 30 min cap as SSE streaming). */ maxMs?: number; /** Per-POST attempt timeout. Defaults to 10 s. */ requestTimeoutMs?: number; /** Backoff between POST attempts (nth retry waits nth entry). Defaults to * `[1 s, 5 s]` — at most 3 attempts total. */ retryDelaysMs?: readonly number[]; sleep?: (ms: number) => Promise; now?: () => number; /** Failures are logged here, never thrown. Defaults to a silent log. */ log?: (line: string) => void; } /** * `POST /a2a/apps/:appId` — A2A 1.0 JSON-RPC 2.0 task ingress for one * installed app. `SendMessage` starts an `app_run` for an exposed agent * skill or a background workflow run for an exposed workflow skill, * `GetTask` reports it, `ListTasks` pages the ledger for the app, and * `CancelTask` stops it. `SendStreamingMessage` starts * a run the same way and answers `Content-Type: text/event-stream`; * `SubscribeToTask` attaches to a task that is still running the same way. * Both streams are a poll of `readTask` (no event bus): every SSE event is * `data: ` whose `result` is exactly one of `{task}`, * `{message}`, `{statusUpdate}` or `{artifactUpdate}` — A2A 1.0's oneof — and * the stream ends on a terminal state, a client disconnect, or the * `streamMaxMs` cap. Everything runs through the * daemon's own `app_run` / `app_status` / `app_stop` / `app_artifact_get` * and `workflow_run_file` / `workflow_status` / `workflow_cancel` tools via * `dispatchTool` (the same in-process dispatcher the REST `tool-call` twin * uses), so there is one implementation of a run. * * The four push-config methods (`CreateTaskPushNotificationConfig`, * `GetTaskPushNotificationConfig`, `ListTaskPushNotificationConfigs`, * `DeleteTaskPushNotificationConfig`) manage per-task webhook registrations * in a JSON store beside the ledger; a config on a live task arms one * background watcher (a2a-push.ts) that POSTs the same `StreamResponse` * events the SSE streams write. `SendMessage` / `SendStreamingMessage` accept * a `configuration.taskPushNotificationConfig` (or its `pushNotificationConfig` * alias) the same way. * * Mapping and the task ledger live in a2a-tasks.ts. Auth (bearer + browser * origin guard) is applied by the dispatch block in http-server.ts. */ /** Optional knobs on `RuntimeHttpServerOptions.a2aTasks`. */ interface A2aTaskHttpConfig { /** Daemon state dir; the ledger lives in `/a2a-tasks/`. * Defaults to `~/.agentproto`, next to `apps.json`. */ stateDir?: string; /** Reads `accepts` / `exposes` for an installed app dir. Defaults to * app's `loadAppHandle`. */ loadHandle?: (dir: string) => Promise; /** Poll cadence of the SSE task streams (`SendStreamingMessage`, * `SubscribeToTask`). Defaults to 1000 ms. */ streamPollMs?: number; /** Hard cap on one SSE stream: it ends with a `statusUpdate` of the state * the task is actually in. Defaults to 30 minutes. */ streamMaxMs?: number; /** Push delivery knobs (fetch, poll cadence, retries, clock) — injectable * so tests run fast. See a2a-push.ts. */ push?: A2aPushDeps; } /** * `config_get` / `config_set` — the one MCP (+ HTTP) surface for reading and * writing `~/.agentproto/config.json`, built on the zod schema + key * registry `config-schema.ts` (PR-1) declared. See * `.plans/agentproto-config/PLAN.md` PR-2. * * `config_get` reports, per registered key: the raw file `value`, the * `effective` value actually in force (env > config > registry default, * using the SAME resolvers the daemon itself uses where one exists — * `loadWorktreeIsolation`, `loadSpawnAttach`, `loadSpawnDedupe`, * `resolveAttentionDelaySec`, `loadProvenanceWrapGh`, * `loadAgentsMdInlineMaxKb`), and — for a `restart`-class key — whether the * file has changed since the daemon booted (`pendingRestart`, computed * against the BOOT SNAPSHOT captured once in `index.ts`, never re-read). * * `config_set` writes exactly one key through the registry's allowlist: * rejects an unknown key or a non-`writable` one (secret / lockout fields — * see `config-schema.ts`'s `CONFIG_KEYS` docs), type-validates the value, * then validates the WHOLE resulting config before saving, optionally * gated by an optimistic-concurrency `revision` (sha256 of the file bytes). * It never restarts anything — it only reports whether the daemon needs * one (`applied: "restart-required"`) and whether an env var already * shadows the write (`shadowedByEnv`). * * Registered on the root `/mcp` server only (see `index.ts`) — NOT added to * `DEFAULT_ORCHESTRATOR_TOOLS` (`orchestrator-gateway.ts`), so a scoped * child orchestrator can never reconfigure the daemon it runs on. */ /** Boot-computed values for the four `daemon.*` restart-class knobs whose * actual env>config>default resolution happens CLI-side (`serve.ts`'s * `resolveIdleReapAfterMs` & co.) before `createGateway` ever runs — the * runtime layer never re-implements that resolution, it just reports the * number the daemon actually booted with (same values fed to * `daemon_health` / `GET /health`). Keyed by the registry's own dotted * path so `describeKey` can look one up generically. */ interface BootDaemonKnobs { "daemon.idleReapAfterMs"?: number; "daemon.sandboxIdleReapAfterMs"?: number; "daemon.crashDetectIntervalMs"?: number; "daemon.restartSweepIntervalMs"?: number; "daemon.turnStallAfterMs"?: number; } interface ConfigToolsDeps { /** Defaults to the real `loadConfig` — tests inject a stub bound to a * temp-dir path so nothing here ever touches the real `~/.agentproto`. */ loadCfg?: () => Promise; /** Defaults to the real `saveConfig`. */ saveCfg?: (next: AgentprotoConfig) => Promise; /** Defaults to `CONFIG_FILE_PATH()` — the path `revision` is hashed from * and the value returned as `config_get`'s top-level `path`. */ configPath?: () => string; /** The config the daemon booted with, captured ONCE in `index.ts` where * `daemonConfig` is loaded — never re-read at call time. This is the * baseline `pendingRestart` compares the live file against for every * `apply: "restart"` key. */ bootConfig: AgentprotoConfig; /** The daemon-wide event bus `config:changed` is emitted on. */ events: RuntimeEvents; /** See {@link BootDaemonKnobs}. Omitted in a host that doesn't wire the * four idle-reap/crash-detect/restart-sweep/turn-stall knobs (tests) — * those four keys then fall back to the generic boot-value-or-default * rule like every other `restart`-class key. */ bootDaemonKnobs?: BootDaemonKnobs; } /** * mcp-proxy — connect the daemon as an MCP *client* to every server * the user imported via `~/.agentproto/imported-mcps.json`, and * surface their tools through dedicated MCP tools on the daemon's * own server. The chain looks like: * * operator (cloud Acme) ──MCP──▶ agentproto-daemon (this proxy) * │ * ├──stdio──▶ chrome-devtools-mcp * └──http───▶ goose-bridge * * v1 design choice: instead of re-registering each upstream tool * under a namespaced name (which requires JSON-Schema↔Zod conversion * for every exotic shape — recursive refs, oneOf, etc.), the proxy * exposes two indirection tools: * - `mcp_list_imported_tools(alias?)` lets the operator discover * what's available * - `mcp_call_imported(alias, toolName, args)` invokes a specific * tool, forwarding the JSON args verbatim * * Trade-off: agents do a 2-step (list → call) instead of seeing the * imports directly in their tool palette. We keep tool inputs * unconstrained at the MCP layer; validation is the upstream * server's job. v2 can re-expose namespaced tools once we ship a * solid JSON-Schema → Zod converter. * * Lifecycle: clients are connected lazily on the first call that * touches them and held open until daemon shutdown. The registry * notices new/removed imports by stat'ing the imports file's mtime * before each call — cheap, avoids forcing the HTTP routes to push. */ interface ProxyToolDescriptor { name: string; description?: string; /** JSON Schema as published by the upstream server. Forwarded to * the operator verbatim — they read it to figure out args. */ inputSchema?: unknown; /** Opaque metadata from the upstream tool listing. Carries client-side * hints such as `x-client-resolve`. */ _meta?: Record; } interface ProxyAliasSummary { alias: string; importId: string; source: DiscoveredMcp["source"]; type: DiscoveredMcp["type"]; /** "connected" | "error" | "pending" — pending = never tried yet. */ status: "connected" | "error" | "pending"; toolCount: number; lastError?: string; /** `live` re-reads the source harness config; `snapshot` uses the stored copy. */ resolve?: "live" | "snapshot"; /** Set when the last resolution could not use the live source / a secret. */ stale?: { reason: string; }; /** Header/env KEY names held behind secret refs (never values). */ secretRefKeys?: { headers?: string[]; env?: string[]; }; } interface CallResult { ok: true; result: unknown; } interface CallError { ok: false; error: string; } type ProxyCallOutcome = CallResult | CallError; /** Who is making an imported-MCP call, when the entry point knows. */ interface ProxyCallContext { callerSessionId?: string; } /** * Pre-dispatch hook consulted by every `callTool`. Returning `{allow:false}` * short-circuits the call with `reason` as its error; the upstream is never * contacted. `allow` may carry per-call `headers` (the caller session and node, * `caller-scope.ts`) that a connection opened for forwarding sends with that * call and no other. Unset by default, so a bare registry dispatches exactly * as before. */ type ProxyCallGuard = (call: { alias: string; toolName: string; args: unknown; context?: ProxyCallContext; }) => Promise<{ allow: true; headers?: Record; } | { allow: false; reason: string; }>; /** * Post-dispatch hook consulted by every successful `callTool`. It sees the * upstream result and may return a replacement (e.g. one carrying an approval * id). It must not throw; if it does, the registry keeps the original result. * Unset by default, so a bare registry returns exactly what the upstream sent. */ type ProxyResultHook = (call: { alias: string; toolName: string; result: unknown; context?: ProxyCallContext; }) => Promise | unknown; interface McpProxyRegistryOptions { /** `http`/`sse` only: how long a cached `tools/list` stays fresh. */ toolCacheTtlMs?: number; /** Clock seam for tests. */ now?: () => number; /** How long `listAliases` (mcp_imported_status) waits on a stale refresh * before answering from the cache, so a hung server cannot block status. */ statusRefreshTimeoutMs?: number; } declare class McpProxyRegistry { private callGuard; private resultHook; private readonly ttlMs; private readonly now; private readonly statusRefreshTimeoutMs; constructor(options?: McpProxyRegistryOptions); setCallGuard(guard: ProxyCallGuard | undefined): void; setResultHook(hook: ProxyResultHook | undefined): void; private clients; private lastMtimeMs; /** Sentinel so we know whether the file has *ever* been read. * Distinguishes "file missing on first call" (legit empty state) * from "we've read it before and it's gone" (treat as empty too, * but only after closing live clients). */ private hasReadOnce; /** * Reload the imports file when its mtime has advanced. Avoids * repeated parsing when nothing changed — most calls are no-ops. * Disconnects clients whose import was removed; connects the new * set lazily (the first call that touches them). */ ensureCurrent(): Promise; /** * For `live` entries, stat the source config file(s); an mtime change * closes the client and installs a fresh placeholder so the next call * re-resolves against the edited source. First sight only records the * signature. */ private invalidateLiveSources; /** * Lazy connect: the first call to `connectIfNeeded(alias)` * actually opens the transport + handshakes. Subsequent calls * reuse the live client, re-listing first when the cached list is * missing, expired (network TTL) or `refresh` is forced. */ private connectIfNeeded; /** Re-list one connection's tools, coalescing concurrent callers. A failed * refresh keeps the existing cache unless the connection itself died. */ private refreshTools; /** Refresh with a status-only deadline: a hung server must not block * `mcp_imported_status`, which used to be a pure in-memory read. The * refresh keeps running and updates the cache if it eventually lands. */ private boundedRefresh; /** A network cache older than the TTL is stale; stdio is not TTL'd (its * process death is already a visible disconnect). */ private toolsStale; /** * Drop one import's pooled client and cache so the next read reconnects and * re-lists. `mcp_import` of an existing id calls this: re-saving an * unchanged snapshot leaves `ensureCurrent`'s cache untouched, which is how * a re-import could still report the old tool count. */ invalidate(importIdOrAlias: string): Promise; /** Find a client handle by alias *or* import id (defensive — agents * sometimes pass the id from `mcp_imported_list`). */ private findByAlias; listAliases(): Promise; listTools(alias: string): Promise<{ ok: true; tools: ProxyToolDescriptor[]; } | { ok: false; error: string; }>; callTool(alias: string, toolName: string, args: unknown, context?: ProxyCallContext): Promise; /** * Relay one `resources/read` to an import. No allowlist here: the caller * (the /mcp gateway's exposed resources) decides which URIs may reach it. */ readResource(alias: string, uri: string): Promise<{ ok: true; result: ReadResourceResult; } | { ok: false; error: string; }>; closeAll(): Promise; } /** * outbound-adapters — provider-agnostic send for outbound messages. * Symmetric to inbound-adapters.ts on the read side. * * Supports the dialects documented in packages/runtime/docs/TRANSMITTER.md. */ type OutboundProvider = "agentpush" | "telegram" | "whatsapp" | "slack" | "generic" | "native"; /** * TransmitterBindingStore — persists which agentproto session a given * agentpush (alias, source, contactRef) triple should route inbound * messages into. * * State is in-memory; bindings persist to disk (debounced async write), * mirroring the cursor-store pattern in inbound-watcher.ts * (loadCursors/schedulePersist/flushSync). */ interface TransmitterBinding { /** Imported agentpush MCP alias (or bot alias for native providers). */ alias: string; /** Channel/phone the poll is scoped to. */ source: string; /** Sender id (agentpush contact_ref). */ contactRef: string; /** agentproto session to route inbound INTO. */ sessionId: string; mode: "route" | "route-or-spawn"; /** Outbound provider this binding was created through. Default "agentpush". */ provider?: OutboundProvider; /** ms epoch of last activity. */ lastSeenTs: number; } interface TransmitterBindingStore { get(alias: string, source: string, contactRef: string): TransmitterBinding | undefined; upsert(b: Omit & { lastSeenTs?: number; }): TransmitterBinding; remove(alias: string, source: string, contactRef: string): boolean; list(): TransmitterBinding[]; } /** * inbound-router — shared routing decision for inbound agentpush messages, * used by both the poll loop (`inbound-watcher.ts`) and the push ingress * (`POST /inbound` in `http-server.ts`). * * Given a mode and an optional session binding, decides whether to: * - spawn a brand-new agent (today's poll-loop behavior), * - route the message as a user turn into an already-bound live session, * - resurrect a dead bound session and then route into it, or * - skip (no binding, routing-only mode). */ type InboundRouteMode = "spawn" | "route" | "route-or-spawn"; interface InboundMessage { alias: string; source: string; contactRef: string; /** Rendered user-turn text. */ text: string; /** Human-readable name of the sender, when the ingress knows one. * Present => the routed turn is prefixed so the agent can tell senders * apart. Absent => the text is enqueued exactly as before. */ displayName?: string; /** The surface the message came in on (`telegram`, `whatsapp`, `email`). * Distinct from `source`, which is a routing key, not something to show * an agent. */ surface?: string; /** Raw agentpush events, forwarded to the spawn fallback template. */ messages?: unknown[]; } /** Deliver `text` as a new user turn on a live session. Same shape as * `SessionsRegistry.enqueuePrompt` (sessions.ts) — the daemon wires that * method in directly. */ type InboundEnqueuePrompt = (sessionId: string, text: string, opts?: { interrupt?: boolean; queue?: boolean; }) => Promise | void; /** Whether `sessionId` is currently live enough to route into without a * restart first. */ type InboundIsSessionAlive = (sessionId: string) => boolean; /** Resurrect a dead session in place. Returns the (possibly new) live * session id. */ type InboundRestartSession = (sessionId: string) => Promise; /** Spawn-fallback for an unbound contact — today's poll-loop behavior. */ type InboundSpawnForContact = (msg: InboundMessage) => Promise; /** Diagnostic sink for routing decisions (e.g. a missing spawn fallback). */ type InboundRouterLog = (msg: string) => void; interface InboundRouterDeps { bindings: TransmitterBindingStore; enqueuePrompt: InboundEnqueuePrompt; isSessionAlive: InboundIsSessionAlive; restartSession: InboundRestartSession; spawnForContact?: InboundSpawnForContact; log?: InboundRouterLog; } /** * inbound-adapters — provider-agnostic normalization + signature verification * for inbound push ingress. Pure functions, no I/O. * * Supports the dialects documented in packages/runtime/docs/TRANSMITTER.md. */ type InboundProvider = "agentpush" | "telegram" | "whatsapp" | "slack" | "generic" | "native" /** GitHub repo webhooks feeding the `webhook` sentinel provider (AIP-60). * Not a user-registrable endpoint dialect: `handleProviderInbound` routes * `/inbound/sentinel-` straight into the sentinel runtime, and the * provider verifies with this dialect's `X-Hub-Signature-256` check. */ | "sentinel"; declare const INBOUND_PROVIDERS: readonly InboundProvider[]; type NormalizeInboundResult = { ok: true; msg: InboundMessage; providerMessageId?: string; } | { ok: true; challenge: string; } | { ok: false; error: string; message?: string; }; declare function normalizeInbound(provider: InboundProvider, body: unknown, ctx: { alias: string; sourceOverride?: string; }): NormalizeInboundResult; declare function verifyInboundSignature(provider: InboundProvider, input: { rawBody: string; headers: Record; secret: string; nowMs: number; }): { ok: true; } | { ok: false; reason: string; }; /** * InboundEndpointStore — persists per-slug inbound provider endpoints. * * State is in-memory; endpoints persist to disk (debounced async write + * sync flush), mirroring the cursor-store pattern in inbound-watcher.ts and * the transmitter-binding store in transmitter-bindings.ts. * * Deduplication (`markSeen`) is intentionally in-memory only: a bounded FIFO * per slug (cap 500 ids) with a global cap (~5000). A daemon restart re-accepting * one redelivery is acceptable; an unbounded map is not. */ interface InboundEndpoint { /** Path segment: POST /inbound/. */ slug: string; provider: InboundProvider; /** Binding alias — MUST match what transmit_message wrote. */ alias: string; /** Force binding source; default = provider channel. */ source?: string; /** When set, signature auth is REQUIRED. */ secret?: string; mode: InboundRouteMode; enabled: boolean; createdTs: number; lastSeenTs?: number; } interface InboundEndpointUpsert { slug: string; provider: InboundProvider; alias: string; source?: string; secret?: string; mode?: InboundRouteMode; enabled?: boolean; createdTs?: number; lastSeenTs?: number; } interface InboundEndpointStore { get(slug: string): InboundEndpoint | undefined; upsert(e: InboundEndpointUpsert): InboundEndpoint; remove(slug: string): boolean; list(): InboundEndpoint[]; /** true = first time we've seen this provider message id on this slug. */ markSeen(slug: string, providerMessageId: string): boolean; /** Synchronous flush for shutdown paths. */ flushSync(): void; } interface InboundEndpointStoreOptions { /** Override persist path. Default ~/.agentproto/inbound-endpoints.json. */ filePath?: string; /** Injectable clock for tests. */ nowMs?: () => number; /** Debounce interval for disk persistence. */ debounceMs?: number; /** Disable disk persistence (unit tests). Default false. */ persist?: boolean; } declare function createInboundEndpointStore(opts?: InboundEndpointStoreOptions): InboundEndpointStore; /** * The daemon's browser tools. Every one forwards to Bureau, the local * browser service imported as an MCP (`defaults.browser.proxyImport`, * `"bureau"` by default); the daemon no longer drives a browser of its own. * * fetch_page plain HTTP read (no browser) -> { title, text, url, blocked } * list_browsers -> Bureau browser_list_instances * browser_navigate -> Bureau browser_navigate * browser_screenshot -> Bureau browser_screenshot * browser_get_dom -> Bureau browser_get_dom * browser_click -> Bureau browser_click * browser_fill -> Bureau browser_fill * browser_evaluate -> Bureau browser_evaluate * browser_press_key -> Bureau browser_press_key * browser_list_tabs -> Bureau browser_list_owned_tabs * browser_screencast_* -> Bureau browser_record_start/frame/stop * browser_extract_text Bureau browser_get_dom, then the daemon's extractPageText * browser_scroll Bureau browser_evaluate with a fixed scroll script * * `defaults.browser.builtin: "off"` registers `fetch_page` alone. * * Retired from the daemon: `browser_select`, `browser_wait_for`, * `browser_upload_file`, `browser_new_tab`, `start_browser`, `stop_browser`, * `browser_status`, `browser_adapter_list`. Bureau itself DOES have * `browser_new_tab` and `browser_upload_file` (call them on the `bureau` MCP * server, or through `mcp_imported_call`); the daemon just does not relay them. * Bureau gives every caller session its own tab on first use, so * `browser_navigate` replaces `start_browser` + `browser_new_tab` here. * * The calling session id rides on every forwarded call, so Bureau's tab * ownership applies per agent session. * * P4b: the chrome-live implementation (browser-screencast.ts, * browser-adapters.ts, @agentproto/adapter-browser, the `agentproto browser` * CLI, the bureau-sessions panel) is no longer reachable from any MCP tool. * The structural types and the live-instance map below survive only for the * HTTP chrome-live routes in http-server.ts and are deleted with them. * * Auth: same as every other daemon tool, gated by the gateway's auth source. */ /** * Minimal shape of a BrowserAdapterInstance — structurally compatible with * @agentproto/adapter-browser's BrowserAdapterInstance. Kept local so the * runtime package stays free of a hard dependency on the adapter package. */ interface BrowserInstanceLike { id: string; port: number; baseUrl: string; pid?: number; wasAlreadyRunning: boolean; navigate?(url: string, tabId?: string): Promise<{ targetId: string; url: string; }>; getDom?(tabId?: string): Promise<{ targetId: string; url: string; html: string; }>; click?(options: { selector: string; button?: "left" | "middle" | "right"; clickCount?: number; }, tabId?: string): Promise; fill?(options: { selector: string; value: string; clear?: boolean; }, tabId?: string): Promise; evaluate?(options: { expression: string; awaitPromise?: boolean; returnByValue?: boolean; maxResultBytes?: number; }, tabId?: string): Promise<{ value: T | undefined; truncated: boolean; }>; scroll?(options: { selector?: string; x?: number; y?: number; }, tabId?: string): Promise<{ targetId: string; }>; /** Press one key via trusted CDP input, optionally focusing a selector first (chrome-live). */ pressKey?(options: { key: string; selector?: string; count?: number; modifiers?: readonly ("Alt" | "Control" | "Meta" | "Shift")[]; }, tabId?: string): Promise<{ targetId: string; key: string; }>; /** Select a `` on an owned tab (CDP DOM.setFileInputFiles; paths absolute). */ uploadFileOntoFileInput?(options: { selector: string; paths: readonly string[]; }, tabId?: string): Promise<{ targetId: string; files: readonly string[]; }>; /** Open a FRESH tab (never reusing an existing one) and navigate it to `url`. */ openNewTab?(url?: string): Promise<{ targetId: string; url: string; }>; /** Tabs owned by this provider instance on its endpoint. */ listOwnedTabs?(): Promise<{ targetId: string; url: string; windowId?: number; }[]>; /** False when a non-blocking cold start returned before the service * finished converging (background health-wait still running). */ healthy: boolean; health?(): Promise<{ ok: boolean; reason?: string; }>; screenshot?(tabId?: string): Promise<{ data: string; format: "png" | "jpeg"; width?: number; height?: number; }>; stop(): Promise; } /** * Minimal shape of a BrowserAdapterHandle — structurally compatible with * @agentproto/adapter-browser's BrowserAdapterHandle. */ interface BrowserAdapterLike { id: string; name: string; description: string; defaultPort: number; healthPath: string; /** Where this adapter runs — "local" (default) or "cloud". */ location?: "local" | "cloud"; ensure(opts: { port?: number; /** forwarded to dependent adapters (e.g. bureau→camofox) */ camofoxPort?: number; launchCmd?: string; env?: Record; timeoutMs?: number; /** Opt-in non-blocking cold start: wait only this long for a freshly * spawned service before returning `healthy:false` and converging * in the background. */ initialWaitMs?: number; log?: (s: string) => void; /** Override execution location ("local" or "cloud"). */ location?: "local" | "cloud"; /** Base URL of the remote service when location="cloud". */ baseUrl?: string; /** Override the binary path for a local spawn. */ binPath?: string; /** chrome-live only: "dedicated" (default) or "personal" (attachIntent). Every other adapter ignores this. */ profile?: "dedicated" | "personal"; /** chrome-live only: the real Chrome profile directory a configured cookie source should trace injected cookies back to. Every other adapter ignores this. */ chromeProfile?: string; /** chrome-live only: narrows which domains' cookies a configured cookie source injects. Every other adapter ignores this. */ domains?: readonly string[]; }): Promise; } type BrowserAdapterResolver = (id: string) => BrowserAdapterLike | undefined; type BrowserAdapterLister = () => { id: string; name: string; description: string; defaultPort: number; /** Where this adapter runs — "local" (default) or "cloud". */ location?: "local" | "cloud"; /** Install methods — informational metadata from the adapter manifest. */ install?: unknown[]; /** Config prompts — informational metadata from the adapter manifest. */ config?: unknown[]; }[]; /** * Family-specific descriptor of one browser adapter (the kit-path lister in * browser-adapters.ts). P4b: dead with the adapter lister. */ interface BrowserAdapterInfo { id: string; name: string; description: string; defaultPort: number; } /** * The single place every stable `SessionDescriptor.endedReason` / * `SessionOutcome.termination.reason` value is declared, so a UI can render * a label for each one without chasing the call site that set it. * * Two families: * - operator-issued — set ONLY by an explicit `POST /sessions/:id/kill` * or the `agent_kill` MCP tool, distinguishing an operator's deliberate * stop from every automatic teardown below; * - internal/automatic — set by the daemon itself, without an operator * in the loop, for a reason the operator couldn't have expressed. * * Backward compatible by construction: this is a value list, not a closed * validator. A descriptor persisted by an older daemon (or a newer one an * older UI doesn't know about yet) carries a `reason` string outside this * list — {@link isKnownSessionEndReason} says so, and callers should fall * back to a generic label rather than throw. */ declare const SESSION_END_REASONS: readonly ["daemon-restart", "idle-reaped", "guard-reaped", "crashed", "operator-completed", "operator-stopped", "cost-cap-exceeded", "context-hard-stop", "policy-cleanup", "parent-exited", "provider-limit", "forgotten", "steward-completed", "steward-abandoned", "restarted", "sandbox_gone", "sandbox-expired"]; type SessionEndReason = (typeof SESSION_END_REASONS)[number]; /** True when `reason` is one of {@link SESSION_END_REASONS}. A label * lookup, not a wire-format gate — an unrecognized string is still a * valid `endedReason` from a daemon version this build doesn't know * about; callers should render it with a generic fallback, never reject * it. */ declare function isKnownSessionEndReason(reason: string | undefined): reason is SessionEndReason; /** * Classify a driver-reported error message as a provider/subscription * usage cap rather than an ordinary tool/turn failure. Used wherever the * daemon would otherwise tag a dead session with the generic `"crashed"` / * `"error"` reason, so an operator sees "wait for your quota to reset" * instead of chasing a phantom bug. */ declare function isProviderLimitError(message: string | undefined): boolean; /** * Cursor-based ring buffer for session events. Bridges the in-process * SessionEventBus (push) to the session_events_poll MCP tool (pull). * * Capacity default: 1 000 events. Oldest entry dropped on overflow — * callers that lag beyond the cap see a gap in their cursor but never * a block. `since()` returns `nextCursor = totalEmitted` so a fresh * call with that value always starts just past the current tail. */ interface EventRingSnapshot { events: SessionEvent[]; nextCursor: number; } interface EventRingQueryOpts { sessionIds?: string[]; types?: SessionEventType[]; /** Default 50. */ limit?: number; } interface EventRing { /** * Return events whose ring-index >= `cursor`. Pass 0 to get all * retained events; pass the previously returned `nextCursor` for an * incremental read. The returned `nextCursor` is always equal to * `totalEmitted` — use it as the next `cursor` argument. * * Negative or below-base cursors are clamped to the oldest retained * event (no error, just a potential replay of a partial window). */ since(cursor: number, opts?: EventRingQueryOpts): EventRingSnapshot; /** Wire the ring to a SessionEventBus. Returns an unsubscribe fn. */ wire(bus: SessionEventBus): () => void; } /** * Orchestrator sub-gateway (ADR §4.2 / WP2) — the security primitive * that lets a spawned agent become a *scoped* orchestrator without * handing it the daemon's full toolset. * * The plain `/mcp` endpoint registers EVERY tool (command_execute, * fs_*, remote_*, mcp_import, terminals, driver CRUD) and bypasses auth * on loopback — pointing a child at it would be a privilege handout. * This module builds a second, scoped MCP server that registers ONLY a * curated orchestration allowlist, gated by an unguessable per-child * scope-token. The HTTP layer mounts it at `/mcp/orchestrator` * (`http-server.ts`); WP3 will auto-mint a token and inject the URL at * spawn time. WP2 only builds the primitive. * * Three pieces: * - DEFAULT_ORCHESTRATOR_TOOLS — the curated allowlist. * - createScopeTokenRegistry() — mint / verify / revoke scope-tokens. * - createOrchestratorMcpServerFactory() — build a scoped server for * a verified scope. */ /** * The curated set of tools a scoped child orchestrator may call. * * INCLUDED — the orchestration primitives: * agent_start, agent_prompt, agent_output, agent_kill, * session_monitor, session_events_poll (spawn + drive + fan-in) * session_list, session_tree (observe). NB: list is NOT yet scoped * to the child's own subtree — that subtree filter is WP4 * (parentSessionId/depth). For WP2 it is exposed daemon-wide; * documented debt. * * EXCLUDED — the danger surface (each a separate trust boundary): * command_execute, terminal/PTY tools (raw shell), file_* / * directory_* tools, remote_* (publish the daemon to the internet), * mcp_import / mcp_discovered_* / mcp_imported_* (widen the daemon's * own MCP surface), and driver CRUD (create_/delete_/update_driver — * these never register here because the scoped server is built with * no doctype specs). */ declare const DEFAULT_ORCHESTRATOR_TOOLS: readonly string[]; interface OrchestratorScope { /** The opaque scope-token handed to (and presented by) the child. */ token: string; /** The effective tool allowlist for this scope (⊆ the default and, * for a recursively-spawned child, ⊆ its parent's allowlist). */ tools: ReadonlySet; /** * Session id of the orchestrator that OWNS this token — i.e. the * child session that presents it back on `/mcp/orchestrator`. The * token is minted *before* the child session exists (the injector * needs the URL to compose the spawn), so this is bound late, after * `spawnAgent` returns the id, via `bindOwner`. Until bound, spawns * through this scope are attributed to no parent and its subtree is * empty (safe degradation). (ADR §4.5 / WP4) */ ownerSessionId?: string; /** Recursion depth of the owning orchestrator session. A spawn made * *through* this scope produces a child at `depth + 1`. Root scopes * (minted for a direct `/mcp` spawn) are depth 0. */ depth: number; /** Max recursion depth reachable through this scope. A spawn whose * child depth (`depth + 1`) would exceed this is rejected. Clamped * to `HARD_MAX_DEPTH`. */ maxDepth: number; /** Max concurrently-alive children the owning orchestrator may spawn * before further spawns are rejected. */ maxChildren: number; /** * Name of the resolved role that owns this scope (spawn-role- * profiles / privilege lattice). This is the "parent role" the * `canSpawn` gate checks against when this scope is used to spawn a * further child (`session-spawn.ts`). Defaults to `"supervisor"` at * mint time when the caller doesn't say — every role that can reach * `orchestrator: true` today resolves to supervisor (executor's * `toolPolicy.delegation: "deny"` already excludes it from ever * minting a scope), so this preserves #214 behaviour exactly until a * custom role is actually granted delegation. */ role: string; } /** * Narrow a caller-requested tool list to ⊆ a ceiling subset. * * The `ceiling` is the maximum a caller may end up with — the global * `DEFAULT_ORCHESTRATOR_TOOLS` for a root scope, or the *parent's* * effective tools for a recursively-spawned child (non-re-grant: a * child can never widen beyond what its parent holds — ADR §4.5 #5). * The `{ tools: [...] }` form can only REMOVE from the ceiling, never * add: any name outside it is dropped. Omitting `requested` yields the * full ceiling. Omitting `ceiling` defaults to the global default. */ declare function narrowOrchestratorTools(requested?: readonly string[], ceiling?: ReadonlySet): Set; interface MintScopeOptions { /** Caller-requested allowlist — narrowed ⊆ `ceiling` (or the default * when no ceiling is given). */ tools?: readonly string[]; /** Upper bound on the minted tools (the parent's effective tools for * a recursive child). Omit for a root scope (defaults to the global * default subset). */ ceiling?: ReadonlySet; /** Depth of the owning orchestrator (default 0). */ depth?: number; /** Max depth reachable through this scope (default DEFAULT_MAX_DEPTH, * clamped to HARD_MAX_DEPTH). */ maxDepth?: number; /** Per-orchestrator alive-child quota (default DEFAULT_MAX_CHILDREN). */ maxChildren?: number; /** Name of the resolved role that owns this scope. Default * `"supervisor"` — see `OrchestratorScope.role`. */ role?: string; } interface ScopeTokenRegistry { /** Mint a fresh scope-token. See `MintScopeOptions`. */ mint(opts?: MintScopeOptions): OrchestratorScope; /** Resolve a presented token to its scope, or null when unknown. */ verify(token: string | null | undefined): OrchestratorScope | null; /** Late-bind the owning child session id onto a minted scope (the * token is minted before the child exists). No-op when the token is * unknown. Mutates the live scope object so `verify` reflects it. */ bindOwner(token: string, sessionId: string): void; /** Drop a token (e.g. when the child session ends). The dropped scope * stops verifying at once; an owned scope's parameters are kept as a * tombstone (persisted with the live scopes, so it survives a daemon * restart) so `reinstate` can bring it back if the same lineage is * revived. */ revoke(token: string): void; /** True when `token` is a revoked scope still held as a tombstone. */ isRevoked(token: string): boolean; /** True when the registry was loaded from an existing persist file: a * daemon that persists scopes already owned this host's tokens, so a * token it does not know was revoked or pruned, never a legacy one. */ hasPersistedState(): boolean; /** Every LIVE scope whose owner is `sessionId`. */ ownedBy(sessionId: string): OrchestratorScope[]; /** Move every live scope owned by `from` to `to` (a restart handing the * scope to its successor row). Returns how many moved. */ transferOwner(from: string, to: string): number; /** Bring back every revoked scope last owned by `sessionId`, same token * and same parameters (role, depth, tools, limits), still owned by * `sessionId`. Returns the reinstated scopes; empty when there is * nothing to bring back. */ reinstate(sessionId: string): OrchestratorScope[]; /** Register a PRE-EXISTING token (legacy migration — see * `adoptLegacyOrchestratorScopes`). No-op when the token is already * known, live or revoked, so a registry entry always wins over an * adopted one. */ adopt(token: string, scope: Omit): void; /** Drop every scope, live or revoked tombstone, for which `shouldDrop` * returns true (receives the full scope so the caller can branch on * owner vs unowned). Returns how many were dropped (0 → no persist * write). */ prune(shouldDrop: (scope: OrchestratorScope) => boolean): number; /** Synchronous flush of the pending debounced persist write (shutdown * path). No-op when persistence is off. */ flushSync(): void; } interface ScopeTokenRegistryOptions { /** Persist the registry to this JSON file (mode 0600, atomic * tmp+rename, debounced/coalesced writes). Loaded synchronously at * creation, so tokens minted before a daemon restart verify again * afterwards. Omitted → in-memory only (the test default). */ persistPath?: string; /** Debounce for the coalesced disk write. Default 250ms. */ debounceMs?: number; } /** * Default persist location — `/orchestrator-scopes.json`, * the same home-dir resolution every other store in this runtime uses * (`sentinel-store.ts`, `session-follow-store.ts`, …). */ declare function orchestratorScopesFile(): string; declare function createScopeTokenRegistry(opts?: ScopeTokenRegistryOptions): ScopeTokenRegistry; /** * Every `/mcp/orchestrator?scope=` token referenced by the given * descriptors' persisted `mcpServers` — the boot prune's "still needed?" * set for UNOWNED scopes: a token minted in a previous daemon life whose * spawn died before `bindOwner` is garbage, EXCEPT when an alive / * resumable descriptor still carries its URL (crash between the adapter * start that mounted the config and the late owner bind). */ declare function collectReferencedOrchestratorScopeTokens(descriptors: readonly SessionDescriptor[]): Set; /** * Boot-time prune of a freshly-loaded persisted registry (see the call * site in `index.ts`). Drops: * - owned scopes, live or revoked tombstones, whose owning session is * gone from `descriptors` entirely, or ended (`exited`/`killed`/ * `error`) in a state that can never be revived (`!isResumable`); * - UNOWNED scopes (minted in a previous daemon life whose spawn died * before `bindOwner`, so nothing ever revokes them) that no alive / * resumable descriptor still references — a crash between the adapter * start that mounted the URL and the late owner bind keeps its token, * everything else is garbage. * Sessions merely marked killed by the boot history load are KEPT: they * are exactly the resumable rows whose persisted `mcpServers` still carry * the `/mcp/orchestrator?scope=` URL this persistence exists to keep * working (a NORMAL exit already revoked its token through the * `session:exited` lifecycle handler). Exported so the tests exercise the * production predicate, not a copy. */ declare function pruneOrchestratorScopesOnBoot(registry: ScopeTokenRegistry, descriptors: readonly SessionDescriptor[]): number; /** * Legacy migration for tokens minted by a daemon that predates scope-token * persistence: those tokens live on only inside the persisted `mcpServers` * of session descriptors (`…/mcp/orchestrator?scope=`) and are * absent from `orchestrator-scopes.json`. Re-adopt each such token with the * referencing session as owner so its already-baked URL keeps authorizing * after a restart, with no session restart required. * * Runs only while no persist file exists yet (`hasPersistedState`): once a * persisting daemon has owned this host's tokens, a token it does not know * was revoked (its session exited) or pruned, and re-adopting it would * bring a dead scope back with default parameters, wider than the one it * was minted with. A token held as a revoked tombstone is never adopted * either; a revival gets it back through `reinstate` with its original * parameters. Retire this function (and its call site) once every * pre-persistence daemon life has been flushed out. * * Fail-safe tools: the original mint's narrowing is unknowable from the URL * alone, so an adopted scope gets exactly the DEFAULT orchestrator subset — * never wider. Depth is the session's ancestor count (via `parentSessionId`); * limits are the defaults. The role is the supervisor one, so a descriptor * whose recorded spawn role (`meta.role`) is anything else is skipped: its * scope may have been a report-only one, and the defaults would widen it. * A token the registry already knows is never overwritten (a live entry * wins over an adopted one). * * Kept separate from the registry factory so it can be deleted once every * pre-persistence daemon has been retired. * * Returns the number of tokens adopted. */ declare function adoptLegacyOrchestratorScopes(registry: ScopeTokenRegistry, descriptors: readonly SessionDescriptor[]): number; interface OrchestratorGatewayDeps { workspace: string; name?: string; version?: string; registry: SessionsRegistry; sessionEvents: SessionEventBus; eventRing: EventRing; supervisor?: CompletionPolicySupervisor; /** Task ledger — when wired, spawned children get live `task_*` tools * (they're in the default allowlist either way; without a ledger they * answer a structured error). Same instance as the root gateway's. */ taskLedger?: TaskLedger; resolveAgentAdapter?: AgentAdapterResolver; listAgentAdapters?: AgentAdapterLister; listHarnessCapabilities?: AdapterCapabilitiesLister; /** Orchestrator injector (WP3/WP4). When wired, a child orchestrator * driving the scoped server can itself spawn sub-orchestrators * (`orchestrator: true` on its `agent_start`) — the new * token inherits depth+1 and is bounded by the caller's tools * (non-re-grant). Omitted → recursion injection is unavailable on * the scoped surface (a child can still spawn plain sub-agents). */ orchestratorInjector?: OrchestratorInjector; /** Optional webhook notifier — same singleton as the root /mcp server. * When provided, per-session notifyUrl values from agent_start * are registered on spawn and unregistered on exit, so child * orchestrators spawning through this scoped gateway also fire webhooks. */ webhookNotifier?: WebhookNotifier; /** Forwarded to `registerSessionTools` — the daemon's own plain `/mcp` * gateway URL, defaulted onto `hermes` `agent_start` spawns issued * through this scoped sub-gateway that pass no `mcpServers`. See * `RegisterAgentToolsOptions.daemonMcpUrl`. */ daemonMcpUrl?: string; /** Resolves an `agent_start.sandbox` slug (or an inline spec's own * `.provider`) to a concrete sandbox provider handle — forwarded to * `registerSessionTools` so a child spawned THROUGH this scoped * sub-gateway can declare `sandbox` too. Same resolver instance as the * root `/mcp` gateway. Omitted → a scoped-gateway child's `sandbox` * spawn is rejected with `sandbox_provider_not_found`, exactly as the * root gateway would be without it. */ resolveSandboxProvider?: SandboxProviderResolver; /** Workspace command allowlist loader for the stdio mount gate, forwarded * to `registerSessionTools` so a spawn issued THROUGH this scoped * sub-gateway (the surface a nested supervisor uses) is judged against * the same list `command_execute` gates against. Omitted → every stdio * mount of a scoped caller reads as outside the allowlist. */ loadCommandAllowlist?: () => Promise; /** EXPLICIT override for config.json `defaults.agentPromptInterrupt` — * wins over the fresh per-call resolve (`resolveMessagingDefaults`, * see the factory body below). Tests inject this to pin a value without * touching the filesystem; production leaves it unset so every request * reads the live config, hot-applying a `config_set` change with no * restart. Forwarded to `registerSessionTools`. */ defaultAgentPromptInterrupt?: boolean; /** EXPLICIT override for config.json `defaults.messaging.allowSiblings` - * see `defaultAgentPromptInterrupt` above for the override/resolve * precedence. Forwarded to `registerAgentTools`. */ messagingAllowSiblings?: boolean; /** EXPLICIT override for config.json * `defaults.messaging.allowSameWorkspace` - see * `defaultAgentPromptInterrupt` above for the override/resolve * precedence. Forwarded to `registerAgentTools`. */ messagingAllowSameWorkspace?: boolean; /** EXPLICIT override for config.json * `defaults.messaging.peerGroups` - see `defaultAgentPromptInterrupt` * above for the override/resolve precedence. Forwarded to * `registerAgentTools`. */ messagingPeerGroups?: string[][]; /** EXPLICIT override for config.json `defaults.messaging.grants` - see * `defaultAgentPromptInterrupt` above for the override/resolve * precedence. Forwarded to `registerAgentTools`. */ messagingGrants?: Grant[]; /** EXPLICIT override for config.json `defaults.messaging.peerBinding`. * Forwarded to `registerAgentTools`. */ messagingPeerBinding?: "slug" | "verified"; /** EXPLICIT override for config.json `defaults.messaging.agentInterrupt` — * see `defaultAgentPromptInterrupt` above for the override/resolve * precedence. Forwarded to `registerAgentTools`. */ messagingAgentInterrupt?: "allow" | "deny"; /** EXPLICIT override for config.json `defaults.messaging.anonymousSend`. * Forwarded to `registerAgentTools`. */ messagingAnonymousSend?: "block" | "label"; messagingLabelAddressing?: "open" | "tree" | "operator"; } type OrchestratorMcpServerFactory = (scope: OrchestratorScope) => Promise; /** * Build a factory that produces a scoped MCP server for a verified * scope. The server is created with NO doctype specs and NO workspace * (so no CRUD verbs, no `self_inspect`, no driver tools leak in), then * the orchestration passes run against a `withToolSubset` wrapper so * only `scope.tools` survive. Critically, `mcpProxy` and the PTY * factory are never wired here — import + terminal tools stay unwired * AND are excluded from the subset (defense in depth). */ declare function createOrchestratorMcpServerFactory(deps: OrchestratorGatewayDeps): OrchestratorMcpServerFactory; /** * The auto-injection assembly (ADR §4.4 / WP3) — turns the "make this * child an orchestrator" intent into the concrete `mcpServers` entry * the ACP `session/new` call mounts, plus the token lifecycle. * * One call (`inject`) does three things: * 1. mint a scope-token (narrowed ⊆ default when `tools` is given); * 2. build the `mcpServers` entry pointing the child at the daemon's * own scoped sub-gateway (`/mcp/orchestrator?scope=`); * 3. hand back `bindLifecycle(sessionId)` so the caller can revoke * the token the moment that child session exits — no token leaks * past the life of the session it was minted for. * * Assembled in `createGateway` (not the CLI resolver) because it needs * the gateway's scope-token registry, the session-event bus, and the * HTTP listener's port — all of which live there. */ interface OrchestratorInjection { /** The `mcpServers` entry to merge into the child's `session/new`. */ entry: AcpMcpServer; /** The minted scope — `token` gates the endpoint, `tools` is the * effective (narrowed) allowlist. */ scope: OrchestratorScope; /** * Make `sessionId` the scope's owner, so the scope-token is revoked (and * the owner's live children reaped) once the owner exits. The exit is * matched on the scope's CURRENT owner, so a restart that hands the * scope to its successor row (`ScopeTokenRegistry.transferOwner`) moves * the binding with it. Returns a no-op, kept for the call sites' type. */ bindLifecycle(sessionId: string): () => void; } /** * The slice of the sessions registry the orphan-reaper needs: enumerate * every session (so the subtree walk sees archived intermediate ancestors * too) and terminate one by id via the SAME graceful SIGTERM path * `agent_kill` uses (`registry.kill`). Kept structural so the reaper is a * pure, unit-testable function decoupled from the full registry surface. */ interface OrphanReaperRegistry { list(opts?: { includeArchived?: boolean; }): readonly SessionDescriptor[]; kill(id: string, signal?: NodeJS.Signals, reason?: SessionEndReason): boolean; } /** * Reap a dying parent's live descendants (WP-B — orphan reaping). A * supervisor/orchestrator that exits or is killed must not leave the * sessions it spawned running unattended (zombies still holding a shared * checkout, still burning resources, with no parent watching them). * * Walks the subtree rooted at `parentSessionId` and terminates every * still-alive descendant via `registry.kill` — SIGTERM + status→"killed", * the exact primitive `agent_kill` uses, so there's no second kill path * and reaping reuses the graceful-stop transition the rest of the daemon * already understands. The parent itself is skipped (it's the one already * exiting). We DELIBERATELY reap rather than mint a new `orphaned` status: * the lifecycle has no such state today, and `killed` already carries "was * terminated, not a natural exit" — inventing a status would be a new * lifecycle concept where an existing one fits. * * Idempotent and safe: * - a descendant that already raced to a terminal status is skipped * (never re-killed), so `kill()`'s own no-op-on-terminal guard is * belt-and-suspenders here; * - only sessions transitively under `parentSessionId` are touched — * siblings and unrelated roots are never reaped, because the subtree * walk starts strictly at the exiting parent; * - `kill()` synchronously emits the child's own `session:exited`, so a * reaped child that is ITSELF an orchestrator cascades — its bound * lifecycle handler revokes its token and reaps its own children — * but the up-front subtree snapshot + terminal-status skip make the * cascade and this walk converge without double-killing anything. * * Returns the ids actually reaped (for logging / assertions). */ declare function reapOrphanedDescendants(registry: OrphanReaperRegistry, parentSessionId: string): string[]; interface OrchestratorInjectorDeps { scopeTokens: ScopeTokenRegistry; sessionEvents: SessionEventBus; /** Port the daemon's HTTP listener (and thus `/mcp/orchestrator`) * binds. The child reaches it over loopback. */ port: number; /** Loopback host for the injected `ref`. Always loopback — the child * is co-located on the host. Default `127.0.0.1`. */ host?: string; /** `name` advertised on the injected `mcpServers` entry. The child * sees its orchestration tools namespaced under this. Default * `agentproto`. */ entryName?: string; /** * Reap the parent's live descendants when it exits (WP-B). Called from * the same `session:exited` handler that revokes the scope-token, right * after the revoke — so a killed/exited orchestrator never leaves its * children orphaned-and-running alongside a now-dead parent. Given the * exiting parent's session id; typically wired to * `reapOrphanedDescendants(registry, id)`. Optional: when unset, only the * scope-token is revoked (pre-WP-B behaviour, children left as-is). */ reapChildren?: (parentSessionId: string) => void; } type OrchestratorInjector = (opts?: { tools?: readonly string[]; /** The calling orchestrator's scope, when this spawn arrives via the * scoped sub-gateway (recursive spawn). The minted child token then * inherits `depth = caller.depth + 1`, its tools are bounded by the * caller's tools (non-re-grant — ADR §4.5 #5), and its depth/child * limits never exceed the caller's. Omit for a root spawn (direct * `/mcp`) → depth 0, full default subset, default limits. */ caller?: OrchestratorScope; /** Override the max depth reachable through the minted scope (clamped * to the caller's, then to HARD_MAX_DEPTH). Root-only knob. */ maxDepth?: number; /** Override the per-orchestrator child quota for the minted scope * (clamped to the caller's). Root-only knob. */ maxChildren?: number; /** Name of the resolved role for the session THIS scope is being * minted for (i.e. the session becoming an orchestrator) — becomes * `OrchestratorScope.role`, the "parent role" a future spawn * through this scope is gated against. Default `"supervisor"`. */ role?: string; }) => OrchestratorInjection; /** * Build the orchestrator injector. Closed over the gateway's * scope-token registry + session-event bus + HTTP port. Returns a * function that the `agent_start` handler calls when its * `orchestrator` field is set. */ declare function createOrchestratorInjector(deps: OrchestratorInjectorDeps): OrchestratorInjector; /** * What a session's harness ACTUALLY loaded from the daemon's own `/mcp` * mount, as opposed to what `mcpServers` merely declares. * * `session_capabilities` used to report only the declared mount, which is * exactly the blind spot that hid the "server/discover advertises an era we * don't serve" bug: the descriptor said `agentproto` was mounted while the * harness saw zero tools. The `/mcp` endpoint is stateless (a fresh * server+transport per POST), so the only place the session's handshake is * visible is the transport itself: this module wraps it (incoming * `initialize` / `server/discover` / `tools/list`, and the matching * responses) and keeps the latest outcome of each, keyed by the trusted * `?callerSessionId=` the self-mount carries. * * State is in memory only: a daemon restart resets it, and a harness * resumed after the restart reconnects (and re-lists) anyway. */ /** Methods whose outcome tells us whether the harness loaded the mount. */ type ObservedMethod = "initialize" | "server/discover" | "tools/list"; interface McpObservedCall { at: string; ok: boolean; /** `: ` of the JSON-RPC error, or a transport failure note. */ error?: string; /** `initialize`: the version the server answered. Other methods: the * `mcp-protocol-version` header the client sent. */ protocolVersion?: string; } interface McpObservedTool { name: string; description?: string; } interface McpToolsListObservation extends McpObservedCall { toolCount: number; /** `true` when the list is the lazy projection (it carries `tool_search`, * which only the deferred wrapper registers). */ deferred: boolean; tools: McpObservedTool[]; } interface McpSessionObservation { firstSeenAt: string; lastSeenAt: string; initialize?: McpObservedCall; discover?: McpObservedCall; toolsList?: McpToolsListObservation; /** Last request that the transport rejected before any JSON-RPC message * was read (e.g. a 400 on the protocol-version header). */ httpError?: { at: string; status: number; }; } interface McpObservationStore { /** Wrap an already-`connect()`ed transport. Never throws into the request. */ observe(transport: Transport, ctx: { sessionId: string; clientProtocolVersion?: string; }): void; /** Record an HTTP-level rejection that produced no JSON-RPC message. */ recordHttpError(sessionId: string, status: number): void; /** Record a response produced WITHOUT a transport the observer could wrap (the modern-era in-process bridge). */ recordResult(sessionId: string, method: ObservedMethod, message: { result?: unknown; error?: { code?: unknown; message?: unknown; }; }, clientProtocolVersion?: string): void; get(sessionId: string): McpSessionObservation | undefined; delete(sessionId: string): void; } /** * Activity ledger v1 — the side-effecting PROJECTOR. * * Sits on the session event bus and keeps the pure projection * (`activity-projection.ts`) fresh: on each incoming lifecycle event it * re-projects the owner(s) that event can have touched, diffs each record * against an in-memory last-projection cache (keyed by the deterministic * activity id), and emits `activity:changed` for records whose * state/waitingOn actually changed. Because EventRing distributes via * `onAny` (`event-ring.ts`), `session_events_poll`, SSE `/events`, and the * webhook notifier all carry the new event with no second cursor. * * **Projection, not a registry** (the repo has ruled twice against * registries that mirror derivable state — see `supervisor.ts`'s * session→policy note and `worktree/src/status.ts`): `list()` RECOMPUTES * from the owners on every call; the cache exists only so the diff knows * what it last announced, and deleting it costs nothing but a burst of * re-announcements. Deterministic ids make re-projection idempotent. * * Strictly best-effort: the bus handler and every per-owner projection are * wrapped so a throwing owner `list()` can never escape a bus callback. * The handler ignores `activity:changed` itself — the projector must never * re-enter off its own emissions. * * Owner inputs are narrow STRUCTURAL slices (the reconciler's * `ReconcilerRegistry` pattern): the real `SessionsRegistry`, supervisor, * and runners satisfy them, and tests fake them without casts. * * The one ASYNC enrichment — PR settlement — stays outside the projection: * the injected {@link PrStateResolver} port (CLI-wired, the `OpenPrResolver` * pattern) fills a memoized url→state map at `session:exited` and on a * bounded periodic sweep, and the pure pr mapper merely READS that map, so * `list()` never awaits and the runtime never touches a forge. */ /** A session as the projector reads it: the turn slice + the PR slice. * The full `SessionDescriptor` satisfies this structurally. */ interface ActivityProjectorSession extends ActivityTurnSession, ActivityPrSession { } /** The registry slice the projector needs — structurally satisfied by the * full `SessionsRegistry` (whose no-arg `list()` already excludes archived * sessions, which is exactly the v1 `pr` scoping), and by a trivial fake in * tests. */ interface ActivityProjectorRegistry { list(): readonly ActivityProjectorSession[]; } /** The supervisor slice — structurally satisfied by * `CompletionPolicySupervisor` (same `list()` that `policy_list` reads). */ interface ActivityPolicyLister { list(): readonly ActivityPolicySlice[]; } /** The workflow-runner slice — structurally satisfied by `WorkflowRunner`. */ interface ActivityWorkflowLister { list(): readonly ActivityWorkflowRunSlice[]; } /** The task-ledger slice — structurally satisfied by `TaskLedger` (whose * `snapshot()` returns every task, all boards; the scoped `list()` would * hide boards the join must see). Enriches `turn`/`policy` activities with * `taskId` at read time. */ interface ActivityTaskLister { snapshot(): readonly ActivityTaskSlice[]; } /** * Resolve a PR url's current forge state — `null` when it could not be * resolved (no `gh`, unreachable forge, non-GitHub url; never a throw the * projector has to guard beyond a catch). Injected by the CLI host because * forge access runs over `@agentproto/worktree`, a dependency the runtime * deliberately does not take (the {@link OpenPrResolver} pattern). Omitted → * `pr` activities stay pending on the forge forever (the v1 behaviour). */ type PrStateResolver = (prUrl: string) => Promise; /** A resolved PR state plus, for a merged PR, the forge's real merge time. * A resolver may return this instead of the bare state so the projector * can stamp the `pr-merged` activity with WHEN it merged, not when the * daemon first noticed. */ interface PrResolution { state: PrResolvedState; /** ISO 8601 merge time (merged PRs only). */ mergedAt?: string; } interface ActivityProjector { /** Recompute the full projection from the owners and filter it. Never * answered from the cache — this is a projection, not a registry. */ list(filter?: ActivityListFilter): ActivityRecord[]; /** * Block until the activity with `id` next announces a change * (`activity:changed` — its state/waitingOn actually moved), resolving * with the freshly-projected record. Resolves IMMEDIATELY when the id is * already terminal (terminal records are immutable — nothing further will * ever announce), and with `null` when `timeoutMs` (default 25s) elapses * with no change. An id that doesn't exist yet is a legitimate wait — the * record may appear (and announce) during the window; callers wanting a * fast 404 check `list({includeTerminal:true})` themselves (the * `GET /activities/:id/wait` route does). */ wait(id: string, opts?: { timeoutMs?: number; }): Promise; /** Detach the bus subscription + refresh timer and clear the caches. */ dispose(): void; } declare function createActivityProjector(opts: { registry: ActivityProjectorRegistry; sessionEvents: SessionEventBus; supervisor: ActivityPolicyLister; workflowRunner?: ActivityWorkflowLister; taskLedger?: ActivityTaskLister; /** Optional forge port for PR settlement — see {@link PrStateResolver}. */ resolvePrState?: PrStateResolver; }): ActivityProjector; /** * Generic model policy: the only model rule a session can carry. `allow` and * `block` hold model-list ids (see `model-list-store.ts`); nothing here knows * about price. A session without a policy may use any model its account allows. */ interface ModelPolicy { /** List ids. When present, a model outside every one of them is refused, * uncataloged ids included. */ allow?: string[]; /** List ids. A model in any of them is refused; always wins over `allow`. */ block?: string[]; /** Composition form: every entry must pass. Used when two policies are * combined (a session preset's and the request's) and the intersection of * their `allow` lists cannot be represented by one list id array. Never * accepted from caller input; see {@link composeModelPolicies}. */ all?: ModelPolicy[]; } type PolicyVerdict = { ok: true; } | { ok: false; code: "model_blocked" | "model_not_allowed" | "model_unresolved" | "unknown_list"; reason: string; }; /** Compose policies so BOTH apply: a model must pass every one. A single * policy passes through unchanged; otherwise the result is an `all` node * (an intersection of two allow lists has no single-list representation). * `undefined` when no policy contributes a rule. */ declare function composeModelPolicies(...policies: Array): ModelPolicy | undefined; /** * Check a workspace's registered `remote` out inside a sandbox. * * `agent_start({ workspaceSlug, sandbox })` for a workspace carrying a * `remote` clones that repo into the box (the host path means nothing there), * optionally cuts `wt/` from a base ref, and lands the session in the * checkout. This module is the pure half: it turns the request into an ordered * list of shell steps and runs them through any `exec` seam, so it works for * every provider that implements `BootedSandbox.exec` and is testable with a * fake. * * The git token never appears in a command, URL or argv. The box receives it * as the env var {@link GIT_TOKEN_ENV} (resolved from the keychain by * `sandbox-secret-resolver`), and a credential helper configured here reads it * from the environment when git asks. The same token is also exposed as * {@link GH_TOKEN_ENV} so the `gh` CLI baked into the workstation template can * open pull requests with it. */ /** Which snapshot {@link restoreCheckpointSteps} may put back: `"any"` — the * one on the remote, if it fits the checkout (restart on a dead box); * `"none"` — none (the last checkpoint was clean, so a stale snapshot left on * the remote must not resurface); `{ sha }` — only that exact snapshot commit * (migrate: the one the final checkpoint just pushed). */ type CheckpointRestoreSnapshot = "any" | "none" | { sha: string; }; /** * User-owned spawn presets. * * This is deliberately separate from `preset-tools.ts`: provider presets are * static gateway definitions shipped by packages, while a UserPreset is a * private saved combination of the orthogonal session-config axes. */ /** A reusable, user-scoped subset of the spawn/session config axes. */ interface UserPreset extends Partial { /** Stable machine-local id, e.g. `fast-deepseek`. */ id: string; /** Human-readable name shown by CLI and editor pickers. */ label: string; /** @deprecated Alias of `harness`, kept as a mirrored duplicate for old * readers; removed in the next major of @agentproto/runtime. */ adapter?: string; /** Harness to use (canonical). Omitted means the caller selects one. */ harness?: string; model?: string; route?: RouteSpec; access?: { profileRef?: string; }; posture?: Posture; effort?: EffortLevel; contextProfile?: ContextProfile; /** Working directory the favorite pins to. When set, a spawn from this * preset lands here regardless of the caller's active folder — the axis * that makes a favorite fully location-pinned (true zero-input). Omitted * means the caller's cwd ladder resolves it as before. */ cwd?: string; /** Skills to preload for a spawn from this preset — the same axis as * `SpawnAgentSessionInput.skills`. Omitted means the adapter/defaults * decide. */ skills?: string[]; /** Capability bundle ids (`bundle_list`) for a spawn from this preset — the * same axis as `SpawnAgentSessionInput.bundles`. Omitted means the * adapter/defaults decide. */ bundles?: string[]; /** `agent_start.browser` for spawns from this preset. Ranks below the * role's own default (see `resolveBrowserMode`). */ browser?: SpawnBrowserMode; /** `agent_start.turnRetry` for spawns from this preset (opt-in retry of a * turn that failed on a transient provider error). An explicit * `turnRetry` on the spawn wins. */ turnRetry?: TurnRetryInput; /** Discovery tags; unioned with the request's when this preset resolves. */ tags?: string[]; /** Other session presets applied first, left to right. A missing target or * a cycle is rejected at save time. */ extends?: string[]; /** Harness slug this preset is the default for. At most one preset per * harness; a second one is rejected at save time. */ defaultFor?: string; /** This implementation's form of the AIP-38 policy (the preset's policy). * Composes with the request's: both apply. */ modelPolicy?: ModelPolicy; /** Harness-native options not covered by an axis; merged key by key. */ options?: Record; /** Nested form of the same axes, accepted on input for AIP-46 callers. Flat * fields win when both name an axis. The store persists the flattened * form. */ config?: Partial & { options?: Record; }; /** ISO 8601 timestamp of the last spawn that resolved a `presetId` to this * preset (agent_start, `/sessions/agent`, `/sessions/chat` — stamped once * in `spawnAgentSession`, the shared core all three route through). Never * set by a caller directly; `saveUserPreset` preserves the existing value * across an edit unless the write explicitly overrides it. Absent for a * preset that has never been used to spawn. */ lastUsedAt?: string; } declare const userPresetSchema: z.ZodObject<{ id: z.ZodString; label: z.ZodString; adapter: z.ZodOptional; harness: z.ZodOptional; model: z.ZodOptional; route: z.ZodOptional; }, z.core.$strip>>; access: z.ZodOptional; }, z.core.$strip>>; posture: z.ZodOptional, z.ZodObject<{ harnessModeId: z.ZodString; }, z.core.$strip>]>>; effort: z.ZodOptional>; contextProfile: z.ZodOptional; cwd: z.ZodOptional; skills: z.ZodOptional>; bundles: z.ZodOptional>; browser: z.ZodOptional, z.ZodLiteral]>>; turnRetry: z.ZodOptional>; 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>, z.ZodNull]>>; tags: z.ZodOptional>; extends: z.ZodOptional>; defaultFor: z.ZodOptional; modelPolicy: z.ZodOptional>; block: z.ZodOptional>; }, z.core.$strict>>; options: z.ZodOptional>; config: z.ZodOptional; model: z.ZodOptional; route: z.ZodOptional; }, z.core.$strip>>; access: z.ZodOptional; }, z.core.$strip>>; posture: z.ZodOptional, z.ZodObject<{ harnessModeId: z.ZodString; }, z.core.$strip>]>>; effort: z.ZodOptional>; contextProfile: z.ZodOptional; cwd: z.ZodOptional; skills: z.ZodOptional>; bundles: z.ZodOptional>; browser: z.ZodOptional, z.ZodLiteral]>>; options: z.ZodOptional>; turnRetry: z.ZodOptional>; 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>, z.ZodNull]>>; }, z.core.$strip>>; lastUsedAt: z.ZodOptional; }, z.core.$strip>; type UserPresetsFile = { version: 1; presets: UserPreset[]; }; /** A save-time invariant failure: a typed, actionable error rather than a * generic parse message. */ declare class UserPresetValidationError extends Error { readonly code: "unknown_extends" | "extends_cycle" | "duplicate_default_for"; constructor(code: "unknown_extends" | "extends_cycle" | "duplicate_default_for", message: string); } /** Flatten the optional nested `config` under the flat fields. The flat field * wins when both name an axis, per the AIP-46 migration note. */ declare function normalizeUserPreset(input: UserPreset): UserPreset; declare function userPresetsPath(): string; /** Missing or malformed user config is treated as empty — a bad preset must * never prevent the daemon from starting. Writes always restore valid JSON. */ declare function loadUserPresets(): Promise; declare function listUserPresets(): Promise; declare function getUserPreset(id: string): Promise; /** Add or replace a preset by id. The parser makes this the single validation * boundary for CLI, MCP and editor callers. An edit that doesn't name its own * `lastUsedAt` keeps the existing preset's stamp rather than wiping it — a * rename/retune of a favorite must not erase its recency. */ declare function saveUserPreset(preset: UserPreset): Promise; declare function deleteUserPreset(id: string): Promise; /** Stamp `lastUsedAt` on the preset a spawn just resolved `presetId` to. * Best-effort: an unknown id is a no-op, and a write failure here must never * fail the spawn it's timestamping — callers should await it inside a * `.catch(() => {})`. */ declare function touchUserPreset(id: string): Promise; /** One de-duplicated recent spawn configuration, derived from session * history rather than persisted — the `user_preset_list({ includeRecent: * true })` / `GET /user-presets?includeRecent=1` companion view to actual * favorites, so a caller can "save as favorite" something they've spawned * before without retyping it. */ interface RecentSpawnConfig { /** Canonical harness slug. */ harness?: string; /** @deprecated Mirror of `harness`; removed in the next major of @agentproto/runtime. */ adapter?: string; model?: string; profileRef?: string; cwd?: string; /** Always true — the marker that distinguishes a derived row from a * persisted {@link UserPreset} when the two are rendered in one list. */ recent: true; } /** Derive up to `limit` distinct recent spawn configurations (adapter, * model, profileRef, cwd) from the registry's own newest-first session * list. Only `agent-cli` sessions carry a spawn config; a session that * named neither `harness` nor `adapterSlug` is skipped (nothing to offer * as a favorite). Distinctness is by the exact (adapter, model, profileRef, * cwd) tuple, keeping only the most recent occurrence of each. */ declare function deriveRecentSpawnConfigs(descriptors: readonly SessionDescriptor[], limit?: number): RecentSpawnConfig[]; /** * Account health: a persistent circuit breaker per REAL auth profile. * * The daemon used to have no memory of "this account is empty until such a * date": every spawn retried an account known to be spent, and `model-cooldowns.ts` * (per model, in memory, 10 to 60 min) says nothing about a wallet. This module * records, in `~/.agentproto/account-health.json`, which profiles are * `exhausted` and until when. Keys are real `profileRef`s, never `slot:` refs. * * States, derived at read time from the file and the clock: * - `ok` no entry; * - `exhausted` an entry whose `until` is still in the future: the account * is closed, nothing should be started on it; * - `probing` an entry whose `until` has passed: the account is eligible * again and the next real use is the trial. No manual * unblock is ever needed after a renewal. * * `until` comes, in decreasing order of trust, from a quota reader's * `resetsAt` (`untilBasis` `provider`, or `probe` for an undocumented * surface), from the provider's own message (`observed`: "resets in 1d 9h", * "resets 12pm (Europe/Paris)", "try again at ...", Retry-After), or from a * backoff on `strikes` (`estimated`: 30 min, 2 h, 6 h, then 24 h at most). * `untilBasis` reuses the AIP-67 `basis` vocabulary, since it answers the same * question: where this figure came from. A successful turn on the account * clears the entry; a new failure of the same kind while it is `probing` adds * a strike and a fresh `until`. * * Same persistence style as `remaining-quota-store.ts`: versioned file, mode * 0600, atomic replace, a read that never throws. `dir` is injectable so tests * round-trip against a temp directory. */ declare const ACCOUNT_UNTIL_BASES: readonly ["provider", "probe", "observed", "estimated"]; type AccountUntilBasis = (typeof ACCOUNT_UNTIL_BASES)[number]; /** Backoff by strike count when nothing better says when the account returns. */ declare const ACCOUNT_BACKOFF_MS: readonly [number, number, number, number]; /** What a caller sees for one account that is not `ok`. */ interface AccountHealthView { profileRef: string; state: "exhausted" | "probing"; until: string; untilBasis: AccountUntilBasis; reason: string; since: string; strikes: number; /** Milliseconds until `until` (0 once probing). */ remainingMs: number; } interface AccountHealthOptions { /** Overrides `~/.agentproto` (tests inject a temp dir). */ dir?: string; /** Clock, injectable for tests. */ now?: () => number; } /** Health of one account: `undefined` means `ok` (no entry). A `probing` * account is returned too, so a caller can show it, but it is eligible. */ declare function accountHealthOf(profileRef: string, opts?: AccountHealthOptions): Promise; /** Every account with an entry, soonest `until` first. */ declare function listAccountHealth(opts?: AccountHealthOptions): Promise; interface MarkExhaustedInput { /** Short human reason, e.g. the provider's message (echoed, trimmed). */ reason: string; /** Epoch ms the account returns, when known. */ until?: number; /** Where `until` came from. Required with `until`; ignored without. */ untilBasis?: Exclude; } /** * Close an account. A first failure, or one that follows a `probing` entry * (the trial failed), takes a strike; a failure reported while the account is * already closed (another session failing on the same wallet) keeps the * strike count and only ever extends `until`. Never throws on a bad `until`: * a missing or unusable one falls back to the strike backoff. */ declare function markAccountExhausted(profileRef: string, input: MarkExhaustedInput, opts?: AccountHealthOptions): Promise; /** Forget an account's entry (a recharge, or a successful turn). Returns * whether there was one. Writes nothing when there was none. */ declare function clearAccountHealth(profileRef: string, opts?: AccountHealthOptions): Promise; /** * Read the return time of an exhausted account out of the provider's own * words. Recognised, all observed or documented forms: * - OpenCode Go: `usage limit reached (weekly, resets in 1d 9h)`, * `(5-hour, resets in 2h 1m)`; * - Claude: `resets 5pm`, `resets 12pm (Europe/Paris)`, `resets Nov 20, 12pm`; * - generic: `retry after 30s`, `Retry-After: 12`, `try again in 2 minutes`, * `try again at 2026-11-20T05:00:00Z`. * Returns epoch ms in the future, or undefined (the caller then uses the strike * backoff). Never throws, never returns a past time. */ declare function parseExhaustionUntil(message: string | undefined, now: number): number | undefined; /** The slice of the health store the daemon logic talks to, so a test (or a * future remote store) can swap it. Every method resolves; none throws on a * missing or corrupt file. */ interface AccountHealthStore { get(profileRef: string): Promise; list(): Promise; mark(profileRef: string, input: MarkExhaustedInput): Promise; clear(profileRef: string): Promise; } /** The store over `~/.agentproto/account-health.json` (or `opts.dir`). */ declare function createAccountHealthStore(opts?: AccountHealthOptions): AccountHealthStore; /** * Account slots: a named indirection between a `profileRef` and a real auth * profile (AIP-46 access axis, `accountSlots` in `~/.agentproto/config.json`). * * Code and presets name a SLOT (`slot:claude-primary`), never a real account. * The slot map translates it to a profile id at the moment of use: * * ```json * "accountSlots": { * "claude-primary": "anthropic-sub-hodl", * "claude-secondary": "claude-subs-agentik" * } * ``` * * A slot can also be an ordered list of accounts: * * ```json * "accountSlots": { * "opencode-go": ["opencode-ws01", "opencode-developerws003", "opencode-hodl-ws01"], * "claude-primary": "anthropic-sub-hodl" * } * ``` * * `slot:opencode-go` resolves to the FIRST account of the slot that exists, is * enabled, may run the requested model, and is not `exhausted` in the account * health file (`account-health.ts`). A string is a slot with one account. When every * account of a multi-account slot is exhausted the resolution throws * {@link AccountSlotExhaustedError} with the nearest return time; it never * hands out a spent account. * * Changing subscription is then one config write (or `agentproto accounts * swap claude`), not a commit. There is ONE resolution point, * {@link resolveProfileRef}: a `slot:` ref becomes the real profile id, * any other ref passes through unchanged. An unknown slot, or a slot pointing * at a missing or disabled profile, is an explicit error at use time. There is * never a silent fallback to some other profile. * * Slot names carry no dot: `config_get` / `config_set` paths are dotted, so a * dotted slot name could not be addressed as `accountSlots.`. */ /** What a slot points at: one real auth-profile id (a slot with one account), or an * ORDERED list of them (a multi-account slot: first healthy, eligible account wins). */ type AccountSlotTarget = string | string[]; /** The `accountSlots` map: slot name -> real auth-profile id, or an ordered * slot of them. */ type AccountSlots = Record; /** The accounts of a slot target, in order. */ declare function slotMembers(target: AccountSlotTarget): string[]; type AccountSlotErrorCode = "account_slot_invalid" | "account_slot_unknown" | "account_slot_profile_missing" | "account_slot_profile_disabled" | "account_slot_profile_ineligible" | "account_slot_exhausted"; /** A slot reference that cannot be resolved. Always surfaced to the caller, * never swallowed into a fallback. */ declare class AccountSlotError extends Error { readonly code: AccountSlotErrorCode; readonly slot: string; constructor(code: AccountSlotErrorCode, slot: string, message: string); } /** Every account of a multi-account slot is `exhausted`: nothing may be started on it until * the nearest `until`. Carries the data a caller needs to say "back at ...". */ declare class AccountSlotExhaustedError extends AccountSlotError { /** ISO time the first account of the slot returns. */ readonly retryAfter: string; readonly accounts: Array<{ profileRef: string; until: string; untilBasis: string; reason: string; }>; constructor(slot: string, accounts: AccountHealthView[]); } /** True when `ref` is a `slot:` reference. */ declare function isSlotRef(ref: string | undefined | null): ref is string; /** The slot name of a `slot:` ref, or undefined for a plain id. */ declare function slotNameOf(ref: string | undefined | null): string | undefined; /** `slot:` for a slot name. */ declare function slotRef(name: string): string; /** Read the `accountSlots` map from config.json (empty when absent). */ declare function loadAccountSlots(path?: string): Promise; interface ResolveProfileRefDeps { /** Slot map source. Defaults to config.json's `accountSlots`. */ loadAccountSlots?: () => Promise; /** Profile lookup. Defaults to `@agentproto/auth`'s store. */ getAuthProfile?: (id: string) => Promise | undefined>; /** The model the caller is about to run. A multi-account slot skips an account whose * per-profile model allow-list refuses it. */ model?: string; /** Account health source. Defaults to `~/.agentproto/account-health.json`. */ accountHealth?: Pick; } interface ResolvedProfileRef { /** The real auth-profile id to bill. */ profileRef: string; /** The slot the caller named, when the ref was `slot:`. */ slot?: string; } /** * THE resolution point for a `profileRef`. `slot:` -> the real profile * id the slot points at now; a plain id is returned unchanged (its own * existence is checked by whichever caller already checks it). * * Throws {@link AccountSlotError} for a malformed slot name, an unknown slot, * a slot whose target is itself a slot, or a target profile that is missing * or disabled. */ declare function resolveProfileRef(ref: string, deps?: ResolveProfileRefDeps): Promise; interface AccountSlotSwapPlan { family: string; primarySlot: string; secondarySlot: string; /** Profile the primary slot points at BEFORE the swap (the one that leaves). */ departing: string; /** Profile the primary slot points at AFTER the swap. */ arriving: string; before: AccountSlots; after: AccountSlots; } /** Compute a `-primary` <-> `-secondary` swap. Throws * {@link AccountSlotError} when the family name is invalid or a slot of the * pair is missing. Pure: nothing is written. */ declare function planAccountSlotSwap(slots: AccountSlots, family: string): AccountSlotSwapPlan; /** Minimal session shape the slot views read. */ interface SlotSessionLike { id: string; kind?: string; status?: string; name?: string; label?: string; accessSlot?: string; accessProfile?: { profileRef: string; }; } /** * The sessions `swap --move-alive` restarts: ALIVE agent sessions billing the * departing profile, whether they reached it through the primary slot * (`accessSlot`) or by naming the profile literally (the mixed migration * period). Dead sessions are never selected. */ declare function sessionsToMoveOnSwap(sessions: readonly S[], plan: Pick): S[]; interface AccountSlotAccountRow { profileRef: string; /** Missing / disabled status of the profile, when not usable. */ problem?: "missing" | "disabled"; /** Health when the account is not `ok`: exhausted (closed) or probing. */ health?: Pick; } interface AccountSlotRow { slot: string; /** The account a spawn on this slot lands on now: the first usable, open * account of the slot, else its first member. For a single-account slot, * that account. */ profileRef: string; /** Missing / disabled status of `profileRef`, when not usable. */ problem?: "missing" | "disabled"; /** Health of `profileRef` when it is not `ok` (single-account slot). */ health?: AccountSlotAccountRow["health"]; /** A multi-account slot's accounts in order, each with its health. Absent for a * single-account slot. */ accounts?: AccountSlotAccountRow[]; /** Alive sessions on this slot: `accessSlot` matches, or (no slot recorded) * the session names one of the slot's profiles literally. */ aliveSessions: Array<{ id: string; label: string; via: "slot" | "profile"; }>; } interface AccountSlotPreferPlan { slot: string; /** The account at the head of the slot BEFORE the move. */ departing: string; /** The account at the head of the slot AFTER the move. */ arriving: string; before: AccountSlots; after: AccountSlots; } /** Put `profile` at the head of the slot `slot` (the rest keep their order). * A profile that is not in the slot is added at the head. Pure: nothing is * written. */ declare function planAccountSlotPrefer(slots: AccountSlots, slot: string, profile: string): AccountSlotPreferPlan; /** The sessions `prefer --move-alive` restarts: ALIVE agent sessions on the * slot (recorded `accessSlot`, or literally on a member) whose account is not * the new head. */ declare function sessionsToMoveOnPrefer(sessions: readonly S[], plan: Pick): S[]; /** * Spawn-time role profiles — the primitive that decides whether a * spawned agent may itself delegate (spawn further children). * * A role is 3 layers: * - `disposition` — a system-prompt fragment. Soft: sets the mindset. * - `toolPolicy` — whether delegation tools are injected into the * child at all. HARD: enforced by the daemon at the `agent_start` * injection point (`session-spawn.ts`), not by the child's own * behaviour. A child cannot widen its own `toolPolicy` — not via * `promptAppend`, not by requesting `orchestrator` itself. * - `skills[]` — role-specific skill set (built-ins ship empty/ * unset; a future pack-carried role can populate this). * * Why the asymmetry matters: a process can bring its own disposition * and skills (those are portable, could live in a skill/pack), but it * can never strip tools the daemon already injected into it. Only the * spawner controls that — which is exactly why `toolPolicy` must be * resolved and enforced here, at spawn time, rather than left to a * prompt instruction the model could rationalize past. */ type DelegationPolicy = "allow" | "deny"; interface RoleToolPolicy { delegation: DelegationPolicy; } interface RoleProfile { name: string; disposition: string; toolPolicy: RoleToolPolicy; skills?: string[]; /** * Files injected, fenced by their tag, into the spawn prompt right after the * disposition (`role-context-files.ts`). ROLE.md: `contextFiles: tag=path`. */ contextFiles?: Array<{ tag: string; path: string; }>; /** * Privilege level in the spawn lattice. Higher = more privileged. * The default spawn-gate rule (`canSpawn`) is non-escalation: a * parent may spawn a child only when `child.level <= parent.level` * — peers and subordinates are fine, spawning something MORE * privileged than yourself is not. (Unbounded same-level recursion — * e.g. supervisor spawning supervisor spawning supervisor — is a * pre-existing, deliberate pattern bounded separately by * `maxDepth`/`maxChildren`, not this lattice; see `spawnableRoles` * below for a role that also needs to cap recursion itself.) * `spawnableRoles` (below), when set, opts a role into a closed * allowlist instead — level is then only used for display/ordering. */ level: number; /** * Closed allowlist of role names this role may spawn, by name — the * opt-in "figé pipeline" mode. When set, `canSpawn` checks name * membership instead of the level comparison. Undefined (the * default, open mode) ⇒ non-escalation by `level`. */ spawnableRoles?: string[]; /** * Role-level default for the daemon self-mount's deferred/lazy tool * loading (harness-parity item 3 — see `deferred-tools.ts`). Applied to * the injected `mcpServers` entry (`session-spawn.ts`'s * `shouldInjectDaemonSelfMount` path) as `?deferred=1|0` when the spawn * itself didn't pass an explicit `deferredTools` override AND the adapter * declares `capabilities.deferredToolDiscovery: true` (a harness that * validates calls against its last `tools/list` is always eager — it * cannot call a tool `tool_search` only described). Undefined ⇒ no * role-level opinion, the gateway's own boot-time default * (`defaults.mcp.deferredTools` in config.json) applies unchanged (same * capability gate). */ deferredTools?: boolean; /** * Role-level default for `agent_start.browser` (see `browser-mount.ts`): * `"headless"` gives every spawn of this role its own isolated headless * Chrome. An explicit spawn `browser` wins; undefined ⇒ no opinion (the * user preset, then `defaults.spawn.browser`, decide). */ browser?: SpawnBrowserMode; /** * AIP-46 §Delegation: the agents a session bound to this role may spawn, * by name. Data only for now: the delegation gate still reads `level`, * `spawnableRoles` and `toolPolicy` until it is moved onto this list. * Undefined ⇒ the role declares nothing (a pack-carried role). */ delegatesTo?: readonly string[]; } /** The built-in agent a spawn naming none binds below the depth cutoff. */ declare const DEFAULT_ROOT_AGENT = "supervisor"; /** The built-in agent a spawn naming none binds at or above the depth cutoff. */ declare const DEFAULT_NESTED_AGENT = "executor"; /** `defaults.spawn.defaultAgent`: which agent a spawn that names none binds. */ interface DefaultAgentConfig { root?: string; nested?: string; } /** * The names `defaultAgent` configures that the registry does not know (so the * built-in default applies instead). Pure; used to warn, never to reject. */ declare function unknownDefaultAgents(defaultAgent: DefaultAgentConfig | undefined, registry?: Readonly>, side?: "root" | "nested"): string[]; /** * Daemon-side AGENTS.md resolution + injection (WP-R2). * * The daemon historically had ZERO first-class handling of `AGENTS.md` — it * was read only when an adapter happened to do so natively (opencode by its * own convention, claude-code via `CLAUDE.md`, hermes not at all), and the * supervisor brief told a child to "go read AGENTS.md" by hand, which is a * loterie, not a guarantee. This module makes the daemon resolve and inject * it itself, adapter-agnostic, at spawn time — the same way it already * composes the role disposition (see `role.ts`'s `composeRoleContext`). * * Resolution runs once per spawn, from the session's resolved `cwd`: * - walk UP directory by directory, checking for an `AGENTS.md` at each * level; the FIRST one found (nearest to `cwd`) wins. * - the walk is bounded by the git toplevel of `cwd`'s own repo * (`git rev-parse --show-toplevel` from `cwd`) — it never walks past it * into an outer/parent repo. A nested repo has its own `.git`, so git's * toplevel resolves to the nested root and the walk stops exactly there. * - if `cwd` is not inside a git repo at all, only `cwd` itself is checked * (no walk), falling through to "absent" when nothing is there. * * Injection is a block in the child's single composed initial prompt (there * is no separate system-prompt channel — see `session-spawn.ts`'s * `effectivePrompt` construction): a full inline copy when the file is small * enough, a pointer to read it first when it's large, or nothing extra when * absent — plus a standing cd-contract sentence regardless of mode. */ type AgentsMdMode = "inline" | "pointer" | "absent"; /** The resolved AGENTS.md's absolute path; undefined when mode is "absent". */ interface AgentsMdResolution { mode: AgentsMdMode; /** Absolute path of the resolved AGENTS.md. Undefined when mode is * `"absent"`. */ path?: string; /** Full text of the AGENTS.md (inline mode only). */ content?: string; /** The prompt block to inject (full inline text or a pointer), or * undefined when absent. Excludes the always-present cd-contract line. */ block?: string; /** The standing cd-contract sentence, present in every mode. */ contractLine: string; } interface WorkspaceRulesResolution { /** Absolute path of the resolved RULES.md. Undefined when absent (or a * read failure degraded to absent). */ path?: string; /** Full text of the RULES.md, inlined. Present exactly when `block` is. */ content?: string; /** The prompt block to inject, or undefined when absent. */ block?: string; } /** * App boundary — filesystem zones for sessions an app (or an app workflow) * spawns. * * readOnly the installed app source (dir, `.agentproto/`, `scripts/`, …) * writable the workflow run workspace (`~/.agentproto/runs//`, * `$run.workspace`) and the app `data/` dir * hidden host trees that must not be readable even though the OS * sandbox alone would allow them (the daemon workspace, the host * monorepo the app happens to be installed inside) * else denied * * One `AppBoundary` value drives every enforcement surface: * - daemon file tools (`fs-tools.ts`) and `command_execute` * (`command-tools.ts`) resolve paths through {@link resolveBoundaryPath}; * - the harness's native tools are confined by the OS sandbox * (`@agentproto/command-sandbox`) built from {@link boundaryToSandboxZones}; * - the boundary rides on the session descriptor (`meta.appBoundary`) so the * daemon gateway can recover a caller's boundary from its trusted * `callerSessionId`, and children/restarts inherit it. */ type AppBoundaryEnforce = "required" | "best-effort"; interface AppBoundary { readonly appId: string; /** Base for relative paths in the daemon file tools — the app dir. */ readonly root: string; readonly readOnly: readonly string[]; readonly writable: readonly string[]; readonly hidden: readonly string[]; readonly enforce: AppBoundaryEnforce; /** Operator-granted read-only paths (a subset of `readOnly`, kept apart for * audit: `describeBoundary`, `app_list`). Absent = none. */ readonly readGrants?: readonly string[]; /** Secret files/dirs inside a read grant, denied for read and write even * though their parent is readable. Absent = none. */ readonly unreadable?: readonly string[]; } /** * Session inference binding — resolve `agent_start`'s `inference` field * (`{endpoint}` / `{endpoint, model}` / `{model: "@"}`) * into a concrete local/LAN endpoint + model, run the harness fit check * against its loaded ctx BEFORE spawn, and project the result into the * ordinary `model`/`route`/`access`/`auth`/`deferredTools` fields the rest of * `session-spawn.ts`'s pipeline already understands — see * `.plans/agentproto-onboarding/SESSION-INFERENCE-BINDING.md`. * * A configured endpoint's ctx/model list comes from * `@agentproto/inference-endpoint`'s connectors (`connectorById(...).listModels`) — * the SAME probe `agentproto llm endpoints test`/`doctor` already use, never * reimplemented per-runtime here. A `@` reference (a * paired host's own shared endpoint, DEVICES-PLAN item 2) is resolved through * an injected device probe (real implementation: `HostRegistry.forwardHttp` * against `/devices/:id/exec-stream/device-inference/v1/models`) — that route * only ever returns model IDS, never loaded ctx (the gateway's aggregate * `/v1/models` merges named-endpoint models by id only — see * `packages/inference-endpoint/src/index.ts`'s `probeFileEndpointModels`), so a * device-routed harness's fit check is always `unknown` (warn, never block) * — an OFFLINE/unreachable device is a distinct, harder failure (the * endpoint can't be resolved at all), surfaced as `ok:false`. */ interface InferenceBindingRequest { /** A configured endpoint id, or `@` for a paired * host's own shared endpoint. */ endpoint?: string; /** A bare model id (paired with `endpoint`), or — when `endpoint` is * omitted — the shorthand `"@"`. */ model?: string; /** Skip the fit-check refusal (still runs the check, still warns). */ force?: boolean; /** Headroom percentage (0-95) held back from the endpoint's loaded ctx for * the fit check — the wire form of {@link DEFAULT_HEADROOM_RATIO} from * `@agentproto/inference-endpoint`. Converted to a 0-1 ratio by the caller * before reaching {@link fitCheckForTarget}. */ headroomPct?: number; } /** Outcome of probing a paired device for its own shared inference models — * the daemon-to-daemon leg of a `@` / `@` * reference. Never throws; a network/pairing failure resolves `reachable:false`. */ type DeviceProbeResult = { reachable: true; endpointId: string; modelIds: string[]; } | { reachable: false; message: string; }; interface ModelCooldownEntry { model: string; /** ISO time the cooldown ends. */ until: string; remainingMs: number; /** Why it was recorded (`rate-limit` / `no-output-stall` / `usage-limit`). */ reason: string; /** The session whose failure recorded it. */ sessionId?: string; } /** * Placement ladder (`agent_start.placement`): an ordered list of rungs, each a * sandbox (plus optional model / access / preflight / turnRetry overrides). The * spawn tries rung 1; when the box cannot be placed there, it moves to rung 2, * and so on. Whatever rung the session starts on, a mid-run failure is * `turnRetry`'s job, never the ladder's. * * The criteria are typed, never a provider message match: a rung is skipped on * a failed preflight, a typed boot failure (capacity, overflow refused, egress * pool exhausted) or a boot-phase code listed in {@link LADDER_ADVANCE_CODES}. */ declare const placementRungSchema: z.ZodObject<{ sandbox: z.ZodUnion; schema: z.ZodOptional>; id: z.ZodOptional; version: z.ZodOptional; provider: z.ZodString; config: z.ZodObject<{ installHarnesses: z.ZodOptional>; }, z.core.$catchall>; limits: z.ZodOptional; memory_mb: z.ZodOptional; cpu_ms: z.ZodOptional; cpus: z.ZodOptional; }, z.core.$strict>>; env: z.ZodOptional; passthrough: z.ZodDefault>; autoPassthrough: z.ZodOptional; }, z.core.$strict>>; network: z.ZodOptional>; egressIp: z.ZodDefault; }, z.core.$strict>>; join: z.ZodOptional>; mounts: z.ZodDefault>; identity: z.ZodOptional; policy: z.ZodOptional; lifecycle: z.ZodOptional; destroy_on: z.ZodOptional; }, z.core.$strict>>; read_only: z.ZodDefault; extraPorts: z.ZodOptional>; metadata: z.ZodOptional>; }, z.core.$strict>]>; model: z.ZodOptional; access: z.ZodOptional; profileRefs: z.ZodOptional>; }, z.core.$strict>>; preflight: z.ZodOptional>; turnRetry: z.ZodOptional>; 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>, z.ZodNull]>>; agentStartTimeoutMs: z.ZodOptional; }, z.core.$strict>; declare const placementInputSchema: z.ZodObject<{ ladder: z.ZodArray; schema: z.ZodOptional>; id: z.ZodOptional; version: z.ZodOptional; provider: z.ZodString; config: z.ZodObject<{ installHarnesses: z.ZodOptional>; }, z.core.$catchall>; limits: z.ZodOptional; memory_mb: z.ZodOptional; cpu_ms: z.ZodOptional; cpus: z.ZodOptional; }, z.core.$strict>>; env: z.ZodOptional; passthrough: z.ZodDefault>; autoPassthrough: z.ZodOptional; }, z.core.$strict>>; network: z.ZodOptional>; egressIp: z.ZodDefault; }, z.core.$strict>>; join: z.ZodOptional>; mounts: z.ZodDefault>; identity: z.ZodOptional; policy: z.ZodOptional; lifecycle: z.ZodOptional; destroy_on: z.ZodOptional; }, z.core.$strict>>; read_only: z.ZodDefault; extraPorts: z.ZodOptional>; metadata: z.ZodOptional>; }, z.core.$strict>]>; model: z.ZodOptional; access: z.ZodOptional; profileRefs: z.ZodOptional>; }, z.core.$strict>>; preflight: z.ZodOptional>; turnRetry: z.ZodOptional>; 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>, z.ZodNull]>>; agentStartTimeoutMs: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>; type PlacementRung = z.infer; type PlacementInput = z.infer; interface PlacementAttempt { /** 0-based index into the ladder. */ rung: number; provider: string; model?: string; outcome: "ok" | "failed"; /** Typed reason a failed rung was skipped: the failure code, or the more * specific `errorClass` it carried (e.g. `sandbox_overflow_refused`). */ errorClass?: string; egressIp?: string; durationMs: number; } /** What the descriptor records once a ladder spawn settles. */ interface SessionPlacement { /** The rung the session runs on (0-based). */ rung: number; /** The ladder as requested, so a restart or migration can re-place. */ ladder: PlacementRung[]; attempts: PlacementAttempt[]; } /** * WP3 — `agent_start.sandbox` + `appServe`: serve an agentproto app's UI * from INSIDE a booted sandbox box and hand back its public URL. * * The sandbox spawn path (`session-spawn.ts`'s `bootSandboxAgentSession`) * boots a box whose own agentproto daemon is reachable at `BootedSandbox * .mcpUrl`. That daemon already registers every tool the plain `/mcp` * gateway mounts — notably `app_install` (app-tools.ts), `file_read` / * `file_write` (fs-tools.ts, anchored to the box workspace) and * `command_execute` (command-tools.ts, allowlist-gated). This module * drives exactly those three, in order: * * 1. `app_install { dir }` — install the app (dir is a path INSIDE * the box; on the workstation image the * daemon workspace is `/home/user`, so a * pulled app lives at * `/home/user/apps/`). * 2. allowlist seed — `command_execute` is default-deny * against the box workspace's * `.agentproto/allowed-commands.json`. * The launcher below needs `sh` (the * detached backgrounding shell) and * `agentproto` (the CLI that runs the * server). Both are merged into the * existing allowlist via `file_read` + * `file_write` — additive only, so an * operator-seeded allowlist is preserved. * 3. `command_execute` — launch `agentproto app serve * --host 0.0.0.0 --port ` DETACHED * (`sh -c 'nohup … &'`): the sh wrapper * exits immediately, so the RPC returns * while the orphaned server lives as * long as the box does. A direct * (non-backgrounded) call would be * hard-killed at `command_execute`'s * timeoutMs cap — the server must * outlive the RPC. * * The caller resolves the PUBLIC URL from the provider (a port declared in * `SandboxSpec.extraPorts` comes back pre-resolved in `BootedSandbox.ports`; * otherwise `BootedSandbox.expose(port)` works for any port on providers * that support it) and passes it in — readiness is probed against it. */ /** The `appServe` request carried on `agent_start` — an in-box app dir plus * the port to serve its UI on. */ interface SandboxAppServeSpec { /** Absolute path to the app's directory INSIDE the box (e.g. * `/home/user/apps/`). Must not contain a single quote — the * launcher shell-quotes it. */ dir: string; /** Port `agentproto app serve` binds inside the box. Must also be exposed * by the provider (the spawn path appends it to `extraPorts` so a * boot-time exposure exists on providers that pre-resolve). Defaults to * `DEFAULT_APP_SERVE_PORT` when omitted. */ port?: number; } /** What a served app records on the session descriptor and echoes in the * spawn result — non-secret, caller-visible. */ interface SessionAppServeInfo { /** App id the box's `app_install` registered. */ appId: string; /** The in-box app dir that was installed + served. */ dir: string; /** Port the UI binds inside the box. */ port: number; /** Provider-resolved public URL for the served UI. */ url: string; /** True when a probe against `url` answered OK within the readiness * window. False means the URL is the right address but the server had * not answered yet — retry the fetch rather than re-spawning. */ ready: boolean; /** Error text from the in-box serve log when `ready` is false (e.g. the * server exited immediately because the UI root is missing). Absent when * the log holds no recognizable error or could not be read. */ message?: string; } /** * Policy layer for `agent_start.worktree` — the config-driven decision of * WHETHER to isolate a spawn into its own git worktree, kept deliberately * separate from HOW one is provisioned. * * This module holds no dependency on `@agentproto/worktree`. Same reasoning * as `worktree-identity.ts`'s docblock, only stronger: provisioning runs the * `worktree.provision` TOOL (git + the base tree's `agentproto.json` setup * hooks), which would drag the driver/harness/provider graph into * `@agentproto/runtime` for a capability the runtime only ever *triggers*. * So the concrete provisioner is an INJECTED PORT ({@link WorktreeProvisioner}) * wired at the composition root by a host that already depends on the * worktree package (the CLI). The runtime owns only the pure decision * ({@link decideWorktreeIsolation}) and the config/env resolution * ({@link loadWorktreeIsolation}) — both trivially unit-testable without git. * * Mirrors `agent_start.sandbox`'s `resolveSandboxProvider` injection shape, * except sandbox can default its resolver inside the runtime (the runtime * depends on `@agentproto/sandbox`); worktree cannot, so an unwired daemon * simply has no provisioner and a spawn that would need one fails loud rather * than silently spawning unisolated. */ /** Env override for the isolation policy. Highest-priority source, ahead of * the `worktrees.isolation` config field — see `loadWorktreeIsolation`. */ declare const WORKTREE_ISOLATION_ENV = "AGENTPROTO_WORKTREES_ISOLATION"; /** Env override for the daemon-wide cap on concurrently running HEAVY * worktree-provisioning segments (`depsCmd` etc.). Highest-priority source, * ahead of `worktrees.provisionConcurrency`. Enforced by * `@agentproto/worktree`'s scheduler (which reads the same env name); the * runtime only carries the name and the default for the config registry. */ declare const WORKTREE_PROVISION_CONCURRENCY_ENV = "AGENTPROTO_WORKTREES_PROVISION_CONCURRENCY"; /** Default cap on concurrently running heavy provisioning segments. Mirrors * `@agentproto/worktree`'s `DEFAULT_PROVISION_CONCURRENCY` (a CLI test pins * the two together — the runtime takes no dependency on that package). */ declare const DEFAULT_WORKTREE_PROVISION_CONCURRENCY = 2; /** Env overrides for the provisioning boot bounds, ahead of * `worktrees.provisionStallTimeoutMs` / `provisionMaxMs`. Enforced by * `@agentproto/worktree` (same names; a CLI test pins them together). */ declare const WORKTREE_PROVISION_STALL_TIMEOUT_ENV = "AGENTPROTO_WORKTREES_PROVISION_STALL_TIMEOUT_MS"; declare const WORKTREE_PROVISION_MAX_ENV = "AGENTPROTO_WORKTREES_PROVISION_MAX_MS"; /** Defaults for those bounds; mirror `@agentproto/worktree`'s. */ declare const DEFAULT_WORKTREE_PROVISION_STALL_TIMEOUT_MS = 120000; declare const DEFAULT_WORKTREE_PROVISION_MAX_MS: number; /** The default when nothing is configured. Back-compat-preserving: a caller * that passes no `worktree` field spawns exactly where it asked. */ declare const DEFAULT_WORKTREE_ISOLATION: WorktreeIsolationMode; /** * The `agent_start.worktree` field. `true` isolates with an auto-minted slug; * an object additionally pins the slug and/or base ref, and can opt into * async provisioning (`async: true` — see `WorktreeRequest.async`); `false` * (or omitted) is "no explicit request" — the policy mode decides. */ type WorktreeField = boolean | { slug?: string; base?: string; async?: boolean; stallTimeoutMs?: number; maxMs?: number; }; /** The caller's explicit request, normalized — `undefined` when the field is * absent or `false`, otherwise the (possibly empty) slug/base overrides. */ interface WorktreeRequest { slug?: string; base?: string; /** Return a real, registered session as soon as it's minted, provisioning * the worktree in the BACKGROUND instead of blocking `agent_start`'s * response on `git worktree add` + the repo's setup hooks (which can run * minutes — see `session-spawn.ts`'s async-provision branch). * * DEFAULTS TO TRUE for any spawn that provisions a worktree, UNLESS this * spawn also carries `wait` (which needs a first turn to block on — see * `worktree_async_wait_conflict` — so the presence of `wait` alone falls * back to the synchronous path rather than conflicting by default). That * default is applied by `session-spawn.ts` itself (WP-H), not by this * field or `normalizeWorktreeField` — the normalizer leaves `async` * exactly as the caller sent it (`undefined` when omitted; see its own * test), so a caller inspecting the normalized request never sees a * value it didn't write. WP-H incident: the synchronous contract this * field opts OUT of — hold the RPC open for however long setup hooks * take, routinely minutes — is exactly what let a client's own request * timeout retry into a second live agent sharing the first one's * worktree (closed on the other side too — see `session-spawn.ts`'s * `findWorktreeLabelCwdCollision`, which now refuses that retry outright * rather than merely warning). Pass `false` explicitly to keep the old * blocking ok/fail contract (this package's own `worktree_provision_failed` * test coverage exercises it deliberately synchronous). */ async?: boolean; /** Per-spawn boot bound: kill the setup and fail the session when the * deps/setup process prints nothing for this many ms. `0` disables it. * Omitted ⇒ env / `worktrees.provisionStallTimeoutMs` / default (120 s). */ stallTimeoutMs?: number; /** Per-spawn hard cap on the heavy provisioning segment, in ms. `0` * disables it. Omitted ⇒ env / `worktrees.provisionMaxMs` / default (30 min). */ maxMs?: number; } /** What the runtime hands the provisioner. `cwd` is where the session would * otherwise spawn; the provisioner resolves the owning repo from it. */ interface WorktreeProvisionRequest { cwd: string; /** Explicit slug from the caller; omitted ⇒ the provisioner mints a * collision-free one (see the host implementation). */ slug?: string; /** Base ref the worktree branch is cut from; omitted ⇒ the provisioner's * default (`origin/main`). */ base?: string; /** Free-text label (the session's `label`) the provisioner may fold into a * minted slug for human readability. Never load-bearing for correctness. */ labelHint?: string; /** Absolute path the provisioner should append the setup hooks' FULL * stdout+stderr to (see `worktree.provision`'s `setupLogPath` input and * `@agentproto/worktree`'s `runSetup`). `session-spawn.ts` passes the * spawning session's own transcript dir here, so a failing setup hook's * full output survives even after a subsequently-reclaimed worktree is * gone — the short `HookError` message alone only carries a filtered * tail. Omitted callers (e.g. `agentproto worktree new`, no session to * log into) simply get no persisted log. */ setupLogPath?: string; /** Re-run a failing `worktree.setup` command exactly once before giving * up — see `worktree.provision`'s `retrySetupOnFailure` input and * `runSetup`'s doc for why this is a bounded complement, not a * substitute, and why the daemon opts in while `agentproto worktree new` * doesn't. */ retrySetupOnFailure?: boolean; /** Cancels this provisioning: a queued one is dropped from the daemon-wide * provisioning queue, a running one has its child process tree killed (no * orphaned `pnpm install`). The provisioner then rejects. */ signal?: AbortSignal; /** Whose spawn this is, for the scheduler's fair-share dispatch (the parent * session id, or an anonymous key for a top-level spawn). */ callerId?: string; /** Progress of the heavy provisioning segment (queued / started / phase / * done). Best-effort; never throws into the provisioner. */ onProgress?: (progress: WorktreeProvisionProgress) => void; /** Live stdout/stderr of the deps/setup processes, chunk by chunk, so the * session's output shows progress while it is still `starting`. */ onOutput?: (text: string, stream: "stdout" | "stderr") => void; /** Per-spawn overrides of the provisioning boot bounds (see * {@link WorktreeRequest.stallTimeoutMs} / `maxMs`); omitted ⇒ the * provisioner resolves env / config / defaults. */ stallTimeoutMs?: number; maxMs?: number; } /** Phases of a worktree provisioning. `worktree` is the unthrottled * `git worktree add` step; the rest are the throttled heavy ones. */ type WorktreeProvisionPhase = "worktree" | "clone" | "deps" | "copy" | "setup" | "sandbox"; /** Structural mirror of `@agentproto/worktree`'s `ProvisionProgress` (the * runtime deliberately takes no dependency on that package). */ type WorktreeProvisionProgress = { kind: "queued"; position: number; phase: WorktreeProvisionPhase; } | { kind: "started"; phase: WorktreeProvisionPhase; } | { kind: "phase"; phase: WorktreeProvisionPhase; } | { kind: "done"; outcome: "ok" | "failed" | "cancelled"; }; /** The provisioner's outcome. `isolated: false` is NOT a failure — it means * there was nothing to isolate (`cwd` sits in no git repo), and the caller * should spawn plain at the original cwd. A genuine failure throws. */ type WorktreeProvisionOutcome = { isolated: true; cwd: string; branch: string; } | { isolated: false; reason: "not-a-git-repo"; }; /** * Injected port: provision a git worktree for `req.cwd` and return the * worktree's own cwd for the spawn to land in. Wired at the composition root * by the CLI (over `@agentproto/worktree`); absent on a bare runtime. */ type WorktreeProvisioner = (req: WorktreeProvisionRequest) => Promise; /** * Injected port: best-effort attempt to reclaim ONE worktree by path, called * when its session reaches a terminal state (see * `SessionDescriptor.worktreeAutoProvisioned` and `createSessionsRegistry`'s * `runWorktreeAutoReclaim` option in `sessions.ts`). Deliberately scoped to * exactly the one path a session's own exit is allowed to touch — never a * repo-wide sweep. The implementation (wired by the CLI over * `@agentproto/worktree`'s `reclaimOneWorktree`) re-classifies fresh and only * ever removes the worktree when that comes back `reclaim` (merged-or-fresh, * clean, idle) — a dirty or held worktree is simply left alone. Must never * reject in a way the caller can't safely ignore; `sessions.ts` treats any * rejection as "couldn't reclaim this time, leave it for a manual or * scheduled `gc` sweep" and logs rather than lets it interrupt session * teardown. Absent on a bare runtime — auto-reclaim is simply skipped, and a * caller-explicit worktree request is never routed through this port at all * (see `WorktreeDecision.provision.implicit`). */ type WorktreeAutoReclaimer = (worktreePath: string) => Promise; /** * Exit-time best-effort reclaimer for a sandboxed session's checkpoint * branch: when a `wt/` session ends and the work it rescued onto * `agentproto-checkpoint/` is provably elsewhere (PR merged/closed, * content in base or the work branch, squash- or patch-merged), the ref may * be deleted from the workspace remote. Same contract as * {@link WorktreeAutoReclaimer}: a rejection is "couldn't reclaim this time" * — `sessions.ts` logs it and never lets it interrupt summarisation or the * `session:exited` event. Absent on a bare runtime: nothing is ever deleted * by the session sweep itself, and `agentproto sandbox checkpoint-gc` remains * the manual tool. */ type SandboxCheckpointReclaimer = (input: { cwd?: string; branch: string; }) => Promise; /** The pure decision's three outcomes. `spawn-in-place` may carry a `warn`: * a non-fatal notice the caller should surface (the child is about to run in * a shared, dirty checkout it doesn't own). A `warn` never blocks the spawn — * it's the loud-but-legitimate middle ground between silently spawning into a * shared tree and hard-rejecting an in-place spawn that's normal at depth. * `provision.implicit` is `true` exactly when the caller made no explicit * `worktree` request and the `"always"` policy provisioned one anyway (the * worktree the caller never asked to keep) — `false` whenever the request * came from the caller itself (`on-request`'s only path here, or `"always"` * with an explicit field). This is the signal `session-spawn.ts` threads * onto the session descriptor so exit-time auto-reclaim (`sessions.ts`) * only ever touches a worktree the daemon minted on its own — a worktree a * caller explicitly asked to keep is never auto-removed. */ type WorktreeDecision = { action: "spawn-in-place"; warn?: string; } | { action: "provision"; request: WorktreeRequest; implicit: boolean; } | { action: "reject"; message: string; }; /** * Normalize the raw field into an explicit request, or `undefined` when the * caller made no request (`false` / omitted). An object with no overrides * still counts as a request (`{}`) — the caller opted in, just without pins. */ declare function normalizeWorktreeField(field: WorktreeField | undefined): WorktreeRequest | undefined; /** * The resolution matrix — mode × explicit-request × depth — with no side * effects. Every branch is exercised in `worktree-isolation.test.ts`. * * Depth-0 gate: a nested spawn (`depth > 0`, i.e. made through the scoped * orchestrator sub-gateway) NEVER provisions a worktree of its own — it * inherits its parent's ground, per AIP-46 §Delegation. This bites before * the mode is even consulted, so `always` too provisions only at the root. * But "never provisions" is NOT "silently ignore an explicit request": a * nested caller that passes an EXPLICIT `worktree` (`true` / `{slug}`) asked * for isolation and would silently get none — the spawn quietly runs in the * shared checkout, exactly the footgun that nearly clobbered a shared tree. * So an explicit request at depth > 0 is REJECTED loudly (same shape as the * `never`-policy reject below), pointing the caller at sandbox isolation — * child isolation is the sandbox, not a second worktree. Only the IMPLICIT/ * absent case (`undefined` / `false`) stays an in-place spawn: the child is * meant to share the parent's tree and made no request to the contrary. * * That implicit case still has a footgun, though: the inherited cwd may be a * LIVE, DIRTY, shared checkout (the real repo, not a daemon-provisioned * worktree) — spawning in place there lets a nested child edit a tree someone * else is actively working in. We don't hard-reject it (implicit in-place is * legitimate and common), but we DON'T stay silent either: when the caller * hands us `sharedDirtyCwd` (an impure signal it computed — see * `session-spawn.ts`), the in-place spawn carries a `warn`. A caller that * genuinely intends it passes `allowSharedCwd` to acknowledge and silence the * warning. The signal is only consulted for the implicit nested case; every * other branch ignores it, keeping the root matrix unchanged. */ declare function decideWorktreeIsolation(input: { mode: WorktreeIsolationMode; field: WorktreeField | undefined; depth: number; /** Impure signal, computed by the caller (never inside this pure fn): the * inherited cwd is a git work tree that is DIRTY and NOT a daemon- * provisioned worktree — i.e. a shared checkout the child would edit in * place. Only consulted for an implicit nested spawn. */ sharedDirtyCwd?: boolean; /** Caller's explicit acknowledgement that spawning into a shared dirty cwd * is intended — silences the `sharedDirtyCwd` warning. */ allowSharedCwd?: boolean; }): WorktreeDecision; /** Parse a raw string into a valid mode, or `undefined` when it isn't one. */ declare function parseWorktreeIsolationMode(raw: string | undefined): WorktreeIsolationMode | undefined; /** * Resolve the effective isolation mode: env > config field > default. Mirrors * `resolveWorktreesRoot`'s precedence (there's no flag layer — this is read * daemon-side at spawn, not from an invocation). Never throws: an unreadable * config falls through to the default. */ declare function loadWorktreeIsolation(loadCfg?: () => Promise<{ worktrees?: { isolation?: WorktreeIsolationMode; }; }>): Promise; /** * Policy layer for `agent_start.attach` — the config-driven decision of WHO a * spawn nests under, kept deliberately separate (and pure) from the spawn * plumbing in `session-spawn.ts`, exactly as `worktree-isolation.ts` is for * `agent_start.worktree`. * * The problem it fixes: on the plain `/mcp` path (no scoped orchestrator * gateway), a spawn was attributed to a parent ONLY when the caller passed an * explicit `parentSessionId` hint — so a supervisor that spawned an executor * without wiring itself as an orchestrator produced a depth-0 ORPHAN. The * daemon already knows the caller's own id on that path (the trusted * `?callerSessionId=` query the self-ref `mcpServers` URL carries — PR 7 / * Gap 7), it just wasn't being used for lineage. This module decides whether * to use it. * * Trust boundary (unchanged from the hint): the scoped `/mcp/orchestrator` * gateway's token is the UNSPOOFABLE source — when a `callerScope` is present * the caller derives its parent from the token and this whole module is * bypassed (see `session-spawn.ts`). Everything here is descriptor-only * lineage on the anonymous root path; it never moves the gating `childDepth` * and so never relaxes a depth-gated worktree/role guard. */ /** * The `agent_start.attach` field. `true` opts in to attaching under the * derived parent (the caller's own id / an explicit hint) even when the * policy is `on-request`; an object additionally pins an explicit parent id; * `false` forces an INDEPENDENT root (no parent, depth 0) regardless of * policy or derivable identity — the deliberate "launch detached" escape * hatch, mirroring `worktree: false`. Omitted ⇒ the policy mode decides. */ type AttachField = boolean | { parent?: string; }; type AdmissionDecision = { outcome: "allow"; } | { outcome: "deny"; code: string; message: string; } | { outcome: "reuse"; targetId: string; code: string; } | { outcome: "defer"; queueEntryId: string; retryAfterMs?: number; code: string; }; /** * Parity layer of the `builtin:spawn-admission` policy. * * Today this produces `allow`, `reuse` and `deny` for the spawn decisions * that `spawnAgentSession` already makes. `defer` (capacity) is added later * behind an opt-in. The claim map in `session-spawn.ts` stays the atomic * guard; this function only evaluates the facts the caller already has and * reads no registry, clock or claim map. */ type SpawnDedupeSource = "explicit" | "implicit" | "worktree-cwd"; type SpawnAdmissionCheck = { stage: "claim"; source: "explicit" | "implicit"; existing: undefined | { ok: true; sessionId: string; } | { ok: false; code: string; message: string; }; } | { stage: "worktree-policy"; reject?: { message: string; }; } | { stage: "worktree-collision-sync"; collisionSessionId?: string; } | { stage: "worktree-collision-async"; collisionSessionId?: string; label: string; cwd: string; }; /** * Resolver for the `config.json` `defaults.identity` knobs (ts#2165 step 5). * * `defaults.identity.sessionTokens`: `"shadow"` (default) mints a per-session * token at spawn, puts it on the session's daemon self-mount and counts, on * the receiving side, how many calls are verified, claim-only, mismatching * or anonymous (`GET /identity`). Nothing is refused. `"enforce"` mints and * delivers exactly like `"shadow"` and also refuses, per request, an invalid * token, a mismatching claim and a claim without token naming a session the * token was delivered to (AIP-46 §Session principals rules 3, 4 and 8). * `"off"`: no mint, no header, no observation, nothing refused. * * Hot, read the same way as `messaging-defaults.ts`: the spawn paths read it * when a session is spawned (so a change applies to sessions spawned after * it), and the HTTP observer reads it per request. */ type SessionTokenMode = "off" | "shadow" | "enforce"; /** * Shared `agent_start` spawn logic — orchestrator scoped sub-gateway * minting, `mcpServers` merge, hermes default-mcpServers safety net, * depth/quota checks. Extracted from `agent-tools.ts` (the MCP tool) * so the HTTP route can reuse it without re-implementing (and * re-drifting from) the same behaviour. */ /** `agent_start.sandbox`'s inline-spec form, plus the PR3 reuse field. See * `SpawnAgentSessionInput.sandbox`. */ type SandboxSpecInput = SandboxSpec & { reuse?: string; }; /** Matches `RegisterAgentToolsOptions.buildOrchestratorMcp` in * agent-tools.ts — kept as its own alias here since that's the shape * actually passed in (opts required), not the more permissive * `OrchestratorInjector` (opts optional) from orchestrator-gateway.ts. */ type BuildOrchestratorMcp = (opts: { tools?: readonly string[]; caller?: OrchestratorScope; maxDepth?: number; maxChildren?: number; role?: string; }) => { entry: AcpMcpServer; bindLifecycle: (sessionId: string) => () => void; /** The minted scope — only `tools` (the effective, narrowed allowlist) * is read here, to tell whether the child can actually reach * `agent_start` through it (see `delegationReachFor`). Optional so * minimal injectors (tests) needn't return it. */ scope?: { tools: ReadonlySet; }; }; interface SpawnAgentSessionDeps { registry: SessionsRegistry; /** Account slot map source for `slot:` access refs. Defaults to * config.json's `accountSlots`; tests inject a stub so they never read the * real file. */ loadAccountSlots?: () => Promise; /** Account health source for slot resolution (an `exhausted` account is * skipped). Defaults to `~/.agentproto/account-health.json`; tests inject a * temp-dir store. */ accountHealth?: AccountHealthStore; /** Required — callers must check for its absence themselves (the MCP * tool and HTTP route each have their own "not enabled" response * shape for the missing-resolver case). */ resolveAgentAdapter: AgentAdapterResolver; /** Installed-adapter lister — ONLY used to enumerate the valid slugs in * the generic `adapter_not_found` error, so a genuinely unknown adapter * name names what IS installed instead of just saying "install it". * Omitted ⇒ the error keeps its previous wording. Mirrors * `CronAdapterCheckDeps.listAgentAdapters` (cron's create-time check). */ listAgentAdapters?: AgentAdapterLister; /** Optional orchestrator-injection builder (WP3). See * `RegisterAgentToolsOptions.buildOrchestratorMcp` for the full * contract. Omitted → `orchestrator` is rejected with * `orchestrator_not_enabled`. */ buildOrchestratorMcp?: BuildOrchestratorMcp; /** The daemon's own plain `/mcp` gateway URL. See * `RegisterAgentToolsOptions.daemonMcpUrl`. */ daemonMcpUrl?: string; /** Calling orchestrator's scope (orchestrator WP4). See * `RegisterAgentToolsOptions.callerScope`. */ callerScope?: OrchestratorScope; /** The session a valid session token on this request was minted for * (AIP-46 §Session principals). Trusted transport data, never a caller * body: the MCP path forwards the verified token's session, the HTTP * spawn routes resolve it from the request header. A `callerScope` is * already proof, so this is only read on the unscoped path. */ callerCredentialSessionId?: string; /** Optional webhook notifier — see `RegisterAgentToolsOptions.webhookNotifier`. */ webhookNotifier?: WebhookNotifier; /** Loads config.json's `defaults` block (global + per-adapter skills/ * options auto-applied at every spawn — see `resolveSpawnDefaults`). * Defaults to reading the real `~/.agentproto/config.json` via * `loadConfig` when omitted; tests inject a stub to avoid touching * the real file. */ loadDefaultsConfig?: () => Promise; /** Loads the workspace command allowlist (`.agentproto/allowed-commands.json`) * for the stdio mount gate; the SAME workspace `command_execute` gates * against. Omitted ⇒ an EMPTY list, so every session stdio mount reads * `would_deny` (conservative). Read per spawn, only when the gate is not * `off` and the request carries at least one stdio mount. */ loadCommandAllowlist?: () => Promise; /** Loads `~/.agentproto/bundles.json` for capability-bundle expansion * (`agent_start.bundles` / config `defaults.bundles`, PLAN D phase 1). * Defaults to the real loader when omitted; tests inject a stub to avoid * touching the real file. */ loadBundlesConfig?: () => Promise; /** Loads `~/.agentproto/imported-mcps.json` — resolves a bundle's * `mcpImports` ids to their alias/snapshot and detects dangling ones. * Defaults to the real loader when omitted; tests inject a stub. */ loadImportedMcpsConfig?: () => Promise; /** Loads `~/.agentproto/imported-skills.json` — resolves a spawn's resolved * skill ids to the imported copies delivered to the child's session config * dir. Defaults to the real loader when omitted; tests inject a stub. */ loadImportedSkillsConfig?: () => Promise; /** Builds the per-session headless-browser mount for `browser: * "headless"` (see `browser-mount.ts`). Defaults to the real resolver * (installs chrome-devtools-mcp on first use); tests inject a stub. */ resolveHeadlessBrowser?: ResolveHeadlessBrowser; /** Loads the custom (pack-carried) role registry, merged with the * two built-ins by `resolveRole`/`canSpawn` — see `role.ts`'s * `mergeRoleRegistry`. Defaults to `loadDefaultRoleRegistry()` * (`~/.agentproto/roles/` + adapter-carried packs) when omitted; * tests inject a stub registry to avoid touching the real * filesystem. */ loadRoleRegistry?: () => Promise>; /** The AIP-72 store at a resolved root, read by the spawn digest. * Defaults to the daemon's shared per-root stores (`memory-stores.ts`); * tests inject a temp-dir store. */ memoryStoreAt?: (root: string) => MemoryStore; /** Resolves an `agent_start.sandbox` slug (or an inline spec's own * `.provider`) to a concrete sandbox provider handle. Required for * `input.sandbox` — omitted ⇒ `sandbox_provider_not_found`. */ resolveSandboxProvider?: SandboxProviderResolver; /** Provision a git worktree and return the cwd the spawn should land in — * the injected port behind `agent_start.worktree` (see * `worktree-isolation.ts`). Wired at the composition root by a host that * depends on `@agentproto/worktree` (the CLI). Omitted ⇒ a spawn the * policy says to isolate fails with `worktree_provisioner_not_enabled` * rather than silently spawning unisolated. */ provisionWorktree?: WorktreeProvisioner; /** Resolves the effective `worktrees.isolation` policy (env > config > * `on-request`). Defaults to reading the real `~/.agentproto/config.json` * via `loadWorktreeIsolation` when omitted; tests inject a stub to pin the * mode without touching the real file or env. */ resolveWorktreeIsolation?: () => Promise; /** Resolves the effective `spawn.attach` policy (env > config > `always`). * Defaults to `loadSpawnAttach` (reads the real config) when omitted; * tests inject a stub to pin the mode without touching env or the file. */ resolveSpawnAttach?: () => Promise; /** Resolves the effective `spawn.dedupe` policy (env > config > `always`). * Defaults to `loadSpawnDedupe` (reads the real config) when omitted; * tests inject a stub to pin the mode without touching env or the file. * See `spawn-dedupe.ts`. */ resolveSpawnDedupe?: () => Promise; /** Parity telemetry hook for the `builtin:spawn-admission` policy. Called * once per evaluated admission stage, including `allow`. A throwing * observer is swallowed and can never change a spawn. */ onSpawnAdmission?: (event: { stage: SpawnAdmissionCheck["stage"]; decision: AdmissionDecision; dedupeSource?: SpawnDedupeSource; label?: string; }) => void; /** Resolves the effective `provenance.wrapGh` opt-in (env > config > * `false`). When it resolves true, a `gh` PATH shim is prepended to the * spawned session's env so any `gh pr create` it (or an adapter * subprocess) runs gets the daemon's provenance footer appended to the * created PR's body — see `gh-provenance-shim.ts`. Defaults to * `loadProvenanceWrapGh` (reads the real config) when omitted; tests * inject a stub to pin it without touching env or the file. */ resolveProvenanceWrapGh?: () => Promise; /** Resolves `defaults.prProvenance.footer.skipRepos` when the `gh` shim is * installed, so a listed repo gets no footer from the shim either. * Defaults to `loadFooterSkipRepos` (reads the real config); tests inject * a stub. */ resolveFooterSkipRepos?: () => Promise; /** Resolves + shapes the AGENTS.md for a spawn's `cwd` (see * `agents-md.ts`): inline / pointer / absent, plus the standing cd-contract * line. Defaults to the real resolver over `loadAgentsMdInlineMaxKb`'s * config-derived threshold when omitted; tests inject a stub to avoid * touching the filesystem, git, and the real config on every spawn. */ resolveAgentsMd?: (cwd: string, inlineMaxKb?: number, opts?: { stopAt?: string; }) => Promise; /** Resolves + shapes the per-workspace RULES.md for a spawn (see * `workspace-rules.ts`): the path of the workspace's `RULES.md`, inlined * in full when present, absent otherwise. Injected into EVERY spawn in * the workspace (root and nested — no depth gate). Defaults to the real * resolver over the workspace state bucket when omitted; tests inject a * stub to avoid touching the real `~/.agentproto` directory. */ resolveWorkspaceRules?: (slug: string | undefined) => Promise; /** Feeds the adapter-capability spawn guard (`checkModelAdapterEligibility`) * — the SAME `listCatalogModels` the `catalog_models` MCP tool / * `GET /catalog/models` route already use (`RegisterAgentToolsOptions. * listCatalogModels`), reused here rather than re-derived. Omitted ⇒ the * guard is skipped — a spawn that would 404 upstream on an adapter's * manifest not covering the requested model still reaches the driver, * same as before this guard existed. */ listCatalogModels?: CatalogModelsLister; /** Ensure the local `llm-endpoint` proxy sidecar (`LlmEndpointRegistry`) * is up before a spawn that bills through it. Without this hook, a spawn * whose resolved gateway is `"llm-endpoint"` assumed the sidecar was * already running (started externally, or via the `llm_endpoint_start` * MCP tool) — a fresh install with `features.llmEndpoint` on but nothing * having called that tool yet would spawn fine and only fail once the * adapter made its first request. Wired to the registry's own * (idempotent) `start()` at the composition root; omitted ⇒ unchanged * pre-existing behavior. Best-effort: a rejection here is swallowed by * the caller, not surfaced as a spawn failure — the adapter's own first * request is left to report the real connection error. */ ensureLlmEndpointRunning?: () => Promise; /** Probe a paired device's own shared inference endpoint for a model — * the device-qualified leg of `agent_start.inference` (DEVICES-PLAN item * 2). Wired at the composition root to `HostRegistry.forwardHttp` against * `/devices/:id/exec-stream/device-inference/v1/models`. Omitted ⇒ a * device-qualified `inference` reference fails fast with a clear * "no device probe wired" error instead of hanging. */ probeDeviceInference?: (device: string, modelId: string) => Promise; } interface SpawnAgentSessionInput { /** The session this spawn replaces (a continue-fresh): the new row takes over * its slug and the replaced row gives it up. See `SpawnAgentInput.replaces`. * Internal: not part of the `agent_start` tool schema. */ replaces?: string; adapter: string; /** Canonical harness slug — recorded on the descriptor; defaults to `adapter`. */ harness?: string; /** Managed cloud vendor slug (AIP-66). Set ⇒ this spawn resolves to the * vendor's cloud adapter (`cloud:"anthropic"` ⇒ adapter * `claude-code-cloud`, harness `claude-code`) BEFORE inference/preset/ * worktree/sandbox/auth/profile resolution, and the vendor's session * identity is persisted as `meta.cloud = { vendor, sessionId, url }`. * Mutually exclusive with `sandbox`; the §4 fields it can never apply * (worktree, commandSandbox, mcpServers, daemonMount, bundles, browser, * appServe, inference) are refused by name — see cloud-vendors.ts. */ cloud?: string; cwd?: string; workspaceSlug?: string; /** CONTROLLER-side marker (issue #1647): set ONLY by the device-sandbox * proxy path when the controller dials the TARGET daemon's own * `agent_start` through the `/device-spawn` bridge (the bridge carries * no ambient marker paths — the controller-side spawn already knows * which spawns cross a device). On the TARGET daemon this marks the * spawn as arriving "through the bridge", so an unresolvable * `workspaceSlug` there fails loudly with the slug + the target's known * slugs instead of silently falling through to the active workspace. * NEVER set (never expose) on a local spawn — local fallback semantics * are deliberately unchanged. Stripped by the controller before the * inner `agent_start` call (the target's own schema has no such field; * an unknown extra key there would 400 an otherwise-fine spawn). Controller * input arriving with this field is consumed immediately (read + delete, * never an error) so it can't leak into spawn defaults or the registry. */ deviceBridge?: boolean; /** Trusted-loopback parent-lineage hint (WP-R1). Attributes this spawn to a * logical parent session so it nests under that node in the sessions tree, * filling the gap that otherwise leaves an anonymous `agent_start` (an * agent-to-agent spawn on the root `/mcp`, or a caller that IS a session but * didn't come through the scoped orchestrator gateway) a depth-0 orphan. * * Trust boundary: the scoped `/mcp/orchestrator` gateway derives parent from * its unspoofable scope token, so a hint arriving WITH a `callerScope` is * IGNORED — the scope always wins. The hint is honoured ONLY on the * anonymous root path (no `callerScope`), where there is no scope to * attribute from. `depth` is derived from the resolved parent descriptor * (parent's `depth + 1`, defaulting to 1 when the parent isn't registered) * rather than trusted from the caller. Descriptor-only: a hint never relaxes * the depth-gated worktree/role guards — declaring a logical parent is not * the same as being a nested (scoped) spawn. */ parentSessionId?: string; /** Daemon-internal: force the new descriptor to record * {@link SessionDescriptor.detached} without deriving it from the attach * policy. Used by continue-fresh to carry a detached predecessor's status * forward while STILL passing its `parentSessionId` (lineage must survive; * `attach: false` would drop the parent). OR-ed with * `attachDecision.detached` at the two descriptor literals below — internal, * not part of the `agent_start` tool schema. */ detached?: boolean; /** Daemon-internal: the call carried no caller identity and * `mcp.noCallerIdentity` let it through. Stamped as `meta.anonymous`; it * grants nothing (no ACL elevation). Set by `agent_start`, never by input. */ anonymousCaller?: boolean; /** Attach policy override for THIS spawn (`agent_start.attach`). `false` * forces an independent root even when a parent is derivable; `true` opts * in to attaching under the derived parent even under an `on-request` * policy; `{ parent }` pins an explicit parent. Omitted ⇒ the daemon's * `spawn.attach` policy decides. Resolved together with `parentSessionId` * and `autoParentSessionId` in `decideSpawnAttach` — see `spawn-attach.ts`. * Ignored WITH a `callerScope` (the scoped orchestrator token always wins). */ attach?: AttachField; /** Daemon-DERIVED caller session id — the spawning session's own id, read * from the trusted `?callerSessionId=` query the self-ref `mcpServers` URL * carries (PR 7 / Gap 7), NOT from the caller's arguments. This is the * implicit auto-parent that makes attach-by-default work without the caller * passing its own id. Threaded from `registerAgentTools`' `callerSessionId` * option; lower precedence than an explicit `parentSessionId` hint. */ autoParentSessionId?: string; /** Task-board pin for the spawned child, stamped onto its descriptor as * `meta.boardId`. The Task ledger's board resolution prefers this over * the `parentSessionId` lineage walk (see task-ledger.ts's * `resolveBoardId`), so a client spawning several depth-0 roots — a * cowork/operator harness fanning out executors with no shared lineage — * can join them all onto ONE board. Descriptor-only: it never enters the * depth/quota/role gates, and an explicit `boardId` on a task verb still * wins over it. */ boardId?: string; /** Workflow ownership of this spawn, stamped onto the descriptor as * `meta.workflowRunId` / `workflowId` / `workflowStepId` — the same keys a * `wf:*` agent-step session carries, so reports and session outcomes link * the session to its run and step. Descriptor-only: no gate reads it. */ workflowOwner?: { runId: string; workflowId: string; stepId: string; }; /** Source label for this spawn (channel/harness). Descriptor-only. */ origin?: string; /** Installed app id this spawn runs on behalf of (`app_run` sets this to * the app's own id). Forwarded to the child process as `APP_ID_ENV` — a * daemon-tool proxy the child builds (mastra-agent's `daemon-mcp-tools.ts`, * P7) auto-injects it into an `app_*` tool call that omits `appId`, since * the model driving the session has no way to know its own appId unless * told. Absent on a spawn made outside `app_run`. */ appId?: string; /** AIP-42 manifest by logical id: resolve `/.agents//AGENT.md` * and apply its prompt/persona/model/skills/tools as spawn DEFAULTS (a * caller-supplied field always wins). The by-id twin of `agentPath`; when * both are set, `agentPath` wins. See `spawn-agent-manifest.ts`. */ agentId?: string; /** AIP-42 manifest by explicit AGENT.md path (absolute, or relative to the * resolved cwd). Same default-filling semantics as `agentId`. */ agentPath?: string; /** ONE agent reference: an AGENT.md path, an agent id, or a role name. * Resolved by `resolveAgentRef` (agent-ref.ts) into `agentId`/`agentPath`/ * `role`, which keep working as aliases. */ agent?: string; /** A manifest identity already frozen on a prior session (continue-fresh): * its `meta` identity keys (`carryAgentIdentityMeta`), AGENT.md opt-in and * deny grants, recorded and staged as-is instead of re-reading the * manifest. Ignored when `agentId`/`agentPath` resolves a manifest. Daemon- * internal: never filled from a request body. */ carriedAgentIdentity?: { meta: Readonly>; exposedToolOptIn?: readonly string[]; toolDenyGrants?: readonly Grant[]; }; /** AIP-46 operator binding: `operator:[@/]` or * `ws://operators/`. Validated for form here (the daemon has no * operator resolver) and recorded on the descriptor in its compact form. * Never inherited from a calling session. */ operator?: string; /** The composing host's digest of the operator body it resolved; recorded * beside `operator` so a later read can flag a drifted operator. */ operatorDigest?: string; /** The session making this call, derived by the daemon from the transport * (MCP caller scope, HTTP caller header), NEVER from a request body. Absent * means the host. Gates who may name an operator (AIP-46 rule 4). */ callerSessionId?: string; /** * Filesystem boundary for this spawn (see `app-boundary.ts`): app source * read-only, run workspace + data dir writable, the rest denied. Set by * `app_run` and by app-workflow agent steps; a child spawned by an * already-boundaried session inherits its parent's boundary instead (this * field cannot widen it). Makes the spawn: refuse `worktree`, resolve * AGENTS.md no higher than the boundary root, isolate host CLAUDE.md, and * either confine the harness's native tools through the OS sandbox or * warn / refuse (`boundaries.enforce: "required"`) — never silently * downgrade. */ appBoundary?: AppBoundary; /** Reattach to a pre-existing adapter-native session (claude-code's * conversation id, hermes' chat handle, …) instead of starting * blank. Accepts a raw adapter conversation id (the HTTP * `sessions restart` / `POST /sessions` route) OR a session id on * THIS daemon (the box re-attach path passes the prior in-box * session id — resolved to that row's conversation + isolated * config dir; see `agent-start-schema.ts` `resumeSessionId`). */ resumeSessionId?: string; /** The caller's initial ask — a plain string (the common case, composed * with the role/AGENTS.md/RULES.md preamble below into one string turn), * or a content block / block array (an attachment-bearing first message, * same loose shape `POST /sessions/:id/prompt` accepts). The block form * is a narrow path: composing daemon-synthesized preamble TEXT onto a * turn that opens with an image isn't meaningful string concatenation, * so it SKIPS the whole preamble composition below (role disposition, * AGENTS.md, RULES.md, parent-lineage line, posture-as-prompt fallback) * and is sent to the adapter verbatim — see `effectivePrompt`'s doc. * Acceptable because this path is human/UI-initiated (an attachment * typed into a chat composer), not the orchestrator-driven role spawns * that actually depend on the composed disposition text. */ prompt?: string | Record | unknown[]; label?: string; /** Explicit session title (SPEC-3 FIX C, `agentproto sessions start * --title`). When set, it wins over the first-sentence derivation from * `prompt` — so a CLI-named session isn't limited to whatever its opening * prompt happened to say. Unlike `label`, it fills the `title` slot, so a * spawner `label` still out-ranks it in the display chain. */ title?: string; mode?: string; /** Manifest-declared option id → value map (AIP-45 `options`), applied * at spawn time alongside `mode`. Forwarded verbatim to the driver's * `startSession({ options })` → `composeSpawn`'s option patches. */ options?: Record; /** Normalized, adapter-agnostic skill ids for this session. Merged with * config.json's `defaults.skills` / `defaults.adapters..skills` * (global < per-adapter < this field, which REPLACES the union rather * than merging into it when provided — a deliberate exact set). Folded * into `options.skills` per the resolved adapter's declared `skills` * option shape (e.g. hermes' comma-joined string); adapters with no * such option (e.g. claude-code, which auto-discovers skills) ignore * it. See `resolveSpawnDefaults` / `normalizeSkillsOption`. */ skills?: string[]; /** Capability bundle ids (`bundle_list`) to attach (PLAN D phase 1). Merged * with config.json's `defaults.bundles` / `defaults.adapters..bundles` * with the same precedence/replace semantics as `skills` — see * `resolveBundleDefaults`. Each bundle expands to its `mcpImports` (mounted * as native MCP servers via the daemon's `/mcp/imported/` passthrough, * never the two-step `mcp_imported_*` indirection), optionally the * daemon's own `/mcp` (`includeDaemon`), and its `skills` (unioned into * the resolved skill list). Ignored (with a warning) for a sandbox spawn — * the box cannot reach this daemon's loopback `/mcp`. */ bundles?: string[]; /** Explicitly mount the daemon's own scoped `/mcp` for this spawn -- * mainly useful for sandbox spawns or after an `mcpServers: []` opt-out, * since the universal on-host default now covers all adapters. Merged * with config's `defaults.adapters..daemonMount` (per-spawn wins). * Ignored (with a warning) for a sandbox spawn. */ daemonMount?: boolean; model?: string; effort?: string; /** Decomposed route identity. This is canonical transport; `mode` remains * a legacy adapter projection only. */ route?: RouteSpec; /** Named billing credential. `profileRefs` (ordered) supersedes `profileRef`; * the runtime bills the FIRST profile eligible for the model's route. * Resolved from auth-profiles + keychain at the final spawn boundary; the * secret never crosses HTTP/MCP. */ access?: { profileRef?: string; profileRefs?: string[]; delegateProfileRefs?: string[]; }; /** Bind this spawn to a local/LAN inference endpoint — resolved (and fit- * checked) at the very top of `spawnAgentSession`, BEFORE preset * expansion, into ordinary `model`/`route`/`access`/`auth`/`deferredTools` * values the rest of this function already understands. Mutually * exclusive with those fields — see `resolveInferenceBindingInput`. */ inference?: InferenceBindingRequest; posture?: Posture; contextProfile?: ContextProfile; /** A preloaded user preset. Callers resolve its id at their boundary so a * preset can also provide the adapter before this core is invoked. */ preset?: UserPreset; /** The full user preset store, so this core can also apply the harness's * `defaultFor` preset and a named preset's `extends` chain. Callers that * only pass `preset` keep working (the chain is then just that preset). */ sessionPresets?: readonly UserPreset[]; /** * Deterministic billing-auth mode + EXPLICIT credential for adapters that * declare it (an `authSubscription` login and/or an API-key `provider` * in their manifest — see `AdapterAuthDescriptor`). `mode` wins over * `~/.agentproto/config.json`'s `defaults.adapters..auth.mode` * (default `"subscription"`); the credential (`token` for `"subscription"`, * `apiKey` for `"api-key"`) wins over the config field matching the * RESOLVED mode — see `resolveSpawnDefaults`. Never read from the ambient * shell env; never logged (only a fingerprint is recorded on the session * descriptor — see `credentialFingerprint`). Adapters that don't declare * the vocabulary ignore this field entirely. */ auth?: DefaultsAdapterAuthConfig; mcpServers?: AcpMcpServer[]; /** Scope the daemon self-mount to exactly these tool names * (`?allowTools=`, deferred loading off so nothing hides behind * `tool_search`) and mount it for ANY adapter — an AIP-42 agent's * declared `tools` (`app_run`, see `agent-projection.ts`), the same * scoping a workflow agent step gets (`agentStepMcpServers`). Ignored * (with a warning) when the caller supplied its own `mcpServers` or for * a sandbox spawn. Not on the `agent_start` MCP schema. */ allowTools?: string[]; /** Caller-computed warnings about what this harness cannot honour (an * AIP-42 manifest projected onto it — `agent-projection.ts`). Emitted as * a `session:harness-warning` with the spawn's own boundary warnings and * returned in the result's `warnings`. */ harnessWarnings?: string[]; /** Extra system-prompt text for this session (the AIP-42 AGENT.md body, * when the resolved adapter declares a real system-prompt channel — * `ResolvedAgentAdapter.supportsSystemPrompt`). Delivered through * `startSession({ appendSystemPrompt })` → the driver's declared channel; * a sandbox spawn or an adapter with no channel falls back to a * first-prompt prefix + harness warning right here (never-silent, same * rule as `allowTools`). Persisted on the descriptor so restart / * fresh-continuation can re-apply it. */ appendSystemPrompt?: string; orchestrator?: boolean | { tools?: string[]; maxDepth?: number; maxChildren?: number; }; notifyUrl?: string; notifySecret?: string; wait?: boolean; maxCostUsd?: number; /** Windowed cost-budget cap (phase 4). DISTINCT from the scalar `maxCostUsd` * session-kill: this is recorded on the descriptor/runtime and drives an * auto-attached governance policy (`policy:failed` on windowed overage) — it * never kills the session. Omit ⇒ no windowed budget. */ costBudget?: CostBudget; /** Opt-in auto-restart policy (restart-scheduler, PR-2). When set, an * unexpected death (`crashed` and/or `error`, per `restartPolicy.on`) is * proactively revived in place — EXCEPT a box session whose box is gone * (`"sandbox-gone"` in `on`), which moves to a fresh box instead; see * `RestartPolicy`'s doc in `sessions.ts`. Omitted ⇒ today's * lazy-resume-only behaviour (or the `daemon.sandboxGoneRestartDefault` * box-session default, when that's on). */ restartPolicy?: RestartPolicy; /** Opt-in turn-retry policy (`turn-retry.ts`): re-prompt the live session * when a turn fails on a transient provider error. Defaults are filled * here (`resolveTurnRetryPolicy`) before it lands on the descriptor. * Omitted ⇒ no automatic retry. */ turnRetry?: TurnRetryInput; /** User-set model policy: model-list ids this session may (`allow`) or may * not (`block`) use. Absent ⇒ any model the account allows. Enforced at * spawn (effective model, adapter default included), `setModel`, restart * and every `turnRetry.rotate` target; persisted on the descriptor. */ modelPolicy?: ModelPolicy; /** AIP-68 clerk hook configuration - the AGENT level of the three-level * resolution (agent > workspace > daemon default). Either the * `agent_start.hooks.clerk` option or the agent manifest's * `metadata.hooks.clerk`; the explicit option wins over the manifest. * Resolved here and recorded on the descriptor (`clerkHook`). */ hooks?: { clerk?: Partial; }; /** Context-continuity policy for this session — controls warning, * opportunistic compaction, fresh-continuation, and hard-stop thresholds. * Resolved from global → per-adapter → per-model → explicit override, * key by key. */ contextContinuity?: ContextContinuityPolicy; /** The AIP-46 name of the same block; layered per setting over the adapter * and daemon blocks and wins over `contextContinuity` key by key. */ contextSettings?: ContextSettings; /** Spawn-time role — `"executor"` | `"supervisor"` | omitted. See * `resolveRole` in `role.ts`. Omitted ⇒ derived from spawn depth * against `defaults.defaultRoleDepthCutoff` (default 1). A resolved * role with `toolPolicy.delegation === "deny"` is a HARD gate: * `orchestrator` is ignored outright and the hermes/default * full-gateway injection excludes `DELEGATION_TOOL_NAMES` — neither * this field's own request nor `promptAppend` can re-open it. */ role?: string; /** One-off runtime text layered ON TOP of the resolved role's * disposition (never replacing it) and prepended to `prompt`. See * `composeRoleContext`. Cannot widen `toolPolicy` — see `role` above. */ promptAppend?: string; /** Per-spawn override for the daemon self-mount's deferred/lazy * `tools/list` loading (harness-parity item 3 — see `deferred-tools.ts`). * Wins over a harness with native tool search (manifest * `capabilities.nativeToolSearch` ⇒ eager), a harness that cannot call a * tool omitted from its last `tools/list` (manifest * `capabilities.deferredToolDiscovery` absent/false ⇒ eager), and the * resolved role's own default (`RoleProfile.deferredTools` — on for * `executor`), which only apply when this is omitted * (`resolveSpawnDeferredTools`). Threaded onto the injected `mcpServers` * self-mount ref as `?deferred=1|0` (`shouldInjectDaemonSelfMount` path * below); has no effect on a caller-supplied `mcpServers` (that URL is * the caller's to compose). Omitted entirely ⇒ no override at all — the * gateway's own boot-time `defaults.mcp.deferredTools` default applies * unchanged, unless the harness lacks `deferredToolDiscovery`. */ deferredTools?: boolean; /** Give the agent its own isolated headless Chrome: a per-session * chrome-devtools-mcp stdio server appended to `mcpServers` (named * `browser`), plus a short prompt hint naming its tools. Wins over the * resolved role's `browser`, then the user preset's, then config * `defaults.spawn.browser`; all unset ⇒ off. Explicit `true` with a * `sandbox` spawn is rejected (no Chrome in the box image yet). */ browser?: SpawnBrowserMode; /** Opt this session into Langfuse tracing (prompt/completion + tool spans + * tokens/cost). Effective opt-in is `trace ?? langfuseTracingDefault ?? false` * — see `SpawnAgentInput.trace` in sessions.ts. */ trace?: boolean; /** Run this session inside a sandbox instead of on the host — a provider * slug from `list_sandbox_providers` (e.g. `"local"`, `"e2b"`), or an * inline AIP-36 `SandboxSpec`, optionally carrying `reuse: ""` * to reconnect to an existing box instead of booting fresh. When set, * this branch resolves the provider, boots (or reconnects) the box, * spawns `adapter` on the BOX's own `agent_start`, and wires a * `SandboxAgentSessionProxy` in place of the local `resolveAgentAdapter` * path — see `sandbox-agent-session-proxy.ts`. */ sandbox?: string | SandboxSpecInput; /** Per-spawn override of the sandbox checkpoint safety net (`sandbox- * delivery.ts`'s `resolveSandboxCheckpointConfig`) — `false` disables it * entirely for THIS spawn; an object overrides individual knobs * (`enabled`/`on`/`refPrefix`/`minIntervalMs`/`timeoutMs`) over the global * `defaults.sandbox.checkpoint`. Meaningful only for a `sandbox` spawn * with a workspace-remote delivery target; ignored otherwise. */ sandboxCheckpoint?: SandboxCheckpointConfig | false; /** Preflight probe ids (`sandbox-preflight.ts`) run against the booted box * BEFORE the agent starts, in order. A `ko` destroys the box and fails the * spawn with `sandbox_preflight_failed`; `unknown` never blocks. Only * meaningful with `sandbox`; an id with no registered probe is refused * (`sandbox_preflight_invalid`) before any box boots. */ preflight?: string[]; /** Budget, ms, for the box's own `agent_start` (the adapter spawn on the * booted box). Unset keeps the harness client's 5 minute request timeout. * Set per placement rung (`placement.ladder[].agentStartTimeoutMs`) so a * box that accepted the workspace but never starts the adapter costs the * ladder that budget instead of 5 minutes; an expiry fails the rung with * `sandbox_proxy_failed` (`details.errorClass: "sandbox_agent_start_timeout"`) * and tears the box down. Only meaningful with `sandbox`. */ agentStartTimeoutMs?: number; /** INTERNAL (the placement ladder sets it, never an `agent_start` argument): * this spawn is a non-final ladder rung, so a provider that would wait out a * capacity refusal gives up at once (no retry hint) or waits once, at most * this many ms, and lets the ladder move on. Unset keeps the provider's own * wait: a plain `sandbox` spawn and the last rung. */ ladderCapacityWaitBudgetMs?: number; /** Ordered placement ladder: rung 1 is tried first and the spawn moves down * the list when a rung cannot place the box (failed preflight, capacity or * overflow refusal, egress pool exhausted, any boot failure before the * agent started). Each rung is a `sandbox` plus optional `model` / `access` * / `preflight` / `turnRetry` overrides; omitted axes inherit this input's * own. Mutually exclusive with a top-level `sandbox` (`placement_invalid`). * Once the agent started the ladder never moves the session: that is * `turnRetry`'s job. The attempts land on the descriptor's `placement`. */ placement?: PlacementInput; /** INTERNAL (`session_migrate`, never an `agent_start` argument): which * checkpoint snapshot the new box restores onto the work branch's * checkout. Default `"any"` — see `CheckpointRestoreSnapshot`. */ sandboxCheckpointRestore?: CheckpointRestoreSnapshot; /** CRASH RESUME - link this spawn to the DEAD session whose work it * continues: `{ sessionId }` names the session explicitly, `{ label }` * (or `{ taskId }`) correlates with the dead sessions carrying that * label. The dead session's last checkpoint (the ref its snapshot was * pushed to) is restored onto this spawn's checkout with * `git restore --source=`, and the dead session's work branch is * reused so its pushed commits come back as commits. A live session is * never resumed. Absent ⇒ no resume, the spawn starts from its base * branch. */ resumeFrom?: { sessionId?: string; label?: string; taskId?: string; }; /** WP3 — serve an agentproto app's UI from INSIDE the sandbox box and * return its public URL on the descriptor + result. Requires `sandbox` * (a non-sandbox spawn carrying `appServe` is rejected): the app dir is * resolved INSIDE the box (e.g. `/home/user/apps/` on the * workstation image), installed via the box daemon's `app_install`, and * `agentproto app serve --host 0.0.0.0 --port ` is launched * detached through the box's `command_execute`. The port is appended to * the spec's `extraPorts` so the provider resolves its public URL (also * stamped into `sandboxPorts`), and the serve result lands on the * descriptor's `appServe` field. See `sandbox-app-serve.ts`. */ appServe?: SandboxAppServeSpec; /** Isolate this session into its own git worktree instead of spawning in * `cwd` directly. `true` provisions a worktree with an auto-minted branch/ * slug; `{ slug?, base? }` pins the slug and/or the base ref it's cut from. * Honoured only at spawn depth 0 (a nested spawn inherits the parent's * ground) and only for a `cwd` inside a git repo (nothing to isolate * otherwise ⇒ spawns plain). The daemon's `worktrees.isolation` policy can * force this on (`always`) or off (`never`) regardless — see * `worktree-isolation.ts`. Ignored entirely for a `sandbox` spawn (the box * already isolates). Cleanup is the human's job (`agentproto worktree * rm|archive|gc`); the tree is never auto-removed on session exit. */ worktree?: WorktreeField; /** Acknowledge that spawning IN PLACE into a shared, dirty working tree is * intended, silencing the `sharedDirtyCwd` warning a nested implicit spawn * would otherwise emit (see `decideWorktreeIsolation`). Only meaningful for * a nested (depth > 0) spawn with no `worktree` request and no `sandbox`; * ignored everywhere else. Default false — the warning fires. */ allowSharedCwd?: boolean; /** Start this session in permission-hold mode: every ACP permission request * is surfaced + parked in the cross-session inbox (`permissions_list` / * `permissions_respond`) instead of auto-answered. Threaded to the driver's * `startSession({ permissionHold })` and recorded on the descriptor. Ignored * for sandbox spawns (the box's own daemon owns permission handling). * Default false — unchanged auto-answer behaviour. */ permissionHold?: boolean; /** Opt this child into the direct in-band crash notification: when it * crashes (`markCrashed`), the supervisor-notify subscriber * (`supervisor-notify.ts`) delivers a `[child-crashed] …` notice into its * `parentSessionId`, if any — enqueued immediately when the parent is * alive and idle, queued for its next turn when busy (never * interrupted). Recorded verbatim onto {@link SessionDescriptor * .notifyParentOnCrash}; see that field's doc. Default true for an * `executor` that has a declared or attached parent, false otherwise; * an explicit `false` always opts out. The free external webhook path * (`notifyUrl`) fires regardless of this flag. */ notifyParentOnCrash?: boolean; /** A REMOTE parent (host relay) forwarded by the host into a BOX daemon's * `agent_start`: the parent session lives in the HOST daemon's registry, * so the box row records it as `remoteParent` instead of * `parentSessionId` and `message_parent` relays the report to the host * (see `parent-relay.ts` and `docs/lineage-handover.md`). Recorded * verbatim onto {@link SessionDescriptor.remoteParent}. */ remoteParent?: { sessionId: string; url: string; token: string; }; /** A CREDENTIAL relay forwarded by the host into a BOX daemon's * `agent_start` (see `credential-relay.ts`): where this session's nested * spawns ask the HOST to resolve a profile the box does not hold. The * token is kept in memory only, never on a descriptor. */ credentialRelay?: { url: string; token: string; }; /** Per-spawn opt-out of sentinel auto-link (AIP-60 §6/step 4): `false` * means a PR this session opens is never auto-watched, regardless of * `config.sentinel.autoWatchPrs`. Recorded verbatim onto * {@link SessionDescriptor.sentinelAutoWatch}; `undefined`/`true` = allowed * (still gated by the config default). */ sentinel?: boolean; /** Exempt this session from the idle-reaper (`isReapable` in * idle-reaper.ts) regardless of how long it sits idle. Stamped straight * onto the descriptor — see `SessionDescriptor.keepAlive`. Default false * — unchanged reap-eligible behaviour. Toggleable later via the * `session_set_keepalive` MCP verb. */ keepAlive?: boolean; /** Caller-declared "this is the same logical spawn" token — a PROMISE, not * a guess. A second `agent_start` with the same `(adapter, cwd, * idempotencyKey)` within `SPAWN_CLAIM_WINDOW_MS` of a SUCCESSFUL spawn * returns that spawn's descriptor instead of forking a second process — * the fix for a retried call otherwise silently duplicating a live * agent. Always wins over the daemon's own derived (implicit) key when * both would apply — see `dedupe` and `spawn-dedupe.ts`. Omitting this * does NOT mean "spawn unconditionally" anymore: when the daemon's * `spawn.dedupe` policy is `"always"` (the default) and this spawn * carries a `label`, the daemon derives an implicit key in its place — * see `dedupe` below to opt out per-call. */ idempotencyKey?: string; /** Per-call override for the daemon's `spawn.dedupe` policy (implicit * dedupe when no `idempotencyKey` was supplied — see `spawn-dedupe.ts`). * `false` is the escape hatch: never derive an implicit key for THIS * spawn, regardless of policy — mirrors `attach: false` / `worktree: * false`. `true` forces derivation even under an `"on-request"` policy, * mirroring `attach: true`. Omitted ⇒ the policy mode decides. Has no * effect when an explicit `idempotencyKey` is supplied (it already wins * outright) or when this spawn carries no `label` (nothing to derive * from either way). */ dedupe?: boolean; /** * OS-level confinement for the adapter's OWN spawned process * (`@agentproto/command-sandbox` — macOS Seatbelt / Linux bubblewrap), * threaded verbatim to `resolved.startSession({ commandSandbox })` → * `AgentCliRuntime.start`. NOT the AIP-36 `sandbox` field above — that * boots a whole nested daemon on a different machine/box (remote-box * session provider); this wraps THIS host's spawn argv so the adapter's * own process tree can't read/write outside `cwd` (and, `"strict"`, * reach the network), confinement an ACP permission seam can never see * since it only covers tool calls the adapter chooses to report. Exposed * on the `agent_start` MCP tool schema (`agent-tools.ts`) as of PR 6b — * when omitted here, the driver falls back to the workspace's * `.agentproto/command-sandbox.json` `adapterSpawn` key (a key distinct * from the top-level `mode` that same file also carries for * `command_execute` — see `@agentproto/command-sandbox`'s module doc for * why the two axes are never shared), or stays unconfined if that's unset * too. Ignored for a `sandbox` spawn (the box's own daemon would need to * apply this itself). */ commandSandbox?: SandboxMode; } /** * Shared kernel for the daemon's worktree-status query surface. * * The heavy join itself (`listWorktreeStatuses`) lives in * `@agentproto/worktree`, a dependency the runtime deliberately does NOT take * (see `worktree-isolation.ts`). So the runtime only defines: * - the VSCode-friendly view type * - the pure projection from a raw `WorktreeStatusEntry`-shaped object * - workspace→repo-root resolution for tool/route inputs * - the injected `WorktreeStatusLister` port * * The CLI host wires the real lister (it has access to both * `@agentproto/worktree` and this module's `toWorktreeStatusView`). */ /** Trimmed, VSCode-friendly projection of one worktree status. */ interface WorktreeStatusView { path: string; branch: string | null; class: "reclaim" | "salvage" | "hold"; reclaimable: boolean; /** Uncommitted work in the tree (modified, staged or untracked paths). */ dirty: boolean; /** Per-kind counts, present only when `dirty`. */ changes?: { modified: number; staged: number; untracked: number; }; /** Ahead/behind vs the base ref the integration check compares against * (the repo's default branch, e.g. `origin/main`). `null` for a detached * tip or when git couldn't resolve the base. */ base: null | { ref: string; ahead: number; behind: number; }; /** Integration state; `number` whenever the forge matched a PR (open, * merged, partial), `url` when the host knows the forge's web URL. */ pr: null | { state: string; number?: number; url?: string; }; sessions: Array<{ id: string; adapterSlug?: string; model?: string; status: string; startedAt: string; }>; liveness: { state: string; sessionCount: number; }; } /** Narrows a lister call. `paths` computes only those worktrees (compared * resolved) instead of every worktree of the repo: one forge round-trip for * a per-session lookup, not one per worktree. */ interface WorktreeStatusListOptions { paths?: readonly string[]; } /** Injected port: the runtime asks the host to list worktrees for a repo. */ type WorktreeStatusLister = (repoRoot: string, options?: WorktreeStatusListOptions) => Promise; interface ToWorktreeStatusViewOptions { /** Web URL of PR `number` on this repo's forge, when the host can build * one (e.g. from a GitHub `origin` remote). */ prUrl?: (number: number) => string | undefined; } /** * Pure projection from a raw `WorktreeStatusEntry` to the view the daemon * surfaces. Kept in one place so the MCP tool and HTTP route cannot drift. */ declare function toWorktreeStatusView(entry: unknown, options?: ToWorktreeStatusViewOptions): WorktreeStatusView; /** * Shared kernel for the daemon's worktree-`gc` surface — the transport twin of * `worktree-status.ts`. The `gc` engine itself (`planGc` / `applyGc`, with all * of its merge-gated-reclaim / open-PR-is-hold / dirty-is-salvage-only safety * layers) lives in `@agentproto/worktree`, a dependency the runtime * deliberately does NOT take (see `worktree-isolation.ts`). So — exactly as the * status surface does — the runtime only defines: * - runtime-local structural result types (the dry-run plan AND the apply * outcomes), so no gc type is imported into the runtime * - the injected `WorktreeGcRunner` port * * The CLI host wires the real runner (it has access to `@agentproto/worktree`). * Repo-root resolution is shared with the status surface via * `resolveWorktreeQueryRoot` in `worktree-status.ts`. */ /** `gc`'s three classes, mirrored runtime-local (matches `GcClass`). */ type WorktreeGcClass = "reclaim" | "salvage" | "hold"; /** * `gc`'s reclaim reasons, mirrored runtime-local (matches `GcReclaimReason`). * `dep-bump` is set on a `reclaim`-class entry/outcome that was promoted out * of `hold` by the dep-bump exemption (`resolveGcClass` in * `@agentproto/worktree`) — absent for an ordinary merged/fresh reclaim, so * its presence alone is the "why does this line have unpushed commits and * still leave" signal a human reading the plan/outcome table needs. * `orphan` is set on an entry/outcome the orphan scan found — a directory * physically present under the repo's worktree pool with no `git worktree * list` entry at all (see `WorktreeGcPlanEntryView.orphan`). * `prunable` is set on an entry/outcome `git worktree list --porcelain` * itself already reported dead — the mirror image of `orphan`: the * registration is still there, but the working directory is gone (see * `WorktreeGcPlanEntryView.prunable`). */ type WorktreeGcReclaimReason = "dep-bump" | "orphan" | "prunable" | "squash-merged" | "patch-merged" | "content-merged" | "dirty-no-work"; /** * One entry of the dry-run plan — a runtime-local projection of a * `GcPlanEntry`. `tree` / `integration` / `liveness` are flattened to their * discriminant `state` (plus the PR number when the integration carries one) * so the runtime never depends on the gc engine's richer state objects. */ interface WorktreeGcPlanEntryView { path: string; branch: string | null; head: string; class: WorktreeGcClass; /** Set only when `class === "reclaim"` via the dep-bump exemption, the orphan scan, or the prunable signal. */ reclaimReason?: WorktreeGcReclaimReason; /** * Set only when `class === "hold"`: WHY it held — `live-session-cwd` * (its path is or contains a live session's cwd) or `recent-activity` * (its own git index was written within the active window, so someone is * working in it right now). The engine's other holds (open PR, dirty tree, * unresolved verdict) leave it absent — those are already explained by the * tree/integration/liveness axes this entry carries. */ holdReason?: string; /** Set only with `reclaimReason: "dirty-no-work"`: the sub-cases that explained the dirt and how many paths removal puts back first. */ dirtyNoWork?: { cases: string[]; paths: number; }; /** * mtime (epoch ms) of the worktree's git index when the plan read it. Echoed * back as part of `WorktreeGcRunInput.expectedPlan` so apply can tell the * worktree changed since the plan. Absent for orphan/prunable entries. */ indexMtimeMs?: number; /** * `true` only for an orphan-scan entry: a directory physically present * under the repo's worktree pool with no `git worktree list` entry at all * (even after a prune). `tree`/`integration`/`liveness` carry no real axis * read for these — git itself can't answer those questions for a * directory it no longer recognizes as a worktree — so they're set to the * literal `"orphan"` placeholder below rather than a fabricated value. */ orphan?: boolean; /** * `true` only for a linked worktree `git worktree list --porcelain` itself * already marked `prunable`. Same reasoning as `orphan` above — no * tree/integration/liveness axis was ever read for a working directory * that's gone — projected as the literal `"prunable"` placeholder below. */ prunable?: boolean; tree: string; integration: { state: string; pr?: number; }; liveness: { state: string; sessionCount: number; }; } /** * One outcome of an apply run — a runtime-local projection of a * `GcApplyOutcome`. Every discriminant `result` the engine can emit is * preserved; the extra fields (`salvageDir`, `from`/`to`, `message`) are * present only for the results that carry them, exactly as the engine's * discriminated union has them. */ interface WorktreeGcOutcomeView { path: string; branch: string | null; result: "reclaimed" | "salvaged" | "held" | "skipped-dirty" | "aborted-reclassified" | "aborted-vanished" | "skipped-stale" | "removed-keep-branch" | "failed"; /** Set only for a `reclaimed` outcome via the dep-bump exemption. */ reclaimReason?: WorktreeGcReclaimReason; /** Set only for `salvaged`. */ salvageDir?: string; /** Set only for `aborted-reclassified`. */ from?: WorktreeGcClass; /** Set only for `aborted-reclassified`. */ to?: WorktreeGcClass; /** * Set when the entry was held (or refused at apply time) because of a * specific hold reason — `live-session-cwd` or `recent-activity` (the * worktree's own git index was written within the active window). */ holdReason?: string; /** Set only for `failed`. */ message?: string; /** Set only for `skipped-stale`: what changed between the plan and the apply (branch, HEAD, or git index). */ reason?: string; } /** * The runner's result — a dry run returns the plan, an apply returns the * outcomes. The `mode` discriminant lets the tool/route render either without * a second call and without importing gc types. */ type WorktreeGcResult = { mode: "plan"; plan: WorktreeGcPlanEntryView[]; } | { mode: "apply"; outcomes: WorktreeGcOutcomeView[]; }; /** Input to the injected runner. `apply` defaults to false at the tool/route * boundary — a bare call is a dry run. */ interface WorktreeGcRunInput { repoRoot: string; apply: boolean; salvageDirty: boolean; includeDetached: boolean; /** * Absolute cwds of every live session the daemon knows about right now — * see `livingSessionCwds` below. Threaded straight to the gc engine's own * `protectedPaths` (`@agentproto/worktree`'s `PlanGcInput`/`ApplyGcOptions`): * a worktree that IS or CONTAINS one of these paths is held, never * reclaimed/salvaged, regardless of what `classify`'s own (snapshot-based) * liveness axis concludes. Optional — a host that can't cheaply enumerate * its own live sessions (or has none, e.g. the bare CLI `worktree gc` * command) omits it and gets exactly today's behavior. */ protectedPaths?: string[]; /** * Worktree-relative paths whose dirt is known noise: a worktree dirty ONLY * on these reads clean (and is removed non-force after they are restored). * Omitted → the engine's default (`.opencode/package-lock.json`); `[]` * disables the allowlist. */ noisePaths?: string[]; /** * Recency window, in minutes, for the engine's recent-activity guard: a * worktree whose own git index mtime is younger than this holds (reason * `recent-activity`) instead of reclaiming/salvaging, at plan time and * again at apply time. Omitted → the engine's default (60); `0` disables * the guard. */ activeMinutes?: number; /** * A plan an earlier call produced (`mode: "plan"`). With `apply`, the runner * applies THIS plan instead of planning afresh, and `applyGc` re-checks each * entry (branch, HEAD, git index mtime, live sessions) against it, skipping * any that changed (`skipped-stale`). Without it, `apply` plans and applies * in one call. */ expectedPlan?: WorktreeGcPlanEntryView[]; /** * The reviewed tier, apply only: `hold`-class worktrees at these paths are * removed WORKTREE ONLY (result `removed-keep-branch`, the branch is kept) * when, re-checked at apply time, they are unchanged since the plan, clean, * idle, with no open PR, and the branch verdict store holds an agreeing * verdict for the exact tip. Any failed check leaves the worktree as * `skipped-stale` with the reason. The branch is left for `branch_gc`'s * reviewed rung and its line-coverage guard. */ reviewedPaths?: string[]; } /** * Injected port: the runtime asks the host to plan (and, when `apply`, execute) * a `gc` sweep for a repo. The host is responsible for resolving `repoRoot` * onto the true git repo root (e.g. via `repoRootOf`), just like the status * lister. */ type WorktreeGcRunner = (input: WorktreeGcRunInput) => Promise; /** * Shared kernel for the daemon's branch-`gc` surface — the sibling of * `worktree-gc.ts`. The engine (`planBranchGc` / `applyBranchGc` / * `recordBranchVerdict`) lives in `@agentproto/worktree`, a dependency the * runtime deliberately does NOT take, so — exactly as the worktree gc surface * does — the runtime only defines runtime-local structural result types and * the injected ports. The CLI host wires the real runners. Repo-root * resolution is shared with the worktree surfaces via * `resolveWorktreeQueryRoot` in `worktree-status.ts`. */ type BranchGcKind = "local" | "remote" | "orphan"; type BranchGcClass = "reclaim" | "review" | "hold"; type BranchGcStatus = "pr-merged" | "forge-mirror" | "merged" | "squash-merged" | "patch-merged" | "content-merged" | "unmerged"; type BranchGcReclaimReason = Exclude | "reviewed" | "checkpoint-superseded"; type BranchGcHoldReason = "protected" | "worktree" | "open-pr" | "pr-check-unavailable" | "young"; type BranchGcTriageVerdict = "obsolete" | "superseded" | "salvage" | "in-progress" | "unclear"; interface BranchGcCoverageView { residual: number; covered: number; ignored: number; evolved: number; unique: number; deletes: number; } /** Share of a tip's added lines already verbatim in base — mirrors `BranchLineCoverage`. */ interface BranchGcLineCoverageView { added: number; inBase: number; pct: number; missing: Array<{ file: string; line: string; }>; /** Every file with an added line not in base. Absent on an older result. */ missingFiles?: string[]; } /** The `dep-bump` pass's proof, mirrors `DepBumpProof`. */ interface BranchGcDepBumpView { dependencies: number; versions: number; lockfileLines: number; changesetLines: number; packageFiles: string[]; goneOnBase?: string[]; } /** The `history-covered` pass's proof, mirrors `HistoryCoveredProof`. */ interface BranchGcHistoryCoveredView { filesChecked: number; linesMatched: number; files: Array<{ file: string; lines: number; oldest: string; newest: string; movedTo?: string[]; }>; } /** The `verified-pr` pass's proof, mirrors `VerifiedPrProof`. */ interface BranchGcVerifiedPrView { prs: number[]; files: Array<{ file: string; why: "pr-touched" | "changeset" | "gone-on-base" | "manifest-proven"; pr?: number; }>; } /** One classified ref — mirrors `BranchGcPlanEntry` structurally. */ interface BranchGcPlanEntryView { kind: BranchGcKind; name: string; ref: string; sha: string; date: string; author: string; subject: string; remote?: string; status: BranchGcStatus; history: "current" | "pre-rewrite" | "unrelated"; ahead: number | null; behind: number | null; conflicts?: boolean; compareBase?: string; mergeBase?: string; mergedTree?: string | null; coverage?: BranchGcCoverageView; residualFiles?: string[]; residualFileCount?: number; lineCoverage?: BranchGcLineCoverageView; /** `git cherry` summary of an unmerged tip: commits with no patch-equivalent on the compare base. */ cherry?: { total: number; unmatched: number; }; ageDays: number; class: BranchGcClass; reclaimReason?: BranchGcReclaimReason; mergedPr?: number; /** How a `pr-merged` tip matched `mergedPr`: its exact head, an ancestor of that head, or patch-equivalent commits. */ mergedPrMatch?: "head" | "ancestor" | "patch"; forgePr?: number; /** The forge's PR for this branch NAME (open, else newest merged, else newest closed unmerged, else `none`); absent when the forge could not answer. */ headPr?: { state: "open" | "merged" | "closed-unmerged" | "none"; number?: number; }; holdReason?: BranchGcHoldReason; holdDetail?: string; pushed?: string; verdict?: { triage: BranchGcTriageVerdict; agree: boolean | null; reviewer: string; operator?: { by: string; note?: string; }; /** The gate's verdict, when the verdict has a gate. Absent on an older result. */ gateVerdict?: BranchGcTriageVerdict; /** The PRs the verdict cites (`landedIn`, else `#N` in the gate): what the `verified-pr` pass checks. Absent on an older result. */ citedPrs?: number[]; /** How many earlier verdicts for this tip the stored one replaced; absent on a first verdict. */ revision?: number; }; /** Why an agreeing verdict was refused (e.g. line coverage under `minLineCoverage`), or that an operator or the `verified-pr` pass got it past that guard. */ verdictGuard?: string; /** Set when the `verified-pr` pass reclaimed a guard-refused verdict. */ verifiedPr?: BranchGcVerifiedPrView; /** Set when the guard refused and the `verified-pr` pass did too: the condition that failed. */ verifiedPrRefusal?: string; /** Set when the `dep-bump` pass reclaimed a guard-refused verdict. */ depBump?: BranchGcDepBumpView; /** Set when the guard, `verified-pr` and `dep-bump` all refused: the first line `dep-bump` could not explain. */ depBumpRefusal?: string; /** Set when the `history-covered` pass reclaimed a guard-refused verdict. */ historyCovered?: BranchGcHistoryCoveredView; /** Set when the `history-covered` pass refused too: the first file or line it could not find in base's history. */ historyRefusal?: string; } interface BranchGcPlanView { repoRoot: string; repoName: string; base: string; baseSha: string; baseTree: string; remote: string | null; anchor: string | null; prCheck: { available: boolean; reason?: string; }; scopes: BranchGcKind[]; minAgeDays: number; includeReviewed: boolean; /** Absent on a result from before the line-coverage guard. */ minLineCoverage?: number; /** true = the `verified-pr` pass was off. Absent on an older result. */ requireOperatorBelowGuard?: boolean; /** `git ls-remote refs/pull//head` for the forge-mirror shortcut. Absent on an older result. */ forgeMirrorCheck?: { available: boolean; reason?: string; }; generatedAt: string; otherRemoteRefs: number; /** true = base-remote `fetch --prune` succeeded; false = failed; null = skipped / no remote. */ fetched: boolean | null; entries: BranchGcPlanEntryView[]; } /** kind → class → count, and kind → (status | "protected") → count. */ interface BranchGcSummaryView { byClass: Record>; byStatus: Record>; /** The same counts keyed by branch name across kinds (a local branch and * its remote twin count once). Absent on a result from before it existed. */ distinct?: { branches: number; refs: number; byClass: Record; byStatus: Record; }; } interface BranchGcOutcomeView { kind: BranchGcKind; name: string; sha: string; result: "deleted" | "held" | "skipped-review" | "refused-guard" | "aborted-moved" | "aborted-vanished" | "aborted-reclassified" | "failed"; reclaimReason?: BranchGcReclaimReason; holdReason?: BranchGcHoldReason; currentSha?: string; from?: BranchGcClass; to?: BranchGcClass; message?: string; /** `refused-guard`: why the agreeing verdict was refused. `deleted`: `"verified-pr"`, `"dep-bump"` or `"history-covered"` when that pass reclaimed it. */ guard?: string; /** `deleted` by the `verified-pr` pass: its proof. */ verifiedPr?: BranchGcVerifiedPrView; /** `refused-guard`: why the `verified-pr` pass refused too. */ verifiedPrRefusal?: string; /** `deleted` by the `dep-bump` pass: its proof. */ depBump?: BranchGcDepBumpView; /** `refused-guard`: why the `dep-bump` pass refused too. */ depBumpRefusal?: string; /** `deleted` by the `history-covered` pass: its proof. */ historyCovered?: BranchGcHistoryCoveredView; /** `refused-guard`: why the `history-covered` pass refused too. */ historyRefusal?: string; } /** Per-scope tally of apply outcomes. `skipped` = everything that was not * deleted and did not fail (held, skipped-review, refused-guard, aborted-*); the exact * per-result counts stay in `byResult`. */ interface BranchGcApplyScopeCounts { deleted: number; skipped: number; failed: number; } interface BranchGcApplySummary { /** `ok` = deletes only, no failures/aborts; `partial` = some deleted but * also failed or aborted; `failed` = failures and nothing deleted; * `noop` = nothing deleted, nothing failed. */ status: "ok" | "partial" | "failed" | "noop"; totals: BranchGcApplyScopeCounts; byScope: Record; byResult: Partial>; restoreLog: string | null; } type BranchGcApplyResult = { mode: "apply"; plan: BranchGcPlanView; summary: BranchGcSummaryView; outcomes: BranchGcOutcomeView[]; /** Restore log written before the first delete; `null` when nothing was deleted. */ restoreLog: string | null; /** Same value as `applySummary.status`, hoisted so a caller can branch on it. */ status?: BranchGcApplySummary["status"]; applySummary?: BranchGcApplySummary; }; type BranchGcResult = { mode: "plan"; plan: BranchGcPlanView; summary: BranchGcSummaryView; } | BranchGcApplyResult; /** Pure: tally an apply result's outcomes per scope. */ declare function summarizeBranchGcApply(result: BranchGcApplyResult): BranchGcApplySummary; /** Attach `status` + `applySummary` to an apply result; a plan passes through. */ declare function withBranchGcApplySummary(result: BranchGcResult): BranchGcResult; /** Input to the injected runner. `apply` defaults to false at the tool/route * boundary — a bare call is a dry run — and an apply requires `scopes`. */ interface BranchGcRunInput { repoRoot: string; apply: boolean; base?: string; scopes?: BranchGcKind[]; minAgeDays?: number; includeReviewed: boolean; /** `includeReviewed` refuses an agreeing verdict below this line coverage (percent). Engine default 95. */ minLineCoverage?: number; /** Turn the `verified-pr` pass off: below the line guard only an operator approval reclaims. Engine default false. */ requireOperatorBelowGuard?: boolean; anchor?: string; } type BranchGcRunner = (input: BranchGcRunInput) => Promise; interface BranchGcVerdictInput { repoRoot: string; /** Validated by the engine (`branchVerdictSchema`) — the runtime only shapes it. */ verdict: unknown; } interface BranchGcVerdictRecordView { repo: string; name: string; sha: string; recordedAt: string; /** How many earlier verdicts for this tip this record replaced; absent on a first verdict. */ revision?: number; triage: { verdict: BranchGcTriageVerdict; confidence: number; reason: string; salvage?: string; }; gate?: { agree: boolean; verdict: BranchGcTriageVerdict; reason: string; evidence: string[]; }; /** The PR(s) a superseded verdict says landed the work. */ landedIn?: Array<{ pr: number; commit?: string; }>; reviewer: string; /** Human operator approval overriding the line-coverage guard for this exact tip. */ operator?: { by: string; note?: string; }; } /** Injected port: validate + store one reviewer verdict, keyed by repo + tip sha. Throws on an invalid verdict. */ type BranchGcVerdictRecorder = (input: BranchGcVerdictInput) => Promise; interface BranchGcVerdictLookupInput { repoRoot: string; /** Full tip sha — the store's key, together with the repo. */ sha: string; } /** Injected port: the stored verdict for this exact tip, or `null` — a read-only * lookup, so a caller can check one tip without re-running a whole `branch_gc` plan. */ type BranchGcVerdictReader = (input: BranchGcVerdictLookupInput) => Promise; interface BranchGcOperatorApprovalInput { repoRoot: string; /** A full tip sha, or a branch name whose current tip has a stored verdict. */ target: string; /** The approving human. Must differ from the stored verdict's reviewer. */ by: string; note?: string; /** Check and report what would be recorded, without writing. */ dryRun?: boolean; } type BranchGcOperatorApprovalResult = { ok: true; status: "recorded" | "would-record" | "already-approved"; target: string; name: string; sha: string; refs: string[]; verdict: Omit; record?: BranchGcVerdictRecordView; } | { ok: false; refusal: "no-ref" | "ambiguous" | "no-verdict" | "not-agreed" | "tip-moved" | "by-is-reviewer"; target: string; message: string; }; /** Injected port behind `POST /branches/gc/approve`: copy the stored verdict * for one tip and add the operator block. The route is the trust boundary; * this port only checks the verdict (stored, agreeing, current tip, `by`). */ type BranchGcOperatorApprover = (input: BranchGcOperatorApprovalInput) => Promise; interface BranchGcRestoreInput { /** Path of a `branch-gc-restore/v1` log written by an apply. */ logPath: string; /** The repo to restore into: the log's own `repoRoot` must be this repo, or the restore refuses. */ repoRoot: string; /** Only entries whose sha equals or starts with one of these. Default every entry. */ shas?: string[]; /** Re-create remote-kind refs as local branches instead of pushing them back. */ localOnly?: boolean; dryRun?: boolean; /** Keep the operator approval of restored tips (default: dropped, so the next run re-judges them). */ keepApproval?: boolean; } /** One re-created (or refused) ref, mirrors `BranchGcRestoreOutcome`. */ interface BranchGcRestoreOutcomeView { kind: BranchGcKind; name: string; sha: string; target: string; result: "restored" | "would-restore" | "already-present" | "contained" | "refused-conflict" | "missing-commit" | "invalid-entry" | "failed"; command?: string; message?: string; approvalRevoked?: boolean; } interface BranchGcRestoreResultView { logPath: string; repoRoot: string; outcomes: BranchGcRestoreOutcomeView[]; unmatched: string[]; } /** Injected port behind `branch_gc_restore`: re-create refs from a restore log. */ type BranchGcRestorer = (input: BranchGcRestoreInput) => Promise; /** * AIP-46 spawn proof gate, counters always on. * * AIP-46 §Session principals has three proof levels: `proven` (the caller * presented a credential: a scoped orchestrator token, or a session token * minted for the session it claims), `claimed` (it only named a session) and * `none` (it named none, which on loopback is the operator, rule 5). Rule 9 * lets a host list actions that require `proven`; a `claimed` caller of a * listed action is refused `identity_unverified`, a caller whose token names * another session than its claim is refused `identity_mismatch`. * * The list is opt-in and defaults empty. Enforcement cannot outrun delivery * (rule 8): a session whose adapter or placement could not carry a token can * never be proven, so listing `session:spawn` would break it. The counters * here let the operator read who would be refused before listing anything. * * 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 * caller id is a session id, never a secret; no token, credential id or hash * ever reaches the log or the report. */ /** Actions whose callers must be `proven`. Only what this build evaluates. */ type RequireProofAction = "session:spawn"; /** Deps for the `/sentinels/*` HTTP routes — the same shape * `registerSentinelTools` closes over, minus `defaultSessionId` (an HTTP * caller has no implicit calling-session identity; `sessionId` is always * required in the request body). */ interface SentinelHttpDeps { store: SentinelStore; resolveProvider: (slug: string) => Promise; isSessionAlive: (sessionId: string) => boolean; activeIntervalMs?: number; /** Persisted remote-cancel store (the runtime's `cancelTombstones`). */ tombstones?: CancelTombstoneStore; /** Per-sentinel webhook delivery health for `GET /sentinels`. */ deliveryStatus?: (sentinelId: string) => SentinelDeliveryStatus | undefined; /** Enables `POST /inbound/sentinel-` (push providers). Without it * that path falls through to the ordinary inbound-endpoint lookup. */ runtime?: SentinelInboundDeps["runtime"]; /** Shadow signal routing: stamps `POST /sentinels` decisions and backs * `GET /sentinels/routes[/explain]`. Never changes the provider used. */ routing?: SentinelRoutingDeps; /** Public-URL source, for replaying the legacy choice in `explain`. */ publicUrl?: () => SentinelPublicUrl | undefined; } /** * Set by the tunnel server (never a caller) on every `http_request` it * forwards from a HOST-scoped pairing (DEVICES-PLAN item 1) — * `buildDaemonTunnelServerOptions`'s `pairingScope` in * `packages/cli/src/util/tunnel-serve.ts`. `httpInjectHeaders` overrides any * same-named header the ORIGINAL caller's frame carried, so this can never be * spoofed by whoever dials in over a pairing — only the daemon's own * server-side scope decision at serve time ever sets it. * * Deliberately NOT paired with an `isLoopback` bypass the way most other * routes are: every `http_request` a tunnel forwards to THIS server lands as * a loopback socket (the daemon dialing its own gateway via `fetch`), so * `isLoopback` is true for ALL forwarded traffic — host-scoped or not — and * cannot distinguish them. `handleDeviceInference` checks this header alone. */ declare const HOST_SCOPE_HEADER = "x-agentproto-host-scope"; /** * Pluggable adapter resolver — keeps the runtime package free of any * @agentproto/cli dep. The host (cli `serve`, playground, embedding * apps) builds the resolver and hands it in. Returning null means * "adapter not found" → 404. */ type AgentAdapterResolver = (slug: string) => Promise<{ /** Build a fresh AgentSessionLike for the given cwd. The driver * spawns the adapter binary, opens the protocol, and the * registry holds the result. * * When `resumeSessionId` is set, the driver reattaches to that * pre-existing adapter session (claude-code's conversation id, * hermes' chat handle, …) rather than starting blank. Same * mechanism as `agentproto run --resume ` — exposed over * HTTP so `agentproto sessions restart` works on agent-cli * sessions, not just PTY ones. */ startSession(opts: { cwd: string; resumeSessionId?: string; /** Persistent isolated-config location for the adapter (claude-code's * `CLAUDE_CONFIG_DIR`) — forwarded to the driver's * `start({ configDir })`. The daemon keys it per session lineage * (`SessionDescriptor.adapterConfigDir`) so the provider's own * conversation store survives adapter respawns and `resumeSessionId` * can restore full context instead of falling back to a digest. * Adapters that don't isolate a config dir ignore it. */ configDir?: string; /** * Manifest-declared mode id forwarded from `agent_start` (AIP-45 * `AgentCliHandle.modes` — e.g. claude-code's `plan` / * `accept-edits` / `bypass-permissions`, codex's `read-only`, * mastracode/opencode's `plan`). Applied at spawn time via * `composeSpawn`'s mode patch (`bin_args_append` / `env`) — BEFORE * the child process is exec'd, unlike `model`/`effort` below. * Adapters with no declared `modes` (e.g. hermes) ignore it; an * unknown id for an adapter that DOES declare modes throws * `RuntimeConfigError` (composeSpawn validates against the * manifest, so a typo fails the spawn rather than silently no-op). */ mode?: string; /** * Manifest-declared option id → value map forwarded from * `agent_start` (AIP-45 `AgentCliHandle.options` — e.g. hermes' * `skills`). Applied at spawn time via `composeSpawn`'s option * patches (`bin_args_prepend` / `bin_args_template` / * `bin_args_append_when_true` / `env`), validated against each * option's declared `type`/`enum`/`min`/`max`. An id the adapter * doesn't declare throws `RuntimeConfigError` (composeSpawn * validates against the manifest, same as an unknown `mode`). */ options?: Record; /** Model identifier forwarded from `agent_start`. For ACP * adapters this is applied via session/set_config_option after * newSession (the ACP wrapper does not forward CLI args to claude). * Adapters that don't support model selection ignore it. */ model?: string; /** Effort level forwarded from `agent_start`. Effort is * model-dependent — same label ≠ same budget across models; defaults * differ by model. Omit to keep the model's own default. Applied * via session/set_config_option on ACP adapters; others ignore it. */ effort?: string; /** Decomposed permission posture. The host maps canonical string values * to the adapter's native spawn mechanism; raw harness ids may instead be * applied through the live ACP mode surface after connect. */ posture?: Posture; /** Decomposed context profile. A matching manifest `kind:"context"` mode * is projected independently of the legacy `mode` field. */ contextProfile?: ContextProfile; /** MCP servers to mount into the spawned agent's session at spawn * time. Forwarded verbatim to the driver's `start({ mcpServers })` * → the ACP arm's `session/new.mcpServers`, giving the child agent * a host-chosen scoped toolset (e.g. the daemon's own orchestration * gateway). Adapters that don't model MCP mounting ignore it. */ mcpServers?: AcpMcpServer[]; /** Called on any adapter-process activity (ACP JSON-RPC traffic in * either direction) — forwarded to the driver's * `runtime.start({ onActivity })`. The caller (agent_start's MCP * handler, POST /sessions/agent) wires this to pulse * `SessionDescriptor.lastActivityAt` via `registry.pulseActivity(id)`. */ onActivity?: () => void; /** Start the session in permission-hold mode — forwarded to the driver's * `runtime.start({ permissionHold })` so each ACP permission request is * surfaced + parked in the daemon's inbox instead of auto-answered. * Adapters/arms with no permission surface ignore it. Default false. */ permissionHold?: boolean; /** FULLY-RESOLVED billing-auth spec forwarded from `agent_start` to the * driver's `runtime.start({ auth })`, computed by the runtime's * `resolveAuthSpec` (provider, ordered mode, setEnv/scrub, credential * source all pre-decided). The driver applies it mechanically. Absent * when the resolver produced no spec (ambient). */ auth?: ResolvedAuthSpec; /** OS-level confinement for the adapter's OWN spawned process * (`@agentproto/command-sandbox` — macOS Seatbelt / Linux bubblewrap), * forwarded from `agent_start`'s `commandSandbox` field to the driver's * `runtime.start({ commandSandbox })`. NOT the AIP-36 `sandbox` field * (a remote-box session provider) — this wraps THIS host's spawn argv. * Undefined ⇒ falls back to the workspace's `.agentproto/ * command-sandbox.json` `adapterSpawn` key (see `@agentproto/ * command-sandbox`'s `loadAdapterSpawnSandboxConfig`), or stays * unconfined if that's unset too. */ commandSandbox?: SandboxMode; /** Extra env for the spawned adapter process — forwarded verbatim to the * driver's `runtime.start({ env })`, which the AIP-45 driver already * applies LAST (after manifest/mode/option env and billing-auth), so * these keys always win. `spawnAgentSession` (session-spawn.ts) uses * this to inject the daemon's own session-identity vars * (`SESSION_ID_ENV`/`WORKSPACE_SLUG_ENV`, see sessions.ts) — there is * no caller-facing `env` passthrough on `agent_start` today, so this is * daemon-authored only, not a general escape hatch. */ env?: Record; /** Absolute paths OUTSIDE the session cwd the adapter's workspace * toolset may READ (never write). Daemon-authored only — used for the * exact AGENTS.md file an inherited (pointer-mode) prompt names, so a * cwd below the repo root can actually read the contract file its * prompt points at instead of erroring * (`path … escapes the workspace`). NOT a general escape hatch: the * driver forwards these to its confinement layer as extra READ paths * and (for the mastra-agent adapter) to `makeWorkspaceTools` as a * read-only grant; writes and sibling reads stay denied. Adapters * that can't model the grant ignore it. */ additionalReadPaths?: string[]; /** App-boundary filesystem zones (app source read-only, run workspace + * data dir writable, `hidden` denied) for the adapter's OWN process * tree — forwarded to the driver's `runtime.start({ fsZones })`, which * confines it through the OS sandbox (always engaged; refuses * `commandSandbox: "off"`) and, on claude-code, registers the writable * zones as `additionalDirectories`. Only passed to adapters whose * resolver entry sets `supportsFsZones`. */ fsZones?: { readOnly: string[]; writable: string[]; hidden?: string[]; unreadable?: string[]; }; /** Don't load the host repo's CLAUDE.md/AGENTS.md above the session cwd * (claude-code: `claudeMdExcludes`). Only passed to adapters whose * resolver entry sets `supportsHostContextIsolation`. */ isolateHostContext?: boolean; /** Command line of the projected Claude Code PreCompact hook * (`defaults.nativeHooks`), forwarded to the driver's * `start({ preCompactCommand })`. Set only for local claude-code spawns. */ preCompactCommand?: string; /** Resolved imported skills to deliver into this session's isolated * config dir — forwarded verbatim to the driver's * `start({ sessionSkills })` (see `AgentCliStartOptions.sessionSkills`). * Populated by `session-spawn.ts` from the skill-imports registry and * replayed on restart/lazy-resume so a revived session keeps its skills. * Adapters that declare no `metadata.sessionSkills` ignore it. */ sessionSkills?: ResolvedSessionSkill[]; /** Extra system-prompt text for this session — forwarded verbatim to the * driver's `start({ appendSystemPrompt })` (see * `AgentCliStartOptions.appendSystemPrompt`), which applies it per the * adapter manifest's declared `systemPrompt.via` channel (`acp-meta` * `_meta.systemPrompt.append` on new+load, `inline-config` the * inline-config env, `argv` the CLI flag, `env-file` the env var naming * the written text file). ONLY meaningful when this * adapter's resolver entry sets `supportsSystemPrompt` — the runtime * (`session-spawn.ts`) falls back to a first-prompt prefix + harness * warning when that flag is absent/false, so the text is never * silently dropped. */ appendSystemPrompt?: string; /** AIP-72 native-dir inject: the session's in-force items plus their * system-prompt digest as the driver's fallback, forwarded verbatim to * `start({ memoryProjection })` (see * `AgentCliStartOptions.memoryProjection`). Set only for an adapter * whose `memoryInject` is `native-dir`. */ memoryProjection?: { items: readonly _agentproto_memory.MemoryDocument[]; digest?: string; }; }): Promise; /** True when `startSession` honours `fsZones` (native tools confined by the * OS sandbox). Omitted/false ⇒ an app-boundary spawn on this adapter gets * an explicit `session:harness-warning` (or is refused when the app * declares `boundaries.enforce: "required"`). */ supportsFsZones?: boolean; /** True when `startSession` honours `isolateHostContext`. */ supportsHostContextIsolation?: boolean; /** True when this adapter declares a real system-prompt channel for * `startSession({ appendSystemPrompt })` — i.e. its AIP-45 manifest has * `systemPrompt` (`acp-meta` / `inline-config` / `argv` / `env-file`), * and (for a conditional channel like hermes') the conditions for it * hold on this host. Absent/false ⇒ `session-spawn.ts` falls back to * prefixing the text onto the first prompt and raising an `agent_start` * harness warning (never-silent, matching `allowTools`); when true the * text rides the channel instead and NO warning is raised. */ supportsSystemPrompt?: boolean; /** Character budget of this adapter's declared system-prompt channel (the * manifest `systemPrompt.maxChars`, e.g. hermes' plugin 7500). Set ⇒ a * longer text does NOT ride the channel: `session-spawn.ts` falls back to * the first-prompt prefix + a warning naming the limit, and * `agent-projection.ts` projects the text as `instructions` instead of * `systemPrompt`. */ systemPromptMaxChars?: number; /** Why `supportsSystemPrompt` is false even though the manifest declares a * channel (hermes: the agentproto hermes plugin is not installed/enabled * on this host). Appended to the spawn fallback warning so the fix is * named, not guessed. Evaluated per resolve, never cached at boot. */ systemPromptUnavailable?: string; /** True when this adapter takes part in per-session imported-skill delivery * — i.e. its manifest declares `metadata.sessionSkills` telling the driver * where to materialize `start({ sessionSkills })`. Adapters without it * (hermes, whose `skills` is an opaque comma-joined option) are skipped * entirely by `session-spawn.ts`: their option ids are forwarded * untouched and no "unknown skill id" warning is raised. */ deliversSessionSkills?: boolean; /** The id of the manifest option that takes an AIP-42 AGENT.md PATH and * makes this adapter honour the whole manifest itself — declared by the * adapter as `metadata.agentManifestOption` (mastra-agent: `"agent"`). * Absent ⇒ `app_run` / workflow agent refs project the manifest onto * ordinary spawn fields instead (`agent-projection.ts`). An option merely * NAMED `agent` (antigravity's `agy` agent name) is not this. */ agentManifestOption?: string; /** Manifest-declared AIP-72 `capabilities.memory.inject` (AIP-45). Read * by the spawn digest (`memory-digest.ts`): `native-dir` gets the native * projection (`startSession({ memoryProjection })`, the driver falls back * to the system prompt); `system-prompt` gets the digest through the * system-prompt channel when there is one; absent and `none` get no * digest (AIP-72 section 9, step 3). */ memoryInject?: "native-dir" | "system-prompt" | "none"; /** Manifest-declared AIP-72 `capabilities.memory.capture`. `native-dir-diff` * makes the daemon diff the session's projected native memory dir at * turn end and exit and write what changed as proposals * (`memory-capture.ts`). */ memoryCapture?: "native-dir-diff" | "none"; /** Display label for the descriptor's `command` field. */ commandPreview?: string; /** Best-effort per-session usage reader (adapter-specific, e.g. hermes * state.db, the claude-code transcript JSONL). `ctx` carries the spawn's * cwd + isolated config dir for readers that locate their store by them. */ readUsage?: (adapterSessionId: string, ctx?: UsageReadContext) => Promise; /** AIP-45 `options[]` this adapter's manifest declares (id + type only — * no spawn internals). Lets `session-spawn.ts` fold a config-level * `defaults.skills` list into `options.skills` using the shape the * manifest actually declared (e.g. hermes' comma-joined string), * instead of guessing. Omitted/empty ⇒ the skills normalization is a * documented no-op for that adapter (e.g. claude-code, which * auto-discovers skills and declares no such option). */ declaredOptions?: readonly DeclaredAdapterOption[]; /** Billing-auth descriptor projected from the adapter manifest * (`provider` / `authEnforce` / `authSubscription`) — the sole input the * runtime's `resolveAuthSpec` reads about the adapter's auth capability * (keeping the catalog coupling in the runtime, the driver mechanical). * Omitted ⇒ ambient (no credential injection). */ authDescriptor?: AdapterAuthDescriptor; /** Manifest-declared `AgentCliDefinition.routeSelection` (AIP-45 launch-menu * drill-down, WP1) — `"derived-from-model"` when the adapter's billing * ROUTE falls out of the requested model id's own vendor prefix (hermes, * pi, opencode, …), `"free"`/omitted otherwise (the route is an * independent choice, e.g. claude-code/claude-sdk gateway modes). Read by * `session-spawn.ts` to decide whether an unusable resolved `base_url` can * be silently skipped (the adapter derives its own gateway) or must fail * loud (it can neither accept `base_url` nor derive its route) — and to * gate the wire-model vendor-prefix strip the same way `stripAnthropicNativeVendor` * always has, generalized to any fixed-provider adapter. */ routeSelection?: "free" | "derived-from-model"; /** Adapter's default model id (`models.default`) — lets the resolver derive * a provider for a by-model spawn that omitted `model`. */ defaultModel?: string; /** Manifest-declared `capabilities.resumable` (AIP-45) — whether THIS * adapter can actually rehydrate a prior conversation from a captured * session id, as opposed to merely having one recorded. Threaded onto * {@link SessionDescriptor.resumable} at spawn/restart time so the resume * path (`resume-strategies.ts`'s `describeResumePath`/`decideRestartStrategy`) * can gate its "resumed via ACP" label on real capability instead of * hardcoding a slug list. `false` ⇒ a captured `adapterSessionId` is a * dead end (e.g. hermes, mastra-agent) — never pass it as * `resumeSessionId`. Omitted/`true` ⇒ unchanged (assumed resumable), * preserving today's behaviour for every adapter that doesn't set this. */ resumable?: boolean; /** * Manifest-declared `capabilities.nativeTerminalResume` (AIP-45) — whether * THIS adapter has a verified native CLI resume into a real terminal/TUI * (e.g. `claude --resume ` or `hermes --resume --tui`). Governs * the `pty-native` restart strategy: only adapters with this flag set may * be restarted via their native resume argv as a PTY session. ACP * resumability (`resumable`) does NOT imply terminal compatibility. * Omitted/`false` ⇒ the adapter falls back to ACP-level or fresh-spawn * restart even when a native resume id is available. */ nativeTerminalResume?: boolean; /** * Manifest-declared `capabilities.hooks` (AIP-71): native hook * callbacks. Threaded onto {@link SessionDescriptor.nativeHooks} at spawn * and restart time so `session_capabilities` can echo them. Metadata only. * Omitted when the harness declares none. Not the AIP-68 clerk `hooks` * option (`agent_start.hooks.clerk`). */ nativeHooks?: readonly HookCapabilityView[]; /** * Manifest-declared `capabilities.nativeToolSearch` (AIP-45) — the * harness defers mounted MCP tools behind its own search tool, so the * daemon's self-mount defaults to EAGER for it rather than double-deferring * (see `resolveSpawnDeferredTools`). Omitted/`false` ⇒ role/daemon default. */ nativeToolSearch?: boolean; /** * Manifest-declared `capabilities.deferredToolDiscovery` (AIP-45) — the * harness can call an MCP tool omitted from its last `tools/list` after * discovering it through the daemon's `tool_search`. Absent/false ⇒ the * daemon defaults the self-mount to eager (see * `resolveSpawnDeferredTools`), because such a harness rejects the call * client-side before it reaches the gateway. */ deferredToolDiscovery?: boolean; /** * Manifest-declared `capabilities.selfCommands` — the allow-list of slash * commands a session may run on itself via `session_command_self`. */ selfCommands?: readonly string[]; } | null>; /** * UI-safe projection of an AIP-45 `modes[]` entry as surfaced by * `adapter_list`. Mirrors `@agentproto/cli`'s `AdapterMode` without * importing it (the runtime deliberately carries no cli dep — see the * `AgentAdapterLister` note above). Spawn internals (`bin_args_*`, `env`) * are intentionally omitted; `status` is normalised to `"active"` by the * lister when the manifest omits it, so a declared mode is never * silently statusless. */ interface AdapterListMode { id: string; description?: string; status: "active" | "noop" | "planned"; status_note?: string; } /** One row of `adapter_models`' paged projection — the per-model metadata a * manifest's `models.allowed` entry carries (`provider`/`mode` are present * only when the manifest states them). Mirrors `@agentproto/cli`'s * `AdapterInfo.modelDetails[]` without importing it. */ interface AdapterModelRow { id: string; provider?: string; mode?: string; } /** * Compact adapter metadata for the discovery endpoints. Independent * of the resolver function above — hosts that can list installed * adapters wire this; hosts that can only resolve by-slug skip it * (the routes 501). */ interface AdapterListEntry { slug: string; name: string; version: string; description: string; protocol: string; streaming: boolean; packageName: string; /** Declared operation modes with their honest support status, so a * client can see e.g. hermes' `lean` mode is a measured no-op instead * of being silently accepted. Empty when the adapter declares none. */ modes: AdapterListMode[]; /** Short human hint shown in pickers (setup/auth remediation, rebuild * notice — the lister computes it from the adapter's status). Absent * when the adapter has nothing special to say. */ hint?: string; /** * How this adapter's spawn ROUTE relates to the chosen model (AIP-45 * launch-menu drill-down): `"free"` = the route is an independent choice; * `"derived-from-model"` = the endpoint falls out of the model id's vendor * prefix (a read-only badge, not a choice). Absent ⇒ `"free"` (back-compat). * A capability-derived spawn/config drill-down reads this so no UI surface * has to re-infer it from the model list and drift. Mirrors `@agentproto/ * cli`'s `AdapterInfo.routeSelection` without importing it. */ routeSelection?: "free" | "derived-from-model"; /** Known-valid model identifiers for this adapter (`@agentproto/cli`'s * `AdapterInfo.models`, forwarded verbatim). Undefined when the lister * behind `AgentAdapterLister` doesn't populate it. Can run to hundreds * of ids per adapter — `adapter_list`'s COMPACT projection only surfaces * its COUNT; the array itself is `full: true` material. */ models?: string[]; /** * Same models as `models`, each carrying the `provider`/`mode` a * structured `models.allowed` entry states (`@agentproto/cli`'s * `AdapterInfo.modelDetails`, forwarded verbatim). Undefined when the * lister doesn't populate it — `adapter_models` serves these rows paged, * and `adapter_list`'s COMPACT projection only surfaces their COUNT. */ modelDetails?: AdapterModelRow[]; /** * Live readiness status as the daemon's merged listing reports it * (`"supported"` = known but not installed). Optional: older listers * (and tests) omit it — an absent status means the entry IS installed * (`adapter_list`'s compact `installed` flag defaults to true). */ status?: "supported" | "available" | "ready" | "unresolvable"; } type AgentAdapterLister = () => Promise; /** * Loads harness capability-discovery records (`@agentproto/provider-kit`'s * `HarnessCapabilities`) for `harness_capabilities` — what each installed * adapter can actually DO on this host (creds present, reachable billing * providers, model-discovery mechanism, endpoint compat, model/posture * application). `adapter` optionally narrows to one slug; omitted → every * installed adapter. Mirrors `AgentAdapterLister`'s injection shape. Hosts * ship the cli's lister (built over `resolveAdapter`'s optional * `capabilitiesStrategy` + `discoverCapabilities`). Omitted ⇒ the tool * reports "not enabled" (same convention as `listAgentAdapters`). */ type AdapterCapabilitiesLister = (opts?: { adapter?: string; }) => Promise; /** * Outcome of an `adapter_install` / `POST /adapters/:slug/install` request. * Independent of the lister/resolver above — a host that can drive an * install path wires an `AgentAdapterInstaller`; a host that can't skips it * (the tool/route report "not enabled", same convention as the lister). * * `method` names WHICH install path ran so a client can explain it: * - `"npm-global"` — `npm i -g ` for an acp-catalog CLI * - `"agentproto-install"` — drove `agentproto install ` (the * manifest `install[]` pipeline for a first-party * adapter) * - `"already-installed"` — nothing to do; the slug was already `ready` * - `"unsupported"` — no known install path for this slug * * `ok` reflects only whether the install COMMAND succeeded. `status` carries * the adapter's readiness re-read after the attempt (via the same lister the * discovery endpoints use), so a client can refresh a row without a second * round-trip; it's absent when the re-read itself failed. */ interface AdapterInstallResult { slug: string; ok: boolean; method: "npm-global" | "shell-hint" | "agentproto-install" | "already-installed" | "unsupported"; /** Human-readable one-liner: what ran, and how it ended. */ message: string; /** The shell command that was run, for surfacing in logs / errors. * Absent for the `already-installed` / `unsupported` methods. */ command?: string; /** Exit code of `command` when one ran. */ exitCode?: number; /** The adapter's readiness re-read after the attempt. Absent if the * post-install re-list failed (the install itself may still have * succeeded — read `ok`). */ status?: "supported" | "available" | "ready" | "unresolvable"; /** True when the install failed ONLY because a manifest setup step * declares `interactive: true` and this process has no TTY to run it * in (e.g. openclaw's `onboard --install-daemon` TUI). The remedy is a * real terminal — `agentproto setup ` — which a UI can offer * directly as a PTY terminal session. */ needsInteractiveSetup?: boolean; } /** * Installs an agent CLI adapter by slug and reports the outcome. Wired by * the daemon from `@agentproto/cli`'s `installAdapter` (which knows the * catalog + the two install classes); the runtime stays cli-free and only * exposes the verb. Must never throw for an ordinary install failure — * report it via `ok:false` + `message` — so the MCP tool / HTTP route can * return a clean result instead of a 500. */ type AgentAdapterInstaller = (slug: string) => Promise; /** Loads the read-only vendor/product/route catalog (SPEC §5) for * `GET /catalog/models` + the `catalog_models` MCP tool. A host wires this * from `buildCatalogModels` (`catalog-models.ts`) fed by its installed * adapters + `@agentproto/auth`'s `listAuthProfiles()` — the query params * are forwarded verbatim from the request. Omitted ⇒ the route/tool * report "not enabled" (same convention as `listAgentAdapters`). */ type CatalogModelsLister = (query: CatalogModelsQuery) => Promise; interface AuthOptions { mode: "none" | "bearer"; token?: string; } /** * Auth can be a fixed value (set at startup) or a getter (re-read on * every request). The getter form lets `remote_enable` flip bearer on * at runtime without restarting the gateway. */ type AuthSource = AuthOptions | (() => AuthOptions); interface RuntimeHttpServerOptions { port: number; bind?: string; auth?: AuthSource; /** * Heap diagnostics (E99), behind the operator-only `GET /debug/heap` and * `POST /debug/heap-snapshot`. Absent ⇒ both routes 404. */ heapDiagnostics?: { report(): HeapReport; snapshot(): HeapSnapshotResult; }; /** * Per-request McpServer factory. * * The SDK's `StreamableHTTPServerTransport` is single-use — once a * transport has handled one request, the underlying `Protocol` * cannot be reattached, so subsequent requests on a shared transport * 500. The official stateless pattern (see SDK * `examples/server/simpleStatelessStreamableHttp.js`) builds a * fresh `McpServer` and `StreamableHTTPServerTransport` per request, * connects them, and tears both down on `res.close`. We follow that. * * The factory is invoked once per `/mcp` POST. It must register * tools / resources / prompts on the returned server before * resolving — by the time the transport's `handleRequest` fires, * the server is locked in. * * `denyTools`, when non-empty, is parsed from the request's * `?denyTools=a,b` query string (see `handleMcp` below) and is the * spawn-role-profiles tool gate for THIS surface: the hermes-default * `mcpServers` entry injected for an executor-role child (see * `session-spawn.ts`) carries this query param so the resulting * server excludes `agent_start`/`agent_prompt` while keeping every * other tool (fs, command_execute, …) — unlike the orchestrator's * curated allowlist, this surface can't just narrow to a small * subset without breaking the child's ability to do real work. * * `callerSessionId`, when present, is parsed from the request's * `?callerSessionId=` query string (see `handleMcp` below) — the * same hermes-default `mcpServers` entry carries it (PR 7 / Gap 7) * so a `command_execute` call made through THIS one-shot server can * be attributed to the session that made it (see `command-tools.ts`'s * `RegisterCommandToolsOptions.callerSessionId`). */ /** * `origin`, when present, is parsed from the request's `?origin=