@aiwayds/dsh-opentui 0.26.1 → 0.26.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  "sources": ["../src/client/host-probe.ts", "../src/client/append-system.ts", "../src/client/safe-kill.ts", "../src/client/lifecycle.ts", "../src/client/host-registry.ts", "../src/client/client-lifecycle.ts", "../src/client/watchdog-cli.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * Host liveness probes used by the lifecycle manager before it hands an\n * authority to the client carrier.\n *\n * Two distinct questions:\n *\n * - `probeHostHttp` — \"is this authority OUR dsh host?\" A `GET /` carrying\n * the cookie minted from this home's grant must answer with a web-app\n * response (2xx/3xx). A live process that merely holds the TCP port (a\n * foreign home's host, a test server, a wedge that lost its connection\n * service) answers 401/404/5xx and must NOT be adopted: adopting it makes\n * the carrier reconnect forever against an authority it can never\n * authenticate.\n *\n * - `probeHostMux` — \"is the client mux actually serving?\" The carrier's\n * readiness gate is the validated `$events` ready item, so the lifecycle\n * uses the same handshake (upgrade + open `$events` + first item) before\n * returning from a cold boot. Without it, readiness can resolve on a bare\n * TCP listener and the first carrier attempt is rejected while the HTTP\n * stack is still mounting — the `[connection] connection lost, retry #n`\n * burst this module exists to eliminate.\n *\n * Both probes are bounded and never throw: the caller decides what a false\n * result means (stale lock vs. boot failure).\n */\n\nimport { randomUUID } from \"node:crypto\"\nimport WS from \"ws\"\nimport { openEventsStreamFrame, parseMuxFrame } from \"./mux-frame.ts\"\n\n/** Default bound for one probe. */\nexport const DEFAULT_HOST_PROBE_TIMEOUT_MS = 2_000\n\n/** Minimal socket seam the probe drives; defaults to a real `ws` socket.\n * Tests inject a fake that reproduces ws's async CONNECTING-close error. */\nexport type HostProbeSocketFactory = () => WS\n\n/** Extra surface a real `ws` socket exposes for bounded teardown. The ambient\n * `ws.d.ts` declares only the transport's minimal slice, so the probe names the\n * teardown methods it relies on locally (no `any` / suppression needed). */\ninterface TeardownSocket extends WS {\n removeAllListeners(): this\n terminate(): void\n}\n\nexport interface HostProbeOptions {\n /** `host:port` (scheme omitted) exactly as the host binds it. */\n authority: string\n /** Full `Cookie` header value minted for this authority. */\n cookieHeader: string\n /** Bound for the whole probe; defaults to 2s. */\n timeoutMs?: number\n /** Injectable socket factory (tests). Default: real `ws` to the mux path. */\n socketFactory?: HostProbeSocketFactory\n}\n\nfunction validAuthority(authority: string): boolean {\n return typeof authority === \"string\" && authority.length > 0 && !/[\\r\\n/]/.test(authority)\n}\n\n/**\n * Raw HTTP status of the authenticated `GET /` probe, or `null` when the\n * authority is malformed or the request could not complete (timeout / TCP\n * refused / fetch threw). Exposed so callers that decide health themselves\n * (e.g. `host-health.ts`) can compose TCP + status without duplicating the\n * cookie/authority/timeout plumbing. Never throws.\n */\nexport async function probeHostHttpStatus(options: HostProbeOptions): Promise<number | null> {\n if (!validAuthority(options.authority)) return null\n const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS\n try {\n const response = await fetch(`http://${options.authority}/`, {\n headers: { cookie: options.cookieHeader },\n signal: AbortSignal.timeout(timeoutMs),\n })\n // The body is irrelevant; drop it so the socket is released promptly.\n try {\n await response.body?.cancel()\n } catch {\n /* already consumed/closed */\n }\n return response.status\n } catch {\n return null\n }\n}\n\n/**\n * Authenticated liveness: `GET /` with the owner cookie must reach the web\n * app. Any 2xx/3xx counts; 401/403 (cookie not accepted), 404 (something\n * else holds the port) and 5xx (broken host) all mean \"not usable\".\n */\nexport async function probeHostHttp(options: HostProbeOptions): Promise<boolean> {\n const status = await probeHostHttpStatus(options)\n return status !== null && status >= 200 && status < 400\n}\n\n/**\n * Full client-generation handshake: upgraded mux WebSocket + `$events` open\n * frame + the validated ready item. This is exactly what the carrier's\n * `createEventsPumpSource` gates on, so a true result guarantees the first\n * carrier attempt has something to attach to.\n */\nexport async function probeHostMux(options: HostProbeOptions): Promise<boolean> {\n if (!validAuthority(options.authority)) return false\n const timeoutMs = options.timeoutMs ?? DEFAULT_HOST_PROBE_TIMEOUT_MS\n const makeSocket: HostProbeSocketFactory =\n options.socketFactory ??\n (() => new WS(`ws://${options.authority}/api/remote.mux`, { headers: { cookie: options.cookieHeader } }))\n return await new Promise<boolean>((resolve) => {\n let settled = false\n let socket: WS | undefined\n const timer = setTimeout(() => done(false), timeoutMs)\n function done(ok: boolean): void {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try {\n const teardown = socket as TeardownSocket | undefined\n teardown?.removeAllListeners()\n // Closing a still-CONNECTING socket makes `ws` emit 'error' (\"closed\n // before established\") ASYNCHRONOUSLY, after removeAllListeners() has\n // removed the probe's own listeners — keep a noop handler attached so\n // it can never surface as an uncaught exception (events-source.ts and\n // remote-stream.ts fixed the identical race the same way). Every\n // settlement path funnels through done(), so all of them are covered.\n socket?.on(\"error\", () => {})\n teardown?.terminate()\n } catch {\n /* already gone */\n }\n resolve(ok)\n }\n try {\n socket = makeSocket()\n } catch {\n done(false)\n return\n }\n socket.on(\"open\", () => {\n try {\n socket?.send(JSON.stringify(openEventsStreamFrame(randomUUID())))\n } catch {\n done(false)\n }\n })\n socket.on(\"message\", (data) => {\n try {\n const frame = parseMuxFrame(String(data))\n if (frame.type !== \"item\") {\n done(false)\n return\n }\n const value = frame.value as { type?: unknown } | undefined\n done(value?.type === \"ready\")\n } catch {\n done(false)\n }\n })\n socket.on(\"unexpected-response\", (_request, response) => {\n try {\n ;(response as { resume(): void }).resume()\n } catch {\n /* already drained */\n }\n done(false)\n })\n socket.on(\"error\", () => done(false))\n socket.on(\"close\", () => done(false))\n })\n}\n",
6
- "/**\n * Append-system (ported from dsh-tui-pi's APPEND_SYSTEM.md, P2 gap closure).\n *\n * tui-pi semantics: `$DSH_HOME/APPEND_SYSTEM.md` is appended to the system\n * prompt of every TUI-created main agent (subagents excluded). The opentui\n * host exposes no wire to register a system-prompt section, so the delivery\n * channel here is an agentPreset: the client maintains one `@deepseek-ai/\n * dsh-agent-preset` row in the opentui profile's `cordis.patch.yml` whose\n * composition is the shipped `standard` preset verbatim with the persona row\n * carrying `{ suffix: <APPEND_SYSTEM.md> }`. The preset scope shadows only\n * the persona sections, so the session face is standard's plus the suffix —\n * additive by construction. `session/create` rides that preset when the host\n * roster composes it (remote-host-session.ts).\n *\n * File-driven persona: the suffix is a `!!js` expression the HOST evaluates\n * at boot — a guarded `readFileSync` of `$DSH_HOME/APPEND_SYSTEM.md` (probe\n * 2026-11-15, host 0.2.2-rc.3: `process.getBuiltinModule('node:module')\n * .createRequire(baseUrl)` and `baseUrl` are both reachable from user-patch\n * `!!js` rows; missing file resolves to '' and the empty section is dropped\n * by the prompt renderer). The patch block is therefore content-independent:\n * it is written once and never resynced, and persona edits follow the file\n * on the next host boot.\n *\n * Boot-time seeding (tui-pi parity): a missing APPEND_SYSTEM.md is seeded\n * from the embedded template; an existing file is user-owned — zero writes.\n */\n\nimport { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/** The preset id the client rides on `session/create` (unique vs the shipped roster: standard/ptc/minimal/cordis). */\nexport const APPEND_SYSTEM_PRESET_ID = \"opentui-append-system\"\n/** The patch row id carrying the preset declaration (unique vs profile patch row ids). */\nexport const APPEND_SYSTEM_ROW_ID = `preset-${APPEND_SYSTEM_PRESET_ID}`\n/** The managed-block marker comment: its presence marks OUR lines; resync never touches other lines. */\nexport const APPEND_SYSTEM_MARKER = \"# dsh-opentui:append-system\"\n\n/** Default harness home: `$DSH_HOME` or `~/.dsh` (tui-pi parity; an empty DSH_HOME falls back, host-side parity). */\nexport function defaultDshHome(): string {\n\treturn process.env.DSH_HOME || join(homedir(), \".dsh\")\n}\n\n/** The user-editable append file (`$DSH_HOME/APPEND_SYSTEM.md`). */\nexport function appendSystemPath(home: string = defaultDshHome()): string {\n\treturn join(home, \"APPEND_SYSTEM.md\")\n}\n\n/**\n * The seed template for a missing APPEND_SYSTEM.md — neutral scaffolding\n * (the tui-pi template is the original user's personal orchestrator identity,\n * not shippable content) carrying the one iron rule tui-pi maintained. The\n * todo-lifecycle section is deliberately absent: the opentui host clears\n * todos every turn (loop.ts), so tui-pi's pinned-list problem does not exist\n * here.\n */\nexport const APPEND_SYSTEM_TEMPLATE = `# APPEND_SYSTEM.md — standing system-prompt additions\n\nThe content of this file is appended to the system prompt of every main\nsession the dsh-opentui client creates (ported from dsh-tui-pi).\n\nThe file is user-owned: the client seeds it once and never rewrites it.\nEdits apply to sessions created after the next client start; clearing or\ndeleting this file switches the append off (it is not re-seeded).\n\n## Vocabulary\n\n- \"subagent\" means the registered subagents only; never invent or use\n unregistered subagents.\n\n## Additions\n\nWrite your persistent instructions below this line.\n`\n\n/**\n * The persona suffix the host evaluates at boot: guarded read of\n * `$DSH_HOME/APPEND_SYSTEM.md`, '' when missing/unreadable. One line, no\n * double quotes (survives YAML double-quoted scalars), no backslashes.\n */\nexport const APPEND_SYSTEM_SUFFIX_EXPR =\n\t`((req, path) => { try { const text = req('node:fs').readFileSync(path.join(process.env.DSH_HOME || ((process.env.HOME || '') + '/.dsh'), 'APPEND_SYSTEM.md'), 'utf8'); return text.length > 65536 ? text.slice(0, 65536) + String.fromCharCode(10) + '[append-system: truncated at 64KiB]' : text } catch { return '' } })(process.getBuiltinModule('node:module').createRequire(baseUrl), process.getBuiltinModule('node:path'))`\n\n/**\n * The managed patch block. The plugin list is the shipped `standard` preset\n * verbatim (dsh-web-app presets/standard.patch.yml — the effective default\n * this profile's sessions compose from) except the persona row, whose prefix\n * is copied verbatim and whose suffix is the APPEND_SYSTEM.md read. Copying\n * the whole composition is what makes the preset additive: a persona-only\n * preset would shadow standard's skill/plan/compaction/delegation rows and\n * shrink the session face (agents-mount gate).\n */\nexport function appendSystemPresetBlock(): string {\n\treturn `${APPEND_SYSTEM_MARKER} — managed block (client-owned; the client appends it once and never rewrites other lines).\n${APPEND_SYSTEM_MARKER} persona suffix = $DSH_HOME/APPEND_SYSTEM.md, evaluated by the host at boot (!!js guarded read; empty file => empty section => dropped).\n- insert:\n - id: ${APPEND_SYSTEM_ROW_ID}\n name: '@deepseek-ai/dsh-agent-preset'\n config:\n id: ${APPEND_SYSTEM_PRESET_ID}\n name: Standard + Append\n description: The shipped standard preset plus the user's APPEND_SYSTEM.md appended to the system prompt.\n order: 5\n plugins:\n - id: persona\n name: '@deepseek-ai/dsh-persona'\n config:\n prefix: You are a coding agent powered by the {{model}} model.\n suffix: !!js \"${APPEND_SYSTEM_SUFFIX_EXPR}\"\n - id: agent-instructions\n name: '@deepseek-ai/dsh-agent-instructions'\n config:\n maxBytes: 65536\n - id: time-context\n name: '@deepseek-ai/dsh-time-context'\n - id: tool-bash\n name: '@deepseek-ai/dsh-tool-bash'\n disabled: !!js process.platform === 'win32'\n - id: tool-pwsh\n name: '@deepseek-ai/dsh-tool-pwsh'\n disabled: !!js process.platform !== 'win32'\n - id: tool-fs\n name: '@deepseek-ai/dsh-tool-fs'\n config:\n # Set false to drop the apply_patch tool beside edit.\n applyPatch: false\n - id: tool-fs-search\n name: '@deepseek-ai/dsh-tool-fs-search'\n config:\n sampleOverCapGlobResults: false\n - id: tool-jobs\n name: '@deepseek-ai/dsh-tool-jobs'\n - id: tool-schedule\n name: '@deepseek-ai/dsh-tool-schedule'\n - id: skill-filesystem\n name: '@deepseek-ai/dsh-skill-filesystem'\n config:\n customSkillDirs:\n - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills')\n - id: tool-skill\n name: '@deepseek-ai/dsh-tool-skill'\n - id: command-goal\n name: '@deepseek-ai/dsh-command-goal'\n - id: tool-goal\n name: '@deepseek-ai/dsh-tool-goal'\n - id: planning\n name: cordis:group\n group: true\n isolate:\n planMode: true\n config:\n - id: plan-mode\n name: '@deepseek-ai/dsh-plan-mode'\n config:\n section: |\n You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.\n\n Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.\n\n The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.\n\n Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.\n\n Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.\n\n When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask \"should I proceed?\" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation.\n - id: compaction\n name: cordis:group\n group: true\n isolate:\n compaction: true\n toolResultPruner: true\n config:\n - id: compaction-basic\n name: '@deepseek-ai/dsh-compaction-basic'\n - id: command-compact\n name: '@deepseek-ai/dsh-command-compact'\n - id: tool-result-pruner\n name: '@deepseek-ai/dsh-compaction-tool-result-pruner'\n config:\n thresholdChars: 8192\n headChars: 4096\n tailChars: 1024\n - id: delegation\n name: cordis:group\n group: true\n isolate:\n workflowEngine: true\n config:\n - id: tool-subagent-control\n name: '@deepseek-ai/dsh-tool-subagent-control'\n config:\n interrupt: false\n - id: tool-subagent\n name: '@deepseek-ai/dsh-tool-subagent'\n config:\n provider: spawn\n toolName: subagent\n modelSelection: true\n modelDiscovery: true\n - id: tool-subagent-fork\n name: '@deepseek-ai/dsh-tool-subagent'\n config:\n provider: fork\n toolName: subagent_fork\n - id: workflow-ptc\n name: '@deepseek-ai/dsh-workflow-ptc'\n config:\n provider: spawn\n - id: tool-workflow\n name: '@deepseek-ai/dsh-tool-workflow'\n - id: tool-ask-user\n name: '@deepseek-ai/dsh-tool-ask-user'\n - id: tool-todo\n name: '@deepseek-ai/dsh-tool-todo'\n config:\n allowParallelInProgress: true\n - id: tool-web\n name: '@deepseek-ai/dsh-tool-web'\n config:\n fetch: true\n searchTimeoutMs: 60000\n - id: present\n name: '@deepseek-ai/dsh-tool-present'\n - id: tool-office\n name: '@deepseek-ai/dsh-tool-office'\n - id: tool-plugin-manager\n name: '@deepseek-ai/dsh-plugin-manager/tools'\n disabled: !!js \"!ctx.get('profileContext')\"\n - id: tool-plugin-market\n name: '@deepseek-ai/dsh-plugin-market/tools'\n disabled: true\n`\n}\n\n/**\n * Read the append file for prompt assembly. Missing/unreadable => ''\n * (tui-pi parity: the empty section is dropped by the renderer).\n */\nexport function readAppendSystem(path: string = appendSystemPath()): string {\n\ttry {\n\t\treturn readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn \"\"\n\t}\n}\n\n/** Atomic write: temp file in the same directory, then rename (tui-pi parity). */\nfunction writeAtomically(path: string, content: string, mode: number): void {\n\tmkdirSync(join(path, \"..\"), { recursive: true })\n\tconst tmp = `${path}.${process.pid}.tmp`\n\ttry {\n\t\twriteFileSync(tmp, content, { mode })\n\t\trenameSync(tmp, path)\n\t} catch (error) {\n\t\ttry {\n\t\t\tunlinkSync(tmp)\n\t\t} catch {\n\t\t\t/* sweep is best-effort */\n\t\t}\n\t\tthrow error\n\t}\n}\n\n/**\n * Seed the append file — FIRST PROVISIONING ONLY: a missing file is seeded\n * solely when the managed preset block is absent too. After provisioning,\n * deleting the file is how the user switches the append OFF (an empty persona\n * suffix renders no section), and this function must not resurrect it (the\n * block's presence answers \"provisioned\"). An existing file — even an empty\n * one — is user-owned: zero writes. Atomic; throws on write failure (the\n * caller degrades to booting without the feature, never fails the boot).\n * @param path - target file (injectable for tests). Whether the install is\n * already provisioned (managed block present => deleted file stays deleted)\n * is the CALLER's judgment — see {@link provisionAppendSystem}.\n */\nexport function ensureAppendSystemFile(path: string = appendSystemPath()): \"seeded\" | \"kept\" {\n\ttry {\n\t\treadFileSync(path, \"utf8\")\n\t\treturn \"kept\"\n\t} catch {\n\t\twriteAtomically(path, APPEND_SYSTEM_TEMPLATE, 0o644)\n\t\ttry {\n\t\t\tchmodSync(path, 0o644)\n\t\t} catch {\n\t\t\t/* best-effort mode normalization */\n\t\t}\n\t\treturn \"seeded\"\n\t}\n}\n\n/** Outcome of one profile-patch sync pass. */\nexport type AppendPresetSyncResult =\n\t| { status: \"added\" }\n\t| { status: \"present\" }\n\t| { status: \"collision\"; detail: string }\n\t| { status: \"skipped\"; detail: string }\n\n/**\n * The profile patch file the client maintains (`~/.dsh/profiles/<profile>/cordis.patch.yml`).\n */\nexport function profilePatchPath(home: string, profile: string): string {\n\treturn join(home, \"profiles\", profile, \"cordis.patch.yml\")\n}\n\n/**\n * The [start, end) line span of OUR managed block: from the first marker\n * comment through our single top-level `- insert:` entry — the span ends at\n * the NEXT top-level patch row (`^- `) after our insert line, or EOF. Lines\n * outside the span are the user's (or other tools') — this module never\n * rewrites them.\n */\nfunction managedSpan(lines: readonly string[]): [number, number] | undefined {\n\tconst start = lines.findIndex((line) => line.startsWith(APPEND_SYSTEM_MARKER))\n\tif (start < 0) return undefined\n\tlet end = lines.length\n\tlet seenOwnInsert = false\n\tfor (let i = start + 1; i < lines.length; i++) {\n\t\tif (/^- /.test(lines[i])) {\n\t\t\t// The first top-level row after the marker is our own `- insert:`.\n\t\t\tif (!seenOwnInsert) {\n\t\t\t\tseenOwnInsert = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn [start, end]\n}\n\n/**\n * One boot-time provisioning pass (the lifecycle entry point): maintain the\n * managed preset row, then seed the append file only when the install is not\n * yet provisioned (no managed block) AND the file is missing — afterwards a\n * deleted file means OFF and stays deleted. Returns both outcomes for the\n * caller's structured logging; write failures propagate.\n */\nexport function provisionAppendSystem(home: string, profile: string): { patch: AppendPresetSyncResult; file: \"seeded\" | \"kept\" } {\n\t// Provisioning is judged on the PRE-sync patch state: the block this pass\n\t// just added must not count (a fresh install seeds the file in the same\n\t// breath), while a block that already existed means the user may have\n\t// deleted the file to switch OFF — never re-seed over that.\n\tlet preText: string | undefined\n\ttry {\n\t\tpreText = readFileSync(profilePatchPath(home, profile), \"utf8\")\n\t} catch {\n\t\tpreText = undefined // no patch file: nothing provisioned, seeding stays eligible\n\t}\n\tconst patch = syncAppendSystemPreset(home, profile)\n\tif (preText !== undefined && managedSpan(preText.split(\"\\n\")) !== undefined) {\n\t\treturn { patch, file: \"kept\" } // provisioned install: deleted file stays deleted (delete = off)\n\t}\n\treturn { patch, file: ensureAppendSystemFile(appendSystemPath(home)) }\n}\n\n/**\n * Maintain the append-system preset row in the profile patch (conservative\n * line-level editing — the file is user-owned YAML, no parse-and-reserialize):\n *\n * - the ids appear OUTSIDE our block (a preset/row the user declared or a\n * future host ships with the same id) => `collision`, zero writes;\n * - otherwise: block present => `present`, untouched (the block is content-\n * independent in file-driven mode; there is nothing to resync); block\n * absent => append at EOF (`added`);\n * - patch file or profile dir missing => `skipped` (the host owns that\n * layout; enrichment must not create profile plumbing).\n *\n * The write is atomic (tmp + rename) and preserves the file mode (0600 for a\n * fresh file, matching the host's config-editor convention).\n */\nexport function syncAppendSystemPreset(home: string, profile: string): AppendPresetSyncResult {\n\tconst path = profilePatchPath(home, profile)\n\tlet before: string\n\ttry {\n\t\tbefore = readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn { status: \"skipped\", detail: `no profile patch at ${path}` }\n\t}\n\tconst lines = before.split(\"\\n\")\n\tconst span = managedSpan(lines)\n\tconst outside = (needle: string): string | undefined => {\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tif (span !== undefined && i >= span[0] && i < span[1]) continue\n\t\t\tif (lines[i].includes(needle)) return `line ${i + 1}: ${lines[i].trim()}`\n\t\t}\n\t\treturn undefined\n\t}\n\tfor (const needle of [APPEND_SYSTEM_PRESET_ID, APPEND_SYSTEM_ROW_ID]) {\n\t\tconst hit = outside(needle)\n\t\tif (hit !== undefined) {\n\t\t\treturn { status: \"collision\", detail: `${needle} already declared (${hit})` }\n\t\t}\n\t}\n\tif (span !== undefined) return { status: \"present\" }\n\t// Append at EOF: the patch is a YAML sequence; a new top-level entry is\n\t// safe at the end (the last layer wins per id, and we collide-checked).\n\tconst separator = before.length === 0 || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\"\n\tconst next = `${before}${separator}${appendSystemPresetBlock()}`\n\twriteAtomically(path, next, 0o600)\n\treturn { status: \"added\" }\n}\n",
6
+ "/**\n * Append-system (ported from dsh-tui-pi's APPEND_SYSTEM.md, P2 gap closure).\n *\n * tui-pi semantics: `$DSH_HOME/APPEND_SYSTEM.md` is appended to the system\n * prompt of every TUI-created main agent (subagents excluded). The opentui\n * host exposes no wire to register a system-prompt section, so the delivery\n * channel here is an agentPreset: the client maintains one `@deepseek-ai/\n * dsh-agent-preset` row in the opentui profile's `cordis.patch.yml` whose\n * composition is the shipped `standard` preset verbatim with the persona row\n * carrying `{ suffix: <APPEND_SYSTEM.md> }`. The preset scope shadows only\n * the persona sections, so the session face is standard's plus the suffix —\n * additive by construction. `session/create` rides that preset when the host\n * roster composes it (remote-host-session.ts).\n *\n * File-driven persona: the suffix is a `!!js` expression the HOST evaluates\n * at boot — a guarded `readFileSync` of `$DSH_HOME/APPEND_SYSTEM.md` (probe\n * 2026-11-15, host 0.2.2-rc.3: `process.getBuiltinModule('node:module')\n * .createRequire(baseUrl)` and `baseUrl` are both reachable from user-patch\n * `!!js` rows; missing file resolves to '' and the empty section is dropped\n * by the prompt renderer). The patch block is therefore content-independent:\n * it is written once and never resynced, and persona edits follow the file\n * on the next host boot.\n *\n * Boot-time seeding (tui-pi parity): a missing APPEND_SYSTEM.md is seeded\n * from the embedded template; an existing file is user-owned — zero writes.\n */\n\nimport { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/** The preset id the client rides on `session/create` (unique vs the shipped roster: standard/ptc/minimal/cordis). */\nexport const APPEND_SYSTEM_PRESET_ID = \"opentui-append-system\"\n/** The patch row id carrying the preset declaration (unique vs profile patch row ids). */\nexport const APPEND_SYSTEM_ROW_ID = `preset-${APPEND_SYSTEM_PRESET_ID}`\n/** The managed-block marker comment: its presence marks OUR lines; resync never touches other lines. */\nexport const APPEND_SYSTEM_MARKER = \"# dsh-opentui:append-system\"\n\n/** Default harness home: `$DSH_HOME` or `~/.dsh` (tui-pi parity; an empty DSH_HOME falls back, host-side parity). */\nexport function defaultDshHome(): string {\n\treturn process.env.DSH_HOME || join(homedir(), \".dsh\")\n}\n\n/** The user-editable append file (`$DSH_HOME/APPEND_SYSTEM.md`). */\nexport function appendSystemPath(home: string = defaultDshHome()): string {\n\treturn join(home, \"APPEND_SYSTEM.md\")\n}\n\n/**\n * The seed template for a missing APPEND_SYSTEM.md — neutral scaffolding\n * (the tui-pi template is the original user's personal orchestrator identity,\n * not shippable content) carrying the one iron rule tui-pi maintained. The\n * todo-lifecycle section is deliberately absent: the opentui host clears\n * todos every turn (loop.ts), so tui-pi's pinned-list problem does not exist\n * here.\n */\nexport const APPEND_SYSTEM_TEMPLATE = `# APPEND_SYSTEM.md — standing system-prompt additions\n\nThe content of this file is appended to the system prompt of every main\nsession the dsh-opentui client creates (ported from dsh-tui-pi).\n\nThe file is user-owned: the client seeds it once and never rewrites it.\nEdits apply to sessions created after the next client start; clearing or\ndeleting this file switches the append off (it is not re-seeded).\n\n## Vocabulary\n\n- \"subagent\" means the registered subagents only; never invent or use\n unregistered subagents. There are two by-name entrances: the native\n \\`subagent\\` / \\`subagent_fork\\` tools, and the \\`use_agent\\` roster of\n locally-defined agents under \\`$DSH_HOME/agents/\\` (with \\`ask_agent\\` for\n follow-ups). Use the roster entry whose name matches the role you need.\n\n## Additions\n\nWrite your persistent instructions below this line.\n`\n\n/**\n * The persona suffix the host evaluates at boot: guarded read of\n * `$DSH_HOME/APPEND_SYSTEM.md`, '' when missing/unreadable. One line, no\n * double quotes (survives YAML double-quoted scalars), no backslashes.\n */\nexport const APPEND_SYSTEM_SUFFIX_EXPR =\n\t`((req, path) => { try { const text = req('node:fs').readFileSync(path.join(process.env.DSH_HOME || ((process.env.HOME || '') + '/.dsh'), 'APPEND_SYSTEM.md'), 'utf8'); return text.length > 65536 ? text.slice(0, 65536) + String.fromCharCode(10) + '[append-system: truncated at 64KiB]' : text } catch { return '' } })(process.getBuiltinModule('node:module').createRequire(baseUrl), process.getBuiltinModule('node:path'))`\n\n/**\n * The managed patch block. The plugin list is the shipped `standard` preset\n * verbatim (dsh-web-app presets/standard.patch.yml — the effective default\n * this profile's sessions compose from) except the persona row, whose prefix\n * is copied verbatim and whose suffix is the APPEND_SYSTEM.md read. Copying\n * the whole composition is what makes the preset additive: a persona-only\n * preset would shadow standard's skill/plan/compaction/delegation rows and\n * shrink the session face (agents-mount gate).\n */\nexport function appendSystemPresetBlock(): string {\n\treturn `${APPEND_SYSTEM_MARKER} — managed block (client-owned; the client appends it once and never rewrites other lines).\n${APPEND_SYSTEM_MARKER} persona suffix = $DSH_HOME/APPEND_SYSTEM.md, evaluated by the host at boot (!!js guarded read; empty file => empty section => dropped).\n- insert:\n - id: ${APPEND_SYSTEM_ROW_ID}\n name: '@deepseek-ai/dsh-agent-preset'\n config:\n id: ${APPEND_SYSTEM_PRESET_ID}\n name: Standard + Append\n description: The shipped standard preset plus the user's APPEND_SYSTEM.md appended to the system prompt.\n order: 5\n plugins:\n - id: persona\n name: '@deepseek-ai/dsh-persona'\n config:\n prefix: You are a coding agent powered by the {{model}} model.\n suffix: !!js \"${APPEND_SYSTEM_SUFFIX_EXPR}\"\n - id: agent-instructions\n name: '@deepseek-ai/dsh-agent-instructions'\n config:\n maxBytes: 65536\n - id: time-context\n name: '@deepseek-ai/dsh-time-context'\n - id: tool-bash\n name: '@deepseek-ai/dsh-tool-bash'\n disabled: !!js process.platform === 'win32'\n - id: tool-pwsh\n name: '@deepseek-ai/dsh-tool-pwsh'\n disabled: !!js process.platform !== 'win32'\n - id: tool-fs\n name: '@deepseek-ai/dsh-tool-fs'\n config:\n # Set false to drop the apply_patch tool beside edit.\n applyPatch: false\n - id: tool-fs-search\n name: '@deepseek-ai/dsh-tool-fs-search'\n config:\n sampleOverCapGlobResults: false\n - id: tool-jobs\n name: '@deepseek-ai/dsh-tool-jobs'\n - id: tool-schedule\n name: '@deepseek-ai/dsh-tool-schedule'\n - id: skill-filesystem\n name: '@deepseek-ai/dsh-skill-filesystem'\n config:\n customSkillDirs:\n - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills')\n - id: tool-skill\n name: '@deepseek-ai/dsh-tool-skill'\n - id: command-goal\n name: '@deepseek-ai/dsh-command-goal'\n - id: tool-goal\n name: '@deepseek-ai/dsh-tool-goal'\n - id: planning\n name: cordis:group\n group: true\n isolate:\n planMode: true\n config:\n - id: plan-mode\n name: '@deepseek-ai/dsh-plan-mode'\n config:\n section: |\n You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.\n\n Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.\n\n The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.\n\n Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.\n\n Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.\n\n When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask \"should I proceed?\" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation.\n - id: compaction\n name: cordis:group\n group: true\n isolate:\n compaction: true\n toolResultPruner: true\n config:\n - id: compaction-basic\n name: '@deepseek-ai/dsh-compaction-basic'\n - id: command-compact\n name: '@deepseek-ai/dsh-command-compact'\n - id: tool-result-pruner\n name: '@deepseek-ai/dsh-compaction-tool-result-pruner'\n config:\n thresholdChars: 8192\n headChars: 4096\n tailChars: 1024\n - id: delegation\n name: cordis:group\n group: true\n isolate:\n workflowEngine: true\n config:\n # The by-name custom-agent entrances (use_agent / ask_agent) are\n # registered globally by the @aiwayds/dsh-subagent-registry\n # companion, not by a preset row — declaring them here would\n # double-mount the plugin. Its delegation-guidance listener also\n # rewrites the host delegation section to point at the roster, so\n # do not duplicate that prose here. This group only carries the\n # native subagent/workflow tools.\n - id: tool-subagent-control\n name: '@deepseek-ai/dsh-tool-subagent-control'\n config:\n interrupt: false\n - id: tool-subagent\n name: '@deepseek-ai/dsh-tool-subagent'\n config:\n provider: spawn\n toolName: subagent\n modelSelection: true\n modelDiscovery: true\n - id: tool-subagent-fork\n name: '@deepseek-ai/dsh-tool-subagent'\n config:\n provider: fork\n toolName: subagent_fork\n - id: workflow-ptc\n name: '@deepseek-ai/dsh-workflow-ptc'\n config:\n provider: spawn\n - id: tool-workflow\n name: '@deepseek-ai/dsh-tool-workflow'\n - id: tool-ask-user\n name: '@deepseek-ai/dsh-tool-ask-user'\n - id: tool-todo\n name: '@deepseek-ai/dsh-tool-todo'\n config:\n allowParallelInProgress: true\n - id: tool-web\n name: '@deepseek-ai/dsh-tool-web'\n config:\n fetch: true\n searchTimeoutMs: 60000\n - id: present\n name: '@deepseek-ai/dsh-tool-present'\n - id: tool-office\n name: '@deepseek-ai/dsh-tool-office'\n - id: tool-plugin-manager\n name: '@deepseek-ai/dsh-plugin-manager/tools'\n disabled: !!js \"!ctx.get('profileContext')\"\n - id: tool-plugin-market\n name: '@deepseek-ai/dsh-plugin-market/tools'\n disabled: true\n`\n}\n\n/**\n * Read the append file for prompt assembly. Missing/unreadable => ''\n * (tui-pi parity: the empty section is dropped by the renderer).\n */\nexport function readAppendSystem(path: string = appendSystemPath()): string {\n\ttry {\n\t\treturn readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn \"\"\n\t}\n}\n\n/** Atomic write: temp file in the same directory, then rename (tui-pi parity). */\nfunction writeAtomically(path: string, content: string, mode: number): void {\n\tmkdirSync(join(path, \"..\"), { recursive: true })\n\tconst tmp = `${path}.${process.pid}.tmp`\n\ttry {\n\t\twriteFileSync(tmp, content, { mode })\n\t\trenameSync(tmp, path)\n\t} catch (error) {\n\t\ttry {\n\t\t\tunlinkSync(tmp)\n\t\t} catch {\n\t\t\t/* sweep is best-effort */\n\t\t}\n\t\tthrow error\n\t}\n}\n\n/**\n * Seed the append file — FIRST PROVISIONING ONLY: a missing file is seeded\n * solely when the managed preset block is absent too. After provisioning,\n * deleting the file is how the user switches the append OFF (an empty persona\n * suffix renders no section), and this function must not resurrect it (the\n * block's presence answers \"provisioned\"). An existing file — even an empty\n * one — is user-owned: zero writes. Atomic; throws on write failure (the\n * caller degrades to booting without the feature, never fails the boot).\n * @param path - target file (injectable for tests). Whether the install is\n * already provisioned (managed block present => deleted file stays deleted)\n * is the CALLER's judgment — see {@link provisionAppendSystem}.\n */\nexport function ensureAppendSystemFile(path: string = appendSystemPath()): \"seeded\" | \"kept\" {\n\ttry {\n\t\treadFileSync(path, \"utf8\")\n\t\treturn \"kept\"\n\t} catch {\n\t\twriteAtomically(path, APPEND_SYSTEM_TEMPLATE, 0o644)\n\t\ttry {\n\t\t\tchmodSync(path, 0o644)\n\t\t} catch {\n\t\t\t/* best-effort mode normalization */\n\t\t}\n\t\treturn \"seeded\"\n\t}\n}\n\n/** Outcome of one profile-patch sync pass. */\nexport type AppendPresetSyncResult =\n\t| { status: \"added\" }\n\t| { status: \"present\" }\n\t| { status: \"collision\"; detail: string }\n\t| { status: \"skipped\"; detail: string }\n\n/**\n * The profile patch file the client maintains (`~/.dsh/profiles/<profile>/cordis.patch.yml`).\n */\nexport function profilePatchPath(home: string, profile: string): string {\n\treturn join(home, \"profiles\", profile, \"cordis.patch.yml\")\n}\n\n/**\n * The [start, end) line span of OUR managed block: from the first marker\n * comment through our single top-level `- insert:` entry — the span ends at\n * the NEXT top-level patch row (`^- `) after our insert line, or EOF. Lines\n * outside the span are the user's (or other tools') — this module never\n * rewrites them.\n */\nfunction managedSpan(lines: readonly string[]): [number, number] | undefined {\n\tconst start = lines.findIndex((line) => line.startsWith(APPEND_SYSTEM_MARKER))\n\tif (start < 0) return undefined\n\tlet end = lines.length\n\tlet seenOwnInsert = false\n\tfor (let i = start + 1; i < lines.length; i++) {\n\t\tif (/^- /.test(lines[i])) {\n\t\t\t// The first top-level row after the marker is our own `- insert:`.\n\t\t\tif (!seenOwnInsert) {\n\t\t\t\tseenOwnInsert = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn [start, end]\n}\n\n/**\n * One boot-time provisioning pass (the lifecycle entry point): maintain the\n * managed preset row, then seed the append file only when the install is not\n * yet provisioned (no managed block) AND the file is missing — afterwards a\n * deleted file means OFF and stays deleted. Returns both outcomes for the\n * caller's structured logging; write failures propagate.\n */\nexport function provisionAppendSystem(home: string, profile: string): { patch: AppendPresetSyncResult; file: \"seeded\" | \"kept\" } {\n\t// Provisioning is judged on the PRE-sync patch state: the block this pass\n\t// just added must not count (a fresh install seeds the file in the same\n\t// breath), while a block that already existed means the user may have\n\t// deleted the file to switch OFF — never re-seed over that.\n\tlet preText: string | undefined\n\ttry {\n\t\tpreText = readFileSync(profilePatchPath(home, profile), \"utf8\")\n\t} catch {\n\t\tpreText = undefined // no patch file: nothing provisioned, seeding stays eligible\n\t}\n\tconst patch = syncAppendSystemPreset(home, profile)\n\tif (preText !== undefined && managedSpan(preText.split(\"\\n\")) !== undefined) {\n\t\treturn { patch, file: \"kept\" } // provisioned install: deleted file stays deleted (delete = off)\n\t}\n\treturn { patch, file: ensureAppendSystemFile(appendSystemPath(home)) }\n}\n\n/**\n * Maintain the append-system preset row in the profile patch (conservative\n * line-level editing — the file is user-owned YAML, no parse-and-reserialize):\n *\n * - the ids appear OUTSIDE our block (a preset/row the user declared or a\n * future host ships with the same id) => `collision`, zero writes;\n * - otherwise: block present => `present`, untouched (the block is content-\n * independent in file-driven mode; there is nothing to resync); block\n * absent => append at EOF (`added`);\n * - patch file or profile dir missing => `skipped` (the host owns that\n * layout; enrichment must not create profile plumbing).\n *\n * The write is atomic (tmp + rename) and preserves the file mode (0600 for a\n * fresh file, matching the host's config-editor convention).\n */\nexport function syncAppendSystemPreset(home: string, profile: string): AppendPresetSyncResult {\n\tconst path = profilePatchPath(home, profile)\n\tlet before: string\n\ttry {\n\t\tbefore = readFileSync(path, \"utf8\")\n\t} catch {\n\t\treturn { status: \"skipped\", detail: `no profile patch at ${path}` }\n\t}\n\tconst lines = before.split(\"\\n\")\n\tconst span = managedSpan(lines)\n\tconst outside = (needle: string): string | undefined => {\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tif (span !== undefined && i >= span[0] && i < span[1]) continue\n\t\t\tif (lines[i].includes(needle)) return `line ${i + 1}: ${lines[i].trim()}`\n\t\t}\n\t\treturn undefined\n\t}\n\tfor (const needle of [APPEND_SYSTEM_PRESET_ID, APPEND_SYSTEM_ROW_ID]) {\n\t\tconst hit = outside(needle)\n\t\tif (hit !== undefined) {\n\t\t\treturn { status: \"collision\", detail: `${needle} already declared (${hit})` }\n\t\t}\n\t}\n\tif (span !== undefined) return { status: \"present\" }\n\t// Append at EOF: the patch is a YAML sequence; a new top-level entry is\n\t// safe at the end (the last layer wins per id, and we collide-checked).\n\tconst separator = before.length === 0 || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\"\n\tconst next = `${before}${separator}${appendSystemPresetBlock()}`\n\twriteAtomically(path, next, 0o600)\n\treturn { status: \"added\" }\n}\n",
7
7
  "/**\n * Three-evidence safe process stop — the ONE module allowed to signal a host\n * (ADR-0009 decision 8; DESIGN-redesign §6).\n *\n * A process may only be signalled when ALL of these agree:\n * 1. the pid recorded in the v2 registry (`registryPid`) equals the pid we\n * are about to signal;\n * 2. its `ps` cmdline contains `--profile <expected>` AND no other `--profile`;\n * 3. its environment carries `DSH_OPENTUI_SERVER=1`.\n *\n * Evidence 3 is OPTIONAL when the env is genuinely unreadable (DESIGN §6):\n * on some platforms `ps eww` cannot expose a detached process's environment.\n * In that case only the two hard evidences (registry pid + exact\n * `--profile <expected>` cmdline) are required, and a fallback log is emitted.\n * A bare \"dsh\" substring match remains explicitly forbidden in ALL cases.\n * Every signal goes\n * through {@link ProcessKillHooks.kill}, which is injectable so unit tests\n * never signal a real process. No other module in the T3b path calls\n * `process.kill` on a host pid directly.\n *\n * Default signal sequence for a confirmed host: SIGTERM (let the host flush /\n * persist), wait a grace window, then SIGKILL only if the pid is still alive.\n */\n\nimport { spawnSync } from 'node:child_process'\n\n/** Env marking a process as THIS launcher's Host service (ADR-0009 decision 1). */\nexport const SERVER_ENV_NAME = 'DSH_OPENTUI_SERVER'\nexport const SERVER_ENV_VALUE = '1'\n/** The one product profile whose host may be signalled. */\nexport const HOST_PROFILE = 'opentui'\n/** Default wait after SIGTERM before escalating to SIGKILL. */\nexport const DEFAULT_TERM_GRACE_MS = 5_000\n/** Default wait after SIGKILL to confirm the pid is gone. */\nexport const DEFAULT_KILL_GRACE_MS = 2_000\n/** Poll cadence while waiting for a pid to exit. */\nexport const DEFAULT_EXIT_POLL_MS = 50\n\n/** The three-evidence process-identification seam, fully injectable. */\nexport interface ProcessKillHooks {\n /** Full cmdline of `pid`, or null when the process is gone / unreadable. */\n cmdline(pid: number): string | null\n /** True when `pid`'s environment contains `DSH_OPENTUI_SERVER=1`. */\n hasServerEnv(pid: number): boolean\n /** Send a signal to `pid` (no-op on ESRCH is fine). */\n kill(pid: number, signal: NodeJS.Signals): void\n /** Pid liveness probe (defaults to `process.kill(pid, 0)`). */\n pidAlive?(pid: number): boolean\n /**\n * Whether `pid`'s environment can be READ AT ALL (distinct from \"readable\n * but lacks the marker\"). When this returns false, `evidencesAgree` waives\n * evidence 3 and requires only registry pid + exact cmdline. Hooks that omit\n * it keep the strict three-evidence rule (backward compatible).\n */\n envReadable?(pid: number): boolean\n /** Called once when the two-evidence fallback is used (logging seam). */\n onEnvFallback?(pid: number): void\n}\n\n/** Read a pid's process state via `ps -o stat=`; null when ps is unavailable. */\nfunction psStat(pid: number): string | null {\n try {\n const result = spawnSync('ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' })\n if (result.error || result.status !== 0) return null\n return (result.stdout ?? '').trim() || null\n } catch {\n return null\n }\n}\n\n/** True when a `ps -o stat=` row denotes a zombie (Z / Z+ / Z<...>). */\nfunction statIsZombie(stat: string): boolean {\n return stat.startsWith('Z')\n}\n\nexport function defaultPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM'\n }\n // kill(0) succeeds for a zombie the parent has not reaped yet. Confirm via\n // ps; when ps is unavailable keep the kill(0) verdict (no semantic change).\n const stat = psStat(pid)\n if (stat !== null && statIsZombie(stat)) return false\n return true\n}\n\n/** Default three-evidence hooks via `ps` (portable enough for darwin/linux). */\nexport const psKillHooks: ProcessKillHooks = {\n cmdline(pid) {\n try {\n return spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).stdout?.trim() || null\n } catch {\n return null\n }\n },\n hasServerEnv(pid) {\n try {\n const out = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).stdout ?? ''\n return out.includes(`${SERVER_ENV_NAME}=${SERVER_ENV_VALUE}`)\n } catch {\n return false\n }\n },\n envReadable(pid) {\n try {\n const result = spawnSync('ps', ['eww', '-p', String(pid), '-o', 'command='], { encoding: 'utf8' })\n if (result.error || (result.status !== null && result.status !== 0)) return false\n const out = (result.stdout ?? '').trim()\n // A zombie's command degrades to `<defunct>` and carries no readable env.\n if (!out || out.includes('<defunct>')) return false\n const stat = psStat(pid)\n if (stat !== null && statIsZombie(stat)) return false\n // A non-empty `ps eww` row means the env was readable, even if the\n // marker itself is absent (that case must still refuse to signal).\n return true\n } catch {\n return false\n }\n },\n onEnvFallback(pid) {\n console.warn(\n `[safe-kill] ${SERVER_ENV_NAME} env unreadable for pid ${pid}; ` +\n `using registry + cmdline two-evidence fallback (no \"dsh\" match)`,\n )\n },\n kill(pid, signal) {\n try {\n process.kill(pid, signal)\n } catch {\n /* already gone */\n }\n },\n}\n\n/**\n * True when the ADR-0009 decision-8 evidences agree. Evidences 1 (registry\n * pid) and 2 (exact `--profile <expectedProfile>` cmdline, no other profile)\n * are always required. Evidence 3 (the env marker) is waived ONLY when the env is\n * genuinely unreadable (`hooks.envReadable(pid) === false`, e.g. `ps eww` is\n * unavailable) — in that case a fallback log is emitted. When the env is\n * readable but lacks the marker, this still refuses to signal. This is the\n * sole gate before any host signal and never falls back to a \"dsh\" substring\n * or port guess.\n */\nexport function evidencesAgree(\n pid: number,\n registryPid: number,\n hooks: ProcessKillHooks,\n expectedProfile: string = HOST_PROFILE,\n): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n if (registryPid !== pid) return false // (1) registry pid\n const cmd = hooks.cmdline(pid)\n if (!cmd) return false\n // (2) exactly one --profile, compared by equality (never a substring match).\n const profiles = [...cmd.matchAll(/--profile[= ]+([^\\s]+)/g)].map((m) => m[1])\n if (profiles.length === 0 || profiles.some((p) => p !== expectedProfile)) return false\n // (3) env marker — required when readable, optional when unreadable.\n if (hooks.hasServerEnv(pid)) return true\n if (hooks.envReadable && !hooks.envReadable(pid)) {\n hooks.onEnvFallback?.(pid)\n return true\n }\n return false\n}\n\nexport interface SafeStopOptions {\n /** The pid we intend to signal. */\n pid: number\n /** The pid recorded in the registry (evidence 1). */\n registryPid: number\n hooks: ProcessKillHooks\n /** Profile this host belongs to; must equal the cmdline profile (default `HOST_PROFILE`). */\n profile?: string\n termGraceMs?: number\n killGraceMs?: number\n sleep?: (ms: number) => Promise<void>\n pidAlive?: (pid: number) => boolean\n /** Injectable clock for wait deadlines (defaults to `Date.now`). */\n now?: () => number\n}\n\nexport interface SafeStopResult {\n /** Whether any signal was sent (false when evidence failed). */\n attempted: boolean\n /** Whether the three evidences agreed. */\n evidencesOk: boolean\n /** Signals actually sent, in order. */\n signals: NodeJS.Signals[]\n /** Whether the pid was confirmed gone at the end. */\n stopped: boolean\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nasync function waitGone(\n pid: number,\n budgetMs: number,\n alive: (pid: number) => boolean,\n sleep: (ms: number) => Promise<void>,\n now: () => number,\n): Promise<boolean> {\n if (!alive(pid)) return true\n const deadline = now() + budgetMs\n // Bound by BOTH the clock and an iteration cap: an injected clock that does\n // not advance (or a sleep that does not move it) must never spin forever.\n const maxIterations = Math.max(1, Math.ceil(budgetMs / DEFAULT_EXIT_POLL_MS) + 8)\n for (let i = 0; i < maxIterations && now() < deadline; i++) {\n await sleep(DEFAULT_EXIT_POLL_MS)\n if (!alive(pid)) return true\n }\n return !alive(pid)\n}\n\n/**\n * Confirm the three evidences, then SIGTERM → grace → SIGKILL a host. When any\n * evidence is missing this is a strict no-op (no signal at all). All I/O is\n * injectable; tests drive it with fake hooks / clock / sleep.\n */\nexport async function safeStopHost(options: SafeStopOptions): Promise<SafeStopResult> {\n const {\n pid,\n registryPid,\n hooks,\n profile = HOST_PROFILE,\n termGraceMs = DEFAULT_TERM_GRACE_MS,\n killGraceMs = DEFAULT_KILL_GRACE_MS,\n sleep = defaultSleep,\n pidAlive = hooks.pidAlive ?? defaultPidAlive,\n now = Date.now,\n } = options\n\n if (!evidencesAgree(pid, registryPid, hooks, profile)) {\n return { attempted: false, evidencesOk: false, signals: [], stopped: !pidAlive(pid) }\n }\n\n const signals: NodeJS.Signals[] = []\n hooks.kill(pid, 'SIGTERM')\n signals.push('SIGTERM')\n if (await waitGone(pid, termGraceMs, pidAlive, sleep, now)) {\n return { attempted: true, evidencesOk: true, signals, stopped: true }\n }\n\n hooks.kill(pid, 'SIGKILL')\n signals.push('SIGKILL')\n const stopped = await waitGone(pid, killGraceMs, pidAlive, sleep, now)\n return { attempted: true, evidencesOk: true, signals, stopped }\n}\n",
8
8
  "// Client-mode host lifecycle manager (ADR-0005 decision 5; audit bucket (e)).\n//\n// `ensureHost` manages ONE resident `dsh` host per profile per machine:\n//\n// const host = await ensureHost({ profile: 'opentui', idleExitSec: 5 })\n// host.authority // '127.0.0.1:45931' — where the host listens\n// host.cookieHeader // minted Cookie header for /api + /connect auth\n// host.pid // host child process id (or adopted pid)\n// host.port / host.url / host.token\n// host.adopted // true when a host spawned by another (dead) client was taken over\n// host.refCount // live users of this host from this process\n// host.retain() // +1 (join; cancels a pending idle-exit)\n// host.release() // -1; reaching 0 arms the idle-exit timer\n// await host.dispose() // SIGTERM (+SIGKILL escalation) now, remove lockfile\n//\n// Idempotency: a second `ensureHost` for the same profile + dshHome joins the\n// live host (refcount +1, pending idle-exit cancelled) instead of re-booting.\n//\n// Single-instance lock: `$DSH_HOME/opentui-host.<profile>.json` holds\n// { pid, port, authority, startedAt, profile }. A lock whose pid is dead or\n// whose listener is gone is stale and taken over (replaced by a fresh boot).\n// A lock whose pid lives and whose port listens is adopted ONLY after an\n// authenticated probe (`GET /` with the cookie minted from this home) proves\n// the process is OUR host: a foreign home / rotated grant answers 401 and\n// would otherwise leave the carrier reconnecting forever. The foreign pid is\n// never signalled; only the stale lock is removed.\n// A fresh lock is adopted (no spawn) — that is the crashed-client recovery\n// path. Unexpected child death clears the lock; the next `ensureHost`\n// respawns, capped at MAX_RAPID_RESPAWNS spawn attempts inside\n// RESPAWN_WINDOW_MS after which HostRespawnLoopError surfaces instead of\n// looping.\n//\n// Cold-boot mutual exclusion: before spawning, the booter claims the\n// lockfile as a `booting: true` placeholder (atomic create-if-absent —\n// exactly one cold boot wins per profile across processes). Another client\n// that finds a fresh booting lock WAITS for it to flip into a real lock and\n// then adopts it (join); it takes over (removes the placeholder and boots\n// itself) when the booting pid dies or the join budget\n// (`readinessTimeoutMs + BOOT_JOIN_MARGIN_MS`) lapses. The real lock is only\n// written after readiness + mint and only while the claim is still intact —\n// a superseded booter kills its own child (HostBootSupersededError) instead\n// of clobbering the winner's lock.\n//\n// Adoption bumps the lockfile (fresh startedAt/mtime): the detached idle\n// reaper (scripts/idle-reaper.mjs) treats a lockfile generation change since\n// its own start as a live adopter, so a client that adopted at the grace edge\n// and is still minting its cookie (no ESTABLISHED connection yet) is not\n// reaped underneath.\n//\n// Idle exit (ADR-0005 decision 5): when the refcount reaches 0 a timer of\n// `idleExitSec` seconds (default 5, overridable with\n// DSH_OPENTUI_HOST_IDLE_MS; `0` = never exit, resident) SIGTERMs the child\n// and cleans the lockfile; an `ensureHost` inside the grace window cancels the\n// timer and re-attaches. Because the in-process timer is unref()ed and dies\n// with the client, a clean quit also hands the window to the detached reaper\n// (scripts/idle-reaper.mjs), which owns it after this process is gone.\n//\n// Readiness: the `dsh web: http://127.0.0.1:<port>/?token=...` stdout line\n// (verified against the shipped CLI; it prints only after the loader and the\n// connection service are mounted) or an HTTP-responds fallback, within\n// `readinessTimeoutMs` (default 30s) — a typed HostBootTimeoutError on miss.\n// The HTTP fallback is deliberately stronger than a TCP accept: a bound\n// socket that does not answer HTTP rejects the carrier's first mux upgrade.\n// After a fallback boot (and the cookie mint) the lifecycle also performs the\n// full `$events` handshake, so a returned host is always mux-serving. Boot\n// errors quote the child's output tail (last 12 lines) in their message.\n// The child is spawned detached with a bind-probed free port, so it survives\n// this process and is adopted by the next client via the lockfile.\n//\n// Auth: `mintOwnerCookie({ home, authority, maxAgeMs? }): string` from\n// ./cookie-mint.ts (owned by the transport/cookie agent; contract frozen).\n// It resolves lazily at runtime so this file works before that module lands;\n// tests inject a fake via `mintCookie`. A missing module at runtime throws\n// MintUnavailableError. First-boot mint races (\"credentials grant not yet\n// written\") are retried for 15s before surfacing.\n//\n// Known v1 limit (per ADR-0005 decision 5): the refcount is per\n// manager-process. A client process that dies while holding the host leaves\n// it resident; the next client adopts it through the lockfile, and a clean\n// owner exit with refcount 0 shuts it down.\n\nimport { spawn } from 'node:child_process'\nimport { existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { connect as netConnect, Server, type AddressInfo } from 'node:net'\nimport { join } from 'node:path'\nimport { probeHostHttp, probeHostMux } from './host-probe.ts'\nimport { provisionAppendSystem } from './append-system.ts'\nimport { defaultPidAlive } from './safe-kill.ts'\n\nexport const DEFAULT_PROFILE = 'opentui'\n/** Idle-exit window: the resident host exits this long after the LAST client\n * disconnects, unless a client re-attaches inside the window. 5s is the\n * product default; `0` = never exit (resident). Override per process with\n * `DSH_OPENTUI_HOST_IDLE_MS` (milliseconds), or per call with\n * `ensureHost({ idleExitSec })`. */\nexport const DEFAULT_IDLE_EXIT_MS = 5_000\nexport const DEFAULT_IDLE_EXIT_SEC = DEFAULT_IDLE_EXIT_MS / 1000\n/** Env override for the idle-exit window, in milliseconds (`0` = resident;\n * an empty or unparsable value falls back to the default). */\nexport const ENV_IDLE_EXIT_MS = 'DSH_OPENTUI_HOST_IDLE_MS'\nexport const DEFAULT_READINESS_TIMEOUT_MS = 30_000\n/** Env override for the host-start readiness budget, in milliseconds. */\nexport const ENV_BOOT_TIMEOUT_MS = 'DSH_OPENTUI_BOOT_TIMEOUT_MS'\n/** Env override for the post-mint mux-readiness budget, in milliseconds. */\nexport const ENV_MUX_TIMEOUT_MS = 'DSH_OPENTUI_MUX_TIMEOUT_MS'\n/** Default mux-readiness budget (the former SERVE_PROBE_BUDGET_MS constant). */\nexport const DEFAULT_SERVE_PROBE_BUDGET_MS = 20_000\n/** Env override for the first-connection budget, in milliseconds (transport). */\nexport const ENV_CONNECT_TIMEOUT_MS = 'DSH_OPENTUI_CONNECT_TIMEOUT_MS'\n/** Default first-connection budget (mirrors transport.ts's former constant). */\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 30_000\n\n/** Resolve the idle window (ms) for this process: explicit seconds option >\n * `DSH_OPENTUI_HOST_IDLE_MS` > `DEFAULT_IDLE_EXIT_MS`. Negative values are\n * clamped to 0 (resident); sub-millisecond values round to the nearest ms. */\nexport function resolveIdleExitMs(explicitSec?: number): number {\n if (explicitSec !== undefined && Number.isFinite(explicitSec)) {\n return Math.max(0, Math.round(explicitSec * 1000))\n }\n const raw = process.env[ENV_IDLE_EXIT_MS]\n if (raw !== undefined && raw.trim() !== '') {\n const parsed = Number(raw)\n if (Number.isFinite(parsed)) return Math.max(0, Math.round(parsed))\n }\n return DEFAULT_IDLE_EXIT_MS\n}\n\n/** Same window in seconds (the `ensureHost`/`release()` unit). */\nexport function resolveIdleExitSec(explicitSec?: number): number {\n return resolveIdleExitMs(explicitSec) / 1000\n}\n\n/** A usable millisecond budget: finite, integer and strictly positive. */\nfunction validBudgetMs(value: number): boolean {\n return Number.isFinite(value) && Number.isInteger(value) && value > 0\n}\n\n/** Resolve a millisecond budget: explicit option > env > default. Non-finite,\n * non-integer and non-positive values are ignored (never thrown), falling\n * through to the next source — the same shape as resolveIdleExitMs. An env\n * value must be a plain decimal integer: `Number()` alone would also accept\n * hex/octal (`0x1D`), exponent (`30e2`) and numeric separators (`1_000`),\n * which are not valid spellings of a millisecond budget here. */\nfunction resolveBudgetMs(explicitMs: number | undefined, envName: string, defaultMs: number): number {\n if (explicitMs !== undefined && validBudgetMs(explicitMs)) return explicitMs\n const raw = process.env[envName]\n if (raw !== undefined && /^\\d+$/.test(raw)) {\n const parsed = Number(raw)\n if (validBudgetMs(parsed)) return parsed\n }\n return defaultMs\n}\n\n/** Host-start readiness budget: explicit > DSH_OPENTUI_BOOT_TIMEOUT_MS > 30s. */\nexport function resolveBootTimeoutMs(explicitMs?: number): number {\n return resolveBudgetMs(explicitMs, ENV_BOOT_TIMEOUT_MS, DEFAULT_READINESS_TIMEOUT_MS)\n}\n\n/** Post-mint mux-readiness budget: explicit > DSH_OPENTUI_MUX_TIMEOUT_MS > 20s. */\nexport function resolveMuxTimeoutMs(explicitMs?: number): number {\n return resolveBudgetMs(explicitMs, ENV_MUX_TIMEOUT_MS, DEFAULT_SERVE_PROBE_BUDGET_MS)\n}\n\n/** First-connection budget: explicit > DSH_OPENTUI_CONNECT_TIMEOUT_MS > 30s.\n * Lives here next to the other two so all three env contracts stay in sync;\n * transport.ts imports it for its connectBudgetMs. */\nexport function resolveConnectTimeoutMs(explicitMs?: number): number {\n return resolveBudgetMs(explicitMs, ENV_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS)\n}\n/** How long a lock whose pid is alive but not yet listening gets to come up\n * before we declare the lock stale (covers a cold host mid-boot). */\nexport const DEFAULT_STALE_PROBE_MS = 8_000\n/** Join budget over the readiness budget for a foreign booting placeholder:\n * covers the post-readiness cookie mint (MINT_RETRY_BUDGET_MS = 15s) that\n * still precedes the real lock write, plus slack. */\nconst BOOT_JOIN_MARGIN_MS = 20_000\n/** Poll cadence while waiting out a foreign booting placeholder. */\nconst BOOT_JOIN_POLL_MS = 200\nconst RESPAWN_WINDOW_MS = 15_000\nconst MAX_RAPID_RESPAWNS = 3\nconst LISTEN_PROBE_TIMEOUT_MS = 750\nconst LISTEN_POLL_MS = 200\n/** Bound for one authenticated adoption probe (a live host answers in ms). */\nconst ADOPT_PROBE_TIMEOUT_MS = 2_000\n/** Cadence for the post-boot mux-readiness poll (listener-fallback boots). */\nconst SERVE_PROBE_POLL_MS = 250\n/** Lines of child output quoted in surfaced error messages. */\nconst ERROR_TAIL_LINES = 12\nconst KILL_GRACE_MS = 5_000\nconst KILL_ESCALATE_MS = 2_000\nconst OUTPUT_TAIL_CAP = 8_000\n/** The host's readiness line (empirical, shipped dsh CLI):\n * `dsh web: http://127.0.0.1:<port>/?token=...` */\nconst URL_LINE = /dsh web: (https?:\\/\\/\\S+)/\n\n// ---------------------------------------------------------------------------\n// Errors — all typed, all carrying `code`.\n// ---------------------------------------------------------------------------\n\nexport class HostLifecycleError extends Error {\n readonly code: string\n constructor(code: string, message: string) {\n super(message)\n this.name = new.target.name\n this.code = code\n }\n}\n\n/** Last `ERROR_TAIL_LINES` lines of captured child output, for error text. */\nfunction errorTail(outputTail: string): string {\n const lines = outputTail.split(/\\r?\\n/).filter((line) => line.length > 0)\n if (lines.length === 0) return ''\n return `\\n--- dsh host output (last ${Math.min(lines.length, ERROR_TAIL_LINES)} lines) ---\\n${lines\n .slice(-ERROR_TAIL_LINES)\n .join('\\n')}`\n}\n\nexport class HostBootTimeoutError extends HostLifecycleError {\n constructor(readonly budgetMs: number, readonly outputTail: string) {\n super('host-boot-timeout', `dsh host did not become ready within ${budgetMs}ms${errorTail(outputTail)}`)\n }\n}\n\nexport class HostDiedError extends HostLifecycleError {\n constructor(\n readonly exitCode: number | null,\n readonly signal: string | null,\n readonly outputTail: string,\n ) {\n super(\n 'host-died',\n `dsh host exited before readiness (code=${exitCode ?? 'null'}, signal=${signal ?? 'null'})${errorTail(outputTail)}`,\n )\n }\n}\n\n/** The listener came up but the client mux never served a ready item — the\n * host is wedged or died just after binding (a patch/plugin failure). The\n * child's output tail is quoted so the failure is diagnosable from the TUI\n * error line alone. */\nexport class HostNotServingError extends HostLifecycleError {\n constructor(readonly outputTail: string, readonly budgetMs: number = DEFAULT_SERVE_PROBE_BUDGET_MS) {\n super(\n 'host-not-serving',\n `dsh host is listening but never served the client mux (${budgetMs}ms budget)${errorTail(outputTail)}`,\n )\n }\n}\n\nexport class HostSpawnError extends HostLifecycleError {\n constructor(readonly cause: Error) {\n super('host-spawn-failed', `failed to start dsh host: ${cause.message}`)\n this.name = new.target.name\n }\n}\n\nexport class HostRespawnLoopError extends HostLifecycleError {\n constructor(readonly attempts: number, readonly windowMs: number) {\n super(\n 'host-respawn-loop',\n `dsh host failed ${attempts} rapid spawn attempts within ${windowMs}ms — giving up instead of looping`,\n )\n }\n}\n\nexport class HostBootSupersededError extends HostLifecycleError {\n constructor() {\n super(\n 'host-boot-superseded',\n 'another client took over this boot while it was coming up — our child was shut down; retry ensureHost to join the winner',\n )\n }\n}\n\nexport class ProfileMissingError extends HostLifecycleError {\n constructor(readonly profile: string, readonly profileDir: string) {\n super(\n 'profile-missing',\n `profile '${profile}' is not provisioned (${profileDir} missing) — run scripts/provision-opentui-profile.mjs or: dsh ${profile} --from-default-profile web --dump-config`,\n )\n }\n}\n\nexport class MintUnavailableError extends HostLifecycleError {\n constructor() {\n super(\n 'mint-unavailable',\n 'mintOwnerCookie is unavailable: ./cookie-mint.ts not found and no mintCookie injected',\n )\n }\n}\n\n// ---------------------------------------------------------------------------\n// Injectable seams + public contract.\n// ---------------------------------------------------------------------------\n\n/** Minimal shape of the spawned child the manager needs (structurally\n * satisfied by node's ChildProcess; faked in tests). */\nexport interface HostChildProcess {\n pid: number\n exitCode: number | null\n stdout: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n stderr: { on(event: 'data', listener: (chunk: unknown) => void): unknown }\n on(event: 'exit', listener: (code: number | null, signal: string | null) => void): unknown\n on(event: 'error', listener: (err: Error) => void): unknown\n kill(signal?: string): boolean\n unref?(): void\n}\n\nexport type SpawnDsh = (\n argv: string[],\n options: { cwd: string; env: NodeJS.ProcessEnv },\n) => HostChildProcess\n\n/** Frozen contract with ./cookie-mint.ts (parallel agent owns the real file). */\nexport type MintOwnerCookie = (opts: {\n home: string\n authority: string\n maxAgeMs?: number\n}) => string\n\nexport interface EnsureHostOptions {\n /** Host profile to run. Fixed product profile per ADR-0005 decision 3. */\n profile?: string\n /** Idle seconds after the last release before the host is SIGTERMed.\n * Default 60. `0` = never exit (resident). */\n idleExitSec?: number\n /** dsh home dir. Default $DSH_HOME or ~/.dsh. */\n dshHome?: string\n /** Injectable spawn runner (tests). Default: real `dsh` from PATH. */\n spawnDsh?: SpawnDsh\n /** Injectable cookie mint (tests). Default: ./cookie-mint.ts import. */\n mintCookie?: MintOwnerCookie\n /** Readiness budget. Default 30_000 (or DSH_OPENTUI_BOOT_TIMEOUT_MS). */\n readinessTimeoutMs?: number\n /** Post-mint mux-readiness budget for listener-fallback boots.\n * Default 20_000 (or DSH_OPENTUI_MUX_TIMEOUT_MS). */\n serveProbeBudgetMs?: number\n /** Max wait for a concurrently-booting host (another process holding the\n * `booting` placeholder) to finish, when this client cold-boots behind it.\n * Default `readinessTimeoutMs + 20s` (readiness + mint budget + slack). */\n bootJoinTimeoutMs?: number\n /** Grace window for a locked-but-not-listening pid (default 8_000). */\n staleProbeMs?: number\n /** Cookie max age forwarded to mintOwnerCookie. */\n maxAgeMs?: number\n /** v2 host-launch seam (ADR-0009). Called by `ensureV2Host` to claim/attach\n * the singleton host through the v2 registry. Default: the real\n * `host-launch.ts ensureHost` (dynamically imported to avoid the registry↔\n * lifecycle import cycle). Tests inject a fake that writes a v2 record. */\n launchHost?: (deps: V2LaunchDeps) => Promise<V2LaunchResult>\n /** Child cwd for the v2 launcher (default `process.cwd()`). */\n cwd?: string\n}\n\n/** Minimal deps the v2 launcher needs from the client. */\nexport interface V2LaunchDeps {\n home: string\n profile: string\n cwd: string\n}\n\n/** The subset of host-launch's `HostLaunchResult` the v2 adapter consumes. */\nexport interface V2LaunchResult {\n port: number\n adopted: boolean\n spawned: boolean\n hostPid?: number\n}\n\nexport interface HostHandle {\n readonly profile: string\n readonly dshHome: string\n readonly pid: number\n readonly port: number\n /** '127.0.0.1:<port>' — audience for the minted cookie. */\n readonly authority: string\n /** Minted Cookie header value; send as `Cookie: <cookieHeader>`. */\n readonly cookieHeader: string\n /** The printed `dsh web:` URL, or null when readiness came from the probe. */\n readonly url: string | null\n /** Launch token parsed out of the URL, or null. */\n readonly token: string | null\n /** Child stdout/stderr tail captured by this process ('' when adopted). */\n diagnostics(): string\n /** True when this host was adopted from the lockfile, not spawned here. */\n readonly adopted: boolean\n /** ADR-0009: true when this handle is backed by the v2 host-launch stack\n * (v2 registry + heartbeat/watchdog lifecycle) rather than the legacy v1\n * lockfile. v2 handles never arm the v1 idle-5s timer or write the lock. */\n readonly v2Managed?: boolean\n readonly refCount: number\n /** +1 user (cancels a pending idle-exit). */\n retain(): void\n /** -1 user; at 0 arms the idle-exit timer (unless idleExitSec is 0). */\n release(): void\n /** SIGTERM (+SIGKILL escalation), remove the lockfile, evict the entry. */\n dispose(): Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Internal state.\n// ---------------------------------------------------------------------------\n\ntype HostState = 'booting' | 'ready' | 'disposing' | 'dead'\n\ninterface ManagedHost {\n key: string\n profile: string\n dshHome: string\n pid: number\n port: number\n authority: string\n cookieHeader: string\n url: string | null\n token: string | null\n adopted: boolean\n /** ADR-0009 v2-backed host: no v1 lockfile writes, no v1 idle timer. */\n v2Managed?: boolean\n child: HostChildProcess | null\n refCount: number\n idleTimer: ReturnType<typeof setTimeout> | null\n idleExitSec: number\n maxAgeMs?: number\n state: HostState\n /** The lockfile currently describes this host. */\n lockOwned: boolean\n outputTail: string\n exitInfo: { code: number | null; signal: string | null } | null\n resolveExit: () => void\n exitPromise: Promise<void>\n termination: Promise<void> | null\n handle: HostHandle | null\n mintCookie?: MintOwnerCookie\n}\n\ninterface LockFile {\n pid: number\n port: number\n authority: string\n startedAt: string\n profile: string\n /** True on the O_EXCL placeholder a booter holds between spawn and\n * readiness+mint; absent (false) on the real post-boot lock. */\n booting?: boolean\n}\n\n/** Live managed hosts, keyed by `<dshHome>\\u0000<profile>`. */\nconst registry = new Map<string, ManagedHost>()\n/** In-flight boots, same keys — concurrent ensureHosts join them. */\nconst pendingBoots = new Map<string, Promise<ManagedHost>>()\n/** Spawn-attempt timestamps per key, for the rapid-respawn cap. */\nconst respawnHistory = new Map<string, number[]>()\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nfunction registryKey(dshHome: string, profile: string): string {\n return `${dshHome}\\u0000${profile}`\n}\n\nexport function defaultDshHome(): string {\n return process.env.DSH_HOME || join(homedir(), '.dsh')\n}\n\nfunction lockPathFor(dshHome: string, profile: string): string {\n return join(dshHome, `opentui-host.${profile}.json`)\n}\n\n// ---------------------------------------------------------------------------\n// Primitives: pid / listener / port / lockfile.\n// ---------------------------------------------------------------------------\n\nexport function pidAlive(pid: number): boolean {\n return defaultPidAlive(pid)\n}\n\nexport function isListening(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false\n const socket = netConnect({ host: '127.0.0.1', port })\n const finish = (value: boolean) => {\n if (settled) return\n settled = true\n socket.destroy()\n resolve(value)\n }\n socket.setTimeout(LISTEN_PROBE_TIMEOUT_MS)\n socket.once('connect', () => finish(true))\n socket.once('error', () => finish(false))\n socket.once('timeout', () => finish(false))\n })\n}\n\n/** Stronger than a bare TCP accept: the port answers HTTP. A host binds its\n * socket before the HTTP/WS stack is mounted, so a TCP-only readiness signal\n * hands the carrier an authority whose first mux upgrade is rejected — the\n * `[connection] connection lost, retry #n` burst this check prevents. Any\n * status counts (401/404 prove the HTTP stack is serving). */\nasync function httpResponds(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://127.0.0.1:${port}/`, {\n signal: AbortSignal.timeout(LISTEN_PROBE_TIMEOUT_MS),\n redirect: 'manual',\n })\n try {\n await response.body?.cancel()\n } catch {\n /* already drained */\n }\n return true\n } catch {\n return false\n }\n}\n\n/** Bind-probe a free loopback port to hand to `dsh --port` (macOS has no\n * `timeout` command — all waiting here is JS timers). */\nfunction getFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = new Server((socket) => socket.destroy())\n server.once('error', reject)\n server.listen(0, '127.0.0.1', () => {\n const { port } = server.address() as AddressInfo\n server.close(() => resolve(port))\n })\n })\n}\n\n/** ADR-0009 v2 guard: the registry file at `<dshHome>/opentui-host.<profile>.json`\n * is shared by the v1 lockfile and the v2 registry. A record carrying\n * `version: 2` belongs to the host-launch stack and is NEVER a valid v1 lock.\n * v1 code must treat it as absent (read-only) — never downgrade it to v1. */\nfunction isV2Registry(dshHome: string, profile: string): boolean {\n try {\n const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as { version?: unknown } | null\n return raw !== null && typeof raw === 'object' && raw.version === 2\n } catch {\n return false\n }\n}\n\nfunction readLock(dshHome: string, profile: string): LockFile | null {\n try {\n const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as Partial<LockFile>\n // v2 records are not v1 locks: refuse to read them as such (P0-1).\n if ((raw as { version?: unknown }).version === 2) return null\n if (typeof raw.pid !== 'number' || typeof raw.port !== 'number') return null\n return {\n pid: raw.pid,\n port: raw.port,\n authority: typeof raw.authority === 'string' ? raw.authority : `127.0.0.1:${raw.port}`,\n startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '',\n profile: typeof raw.profile === 'string' ? raw.profile : profile,\n booting: raw.booting === true,\n }\n } catch {\n return null // missing or corrupt → stale\n }\n}\n\nfunction writeLock(dshHome: string, profile: string, host: ManagedHost): void {\n // P0-1: never overwrite a v2 registry with a v1 payload. The v2 stack owns\n // this file once written; an adopted client is strictly read-only here.\n if (isV2Registry(dshHome, profile)) return\n mkdirSync(dshHome, { recursive: true })\n const path = lockPathFor(dshHome, profile)\n const payload: LockFile = {\n pid: host.pid,\n port: host.port,\n authority: host.authority,\n startedAt: new Date().toISOString(),\n profile,\n }\n const tmp = `${path}.tmp`\n writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\\n')\n renameSync(tmp, path) // near-atomic single-instance lock write\n}\n\n/** Remove the lockfile only if it still describes THIS host (never clobber a\n * newer host's lock). */\nfunction clearOurLock(host: ManagedHost): void {\n if (!host.lockOwned) return\n const lock = readLock(host.dshHome, host.profile)\n if (lock && lock.pid === host.pid && lock.port === host.port) {\n rmSync(lockPathFor(host.dshHome, host.profile), { force: true })\n }\n}\n\n// -- Cold-boot mutual exclusion (the `booting` placeholder) -----------------\n\n/** Atomically claim the lockfile as a booting placeholder (create-if-absent\n * via link(2) on a fully-written tmp file — the winner's content is complete\n * at creation, so readers never see a partial claim). Exactly one cold boot\n * per profile wins across processes. Returns the claim's startedAt token, or\n * null when a rival (booting placeholder or real lock) already holds the\n * file. The placeholder's pid is the BOOTER's pid — the liveness anchor until\n * the real lock (child pid) replaces it. */\nfunction claimBootLock(dshHome: string, profile: string): string | null {\n // P0-1: a v2 registry is a live single-instance claim — a v1 booter must\n // never clobber it with a booting placeholder (that would orphan the v2 host).\n if (isV2Registry(dshHome, profile)) return null\n mkdirSync(dshHome, { recursive: true })\n const path = lockPathFor(dshHome, profile)\n const payload: LockFile = {\n pid: process.pid,\n port: 0, // unknown until the bind probe; waiters never probe it\n authority: '127.0.0.1:0',\n startedAt: new Date().toISOString(),\n profile,\n booting: true,\n }\n const tmp = `${path}.claim-${process.pid}-${Date.now()}`\n writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\\n')\n try {\n linkSync(tmp, path) // EEXIST when a rival holds the file\n return payload.startedAt\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') return null\n throw err\n } finally {\n rmSync(tmp, { force: true })\n }\n}\n\n/** Remove a booting placeholder only if it still describes THIS claim (pid,\n * optionally the startedAt token) — never a completed boot's real lock or a\n * rival's newer claim. */\nfunction removeBootClaim(\n dshHome: string,\n profile: string,\n claim: { pid: number; startedAt?: string },\n): boolean {\n const path = lockPathFor(dshHome, profile)\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<LockFile>\n if (raw.booting !== true || raw.pid !== claim.pid) return false\n if (claim.startedAt !== undefined && raw.startedAt !== claim.startedAt) return false\n } catch {\n return false // gone or corrupt — nothing of ours to remove\n }\n rmSync(path, { force: true })\n return true\n}\n\n/** Remove a stale REAL lock only if it still describes the lock we judged\n * stale (never clobber a fresher write, never touch a placeholder). */\nfunction removeStaleLock(dshHome: string, profile: string, stale: LockFile): boolean {\n const path = lockPathFor(dshHome, profile)\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial<LockFile>\n if (raw.booting === true || raw.pid !== stale.pid || raw.port !== stale.port) return false\n } catch {\n return false\n }\n rmSync(path, { force: true })\n return true\n}\n\n/** True while the lockfile still holds OUR booting claim. */\nfunction bootClaimIntact(dshHome: string, profile: string, startedAt: string): boolean {\n try {\n const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as Partial<LockFile>\n return raw.booting === true && raw.pid === process.pid && raw.startedAt === startedAt\n } catch {\n return false\n }\n}\n\n/** Wait out a foreign booting placeholder (cross-process cold-boot mutual\n * exclusion): poll until the claim either flips into a real lock (the boot\n * completed — bootHost re-evaluates and adopts it) or becomes takeable\n * (booting pid dead / join budget lapsed — bootHost re-evaluates, finds no\n * lock and claims the boot itself). Never signals the booting pid. */\nasync function waitOutBootingLock(first: LockFile, o: ResolvedOptions): Promise<void> {\n // A booting claim naming OUR pid is a leftover from a previous incarnation\n // of this pid (crash + pid reuse): take it over immediately.\n if (first.pid === process.pid) {\n removeBootClaim(o.dshHome, o.profile, { pid: first.pid })\n return\n }\n const budget = o.bootJoinTimeoutMs ?? o.readinessTimeoutMs + BOOT_JOIN_MARGIN_MS\n const deadline = Date.now() + budget\n const claim = { pid: first.pid, startedAt: first.startedAt }\n while (Date.now() < deadline) {\n await sleep(BOOT_JOIN_POLL_MS)\n if (!pidAlive(claim.pid)) {\n // the booter died mid-boot: its claim is abandoned — take it over\n removeBootClaim(o.dshHome, o.profile, claim)\n return\n }\n const current = readLock(o.dshHome, o.profile)\n if (!current || !current.booting) return // boot completed (or claim gone) — re-evaluate\n }\n // Join budget lapsed: force the takeover if the claim is unchanged.\n removeBootClaim(o.dshHome, o.profile, claim)\n}\n\n// ---------------------------------------------------------------------------\n// Cookie mint resolution (real module owned by the transport/cookie agent).\n// ---------------------------------------------------------------------------\n\nlet realMintPromise: Promise<MintOwnerCookie | null> | null = null\n\n/** Resolves `mintOwnerCookie` from ./cookie-mint.ts at runtime. The specifier\n * is built dynamically on purpose: the module is owned by the parallel\n * transport/cookie agent and may not exist yet — a literal import would fail\n * to typecheck until it lands, and flipping ts-ignore/expect-error would\n * break whichever side lands last. */\nfunction loadRealMint(): Promise<MintOwnerCookie | null> {\n realMintPromise ??= (async () => {\n const dynamicImport = (specifier: string): Promise<unknown> => import(specifier)\n for (const specifier of ['./cookie-mint.js', './cookie-mint.ts']) {\n try {\n const mod: unknown = await dynamicImport(specifier)\n const mint = (mod as { mintOwnerCookie?: unknown }).mintOwnerCookie\n if (typeof mint === 'function') return mint as MintOwnerCookie\n } catch {\n // try next specifier / fall through to null\n }\n }\n return null\n })()\n return realMintPromise\n}\n\nasync function mintCookieFor(host: ManagedHost): Promise<string> {\n const mint = host.mintCookie ?? (await loadRealMint())\n if (!mint) throw new MintUnavailableError()\n return mint({\n home: host.dshHome,\n authority: host.authority,\n ...(host.maxAgeMs !== undefined ? { maxAgeMs: host.maxAgeMs } : {}),\n })\n}\n\n/** Mint errors that mean \"the host has not written its grant yet\" (first-boot\n * race — the Host persists `client-connection/browser-session` during\n * connection activation, which can lag the readiness line on a cold boot).\n * cookie-mint.ts already retries these for 2s internally; a cold scratch\n * home needs more, so the manager retries them here too. Permanent mint\n * failures (insecure file, invalid grant shape) surface immediately. */\nconst RETRYABLE_MINT_ERRORS = new Set(['CredentialsFileMissingError', 'CredentialsGrantMissingError'])\nconst MINT_RETRY_BUDGET_MS = 15_000\nconst MINT_RETRY_INTERVAL_MS = 250\n\nasync function mintCookieWithRetry(host: ManagedHost): Promise<string> {\n const deadline = Date.now() + MINT_RETRY_BUDGET_MS\n for (;;) {\n try {\n return await mintCookieFor(host)\n } catch (err) {\n const retryable = err instanceof Error && RETRYABLE_MINT_ERRORS.has(err.name)\n if (!retryable || Date.now() >= deadline) throw err\n await sleep(MINT_RETRY_INTERVAL_MS)\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Child plumbing.\n// ---------------------------------------------------------------------------\n\nfunction defaultSpawnDsh(argv: string[], options: { cwd: string; env: NodeJS.ProcessEnv }): HostChildProcess {\n const env = { ...options.env }\n // npm_config_* leaks from `npm run` wrappers confuse the dsh boot; strip.\n for (const key of Object.keys(env)) {\n if (key.startsWith('npm_config_')) delete env[key]\n }\n const child = spawn('dsh', argv, {\n cwd: options.cwd,\n env,\n detached: true, // resident host must survive this client process\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n child.unref()\n // piped stdio keeps the manager's event loop alive; unref the pipes too\n // (bun's stream types omit unref, hence the structural cast)\n for (const pipe of [child.stdout, child.stderr]) {\n ;(pipe as unknown as { unref?: () => void }).unref?.()\n }\n return child as unknown as HostChildProcess\n}\n\n/** OpenTUI's native layer (host-entry-v2) needs node's `--experimental-ffi`;\n * a bare `dsh --profile <profile>` does not carry it (only the dsh-opentui\n * launcher injects it, and client mode never runs through that launcher).\n * Without the flag the mounted v2 shell re-execs the whole dsh command line\n * to add it (reExecWithFfi) — a second host instance then races the booting\n * listener (EADDRINUSE) and the client's TUI renders blank. Merge the flag\n * into NODE_OPTIONS here, once, deduped as a space-delimited token (the same\n * rule as the dsh-opentui launcher's `--plugin` branch) so an inherited\n * NODE_OPTIONS that already carries the flag is passed through untouched. */\nconst FFI_FLAG = '--experimental-ffi'\n\nfunction withFfiFlag(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const existing = env.NODE_OPTIONS ?? ''\n if (existing.split(/\\s+/).includes(FFI_FLAG)) return env\n return { ...env, NODE_OPTIONS: `${existing} ${FFI_FLAG}`.trim() }\n}\n\nfunction childEnv(dshHome: string): NodeJS.ProcessEnv {\n return withFfiFlag({ ...process.env, DSH_HOME: dshHome })\n}\n\nfunction attachChildWatchers(host: ManagedHost, child: HostChildProcess): void {\n const push = (chunk: unknown) => {\n host.outputTail = (host.outputTail + String(chunk)).slice(-OUTPUT_TAIL_CAP)\n }\n child.stdout.on('data', push)\n child.stderr.on('data', push)\n child.on('error', () => {\n // post-boot spawn errors (rare; boot-time ones are surfaced by the\n // readiness waiter's own 'error' listener)\n })\n child.on('exit', (code, signal) => {\n host.exitInfo = { code, signal }\n host.resolveExit()\n if (host.state === 'ready') {\n // unexpected death: clear the lock, evict; the next ensureHost respawns\n if (host.idleTimer) {\n clearTimeout(host.idleTimer)\n host.idleTimer = null\n }\n clearOurLock(host)\n host.state = 'dead'\n registry.delete(host.key)\n }\n // 'booting' → the readiness waiter rejects; 'disposing' → our own kill.\n })\n}\n\ninterface ReadyResult {\n url: string | null\n token: string | null\n port: number\n authority: string\n /** Which signal resolved readiness. `url` is the host's post-loader line\n * (the full plugin tree and the connection service are mounted); `listener`\n * is the weaker HTTP fallback and must be followed by a mux probe. */\n via: 'url' | 'listener'\n}\n\nfunction readyFromUrl(urlText: string): ReadyResult {\n const url = new URL(urlText)\n const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80)\n return {\n url: urlText,\n token: url.searchParams.get('token'),\n port,\n authority: `${url.hostname}:${port}`,\n via: 'url',\n }\n}\n\nfunction waitForReadiness(\n child: HostChildProcess,\n expectedPort: number,\n budgetMs: number,\n getTail: () => string,\n): Promise<ReadyResult> {\n return new Promise<ReadyResult>((resolve, reject) => {\n let settled = false\n const done = (ok: boolean, value: ReadyResult | HostLifecycleError) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n clearInterval(poll)\n if (ok) resolve(value as ReadyResult)\n else reject(value)\n }\n const timer = setTimeout(() => {\n child.kill('SIGTERM')\n done(false, new HostBootTimeoutError(budgetMs, getTail()))\n }, budgetMs)\n child.on('exit', (code, signal) =>\n done(false, new HostDiedError(code, signal, getTail())),\n )\n child.on('error', (err) => done(false, new HostSpawnError(err)))\n child.stdout.on('data', (chunk) => {\n const match = URL_LINE.exec(String(chunk))\n if (match) done(true, readyFromUrl(match[1]!))\n })\n // Fallback: wait for the HTTP stack, not just the bound socket (in case\n // the stdout contract changes). TCP-bind readiness is too early — the\n // carrier's first mux upgrade would be rejected.\n const poll = setInterval(() => {\n void httpResponds(expectedPort).then((up) => {\n if (up) {\n done(true, {\n url: null,\n token: null,\n port: expectedPort,\n authority: `127.0.0.1:${expectedPort}`,\n via: 'listener',\n })\n }\n })\n }, LISTEN_POLL_MS)\n })\n}\n\n// ---------------------------------------------------------------------------\n// Boot / adopt / terminate.\n// ---------------------------------------------------------------------------\n\nfunction makeHandle(host: ManagedHost): HostHandle {\n host.handle ??= {\n get profile() {\n return host.profile\n },\n get dshHome() {\n return host.dshHome\n },\n get pid() {\n return host.pid\n },\n get port() {\n return host.port\n },\n get authority() {\n return host.authority\n },\n get cookieHeader() {\n return host.cookieHeader\n },\n get url() {\n return host.url\n },\n get token() {\n return host.token\n },\n diagnostics() {\n return errorTail(host.outputTail).replace(/^\\n/, '')\n },\n get adopted() {\n return host.adopted\n },\n get v2Managed() {\n return host.v2Managed === true\n },\n get refCount() {\n return host.refCount\n },\n retain() {\n attachHost(host)\n },\n release() {\n releaseHost(host)\n },\n dispose() {\n return terminateHost(host)\n },\n }\n return host.handle!\n}\n\nfunction adoptHost(lock: LockFile, o: ResolvedOptions): ManagedHost {\n const host: ManagedHost = {\n key: o.key,\n profile: o.profile,\n dshHome: o.dshHome,\n pid: lock.pid,\n port: lock.port,\n authority: lock.authority,\n cookieHeader: '',\n url: null,\n token: null,\n adopted: true,\n child: null,\n refCount: 0,\n idleTimer: null,\n idleExitSec: o.idleExitSec,\n maxAgeMs: o.maxAgeMs,\n state: 'ready',\n lockOwned: true, // the existing lockfile already describes this host\n outputTail: '',\n exitInfo: null,\n resolveExit: () => {},\n exitPromise: Promise.resolve(),\n termination: null,\n handle: null,\n mintCookie: o.mintCookie,\n }\n registry.set(o.key, host)\n // Adoption bump: refresh startedAt/mtime so the detached idle reaper sees\n // recent liveness — the adopted client can spend up to MINT_RETRY_BUDGET_MS\n // minting its cookie before its first ESTABLISHED connection, past a\n // grace-edge adoption.\n writeLock(o.dshHome, o.profile, host)\n return host\n}\n\ninterface ResolvedOptions {\n profile: string\n dshHome: string\n idleExitSec: number\n readinessTimeoutMs: number\n serveProbeBudgetMs: number\n bootJoinTimeoutMs?: number\n staleProbeMs: number\n maxAgeMs?: number\n spawnDsh: SpawnDsh\n mintCookie?: MintOwnerCookie\n key: string\n}\n\nfunction resolveOptions(opts: EnsureHostOptions): ResolvedOptions {\n const profile = opts.profile ?? DEFAULT_PROFILE\n const dshHome = opts.dshHome ?? defaultDshHome()\n const idleExitSec = resolveIdleExitSec(opts.idleExitSec)\n return {\n profile,\n dshHome,\n idleExitSec,\n readinessTimeoutMs: resolveBootTimeoutMs(opts.readinessTimeoutMs),\n serveProbeBudgetMs: resolveMuxTimeoutMs(opts.serveProbeBudgetMs),\n ...(opts.bootJoinTimeoutMs !== undefined ? { bootJoinTimeoutMs: opts.bootJoinTimeoutMs } : {}),\n staleProbeMs: opts.staleProbeMs ?? DEFAULT_STALE_PROBE_MS,\n ...(opts.maxAgeMs !== undefined ? { maxAgeMs: opts.maxAgeMs } : {}),\n spawnDsh: opts.spawnDsh ?? defaultSpawnDsh,\n ...(opts.mintCookie !== undefined ? { mintCookie: opts.mintCookie } : {}),\n key: registryKey(dshHome, profile),\n }\n}\n\nasync function bootHost(o: ResolvedOptions): Promise<ManagedHost> {\n // Respawn cap: no infinite loops. Spawn attempts inside the rolling window\n // count; a successful boot resets the history.\n const now = Date.now()\n const history = (respawnHistory.get(o.key) ?? []).filter((t) => now - t < RESPAWN_WINDOW_MS)\n if (history.length >= MAX_RAPID_RESPAWNS) {\n throw new HostRespawnLoopError(MAX_RAPID_RESPAWNS, RESPAWN_WINDOW_MS)\n }\n respawnHistory.set(o.key, [...history, now])\n\n // Phase 1 — resolve the single-instance lock. Loops until this process\n // either adopts a live host or holds the O_EXCL booting claim.\n let claimStartedAt = ''\n for (;;) {\n const lock = readLock(o.dshHome, o.profile)\n if (lock?.booting) {\n // Another process holds the cold-boot claim: wait it out (join on\n // success, takeover on booter death / join-budget lapse), then\n // re-evaluate — a completed boot is adopted below.\n await waitOutBootingLock(lock, o)\n continue\n }\n if (lock && (await lockIsFresh(lock, o.staleProbeMs))) {\n const adopted = adoptHost(lock, o) // bumps the lockfile (reaper liveness)\n adopted.cookieHeader = await mintCookieWithRetry(adopted)\n // A live pid + open port is not enough: the process must accept OUR\n // cookie (same home grant) and serve the web app. A foreign/rotated\n // host on that port answers 401/404 and would make the carrier retry\n // forever — treat the lock as stale and boot fresh instead.\n if (\n await probeHostHttp({\n authority: adopted.authority,\n cookieHeader: adopted.cookieHeader,\n timeoutMs: ADOPT_PROBE_TIMEOUT_MS,\n })\n ) {\n respawnHistory.delete(o.key)\n return adopted\n }\n // Never signal the foreign pid (it may belong to another home / user);\n // drop only the stale lock so the fresh boot can claim it.\n registry.delete(o.key)\n removeStaleLock(o.dshHome, o.profile, lock)\n continue\n }\n // Stale lock (or none): clear the way, verify the profile, claim the\n // boot placeholder. A rival that claimed first leaves the file in place\n // (EEXIST) — re-evaluate against its booting claim.\n if (lock) removeStaleLock(o.dshHome, o.profile, lock)\n const lockPath = lockPathFor(o.dshHome, o.profile)\n if (!existsSync(lockPath)) {\n const profileDir = join(o.dshHome, 'profiles', o.profile)\n if (!existsSync(profileDir)) throw new ProfileMissingError(o.profile, profileDir)\n const claimed = claimBootLock(o.dshHome, o.profile)\n if (claimed !== null) {\n claimStartedAt = claimed\n break // we hold the claim — proceed to spawn\n }\n } else if (readLock(o.dshHome, o.profile) === null) {\n // File exists but is unreadable/corrupt: pre-fix semantics treat a\n // corrupt lock as stale — remove it and re-evaluate.\n rmSync(lockPath, { force: true })\n }\n await sleep(BOOT_JOIN_POLL_MS)\n }\n\n // Phase 2 — boot under the claim. The claim is released by writeLock on\n // success and removed in the failure path.\n const profileDir = join(o.dshHome, 'profiles', o.profile)\n // Append-system (dsh-tui-pi port): seed $DSH_HOME/APPEND_SYSTEM.md and keep\n // the managed preset row in the profile patch BEFORE the host spawns — the\n // host reads the patch (and evaluates the persona suffix's `!!js` read) at\n // its own boot. Best-effort: a failure boots without the preset, and the\n // roster gate in remote-host-session keeps `agentPreset` off the wire, so\n // an enrichment must never fail the boot.\n try {\n const provision = provisionAppendSystem(o.dshHome, o.profile)\n // Same channel as the throw path: a skipped/collision outcome boots\n // WITHOUT the preset and must be visible in the error log, never silent.\n if (provision.patch.status === 'collision' || provision.patch.status === 'skipped') {\n console.error(`[lifecycle] append-system preset not provisioned (${provision.patch.status}): ${provision.patch.detail}`)\n }\n } catch (error) {\n console.error('[lifecycle] append-system sync failed (booting without the preset):', error)\n }\n const port = await getFreePort()\n const child = o.spawnDsh(['--profile', o.profile, '--no-open', '--port', String(port)], {\n cwd: profileDir,\n env: childEnv(o.dshHome),\n })\n const host: ManagedHost = {\n key: o.key,\n profile: o.profile,\n dshHome: o.dshHome,\n pid: child.pid,\n port,\n authority: `127.0.0.1:${port}`,\n cookieHeader: '',\n url: null,\n token: null,\n adopted: false,\n child,\n refCount: 0,\n idleTimer: null,\n idleExitSec: o.idleExitSec,\n maxAgeMs: o.maxAgeMs,\n state: 'booting',\n lockOwned: false,\n outputTail: '',\n exitInfo: null,\n resolveExit: () => {},\n exitPromise: Promise.resolve(),\n termination: null,\n handle: null,\n mintCookie: o.mintCookie,\n }\n {\n let resolveExit!: () => void\n host.exitPromise = new Promise<void>((resolve) => {\n resolveExit = resolve\n })\n host.resolveExit = resolveExit\n }\n attachChildWatchers(host, child)\n\n try {\n const ready = await waitForReadiness(child, port, o.readinessTimeoutMs, () => host.outputTail)\n host.url = ready.url\n host.token = ready.token\n if (ready.port !== port) {\n host.port = ready.port\n }\n host.authority = ready.authority\n host.cookieHeader = await mintCookieWithRetry(host)\n // The listener-fallback readiness only proves the HTTP stack answers.\n // Gate on the actual client mux ($events ready item) so the carrier's\n // first attempt cannot land in the retry loop; the URL line already\n // implies the loader + connection service are mounted.\n if (ready.via === 'listener') {\n const deadline = Date.now() + o.serveProbeBudgetMs\n let serving = false\n while (Date.now() < deadline) {\n serving = await probeHostMux({\n authority: host.authority,\n cookieHeader: host.cookieHeader,\n timeoutMs: 1_500,\n })\n if (serving) break\n if (!pidAlive(child.pid)) break // died after binding: surface the tail now\n await sleep(SERVE_PROBE_POLL_MS)\n }\n if (!serving) throw new HostNotServingError(host.outputTail, o.serveProbeBudgetMs)\n }\n // Claim still ours? A join-budget takeover by another client replaced the\n // placeholder — kill our child rather than clobber the winner's lock\n // (which would leave two live hosts and concurrent DSH_HOME writers).\n if (!bootClaimIntact(o.dshHome, o.profile, claimStartedAt)) {\n throw new HostBootSupersededError()\n }\n writeLock(o.dshHome, o.profile, host) // replaces the booting placeholder\n host.lockOwned = true\n host.state = 'ready'\n respawnHistory.delete(o.key)\n registry.set(o.key, host)\n return host\n } catch (err) {\n // Boot failed (timeout / death / mint / superseded): release the claim\n // and shut down what we started.\n removeBootClaim(o.dshHome, o.profile, { pid: process.pid, startedAt: claimStartedAt })\n await terminateHost(host).catch(() => {})\n throw err\n }\n}\n\n/** Fresh lock check: pid alive AND listener up. A pid that is alive but not\n * listening may be mid-boot, so it gets `staleProbeMs` to come up. */\nasync function lockIsFresh(lock: LockFile, staleProbeMs: number): Promise<boolean> {\n if (!pidAlive(lock.pid)) return false\n if (await isListening(lock.port)) return true\n const deadline = Date.now() + staleProbeMs\n while (Date.now() < deadline) {\n await sleep(LISTEN_POLL_MS)\n if (!pidAlive(lock.pid)) return false\n if (await isListening(lock.port)) return true\n }\n return false\n}\n\nfunction attachHost(host: ManagedHost): void {\n host.refCount += 1\n if (host.idleTimer) {\n clearTimeout(host.idleTimer)\n host.idleTimer = null\n }\n}\n\nfunction releaseHost(host: ManagedHost): void {\n host.refCount = Math.max(0, host.refCount - 1)\n // ADR-0009 decision 6: v2-backed hosts are shut down by the refcount +\n // heartbeat + last-one grace path (client-lifecycle), never by the legacy\n // idle-5s timer. A v2 release only drops the in-process ref; it never arms\n // a kill timer (two lifecycles must not coexist on one host).\n if (host.v2Managed) return\n if (host.refCount === 0 && host.state === 'ready' && host.idleExitSec > 0) {\n const timer = setTimeout(() => {\n host.idleTimer = null\n void terminateHost(host)\n }, host.idleExitSec * 1000)\n timer.unref?.() // a refcount-0 manager must not hang on this timer\n host.idleTimer = timer\n }\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(pid, signal)\n } catch {\n // already gone — fine\n }\n}\n\nasync function waitPidGone(pid: number, budgetMs: number): Promise<boolean> {\n const deadline = Date.now() + budgetMs\n while (pidAlive(pid)) {\n if (Date.now() > deadline) return false\n await sleep(LISTEN_POLL_MS)\n }\n return true\n}\n\nasync function terminateHost(host: ManagedHost): Promise<void> {\n if (host.state === 'dead') {\n clearOurLock(host)\n registry.delete(host.key)\n return\n }\n if (host.state === 'disposing' && host.termination) return host.termination\n if (host.termination) return host.termination\n\n host.state = 'disposing'\n clearOurLock(host)\n registry.delete(host.key)\n\n host.termination = (async () => {\n if (host.child) {\n host.child.kill('SIGTERM')\n await Promise.race([host.exitPromise, sleep(KILL_GRACE_MS)])\n if (!host.exitInfo) {\n signalPid(host.pid, 'SIGKILL')\n await Promise.race([host.exitPromise, sleep(KILL_ESCALATE_MS)])\n }\n } else {\n // Adopted host: no child object in this process; signal by pid.\n signalPid(host.pid, 'SIGTERM')\n if (!(await waitPidGone(host.pid, KILL_GRACE_MS))) {\n signalPid(host.pid, 'SIGKILL')\n await waitPidGone(host.pid, KILL_ESCALATE_MS)\n }\n }\n host.state = 'dead'\n })()\n // The exit watcher only acts on state 'ready', so our own SIGTERM here\n // ('disposing') and booting failures ('booting') are not re-evicted.\n return host.termination\n}\n\n// ---------------------------------------------------------------------------\n// v2 host-launch attach (ADR-0009 — the production path).\n// ---------------------------------------------------------------------------\n\n/** The v2 registry fields the client adapter needs (host-registry.ts owns the\n * canonical type; read locally to avoid the registry→lifecycle import cycle). */\nfunction readV2Record(dshHome: string, profile: string): { pid: number; port: number; authority: string } | null {\n try {\n const raw = JSON.parse(readFileSync(lockPathFor(dshHome, profile), 'utf8')) as {\n version?: unknown\n pid?: unknown\n port?: unknown\n authority?: unknown\n } | null\n if (raw === null || typeof raw !== 'object' || raw.version !== 2) return null\n if (typeof raw.pid !== 'number' || typeof raw.port !== 'number') return null\n return {\n pid: raw.pid,\n port: raw.port,\n authority: typeof raw.authority === 'string' ? raw.authority : `127.0.0.1:${raw.port}`,\n }\n } catch {\n return null\n }\n}\n\n/** Default v2 launcher: dynamically import host-launch so this module never\n * statically depends on the registry/health/port modules that import it back\n * (their `pidAlive`/`isListening` helpers are used at call time only). */\nasync function defaultLaunchHost(deps: V2LaunchDeps): Promise<V2LaunchResult> {\n const mod = await import('./host-launch.ts')\n return mod.ensureHost({ home: deps.home, profile: deps.profile, cwd: deps.cwd })\n}\n\n/** Boot/adopt the host via the v2 host-launch stack and wrap it in a\n * HostHandle. This performs NO v1 lockfile write: `lockOwned` is false and a\n * v2 registry is consumed read-only. The host's real lifecycle is refcount +\n * heartbeat + last-one grace + watchdog (client-lifecycle.ts), not the v1\n * idle-5s timer. */\nasync function bootV2Host(o: ResolvedOptions, opts: EnsureHostOptions): Promise<ManagedHost> {\n const launch = opts.launchHost ?? defaultLaunchHost\n const result = await launch({ home: o.dshHome, profile: o.profile, cwd: opts.cwd ?? process.cwd() })\n\n // The launcher writes the v2 registry; adopt it read-only. Fall back to the\n // launcher result when a fake seam did not materialise a record on disk.\n const record = readV2Record(o.dshHome, o.profile)\n const port = record?.port ?? result.port\n const pid = record?.pid ?? result.hostPid ?? 0\n const authority = record?.authority ?? `127.0.0.1:${port}`\n\n const host: ManagedHost = {\n key: o.key,\n profile: o.profile,\n dshHome: o.dshHome,\n pid,\n port,\n authority,\n cookieHeader: '',\n url: null,\n token: null,\n adopted: result.adopted,\n v2Managed: true,\n child: null,\n refCount: 0,\n idleTimer: null,\n idleExitSec: 0, // no legacy idle timer: ADR-0009 decision 6\n state: 'ready',\n lockOwned: false, // never write/clear the v1 lockfile\n outputTail: '',\n exitInfo: null,\n resolveExit: () => {},\n exitPromise: Promise.resolve(),\n termination: null,\n handle: null,\n ...(o.maxAgeMs !== undefined ? { maxAgeMs: o.maxAgeMs } : {}),\n ...(o.mintCookie !== undefined ? { mintCookie: o.mintCookie } : {}),\n }\n registry.set(o.key, host)\n host.cookieHeader = await mintCookieWithRetry(host)\n return host\n}\n\n/** ADR-0009 production entry: ensure/adopt the singleton host through the v2\n * host-launch stack (v2 registry), producing a HostHandle with no v1 writes. */\nexport async function ensureV2Host(opts: EnsureHostOptions = {}): Promise<HostHandle> {\n const o = resolveOptions(opts)\n\n const live = registry.get(o.key)\n if (live && live.state === 'ready' && live.v2Managed) {\n attachHost(live)\n return makeHandle(live)\n }\n\n const pending = pendingBoots.get(o.key)\n if (pending) {\n const host = await pending\n attachHost(host)\n return makeHandle(host)\n }\n\n const boot = bootV2Host(o, opts).finally(() => pendingBoots.delete(o.key))\n pendingBoots.set(o.key, boot)\n const host = await boot\n attachHost(host)\n return makeHandle(host)\n}\n\n// ---------------------------------------------------------------------------\n// Public entry point.\n// ---------------------------------------------------------------------------\n\n/** Manage one resident dsh host per profile (see file header for the full\n * contract). Idempotent: existing live hosts are joined, not re-booted.\n *\n * ADR-0009 (P0-1): when the registry is already a version-2 record, this\n * delegates to `ensureV2Host` so the legacy v1 lockfile path never touches it.\n * The legacy path remains only for pre-upgrade (v1) registries. */\nexport async function ensureHost(opts: EnsureHostOptions = {}): Promise<HostHandle> {\n const o = resolveOptions(opts)\n if (isV2Registry(o.dshHome, o.profile)) return ensureV2Host(opts)\n\n const live = registry.get(o.key)\n if (live && live.state === 'ready') {\n attachHost(live)\n return makeHandle(live)\n }\n\n const pending = pendingBoots.get(o.key)\n if (pending) {\n const host = await pending\n attachHost(host)\n return makeHandle(host)\n }\n\n const boot = bootHost(o).finally(() => pendingBoots.delete(o.key))\n pendingBoots.set(o.key, boot)\n const host = await boot\n attachHost(host)\n return makeHandle(host)\n}\n\n// ---------------------------------------------------------------------------\n// Test-only internals.\n// ---------------------------------------------------------------------------\n\n/** Exposed strictly for the lifecycle tests: registry eviction checks and\n * probing whether the real cookie-mint module has landed. Not a public API. */\nexport const __internals = {\n registry,\n pendingBoots,\n respawnHistory,\n loadRealMint,\n lockPathFor,\n registryKey,\n}\n",
9
9
  "/**\n * Singleton host registry — schema v2 (ADR-0009 decisions 4 & 8;\n * DESIGN-redesign §7).\n *\n * File: `<DSH_HOME>/opentui-host.<profile>.json`\n *\n * {\n * version: 2, profile, home, pid, port,\n * phase: \"claim|booting|ready|stopping\",\n * startedAt, updatedAt, authority,\n * clients: [{ id, pid, lastSeen }]\n * }\n *\n * Invariants this module enforces:\n * - writes are ATOMIC (temp file in the same directory + rename); readers\n * never observe a half-written record;\n * - the O_EXCL claim uses `link(2)` on a fully-written temp file, so exactly\n * one of N concurrent claimers wins and a loser gets \"occupied\", never a\n * clobbered winner;\n * - reads are SCHEMA-VALIDATED: a v2 record is returned typed; an old record\n * (no `version` / no `clients`) is tagged `legacy`; garbage is `invalid`;\n * - stale detection and legacy cleanup NEVER signal a process\n * (`safeClearLegacy` only unlinks the registry FILE). Killing a host needs\n * the three-evidence rule in ADR-0009 decision 8 and belongs to a later\n * task — this module deliberately has no `process.kill` call.\n *\n * Reuse: the schema is a superset of the existing v1 lockfile handled by\n * `lifecycle.ts` (`{ pid, port, authority, startedAt, profile }`), which is\n * exactly the `legacy` shape detected here. The default liveness probe\n * delegates to `lifecycle.pidAlive`. No existing export or behavior in\n * lifecycle.ts is changed by this module.\n *\n * Filesystem and clock are injectable seams so concurrency / stale / legacy\n * cases are unit-testable without touching the real HOME or spawning a host.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n existsSync,\n linkSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { pidAlive as defaultPidAlive } from './lifecycle.ts'\n\n/** Current registry schema version. */\nexport const REGISTRY_SCHEMA_VERSION = 2\n\n/** Lifecycle phases a v2 registry may record. */\nexport const REGISTRY_PHASES = ['claim', 'booting', 'ready', 'stopping'] as const\nexport type RegistryPhase = (typeof REGISTRY_PHASES)[number]\n\n/** One attached client recorded in the registry. */\nexport interface RegistryClient {\n id: string\n pid: number\n /** ISO timestamp of the last heartbeat. */\n lastSeen: string\n}\n\n/** A validated schema-v2 host registry record. */\nexport interface HostRegistryV2 {\n version: 2\n profile: string\n home: string\n pid: number\n port: number\n phase: RegistryPhase\n startedAt: string\n updatedAt: string\n authority: string\n clients: RegistryClient[]\n}\n\n/** The shape of a pre-v2 (legacy) lockfile — kept for callers that migrate. */\nexport interface LegacyRegistry {\n pid: number\n port: number\n authority?: string\n startedAt?: string\n profile?: string\n booting?: boolean\n}\n\n/** Tagged result of reading + validating a registry file. */\nexport type RegistryReadResult =\n | { kind: 'v2'; value: HostRegistryV2 }\n | { kind: 'legacy'; raw: LegacyRegistry }\n | { kind: 'invalid'; raw: unknown; reason: string }\n | { kind: 'missing' }\n\n// ---------------------------------------------------------------------------\n// Injectable seams.\n// ---------------------------------------------------------------------------\n\n/** The slice of `node:fs` this module needs (injectable in tests). */\nexport interface RegistryFs {\n existsSync(path: string): boolean\n mkdirSync(path: string, options?: { recursive?: boolean }): void\n readFileSync(path: string, encoding: 'utf8'): string\n writeFileSync(path: string, data: string, options?: { mode?: number }): void\n renameSync(from: string, to: string): void\n linkSync(from: string, to: string): void\n unlinkSync(path: string): void\n}\n\n/** Default filesystem: the real `node:fs`. */\nexport const nodeRegistryFs: RegistryFs = {\n existsSync: (path) => existsSync(path),\n mkdirSync: (path, options) => {\n mkdirSync(path, options)\n },\n readFileSync: (path, encoding) => readFileSync(path, encoding),\n writeFileSync: (path, data, options) => {\n writeFileSync(path, data, options)\n },\n renameSync: (from, to) => renameSync(from, to),\n linkSync: (from, to) => linkSync(from, to),\n unlinkSync: (path) => unlinkSync(path),\n}\n\n// ---------------------------------------------------------------------------\n// Path + construction + validation.\n// ---------------------------------------------------------------------------\n\n/** Absolute registry path for a `(home, profile)` — the v1 lockfile path. */\nexport function registryPath(home: string, profile: string): string {\n return join(home, `opentui-host.${profile}.json`)\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value)\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n\nfunction nonEmpty(value: unknown): value is string {\n return isString(value) && value.trim() !== ''\n}\n\nfunction invalid(reason: string, raw: unknown): RegistryReadResult {\n return { kind: 'invalid', raw, reason }\n}\n\n/**\n * Validate a parsed JSON value into a tagged {@link RegistryReadResult}.\n * A record with `version === 2` is checked field-by-field; a record with no\n * version (or version 1) that still carries `pid`/`port` is `legacy`; anything\n * else is `invalid`. Pure — no filesystem access.\n */\nexport function validateRegistry(raw: unknown): RegistryReadResult {\n if (!isPlainObject(raw)) return invalid('registry is not an object', raw)\n\n if (raw.version === REGISTRY_SCHEMA_VERSION) {\n if (!nonEmpty(raw.profile)) return invalid('profile must be a non-empty string', raw)\n if (!nonEmpty(raw.home)) return invalid('home must be a non-empty string', raw)\n if (!isInteger(raw.pid) || raw.pid < 0) return invalid('pid must be a non-negative integer', raw)\n if (!isInteger(raw.port) || raw.port < 0 || raw.port > 65535) return invalid('port must be an integer in [0, 65535]', raw)\n if (!(REGISTRY_PHASES as readonly string[]).includes(raw.phase as string)) {\n return invalid(`phase must be one of ${REGISTRY_PHASES.join('|')}`, raw)\n }\n if (!nonEmpty(raw.startedAt)) return invalid('startedAt must be a non-empty string', raw)\n if (!nonEmpty(raw.updatedAt)) return invalid('updatedAt must be a non-empty string', raw)\n if (!isString(raw.authority)) return invalid('authority must be a string', raw)\n if (!Array.isArray(raw.clients)) return invalid('clients must be an array', raw)\n const clients: RegistryClient[] = []\n for (const [index, item] of raw.clients.entries()) {\n if (!isPlainObject(item)) return invalid(`clients[${index}] must be an object`, raw)\n if (!nonEmpty(item.id)) return invalid(`clients[${index}].id must be a non-empty string`, raw)\n if (!isInteger(item.pid) || item.pid < 0) return invalid(`clients[${index}].pid must be a non-negative integer`, raw)\n if (!nonEmpty(item.lastSeen)) return invalid(`clients[${index}].lastSeen must be a non-empty string`, raw)\n clients.push({ id: item.id, pid: item.pid, lastSeen: item.lastSeen })\n }\n return {\n kind: 'v2',\n value: {\n version: 2,\n profile: raw.profile,\n home: raw.home,\n pid: raw.pid,\n port: raw.port,\n phase: raw.phase as RegistryPhase,\n startedAt: raw.startedAt,\n updatedAt: raw.updatedAt,\n authority: raw.authority,\n clients,\n },\n }\n }\n\n // Any other explicit version is unsupported (not \"legacy\" — legacy is the\n // pre-version lockfile only).\n if (raw.version !== undefined) return invalid(`unsupported registry version ${String(raw.version)}`, raw)\n if (!isInteger(raw.pid) || !isInteger(raw.port)) {\n return invalid('legacy registry is missing pid/port', raw)\n }\n return {\n kind: 'legacy',\n raw: {\n pid: raw.pid,\n port: raw.port,\n ...(isString(raw.authority) ? { authority: raw.authority } : {}),\n ...(isString(raw.startedAt) ? { startedAt: raw.startedAt } : {}),\n ...(isString(raw.profile) ? { profile: raw.profile } : {}),\n ...(raw.booting === true ? { booting: true } : {}),\n },\n }\n}\n\n/** Build a well-formed v2 claim record (the O_EXCL placeholder content). */\nexport function createClaimRegistry(home: string, profile: string, pid: number, nowIso: string): HostRegistryV2 {\n return {\n version: 2,\n profile,\n home,\n pid,\n port: 0,\n phase: 'claim',\n startedAt: nowIso,\n updatedAt: nowIso,\n authority: '',\n clients: [],\n }\n}\n\n/** Copy a registry with a new `phase` / `updatedAt` (no in-place mutation). */\nexport function withPhase(reg: HostRegistryV2, phase: RegistryPhase, nowIso: string): HostRegistryV2 {\n return { ...reg, phase, updatedAt: nowIso }\n}\n\n/** Copy a registry with a new `updatedAt` (heartbeat / adoption bump). */\nexport function touchRegistry(reg: HostRegistryV2, nowIso: string): HostRegistryV2 {\n return { ...reg, updatedAt: nowIso }\n}\n\n// ---------------------------------------------------------------------------\n// Read / atomic write.\n// ---------------------------------------------------------------------------\n\n/** Read + validate the registry file. Never throws — IO/JSON errors are tagged. */\nexport function readRegistryAt(path: string, fs: RegistryFs = nodeRegistryFs): RegistryReadResult {\n let text: string\n try {\n text = fs.readFileSync(path, 'utf8')\n } catch {\n return { kind: 'missing' }\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return invalid('registry file is not valid JSON', text)\n }\n return validateRegistry(raw)\n}\n\n/** Read + validate `<home>/opentui-host.<profile>.json`. */\nexport function readRegistry(home: string, profile: string, fs: RegistryFs = nodeRegistryFs): RegistryReadResult {\n return readRegistryAt(registryPath(home, profile), fs)\n}\n\nlet writeSeq = 0\n\n/**\n * Atomically write a v2 registry: serialize to a temp file in the same\n * directory, then rename over the target. On a rename error the temp file is\n * swept so no orphan accumulates. The record is validated first — callers\n * cannot persist a malformed v2 shape.\n */\nexport function writeRegistry(home: string, profile: string, record: HostRegistryV2, fs: RegistryFs = nodeRegistryFs): void {\n const checked = validateRegistry(record)\n if (checked.kind !== 'v2') {\n throw new Error(`writeRegistry: refusing to write invalid v2 record (${checked.kind === 'invalid' ? checked.reason : checked.kind})`)\n }\n fs.mkdirSync(home, { recursive: true })\n const path = registryPath(home, profile)\n const tmp = `${path}.tmp-${process.pid}-${++writeSeq}`\n fs.writeFileSync(tmp, JSON.stringify(checked.value, null, 2) + '\\n')\n try {\n fs.renameSync(tmp, path)\n } catch (error) {\n try {\n fs.unlinkSync(tmp)\n } catch {\n /* nothing to sweep */\n }\n throw error\n }\n}\n\n// ---------------------------------------------------------------------------\n// Atomic claim / release (link(2) = O_EXCL).\n// ---------------------------------------------------------------------------\n\nexport interface ClaimOptions {\n fs?: RegistryFs\n now?: () => number\n /** Claimer pid (default `process.pid`). Stored in the claim record. */\n pid?: number\n}\n\nexport type ClaimResult =\n | { ok: true; token: string; path: string; registry: HostRegistryV2 }\n | { ok: false; reason: 'occupied'; path: string }\n\nfunction isErrno(error: unknown, code: string): boolean {\n return error instanceof Error && (error as NodeJS.ErrnoException).code === code\n}\n\n/**\n * Atomically claim the registry as a `phase=claim` placeholder.\n *\n * The fully-written temp file is `link(2)`ed to the target: `link` fails with\n * EEXIST when the target already exists, so exactly one concurrent claimer\n * wins. Unlike `writeFileSync('wx')`-style approaches the placeholder content\n * is complete at creation — readers never see a partial claim.\n *\n * Returns `{ ok: false, reason: 'occupied' }` for a rival (a live claim OR an\n * existing v2 record); the existing file is never modified.\n */\nexport function claimRegistry(home: string, profile: string, options: ClaimOptions = {}): ClaimResult {\n const fs = options.fs ?? nodeRegistryFs\n const now = options.now ?? Date.now\n const pid = options.pid ?? process.pid\n const nowIso = new Date(now()).toISOString()\n fs.mkdirSync(home, { recursive: true })\n const path = registryPath(home, profile)\n const registry = createClaimRegistry(home, profile, pid, nowIso)\n const tmp = `${path}.claim-${process.pid}-${randomUUID()}`\n fs.writeFileSync(tmp, JSON.stringify(registry, null, 2) + '\\n')\n try {\n fs.linkSync(tmp, path) // EEXIST when a rival holds the file\n return { ok: true, token: registry.startedAt, path, registry }\n } catch (error) {\n if (isErrno(error, 'EEXIST')) return { ok: false, reason: 'occupied', path }\n throw error\n } finally {\n try {\n fs.unlinkSync(tmp)\n } catch {\n /* nothing to sweep */\n }\n }\n}\n\nexport interface ReleaseClaimOptions {\n fs?: RegistryFs\n}\n\n/**\n * Remove a claim ONLY if the file still holds THIS claim (phase `claim`, same\n * claimer pid + startedAt token). Never removes a completed boot's real\n * record or a rival's newer claim. Returns whether anything was removed.\n */\nexport function releaseClaim(\n home: string,\n profile: string,\n claim: { pid: number; token: string },\n options: ReleaseClaimOptions = {},\n): boolean {\n const fs = options.fs ?? nodeRegistryFs\n const path = registryPath(home, profile)\n const read = readRegistryAt(path, fs)\n if (read.kind !== 'v2') return false\n const value = read.value\n if (value.phase !== 'claim' || value.pid !== claim.pid || value.startedAt !== claim.token) return false\n fs.unlinkSync(path)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Stale detection + safe legacy cleanup (NO process signalling).\n// ---------------------------------------------------------------------------\n\nexport interface StaleDeps {\n now?: () => number\n /** Pid liveness probe. Default: `lifecycle.pidAlive`. */\n pidAlive?: (pid: number) => boolean\n /** Optional max age of `updatedAt` before a live-pid record is stale. */\n registryMaxAgeMs?: number\n}\n\nexport type StaleReason = 'legacy-schema' | 'invalid-schema' | 'dead-pid' | 'registry-too-old'\n\nexport interface StaleVerdict {\n stale: boolean\n reasons: StaleReason[]\n}\n\nfunction looksLikeV2(value: RegistryReadResult | HostRegistryV2): value is HostRegistryV2 {\n // Narrow through an `unknown` candidate: applying isPlainObject() directly to\n // the tagged union keeps the {kind:'v2', value:...} branch in play, which has\n // no top-level `version` and fails the check. A raw HostRegistryV2 does.\n const candidate: unknown = value\n return isPlainObject(candidate) && candidate.version === REGISTRY_SCHEMA_VERSION\n}\n\n/**\n * Decide whether a registry is stale. Pure given the injected clock / pid\n * probe. Legacy and invalid records are stale by schema; a v2 record is stale\n * when its pid is dead. The optional `registryMaxAgeMs` applies ONLY to\n * `claim`/`booting` records — a `ready`/`stopping` host is steady-state and\n * nobody refreshes its `updatedAt` (heartbeats live in separate files), so an\n * age check there would falsely stale (>60s) healthy hosts (P1-1). A missing\n * registry is not stale — it is simply free to claim.\n */\nexport function isRegistryStale(input: RegistryReadResult | HostRegistryV2, deps: StaleDeps = {}): StaleVerdict {\n const read: RegistryReadResult = looksLikeV2(input) ? { kind: 'v2', value: input } : input\n if (read.kind === 'missing') return { stale: false, reasons: [] }\n if (read.kind === 'legacy') return { stale: true, reasons: ['legacy-schema'] }\n if (read.kind === 'invalid') return { stale: true, reasons: ['invalid-schema'] }\n\n const reasons: StaleReason[] = []\n const alive = deps.pidAlive ?? defaultPidAlive\n if (!alive(read.value.pid)) reasons.push('dead-pid')\n if (\n deps.registryMaxAgeMs !== undefined &&\n (read.value.phase === 'claim' || read.value.phase === 'booting')\n ) {\n const now = (deps.now ?? Date.now)()\n const updated = Date.parse(read.value.updatedAt)\n if (!Number.isNaN(updated) && now - updated > deps.registryMaxAgeMs) reasons.push('registry-too-old')\n }\n return { stale: reasons.length > 0, reasons }\n}\n\n/** Read a registry and classify staleness in one call (IO + injected seams). */\nexport function checkRegistryStale(\n home: string,\n profile: string,\n fs: RegistryFs = nodeRegistryFs,\n deps: StaleDeps = {},\n): { read: RegistryReadResult; verdict: StaleVerdict } {\n const read = readRegistry(home, profile, fs)\n return { read, verdict: isRegistryStale(read, deps) }\n}\n\nexport interface ClearLegacyResult {\n removed: boolean\n reason: 'legacy-removed' | 'not-legacy' | 'missing' | 'legacy-host-alive'\n}\n\nexport interface SafeClearOptions {\n fs?: RegistryFs\n /** Pre-read registry (e.g. from `checkRegistryStale`) to avoid a second read. */\n read?: RegistryReadResult\n /** Pid liveness probe. Default: `lifecycle.pidAlive` (EPERM counts as alive). */\n pidAlive?: (pid: number) => boolean\n}\n\n/**\n * Remove a legacy registry FILE on first run of the new version — ONLY when\n * its pid is confirmed dead. P1-4: a legacy record can be the sole record of\n * a still-running old host; unlinking it would orphan that host and make\n * `--force` unable to locate it. When the pid is alive (or its liveness is\n * uncertain — EPERM counts as alive), the record is KEPT for `--force` /\n * manual intervention. DESIGN §7: \"if it cannot be confirmed, leave it for\n * stale cleanup\".\n *\n * Accepts either a `(home, profile)` pair (reads the file itself) or a\n * pre-read registry via `options.read`. CONTRACT: this function only ever\n * unlinks the registry file. It NEVER signals or kills the legacy pid —\n * identifying and stopping that host needs the three-evidence rule\n * (ADR-0009 decision 8). A v2 record (or a missing/unreadable file) is left\n * untouched.\n */\nexport function safeClearLegacy(home: string, profile: string, options: SafeClearOptions = {}): ClearLegacyResult {\n const fs = options.fs ?? nodeRegistryFs\n const path = registryPath(home, profile)\n const read = options.read ?? readRegistryAt(path, fs)\n if (read.kind === 'missing') return { removed: false, reason: 'missing' }\n if (read.kind !== 'legacy') return { removed: false, reason: 'not-legacy' }\n const alive = options.pidAlive ?? defaultPidAlive\n if (read.raw.pid > 0 && alive(read.raw.pid)) {\n return { removed: false, reason: 'legacy-host-alive' }\n }\n fs.unlinkSync(path) // file only — no process.kill anywhere in this module\n return { removed: true, reason: 'legacy-removed' }\n}\n",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.26.1",
3
+ "version": "0.26.3",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,213 @@
1
+ // Pure decision table for the `opentui-inproc` profile's companion step.
2
+ //
3
+ // No filesystem I/O, no process spawn and no ambient process.env reads in the
4
+ // policy functions: every input is passed in, so the catalog, the selection and
5
+ // the per-package install decision are unit-testable without a registry or a
6
+ // real dsh profile. Only `queryDistTagLatest` performs I/O, and it takes an
7
+ // injectable executor for the same reason.
8
+ //
9
+ // Why this table exists: the inproc profile is deliberately minimal
10
+ // (dsh-base + the in-process bridge + the bridge-owned approval gate). Adding
11
+ // every @aiwayds companion "just in case" would pull client UI bundles into a
12
+ // headless-ish profile and create new failure modes. Each candidate below is
13
+ // judged by whether the inproc assembly has a CONSUMER for it; the ones without
14
+ // one are listed explicitly with `defaultOn: false` and are opt-in only.
15
+ //
16
+ // Reference precedent: dsh-tui-pi 2.38.2's `bin/companion-policy.mjs` +
17
+ // `DSH_TUI_COMPANION_LATEST`. The switch name here follows the same style with
18
+ // the opentui prefix.
19
+
20
+ import { execFileSync } from 'node:child_process'
21
+
22
+ /** Master kill switch. Anything other than 0/false/off (including unset) = enabled. */
23
+ export const COMPANION_LATEST_ENV = 'DSH_OPENTUI_COMPANION_LATEST'
24
+ /** Opt-in list of additional companions (comma-separated short names or full package names). */
25
+ export const COMPANIONS_ENV = 'DSH_OPENTUI_COMPANIONS'
26
+
27
+ /**
28
+ * The companion catalog.
29
+ *
30
+ * `short` is the token accepted by DSH_OPENTUI_COMPANIONS. `declaredRange` is
31
+ * the caret range used ONLY as a breaking-version guard against a moved
32
+ * `latest` dist-tag (major, plus minor while still 0.x) — it is never
33
+ * installed. `defaultOn` marks the minimal set.
34
+ */
35
+ export const COMPANIONS = Object.freeze([
36
+ Object.freeze({
37
+ name: '@aiwayds/dsh-subagent-registry',
38
+ short: 'registry',
39
+ declaredRange: '^0.21.0',
40
+ defaultOn: true,
41
+ reason: 'registers the `use_agent` (by-name custom-agent dispatch) and `ask_agent` follow-up tools; the inproc delegation roster and the APPEND_SYSTEM.md "subagent" vocabulary need a named dispatch entry. Its own cordis.patch.yml mounts it when its bundle is selected.',
42
+ }),
43
+ Object.freeze({
44
+ name: '@aiwayds/dsh-ask-router',
45
+ short: 'ask-router',
46
+ declaredRange: '^0.7.0',
47
+ defaultOn: false,
48
+ reason: 'inproc owns the ask surface bridge-side (ask.request frames from packages/bridge/src/ask-registry.ts); no inproc row consumes @aiwayds/dsh-ask-router.',
49
+ }),
50
+ Object.freeze({
51
+ name: '@aiwayds/dsh-approval-policy',
52
+ short: 'approval-policy',
53
+ declaredRange: '^0.3.0',
54
+ defaultOn: false,
55
+ reason: 'inproc uses its own bridge /approval-gate row plus @deepseek-ai/dsh-permission-presets; no consumer of the @aiwayds policy plugin.',
56
+ }),
57
+ Object.freeze({
58
+ name: '@aiwayds/dsh-llm-net-retry',
59
+ short: 'llm-net-retry',
60
+ declaredRange: '^0.8.0',
61
+ defaultOn: false,
62
+ reason: 'dsh-base already mounts @deepseek-ai/dsh-llm-retry in the inproc assembly; a second retry layer has no consumer.',
63
+ }),
64
+ Object.freeze({
65
+ name: '@aiwayds/dsh-model-sync',
66
+ short: 'model-sync',
67
+ declaredRange: '^0.9.0',
68
+ defaultOn: false,
69
+ reason: 'the inproc patch pins its own provider model list; nothing in the profile asks this plugin to sync it.',
70
+ }),
71
+ Object.freeze({
72
+ name: '@aiwayds/dsh-llm-stats',
73
+ short: 'llm-stats',
74
+ declaredRange: '^0.9.0',
75
+ defaultOn: false,
76
+ reason: 'token/cost accounting behind /usage; no /usage consumer exists in the inproc client path.',
77
+ }),
78
+ Object.freeze({
79
+ name: '@aiwayds/dsh-mcp-adapter',
80
+ short: 'mcp-adapter',
81
+ declaredRange: '^0.8.0',
82
+ defaultOn: false,
83
+ reason: 'the inproc patch carries a mcp-context7 client row, but no inproc row consumes the adapter\'s mcp_list/mcp_call meta-tools; opt-in only.',
84
+ }),
85
+ Object.freeze({
86
+ name: '@aiwayds/dsh-web-search-anysearch',
87
+ short: 'web-search',
88
+ declaredRange: '^0.9.0',
89
+ defaultOn: false,
90
+ reason: 'tool-web is enabled in the inproc patch but no search provider is pinned; independent of delegation, opt-in only.',
91
+ }),
92
+ Object.freeze({
93
+ name: '@aiwayds/dsh-vault',
94
+ short: 'vault',
95
+ declaredRange: '^0.8.2',
96
+ defaultOn: false,
97
+ reason: 'secret storage; no consumer in the minimal inproc set.',
98
+ }),
99
+ ])
100
+
101
+ /** True unless the master switch is explicitly disabled. */
102
+ export function companionLatestEnabled(env = process.env) {
103
+ const raw = env[COMPANION_LATEST_ENV]
104
+ if (raw === undefined) return true
105
+ return !['0', 'false', 'off'].includes(String(raw).trim().toLowerCase())
106
+ }
107
+
108
+ /**
109
+ * The companions this launch should satisfy.
110
+ * - master switch off => no companions at all (non-destructive: already
111
+ * installed packages are left in place, they are just not queried/installed)
112
+ * - DSH_OPENTUI_COMPANIONS unset => the `defaultOn` set (registry only)
113
+ * - explicit list => defaultOn set is replaced by the named entries;
114
+ * `none` means empty, `all` means the whole catalog.
115
+ */
116
+ export function selectCompanions(env = process.env) {
117
+ if (!companionLatestEnabled(env)) return []
118
+ const raw = env[COMPANIONS_ENV]
119
+ if (raw === undefined || String(raw).trim() === '') return COMPANIONS.filter((entry) => entry.defaultOn)
120
+ const tokens = String(raw).split(',').map((token) => token.trim()).filter(Boolean)
121
+ if (tokens.includes('none')) return []
122
+ if (tokens.includes('all')) return [...COMPANIONS]
123
+ return COMPANIONS.filter((entry) => tokens.includes(entry.short) || tokens.includes(entry.name))
124
+ }
125
+
126
+ /** npm dist-tags are usually bare, occasionally v-prefixed. */
127
+ export function normalizeVersion(version) {
128
+ return String(version).trim().replace(/^v/, '')
129
+ }
130
+
131
+ function parseCore(version) {
132
+ if (typeof version !== 'string') return null
133
+ const match = /^[v^~><=\s]*(\d+)\.(\d+)\.(\d+)/.exec(version.trim())
134
+ if (!match) return null
135
+ return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) }
136
+ }
137
+
138
+ function compareCore(a, b) {
139
+ const pa = parseCore(a)
140
+ const pb = parseCore(b)
141
+ if (!pa || !pb) return null
142
+ for (const key of ['major', 'minor', 'patch']) {
143
+ if (pa[key] !== pb[key]) return pa[key] - pb[key]
144
+ }
145
+ return 0
146
+ }
147
+
148
+ /** Outcome: { action: 'install'|'skip', spec, reason }. */
149
+ const skip = (reason) => ({ action: 'skip', spec: null, reason })
150
+ const install = (spec, reason) => ({ action: 'install', spec, reason })
151
+
152
+ /**
153
+ * Decide one companion's install action.
154
+ *
155
+ * - unresolved dist-tag + already installed => skip (offline: keep the pin)
156
+ * - unresolved dist-tag + nothing installed => install `@latest` (pnpm resolves)
157
+ * - breaking latest vs declaredRange => skip (major change, or minor change
158
+ * while 0.x — under 0.x the minor IS the breaking boundary)
159
+ * - installed version === latest => skip (idempotent, no add on every launch)
160
+ * - installed version > latest => skip (never downgrade)
161
+ * - otherwise => install the exact `pkg@<resolved>` spec
162
+ */
163
+ export function decideCompanionInstall({
164
+ packageName,
165
+ declaredRange,
166
+ resolved = null,
167
+ currentPin = null,
168
+ } = {}) {
169
+ const normalized = resolved === null ? null : normalizeVersion(resolved)
170
+ const resolvedCore = parseCore(normalized)
171
+ const declaredCore = parseCore(declaredRange)
172
+ if (!resolvedCore || !declaredCore) {
173
+ return currentPin
174
+ ? skip('unresolved')
175
+ : install(`${packageName}@latest`, 'unresolved')
176
+ }
177
+ if (resolvedCore.major !== declaredCore.major) {
178
+ return skip(`cross_major (${normalized} outside ${declaredRange})`)
179
+ }
180
+ // `^0.21.0` excludes 0.22.0: while major is 0 the minor is the breaking
181
+ // boundary, so a major-only guard would let breaking bumps into the profile.
182
+ if (resolvedCore.major === 0 && resolvedCore.minor !== declaredCore.minor) {
183
+ return skip(`cross_minor (${normalized} outside ${declaredRange})`)
184
+ }
185
+ if (currentPin) {
186
+ const cmp = compareCore(normalized, currentPin)
187
+ if (cmp === null) return skip('unresolved-pin')
188
+ if (cmp === 0) return skip('idempotent')
189
+ if (cmp < 0) return skip(`downgrade (${currentPin} > ${normalized})`)
190
+ }
191
+ return install(`${packageName}@${normalized}`, 'latest')
192
+ }
193
+
194
+ /**
195
+ * Query the `latest` dist-tag. Injectable `exec` keeps this pure in tests.
196
+ * Returns null on any failure (offline / no npm / malformed JSON) — the caller
197
+ * then uses the `@latest` fallback decision above.
198
+ */
199
+ export function queryDistTagLatest(name, { cwd, env, exec } = {}) {
200
+ const run = exec ?? execFileSync
201
+ try {
202
+ const out = run('npm', ['view', name, 'dist-tags', '--json'], {
203
+ cwd,
204
+ env,
205
+ encoding: 'utf8',
206
+ timeout: 30_000,
207
+ })
208
+ const tags = JSON.parse(typeof out === 'string' ? out : String(out?.stdout ?? ''))
209
+ return typeof tags?.latest === 'string' ? normalizeVersion(tags.latest) : null
210
+ } catch {
211
+ return null
212
+ }
213
+ }