import { S as SpawnDefaultsConfig } from './spawn-defaults-B0Yi8_MN.js'; import { Floor, Level, Classifier, Envelope, DeliveryApplyConfig } from '@agentproto/delivery'; import { ReachRouteEntry } from '@agentproto/reach'; import { SentinelRoute, SentinelRoutingMode } from '@agentproto/sentinel'; /** * follow-triage — deterministic, LLM-free triage of session-follow events, * run BEFORE a digest is allowed to wake the follower. * * The problem: an orchestrator that follows many sessions is woken dozens of * times an hour, and most digests ask for nothing. The fix is not a better * prompt but a pre-wake filter: every event that would enter a digest is * classified `wake` | `fyi` | `drop` by rules the operator can see, toggle, * and audit. * * DESIGN * - Disabled by default. A follow without `triage.enabled` behaves EXACTLY * as before (no triage, no JSONL, same digests). * - Each rule is a separate switch. The rules are checked in a fixed order; * the first match wins and names itself in the decision record. * - `wake`/`fyi`/`drop` are about ATTENTION, not truth: `drop` events are * still written to the JSONL ledger (training data for a future * classifier), they are just not shown. * - The `classifier` hook is the extension point for a future LLM * classifier (Jev): it receives the event as JSON and answers * `wake`/`fyi`/`drop`. On timeout, error, or an unparsable answer the * engine FALLS BACK to the deterministic rules — a classifier can never * silence the pipeline, only refine it. The always-wake events * (awaiting-input, crashed, a turn-end with a question) are never * overridable. * * The module is pure: it takes an event, the resolved config, and a small * set of FACTS the engine knows (did this session just report up? is it a * live session of the follower? did a new turn start? did its cron run * finish OK?) and returns a decision. No I/O except the classifier call and * the optional JSONL ledger, both injected by the caller. */ declare const FOLLOW_TRIAGE_DECISIONS: readonly ["wake", "fyi", "drop"]; type TriageDecision = (typeof FOLLOW_TRIAGE_DECISIONS)[number]; declare function isTriageDecision(value: unknown): value is TriageDecision; /** * The per-rule switches. Every rule is independently activatable; a rule * that is off simply never fires (the event then falls through to the next * rule, and finally to the default `wake`). */ interface FollowTriageRules { /** `task-changed` whose ACTOR is the follower itself → `drop`. The * follower's own board writes are its own business. */ ownTaskChanges: boolean; /** `exited` with reason `operator-stopped` / `operator-completed` (the * follower or the operator asked for the stop) → `fyi`. Nobody is * waiting on a session that was deliberately stopped. */ operatorExit: boolean; /** `exited` for a session whose cron run finished OK → `drop`. The cron * run already reported its own success. */ cronOk: boolean; /** `turn-end` from a session that reported UP to the follower in the * last `reportWindowMs` → `drop`: the report already arrived, the * turn-end is the echo. */ reportedTurnEnd: boolean; /** an empty or `cancelled` turn-end that was FOLLOWED BY A NEW TURN → * `fyi`: the session moved on, the stale turn-end is noise. */ emptyTurnEnd: boolean; /** `pr-opened` / `pr-merged` authored by another LIVE session of the * follower → `fyi`: the follower will hear about its own PR from the * session that opened it. */ ownPr: boolean; } declare const DEFAULT_FOLLOW_TRIAGE_RULES: FollowTriageRules; /** How long after a `message_parent` report a turn-end is considered its * echo. Default 60s. */ declare const DEFAULT_FOLLOW_TRIAGE_REPORT_WINDOW_MS = 60000; /** Default timeout for one classifier call. */ declare const DEFAULT_FOLLOW_TRIAGE_CLASSIFIER_TIMEOUT_MS = 5000; /** * The classifier extension point. `command` is a shell command that receives * the event as JSON on stdin and answers `wake`/`fyi`/`drop` on stdout; * `url` is an HTTP endpoint that receives the same JSON and answers * `{"decision":"wake"}` (a bare `wake`/`fyi`/`drop` body is accepted too). */ interface FollowTriageClassifier { command?: string; url?: string; timeoutMs?: number; } /** The resolved triage configuration. */ interface FollowTriageConfig { enabled: boolean; rules: FollowTriageRules; classifier?: FollowTriageClassifier; reportWindowMs: number; } /** The (partial) triage block as stored on a follow / in the daemon config. * Everything is optional: an unset field falls back to the daemon default. */ interface FollowTriageInput { enabled?: boolean; rules?: Partial; classifier?: FollowTriageClassifier; reportWindowMs?: number; } /** The triage block a FOLLOW may carry. No `classifier`: that hook runs a * command / HTTP call on the daemon host, so it is operator-owned * (`~/.agentproto/config.json`) and never reachable from a tool call. */ type FollowTriageFollowInput = Omit; /** Resolve a partial triage block against the daemon-level default. */ declare function resolveFollowTriageConfig(base?: FollowTriageConfig, override?: FollowTriageFollowInput): FollowTriageConfig; /** The daemon-level default: triage OFF, every rule ON. */ declare function defaultFollowTriageConfig(): FollowTriageConfig; /** The event as the triage sees it — the digest entry plus the few facts * that only exist at event time. */ interface TriageEvent { /** The session that would be woken. */ follower: string; event: FollowEvent; /** The session the event is ABOUT (the turn-end's session, the PR's * author, the task-change's actor). */ sessionId: string; ts: string; label?: string; detail?: string; key?: string; boardId?: string; taskId?: string; /** `turn-end` / `awaiting-input`: the session is waiting on the human. */ awaitingInput?: boolean; /** `turn-end`: the turn produced no output at all. */ empty?: boolean; /** `turn-end` reason (`cancelled`, `error`, …) or `exited` reason * (`operator-stopped`, …). */ reason?: string; /** The level-3 pin, carried by the envelope the producer built. */ floor?: Floor; } /** * The facts the engine knows and the event itself does not carry. All of * them are optional: a missing fact means "unknown", never "true". */ interface TriageFacts { /** Did this session send a `message_parent` to the follower within the * report window preceding the event? */ reportedRecently?: (event: TriageEvent, windowMs: number) => boolean; /** Is this session a LIVE session of the follower (the follower itself or * one of its descendants)? */ isFollowerSession?: (sessionId: string, follower: string) => boolean; /** Was this turn-end followed by a NEW turn of the same session? */ supersededByNewTurn?: (event: TriageEvent) => boolean; /** Did this session's cron run finish OK? */ cronOk?: (sessionId: string) => boolean | undefined; } /** The outcome of classifying one event. `rule` names the rule that fired * (`"default"` when nothing matched). */ interface TriageResult { decision: TriageDecision; rule: string; /** The computed level (3 only when the envelope carries a floor). */ level?: Level; } /** Rule ids — the vocabulary the JSONL ledger is written in. */ declare const TRIAGE_RULES: { readonly alwaysWake: "always-wake"; readonly ownTaskChanges: "own-task-changed"; readonly operatorExit: "operator-exit"; readonly cronOk: "cron-ok"; readonly reportedTurnEnd: "reported-turn-end"; readonly emptyTurnEnd: "empty-turn-end"; readonly ownPr: "own-pr"; readonly default: "default"; }; /** * The floor a follow event pins, if any: awaiting input and a turn-end that * carries a question are `awaiting-human`; a crash is `crash`. This is the * single source of the always-wake set. `computeLevel` turns it into level 3. */ declare function followFloor(event: FollowEvent, awaitingInput?: boolean): Floor | undefined; /** * The deterministic rules. Pure: same event + same facts ⇒ same decision. * * Order matters and is fixed: * 1. a floored event (never overridable), * 2. the six operator-tunable rules, in declaration order, * 3. default → `wake`. */ declare function classifyFollowEvent(event: TriageEvent, rules: FollowTriageRules, facts?: TriageFacts, reportWindowMs?: number): TriageResult; interface ClassifierOutcome { decision?: TriageDecision; /** Why the classifier failed (timeout, non-zero exit, unparsable body). */ error?: string; } /** Parse a classifier answer: a bare `wake`/`fyi`/`drop`, or JSON carrying * a `decision` field. */ declare function parseClassifierAnswer(body: string): TriageDecision | undefined; /** * Run the classifier hook for one event. Never throws: a failure is * reported as `error` so the caller can fall back to the rules. */ declare function runFollowTriageClassifier(event: TriageEvent, classifier: FollowTriageClassifier): Promise; /** * Apply a decision through `computeLevel`: the envelope's floor always wins, * so this is the ONE place a level-3 pin is honoured. Every other path reads * the level this returns, never a separate must-wake branch. */ declare function levelOfDecision(event: Pick, decision: TriageDecision, cap?: Level): Level; /** * The deterministic verdict plus its computed level. Pure: same event + same * facts ⇒ same result. A floored event always comes back as level 3 and is * named `always-wake`, whatever the tunable rules would otherwise say. */ declare function evaluateFollowEvent(event: TriageEvent, rules: FollowTriageRules, facts?: TriageFacts, reportWindowMs?: number, cap?: Level): TriageResult & { level: Level; }; /** * Classify one event, consulting the classifier hook when one is * configured. The hook may refine a non-floored decision; a floored event * is decided by `computeLevel` and any failure falls back to the rules. */ declare function triageFollowEvent(event: TriageEvent, config: FollowTriageConfig, facts?: TriageFacts): Promise; /** Stable classifier id, recorded in the delivery ledger as `rule`. */ declare const SESSION_LIFECYCLE_CLASSIFIER_ID = "session-lifecycle"; /** The delivery envelope `type` for a follow event. */ declare function followEnvelopeType(event: FollowEvent): string; /** Rebuild the rule-layer event from the producer's envelope. */ declare function triageEventFromEnvelope(env: Envelope, follower: string): TriageEvent; interface SessionLifecycleClassifierOptions { rules: FollowTriageRules; /** The engine facts, closed over here (never threaded through * `ClassifyContext`, which no longer carries them). */ facts?: TriageFacts; reportWindowMs?: number; /** Follower whose events these are; defaults to `ctx.targetId`. */ follower?: string; } /** Build the `session-lifecycle` classifier over the follow rules. */ declare function createSessionLifecycleClassifier(options: SessionLifecycleClassifierOptions): Classifier; /** * SessionFollowStore — persists `~/.agentproto/follows.json`. * * A "follow" lets one long-lived session (the FOLLOWER) be woken by the * lifecycle events of OTHER sessions matched by a selector — including root * sessions it did not spawn. The matching engine lives in `session-follow.ts`; * this file is only the record shape + persistence. * * Persistence model mirrors `sentinel-store.ts`: in-memory Map, loaded on * construct, debounced atomic write (per-process tmp file + rename, mode * 0600), synchronous flush at shutdown. A follow whose follower session no * longer exists is KEPT — the follower may be revived. */ /** The event kinds a follow can subscribe to. */ declare const FOLLOW_EVENTS: readonly ["turn-end", "awaiting-input", "exited", "crashed", "pr-opened", "pr-merged", "task-changed"]; type FollowEvent = (typeof FOLLOW_EVENTS)[number]; /** How a follow's digest is delivered: `next-turn` wakes the follower for a * turn; `fyi` parks it in the follower's inbox without starting one. */ declare const FOLLOW_URGENCIES: readonly ["next-turn", "fyi"]; type FollowUrgency = (typeof FOLLOW_URGENCIES)[number]; interface FollowSelector { /** Explicit session ids to follow (always match, regardless of `rootOnly`). */ sessionIds?: string[]; /** Follow every session that exists at EVENT time (auto-covers sessions * spawned after the follow was created). */ all?: boolean; /** Match sessions whose cwd is this path or below it. */ cwdPrefix?: string; /** Follow task-board changes: deliver a `task-changed` whenever a task on * THIS board changes (created, claimed, a status transition, or a release) * by another actor — never a pure field edit. Independent of the session * selector (`sessionIds`/`all`/`cwdPrefix` are ignored for these events). */ boardId?: string; /** Only sessions with no `parentSessionId`. Effective default: `true` when * `all`, otherwise `false`. Stored resolved. */ rootOnly?: boolean; } interface FollowExclude { sessionIds?: string[]; labels?: string[]; } interface SessionFollow { /** `fol_`, daemon-minted. */ id: string; /** Optional stable caller-chosen key: re-posting the same key updates the * existing follow in place (UPSERT). */ key?: string; /** The session that gets woken. */ follower: string; /** ISO-8601 creation time. */ createdAt: string; selector: FollowSelector; exclude?: FollowExclude; /** Subscribed event kinds. Stored resolved (default: all of them). */ events: FollowEvent[]; /** Coalescing window per follower. Default 15000; 0 = next tick. */ batchMs: number; /** Drop turn-ends flagged `empty` (silent no-op turns). Default true. */ skipEmptyTurns: boolean; /** Ignore sessions descending from the follower. Default true. When false, * they are delivered whenever the selector is broad (`all`/`cwdPrefix`), * bypassing `rootOnly`/`cwdPrefix` like explicit ids. */ excludeFollowerChildren: boolean; /** Digest delivery mode. Default "next-turn"; records persisted before this * field existed load as "next-turn". */ urgency: FollowUrgency; /** Per-follow triage block: classify each event `wake`/`fyi`/`drop` BEFORE * the digest is allowed to wake the follower. Unset ⇒ the daemon default * (`config.follow.triage`) applies; triage is OFF by default. */ triage?: FollowTriageFollowInput; /** ISO timestamp after which the wiring sweep removes the follow. Defaults * to `createdAt + DEFAULT_FOLLOW_TTL_MS`; a follower that is gone/retired * is removed sooner by the same sweep. */ expiresAt?: string; } /** Fully-resolved input for {@link SessionFollowStore.upsert}. */ interface SessionFollowInput { key?: string; follower: string; selector: FollowSelector; exclude?: FollowExclude; events?: readonly FollowEvent[]; batchMs?: number; skipEmptyTurns?: boolean; excludeFollowerChildren?: boolean; urgency?: FollowUrgency; triage?: FollowTriageFollowInput; expiresAt?: string; } interface SessionFollowStore { get(id: string): SessionFollow | undefined; /** Look up by id first, then by `key`. A key is scoped to its follower: * pass `follower` to resolve it inside that follower's own follows. */ find(idOrKey: string, follower?: string): SessionFollow | undefined; list(filter?: { follower?: string; }): SessionFollow[]; /** UPSERT by (`follower`, `key`) when a key is given (keeps `id` + * `createdAt`), else create. Two followers may use the same key. */ upsert(input: SessionFollowInput): { follow: SessionFollow; created: boolean; }; /** Re-point a follow at another follower session (a revived follower). */ setFollower(id: string, follower: string): SessionFollow | undefined; /** Remove by id or key (key scoped to `follower` when given). */ remove(idOrKey: string, follower?: string): SessionFollow | undefined; /** Synchronous flush for shutdown paths. */ flushSync(): void; } interface SessionFollowStoreOptions { /** Override persist path. Default ~/.agentproto/follows.json (or * AGENTPROTO_HOME/follows.json). */ filePath?: string; /** Injectable clock for tests. */ nowMs?: () => number; /** Debounce interval for disk persistence. */ debounceMs?: number; /** Disable disk persistence (unit tests). Default true, unless `false` * is passed; an explicit `filePath` implies persistence. */ persist?: boolean; } declare function createSessionFollowStore(opts?: SessionFollowStoreOptions): SessionFollowStore; /** * Model roles — ONE place to say "which model does role X use". * * A role is a dotted name for a job a model does inside agentproto * (`review.small`, `review.large`, `review.pr`, `judge.session`, …). * Consumers (the repo-maintenance workflow, the session-steward, agent * manifests via `model: role:`, and later the CI reviewer and the * local push gate) ask for the ROLE instead of hard-coding a model id, so * "use GLM for review" is one config edit, not five files in three formats. * * PRECEDENCE — the single definition (highest first): * 1. `input` an explicit workflow/run input (`reviewModelSmall`, …) * 2. `workspace` the repo's own `agentproto.json` → `models` * 3. `daemon` `~/.agentproto/config.json` → `models` * 4. `preset` the active named preset ({@link MODEL_ROLE_PRESETS}), * chosen by `modelRolePreset` in the daemon config or a * per-run `preset` — a one-key switch between model sets * 5. `default` {@link DEFAULT_MODEL_ROLES} below — the only built-in table * * Every resolution reports which layer won (`source`). A layer value that is * empty or not a string / `{ model }` object is skipped, never fatal. * * This file is pure (no I/O) so the config schema can import it without a * cycle; the loaders + the `model_roles` MCP tool live in * `model-roles-tools.ts`. */ /** Object form of a role value: a model id plus optional serving hints. */ interface ModelRoleEntry { model: string; /** Router/gateway the model should be reached through (e.g. `openrouter`). */ route?: string; /** Named auth profile to spawn the role's session with. */ profile?: string; } /** A role value as written in a config file: a bare model id, or an entry. */ type ModelRoleValue = string | ModelRoleEntry; /** ROLE → value, the shape of the `models` block in every layer. */ type ModelRolesConfig = Record; type ModelRoleSource = "input" | "workspace" | "daemon" | "preset" | "default"; /** The built-in defaults — the ONLY hard-coded model ids for these jobs. */ declare const DEFAULT_MODEL_ROLES: Readonly>; /** One named model set for the review roles — switch them all with one key. */ interface ModelRolePreset { description: string; roles: Readonly>; } /** * Named presets, selected by `modelRolePreset` (daemon config) or a per-run * `preset`. A preset fills only the roles it names; an explicit value in any * higher layer still wins. `opus` is the built-in default spelled out, so * switching back is one key too. */ declare const MODEL_ROLE_PRESETS: Readonly>; /** The preset names, for schemas and help text. */ declare const MODEL_ROLE_PRESET_NAMES: [string, ...string[]]; /** * The adapter a role's model has to run on, when the model id says so: * `opencode/…` and `opencode-go/…` ids only exist on the opencode adapter (an * `opencode-go/claude-*` id included), a bare `claude-*` id on claude-code. * Undefined leaves the consumer's own default (e.g. the agent manifest's). */ declare function adapterForModelId(model: string): string | undefined; /** Prefix an agent manifest's `model:` uses to reference a role. */ declare const MODEL_ROLE_REF_PREFIX = "role:"; interface ModelRoleContext { /** Explicit per-run values keyed by role (layer 1). */ input?: Record | undefined; /** The workspace/repo `models` block (layer 2). */ workspace?: Record | undefined; /** The daemon config `models` block (layer 3). */ daemon?: Record | undefined; /** Active preset name (layer 4); an unknown name is ignored. */ preset?: string | undefined; } interface ResolvedModelRole { role: string; model: string; route?: string; profile?: string; /** Adapter the model id requires ({@link adapterForModelId}), when it requires one. */ adapter?: string; source: ModelRoleSource; } /** `role:review.large` → `review.large`; undefined for a non-role string. */ declare function parseModelRoleRef(ref: string): string | undefined; /** * Resolve ONE role through the precedence chain. `undefined` only when no * layer — including the built-in table — knows the role. */ declare function resolveModelRole(role: string, ctx?: ModelRoleContext): ResolvedModelRole | undefined; /** * Every role in play — the built-in ones plus any a layer configures — each * resolved with its source, sorted by role name. `roles` narrows the list * (an unknown role with no value anywhere is simply omitted). */ declare function listModelRoles(ctx?: ModelRoleContext, roles?: readonly string[]): ResolvedModelRole[]; /** * `~/.agentproto/config.json` — single hand-editable JSON for the * agentproto control plane's defaults. Sits alongside the existing * surface files (workspaces.json, credentials.json, sessions.json): * * workspaces.json which directories are workspaces + which is active * credentials.json tunnel host bearer tokens (mode 0600) * sessions.json last-known snapshot of the registry (informational) * config.json daemon defaults: port, bind, allowed origins, * tunnel host, feature toggles * * Resolution order for every daemon knob is: * 1. CLI flag (e.g. --port) * 2. Env var (where one exists, e.g. AGENTPROTO_TOKEN) * 3. config.json * 4. Hardcoded default * * This means a user can call `agentproto config set daemon.port 18791` * once and never re-pass `--port 18791` to `serve install` etc. CLI * flags still win for one-off overrides. * * Schema is intentionally narrow + extensible — unknown keys are * preserved on save (deep-merge), so a newer CLI writing a new * field won't drop one an older CLI doesn't know about. No secrets * here; credentials stay in credentials.json (mode 0600). */ declare const CONFIG_VERSION: 1; interface DaemonConfig { /** Absolute path to the workspace the daemon binds to at boot. */ workspace?: string; /** HTTP port. Default 18790. */ port?: number; /** Bind addr. Default 127.0.0.1. */ bind?: string; /** Trusted browser origins for mutating /sessions/* routes (in * addition to the hardcoded localhost defaults). */ allowedOrigins?: string[]; /** Extra origins (or custom URI schemes) allowed to EMBED the standalone * app page `GET /apps/:appId/ui` in an iframe, added to the built-in * `vscode-webview:` / `vscode-file:`. For example a browser-based * Telegram client. A different axis from `allowedOrigins` (who may call * the daemon). Only exact `https://host[:port]` origins and custom * schemes are honoured; `*`, wildcards and bare `http:`/`https:` are * dropped with a warning at boot. A bare string is read as a * comma-separated list. */ frameAncestors?: string[] | string; /** When true, the daemon does NOT auto-trust localhost-on-any-port. * Only origins explicitly listed in `allowedOrigins` are allowed. * Pair with a curated list (e.g. `["http://localhost:3000"]`) for * hardened setups. Default false. */ strictOrigins?: boolean; /** Server label sent in tunnel hello frames. */ label?: string; /** Bearer token gating the gateway at boot (`AuthOptions` with * `mode: "bearer"`). Unlike `remote_enable`'s ephemeral quick-tunnel * token, this one lives in config.json and survives daemon restarts. * Set via `agentproto config set daemon.authToken ` (e.g. * `$(openssl rand -hex 32)`). Unset ⇒ the gateway boots with * `mode: "none"` — fully open on loopback, same as today. */ authToken?: string; /** Opt-in eager resume-on-boot (session-survivability plan §5 * "Opt-in vs automatic", PR-4). When true, a daemon restart doesn't just * leave agent-cli sessions dead-but-lazy-resumable — the boot pass eagerly * re-spawns the eligible ones (those that died with * `endedReason: "daemon-restart"` and still pass `canResume`) IN PLACE, * restoring liveness without waiting for a prompt. Lazy resume-on-prompt is * always on regardless of this flag (it costs nothing until someone acts); * this flag only controls the *automatic* boot-time pass. Default false: a * box-wide restart should not silently relaunch every adapter (cost, spawn * storm, credential re-resolution), and default-off also keeps two daemons * sharing the workspace buckets from racing to resume the same rows. Set via * `agentproto config set daemon.resumeSessionsOnBoot true`. Surfaced in * `daemon_health` / `GET /health`. */ resumeSessionsOnBoot?: boolean; /** Which sessions automatic boot recovery restores; all preserves legacy behavior. */ bootResumePolicy?: "all" | "keepalive"; /** Idle cutoff, in minutes, for eagerly resuming a `keepAlive` session at * boot. A `keepAlive` row is exempt from the idle reaper, so without this * it would be revived on every daemon restart even after its work finished * days earlier. Rows idle longer than this (measured from their last * turn-end) are left dead-but-lazy-resumable: the next prompt, or an * explicit `session_restart`, revives them on demand. Explicitly pinned * sessions are always resumed; an `operatorLabel` does not exempt a row * (it is an identity stamped on every operator spawn). Default 30. Set to 0 to disable the * cutoff (restore the old resume-everything behavior); only meaningful * when `resumeSessionsOnBoot` is on. Set via * `agentproto config set daemon.bootResumeKeepAliveMaxIdleMinutes 30`. */ bootResumeKeepAliveMaxIdleMinutes?: number; /** Boot re-ensure of installed apps' service owners. DEFAULT ON: an * installed app's services are part of the service contract, and they * are deterministic processes (cost/spawn-storm concerns behind * `resumeSessionsOnBoot`'s default-off do not apply). Set * `daemon.resumeServicesOnBoot false` to keep services down after a * restart. Surfaced in `daemon_health` / `GET /health`. */ resumeServicesOnBoot?: boolean; /** Opt-in continue-on-boot (continue-interrupted). When true, right after * the eager resume pass, the boot sends a "the daemon restarted mid-turn, * check the state on disk and continue" prompt to every session the LAST * restart interrupted mid-turn (`interrupted: true`) that is resumable, * under the resume cap, idle, and whose resume didn't fail. Never loops: at * most one auto-continue per restart and `MAX_AUTO_CONTINUE_ATTEMPTS` in a * row without a successful turn-end. Default false — the interrupted prompt * itself is never auto-retried, and a continue prompt is still a prompt * (tokens, side effects), so it's opt-in. The manual * `session_continue_interrupted` verb works regardless. Set via * `agentproto config set daemon.continueInterruptedOnBoot true`. */ continueInterruptedOnBoot?: boolean; /** Idle agent-session reaper (PR-6). When set to a positive number of * milliseconds, the daemon periodically retires agent-cli sessions that have * been idle (not busy, not awaiting input, `status:"running"`) longer than * this: it SIGTERMs the adapter child to free the process and flips the row * to `killed`/`endedReason:"idle-reaped"` — dead-but-lazy-resumable (a later * prompt revives it) and, critically, excluded from eager resume-on-boot * (#638 gates on `endedReason === "daemon-restart"`), so enabling this makes * eager resume safe: only genuinely-recent work survives a restart. Default * OFF (unset / 0 / negative ⇒ the reaper never runs). Resolution order * mirrors the module docblock: `AGENTPROTO_IDLE_REAP_AFTER_MS` env > this * field > off. Set via `agentproto config set daemon.idleReapAfterMs * `. Surfaced in `daemon_health` / `GET /health`. */ idleReapAfterMs?: number; /** Shorter idle threshold in ms for SANDBOXED sessions (a session running in * a provider box — e2b, …). A finished turn never closes the session, so an * idle box otherwise lives until its provider lifetime expires. A sandboxed * session that is not busy, not blocked on a command/sub-agent/background * task and not `keepAlive` is reaped once idle this long: a final checkpoint * of its work, then the box is torn down per its lifecycle policy (kill * unless the spec asked to pause), and a ledger row records the reap. The * row stays revivable: a later prompt cold-boots a fresh box from the * checkpoint branch. DEFAULT ON (15 min); `0` turns it off. Does not touch * non-sandbox sessions (those follow `idleReapAfterMs` only). Resolution * order: `AGENTPROTO_SANDBOX_IDLE_REAP_AFTER_MS` env > this field > 15 min. * Set via `agentproto config set daemon.sandboxIdleReapAfterMs `. */ sandboxIdleReapAfterMs?: number; /** Crash-detect sweep interval in ms (crash-detect PR-1). Unlike * `idleReapAfterMs`, this is DEFAULT ON (non-destructive observability): * the daemon periodically probes every live agent-cli session's OS * process (`process.kill(pid, 0)`) and, when it's provably gone with no * exit event ever emitted for it, flips the row to * `error`/`endedReason:"crashed"` with a `lastError` string — surfacing a * death that would otherwise sit silently as `status:"running"` until the * next prompt's RPC throws (or forever, for a parked session with no next * prompt). Detects only; never restarts or notifies (later PRs). Set to a * non-positive value to disable the sweep entirely. Resolution order * mirrors `idleReapAfterMs`: `AGENTPROTO_CRASH_DETECT_INTERVAL_MS` env > * this field > the hardcoded default (30s). Set via `agentproto config * set daemon.crashDetectIntervalMs `. Surfaced in `daemon_health` / * `GET /health`. */ crashDetectIntervalMs?: number; /** Restart-scheduler sweep interval in ms (restart-scheduler PR-2). OFF by * default (unset / 0 / negative ⇒ the sweep never runs), unlike * `crashDetectIntervalMs` — a positive value here only arms the periodic * sweep that EXECUTES an already-scheduled restart; it never opts a * session in by itself (that's the per-session `agent_start.restartPolicy` * field). Resolution order mirrors `idleReapAfterMs`: * `AGENTPROTO_RESTART_SWEEP_INTERVAL_MS` env > this field > off. Set via * `agentproto config set daemon.restartSweepIntervalMs `. Surfaced in * `daemon_health` / `GET /health`. */ restartSweepIntervalMs?: number; /** Default `restartPolicy` for BOX sessions (`agent_start.sandbox`) that * were spawned with NO explicit `restartPolicy`. OFF unless set — an unset * / false value changes nothing for anyone. When true, such a session is * stamped with `on: ["sandbox-gone"]` (see * `SANDBOX_GONE_DEFAULT_RESTART_POLICY` in `sessions.ts`), so a box session * whose BOX dies — provider lifetime cap, reclaim, unrecoverable * unreachability — is moved to a FRESH box by the restart scheduler * instead of staying dead. An explicit per-session * `agent_start.restartPolicy` always wins, and nothing else about * restarts changes (classic `crashed`/`error` in-place revival still * needs its own opt-in). Because the scheduler only SCHEDULES, turning * this on with `daemon.restartSweepIntervalMs` unset also arms the sweep * at 30s so the scheduled move actually executes. Set via `agentproto * config set daemon.sandboxGoneRestartDefault true`. */ sandboxGoneRestartDefault?: boolean; /** Turn-liveness watchdog threshold in ms (turn-liveness-watchdog * chantier). Same shape as `crashDetectIntervalMs`: DEFAULT ON * (non-destructive observability). The daemon periodically sweeps every * BUSY agent-cli session and, for one that is mid-turn, NOT legitimately * `blockedOn` a subagent/command, and has had no adapter activity * (`lastActivityAt`) for longer than this threshold, stamps * `stalledSinceMs` on the descriptor and emits `session:stalled` — * surfacing a dead adapter stream (network drop, hung child — zero * frames mid-turn) that would otherwise sit indistinguishable from * healthy long work: `status:"running"`, `lastError:null`, no other * signal. Conservative by design: a session legitimately blocked on a * long tool call is NEVER a candidate, no matter how long it's silent — * see `stall-watchdog.ts`'s docblock for why. Detects only; never kills * or restarts (this is a later concern, if ever). Set to a non-positive * value to disable the sweep entirely. Resolution order mirrors * `idleReapAfterMs`: `AGENTPROTO_TURN_STALL_AFTER_MS` env > this field > * the hardcoded default (5 min). Set via `agentproto config set * daemon.turnStallAfterMs `. Surfaced in `daemon_health` / * `GET /health`. */ turnStallAfterMs?: number; /** How long an `external` session (a Claude Desktop / `claude` CLI session * the daemon did not spawn, registered from `?callerSessionId=&host=` on * `/mcp`) stays alive after its last MCP request / inbox poll. Default * 30 min; non-positive falls back to the default. Set via `agentproto * config set daemon.externalSessionLivenessMs `. */ externalSessionLivenessMs?: number; /** Opt-in `claude-socket` wake adapter for external Claude Code sessions * (`cc:` rows). When true, a level 2+ message (next-turn / * steer) also wakes the idle Claude Code process over its per-session * unix socket, instead of waiting for the next hook poll. Level 1 (fyi) * always falls back to the inbox. A `bypassPermissions` target is written * to too, but Claude Code holds the message unless the user's * `crossSessionInbound` is `accept`; the held message is also parked in the * inbox (`agentproto doctor --fix`). Default false. Set via `agentproto config set daemon.claudeSocketWake true`. */ claudeSocketWake?: boolean; /** Local opt-in for private IPC wake notifications in these Codex Desktop chat UUIDs. */ codexDesktopWakeThreadIds?: string[]; /** Exact local chat UUIDs opted into bounded untrusted input on wake. */ codexDesktopWakeDirectThreadIds?: string[]; /** Senders trusted as instructions in a Codex Desktop direct wake: `off` (default) | `operator` | `tree` | explicit list (session ids, `label:`, `human`, `claude-desktop`). */ desktopTrustedSenders?: "off" | "operator" | "tree" | string[]; /** Per-thread override of `desktopTrustedSenders`, keyed by Codex Desktop chat UUID. */ desktopTrustedSendersByThread?: Record; /** On-disk retention for REVIEW-LANE sessions (`origin: "review"` / * `review:` label): a terminal review session whose last activity is older * than this many days has its `~/.agentproto/sessions//` dir DELETED * by the daemon's periodic retention sweep (boot + 10 min, then every 6 h) * and `session_gc retention:true`. Default 7; `0` / negative disables the * review rule. Set via `agentproto config set * daemon.reviewSessionRetentionDays `. */ reviewSessionRetentionDays?: number; /** On-disk retention for EVERY other terminal session, in days. Default * OFF (unset / `0` / negative ⇒ regular sessions are never deleted). * Pinned, keepAlive and live sessions (and ancestors of a live one) are * never deleted either way. Set via `agentproto config set * daemon.sessionRetentionDays `. */ sessionRetentionDays?: number; /** Adapter-config cache retention, in days: once every session of a * lineage is terminal and quiet this long, the periodic sweep deletes the * cache paths of its `~/.agentproto/adapter-config//` dir (pnpm store, * opencode snapshot/tool-output/log), keeping what a resume reads. * Default 1; `0` / negative disables. Set via `agentproto config set * daemon.harnessCacheRetentionDays `. */ harnessCacheRetentionDays?: number; /** @deprecated Old name of `harnessCacheRetentionDays`, read only when * that key is unset; removed in the next major of @agentproto/runtime. */ adapterCacheRetentionDays?: number; } interface TitlerConfig { /** Enable the daemon-side session titler. Default false. */ enabled?: boolean; /** OpenRouter model id used to generate titles. Default * `z-ai/glm-5.2@openrouter`. Requires `OPENROUTER_API_KEY` in the * daemon's environment; without a key the titler falls back to the * local (first-prompt-line) title. */ model?: string; } interface JevConfig { /** Jev (TypeSafe System One) API key. Read by `resolveJevApiKey` BEFORE * the `JEV_API_KEY` environment variable: the config file is the * primary home for this first-party secret and the env var is the * fallback. Secret: redacted by `config_get`. */ apiKey?: string; /** Jev model id. Default `jev-latest`. */ model?: string; /** Jev endpoint override. Default `https://api.typesafe.ai/v1/systemone`. */ baseUrl?: string; } interface CatalogSourceConfig { /** HTTP(S) URL returning `{ entries: AppCatalogEntry[] }`. */ url: string; } interface CatalogConfig { /** Remote app-catalog sources merged into `app_catalog`, IN ADDITION to the * default catalog (`defaultSource`). When set, these win over (replace) * `sources` in `~/.agentproto/app-catalog.json`. */ sources?: CatalogSourceConfig[]; /** The default public catalog (`DEFAULT_CATALOG_SOURCE_URL` in * app-catalog.ts): `false` turns it off, a URL replaces it. Absent = on. */ defaultSource?: string | false; } interface TunnelConfig { /** Cloud WS URL. When set + autoconnect=true, `agentproto serve` * bootstraps with `--connect `. */ host?: string; /** apt_ daemon token to present at the tunnel upgrade. When set, * `agentproto serve` uses this BEFORE falling back to * credentials.json — handy in profiles where the token-per-host * mapping in credentials.json doesn't fit (e.g. host = tunnel URL * but credentials were minted against the api URL). */ token?: string; /** Whether `agentproto daemon start` connects the tunnel by * default. v0 only — implementer can ignore until daemon needs it. */ autoconnect?: boolean; /** * Opt into end-to-end encryption of the outbound `serve --connect` tunnel * (design: tunnel-e2e/v1). When true, the daemon negotiates a * token-authenticated ephemeral handshake with the host and wraps the tunnel * frames in an AEAD box, so even the trusted host loses plaintext visibility. * The handshake authenticates both ends against the shared `tunnel.token`, so * `token` MUST also be set. Fully backward-compatible: if the host doesn't * advertise e2e (an older host), the daemon falls back to today's plaintext * tunnel. Unset/false ⇒ plaintext, byte-identical to today. */ e2e?: boolean; } interface FeaturesConfig { /** Hint that PTY is desired — informational; the daemon still * detects node-pty's presence at runtime. */ pty?: boolean; /** Enable the local LLM Endpoint proxy sidecar (route registration, * MCP tools, child-process lifecycle). Default false — the endpoint is * an opt-in feature; when off, the `llm-endpoint` custom route is not * registered and the `llm_endpoint_*` MCP tools are not exposed. */ llmEndpoint?: boolean; /** Expose this daemon's local inference endpoint(s) (the `llmEndpoint` * sidecar above) to paired controllers over a HOST-scoped pairing — * `GET /device-inference/v1/models` + `POST * /device-inference/v1/chat/completions` in http-server.ts. Default * false: even with `llmEndpoint` on, a plain remote-control pairing (or * `serve --connect`) never gets these routes regardless of this flag — * it also requires the pairing itself to be host-scoped (`pair offer * --host` + `devices add`). Toggle via `agentproto devices * share-inference on|off`. */ deviceInferenceShare?: boolean; /** Opt this daemon in to being usable as an `agent_start({ sandbox: * "device:" })` target (DEVICES-PLAN PR-D) — exposes * `/device-spawn/*` in http-server.ts, a self-proxy onto this daemon's * own `/mcp` + `/sessions/:id/events/stream`. Default false: even with * this on, only a HOST-scoped pairing (`pair offer --host` + `devices * add`) can reach the routes — a plain remote-control pairing never can, * whatever this is set to. Toggle via `agentproto devices allow-spawn * on|off`. */ deviceSpawnAllow?: boolean; } /** * Policy for `agentproto worktree new` (PLAN.md §1.4 — config carries * policy, never state; git itself is the authority for which worktrees * exist). This is the fix for the sprawl the plan measured: 31 linked * worktrees across 6 different parent directories, because there was no * `worktree new` verb and therefore no convention to converge on. */ /** * How the daemon isolates a freshly-spawned agent session into its own git * worktree (`agent_start.worktree`): * - `"always"` — every depth-0 spawn is provisioned into a worktree, * whether or not the caller asked. A cwd that is not in * a git repo has nothing to isolate, so it spawns plain. * - `"on-request"` — isolate ONLY when the caller passes `worktree`. This * is the default and the back-compatible behaviour: * today's callers pass nothing and spawn exactly where * they asked. * - `"never"` — isolation is off; an explicit `worktree` field is * REJECTED (loud, not silently ignored) so a caller * never believes it got an isolated tree it didn't. */ type WorktreeIsolationMode = "always" | "on-request" | "never"; interface WorktreesConfig { /** * Absolute path new worktrees are created under. Layout: * `//`. Resolution order (mirrors every other * knob in this file, see the module docblock): `--root` flag > * `AGENTPROTO_WORKTREES_ROOT` env > this field > the hardcoded default * `~/.agentproto/worktrees`. The default is a real single root, not * "unconfigured" — `worktree new` converges to one place with zero * setup, which is the only way the sprawl actually stops (the 6 roots * that exist today are 6 people each inventing a default by hand). */ root?: string; /** * Extra directories `agentproto maintain --all` scans for worktrees, in * addition to `root`. For pools that live outside `root` (a repo's own * `_worktrees/`, sibling `*-wt-*` dirs). Each dir holds worktrees directly * (`/`) or in buckets (`//`); `~/` expands. * The `--worktrees-root` flag adds to this list, it does not replace it. */ extraRoots?: string[]; /** * Policy for `agent_start.worktree` isolation. Resolution order mirrors * the module docblock (there is no CLI flag — this is a daemon-side * policy read at spawn, not a per-invocation flag): * `AGENTPROTO_WORKTREES_ISOLATION` env > this field > the hardcoded * default `"on-request"`. `"on-request"` is deliberately the default: * any other would break back-compat by isolating callers that never * asked (see `worktree-isolation.ts`). */ isolation?: WorktreeIsolationMode; /** * Max worktree provisionings running their HEAVY phases (`cloneGlobs`, * `depsCmd`, `copyGlobs`, the `worktree.setup` hooks) at once, daemon-wide. * A burst of `agent_start({worktree})` spawns otherwise runs that many * concurrent `pnpm install`s against one store on one disk (the 2026-09-28 * incident: load average 170, installs 3.5x slower). The rest wait in a * FIFO queue, fair across spawning callers. `git worktree add` and the * cheap prep stay unthrottled. Resolution order: * `AGENTPROTO_WORKTREES_PROVISION_CONCURRENCY` env > this field > the * default `2`. An integer >= 1; `0` means unlimited (the pre-queue * behavior). Invalid values fall back to the default. */ provisionConcurrency?: number; /** * Per-repo overrides of {@link provisionConcurrency}, additional to (never * looser than) the global cap. Keys are an absolute repo-root path (`~/` * expands) or a bare repo directory name; values as above. Example: * `{ "demo-app": 1 }` serializes installs of that repo even when * other repos may install two at a time. */ provisionConcurrencyByRepo?: Record; /** * Optional load guard: hold back starting a NEW heavy segment while the * 1-minute load average exceeds `cores x provisionLoadFactor`. Unset / `0` * = off (the default). Never blocks when nothing is running, so a loaded * host cannot deadlock the queue. */ provisionLoadFactor?: number; /** * Boot stall timeout for a provisioning, in ms: when the deps / setup-hook * process prints nothing for this long, its process tree is killed and the * session fails with `error` (phase, last output lines, elapsed). A slow * setup that keeps printing never trips it. `0` disables. Resolution order: * `agent_start.worktree.stallTimeoutMs` > env * `AGENTPROTO_WORKTREES_PROVISION_STALL_TIMEOUT_MS` > this field > the * default `120000`. */ provisionStallTimeoutMs?: number; /** * Hard cap on one provisioning's heavy segment, in ms (counted from when it * gets its slot, not while queued); same failure path as the stall timeout. * `0` disables. Resolution order: `agent_start.worktree.maxMs` > env * `AGENTPROTO_WORKTREES_PROVISION_MAX_MS` > this field > the default * `1800000` (30 min). */ provisionMaxMs?: number; } /** * Where `maintain_run` reports: the same shape as the `maintain` workflow's * `notify` input (`{ provider?, alias?, address?, source? }`, plus the * legacy `channel`). Passed to the workflow verbatim. */ interface MaintainNotifyConfig { provider?: "telegram" | "agentpush"; alias?: string; address?: string; source?: string; channel?: string; } /** * `maintain`: which repos the repo-maintenance runs cover, and the run * defaults, for `agentproto maintain --all` and the daemon's `maintain_run` * tool. Everything personal to one operator (which repos, the notification * target) lives here, in the uncommitted user config, so the shipped * routines stay generic. * * Repo list = (workspaces ? registered non-app workspaces that are a repo * toplevel : none) + (discover ? repos owning a worktree under * `worktrees.root` + `worktrees.extraRoots` : none) + `repos`, minus * `exclude`, deduped by * realpath of each repo's main toplevel. Explicit `--repo` / `repos` inputs * are added on top and are not filtered by `exclude`. */ interface MaintainConfig { /** Include every workspace registered in `~/.agentproto/workspaces.json` * (`agentproto workspace add`) that is not app-owned (`ownerApp`) and * whose path is a git repo's toplevel. Default true. */ workspaces?: boolean; /** Discover repos owning a worktree under the worktrees roots. Default true. */ discover?: boolean; /** Extra repos (any dir inside one; `~/` expands), added to discovery. */ repos?: string[]; /** Repos left out (any dir inside one; `~/` expands). */ exclude?: string[]; /** Default `maxReviews` per run when the caller gives none. */ maxReviews?: number; /** Default reviewer model preset when the caller gives none. */ reviewPreset?: string; /** Default report target when the caller gives none. */ notify?: MaintainNotifyConfig; } /** * Policy for `agent_start.attach` — whether a spawn AUTO-attaches to its * calling session as parent lineage. `"always"` (the default) nests a * spawned child under the session that spawned it whenever that identity is * derivable (the trusted `?callerSessionId=` on the daemon self-ref URL, or * an explicit `parentSessionId` hint), so a supervisor's executors stop * landing as depth-0 orphans. `"on-request"` reverts to the pre-attach * behaviour: auto-attribution is off, and a child nests only when the caller * explicitly opts in (`attach: true` / `attach: { parent }` / an explicit * `parentSessionId`). Either way a per-call `attach: false` forces an * independent root, exactly as `worktree: false` opts out of isolation. See * `spawn-attach.ts`. */ type SpawnAttachMode = "always" | "on-request"; /** * Policy for `agent_start`'s IMPLICIT dedupe — what happens when a caller * spawns with NO `idempotencyKey` at all (see `spawn-dedupe.ts`): * - `"always"` — the daemon DERIVES an implicit key from the spawn's * `label` (required — see below) plus a hash of the * initial `prompt`, and dedupes a same-adapter/cwd * repeat against it exactly as an explicit key would. * This is the default, mirroring `attach`'s own * "opt-in-only guard is not a guard" precedent above. * Deriving needs a `label` to produce anything at all * — an unlabelled spawn is untouched, which is what * keeps this safe for the fan-out pattern this repo * exercises (several agents into one cwd with no * shared label): see `spawn-dedupe.ts`'s docblock for * the full false-dedup analysis, and PR #803's own * no-opt-in label+cwd warning backstop in * `session-spawn.ts`, which independently landed on * the same label-is-the-signal boundary. * - `"on-request"` — no implicit derivation; only an explicit * `idempotencyKey` dedupes (today's behaviour, * unchanged). A per-call `dedupe: true` still opts in * under this policy, mirroring `attach: true`. * Either way a per-call `dedupe: false` disables implicit derivation for * that one spawn regardless of policy — the escape hatch, mirroring * `attach: false` / `worktree: false`. An explicit `idempotencyKey` always * wins over a derived one (derivation is only attempted when the caller * supplied none). */ type SpawnDedupeMode = "always" | "on-request"; interface SpawnConfig { /** * Attach policy for `agent_start`. Resolution order mirrors the module * docblock (no CLI flag — a daemon-side policy read at spawn): * `AGENTPROTO_SPAWN_ATTACH` env > this field > the hardcoded default * `"always"`. Unlike `worktrees.isolation` (whose default preserves * back-compat by NOT isolating), attach defaults ON: an orphaned executor * is a bug, not a feature, and the auto-parent is descriptor-only lineage * that never relaxes a privilege gate. */ attach?: SpawnAttachMode; /** * Implicit-dedupe policy for `agent_start`. Resolution order mirrors * `attach` above (no CLI flag — a daemon-side policy read at spawn): * `AGENTPROTO_SPAWN_DEDUPE` env > this field > the hardcoded default * `"always"`. See {@link SpawnDedupeMode} and `spawn-dedupe.ts` for the * full reasoning: a retry-safety guard that only works when a caller * remembers to ask for it (`idempotencyKey`) is not a guard — the same * argument `attach` already settled for parent lineage. */ dedupe?: SpawnDedupeMode; } /** * Provenance policy — the opt-in `gh` PATH shim (`gh-provenance-shim.ts`). * Off by default. When `wrapGh` is on, every agent session the daemon spawns * gets a shim directory prepended to its PATH so that any `gh pr create` the * session (or an adapter subprocess shelling out — claude-code, codex, …) runs * has a deterministic `@agentproto-bot` provenance footer appended to the * created PR's BODY, matching the footer the cloud runner stamps. The TOOL * stamps, never the model; commit messages are never touched (the repo's * hygiene-check forbids attribution there). Resolution order mirrors * `spawn.attach`: `AGENTPROTO_PROVENANCE_WRAP_GH` env > this field > default * `false`. */ interface ProvenanceConfig { /** Enable the opt-in `gh` provenance PATH shim for spawned sessions. */ wrapGh?: boolean; } /** * Approvals policy (`packages/runtime/src/approvals/`, E1a) — config for * the `web_click` human decision channel. See AIP-7 * (https://agentproto.dev/docs/aip-7) for the full channel design. */ interface ApprovalsConfig { /** * Origins allowed to decide a pending approval through `POST * /approvals/:id/decision` (in addition to the daemon's own per-boot * bearer token, which is ALWAYS required on that route regardless of * this list). Default empty — `web_click` is OFF until at least one * origin is configured. Lockout-shaped like `daemon.allowedOrigins`, * but a SEPARATE list: the general browser-origin allowlist is not * automatically trusted to decide approvals. */ webOrigins?: string[]; /** * Shared secret gating the `telegram` decide route (`POST * /approvals/:id/decision/telegram`) — presented by a trusted bot-bridge * service in place of `web_click`'s browser Origin (a Telegram webhook * callback has none). Default absent — `telegram` is OFF until set. */ telegramBotSecret?: string; /** * Telegram tap-to-approve for the pending-permissions inbox * (`permission-telegram-bridge.ts`). The bridge starts only when BOTH * `permissionTelegramChatId` and a non-empty `permissionTelegramUserIds` * are set; default absent = no bridge, no behaviour change. Chat that gets * the approval messages and the only chat taps are accepted from. */ permissionTelegramChatId?: string; /** Telegram user ids allowed to tap Allow/Reject. */ permissionTelegramUserIds?: string[]; /** Bot credential alias (`telegram_bot_token_set`) and the signed telegram * inbound endpoint alias that receives the taps. Default `"default"`. */ permissionTelegramAlias?: string; /** Tool names mirrored to Telegram. Default `["send_message"]`. */ permissionTelegramTools?: string[]; /** * Also send each pending approvals-engine record (`approval:requested`, * e.g. a Bureau recipe write) to the same Telegram chat as an * Approve / Refuse card (`approval-telegram-bridge.ts`). Reuses * `permissionTelegramChatId`, `permissionTelegramUserIds` and * `permissionTelegramAlias`; does nothing unless those are set. Default * false. Turning it on also adds `telegram` to new approvals' `channels`. */ telegramApprovalCards?: boolean; /** * Send the files named in `preview.attachments` to the Telegram chat as * documents and photos before the approval card. Default false: the card * only names them. Read at boot; lockout key (`writable: false`). */ telegramAttachments?: boolean; /** * Telegram user ids (digits only) allowed to read and decide ONE pending * approval through an approval link: a link-session token whose * `approvalId` claim equals the route's id, on `GET /approvals/:id` and * `POST /approvals/:id/decision/telegram` (`app-link-gate.ts`, * `approvals/http.ts`). Default empty = approval links are off. Lockout * key (`writable: false`): an agent must not widen who can approve. */ humanTelegramIds?: string[]; } /** * REACH (`reach/`): how the daemon reaches its human. `routes.` is * the ordered list of adapter instances for that principal; only `owner` is * read today. Absent or empty: no router, the Telegram approval bridge * announces on its own exactly as before. Read at boot; lockout key, and each * webhook `secret` and chat-sdk `accessToken` is redacted on read. */ interface ReachConfig { routes?: Record; } /** * MCP gateway policy (top-level `mcp`). Distinct from `defaults.mcp`, which * configures the MCP servers a SPAWN mounts. */ interface McpConfig { /** How a tool call that reaches the gateway WITHOUT a caller identity * (Claude Code / Claude Desktop talking to the MCP server directly, no * `?session=` / bearer caller) is handled. `block` (default) refuses with * `no_caller_identity`; `accept` allows an identity-less `message_send` * to go out as the anonymous literal sender `claude-code` (never as any * session, never an ACL elevation); `ask` parks the send on a human * approval before delivering it. */ noCallerIdentity?: "block" | "ask" | "accept"; } /** * Sentinel auto-link policy (AIP-60 §6, step 4) — whether a PR an executor * session opens gets a sentinel created for it automatically. */ interface SentinelConfig { /** Auto-watch a PR when a session opens one (`recordOpenedPr`, fed by * `command_execute`'s stamper and the reconciler's tool-call and * branch→PR lanes; PRs merely mentioned in a session's output are not * auto-watched). When unset, the daemon defaults to `true` only when the * `local-gh` provider is available (i.e. `gh auth status` succeeds) — * otherwise `false`, logged once. Explicitly setting this always wins * over that probe. Per-spawn opt-out: `agent_start.sentinel: false`. */ autoWatchPrs?: boolean; /** Urgency the auto-created PR sentinel delivers at (`fyi` | `next-turn` | * `steer` | `interrupt`). Default `"next-turn"`. Read per PR, so a * `config_set` applies to the next one without a restart. */ autoWatchUrgency?: "fyi" | "next-turn" | "steer" | "interrupt"; /** Signal-routing rule table (`@agentproto/sentinel`'s `sentinel-routes.ts`): * which provider should carry which subject. Shadow only for now: the * router decides, logs to `~/.agentproto/sentinel-routing.jsonl` and * stamps `route` on the sentinel, it never changes the provider used. */ routes?: SentinelRoute[]; routing?: { /** `shadow` (default). `enforce` is accepted but not applied yet. */ mode?: SentinelRoutingMode; }; } /** * Delivery-kernel application policy (`@agentproto/delivery`). Which event * types a producer hands to the kernel's level mapping; everything not opted * in keeps its original delivery path. */ interface DeliveryConfig { apply?: DeliveryApplyConfig; } /** * Session-follow policy (`session-follow.ts` + `follow-triage.ts`). */ interface FollowConfig { /** Daemon-wide triage default for every session-follow digest: classify * each event `wake`/`fyi`/`drop` BEFORE a digest is allowed to wake the * follower. OFF by default. A follow's own `triage` block overrides it. */ triage?: FollowTriageInput; } /** * Review-primitive host policy (`@agentproto/review` + `review-runner.ts`). */ interface ReviewConfig { /** The owner identity attestation signatures claim (`attestor.signature. * principal`) — see `review-signing.ts`'s `resolvePrincipal`. When unset, * the daemon falls back to `git config user.email` of the reviewed repo, * then a host-derived value; this never blocks signing, it only lets an * operator pin one identity across every repo the daemon reviews. */ principal?: string; /** Extra attempts for an agent lane whose reviewer turn ends in a * transient error (dropped socket, 5xx, overloaded provider). Auth, * quota and unknown-model errors are never retried. Default 1; `0` * disables; capped at 5. All attempts share the lane's `timeoutMs`. */ laneRetries?: number; /** Reviewer presets (harness/user preset ids — the same surface lanes use, * so the OpenRouter-billing guard and wallet cooldowns apply) the bounded * verdict-RECOVERY step may run on, tried in order. That step runs only * when a reviewer ends its turn without a valid verdict file: a small, * read-only, tool-less model reads the reviewer's own latest output and * either recovers its stated conclusion or classifies why it failed. * Prefer a small subscription/free route. Unset or empty ⇒ no recovery * model: such a lane is left incomplete (`recovery.outcome: * "unavailable"`). The `review.recovery` model role (`models` block) * overrides the model/profile these presets would run. */ recoveryPresets?: string[]; } /** * Session-presence policy — how the dashboard triages a session into its * `running` / `tending` / `attention` / `quiet` presence state (see * `session-presence.ts`). Optional block on `AgentprotoConfig.sessions`. */ interface SessionsConfig { /** * How long (seconds) a session stays shown as `running` after its last * turn ends, before it settles into `attention`/`quiet`. The grace window * is measured from the session's most recent `lastActivityAt` — ANY new * event resets it — so a session that just answered does not read as * "quiet" the instant its turn finishes, but something that went idle long * ago, with nothing waiting on it, settles grey. Resolution order mirrors * every other knob in this file (module docblock): env var * `AGENTPROTO_SESSIONS_ATTENTION_DELAY_SEC` > this field > the hardcoded * default `60`. Absent ⇒ 60s. */ attentionDelaySec?: number; /** * Root directory the daemon stores per-session transcripts under — each * session's `events.jsonl` lands at `//events.jsonl` * (and a terminal session's `terminal.jsonl` alongside it). Every * reader/writer (transcript writer, `/sessions/:id/events` HTTP routes, * exports, tool-call/usage logs) resolves through this single knob. * Resolution order mirrors every other knob in this file: relative paths * resolve against the home directory. Absent ⇒ the hardcoded default * `~/.agentproto/sessions` — zero behaviour change out of the box. A * change requires a daemon restart to take effect (and existing sessions' * transcripts do NOT move). */ eventsDir?: string; } /** * Where the daemon's AIP-72 memory store lives (`memory-stores.ts`). The * `memory_*` MCP tools and the spawn digest read the store at this root * unless an agent's AIP-42 `memory.store` names its own files root. */ interface MemoryStoreConfig { /** * Root of the default reference-layout store (`items//.md`, * `proposals/.md`). Absolute, `~/`, or relative to the home * directory. Read at boot; unset means `~/.agentproto/memory`. */ root?: string; } /** * Policy for the daemon's own AGENTS.md resolution + injection (WP-R2) — * how a spawned session's initial prompt carries the repo's `AGENTS.md` * (see `agents-md.ts`). The daemon resolves the nearest `AGENTS.md` walking * up from the session's `cwd`, bounded by that repo's git toplevel, and * injects one AGENTS.md block after the role disposition whenever the spawn * carries a prompt. */ interface AgentsMdConfig { /** * Inline-vs-pointer threshold in KiB. A resolved AGENTS.md whose byte size * is STRICTLY LESS than `inlineMaxKb` KiB is inlined in full into the * spawn's initial prompt, clearly delimited; `>=` the threshold is injected * as a short pointer telling the agent to read the file before its first * tool call instead. An absent AGENTS.md (nothing found up the walk) injects * nothing but is still reported on the descriptor via * `SessionDescriptor.agentsMdMode === "absent"`. Resolution order mirrors * the module docblock (no CLI flag, and no env override — not part of the * approved design): this field > the hardcoded default `8` (KiB). */ inlineMaxKb?: number; } interface PairingConfig { /** Rendezvous broker WS URL (ws:// or wss://) used by `pair offer` and by * autoconnect on boot. When unset, `pair offer` requires an explicit * `--rendezvous`. Mirrors `tunnel.host`. */ rendezvous?: string; /** Whether the daemon opens standing rendezvous connections for every * persisted pairing on boot (so a paired client can reconnect anytime). * Mirrors `tunnel.autoconnect`. Default true when a rendezvous is set. */ autoconnect?: boolean; /** Web pair page for `pair offer --qr` (the offer rides in its fragment). * A template with `{fp}` in the HOSTNAME, filled with the daemon * fingerprint (one origin per daemon), or a plain http(s) URL (one shared * origin). Unset → `https://{fp}.agentproto.cloud/pair`. `--pair-page` * overrides it. */ pairPage?: string; } /** * A user-defined generic ACP agent — the config-file half of * `AcpAgentSpec` (the slug is the record key in `acpAgents`, so it's * omitted here). Any CLI that already speaks the Agent Client Protocol * can be wired with zero code by declaring one of these under * `acpAgents.` in `~/.agentproto/config.json`; the CLI's * `acpHandleFromSpec` mints a runnable `AgentCliHandle` from it at * resolve time (see `packages/cli/src/registry/acp-generic.ts`). Kept * in this package (not the CLI's) so `config.ts` stays the single * source of truth for the config surface without a cli→runtime→cli * import cycle — the CLI's `AcpAgentSpec` extends this shape. */ interface AcpAgentConfigEntry { /** Display name. Defaults to the slug when omitted. */ name?: string; /** One-line description surfaced in `agentproto acp ls`. */ description?: string; /** Executable to spawn, e.g. "gemini". */ bin: string; /** Extra argv appended after `bin`, e.g. ["--experimental-acp"]. */ bin_args?: string[]; /** Extra environment variables for the spawned process. */ env?: Record; /** Flag the CLI uses to receive the working directory, if it needs * one passed explicitly (most ACP agents take cwd over the wire). */ cwd_flag?: string; /** When true, advertise resumable + native-resume continuation. */ resumable?: boolean; /** Known model ids for the agent (informational + validation hints). */ models?: { default?: string; allowed?: string[]; }; /** Billing endpoint this CLI's own auth bills (e.g. "mistral", * "moonshot", "google") — the provider whose wallet/auth-profile the * agent consumes. Lets clients link the harness to that provider's * wallets even when no model list is declared. Unset when the CLI's * billing target isn't a single known endpoint. */ provider?: string; /** Shown when `bin` is missing from PATH (how to install the CLI). */ install_hint?: string; /** Declare `capabilities.deferredToolDiscovery`: the CLI can call an MCP tool * that the daemon hid from `tools/list` after finding it via `tool_search`. * Only set it after proving that live: it makes the daemon's self-mount * deferred by default for this harness (a small-context CLI otherwise loads * every daemon tool schema up front and starts near its context limit). */ deferred_tool_discovery?: boolean; /** Slash-command names (no leading `/`) a session of this agent may run on * itself via `session_command_self`. Absent/empty ⇒ none. */ self_commands?: string[]; } /** * Per-environment connection bundle. A profile overrides specific * fields of the top-level `daemon` / `tunnel` / `features` blocks * when selected via `--profile ` (or the top-level * `activeProfile` setting). Missing fields fall through to the * top-level config, so a profile only needs to declare what's * different — typically just `tunnel.host` + `tunnel.token`. * * Example: * { * "daemon": { "workspace": "/code", "port": 18790 }, * "activeProfile": "local", * "profiles": { * "local": { "tunnel": { "host": "ws://localhost:3200/connect", * "token": "apt_local", "autoconnect": true } }, * "prod": { "tunnel": { "host": "wss://tunnel.example.com/connect", * "token": "apt_prod", "autoconnect": true }, * "daemon": { "port": 18791 } } * } * } * * Sandbox daemons generate per-sandbox profile entries at provision * time so the daemon inside the sandbox boots with * `agentproto serve --profile sandbox-` and no extra plumbing. */ interface ProfileConfig { daemon?: DaemonConfig; tunnel?: TunnelConfig; features?: FeaturesConfig; } /** * A user-defined named terminal/TUI preset stored in * `~/.agentproto/config.json` under `terminalPresets`. Presets keep * local launch recipes (argv, env, cwd, name/label) out of shared * adapter manifests — e.g. pointing a Claude Code TUI at a local * LLM gateway without retyping proxy env vars every spawn. */ interface TerminalPreset { /** Command + args to spawn. When provided, `sessions terminal` can * be used without `-- `. */ argv?: string[]; /** Extra environment variables layered on top of the daemon's * inherited process.env. Values MUST be strings. */ env?: Record; /** Working directory for the PTY session. Relative paths are * resolved against the current working directory at CLI time. */ cwd?: string; /** Workspace slug used for cwd fallback when `cwd` is omitted. */ workspace?: string; /** Stable session name passed to the registry (`name` field). */ name?: string; /** Human-readable label surfaced in session listings. */ label?: string; /** Named auth profile (e.g. `claude-subs-agentik`, an OpenCode Go profile) * the provider TUI bills instead of the daemon's ambient login. Resolved * by the daemon at spawn (`resolveTerminalAccess`); an unresolvable * profile refuses the spawn rather than falling back. */ accessProfile?: string; } interface AppsConfig { /** appId -> absolute paths outside the app folder the app may READ * (never write). Validated by `app-read-grants.ts`; hand-edit only. */ readGrants?: Record; [unknown: string]: unknown; } interface AgentprotoConfig { version?: number; daemon?: DaemonConfig; tunnel?: TunnelConfig; features?: FeaturesConfig; /** E2E daemon-pairing defaults (rendezvous URL + autoconnect). */ pairing?: PairingConfig; /** Where `agentproto worktree new` creates worktrees. See * {@link WorktreesConfig}. */ worktrees?: WorktreesConfig; /** Repo-maintenance repo set + run defaults (`maintain --all`, * `maintain_run`). See {@link MaintainConfig}. */ maintain?: MaintainConfig; /** Spawn-time policy (`agent_start`). See {@link SpawnConfig}. */ spawn?: SpawnConfig; /** Session-presence policy for the dashboard. See {@link SessionsConfig}. */ sessions?: SessionsConfig; /** Provenance policy — the opt-in `gh` PATH shim. See {@link ProvenanceConfig}. */ provenance?: ProvenanceConfig; /** Approvals policy — the `web_click` origin allowlist. See {@link ApprovalsConfig}. */ approvals?: ApprovalsConfig; /** How the daemon reaches its human. See {@link ReachConfig}. */ reach?: ReachConfig; /** MCP gateway policy. See {@link McpConfig}. */ mcp?: McpConfig; /** Sentinel auto-link policy. See {@link SentinelConfig}. */ sentinel?: SentinelConfig; /** Session-follow policy (triage). See {@link FollowConfig}. */ follow?: FollowConfig; /** Delivery-kernel application policy. See {@link DeliveryConfig}. */ delivery?: DeliveryConfig; /** Review-primitive host policy. See {@link ReviewConfig}. */ review?: ReviewConfig; /** Daemon-side AGENTS.md resolution/injection policy. See {@link AgentsMdConfig}. */ agentsMd?: AgentsMdConfig; /** The default AIP-72 memory store. See {@link MemoryStoreConfig}. */ memory?: MemoryStoreConfig; /** Model roles: ROLE → model id (or `{ model, route?, profile? }`), the * one place reviewer/judge models are configured. Layer 3 of the * precedence documented in `model-roles.ts` (input > workspace * `agentproto.json` > this > built-in default). Role names contain dots, * so `getConfigKey`/`setConfigKey` treat everything after `models.` as * ONE key (`models.review.pr` → `models["review.pr"]`). */ models?: ModelRolesConfig; /** Active model role preset (`MODEL_ROLE_PRESETS` in `model-roles.ts`): * one key to switch the review roles between named model sets. Layer 4 * of the role precedence — an explicit `models.` still wins. */ modelRolePreset?: string; /** Daemon-side session titler (`session-titler.ts`). DEFAULT OFF — when * `enabled` is not explicitly true the titler is a complete no-op and * nothing renames anything. When on, at the end of the FIRST completed * turn of a `kind:"agent-cli"` session whose label is still a spawn * default (`chat-starter`, `chat-starter-autoprompt`, `agentproto`, empty, * or equal to the derived title), the daemon generates a short prosaic * title (4-8 words) from the first turn's transcript and renames the * session via the same write path as `session_rename`. Generation tries * OpenRouter (`model`, default `z-ai/glm-5.2@openrouter`, needs * `OPENROUTER_API_KEY`) and falls back locally (first line of the first * user prompt, 6 whole words) on any failure. A user-created label is * NEVER overwritten, and a session is titled at most once. */ titler?: TitlerConfig; /** Jev judge backend settings (`jev-client.ts`). See {@link JevConfig}. */ jev?: JevConfig; /** App catalog settings (`app-catalog.ts`). See {@link CatalogConfig}. */ catalog?: CatalogConfig; /** Named connection profiles. See `ProfileConfig` for the merge * semantics — a profile's fields shallow-override the top-level * defaults for the selected run. */ profiles?: Record; /** Profile name to use when `--profile` isn't passed. When unset, * the top-level `daemon` / `tunnel` blocks are used directly. */ activeProfile?: string; /** Account slots (AIP-46 access axis): slot name (no dot) -> real auth * profile id. A `profileRef` of `slot:` resolves through this map at * the moment of use (`resolveProfileRef`, `account-slots.ts`). A value is * one profile id, or an ordered list of profile ids: the slot then resolves * to the first account that is enabled, may run the model and is not * `exhausted` in `account-health.json`. */ accountSlots?: Record; /** Default `skills` + `options` auto-applied to every `agent_start` * spawn — global and per-adapter. See `resolveSpawnDefaults` in * `spawn-defaults.ts` for the merge precedence with an explicit call. * Absent ⇒ current behaviour exactly (no regression). */ defaults?: SpawnDefaultsConfig; /** User-defined generic ACP agents, keyed by adapter slug. Each entry * is minted into a runnable handle by the CLI's `acpHandleFromSpec` * when `resolveAdapter(slug)` finds no npm adapter package. User * entries shadow the curated `ACP_CATALOG` on slug collision. */ acpAgents?: Record; /** User-defined named terminal/TUI presets. Local-only; never * packaged in shared adapter manifests or defaults. */ terminalPresets?: Record; /** Operator-side settings for installed apps. Never read from an app * manifest: an app cannot grant itself anything here. */ apps?: AppsConfig; /** Unknown keys preserved across save round-trips. */ [unknown: string]: unknown; } declare const CONFIG_FILE_PATH: () => string; /** * The deprecated `adapter` spellings a config still uses, one dated line * each. Read-only: the daemon never rewrites the file to migrate them; the * old keys keep working as a fallback of the new ones. */ declare function harnessConfigDeprecations(cfg: AgentprotoConfig): string[]; /** `daemon.harnessCacheRetentionDays`, falling back to the deprecated * `daemon.adapterCacheRetentionDays`. */ declare function harnessCacheRetentionDays(cfg: AgentprotoConfig): number | undefined; /** * Load config.json. Returns an empty object (NOT null) when the file * is missing, malformed, or unreadable — callers can `cfg.daemon?.port` * safely without null-guards. Errors during a malformed-read are * logged once so the user notices the file is broken without the * daemon refusing to boot. */ declare function loadConfig(path?: string): Promise; /** * Write config.json atomically (tmp + rename) so a concurrent * `agentproto config edit` can't half-truncate the file. Writes * `next` AS-IS — callers are expected to pass the full desired * state (loaded the existing config, mutated, passed it back). * * Earlier versions deep-merged with the on-disk file, but that made * deletions impossible: `setConfigKey(cfg, "x", undefined)` would * remove the key from memory, then the deep-merge would silently * re-add it from disk. The current design trusts the caller's * snapshot and uses atomic rename for crash safety. */ declare function saveConfig(next: AgentprotoConfig, path?: string): Promise; /** Split a dotted key into path segments. `models.` is the one * exception: role names are themselves dotted (`review.pr`), so everything * after `models.` is a single segment. */ declare function splitConfigPath(dotted: string): string[]; /** * Read a dot-notation key (`daemon.port`) out of a config. Returns * `undefined` when any segment is missing. */ declare function getConfigKey(cfg: AgentprotoConfig, dotted: string): unknown; /** * Set a dot-notation key in a config. Returns a new object — does * NOT mutate. Creates intermediate objects as needed. Setting * `value: undefined` is treated as a delete. */ declare function setConfigKey(cfg: AgentprotoConfig, dotted: string, value: unknown): AgentprotoConfig; export { type WorktreeIsolationMode as $, type ApprovalsConfig as A, type FollowTriageInput as B, type CatalogConfig as C, type DaemonConfig as D, type FollowTriageRules as E, type FeaturesConfig as F, MODEL_ROLE_PRESET_NAMES as G, MODEL_ROLE_REF_PREFIX as H, type ModelRoleContext as I, type ModelRoleEntry as J, type ModelRolePreset as K, type ModelRoleSource as L, type McpConfig as M, type ModelRoleValue as N, type ModelRolesConfig as O, type PairingConfig as P, SESSION_LIFECYCLE_CLASSIFIER_ID as Q, type ReachConfig as R, type SpawnConfig as S, type TunnelConfig as T, type SessionFollow as U, type SessionLifecycleClassifierOptions as V, type WorktreesConfig as W, TRIAGE_RULES as X, type TriageDecision as Y, type TriageEvent as Z, type TriageResult as _, type MaintainConfig as a, adapterForModelId as a0, classifyFollowEvent as a1, createSessionFollowStore as a2, createSessionLifecycleClassifier as a3, defaultFollowTriageConfig as a4, evaluateFollowEvent as a5, followEnvelopeType as a6, followFloor as a7, isTriageDecision as a8, levelOfDecision as a9, listModelRoles as aa, parseClassifierAnswer as ab, parseModelRoleRef as ac, resolveFollowTriageConfig as ad, resolveModelRole as ae, runFollowTriageClassifier as af, triageEventFromEnvelope as ag, triageFollowEvent as ah, type SpawnAttachMode as ai, type SpawnDedupeMode as aj, type AppsConfig as ak, CONFIG_FILE_PATH as al, CONFIG_VERSION as am, type CatalogSourceConfig as an, type FollowConfig as ao, type JevConfig as ap, type ReviewConfig as aq, getConfigKey as ar, harnessCacheRetentionDays as as, harnessConfigDeprecations as at, loadConfig as au, saveConfig as av, setConfigKey as aw, splitConfigPath as ax, type SessionsConfig as b, type ProvenanceConfig as c, type AgentsMdConfig as d, type MemoryStoreConfig as e, type DeliveryConfig as f, type SentinelConfig as g, type TitlerConfig as h, type ProfileConfig as i, type AcpAgentConfigEntry as j, type TerminalPreset as k, type MaintainNotifyConfig as l, type AgentprotoConfig as m, type ResolvedModelRole as n, MODEL_ROLE_PRESETS as o, type SessionFollowStore as p, type FollowTriageConfig as q, type TriageFacts as r, DEFAULT_FOLLOW_TRIAGE_CLASSIFIER_TIMEOUT_MS as s, DEFAULT_FOLLOW_TRIAGE_REPORT_WINDOW_MS as t, DEFAULT_FOLLOW_TRIAGE_RULES as u, DEFAULT_MODEL_ROLES as v, FOLLOW_EVENTS as w, FOLLOW_TRIAGE_DECISIONS as x, type FollowEvent as y, type FollowTriageClassifier as z };