import { readFileSync } from "node:fs"; import { InstructedIpcSocket } from "./instructed-ipc.ts"; import { join, resolve } from "node:path"; import { projectContext } from "./project.ts"; import { newToolRequestId, TOOL_WRITE_FEATURE, toolWriteOperation, toolWriteUnknownReply, toolWriteRefusedReply } from "./tool-request.ts"; import { externalAdapterMetadata, externalInstanceCatalog, type ExternalInstanceCatalog, type ExternalAdapterMetadata } from "../adapters/external-metadata.ts"; import { negotiateProtocol, protocolWindow, type ProtocolWindow } from "./protocol-window.ts"; import { ControlWriteTelemetry, controlWriteMetadata, controlWriteSpan } from "./control-write-trace.ts"; import { VERSION } from "../version.ts"; // The client has no authoritative task privacy view. Keep kind/timing only, never its args or task id. const clientWriteTelemetry = new ControlWriteTelemetry({ emit: line => { if (process.env.AHUB_CONTROL_WRITE_TIMING === "1") console.error(`[agent-hub] ${line}`); } }); const publicClientTiming = () => true; export function stateDirFor(cwd: string): string { return projectContext(cwd).stateDir; } /** Control WS wire version. 2 = `deliver` carries `envs` (digests); 3 = `tools` role and task messages; 4 = budget messages and `hub_checkpoint`; 5 = `ask`; 6 = console-only `ui` session bootstrap; 8 = controlled recovery; 9 = Pi bridge metadata; 10 = durable delivery receipts; 11 = queue hold diagnostics; 12 = generation-bound channel settlement and execution budgets; 13 = turn-free facts (`facts` with tool, session and transcript binding, `silenced`) and per-recipient send results (issue #108). 14 = native context-window status and session-bound context checkpoint request ids (issue #185). 15 = conductor tools and permission deadlines/closed events (issues #190, #194). 16 = a Claude session without channel evidence: hello `channel: false` and `inbox` (issue #205). The plugin is installed apart from the daemon, so they can drift. */ export const PROTOCOL = 17; /** The descriptor's legacy protocol field remains this floor for previous published clients. */ export const PROTOCOL_MIN = 16; // Literal metadata is read without executing a recovery target; consistency is pinned in tests. export const DAEMON_FEATURES = ["instructed_intent", "instructed_exact", "roadmap", "roadmap_instructed", "guidance_views", "guidance_variants", "guidance_probes", "guidance_probe_receipts", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "reviewer_quota", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "research_synthesis", "research_evidence_withdrawal", "advisor_surveys", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const; /** Protocols a current coordinator may authenticate while upgrading a running source. */ export const RECOVERY_SOURCE_PROTOCOLS = [9, 10, 11, 12, 13, 14, 15, 16, PROTOCOL] as const; /** Modern descriptors advertise their maximum separately; old descriptors represent singleton windows. */ export function controlProtocolWindow(descriptor: { protocol?: unknown; protocolMin?: unknown; protocolMax?: unknown }): ProtocolWindow | undefined { const legacy = protocolWindow(descriptor.protocol); const window = protocolWindow(descriptor.protocolMax ?? descriptor.protocol, descriptor.protocolMin ?? descriptor.protocol); if (!legacy || !window || legacy.v < window.vMin || legacy.v > window.v) return undefined; return window; } /** Only a launch retries transient transport failures. Refusals and identity mismatches * remain terminal; every attempt rereads the descriptor and applies the instance pin. */ export async function retryLaunchConnect(attempt: (timeoutMs: number) => Promise, onRetry: () => void, ports: { now(): number; sleep(ms: number): Promise } = { now: Date.now, sleep: ms => Bun.sleep(ms) }): Promise { const until = ports.now() + 15_000; let backoff = 250, announced = false; for (;;) { try { return await attempt(Math.max(1, Math.min(3000, until - ports.now()))); } catch (error) { const code = (error as { code?: unknown } | null)?.code; if (!["AHUB_CONNECT_TIMEOUT", 1006].includes(code as string | number) || ports.now() >= until) throw error; if (!announced) { announced = true; onRetry(); } await ports.sleep(Math.min(backoff, until - ports.now())); if (ports.now() >= until) throw error; backoff = Math.min(1000, backoff * 2); } } } export interface Hello { /** `tools`: acts for `peer` (task tools, hub_send) without being a delivery target: the MCP server Kimi and Codex run. */ role: "peer" | "console" | "tools"; peer?: string; /** `peer` only: false when the session cannot show channel pushes; its queue then waits for `inbox` (issue #205). */ channel?: boolean; /** Closed, display-only evidence for Claude's channel attachment decision. */ channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported"; /** Managed Claude launch identity; absent for plain or pre-daemon sessions. */ launchId?: string; /** Optional canonical native execution cwd; ownership requires independent host proof. */ cwd?: string; /** * agent-hub#1036: the plugin has no project of its own and its inherited state directory belongs to another project. It asks to join as a distinct session; the value is the origin label * (possibly empty). The daemon mints `~