/** One host-latched runtime choice; applied binds the captured revision and boundary, never a later value. */ export interface ModelOverrideSelection { readonly model: string | undefined; applied(nativeModel?: string): void; /** Retire only this still-unacknowledged capture after a definitive native pre-start rejection. */ rejected?(): void; } import type { ClaudeImplementerOptions } from "./claude-implementer.ts"; import type { ReviewerBackend, ReviewerPrintOptions } from "./reviewer-print.ts"; import type { SettingDef } from "../hub/settings.ts"; import type { CapabilityManifest } from "../hub/capabilities.ts"; import type { Addon } from "../hub/tooling.ts"; import type { RecoveryContinuityBookmark } from "../hub/recovery-continuity.ts"; import type { RecoveryPeer } from "../cli/upgrade.ts"; import type { Launch, StatusLineTee, FactsHook } from "../cli/launch.ts"; import type { LaunchMetadata, TerminalBinding, SessionRef } from "../cli/terminal-recovery.ts"; import type { UsageWindow } from "../hub/budget.ts"; import type { ContextReading } from "../hub/context-window.ts"; import type { PeerAdapter } from "../hub/peers.ts"; import type { PermissionMode } from "../hub/permission-mode.ts"; import type { AcpOptions } from "./acp.ts"; import type { CodexOptions } from "./codex-appserver.ts"; import type { JcodeOptions } from "./jcode.ts"; import type { LocalOptions } from "./local-worker.ts"; import type { PiOptions } from "./pi.ts"; import type { CompatId } from "./compat.ts"; import type { QwenDualOptions } from "./qwen-dual.ts"; import type { ClaudePrintOptions } from "./claude-print.ts"; import type { BuiltinCliEntry } from "./definitions/native-cli-entry-types.ts"; import type { NativePreviewBuilder } from "./definitions/native-cli-preview-common.ts"; export type StartForm = "tui" | "headless"; export type DaemonEngine = "codex-appserver" | "acp" | "qwen-dual" | "owned-acp" | "pi-rpc" | "local-worker" | "claude-print" | "reviewer-print" | "claude-implementer"; /** Existing buildLaunch inputs plus the startup-bound instance and project identity. */ export interface LaunchContext { instance: string; form: StartForm; projectRoot: string; stateDir: string; entrypoint: string; userArgs: string[]; unattended: boolean; proxyUrl?: string; /** Env var holding the terminal launch id; Codex sends it as the proxy upgrade's bearer token (#586). */ launchTokenEnv?: string; codexBin?: string; statusLine?: StatusLineTee; facts?: FactsHook; preview?: boolean; model?: string; fresh?: boolean; env: Readonly>; /** Existing validated config argv (or the existing redacted preview), never model input. */ nativeCommand?: readonly string[]; /** Existing trusted Pi builder inputs; never populated from a request or model. */ pi?: { options: Pick; extension: string; bridgePort: number | string; bridgeToken: string; }; } export type LaunchPlan = Launch & { env?: NodeJS.ProcessEnv; metadata: LaunchMetadata; mcpFile?: { path: string; entry: unknown } }; /** A factory receives exactly its existing transport options, with no cross-transport callback widening. */ export type DaemonPorts = | { codex: CodexOptions } | { acp: AcpOptions } | { qwenDual: QwenDualOptions } | { jcode: JcodeOptions } | { pi: PiOptions } | { local: LocalOptions } | { claudePrint: ClaudePrintOptions } | { reviewerPrint: ReviewerPrintOptions } | { claudeImplementer: ClaudeImplementerOptions }; export interface CreateContext { instance: string; projectRoot: string; stateDir: string; /** Host-derived private external-instance state namespace; stateDir remains the canonical daemon control directory. */ instanceStateDir?: string; kindConfig: unknown; permission: PermissionMode | "read-only"; mcpServers: NonNullable; daemon: Ports; } /** `native-stop`: Claude's transcript-verified Stop. `turn-completed`: Codex's `turn/completed` with no active turn. `agent-settled`: Pi's own settled event. `route-outcome`: the local worker's per-decision outcome. `prompt-response`: an ACP `session/prompt` response. `message-stop`: Qwen's TUI `message_stop`. */ export type SettleSignal = "native-stop" | "turn-completed" | "agent-settled" | "route-outcome" | "prompt-response" | "message-stop"; export const SETTLE_SIGNALS: readonly SettleSignal[] = Object.freeze(["native-stop", "turn-completed", "agent-settled", "route-outcome", "prompt-response", "message-stop"]); export interface StartRequest { instance: string; form?: StartForm; model?: string; route?: string; unattended?: boolean; replaceSession?: boolean; existing?: PeerAdapter; } export interface VersionContext { instance: string; observedVersion?: string; nativeCommand?: readonly string[]; projectRoot?: string; peer?: PeerAdapter; env: Readonly>; } /** Compatibility type for frozen A1 permission metadata, not a runtime permission port. */ export type NativeModeSpec = | { kind: "acp-mode"; modeId: string } | { kind: "codex-approval"; policy: string } | { kind: "launch-flag"; argv: string[] } | { kind: "hub-gate"; allow: readonly ("read" | "search" | "think")[] } | { kind: "native-only"; note: string }; export interface QuotaReader { source: string; read(value: unknown): UsageWindow[]; } export interface ContextReader { source: ContextReading["source"]; read(value: unknown, sessionId: string, measuredAt: number): ContextReading; } /** #445 C1: the manifest shape lives with its digest, sanitizer and share rules in `src/hub/capabilities.ts`; the `exec` class is gone (arbitrary execution is `destructive`). */ export type { Capability, CapabilityManifest, SideEffect } from "../hub/capabilities.ts"; export interface NativeFactsInput { event: "SessionStart" | "PreInvocation" | "PostInvocation" | "PreToolUse" | "PostToolUse" | "Stop" | "TurnStarted" | "StopFailure" | "Interrupt" | "SessionEnd" | "TaskStarted" | "Notification"; phase: "session" | "start" | "pre" | "post" | "stop"; sessionId: string; transcriptPath: string; workspacePaths: string[]; tool: string; input: Record; toolUseId?: string; invocation?: number; fullyIdle?: boolean; terminationReason?: string; /** #1402: the hook payload's `modelName` when it is a safe model id; the session's current model, never a per-response one. */ model?: string; } export interface NativeFactsReadOptions { completion?: boolean; sinceOffset?: number; unchanged?: { size: number; mtimeMs: number }; } export interface NativeFactsUsage { id: string; index: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; totalTokens: number; at?: string; } export interface NativeFactsTranscript { completion?: { id: string; index: number; reason?: "completed" | "failed" | "cancelled" }; started?: { id: string; index: number; origin: string }; background?: number; factIds: string[]; usage?: NativeFactsUsage[]; size?: number; mtimeMs?: number; scannedFrom?: number; unchanged?: boolean; } /** Fixed native codec and bounded readback, never supplied by project configuration. */ export interface NativeFactsPort { decode(event: string, input: unknown): NativeFactsInput | undefined; encode(event: string, text?: string): Record | undefined; read(session: string, transcript: string, options?: NativeFactsReadOptions): NativeFactsTranscript; } /** Only the frozen native seams are extensible; a definition cannot add an arbitrary daemon callback. */ export interface NativeHooks { factsHook: NativeFactsPort; pluginInventory(ctx: { home: string; cwd?: string; env: Readonly> }): Addon[]; recallSource: string; recallInjected: boolean; classifyTool(name: string, command?: string): "edit" | undefined; recallPlatform: string; } export type NativeConfigCheck = (value: unknown, key: string) => void; export interface NativeConfigValidators { bool: NativeConfigCheck; text: NativeConfigCheck; strings: NativeConfigCheck; argv: NativeConfigCheck; number(min?: number, max?: number, integer?: boolean): NativeConfigCheck; words(values: readonly string[]): NativeConfigCheck; block(fields: Record): NativeConfigCheck; } /** Adapter API 1, including the merged revision-3 members frozen in issue #451. */ export interface AdapterDefinition { api: 1; kind: string; displayName: string; family: string; transport: "acp" | "codex-appserver" | "claude-channel" | "ws-pull" | "hub-native"; roles: readonly string[]; optional?: boolean; defaultOnRoster?: boolean; /** A legacy enable switch gates new starts, not retained sockets or queues. */ enabledSwitchStartOnly?: boolean; trust: { onPrem: boolean; hubSandboxed: boolean }; start: { forms: readonly StartForm[]; defaultForm: StartForm; /** A real native argv planner; absent when startup belongs to a separate verified host port. */ launch?(ctx: LaunchContext): LaunchPlan; create?(ctx: CreateContext): PeerAdapter; /** A second, explicit-only TUI driver for a kind whose default form stays headless (Qwen's dual-output TUI, #286 Part 3). Fixed builtins only; never an extra start mode. */ createTui?(ctx: CreateContext): PeerAdapter; daemonPort?: DaemonEngine; preflight?(ctx: StartRequest): string | undefined; version?(ctx: VersionContext): string | undefined; conductorStartable: boolean; /** #608: whether `ahub up` may start this kind from the `start.agents` set, and whether it is in the default set. `allowed: false` carries the reason a listing is refused. Absent: not startable by `ahub up`, refused with the generic reason. Fixed builtins only. */ upStart?: { allowed: true; default?: true } | { allowed: false; refusal: string }; passthrough?: boolean; autoStart?: "pi.auto_start"; exclusiveStartRefusal?: string; refreshTools?: boolean; explicitHeadlessMode?: boolean; planCommand?(form: StartForm): string; acpCommand?(command: readonly string[], model?: string): string[]; reconfigureWhileAttached?: boolean; unattended?: boolean; hubSwitches: readonly string[]; ownedFlags: readonly string[]; conductorStartArgs?(args: string[]): { mode?: StartForm } | Error; }; identity: { mcp: "acp-session" | "project-file" | "env" | "channel-plugin"; currentChild?: true }; /** Who owns the session title; only hub-owned slots receive hub_set_title. */ title?: "native" | "hub"; /** Fixed builtins only: the title slot survives native-session restoration. Absent means ephemeral. */ titlePersistence?: "native"; /** #1053: how long a `hub_ask` call waits for the person before it answers `pending` (milliseconds). MCP peers 45 s, hub-native peers 300 s; config `questions.wait_ms.` overrides it. Fixed builtins only. */ questionWaitMs?: number; /** * #1054: the code-verified signal that ends a peer's logical run, declared per definition. ABSENT means the adapter creates no completion: nothing is guessed (owner * decision 2026-11-04). Fixed builtins only (`assertNativeCapabilityScope`): a project or external definition cannot claim one. A definition with a pull-only form (Kimi's TUI) * declares it for its headless form only, because the daemon starts no run for a peer that attached pull-only. */ settle?: { signal: SettleSignal }; /** External module data-only opt-in. The verified loader derives the internal instances policy from it (#754). */ headlessInstances?: { form: "headless"; roles: readonly ("implementer" | "verifier" | "reviewer")[] }; /** Declaration admission only; execution-root and runtime owner proof remain host responsibilities. */ instances?: { mode: "external" | "headless"; roles?: readonly string[]; /** Each declared instance runs its own native data home (`jcode_home`) and may pass its own provider, model and profile names (#685). Fixed builtins only. */ nativeHome?: true; /** A declared headless instance of this definition may pass one validated `model` word to its native child (#844). Fixed builtins only. */ modelSelect?: true }; attach?: { /** The authenticated external hello may claim this id; independent of MCP configuration shape. */ externalHello?: boolean; pullOnlyForms?: readonly StartForm[]; recoveryLaunch?(instance: string): Record; pullOnlyNotice?: string; admission?: { reservedRefusal: string; watchRefusal: string }; }; permission: { /** Consumed configured-ACP mode capability; native runtime and instance ceiling use the same validated mapping. */ genericAcp?: { modes?: Partial>; readOnly?: string }; grants?: Partial>; unmanaged?: string; unmanagedForms?: readonly StartForm[]; unmanagedNote?: string; unmanagedStatusNote?: string; trackUnattended?: boolean; }; session: { /** Observational recovery preflight only; actual native startup repeats its own version admission. */ restoreVersionGate?: CompatId; nativeRevert?: boolean; crashPlan?(meta: Record): { resume?: Record; how: string; fresh?: Record; tui?: true }; unrecordedTerminal?: "always" | "tui"; continuityBookmark?(peer: RecoveryPeer, binding?: TerminalBinding): Pick; continuity?: { key: string; parse(value: unknown): unknown | undefined }; idField: "sessionId" | "threadId"; currentId(peer: PeerAdapter): string | undefined; configDirEnv?: "CODEX_HOME" | "CLAUDE_CONFIG_DIR"; resumeArgv?(binding: SessionRef, fresh: boolean): string[]; transcriptPath?(binding: TerminalBinding): string | undefined; transcriptExists?(binding: TerminalBinding): boolean | "unknown"; zeroTurnFresh?: boolean; zeroTurn?(ctx: { stateDir: string; binding: TerminalBinding; phase: "plan" | "attach" | "verify" }): boolean; restoreArgs?(peer: RecoveryPeer): Record; recoveryRefusal?(peer: RecoveryPeer, phase?: "plan" | "restore"): string | undefined; personFresh?: boolean; missingEvidence?: "rollout" | "transcript"; /** Fixed source-only compatibility reads used by released recovery coordinators. */ legacyTargetSupport?: { file: "src/hub/peer-catalog.ts"; exportName: "OPTIONAL_PEERS"; refusal: string }; legacyHeadlessArgv?: { file: "src/hub/start-mode.ts"; exportName: "START_MODE_PEERS"; argv: readonly string[] }; freshOnRestore?: boolean; /** The daemon restores recorded startup options before auto-starting this kind. */ restoreOnStart?: boolean; /** Recovery passes the verified native session id to this kind's start command. */ resumeById?: boolean; launchKind?: string; launchRecord?: boolean; crashIdentity?(row: unknown): { sessionId?: string; sessionFile?: string }; }; turnEnd: "adapter" | "native-hook"; reporting?: { tokensNotReported?: boolean }; /** Legacy native routing policy; external definitions cannot claim these host-specific policies. */ routing?: { /** Takes reviews only: never chosen or nominated as a task owner, for any class. */ reviewOnly?: true; /** Fixed role ceiling; project roles cannot turn an unmanaged implementer into a planner/reviewer. */ allowedRoles?: readonly string[]; localAllowedRefusal?: string; longContext?: "backend-limit" | "skip-owner"; preferredTier?: boolean; handoffPriority?: number; trace?: "route" | "backend"; backendLabel?: string; }; budget?: { account: string; quotaExempt?: boolean; /** Why this peer has no provider quota, shown by `ahub budget` and the dashboard (#285 AC6). */ noQuotaReason?: string; instrumented?: boolean; reader?: QuotaReader; context?: ContextReader; checkpoint?: boolean; resetSoftTokensOnResume?: boolean }; configuration?: { schema?(ports: NativeConfigValidators): Record; routingSchema?(ports: NativeConfigValidators): Record; settings?: readonly SettingDef[]; restartReasons?: Readonly>; validateEffective?(raw: Record, fail: (key: string, reason: string) => never): void; }; capabilities?: { manifest?(peer: PeerAdapter): Promise; watch?: boolean }; /** Fixed factory support only; the host still checks the actual native surface and form. */ modelOverride?: { readonly boundary: "turn"; readonly acp?: import("./acp-model-policy.ts").AcpModelPolicy }; /** Stable host projection order and planner eligibility, independent of default task roles. */ projection?: { roleRank?: number; startRank?: number; helpRank?: number; plannerEligible?: boolean; /** #1408 R1: true only for a kind with an interactive form that receives hub pushes and holds a writable tools connection. Absent means false: a kind not yet proven is not eligible. */ conductorEligible?: boolean; /** #1408 R1: the kind can receive `hub_review`. Absent means false. */ reviewerEligible?: boolean }; cli: { command: string; /** Fixed builtin CLI ports; project definitions cannot supply these callbacks. */ entry?: Readonly>; preview?: NativePreviewBuilder; /** `[usage, description, summary?]`: the optional third element is the one-line row of `ahub help` for this form (#1504; three or more words, at most 56 cells). It rides this field's fixed-builtin restriction. */ usage?: readonly (readonly [usage: string, description: string, summary?: string])[]; /** Configuration leaves that select this peer's next native launch command or provider profile. */ launchConfigKeys?: readonly string[]; /** Restrictions only; core identity remains authoritative. */ authority?: "person" | "conductor"; personOnlyFlags?: readonly string[]; startWords(form: StartForm): string[]; stopNotice?(form: StartForm, owner: PeerAdapter | undefined): string; previewArgs?: readonly string[]; retainedTerminalNotice?(instance: string, form: StartForm | undefined, resumeCommand: string): string | undefined; rosterReturnNotice?(resumeCommand: string): string; }; display: { palette: { fg: string; bg: string; tone?: string; ansi?: string } }; hooks?: Partial; /** #223: what a declared headless reviewer-only instance of this kind runs as. Fixed builtins only. */ reviewerVariant?: AdapterDefinition; /** #525: fixed builtin variant for declared headless implementer instances. */ headlessVariant?: AdapterDefinition; /** Fixed host backend; runtime isolation proof is required before bus admission. */ reviewer?: { backend?: ReviewerBackend; defaultPool: boolean; unavailable?: string; declaration: "automatic" | "explicit"; /** #852: what a reviewer of this kind reads. `code`: the code only, its sandbox cannot run tests or read CI. Unset means `full`. Fixed builtins only. */ scope?: "full" | "code" }; } /** Explicit project declarations, passed by the bound host. No process-global instance registration. */ export type KindMap = Readonly>; /** Immutable per-project resolver; exported globals remain builtin-only. */ export interface ProjectAdapterCatalog { readonly definitions: readonly AdapterDefinition[]; readonly externalDefinitions: readonly AdapterDefinition[]; definitionOf(id: string, instances?: KindMap): AdapterDefinition | undefined; kindOf(id: string, instances?: KindMap): string | undefined; familyOf(id: string, instances?: KindMap): string | undefined; isSupportedPeer(id: unknown, instances?: KindMap): id is string; }