import { S as SessionDescriptor, a as SessionsRegistry, b as SandboxProviderResolver, P as PrFooterState, c as SessionEventBus, T as ToolCallRecord, G as GhRunner$1, I as InboundRouteMode, W as WorkspaceBrains, A as AccountSlots, E as EventRing, d as AgentAdapterResolver, e as SpawnAgentSessionDeps, U as UserPreset, f as SpawnAgentSessionInput, M as ModelPolicy, B as BrowserAdapterResolver, g as BrowserAdapterLister, h as BrowserAdapterInfo, i as SandboxProviderHandle, j as PendingPromptView, k as StatsSessionDescriptor, l as ProcRow, m as ProvisionInFlight, n as ProvisionTracker, o as SessionCrashReason, p as SessionUsage, q as UsageReadResult, r as UsageRollup, R as RemainingQuotaReader, Q as QuotaReadableProfile, s as UsageSnapshotRecord, t as SessionMessage, u as QueuedDigest, v as QueuedPrompt, F as ForwardHttpRequest, w as ForwardHttpResponse, H as HostRegistry, J as JoinTokenRegistry, x as SessionAwaitingQuestion, C as CompletionPolicySupervisor, y as PolicyRunState, z as AccountSlotSwapPlan, D as AccountSlotPreferPlan, K as AccountHealthStore, L as ResolveProfileRefDeps, N as AccountHealthView, O as StoredProfileQuota, V as AuthOptions, X as AgentAdapterLister, Y as AdapterCapabilitiesLister, Z as AgentAdapterInstaller, _ as CatalogModelsLister, $ as PtyFactory, a0 as SandboxProviderLister, a1 as WorktreeProvisioner, a2 as WorktreeStatusLister, a3 as WorktreeGcRunner, a4 as BranchGcRunner, a5 as BranchGcVerdictRecorder, a6 as BranchGcVerdictReader, a7 as BranchGcRestorer, a8 as BranchGcOperatorApprover, a9 as WorktreeAutoReclaimer, aa as TerminalUsageReader, ab as SandboxCheckpointReclaimer, ac as PrStateResolver, ad as TunnelRegistry, ae as OrchestratorScope, af as ApprovalsEngine } from './sessions-BYjOhHM1.js'; export { ag as ACCOUNT_BACKOFF_MS, ah as APP_INSTALL_WORKTREE_REPOINT_REFUSED, ai as AccountSlotError, aj as AccountSlotErrorCode, ak as AccountSlotExhaustedError, al as AccountSlotRow, am as AccountSlotTarget, an as AccountUntilBasis, ao as ActivityKind, ap as ActivityListFilter, aq as ActivityPolicyLister, ar as ActivityProjector, as as ActivityProjectorRegistry, at as ActivityProjectorSession, au as ActivityRecord, av as ActivitySource, aw as ActivityState, ax as ActivityWaitingOn, ay as ActivityWorkflowLister, az as AdapterCacheRetentionOptions, aA as AdapterCacheRetentionRegistry, aB as AdapterCacheRetentionResult, aC as AdapterInstallResult, aD as AdapterListEntry, aE as AgentSessionLike, aF as AgentStreamEvent, aG as AnthropicReaderConfig, aH as AnthropicRemainingQuotaReader, aI as AttachPolicyInput, aJ as BrainIngestLimits, aK as BranchGcApplyScopeCounts, aL as BranchGcApplySummary, aM as BranchGcClass, aN as BranchGcCoverageView, aO as BranchGcHoldReason, aP as BranchGcKind, aQ as BranchGcOperatorApprovalInput, aR as BranchGcOperatorApprovalResult, aS as BranchGcOutcomeView, aT as BranchGcPlanEntryView, aU as BranchGcPlanView, aV as BranchGcReclaimReason, aW as BranchGcRestoreInput, aX as BranchGcRestoreOutcomeView, aY as BranchGcRestoreResultView, aZ as BranchGcResult, a_ as BranchGcRunInput, a$ as BranchGcStatus, b0 as BranchGcSummaryView, b1 as BranchGcTriageVerdict, b2 as BranchGcVerdictInput, b3 as BranchGcVerdictLookupInput, b4 as BranchGcVerdictRecordView, b5 as BranchGcVerifiedPrView, b6 as CLAUDE_SESSION_HEADER, b7 as CommandGroupStats, b8 as CommitSpec, b9 as CreateJoinTokenInput, ba as CreatedJoinToken, bb as DECLARED_CC_ADDRESS, bc as DEFAULT_ADAPTER_CACHE_RETENTION_DAYS, bd as DEFAULT_BRAIN_MAX_TRANSCRIPT_BYTES, be as DEFAULT_BRAIN_MAX_TRANSCRIPT_TEXT_BYTES, bf as DEFAULT_NESTED_AGENT, bg as DEFAULT_ORCHESTRATOR_TOOLS, bh as DEFAULT_REVIEW_SESSION_RETENTION_DAYS, bi as DEFAULT_ROOT_AGENT, bj as DEFAULT_SANDBOX_GC_PROVIDER_SLUGS, bk as DEFAULT_SANDBOX_PROVIDER_SLUGS, bl as DEFAULT_SESSION_RETENTION_BOOT_DELAY_MS, bm as DEFAULT_SESSION_RETENTION_INTERVAL_MS, bn as DEFAULT_WORKTREE_ISOLATION, bo as DEFAULT_WORKTREE_PROVISION_CONCURRENCY, bp as DEFAULT_WORKTREE_PROVISION_MAX_MS, bq as DEFAULT_WORKTREE_PROVISION_STALL_TIMEOUT_MS, br as DefaultAgentConfig, bs as EagerResumeFailReason, bt as EagerResumeOutcome, bu as EagerResumeSkipReason, bv as EnableInput, bw as EnableResult, bx as GateSpec, by as HOSTS_VERSION, bz as HOST_HANDSHAKE_REMEDIATION_HINT, bA as HOST_SCOPE_HEADER, bB as HostInfo, bC as HostJoinMeta, bD as HostRecord, bE as HostRegistryDeps, bF as INBOUND_PROVIDERS, bG as InboundEndpoint, bH as InboundEndpointStore, bI as InboundEndpointStoreOptions, bJ as InboundEnqueuePrompt, bK as InboundIsSessionAlive, bL as InboundMessage, bM as InboundProvider, bN as InboundRestartSession, bO as InboundRouterDeps, bP as InboundRouterLog, bQ as InboundSpawnForContact, bR as JOIN_TOKENS_VERSION, bS as JoinTokenRecord, bT as JoinTokenRegistryDeps, bU as JudgeGateSpec, bV as LEGACY_CACHE_PATHS, bW as LabeledProcessStatsReport, bX as LabeledSessionStats, bY as LlmEndpointDescriptor, bZ as LlmEndpointStatus, b_ as LlmEndpointStatusReport, b$ as MAX_MESSAGE_DATA_BYTES, c0 as MESSAGE_KINDS, c1 as MESSAGE_PREAMBLE, c2 as MESSAGE_TAG, c3 as MESSAGE_URGENCIES, c4 as MessageAclDecision, c5 as MessageAclOptions, c6 as MessageDeliveryVia, c7 as MessageFilter, c8 as MessageKind, c9 as MessageRelation, ca as MessageTreeNode, cb as MessageUrgency, cc as NO_OUTPUT_STALL_TURN_ERROR, cd as NormalizeInboundResult, ce as OnFailSpec, cf as OrchestratorGatewayDeps, cg as OrchestratorInjection, ch as OrchestratorInjector, ci as OrchestratorInjectorDeps, cj as OrchestratorMcpServerFactory, ck as OrphanGroup, cl as OrphanReaperRegistry, cm as PERMISSION_ACTIONS, cn as PERMISSION_ACTION_INFO, co as POSTURE_NATIVE_ALIASES, cp as POSTURE_PREAMBLES, cq as PROTECTED_MESSAGE_KINDS, cr as PendingPermission, cs as PermissionAction, ct as PermissionContext, cu as PermissionDecision, cv as PermissionDecisionBody, cw as PermissionDeniedError, cx as PermissionPrincipal, cy as PermissionResource, cz as PermissionRespondInput, cA as PermissionRespondResult, cB as PolicyRunStatus, cC as PolicyVerdict, cD as PostureEnforcement, cE as PostureResolution, cF as PrResolution, cG as PrResolvedState, cH as PricingResolver, cI as ProcessDetail, cJ as ProcessStatsReport, cK as ProcessStatsService, cL as QuotaStoreFile, cM as QuotaStoreOptions, cN as RegisterBrowserInput, cO as RegisterSessionInput, cP as RemainingQuota, cQ as RemoteStatus, cR as ResolvedProfileRef, cS as ResourceStats, cT as ResumeDisabledError, cU as SESSION_END_REASONS, cV as SESSION_ID_ENV, cW as SHARED_CLAUDE_DESKTOP_ID, cX as SandboxAdapterInfo, cY as SandboxProviderCapabilities, cZ as ScopeTokenRegistry, c_ as ScopeTokenRegistryOptions, c$ as SessionCurrentPhase, d0 as SessionEndReason, d1 as SessionKind, d2 as SessionMessageFrom, d3 as SessionMessageSentRecord, d4 as SessionObserver, d5 as SessionOutcome, d6 as SessionOutcomeArtifact, d7 as SessionOutcomeCompact, d8 as SessionOutcomeLink, d9 as SessionResourceStats, da as SessionRetentionOptions, db as SessionRetentionRegistry, dc as SessionRetentionResult, dd as SessionRetiredError, de as SessionSnapshots, df as SessionStatus, dg as ShellGateSpec, dh as SpawnAgentInput, di as SpawnSessionInput, dj as StatsDetail, dk as TASK_STATUSES, dl as TaskCaller, dm as TaskChangedEvent, dn as TaskClaimInput, dp as TaskCreateInput, dq as TaskGateOutcome, dr as TaskGateRunner, ds as TaskLedger, dt as TaskLedgerRegistry, du as TaskLedgerSessionSlice, dv as TaskListFilter, dw as TaskRecord, dx as TaskStatus, dy as TaskUpdateInput, dz as TaskVerification, dA as TaskVerifySupervisor, dB as TaskWriteResult, dC as TerminalUsageSources, dD as TokenPricing, dE as ToolPermissionOutcome, dF as ToolPermissionRequest, dG as TransmitterBinding, dH as TransmitterBindingStore, dI as TunnelDescriptor, dJ as TunnelHealth, dK as TunnelHealthState, dL as TunnelProvider, dM as TunnelStartAbortedError, dN as TunnelStatus, dO as UsageBilling, dP as UsageBucket, dQ as UsageComputeInput, dR as UsageDetail, dS as UsageReadContext, dT as UsageSource, dU as UserPresetValidationError, dV as UserPresetsFile, dW as WORKSPACE_SLUG_ENV, dX as WORKTREE_ISOLATION_ENV, dY as WORKTREE_PROVISION_CONCURRENCY_ENV, dZ as WORKTREE_PROVISION_MAX_ENV, d_ as WORKTREE_PROVISION_STALL_TIMEOUT_ENV, d$ as WorktreeDecision, e0 as WorktreeField, e1 as WorktreeGcClass, e2 as WorktreeGcOutcomeView, e3 as WorktreeGcPlanEntryView, e4 as WorktreeGcReclaimReason, e5 as WorktreeGcResult, e6 as WorktreeGcRunInput, e7 as WorktreeProvisionOutcome, e8 as WorktreeProvisionPhase, e9 as WorktreeProvisionProgress, ea as WorktreeProvisionRequest, eb as WorktreeRequest, ec as WorktreeStatusView, ed as accountHealthOf, ee as activityCounts, ef as adoptLegacyOrchestratorScopes, eg as assertDecisionAllows, eh as canonicalForModeId, ei as clearAccountHealth, ej as collectMessageRelations, ek as collectReferencedOrchestratorScopeTokens, el as compactOutcome, em as composeModelPolicies, en as composeSessionObservers, eo as createAccountHealthStore, ep as createActivityProjector, eq as createHostRegistry, er as createInboundEndpointStore, es as createJoinTokenRegistry, et as createOrchestratorInjector, eu as createOrchestratorMcpServerFactory, ev as createProcessStatsService, ew as createScopeTokenRegistry, ex as createSessionMessage, ey as createSessionsRegistry, ez as createSupervisorTaskGateRunner, eA as createTaskLedger, eB as createTerminalUsageReaders, eC as createWorkspaceBrains, eD as decidePermission, eE as decideWorktreeIsolation, eF as declaredSenderPrefix, eG as deleteUserPreset, eH as deriveSessionOutcome, eI as deriveSessionUsage, eJ as detectClaudeBilling, eK as detectCodexBilling, eL as effectiveMessageUrgency, eM as escapeHumanPrompt, eN as escapeMessageBody, eO as filterActivities, eP as findNativeMode, eQ as getProcessStatsService, eR as getUserPreset, eS as isClosedTaskStatus, eT as isKnownSessionEndReason, eU as isMessageAllowed, eV as isNoiseMessage, eW as isOutcomeCompleted, eX as isPermissionAction, eY as isProtectedMessage, eZ as isProviderLimitError, e_ as isReviewLaneSession, e$ as isSlotRef, f0 as isTerminalActivityState, f1 as listAccountHealth, f2 as listUserPresets, f3 as loadAccountSlots, f4 as loadQuotaStore, f5 as loadUserPresets, f6 as loadWorktreeIsolation, f7 as makeSandboxCredsStore, f8 as makeSandboxResolver, f9 as markAccountExhausted, fa as matchesMessageFilter, fb as messageFrom, fc as mintMessageId, fd as narrowOrchestratorTools, fe as normalizeCommand, ff as normalizeInbound, fg as normalizeMessageRelation, fh as normalizeModeId, fi as normalizeUserPreset, fj as normalizeWorktreeField, fk as opencodeBilling, fl as orchestratorScopesFile, fm as paidCostFor, fn as parseAnthropicRateLimitHeaders, fo as parseCodexRolloutUsage, fp as parseExhaustionUntil, fq as parseTaskStatus, fr as parseWindow, fs as parseWorktreeIsolationMode, ft as pickUsageDetail, fu as planAccountSlotPrefer, fv as planAccountSlotSwap, fw as policyToActivities, fx as policyWatchesSession, fy as postureEnforcement, fz as prToActivities, fA as projectSessionUsage, fB as pruneOrchestratorScopesOnBoot, fC as readCodexRolloutUsage, fD as readHostsSnapshot, fE as readProfileQuota, fF as readSessionForBrain, fG as reapOrphanedDescendants, fH as recordProfileQuota, fI as renderInboxDigest, fJ as renderSessionMessage, fK as renderSessionMessages, fL as replyToUnverifiedSenderPrefix, fM as resolveBrainIngestLimits, fN as resolveEffectiveRelation, fO as resolveMessageAcl, fP as resolvePosture, fQ as resolveProfileRef, fR as resolveRelation, fS as rollupUsage, fT as runAdapterCacheRetentionPass, fU as runSessionRetentionPass, fV as samePeerGroup, fW as sameWorkspace, fX as sanitizeLabel, fY as saveUserPreset, fZ as sessionsToMoveOnPrefer, f_ as sessionsToMoveOnSwap, f$ as slotMembers, g0 as slotNameOf, g1 as slotRef, g2 as startHttpServer, g3 as summarizeBranchGcApply, g4 as toWorktreeStatusView, g5 as trackWorktreeProvision, g6 as turnToActivities, g7 as unknownDefaultAgents, g8 as unverifiedSenderPrefix, g9 as userPresetsPath, ga as verifyInboundSignature, gb as withBranchGcApplySummary, gc as workflowToActivities } from './sessions-BYjOhHM1.js'; import { DoctypeSpec } from '@agentproto/manifest'; import { S as SpawnDefaultsConfig, T as TurnRetryInput, a as SpawnBrowserMode, P as PreflightRegistry, b as CredentialSource, A as AdapterAuthDescriptor, R as ResolvedAuthSpec, D as DeclaredAdapterOption } from './spawn-defaults-B0Yi8_MN.js'; export { c as AuthEcho, d as AuthResolutionError, e as CLAUDE_CODE_OAUTH_SOURCE, f as ContextSettings, g as DefaultsAdapterAuthConfig, h as DefaultsAdapterConfig, i as DeferredToolsConfig, j as DelegationGateMode, k as DelegationReport, l as DelegationVerdict, m as ProfileGateMode, n as ProfileReport, o as ProfileVerdict, p as ResolveSubscriptionCredentialInput, q as ResolvedSpawnAuthMaterial, r as ResolvedSpawnDefaults, s as SubscriptionCredentialResolution, t as SubscriptionSourceError, u as credentialFingerprint, v as harnessDefaultsFor, w as harnessDefaultsMap, x as layerContextSettings, y as normalizeSkillsOption, z as resolveAuthSpec, B as resolveDeferredToolsGatewayOption, E as resolveSpawnDefaults, F as resolveSubscriptionCredential } from './spawn-defaults-B0Yi8_MN.js'; import { ClassifierOutcome } from '@agentproto/decision'; import { n as ResolvedModelRole, o as MODEL_ROLE_PRESETS, m as AgentprotoConfig, p as SessionFollowStore, q as FollowTriageConfig, r as TriageFacts } from './config-Bvuv9HOv.js'; export { s as DEFAULT_FOLLOW_TRIAGE_CLASSIFIER_TIMEOUT_MS, t as DEFAULT_FOLLOW_TRIAGE_REPORT_WINDOW_MS, u as DEFAULT_FOLLOW_TRIAGE_RULES, v as DEFAULT_MODEL_ROLES, w as FOLLOW_EVENTS, x as FOLLOW_TRIAGE_DECISIONS, y as FollowEvent, z as FollowTriageClassifier, B as FollowTriageInput, E as FollowTriageRules, G as MODEL_ROLE_PRESET_NAMES, H as MODEL_ROLE_REF_PREFIX, I as ModelRoleContext, J as ModelRoleEntry, K as ModelRolePreset, L as ModelRoleSource, N as ModelRoleValue, O as ModelRolesConfig, Q as SESSION_LIFECYCLE_CLASSIFIER_ID, U as SessionFollow, V as SessionLifecycleClassifierOptions, X as TRIAGE_RULES, Y as TriageDecision, Z as TriageEvent, _ as TriageResult, $ as WorktreeIsolationMode, a0 as adapterForModelId, a1 as classifyFollowEvent, a2 as createSessionFollowStore, a3 as createSessionLifecycleClassifier, a4 as defaultFollowTriageConfig, a5 as evaluateFollowEvent, a6 as followEnvelopeType, a7 as followFloor, a8 as isTriageDecision, a9 as levelOfDecision, aa as listModelRoles, ab as parseClassifierAnswer, ac as parseModelRoleRef, ad as resolveFollowTriageConfig, ae as resolveModelRole, af as runFollowTriageClassifier, ag as triageEventFromEnvelope, ah as triageFollowEvent } from './config-Bvuv9HOv.js'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; import { ResolvedMaintainRepos } from './maintain-repos.js'; import { WorkspaceEntry } from './workspaces-config.js'; import { B as BuildHeartbeatAgent } from './heartbeat-BIvuS0Hv.js'; export { H as HeartbeatAgent, a as HeartbeatRunner, R as RuntimeEvent, b as RuntimeEvents, c as createRuntimeEvents, p as parseDuration } from './heartbeat-BIvuS0Hv.js'; import { FooterSession } from './pr-provenance.js'; import { IncomingHttpHeaders } from 'node:http'; import { NodeTree, TreeNode } from '@agentproto/workspace'; import * as _agentproto_tool from '@agentproto/tool'; import { ToolContext } from '@agentproto/tool'; import { DriverHandle } from '@agentproto/driver'; import { Attestation, LedgerKey, RubricDigest, PackDigest, ReviewPrRef, Severity, LaneFallback, LaneRecovery, LaneSharedExecution, LaneResult, ReviewLaneExecutor, LaneOutcome, Attestor, PackLoader } from '@agentproto/review'; import { AuthProfile, SubaccountPin, CredentialStore, CostBudgetScope, CostBudget } from '@agentproto/auth'; import { E as EffortLevel, R as RouteSpec, P as Posture, C as ContextProfile } from './catalog-models-CSvq5qBI.js'; export { A as AuthMethod, a as CanonicalPosture, b as CatalogAdapterInput, c as CatalogAdapterModelInput, d as CatalogModelsQuery, e as CatalogModelsResponse, f as CatalogPricing, g as CatalogProduct, h as CatalogRoute, i as CatalogRouteSummary, j as CatalogVendor, D as DeclaredAdapterMode, S as SessionConfig, k as buildCatalogModels, l as composeMode, m as decomposeMode } from './catalog-models-CSvq5qBI.js'; import { ResolvedModel } from '@agentproto/model-catalog'; import { AdapterHandle, AdapterLister, AdapterEntry } from '@agentproto/provider-kit'; import { SandboxEgressCooldown, SandboxEgressHealthView, SandboxProviderBox, SandboxProvider, SandboxBox, SandboxUsageWindow } from '@agentproto/sandbox'; export { McpCredentialDeps, getMcpCredentialDeps, setMcpCredentialDeps } from './mcp-credential-deps.js'; import { PairingRegistry } from '@agentproto/pairing-host'; export { CreateOfferInput, CreatedOffer, PAIRINGS_VERSION, PairingChannelContext, PairingChannelHandle, PairingChannelMode, PairingRecord, PairingRegistry, PairingRegistryDeps, ReconnectLogGate, createPairingRegistry, createReconnectLogGate, readPairingsSnapshot } from '@agentproto/pairing-host'; import { WorkspaceFs } from './workspace-fs.js'; export { createWorkspaceFs } from './workspace-fs.js'; export { ConversationMeta, ConversationStore, ConversationTurn, fileConversationStore } from './conversations.js'; import { DeliveryApplyConfig, ClassifierRegistry, Classifier } from '@agentproto/delivery'; import { SentinelMatchClause, SentinelStore, SentinelProviderHandle, CancelTombstoneStore, SentinelUntil, SentinelEvent } from '@agentproto/sentinel'; import { ProviderPreset } from '@agentproto/provider-presets'; export { PROVIDER_ENV_VARS, ProviderEntry, ProvidersFile, getProviderKey, injectProviderKeysIntoEnv, loadProviders, providerEnvVar, providersPath, removeProviderKey, setProviderKey } from '@agentproto/providers-store'; export { SessionMode } from '@agentproto/acp/client'; import '@agentproto/model-catalog/llm'; import '@agentproto/acp'; import '@agentproto/quota'; import 'node:child_process'; import '@agentproto/policy'; import './skill-imports.js'; import '@agentproto/routine'; import '@agentproto/lifecycle'; import '@agentproto/memory'; import '@agentproto/command-sandbox'; import '@agentproto/clerk'; import './command-allowlist.js'; import '@agentproto/workspace-brain'; import '@agentproto/acp/tunnel'; import '@agentproto/secrets/identity'; import '@agentproto/workflow-runtime'; import '@agentproto/run'; import './app-registry-DtUAlxkN.js'; import '@agentproto/app'; import '@modelcontextprotocol/sdk/types.js'; import './mcp-discovery-CLihUe93.js'; import '@modelcontextprotocol/sdk/shared/transport.js'; import './bundles.js'; import './mcp-imports.js'; import '@agentproto/reach'; import '@agentproto/cloud-agent'; /** * Service-owner launcher (Orchestrator AIP-standardization, Phase 1b item 2). * * An app manifest MAY declare a `services:` block of long-running processes * the app needs alongside its agents/workflows: * * services: * - name: web # kebab slug, unique per app * entry: node server.js # the shell command to run * port: 4321 # optional 1..65535 bookkeeping/health touchpoint * * One managed process per entry, kept alive (see `app-service-process.ts` — a * deterministic, non-PTY child spawned detached and adopted into the * `sessions` REGISTRY, no LLM adapter involved) with its ownership * bookkeeping (label, origin, store record) here. The runner restarts the * child with backoff on an unexpected exit, capped; there is deliberately * NO scheduler here — no cron, no k8s, no queue. An entry with * `activation: { mode: "on-demand" }` is not kept alive: the host holds its * port and runs the process only while it is used (`app-service-on-demand.ts`). * * Ownership is persisted (appId + name + entry + the live process's * `sessionId` + its process-group-leader `pid`, in a JSON store next to the * installed-app registry) so `app_uninstall` can kill the recorded process * group and its registry row — otherwise a reinstall spawns a second owner * for a service still running from the old install * ("double-cerveau à la réinstall"). * * Scope note: this module is the whole SERVICE-LAUNCHER behaviour, lifted out * of app-tools.ts so it is unit-testable without an MCP server or a real * spawn. `services:` validation itself now delegates to app's * `parseServiceList` — the single validator for the manifest `services:` * array, shared with `defineApp`/`loadAppHandle`. */ /** One service owner: the persisted ownership record — `appId` + the service * `name`/`entry` + the registry row id and process-group-leader `pid` of the * currently-live attempt, so uninstall can kill both. */ interface AppServiceOwner { appId: string; name: string; entry: string; /** Registry row id of the live attempt's process (`app_uninstall` kills * the row + the process group). Updated on every respawn. */ sessionId: string; /** Process-group-leader pid of the live attempt (`app_uninstall` signals * `-pid`), when the spawn surfaced one. Updated on every respawn. */ pid?: number; /** `/proc//stat` start ticks of the recorded pid, captured at spawn * time — the identity token a later boot reconcile verifies BEFORE * signalling the recorded pid (a recycled pid has different ticks; see * `assessRecordedServicePid`). Never signal a bare recorded pid without * this check. */ startTicks?: number; /** Mirrors the declared `port` for bookkeeping. */ port?: number; /** Set for an `activation: on-demand` service (AIP-53 Activation); absent = * keep-alive. `sessionId`/`pid`/`startTicks` then name the LIVE process, * or the last one while the service is idle (no `pid`). A kept owner * whose mode no longer matches the manifest is replaced. */ activation?: "on-demand"; /** The `AGENTPROTO_PUBLIC_URL` origin the live process was spawned with * (AIP-53 Exposure rule 3). Unset: spawned without one. A kept owner * whose origin is no longer the current one is respawned. */ publicUrl?: string; startedAt: string; } /** Persisted service-owner registry — mirrors `app-registry.ts`'s pattern * (in-memory store, write-tmp + rename on every mutation). */ interface AppServiceStore { list(): AppServiceOwner[]; listForApp(appId: string): AppServiceOwner[]; /** Insert or, keyed by `appId` + `name`, replace a service owner. */ upsert(owner: AppServiceOwner): AppServiceOwner; /** Remove one service owner by `appId` + `name`. Returns it, or undefined. */ remove(appId: string, name: string): AppServiceOwner | undefined; /** Remove every owner of an app. Returns how many were removed. */ removeForApp(appId: string): number; } /** * Import-free constants for account slot refs (`slot:`), shared by the * config schema and `account-slots.ts`. Kept in their own module so the schema * can import them without a cycle through `config.ts`. */ /** Prefix that marks a `profileRef` as a slot reference. */ declare const SLOT_REF_PREFIX = "slot:"; /** A valid slot name: letters, digits, `_` and `-`. No dot (config paths are * dotted), no colon (a slot cannot name another slot). */ declare const ACCOUNT_SLOT_NAME_RE: RegExp; /** * Conversation as pivot: one store abstraction per provider, read on any * session. A "conversation" is the provider's own persisted session — the * durable object. An agentproto session (ACP or PTY) is just an attachment * to it. `CONVERSATION_STORES` is the single source of truth for "where does * this provider keep its conversations, and how do I read/attach to one" — * `RESUME_STRATEGIES` (resume-strategies.ts) and `EXPORT_STRATEGIES` * (transcript-export.ts) are thin adapters over it so the two historically * drifted tables can never diverge again. */ /** * Claude Code's own `cwd` → project-dir-name encoder. * * The real rule (verified empirically against `~/.claude/projects/` * directory names for dozens of known cwds, including dotted worktree * paths and macOS temp dirs): every character that is NOT `[a-zA-Z0-9]` * is replaced 1:1 with `-`. Crucially, runs of consecutive non-alnum * characters are NOT collapsed — each input character produces exactly * one output character. * * This used to be `cwd.replace(/\//g, "-")` — slashes only. That's wrong * for any cwd containing a dot (every `.agentproto` worktree, any * dotdir), an underscore-prefixed segment, a space, etc., because those * characters are left untouched instead of becoming `-`, so the computed * directory never matches the one claude actually created. * * Reconstruction proof (both real, both `ls ~/.claude/projects/`-verified): * cwd /Users/jeremy/.agentproto/worktrees/ts/gc-fresh-hold * → -Users-jeremy--agentproto-worktrees-ts-gc-fresh-hold * (note the "--" from "/." — one dash for "/", one for ".", not collapsed) * * cwd /Volumes/SSDExternalMacStudio/Code/_agentproto-worktrees/adapter-claude-sdk * → -Volumes-SSDExternalMacStudio-Code--agentproto-worktrees-adapter-claude-sdk * (same double-dash shape, this time from "/_") */ declare function claudeProjectSlug(cwd: string): string; /** * Egress IP health ledger. A free-tier model cap is enforced per source IP, so * "model M is capped" is really "model M is capped FROM THIS IP". The * model-cooldown map in `model-cooldowns.ts` forgets which IP failed, and * forgets everything on a restart. This ledger remembers `(publicIp, model, * errorClass) -> until` on disk (`~/.agentproto/egress-health.json`, or * `AGENTPROTO_EGRESS_HEALTH`), so a computer provider picking an egress slot * can skip an address that is already burned for the model, and the CLI can * show the same state without the daemon. * * Stateless over the file: every operation re-reads it, so the daemon, the CLI * and a probe run in another process all see one truth. Writes are best-effort * (tmp + rename, like `sandbox-ledger.ts`): a ledger failure must never fail a * spawn or a turn. */ /** The failure classes that burn an address for a model. */ type EgressHealthErrorClass = "usage-limit" | "rate-limit"; declare const isEgressHealthErrorClass: (value: unknown) => value is EgressHealthErrorClass; /** A usage cap outlives a burst limit: it clears on the provider's window, not in seconds. */ declare const DEFAULT_EGRESS_COOLDOWN_MS: Record; /** A longer hint than this is clamped so one bad header cannot park an address for days. */ declare const MAX_EGRESS_COOLDOWN_MS: number; declare const egressHealthPath: () => string; interface EgressCooldownEntry { publicIp: string; model: string; errorClass: EgressHealthErrorClass; /** ISO time the cooldown ends. */ until: string; remainingMs: number; slot?: string; source?: string; } interface MarkEgressCooldownInput { publicIp: string; model: string; errorClass: EgressHealthErrorClass; durationMs?: number; slot?: string; source?: string; } interface EgressHealthLedger { /** Cool `(publicIp, model, errorClass)` down. Never shortens an active cooldown. */ mark(input: MarkEgressCooldownInput): EgressCooldownEntry; /** Drop the cooldowns for `(publicIp, model)`, one class or all. Returns how many were dropped. */ clear(input: { publicIp: string; model: string; errorClass?: EgressHealthErrorClass; }): number; /** The longest active cooldown for `(publicIp, model)` across classes, if any. */ cooling(publicIp: string, model: string): SandboxEgressCooldown | undefined; /** A model-scoped read view for a provider choosing a slot. */ view(model: string): SandboxEgressHealthView; /** Active cooldowns, soonest-to-expire first; `model` narrows to one model. */ list(opts?: { model?: string; }): EgressCooldownEntry[]; } declare function createEgressHealthLedger(opts?: { path?: string; now?: () => number; }): EgressHealthLedger; /** The process-wide ledger over the default path. The path is resolved per * call, so a test (or an operator) can repoint `AGENTPROTO_EGRESS_HEALTH`. */ declare const egressHealthLedger: EgressHealthLedger; /** * The ONE retirement predicate. A session is RETIRED when it is archived, its * `endedReason` is a deliberate end, it has a successor (`continuedTo`), or it * carries an explicit `retiredAt` stamp. A retired session is never revived by * an automated path (follow, sentinel, cron, message routing), in place or * under a new id; a human prompt to one with a successor is refused with * `session_superseded` (wire: 409 `session_not_alive` + `reason`). * * Inbound (WhatsApp / Telegram / agentpush) is the one exception to "retired * ⇒ never revived", because an inbound message is a real human: * - a row with `continuedTo` routes to its successor (end of the chain); * - any other retired row may be revived IN PLACE (same id); * - an ARCHIVED row is never revived under a NEW id — the message is parked * with a log line instead (`makeRestartForRouting`, `routeInboundMessage`). */ type RetirementFields = Pick; declare function isRetired(desc: Omit & { endedReason?: string; }): boolean; /** Prompt sources that are daemon- or agent-driven rather than a human at a * keyboard (UI chat is `http:chat`, channels are `telegram`/…, the default * is absent/`"user"` — all human). An allowlist on purpose: an unknown source * stays human so a legitimate operator surface is never locked out. */ declare function isAutomatedPromptSource(source: string | undefined): boolean; /** End of `id`'s `continuedTo` chain (followed transitively, cycle-capped), * stopping at the last row that still exists. `undefined` when `id` has no * existing successor. */ declare function resolveSuccessor(get: (id: string) => RetirementFields | undefined, id: string): string | undefined; /** * `decision_decide` — the callable MCP seam for the decision router * (`decision.ts` + `decision-policy.ts`), registered on the root `/mcp` * server next to `model_roles`. Workflows (review routing, steward classify, * …) call it from `tool` steps the same way they call `session_judge_jev`: * pass a DECISION.md (as markdown text) plus the domain evidence object; * get back a validated closed choice with provenance. * * The classifier backend is the existing generic Jev client * (`callJevSystemOne`), resolved through `resolveJevApiKey`/`resolveJevConfig` * — no new credential surface. No escalation backend is wired here: the * harness escalation lives in the staged workflow tools * (`decision-workflow-tools.ts`), where the execution profile gates it before * any spawn. Acts on nothing; never an MCP error result for a failed * classification. */ /** Jev adapter for `decide()`: one typed-choice call over the policy's * closed choice set. Failures come back `{ ok:false }` — never thrown. */ declare function makeJevDecisionClassifier(opts: { readonly apiKey: string | null; readonly model?: string | undefined; readonly baseUrl?: string | undefined; readonly fetchImpl?: typeof fetch; readonly sleep?: (ms: number) => Promise; /** Transient-status retries inside the Jev client (default: the client's own). */ readonly maxRetries?: number | undefined; /** Per-attempt timeout (default: the client's own). */ readonly timeoutMs?: number | undefined; }): (input: { state: unknown; question: { instructions: string; criteria: Readonly>; }; }) => Promise; /** Reads the workspaces config once and returns a cwd to registered-workspace-slug lookup. Never throws. */ declare function createWorkspaceOfCwd(configPath?: string): (cwd: string) => string | undefined; /** * `model_roles` — read-only MCP tool listing every model role, the model it * resolves to right now, and which layer supplied it. The precedence itself * (input > workspace > daemon > preset > built-in default) is defined once, in * `model-roles.ts`; this file only loads the layers and exposes the result. * * Workflow `tool` steps call it (the daemon's `dispatchTool` reaches every * root-`/mcp` tool) to resolve a role at RUN time — a workflow's own * `reviewModelSmall`-style input is passed as `inputs` so an explicit input * still wins, and the tool reports `source: "input"` for it. * * Registered on the root `/mcp` server only, next to `config_get`. */ interface ModelRolesInput { /** Narrow to these roles. Omit for every built-in + configured role. */ roles?: string[] | undefined; /** Explicit per-role values (layer 1) — e.g. a workflow's own inputs. */ inputs?: Record | undefined; /** Repo whose `agentproto.json` `models` is the workspace layer. */ repoRoot?: string | undefined; /** Workspace slug (resolved to its path). The active workspace when both are omitted. */ workspaceSlug?: string | undefined; /** Preset for this call only; wins over the daemon's `modelRolePreset`. */ preset?: string | undefined; } interface ModelRolesOutput { roles: ResolvedModelRole[]; /** role → resolved model id, for a workflow `$steps..models["review.small"]`-style read. */ models: Record; /** role → adapter its model requires, only for roles whose model id requires one. */ adapters: Record; /** role → named auth profile the role's session should bill, when one is configured. */ profiles: Record; /** role → gateway/route the role's model should be reached through, when one is configured. */ routes: Record; /** The preset in effect (per-call `preset` > daemon `modelRolePreset`), when one is set. */ preset?: string; /** Every built-in preset: name → { description, roles }. */ presets: typeof MODEL_ROLE_PRESETS; /** Directory whose `agentproto.json` supplied the workspace layer, when one was found. */ workspaceRoot?: string; precedence: readonly string[]; } /** `models` from `/agentproto.json`; undefined when absent/unreadable/malformed. */ declare function loadWorkspaceModelRoles(root: string): Promise | undefined>; /** * `maintain_run`: the daemon-side twin of `agentproto maintain`, so a routine * (`target.tool: maintain_run`) or any MCP caller can run repo maintenance * over every repo the operator's config names, not just one. * * Why it exists: a routine with a `workflow` target runs the `maintain` * workflow for exactly one `repoRoot` (the registrar injects the routine's * workspace), and multi-repo discovery only existed in the CLI. The shipped * routines therefore had to hardcode a repo path and a chat id. This tool * reads both from the user config's `maintain` section * (`maintain-repos.ts`), so the shipped routines stay generic. * * Behaviour: `all: true` resolves the repo list from the config * (`resolveMaintainRepos`), else the explicit `repos` (refused when neither). * Installs the bundled repo-maintenance app (an `app_install` refused as a * worktree re-point keeps the installed copy, as the CLI does), then starts * ONE `maintain` workflow run per repo through `workflow_run_file`, which * returns as soon as the run is queued. So the tool answers immediately with * `{repo, runId}` per repo and never holds a cron tick. A repo that fails to * start is reported and the next ones still start. */ type MaintainDispatchTool = (name: string, inputs: Record) => Promise; interface MaintainRunDeps { /** The daemon's in-process tool dispatch (`app_install`, `workflow_run_file`). */ dispatchTool: MaintainDispatchTool; /** Default: `loadConfig()` (`~/.agentproto/config.json`). */ loadConfig?: () => Promise; /** Default: the bundled app under `@agentproto/apps`. */ resolveApp?: () => { appDir: string; workflowPath: string; }; /** The registered workspaces. Default: `/.agentproto/workspaces.json`. */ loadWorkspaces?: () => Promise; /** Dir -> main repo root. Default: `git rev-parse --git-common-dir`. */ resolveRepoRoot?: (dir: string) => string | null; env?: NodeJS.ProcessEnv; home?: string; } declare const maintainRunInputSchema: z.ZodObject<{ repos: z.ZodOptional>; all: z.ZodOptional; applyMerged: z.ZodOptional; applyReviewed: z.ZodOptional; requireOperatorBelowGuard: z.ZodOptional; maxReviews: z.ZodOptional; reviewPreset: z.ZodOptional>; notify: z.ZodOptional>; alias: z.ZodOptional; address: z.ZodOptional; source: z.ZodOptional; channel: z.ZodOptional; }, z.core.$strict>>; }, z.core.$strict>; type MaintainRunInput = z.infer; interface MaintainRunRepoResult { repo: string; runId?: string; status?: string; error?: string; } interface MaintainRunResult { runs: MaintainRunRepoResult[]; /** `installed`, or `kept` when the install was refused as a worktree re-point. */ app: "installed" | "kept"; skipped: ResolvedMaintainRepos["skipped"]; excluded: string[]; } /** The bundled repo-maintenance app dir + its `maintain` WORKFLOW.md, * resolved through `@agentproto/apps`'s own package (monorepo or npm). */ declare function resolveRepoMaintenanceApp(): { appDir: string; workflowPath: string; }; /** * The whole `maintain_run` behaviour, transport-free (the MCP handler below * wraps it). Throws on a caller error (no repos, invalid config, nothing to * maintain, the app cannot be installed); per-repo start failures are * reported in `runs[].error`, never thrown. */ declare function runMaintainRun(input: MaintainRunInput, deps: MaintainRunDeps): Promise; declare function registerMaintainRunTools(server: McpServer, deps: MaintainRunDeps): void; /** * Shared kernel for the daemon's sandbox-checkpoint-`gc` surface — the * sibling of `branch-gc.ts`. The engine (`planSandboxCheckpointGc` / * `applySandboxCheckpointGc`) lives in `@agentproto/worktree`, a dependency * the runtime deliberately does NOT take, so the runtime only defines * runtime-local structural result types and the injected port. The CLI host * wires the real runner. * * `sandbox_checkpoint_gc` sweeps the `agentproto-checkpoint/*` refs a dead * sandbox leaves on a workspace remote. It is a dry run by default; an apply * re-plans and re-classifies every ref immediately before deleting it, so a * stale plan can never delete work that has since changed classification. */ type SandboxCheckpointGcVerdict = "safe" | "keep" | "unknown"; interface SandboxCheckpointGcPrView { number: number; state: "open" | "merged" | "closed"; } /** One classified `agentproto-checkpoint/*` ref — mirrors the engine entry. */ interface SandboxCheckpointGcEntryView { /** Short remote branch name: `agentproto-checkpoint/wt/x`. */ ref: string; /** Remote the ref lives on (default `origin`). */ remote: string; /** Tip commit of the ref, or null when it could not be resolved. */ sha: string | null; /** The work branch the checkpoint belongs to (`wt/x`). */ workBranch: string; /** True when the remote still carries the work branch itself. */ workBranchOnRemote: boolean; /** HEAD PR of the work branch, per the forge, or null when unknown. */ pr: SandboxCheckpointGcPrView | null; verdict: SandboxCheckpointGcVerdict; /** Why: the proven tier, or what a `keep`/`unknown` entry is waiting on. */ reason: string; } interface SandboxCheckpointGcPlanView { repoRoot: string; remote: string; /** The branch content was judged against. */ base: string; /** Whether a usable `gh`-backed forge client answered PR questions. */ prCheckAvailable: boolean; /** Why the PR check was unavailable, when it was. */ prCheckReason?: string; refs: SandboxCheckpointGcEntryView[]; } /** safe / keep / unknown tallies over a plan. */ interface SandboxCheckpointGcSummaryView { total: number; safe: number; keep: number; unknown: number; } interface SandboxCheckpointGcApplyOutcomeView { ref: string; result: "deleted" | "failed" | "skipped-keep" | "skipped-moved"; verdict?: SandboxCheckpointGcVerdict; message?: string; } /** Apply tallies: deleted / skipped / failed, plus a coarse status. */ interface SandboxCheckpointGcApplySummaryView { /** `ok` = deletes only; `partial` = some deleted and some failed; * `failed` = failures and nothing deleted; `noop` = nothing to do. */ status: "ok" | "partial" | "failed" | "noop"; deleted: number; skipped: number; failed: number; } type SandboxCheckpointGcResult = { mode: "plan"; plan: SandboxCheckpointGcPlanView; summary: SandboxCheckpointGcSummaryView; } | { mode: "apply"; plan: SandboxCheckpointGcPlanView; summary: SandboxCheckpointGcSummaryView; outcomes: SandboxCheckpointGcApplyOutcomeView[]; /** Attached by the tool/runner boundary (`withSandboxCheckpointGcApplySummary`). */ applySummary?: SandboxCheckpointGcApplySummaryView; }; declare function summarizeSandboxCheckpointGcPlan(plan: SandboxCheckpointGcPlanView): SandboxCheckpointGcSummaryView; declare function summarizeSandboxCheckpointGcApply(result: Extract): SandboxCheckpointGcApplySummaryView; /** Attach `applySummary` to an apply result; a plan passes through. */ declare function withSandboxCheckpointGcApplySummary(result: SandboxCheckpointGcResult): SandboxCheckpointGcResult; /** Input to the injected runner. `apply` defaults to false at the tool * boundary — a bare call is a dry run. */ interface SandboxCheckpointGcRunInput { repoRoot: string; apply: boolean; base?: string; remote?: string; } type SandboxCheckpointGcRunner = (input: SandboxCheckpointGcRunInput) => Promise; /** * Bounded eager resume-on-boot pass (session-survivability plan §5, PR-4). * * Lazy resume-on-prompt (`maybeResumeAgent`, triggered by the first * `sendPrompt`/`enqueuePrompt` on a dead row) is always on — it costs nothing * until someone acts. This pass is the OPT-IN eager half: after a daemon * restart, walk the rehydrated ghosts and re-spawn the eager-eligible ones IN * PLACE, without waiting for a prompt, so orchestrated fleets and completion * policies find their sessions live again rather than dead-but-lazy-resumable. * * The per-row work — eligibility, auth re-resolution, the `session:resumed` * event + interrupted banner, the attempt cap, and the no-fresh-spawn rule — * all lives behind the registry's `resumeOnBoot(id)`. This module owns only the * ORCHESTRATION the plan pins to the boot pass: * - candidate selection (`canResume` ∧ `endedReason === "daemon-restart"`, * minus rows this daemon doesn't serve — the cross-process gate); * - ordering by `lastActivityAt` desc so the most relevant sessions come back * first (§5 "Resume-storm control"); * - a small concurrency cap so a box-wide restart doesn't spawn N adapters at * once (§5 "Resume-storm control"); * - a summary the caller turns into the boot-banner line. * * MUST run AFTER the supervisor is re-armed (§5 "Event ordering vs the * supervisor"): this pass emits `session:resumed`, never a second * `session:exited`, so a re-armed lone-session completion policy survives the * restart instead of being cancelled. The caller enforces the ordering by * invoking this only once the gateway (and its supervisor) is fully built. */ /** Tally of one eager resume-on-boot pass, for the boot-banner summary line. */ interface EagerResumeSummary { /** Whether the pass actually ran. False when the daemon config knob * (`daemon.resumeSessionsOnBoot`) is off — the pass short-circuits and * every count is 0. Lets a caller distinguish "ran, found nothing" from * "never ran". */ enabled: boolean; /** Rows that matched eager-eligibility — the denominator of the * "eager-resumed N/M sessions" banner line. */ candidates: number; /** Rows brought back to `running` (`resumeOnBoot` → `resumed`). */ resumed: number; /** Rows attempted but not resumed — adapter refused the id (left * dead-but-lazy-resumable, never fresh-spawned) or the worktree was gone. */ failed: number; /** Rows that never reached the adapter — already live (a lazy prompt raced * this pass), cap-exhausted, or a worktree-generation mismatch. */ skipped: number; } /** * Run the bounded eager resume-on-boot pass. See the module docblock for the * ordering contract. Returns the tally; the caller (serve.ts) prints the banner * line and does not otherwise act on it. */ declare function runEagerResumePass(opts: { /** The gateway's sessions registry (already rehydrated from disk at boot). */ registry: Pick; /** Max adapters spawned concurrently (§5 "Resume-storm control"). Clamped to * at least 1 — a non-positive cap would resume nothing. */ concurrency: number; /** Restrict automatic recovery without changing lazy resume-on-prompt. */ policy?: "all" | "keepalive"; /** How long a `keepAlive` row may be idle before this pass stops reviving * it automatically (published as * `daemon.bootResumeKeepAliveMaxIdleMinutes`). Only explicitly `pinned` rows * are exempt: pinning is the deliberate "always keep" flag, while an * `operatorLabel` is identity only and is stamped on every operator spawn. * `undefined` ⇒ the 30 min default; `0` or negative * disables the cutoff. The row itself is never killed, archived or * modified: it just stays dead-but-lazy-resumable until the next prompt or * an explicit `session_restart`. */ keepAliveMaxIdleMs?: number; /** Clock override for tests. Default `Date.now()`. */ now?: number; /** Cross-process gate (§5): with two daemons sharing the workspace buckets, * each must only resume rows for the workspace IT serves. Return false to * exclude a row from THIS daemon's pass. Omitted ⇒ every eligible row is * served (the single-daemon common case + tests). */ isServed?: (desc: SessionDescriptor) => boolean; }): Promise; /** * Boot-time reattach pass for sandbox sessions a previous daemon process * detached from (or died holding) — the second half of "sandbox sessions * survive a host daemon restart". * * Shutdown no longer kills a provider box's session: it closes the host's * connection and leaves the box + its agent session running (see * `SessionsRegistry.detachSandboxSessions`). This pass runs at the next boot, * BEFORE the eager-resume / continue-interrupted passes, and for every row * still flagged `hostDetached`: * 1. `SandboxProvider.connect(sandboxId)` — the same `reuse` path a * `sandbox.reuse` spawn takes (never boots); * 2. probes the box's own session — gone / ended / busy / unseen backlog / * idle; * 3. hands the live proxy (cursor = the saved transcript seq) to the * registry, which re-binds the SAME session id and, when the box kept * working, replays the missed events into the host transcript. The box's * agent is never re-prompted, and `continue-interrupted` is not involved. * A box that no longer exists ends the row with `sandbox_gone` and a ledger * entry. * * Every row runs under a PER-ROW DEADLINE ({@link DEFAULT_REATTACH_TIMEOUT_MS}) * covering the whole connect→probe chain. None of the steps below is unbounded * on its own — the e2b provider's control-plane calls cap at the SDK's 60s * request timeout (3 retries), the in-box daemon readiness poll at * `daemonReadyTimeoutMs`, the MCP handshake at the SDK's 60s request timeout, * the box probe at 10s — but STACKED they legitimately run for minutes per row * (a resumed box that needs `npm i -g` alone allows 120s), which is exactly * how the pass was observed still showing `pending: N` long after boot while * every observer gave up waiting. The deadline bounds the row, resolves it * (`gone` when the provider can still say the box is gone, otherwise `failed` * with "reattach timed out after Ns"), and releases any half-open handle * WITHOUT killing a live box — so `pending` always settles to 0. */ /** Tally of one reattach pass, for the boot banner. */ interface SandboxReattachSummary { /** Detached rows found at boot — the denominator of the banner line. */ candidates: number; reattached: number; /** Box (or its session) no longer exists → row ended `sandbox_gone`. */ gone: number; /** The box session had finished while the daemon was down. */ ended: number; /** Box unreachable / provider unresolvable / row timed out — row fell back * to the plain `daemon-restart` ghost. */ failed: number; /** Detached rows that belong to a workspace bucket this daemon does not * serve — left untouched for the daemon that does. Not counted in * `candidates`. */ unserved: number; } /** * Run the bounded reattach pass. Never throws: a per-row failure is tallied * and leaves that row as a plain ghost. */ declare function runSandboxReattachPass(opts: { registry: Pick & Partial>; resolveSandboxProvider: SandboxProviderResolver; /** Max boxes reconnected concurrently. */ concurrency?: number; /** Per-row deadline for the whole reattach (connect + daemon connect + * probe), ms. Defaults to {@link DEFAULT_REATTACH_TIMEOUT_MS}. */ timeoutMs?: number; /** Cross-process gate, same meaning as the eager-resume pass's. */ isServed?: (desc: SessionDescriptor) => boolean; /** `defaults` block the checkpoint policy is resolved from; defaults to the * config file. */ loadDefaultsConfig?: () => Promise; }): Promise; /** * Continue-interrupted: pick back up the sessions a daemon restart cut off * mid-turn, by sending each an explicit "continue" prompt. * * Everything below the prompt already exists — the persisted registry is the * snapshot, `maybeResumeAgent` resumes a dead row in place (lazily on its first * prompt, or eagerly at boot via `eager-resume.ts`), and the row keeps the * derived `interrupted` marker until its next successful turn-end. What a * restart does NOT do, by design, is re-run the interrupted prompt (prompts * aren't idempotent). This module is the explicit, opt-in replacement for that: * a NEW prompt that tells the agent its last turn was cut off and to check the * state on disk before carrying on. * * Two callers share one eligibility rule + one sender: * - the manual verb (`session_continue_interrupted` MCP tool, * `POST /sessions/continue-interrupted`, `agentproto sessions * continue-interrupted`) — `mode: "manual"`, dry-run by default; * - the opt-in boot pass (`daemon.continueInterruptedOnBoot`) — * `mode: "boot"`, run by serve.ts right after the eager resume pass. * * Eligibility (both modes): an agent-cli row that is `interrupted` BY THE LAST * RESTART (`interruptedAtBoot === registry.bootId` — a stale interruption from * an older restart that nobody picked up is left alone), resumable under the * attempt cap (`canResume`), not already busy, and whose `cwd` still exists * (a removed worktree fails the adapter respawn every time — knowable up front, * so the dry run must not call such a row eligible). The prompt goes through * `enqueuePrompt`, the same entry MCP `agent_prompt` uses, so a * dead-but-resumable row lazy-resumes with its billing auth re-resolved exactly * as a human prompt would. When that resume fails, the outcome says so instead * of passing on the bare post-resume "not alive" admission error. * * No-loop rules (boot mode only — a human pressing the button is intent): * - never auto-continue a row whose resume has failed (`resumeAttempts > 0`: * the eager pass, or an earlier attempt, could not bring it back); * - at most one auto-continue per restart (`lastAutoContinueBoot`); * - at most `MAX_AUTO_CONTINUE_ATTEMPTS` auto-continues without a successful * turn-end in between (`autoContinueAttempts`, booked BEFORE sending), so a * continue turn that keeps getting cut off — or keeps taking the daemon * down with it — stops being retried. * * Ordering (boot mode): MUST run after the supervisor is re-armed, same * constraint as `eager-resume.ts` — the continue turn's `turn-end` is exactly * what a re-armed completion policy is waiting for — and after the eager pass, * so a row whose eager resume failed is recognisable (`resumeAttempts`) and * skipped rather than lazily retried. */ /** The prompt sent when the caller doesn't supply one. */ declare const DEFAULT_CONTINUE_PROMPT: string; /** Transcript provenance for the continue prompt (`opts.source`). */ declare const CONTINUE_PROMPT_SOURCE = "daemon:continue-interrupted"; /** Cap on automatic continue prompts sent to one row without a successful * turn-end in between (boot mode). 2 = the original interruption gets one * auto-continue, and if a second restart cuts THAT turn off it gets one more; * after that only a human (manual verb) re-sends. */ declare const MAX_AUTO_CONTINUE_ATTEMPTS = 2; type ContinueInterruptedSkipReason = /** Unknown id (explicit `ids` filter only). */ "unknown" /** Not interrupted at all — no turn was cut off. */ | "not-interrupted" /** Interrupted by an EARLIER restart, not the last one. */ | "stale-interrupt" /** Retired (`isRetired`: archived, deliberately ended, superseded) — never * revived by an automatic pass. */ | "retired" /** Not in-place resumable (not agent-cli / missing adapter session / archived). */ | "not-resumable" /** Already burned through `MAX_RESUME_ATTEMPTS` failed resumes. */ | "resume-cap-exhausted" /** Mid-turn already — someone got there first. */ | "busy" /** The row's `cwd` is gone (removed worktree) — the resume would fail. */ | "cwd-missing" /** Boot mode: a resume attempt has failed on this row. */ | "resume-failed" /** Boot mode: already auto-continued by this boot. */ | "already-auto-continued" /** Boot mode: `MAX_AUTO_CONTINUE_ATTEMPTS` reached without recovering. */ | "auto-continue-cap" /** Excluded by the cross-process `isServed` gate (another daemon's row). */ | "not-served"; type ContinueInterruptedOutcome = { id: string; name?: string; status: "eligible"; } | { id: string; name?: string; status: "sent"; } | { id: string; name?: string; status: "skipped"; reason: ContinueInterruptedSkipReason; } | { id: string; name?: string; status: "failed"; error: string; }; interface ContinueInterruptedResult { dryRun: boolean; /** The prompt that was (or, on a dry run, would be) sent. */ prompt: string; /** The boot the candidates were interrupted before (`registry.bootId`). */ bootId: string; /** One entry per considered row — every interrupted row when `ids` is * omitted, every requested id otherwise. Eligible-first ordering matches * the send order (newest activity first). */ sessions: ContinueInterruptedOutcome[]; /** Counts by outcome status. */ eligible: number; sent: number; skipped: number; failed: number; } type ContinueInterruptedMode = "manual" | "boot"; /** Decide one row. `undefined` ⇒ eligible. Pure — reads the descriptor only. */ declare function continueSkipReason(desc: SessionDescriptor, bootId: string, mode: ContinueInterruptedMode): ContinueInterruptedSkipReason | undefined; /** * List — and unless `dryRun` — continue the sessions interrupted by the last * restart. See the module docblock for eligibility, the no-loop rules, and the * ordering contract. No-throw per row: a send that fails admission (row went * busy, resume refused) is reported as `failed` and the pass carries on. */ declare function continueInterruptedSessions(opts: { registry: Pick; mode: ContinueInterruptedMode; /** Default true: report what would be sent, send nothing. */ dryRun?: boolean; /** Restrict to these session ids. Omitted ⇒ every interrupted row. */ ids?: readonly string[]; /** Custom prompt. Omitted/blank ⇒ `DEFAULT_CONTINUE_PROMPT`. */ prompt?: string; /** Max sends in flight at once (each may lazily resume an adapter). Clamped * to ≥1. Default 4, same as the eager pass. */ concurrency?: number; /** Cross-process gate — see `runEagerResumePass`. Omitted ⇒ all served. */ isServed?: (desc: SessionDescriptor) => boolean; /** Extra visibility filter (a scoped orchestrator's subtree). Rows it * rejects are dropped silently — never reported, never sent. */ visible?: (desc: SessionDescriptor) => boolean; /** Filesystem probe for the `cwd-missing` check. Default `existsSync`. */ cwdExists?: (cwd: string) => boolean; }): Promise; /** Tally of the boot-time continue pass, for the boot-banner line. */ interface ContinueOnBootSummary { /** False when `daemon.continueInterruptedOnBoot` is off (nothing ran). */ enabled: boolean; /** Rows passing eligibility at selection time — the banner's denominator. */ eligible: number; sent: number; skipped: number; failed: number; } /** * The boot pass: `continueInterruptedSessions` in `mode: "boot"`, not a dry * run, reduced to the banner tally. Caller (the gateway handle, invoked from * serve.ts) is responsible for the ordering contract in the module docblock. */ declare function runContinueOnBootPass(opts: { registry: Parameters[0]["registry"]; concurrency: number; /** Apply the same automatic recovery policy as the eager resume pass. */ policy?: "all" | "keepalive"; isServed?: (desc: SessionDescriptor) => boolean; }): Promise; /** * Named MCP surface profiles. * * A root `/mcp` connection normally sees every daemon tool. That is the * right default for an operator, but it is a large context tax for clients * that mount `/mcp` by hand (Claude Desktop, IDEs) and cannot use the * spawn-side knobs. A profile narrows that surface to a named allowlist, * composed with `?profile=core,apps` on `/mcp` or `defaults.mcp.profile` * in `~/.agentproto/config.json`. * * `full` is the default when neither source names a profile, so existing * callers keep exactly the surface they had before. Profiles only ever * REMOVE tools from `tools/list` / registration; `tool_help` still reads * docs for tools outside the active profile (see `profilesExposingTool`). * * The per-request `?allowTools=` / `?denyTools=` filters still apply on top: * `denyTools` wins over a profile, and `allowTools` intersects with one. */ declare const TOOL_PROFILE_NAMES: readonly ["core", "orchestrator", "apps", "admin", "full"]; type ToolProfileName = (typeof TOOL_PROFILE_NAMES)[number]; /** Split a comma-separated `?profile=` / config value into known names. * Duplicates collapse; unknown names are ignored, and a value with no * known name falls back to `undefined` (the full surface). */ declare function parseToolProfileList(raw: string | readonly string[] | undefined): ToolProfileName[] | undefined; /** * The per-request query wins over the boot-time config default when it names * at least one known profile. An absent / unusable query falls through to * the config, and an absent / unusable config means `full`. */ declare function resolveToolProfileSelection(input: { query?: string | readonly string[]; config?: string | readonly string[]; }): ToolProfileName[] | undefined; /** * The allow set to pass to `withToolSubset`, or `undefined` when the * surface should stay unrestricted (`full`, or no profile named at all). */ declare function resolveToolProfileAllowSet(profiles: readonly ToolProfileName[] | undefined): ReadonlySet | undefined; /** * Which profiles expose a tool, for `tool_help` when the tool is outside the * active profile. `full` is included for every real daemon tool; dynamic * `app_ui_` panels are exposed by `apps` and `full`. */ declare function profilesExposingTool(name: string): ToolProfileName[]; /** * Daemon-lane PR provenance RECONCILER. * * The `command_execute` stamper (`pr-provenance-stamp.ts`, wired in * `command-tools.ts`) only fires when a PR is opened THROUGH the daemon's * `command_execute` tool. Executor harnesses (claude-code, codex, …) open PRs * with their OWN native shell tool, which never routes through * `command_execute` — so the daemon never observes that `gh pr create` and the * footer is never applied. * * This closes that gap tool-agnostically: it subscribes to the session event * bus and, at each executor session's turn-end / exit, checks two lanes in * order and stamps the same `@agentproto-bot` footer if it's missing — * reusing {@link stampFooterOnPr}: * * A. EXACT — the session's own recorded tool calls: the transcript writer * marks a successful `gh pr create` with the created PR's url/number * (`ToolCallRecord.createdPrUrl`), naming the author session directly. * Immune to branch switches and shared checkouts. * B. BRANCH — resolve the OPEN PR for the session cwd's current branch * (via the injected {@link OpenPrResolver} port), the fallback for * adapters whose tool calls aren't recorded. * C. TEXTUAL — pull-request urls mentioned in the session's own assistant * output (bounded transcript-tail scan); records on `openedPrs` * (adapter "output-scan") but never stamps a footer — a mention is * not proof of creation. * * Turn-end/exit are only poll checkpoints, never an assertion the PR is * ready: the real predicate is "did this session create a PR / does an open * PR for this branch now exist?", answered by the records and resolver, not * by timing. * * Strictly best-effort: every handler is wrapped so a missing session, an * unreachable forge, or a failed `gh` can never throw out of a bus callback. * Idempotent by construction — the footer's `MARKER` guard (inside * `stampFooterOnPr`) plus `SessionDescriptor.openedPrs` and an in-memory set of * already-stamped PR urls mean each PR is stamped at most once. The dedupe is * per-PR, not per-session, so a session that opens several PRs (across * branches) stamps each of them exactly once. */ /** * Resolve the OPEN pull request for a session's working directory — i.e. the * PR whose head is that cwd's current git branch. Returns `null` when there is * no branch, no open PR, or the forge is unreachable (never throws; the * reconciler treats any failure as "no PR right now"). Injected by the CLI host * because branch→PR resolution runs over `@agentproto/worktree`, a dependency * the runtime deliberately does not take. * * `opts.branch` overrides "the cwd's current branch": a sandboxed session's * work branch lives in its box (`SessionDescriptor.sandboxDeliveryTarget`), so * the reconciler asks about THAT branch against a local checkout of the same * repo (the session's workspace) — `cwd` then only identifies the repo. */ type OpenPrResolver = (cwd: string, opts?: { branch?: string; }) => Promise<{ number: number; url: string; } | null>; /** A session as the reconciler inspects it: the footer's {@link FooterSession} * shape plus the two descriptor fields it reads for dedupe/attribution. The * full `SessionDescriptor` satisfies this structurally. */ interface ReconcilerSession extends FooterSession { worktreePath?: string; openedPrs?: readonly { url: string; number?: number; /** Footer bookkeeping the daemon persists (see `PrFooterState`). */ footerStampedAt?: string; footerBodyHash?: string; footerRemovals?: number; footerDisabled?: boolean; }[]; /** Ephemeral transcript path the live registry stamps on every read * (see `SessionDescriptor.eventsPath`); lane C's bounded tail read * needs it. Absent from test fakes without a transcript on disk. */ eventsPath?: string; /** Sandboxed session: its cwd is a path inside the box, never on this * host — see {@link localRepoCwdFor}. */ remote?: boolean; /** Sandboxed session's work branch inside its box. */ sandboxDeliveryTarget?: { branch: string; }; workspaceSlug?: string; } /** The registry slice the reconciler needs — structurally satisfied by the full * `SessionsRegistry`, and by a trivial fake in tests. It is also a valid * `StampRegistry` for {@link stampFooterOnPr} (get/list/recordOpenedPr). */ interface ReconcilerRegistry { get(id: string): ReconcilerSession | undefined; list(): readonly FooterSession[]; recordOpenedPr(sessionId: string, input: { adapter: string; number: number; url: string; }): unknown; /** Persist footer bookkeeping onto an already-recorded PR. Optional so * lightweight fakes keep working. */ recordPrFooterState?(sessionId: string, url: string, state: PrFooterState): unknown; } interface PrProvenanceReconciler { /** Detach both bus subscriptions and clear in-memory state. */ dispose(): void; } declare function createPrProvenanceReconciler(opts: { registry: ReconcilerRegistry; sessionEvents: SessionEventBus; resolveOpenPr: OpenPrResolver; /** Session's recorded tool calls, the exact-attribution source (lane A). * Defaults to reading the session's own events.jsonl via * {@link readToolCallRecords}; injectable for tests. */ listToolCalls?: (sessionId: string) => Promise; run?: GhRunner$1; host?: string; /** Host-side checkout of the repo a SANDBOXED session works on (its * workspace's path) — the session's own `cwd` is a box path that does not * exist here. Lane B then resolves the PR whose head is the box's work * branch (`sandboxDeliveryTarget.branch`) against that checkout, and every * `gh` call runs there. Absent / unresolvable ⇒ lane B is skipped for the * session and the url-addressed `gh` calls run from the home dir. */ localRepoCwdFor?: (session: ReconcilerSession) => Promise; /** The daemon's GLOBAL checkpoint ref namespace * (`defaults.sandbox.checkpoint.refPrefix`). The session's own per-spawn * override wins over it, the checkpoint the delivery pushed lives under * the session's namespace, not the global one. */ checkpointRefPrefix?: string; /** `owner/name` repos whose PRs never receive or refresh a footer * (`defaults.prProvenance.footer.skipRepos`). Resolved on every reconcile * so a config change takes effect without a daemon restart. */ skipFooterRepos?: () => Promise | readonly string[]; /** Info logger for the one line emitted when a PR opts out of stamping * after two deliberate footer removals. Defaults to `console.log`. */ log?: (line: string) => void; }): PrProvenanceReconciler; /** * InboundWatcher — polls agentpush `poll_inbound` on a timer and * spawns one agent per contact_ref that has unread inbound messages. * * Flow per tick: * mcp_imported_call(alias, "poll_inbound", {source, since:cursor}) * → group events by contact_ref * → spawn one agent per contact with prompt from promptTemplate * → advance + persist cursor to ~/.agentproto/agentpush-cursors.json * * Cursor key = "${alias}:${source}" — stable across daemon restarts so * cursor resume actually works (a random watcherId would break it). * * Prompt template variables: {{source}}, {{contact_ref}}, * {{messages_json}}, {{count}}. * * The mcpServersForChild array is forwarded to the spawned agent's * startSession + spawnAgent so the child can call dispatch_request * directly on the mounted agentpush MCP server. * * State is in-memory; cursors persist to disk (debounced async write * + sync flush at shutdown), matching the supervisor.ts pattern. */ interface WatcherStartInput { /** Imported MCP alias (e.g. "agentpush"). */ alias: string; /** Contact ref / channel to watch — forwarded as `source` to poll_inbound. */ source: string; /** Agent adapter slug (e.g. "claude-code"). */ adapter: string; /** * Prompt template with placeholders: * {{source}} — the watched source * {{contact_ref}} — the sender's contact_ref * {{messages_json}} — JSON array of the new events * {{count}} — number of new messages */ promptTemplate: string; /** Poll interval in ms. Default 5 000. */ pollIntervalMs?: number; /** Working directory for spawned agents. Default process.cwd(). */ cwd?: string; /** Optional label suffix on spawned sessions. */ label?: string; /** * MCP servers to mount in the child agent at spawn time. * Pass agentpush here so the child can call dispatch_request. */ mcpServersForChild?: Array<{ name: string; transport: "stdio" | "http" | "sse"; ref?: string; }>; /** * Routing mode for new inbound messages — see `inbound-router.ts`. * Default `"spawn"` (today's behavior: always spawn a fresh agent). * Modes other than `"spawn"` require `bindings`/`enqueuePrompt`/ * `isSessionAlive`/`restartSession` to be wired on the factory opts; * when they aren't, the watcher falls back to `"spawn"` and logs a * warning rather than crashing. */ mode?: InboundRouteMode; } interface WatcherDescriptor { watcherId: string; alias: string; source: string; adapter: string; pollIntervalMs: number; status: "running" | "stopped"; /** Next `since` value for poll_inbound (exclusive lower bound). */ cursor: number; lastPollAt?: string; lastFireAt?: string; /** Total agent sessions spawned since the watcher started. */ spawned: number; } interface InboundWatcher { start(input: WatcherStartInput): WatcherDescriptor; /** Returns false when watcherId is unknown. */ stop(watcherId: string): boolean; list(): WatcherDescriptor[]; /** Stops all watchers and flushes cursor state to disk synchronously. */ shutdown(): void; } /** * Header the daemon itself sets, on a request it forwards to its own gateway, * to say "the public base of this request is X" (pairing path, link-guard). * The value is HMAC-signed with a per-process key, so a client that sends its * own copy cannot make the gateway believe a base it did not set: an unsigned * or foreign-signed value is ignored, and the daemon strips client copies at * every place it injects one. */ declare const PUBLIC_BASE_HEADER = "x-agentproto-public-base"; type PublicBaseSource = "env" | "trusted-header" | "forwarded" | "host" | "loopback"; interface PublicBase { /** `scheme://host[:port]`, no path. */ origin: string; /** `""` or a path such as `/d/` (no trailing slash). */ pathPrefix: string; /** `origin + pathPrefix`: what a page should resolve its links against. */ baseUrl: string; source: PublicBaseSource; } /** Sign a public base for `PUBLIC_BASE_HEADER`. Throws on a value that is not an http(s) base. */ declare function signPublicBase(base: string): string; /** * Resolve the public base (origin + optional path prefix) one request was * reached at. Order, first match wins: * * 1. `configuredOrigin` (env `AGENTPROTO_PUBLIC_HTTP_ORIGIN`), prefix allowed. * 2. `PUBLIC_BASE_HEADER`, set by the daemon on the pairing path and by * link-guard; only a validly signed value counts. * 3. `X-Forwarded-Host` (first value) with `X-Forwarded-Proto`, or the host * default (https for a DNS name, see `defaultProtoForHost`) when absent. * 4. a non-loopback `Host`, with `X-Forwarded-Proto` if present, else http. * 5. the loopback `Host` (or `127.0.0.1` when there is none). * * `X-Forwarded-Prefix` and RFC 7239 `Forwarded` are not read. */ declare function resolvePublicBase(headers: IncomingHttpHeaders, configuredOrigin?: string | undefined): PublicBase; /** * The PTY WebSocket base that goes with an HTTP base: the explicit * `AGENTPROTO_PUBLIC_WS_ORIGIN` when valid, else the HTTP base with its scheme * swapped (http to ws, https to wss), prefix kept. */ declare function deriveWsBaseUrl(httpBaseUrl: string, configuredWsOrigin?: string | undefined): string; /** * `capabilities_inventory` — one read that answers "what MCP servers and * skills does this daemon actually know about, and which harnesses can * reach them?" Backs both the `capabilities_inventory` MCP tool * (session-tools.ts) and its HTTP twin (`GET /capabilities/inventory`, * http-server.ts) so the two surfaces can never drift. * * Read-only, never throws: a failure in one source (MCP discovery, the * proxy registry, an adapter package that fails to import) becomes an * `error` string on that block alone — the rest of the inventory still * returns. Redaction: nothing here ever carries command/args/env/headers/ * url — only the identity/status fields a UI needs (same discipline as * `compactDiscoveredMcp` / `compactImportedMcpEntry`). * * The `skills` block's per-adapter `metadata.skills` / `options` read uses * the same dynamic-`import()` + duck-typed-export technique as * `role-registry.ts`'s adapter-carried role discovery — reused rather than * reinvented, and importantly NOT a `packages/cli` dependency: it walks the * exact adapter list `listAgentAdapters` already returned (so `byHarness` * is guaranteed the same installed set as `adapter_list`), importing each * adapter's own already-installed package by its `packageName`. */ /** How a harness reaches one imported MCP by default: * - `native` — a default bundle mounts it as a native mcpServers entry; * - `indirect` — only via the daemon's own `/mcp` (`mcp_imported_call`), * which the harness gets by default / config / bundle; * - `none` — no default path (still reachable on request). */ type ImportedMcpReach = "native" | "indirect" | "none"; interface CapabilitiesInventoryImportedMcp { id: string; alias?: string; name: string; type: string; source: string; status: "connected" | "idle" | "error" | "unknown"; error?: string; /** Only present when `status === "connected"` — never connects just to count. */ toolCount?: number; usedBySessions: string[]; /** `live` re-reads the source harness config; `snapshot` uses the stored copy. */ resolve?: "live" | "snapshot"; /** Set when the last resolution fell back (source missing / secret unresolved). */ stale?: { reason: string; }; /** Header/env KEY names held behind secret refs (never values). */ secretRefKeys?: { headers?: string[]; env?: string[]; }; /** Per installed adapter: how it reaches this import with NO per-spawn * arguments (resolved default bundles + daemon self-mount default). */ reach: Record; /** Double-mount report (P3): OTHER discovered harness-config entries that * point at the same upstream as this import, i.e. a harness likely * mounts it natively AND through the daemon. Omitted when none. Identity * fields only — never url/command/args/headers/env. * `sameName` = the slugified alias equals the native name (claude-code * then shadows one with the other: no duplicate tools, but they may * silently be different servers/creds). * Limitation: discovery scans the host configs + registered workspaces * only; a session's own cwd `.mcp.json` outside a registered workspace is * NOT seen here (only `mcp-app-resolve` sees it). Report only — nothing * is rewritten. */ alsoNativeIn?: CapabilitiesInventoryAlsoNative[]; } interface CapabilitiesInventoryAlsoNative { source: string; scope: string; name: string; sameName: boolean; } interface CapabilitiesInventoryDiscoveredMcp { id: string; source: string; scope: string; name: string; type: string; imported: boolean; } interface CapabilitiesInventoryMcp { imported: CapabilitiesInventoryImportedMcp[]; discovered: CapabilitiesInventoryDiscoveredMcp[]; /** Which harnesses get the daemon's own `/mcp` (and so the imported pool) * mounted by default — derived from `shouldInjectDaemonSelfMount` + * each installed adapter's declared protocol, never a hardcoded list. */ daemonMountByHarness: Record; error?: string; } interface SkillPackInventoryEntry { name: string; version?: string; path: string; skills: string[]; } interface SkillsByHarnessEntry { adapter: string; target?: { format: string; dir: string; unit?: string; }; installed: string[]; native: string[]; spawnOption: boolean; } interface CapabilitiesInventorySkills { packs: SkillPackInventoryEntry[]; byHarness: SkillsByHarnessEntry[]; defaults: { global: string[]; byAdapter: Record; }; error?: string; } interface CapabilitiesInventory { mcp: CapabilitiesInventoryMcp; skills: CapabilitiesInventorySkills; } /** * Daemon-side `pr_open` — open a PR on behalf of a SANDBOX session. * * Boxes (E2B, computer) have no `gh` and never get a GitHub token — they * push their work branch (`sandboxDeliveryTarget.branch` via * `sandbox-delivery.ts`) and stop. Today the host's orchestrator session * then runs `gh pr create` itself, so the provenance footer credits the * ORCHESTRATOR: its model, its wallet, its cumulative cost — none of which * is the PR's. This module lets the daemon open that PR against the branch * a named authoring session pushed, using the HOST's `gh` (full token, * never exposed to the box), and attribute the provenance to the right * sessions: * * - the branch's authoring sessions ("Authored by", each with its own * model/wallet/box provider and per-session cost — registry sessions on * the branch plus `Agentproto-Session:` trailers on the PR's commits, * resolved by `stampFooterOnPr` via `collectBranchAuthors`); * - the opener, as reported by the caller ("Opened by") — usually the * orchestrator session that invoked `pr_open`, shown for what it IS; * - cost rendered is the AUTHORS' spend, never the opener's ledger. * * The `gh` runner is injected so tests drive everything without `gh`. */ /** Registry slice `openPrForSession` needs — the full `SessionsRegistry` * satisfies it structurally; a fake suffices in tests. */ interface OpenPrRegistry { get(id: string): (FooterSession & { remote?: boolean; }) | undefined; list(): readonly FooterSession[]; recordOpenedPr(sessionId: string, input: { adapter: string; number: number; url: string; }): unknown; } interface OpenPrForSessionInput { /** The authoring session whose work branch the PR opens — resolves the * branch from `sandboxDeliveryTarget.branch`; its `kind` must be * `agent-cli`. */ sessionId: string; registry: OpenPrRegistry; /** Host checkout the PR is opened against — the workspace's local repo * path (a sandboxed session's own cwd lives inside its box). Required: * `gh` has no session for a cwd we can't resolve. */ workspacePath?: string; /** PR title and body (both required — `--fill` is not supported). */ title: string; body: string; /** The session that invoked the open (e.g. the orchestrator) — rendered * as "Opened by" when it differs from the authoring session. */ openedBy?: string; /** Injected `gh` runner; defaults to the real subprocess spawn shared * with the stamp lane. */ run?: GhRunner$1; host?: string; /** The daemon's GLOBAL checkpoint ref namespace * (`defaults.sandbox.checkpoint.refPrefix`), when the deployment moved it. * The target session's own per-spawn override wins over it (see * `checkpointRefPrefixForSession`), the stamper must read the checkpoint * from the namespace the delivery actually pushed to. */ checkpointRefPrefix?: string; /** Gate every `gh` argv about to run (the MCP lane checks each one * against the workspace's `allowed-commands.json`): both the `gh pr * create` that opens the PR AND the footer stamp's own `gh` calls * (`pr view`, `pr edit`, the checkpoint `gh api` read). A returned string * refuses that call; nothing has run yet. */ authorizeArgs?: (args: readonly string[]) => string | undefined; /** Resolve `defaults.prProvenance.footer.skipRepos` per call. A PR in a * listed repo is still created, but never receives a provenance footer. */ skipFooterRepos?: () => Promise | readonly string[]; } type OpenPrForSessionOutcome = { opened: true; url: string; number: number; sessionId: string; stamped: boolean; } | { opened: false; reason: string; }; /** * Run `gh pr create` on the host for a box session's work branch, then * stamp the authorship-aware provenance footer and record the PR against * the authoring session. Never throws — every failure returns a `{ opened: * false, reason }` outcome; the caller decides how to surface it. * Attribution is the point: boxes can't hold `gh`, so whoever runs this on * the host opens it AS the authoring session, not as themselves. */ declare function openPrForSession(input: OpenPrForSessionInput): Promise; /** * Dynamic MCP-app panels for installed `@agentproto/app` apps that ship * a `ui` block (`defineApp({ ui: { html, title?, tools?, csp? } })`, * `app-tools.ts`'s `performInstall`). Bridges `AppRegistry` → `AgnoMcpApp[]` * so `registerMcpApps` (mcp-apps-adapter.ts) can mount them next to the * built-in panels (agentproto_sessions, agents_overview, ...). * * `mcpServerFactory` (index.ts) rebuilds a fresh McpServer per `/mcp` * request, so this module never throws — a bad app record must not take * down every other request. A collided tool id is still skipped with a * `console.warn` (there's nowhere else for a second panel to live). Every * OTHER failure — a removed app dir, a missing/unreadable `ui.path`, a * failed or in-flight `ui.build` — still mounts the panel, serving a * readable HTML placeholder/error page in place of the real bundle * (app-ui-placeholder.ts) instead of skipping it outright: a `ui://` * resource that silently doesn't exist just shows as a JSON-RPC "resource * not found" in a host, which is what motivated this file's placeholder * page in the first place — a HOST-VISIBLE page, even a stand-in one, beats * a resource the host has to explain away as missing. */ /** * The MCP Apps wire (spec `2026-01-26`) over `postMessage` JSON-RPC, exposed * as `window.McpApp.connect() -> Promise<{ callTool, sendMessage, * updateModelContext, openLink, onTeardown }>`. No host in this stack injects * an SDK global into the app iframe, so every UI panel that talks through * `window.McpApp` (all of them — see each app's `ui.ts` under * `packages/apps/src`) would otherwise throw `Cannot read properties of * undefined (reading 'connect')` at boot. Injected here, at serve time, so * every installed app's panel is covered without each app shipping its own * copy of the bridge. * * Bridge surface: * - `callTool(name, args)` — JSON-RPC `tools/call` * - `sendMessage(content)` — JSON-RPC `ui/message` * - `updateModelContext({content?, structuredContent?})` — JSON-RPC * `ui/update-model-context`; each call replaces the previous context. * - `openLink(url)` — JSON-RPC `ui/open-link` {url} * - `onTeardown(cb)` — register a cleanup callback invoked on * `ui/resource-teardown` from the host, at which point the bridge also * replies `{result:{}}` automatically. * - `getHostContext()` / `onHostContext(cb)` — the host context captured * from the `ui/initialize` result and merged on every * `ui/notifications/host-context-changed` (the notification carries only * the changed keys, per the ext-apps spec). * - `getToolInput()` / `onToolInput(cb)` — the arguments the panel's own tool * (`app_ui_`) was invoked with, from `ui/notifications/tool-input`, * falling back to the tool's own result (`ui/notifications/tool-result`, * which `registerMcpApps` fills with `execute()`'s return value) for a host * that forwards results but not inputs. A late subscriber is replayed the * last value, same as `onHostContext`. Lets an MCP-hosted panel resolve a * deep link (e.g. `{view: "wallets/my-profile"}`) the way the browser-served * panel resolves `location.hash`. * - `displayMode` — `{get, available, request, onChange, mountToggle}`, the * shared controller from `@agentproto/app-client/display-mode` (also * published as `window.McpApp.displayMode` once connected). It is what * mounts the floating ⤢ toggle; an app that wants the control in its own * header opts the floating one out (``, or `connect({displayToggle: "none"})`) and calls * `displayMode.mountToggle(el)` instead. */ declare const MCP_APP_BRIDGE_SCRIPT = "\n"; /** Apply the public base to already bridge-injected html (the cached form); * a no-op when this exact assignment is already present. */ declare function injectPublicBaseUrl(html: string, baseUrl: string): string; /** Inject `MCP_APP_BRIDGE_SCRIPT` followed by the two * `window.AgentprotoUI` scripts (`DISPLAY_MODE_SCRIPT`, then * `RUNNER_SELECT_SCRIPT`) — every installed app UI gets the shared * display-mode toggle and `mountRunnerSelect` for free, same as it gets * `window.McpApp` (see `injectAfterStructuralTag` for the placement rule). * The halves are independently idempotent, so a single * `injectAfterStructuralTag` call inserts only whichever ones the document * doesn't already define — inserting them one call each would place the * second BEFORE the first (all target "right after the same structural * tag"), which is why they're concatenated first instead. `window. * AgentprotoUI` gates BOTH of its scripts as one unit: a document that * already defines that namespace brings its own, and the bridge's * `installDisplayMode` falls back to a controller with no button rather * than fighting it. The bridge guard matches an assignment only — every * app panel CONSUMES `window.McpApp.connect()`, so matching any mention * would skip injection for exactly the documents that need it, leaving * `window.McpApp` undefined in the host iframe. */ declare function injectMcpAppBridge(html: string, baseUrl?: string): string; /** * The caller's node scope, derived once and shared by every daemon read path * (memory tools and digest, file tools, app data, brain query, imported-call * gate). * * AIP-34 §Node scope of a session: the scope is read from the CALLER session's * AIP-46 ground (here `SessionDescriptor.cwd`), never from the configuration of * the server that executes the call. A call whose caller cannot be identified is * refused, never served unscoped. A call with no caller session at all on the * daemon's own authenticated surface is a host call and stays unscoped. A * session whose ground lies in no declared tree has no node scope and keeps * today's behaviour. * * `sealed` is a guarantee about what the host composes and returns, not an OS * wall, and the caller id is a claim (AIP-34 §What `sealed` guarantees). */ interface CallerNode { tree: NodeTree; node: TreeNode; /** The node, then each ancestor by parent link up to the tree root. */ chain: readonly TreeNode[]; /** AIP-72 section 10 projection: `chain` cut after the first sealed or hard node. */ projection: readonly TreeNode[]; } type CallerScope = { kind: "host"; } | { kind: "refused"; reason: string; } | { kind: "session"; sessionId: string; /** Canonical AIP-54 operator ref the session runs for (AIP-46 §Operator binding). */ operator?: string; /** Absent: the session's ground lies in no declared node, so no wall applies to it. */ node?: CallerNode; }; declare const HOST_CALLER: CallerScope; declare class CallerRefusedError extends Error { constructor(reason: string); } interface SessionLookup { get(id: string): { cwd?: string; operator?: string; } | undefined; } interface CallerScopesOptions { /** How long a loaded tree is reused. A WORKSPACE.md edited inside the window is seen after it. */ treeTtlMs?: number; now?: () => number; } interface LocatedNode { tree: NodeTree; node: TreeNode; } declare class CallerScopes { #private; constructor(opts?: CallerScopesOptions); clear(): void; /** The declared node that owns `path`, or undefined when no declared tree contains it. Throws when a tree cannot be read. */ locate(path: string): LocatedNode | undefined; /** The scope of a session from its ground and operator. A ground the tree cannot place, or a tree that cannot be read, is refused. */ ofSession(input: { sessionId: string; ground?: string; operator?: string; }): CallerScope; /** * The caller of one gateway request. No `callerSessionId` is a host call * (the daemon's own authenticated surface); an id the daemon does not know * is refused. */ resolve(callerSessionId: string | undefined, sessions: SessionLookup): CallerScope; /** * Whether `path` may be shown to the caller. A path outside every declared * tree is not walled. With `subtree`, every declared node strictly inside * `path` must be visible too (a recursive delete of a folder holding a * sealed node is a write into that node). */ pathVisible(caller: CallerScope | undefined, path: string, opts?: { subtree?: boolean; }): boolean; } /** The one instance the daemon shares between spawn, restart and the gateway. */ declare const callerScopes: CallerScopes; /** * MCP tools that expose the per-workspace brain to agents. * * Three tools over the shared {@link WorkspaceBrains} registry: * * - `workspace_brain_query` — BM25 recall over a workspace's ingested * conversations (dispatch to the provider). * - `workspace_brain_status` — how many sessions a workspace has ingested. * - `workspace_brain_ingest` — manually trigger ingestion (a session, or * every known-but-uningested session). * * Every tool resolves its target workspace the same way: an explicit * `workspace` argument wins; otherwise the calling session's own workspace is * used (from its descriptor's `workspaceSlug`). Resolution applies the bucket * membership rule, so an unregistered slug degrades to `default` rather than * pointing a brain at an arbitrary path. * * Node scope (AIP-34): a hit is a fragment of one session's transcript, and a * session belongs to the node of its ground. A caller scoped to a node only * receives hits from sessions whose node is visible to it; the filter runs * before the top-K cut, and a hit whose session cannot be placed is dropped, * never served unscoped. A caller that cannot be identified is refused. A host * call, and a session whose ground lies in no declared tree, are not filtered. */ interface RegisterBrainToolsOptions { /** The shared per-workspace brain registry. */ brains: WorkspaceBrains; /** Registry used to resolve the calling session's own workspace. */ registry: SessionsRegistry; /** The calling agent session id (from `?callerSessionId=` on `/mcp`). */ callerSessionId?: string; /** Whose node scope filters the answers. Missing or refused: every tool refuses. */ callerScope?: CallerScope; /** Where trees are read from. Default: the daemon's shared instance. */ scopes?: CallerScopes; } declare function registerBrainTools(server: McpServer, opts: RegisterBrainToolsOptions): void; declare const webSearchInputSchema: z.ZodObject<{ query: z.ZodString; count: z.ZodDefault>; country: z.ZodOptional; language: z.ZodOptional; freshness: z.ZodOptional>; safesearch: z.ZodOptional>; }, z.core.$strip>; type WebSearchInput = z.infer; declare const webSearchOutputSchema: z.ZodObject<{ provider: z.ZodEnum<{ brave: "brave"; serper: "serper"; }>; results: z.ZodArray; position: z.ZodNumber; }, z.core.$strip>>; }, z.core.$strip>; type WebSearchOutput = z.infer; type WebSearchResult = WebSearchOutput["results"][number]; declare const webSearchTool: _agentproto_tool.ToolHandle<{ query: string; count: number; country?: string | undefined; language?: string | undefined; freshness?: "pm" | "pd" | "pw" | "py" | undefined; safesearch?: "off" | "strict" | "moderate" | undefined; }, { provider: "brave" | "serper"; results: { title: string; url: string; position: number; snippet?: string | undefined; }[]; }, ToolContext>; declare function defineBraveSearchHttpDriver(): DriverHandle; declare function defineSerperHttpDriver(): DriverHandle; interface RegisterWebSearchToolsOptions { /** Injectable env (tests); default `process.env`. */ env?: NodeJS.ProcessEnv; /** Injectable fetch (tests / live e2e); default `globalThis.fetch`. */ fetch?: typeof fetch; } /** * Register the `web.search` MCP tool (`web_search`) when at least one * provider key is configured. With NEITHER key present, nothing is * registered — no broken tool is advertised, silently. */ declare function registerWebSearchTools(server: McpServer, opts?: RegisterWebSearchToolsOptions): void; /** * Workshop-brain subscriber — auto-ingest a workspace's conversations when its * sessions exit. * * Subscribes to `session:exited` on the {@link SessionEventBus} and, after a * short debounce, fire-and-forgets an ingestion of each freshly-exited session * into its workspace's brain. The debounce batches a flurry of exits (e.g. an * orchestrator tearing down N children at once) into one pass instead of N * index rebuilds. * * Mirrors `webhook-notifier.ts`'s containment discipline: the handler never * throws into the bus's hot path — every error is swallowed and logged, so a * brain hiccup can never take down an exit event. */ interface WorkspaceBrainSubscriberOptions { readonly bus: SessionEventBus; /** The shared brain registry. */ readonly brains: WorkspaceBrains; /** Debounce window for batching consecutive exits. Default 5000ms. */ debounceMs?: number; /** Returns true when another owner (the brain-ingest reaction) handles this * workspace, so the legacy subscriber must skip it. A throw is caught by the * existing per-ingest try/catch: the ingest is then skipped like any other * failure. */ skipWorkspace?: (workspace: string) => boolean | Promise; } interface WorkspaceBrainSubscriber { /** Wire the handler onto the bus (idempotent). */ start(): void; /** Unsubscribe (idempotent). */ stop(): void; /** Flush any pending (not-yet-debounced) exits now. */ flush(): void; } declare function createWorkspaceBrainSubscriber(opts: WorkspaceBrainSubscriberOptions): WorkspaceBrainSubscriber; /** * Review ledger — the daemon-side record of every review attestation. * * Lives under the daemon state dir, NEVER in the reviewed repo's working * tree: `~/.agentproto/reviews////.json` * — the path IS the ledger key `(repoRemote, manifestSha, binding, rangeSha)` * (the repo slug is a filesystem-safe form of the normalized remote). One * file per key; a re-run of the same key overwrites it with the newer * attestation. * * Every attestation is recorded — including `incomplete` and dirty-tree ones, * so `review_ledger` shows the history honestly — but only a clean `pass` / * `block` is ever served back as a cache hit (see `lookupCached`). * * Each file is an {@link LedgerEntry}: the self-contained attestation (what * `review_export` writes out) plus host-local metadata that is NOT part of * what gets attested (the checkout path, the manifest path, the manifest's * `verdict.exportDir`). * * Beside each entry sits an optional `.annotations.json` * ({@link LedgerAnnotations}): the MUTABLE follow-up layer — a PR link found * after the fact, and `review_pr` status snapshots appended over time. It is * never hashed into (or exported with) the attestation, so annotating an * entry can't disturb a signature over it. * * Same persistence primitives as the sibling JSON stores (`node:fs/promises`, * write-tmp + rename). The root is injectable so tests never touch * `~/.agentproto`. */ /** Host-local metadata stored beside an attestation (never exported). */ interface LedgerHostMeta { /** Absolute path of the checkout the review ran in. */ repoRoot: string; /** Absolute path of the REVIEW.md that was used. */ manifestPath: string; /** The manifest's `verdict.exportDir`, resolved against `repoRoot`. */ exportDir?: string; } interface LedgerEntry { attestation: Attestation; host: LedgerHostMeta; } /** One `review_pr` status fetch. */ interface PrStatusSnapshot { /** ISO timestamp of the fetch. */ fetchedAt: string; state: "open" | "merged" | "closed"; reviews: Array<{ login: string; state: string; submittedAt: string; }>; checks?: Array<{ name: string; conclusion: string | null; }>; /** The PR's head commit at fetch time — absent from snapshots taken * before this field existed. */ headSha?: string; /** The PR's head branch name at fetch time — absent from snapshots taken * before this field existed. Unlike GitHub's `author` (the same bot * account for every PR we open), the branch prefix (`pm-brain/...`, * `mainteneur/...`, `fix-pr--...`) identifies which role/agent opened * the PR. */ headRefName?: string; } /** The mutable annotations sidecar of a ledger entry. */ interface LedgerAnnotations { pr?: ReviewPrRef; /** Oldest first — each `review_pr` call appends one. */ prStatus?: PrStatusSnapshot[]; } interface ReviewLedgerFilter { repoRemote?: string; rangeSha?: string; binding?: string; manifestSha?: string; /** Keep only entries whose `attestation.requester.sessionId` is one of * these — backs `review_ledger({requesterSessionId, subtree})`: a single * id, or (with `subtree: true`) that session's whole subtree, resolved by * the caller before reaching the ledger. Answered from an in-memory * `requesterSessionId -> ledger keys` index (built lazily on first use, * kept current on every `put()`), never a full re-scan. */ requesterSessionIds?: readonly string[]; } interface ReviewLedger { /** Absolute root directory of the ledger. */ readonly root: string; put(entry: LedgerEntry): Promise; get(key: LedgerKey): Promise; /** A reusable verdict for `key`: a clean (not dirty) `pass`/`block` whose * rubric AND pack digests still match. `incomplete` is never reused. */ lookupCached(key: LedgerKey, rubrics: readonly RubricDigest[], packs?: readonly PackDigest[]): Promise; findByRunId(runId: string): Promise; /** Entries matching `filter`, newest first. */ list(filter?: ReviewLedgerFilter): Promise; /** The annotations sidecar of `key` (`{}` when there is none). */ getAnnotations(key: LedgerKey): Promise; /** Read-modify-write the annotations sidecar of `key`; returns the result. */ updateAnnotations(key: LedgerKey, update: (current: LedgerAnnotations) => LedgerAnnotations): Promise; } /** Record `pr` as the entry's PR link (replacing any previous link). */ declare const withPr: (pr: ReviewPrRef) => (a: LedgerAnnotations) => LedgerAnnotations; /** Append one status snapshot. */ declare const withPrStatus: (snapshot: PrStatusSnapshot) => (a: LedgerAnnotations) => LedgerAnnotations; declare const defaultReviewLedgerRoot: () => string; /** Filesystem-safe slug of a normalized repo remote * (`github.com/agentproto/ts` → `github.com_agentproto_ts`). */ declare function repoSlug(repoRemote: string): string; declare function createReviewLedger(opts?: { root?: string; }): ReviewLedger; /** * Run-scoped sharing of equivalent reviewer executions. * * Several lanes of one review run can resolve — through their own * `fallbackPresets` chains — to the SAME reviewer: same actual adapter / * model / auth profile, same rubric bytes, same effective frozen git range * (including a composed delta base) and same check options. Running that * reviewer once per lane pays for N identical reviews and records N verdicts * that look like independent agreement. This coordinator lets the first lane * (the OWNER) run the execution and every later lane that asks for the same * key (a JOINER) wait for it instead. * * What it does NOT do (those already exist elsewhere, and are not duplicated): * wallet / rate-limit cooldowns and the OpenRouter guard stay in * `review-reviewer-host.ts`; ledger composition stays in `review-compose.ts`; * cancellation stays the run's `AbortSignal`. * * Contract: * - one coordinator per run (the lane executor builds it), so nothing is * shared across runs; the owner/joiner decision is made synchronously, so * concurrent acquires can never produce two owners; * - the execution is bound by the OWNER's deadline (inside `execute`); a * joiner never extends it and leaves with its own deadline if that is * earlier; * - the execution's abort signal fires only when EVERY participant has left * (cancelled / hit its deadline), so cancelling the owner while joiners * still wait does not kill their reviewer; * - only a result `retain` accepts (a settled success) is kept for later * lanes of the run; any other result is shared with the participants that * were in flight and then forgotten, so a later lane retries for itself; * - joiners and (when someone joined) the owner get a {@link SharedMark}; * lanes carrying one executionId are ONE reviewer's verdict. */ /** Provenance of a shared execution — mirrors `LaneSharedExecution`. */ interface SharedMark { executionId: string; role: "owner" | "joiner"; ownerLane: string; } type ShareOutcome = { kind: "value"; value: T; mark?: SharedMark; } /** This participant stopped waiting (its signal aborted / its deadline * passed). The execution itself keeps going while any participant remains. */ | { kind: "left"; why: "cancelled" | "deadline"; mark?: SharedMark; }; interface ShareRunArgs { /** Full equivalence key (caller-built; see `shareKeyOf`). */ key: string; laneId: string; /** This participant's own cancel signal. */ signal?: AbortSignal; /** This participant's absolute deadline (epoch ms). Applied to JOINERS; the * owner's `execute` enforces the owner's own deadline itself. */ deadline: number; /** Runs the work. Only called for the owner. `signal` aborts when every * participant has left. */ execute: (signal: AbortSignal) => Promise; /** Whether a settled value is kept for later lanes of the run. */ retain: (value: T) => boolean; } interface ReviewExecutionShare { run(args: ShareRunArgs): Promise>; /** Executions currently running / settled-and-retained. */ stats(): { inFlight: number; retained: number; }; } /** What the runner hands the reviewer host so its fallback steps can share. */ interface ReviewerShareInput { coordinator: ReviewExecutionShare; /** Run-scoped equivalence key (review id, rubric digest, effective range, * check options). The host adds the resolved adapter/model/profile. */ key: string; laneId: string; } /** * Review runner — the daemon host for `@agentproto/review`. * * The pure package parses REVIEW.md and compiles a binding into an ordinary * AIP-15 workflow; this module supplies everything that touches the world: * * 1. resolve the repo + range — `merge-base(, HEAD)..HEAD` * unless the caller pins `base`/`head`; * 2. ledger pre-check — a clean `pass`/`block` already recorded for the * same `(repoRemote, manifestSha, binding, rangeSha)` (and the same * rubric digests) is returned with `cached: true`, nothing runs; * 3. execute the compiled workflow through `@agentproto/workflow-runtime`'s * `compileWorkflow` + `runWorkflow` — prepare steps (the engine's own * gate runner), then the FREEZE (head resolved after prepare), then the * lanes in parallel through {@link createReviewLaneExecutor}, then the * fan-in verdict; * 4. build the attestation and write it to the ledger. A CANCELLED run * (`cancel()`, or superseded by a newer head — see `supersede`) writes * nothing: nobody asked for its verdict any more. * * Lanes: command lanes run `sh -c ` in their own process group with a * hard timeout; agent lanes spawn a CHILD REVIEWER SESSION through * {@link ReviewerSessionHost} — in the daemon, {@link createDaemonReviewerHost}, * which uses the same `spawnAgentSession` core `agent_start` uses and kills * the session through the registry on timeout/cancel (a child session, never * an orphan pid). The reviewer gets a pointer-style prompt (range + rubric * path) and writes a structured verdict file under the ledger's run dir — * outside the reviewed tree. * * Async pattern mirrors `WorkflowRunner`: `start()` returns a run record * immediately and executes in the background; `status()` polls; `wait()` * blocks. Runs live in memory for the daemon's lifetime; the ATTESTATION is * what persists (the ledger), and `status()` falls back to it for a run that * finished before a daemon restart. */ /** * Normalize a git remote URL so SSH and HTTPS clones of the same repo agree: * `git@github.com:agentproto/ts.git` and `https://user@github.com/agentproto/ts` * both become `github.com/agentproto/ts`. Credentials are always stripped. */ declare function normalizeRemote(url: string): string; /** Run one command lane: `sh -c ` in its own process group, output * captured (tail-bounded), hard-killed on timeout or cancel. */ declare function runShellLane(input: { command: string; cwd: string; timeoutMs: number; signal?: AbortSignal; }): Promise; /** Outcome of one reviewer session's run. */ type ReviewerRunResult = ({ status: "ended"; sessionId: string; preset: string; model?: string; } | { status: "timeout"; sessionId: string; preset: string; model?: string; } | { status: "failed"; error: string; sessionId?: string; preset?: string; model?: string; }) & { /** Reviewers that were unavailable BEFORE the one in `preset`, in order, each * with its error. Set only when a `fallbackPresets` chain advanced past at * least one reviewer; `preset`/`model`/`sessionId` always name the reviewer * that produced this result. */ fallbacks?: LaneFallback[]; /** Set when the verdict artifact was missing or invalid at turn end and the * host ran its bounded recovery step — what that step concluded. Absent * when the artifact was valid as written (no recovery ran). */ recovery?: LaneRecovery; /** Set when this result came from a reviewer execution shared with other * lanes of the run (same resolved model/config, rubric and range). */ sharedExecution?: LaneSharedExecution; }; /** * The agent-lane executor seam: spawn a reviewer session under a harness * preset, run ONE turn with `prompt`, and stop it — killing it through the * session lifecycle on timeout or cancel. The daemon wires * {@link createDaemonReviewerHost}; tests wire a fake. */ interface ReviewerSessionHost { run(input: { preset: string; /** Tried in order, after `preset`, only when the preceding reviewer was * unavailable (never after a verdict, timeout, or cancel). */ fallbackPresets?: string[]; cwd: string; prompt: string; label: string; timeoutMs: number; parentSessionId?: string; signal?: AbortSignal; /** The verdict file the reviewer must have written by turn end. The host * checks it WHILE the reviewer session is still alive (before cleanup) * and, if it is missing/invalid, runs its one bounded recovery step — * the runner still re-reads and re-validates it afterwards. */ artifact?: { path: string; laneId: string; blockOn: Severity; }; /** Run-scoped sharing: a chain step whose resolved reviewer is equivalent * to another lane's (same key) runs once and the lanes share the result. * Hosts that do not share ignore it. */ share?: ReviewerShareInput; }): Promise; } /** Attestation composition wiring for `createReviewLaneExecutor` — omitted * or `enabled: false` disables composition and every agent lane reviews the * full frozen range, same as before Goal B. */ interface ReviewComposeContext { enabled: boolean; ledger: ReviewLedger; manifestSha: string; binding: string; rubrics: RubricDigest[]; /** `as` → this run's resolved pack digest — a lane whose check came from * a `uses[]` pack additionally requires the candidate to carry an * identical digest for that pack (see `review-compose.ts`). */ packByNamespace?: Record; } interface ReviewLaneExecutorContext { runId: string; reviewId: string; repoRoot: string; manifestPath: string; /** Directory the agent lanes' verdict files are written under. */ runDir: string; reviewers?: ReviewerSessionHost; parentSessionId?: string; compose?: ReviewComposeContext; } /** The daemon's {@link ReviewLaneExecutor}: subprocess command lanes, child * reviewer sessions for agent lanes. */ declare function createReviewLaneExecutor(ctx: ReviewLaneExecutorContext): ReviewLaneExecutor; interface ReviewRunInput { /** Any directory inside the repo to review. */ cwd: string; /** REVIEW.md path — absolute, or relative to `cwd`. Default: `/REVIEW.md`. */ manifestPath?: string; /** Binding name. Default: the sole binding, or `default`. */ binding?: string; /** Range base (ref or sha). Default: `merge-base(, HEAD)`. */ base?: string; /** Range head (ref or sha). Default: `HEAD`, resolved AFTER prepare. */ head?: string; /** Ignore a cached ledger verdict and re-run. */ nocache?: boolean; /** Let an agent lane reuse a prior passing attestation and review only the * delta on top of it (attestation composition — see `review-compose.ts`). * Default true. `nocache: true` implies `compose: false` — a caller * asking to ignore the cache wants a full fresh review, not a partial * one. Command lanes are never composed regardless of this flag. */ compose?: boolean; /** Session the agent lanes' reviewer sessions nest under. */ parentSessionId?: string; /** Session that requested the review — recorded as * `attestation.requester.sessionId`. Default: `parentSessionId`. */ requesterSessionId?: string; /** The PR the range is being reviewed for, when the caller knows it — * recorded as `attestation.pr` and as the entry's annotation link. */ pr?: ReviewPrRef; /** Before running, cancel in-flight runs for the same repo + binding + base * whose head DIFFERS (an older push nobody will read the verdict of) — as * long as that run is the same line of work: the same checkout, or the same * branch name with a head that is an ancestor of this one (a re-push from * another worktree after amend/fixup). A sibling or stacked branch reviewed * from another worktree is never cancelled, even when its head is an * ancestor of this one; a detached HEAD only matches its own checkout. * Gates should pass `true`; the default is `false`. */ supersede?: boolean; } type ReviewRunStatus = "running" | "done" | "failed" | "cancelled"; interface ReviewRun { runId: string; status: ReviewRunStatus; startedAt: string; endedAt?: string; reviewId?: string; binding?: string; repoRemote?: string; /** The resolved range base, once known. */ baseSha?: string; /** The range head: the pre-prepare head once resolved, then the frozen head. */ headSha?: string; /** The checkout the run reviews, once resolved. */ repoRoot?: string; /** The branch checked out in `repoRoot` when the range resolved; absent on a * detached HEAD. */ branch?: string; /** Set on a run cancelled because a newer head superseded it. */ supersededBy?: string; /** Lanes settled so far (live progress while `running`). */ lanes: LaneResult[]; /** Set once `done`. */ attestation?: Attestation; /** True when `attestation` was served from the ledger — nothing ran. */ cached?: boolean; /** Where the attestation was written in the ledger. */ ledgerPath?: string; error?: string; /** The session that requested this run (`input.requesterSessionId ?? * input.parentSessionId`), when known — mirrors * `Attestation.requester.sessionId` for a run that hasn't (or never will) * reach the ledger, so `review_ledger({includeRunning: true})` and the * `session_tree` badge (WP-review-panel) can attribute an in-flight/ * cancelled/failed run to its requester without waiting for an * attestation. */ requesterSessionId?: string; /** Set when the attestation was written UNSIGNED because signing failed * (no `ssh-keygen`, an unreadable/unwritable key, …) — a signing failure * never fails the review itself, but the reason is surfaced here rather * than silently dropped. Absent when the attestation is signed, or the * run never reached a verdict. */ signingError?: string; } interface ReviewRunner { start(input: ReviewRunInput): ReviewRun; status(runId: string): Promise; wait(runId: string): Promise; cancel(runId: string): boolean; /** Every run this daemon process has started, newest first — running runs * plus ones that settled (done/failed/cancelled) without a daemon * restart in between. Runs live in memory only for the process lifetime * (a restart loses this list, same as the rest of `runs` — the ATTESTATION * is what persists, in the ledger). Backs `review_ledger({includeRunning: * true})` and the `session_tree` review badge. */ list(): ReviewRun[]; readonly ledger: ReviewLedger; } interface CreateReviewRunnerOptions { ledger: ReviewLedger; /** Agent-lane executor. Omitted ⇒ agent lanes are `skipped` (and the * verdict therefore `incomplete`), never silently passed. */ reviewers?: ReviewerSessionHost; /** Attestor identity. Default: `agentproto-runtime@`. */ daemonId?: string; /** Directory the review signing keypair lives in. Default: * `~/.agentproto/keys` (see `review-signing.ts`'s `defaultReviewKeysDir`). * Override for a throwaway HOME in a live-proof daemon, or a temp dir in * tests — production code should leave this unset. */ signingKeysDir?: string; /** Overrides the resolved signing principal for every run (tests; a * configured `review.principal`). Default: `git config user.email` of * the reviewed repo, else a host-derived fallback — see * `review-signing.ts`'s `resolvePrincipal`. */ signingPrincipal?: string; /** `env` passed to the `ssh-keygen` child processes signing shells out to * — tests use this to simulate "ssh-keygen not on PATH" without touching * the real PATH. Default: `process.env`. */ signingEnv?: NodeJS.ProcessEnv; /** Called once a run with a `requesterSessionId` reaches `done` — never * for `failed`/`cancelled` (no verdict to report). Display-only: the * daemon writes `text` into the requester's transcript as a `notice` * (see `sessions.ts`'s `recordNotice`) so `session_story`/`live_session` * show it — this never enqueues a prompt, touches the inbox, or starts a * turn. Fire-and-forget from the runner's perspective; a throw here is * swallowed. */ notifyRequester?: (sessionId: string, text: string) => void; } /** Placeholder values the daemon binds for every review. `{changed}` is a * shell-quoted turbo filter for the packages changed since the range base * (compose dependents with `...{changed}`). */ declare function hostPlaceholders(baseSha: string): Record; declare function createReviewRunner(opts: CreateReviewRunnerOptions): ReviewRunner; /** * Attestation signing — the daemon host side of the review primitive's * frozen "who signs" design (see `.plans/review-primitive/PLAN-step1.6-signing.md`): * only the daemon signs, with ONE ed25519 keypair per daemon install at * `~/.agentproto/keys/review_ed25519` (+ `.pub`), generated on first use. * Owner/session/model/presets stay claims inside the attestation payload — * they are never signers. * * Deliberately shells out to `ssh-keygen -Y sign` / `-Y verify` rather than * vendoring ed25519 + the SSHSIG envelope format: the signature an operator * gets is the same shape `git commit -S` and `ssh -Y sign` already produce * (an allowed_signers file, `ssh-keygen -Y verify`), so nothing here is a * bespoke format a reviewer has to learn. * * A signing failure (no `ssh-keygen` on PATH, an unreadable/unwritable key) * must NEVER fail the review — {@link signAttestation} always resolves, * returning `{ error }` instead of a signature for the caller to record as * an unsigned attestation + a reason (never thrown). */ /** The `-n ` every sign/verify call is scoped to — distinct from * any other SSHSIG use of the same key (git commit signing, SSH auth). */ declare const SIGN_NAMESPACE = "agentproto-review"; declare const defaultReviewKeysDir: () => string; interface ReviewSigningKey { privateKeyPath: string; publicKeyPath: string; /** `ssh-keygen -lf` fingerprint, e.g. `SHA256:xxxx`. */ fingerprint: string; /** Raw contents of the `.pub` file (`ssh-ed25519 AAAA... comment`). */ publicKeyLine: string; } /** Ensure the daemon's review signing keypair exists at `dir` (default * `~/.agentproto/keys`), generating it with `ssh-keygen -t ed25519` on * first use. The private key is always left/made mode 0600. Throws if * `ssh-keygen` is unavailable or the directory isn't writable — callers * that must not fail the review catch this (see `signAttestation`). */ declare function ensureReviewSigningKey(opts?: { dir?: string; env?: NodeJS.ProcessEnv; }): Promise; /** The ready-to-paste `allowed_signers` line for `principal` + this key — * what `agentproto review key show` prints. */ declare function allowedSignersLine(principal: string, publicKeyLine: string): string; /** `principal` = the owner identity a signature claims: an explicitly * configured value if the caller has one, else `git config user.email` of * the reviewed repo, else a host-derived fallback so signing never blocks * on an unconfigured git identity. */ declare function resolvePrincipal(opts: { repoRoot: string; configuredPrincipal?: string; }): Promise; type ReviewSignature = NonNullable; /** * Sign `att` with the daemon's review key, generating it on first use. * NEVER throws — a signing failure (no `ssh-keygen`, unreadable key, …) * resolves `{ error }` so the caller can write the attestation unsigned * with the reason recorded, rather than failing the review. */ declare function signAttestation(att: Attestation, opts: { principal: string; keysDir?: string; env?: NodeJS.ProcessEnv; }): Promise<{ signature?: ReviewSignature; error?: string; }>; interface VerifySignedAttestationResult { ok: boolean; problems: string[]; } /** * Verify `att.attestor.signature` against `allowedSignersPath`: the claimed * principal must map (per the allowed_signers file) to the signing key * (`ssh-keygen -Y find-principals`), and the signature must verify over the * canonical bytes recomputed from `att` right now (`ssh-keygen -Y verify`) — * so ANY tamper (verdict, a lane, the principal claim itself) breaks it. * Never throws; every failure mode (missing signature, missing/unreadable * allowed_signers, key not recognized, bad signature, no `ssh-keygen`) * comes back as a `problems` entry. */ declare function verifySignedAttestation(att: Attestation, opts: { allowedSignersPath: string; env?: NodeJS.ProcessEnv; }): Promise; /** Small helper so callers (the CLI's `review verify`) can resolve a default * `.agentproto/allowed_signers` without their own `existsSync` import. */ declare function fileExists(path: string): Promise; /** * Attestation composition — the delta re-review (Goal B, * `.plans/review-primitive/PLAN-step1.6-signing.md`). * * A range that grew (`base..mid` attested `pass`, then `base..head` * requested) lets an AGENT lane reuse the prior attestation and review only * `mid..head` instead of the whole range from scratch. Command lanes are * never composed — they check tree state, not a diff, so they always run at * the new head (see `review-runner.ts`'s `createReviewLaneExecutor`, which * never calls into this module for a command check). * * Every eligibility rule lives in {@link findComposeCandidate}, checked one * at a time so a caller can tell exactly which rule rejected a candidate: * same repoRemote + binding + manifestSha + rubric digest for the lane, the * prior attestation's own `verdict` AND this lane's own status both `pass`, * the prior `baseSha` equal to the new base, the prior `headSha` a strict * ancestor of the new head, the prior not `dirty` — and, when this lane's * check comes from a `uses[]` review pack (Step 5), the prior attestation * must ALSO carry an identical digest for that pack (`input.packDigest`): * the rubric-digest check alone only catches an edit to THIS check's rubric * file, not an edit elsewhere in the pack (another check's config, the * pack's own REVIEW.md) that could change what this check's config resolves * to. Trust is automatic here: * a candidate is only ever drawn from THIS daemon's own ledger (`ledger.list`), * which is the "own ledger" half of the frozen trust rule — the "or signed by * a key in the allowed_signers in use" half applies to a prior attestation * from OUTSIDE this daemon's ledger, which this daemon-local runner never * encounters (nothing here imports attestations from elsewhere to compose * from). */ interface FindComposeCandidateInput { ledger: ReviewLedger; repoRoot: string; repoRemote: string; manifestSha: string; binding: string; checkId: string; rubricSha256: string; /** Set when `checkId` is a `uses[]` pack check (namespaced `/`): * the id + digest of the pack CURRENTLY resolved for that namespace. * Composition additionally requires the prior attestation's `packs` to * carry an entry with this same id and digest. `undefined` for a local * (non-pack) check — nothing extra to require. */ packDigest?: { id: string; alg: string; sha256: string; }; baseSha: string; headSha: string; } interface ComposeCandidate { attestation: Attestation; } /** The newest prior attestation this agent lane can build on, or `undefined` * if none qualifies. `ledger.list` returns newest-first, so the first match * found is already the freshest (the smallest possible delta). */ declare function findComposeCandidate(input: FindComposeCandidateInput): Promise; /** The ledger-key rangeSha of `candidate`'s OWN attestation — what * `LaneResult.composedFrom.rangeSha` records, so a verifier can resolve it * directly via `ledger.get({repoRemote, manifestSha, binding, rangeSha})` * without first decoding anything else. Valid because composition requires * the prior `baseSha` to equal the new run's base (checked above). */ declare function composedFromRangeSha(candidate: ComposeCandidate): string; /** * The runtime's {@link PackLoader}: resolves a `uses[].pack` ref to actual * pack content, for `@agentproto/review`'s `resolvePacks` to merge in. * * Three ref forms, told apart by shape: * - `./relative/path` or `../relative/path` (or an absolute path) — * resolved against the CONSUMER's REVIEW.md directory, same convention * as a check's own `rubric` path. NOT automatically same-repo-same-trust * just because the ref string looks relative: {@link isTrustedRelativePack} * requires the resolved root (realpath'd, so a symlink can't escape) to * sit INSIDE the reviewed repo root AND its REVIEW.md to be tracked by * git there. A ref that resolves outside the repo (`../..`, an absolute * path elsewhere), or inside but untracked (`./node_modules/`, a * gitignored scratch dir), still loads — it just isn't exempt from * `allowCommands`, same as npm/git. * - `git+https://...#<40-hex sha>` — ONLY `https://` is accepted (no * ssh://, file://, ext::, or plain http://; `ext::` in particular can * run an arbitrary local command). Cloned once into * `~/.agentproto/review-packs//` and reused from there on every * later resolve (content-addressed by the pinned sha, so a cache hit * needs no network at all). `parseReviewManifest` already rejects a * floating ref (branch/tag/short sha) or a non-https transport before * this loader ever runs, but both checks are repeated here defensively — * this is the code that actually shells out to `git`, so it doesn't * lean on the caller alone. The URL is also passed to `git clone` after * a literal `--`, so even a scheme-valid but adversarial URL can never * be misread as a flag. * - anything else — an npm package name, resolved from the reviewed * repo's root via Node's own module resolution (`node_modules`, no * network, no install). The looked-up path is `/package.json` — * works for a files-only package with no `main`/`exports` restricting * subpaths, as long as it exposes `"./package.json"` (or none at all). * * A separate confinement, orthogonal to the three forms above and applied * regardless of which one resolved a pack: a check's own `rubric` field is * untrusted input (the pack author's, not the consumer's), so * {@link readRubricConfined} refuses to read outside the pack's own root — * see its doc comment. */ declare const defaultReviewPackCacheDir: () => string; /** Create the daemon's {@link PackLoader}. `manifestDir` (the consumer * REVIEW.md's own directory) anchors a relative-path pack ref; `repoRoot` * anchors npm resolution AND is the trust boundary a relative pack's * resolved root must sit inside of (see {@link isTrustedRelativePack}); * `cacheDir` overrides where pinned git packs are cached (default * `~/.agentproto/review-packs` — tests use a temp dir); `env` overrides * the environment `git` runs under (tests only — e.g. a local HTTPS * fixture with `GIT_SSL_NO_VERIFY`; default `process.env`). */ declare function createReviewPackLoader(opts: { repoRoot: string; manifestDir: string; cacheDir?: string; env?: NodeJS.ProcessEnv; }): PackLoader; /** * PR follow-up for review attestations — the host side of `review_pr`. * * A review attests a git range; whether that range became a PR, and what * happened to the PR afterwards, is only knowable later. This module asks * GitHub through the daemon host's authed `gh` CLI (shelled out — no HTTP * client, no token handling of our own): * * - {@link findPrForCommit}: `headSha → PR` via * `gh api repos/{owner}/{repo}/commits/{sha}/pulls`; * - {@link fetchPrStatus}: the PR's state + reviews (+ check runs on the * PR head, best-effort) as one {@link PrStatusSnapshot}. * * Every failure is a {@link PrLookupError} with a stable `code` — `gh` * missing, `gh` failing (auth, network, 404), a non-GitHub remote, no PR for * the commit — so the tool can return it as structured data instead of * throwing. */ type PrLookupErrorCode = "gh_unavailable" | "gh_failed" | "unsupported_remote" | "no_pr"; declare class PrLookupError extends Error { readonly code: PrLookupErrorCode; constructor(code: PrLookupErrorCode, message: string); } /** Runs `gh ` and resolves its stdout. */ type GhRunner = (args: readonly string[]) => Promise; /** The real runner: `gh` from the daemon's PATH. A missing binary is * `gh_unavailable`; any non-zero exit is `gh_failed` with gh's stderr. */ declare const execGh: GhRunner; /** `github.com/owner/name` → `owner/name`; `undefined` for any other host. * Also accepts the multi-account SSH host-alias convention * (`git@github.com-work:owner/name` normalizes to `github.com-work/owner/name`). */ declare function githubRepoOf(repoRemote: string): string | undefined; /** Parse `https://github.com/owner/name/pull/42` (trailing path/query ok). */ declare function parsePrUrl(url: string): { repo: string; number: number; } | undefined; /** The PR `headSha` belongs to, or `undefined` when GitHub knows none. * Prefers a PR whose head IS `headSha`, then an open one, then the first. */ declare function findPrForCommit(gh: GhRunner, repo: string, headSha: string): Promise; /** The PR's head sha (for matching a `prUrl` to ledger entries). */ declare function prHeadSha(gh: GhRunner, repo: string, number: number): Promise; /** One status snapshot of `pr`: state, reviews, and (best-effort — omitted * when that call fails) the check runs on the PR's current head. */ declare function fetchPrStatus(gh: GhRunner, pr: ReviewPrRef, now?: () => Date): Promise; /** * `~/.agentproto/harness-presets.json` — the persisted harness→profile binding * (mode 0600). A {@link HarnessPreset} names, per adapter harness, WHICH auth * profile and default model a fresh spawn should bill through, so the operator * no longer re-picks the profile every time (today that link lives only * ephemerally per-session `setSessionAccessProfile` or per-spawn in the * Configuration Lab picker). * * This is a POINTER store, like `auth-profiles.json` and * `llm-endpoint-links.json`, not a secret store: an entry holds a `profileRef` * (an {@link AuthProfile} id) and a `defaultModel` string, never a credential — * so it needs no encryption. It reuses the exact persistence primitives the * sibling stores established (a versioned JSON file under `~/.agentproto/`, * `node:fs/promises`, mode 0600, whole-file write) — see * `user-presets.ts` / `profile-store.ts` / `llm-endpoint-links-store.ts`. * * Invariants enforced on write (validated once, at this boundary, for every * CLI/MCP/editor caller): * • at most one `isDefault: true` per `harnessSlug` — the spawn path reads * exactly one default per harness (see `getDefaultHarnessPreset`); * • `profileRef` must reference an EXISTING, ENABLED auth profile — a dangling * or disabled profile can never become the silent default a spawn bills; * • `defaultModel` must be serviceable by that profile's curation allowlist * (a `mode: "allow"` profile only bills the models it lists). * The profile lookup is injected ({@link HarnessPresetValidationDeps}) so the * store is testable without touching the real auth-profile store; it defaults * to `@agentproto/auth`'s `getAuthProfile`. */ /** * A persisted harness→profile binding: for one adapter harness, which auth * profile + default model a fresh spawn bills through when the caller pins * neither explicitly. */ interface HarnessPreset { /** Stable, machine-local id — unique across all presets (e.g. `hm-cheap`). */ id: string; /** Adapter harness slug this preset binds (e.g. `hermes`). Matched against a * spawn's `harness ?? adapter`. */ harnessSlug: string; /** Human-readable display name (e.g. `Cheap`). */ name: string; /** The {@link AuthProfile} id this preset bills through — must exist and be * enabled at write time. Absent = the harness bills on its OWN login (e.g. * `claude-code-cloud`, or `claude-code`/`codex` on their CLI login): a spawn * through this default passes no `access`. */ profileRef?: string; /** Model id applied at spawn when the caller named none (e.g. `z-ai/glm-5.2`). * Absent = the harness/vendor picks its own default (spawn sends no model). */ defaultModel?: string; /** Whether this is THE default preset for its `harnessSlug`. At most one per * harness — enforced on write. */ isDefault: boolean; /** `agent_start.turnRetry` applied to spawns that resolve THIS preset as the * harness default (an explicit `turnRetry` on the spawn wins), so e.g. a * free-model preset can rotate by default. Absent ⇒ no turn retry. */ turnRetry?: TurnRetryInput; } declare const harnessPresetsFileSchema: z.ZodObject<{ version: z.ZodLiteral<1>; presets: z.ZodArray; defaultModel: z.ZodOptional; isDefault: z.ZodBoolean; 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>>; }, z.core.$strip>; type HarnessPresetsFile = z.infer; /** Thrown when a create/update violates a store invariant (unknown/disabled * profile, a model the profile can't service, …). A validation failure, not * an I/O failure — callers surface it as a rejected request, not a crash. */ declare class HarnessPresetValidationError extends Error { constructor(message: string); } /** Injected profile lookup — lets the store validate `profileRef` without a * hard dependency on the real auth-profile file (tests stub it). */ interface HarnessPresetValidationDeps { getProfile: (id: string) => Promise; /** Account slot map for a `slot:` profileRef. Defaults to config.json. */ loadAccountSlots?: () => Promise; } declare function harnessPresetsPath(): string; /** Missing or malformed config is treated as empty — a bad preset file must * never prevent the daemon from spawning. Writes always restore valid JSON. */ declare function loadHarnessPresets(): Promise; /** List all presets, optionally filtered to one harness slug. */ declare function listHarnessPresets(harnessSlug?: string): Promise; /** Look up a single preset by id, or undefined if none exists. */ declare function getHarnessPreset(id: string): Promise; /** The default preset for `harnessSlug`, or undefined when none is marked. The * spawn path reads this to fill an unpinned `access.profileRef` + model. */ declare function getDefaultHarnessPreset(harnessSlug: string): Promise; /** * Add or replace a preset by id. Validates the profile binding, then upserts. * When the incoming preset is `isDefault`, every OTHER preset for the same * `harnessSlug` is demoted first, preserving the one-default-per-harness * invariant even across a replace that flips an id's harness or default flag. */ declare function addHarnessPreset(preset: HarnessPreset, deps?: HarnessPresetValidationDeps): Promise; /** Partial update of an existing preset. Re-validates the resulting profile * binding and re-applies the one-default invariant. Returns the updated * preset, or undefined when `id` doesn't exist. */ declare function updateHarnessPreset(id: string, patch: Partial>, deps?: HarnessPresetValidationDeps): Promise; /** Remove a preset by id. Returns true if it existed. */ declare function removeHarnessPreset(id: string): Promise; /** * Mark `presetId` as THE default for its harness, demoting every other preset * that shares its `harnessSlug`. Idempotent. Throws * {@link HarnessPresetValidationError} when `presetId` doesn't exist or when the * caller-supplied `harnessSlug` disagrees with the preset's own — the latter * guards against defaulting a preset under the wrong harness by a stale id. */ declare function setDefaultPreset(harnessSlug: string, presetId: string): Promise; /** * The daemon's {@link ReviewerSessionHost}: agent review lanes as CHILD * SESSIONS, spawned through the same `spawnAgentSession` core `agent_start` * uses, waited on with the same `monitorSessionWait` core `session_monitor` / * `sessions wait` use, and stopped through `registry.kill` — the normal * session lifecycle, so a timed-out or cancelled reviewer is a killed session * in `session_list`, never an orphan pid. * * A lane's `preset` names the daemon's existing preset surface — no parallel * model/auth config: first a harness preset (`harness-presets.json`: adapter * harness + auth profile + default model), then a user preset * (`presets.json`, handed to `spawnAgentSession` as-is so it expands the * preset exactly like `agent_start.presetId` does). * * Reviewers spawn with role `executor` (no re-delegation), `worktree: false` * (they read the reviewed checkout's history; they never edit), and * `dedupe: false` (two lanes/runs with the same label are distinct * reviewers, never merged). */ interface DaemonReviewerHostDeps { registry: SessionsRegistry; sessionEvents: SessionEventBus; eventRing: EventRing; resolveAgentAdapter: AgentAdapterResolver; /** Extra spawn deps forwarded to `spawnAgentSession` (sandbox resolver, * catalog models, …). `registry`/`resolveAgentAdapter` always win. */ spawnDeps?: Partial; /** Preset lookups — injectable for tests; default to the real stores. */ getHarnessPreset?: (id: string) => Promise; getUserPreset?: (id: string) => Promise; /** Extra attempts for a lane whose turn ends in a transient error (socket * closed, 5xx, overloaded). Default {@link DEFAULT_LANE_RETRIES}; `0` * disables. Mirrors `config.review.laneRetries`. */ laneRetries?: number; /** Auth-profile lookup for the OpenRouter guard — injectable for tests. */ getAuthProfile?: (id: string) => Promise; /** Clock for the exhausted-wallet cooldowns — injectable for tests; * default {@link Date.now}. */ now?: () => number; /** Where the bounded verdict-recovery step runs (read per recovery, so a * config change applies without a restart). Unset / no presets ⇒ a lane * that ends without a valid verdict file is classified `unavailable` and * left incomplete — recovery never silently picks a model. */ getRecovery?: () => ReviewRecoveryConfig | undefined; } /** The recovery step's model selection. `presets` are reviewer presets (the * same harness/user presets lanes use, so the same OpenRouter guard and * wallet cooldowns apply); `model`, when set (the `review.recovery` model * role), overrides the model/profile each of them would run. */ interface ReviewRecoveryConfig { presets: string[]; model?: { model: string; profile?: string; }; } /** Resolve a lane's `preset` to spawn fields — harness preset first, then a * user preset. `undefined` when neither store knows the id. */ declare function resolveReviewerPreset(preset: string, lookups?: Pick): Promise | undefined>; declare function createDaemonReviewerHost(deps: DaemonReviewerHostDeps): ReviewerSessionHost; /** * MCP tools for the review primitive (`@agentproto/review`): * * review_run run a REVIEW.md binding over a git range → attestation * (ledger hit ⇒ the cached verdict, `cached: true`) * review_status poll a run started with `wait: false` * review_cancel cancel a running review (lane sessions are killed) * review_ledger list recorded attestations * review_export write one attestation out as a standalone JSON file * review_pr follow a recorded review to its GitHub PR (via `gh`): * link it, snapshot the PR's state/reviews/checks into the * entry's annotations, return the combined view * * Async pattern mirrors `workflow_start`/`workflow_status`: `review_run` * blocks by default (`wait: true`) — pass `wait: false` for long reviews and * poll `review_status` with the returned `runId`. * * Trust note: `review_run` executes the command checks the repo's own * REVIEW.md declares (`sh -c`), the same trust `workflow_run_file` extends to * a WORKFLOW.md's gate steps — not the `command_execute` allowlist, which * governs ad-hoc commands a remote caller composes. */ interface RegisterReviewToolsOptions { runner: ReviewRunner; /** The calling session (from `?callerSessionId=`) — agent-lane reviewer * sessions nest under it, and it is the default requester. */ callerSessionId?: string; /** `gh` runner for `review_pr` — injectable for tests. Default: the real * `gh` on the daemon's PATH. */ gh?: GhRunner; /** Resolve a session id to its subtree (itself + every session it * transitively spawned) — backs `review_ledger({requesterSessionId, * subtree: true})`. Omitted ⇒ `subtree` is ignored (scoped to the exact * id only), so a caller without sessions-registry access still works, * just without the subtree expansion. */ resolveSubtree?: (sessionId: string) => readonly string[]; } declare function registerReviewTools(server: McpServer, opts: RegisterReviewToolsOptions): void; /** * Pure session-config resolution (AIP-46 §Session config, presets and * fallback). Builds the effective config axis by axis from the layers, lowest * precedence first: * * manifest -> host -> definition -> harness preset -> preset (defaultFor, * then the named preset after its extends chain) -> request * * Each axis is replaced whole by the highest layer that sets it, except: * `options` merges key by key, `tags` union, and `modelPolicy` entries * accumulate (both apply). No I/O lives here, so the spawn path, the CLI and * the MCP tools all resolve a config through the same code. */ /** Every axis the resolver knows. Placement (sandbox, worktree) is out of * scope by contract. */ type SessionConfigAxis = "harness" | "model" | "effort" | "access" | "route" | "posture" | "contextProfile" | "cwd" | "skills" | "bundles" | "browser" | "turnRetry" | "options" | "tags" | "modelPolicy"; /** Where an axis came from. `preset:` is a named preset (or a member of * its `extends` chain); `preset-default:` is the `defaultFor` preset. */ type SessionConfigLayer = "manifest" | "host" | "definition" | "harness-preset" | `preset:${string}` | `preset-default:${string}` | "request"; interface SessionConfigAxes { harness?: string; model?: string; effort?: EffortLevel; access?: { profileRef?: string; }; route?: RouteSpec; posture?: Posture; contextProfile?: ContextProfile; cwd?: string; skills?: string[]; bundles?: string[]; browser?: SpawnBrowserMode; turnRetry?: TurnRetryInput; /** Harness-native options not covered by an axis; merged key by key. */ options?: Record; /** Preset discovery tags; unioned across layers. */ tags?: string[]; /** This implementation's form of the AIP-38 policy. */ modelPolicy?: ModelPolicy; } interface SessionConfigResolution { config: SessionConfigAxes; /** The layer that produced each axis. Absent = no layer set it. */ layers: Partial>; } /** The legacy harness default (`harness-presets.json`) projected onto the * session-config axes. It ranks below the `defaultFor` session preset. */ interface HarnessPresetOverlay { id: string; access?: { profileRef?: string; }; model?: string; turnRetry?: TurnRetryInput; } interface ResolveSessionConfigInput { /** Explicit spawn request axes: the highest layer. */ request?: SessionConfigAxes; /** The user's session preset store. */ presets?: readonly UserPreset[]; /** The harness slug the request resolves to. */ harness?: string; /** Named preset id. `request.presetId` is accepted for convenience. */ presetId?: string; manifest?: SessionConfigAxes; host?: SessionConfigAxes; definition?: SessionConfigAxes; harnessPreset?: HarnessPresetOverlay; } /** Typed resolution failure (missing extends target or a cycle). Save-time * validation in `user-presets.ts` also uses these codes. */ declare class SessionPresetResolutionError extends Error { readonly code: "unknown_extends" | "extends_cycle"; constructor(code: "unknown_extends" | "extends_cycle", message: string); } /** The preset followed by its `extends` ancestors, applied order: ancestors * first, left to right, then the preset itself. Throws on a missing target * or a cycle. */ declare function presetChain(id: string, presets: readonly UserPreset[]): UserPreset[]; /** The preset whose `defaultFor` names `harness`, if any. Save-time * validation keeps this unique; a hand-edited file resolves to the first. */ declare function defaultPresetFor(harness: string | undefined, presets: readonly UserPreset[]): UserPreset | undefined; /** A preset's flat fields with any nested `config` underneath them. Flat * fields win when both name the same axis (AIP-46 migration note). */ declare function presetAxes(preset: UserPreset): SessionConfigAxes; declare function resolveSessionConfig(input: ResolveSessionConfigInput): SessionConfigResolution; /** * Built-in custom-route registration (PR-5). * * `resolveLlmModelRoute` (`@agentproto/model-catalog/route-identity`) resolves * direct/openrouter/requesty/huggingface routes from generated tables, then * falls through to `resolveCustomRoute(route)` — the operator-configurable * extension point. Until something calls `registerCustomRoute`, that map is * empty, so a `/@llm-endpoint` ref resolves to `undefined` * (no baseUrl, no pricing) and the curated `@llm-endpoint` catalog rows carry * no transport to spawn against. * * This module activates the one built-in custom route the runtime ships: the * local `llm-endpoint` Anthropic-compatible proxy. It is NOT a private/operator * secret — the base URL, flavor, and key-env NAME are the same public facts the * `llm-endpoint` gateway preset already declares (`@agentproto/provider-presets`), * so we derive them from that single source of truth rather than re-hardcoding * (and re-drifting) `localhost:18090` here. * * Called once at daemon boot (`createGateway`, `index.ts`) BEFORE any catalog * or route consumer runs. Additive — direct and generated router routes are * untouched. Operator-declared routes from `~/.agentproto/routes.json` are * loaded after the built-in so they can deliberately override a shipped default. */ /** * Register every built-in custom route. Additive — direct and the generated * router routes (openrouter/requesty/huggingface) are untouched. * * BREAKING (major): this function is `async` — it now also loads and applies * operator-declared routes from `~/.agentproto/routes.json` before resolving. * It was previously synchronous (`() => void`); every caller, internal or * external, must `await` the returned promise or operator-route overrides * will silently not apply. */ declare function registerBuiltinRoutes(opts?: { llmEndpoint?: boolean; }): Promise; /** * Read-only per-provider model enumeration (AIP-45 launch-menu "+" picker, * phase 1) — the EXHAUSTIVE list of every model a single provider can serve. * * Deliberately separate from the spawn-facing `catalog_models` join * (`catalog-models.ts`). That tool answers "what is spawnable given this * host's adapters + auth profiles", and stays lean on purpose — it only * widens the curated (vendor, product) pairs through the router routes. This * tool answers the orthogonal, spawn-agnostic question "everything * offers", the full set the "+" picker browses before any adapter/profile is * chosen. Keeping the two apart is what lets the spawn catalog stay small * while the picker still sees the whole provider surface. * * Backed straight by the static catalog's `getModelsByProvider` * (`@agentproto/model-catalog`, `registry/index.ts`) — a pure query over the * kind-organized catalogs, so NO adapters, NO profiles, NO host wiring. * `getModelsByProvider` is itself router-aware: OpenRouter's route table is * spread into `LLM_PRICING_CATALOG` upstream (`llm/catalog.ts`), so an * `openrouter` query returns that full, large list with bare ids; Requesty, * HuggingFace and OpenCode's two hosted endpoints (`opencode-go`, * `opencode`) are NOT spread into that catalog — spreading a second router's * bare-id pricing there would repoint direct-vendor ids at router pricing * (`route-identity/index.ts`) — so `getModelsByProvider` instead folds their * generated route tables in directly. The emitted id is whatever the ref * formats to: `vendor/product@route` for the vendor-namespacing routers, and * the bare `opencode-go/glm-5.3` form for the OpenCode endpoints, whose route * IS the id's leading segment. Every provider enumerates through the same * path; the picker paginates client-side. NEVER log the rows: OpenRouter * alone is thousands. */ interface CatalogProviderModelsQuery { /** Provider / billing endpoint to enumerate (anthropic, openai, openrouter, * replicate, minimax, …). `route` is an accepted synonym — the picker * keys on a route id, an operator on an endpoint, and both mean the same * provider key here. An unknown or empty provider yields `models: []`. */ endpoint?: string; /** Synonym for `endpoint` (takes precedence when both are given). */ route?: string; } /** Per-1M-token USD pricing, mirroring `catalog-models.ts`'s `CatalogPricing`. */ interface CatalogProviderPricing { inPer1M: number; outPer1M: number; } /** One servable model in a provider's enumeration. */ interface CatalogProviderModel { /** The model id exactly as the caller would spawn/select it. */ id: string; /** llm / image / video / audio / voice. */ kind: ResolvedModel["kind"]; /** User-facing name where the catalog carries one (image/video/audio * `name`, voice `label`); falls back to the canonical id for LLM entries, * which have no display name in the catalog. */ label: string; /** The provider/route this model is served on — the LLM pricing provider * (== the queried provider) for LLM, the statically-pinned adapter * platform for the media kinds. `null` when the catalog carries none. */ route: string | null; /** Per-1M-token pricing for LLM models; `null` for the media kinds, whose * pricing is per-image/second/character rather than per token. */ pricing: CatalogProviderPricing | null; /** ISO date (`YYYY-MM-DD`) this model first appeared in the catalog, when * known — see `LLMPricing.addedAt` (`model-catalog/src/llm/catalog.ts`) * for the convention. `null` for media kinds and for LLM entries the sync * never stamped (hand-maintained rows). Lets a picker show a "new" badge. */ addedAt: string | null; } interface CatalogProviderModelsResponse { /** The provider key that was enumerated (echoed back, trimmed). */ provider: string; models: CatalogProviderModel[]; } /** * The pure per-provider enumeration behind the `catalog_provider_models` MCP * tool. No I/O, no host state — just a projection over the static catalog. * An unknown or empty provider returns an empty list rather than throwing: * "this provider serves nothing here" is a valid answer, not an error, so the * picker can query any provider key without a guard. */ declare function buildCatalogProviderModels(query?: CatalogProviderModelsQuery): CatalogProviderModelsResponse; /** * Observer seam for the browser tools (AIP-63 section 7, rules O1-O7). * * Optional and empty by default: with no observer registered every browser * tool behaves exactly as before. State lives at module scope because * `registerBrowserTools` re-runs on every stateless `/mcp` request (O3). * Observers are registered by the operator only (in process, or through * `loadBrowserObserverModule`), never by a tool call (O2). */ /** * Driver access an observer may use for its own captures (frames, page * probes). It exists only on `onAttach`, only for providers that implement the * owned-target `screenshot` and `evaluate` primitives, and only for observers * the operator registered (O2). It is not reachable from a tool call. */ interface BrowserCaptureHandle { screenshot(tabId?: string): Promise<{ data: string; format: "png" | "jpeg"; width?: number; height?: number; }>; /** Evaluates `expression` in the owned tab and returns its value. */ evaluate(expression: string, tabId?: string): Promise; } interface BrowserAttachEvent { sessionId: string; provider: string; instanceId: string; /** Present when the provider can screenshot and evaluate. */ capture?: BrowserCaptureHandle; } interface BrowserDetachEvent { sessionId: string; reason: "stop" | "crash" | "shutdown"; } interface BrowserCallEvent { callId: string; sessionId: string; /** Tool id without the `browser_` prefix, e.g. `click`. */ tool: string; tabId?: string; /** Locator-style arguments only. Value-bearing fields are removed before observers see them (O7). */ args: Record; } interface BrowserCallResultEvent extends BrowserCallEvent { durationMs: number; ok: boolean; error?: { code: string; }; } interface BrowserScreenshotImage { /** Base64, no `data:` prefix. */ data: string; mimeType: string; width?: number; height?: number; } interface BrowserObserver { onAttach?(event: BrowserAttachEvent): void | Promise; onDetach?(event: BrowserDetachEvent): void | Promise; beforeCall?(event: BrowserCallEvent): void | Promise; afterCall?(event: BrowserCallResultEvent): void | Promise; transformScreenshot?(ctx: { sessionId: string; tabId?: string; }, image: BrowserScreenshotImage): BrowserScreenshotImage | Promise; } interface BrowserObserverRegistration { /** When true, a failing or timed-out `transformScreenshot` fails the tool call instead of passing the original through (O6). */ requiredTransform?: boolean; } declare function registerBrowserObserver(id: string, observer: BrowserObserver, opts?: BrowserObserverRegistration): void; declare function unregisterBrowserObserver(id: string): void; declare function configureBrowserObservers(opts: { timeoutMs?: number; transformTimeoutMs?: number; log?: (msg: string) => void; }): void; interface BrowserObserverModuleApi { registerBrowserObserver: typeof registerBrowserObserver; log: (msg: string) => void; } /** * Load the operator-supplied observer module named by * `AGENTPROTO_BROWSER_OBSERVER_MODULE`. Trust rules: the path comes from the * daemon's own environment only, must be absolute, must resolve to a regular * file owned by the current user and not writable by group or others. The * module's default export is `(api) => void | Promise`. */ declare function loadBrowserObserverModule(modulePath: string, api: Pick): Promise; /** * Browser family on top of `@agentproto/provider-kit` — Phase 3 (lightest * adoption: no creds, no wizard, no catalog file). * * Provides the kit-compatible types (`BrowserAdapterHandle`) and the * `makeBrowserAdapterLister` factory that wraps the existing injected * `listBrowserAdapters` / `resolveBrowserAdapter` functions in a standard * `AdapterLister`. * * The resulting lister is passed as the `lister` option to * `registerBrowserTools`, which uses it to produce the same * `{ id, name, description, defaultPort }[]` JSON the legacy path emits * (output shape is unchanged — only the internal flow changes). * * Kit invariants honoured: * - `check()` is NEVER called by the lister (OQ-5). * - `BrowserAdapterInfo` carries no cred values (Appendix B). * - `requiresSetup = false` → status is always "ready" without a ledger. */ /** * Kit-compatible handle for a single in-process browser adapter. * `requiresSetup` is always `false` — browser adapters need no creds or * setup wizard, so the kit classifies them as "ready" on first resolution. */ interface BrowserAdapterHandle extends AdapterHandle { readonly requiresSetup: false; readonly defaultPort: number; } /** * Build a kit-compatible `AdapterLister` from the * existing injected browser adapter functions. The returned lister uses an * empty catalog and `discoverExtras` to surface the injected adapters, then * maps each resolved handle's fields into a `BrowserAdapterInfo` descriptor. * * The caller should pass the result as the `lister` option to * `registerBrowserTools`, which extracts `AdapterEntry.info` to preserve the * existing tool response shape. */ declare function makeBrowserAdapterLister(opts: { listBrowserAdapters: BrowserAdapterLister; resolveBrowserAdapter?: BrowserAdapterResolver; }): AdapterLister; /** * The one built-in adapter table the daemon, the HTTP route and the CLI share: * the `@agentproto/adapter-browser` facade (kit providers camofox, bureau, * chromium behind the legacy handle shape). Hosts that want a different set * still inject their own `resolveBrowserAdapter` / `listBrowserAdapters`. */ declare function defaultBrowserAdapterResolution(): { resolveBrowserAdapter: BrowserAdapterResolver; listBrowserAdapters: BrowserAdapterLister; }; /** Ids of the built-in adapters, for "not found, available: ..." messages. */ declare function defaultBrowserAdapterIds(): string[]; /** * AIP-36 `sandbox attach` — Phase 1: CONNECT to an already-existing sandbox * (Box/e2b/local) without tearing it down. * * Boot-and-drive (`session-spawn.ts`'s `bootSandboxAgentSession`) boots a * box, spawns an adapter ON it, and owns its lifecycle end-to-end. Attach is * a different primitive entirely: it's the "rendezvous with my sandbox" * verb — resolve the provider, resume the box, ensure its daemon is healthy * and reachably exposed, and hand back a durable connection descriptor any * MCP client (local Claude, a GitHub Action, another ephemeral sandbox) can * use to reach it. It never calls `stop()`/`pause()` — the sandbox it * attaches to stays running and addressable exactly as it was. * * Boot-and-drive's URL is fine to leave ungated: it's ephemeral, * provider-owned, and only this process ever learns it. Attach's URL is the * opposite — a PERSISTENT address handed to a caller who may be a different * process entirely — so it MUST be token-gated. `SandboxBootOpts.expose: * "private"` (see `@agentproto/sandbox`) is how attach asks a provider's * `connect()` for that; a provider that can't honour it (or a sandbox that * wasn't set up to support it) simply doesn't return a token, and this * module fails closed rather than emit an ungated URL. */ /** * Durable connection descriptor for an attached sandbox — everything a * client needs to reach its agentproto daemon directly, without going * through this process again. */ interface SandboxConnectionDescriptor { /** Sandbox provider slug attached to (e.g. "box", "e2b"). */ provider: string; /** Provider-assigned sandbox id. */ sandboxId: string; /** The sandbox's `/mcp` endpoint. */ mcpUrl: string; /** Opaque secret gating `mcpUrl` — see module docs on why attach always * requires one. How to PRESENT it is provider-specific (`authHeaders`): * Box gates on a `Cookie: _port_auth=`, not a bearer. */ token?: string; /** Exact HTTP header(s) a client must send to reach `mcpUrl` — carried * through from `BootedSandbox.authHeaders`. Absent for a token-only * provider, in which case clients (and `buildMcpConfigSnippet`) fall back * to `Authorization: Bearer `. */ authHeaders?: Record; /** The Origin the daemon's own `--allow-origin` allowlist already trusts * (derived from `mcpUrl`'s own origin) — informational, for a caller * that wants to drive the sandbox from a browser-hosted tool. A * non-browser MCP client (no `Origin` header sent) doesn't need this at * all; the daemon only gates requests that DO carry an Origin header. */ allowOrigin: string; /** Whether `AttachSandboxOpts.keepAlive` was requested — informational, * echoing back that the sandbox was (re-)pinned no-auto-stop for the * always-on rendezvous model (provider support permitting). */ keepAlive: boolean; } interface AttachSandboxOpts { /** Sandbox provider slug from `list_sandbox_providers` (e.g. "box", "e2b"). */ provider: string; /** Provider-assigned sandbox id to attach to. */ sandboxId: string; /** Provider-specific `SandboxSpec.config` overrides (e.g. box's `{ port, * workspace }`) — same shape `agent_start.sandbox`'s inline spec takes. */ config?: Record; /** * Keep the attached sandbox awake indefinitely for the always-on * rendezvous model, instead of leaving it subject to the provider's * default idle/TTL auto-stop. Forwarded to `SandboxProvider.connect` as * `SandboxBootOpts.keepAlive` — a provider that supports an explicit * no-auto-stop assertion (e.g. Box's `ttlSeconds: null`) (re-)applies it * defensively; providers with no such concept ignore it. */ keepAlive?: boolean; /** Injectable resolver — defaults to the same creds-backed resolver * `list_sandbox_providers`/`setup_sandbox_provider` use, reading * `~/.agentproto/sandbox-creds/.json`. Override for tests. */ resolveSandboxProvider?: SandboxProviderResolver; } type AttachSandboxResult = { ok: true; descriptor: SandboxConnectionDescriptor; } | { ok: false; code: "sandbox_provider_not_found" | "sandbox_no_connect" | "sandbox_attach_failed" | "sandbox_attach_ungated"; message: string; }; /** * Resolve `opts.provider`, connect (never boot) to `opts.sandboxId` * requesting a private, token-gated exposure, and return a durable * descriptor. Never tears down or pauses the sandbox — on any failure past * the resolve step, the sandbox is left exactly as `connect()` left it (the * providers' own `connect()` implementations are responsible for not * leaking partial state; attach adds no teardown of its own). */ declare function attachSandbox(opts: AttachSandboxOpts): Promise; /** Paste-ready `.mcp.json` (Claude Code project-scope MCP config) entry for * a connection descriptor — http transport, with the provider's own auth * header(s) when gated (e.g. Box's `Cookie: _port_auth=…`), falling back to * `Authorization: Bearer ` for a token-only provider. */ declare function buildMcpConfigSnippet(descriptor: SandboxConnectionDescriptor): { mcpServers: Record; }>; }; interface RegisterSandboxAttachToolOptions { /** Same injection seam as `AttachSandboxOpts.resolveSandboxProvider` — * pass the daemon's shared resolver so this tool sees the same provider * set as `list_sandbox_providers`/`agent_start.sandbox`. */ resolveSandboxProvider?: SandboxProviderResolver; } /** Register the `sandbox_attach` MCP tool. */ declare function registerSandboxAttachTool(server: McpServer, opts?: RegisterSandboxAttachToolOptions): void; /** * `sandbox egress-health` - the read side of the egress IP health ledger, plus * the on-demand re-probe. The read lists the provider's pool slots, their * public addresses and the active cooldowns; the probe boots one box per slot, * runs the `model-answers` preflight from that address, and clears or sets the * cooldown from the verdict. There is deliberately no scheduler: a probe boots * real boxes, so it runs when an operator (or a placement ladder) asks. */ declare const DEFAULT_EGRESS_HEALTH_PROVIDER = "computer"; interface EgressHealthSlotView { slot: string; publicIp: string; /** Boxes currently using the slot, when the provider reports it. */ computers?: number; /** Active cooldowns on this slot's address, soonest-to-expire first. */ cooling: EgressCooldownEntry[]; } type EgressHealthReport = { ok: true; provider: string; /** Set when the read was narrowed to one model. */ model?: string; slots: EgressHealthSlotView[]; /** Every active cooldown, including addresses no longer in the pool. */ cooldowns: EgressCooldownEntry[]; } | { ok: false; code: "egress_provider_not_found" | "egress_pool_unsupported" | "egress_pool_failed"; message: string; }; interface EgressHealthDeps { resolveSandboxProvider?: SandboxProviderResolver; ledger?: EgressHealthLedger; } /** The pool's slots and addresses with the active cooldowns folded in. */ declare function readEgressHealth(opts: { provider?: string; model?: string; }, deps?: EgressHealthDeps): Promise; type EgressProbeSlotResult = { slot: string; publicIp?: string; verdict: "ok" | "ko" | "unknown"; detail: string; cleared?: number; cooldown?: EgressCooldownEntry; } | { slot: string; verdict: "error"; detail: string; }; type EgressProbeReport = { ok: true; provider: string; model: string; adapter: string; results: EgressProbeSlotResult[]; } | Extract; interface EgressProbeDeps extends EgressHealthDeps { preflightRegistry?: PreflightRegistry; /** Per-slot probe budget, ms. Defaults to the probe's own budget. */ timeoutMs?: number; } /** * Boot one box per slot, run `model-answers` for `model` from it, then stop * the box. A `ko` that is a usage or rate limit sets the cooldown; an `ok` * clears every cooldown on that address for the model; `unknown` and boot * errors change nothing. Every slot's box boots in parallel: each is a real * boot, so probing sequentially made a full sweep take minutes. */ declare function probeEgressSlots(opts: { provider?: string; model: string; adapter?: string; }, deps?: EgressProbeDeps): Promise; interface RegisterSandboxEgressHealthToolOptions { resolveSandboxProvider?: SandboxProviderResolver; } /** Register the read-only `sandbox_egress_health` MCP tool. */ declare function registerSandboxEgressHealthTool(server: McpServer, opts?: RegisterSandboxEgressHealthToolOptions): void; /** * Spawn-time application of a profile's pinned sub-account (org / workspace / * project). The runtime never imports a provider: it asks the registry in * `@agentproto/auth` for the one that owns the profile's account and maps the * provider's {@link SubaccountResolution} onto `resolveAuthSpec` inputs. */ interface ResolvedProfileSubaccount { pin: SubaccountPin; /** The credential to inject: the provider's own, else the profile's stored one. */ credential?: string; /** Spread straight into `resolveAuthSpec`'s input. */ authInputs: { credentialEnvOverride?: string; apiKeyCredentialSource?: CredentialSource; extraEnv?: Record; isolateDataHome?: boolean; }; } /** * `sandbox_exec.envProfiles` — put an auth profile's credential into the * command's env WITHOUT the caller ever holding the value. * * Security rule (same as the `agent_start({sandbox})` keychain fallback in * `sandbox-secret-resolver.ts`): the caller names an auth PROFILE ID, which is * operator-configured and daemon-owned. The keychain ref always comes from the * profile record — a caller-supplied ref is not accepted anywhere, since it * would read any keychain slot. The daemon-env broker is deliberately NOT * layered in (`base` resolves to null): an env NAME the caller picks must never * select a daemon env var to exfiltrate. * * Returned values are for the provider's exec env and the redactor ONLY — they * are never logged, echoed in a result, or placed in argv. */ interface EnvProfilesDeps { getAuthProfile?: (id: string) => Promise; /** Keychain backend; defaults to the OS keychain. Injectable for tests. */ secretStore?: Pick; resolveSubaccount?: (profile: AuthProfile, ctx: { credential?: string; }) => Promise; /** Account slot map for a `slot:` profile id. Defaults to config.json. */ loadAccountSlots?: () => Promise; } /** * AIP-36 `sandbox exec` — run ONE command inside a sandbox box (typically a * test gate) and get the exit code + captured stdout/stderr back to the * HOST session, without moving the whole agent session into the box. * * Facet of the same story as the two other box paths. Boot-and-drive * (`session-spawn.ts`'s `bootSandboxAgentSession`) spawns the ENTIRE agent * in the box; `sandbox attach` (`sandbox-attach.ts`) hands out a durable * connection descriptor for driving the box's own daemon directly. Exec is * the lighter primitive in between: the host agent stays where it is and * calls out for a single command run (e.g. run the test suite in the box, * get its output into the host conversation). * * The exec capability itself is OPTIONAL on `BootedSandbox` (`exec?`, * `@agentproto/sandbox`) — providers shell into their own thing (e2b: * `sandbox.commands.run` + `CommandExitError`; other providers have no * implemented seam yet) and are expected to return a non-zero exit as a * RESULT, not a throw. This module is the tool layer only: resolve the * provider, procure the box handle (attach when `sandboxId` is given, an * EPHEMERAL box otherwise — always stopped at the end of the call, success * or failure, so a sandboxId-less exec never leaks a live box), run, then * truncate the streams for display before returning. */ /** Per-stream display cap, in characters. Anything longer is cut to this * many leading chars with a `…[truncated]` marker (the cap is generous — * a green gate's stdout or a failing test's full report fits; a runaway * `cat` of a binary database does not, and that's exactly the case the * marker exists for). */ declare const SANDBOX_EXEC_STREAM_MAX_CHARS = 20000; /** Command text ceiling, bytes. E2B rejects a ~30 KB inline command with an opaque * `[invalid_argument] error starting process`; 16 KB stays well under that. */ declare const SANDBOX_EXEC_MAX_COMMAND_BYTES: number; /** Total env ceiling (names + values), bytes — same conservative reasoning. */ declare const SANDBOX_EXEC_MAX_ENV_BYTES: number; /** One file written into the box before the command runs. */ interface SandboxExecFile { /** Absolute path INSIDE the box. Parent directories are created. */ path: string; /** File content, interpreted per `encoding`. */ content: string; /** `utf8` (default) or `base64` for binary content. */ encoding?: "utf8" | "base64"; } /** Options for `execSandboxCommand` — the `sandbox_exec` MCP tool's input. */ interface SandboxExecCommandChoices { /** Sandbox provider slug from `list_sandbox_providers` (e.g. "e2b", "box"). */ provider: string; /** Shell command to run inside the box (provider's SDK shells it verbatim). */ command: string; /** * Provider-assigned sandbox id to run against. REQUIRED-absent means * EPHEMERAL: boot a fresh box, run the command, then ALWAYS stop it * (success, non-zero exit, or failure) — an ephemeral exec never leaks. * With an id, the box is attached to and left exactly as found. */ sandboxId?: string; /** Absolute path INSIDE the box to run the command from (e.g. e2b's * `/home/user`). Never a HOST path — a host path can never resolve in * the box. */ cwd?: string; /** Extra env vars for THIS command only. Literal values: anything the caller * puts here is visible in its own context — prefer `envProfiles` for secrets. */ env?: Record; /** * `ENV_NAME → auth profile id`: the daemon reads that profile's credential * (keychain, or its sub-account provider) and sets it as `ENV_NAME` in the * command's env, so the caller never holds the value. The caller names a * PROFILE, never a keychain ref. Same var in `env` too → rejected. */ envProfiles?: Record; /** Files written into the box before the command runs (instead of inlining * a large script in `command`). */ files?: SandboxExecFile[]; /** Per-command timeout, ms. Provider-dependent expiry error. */ timeoutMs?: number; } /** Successful exec's display shape — truncation is THIS layer's job. */ interface SandboxExecOutput { exitCode: number; stdout: string; stderr: string; durationMs: number; sandboxId: string; stdoutTruncated: boolean; stderrTruncated: boolean; } type SandboxExecResult = { ok: true; result: SandboxExecOutput; } | { ok: false; code: "sandbox_provider_not_found" | "sandbox_no_exec" | "sandbox_exec_failed" | "sandbox_no_connect" | "sandbox_exec_invalid_input" | "sandbox_exec_env_profile" | "sandbox_exec_too_large" | "sandbox_no_write_file"; message: string; }; interface ExecSandboxCommandOptions extends EnvProfilesDeps { /** Injectable resolver — defaults to the same creds-backed resolver * `sandbox_attach` uses. Override for tests. */ resolveSandboxProvider?: SandboxProviderResolver; } /** * Run one command in a box. Resolution + procurement is the same shape as * `attachSandbox` (same resolver, env: {}); procurement differs on * `sandboxId` (attach — box left as found) vs not (boot — box ALWAYS * stopped, even on a failed exec or a missing-exec capability, since the * ephemeral box exists for nobody else). Teardown before error returns for * the ephemeral path, never after — stop() itself is best-effort there. */ declare function execSandboxCommand(opts: SandboxExecCommandChoices, deps?: ExecSandboxCommandOptions): Promise; interface RegisterSandboxExecToolOptions { /** Same injection seam as `ExecSandboxCommandOptions.resolveSandboxProvider` * — pass the daemon's shared resolver so this tool sees the same provider * set as `list_sandbox_providers` / `agent_start.sandbox`. */ resolveSandboxProvider?: SandboxProviderResolver; /** Test seams for `envProfiles` resolution (profile lookup, keychain, sub-account). */ envProfiles?: EnvProfilesDeps; } /** Register the `sandbox_exec` MCP tool. */ declare function registerSandboxExecTool(server: McpServer, opts?: RegisterSandboxExecToolOptions): void; /** * The sandbox ledger — `~/.agentproto/sandboxes.json`. * * The daemon KNOWS when it boots, pauses, reconnects to, or stops a sandbox * box (AIP-36 boot-and-drive, `session-spawn.ts`'s `bootSandboxAgentSession` * and the lifecycle teardown inside `SandboxAgentSessionProxy.close()`), but * it writes none of it down: finding a still-live sandboxId meant grepping * session descriptors for a `remote: true` stamp. This module is the * navigation half — one durable record per sandboxId: * * { sandboxId, provider, label?, state, cwd?, originSessionId?, * createdAt, updatedAt, expiresAt? } * * State machine: "booted" (fresh boot) → "connected" (reuse/attach) → * "paused" (proxy close() chose the pause teardown) | "stopped" (kill or * expiry). `expiresAt` is stamped at boot when the spec's lifecycle policy * carries a known idle window (`lifecycle.pause_after_idle` → * `SandboxLifecyclePolicy.pauseAfterIdleMs`) — the one expiry the daemon * actually knows about at boot time; a provider-side TTL the daemon never * sees is deliberately NOT guessed at here. * * Writes are ALWAYS best-effort: every helper swallows its own failures and * returns without throwing. A ledger error must never fail a spawn, a * pause, or a teardown — the ledger is an index over reality, never a * participant in it. * * Persistence style matches the daemon's other JSON stores * (`workspace-buckets.ts`, `saveWorkspacesConfig`): serialize → write to a * per-process-unique tmp file → rename over the target. A concurrent reader * never sees half a JSON object, and two in-flight writers never share a * tmp path (the pid-only suffix is not unique within one process — see the * 2026-08-14 registry-wipe write-up in `workspace-buckets.ts`). */ /** Lifecycle states a ledger row can carry. `"gone"` is stamped when the * PROVIDER answers the box no longer exists (liveness probe 404 / a * reconnect failing with the provider's not-found error) — distinct from * `"stopped"` (WE tore it down) and from `"paused"` (the last thing WE * did, which a vanished box makes a lie). */ type SandboxLedgerState = "booted" | "paused" | "connected" | "stopped" | "gone"; interface SandboxLedgerEntry { sandboxId: string; provider: string; state: SandboxLedgerState; createdAt: string; updatedAt: string; label?: string; cwd?: string; /** The workspace whose git token this box was booted with * (`AGENTPROTO_GIT_TOKEN` sits in the box env for the box's whole life). A * `reuse` from any other workspace is refused so it cannot inherit it. */ gitTokenWorkspace?: string; /** The HOST session id that first booted / last reconnected to the box. */ originSessionId?: string; /** Every session CURRENTLY attached to this box (AIP-36 shared-box * amendment). Written by `recordSandboxBoot` / `recordSandboxOrigin`, * dropped per-session by `recordSessionDetach`. The refcount source of * truth — on disk, so it survives a daemon restart. * * Known follow-up (scoped, not fixed in this PR): a session that dies * WITHOUT going through `close()` (daemon SIGKILL / crash) leaves a * stale attaché here — the box's real last session never triggers the * teardown and `sandbox gc` conservatively skips the box forever. A * restart-time sweep reconciling `attachedSessions` against the live * session registry should prune dead ids. */ attachedSessions?: string[]; /** ISO instant the box is expected to idle-expire — stamped only when the * boot knew a window (`lifecycle.pause_after_idle`). */ expiresAt?: string; /** Set when the box was torn down because its session was idle-reaped * (`daemon.sandboxIdleReapAfterMs`) rather than closed by a user: the ISO * instant, how long the session had been idle, and the host session id. * Cleared by the next boot/reconnect of the same sandboxId. */ reapedAt?: string; reapedIdleMs?: number; reapedSessionId?: string; /** Last PROVIDER liveness probe verdict (`SandboxProvider.probe`) — the * only signal that distinguishes box death from session death. Absent * when never probed (or the provider can't probe): the ledger's `state` * alone is NOT trustworthy — a dead box looks paused until probed. */ sandboxAlive?: boolean; /** ISO instant `sandboxAlive` was computed. */ sandboxCheckedAt?: string; } /** `~/.agentproto/sandboxes.json`. `AGENTPROTO_SANDBOX_LEDGER` overrides * the path (tests, and a caller that wants a workspace-scoped ledger). */ declare const sandboxLedgerPath: () => string; /** Rows currently on disk. `[]` for a missing/corrupt file — the same * "degrade to nothing rather than throw" contract as every other store * reader in this daemon. Never throws. */ declare function readSandboxLedger(path?: string): SandboxLedgerEntry[]; /** * Upsert (dedup by `sandboxId`) and persist. Sync + best-effort: the * lifecycle hooks that call this run inside teardown/finally paths where * Node won't await, and a failure here is a lost index row, never a lost * box. Swallows every error. */ declare function upsertSandboxLedger(entry: SandboxLedgerEntry, path?: string): void; /** Remove a row by sandboxId. Returns whether a row was actually dropped * (read from the PRE-call disk state). Never throws. */ declare function removeSandboxLedgerEntry(sandboxId: string, path?: string): boolean; /** * Stamp a boot or reconnect into the ledger — the spawn path's hook. * `state` is "booted" for a fresh boot, "connected" for a reuse/attach. * Best-effort: never throws, whatever happens. */ declare function recordSandboxBoot(opts: { sandboxId: string; provider: string; state: "booted" | "connected"; label?: string; cwd?: string; originSessionId?: string; expiresAt?: string; gitTokenWorkspace?: string; /** The host session attaching to the box — appended to the shared-box * refcount (`attachedSessions`) in the same write. */ sessionId?: string; path?: string; }): void; /** Stamp a state transition ("paused"/"stopped"/"gone") for an existing row. * Best-effort: never throws. * * AIP-36 shared-box semantics: `attachedSessions` is a REFCOUNT, so a * generic state stamp must not erase it under the survivors' feet. By * default the stamp CLEARS the list (safe default: every stop is terminal * and a stale attaché must not make `sandbox gc` skip the box forever); * call with `keepAttachedSessions` only when the box physically kept * running for other sessions (e.g. a reuse attach whose failed boot left * the box PAUSED for the survivors — they re-attach through `reuse`). */ declare function recordSandboxState(sandboxId: string, state: "paused" | "stopped" | "gone", path?: string, keepAttachedSessions?: boolean): void; /** Stamp a PROVIDER liveness verdict onto an existing row — `sandboxAlive` * + `sandboxCheckedAt`, and when the verdict is death ALSO flip the row to * `"gone"` (the state alone was never evidence of death; the probe is). * Best-effort: never throws. */ declare function recordSandboxLiveness(sandboxId: string, alive: boolean, path?: string): void; /** Backfill `originSessionId` once the HOST registry has minted the session * id the box was spawned for (the boot hook runs before that id exists). * Best-effort: never throws. */ declare function recordSandboxOrigin(sandboxId: string, originSessionId: string, path?: string): void; type ReuseResolution = { kind: "resolved"; sandboxId: string; entry: SandboxLedgerEntry; } | { kind: "ambiguous"; candidates: SandboxLedgerEntry[]; } | { kind: "unresolved"; }; /** * `reuse: ""` resolution against the ledger (PLAN-D1 §3). * * A reuse token that exactly matches a row's `label`, or is a PREFIX of * exactly one row's `sandboxId`, resolves to that row's sandboxId. Several * matches → `ambiguous` (the caller must disambiguate — the error it * renders lists the candidates). No match at all → `unresolved`, and the * spawn path passes the token through unchanged so the provider's own * `connect()` failure surfaces exactly as it did before this module * existed. */ declare function resolveReuseFromLedger(reuse: string, entries: readonly SandboxLedgerEntry[]): ReuseResolution; /** Record one session DETACHING from a box (AIP-36 shared-box teardown: * teardown = detach, the box survives as long as others remain). Drops * `sessionId` from `attachedSessions`; no-op for a row this session isn't * on. Returns the sessions STILL attached (excluding `sessionId`). * Best-effort: never throws. */ declare function recordSessionDetach(sandboxId: string, sessionId: string, path?: string): string[]; /** * `agentproto sandbox gc` — the orphan-box reaper. * * A sandboxed spawn that FAILS after the box was created (boot failure * after `provider.boot` returned, a reconnect whose daemon MCP connect * failed, the box's own `agent_start` rejecting, …) leaves a live box on * its provider with no owning session. So does a session that then died * (error/killed/exited) while its box idled to a PAUSED state on e2b — * and paused boxes still bill. * * The spawn path now reaps failed boots itself (see * `session-spawn.ts`), but boxes orphaned before that fix exist in the * ledger. The gc selects ledger entries whose ORIGIN SESSION ended in a * terminal-failure state (`error` / `killed` / `exited`), and — with * `apply` — tears the box down on its provider (kill by default; `pause` * keeps it attachable for boxes you still want) and stamps the ledger. * Dry run by default. */ /** Host session statuses after which a session can never use its box again. */ declare const DEAD_SESSION_STATUSES: ReadonlySet; /** One ledger row selected for gc, with the observed origin-session status. */ interface SandboxGcCandidate { entry: SandboxLedgerEntry; sessionStatus: string; } /** The lineage slice the gc needs to find a LIVE successor of an origin * session. Only the predecessor links are read: inverting them covers the * resume/continue/handover chain, and an inverse link (`continuedTo` / * `succeededBy`) can go stale in the other direction. `sandboxTeardown` is * the descriptor's recorded teardown mode; a box whose origin (or the live * successor/attache that last held it) asked for `pause` is paused rather * than deleted. `resumable` stays advisory only: it is true for nearly every * dead agent-cli row, so it must never drive the pause decision. */ interface SandboxGcSessionLineage { resumedFrom?: string; continuedFrom?: string; succeeds?: string; sandboxTeardown?: "kill" | "pause"; resumable?: boolean; } /** * Whether the gc must PAUSE (never delete) a box. Reads the recorded teardown * of the origin descriptor, of every attached session, and of every successor * reachable from the origin through the resume/continue chain. Any `pause` * wins: pausing is recoverable, deleting is not. */ declare function sandboxGcShouldPause(entry: SandboxLedgerEntry, lineage: ReadonlyMap): boolean; /** * Select ledger entries whose origin session is error/killed/exited. * Rows already marked "stopped" are skipped (nothing left to tear down); * rows with no `originSessionId` are skipped too — their owning session * is unknown, so "orphan" cannot be established from this surface. * * `sessionLineage` is optional so callers that only have statuses keep * working; when supplied, the resume/continue chain behind the origin is * walked as well (the 2026-10-23 incident: a `session_restart` resumed a * dead origin's box under a NEW id, so the ledger origin was dead while a * live session still used the box). */ declare function collectGcCandidates(entries: readonly SandboxLedgerEntry[], sessionStatuses: ReadonlyMap, sessionLineage?: ReadonlyMap, absent?: SandboxGcAbsentSessions): SandboxGcCandidate[]; /** * Opt-in: treat a session the registry has NO row for as dead. A session that * was pruned, deleted or never persisted can never close its handle, so the * box it held (and the session slot the provider counts for it) would stay * reserved forever; the default keeps the conservative reading (unknown = * alive) for callers whose status source may not list every row. `graceMs` * (default 10 min) spares a ledger row touched recently: a box booted a * moment ago may be attached by a session the registry has not recorded yet. */ interface SandboxGcAbsentSessions { absentSessionsAreDead?: boolean; graceMs?: number; now?: number; } /** Provider resolution + ledger targeting for the reaper — injectable so * tests can hand a fake provider and a tmp ledger path. */ interface SandboxGcReapDeps { resolveProvider: (slug: string) => Promise; ledgerPath?: string; } /** The slice of `SandboxProviderHandle` the reaper needs. */ interface SandboxGcProviderHandle { provider: { connect?(sandboxId: string, spec: { provider: string; config: Record; }, opts: { env: Record; }): Promise<{ sandboxId: string; stop(): Promise; pause?(): Promise; }>; /** Control-plane destroy WITHOUT connecting — see `SandboxProvider. * remove`. Preferred over `connect()` + `stop()`: connecting to a * suspended computer RESUMES it first (RAM requirement), exactly the * capacity-need that made `sandbox rm`/gc fail on an exhausted host. * The gc runs AFTER its attaché candidate check, so it is the only * caller allowed to `force` past a shared-box 409. Optional: providers * without it fall back to the connect path. */ remove?(sandboxId: string, opts?: { force?: boolean; }): Promise; /** Release one dead session's provider-side slot without connecting * (see `SandboxProvider.releaseSession`). */ releaseSession?(sandboxId: string, holder: string): Promise; /** Control-plane enumeration of the provider's boxes: the orphan-box * gc reads it to find boxes no live session holds (see * `sandbox-orphan-gc.ts`). */ listBoxes?(): Promise; }; } /** Error-message shapes meaning "the box is already gone" — an idempotent * successful gc, never a failure. The bare `not found` spelling is NOT * matched on its own: an unrelated error like `provider "x" not found` * must never be stamped as a successful reap. Prefer the typed sentinel * (`SandboxBoxGoneError`, via {@link isGoneError}); the message regex is * the fallback for providers without one. */ declare const GONE_RE: RegExp; /** Structural check — true when `err` means "the box is gone" (the typed * sentinel or any Error carrying its name). */ declare function isGoneError(err: unknown): boolean; type SandboxGcReapResult = { ok: true; action: "paused" | "stopped"; } | { ok: false; error: string; }; /** * Tear one ledger entry's box down on its provider and stamp the ledger. * `pause` keeps the box (pausing when the provider supports it, falling * back to a kill otherwise); the default kills. A connect failure that * reads as "box doesn't exist anymore" still stamps the row "stopped" so * the candidate stops re-appearing; other failures leave the row alone * (transient network must not mark a live box as reaped). */ declare function reapGcEntry(entry: SandboxLedgerEntry, opts: { pause?: boolean; } & SandboxGcReapDeps): Promise; /** States that still name a box the gc might act on. */ declare const GC_REAPABLE_STATES: readonly SandboxLedgerState[]; /** How long the periodic pass keeps a paused dead-session row before reaping * it anyway. Thirty minutes is long enough for an operator to notice and * reconnect, short enough that a forgotten paused box cannot hold a host's * memory budget all night (2026-10-29: a paused box held 12 GB and every new * create was refused until it vanished an hour later). */ declare const DEFAULT_PAUSED_BOX_MAX_AGE_MS: number; /** Parse the `AGENTPROTO_SANDBOX_GC_PAUSED_MAX_AGE_MS` env knob. Unset or * non-numeric falls back to {@link DEFAULT_PAUSED_BOX_MAX_AGE_MS}; an * explicit `0` reaps every paused row on the next pass. */ declare function parsePausedBoxMaxAge(raw: string | undefined, fallback?: number): number; /** Sources a session-status READ for the periodic gc. Injected so the * daemon pass reads its OWN registry and the CLI keeps its HTTP one. */ interface SandboxGcReadDeps { fetchSessionStatuses: () => Promise> | Map; /** Predecessor lineage + resume eligibility per session. Optional: without * it the pass falls back to the attaché filter only. */ fetchSessionLineage?: () => Promise> | ReadonlyMap; resolveProvider: (slug: string) => Promise; ledgerPath?: string; /** The daemon pass reads its own full registry, so a session it has no row * for is gone for good (see {@link SandboxGcAbsentSessions}). Leave unset * for a status source that may omit live rows. */ absentSessionsAreDead?: boolean; /** How long a paused row may sit before the pass reaps it regardless of a * `pause` teardown. A paused box holds provider capacity (RAM snapshot) and * is not attachable by a new spawn once its session is gone, so "kept * paused forever" is a leak. Defaults to * {@link DEFAULT_PAUSED_BOX_MAX_AGE_MS}; `0` reaps every paused row. */ pausedMaxAgeMs?: number; } /** Tally of one automatic gc pass. */ interface SandboxGcPassSummary { ran: boolean; candidates: number; stopped: number; paused: number; /** Rows already paused on the ledger: skipped with no provider call. */ kept: number; failures: number; /** Dead sessions whose slot on a box that stays in use was released. * Present only when at least one was. */ released?: number; } /** * One automatic `sandbox gc` pass: read the session statuses, select the * ledger rows whose origin session is DEAD (error/killed/exited — * {@link collectGcCandidates}) and reap them with {@link reapGcEntry}. * Unlike the CLI's dry-run-first command, the daemon pass applies by * default (the operator chose to run a daemon; orphan boxes bill while * nobody looks at them), but a failure is always logged, never thrown. */ declare function runSandboxGcPass(deps: SandboxGcReadDeps, log?: (line: string) => void): Promise; /** * The daemon's PERIODIC automatic gc for dead-session boxes. Every * `intervalMs` (default {@link DEFAULT_SANDBOX_GC_INTERVAL_MS}) the pass * reaps ledger boxes whose origin session is gone — a paused computer * holding a RAM snapshot, a surviving-but-billing e2b box whose session * crashed and whose owner never ran `sandbox gc --apply`. * `.unref()` — the timer never keeps the process alive. Returns a handle * whose `stop()` kills the timer (the gateway's `stop()` calls it). */ declare const DEFAULT_SANDBOX_GC_INTERVAL_MS: number; interface SandboxGcTimer { stop(): void; } declare function startSandboxGcTimer(deps: SandboxGcReadDeps & { intervalMs?: number; /** Run one pass this long after start, so sessions a dead daemon left * attached are released on the first boot instead of up to an interval * later. Unset: first pass after `intervalMs`, as before. */ initialDelayMs?: number; log?: (line: string) => void; }): SandboxGcTimer; /** * ORPHAN-BOX gc for the PROVIDER control plane. * * `sandbox-gc.ts` reaps boxes the daemon's own ledger knows about: a row * whose origin session died. That misses a whole class of boxes - the ones * the PROVIDER still holds while the daemon has no row for them at all: * * - a computer the controller created for a session that died before the * ledger row was written (or after the daemon restarted and lost it), * - a box a daemon from another host created on the SHARED controller, * - a box whose ledger row was removed by hand. * * Such a box is invisible to the ledger gc but not to the provider: the * controller keeps it (and its RAM - a suspended computer holds a snapshot) * and keeps counting its session slots, so every later launch can fail with * "host capacity" while the stale boxes sit there. * * This module is the provider-side half of the gc: * * 1. LIST the provider's boxes (`SandboxProvider.listBoxes`). * 2. Select the ORPHANS: boxes the daemon's sandbox registry does not * know AND that no live daemon session holds. A box held by a live * session is NEVER a candidate, whatever else is true of it. * 3. DELETE them with `remove(id, { force: true })` - forced, because a * stale controller-side session slot would otherwise make the * controller refuse the destroy with a 409. * * Every provider is scanned INDEPENDENTLY: a controller that errors (down, * unauthorized, mid-deploy) is reported as an error for THAT provider and * never stops the gc of the others. */ /** Grace window a box must age out of before it can be an orphan * candidate: a box younger than this may still be booting, attaching, or * simply not yet reported by the daemon's ledger. 15 minutes. */ declare const ORPHAN_GRACE_MS: number; /** One box the provider still holds that no live session references. */ interface SandboxOrphanCandidate { /** Provider slug the box belongs to ("computer", …). */ provider: string; /** Provider-assigned box id. */ boxId: string; /** Provider-reported state ("running", "stopped", …) when known. */ state: string; /** Why this box is an orphan - always says what was checked. */ reason: string; /** Session slots the provider still counts for the box, when known. */ sessions?: number; /** Memory the box holds (MiB), when the provider reports it. */ memoryMiB?: number; /** Age of the box in milliseconds, when the provider reports a creation * time. */ ageMs?: number; } /** * Select the orphan boxes of ONE provider. * * A box is a candidate when it is * - unknown to the daemon's sandbox registry (the ledger), AND * - held by no live daemon session, AND * - PAST THE GRACE WINDOW: older than `graceMs` (15 minutes by default). * A box the provider does not date (or that is younger than the * window) can never be proven stale, so it is NOT a candidate: a box * that is still booting, still attaching, or simply not yet in the * ledger must survive the sweep. AND * - attached to NO provider-side session (`sessions === 0`): a box the * controller still counts a session on is IN USE by somebody the * daemon cannot see. `includeAttached` drops that check (an explicit * operator override - the CLI's `--include-attached`). * * A box held by a live session is skipped even when the ledger does not * know it: the live session is the authority on what is in use, and the * gc must never destroy a box somebody is using. */ declare function collectProviderOrphanCandidates(opts: { provider: string; boxes: readonly SandboxProviderBox[]; /** Box ids the daemon's sandbox registry (ledger) knows. */ registryBoxIds: ReadonlySet; /** Box ids held by a live daemon session. */ liveBoxIds: ReadonlySet; /** Grace window on the box age, in ms (default {@link ORPHAN_GRACE_MS}). */ graceMs?: number; /** Also propose boxes the provider still counts a session on. */ includeAttached?: boolean; /** Clock injection for the age computation (tests). */ now?: number; }): SandboxOrphanCandidate[]; /** The result of scanning ONE provider. */ interface SandboxOrphanScan { provider: string; /** The provider's orphan boxes. Empty when the provider errored. */ candidates: SandboxOrphanCandidate[]; /** Why the provider could not be scanned - when it could not. */ error?: string; /** True when the provider's control plane was actually ENUMERATED. * False when the sweep never ran for that provider (not configured, no * control plane, no `listBoxes`, or an error) - the difference between * "no orphan" and "not looked at". */ scanned: boolean; /** Why the provider was not scanned (when it was not). */ skipped?: string; } interface SandboxOrphanScanDeps { resolveProvider: (slug: string) => Promise; /** Provider slugs to scan. */ providerSlugs: readonly string[]; /** Box ids the daemon's sandbox registry (ledger) knows. */ registryBoxIds: ReadonlySet; /** Box ids held by a live daemon session. */ liveBoxIds: ReadonlySet; /** Grace window on the box age, in ms (default {@link ORPHAN_GRACE_MS}). */ graceMs?: number; /** Also propose boxes the provider still counts a session on. */ includeAttached?: boolean; now?: number; } /** * Scan every provider for orphan boxes. One provider's failure is reported * on that provider's scan and never aborts the others. * * A provider that cannot be enumerated (not configured, no control plane, * no `listBoxes`) is reported as NOT SCANNED - never as "no orphan found". */ declare function scanSandboxProviderOrphans(deps: SandboxOrphanScanDeps): Promise; /** The outcome of deleting one orphan box. */ type SandboxOrphanReapResult = { ok: true; } | { ok: false; error: string; }; /** * Delete one orphan box on its provider. FORCED: the box may still carry * stale controller-side session slots, and without `force` the controller * refuses the destroy with a 409 ("still in use") - the very state that * keeps the box's RAM pinned. The candidate list already proved no LIVE * session holds the box. */ declare function reapSandboxOrphan(candidate: SandboxOrphanCandidate, deps: { resolveProvider: (slug: string) => Promise; }): Promise; /** A session row as far as the gc needs it. */ interface SandboxGcLiveSession { id?: string; status?: string; sandboxId?: string; } /** * The box ids held by LIVE sessions. A session that ended in a terminal * failure state holds nothing any more; a session whose status is unknown * is treated as LIVE (conservative: an unknown holder must never lose its * box). */ declare function liveSessionBoxIds(sessions: readonly SandboxGcLiveSession[]): Set; /** The outcome of one orphan-gc pass (the MCP tool's / CLI's shared shape). */ interface SandboxOrphanGcPassResult { /** The orphan boxes the pass found (always listed, apply or not). */ candidates: SandboxOrphanCandidate[]; /** Providers that could not be scanned - reported, never fatal for the * other providers. */ providerErrors: Array<{ provider: string; error: string; }>; /** True when at least ONE provider's control plane was actually * enumerated. False means "nothing was looked at" (no daemon, no * provider configured, no `listBoxes`) - NOT "no orphan found". */ scanned: boolean; /** The providers that were NOT swept, and why. */ notScanned: Array<{ provider: string; reason: string; }>; /** Boxes actually deleted (only with `apply`). */ deleted: string[]; /** Boxes whose delete failed (only with `apply`). */ failed: Array<{ boxId: string; error: string; }>; } /** * One orphan-gc pass: scan every provider for orphan boxes and - with * `apply` - delete them (forced). Dry run by default. */ declare function runSandboxOrphanGcPass(deps: SandboxOrphanScanDeps & { apply?: boolean; }): Promise; /** * Unified sandbox inventory: one read across every concrete provider's * control plane and, optionally, its usage ledger. * * Each provider is scanned INDEPENDENTLY. A provider that is not configured, * cannot enumerate its boxes, or throws is reported in `notScanned` / * `errors` for THAT provider and never makes the call fail or hides another * provider's rows. Rows are tagged with the provider that produced them and * deduplicated on `provider + id` (a provider that reports the same box * twice, or the same box id from two providers, stays distinct per provider). */ /** The slice of a provider the inventory reads. Kept structural so callers * (and tests) can pass a provider that only implements the optional list or * usage methods. */ type SandboxInventoryProvider = Pick; /** A provider already resolved to a handle. */ interface SandboxInventorySource { /** Catalog slug the rows are tagged with. */ slug: string; provider: SandboxInventoryProvider; } /** A provider source, or a slug to resolve through `resolveProvider`. */ type SandboxInventoryProviderInput = string | SandboxInventorySource; interface CollectSandboxInventoryOpts { /** Providers to read. Defaults to {@link DEFAULT_SANDBOX_PROVIDER_SLUGS}. * Entries may be slugs (resolved with `resolveProvider`) or handles. */ providers?: readonly SandboxInventoryProviderInput[]; /** Resolver for slug inputs. Defaults to the sandbox creds store. */ resolveProvider?: (slug: string) => Promise; /** Read usage windows too. One provider without `usage()` is not scanned * for usage and is reported as such. */ includeUsage?: boolean; /** Usage window start (ISO-8601). Defaults to 24 hours before `to`. */ from?: string; /** Usage window end (ISO-8601). Defaults to now. */ to?: string; } interface SandboxInventoryTotals { activeSec: number; vcpuSec: number; gibSec: number; /** Sum of the windows whose cost is known; `null` costs are excluded. */ costEur: number; /** True when at least one usage window had no cost model (`costEur: null`), * so the total is a lower bound. */ costPartial: boolean; } interface SandboxInventory { boxes: SandboxBox[]; usage: SandboxUsageWindow[]; totals: SandboxInventoryTotals; /** Providers whose control plane or usage ledger threw. Never fatal. */ errors: Array<{ provider: string; error: string; }>; /** Providers that could not be read, and why (unconfigured, no list/usage, * unknown slug). */ notScanned: Array<{ provider: string; reason: string; }>; } /** * Read every provider's boxes (and optionally usage windows), tagging rows * and merging duplicates on `provider + id`. Provider failures are reported * individually; the returned inventory always contains every row the other * providers produced. */ declare function collectSandboxInventory(opts?: CollectSandboxInventoryOpts): Promise; /** * Sandbox ledger reconcile — closes the gap between what * `~/.agentproto/sandboxes.json` believes is still booted/paused/connected * and what the PROVIDER actually still has running. A failed teardown, a * daemon that crashed mid-close, or a provider-side idle-reap the daemon * never heard about all leave a ledger row claiming a box is alive long * after the provider reaped it — real-world evidence: one daemon's ledger * carried ~50 rows in "paused" while the provider had far fewer boxes left. * * This is read-only against the PROVIDER (`SandboxProvider.probe`, the same * primitive `GET /sandboxes/:id/alive` and `agentproto sandbox list` already * use per-row) and never tears a box down — it only ever flips a ledger * row's `state` to `"gone"` via `recordSandboxLiveness` when the provider * confirms the box no longer exists. A box a caller still wants stays * completely untouched; this module has no `stop()`/`pause()`/`connect()` * call anywhere in it. */ /** The slice of `SandboxProviderHandle` reconcile needs — just the liveness * probe, so tests (and the `local` provider, which has none) can hand back * a handle without a `probe` at all. */ interface SandboxReconcileProviderHandle { provider: { probe?(sandboxId: string): Promise<{ alive: boolean; state?: string; }>; }; } interface SandboxReconcileDeps { /** Resolve a ledger row's provider slug to a handle. Mirrors * `SandboxGcReapDeps.resolveProvider` (`sandbox-gc.ts`) — same DI shape, * narrower need (probe only, never connect/boot). */ resolveProvider: (slug: string) => Promise; /** Defaults to `readSandboxLedger` — injectable so callers that already * hold a mocked/scoped ledger reader (tests, a scoped CLI mock) can reuse * it instead of this module reaching for the real `~/.agentproto/ * sandboxes.json` on disk. */ readLedger?: (path?: string) => SandboxLedgerEntry[]; /** Defaults to `recordSandboxLiveness` — same injectability reasoning. */ recordLiveness?: (sandboxId: string, alive: boolean, path?: string) => void; ledgerPath?: string; } /** Verdict for one reconciled row. `"skipped"` means the provider has no * `probe()` (e.g. Box today) — never treated as evidence of death. */ type SandboxReconcileVerdict = "alive" | "gone" | "unknown" | "skipped"; interface SandboxReconcileRow { sandboxId: string; provider: string; verdict: SandboxReconcileVerdict; /** Present when `verdict` is "unknown" — the resolve/probe failure message. */ error?: string; } interface SandboxReconcileResult { checked: number; alive: number; gone: number; unknown: number; skipped: number; rows: SandboxReconcileRow[]; } /** * Probe every ledger row still claiming to be alive against its provider, * and stamp the verdict back into the ledger (`recordSandboxLiveness` flips * a dead row to `"gone"`; a live or unprobeable row is left as-is). One * broken row's provider resolution or probe call never aborts the pass for * the rest — each row's outcome is independent and best-effort. */ declare function reconcileSandboxLedger(deps: SandboxReconcileDeps): Promise; /** * Server-side narrowing for the session listers — the `session_list` MCP * tool and `GET /sessions` (+ `agentproto sessions --json`) share this one * module so the vocabulary and the semantics cannot drift between surfaces. * * Every filter is optional and AND-ed with the others. Vocabulary reuses * `session_follow`'s selector/exclude names (`rootOnly`, labels, * `parentSessionId`) rather than inventing a second one. * * Pure: no registry, no I/O, an injectable clock. The callers own subtree * scoping, archived/kind/status handling and pagination. */ /** Raised for caller-fixable filter input (an unparsable time bound). */ declare class SessionListFilterError extends Error { constructor(message: string); } /** A string or a list of strings. HTTP callers send `a,b` or repeat the key. */ type StringOrList = string | readonly string[]; interface SessionListFilterInput { /** Only sessions whose `id` equals one of these (exact match): the cheap read of known sessions. */ ids?: StringOrList; /** Case-insensitive substring over id, name, label, title and cwd. */ q?: string; /** Only sessions whose `label` equals this (case-insensitive exact match). */ label?: string; /** Only sessions whose `cwd` is this path or lives under it (path prefix, boundary-aware). */ cwd?: string; /** Drop sessions whose `label` starts with any of these (case-sensitive). */ excludeLabelPrefix?: StringOrList; /** Drop sessions whose `label` equals any of these (as `session_follow`'s `exclude.labels`). */ excludeLabels?: StringOrList; /** Drop sessions of these kinds (`terminal` | `agent-cli` | `command`). */ excludeKinds?: StringOrList; /** Only sessions with no parent (as `session_follow`'s `selector.rootOnly`). */ rootOnly?: boolean; /** Only direct children of this session (the caller resolves a name to an id first). */ parentSessionId?: string; /** Only sessions whose last activity (else start) is at/after this: ISO-8601 or relative (`30m`, `24h`, `7d`, `2w`). */ updatedSince?: string; /** Only sessions started at/after this: ISO-8601 or relative. */ startedSince?: string; /** Preset: drop review lanes, workflow stages and ended one-shot command runs (see {@link isNoiseSession}). */ excludeNoise?: boolean; } /** Names of every filter key, for surfaces that parse them from a query string. */ declare const SESSION_LIST_FILTER_KEYS: readonly ["ids", "q", "label", "cwd", "excludeLabelPrefix", "excludeLabels", "excludeKinds", "rootOnly", "parentSessionId", "updatedSince", "startedSince", "excludeNoise"]; /** Copy only the filter keys (a tool input carries many other params). */ declare function pickSessionListFilters(input: SessionListFilterInput): SessionListFilterInput; /** * Parse an ISO-8601 instant or a relative age (`90s`, `30m`, `24h`, `7d`, * `2w` = "that long before `now`") into epoch ms. Throws * {@link SessionListFilterError} on anything else. */ declare function parseTimeBound(raw: string, field: string, now?: number): number; type NoiseView = Pick; /** * What `excludeNoise: true` drops — exactly these, nothing else: * 1. review lanes: `label` starts with `review:` or `origin === "review"`; * 2. workflow stage sessions: `label` starts with `wf:` or `origin === "workflow"`; * 3. ended one-shot command runs: `status` is `exited` or `killed` and the * session is a plain command — `kind: "command"`, or `kind: "terminal"` * with no `adapterSlug` (an interactive agent TUI such as `claude` carries * one, so it is kept). * A live session of kind 3 (a running dev server, a `bash` you are typing in) * and every agent-cli session outside 1–2 are kept, as is anything `error`ed. */ declare function isNoiseSession(s: NoiseView): boolean; /** * Just the review-lane / workflow-stage lanes of {@link isNoiseSession} * (steps 1–2): `label` starts with `review:` or `wf:`, or `origin` is * `review` / `workflow`. Used to group these under one synthetic parent node * without also swallowing ended one-shot command runs. */ declare function isReviewOrWorkflowSession(s: Pick): boolean; /** Epoch ms of a session's last activity, falling back to its start. */ declare function sessionActivityMs(s: Pick): number; /** Newest activity first; ties broken by id so cursors stay stable. Returns a new array. */ declare function sortNewestActivityFirst>(rows: readonly T[]): T[]; /** True when `input` carries at least one filter (an empty `q` / `false` flag does not count). */ declare function hasSessionListFilters(input: SessionListFilterInput): boolean; type FilterableSession = Pick; /** * Compile `input` into a row predicate. Validates (and resolves relative * times against `now`) once, up front, so a bad `updatedSince` fails the * whole call instead of silently matching nothing. */ declare function compileSessionListFilters(input: SessionListFilterInput, now?: number): (s: FilterableSession) => boolean; /** Filter `rows` (order preserved). Throws {@link SessionListFilterError} on a bad time bound. */ declare function applySessionListFilters(rows: readonly T[], input: SessionListFilterInput, now?: number): T[]; /** * Read the filters off an HTTP query string. Array-valued keys accept * `a,b` or a repeated key; booleans accept `true`/`1` (anything else is off). */ declare function parseSessionListFilterParams(params: URLSearchParams): SessionListFilterInput; /** Zod fragment spread into `session_list`'s input schema. */ declare const sessionListFilterShape: { readonly ids: z.ZodOptional]>>; readonly q: z.ZodOptional; readonly label: z.ZodOptional; readonly cwd: z.ZodOptional; readonly excludeLabelPrefix: z.ZodOptional]>>; readonly excludeLabels: z.ZodOptional]>>; readonly excludeKinds: z.ZodOptional]>>; readonly rootOnly: z.ZodOptional>; readonly parentSessionId: z.ZodOptional; readonly updatedSince: z.ZodOptional; readonly startedSince: z.ZodOptional; readonly excludeNoise: z.ZodOptional>; }; /** * Per-session structured event capture — one append-only JSONL file per * agent-cli session, written at the same tap point where `projectEvent` * (sessions.ts) flattens `StreamEvent`s into the ANSI ring buffer, but * BEFORE that flattening happens. Gives agentproto the Claude-Code * property: a daemon-owned structured transcript that survives a daemon * restart (the ring buffer doesn't) and that any frontend can render, * not just the two adapters `transcript-export.ts` knows how to re-read * from their own native stores. * * File layout: `~/.agentproto/sessions//events.jsonl` (the * root is overridable via the daemon config's `sessions.eventsDir` — see * `setDefaultSessionsBaseDir`), one JSON object per line: `{seq, ts, kind, ...fields}`. * * PTY (`terminal`) and `command` sessions never call into this writer — * they have no structured event source (see report-transcript- * architecture.md finding C.17), so this module is only ever driven from * `agent-cli` sessions' `runAgentTurn`. */ /** Point the no-`baseDir` path resolution at `dir`. Called once at daemon * boot from the loaded config (`sessions.eventsDir`); `undefined` restores * the hardcoded `~/.agentproto/sessions` default. Relative paths are * resolved against the home directory. */ declare function setDefaultSessionsBaseDir(dir: string | undefined): void; /** The effective default base dir — the configured one, or the hardcoded * `~/.agentproto/sessions`. */ declare function defaultTranscriptBaseDir(): string; declare function sessionTranscriptDir(sessionId: string, baseDir?: string): string; declare function sessionEventsPath(sessionId: string, baseDir?: string): string; /** * Per-session index sidecar — a compact `//index.json` * projection of every session dir under the sessions store, maintained * best-effort on every write-path event (create/rename/turn-end/exit) and * backfilled at daemon startup for sessions that predate the sidecar. * * WHY: recovering a session by its user-visible label (or its cwd, or an id * prefix) used to require `grep -r` across the whole sessions store and a * hand-rolled parse of a multi-thousand-line `events.jsonl`. Everything was * in the jsonl, but answering "which session was that?" meant loading every * file whole. The sidecar turns that into one small JSON read per session * (`sessions find`) and a single bounded tail read for the "where did we * stop" recap (`sessions recap`). * * INVARIANTS: * - additive: `events.jsonl`'s format is never touched; this is a sidecar. * - best-effort: a failed index write must never fail a session write. * - bounded: reads seek from the end and cap the window ({@link INDEX_TAIL_BYTES}); * a whole-file read of `events.jsonl` is never performed here. * - throttled: the registry schedules index writes rather than doing one * per streaming frame (see `scheduleIndexWrite` in sessions.ts). * * Pure by construction apart from the explicit read/write helpers; the * registry owns the scheduling, this module owns the shape and the disk. */ /** Hard cap on `lastUserPrompt.text`, in characters. */ declare const INDEX_MAX_PROMPT = 500; /** Hard cap on `lastOutputText`, in characters. */ declare const INDEX_MAX_OUTPUT = 300; /** How many bytes of `events.jsonl` a tail read may pull back from the end. * Bounded so a multi-MB transcript never turns a find/recap into a scan. */ declare const INDEX_TAIL_BYTES: number; /** Default page size for `sessions find` / `session_search`. */ declare const INDEX_DEFAULT_LIMIT = 20; /** The compact sidecar shape. Every field is optional except `id`/`kind`/ * `status`/`alive`/`startedAt`, so a recovered-from-jsonl entry can be * partial without lying about what it knows. */ interface SessionIndexEntry { id: string; label?: string; title?: string; renamedByUser?: boolean; kind: string; status: string; alive: boolean; adapter?: string; model?: string; cwd?: string; workspaceSlug?: string; origin?: string; depth?: number; parentSessionId?: string; startedAt: string; lastActivityAt?: string; /** True when the session was archived at the time this sidecar was * written. Present from this point on; a sidecar written by an older * daemon simply omits it, so a cold read of such a row shows it as * non-archived. */ archived?: boolean; lastTurnReason?: string; lastUserPrompt?: { ts: string; text: string; }; lastOutputText?: string; turnsCompleted?: number; costUsd?: number; } /** One user prompt recovered from a transcript tail. */ interface TranscriptPrompt { ts: string; text: string; } /** The bounded tail-read result: parsed prompts, the last assistant run, and * how many bytes were actually read (exposed so a test can prove the read * stayed within {@link INDEX_TAIL_BYTES}). */ interface TranscriptTail { prompts: TranscriptPrompt[]; lastOutputText?: string; bytesRead: number; /** `ts` of the first parseable record in the window, when it carries one. */ firstTs?: string; } /** Absolute path of one session's index sidecar. */ declare function sessionIndexPath(sessionId: string, baseDir?: string): string; /** Build the sidecar entry from a live/persisted descriptor, filling the * transcript-derived fields (`lastUserPrompt`/`lastOutputText`) from the * caller when it has them. */ declare function indexEntryFromDescriptor(desc: SessionDescriptor, extra?: { lastUserPrompt?: TranscriptPrompt; lastOutputText?: string; }): SessionIndexEntry; /** Read one session's sidecar. Returns undefined on ENOENT, malformed JSON, * or a shape missing its id — never throws. */ declare function readSessionIndex(sessionId: string, baseDir?: string): SessionIndexEntry | undefined; /** Atomically write one session's sidecar (tmp + rename). Best-effort: * swallows every error — a failed index write must never fail a session * write. */ declare function writeSessionIndex(entry: SessionIndexEntry, baseDir?: string): void; /** * Read the final `maxBytes` of `eventsPath` and extract, in one forward pass, * every `user-prompt` (with its `ts`) and the last non-empty assistant text * run. The window's first line is usually torn; JSON.parse rejects it and it * is skipped. Never reads the whole file. */ declare function readTranscriptTail(eventsPath: string, maxBytes?: number): TranscriptTail; /** Recover a partial sidecar entry for a session from its `events.jsonl` * alone — the backfill path for a missing/corrupt index. Returns undefined * when the session dir has no transcript. */ declare function deriveIndexFromTranscript(sessionId: string, baseDir?: string): SessionIndexEntry | undefined; /** Every sidecar under `baseDir`, newest activity first. Dirs with a missing * or corrupt index are recovered in memory from their transcript tail so a * find still sees them; this never writes. Best-effort: a readdir failure * returns `[]`. */ declare function readAllSessionIndexes(baseDir?: string): SessionIndexEntry[]; /** Case-insensitive query match: `id` by prefix, every other searchable field * by substring. An empty query matches everything. */ declare function matchesSessionQuery(entry: Pick, query: string): boolean; /** Filter + order + cap a set of index entries. `limit` defaults to * {@link INDEX_DEFAULT_LIMIT}. */ declare function searchSessionIndexes(entries: readonly SessionIndexEntry[], query: string, opts?: { status?: string; limit?: number; }): SessionIndexEntry[]; /** The one-glance "where did we stop" recap — the output an agent needs to * resume. Built from the sidecar plus a bounded tail read of the transcript. */ interface SessionRecap { id: string; status: string; alive: boolean; label?: string; title?: string; adapter?: string; model?: string; cwd?: string; workspaceSlug?: string; parentSessionId?: string; children: string[]; startedAt: string; lastActivityAt?: string; turnsCompleted?: number; costUsd?: number; lastTurnReason?: string; /** Last K user prompts, oldest → newest. */ prompts: TranscriptPrompt[]; /** Final assistant text/thought of the last turn (trimmed). */ lastOutputText?: string; queuedPrompts?: number; /** The queued prompts with age — see `SessionDescriptor.pendingPrompts`. */ pendingPrompts?: readonly PendingPromptView[]; } /** * Compose a recap from an index entry + a bounded transcript tail read. * `eventsPath` is read from the end only (≤{@link INDEX_TAIL_BYTES}); * `children`/`queuedPrompts` come from the caller (the daemon has them live, * the CLI derives children from the index set). */ declare function buildSessionRecap(input: { entry: SessionIndexEntry; eventsPath: string; last?: number; children?: readonly string[]; queuedPrompts?: number; pendingPrompts?: readonly PendingPromptView[]; }): SessionRecap; /** * Daemon-startup pass: create the sidecar for every session dir that lacks a * valid one, recovering `lastUserPrompt`/`lastOutputText` from the transcript * tail (never a whole-file parse). When `descriptors` are supplied (the live * registry), their authoritative meta fills the entry. Best-effort and * synchronous — a store with thousands of sessions does one readdir plus one * bounded read per missing index, nothing more. */ declare function backfillSessionIndexes(baseDir?: string, opts?: { descriptors?: Iterable; }): { scanned: number; created: number; skipped: number; }; /** * Non-blocking variant of {@link backfillSessionIndexes} — the one the daemon * runs at boot. Same result, but the readdir and every sidecar check are * async and dirs are processed in batches with a `setImmediate` yield in * between, so a store with thousands of session dirs never holds the event * loop for the whole scan. Only the rare missing-index path (a bounded tail * read + a small write) stays synchronous. */ declare function backfillSessionIndexesAsync(baseDir?: string, opts?: { descriptors?: Iterable; }): Promise<{ scanned: number; created: number; skipped: number; }>; /** * Cold history fallback — the sessions the registry cannot hold. * * `HISTORY_CAP` bounds how many descriptors the registry reinflates at boot * (`loadHistorySnapshot` slices each bucket to the newest {@link HISTORY_CAP} * rows). Everything older survives on disk — its `index.json` sidecar and its * `events.jsonl` transcript are never swept — but it is invisible to * `session_list` / `session_search` / `conversation_read`, which answer only * from the in-memory map. On a busy host that cap is reached in ordinary use, * so "the session I ran last Tuesday" is a real row on disk that no tool can * return. * * This module is the read side of that gap: map the on-disk sidecar back into * a {@link SessionDescriptor} so the existing listers can serve it. Rules: * * - NEVER overrides the live registry: callers drop any cold row whose id * the registry already holds (a live row is authoritative). * - marked `cold: true`, and terminal (`alive: false`) — the registry has no * process for it, so a sidecar that still claims `running`/`starting` is * stale (the same reclassification boot-load applies) and lands `killed`. * - cached for {@link COLD_TTL_MS} per base dir: the fallback is a * best-effort rescue, not a hot path, and a store with thousands of * sidecars must not be re-scanned on every poll. * * Pure apart from the explicit disk reads; the callers own scoping, filters * and pagination. */ /** How long one cold scan is reused before the store is re-read. */ declare const COLD_TTL_MS = 30000; /** * Map a sidecar entry (or a transcript-derived one) back to a descriptor. * Everything the sidecar knows is passed through; everything it cannot know * (a pid, liveness, queued prompts, in-flight flags) is deliberately absent * rather than guessed. */ declare function sessionDescriptorFromIndexEntry(entry: SessionIndexEntry): SessionDescriptor; /** Drop the cold-scan cache — tests, and a caller that just rewrote the store. */ declare function resetColdSessionCache(): void; /** * Every session the registry is NOT holding, newest activity first. One * directory scan per {@link COLD_TTL_MS} window per base dir. * * Returns the CACHED array by reference — treat it as read-only (every * caller copies before filtering/splicing). It is rebuilt on the next * TTL-expired call, so a mutation would survive only until then, but * silently vanish after — a bug class not worth the defensive copy. */ declare function coldSessionRows(baseDir?: string, now?: number): SessionDescriptor[]; /** * One cold session by id — the `conversation_read` rescue path. Targeted * (one sidecar read, or one bounded transcript tail when the sidecar is * missing), never the full scan. Path-like ids (`../x`) are rejected: the * input is caller-supplied and becomes a path segment. */ declare function coldSessionDescriptor(idOrName: string, baseDir?: string): SessionDescriptor | undefined; /** * Shared agent-session restart core — the "agent" branch of * `decideRestartStrategy` (resume-strategies.ts), factored out so both * the `session_restart` MCP tool (session-tools.ts) and the cron * scheduler's `prompt-session` action (cron-scheduler.ts) resume a dead * session via the exact same path. PTY strategies stay inline in * session-tools.ts — cron `prompt-session` jobs only ever target * agent-cli sessions. * * Lives in its own module (not resume-strategies.ts) because * resume-strategies.ts is deliberately duck-typed against a minimal * shape to avoid a value-level import of sessions.ts (see its own * top-of-file comment). This module needs the real `SessionsRegistry` * / `AgentAdapterResolver` types, so it can't share that constraint. * * Billing-auth resolution (money bug fix): a restarted session used to * respawn with NO auth resolution at all, so a session pinned to * `subscription` billing silently came back on whatever the daemon's * ambient env happened to hold (e.g. a leaked `ANTHROPIC_API_KEY`) — * bills org credits under a Max/Pro-pinned session with no signal * anywhere. This module now re-runs the SAME resolver * `session-spawn.ts` uses (`resolveAuthSpec`, fed by * `resolveSpawnDefaults`), sourcing the requested MODE from the prior * descriptor's `auth.mode` (the secret itself is never persisted there, * by design — see `SessionDescriptor.auth`) and re-resolving the actual * credential from `~/.agentproto/config.json` / providers.json, same * merge order as a fresh spawn. The logic is duplicated rather than * shared with `session-spawn.ts` because that file is out of scope for * this fix (see its own callers) — both call sites must stay in sync by * inspection, same as they already do for `decideRestartStrategy`. * * Restart-with-override (SPEC §4.3, build step 6): the base path above copies * the prior descriptor's `auth.mode` and never switches wallets. This module * now also takes an `overrides` map (the decomposed `SessionConfig` axes) so a * restart can DELIBERATELY change an axis. The load-bearing one is `access`: a * restart requesting a different named auth profile resolves the route first * (access is downstream, SPEC §1c), validates the profile's eligibility against * the resolved `(adapter × route)` endpoint (rejecting Rx/Ry mismatches with a * `RestartOverrideError`/400 rather than ever falling back to another wallet — * the R1 money-bug guarantee), and feeds the profile's OWN credential through * the SAME `resolveAuthSpec` gate as the base path — no parallel auth path. The * remaining axes (`route`/`posture`/`contextProfile`/`model`/`effort`) overlay * the prior descriptor and round-trip onto the fresh one; a changed axis is * announced via `session:config-changed` (#490). `mcpServers` (read off * `SessionConfig` itself) is the one array-shaped axis and is a FULL * REPLACEMENT, not a merge — see `buildRestartMcpServers`'s comment in * `restartAgentSession`. */ /** * Why a restart failed — the machine-readable vocabulary every transport * (HTTP `POST /sessions/:id/restart`, the `session_restart` MCP verb, the * CLI) hands to clients so a UI can show a human sentence AND offer the * right next step instead of echoing a provider's raw string. * * `unsupported_strategy` is an addition beyond the sandbox vocabulary: the * pre-sandbox guard (`only agent-adapter sessions are resumable this way`) * needs a code of its own for the same reason the sandbox paths do. */ type SessionRestartErrorCode = "sandbox_gone" | "sandbox_unreachable" | "sandbox_provider_missing" | "sandbox_box_start_failed" | "no_workspace" | "no_workspace_remote" | "no_known_branch" | "adapter_not_found" | "unsupported_strategy" | "retired" | "override_invalid" | "cloud_spawn_refused"; /** * The optional "and here's what to do about it" hint a client turns into a * button. `spawn-on-branch`/`spawn-fresh` are the two recovery moves for a * dead box (re-clone the recorded `wt/` work branch, or start over from the * workspace's base branch); `fix-config` carries the literal remediation * (the command the user has to run before a restart can succeed at all). */ type SessionRestartAction = { kind: "spawn-on-branch"; branch: string; } | { kind: "spawn-fresh"; } | { kind: "fix-config"; detail: string; }; /** * The one-line human sentence behind each code. Sentences, not fragments: * several surfaces (session-chat, the CLI) show `reason` on its own, with * the technical `message` as the detail underneath. Overridable per throw * site when the generic sentence would be wrong for that specific failure. */ declare const SESSION_RESTART_REASONS: Record; /** * A restart failure with a machine-readable `code`, a short human `reason` * and — when there is one — an `action` hint a client can turn into a * button. `message` stays the technical detail (unchanged from the plain * `Error`s these replace), so logs, tests and `--json` output keep reading * exactly as before; `reason` is what a person is shown. * * `status` is the HTTP/MCP rejection status the transports preserve * (400 for a rejected override, 500 for everything else). */ declare class SessionRestartError extends Error { readonly code: SessionRestartErrorCode; readonly reason: string; readonly action?: SessionRestartAction; readonly status: number; constructor(code: SessionRestartErrorCode, message: string, opts?: { reason?: string; action?: SessionRestartAction; status?: number; }); } /** * Thrown when a restart override is invalid — an unknown access profile, or a * profile that isn't eligible for the resolved `(adapter, route)` endpoint * (SPEC risks Rx/Ry). Carries `status: 400` so the MCP/HTTP surfaces reject the * restart with a clear reason instead of ever spawning with the wrong wallet. * * A {@link SessionRestartError} (`code: "override_invalid"`) so every * transport reports it like any other restart failure; `instanceof * RestartOverrideError` callers are untouched. */ declare class RestartOverrideError extends SessionRestartError { constructor(message: string); } /** Map a {@link spawnOnFreshBox} `blocker` string onto its code — the three * why-texts #1910 can produce (no workspace, no remote, no known work * branch). Order matters: a workspace blocker also mentions the missing * branch, so the workspace cause wins over the branch one. */ declare function restartBlockerCode(blocker: string): SessionRestartErrorCode; /** * The wire shape of a restart failure — `POST /sessions/:id/restart`'s body * and the `session_restart` MCP result both carry it. `error.code`/ * `error.reason`/`error.action` are the typed part; `error.message` and the * top-level `message` are the technical detail, kept so every existing * reader (`formatHttpError` in the CLI, `describeError` in the VS Code * client, `--json` consumers) still finds what it looked for before. */ interface SessionRestartErrorPayload { error: { code: SessionRestartErrorCode; reason: string; message: string; action?: SessionRestartAction; }; message: string; } /** * Build {@link SessionRestartErrorPayload} for a thrown restart error, or * `undefined` when the error carries no restart code (a plain `Error` from a * driver, say) — callers keep their existing `{error:"restart_failed", * message}` fallback for those, which is what "fall back to today's message * when no code" means on the client too. * * `SessionRetiredError` is mapped rather than subclassed: it already extends * `SessionNotAliveError` (whose `instanceof` callers must not move) and * already carries its own `code`, so only its payload spelling is derived * here. */ declare function sessionRestartErrorPayload(err: unknown): SessionRestartErrorPayload | undefined; /** * The body a transport sends when a restart failed: the typed payload for a * coded failure, today's `{error:"restart_failed", message}` for anything * else (an uncoded driver error must keep its current shape — no code, no * invented reason). Pass the caught `err` straight in; no branching needed. */ declare function sessionRestartErrorBody(err: unknown): SessionRestartErrorPayload | { error: "restart_failed"; message: string; }; /** * HTTP status for a restart failure: the error's own (400 for a rejected * override, 500 for the rest), 409 for a retired/superseded row — the status * `retiredErrorWire` already uses for a refused prompt — else 500. Note * `SessionRetiredError.status` is the SESSION's status string, never an HTTP * code, so it is deliberately not read here. */ declare function sessionRestartErrorStatus(err: unknown): number; /** * "Launched by" is a read-only, derived answer to WHO started a session. The * data already lives on the descriptor in four separate fields * (`parentSessionId`, `callerSessionId`, `operatorLabel`, `origin`); this * module folds them into one `LaunchedBy` value so `session_list` and the CLI * table cannot drift. It is pure: no I/O, nothing persisted, no behavior * change. */ type LaunchedBy = { kind: "session"; sessionId: string; via?: string; } | { kind: "operator"; via?: string; } | { kind: "origin"; origin: string; }; /** The raw descriptor fields the derivation reads. */ interface LaunchedBySource { parentSessionId?: string; callerSessionId?: string; operatorLabel?: string; origin?: string; } /** Precedence, first match wins: parent, caller, operator, origin. An empty * string counts as absent; a whitespace-only value is kept as given. * `via` (the channel) is attached to the session and operator kinds only, * and only when the origin is non-empty. */ declare function launchedByOf(d: LaunchedBySource): LaunchedBy | undefined; /** Human-readable text for a `LaunchedBy`, e.g. `session sess_1 (brain) via * orchestrator`, `operator via vscode`, or `cron`. `labelOf` supplies the * display label for a session id when the caller has one; an empty result * is treated as no label. */ declare function launchedByText(info: LaunchedBy | undefined, labelOf?: (sessionId: string) => string | undefined): string; /** * Host-level load report - answers "why is this machine on its knees" without * a hand-run `top` / `vm_stat` / `iostat` / `ps` / `lsof` session. * * One collector (`createHostLoadService`) gathers, in parallel and each under * a hard timeout so the whole call stays inside a small budget even at load * 500: * * - load average vs core count, CPU user/sys/idle * - RAM used / wired / compressor / cached / free, swap used * - per-disk transfers/s and MB/s * - the process table, attributed to sessions with the same rules as * `session_stats` (`process-stats.ts`), plus per-process memory footprint * including compressed pages where the OS exposes it * - listening TCP ports and (for a handful of suspects) the cwd, to spot * deleted-cwd loops and duplicate dev servers * * and turns them into WARNINGS: swap pressure, reparented (ppid 1) leftovers * that are old and busy or serving, deleted-cwd processes, filesystem-wide * scans, several servers on one port, load far above the core count. * * macOS shells out to `vm_stat`, `sysctl vm.swapusage`, `iostat`, `top`, `ps`, * `lsof`; Linux reads `/proc` (+ `ps`, `ss`). Nothing needs sudo. A probe that * is missing, denied or too slow is skipped and named in `partial` - the rest * of the report still ships. The collector is exported (`getHostLoadService`, * `createHostLoadService`) so a scheduler can gate heavy jobs on it. */ type HostLoadDetail = "summary" | "full"; interface HostLoadCpu { userPercent: number; sysPercent: number; idlePercent: number; source: "iostat" | "top" | "proc-stat"; } interface HostLoadMemory { totalBytes: number; /** App + wired + compressed (Activity Monitor's "Memory Used"). Absent when * the platform gives no such split. */ usedBytes?: number; wiredBytes?: number; /** Bytes physically occupied by the compressor (macOS). */ compressorBytes?: number; /** File cache + purgeable pages. */ cachedBytes?: number; /** Never-touched pages only. */ freeBytes: number; /** Free + reclaimable: what a new job can actually get without swapping. */ availableBytes: number; } interface HostLoadSwap { totalBytes: number; usedBytes: number; freeBytes: number; percent: number; } interface DiskLoad { name: string; /** Transfers per second over the sampling interval. */ tps: number; mbPerSec: number; /** Average KB per transfer, when the OS reports it. */ kbPerTransfer?: number; } type HostProcessOwner = { kind: "session"; sessionId: string; label?: string; detached?: boolean; } | { kind: "daemon"; } | { kind: "provisioning"; } /** Reparented to init by a session that is gone (or never was one). */ | { kind: "orphan"; sessionHint?: string; } /** OS services and installed apps. */ | { kind: "system"; } /** Anything else: the operator's own shells, editors, other users. */ | { kind: "other"; }; interface HostProcess { pid: number; ppid: number; uid: number; /** Normalized name (`pnpm install`, `vitest`, `node`, ...). */ command: string; /** Raw command line, truncated. */ args: string; rssBytes: number; /** Footprint including compressed pages when measured, else RSS. */ memoryBytes: number; memorySource: "footprint" | "rss"; /** Bytes of this process the OS has compressed / swapped out. */ compressedBytes?: number; cpuPercent: number; elapsedSec: number; owner: HostProcessOwner; /** TCP ports it listens on. */ listening?: number[]; /** Its cwd was deleted out from under it. */ cwdDeleted?: boolean; } type HostWarningKind = "swap" | "load" | "orphan" | "deleted-cwd" | "fs-scan" | "duplicate-port"; interface HostWarning { kind: HostWarningKind; severity: "warn" | "critical"; message: string; pids?: number[]; } interface HostSessionRollup { sessionId: string; label?: string; rssBytes: number; memoryBytes: number; cpuPercent: number; procCount: number; } interface HostLoadReport { sampledAt: string; detail: HostLoadDetail; /** Wall time the collection took. */ elapsedMs: number; /** Probes that failed, timed out or were skipped; the rest is still valid. */ partial: string[]; platform: NodeJS.Platform; loadAvg: [number, number, number]; cpuCount: number; /** 1-minute load divided by core count. */ loadPerCore: number; cpu?: HostLoadCpu; memory: HostLoadMemory; swap?: HostLoadSwap; disks: DiskLoad[]; topByCpu: HostProcess[]; topByMemory: HostProcess[]; warnings: HostWarning[]; /** `detail: "full"` only. */ sessions?: HostSessionRollup[]; /** `detail: "full"` only: every process, largest memory first. */ processes?: HostProcess[]; /** Subtree-scoped caller: only its own sessions' processes are listed. */ scoped?: true; } /** Per-process memory from `top -l 1 -stats pid,mem,cmprs`: `mem` is the * physical footprint (already including compressed memory), `cmprs` the * compressed component. Adding them double-counts compressed pages. */ interface Footprint { memoryBytes: number; compressedBytes: number; } interface HostLoadThresholds { swapWarnPercent: number; swapCriticalPercent: number; /** Reparented processes younger than this are not flagged. */ orphanMinAgeSec: number; orphanCpuPercent: number; /** 1-minute load / cores above which the host is flagged. */ loadPerCoreLimit: number; } declare const DEFAULT_HOST_LOAD_THRESHOLDS: HostLoadThresholds; declare function describeOwner(o: HostProcessOwner): string; interface HostWarningInput { loadAvg: readonly [number, number, number]; cpuCount: number; swap?: HostLoadSwap; processes: readonly HostProcess[]; homeDir: string; thresholds?: Partial; } declare function computeHostWarnings(input: HostWarningInput): HostWarning[]; /** Raw inputs of a Linux CPU/disk sample: two reads of `/proc/stat` and * `/proc/diskstats`. */ interface LinuxCpuDiskSample { statBefore: string; statAfter: string; diskBefore: string; diskAfter: string; intervalSec: number; } interface CwdInfo { path: string; deleted: boolean; } /** Every external read the collector performs. Each takes the time (ms) it may * spend; a probe that is not applicable on the platform is left undefined. */ interface HostProbes { platform: NodeJS.Platform; table: (timeoutMs: number) => Promise; vmStat?: (timeoutMs: number) => Promise; swapUsage?: (timeoutMs: number) => Promise; iostat?: (timeoutMs: number) => Promise; top?: (timeoutMs: number) => Promise; meminfo?: (timeoutMs: number) => Promise; cpuDisk?: (timeoutMs: number) => Promise; listeners?: (timeoutMs: number) => Promise; cwds?: (pids: readonly number[], timeoutMs: number) => Promise>; smaps?: (pids: readonly number[], timeoutMs: number) => Promise>; envHints?: (pids: readonly number[], timeoutMs: number) => Promise>; /** Pids of the child processes the probes themselves spawned, so they are * not billed as host load. */ ownPids?: () => ReadonlySet; loadAvg?: () => [number, number, number]; cpuCount?: () => number; totalMem?: () => number; } declare function createDefaultHostProbes(): HostProbes; interface HostSample { at: number; budgetMs: number; elapsedMs: number; partial: string[]; platform: NodeJS.Platform; loadAvg: [number, number, number]; cpuCount: number; cpu?: HostLoadCpu; memory: HostLoadMemory; swap?: HostLoadSwap; disks: DiskLoad[]; table: ProcRow[]; footprints: Map; listeners: Map; cwds: Map; envHints: Map; } declare const DEFAULT_HOST_LOAD_BUDGET_MS = 1900; /** * Run every probe under the budget and fold the results into one sample. A * failed probe is recorded in `partial` and its section left empty. */ declare function collectHostSample(probes: HostProbes, sessions: readonly StatsSessionDescriptor[], opts?: { budgetMs?: number; now?: () => number; uid?: number; daemonPid?: number; }): Promise; interface BuildHostLoadOptions { sessions: readonly StatsSessionDescriptor[]; detail?: HostLoadDetail; daemonPid?: number; uid?: number; homeDir?: string; provisions?: readonly ProvisionInFlight[]; /** Restrict to these sessions' processes (subtree-scoped MCP caller). */ visible?: ReadonlySet; thresholds?: Partial; topN?: number; } /** Fold a sample plus the session registry into the report. Pure. */ declare function buildHostLoadReport(sample: HostSample, opts: BuildHostLoadOptions): HostLoadReport; interface HostLoadServiceOptions { probes?: HostProbes; tracker?: ProvisionTracker; daemonPid?: number; uid?: number; homeDir?: string; /** How long a sample is reused. Default 2000 ms. */ ttlMs?: number; /** Default per-call budget. */ budgetMs?: number; now?: () => number; } interface HostLoadService { report(sessions: readonly StatsSessionDescriptor[], opts?: { detail?: HostLoadDetail; fresh?: boolean; budgetMs?: number; visible?: ReadonlySet; thresholds?: Partial; }): Promise; } declare function createHostLoadService(opts?: HostLoadServiceOptions): HostLoadService; /** Process-wide collector shared by MCP, HTTP and in-process callers (a job * scheduler gating on `report.loadPerCore` / `report.warnings`), so one probe * round serves them all within the TTL. */ declare function getHostLoadService(): HostLoadService; /** * Idle agent-session reaper (PR-6). * * Agent-cli sessions keep their `claude-agent-acp` child alive between turns * (by design, for multi-turn continuity). But a finished/idle session sits * there as `status:"running"` indefinitely — a live adapter process holding * memory, cluttering `session_list`, and (once #638's eager resume-on-boot is * enabled) a candidate for a pointless resume-storm of dead work on the next * daemon restart. * * This pass sweeps the registry, finds agent-cli sessions that have been idle * past a threshold, and REAPS them (`registry.reapIdle`): SIGTERM the adapter * child to free the process, flip the row to `killed`/`endedReason:"idle-reaped"` * — leaving it dead-but-lazy-resumable (a later prompt revives it in place). A * reaped row is naturally excluded from #638's eager pass (which gates on * `endedReason === "daemon-restart"`), so eager resume only ever revives * genuinely-recent work. * * The reap ACTION and its invariants (agent-cli-only, running-only, * clear-the-binding-so-it-stays-resumable, emit `session:reaped`) live behind * `registry.reapIdle`. This module owns only the POLICY: which rows are idle * enough and safe to reap. * * OFF by default: a non-positive / undefined `idleReapAfterMs` disables the pass * entirely (it returns `enabled:false` and never touches a row) — the same * opt-in shape as eager resume-on-boot. * * SANDBOXED sessions (a box on a metered provider — e2b, …) get their own, * shorter threshold, `sandboxIdleReapAfterMs`: a finished turn never closes * the session, so an idle box otherwise lives until its provider lifetime * expires (observed: a dozen 4 vCPU / 8 GB boxes idling after finished * turns). Reaping such a row closes its `SandboxAgentSessionProxy`, which takes * a final checkpoint of the box's work and tears the box down per its * lifecycle policy (kill unless the spec asked to pause). A sandboxed row * counts as idle only when it is ALSO not blocked on a command/sub-agent/ * background task and has no live child session. A non-sandbox session keeps * the general `idleReapAfterMs` rules unchanged. A sandboxed row whose spec * declared `lifecycle.pause_after_idle` (`desc.sandboxPauseAfterIdleMs`) is * reaped after that window instead, when it is the shorter one. */ /** Tally of one idle-reap sweep, for the periodic log line + tests. */ interface IdleReapSummary { /** Whether the pass actually ran. False when `idleReapAfterMs` is * non-positive/undefined (the knob is off) — the pass short-circuits and * every count is 0. Distinguishes "ran, found nothing idle" from "disabled". */ enabled: boolean; /** Rows that matched the reap policy — the sweep's candidate set. */ candidates: number; /** Rows actually reaped (`reapIdle` returned true). */ reaped: number; /** The reaped ids, for the sweep's summary log line. */ ids: string[]; } /** The slice of the sessions registry the reaper needs: enumerate every row * (including archived, so a depth>0 child's parent is reachable even if the * parent was archived) and reap one by id. Structural so the pass is a pure, * unit-testable function decoupled from the full registry surface — same shape * discipline as `OrphanReaperRegistry`. */ interface IdleReaperRegistry { list(opts?: { includeArchived?: boolean; }): readonly SessionDescriptor[]; reapIdle(id: string, idleMs?: number): boolean; } /** Default `daemon.sandboxIdleReapAfterMs`: a sandboxed session idle this long * loses its box (15 min). Unlike the general knob this one is ON by default — * an idle box is a billed 4 vCPU / 8 GB VM, and the reaped session stays * revivable on a fresh box. */ declare const DEFAULT_SANDBOX_IDLE_REAP_AFTER_MS: number; /** * Run one idle-reap sweep. Pure over the injected `now` (ms epoch), so a test * pins a fake clock and asserts deterministically. Returns the tally; the * caller (the gateway's periodic ticker) turns it into a one-line log per * sweep. */ declare function runIdleReapPass(opts: { registry: IdleReaperRegistry; /** Reap agent-cli sessions idle longer than this many ms. Non-positive / * undefined ⇒ this rule is OFF (the pass as a whole is disabled only when * `sandboxIdleReapAfterMs` is off too). */ idleReapAfterMs: number | undefined; /** Shorter threshold for SANDBOXED sessions (see module doc). Non-positive / * undefined ⇒ sandboxed rows fall back to `idleReapAfterMs`. When both are * on, a sandboxed row is reaped at the shorter one. */ sandboxIdleReapAfterMs?: number; /** Injected clock (ms since epoch). Defaults to `Date.now`. */ now?: () => number; /** Cross-process gate (mirrors the eager pass §5): with two daemons sharing * the workspace buckets, each reaps only rows for the workspace IT serves. * Return false to exclude a row. Omitted ⇒ every row is served. */ isServed?: (desc: SessionDescriptor) => boolean; /** True when the session requested an approval that is pending, or approved * and not consumed (`sessionHoldsApproval`). Such a session is never reaped: * its Bureau tab renders the approval card. Omitted ⇒ no session holds one. */ holdsApproval?: (sessionId: string) => boolean; }): IdleReapSummary; /** * Crash-detect sweep (PR-1 of the crash-detect chantier). * * Agent-cli sessions keep their adapter child alive between turns (by * design, for multi-turn continuity). If that child dies OUTSIDE a turn — * OOM-killed, segfaulted, `kill -9`'d out of band — nothing observes the * death: there's no turn in flight to throw, so the descriptor keeps lying * `status:"running"` until the next prompt's RPC fails. A parked session * with no next prompt never gets that chance; the crash is silent forever. * * The same is true one layer up, for a reason a pid probe can never catch: * an ACP wrapper's PROCESS can outlive its own JSON-RPC stream. The stream * ends, `process.kill(pid, 0)` keeps succeeding, and the row reports * `running`/`alive: true` while every prompt rejects "ACP connection * closed". So this pass probes BOTH axes — process liveness AND transport * liveness (`adapterConnected`, from the live session's `isConnected()`). * * This pass sweeps the registry, finds agent-cli sessions provably dead on * either axis, and MARKS them crashed (`registry.markCrashed`): flips the row to * `error`/`endedReason:"crashed"`, records a short `lastError`, and clears * the dead binding so the row stays lazy-resumable — same shape as * idle-reaper's `reapIdle`, except this pass is DISCOVERING a death that * already happened rather than causing one. * * DETECTION AND SURFACING ONLY (this PR). No auto-restart, no supervisor * notification — those are later PRs; see BRIEF.md. * * The crash ACTION and its invariants (agent-cli-only, running-only, * clear-the-binding-so-it-stays-resumable, emit `session:exited`) live * behind `registry.markCrashed`. This module owns only the POLICY: which * rows are provably dead and safe to mark. * * OFF by default: a non-positive / undefined `crashDetectIntervalMs` * disables the pass entirely (it returns `enabled:false` and never touches a * row) — same opt-in shape as idle-reaper, even though the gateway wires * this pass DEFAULT-ON (see index.ts) since detection is non-destructive * observability. */ /** Tally of one crash-detect sweep, for the periodic log line + tests. */ interface CrashDetectSummary { /** Whether the pass actually ran. False when `crashDetectIntervalMs` is * non-positive/undefined (the knob is off) — the pass short-circuits and * every count is 0. Distinguishes "ran, found nothing crashed" from * "disabled". */ enabled: boolean; /** Rows that matched the crash policy — the sweep's candidate set. */ candidates: number; /** Rows actually marked crashed (`markCrashed` returned true). */ crashed: number; /** The crashed ids, for the sweep's summary log line. */ ids: string[]; } /** The slice of the sessions registry the crash-detect pass needs: enumerate * every row (including archived, for parity with idle-reaper's scan) and * mark one crashed by id. Structural so the pass is a pure, unit-testable * function decoupled from the full registry surface. */ interface CrashReaperRegistry { list(opts?: { includeArchived?: boolean; }): readonly SessionDescriptor[]; markCrashed(id: string, reason?: SessionCrashReason): boolean; } /** * Run one crash-detect sweep. Pure over the registry's own freshly-probed * `processAlive` (stamped by `list()` at read time — no clock injection * needed here, unlike idle-reaper, since crash policy isn't time-based). * Returns the tally; the caller (the gateway's periodic ticker) turns it * into a one-line log per sweep. */ declare function runCrashDetectPass(opts: { registry: CrashReaperRegistry; /** Mark agent-cli sessions whose process is confirmed dead. Non-positive / * undefined ⇒ the pass is DISABLED. (The gateway wires a sane default * interval so this is default-on in practice — see index.ts.) */ crashDetectIntervalMs: number | undefined; /** Cross-process gate (mirrors idle-reaper's §5): with two daemons sharing * the workspace buckets, each sweeps only rows for the workspace IT * serves. Return false to exclude a row. Omitted ⇒ every row is served. */ isServed?: (desc: SessionDescriptor) => boolean; }): CrashDetectSummary; /** * Turn-liveness watchdog (turn-liveness-watchdog chantier). * * Agent-cli sessions report `status:"running"` for the entire life of a * turn, and nothing else observes the adapter's event stream directly. When * that stream dies mid-turn — a network drop, a hung child, zero frames * ever again — nothing throws: there's no RPC failure to catch, just * silence. The descriptor keeps lying `status:"running"`, `lastError:null`, * `blockedOn:undefined` — identical to a session doing genuine, healthy * long work. A supervisor only catches it by manually comparing * `lastActivityAt` to the clock (the live incident this chantier exists * for: `sess_0b94542f`, `lastActivityAt` frozen 36 minutes into a turn with * no other signal). * * This pass sweeps the registry, finds agent-cli sessions that are BUSY * (mid-turn), NOT legitimately `blockedOn` a subagent/command (a real * long-running tool call is expected to go quiet — that's not the failure * mode this catches), and silent past a threshold, and FLAGS them * (`registry.markStalled`): stamps `stalledSinceMs` and emits * `session:stalled` — same shape discipline as `crash-reaper.ts` / * `idle-reaper.ts`, except conservative by design: a `blockedOn` row is * NEVER a candidate, no matter how long it's been silent, because a slow * build and a dead stream are indistinguishable from `lastActivityAt` * alone once a tool call is legitimately in flight. The predicate is * deliberately biased toward missing a genuinely-dead-but-blocked stream * over false-positiving a healthy long tool call. * * DETECTION AND SURFACING ONLY. No auto-kill, no auto-restart — those are * later work, if ever; see AGENTS.md's "definition of done" for why this * pass stops at a signal. * * The trip/clear ACTIONS and their invariants (agent-cli-only, running-only, * busy-only, unblocked-only, idempotent, emit `session:stalled` / * `session:stall-cleared`) live behind `registry.markStalled` / * `registry.clearStalled`. This module owns only the POLICY: which rows have * gone silent long enough mid-turn to be worth flagging. Clearing on * recovery is event-driven (pulseActivity / turn start / turn finally in * sessions.ts), NOT this sweep's job — the sweep only ever adds the flag, * it never removes one, so a row already flagged is simply excluded from * the next sweep's candidate set until something clears it. * * OFF by default in the sense that a non-positive / undefined * `turnStallAfterMs` disables the pass entirely (it returns `enabled:false` * and never touches a row) — same opt-in shape as crash-detect and * idle-reap. Like crash-detect, the gateway wires a sane default threshold * so this is DEFAULT-ON in practice (see index.ts): detection is * non-destructive observability, so the bar for shipping it enabled is * lower than for anything that touches a live process. */ /** Tally of one stall-watchdog sweep, for the periodic log line + tests. */ interface StallWatchdogSummary { /** Whether the pass actually ran. False when `turnStallAfterMs` is * non-positive/undefined (the knob is off) — the pass short-circuits and * every count is 0. Distinguishes "ran, found nothing stalled" from * "disabled". */ enabled: boolean; /** Rows that matched the stall policy — the sweep's candidate set. */ candidates: number; /** Rows actually flagged stalled (`markStalled` returned true). */ stalled: number; /** The flagged ids, for the sweep's summary log line. */ ids: string[]; } /** The slice of the sessions registry the watchdog needs: enumerate every * row (including archived, for parity with idle-reaper's / crash-detect's * scan shape; archived rows are never `running` anyway so the predicate * excludes them regardless) and flag one stalled by id. Structural so the * pass is a pure, unit-testable function decoupled from the full registry * surface. */ interface StallWatchdogRegistry { list(opts?: { includeArchived?: boolean; }): readonly SessionDescriptor[]; markStalled(id: string, stalledSinceMs: number): boolean; } /** * Run one stall-watchdog sweep. Pure over the injected `now` (ms epoch), so * a test pins a fake clock and asserts deterministically. Returns the * tally; the caller (the gateway's periodic ticker) turns it into a * one-line log per sweep. */ declare function runStallWatchdogPass(opts: { registry: StallWatchdogRegistry; /** Flag agent-cli sessions mid-turn and silent longer than this many ms. * Non-positive / undefined ⇒ the pass is DISABLED. (The gateway wires a * sane default so this is default-on in practice — see index.ts.) */ turnStallAfterMs: number | undefined; /** Injected clock (ms since epoch). Defaults to `Date.now`. */ now?: () => number; /** Cross-process gate (mirrors idle-reaper's / crash-detect's §5): with * two daemons sharing the workspace buckets, each sweeps only rows for * the workspace IT serves. Return false to exclude a row. Omitted ⇒ * every row is served. */ isServed?: (desc: SessionDescriptor) => boolean; }): StallWatchdogSummary; /** * Turns a raw tool-call name + args (and its eventual result) into a short, * human-readable line for ring-buffer / CLI / transcript rendering. Without * this, every tool call renders as a bare `[tool] view` with no args and no * outcome — this module is the one place that knows how to summarize both. */ /** A one-line human summary of a tool call, e.g. `read src/foo.ts` or `⏰ wake in 30s — checking CI`. */ declare function formatToolCall(toolName: string, args: unknown): string; /** * A short outcome line for a completed tool call, or `null` when there's * nothing useful to show (e.g. an empty/void result). `toolName` is * accepted for parity with `formatToolCall` and future bespoke result * formatting, but generic text extraction covers today's cases. */ declare function formatToolResult(toolName: string | undefined, result: unknown, isError: boolean): string | null; /** * Pure sizing helper for a `tools/list` response — shared by * `scripts/measure-mcp-tools.mjs` (human-readable before/after report) and * the budget-guard test (`__tests__/tool-schema-budget.test.ts`) so both * measure the exact same thing: the JSON bytes an MCP client actually pays * for per tool (`description` + `inputSchema`), sorted biggest first. */ interface MeasuredToolEntry { name: string; bytes: number; } interface ToolListMeasurement { entries: MeasuredToolEntry[]; totalBytes: number; } interface MeasurableTool { name: string; description?: string; inputSchema?: unknown; } /** UTF-8 byte size of the `{description, inputSchema}` JSON a client * receives for one tool — the same two fields `tools/list` sends over the * wire, so this tracks prompt-token cost rather than just character count. */ declare function measureTool(tool: MeasurableTool): number; declare function measureToolList(tools: readonly MeasurableTool[]): ToolListMeasurement; /** * Long-form MCP tool documentation, read from `docs/mcp-tools/.md`. * * The schema `description` on a tool/field is a contract: what it does, and * the one rule that prevents a wrong call — kept short so `tools/list` stays * cheap. Everything else (edge cases, interactions with other fields, * examples, history) lives here instead, fetched on demand by the `tool_help` * MCP tool (`tool-help-mcp.ts`) and the `agentproto help ` CLI verb * (`packages/cli/src/commands/help.ts`) — both call the two functions below, * so the markdown file is the single source both surfaces read. * * `docs/mcp-tools/` sits at the PACKAGE root (a sibling of `src`/`dist`, not * the repo-level `docs/`) so it ships inside the published npm tarball — * see the `files` array in `package.json`. Resolved relative to this * module's own directory rather than by package name: whether this code is * running from `src` (vitest, no build) or `dist` (built/published), the * module's directory is always a direct child of the package root, so one * `..` reaches it either way — no `require.resolve` needed. */ /** Full markdown help text for `name`, or `undefined` when no doc exists. */ declare function getToolHelp(name: string): string | undefined; /** Every tool name with a help doc available — for a "did you mean" list. */ declare function listToolHelpTopics(): string[]; /** Extract a `## ` section (case-insensitive) up to the next `##` * heading — shared by the `tool_help` MCP tool and the `agentproto help` * CLI verb so both slice a doc identically. `undefined` when no section * with that heading exists. */ declare function extractHelpSection(doc: string, topic: string): string | undefined; /** * Subtree usage rollup: one session's own usage plus the summed usage of * every session it (transitively) spawned — the shape `session_usage * { includeSubtree: true }` and `GET /sessions/:id/usage?includeSubtree=1` * return. * * Pure over a descriptor list (walked by `parentSessionId`, the same graph * `collectSubtree` uses for orchestrator scoping), so it's unit-testable * without a registry. * * Absent stays absent: a total is the sum of the sessions that REPORT the * field, and is omitted entirely when none of them do — a subtree of * cost-less sessions never reads as a measured $0. The same rule applies to * the per-child rows: a child carries its OWN cache / reasoning split when * it reports one, and omits the fields it doesn't. */ /** Summed usage across the root and all its descendants. */ interface SubtreeUsageTotals { /** Sessions counted, root included. */ sessions: number; costUsd?: number; tokensIn?: number; tokensOut?: number; cacheReadTokens?: number; cacheWriteTokens?: number; /** Reasoning tokens, rolled up like the cache split — omitted when no * session in the subtree reports them. */ reasoningTokens?: number; } /** One direct child of the root, with that child's OWN usage (its own * descendants roll up into `subtree`, not here). */ interface SubtreeChildUsage { id: string; label?: string; status: SessionDescriptor["status"]; costUsd?: number; tokensIn?: number; tokensOut?: number; /** The child's own cache split, so a child row carries the same token * detail `self` does. Absent when the child reports none. */ cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; } interface SessionUsageWithSubtree { self: SessionUsage; subtree: SubtreeUsageTotals; children: SubtreeChildUsage[]; } /** * Roll `root`'s usage up over its subtree. `all` should be the FULL * descriptor list (archived included) so an archived intermediate session * doesn't sever the parent→child chain. */ declare function rollupSessionSubtree(root: SessionDescriptor, all: readonly SessionDescriptor[]): SessionUsageWithSubtree; /** * Projection of a REMOTE daemon's `session_usage` answer onto the local * descriptor's usage fields. * * A sandboxed session runs inside a box that has its own daemon, so its * usage is read back over the wire: the box's `session_usage` tool answers * with model / cost / token counts / context window, and the HOST projects * that answer onto its own descriptor (the `readUsage` hook every adapter * reader implements). * * The cache split (`cacheReadTokens` / `cacheWriteTokens` / * `reasoningTokens`) rides along: the box's answer reports it (claude-code's * transcript reader, hermes' state.db), and dropping it here would leave a * sandboxed session with input/output tokens but no cache split — a * half-usage row that reads as "measured" while the cache half is missing. * * Every field is forwarded only when the remote side actually reported it, so * an absent split stays ABSENT — never a measured 0. */ /** * The remote daemon's `session_usage` answer, widened with the cache split. * * `SessionUsageSnapshot` (packages/harness) predates the cache split and * doesn't declare these fields, but the remote `session_usage` tool DOES * return them — they just aren't in the harness's type. Read them through * this widened shape. */ type RemoteUsageSnapshot = { model?: string; costUsd?: number; tokensIn?: number; tokensOut?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; }; /** * Project a remote `session_usage` answer onto the local usage fields. * * Returns null when the remote side reported nothing at all — the reader * hook's "nothing measured" signal. */ declare function projectRemoteUsage(snap: RemoteUsageSnapshot): UsageReadResult | null; /** * Shared disk-read + descriptor-join for the usage-rollup surfaces (the * `usage_rollup` MCP tool and the `GET /usage/rollup` REST route). Keeping the * collection in ONE place means the two surfaces can't drift on how they * enumerate sessions, resolve attribution keys, or tolerate a bad read. * * This is the impure companion to the pure `usage-rollup.ts` reducer: it * touches the registry (which touches disk), where the reducer stays a * side-effect-free fold. Surfaces call `collectSessionSnapshots` to build the * `SessionSnapshots[]` and hand that straight to `rollupUsage`. */ /** * Best-effort enrich a rollup's `byProfile` entries with each profile's live * provider remaining quota. Pure over its inputs (returns a NEW rollup, never * mutates), and non-fatal by construction: * * - `"unknown"`/empty profileRefs are skipped (no real profile to query). * - an unresolvable profile is skipped. * - each `reader.readRemainingQuota` runs under `Promise.allSettled`, so one * rejection attaches no `remaining` and leaves every other entry intact. * - the whole fan-out is capped by `timeoutMs`; if the cap fires first the * ORIGINAL (un-enriched) rollup is returned. */ declare function enrichWithRemainingQuota(rollup: UsageRollup, opts: { reader: RemainingQuotaReader; resolveProfile: (profileRef: string) => QuotaReadableProfile | undefined; window: string; timeoutMs?: number; }): Promise; /** * Surface-shared, fully non-fatal wrapper both the `usage_rollup` MCP tool and * `GET /usage/rollup` call after `rollupUsage`. Instantiates the Anthropic * reader (side-effect-free unless `deps.probe` opts into a live refresh), * resolves the auth profiles once, and enriches — but if ANYTHING throws * (profile load, reader construction, enrichment) it returns the original * rollup untouched. The rollup NEVER depends on this succeeding. * * `deps` is injectable purely for tests; production passes nothing. */ declare function enrichRollupWithProviderQuota(rollup: UsageRollup, window: string, deps?: { reader?: RemainingQuotaReader; loadProfiles?: () => Promise; timeoutMs?: number; /** Opt in to a live provider refresh. Default false = side-effect-free * (last-seen store values only); the reporting read never makes a * provider call unless the caller explicitly asked. */ probe?: boolean; }): Promise; /** * Reader for durable `kind: "usage_snapshot"` transcript records — * mirrors `tool-call-log.ts` / `command-log.ts`. * * Snapshots are WRITTEN by `transcript-writer.ts`'s `recordUsageSnapshot` * (every turn-end and at exit, via the buffered per-session append stream) — * this module only reads them back. It converges on the same per-id path an * agent-cli session's structured transcript uses * (`sessionEventsPath(sessionId, baseDir)`), streams the JSONL line by line, * keeps only the `usage_snapshot` lines, and projects each to a * `UsageSnapshotRecord` (the pure rollup module's input shape). * * Streamed, never read whole: a transcript can be hundreds of MB, and * `collectSessionSnapshots` reads every agent-cli session's. Reading each one * into a single string and `JSON.parse`-ing every line made one rollup cost * the sum of the transcripts in heap (E99). A line that does not mention * `usage_snapshot` is skipped before any parse. * * "Absence is not an error", same convention as `readCommandLogEntry` / * `readToolCallRecords`: a missing/unreadable file returns `[]`, a read that * fails mid-stream returns the records parsed so far, and a single malformed * line is skipped rather than aborting the read. */ /** Read back every `usage_snapshot` line from one session's events.jsonl, in * on-disk order. Returns `[]` when the file is missing/unreadable or has no * such lines; skips any malformed or non-`usage_snapshot` line. Never throws. */ declare function readUsageSnapshots(sessionId: string, baseDir?: string): Promise; /** * PURE session-level report over a start-time window — "how many sessions * ran in the last 12h, by harness/model, how long, how much, which PRs, who's * still running". Companion to `usage-rollup.ts` but a different axis: that * module slices durable `usage_snapshot` DELTAS into a rolling spend window; * this module buckets whole SESSIONS by their own `startedAt`, using each * session's own (already cumulative-at-its-own-end) `costUsd`/tokens/duration * — simpler because a session's own total is never split across two windows. * Deliberately not reused from there: a different question ("what did this * session cost in total" vs "how much money moved in this window"). * * Pure: no fs, no `Date.now`, no side effects — the caller (service layer) * collects sessions off the registry/disk and stamps the wall clock. * * Two sections are NOT window-filtered by design: `activeSessions` and * `permanentAgents` answer "what's true right now", not "what happened in * the window" — a permanent agent started weeks ago should still show up. */ interface SessionReportOpenedPr { adapter: string; number: number; url: string; openedAt: string; } /** The fields the reducer needs, projected off whatever the caller's source * (live registry descriptor, cold sidecar) actually has. */ interface SessionReportInput { id: string; name?: string; label?: string; status: string; alive?: boolean; harness?: string; model?: string; startedAt: string; endedAt?: string; endedReason?: string; /** A number only when a price was actually computed (never fabricated — * see `UsageSource`'s "no-pricing"/"none" doctrine) — the priced/unpriced * signal for the cost bucketing below. */ costUsd?: number; tokensIn?: number; tokensOut?: number; /** Resolved billing mode (`SessionAuthEcho.mode`) — absent when no * credential resolved (every adapter besides claude-code, in practice). */ authMode?: "subscription" | "api-key"; keepAlive?: boolean; openedPrs?: readonly SessionReportOpenedPr[]; } interface SessionReportCountEntry { key: string; count: number; } interface SessionReportCostBucket { costUsd: number; tokensIn: number; tokensOut: number; /** Token deltas from sessions whose cost is unpriced (pin: never a * fabricated $0 — see `usage-rollup.ts`'s same doctrine). */ unpricedTokens: number; sessionCount: number; } interface SessionReportTopEntry { id: string; name?: string; harness?: string; model?: string; status: string; costUsd?: number; durationMs?: number; } interface SessionReportPrEntry { sessionId: string; sessionName?: string; adapter: string; number: number; url: string; openedAt: string; } interface SessionReportActiveEntry { id: string; name?: string; harness?: string; model?: string; status: string; startedAt: string; keepAlive?: boolean; } interface SessionReport { since: string; windowStart: string; now: string; totalSessions: number; byHarness: SessionReportCountEntry[]; byModel: SessionReportCountEntry[]; byStatus: SessionReportCountEntry[]; /** Keyed by the raw `endedReason` string (or `"unknown"` for a terminal * session with none, `"running"` is never a key here — see `byStatus`). */ byEndReason: SessionReportCountEntry[]; duration: { /** Wall-clock elapsed (`endedAt ?? now` minus `startedAt`), summed. A * still-running session counts its elapsed-so-far. */ totalMs: number; averageMs: number; sessionCount: number; }; cost: { subscription: SessionReportCostBucket; apiKey: SessionReportCostBucket; unknown: SessionReportCostBucket; total: SessionReportCostBucket; }; /** PRs opened by an in-window session. This is provenance ("opened during * the window"), not a live GitHub state check — confirming still-open * would mean one `gh`/API call per PR, which this pure/local reducer * deliberately does not make. */ openedPrs: SessionReportPrEntry[]; topByCost: SessionReportTopEntry[]; topByDuration: SessionReportTopEntry[]; /** Currently alive sessions — NOT window-filtered (see module doc). */ activeSessions: SessionReportActiveEntry[]; /** Alive sessions with `keepAlive: true` — NOT window-filtered. */ permanentAgents: SessionReportActiveEntry[]; } /** * Build the report. `sessions` is the FULL candidate set (not pre-filtered * by window) — `activeSessions`/`permanentAgents` deliberately read it * unfiltered; every other section filters to sessions whose `startedAt` * falls in `[now - since, now]` (via {@link parseTimeBound}'s vocabulary: * ISO-8601 or relative age like `"12h"`). */ declare function buildSessionReport(sessions: readonly SessionReportInput[], opts: { since: string; nowMs?: number; topN?: number; }): SessionReport; /** * Shared disk+registry collection for the `sessions_report` surfaces (the * MCP tool and `GET /sessions/report`), mirroring `usage-rollup-service.ts`'s * split between a pure reducer and an impure collector. Keeping this in one * place means the two surfaces can't drift on how they enumerate sessions. * * Merges the live registry (capped at `HISTORY_CAP` per bucket, see * `session-cold-list.ts`) with the cold on-disk rows it cannot hold, so a * `--since 24h` report on a busy host doesn't silently undercount. A live * row always wins over a same-id cold one. */ /** * Every `agent-cli` session the daemon knows about (live + cold), deduped by * id with the live row winning, projected to {@link SessionReportInput}. * `onlyIds` is the subtree scope a scoped orchestrator caller is restricted * to (same convention as `collectSessionSnapshots` in usage-rollup-service). */ declare function collectSessionReportInputs(registry: SessionsRegistry, opts?: { onlyIds?: Set; now?: number; }): SessionReportInput[]; /** Collect + reduce in one call — the common case for both surfaces. */ declare function buildSessionReportFromRegistry(registry: SessionsRegistry, opts: { since: string; nowMs?: number; topN?: number; onlyIds?: Set; }): SessionReport; /** * Pure tunnel-link helpers. * * A tunnel exposes a local port behind a public HTTPS origin (`desc.url`, or * `desc.publicUrl` for a `public:true` tunnel). The Telegram session-chat * miniapp (studio repo `services/telegram-session-chat-miniapp/src/server.ts`) * serves a per-session route at `/s/` on that origin, so the link * to hand a user is simply the tunnel URL with that path appended. * * Kept free of any I/O so it is trivially unit-testable and reusable from both * the daemon (the `app_tunnel` MCP tool) and the CLI. */ /** * Build the miniapp deep link for a session off a tunnel URL: * `/s/`. * * - A trailing slash on `tunnelUrl` is stripped so the result never contains * a doubled `//`. * - A query string / hash already on `tunnelUrl` (e.g. the access guard's * `?t=`) is preserved, and the `/s/` path is inserted * before it — the guarded URL stays usable. * - Throws for an empty `sessionId` or a `tunnelUrl` that is empty, not a * URL, or not `https:` — the miniapp route only exists on the HTTPS origin. */ declare function buildSessionLink(tunnelUrl: string, sessionId: string): string; /** * `app_tunnel` — the daemon-side realization of "the daemon creates the * tunnel for an app" (AIP-standardization Phase 2, Telegram miniapp surface). * * Given an installed app directory (or an explicit `targetPort`), create a * public tunnel for its `ui.port` through the same {@link TunnelRegistry} the * `tunnel_create` tool drives, then optionally hand back the miniapp session * deep link for it. * * Provider selection: * - default → `quick` (Cloudflare Quick Tunnel) with the private access * guard (the returned `url` is the signed link, not the bare host); * - `hostname` set → `cloudflare-named`, a STABLE hostname. The `tunnelId` / * `credentialsFile` are resolved from the daemon's own registered creds * (`~/.agentproto/tunnel-creds/cloudflare-named.json`, written by * `setup_tunnel_provider`) — the daemon holds the secrets; the caller * passes only the hostname. * * Never reads a secret from the environment or echoes one back. */ interface AppTunnelResult { tunnelId: string; url: string; provider: string; targetPort: number; name?: string; hostname?: string; sessionLink?: string; } /** * session-follow — wake a long-lived session (the FOLLOWER) when sessions it * did not necessarily spawn end a turn, await input, exit/crash, or get a PR * opened/merged. No polling: it hangs one `onAny` subscriber off the * in-process session event bus. * * Until now events only reached a parent (`supervisor-notify.ts`, * `notifyParentOnCrash`) or the owner of a PR sentinel. A follow is the * generic primitive: a SELECTOR (`sessionIds` / `all` / `cwdPrefix`, minus an * `exclude`) evaluated at EVENT time against the sessions that exist then, so * a session spawned later by anybody is covered automatically. * * Delivery mirrors `supervisor-notify.ts`: matched events are coalesced per * follower within `batchMs` into ONE daemon-attested system message * (`relation:"system"`, `kind:"notice"`, `urgency:"next-turn"`, or `"fyi"` per follow) through * `registry.sendMessage` — an idle follower runs it as its own turn now, a * busy one parks it in its prompt queue as a separate turn. It never * interrupts. The follower's own events are never delivered to itself, and * (by default) neither are its descendants'. * * Dead follower: first check whether a live replacement already exists — * either because the batch's follow(s) were re-pointed at a new follower * since the events were enqueued (`store.setFollower` / `upsert` by key), or * because the daemon's own lineage (`continuedTo`) already links to one — * and deliver the digest there instead of reviving anything. Only when no * replacement exists do we fall back to the `sentinel-runtime.ts` approach: * resume through the injected `restartSession` hook (never a * deliberately-closed one). Concurrent deliveries racing for the same dead * id share one in-flight revival, so a stale id is never resurrected twice. * Otherwise the digest parks in `~/.agentproto/follows-parked.jsonl` so the * events are not silently lost. The follow record is always kept. */ /** The slice of the sessions registry this subscriber needs (structural, like * `SupervisorNotifyRegistry`). */ interface SessionFollowRegistry { get(id: string): SessionDescriptor | undefined; sendMessage(msg: SessionMessage, opts?: { source?: string; origin?: string; coalesceKey?: string; digest?: QueuedDigest; merge?: (existing: QueuedPrompt) => { message: string; envelope?: SessionMessage; digest: QueuedDigest; }; }): Promise; } interface WireSessionFollowOptions { /** Injectable clock (tests). Default `Date.now`. */ now?: () => number; /** PR events older than this are ignored as catch-up. Default * {@link FOLLOW_STALE_EVENT_MS}. */ staleEventMs?: number; registry: SessionFollowRegistry; sessionEvents: SessionEventBus; store: SessionFollowStore; /** Resume a dead follower; resolves to the session id to deliver to. * Omitted → a dead follower's digest is parked. */ restartSession?: (sessionId: string) => Promise; /** Last assistant text of a session, for the digest excerpt. Default: the * tail of its `events.jsonl`. */ readLastOutput?: (desc: SessionDescriptor) => string | undefined; /** Injectable timers (tests). Default: global `setTimeout`/`clearTimeout`, * resolved at call time so vitest fake timers apply. */ setTimer?: (fn: () => void, ms: number) => unknown; clearTimer?: (handle: unknown) => void; /** Parked-digest journal (tests). Default `~/.agentproto/follows-parked.jsonl`. */ parkedPath?: string; /** Daemon-level triage default (what `config.follow.triage` resolves to). * A follow's own `triage` block overrides it. Triage is OFF by default: * with it off nothing about delivery changes. A FUNCTION is re-read * before every digest (the daemon passes the live config resolver). */ triage?: FollowTriageConfig | (() => FollowTriageConfig | Promise); /** Daemon-level delivery-apply switch (`config.delivery.apply`). A * follow's own `triage.enabled` is the per-subscription override; the * daemon `follow.triage.enabled` still means "apply every type". A * FUNCTION is re-read before every digest. */ apply?: DeliveryApplyConfig | (() => DeliveryApplyConfig | undefined | Promise); /** Append-only delivery ledger (tests). Default * `~/.agentproto/delivery-ledger.jsonl`. */ ledgerPath?: string; /** Classifier registry used for the observation-only (triage off) level. * Defaults to one `session-lifecycle` classifier closing over the follow * facts; tests pass an EMPTY registry to prove a floor alone pins level 3. */ classifierRegistry?: ClassifierRegistry; /** Classifiers to register instead of the built-in session-lifecycle one. * `[]` is the same as an empty registry. */ classifiers?: readonly Classifier[]; /** Extra facts the triage rules need but the engine cannot see alone (e.g. * "did this session's cron run finish OK?"). */ triageFacts?: TriageFacts; /** Resolve, at EVENT time, whether a non-crashed exit is informational * rather than a wake. Called once per exit with the descriptor captured * then, so a later delete or rename cannot change the outcome. */ sourceUrgency?: (desc: SessionDescriptor) => "fyi" | undefined; log?: (line: string) => void; } interface SessionFollowHandle { /** Deliver every pending batch now (or just `followerId`'s). Resolves once * the deliveries settled. */ flush(followerId?: string): Promise; /** Redeliver parked digests whose follower is alive again. With a session * id: only entries parked for it (call it when that follower respawns). * Without: every entry whose follower currently accepts delivery. Resolves * to the number redelivered. */ replayParked(followerId?: string): Promise; /** Unsubscribe and drop pending batches (shutdown). */ dispose(): void; } declare function wireSessionFollow(opts: WireSessionFollowOptions): SessionFollowHandle; /** * SSRF-guarded outbound HTTPS POST for webhook egress (W-A of * `.plans/sentinel-mcp-events/PLAN.md`). * * Frozen failure-mode reasons: `non_https | private_target | redirect | * timeout | connect` — mapped by challenge to the §3 ChallengeFailureReason * table; the SAME function guards BOTH the challenge and delivery path (I3). * No HTTP client library addition: node http/https only. * * Safety model (one predicate, fail closed): * 1. scheme must be https → `non_https` * 2. ALL DNS-resolved addresses (A + AAAA, plus literal-IP hosts) must pass * {@link isPubliclyRoutable}, else `private_target` — one rejected * address fails; unparseable/odd literals fail closed * 3. connect pins the VALIDATED IP (no second resolution → the * DNS-rebinding TOCTOU is closed) while `servername` keeps the ORIGINAL * hostname for TLS SNI + certificate verification * 4. redirects are never followed: a 3xx comes back as a plain * `{status: 3xx}` result (challenge → "non_2xx", delivery → retryable); * a non-https redirect target additionally throws `redirect` * 5. hard `timeoutMs` budget; request body clamped to 256 KiB here too * (defense-in-depth — delivery clamps before signing) */ type SsrfFetchReason = "non_https" | "private_target" | "redirect" | "timeout" | "connect"; declare class SsrfFetchError extends Error { readonly reason: SsrfFetchReason; constructor(reason: SsrfFetchReason, message: string); } interface SsrfFetchInit { method?: "POST"; headers?: Record; /** ≤ 262 144; enforced also on response read (only status + body read). */ body?: Uint8Array; timeoutMs: number; } interface SsrfFetchResult { status: number; body: string; } /** * The one predicate for every address this module may connect to. Fails * closed — anything unparseable, IPv4-mapped with an invalid embedded v4, or * inside a non-globally-routable block is NOT public. * * Plan §4 W-A.2 ranges: * IPv4 — 0/8, 10/8, 127/8, 169.254/16, 172.16/12, 192.0.0.0/24, * 192.0.2.0/24, 198.18/15, 198.51.100.0/24, 203.0.113.0/24, * 100.64/10 (CGNAT), 224/4 (multicast), 240/4 (reserved) * IPv6 — ::, ::1, fc00::/7 (ULA), fe80::/10 (link-local), * ff00::/8 (multicast), 2001:db8::/32 (doc range), and ::ffff: * mapped-v4 whose EMBEDDED v4 re-runs this very predicate */ declare function isPubliclyRoutable(ipRaw: string): boolean; type SsrfResolvers = { /** Replaces both A and AAAA resolution. Returns every address, any family. */ lookup?: (host: string) => Promise>; }; type EgressDispatcher = (req: { url: string; headers: Record; body?: Uint8Array; timeoutMs: number; }) => Promise; /** vitest-only: set a recording dispatcher; pass `null` to restore. */ declare function setEgressDispatcherForTests(dispatcher: EgressDispatcher | null): void; declare function ssrfFetch(url: string, init: SsrfFetchInit, io?: { resolvers?: SsrfResolvers; }): Promise; /** * Callback challenge verification (W-A of `.plans/sentinel-mcp-events/PLAN.md`, * §3 frozen): POST `{"type":"verification","challenge":""}` to * the candidate callback URL, signed with the CANDIDATE secret, carrying * `X-MCP-Subscription-Id`; require 2xx and a constant-time-equal * `{"challenge":""}` echo in the response body. * * Success cache: keyed (principal, normalized callback URL, sha256(secret)), * bounded TTL 10 min. A NEW secret during rotation NEVER resolves a cache * hit — the sha256(secret) key component structurally forces * re-verification (the cache can never bless an unverified secret). * * The outbound POST runs through the SAME `ssrfFetch` gate as delivery (I3) — * injectable here only for tests; production passes nothing. */ type ChallengeOutcome = { ok: true; verificationBytes: Uint8Array; } | { ok: false; reason: ChallengeFailureReason; detail: string; }; type ChallengeFailureReason = "challenge_failed" | "timeout" | "non_https" | "ssrf_blocked" | "non_2xx"; interface VerifyCallbackInput { principal: string; url: string; subscriptionId: string; secret: string; } interface VerifyCallbackDeps { /** Replaces the POST boundary. Default: the shared `ssrfFetch` gate. */ fetch?: (url: string, init: SsrfFetchArgs$1) => Promise; /** Clock for the bounded TTL. Default: real wall clock. */ now?: () => number; } interface SsrfFetchArgs$1 { method?: "POST"; headers?: Record; body?: Uint8Array; timeoutMs: number; } interface SsrfFetchView { status: number; body: string; } /** §4 W-A task 4: the challenge reason table (single mapped, none unmapped). */ declare function challengeReasonForSsrf(reason: SsrfFetchReason): ChallengeFailureReason; declare function challengeCacheSize(): number; /** vitest-only: clear the success cache between suites. */ declare function resetChallengeCacheForTests(): void; /** Cache-key URL normalization (never reused for anything else). */ declare function normalizeCallbackUrl(url: string): string | null; declare function verifyCallback(input: VerifyCallbackInput, deps?: VerifyCallbackDeps): Promise; /** * Signed event delivery with bounded retry (W-A of * `.plans/sentinel-mcp-events/PLAN.md`, §3 frozen). * * I2 — the body is serialized ONCE: the clamp (when needed) happens first, * then the exact bytes are signed per attempt with a FRESH timestamp. An * observer sees a different `webhook-signature` header per attempt while the * body bytes stay bitwise identical — `signWebhook` returns ONLY headers and * never re-serializes. * * ≤ 256 KiB — when the serialized body exceeds 262 144 bytes, `data` is * replaced with `{summary, subject}` and the envelope gains `truncated: true` * (no read tool — plan §5), and the CLAMPED bytes (not the original) are what * every attempt signs. * * Retry — exponential backoff bounded to 5 attempts; 3xx / other 4xx / 5xx / * network errors retry; 410/413 are terminal with NO further attempt; * 2xx = delivered. The returned `DeliveryState` is what the caller persists * into the store for post-restart resume (W-B's job to wire). */ type McpEventEnvelope = { /** OpenAI doc wire shape VERBATIM (developers.openai.com/plugins/build/mcp-events): * `eventId` (NOT `id` — the `webhook-id` header carries eventId), `name`, * `timestamp`, `data`, `cursor`. A top-level `type` field = protocol * control notification only — never sent by us (no control events). */ eventId: string; name: string; timestamp: string; data: Record; cursor: string | null; truncated?: boolean; }; interface DeliveryState { attempts: number; lastError?: string; lastAt?: string; } interface DeliveryReplay { subId: string; callbackUrl: string; secrets: readonly string[]; } /** One event → one POST. Frozen §3 outcome. */ type DeliveryOutcome = { ok: true; delivery: DeliveryState; } | { ok: false; reason: string; delivery: DeliveryState; }; interface SsrfFetchArgs { method?: "POST"; headers?: Record; body?: Uint8Array; timeoutMs: number; } interface DeliverEventDeps { /** Replaces the POST boundary (tests only). Default: the shared `ssrfFetch` gate. */ fetch?: (url: string, init: SsrfFetchArgs) => Promise<{ status: number; body: string; }>; /** Backoff sleep (tests only). Default: real `setTimeout`. */ sleep?: (ms: number) => Promise; /** Clock (tests only). Default: real wall clock. */ now?: () => number; /** Observability hook: one call per attempt outcome. Carries NO url, body or * secret — only the attempt number, HTTP status / redacted error reason, * and whether the attempt ended the delivery (`delivered`/`dead`) or will * be retried. A throwing hook never affects delivery. */ onAttempt?: (info: DeliveryAttemptInfo) => void; } interface DeliveryAttemptInfo { attempt: number; /** HTTP status when the receiver answered. */ status?: number; /** Redacted failure reason (no URL) when there is no usable status. */ error?: string; outcome: "delivered" | "retry" | "dead"; } declare const CLAMP_LIMIT_BYTES = 262144; declare const MAX_ATTEMPTS = 5; /** Bounded exponential backoff: 250, 500, 1000, 2000, capped at 4000 (attempt ≥ 4). */ declare function deliveryBackoffDelay(attempt: number): number; declare function serializeEnvelope(envelope: McpEventEnvelope): Uint8Array; /** Serialize once; over-size → `{summary, subject}` + `truncated:true` (§3). */ declare function envelopeClampedBytes(event: McpEventEnvelope): { bytes: Uint8Array; clamped: boolean; }; declare function deliverEventEnvelope(replay: DeliveryReplay, event: McpEventEnvelope, deps?: DeliverEventDeps): Promise; /** * MCP Events registry (W-C of `.plans/sentinel-mcp-events/PLAN.md`, §2/§3). * * One object per provider scheme. Every registration carries the WIRE * `EventDefinition` (name / description / `delivery:["webhook"]` / * `inputSchema` / `payloadSchema` — official doc verbatim, no extra fields) * PLUS the internal `InternalEventMeta`. Two fields on the meta are * MANDATORY by type: `argumentsToMatch` (the missing link between * `document_id`-style subscription args and `SentinelSpec.match`) and * `authorize`. A registration that omits either does not compile. * * `replayable` is INTERNAL only (it drives `cursor:null` for v1) and must * never appear on the wire — the §3 `EventDefinition` has no such field. * * Day-1 scheme: `github`. The definitions are derived from the ACTUAL event * types the providers declare/emit in `sentinel-providers/` (verified with * `rg 'github\.' packages/runtime/src/sentinel-providers`) — NOT from the * illustrative names in the plan's task text. See `GITHUB_SCHEME` below. */ declare const PRINCIPAL_BRAND: unique symbol; /** * The authenticated caller of a native MCP `events/*` call. REALITY (plan * §1): the root `/mcp` transport authenticates with ONE daemon bearer (or * trusted loopback) and exposes only an optional `callerSessionId` — there is * no per-caller auth-profile principal yet. So v1 has exactly two * constructors; a future W-F multi-tenant widening touches this one file. */ type Principal = string & { readonly [PRINCIPAL_BRAND]: true; }; declare function daemonBearerPrincipal(): Principal; declare function sessionPrincipal(sessionId: string): Principal; interface EventDefinition { name: string; description: string; delivery: ["webhook"]; inputSchema: object; payloadSchema: object; } /** What `argumentsToMatch` produces: explicit Sentinel match clauses plus the * provider slug that can emit the event. `ok:false` becomes `-32602` with a * definition-specific reason. */ type ArgumentsResult = { ok: true; matchClauses: SentinelMatchClause[]; providerSlug: string; } | { ok: false; reason: string; }; interface InternalEventMeta { /** INTERNAL: drives `cursor:null` vs a provider cursor. v1 is all-false. */ replayable: boolean; /** Map `inputSchema`-validated args to explicit match clauses (pure). */ argumentsToMatch: (args: Record) => ArgumentsResult; /** Authorization gate for the given principal. */ authorize: (args: Record, principal: Principal) => boolean; } interface EventRegistration { definition: EventDefinition; meta: InternalEventMeta; } interface SchemeRegistry { scheme: string; events: EventRegistration[]; } /** Validate subscription args against a definition's `inputSchema`. */ declare function validateAgainstInputSchema(schema: object, args: unknown): { ok: true; } | { ok: false; reason: string; }; /** * The day-1 github scheme. Types are the ACTUAL `github.*` strings emitted by * `sentinel-providers/local-gh.ts` (the zero-infra provider the plan names): * - github.pull_request.closed * - github.pull_request.synchronize * - github.pull_request_review.submitted * - github.check_suite.completed * * The plan's illustrative `github.pull_request.opened` and * `github.build.failed` do NOT exist in `sentinel-providers/` (opened is only * producible by the push `webhook` provider's normalizer; build.failed exists * nowhere — the closest real signal is `github.check_suite.completed` with * `data.conclusion === "failure"`). Per the plan's own instruction to surface * actual declared values, only real types ship — no fabricated definition. * * `local-gh`'s `defaultTypes()` also lists `github.workflow_run.completed` and * `github.issue_comment.created`, but its poll implementation does not emit * them (documented in `local-gh.ts`); shipping them here would advertise * subscriptions that can never fire, so they are intentionally omitted. */ declare const GITHUB_SCHEME: SchemeRegistry; /** Every registered scheme. Adding a scheme = one object + one test row. */ declare const EVENT_REGISTRY: readonly SchemeRegistry[]; /** The schemes a principal may discover/subscribe to. v1: single tenant, all. */ declare function tenantScope(_principal: Principal): readonly SchemeRegistry[]; /** Look up a registration by official wire name (all schemes). */ declare function findEventDefinition(name: string): EventRegistration | undefined; /** * MCP Events adapter (W-C of `.plans/sentinel-mcp-events/PLAN.md`, §2/§3). * * Three methods over the existing Sentinel core — `events/list`, * `events/subscribe`, `events/unsubscribe`. This module owns the subscription * lifecycle; the transport (native JSON-RPC methods + `events:{}` in * `server/discover`) lives in `@agentproto/mcp-server` and is wired in * `runtime/index.ts`. * * INVARIANTS v1 (plan §2, code-verified): * - every event is NON-REPLAYABLE → `cursor` is always `null`; subscribe * results carry `truncated: false`, events never set `truncated`; * - no `read` tool, no separate package, no batching. * * Subscription ids are deterministic (`subscription-id.ts`): subscribe upserts * on identity, unsubscribe RECOMPUTES the id (never an id-lookup). The store * has no CAS and `create()` silently overwrites, so every mutation is * serialized behind an in-process async mutex. */ declare const DEFAULT_TTL_MS: number; declare const MAX_TTL_MS: number; /** Store minimum lifetime — prevents churn-refresh for a tiny requested TTL. */ declare const MIN_TTL_MS: number; /** * `refreshBefore` is the GRANTED EXPIRATION itself (`until.ms` as ISO-8601), * per the official doc — never a pre-expiry hint. `until:{kind:"never"}` * (only granted for `ttlMs: null`) yields `null`. */ declare function computeRefreshBefore(until: SentinelUntil): string | null; /** * `ttlMs` mapping (§2): * omitted → default 7d; * number → grant `min(requested, 30d)`, floored at 60s; * null → `until:{kind:"never"}` (no expiration). */ declare function untilForTtl(ttlMs: number | null | undefined, now: number): SentinelUntil; /** * An error the native-method transport surfaces verbatim as a JSON-RPC error: * the SDK's request path copies `code` and `data` straight onto the error * response, so no transport-side catch is needed. */ declare class McpEventsError extends Error { readonly code: number; readonly data?: Record; constructor(code: number, message: string, data?: Record); } interface EventsListRequest { cursor?: string; pageSize?: number; } interface EventsListContext { principal: Principal; } interface EventsListResult { events: EventDefinition[]; nextCursor: string | null; } interface EventsSubscribeInput { name: string; arguments: Record; delivery: { mode: "webhook"; url: string; secret: string; }; ttlMs?: number | null; /** Refresh/replay handle (null on first subscribe). v1 ignores it: all * events are non-replayable, so it never changes the returned cursor. */ cursor?: string | null; } interface EventsSubscribeContext { principal: Principal; store: SentinelStore; resolveProvider: (slug: string) => Promise; nowMs?: () => number; /** DI seam (tests): replaces `verifyCallback`'s POST boundary. */ verify?: typeof verifyCallback; activeIntervalMs?: number; } interface EventsSubscribeResult { id: `sub_${string}`; refreshBefore: string | null; cursor: string | null; truncated?: boolean; } interface EventsUnsubscribeInput { name: string; arguments: Record; delivery: { mode: "webhook"; url: string; }; } interface EventsUnsubscribeContext { principal: Principal; store: SentinelStore; resolveProvider: (slug: string) => Promise; /** Persisted remote-cancel store. Present ⇒ unsubscribe records a tombstone * keyed by provider + remote id, drops the local row (delivery eligibility * ends immediately) and lets the sweep converge an unreachable remote. */ tombstones?: CancelTombstoneStore; } declare function eventsList(r: EventsListRequest, ctx: EventsListContext): Promise; declare function eventsSubscribe(input: EventsSubscribeInput, ctx: EventsSubscribeContext): Promise; declare function eventsUnsubscribe(input: EventsUnsubscribeInput, ctx: EventsUnsubscribeContext): Promise<{}>; /** * CloudEvents `SentinelEvent` → the MCP Events wire envelope (official doc * verbatim): `id→eventId`, `type→name`, `time→timestamp`, `data→data` (plus * the `subject`/`summary` projection so the 256 KiB clamp's `{summary, * subject}` replacement never goes blind), and `cursor: null` (v1 * non-replayable). No top-level `type` — that field is reserved for protocol * control notifications we never send. */ declare function toMcpEvent(event: SentinelEvent): McpEventEnvelope; /** * Deterministic MCP Events subscription ids (W-C of * `.plans/sentinel-mcp-events/PLAN.md`, §3 frozen). * * The id is a pure function of the subscription IDENTITY — authenticated * principal + normalized callback URL + event name + subscription arguments — * so the SAME logical subscription always lands on the SAME id. That is what * makes `events/subscribe` idempotent (upsert, never duplicate) and lets * `events/unsubscribe` recompute the id instead of trusting a caller-supplied * one. * * Hashing input is RFC 8785 (JCS) canonical JSON: recursive key sort by * UTF-16 code units, ECMAScript number serialization, Unicode minimization * (literal non-ASCII, control chars escaped). The `args` payload is trustless * input and nested objects are legal, so a plain `JSON.stringify` (key order * dependent) would let `{a:1,b:2}` and `{b:2,a:1}` mint two different * subscriptions for one logical watch — exactly the duplicate the doc warns * against. The canonical form is a single source of truth shared by subscribe * and unsubscribe. */ interface SubscriptionIdentity { /** Authenticated principal (`daemon-bearer` or `session:`). */ principal: string; /** Callback URL exactly as submitted (identity component; no normalization * beyond what the caller already applied — challenge caching normalizes * separately). */ callbackUrl: string; /** Official wire event name, e.g. `github.pull_request.closed`. */ eventName: string; /** Subscription arguments (JSON, nested objects legal). */ args: Record; } /** * RFC 8785 (JCS) canonical JSON over a JSON-legal value. Throws on values * JSON cannot carry (`undefined`, functions, non-finite numbers) rather than * silently coercing them — a trustless `args` payload must fail loudly, not * hash to a phantom identity. * * `JSON.stringify` already implements the JCS string and number rules for * well-formed JSON: ECMAScript shortest-round-trip number printing (`-0` → * `"0"`), control-char escaping, literal non-ASCII (Unicode minimization), * and `\uXXXX` for lone surrogates (ES2019 well-formed stringify). Only the * recursive object-key sort is added here. */ declare function canonicalizeJcs(value: unknown): string; /** `sub_` — sha256 over the JCS canonical identity, first 128 bits. */ declare function subscriptionId(identity: SubscriptionIdentity): `sub_${string}`; /** * Standard Webhooks `whsec_` signing for webhook egress (W-A of * `.plans/sentinel-mcp-events/PLAN.md`). * * Contract (frozen §3): * - HMAC-SHA256 over `msgId.timestamp.body` (raw bytes; `.update` chained so * the body is never re-encoded — payload arrives as `Uint8Array`, I2). * - Signature print = standard base64 (NOT base64url): `v1,`. * - HMAC key = the base64 payload DECODED after the `whsec_` prefix. * - Multi-secret: space-separated `v1,` segments (rotation window). * - Returns ONLY headers — the caller owns the bytes and signs them again * with a fresh timestamp on retry; signing never re-serializes. */ interface WebhookSignInput { /** Stable event id (`evt_…` / verification `msg_verification_…`) — same across retries. */ msgId: string; /** Seconds, Unix epoch (Standard Webhooks wire format). */ timestamp: number; /** Exact bytes — signed once (I2). Caller passes the serialization; signing never re-serializes. */ payload: Uint8Array; /** One or, during a rotation window, two secrets (`whsec_…`). */ secrets: readonly string[]; } type WebhookSignatureHeaders = { "webhook-id": string; "webhook-timestamp": string; "webhook-signature": string; }; /** * Encode raw secret bytes into the `whsec_` wire format. * Inverse of {@link decodeWhsecSecret}. */ declare function encodeWhsecSecret(raw: Uint8Array): string; /** * Decode a `whsec_…` secret to its raw HMAC key: standard-base64 payload * after the prefix, which must decode to 24..64 bytes. Returns `null` on any * violation (bad prefix, not base64, length out of range). The canonical * validator for W-C: a submit failing this is `-32602` upstream; egress * surfaces it as a categorized challenge failure. */ declare function decodeWhsecSecret(secret: string): Buffer | null; /** * Sign exactly the bytes given. Throws `Error` when any secret fails * {@link decodeWhsecSecret} (callers must have validated upstream; a bad * secret at this point is a programmer error, never silently signed). */ declare function signWebhook(input: WebhookSignInput): WebhookSignatureHeaders; /** * Smart default for `features.llmEndpoint` (daemon-managed-gateway): an * operator who already configured a named endpoint, an upstream credential * link, or an explicit `llm-endpoint` custom route is clearly USING the * proxy already — booting with the sidecar off (today's default) would * silently break their next `route:{gateway:"llm-endpoint"}` spawn on a * fresh install. An operator who never touched any of that gets the * unchanged, conservative default (off). * * An explicit `configured` value (`config.json`'s `features.llmEndpoint`, * profile-overlaid) always wins, in either direction — this resolver only * fills in the gap when the operator left the flag unset. */ /** * Resolve the EFFECTIVE `features.llmEndpoint` flag. `configured` is the * operator's merged config value (`undefined` when never set in either * `config.json` or the active profile). */ declare function resolveEffectiveLlmEndpointFlag(configured: boolean | undefined): Promise; /** * MCP tools that drive the pairing registry — the daemon's "let a client pair * with me over an untrusted rendezvous" surface (design: DESIGN §6). * * Three tools, mirroring the CLI verbs: * * pair_offer : mint a one-time offer + start dialing the rendezvous; * returns the `agentproto://pair?…` URL, fingerprint, expiry. * pair_list : list persisted pairings (name, fingerprint, lastSeen). * pair_pending : list pairings whose handshake succeeded but which are * waiting for the operator's confirmation. * pair_confirm : promote a pending pairing into pairings.json. * pair_decline : drop a pending pairing. * pair_revoke : drop a pairing by fingerprint or name; stops its rendezvous * connections so it can no longer reconnect. * * Registered beside `remote_*` (remote-tools.ts) — same closure-rebind pattern; * the registry singleton lives on the gateway. */ interface RegisterPairingToolsOptions { registry: PairingRegistry; } declare function registerPairingTools(server: McpServer, opts: RegisterPairingToolsOptions): void; /** * Device registry — a read view over `PairingRegistry` (+, when wired, * `HostRegistry`) that presents each pairing/host as a "device" (DEVICES-PLAN * PR-A, hosts added PR-C). A paired CLIENT (today's `pair_offer`/`pair * accept`) gets `role: "client"`; a registered HOST (`pair offer --host` + * `devices add`, host-registry.ts) gets `role: "host"`. * * This is deliberately a thin computed view, not a second store: renaming * and revoking a client device mutate the same `pairings.json` * `PairingRegistry` already owns; a host device mutates the same * `hosts.json` `HostRegistry` — so `pair_*`/`/pairings` and * `device_*`/`/devices` are two surfaces over the same two sources of truth. */ type DeviceRole = "client" | "host"; type DeviceKind = "browser" | "cli" | "daemon"; interface Device { fingerprint: string; name: string; role: DeviceRole; kind: DeviceKind; rendezvous: string; createdAt: string; lastSeen: string; /** A channel (offer or reconnect) is served for this device right now * (client), or for a host: a forward/snapshot is in flight or one reached * it within the online grace window (a background poll keeps that fresh * for joined hosts) — see host-registry.ts's "Online tracking". */ online: boolean; /** A pair/v1 pairing: listed and revocable, but can't connect until * re-paired — see `PairingRecord.legacy`. */ legacy?: true; /** Set when this device's pairing/host record was granted under a * HOST-scoped offer (`agentproto pair offer --host`) — see * offer-url.ts's "Offer scope". Surfaced from either side of a pairing so * a user can see, from EITHER daemon, which of their pairings/hosts grant * host control. */ scope?: "host"; /** Self-reported by a host at join time (SANDBOX-VISIBILITY-JOIN) — see * `HostRecord.provider`/`sandboxId`/`labels`. Absent for a client device. */ provider?: string; sandboxId?: string; labels?: Record; /** Host only: when this daemon last tried to reach it, and why the most * recent attempt failed (absent when the last attempt succeeded). */ lastProbeAt?: string; lastError?: string; /** Host only: a join-added (CI) host that is gone — said goodbye or was * unreachable past the TTL. Hidden from `list()` unless `includeEnded`. */ ended?: true; endedAt?: string; /** Host only: a manually added host unreachable past the TTL. Still listed, * never auto-deleted. */ stale?: true; } interface ListDevicesOptions { /** Include ended (gone) join-added hosts, which `list()` hides by default. */ includeEnded?: boolean; } interface DeviceRegistry { /** Every known device, minus ended join-added hosts unless * `includeEnded`. Read-only. */ list(opts?: ListDevicesOptions): Promise; /** Rename a device (fingerprint or current name) to a new label. Tries the * pairing registry first, then the host registry. Returns false when * nothing matched. */ rename(idOrName: string, newName: string): Promise; /** Drop a device by fingerprint or name — same effect as `pair revoke` for * a client device, `devices revoke`-of-a-host for a host device. Tries * the pairing registry first, then the host registry. Returns false when * nothing matched. */ revoke(idOrName: string): Promise; /** Register a host from an offer URL (delegates to `HostRegistry.add`). * Rejects if no `HostRegistry` was wired into this device registry. */ add(offerUrl: string, name?: string): Promise<{ fingerprint: string; name: string; rendezvousUrl: string; }>; /** * Forward one HTTP request to a HOST device on demand (delegates to * `HostRegistry.forwardHttp`) — the basis for `device_sessions`. Rejects * if no `HostRegistry` was wired, or if `idOrName` doesn't match a host. * * For a GET `/sessions*` request specifically (SANDBOX-VISIBILITY-JOIN * #3): if the live forward fails (most commonly the host is offline — * an ephemeral CI box's ~3min lifetime is well within normal * `device_sessions` polling cadence), falls back to * `HostRegistry.getSessionsSnapshot` — the last successful response for * that EXACT path, `stale: true`, with a `capturedAt` timestamp — instead * of throwing. Still throws if there's no snapshot to fall back to, or * for any other path (exec, device-inference, …), where serving stale * data silently would be actively wrong. */ forwardHttp(idOrName: string, req: ForwardHttpRequest): Promise; } declare function createDeviceRegistry(pairing: PairingRegistry, hosts?: HostRegistry): DeviceRegistry; /** The host-side route `promptHostSession` forwards to — served by the HOST * daemon's `/device-prompt/:sessionId` (http-server.ts), gated by the same * host-scoped-pairing + `deviceSpawnAllow` two-gate as `/device-spawn/*`. */ declare const DEVICE_PROMPT_PATH_PREFIX = "/device-prompt"; interface PromptHostSessionInput { /** * The turn to deliver — same shapes local `agent_prompt` accepts: a * non-empty string, a content block object, or a non-empty array of * content blocks. Validated here (never forwarded ill-formed). */ prompt: unknown; /** When the host session is mid-turn, redirect instead of queueing * (mirrors local `agent_prompt`'s `interrupt`). Default false. */ interrupt?: boolean; /** With a mid-turn session, jump the FRONT of the FIFO instead of the * back (mirrors local `agent_prompt`'s `force`). Default false. */ force?: boolean; /** Block until the prompted turn drains (the session goes idle with an * empty queue) instead of fire-and-forget. Default false. */ wait?: boolean; /** Poll cadence while `wait`ing, ms — clamped to [10, 10_000], default * 1_000. Each poll is a fresh E2E dial to the host, so don't set this * low in production; the clamp floor exists for tests. */ pollMs?: number; /** Give up `wait`ing after this long (ms). 0 (default) = wait forever. */ maxWaitMs?: number; /** Injectable delay for tests. Default a real setTimeout sleep. */ sleep?: (ms: number) => Promise; } interface PromptHostSessionResult { ok: boolean; /** The enqueue landed in the host session's FIFO (it was mid-turn) — * present on the fire-and-forget arm only. */ pending?: boolean; queueId?: string; queuePosition?: number; /** Present on the `wait` arm: how long the turn took to drain. */ waitedMs?: number; /** The host's HTTP status, when the enqueue itself failed. */ status?: number; message?: string; } /** * Prompt a HOST device's session — the write counterpart of `device_sessions` * (BOOTSTRAP P4 item 1). Forwards `POST /device-prompt/:sessionId` over the * host's E2E channel (`HostRegistry.forwardHttp`, the same dial the read * verbs use); the host daemon, if it has opted in (`deviceSpawnAllow`) and * the pairing is host-scoped, calls its own `POST * /sessions/:id/prompt` — queueing rules identical to a local prompt. * * Fire-and-forget by default (the enqueue's 202 comes straight back); * `wait: true` then polls the host's `GET /sessions/:id` until the session * is idle with an empty queue (or dies, or `maxWaitMs` elapses). Never * silently serves stale data — a failed forward throws, there is no * snapshot fallback for a write. */ declare function promptHostSession(hosts: HostRegistry | undefined, target: string, sessionId: string, input: PromptHostSessionInput): Promise; /** A narrow slice of the sessions registry `promptDeviceSession` needs — * kept minimal so tests stub one function. */ interface DevicePromptSessionsLike { findByIdOrName(idOrName: string): { id: string; hostSessionId?: string; hostFingerprint?: string; } | undefined; } /** Is this failure the "the given session id doesn't exist on the host" * shape — the only case P7a's controller-id resolution may rescue? A * `no session ""` envelope (the host's `enqueuePrompt` 404, the shape * behind the field finding's `{"ok":false,"status":404,…}`) is the match; * ANY other failure (pairing gate, wait arm, prompt validation) must pass * through untouched rather than get masked by a mapping retry. */ declare function isNoSessionPromptFailure(result: PromptHostSessionResult): boolean; /** The controller→host mapping for one id, resolved against the LOCAL * registry — dial-free. Answers `kind: "controller"` only when a local * descriptor with that controller id carries BOTH `hostSessionId` AND a * device identity whose fingerprint-or-name belongs to the SAME target * device (exact-string when no `hosts` registry is wired — the raw * `device:<…>` target round-tripped; fingerprint-vs-name reversed against * the host records otherwise). Resolution order at the call site stays * (a) exact host-id first (promoted by the direct-attempt 404), * (b) this mapping second. */ declare function resolveDevicePromptMapping(sessions: DevicePromptSessionsLike | undefined, hosts: HostRegistry | undefined, sessionId: string, target: string): Promise<{ kind: "controller"; hostSessionId: string; } | { kind: "none"; }>; /** * `device_prompt` with P7a id resolution (#1637). Resolution order: * * (a) exact host session id match — the current behavior, tried FIRST, * exactly as `promptHostSession` always has; * (b) controller-id → host-id via the local registry: when (a) fails * with a no-session failure AND a local device descriptor maps the * given id (`hostSessionId` stamped at device spawn), retry once * against the mapped host id. * * Any other failure passes through untouched — the mapping must never mask * a pairing gate, a prompt-validation rejection, or a wait-arm error. When * both fail, the error names the host and the mapping so the operator * knows both halves were checked. */ declare function promptDeviceSession(hosts: HostRegistry | undefined, sessions: DevicePromptSessionsLike | undefined, target: string, sessionId: string, input: PromptHostSessionInput): Promise; /** * MCP tools over the device registry (DEVICES-PLAN PR-A/PR-C) — `device_list` * / `device_rename` / `device_revoke` / `device_add`. A view on top of the * same registries `pair_offer`/`pair_list`/`pair_revoke` (pairing-tools.ts) * and host-registry.ts drive; those keep working unchanged. `device_revoke` * has the exact effect of `pair_revoke` for a client device. * * `device_add` (PR-C) registers a HOST from a `--host`-scoped offer URL — * see `HostRegistry.add`'s scope gate (host-registry.ts). It requires the * gateway to have wired a `HostRegistry` into the `DeviceRegistry`; without * one the call rejects with a clear message rather than a missing-tool error * (this repo always wires one when `pairingRegistry` is wired, so that's * only reachable via a deliberate host misconfiguration). * * Registered beside `pair_*` — same closure-rebind pattern; the registry * singleton lives on the gateway. */ interface RegisterDeviceToolsOptions { registry: DeviceRegistry; /** Optional — the underlying host registry (`device_add`'s), when wired. * `device_prompt` needs it directly: its wait-loop dials the host more * than once, which `DeviceRegistry.forwardHttp`'s snapshot fallback * would happily answer from cache. When absent, `device_prompt` is not * registered. */ hosts?: HostRegistry; /** Optional (BOOTSTRAP P7a) — the session registry, for `device_prompt` * to resolve a CONTROLLER session id onto its mapped HOST session id * (the issue #1637 id split). Absent ⇒ no controller-id resolution and * the tool keeps behaving exactly as before. */ sessions?: DevicePromptSessionsLike; /** Optional (SANDBOX-VISIBILITY-JOIN) — when wired, registers * `join_token_create`/`join_token_list`/`join_token_revoke`. */ joinTokens?: JoinTokenRegistry; } declare function registerDeviceTools(server: McpServer, opts: RegisterDeviceToolsOptions): void; /** * BOOTSTRAP P7b — read-time mirror of a HOST device's turns into the * CONTROLLER's own session reads (issue #1637). * * A `session spawned with sandbox: "device:"` lives on TWO * daemons: the controller keeps a thin proxy-backed descriptor (its `id`, * e.g. `sess_305be17c`) while the real conversation accumulates on the * host' under a DIFFERENT id (`sess_cf318f00`, on the descriptor's * `hostSessionId`). #1640 gave the controller WRITE access across the gap * (`device_prompt`); this module closes the READ half: nothing runs in * the background — every controller READ (`GET /sessions/:id`, the * `/output` tail, `/events`, `/export`, the `agent_output` tool) calls * {@link syncDeviceMirror} first, which: * * 1. derives the dedup cursor from the session's OWN events.jsonl (max * `hostSeq` across records tagged `origin: "device"` — so the cursor * survives a daemon restart by construction, P7b-3), seeding it the * first time from what the controller already knows locally (below), * 2. dials the host ONCE over the existing E2E channel * (`HostRegistry.forwardHttp`, the same path `device_sessions` uses) * and pages `GET /sessions/:hostSessionId/events?since=` — * an EXISTING host route; no host-side changes are consumed for this * (P7b uses today's 1.7.x-compatible endpoints only), * 3. appends the new host records to the controller transcript, * byte-faithful, tagged `origin: "device"` + `hostSeq` + * `sourceRef: "device:"` (idempotent by the hostSeq cursor — * re-reading never duplicates), and * 4. cheaply refreshes the controller descriptor's live projection * fields from the host snapshot (`lastActivityAt`, `busy`, usage), * without touching controller-local fields (label, agentsMdMode…). * * Backward compatibility (P7b constraint): only EXISTING host endpoints * are consumed. An older host, or one whose daemon lacks the events route, * surfaces as `mirrorError` on the descriptor — never a crash, never a * silent stale overwrite. */ /** One raw record off the host's own transcript (the exact on-disk shape — * `{seq, ts, kind, ...}` — so the mirror is byte-faithful to the host). */ type HostEventRecord = Record; /** * Dial the host and read its session's transcript from `sinceSeq` * (exclusive), paginating until the host reports the tail complete. * * Same failure semantics as `device_sessions`' tail mode, but WITHOUT its * stale-snapshot fallback: the host's unreachability must surface as * `{ ok: false, error }` so readers can show "host unreachable" rather * than silently rendering the last snapshot (P7b-1). `404 no_transcript` * (a host session with nothing written — most usefully a just-spawned one) * is a NORMAL empty result, not an error. */ type FetchHostTurnsResult = { ok: true; /** Records strictly AFTER `sinceSeq`, ascending. */ events: HostEventRecord[]; /** Host-reported tip: the seq the next call should use as `sinceSeq`. */ nextSeq: number; } | { ok: false; error: string; staleAt?: string; }; declare function fetchHostTurns(hosts: HostRegistry, hostFingerprint: string, hostSessionId: string, sinceSeq: number): Promise; /** The highest `hostSeq` already mirrored into the session's transcript — * the next sync reads only what is STRICTLY newer, so a daemon restart or * a re-read can never duplicate or skip turns (P7b-3, the correctness * core). Scans for `origin === "device"` records; every other line is * controller-local and owns no `hostSeq`. Standalone fs reader (tests + * tooling): the LIVE sync path uses the registry's own * `scanDeviceMirrorState` so custom transcript base dirs can't drift. */ declare function mirrorCursorForSession(sessionId: string, baseDir?: string): Promise; /** * Seed the cursor so a FIRST mirror read (before anything was ever * mirrored) skips the turns the controller already recorded on its own. * * Walks the host transcript in order; a host `user-prompt` whose text * matches the NEXT unmatched known local prompt is a turn the controller * already has (it captured that turn live through the sandbox proxy) — * consume it and keep walking. The first host turn that does NOT match is * where local knowledge ends: the cursor is the last turn-end BEFORE it, * so everything from that turn onward gets mirrored exactly once. * * Ordered (not set-membership) on purpose: re-issued prompts later in a * conversation legitimately reappear in the host transcript and a * set-membership match would wrongly skip them. * * Exit states: every host turn matched → full tip is known, cursor is the * last turn-end; no local prompts (or the first host prompt already * unknown) → 0, mirror everything. A transcript longer than one page * leaves the seed `undefined` — the caller merges from 0 (a possible * duplicate beats any lost content) rather than trusting a partial walk. */ declare function seedWalkForTranscript(localTexts: readonly string[], hostRecords: readonly HostEventRecord[]): number | undefined; /** Turn a raw host record into the controller-transcript record the mirror * appends — same `kind` (so every existing transcript renderer renders it * unchanged) plus the three mirror tags, and the HOST's own `ts` preserved * inside the record. `undefined` for kinds that carry conversations the * controller doesn't derive value from duplicating (`system-prompt`, * `usage_update`, derived `tool-call-record`, …). */ declare function hostRecordToMirrorRecord(rec: HostEventRecord, hostFingerprint: string): Record | undefined; /** The slice of `SessionsRegistry` (and the descriptor) the sync needs — * kept narrow so tests can stub the registry. */ interface DeviceMirrorTarget { findByIdOrName(idOrName: string): SessionDescriptor | undefined; appendDeviceMirrorRecords(id: string, records: readonly Record[]): number; /** Preferred cursor/prompt source — the registry's own scan (correct * transcript base dir). Falls back to this module's default-dir fs read * when absent (older registry shapes / direct unit calls). */ scanDeviceMirrorState?(id: string): { cursor: number; localPromptTexts: readonly string[]; }; } type DeviceMirrorSyncResult = { ok: true; /** New records merged from the host this call. */ merged: number; /** The advanced mirror cursor after the merge. */ cursor: number; } | { ok: false; reason: "no-session" | "not-device" | "no-host-registry"; error?: string; } | { ok: false; reason: "mirror-error"; error: string; }; /** * One read-time sync for a controller id/name. Fast no-op path: no local * descriptor, or not a device-mirrored session (both fields absent) — * local spawns pay ZERO extra reads/calls (P7b test invariant). Reads the * cursor, dials the host, appends new records, refreshes the descriptor's * live projection fields, and stamps/clears `mirrorError` on the * descriptor for unreachable-host surfacing. */ declare function syncDeviceMirror(sessions: DeviceMirrorTarget, hosts: HostRegistry | undefined, idOrName: string): Promise; /** * Provider-preset family on top of `@agentproto/provider-kit` — the *thin, * honest* lister (Option B). Unlike tunnels/sandboxes/eval-reporters, presets * are bundled static data with no binary to install, no package to resolve, and * no setup ledger: their only "setup" is an ambient API-key env var. So this * module does NOT use `makeAdapterResolver` / `makeAdapterLister` / the wizard * (all install-oriented, a forced fit). It reuses only `makeListTool` — the one * kit primitive that's genuinely about "JSON a lister's output as an MCP tool." * * Status is derived honestly from the daemon's own environment (the env agents * spawn into), not the CLI caller's: * "ready" — `process.env[preset.keyEnv]` is set (key available to spawn) * "available" — key absent (preset known, usable once the env var is provided) * * There is no "supported" state: presets ship in-repo, so they're always at * least "available." `version` is the literal "built-in". * * Security (Appendix B): `PresetInfo` carries only `keyEnv` (the env-var NAME), * never a key value. The list tool never returns creds — there are none to * return; keys live in the operator's environment, not a creds store. */ /** * Manifest-declared AIP-45 preset, the minimum the catalog needs to merge * an adapter-contributed preset into the listing. Mirrors * `AgentCliPresetDeclaration`'s fields without importing * `@agentproto/driver-agent-cli` into the runtime package (same structural- * type pattern as `DeclaredAdapterOption` in spawn-defaults.ts). */ interface DeclaredAdapterPreset { id: string; label: string; description?: string; schemaFlavor: ProviderPreset["schemaFlavor"]; baseUrl: string; keyEnv: string; scrubEnv?: string[]; defaultModel?: string; homepage?: string; } /** * Family descriptor surfaced as `AdapterEntry.info`. User-facing preset facts * only — no cred values (there are none in the registry), no adapter projection * detail (`scrubEnv` stays internal to adapter manifests). */ interface PresetInfo { /** API schema flavor — which adapter family can consume this preset. */ schemaFlavor: ProviderPreset["schemaFlavor"]; /** Base URL the client hits. */ baseUrl: string; /** Env-var NAME holding the API key (never the value). */ keyEnv: string; /** Conventional default model id, if any. */ defaultModel?: string; /** Homepage/docs URL. */ homepage?: string; } /** * Normalize a manifest-declared preset into the canonical `ProviderPreset` * shape the catalog lists. `scrubEnv` defaults to empty (an adapter that * scrubs in code may omit it); `description` defaults to empty. Pure. */ declare function declaredPresetToProviderPreset(decl: DeclaredAdapterPreset): ProviderPreset; /** * Map the static preset registry → status-classified catalog entries, reading * the daemon's environment for key presence. Pure (no I/O) save the `process` * .env read; safe to call on every list invocation. * * `adapterPresets` — manifest-declared presets contributed by loaded adapters * (Stage 3 AIP-45 `presets` field). Merged AFTER the built-in registry and * deduped by id: an adapter-declared id that collides with a built-in is * ignored (the registry is the source of truth for canonical providers), so * an adapter can't silently override moonshot/openrouter facts. The live * wiring that reads each adapter's `.presets` and passes them here is Stage 4; * today this is the tested seam. */ declare function listPresets(env?: Record, adapterPresets?: readonly DeclaredAdapterPreset[]): AdapterEntry[]; /** * `harness` is the canonical name of the agent CLI a session runs (AIP-70 * GLOSSARY); `adapter` is its deprecated alias. This module is the one place * that spells the deprecation, so every surface (MCP tool results, HTTP * bodies, CLI stderr, `session:harness-warning`) warns with the same text. * * Nothing here rejects the old name: it keeps working, and warns. The * removal is a later, major change. */ /** The release the deprecated `adapter` names are removed in. */ declare const HARNESS_ALIAS_REMOVAL = "the next major of @agentproto/runtime"; /** * The deprecation line for one old name and its canonical replacement, e.g. * `adapterDeprecation("adapter", "harness")` or * `adapterDeprecation("adapter_models", "harness_models")`. */ declare function adapterDeprecation(oldName: string, newName: string): string; /** The warning for the `adapter` input field, the most common case. */ declare const ADAPTER_FIELD_DEPRECATION: string; /** * Resolve the harness slug from an input that may carry the canonical * `harness`, the deprecated `adapter`, and an optional preset carrying either. * Resolution order: `harness ?? adapter ?? preset.harness ?? preset.adapter`. * A warning is returned whenever the caller sent the `adapter` key, even * alongside `harness`: every use of the old name warns. * A saved preset's `adapter` is stored data, not a call: it is read without * a warning (`normalizeUserPreset` already mirrors it into `harness`). */ declare function resolveHarnessAlias(input: { harness?: string; adapter?: string; }, preset?: { harness?: string; adapter?: string; }): { harness: string | undefined; warnings: string[]; }; /** * Resolver for the `config.json` `defaults.nativeHooks` knobs: hooks the * daemon projects into a harness's own settings. * * `defaults.nativeHooks.preCompactCheckpoint`: `"on"` projects a synchronous * Claude Code `PreCompact` hook (matcher `auto`) running * ` hook pre-compact`, so the harness's own * compaction is preceded by a daemon checkpoint. When the key is unset the * command is the serving CLI by absolute path. `"off"` (default): nothing. * Local claude-code spawns only: the projection lives in claude-code's * isolated settings.json, and a sandbox spawn runs on the box's own daemon. * * Hot, read at spawn and restart (so a change applies to sessions spawned * after it), the same way as `identity-defaults.ts`. */ /** * The command line that runs THIS CLI (`'' ''`), for a hook the * harness starts through a shell. POSIX only (a win32 daemon keeps the bare * word), and only for two absolute paths with a built JavaScript entry (a * daemon run from TypeScript sources through a loader cannot be re-run as * `node `): anything else returns undefined. */ declare function servingCliCommand(execPath: string | undefined, entry: string | undefined, platform?: NodeJS.Platform): string | undefined; /** * Set once by the CLI's `serve` command: the command line that runs the CLI * serving this daemon. Process-wide module state, read by every in-process * spawn/restart in this daemon; only `agentproto serve` calls it (a host that * loads two runtime instances gets one fallback per instance). */ declare function setServingCli(command: string | undefined): void; /** * Per-workspace state buckets — AIP-46 §State partitioning. * * AIP-46's premise is "a single host serve many bound directories", and * §Workspaces delivered the addressing half of it: a slug resolves to a * path. The state those directories generate stayed pooled in one global * `~/.agentproto/sessions.json` with `workspaceSlug` demoted to a column * on each row — a label, not a boundary. * * What that costs is measurable rather than theoretical. `HISTORY_CAP` * bounds retention across the *union* of every workspace, so the cap is * spent by whoever was busiest. A store pooling a few hundred rows from * several workspaces sits at that ceiling in ordinary use, and the * workspace contributing a handful of them is one busy afternoon in a * NEIGHBOUR away from losing all of them — having done nothing itself. * The eviction is silent and lands on the quietest workspace. * * This module is the slug→bucket rule and nothing more: * * ~/.agentproto/ * ├── workspaces.json # the registry (workspaces-config.ts) * └── workspaces/ # one bucket per workspace (here) * ├── demo-app/sessions.json * └── default/sessions.json * * The registry (a file) and the state (a directory) are deliberate * siblings: one names the workspaces, the other holds what each * accumulated. * * ## Membership is the validation * * `workspaceSlug` arrives on a spawn request — it is caller input * (`session-spawn.ts` passes `input.workspaceSlug` straight through when * an explicit `cwd` accompanies it, so nothing sanitises it on the way * to the descriptor). A bucket is a directory name. Joining the two * without a check hands the caller `../../` under the daemon's own state * root, as the daemon's UID. * * So a slug does not become a directory name by being cleaned up — it * becomes one by coming *back from* the registry lookup. The registry's * slugs were sanitised by `sanitizeSlug` on the way in, so the only * strings that ever reach the filesystem are ones the host itself * minted. An unregistered slug isn't rejected or escaped; it fails to * match and lands in `default` like any other unregistered work. This is * why the rule is membership rather than sanitisation: you cannot forget * to validate a value you never chose. * * ## What this does NOT buy * * Partitioning bounds what a workspace's state *costs* other workspaces. * It does not bound who may read it — every bucket is still served to * every authorised caller, because no workspace-scoped credential * exists to serve them differently (pairings carry no workspace concept * at all; the orchestrator scope-token's `session_list` is daemon-wide * by documented debt, `orchestrator-gateway.ts`). The files moved; the * access did not. AIP-46 §Security Considerations says this in the * negative — do not read this module as an isolation control. */ /** The bucket every record lands in when its slug doesn't resolve — * absent, empty, or naming a workspace that isn't registered. * * A real bucket, not an error state. Refusing to persist an * unregistered session would make this a breaking change for every * one-off `cwd` spawn, and the obvious workaround (auto-register) * turns a registry of the user's intent into a registry of everything * that ever ran. The cost is stated plainly in the AIP: `default`'s * occupants get no separation from *each other* — registering a * workspace is what buys that. */ declare const DEFAULT_BUCKET = "default"; /** Root of the per-workspace state buckets. Sibling of the * `workspaces.json` registry that names them. */ declare const BUCKETS_ROOT: () => string; /** The pre-partition global snapshot. Still read (to migrate from) and * never written after the split — see `migrateLegacySessionsFile`. */ declare const LEGACY_SESSIONS_FILE: () => string; /** Marker recording that the legacy split already ran. Its presence — * not the legacy file's absence — is what makes migration * once-and-only-once, so a user who deletes rows from a bucket doesn't * get them resurrected on the next boot. */ declare const migrationMarkerPath: (root: string) => string; declare const bucketDir: (root: string, slug: string) => string; declare const bucketSessionsFile: (root: string, slug: string) => string; /** Per-bucket transcript directory (AIP-46 §Layout). * * Not yet wired: the registry still writes transcripts to the shared * `~/.agentproto/sessions/`. Moving them needs the read side to move * too, and several readers currently ignore the configured base dir * entirely (`http-server.ts` and `transcript-export.ts` call * `sessionEventsPath(id)` with no `baseDir`, so they resolve off * `homedir()` regardless) — a pre-existing bug that a partial move * would turn into missing transcripts. Exported so the follow-up has * the path rule in one place. The AIP makes transcripts a SHOULD, not * a MUST, for exactly this reason. */ declare const bucketTranscriptDir: (root: string, slug: string) => string; declare const isSafeBucketSlug: (slug: string) => boolean; /** * The slug→bucket rule (AIP-46 §Bucket resolution). * * 1. non-empty AND registered → that workspace's bucket * 2. otherwise → `default` * * `registered` must come from the workspaces registry. Passing a set * built from caller input defeats the entire point of this function. */ declare function resolveBucketSlug(workspaceSlug: string | undefined | null, registered: ReadonlySet): string; /** Registered slugs, read fresh. Cheap (the registry is <1KB) and read * per persist rather than cached at boot, so a workspace registered * while the daemon is up starts bucketing immediately instead of * silently pooling into `default` until restart. Never throws: a * missing/corrupt registry degrades to "nothing is registered", i.e. * everything lands in `default` — today's pooled behaviour, which is * the right failure direction. * * A registry read that fails transiently (a race with a concurrent * `saveWorkspacesConfig` tmp+rename) is indistinguishable here from one * that's genuinely empty — but the persist path never actually needs to * tell them apart: `sessions.ts`'s `sourceBucketOf` already keeps a * loaded row homed to the bucket it came from regardless of what this * returns, so a bad read here degrades a NEW session's placement (still * `default`, same as always) and nothing else. See the 2026-07-18 * bucket-clobber incident for why that distinction matters for loaded * rows, and `sourceBucketOf`'s docblock in `sessions.ts` for where it's * actually enforced. */ declare function readRegisteredSlugs(configPath?: string): ReadonlySet; /** Bucket directories that exist on disk. Order is not meaningful. */ declare function listBuckets(root: string): string[]; interface MigrationMarker { version: 1; migratedAt: string; /** Absolute path of the legacy artifact this split read from. Left * untouched on disk — recorded so the provenance survives. */ from: string; /** Total records read out of the legacy artifact. */ rows: number; /** Records landed, per bucket. Sums to `rows` — the migration never * drops a record it cannot place; it sends it to `default`. */ byBucket: Record; } /** * Split the legacy global snapshot into buckets (AIP-46 §Migration). * * **Additive by mandate.** The legacy file is opened read-only and left * exactly where it is — never deleted, truncated, or rewritten. It is * the user's data and their only rollback; the buckets are a derivative * until they decide otherwise. Reclaiming it is a separate, human-gated * call, and this module deliberately ships no GC: a real store is backed * by a transcript directory that can reach hundreds of megabytes and may * be someone's only copy of months of work — a deleter that guesses * wrong there is unrecoverable. * * Idempotent via the marker, not via the legacy file's absence — the * file stays, so absence would never fire and every boot would re-import * rows the user had since deleted from a bucket. * * Returns the marker it wrote, or `null` when there was nothing to do * (already migrated, or no legacy file). */ declare function migrateLegacySessionsFile(opts: { root: string; legacyFile: string; registered: ReadonlySet; }): MigrationMarker | null; /** * Persisted conversation index — the session ↔ native-transcript link, * stored instead of re-derived (DESIGN.md `agentproto-state-multitenancy` * §6). * * Today the link between an agentproto session and the original * claude/hermes conversation file is DERIVED on every read, through * `claudeCodeProjectDir`/`claudeProjectSlug` (conversation-store.ts) — and * until that function was fixed, derived *wrong* for any cwd containing a * dot. Re-deriving is also blind to cwd drift (a worktree that moved) and * carries no record of subagent transcripts at all. * * This module is the fix: an **append-only** `conversations.jsonl`, one * per workspace bucket (co-located with that bucket's `sessions.json`, * `workspace-buckets.ts`), upserted by `sessionId` — readers take the LAST * record per id. Append-only is deliberate, not incidental: it is immune * to the wholesale-rewrite clobber `sessions.ts`'s `persistSnapshot` * already has (see DESIGN.md §1) — a writer can only ever ADD a line, so a * second process racing a first can't shrink what's on disk. * * Write points (best-effort, mirroring how `transcriptWriter`/ * `persistSnapshot` never throw into the turn path): session spawn, an * ACP-level resume, and a native graceful-exit resume-hint — see * `sessions.ts`'s calls into `recordConversationLink`. * * No tenant layer yet — the index lives directly under the workspace * bucket dir today (`bucketDir(bucketsRoot, slug)/conversations.jsonl`); * DESIGN.md §9 notes it migrates under `tenants//…` at a later PR. */ /** The claude-code native store: one jsonl per conversation, plus any * subagent transcripts nested under `/subagents/agent-*.jsonl`. */ interface ClaudeNativeRef { kind: "claude-jsonl"; path: string; subagents: string[]; } /** The hermes native store: a row in a shared sqlite db, keyed by the same * id agentproto already records as `adapterSessionId` — no path to derive. */ interface HermesNativeRef { kind: "hermes-sqlite"; dbPath: string; rowId: string; } type ConversationNativeRef = ClaudeNativeRef | HermesNativeRef; interface ConversationIndexRecord { sessionId: string; workspace: string; cwd: string; adapterSlug: string; adapterSessionId: string; /** The session's isolated provider config dir at write time (see * `ResolveNativeLinkInput.adapterConfigDir`) — recorded so readers * that go through the store abstraction (`store.read`, not * `native.path`) can resolve the same isolated dir. Absent on * pre-#824 rows and native PTY sessions. */ adapterConfigDir?: string; /** Absent when `adapterSlug` has no known native store (an adapter * outside claude-code/hermes) — the record still links session ↔ * cwd ↔ adapterSessionId, it just can't point at a native file. */ native?: ConversationNativeRef; agentprotoTranscript: string; title?: string; startedAt: string; endedAt?: string; } /** Absolute path to a workspace bucket's conversation index. Sibling of * `bucketSessionsFile` in `workspace-buckets.ts`, same root/slug rule. */ declare function conversationIndexPath(bucketsRoot: string, slug: string): string; interface ResolveNativeLinkInput { cwd: string; adapterSlug: string; adapterSessionId: string; /** The session's isolated provider config dir (`SessionDescriptor. * adapterConfigDir`): since #824 a daemon-spawned claude-code session * writes its transcripts under `/projects/`, * not `~/.claude/projects/`. Absent for a native PTY or a * pre-#824 row — the global dir applies. */ adapterConfigDir?: string; } /** * Resolve where THIS provider keeps this conversation, computed once (at * a write point) rather than re-derived on every read. Claude-code's path * uses the corrected `claudeProjectSlug` via `claudeCodeProjectDir` — the * whole point of pairing this module with the encoder fix in the same PR. * Returns `undefined` for an adapter with no known native store (e.g. * mastracode, claude-sdk) — a record without `native` is still useful * (session ↔ cwd ↔ adapterSessionId), it just has nothing further to add. */ declare function resolveNativeLink(input: ResolveNativeLinkInput): Promise; /** Append one record. Never rewrites — the caller decides when a fresher * snapshot of the same session is worth a new line; readers always take * the last one. Creates the bucket dir if this is its first conversation * record (a bucket that has only ever held terminal/command sessions * won't have one yet). */ declare function appendConversationRecord(bucketsRoot: string, slug: string, record: ConversationIndexRecord): Promise; /** Read one bucket's index, upserted by `sessionId` — a line later in the * file always wins over an earlier one for the same id, append-only's * upsert semantics. A malformed line (partial write, hand-edited garbage) * is skipped, not fatal — the rest of the file still reads. `[]` (not a * throw) when the bucket has no index yet. */ declare function readConversationIndex(bucketsRoot: string, slug: string): Promise; /** Forward lookup within one already-known bucket. */ declare function findConversationRecord(bucketsRoot: string, slug: string, sessionId: string): Promise; interface LocatedConversation { workspace: string; record: ConversationIndexRecord; } /** Forward lookup: sessionId → its record, scanning every bucket (the * caller doesn't have to know which workspace a session landed in). * `undefined` when no bucket's index has ever recorded this session. */ declare function locateConversationBySessionId(bucketsRoot: string, listBuckets: () => string[], sessionId: string): Promise; interface LocatedConversationByPath extends LocatedConversation { /** Set when the match was a subagent transcript rather than the root * conversation file — the path that actually matched. */ matchedSubagentPath?: string; } /** Reverse lookup: a native jsonl path (root conversation OR a subagent * transcript) → the agentproto session/workspace that owns it. Scans * every bucket's index; paths are compared after `path.resolve` so a * relative or `..`-bearing argument still matches an absolute recorded * one. Only meaningful for claude-code's `native.path`/`native.subagents` * — hermes has no per-conversation file to reverse-lookup from. */ declare function locateConversationByNativePath(bucketsRoot: string, listBuckets: () => string[], nativePath: string): Promise; /** * `.agentproto/` config dir — runtime-managed state at the root of * every workspace. Mirrors the `.git/` model: user-content stays at * the workspace root (HEARTBEAT.md, conversations/, .agents/) while * everything the runtime owns lives in `/.agentproto/`. * * What goes here today: * - `runtime.json` — boot-time snapshot of the live config (PID, * port, resolved workspace, MCP server name, startedAt). Useful * for `cat .agentproto/runtime.json` diagnostics + future tooling * that wants to discover a running gateway from disk. * * The same snapshot is ALSO mirrored to the central, workspace- * independent daemon registry at `~/.agentproto/daemons/.json` * (see daemonRegistryDir / writeDaemonRegistryEntry below). The * per-workspace file only helps `cat`-style local diagnostics and * discovery for REGISTERED workspaces; a daemon launched from an * arbitrary cwd (tunnel mode, a repo checkout) writes its workspace * file somewhere discovery never walks. The central entry is what * makes `agentproto chat` / `sessions` find such a daemon. * * What does NOT go here: * - HEARTBEAT.md — user-edited content * - conversations/ — user-readable chat history * - .agents/ — user-authored manifests * * The `.agentproto/` dir is safe to gitignore. The `runtime.json` * file contains a per-boot bearer token used to gate mutating HTTP * routes (POST /sessions/*, WS /sessions/:id/pty). The token lives * in RAM + on disk only — never logged. File mode 0600 below; only * processes running as the workspace user (and the daemon itself) * can read it. A browser-loaded localhost page CAN'T read this file, * which is what defends against the localhost-DNS-rebinding drive-by * spawn vector. */ interface RuntimeMeta { /** Absolute path to the workspace root the gateway is bound to. */ workspace: string; /** HTTP listener port. */ port: number; /** HTTP bind address (loopback or `0.0.0.0`). */ bind: string; /** Process id of the running gateway. */ pid: number; /** Wall-clock ISO timestamp at boot. */ startedAt: string; /** MCP server name advertised in the initialize handshake. */ name: string; /** AIP doctype names + extensions registered as MCP CRUD tools. */ registered: readonly string[]; /** * Per-boot bearer token. Required on mutating routes (POST * /sessions/*, POST /sessions/:id/kill, DELETE /sessions/:id, and * WS upgrade to /sessions/:id/pty). Random uuid generated at boot * by createGateway; regenerated each restart. */ token: string; } /** `~/.agentproto/daemons/` — the central, workspace-independent daemon * registry. Each live daemon owns one `.json` here. */ declare function daemonRegistryDir(): string; /** * Write `/.json` (mode 0600 — holds the bearer token). * Best-effort; failure here never gates the gateway. Mirrors the * per-workspace runtime.json so the same `RuntimeMeta` shape is readable * from either location. */ declare function writeDaemonRegistryEntry(meta: RuntimeMeta): Promise; /** Remove a daemon's central registry entry. Best-effort; missing is a * no-op. Called from graceful shutdown alongside unlinkRuntimeMeta. */ declare function unlinkDaemonRegistryEntry(port: number): Promise; /** * Read every entry in the central daemon registry, newest-first by * `startedAt`. No liveness filtering here — callers decide (discovery * skips dead PIDs; the sweep deletes them). Malformed / unreadable * entries are skipped silently. */ declare function readDaemonRegistry(): Promise & Record; path: string; mtime: Date; }>>; /** * Delete central registry entries whose PID is dead (kill -9, crash, * reboot). Returns the paths cleaned. Called at `serve` boot — the same * footgun the per-workspace sweep guards against, applied to the central * registry. Skips `currentPort` (the booting daemon's own entry). */ declare function sweepStaleDaemonRegistry(currentPort: number): Promise; /** * Buckets served by a daemon OTHER than the one on `currentPort` that is * actually alive (registry entry with a live PID). The boot passes use it to * tell "this row belongs to another running daemon — leave it" apart from * "no daemon serves this row's bucket — it is stranded unless we take it": * a sandbox session spawned into a workspace bucket nobody serves otherwise * stays a `daemon-restart` ghost forever while its box keeps running. * `bucketOf` maps a daemon's workspace path to its bucket slug. */ declare function bucketsServedByOtherLiveDaemons(currentPort: number, bucketOf: (workspacePath: string) => string): Promise>; /** * Delete `/.agentproto/runtime.json`. Best-effort — called * from the daemon's graceful shutdown path so a CLI looking for the * live daemon doesn't pick up a stale token after this process exits. * Missing file is a no-op (the daemon may never have written one). */ declare function unlinkRuntimeMeta(workspace: string, port?: number): Promise; /** * Read a runtime.json from `/.agentproto/`. Returns the * parsed object (no validation) plus the on-disk mtime, or null when * the file is missing / unreadable / malformed. */ declare function readRuntimeMeta(workspace: string): Promise<{ meta: Partial & Record; mtime: Date; } | null>; /** * For each `workspace` path, check whether its runtime.json points * at a now-dead PID; if so, delete it. Returns the list of paths * that were cleaned. Called by `agentproto serve` at boot to keep * the discovery layer's view of "live daemons" honest — a stale * file with the same port as the new daemon is the classic source * of `sessions_unauthorized` 401s. * * Skips the running daemon's own workspace (passed in as * `currentWorkspace`) since that file is OURS to write. */ declare function sweepStaleRuntimeMetas(workspaces: readonly string[], currentWorkspace: string): Promise; /** * Read-only probe: does a credential actually RESOLVE for an adapter slug's * billing auth? Used by `adapter_list` to report an HONEST status instead of * claiming "ready" on a host with zero credentials for an adapter that hard- * fails every spawn (claude-code, `authEnforce: "always"`). * * THE TRAP (see the money regression test in `__tests__/auth-probe.test.ts`): * a probe that answers "is auth configured?" by checking `providers.json` * alone would report `true` for a spawn that still throws * `missing_auth_credential` — the store lookup at `session-spawn.ts:612-617` * is gated on `explicit` (PR #321: an unconfigured `always`-enforcing adapter * must never pick up a leftover store key and bill org credits instead of the * Max subscription). So this mirrors `session-spawn.ts`'s resolution exactly * — same `resolveSpawnDefaults` + `resolveAuthSpec`, same explicit gate on * the store lookup — rather than reimplementing the precedence: a second * copy of this logic WILL drift, and the drift is denominated in money. */ declare function isAgentCliAuthConfigured(slug: string, descriptor: AdapterAuthDescriptor, model?: string): Promise; /** * Route-aware launch-config builder shared by fresh spawn * (`session-spawn.ts`) and restart (`session-restart-core.ts`). * * Centralizes the decisions that must stay identical across the two paths so * a restart cannot silently diverge from a fresh spawn: * - when/how to inject a resolved gateway `base_url` into `config.options` * - skills normalization against the manifest's declared option shape * - stripping catalog route-identity suffixes / native vendor prefixes from * the model id before it reaches the wire * * Secrets never enter this layer: `authSpec` is a fully-resolved billing-auth * spec whose credential is already in-memory; `baseUrl` here is a non-secret * endpoint URL. */ interface RouteAwareLaunchConfigInput { /** Adapter slug — used only in error messages. */ adapter: string; /** Operator-facing model id (may carry `@route` suffix or native vendor prefix). */ model?: string; /** Resolved endpoint/gateway rail. */ route?: RouteSpec; /** Fully-resolved billing-auth spec (carries the gateway baseUrl when one was resolved). */ authSpec?: ResolvedAuthSpec; /** * Options BEFORE any route/base_url injection. For a fresh spawn this is * `spawnDefaults.options`; for a restart it is any explicit override options * (today restart carries none, but the shape stays forward-compatible). */ options?: Record; /** Manifest-declared options — drives whether `base_url` is a valid option id. */ declaredOptions?: readonly DeclaredAdapterOption[]; /** Manifest-declared route selection strategy. */ routeSelection?: "free" | "derived-from-model"; /** Fixed provider for this adapter (e.g. `"anthropic"`), used for wire-model prefix stripping. */ adapterProvider?: string; /** `AdapterAuthDescriptor.modelDerivedApiKey` — see `normalizeModelForWire`'s * `ModelWireOptions.modelDerivedApiKey` doc for why this changes the wire * shape on a gateway-routed `derived-from-model` adapter. */ modelDerivedApiKey?: boolean; /** Skills list folded into `options.skills` per the manifest's declared shape. */ skills?: string[]; /** * Prefix for error messages. `agent_start` for the spawn path, `restart` * for the restart path, so fail-loud messages name the caller. */ prefix?: string; } interface RouteAwareLaunchConfig { /** Options ready for `AgentCliStartOptions.config.options`. */ options?: Record; /** Model id to pass to the wire, with route suffix / native vendor prefix stripped. */ wireModel?: string; /** The resolved base_url that routing applied (or attempted to), for descriptor echo. */ resolvedBaseUrl?: string; } /** * Build the route-aware pieces of an agent-cli `startSession` call. * * Mirrors the logic historically inline in `session-spawn.ts` (the D1 fix): * a gateway-resolved `base_url` is only injected when the adapter manifest * actually declares a `base_url` option, OR when the resolver reported no * declared option vocabulary at all (pre-D1 fallback). For derived-from-model * adapters the resolved gateway `base_url` is skipped silently because the * adapter derives its endpoint from the model prefix. Native fixed-provider * gateway presets (e.g. codex + `route.gateway: "openai"`) have their base_url * dropped upstream in `resolveAuthSpec`, so they pass through this layer * without injection. Any other route base_url for an adapter that cannot accept * it fails loud rather than silently dropping the operator's billing choice or * crashing manifest validation on an undeclared option. * * Returns `options` only when there is at least one option to set, so callers * can omit the `config.options` field entirely when empty. */ declare function buildRouteAwareLaunchConfig(input: RouteAwareLaunchConfigInput): RouteAwareLaunchConfig; /** * MCP tools for event-driven orchestration: * - session_events_poll — cheap cursor-based snapshot of session events * - session_monitor — multiplexed long-poll (1 call for N sessions) * * These complement the existing per-session waitForTurnEnd inside * agent_output. The new tools handle multi-session fan-in * and external-client retrigger without burning polling tokens. */ /** * Event kind a session wait can target. Mirrors the `session_monitor` * `event` parameter. `turn-end` also matches `awaiting-input` (both * signal end-of-turn), matching the MCP tool's semantics. */ type SessionWaitEvent = "turn-end" | "awaiting-input" | "exited" | "any"; /** * Result of a single-session wait. On a hit, carries the session id, the * matched event (ring-bus form, without the `session:` prefix), the * session's current status, and whether it's awaiting input. On a * timeout, `timedOut: true` and the watched id list. */ interface SessionWaitResult { timedOut?: boolean; sessionId?: string; event?: string; source?: "ring" | "state" | "bus"; awaitingInput?: boolean; status?: string; turnsCompleted?: number; sessionIds?: string[]; since?: number; /** Structured awaiting-input question (harness-parity). Surface on * turn-end / awaiting-input matches so callers (MCP session_monitor + * REST /sessions/:id/wait) can read the question without a separate * transcript fetch. Mirrors desc.awaitingQuestion / ev.question. */ question?: SessionAwaitingQuestion; /** DERIVED interrupted-turn marker (§4): present and `true` when the watched * session died with a turn in flight under a daemon restart and hasn't yet * completed a fresh turn (`SessionDescriptor.interrupted`). Lets a * supervisor tell a session that came back idle from one that came back with * dropped work that was NOT re-run — the in-place resume never auto-retries. * Absent (not `false`) when the session was not interrupted. */ interrupted?: boolean; /** True when the matched turn-end produced ZERO assistant output and * zero tool calls — a silent no-op (see `SessionTurnEndEvent.empty`'s * doc). Surfaced on `event: "turn-end"` matches across all three * branches (ring-replay, sync fast-path via * `SessionDescriptor.lastTurnEmpty`, bus long-poll) so a caller doesn't * mistake a green turn-end for real progress. Absent (not `false`) on a * normal, productive turn. */ empty?: boolean; /** The matched turn-end's `SessionTurnEndEvent.reason` (e.g. * `"completed"`, `"error"`, `"aborted"`), when the adapter/daemon * reported one. `"error"` means the adapter reported a failed turn. * Same three-branch coverage as `empty`. */ reason?: string; /** The matched turn-end's captured error text — `SessionTurnEndEvent.error` * on the ring-replay/bus branches, `SessionDescriptor.lastTurnErrorMessage` * on the sync fast-path (no event object to read there). Present only * when `reason` is `"error"` AND the adapter emitted an in-band `error` * stream event during the turn. Same three-branch coverage as `empty`/ * `reason` — this is the field a waiter (a supervisor session, `sessions * wait`, a webhook) needed to actually learn WHY a turn errored instead * of just that it did. */ error?: string; } /** * Block until one of the listed sessions fires a matching lifecycle event * (turn-end / awaiting-input / exited / any), or until `timeoutMs` elapses. * * This is the single-session-capable core that the MCP `session_monitor` * tool and the REST `GET /sessions/:id/wait` route both call. The MCP tool * passes N ids (multiplexed fan-in); the REST route passes exactly one. * The semantics are identical: race-free cursor replay → synchronous * already-in-target-state check → bus long-poll → timeout. * * `since` is an EventRing cursor: when provided, already-emitted matching * events for the watched sessions that occurred after that cursor are * returned immediately (race-free replay) before subscribing to the bus. * * The synchronous already-in-target-state check for `turn-end` ALSO * requires `since` to be present (even `since: 0`) — `turnsCompleted > 0` * never resets, so without a cursor to anchor "since when", it can't tell * a turn this call should wait for apart from any turn the session ever * completed, including ones from long before this call started. A * `since`-less `turn-end` wait (e.g. a fresh `agentproto sessions wait` * process, which has no persisted cursor) always falls through to the real * bus-subscribe long-poll instead. */ declare function monitorSessionWait(opts: { registry: SessionsRegistry; sessionEvents: SessionEventBus; eventRing: EventRing; sessionIds: string[]; event?: SessionWaitEvent; timeoutMs?: number; since?: number; /** * The calling orchestrator's scope, when this wait was initiated by an * agent session (the scoped orchestrator sub-gateway stamps * `ownerSessionId`). Used ONLY to attribute the watcher attach/detach bus * events this wait emits while blocked — an anonymous CLI/HTTP waiter * leaves it absent. Never changes the wait's own semantics. */ callerScope?: { ownerSessionId?: string; }; }): Promise; /** * Block until the named policy's status transitions out of the active * `watching` / `queued` / `gating` / `nudging` states — i.e. reaches * `done`, `blocked`, `awaiting-ack`, or `cancelled` — then return the * full PolicyRunState. Returns `{ timedOut: true }` on timeout. * * Hooks into the supervisor's `onSettle` callback (the single reliable * signal — some terminal transitions like `cancel()` / `ack(false)` / * single-session-exit emit no SessionEventBus event). The MCP * `policy_status` tool and the REST `GET /policies/:id/wait` route both * delegate here, so the wait semantics are shared across transports. */ declare function monitorPolicyWait(opts: { supervisor: CompletionPolicySupervisor; policyId: string; timeoutMs?: number; }): Promise<{ timedOut: true; } | { timedOut: false; state: PolicyRunState; }>; /** * PURE decision helper for windowed cost-budget caps (phase 4). * * A {@link CostBudget} (`@agentproto/auth`) is a windowed spend ceiling that * trips a GOVERNANCE POLICY — it does NOT kill a session. This module is the * side-effect-free predicate at its core: given a budget and an already-computed * windowed `spentUsd` (from the priced `rollupUsage` local-estimate), decide * whether the cap is crossed. No fs, no clock, no rollup here — the impure * spend computation (reading snapshots + `rollupUsage`) lives at the surface * (the supervisor's cost gate) and hands the summed dollars in, exactly as * `usage-rollup.ts` splits the pure fold from `usage-rollup-service.ts`'s * disk read. * * DISTINCT from the scalar `maxCostUsd` session-kill (`sessions.ts` turn-end): * that cap KILLS the session when cumulative cost exceeds it; a `CostBudget` * only reports "tripped", and the caller emits `policy:failed`. The two are * orthogonal and coexist. */ /** * The outcome of evaluating one windowed budget against a spend figure. * `tripped` is the pass/fail signal; the rest echoes the inputs so a caller * (event payload, log line, test) can render the decision without re-deriving * it. `overageUsd` is `0` whenever the budget is not tripped. */ interface CostBudgetDecision { tripped: boolean; spentUsd: number; maxCostUsd: number; window: string; scope: CostBudgetScope; overageUsd: number; } /** * Decide whether `spentUsd` crosses `budget.maxCostUsd`. * * `tripped` is a STRICT `>` — spend exactly AT the cap is within budget (the * cap is the last allowed dollar, not the first denied one), matching the * scalar session-kill's own `> maxCostUsd` boundary (`sessions.ts:3489`). * `overageUsd` is the amount over the cap, clamped at 0 so an under-budget * decision never reports a negative overage. */ declare function evaluateCostBudget(args: { budget: CostBudget; spentUsd: number; }): CostBudgetDecision; /** * MCP tools over account slots (`accountSlots` in config.json, see * `account-slots.ts`): `account_slots_list` and `account_slots_swap`. * * `account_slots_swap` exchanges `-primary` and `-secondary` * (the "a subscription is exhausted" move). With `moveAlive`, it also restarts, * with their context, the ALIVE agent sessions billing the departing profile * (through the primary slot or by naming the profile literally) onto * `slot:-primary`, which now points at the other account. Dead * sessions are never restarted. `dryRun` computes all of it and writes * nothing. * * The CLI (`agentproto accounts slots|swap`) is a thin wrapper over these two * tools, so both surfaces share one implementation. */ interface AccountSlotToolsDeps { registry: { list(opts?: { includeArchived?: boolean; }): SessionDescriptor[]; }; /** Restart a session with its context onto a new access (the daemon wires * `restartAgentSession` + cron re-arm). Absent: `moveAlive` is refused. */ restartSession?: (prev: SessionDescriptor, overrides: { access: { profileRef: string; }; }) => Promise<{ id: string; rearmedCrons?: string[]; }>; /** Slot map source. Defaults to config.json. */ loadAccountSlots?: () => Promise; /** Write a swap. Defaults to config.json. */ applySwap?: (plan: AccountSlotSwapPlan) => Promise; /** Write a prefer. Defaults to config.json. */ applyPrefer?: (plan: AccountSlotPreferPlan) => Promise; /** Account health source for the per-account state in `account_slots_list`. */ accountHealth?: Pick; getAuthProfile?: ResolveProfileRefDeps["getAuthProfile"]; } interface AccountSlotSwapResult { family: string; dryRun: boolean; before: { primary: string; secondary: string; }; after: { primary: string; secondary: string; }; /** Alive sessions selected for the move (`moveAlive`); on a dry run, the * ones that WOULD move. */ moved: Array<{ from: string; to?: string; label: string; rearmedCrons?: string[]; }>; failed: Array<{ id: string; label: string; error: string; }>; } /** The swap, testable without an MCP server. */ declare function runAccountSlotSwap(deps: AccountSlotToolsDeps, input: { family: string; moveAlive?: boolean; dryRun?: boolean; }): Promise; interface AccountSlotPreferResult { slot: string; dryRun: boolean; /** The slot in order, before and after. */ before: string[]; after: string[]; moved: Array<{ from: string; to?: string; label: string; rearmedCrons?: string[]; }>; failed: Array<{ id: string; label: string; error: string; }>; } /** `accounts prefer`, testable without an MCP server. */ declare function runAccountSlotPrefer(deps: AccountSlotToolsDeps, input: { slot: string; profile: string; moveAlive?: boolean; dryRun?: boolean; }): Promise; /** * MCP tools over account health (`account-health.ts`): * * - `account_health_list`: every account the daemon knows about (the ones with * a health entry, plus every account listed in `accountSlots`): state * (`ok` / `exhausted` / `probing`), `until`, where `until` came from * (`untilBasis`), the reason, strikes, and for an Anthropic profile the * last remaining-quota figures a reader stored (no live probe, so nothing * is billed). * - `account_health_clear`: forget an account's entry, for the day it is * topped up before its `until`. * * The CLI (`agentproto accounts health [--clear ]`) is a thin wrapper * over these two tools. */ interface AccountHealthToolsDeps { /** Health source. Defaults to `~/.agentproto/account-health.json`. */ store?: AccountHealthStore; /** Slot map source. Defaults to config.json's `accountSlots`. */ loadAccountSlots?: () => Promise; /** Profile lookup, to read an account's endpoint. Defaults to the auth store. */ getAuthProfile?: (id: string) => Promise<{ endpoint: string; } | undefined>; /** Last stored remaining quota of a profile. Defaults to the usage-quota store. */ readQuota?: (profileRef: string) => Promise; } interface AccountHealthRow { profileRef: string; state: "ok" | "exhausted" | "probing"; until?: string; untilBasis?: AccountHealthView["untilBasis"]; reason?: string; since?: string; strikes?: number; /** Slots whose slot lists this account. */ slots?: string[]; /** Anthropic profiles: the last remaining-quota figures a reader stored. */ quota?: { fetchedAt: string; windows: StoredProfileQuota["windows"]; }; } /** The list, testable without an MCP server. */ declare function listAccountHealthRows(deps?: AccountHealthToolsDeps): Promise; /** The summary `daemon_health` carries: closed accounts and when they return. */ declare function summarizeAccountHealth(store?: AccountHealthStore): Promise>; type AnySpec = DoctypeSpec; declare function makeRestartForRouting(deps: { sessions: SessionsRegistry; resolveAgentAdapter: AgentAdapterResolver | undefined; /** Daemon's own `/mcp` base URL — threaded into `restartPreferInPlace` so * a new-id restart re-stamps `mcpServers`' `callerSessionId` with the * FRESH session's id instead of either keeping the dead OLD id or (worse) * silently stripping it to no identity at all — see * `RestartAgentSessionOptions.daemonMcpUrl`'s doc (session-restart-core.ts). */ daemonMcpUrl?: string; }, config: { name: string; allowDeliberateEnd: boolean; }): (id: string) => Promise; interface CreateGatewayOptions { /** Absolute path to the workspace dir. */ workspace: string; /** AIP doctype specs to expose as MCP CRUD verbs. */ specs: readonly AnySpec[]; /** Port to bind. Default 18790. */ port?: number; /** Bind host. Default `127.0.0.1` (loopback). Set `0.0.0.0` for LAN. */ bind?: string; /** Auth mode. Default `none` (safe only on loopback). */ auth?: AuthOptions; /** Opt-in eager resume-on-boot (§5 "Opt-in vs automatic", PR-4). Mirrors the * `daemon.resumeSessionsOnBoot` config knob; the CLI resolves the knob and * passes it here. When true, the `resumeSessionsOnBoot()` handle method * actually runs the bounded boot pass; when false/omitted it short-circuits * to an `enabled: false` summary. Also surfaced in `daemon_health` / * `GET /health` so an operator can see the effective value. */ 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 after * a daemon restart. Mirrors the * `daemon.bootResumeKeepAliveMaxIdleMinutes` config knob; default 30. A * `keepAlive` row idle longer than this (measured from its last turn-end) * stays dead-but-lazy-resumable instead of being respawned on every boot. * Only explicitly pinned rows are always resumed; an operator label does * not exempt a row. 0 disables the cutoff. */ bootResumeKeepAliveMaxIdleMinutes?: number; /** Boot re-ensure of app-service owners. Mirrors the * `daemon.resumeServicesOnBoot` config knob; DEFAULT ON (services are * deterministic processes, so the agent-adapter spawn-storm concerns * behind `resumeSessionsOnBoot`'s default-off do not apply). When * explicitly false, `reensureAppServicesOnBoot()` short-circuits to an * `enabled: false` summary. Surfaced in `daemon_health` / `GET /health`. */ resumeServicesOnBoot?: boolean; /** Opt-in continue-on-boot. Mirrors the `daemon.continueInterruptedOnBoot` * config knob; when true, the `continueInterruptedOnBoot()` handle method * runs the boot continue pass (see `continue-interrupted.ts`); when * false/omitted it short-circuits to an `enabled: false` summary. Surfaced * in `daemon_health` / `GET /health`. */ continueInterruptedOnBoot?: boolean; /** Idle agent-session reaper threshold in ms (PR-6). Mirrors the * `daemon.idleReapAfterMs` config knob; the CLI resolves it (env > * config > off) and passes it here. When positive, the gateway starts a * periodic sweep that retires agent-cli sessions idle longer than this * (SIGTERM the adapter child, flip to `killed`/`endedReason:"idle-reaped"`, * kept lazy-resumable). Unset / 0 / negative ⇒ the reaper never runs. * Surfaced in `daemon_health` / `GET /health`. */ idleReapAfterMs?: number; /** Idle threshold in ms for SANDBOXED sessions. Mirrors the * `daemon.sandboxIdleReapAfterMs` config knob (the CLI resolves env > * config > default). DEFAULT ON, unlike `idleReapAfterMs`: unset applies * {@link DEFAULT_SANDBOX_IDLE_REAP_AFTER_MS} (15 min); an explicit * non-positive value turns it off. A sandboxed session idle this long gets a * final checkpoint, its box torn down and a ledger row; it stays revivable * on a fresh box. Surfaced in `daemon_health` / `GET /health`. */ sandboxIdleReapAfterMs?: number; /** Crash-detect sweep interval in ms (crash-detect PR-1). Mirrors the * `daemon.crashDetectIntervalMs` config knob; the CLI resolves it (env > * config > a sane default — DEFAULT ON, unlike `idleReapAfterMs`) and * passes it here. The gateway starts a periodic sweep that probes every * live agent-cli session's OS process and marks the row `error`/ * `endedReason:"crashed"` when it's provably gone * (`registry.markCrashed`, driven by `runCrashDetectPass`). Non-positive ⇒ * the sweep never runs. Surfaced in `daemon_health` / `GET /health`. */ crashDetectIntervalMs?: number; /** Restart-scheduler sweep interval in ms (restart-scheduler PR-2). Mirrors * the `daemon.restartSweepIntervalMs` config knob; the CLI resolves it * (env > config > off) and passes it here. OFF by default — unlike * `crashDetectIntervalMs`, a positive value here doesn't itself opt any * session in, it only arms the periodic sweep that EXECUTES an already- * scheduled restart for a session that carries a per-session * `restartPolicy` (`agent_start.restartPolicy`). The event-driven half * that SCHEDULES a restart (`createRestartScheduler`, subscribing to * `session:exited`) runs regardless of this knob — it just has nothing to * execute against until the sweep is armed. Non-positive / undefined ⇒ * the sweep never runs, so a scheduled `nextRestartAt` sits inert. * Surfaced in `daemon_health` / `GET /health`. */ restartSweepIntervalMs?: number; /** `daemon.sandboxGoneRestartDefault` — OFF unless set. When true, a BOX * session spawned with no explicit `agent_start.restartPolicy` is stamped * with {@link SANDBOX_GONE_DEFAULT_RESTART_POLICY}, so a box session whose * box is gone is moved to a fresh box by the restart scheduler instead of * staying dead. An explicit per-session `restartPolicy` always wins, and * nothing else changes — classic `crashed`/`error` in-place revival still * needs its own opt-in. Turning this on with `restartSweepIntervalMs` * unset also arms the sweep at 30s (the scheduler only SCHEDULES; the * sweep EXECUTES), so the opt-in works out of the box. */ sandboxGoneRestartDefault?: boolean; /** Turn-liveness watchdog threshold in ms (turn-liveness-watchdog * chantier). Mirrors the `daemon.turnStallAfterMs` config knob; the CLI * resolves it (env > config > a sane default — DEFAULT ON, same shape as * `crashDetectIntervalMs`) and passes it here. The gateway starts a * periodic sweep that flags a BUSY agent-cli session mid-turn, not * legitimately `blockedOn` a subagent/command, and silent past this * threshold: stamps `stalledSinceMs` and emits `session:stalled` * (`registry.markStalled`, driven by `runStallWatchdogPass`). Non-positive * ⇒ the sweep never runs. Detects only; never kills or restarts. Surfaced * in `daemon_health` / `GET /health`. */ turnStallAfterMs?: number; /** Liveness window (ms) of an `external` session after its last MCP request * / inbox poll. Mirrors `daemon.externalSessionLivenessMs`; unset or * non-positive ⇒ the registry default (30 min). */ externalSessionLivenessMs?: number; /** * Resolves a heartbeat-runnable agent from its workspace id. * Required for HEARTBEAT.md to do anything; without it ticks emit * `heartbeat-error` events instead of generating. */ buildAgent?: BuildHeartbeatAgent; /** Server name advertised over MCP. */ name?: string; /** Server version advertised over MCP. */ version?: string; /** Build identity of the binary actually serving — surfaced verbatim via * `/health` and `daemon_health` so an operator can tell a workspace dist * from the published tarball of the same version. `sha`/`builtAt` are * stamped into the CLI at build time (tsup `define`); `source` is the * serve command's runtime judgement of where its own entry lives. */ build?: { /** Short git sha of the checkout the dist was built from ("" when the * build ran outside git). */ sha?: string; /** ISO timestamp of the build. */ builtAt?: string; /** "workspace" (a checkout's dist), "published" (npm/npx install), or * "unknown". */ source?: string; }; /** * Run BOOT.md once at startup. Pass `false` to disable. Defaults to * `true`. The boot file is plain markdown — frontmatter-free; the * agent named in `defaultBootAgent` (or skipped if unset) gets the * body as a single prompt and the reply is appended to a `boot-` * conversation. */ boot?: boolean; /** Agent id used for BOOT.md if no per-file frontmatter. */ defaultBootAgent?: string; /** Optional adapter resolver — when provided, enables * `POST /sessions/agent` (long-running agent CLIs like * claude-code / hermes via the @agentproto/cli adapter system). * Without this, /sessions still works for raw `argv` spawns. */ resolveAgentAdapter?: AgentAdapterResolver; /** Optional adapter lister — when provided, enables * `GET /adapters` HTTP route + `adapter_list` MCP tool so UIs * can discover what's installed on the host. */ listAgentAdapters?: AgentAdapterLister; /** Optional harness capability-discovery lister — when provided, enables * the `harness_capabilities` MCP tool so callers can introspect what an * installed adapter can actually DO on this host (creds present, * reachable providers, model-discovery mechanism, endpoint compat, * application contract), not just its static manifest fields. */ listHarnessCapabilities?: AdapterCapabilitiesLister; /** Optional adapter installer — when provided, enables * `POST /adapters/:slug/install` HTTP route + `adapter_install` MCP * tool so UIs can install a not-yet-installed harness. Hosts ship the * cli's `installAdapter`. */ installAgentAdapter?: AgentAdapterInstaller; /** Optional catalog lister — when provided, enables * `GET /catalog/models` HTTP route + `catalog_models` MCP tool * (SPEC §5) so UIs can discover every runnable model + route without * trial-and-error against a spawn. */ listCatalogModels?: CatalogModelsLister; /** Optional browser adapter resolver, used by the HTTP * `POST /sessions/browser` route only (no MCP tool since P4). * P4b: removed with that route. */ resolveBrowserAdapter?: BrowserAdapterResolver; /** Optional browser adapter lister, used by the HTTP browser routes only * (no MCP tool since P4). P4b: removed with them. */ listBrowserAdapters?: BrowserAdapterLister; /** Optional PTY factory (node-pty wrapper, typically from the cli * layer's `loadNodePtyFactory()`). When provided, enables * `POST /sessions/terminal`, the `terminal_start` MCP * tool family, and the `/sessions/:id/pty` WebSocket. Without it, * those routes return 501 / the MCP tools aren't registered. */ spawnPty?: PtyFactory; /** Enable filesystem persistence for every store this gateway owns — * the sessions registry plus the supervisor / routine / cron / workflow * / inbound-watcher run stores. Defaults to `true`, i.e. production is * unchanged. * * Tests pass `false`. Without it, a test gateway writes its fake rows * into the *developer's real* `~/.agentproto/sessions.json` (and the * sibling `policies.json` / `cron-jobs.json` / `workflow-runs.json`): * those paths resolve off `homedir()`, and the gateway opted each store * into persistence unconditionally. Since `loadHistorySnapshot` re-reads * sessions.json at boot, the real daemon then restores the fakes and * shows them in the dashboard — and against `HISTORY_CAP` (200) they * evict genuine history. * * The sibling stores already default to persist-off when constructed * directly (see `createWorkflowRunner`); this knob is what lets a * gateway stop overriding that on their behalf. */ persist?: boolean; /** Override the sessions-registry persistence path — tests pin a tmpdir * so an assertion can look at the file the gateway would have written * instead of the developer's real one. Defaults to * `~/.agentproto/sessions.json`. The structured-transcript dir follows * this path's parent, so pinning it isolates transcripts too. */ persistPath?: string; /** Service-owner store shared by `registerAppTools` (app_install/...) * and the boot re-ensure pass. Tests inject a store to observe/seed the * owner records both consumers read and write. Default: one store from * the resolved `persist` switch (`~/.agentproto/app-services.json` in * the daemon, in memory when persistence is off). */ appServiceStore?: AppServiceStore; /** Override the per-boot bearer token. Default: `randomUUID()`. * Tests can pin a known value; production should always let * the gateway generate fresh. The token is written into * `/.agentproto/runtime.json` (mode 0600) and required * on mutating `/sessions/*` routes + the PTY WS upgrade. */ token?: string; /** Trusted browser origins allowed to drive mutating routes * without a bearer token. See `RuntimeHttpServerOptions.allowedOrigins` * for match semantics. Default: localhost on any port. */ allowedOrigins?: readonly string[]; /** When true, drop the localhost-wildcard defaults — only the * explicit `allowedOrigins` list is honoured. */ strictOrigins?: boolean; /** Extra `frame-ancestors` sources for `GET /apps/:appId/ui`, added to the * built-in `vscode-webview:` / `vscode-file:` defaults. Passed straight * through to `startHttpServer`; see `RuntimeHttpServerOptions.frameAncestors` * (the caller is expected to have validated the entries). */ frameAncestors?: readonly string[]; /** * Opt-in deferred/lazy MCP tool loading (harness-parity item 3, see * `deferred-tools.ts`). When set, every root-gateway tool outside * `alwaysOn` registers but starts disabled — excluded from the first * `tools/list` — until the always-on `tool_search` meta-tool pulls it * in by keyword. Omitted (default) → every tool is eagerly enabled, * identical to pre-existing behaviour. Does not affect the scoped * `/mcp/orchestrator` sub-gateway, which already exposes a small * curated allowlist (`DEFAULT_ORCHESTRATOR_TOOLS`). */ deferredTools?: { alwaysOn?: readonly string[]; }; /** * Boot-time MCP surface profile (`defaults.mcp.profile`, see * `tool-profiles.ts`): `core`, `orchestrator`, `apps`, `admin`, `full`, or * a comma-composed list. Omitted ⇒ `full` (every tool registered, exactly * the pre-profile behaviour). A per-request `?profile=` wins over this. */ mcpProfile?: string; /** * Optional sandbox provider resolver — overrides the sandbox family's * default resolver (built-ins + `@agentproto/sandbox-` dynamic * import) used by `list_sandbox_providers` / `setup_sandbox_provider` * AND `agent_start.sandbox`. Mirrors `resolveAgentAdapter`'s injection * shape. */ resolveSandboxProvider?: SandboxProviderResolver; /** Optional sandbox provider lister — mirrors `listAgentAdapters`. * Overrides the default catalog-driven lister behind `list_sandbox_providers`. */ listSandboxProviders?: SandboxProviderLister; /** * Optional git-worktree provisioner powering `agent_start.worktree` and the * `worktrees.isolation` policy. Injected here (rather than defaulted inside * the runtime like `resolveSandboxProvider`) because provisioning runs the * `@agentproto/worktree` TOOL, a dependency the runtime deliberately does * NOT take — see `worktree-identity.ts` / `worktree-isolation.ts`. The CLI * wires it. Omitted → a spawn the policy says to isolate is rejected with * `worktree_provisioner_not_enabled` (never silently spawned unisolated). */ provisionWorktree?: WorktreeProvisioner; /** * Optional git-worktree status lister powering `worktree_status`. * Injected here (rather than defaulted inside the runtime) because the join * runs over `@agentproto/worktree`, a dependency the runtime deliberately * does NOT take. The CLI wires it. Omitted → `worktree_status` returns a * clear "not enabled" error. */ listWorktreeStatuses?: WorktreeStatusLister; /** * Optional git-worktree `gc` runner powering `worktree_gc` (+ the parallel * HTTP surface). Injected for the same reason as `listWorktreeStatuses`: * the plan/apply engine runs over `@agentproto/worktree`, a dependency the * runtime deliberately does NOT take. The CLI wires it. Omitted → * `worktree_gc` returns a clear "not enabled" error. */ runWorktreeGc?: WorktreeGcRunner; /** * Optional branch-`gc` runner powering `branch_gc` (+ `POST /branches/gc`). * Injected for the same reason as `runWorktreeGc`. Omitted → `branch_gc` * returns a clear "not enabled" error. */ runBranchGc?: BranchGcRunner; /** * Optional sandbox-checkpoint-`gc` runner powering * `sandbox_checkpoint_gc`. Injected for the same reason as `runBranchGc`. * Omitted → the tool returns a clear "not enabled" error. */ runSandboxCheckpointGcSweep?: SandboxCheckpointGcRunner; /** Optional verdict recorder powering `branch_gc_verdict` (+ `POST /branches/gc/verdict`). */ recordBranchGcVerdict?: BranchGcVerdictRecorder; /** Optional verdict reader powering `branch_gc_verdict_get`. */ readBranchGcVerdict?: BranchGcVerdictReader; /** Optional restorer powering `branch_gc_restore`: re-creates refs from a restore log. */ restoreBranchGc?: BranchGcRestorer; /** Optional operator approver powering `POST /branches/gc/approve` (the * `agentproto branch gc approve` CLI). HTTP only: no session tool reaches it. */ approveBranchGcVerdict?: BranchGcOperatorApprover; /** * Optional best-effort exit-time reclaim of ONE policy-provisioned * (implicit) session's own worktree — powers `SessionDescriptor. * worktreeAutoProvisioned` (see that field's doc in `sessions.ts`). * Injected for the same reason as `runWorktreeGc`: the classify/remove * logic runs over `@agentproto/worktree`, a dependency the runtime * deliberately does NOT take. The CLI wires it (over `reclaimOneWorktree`). * Omitted → exit-time auto-reclaim is simply skipped; an implicit * worktree is still reclaimable manually or via a scheduled `gc` sweep. */ runWorktreeAutoReclaim?: WorktreeAutoReclaimer; /** Native-TUI usage readers by harness slug, forwarded to the sessions * registry (`createTerminalUsageReaders`). Omitted → terminals carry no * usage. */ terminalUsageReaders?: Record; /** * Optional best-effort exit-time deletion of one sandboxed session's * `agentproto-checkpoint/` remote ref once its work is provably * elsewhere (see `sandbox-checkpoint-gc`, the engine over * `@agentproto/worktree`). Injected like `runWorktreeAutoReclaim` because * the classify/delete logic runs there. Omitted → nothing is deleted at * exit; `agentproto sandbox checkpoint-gc` remains the manual tool. */ runSandboxCheckpointGc?: SandboxCheckpointReclaimer; /** * Optional resolver: given a session's cwd, return the OPEN PR for that * cwd's git branch (or null). Powers the daemon PR-provenance reconciler, * which stamps the `@agentproto-bot` footer onto PRs an executor session * opened through its OWN shell — the path `command_execute` (the only other * stamp trigger) never observes. Injected here because branch→PR resolution * runs over `@agentproto/worktree`, a dependency the runtime deliberately * does NOT take. The CLI wires it. Omitted → the reconciler is not started * (footer stamping stays limited to the `command_execute` path). */ resolveOpenPr?: OpenPrResolver; /** * Optional resolver: given a PR url, return its current forge state * (`"open" | "merged" | "closed"`, or `null` when unresolvable). Powers the * Activity projector's PR settlement pass — a `pr` activity pending on the * forge becomes terminal (`done` when merged, `cancelled` when closed) once * this port reports the verdict. Injected here because forge access runs * over `@agentproto/worktree`, a dependency the runtime deliberately does * NOT take. The CLI wires it. Omitted → pr activities never settle (they * stay pending on the forge, the pre-settlement behaviour). */ resolvePrState?: PrStateResolver; /** * Optional E2E pairing registry (see `createPairingRegistry`). When wired, * the gateway mounts the `/pairings/*` REST routes and the `pair_*` MCP * tools, and exposes the registry on the handle. The CLI builds it (injecting * the ws `dial` + a `createTunnelServer`-backed `serve`) and passes it here so * the runtime stays free of pty/adapter concerns while the pairing surface is * reachable over MCP + HTTP. Autoconnect is the caller's to start (after this * returns) so the injected `serve` can capture the finished gateway. */ pairingRegistry?: PairingRegistry; /** * Optional HOST registry (see `createHostRegistry`, DEVICES-PLAN PR-C) — * the reverse-pairing "client" half of pair/v2, living daemon-side. When * wired alongside `pairingRegistry`, the gateway layers registered hosts * into `device_list`/`GET /devices`, and enables the `device_add` MCP tool * plus `POST /devices/add` + `POST /devices/:id/exec`. Unlike * `pairingRegistry`, this registry keeps no standing connections — every * `add`/`forwardHttp` dials fresh — so there is nothing for the gateway to * autoconnect or tear down on shutdown. */ hostRegistry?: HostRegistry; /** * Optional JOIN TOKEN registry (see `createJoinTokenRegistry`, * SANDBOX-VISIBILITY-JOIN). When wired alongside `pairingRegistry` + * `hostRegistry`, the gateway mounts `POST/GET /devices/join-tokens` + * `DELETE /devices/join-tokens/:id`, the `join_token_create/list/revoke` * MCP tools, and `device_sessions`/`GET /devices/:id/sessions[/…/output]`. * Autoconnect is the caller's to start (after this returns), same as * `pairingRegistry`. */ joinTokens?: JoinTokenRegistry; /** 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; /** Mirrors `config.features.deviceInferenceShare` (DEVICES-PLAN item 1). * Default false. Only meaningful alongside `llmEndpoint: true` — passed * straight through to `startHttpServer`'s `deviceInferenceShare`, which * gates `/device-inference/*` (see http-server.ts's `HOST_SCOPE_HEADER` * doc comment for the full scope-gate story). */ deviceInferenceShare?: boolean; /** Mirrors `config.features.deviceSpawnAllow` (DEVICES-PLAN PR-D). Default * false. Passed straight through to `startHttpServer`'s * `deviceSpawnAllow`, which gates `/device-spawn/*` — this daemon acting * as the RECEIVING end of an `agent_start({ sandbox: "device:" })` * spawn driven from a paired controller. */ deviceSpawnAllow?: boolean; } /** * Default always-on set when `deferredTools` is enabled without an * explicit `alwaysOn` override: the core spawn/drive/observe/report loop * most sessions need immediately — including an EXECUTOR (the role * `deferredTools` defaults on for, see `role.ts`), which cannot spawn * (`agent_start`/`agent_prompt` are stripped for it anyway by * `toolPolicy.delegation: "deny"`, so those two names are simply absent * from a deny-role's registry and cost nothing) but still needs to report * back to its parent (`message_parent`), coordinate over the task ledger * (`task_*`), and observe its own session/turn state and capabilities * (`session_context_status` / `session_capabilities` alongside the * pre-existing `session_list` / `session_monitor` / `session_events_poll`). * Everything else (fs_*, directory_*, command_*, remote_*, browser_*, terminal_*, mcp_*, * routine_*, workflow_*, policy_*, inbound_watcher_*, session_tree, * agent_export, adapter_list, every `app_ui_*` panel tool, ...) starts * deferred — reachable via `tool_search`, never removed from `tools/call`. */ declare const DEFAULT_ALWAYS_ON_TOOLS: readonly string[]; interface GatewayHandle { url: string; workspace: string; workspaceFs: WorkspaceFs; registered: readonly string[]; /** Sessions registry — exposed so MCP tools / external spawners * inside the same process can register their child processes for * visibility through /sessions and the CLI TUI. */ sessions: SessionsRegistry; /** Tunnel registry — manages public cloudflared tunnels for any * local port. Exposed so embedding hosts can open tunnels * programmatically without going through the HTTP/MCP surface. */ tunnels: TunnelRegistry; /** E2E pairing registry, when one was wired via * `CreateGatewayOptions.pairingRegistry`. Undefined otherwise. Exposed so * the CLI can `startAutoconnect()` after boot and `shutdown()` it. */ pairing?: PairingRegistry; /** HOST registry, when one was wired via `CreateGatewayOptions.hostRegistry` * (DEVICES-PLAN PR-C). Undefined otherwise. No autoconnect/shutdown to * call on it — see that option's doc comment. */ hosts?: HostRegistry; /** JOIN TOKEN registry, when one was wired via * `CreateGatewayOptions.joinTokens` (SANDBOX-VISIBILITY-JOIN). Undefined * otherwise. Exposed so the CLI can `startAutoconnect()` after boot and * `shutdown()` it, same as `pairing`. */ joinTokens?: JoinTokenRegistry; /** Per-boot bearer token required on mutating /sessions/* routes * + WS PTY upgrades. Exposed so an embedding host (e.g. the CLI * shell that hosts the gateway in-process) can pass it to child * tools without re-reading the runtime.json file. */ token: string; /** Mint a scope-token for the scoped orchestrator sub-gateway * (`/mcp/orchestrator`). The returned `token` gates that endpoint * and `tools` is the effective allowlist (⊆ the default orchestrator * subset). WP3 will call this at spawn time and inject the URL into * the child's `mcpServers`; for WP2 it's the internal primitive. */ mintOrchestratorScope(opts?: { tools?: readonly string[]; }): OrchestratorScope; /** Run the opt-in eager resume-on-boot pass (§5, PR-4) and return its tally. * A no-op returning `{ enabled: false, ... }` when the * `resumeSessionsOnBoot` config knob is off. The caller (serve.ts) invokes * this AFTER the stale-runtime sweeps — which is after `createGateway` * returned, hence after the supervisor was re-armed (§5 "Event ordering") — * and turns the summary into the boot-banner line. `isServed` is the * cross-process gate: serve.ts supplies a predicate that keeps a daemon from * resuming a sibling daemon's workspace rows out of the shared buckets. */ resumeSessionsOnBoot(opts?: { isServed?: (desc: SessionDescriptor) => boolean; }): Promise; /** Run the opt-in continue-on-boot pass and return its tally — a no-op * returning `{ enabled: false, ... }` when the `continueInterruptedOnBoot` * knob is off. serve.ts invokes this right AFTER `resumeSessionsOnBoot()` * (so a row whose eager resume failed is recognisable and skipped) — and * therefore, like it, after the supervisor was re-armed, so a re-armed * completion policy sees the continue turn's turn-end. Same `isServed` * cross-process gate. */ continueInterruptedOnBoot(opts?: { isServed?: (desc: SessionDescriptor) => boolean; }): Promise; /** Boot re-ensure of app-service owners (Orchestrator phase 1b item 2). * `app_install`'s `ensureServices` runs only on the install path, so a * service whose owner died with the previous daemon stays down until the * next reinstall; this force-replaces every recorded owner at boot. Gated * by its OWN `resumeServicesOnBoot` knob (default ON — services are * deterministic processes, so the agent-adapter spawn-storm concerns * behind resumeSessionsOnBoot's default-off don't apply); a no-op * returning `{ enabled: false, ... }` when it is disabled. serve.ts calls * this AFTER the resume/sandbox passes so it never races them for an owner * session id. */ reensureAppServicesOnBoot(): Promise<{ enabled: boolean; apps: number; spawned: number; errors: string[]; }>; /** Daemon-startup backfill for the per-session index sidecars * (`session-index.ts`): create a compact `index.json` for every session dir * that lacks one, recovering the last prompt/output from the transcript * tail (never a whole-file parse). Async, batched and best-effort — the * scan yields to the event loop between batches, so a store with * thousands of sessions never blocks boot. serve.ts fires this once at * boot (not awaited) so `agentproto sessions find`/`recap` answer * instantly even for sessions that predate the sidecar. */ backfillSessionIndexes(): Promise<{ scanned: number; created: number; skipped: number; }>; /** Run the sandbox reattach pass: reconnect to provider boxes whose * sessions the previous daemon process detached from, re-binding each to * its original session id. serve.ts calls this BEFORE * `resumeSessionsOnBoot()` so the eager/continue passes never touch a row * that is about to be re-attached. Always on — it only acts on rows that * were detached. `isServed` is the same cross-process gate. */ reattachSandboxSessionsOnBoot(opts?: { isServed?: (desc: SessionDescriptor) => boolean; }): Promise; /** Run the reaction receipt boot reconciliation pass and return the post-pass * tally. Never throws: a failure is logged and reported as zeros. */ reconcileReactionsOnBoot(): Promise<{ total: number; pending: number; running: number; failed: number; dead: number; }>; /** The gateway's approvals engine. Exposed so an embedding host (and a test * standing in for a human channel) can read a decision's state without * going through HTTP. Nothing on it is model-reachable; only the declared * human channels can decide. */ approvals: ApprovalsEngine; stop(): Promise; } /** * Spin up the gateway. Order: * 1. Build MCP server + load AIP-40 extensions * 2. Build conversation store + workspace fs adapter * 3. (optional) Run BOOT.md once * 4. Start HTTP server * 5. Start heartbeat ticker * * `stop()` reverses 4–5 (heartbeat first, then HTTP). The MCP server * is owned by the HTTP server's per-session transports and is closed * implicitly when those close. */ declare function createGateway(opts: CreateGatewayOptions): Promise; export { ACCOUNT_SLOT_NAME_RE, ADAPTER_FIELD_DEPRECATION, type AccountHealthRow, AccountHealthStore, AccountHealthView, AccountSlotPreferPlan, type AccountSlotPreferResult, AccountSlotSwapPlan, type AccountSlotSwapResult, AccountSlots, AdapterAuthDescriptor, AdapterCapabilitiesLister, AgentAdapterInstaller, AgentAdapterLister, AgentAdapterResolver, type AppTunnelResult, type ArgumentsResult, type AttachSandboxOpts, type AttachSandboxResult, BUCKETS_ROOT, BranchGcOperatorApprover, BranchGcRestorer, BranchGcRunner, BranchGcVerdictReader, BranchGcVerdictRecorder, type BrowserAdapterHandle, BrowserAdapterInfo, BrowserAdapterLister, BrowserAdapterResolver, type BrowserAttachEvent, type BrowserCallEvent, type BrowserCallResultEvent, type BrowserDetachEvent, type BrowserObserver, type BrowserObserverModuleApi, type BrowserObserverRegistration, type BrowserScreenshotImage, BuildHeartbeatAgent, CLAMP_LIMIT_BYTES, COLD_TTL_MS, CONTINUE_PROMPT_SOURCE, CallerRefusedError, type CallerScope, CallerScopes, type CapabilitiesInventory, type CapabilitiesInventoryMcp, type CapabilitiesInventorySkills, CatalogModelsLister, type CatalogProviderModel, type CatalogProviderModelsQuery, type CatalogProviderModelsResponse, type CatalogProviderPricing, type ChallengeFailureReason, type ChallengeOutcome, type ClaudeNativeRef, type CollectSandboxInventoryOpts, CompletionPolicySupervisor, type ComposeCandidate, ContextProfile, type ContinueInterruptedMode, type ContinueInterruptedOutcome, type ContinueInterruptedResult, type ContinueInterruptedSkipReason, type ContinueOnBootSummary, type ConversationIndexRecord, type ConversationNativeRef, type CostBudgetDecision, type CrashDetectSummary, type CrashReaperRegistry, type CreateGatewayOptions, type CreateReviewRunnerOptions, CredentialSource, DEAD_SESSION_STATUSES, DEFAULT_ALWAYS_ON_TOOLS, DEFAULT_BUCKET, DEFAULT_CONTINUE_PROMPT, DEFAULT_EGRESS_COOLDOWN_MS, DEFAULT_EGRESS_HEALTH_PROVIDER, DEFAULT_HOST_LOAD_BUDGET_MS, DEFAULT_HOST_LOAD_THRESHOLDS, DEFAULT_PAUSED_BOX_MAX_AGE_MS, DEFAULT_SANDBOX_GC_INTERVAL_MS, DEFAULT_SANDBOX_IDLE_REAP_AFTER_MS, DEFAULT_TTL_MS, DEVICE_PROMPT_PATH_PREFIX, type DaemonReviewerHostDeps, DeclaredAdapterOption, type DeclaredAdapterPreset, type DeliveryOutcome, type DeliveryReplay, type DeliveryState, type Device, type DeviceKind, type DeviceMirrorSyncResult, type DeviceMirrorTarget, type DevicePromptSessionsLike, type DeviceRegistry, type DeviceRole, type DiskLoad, EVENT_REGISTRY, type EagerResumeSummary, EffortLevel, type EgressCooldownEntry, type EgressDispatcher, type EgressHealthErrorClass, type EgressHealthLedger, type EgressHealthReport, type EgressHealthSlotView, type EgressProbeReport, type EgressProbeSlotResult, type EventDefinition, type EventRegistration, type EventsListContext, type EventsListRequest, type EventsListResult, type EventsSubscribeContext, type EventsSubscribeInput, type EventsSubscribeResult, type EventsUnsubscribeContext, type EventsUnsubscribeInput, type ExecSandboxCommandOptions, type FetchHostTurnsResult, type FindComposeCandidateInput, FollowTriageConfig, ForwardHttpRequest, ForwardHttpResponse, GC_REAPABLE_STATES, GITHUB_SCHEME, GONE_RE, type GatewayHandle, type GhRunner, HARNESS_ALIAS_REMOVAL, HOST_CALLER, type HarnessPreset, type HarnessPresetOverlay, type HarnessPresetValidationDeps, HarnessPresetValidationError, type HarnessPresetsFile, type HermesNativeRef, type HostEventRecord, type HostLoadCpu, type HostLoadDetail, type HostLoadMemory, type HostLoadReport, type HostLoadService, type HostLoadSwap, type HostLoadThresholds, type HostProbes, type HostProcess, type HostProcessOwner, HostRegistry, type HostSessionRollup, type HostWarning, type HostWarningKind, INDEX_DEFAULT_LIMIT, INDEX_MAX_OUTPUT, INDEX_MAX_PROMPT, INDEX_TAIL_BYTES, type IdleReapSummary, type IdleReaperRegistry, InboundRouteMode, type InboundWatcher, type InternalEventMeta, JoinTokenRegistry, LEGACY_SESSIONS_FILE, type LaunchedBy, type LedgerAnnotations, type LedgerEntry, type LedgerHostMeta, type LocatedConversation, type LocatedConversationByPath, MAX_ATTEMPTS, MAX_AUTO_CONTINUE_ATTEMPTS, MAX_EGRESS_COOLDOWN_MS, MAX_TTL_MS, MCP_APP_BRIDGE_SCRIPT, MIN_TTL_MS, MODEL_ROLE_PRESETS, type MaintainRunDeps, type MaintainRunInput, type MaintainRunResult, type MarkEgressCooldownInput, type McpEventEnvelope, McpEventsError, type MeasurableTool, type MeasuredToolEntry, type MigrationMarker, ModelPolicy, type ModelRolesInput, type ModelRolesOutput, ORPHAN_GRACE_MS, type OpenPrForSessionInput, type OpenPrForSessionOutcome, type OpenPrResolver, OrchestratorScope, PUBLIC_BASE_HEADER, PolicyRunState, Posture, PrLookupError, type PrLookupErrorCode, PrStateResolver, type PrStatusSnapshot, type PresetInfo, type Principal, type PromptHostSessionInput, type PromptHostSessionResult, ProvisionInFlight, type PublicBase, type PublicBaseSource, QuotaReadableProfile, type RegisterBrainToolsOptions, type RegisterDeviceToolsOptions, type RegisterPairingToolsOptions, type RegisterReviewToolsOptions, type RegisterSandboxExecToolOptions, type RegisterWebSearchToolsOptions, RemainingQuotaReader, type RemoteUsageSnapshot, type ResolveNativeLinkInput, type ResolveSessionConfigInput, ResolvedAuthSpec, ResolvedModelRole, RestartOverrideError, type ReuseResolution, type ReviewComposeContext, type ReviewLedger, type ReviewLedgerFilter, type ReviewRun, type ReviewRunInput, type ReviewRunStatus, type ReviewRunner, type ReviewSignature, type ReviewSigningKey, type ReviewerRunResult, type ReviewerSessionHost, type RouteAwareLaunchConfig, type RouteAwareLaunchConfigInput, RouteSpec, type RuntimeMeta, SANDBOX_EXEC_MAX_COMMAND_BYTES, SANDBOX_EXEC_MAX_ENV_BYTES, SANDBOX_EXEC_STREAM_MAX_CHARS, SESSION_LIST_FILTER_KEYS, SESSION_RESTART_REASONS, SIGN_NAMESPACE, SLOT_REF_PREFIX, type SandboxCheckpointGcApplyOutcomeView, type SandboxCheckpointGcApplySummaryView, type SandboxCheckpointGcEntryView, type SandboxCheckpointGcPlanView, type SandboxCheckpointGcResult, type SandboxCheckpointGcRunInput, type SandboxCheckpointGcRunner, type SandboxCheckpointGcSummaryView, type SandboxCheckpointGcVerdict, SandboxCheckpointReclaimer, type SandboxConnectionDescriptor, type SandboxExecCommandChoices, type SandboxExecFile, type SandboxExecOutput, type SandboxExecResult, type SandboxGcCandidate, type SandboxGcLiveSession, type SandboxGcPassSummary, type SandboxGcProviderHandle, type SandboxGcReadDeps, type SandboxGcReapDeps, type SandboxGcReapResult, type SandboxGcSessionLineage, type SandboxGcTimer, type SandboxInventory, type SandboxInventoryProvider, type SandboxInventoryProviderInput, type SandboxInventorySource, type SandboxInventoryTotals, type SandboxLedgerEntry, type SandboxLedgerState, type SandboxOrphanCandidate, type SandboxOrphanGcPassResult, type SandboxOrphanReapResult, type SandboxOrphanScan, type SandboxOrphanScanDeps, SandboxProviderHandle, SandboxProviderLister, SandboxProviderResolver, type SandboxReattachSummary, type SandboxReconcileDeps, type SandboxReconcileProviderHandle, type SandboxReconcileResult, type SandboxReconcileRow, type SandboxReconcileVerdict, type SchemeRegistry, type SessionConfigAxes, type SessionConfigAxis, type SessionConfigLayer, type SessionConfigResolution, SessionDescriptor, type SessionFollowHandle, SessionFollowStore, type SessionIndexEntry, SessionListFilterError, type SessionListFilterInput, SessionMessage, SessionPresetResolutionError, type SessionRecap, type SessionReport, type SessionReportActiveEntry, type SessionReportCostBucket, type SessionReportCountEntry, type SessionReportInput, type SessionReportOpenedPr, type SessionReportPrEntry, type SessionReportTopEntry, type SessionRestartAction, SessionRestartError, type SessionRestartErrorCode, type SessionRestartErrorPayload, SessionUsage, type SessionUsageWithSubtree, type SessionWaitEvent, type SessionWaitResult, SessionsRegistry, type SkillPackInventoryEntry, type SkillsByHarnessEntry, SpawnDefaultsConfig, SsrfFetchError, type SsrfFetchInit, type SsrfFetchReason, type SsrfFetchResult, type StallWatchdogRegistry, type StallWatchdogSummary, StoredProfileQuota, type SubscriptionIdentity, type SubtreeChildUsage, type SubtreeUsageTotals, TOOL_PROFILE_NAMES, TerminalUsageReader, type ToolListMeasurement, type ToolProfileName, type TranscriptPrompt, type TranscriptTail, TriageFacts, UsageReadResult, UsageRollup, UsageSnapshotRecord, UserPreset, type VerifyCallbackInput, type VerifySignedAttestationResult, type WatcherDescriptor, type WatcherStartInput, type WebSearchInput, type WebSearchOutput, type WebSearchResult, type WebhookSignInput, type WebhookSignatureHeaders, type WorkspaceBrainSubscriber, type WorkspaceBrainSubscriberOptions, WorkspaceBrains, WorkspaceFs, WorktreeAutoReclaimer, WorktreeGcRunner, WorktreeProvisioner, WorktreeStatusLister, adapterDeprecation, addHarnessPreset, allowedSignersLine, appendConversationRecord, applySessionListFilters, attachSandbox, backfillSessionIndexes, backfillSessionIndexesAsync, bucketDir, bucketSessionsFile, bucketTranscriptDir, bucketsServedByOtherLiveDaemons, buildCatalogProviderModels, buildHostLoadReport, buildMcpConfigSnippet, buildRouteAwareLaunchConfig, buildSessionLink, buildSessionRecap, buildSessionReport, buildSessionReportFromRegistry, callerScopes, canonicalizeJcs, challengeCacheSize, challengeReasonForSsrf, claudeProjectSlug, coldSessionDescriptor, coldSessionRows, collectGcCandidates, collectHostSample, collectProviderOrphanCandidates, collectSandboxInventory, collectSessionReportInputs, compileSessionListFilters, composedFromRangeSha, computeHostWarnings, computeRefreshBefore, configureBrowserObservers, continueInterruptedSessions, continueSkipReason, conversationIndexPath, createDaemonReviewerHost, createDefaultHostProbes, createDeviceRegistry, createEgressHealthLedger, createGateway, createHostLoadService, createPrProvenanceReconciler, createReviewLaneExecutor, createReviewLedger, createReviewPackLoader, createReviewRunner, createWorkspaceBrainSubscriber, createWorkspaceOfCwd, daemonBearerPrincipal, daemonRegistryDir, declaredPresetToProviderPreset, decodeWhsecSecret, defaultBrowserAdapterIds, defaultBrowserAdapterResolution, defaultPresetFor, defaultReviewKeysDir, defaultReviewLedgerRoot, defaultReviewPackCacheDir, defaultTranscriptBaseDir, defineBraveSearchHttpDriver, defineSerperHttpDriver, deliverEventEnvelope, deliveryBackoffDelay, deriveIndexFromTranscript, deriveWsBaseUrl, describeOwner, egressHealthLedger, egressHealthPath, encodeWhsecSecret, enrichRollupWithProviderQuota, enrichWithRemainingQuota, ensureReviewSigningKey, envelopeClampedBytes, evaluateCostBudget, eventsList, eventsSubscribe, eventsUnsubscribe, execGh, execSandboxCommand, extractHelpSection, fetchHostTurns, fetchPrStatus, fileExists, findComposeCandidate, findConversationRecord, findEventDefinition, findPrForCommit, formatToolCall, formatToolResult, getDefaultHarnessPreset, getHarnessPreset, getHostLoadService, getToolHelp, githubRepoOf, harnessPresetsPath, hasSessionListFilters, hostPlaceholders, hostRecordToMirrorRecord, indexEntryFromDescriptor, injectMcpAppBridge, injectPublicBaseUrl, isAgentCliAuthConfigured, isAutomatedPromptSource, isEgressHealthErrorClass, isGoneError, isNoSessionPromptFailure, isNoiseSession, isPubliclyRoutable, isRetired, isReviewOrWorkflowSession, isSafeBucketSlug, launchedByOf, launchedByText, listAccountHealthRows, listBuckets, listHarnessPresets, listPresets, listToolHelpTopics, liveSessionBoxIds, loadBrowserObserverModule, loadHarnessPresets, loadWorkspaceModelRoles, locateConversationByNativePath, locateConversationBySessionId, makeBrowserAdapterLister, makeJevDecisionClassifier, makeRestartForRouting, matchesSessionQuery, measureTool, measureToolList, migrateLegacySessionsFile, migrationMarkerPath, mirrorCursorForSession, monitorPolicyWait, monitorSessionWait, normalizeCallbackUrl, normalizeRemote, openPrForSession, parsePausedBoxMaxAge, parsePrUrl, parseSessionListFilterParams, parseTimeBound, parseToolProfileList, pickSessionListFilters, prHeadSha, presetAxes, presetChain, probeEgressSlots, profilesExposingTool, projectRemoteUsage, promptDeviceSession, promptHostSession, readAllSessionIndexes, readConversationIndex, readDaemonRegistry, readEgressHealth, readRegisteredSlugs, readRuntimeMeta, readSandboxLedger, readSessionIndex, readTranscriptTail, readUsageSnapshots, reapGcEntry, reapSandboxOrphan, reconcileSandboxLedger, recordSandboxBoot, recordSandboxLiveness, recordSandboxOrigin, recordSandboxState, recordSessionDetach, registerBrainTools, registerBrowserObserver, registerBuiltinRoutes, registerDeviceTools, registerMaintainRunTools, registerPairingTools, registerReviewTools, registerSandboxAttachTool, registerSandboxEgressHealthTool, registerSandboxExecTool, registerWebSearchTools, removeHarnessPreset, removeSandboxLedgerEntry, repoSlug, resetChallengeCacheForTests, resetColdSessionCache, resolveBucketSlug, resolveDevicePromptMapping, resolveEffectiveLlmEndpointFlag, resolveHarnessAlias, resolveNativeLink, resolvePrincipal, resolvePublicBase, resolveRepoMaintenanceApp, resolveReuseFromLedger, resolveReviewerPreset, resolveSessionConfig, resolveSuccessor, resolveToolProfileAllowSet, resolveToolProfileSelection, restartBlockerCode, rollupSessionSubtree, runAccountSlotPrefer, runAccountSlotSwap, runContinueOnBootPass, runCrashDetectPass, runEagerResumePass, runIdleReapPass, runMaintainRun, runSandboxGcPass, runSandboxOrphanGcPass, runSandboxReattachPass, runShellLane, runStallWatchdogPass, sandboxGcShouldPause, sandboxLedgerPath, scanSandboxProviderOrphans, searchSessionIndexes, seedWalkForTranscript, serializeEnvelope, servingCliCommand, sessionActivityMs, sessionDescriptorFromIndexEntry, sessionEventsPath, sessionIndexPath, sessionListFilterShape, sessionPrincipal, sessionRestartErrorBody, sessionRestartErrorPayload, sessionRestartErrorStatus, sessionTranscriptDir, setDefaultPreset, setDefaultSessionsBaseDir, setEgressDispatcherForTests, setServingCli, signAttestation, signPublicBase, signWebhook, sortNewestActivityFirst, ssrfFetch, startSandboxGcTimer, subscriptionId, summarizeAccountHealth, summarizeSandboxCheckpointGcApply, summarizeSandboxCheckpointGcPlan, sweepStaleDaemonRegistry, sweepStaleRuntimeMetas, syncDeviceMirror, tenantScope, toMcpEvent, unlinkDaemonRegistryEntry, unlinkRuntimeMeta, unregisterBrowserObserver, untilForTtl, updateHarnessPreset, upsertSandboxLedger, validateAgainstInputSchema, verifyCallback, verifySignedAttestation, webSearchTool, wireSessionFollow, withPr, withPrStatus, withSandboxCheckpointGcApplySummary, writeDaemonRegistryEntry, writeSessionIndex };