github-router 0.3.377 → 0.3.379

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.
Files changed (61) hide show
  1. package/dist/ado-tools-CRkyU51J.js +1 -0
  2. package/dist/{attribution-settings-CD0_yLqf.js → attribution-settings-BWYL2b8N.js} +7 -7
  3. package/dist/{attribution-settings-CD0_yLqf.js.map → attribution-settings-BWYL2b8N.js.map} +1 -1
  4. package/dist/browser-ext/manifest.json +1 -1
  5. package/dist/{claude-Drda1tQL.js → claude-CSuIdaLV.js} +14 -14
  6. package/dist/{claude-Drda1tQL.js.map → claude-CSuIdaLV.js.map} +1 -1
  7. package/dist/{claude-md-injection-C0EQfdJo.js → claude-md-injection-Biq_Xhve.js} +4 -4
  8. package/dist/{claude-md-injection-C0EQfdJo.js.map → claude-md-injection-Biq_Xhve.js.map} +1 -1
  9. package/dist/{codex-BloFb0Da.js → codex-BG0pfud9.js} +5 -5
  10. package/dist/{codex-BloFb0Da.js.map → codex-BG0pfud9.js.map} +1 -1
  11. package/dist/{copilot-discount-CHNQLYDJ.js → copilot-discount-UXC6NQbN.js} +2 -1
  12. package/dist/copilot-discount-UXC6NQbN.js.map +1 -0
  13. package/dist/engine-V46un8Xl.js +1 -0
  14. package/dist/{gate-discovery-ByWG9xdK.js → gate-discovery-DjH9YXoN.js} +2 -2
  15. package/dist/{gate-discovery-ByWG9xdK.js.map → gate-discovery-DjH9YXoN.js.map} +1 -1
  16. package/dist/hooks.mjs +4 -2
  17. package/dist/hooks.sha256 +1 -1
  18. package/dist/{internal-aic-status-FQB1DQzX.js → internal-aic-status-B_hEeM37.js} +2 -2
  19. package/dist/{internal-aic-status-FQB1DQzX.js.map → internal-aic-status-B_hEeM37.js.map} +1 -1
  20. package/dist/{internal-max-dispatch-guard-D3L00YXj.js → internal-max-dispatch-guard-0teaxIc1.js} +2 -2
  21. package/dist/{internal-max-dispatch-guard-D3L00YXj.js.map → internal-max-dispatch-guard-0teaxIc1.js.map} +1 -1
  22. package/dist/{internal-max-dispatch-guard-fhBX_w49.js → internal-max-dispatch-guard-5LSaHN_y.js} +1 -1
  23. package/dist/{internal-prompt-submit-BbnaMF2R.js → internal-prompt-submit-BixNLmM3.js} +2 -2
  24. package/dist/{internal-prompt-submit-BbnaMF2R.js.map → internal-prompt-submit-BixNLmM3.js.map} +1 -1
  25. package/dist/{internal-prompt-submit-DKzCckz-.js → internal-prompt-submit-Ou8xtRXj.js} +2 -2
  26. package/dist/{internal-rebrief-aEvxp7jw.js → internal-rebrief-BBGM0PMv.js} +3 -3
  27. package/dist/{internal-rebrief-aEvxp7jw.js.map → internal-rebrief-BBGM0PMv.js.map} +1 -1
  28. package/dist/{internal-stop-hook-BC5__bNI.js → internal-stop-hook-DO9Iiaes.js} +2 -2
  29. package/dist/{internal-stop-hook-BC5__bNI.js.map → internal-stop-hook-DO9Iiaes.js.map} +1 -1
  30. package/dist/main.js +10 -10
  31. package/dist/{max-profile-contract-DLLTsSs2.js → max-profile-contract-DbHwiLTx.js} +2 -2
  32. package/dist/max-profile-contract-DbHwiLTx.js.map +1 -0
  33. package/dist/{peer-mcp-personas-B1prNNMJ.js → peer-mcp-personas-OWsSm6To.js} +20 -11
  34. package/dist/peer-mcp-personas-OWsSm6To.js.map +1 -0
  35. package/dist/{pi-CzDdGipf.js → pi-DmeBxzIo.js} +396 -71
  36. package/dist/pi-DmeBxzIo.js.map +1 -0
  37. package/dist/pi-foreign-artifacts-DZ4tioyO.js +660 -0
  38. package/dist/pi-foreign-artifacts-DZ4tioyO.js.map +1 -0
  39. package/dist/pi-memory-bridge-Bp9AnYw9.js +1 -0
  40. package/dist/{pi-memory-bridge-Dvj1T3e3.js → pi-memory-bridge-CICIdDVP.js} +15 -5
  41. package/dist/pi-memory-bridge-CICIdDVP.js.map +1 -0
  42. package/dist/{provision-DktDm-f0.js → provision-DPL8aGe2.js} +2 -2
  43. package/dist/{provision-DktDm-f0.js.map → provision-DPL8aGe2.js.map} +1 -1
  44. package/dist/{serve-CU3bV4e0.js → serve-zbQKfx1E.js} +7 -7
  45. package/dist/{serve-CU3bV4e0.js.map → serve-zbQKfx1E.js.map} +1 -1
  46. package/dist/{server-setup-DjHNoWhQ.js → server-setup-ClZdV33Q.js} +12 -12
  47. package/dist/{server-setup-DjHNoWhQ.js.map → server-setup-ClZdV33Q.js.map} +1 -1
  48. package/dist/{start-RJ2tOdL-.js → start-mnedD5cH.js} +3 -3
  49. package/dist/{start-RJ2tOdL-.js.map → start-mnedD5cH.js.map} +1 -1
  50. package/dist/{static-context-pack-DwC69_VA.js → static-context-pack-CtnBwHSd.js} +12 -11
  51. package/dist/static-context-pack-CtnBwHSd.js.map +1 -0
  52. package/dist/{workiq-tools-CQeCqmyX.js → workiq-tools-DL6rC4bP.js} +1 -1
  53. package/package.json +1 -1
  54. package/dist/ado-tools-aRld02_r.js +0 -1
  55. package/dist/copilot-discount-CHNQLYDJ.js.map +0 -1
  56. package/dist/engine-CtUZAPuu.js +0 -1
  57. package/dist/max-profile-contract-DLLTsSs2.js.map +0 -1
  58. package/dist/peer-mcp-personas-B1prNNMJ.js.map +0 -1
  59. package/dist/pi-CzDdGipf.js.map +0 -1
  60. package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
  61. package/dist/static-context-pack-DwC69_VA.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-foreign-artifacts-DZ4tioyO.js","names":[],"sources":["../src/lib/pi-foreign-artifacts.ts"],"sourcesContent":["/**\n * Bridge the INHERITED artifact directories — Claude Code's `.claude/` /\n * `~/.claude/` and Copilot's `.github/` / `~/.copilot/` — into a\n * `github-router pi` launch.\n *\n * Three namespaces, three different failure modes, one rule set:\n *\n * | namespace | same-name outcome in Pi | reported? |\n * |-----------------|-----------------------------------------------|-----------|\n * | agent registry | `mergeRuntimeAgents` throws, EVERY `subagent` | yes |\n * | | call in the process fails until it is removed | |\n * | `skills/*` | the other `SKILL.md` is overwritten in place | **no** |\n * | `prompts/*.md` | the other file is overwritten in place | **no** |\n *\n * So the planner reserves names BEFORE anything is written, and the rule\n * differs by namespace on purpose:\n *\n * - **agents**: a name the router itself already ships (its roster, the\n * pi-subagents builtins, the read-only CLI adapters) means the role\n * already exists — the foreign definition is **skipped and reported**.\n * Two agents with one purpose in one catalog is the ambiguity that\n * produces wrong delegations, and a registry identity is not the only\n * carrier of the content (the skill and prompt are).\n * - **skills and prompts**: the file IS the only carrier, so they are\n * **renamed, never skipped** — `gh-oracle` → `gh-oracle-2`,\n * `review.md` → `review-2.md`.\n *\n * Renaming happens for anything else that is taken, deterministically:\n * agents become `<slug>-<scope>` (then `-2`, `-3`…), skills and prompts\n * become `<slug>-2` (then `-3`…). No source prefix — a prefix is not a\n * namespace (it walks straight into the builtin `claude-code` /\n * `claude-code-writer`) and it renames artifacts the user recognises for no\n * safety gain, since the reservation is what makes collisions unreachable.\n *\n * Foreign `model:` and `aliases:` are never emitted. The model would be a\n * Copilot slug that `isUnavailableSubagentModel` refuses (so every run of\n * that agent fails), and an alias is another registry identity that can\n * collide invisibly. Every bridged agent therefore runs on the launch's\n * lead model. `tools:` is dropped from the frontmatter and folded into the\n * body as prose, because an unresolvable entry in pi-subagents' strict\n * allowlist hard-fails the child.\n *\n * Nothing here imports pi-subagents or Pi: the router owns one rule and\n * reads the same frontmatter the loaders read, so a version bump upstream\n * cannot silently move a name out from under it.\n */\n\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport { capBytes, redactSecrets, splitFrontmatter } from \"./pi-memory-bridge\"\n\n/**\n * Every name pi-subagents reserves for itself — `BUILTIN_AGENT_NAMES` from\n * the installed package plus the live alias map, the read-only CLI adapters,\n * and the router's own roster.\n *\n * Cannot be imported: pi-subagents is an installed Pi extension, never a\n * router dependency (bundling its internals would couple the launcher to a\n * version it does not pin). LAST_VERIFIED against pi-subagents 0.88.0:\n * `src/agents/builtin-names.js` for the 13 names, and a live `snapshot.all`\n * for the aliases (`oracle → advisor`,\n * `worker → developer, coder, implementer, develop`; every other builtin\n * carries none).\n *\n * Drift here is not a correctness hole: the extension's `tool_result` net\n * unregisters anything the registry rejects at merge time. It is a\n * friendliness hole (a foreign agent skipped needlessly), which is why this\n * list is commented rather than guessed.\n */\nexport const PI_FOREIGN_ROUTER_OWNED_AGENTS: ReadonlyArray<string> = Object.freeze([\n // pi-subagents builtins (BUILTIN_AGENT_NAMES, 0.88.0).\n \"advisor\",\n \"claude-code\",\n \"claude-code-writer\",\n \"codex-exec\",\n \"codex-exec-writer\",\n \"cursor-agent\",\n \"cursor-agent-writer\",\n \"delegate\",\n \"evidence-auditor\",\n \"oracle\",\n \"researcher\",\n \"reviewer\",\n \"scout\",\n \"worker\",\n // Live aliases of those builtins (`oracle`, `worker` above).\n \"developer\",\n \"coder\",\n \"implementer\",\n \"develop\",\n])\n\n/**\n * The router's own agent roster is NOT in the constant above: it depends on\n * the launch (`buildPiAgentFiles` writes Explore / General-Purpose / reviewer /\n * oracle / advisor, and `--no-peers` writes none), so `buildReservedNames`\n * takes it as `emittedAgents` instead. A hardcoded copy here would skip a\n * foreign `Explore` on a peerless launch that publishes no such role.\n */\n\n/** Foreign artifact roots. Project + user, Claude + Copilot. */\nconst SKILL_ROOTS_PROJECT = [\".claude/skills\", \".github/skills\"] as const\nconst SKILL_ROOTS_USER = [\".claude/skills\", \".copilot/skills\"] as const\nconst AGENT_ROOTS_PROJECT = [\".claude/agents\", \".github/agents\"] as const\nconst AGENT_ROOTS_USER = [\".claude/agents\", \".copilot/agents\"] as const\nconst PROMPT_ROOTS_PROJECT = [\".claude/commands\", \".github/prompts\"] as const\nconst PROMPT_ROOTS_USER = [\".claude/commands\"] as const\n\n/** Pi's own artifact roots in the mirror / repo / home, for reservation. */\nconst PI_SKILL_ROOTS_REL = [\"skills\", \".pi/skills\", \".agents/skills\"] as const\nconst PI_PROMPT_ROOTS_REL = [\"prompts\", \".pi/prompts\"] as const\nconst PI_AGENT_ROOTS_REL = [\"agents\", \".pi/agents\", \".agents\"] as const\n\n/** Caps. Pi refuses a skill without a description (`core/skills.js:252`). */\nconst MAX_FOREIGN_AGENT_BODY_BYTES = 8 * 1024\nconst MAX_FOREIGN_DESCRIPTION_CHARS = 200\nconst MAX_FOREIGN_SKILL_DESCRIPTION_CHARS = 1_000\nconst MAX_FOREIGN_INDEX_BYTES = 4 * 1024\n/** Mirrors Pi's own limits so a bridged file can never be rejected. */\nconst MAX_SKILL_NAME_CHARS = 64\n\nexport interface PiForeignAgentSpec {\n /** Final, collision-free, slugged (the authored name unless it was taken). */\n name: string\n /** The name as authored in the source file, before any suffix. */\n originalName: string\n /** One line, whitespace-collapsed, ≤ 200 chars. */\n description: string\n /** Frontmatter stripped, provenance line, tool policy as prose, ≤ 8 KiB. */\n body: string\n source: \"claude\" | \"copilot\"\n scope: \"project\" | \"user\"\n /** Repo- or home-relative provenance, shown in the index. */\n file: string\n /** Set when the name had to change (`gh-oracle` → `gh-oracle-2`). */\n renamedFrom?: string\n}\n\nexport interface PiForeignArtifactDoc {\n /** Final name: skill directory, or prompt file stem. */\n name: string\n content: string\n renamedFrom?: string\n}\n\nexport interface PiForeignPlan {\n /** Written to `<mirror>/skills/<name>/SKILL.md`. */\n skills: Array<PiForeignArtifactDoc>\n /** Written to `<mirror>/prompts/<name>.md`. */\n prompts: Array<PiForeignArtifactDoc>\n /**\n * Registered through the pi-subagents runtime-agent event. NO files are\n * written for these: one registry entry, announced in the prompt index,\n * loaded on demand via `subagent({action:\"list\"})`.\n */\n agents: Array<PiForeignAgentSpec>\n /** Everything dropped rather than bridged, with the reason. Never silent. */\n skipped: Array<{ name: string; file: string; reason: string }>\n}\n\nexport interface PiReservedNames {\n /** Builtins + aliases + adapters + this launch's roster. Never renamed to. */\n routerOwnedAgents: Set<string>\n /** Every agent identity key on disk (name, aliases, localName). */\n agents: Set<string>\n /** Skill names and directory slugs on disk, plus this launch's own. */\n skills: Set<string>\n /** Prompt stems on disk, plus this launch's own. */\n prompts: Set<string>\n}\n\nfunction lower(s: string): string {\n return s.trim().toLowerCase()\n}\n\n/** Collapse to a legal Pi/prompt path segment and registry name. */\nexport function piForeignSlug(raw: string): string {\n const slug = String(raw ?? \"\")\n .toLowerCase()\n // Any run of illegal characters is one separator, so `Copilot Deploy!`\n // and `--spaced Name--` both land on a legal, readable segment.\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n const trimmed = slug.length > MAX_SKILL_NAME_CHARS ? slug.slice(0, MAX_SKILL_NAME_CHARS).replace(/-+$/, \"\") : slug\n // An all-symbols name slugs to nothing; it still needs a usable identity.\n return trimmed.length > 0 ? trimmed : \"foreign\"\n}\n\nfunction collapseLine(raw: string): string {\n return raw.replace(/\\s+/g, \" \").trim()\n}\n\nfunction truncateChars(raw: string, max: number): string {\n if (raw.length <= max) return raw\n return `${raw.slice(0, Math.max(0, max - 1)).trimEnd()}…`\n}\n\n/** YAML-ish frontmatter read: `key: value` on one line, quotes stripped. */\nfunction frontmatterValue(frontmatter: string, key: string): string | undefined {\n const re = new RegExp(`^${key}\\\\s*:\\\\s*(.*)$`, \"im\")\n const match = re.exec(frontmatter)\n if (!match) return undefined\n const value = match[1].trim().replace(/^[\"']/, \"\").replace(/[\"']$/, \"\").trim()\n return value.length > 0 ? value : undefined\n}\n\n/** Space- and comma-separated list value (`tools: read, grep, bash`). */\nfunction frontmatterList(frontmatter: string, key: string): Array<string> {\n const raw = frontmatterValue(frontmatter, key)\n if (!raw) return []\n return raw\n .replace(/^\\[/, \"\")\n .replace(/\\]$/, \"\")\n .split(/[,\\s]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0)\n}\n\nasync function readIfExists(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\nasync function isDirectory(dir: string): Promise<boolean> {\n try {\n return (await fs.stat(dir)).isDirectory()\n } catch {\n return false\n }\n}\n\nasync function listDir(dir: string): Promise<Array<string>> {\n try {\n return (await fs.readdir(dir)).sort()\n } catch {\n return []\n }\n}\n\n/** Repo root: walk up for `.git`, else the given cwd. Never throws. */\nexport async function piForeignRepoRoot(cwd: string): Promise<string> {\n let dir = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(dir, \".git\"))\n return dir\n } catch {\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n return cwd\n}\n\n/**\n * Which product an artifact came from, from its path alone.\n *\n * Normalized to forward slashes first: the roots above are POSIX literals, so\n * a Windows path (`\\.github\\.`) would otherwise match nothing and every\n * artifact would be labelled Claude. The label reaches the index and the\n * provenance line, i.e. the model's view of where an agent came from.\n */\nexport function piForeignSourceOf(file: string): \"claude\" | \"copilot\" {\n const posix = file.replace(/\\\\/g, \"/\")\n return posix.includes(\"/.github/\") || posix.includes(\"/.copilot/\") ? \"copilot\" : \"claude\"\n}\n\nfunction provenancePath(file: string, repoRoot: string, homeDir: string): string {\n const rel = (base: string, prefix: string): string | undefined => {\n const out = path.relative(base, file)\n return out.length > 0 && !out.startsWith(\"..\") ? `${prefix}${out.split(path.sep).join(\"/\")}` : undefined\n }\n // `~` for home on purpose: the index and the provenance line are read by a\n // human in a transcript, and an absolute path would leak the account name\n // into every bridged artifact.\n return rel(repoRoot, \"\") ?? rel(homeDir, \"~/\") ?? path.basename(file)\n}\n\n/* ------------------------------------------------------------------ */\n/* Reservation */\n/* ------------------------------------------------------------------ */\n\n/** Every `<dir>/*.md` under an agent root (flat — that is all Pi scans). */\nasync function agentIdentityKeys(root: string): Promise<Array<string>> {\n const keys: Array<string> = []\n for (const name of await listDir(root)) {\n if (!name.endsWith(\".md\")) continue\n // `.agent.md` (Copilot) and `*.md` (Claude) both reduce to the stem.\n const stem = name.replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\")\n const raw = await readIfExists(path.join(root, name))\n if (raw === undefined) continue\n const { frontmatter } = splitFrontmatter(raw)\n const authored = frontmatterValue(frontmatter, \"name\") ?? stem\n keys.push(authored, stem)\n for (const key of [\"aliases\", \"alias\", \"localName\"]) {\n keys.push(...frontmatterList(frontmatter, key))\n }\n }\n return keys\n}\n\nasync function skillNamesUnder(root: string): Promise<Array<string>> {\n const names: Array<string> = []\n for (const entry of await listDir(root)) {\n if (entry.startsWith(\".\")) continue\n const dir = path.join(root, entry)\n if (await isDirectory(dir)) {\n // Directory-based skill: Pi names it from frontmatter, else the dir.\n names.push(entry)\n const raw = await readIfExists(path.join(dir, \"SKILL.md\"))\n if (raw !== undefined) {\n const named = frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n if (named) names.push(named)\n }\n continue\n }\n if (entry.endsWith(\".md\")) {\n // Single-file skill: the stem is the name.\n const stem = entry.replace(/\\.md$/, \"\")\n names.push(stem)\n const raw = await readIfExists(path.join(root, entry))\n if (raw !== undefined) {\n const named = frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n if (named) names.push(named)\n }\n }\n }\n return names\n}\n\nasync function promptNamesUnder(root: string): Promise<Array<string>> {\n const names: Array<string> = []\n for (const entry of await listDir(root)) {\n const full = path.join(root, entry)\n if (await isDirectory(full)) {\n names.push(...(await promptNamesUnder(full)))\n continue\n }\n if (entry.endsWith(\".md\")) names.push(entry.replace(/\\.md$/, \"\"))\n }\n return names\n}\n\n/**\n * Build the four reservation sets.\n *\n * `emittedSkills` / `emittedPrompts` are the names THIS launch is about to\n * write, so a foreign artifact can never land on top of one the router just\n * created in the same process (the `<mirror>/` scan would see a stale copy\n * from the previous launch, not this one).\n */\nexport async function buildReservedNames(opts: {\n mirrorDir: string\n repoRoot: string\n homeDir: string\n /**\n * The router roster THIS launch really publishes (agent-file stems from\n * `buildPiAgentFiles`, empty under `--no-peers`). Part of the router-owned\n * set, because the role exists and the roster must win the name. Kept\n * separate from the constant so a peerless launch does not skip a foreign\n * `Explore` for a roster it never wrote.\n */\n emittedAgents?: ReadonlyArray<string>\n emittedSkills?: ReadonlyArray<string>\n emittedPrompts?: ReadonlyArray<string>\n}): Promise<PiReservedNames> {\n const routerOwnedAgents = new Set<string>(\n PI_FOREIGN_ROUTER_OWNED_AGENTS.map(lower),\n )\n for (const name of opts.emittedAgents ?? []) routerOwnedAgents.add(lower(name))\n const agents = new Set<string>()\n const skills = new Set<string>()\n const prompts = new Set<string>()\n\n for (const root of [\n path.join(opts.mirrorDir, PI_AGENT_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_AGENT_ROOTS_REL[1]),\n path.join(opts.repoRoot, PI_AGENT_ROOTS_REL[2]),\n path.join(opts.homeDir, \".pi/agent/agents\"),\n path.join(opts.homeDir, \".agents\"),\n ]) {\n for (const key of await agentIdentityKeys(root)) agents.add(lower(key))\n }\n for (const key of routerOwnedAgents) agents.add(key)\n\n for (const root of [\n path.join(opts.mirrorDir, PI_SKILL_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_SKILL_ROOTS_REL[1]),\n path.join(opts.repoRoot, PI_SKILL_ROOTS_REL[2]),\n path.join(opts.homeDir, \".pi/agent/skills\"),\n path.join(opts.homeDir, \".agents/skills\"),\n ]) {\n for (const name of await skillNamesUnder(root)) skills.add(lower(name))\n }\n for (const name of opts.emittedSkills ?? []) skills.add(lower(name))\n\n for (const root of [\n path.join(opts.mirrorDir, PI_PROMPT_ROOTS_REL[0]),\n path.join(opts.repoRoot, PI_PROMPT_ROOTS_REL[1]),\n ]) {\n for (const name of await promptNamesUnder(root)) prompts.add(lower(name))\n }\n for (const name of opts.emittedPrompts ?? []) prompts.add(lower(name))\n\n return { routerOwnedAgents, agents, skills, prompts }\n}\n\n/* ------------------------------------------------------------------ */\n/* Planner */\n/* ------------------------------------------------------------------ */\n\n/** Deterministic suffix search shared by agents and skills/prompts. */\nfunction claim(\n taken: Set<string>,\n base: string,\n suffixes: () => Iterable<string>,\n): string {\n if (!taken.has(lower(base))) {\n taken.add(lower(base))\n return base\n }\n for (const candidate of suffixes()) {\n if (!taken.has(lower(candidate))) {\n taken.add(lower(candidate))\n return candidate\n }\n }\n // Unreachable: the generator is infinite. Keep TypeScript honest.\n return base\n}\n\nfunction* scopeSuffixes(base: string, scope: string): Generator<string> {\n yield `${base}-${scope}`\n for (let n = 2; n < 1_000; n++) yield `${base}-${scope}-${n}`\n}\n\nfunction* ordinals(base: string): Generator<string> {\n for (let n = 2; n < 1_000; n++) yield `${base}-${n}`\n}\n\nasync function collectAgentFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\" }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\" }> = []\n for (const { dir, scope } of roots) {\n for (const entry of await listDir(dir)) {\n if (!entry.endsWith(\".md\")) continue\n out.push({ file: path.join(dir, entry), scope })\n }\n }\n return byScopeThenPath(out)\n}\n\n/**\n * Scope is the FIRST sort key, not the root order.\n *\n * The two roots per scope (`.claude/…`, `.github/…`) are visited in a fixed\n * order, but `readdir` order is filesystem-dependent and the plan's suffixes\n * (`writer` vs `writer-user`) are assigned first-come. A project artifact must\n * win its authored name over a user artifact of the same name on every machine,\n * so the ordering is stated here rather than inherited from the walk.\n */\nfunction byScopeThenPath<T extends { file: string; scope: \"project\" | \"user\" }>(\n rows: Array<T>,\n): Array<T> {\n return rows.sort((a, b) => {\n if (a.scope !== b.scope) return a.scope === \"project\" ? -1 : 1\n return a.file < b.file ? -1 : a.file > b.file ? 1 : 0\n })\n}\n\nasync function collectSkillFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\"; name: string }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\"; name: string }> = []\n for (const { dir, scope } of roots) {\n for (const entry of await listDir(dir)) {\n if (entry.startsWith(\".\")) continue\n const full = path.join(dir, entry)\n if (await isDirectory(full)) {\n const skillFile = path.join(full, \"SKILL.md\")\n const raw = await readIfExists(skillFile)\n if (raw === undefined) continue\n out.push({\n file: skillFile,\n scope,\n name: frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\") ?? entry,\n })\n continue\n }\n if (entry.endsWith(\".md\")) {\n const raw = await readIfExists(full)\n if (raw === undefined) continue\n out.push({\n file: full,\n scope,\n name:\n frontmatterValue(splitFrontmatter(raw).frontmatter, \"name\")\n ?? entry.replace(/\\.md$/, \"\"),\n })\n }\n }\n }\n return byScopeThenPath(out)\n}\n\nasync function collectPromptFiles(\n roots: ReadonlyArray<{ dir: string; scope: \"project\" | \"user\" }>,\n): Promise<Array<{ file: string; scope: \"project\" | \"user\"; name: string }>> {\n const out: Array<{ file: string; scope: \"project\" | \"user\"; name: string }> = []\n const walk = async (dir: string, scope: \"project\" | \"user\", prefix: string): Promise<void> => {\n for (const entry of await listDir(dir)) {\n if (entry.startsWith(\".\")) continue\n const full = path.join(dir, entry)\n if (await isDirectory(full)) {\n await walk(full, scope, `${prefix}${entry}-`)\n continue\n }\n if (!entry.endsWith(\".md\")) continue\n // `.prompt.md` is Copilot's prompt-file suffix; `deploy.prompt.md` is\n // the command `deploy`, not `deploy-prompt`.\n const stem = entry.replace(/\\.prompt\\.md$/, \"\").replace(/\\.md$/, \"\")\n // Nested commands flatten BEFORE the reservation, because a flattened\n // name can collide with a flat one (`nested/deploy` vs `deploy`).\n out.push({ file: full, scope, name: `${prefix}${stem}` })\n }\n }\n for (const { dir, scope } of roots) await walk(dir, scope, \"\")\n return byScopeThenPath(out)\n}\n\n/**\n * Build the bridge plan. Pure over the filesystem: reads the foreign roots\n * and the reservation sets, writes nothing.\n */\nexport async function planForeignArtifacts(opts: {\n repoRoot: string\n homeDir: string\n mirrorDir: string\n reservedNames: PiReservedNames\n}): Promise<PiForeignPlan> {\n const { repoRoot, homeDir, reservedNames: reserved } = opts\n const plan: PiForeignPlan = { skills: [], prompts: [], agents: [], skipped: [] }\n\n // Reservation sets are copied for the skill/prompt namespaces: they are\n // mutated as this plan claims names, so two foreign files that ask for the\n // same thing disambiguate instead of fighting.\n const skillNames = new Set(reserved.skills)\n const promptNames = new Set(reserved.prompts)\n const agentNames = new Set(reserved.agents)\n\n /* ----- skills (always bridged) ----- */\n const skillFiles = await collectSkillFiles([\n ...SKILL_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...SKILL_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n for (const { file, name } of skillFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const { frontmatter, body } = splitFrontmatter(raw)\n const description = collapseLine(frontmatterValue(frontmatter, \"description\") ?? \"\")\n if (!description) {\n // Pi refuses a skill with no description (`core/skills.js:252-254`), so\n // this is a hard skip — reported, never a silent drop.\n plan.skipped.push({ name, file: shown, reason: \"skill has no description (Pi requires one)\" })\n continue\n }\n const authored = piForeignSlug(name)\n const finalName = claim(skillNames, authored, () => ordinals(authored))\n const allowed = frontmatterList(frontmatter, \"allowed-tools\")\n plan.skills.push({\n name: finalName,\n ...(finalName === authored ? {} : { renamedFrom: name }),\n content: `${buildSkillFrontmatter(description)}\\n${buildArtifactBody({\n body,\n source: piForeignSourceOf(file),\n shown,\n allowed,\n })}`,\n })\n }\n\n /* ----- prompts (under --foreign) ----- */\n const promptFiles = await collectPromptFiles([\n ...PROMPT_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...PROMPT_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n for (const { file, name } of promptFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const authored = piForeignSlug(name)\n const finalName = claim(promptNames, authored, () => ordinals(authored))\n // A prompt template is prose + `$1`/`$ARGUMENTS` placeholders. The body is\n // otherwise passed through untouched: rewriting placeholders would silently\n // change what the command means, and `$ARGUMENTS` is documented as not\n // bridged. Only a provenance line is prepended, so the command's origin is\n // visible where it runs.\n const { body } = splitFrontmatter(raw)\n plan.prompts.push({\n name: finalName,\n ...(finalName === authored ? {} : { renamedFrom: name }),\n content: `${buildArtifactBody({ body, source: piForeignSourceOf(file), shown, allowed: [] })}\\n`,\n })\n }\n\n /* ----- agents (specs only — no files) ----- */\n const agentFiles = await collectAgentFiles([\n ...AGENT_ROOTS_PROJECT.map((rel) => ({ dir: path.join(repoRoot, rel), scope: \"project\" as const })),\n ...AGENT_ROOTS_USER.map((rel) => ({ dir: path.join(homeDir, rel), scope: \"user\" as const })),\n ])\n // Content-dekeyed dedupe: first-mate dual-emits the same 8 roles into\n // `.github/agents` AND `.claude/agents` with byte-identical bodies, so the\n // second copy of a role must not become `planner-2`.\n const seenBodies = new Set<string>()\n for (const { file, scope } of agentFiles) {\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const shown = provenancePath(file, repoRoot, homeDir)\n const stem = path.basename(file).replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\")\n const { frontmatter, body } = splitFrontmatter(raw)\n const originalName = frontmatterValue(frontmatter, \"name\") ?? stem\n const description = collapseLine(frontmatterValue(frontmatter, \"description\") ?? \"\")\n // A flat `.md` without a description is not an agent definition (Copilot\n // requires one; Claude allows it but Pi's index line would be empty).\n if (!description) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"no description in frontmatter (not a usable agent definition)\",\n })\n continue\n }\n const authored = piForeignSlug(originalName)\n // Router-owned FIRST: the role already exists under that name, so a second\n // entry with one purpose would only make the catalog ambiguous. Ordered\n // before the dedupe so the dual-emitted `reviewer` from first-mate reports\n // the real reason twice (\"the role exists\") instead of once as a duplicate\n // of a copy that was itself never bridged — the second shape of skip would\n // be true but misleading, since nothing was bridged to duplicate.\n if (reserved.routerOwnedAgents.has(lower(originalName))) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"name is owned by gh-router or a pi-subagents builtin (that role already exists)\",\n })\n continue\n }\n const hash = `${authored}\\u0000${body}`\n if (seenBodies.has(hash)) {\n plan.skipped.push({\n name: originalName,\n file: shown,\n reason: \"duplicate of an identical definition already bridged from another emitted path\",\n })\n continue\n }\n seenBodies.add(hash)\n const finalName = claim(agentNames, authored, () => scopeSuffixes(authored, scope))\n const tools = frontmatterList(frontmatter, \"tools\")\n plan.agents.push({\n name: finalName,\n originalName,\n description: truncateChars(description, MAX_FOREIGN_DESCRIPTION_CHARS),\n // Trimmed because pi-subagents' `validateString` rejects a\n // `systemPrompt` that differs from its own `trim()` — and a markdown\n // body always ends with a newline, so an untrimmed body would fail\n // registration for EVERY bridged agent (`runtime-agent-registry.js:48`).\n body: capBytes(\n buildArtifactBody({ body, source: piForeignSourceOf(file), shown, allowed: tools }),\n MAX_FOREIGN_AGENT_BODY_BYTES,\n \"gh-router foreign-agent bridge\",\n ).text.trim(),\n source: piForeignSourceOf(file),\n scope,\n file: shown,\n ...(finalName === authored ? {} : { renamedFrom: originalName }),\n })\n }\n\n return plan\n}\n\n/**\n * Frontmatter for a bridged skill.\n *\n * The `name:` key is deliberately ABSENT: Pi resolves a skill's name from the\n * frontmatter when present and from the parent directory otherwise\n * (`core/skills.js:245`), so dropping it lets the directory we just wrote\n * decide. Keeping the authored `name: gh-oracle` inside `gh-oracle-2/SKILL.md`\n * makes BOTH copies load as `gh-oracle` and the foreign one loses as a\n * `collision` diagnostic — a silent loss.\n */\nfunction buildSkillFrontmatter(description: string): string {\n const safeDescription = truncateChars(description, MAX_FOREIGN_SKILL_DESCRIPTION_CHARS).replace(\n /\\r?\\n/g,\n \" \",\n )\n return `---\\ndescription: ${safeDescription}\\n---\\n`\n}\n\n/**\n * The shared body shape for bridged artifacts: a provenance line (so the\n * origin is visible where it runs, not only where it was written), the\n * original tool policy as prose (Pi cannot enforce a foreign allowlist, and an\n * unresolvable entry would hard-fail the child), then the authored body.\n *\n * The body is secret-redacted on the way through: a foreign agent or command is\n * user-authored prose that has never been through the router, and copying it\n * into a launch mirror verbatim would move any token pasted into it into a\n * second file tree.\n */\nfunction buildArtifactBody(opts: {\n body: string\n source: \"claude\" | \"copilot\"\n shown: string\n allowed: ReadonlyArray<string>\n}): string {\n const provenance = `> Bridged by github-router from ${opts.source === \"copilot\" ? \"Copilot\" : \"Claude\"} \\`${opts.shown}\\`.`\n const policy =\n opts.allowed.length > 0\n ? `> Authored tool policy (advisory in Pi): ${opts.allowed.join(\", \")}.`\n : undefined\n const trimmed = redactSecrets(opts.body).replace(/^\\n+/, \"\")\n return [provenance, ...(policy ? [policy] : []), \"\", trimmed].join(\"\\n\")\n}\n\n/**\n * The one index the model sees. Deliberately a compact list, not the bodies:\n * runtime agents are never advertised (`advertised-agent-prompt.js`), and\n * spending the 16-entry / 12 KiB catalog on foreign agents would crowd out\n * the router's own roster. The model calls\n * `subagent({action:\"list\", options:{search:\"…\"}})` for full descriptions.\n */\nexport function buildForeignAgentIndex(\n agents: ReadonlyArray<PiForeignAgentSpec>,\n opts: { maxBytes?: number } = {},\n): string {\n if (agents.length === 0) return \"\"\n const maxBytes = opts.maxBytes ?? MAX_FOREIGN_INDEX_BYTES\n const header = [\n \"Agents bridged from .claude / .github / ~/.copilot. They are NOT preloaded:\",\n 'call subagent({action:\"list\", options:{search:\"<term>\"}}) for full descriptions,',\n 'then subagent({agent:\"<name>\", task:\"…\"}). They run on this profile\\'s lead model.',\n ]\n const rows = agents.map(\n (a) => `- ${a.name} [${a.source}, ${a.scope}] — ${a.description}`,\n )\n // Ship whole rows: a half-written index line is worse than a count, because\n // the model would call an agent whose description it cannot read.\n const included: Array<string> = []\n let bytes = Buffer.byteLength([...header, ...included].join(\"\\n\"), \"utf8\")\n for (const row of rows) {\n const size = Buffer.byteLength(`${row}\\n`, \"utf8\")\n if (bytes + size > maxBytes) break\n included.push(row)\n bytes += size\n }\n const omitted = rows.length - included.length\n const tail = omitted > 0 ? [`+${omitted} more; {action:\"list\", options:{search:\"<term>\"}}`] : []\n return [...header, ...included, ...tail].join(\"\\n\")\n}\n\n/**\n * Write the plan's skills and prompts into the mirror.\n *\n * `overwritten` counts a target that already existed. It must be `0` on every\n * launch — the reservation is what guarantees it — and the launcher warns when\n * it is not, which is the tripwire for the silent-clobber failure this whole\n * module exists to prevent. Agents are NOT written: they are registry entries.\n */\nexport async function writeForeignArtifacts(\n mirrorDir: string,\n plan: PiForeignPlan,\n): Promise<{ skills: number; prompts: number; overwritten: number }> {\n let skills = 0\n let prompts = 0\n let overwritten = 0\n const write = async (file: string, content: string): Promise<void> => {\n const existing = await readIfExists(file)\n if (existing !== undefined) overwritten += 1\n await fs.mkdir(path.dirname(file), { recursive: true })\n await fs.writeFile(file, content, \"utf8\")\n }\n for (const skill of plan.skills) {\n await write(path.join(mirrorDir, \"skills\", skill.name, \"SKILL.md\"), skill.content)\n skills += 1\n }\n for (const prompt of plan.prompts) {\n await write(path.join(mirrorDir, \"prompts\", `${prompt.name}.md`), prompt.content)\n prompts += 1\n }\n return { skills, prompts, overwritten }\n}\n\n/**\n * Count the foreign AGENT definitions a `--foreign` launch would consider.\n *\n * Exists so a launch without the flag can still say the artifacts are there:\n * the bridge is invisible by design, and a user who has `.github/agents/` has\n * no other way to learn the flag exists. Deliberately a `readdir` count rather\n * than a plan — no reservations, no body reads, and it must stay cheap because\n * it runs on every non-`--foreign` launch.\n *\n * Counts **stems**, not files, because first-mate dual-emits every role into\n * `.github/agents` AND `.claude/agents` with byte-identical bodies: a file\n * count would report 16 where the user has 8 roles, which reads like the bridge\n * found something it did not.\n */\nexport async function countForeignAgentFiles(opts: {\n repoRoot: string\n homeDir: string\n}): Promise<number> {\n const stems = new Set<string>()\n for (const root of [\n ...AGENT_ROOTS_PROJECT.map((rel) => path.join(opts.repoRoot, rel)),\n ...AGENT_ROOTS_USER.map((rel) => path.join(opts.homeDir, rel)),\n ]) {\n for (const entry of await listDir(root)) {\n if (!entry.endsWith(\".md\")) continue\n stems.add(entry.replace(/\\.agent\\.md$/, \"\").replace(/\\.md$/, \"\"))\n }\n }\n return stems.size\n}\n\n/** Default home dir for the planner (separate seam so tests stay hermetic). */\nexport function piForeignHomeD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-- gh-router memory-bridge end -->";
29
29
  function byteLength(s) {
30
30
  return Buffer.byteLength(s, "utf8");
31
31
  }
32
- function capBytes(s, max) {
32
+ /**
33
+ * Truncate to a UTF-8 byte budget without splitting a code point, marker
34
+ * included in the budget.
35
+ *
36
+ * Exported because the foreign-artifact bridge caps with the same measure Pi's
37
+ * own limits are stated in, and `label` keeps the truncation marker honest
38
+ * about which bridge did the cutting.
39
+ */
40
+ function capBytes(s, max, label = "gh-router memory bridge") {
33
41
  if (byteLength(s) <= max) return {
34
42
  text: s,
35
43
  truncated: false
36
44
  };
45
+ const marker = `\n…[truncated by ${label}]`;
46
+ const budget = Math.max(0, max - byteLength(marker));
37
47
  let low = 0;
38
48
  let high = s.length;
39
49
  while (low < high) {
40
50
  const mid = Math.floor((low + high) / 2);
41
- if (byteLength(s.slice(0, mid)) <= max) low = mid + 1;
51
+ if (byteLength(s.slice(0, mid)) <= budget) low = mid + 1;
42
52
  else high = mid;
43
53
  }
44
54
  return {
45
- text: `${s.slice(0, Math.max(0, low - 1))}\n…[truncated by gh-router memory bridge]`,
55
+ text: `${s.slice(0, Math.max(0, low - 1))}${marker}`,
46
56
  truncated: true
47
57
  };
48
58
  }
@@ -398,6 +408,6 @@ function mergeBridgeIntoAgentsMd(existing, section) {
398
408
  }
399
409
  return `${body.endsWith("\n") ? body : `${body}\n`}\n${section}\n`;
400
410
  }
401
- export { buildMirrorBridgeSection, collectBridgeInputs, mergeBridgeIntoAgentsMd };
411
+ export { capBytes as a, extractScopeGlobs as c, splitFrontmatter as d, buildMirrorBridgeSection as i, mergeBridgeIntoAgentsMd as l, PI_BRIDGE_FENCE_END as n, collectBridgeInputs as o, PI_BRIDGE_STATIC_BUDGET_BYTES as r, extractAtImports as s, PI_BRIDGE_FENCE_BEGIN as t, redactSecrets as u };
402
412
 
403
- //# sourceMappingURL=pi-memory-bridge-Dvj1T3e3.js.map
413
+ //# sourceMappingURL=pi-memory-bridge-CICIdDVP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-memory-bridge-CICIdDVP.js","names":[],"sources":["../src/lib/pi-memory-bridge.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\n/**\n * Pi memory bridge: repo instruction + user-global + auto-memory surfacing.\n *\n * Pi natively loads per-dir first-win\n * `AGENTS.override.md > AGENTS.md > AGENTS.MD > CLAUDE.md > CLAUDE.MD`\n * (agentDir global + fs-root → cwd, concatenated, no trust gate).\n * It does NOT load `.github/copilot-instructions.md`,\n * `.github/instructions/*.instructions.md` (`applyTo`), `.claude/rules/`\n * (`paths:`), `@path` imports, `CLAUDE.local.md`, `./.claude/CLAUDE.md`,\n * `~/.claude/CLAUDE.md`, or Claude auto-memory.\n *\n * Strategy (per approved plan): synthesize the static repo-wide slice into\n * the per-launch mirror's `AGENTS.md` (a Pi-native candidate, so no new\n * loader is needed) and lazy-attach path-scoped rules via the\n * `gh-router-pi` extension's `tool_result` hook (mirrors\n * `pi-code/claude-rules.ts`). Auto-memory is on-demand only (`/memory`\n * command + explicit read), never auto-injected.\n *\n * All filesystem access is best-effort: missing/unreadable files are\n * skipped, never fatal. Pure helpers are exported for unit tests.\n */\n\nexport const PI_BRIDGE_STATIC_BUDGET_BYTES = 24_000 as const\nexport const PI_BRIDGE_IMPORT_MAX_DEPTH = 4 as const\nexport const PI_BRIDGE_IMPORT_MAX_FILES = 10 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_LINES = 200 as const\nexport const PI_BRIDGE_MEMORY_INDEX_MAX_BYTES = 25_000 as const\nexport const PI_BRIDGE_FENCE_BEGIN = \"<!-- gh-router memory-bridge begin -->\"\nexport const PI_BRIDGE_FENCE_END = \"<!-- gh-router memory-bridge end -->\"\n\nexport interface PiBridgeScopedRule {\n /** Display path (absolute or repo-relative) for attribution. */\n file: string\n /** Rule body with frontmatter stripped. */\n body: string\n /** Glob list from `paths:` / `applyTo:` / `globs:`. Empty = unscoped. */\n globs: Array<string>\n /** Where the rule came from (for `/context` surfacing). */\n source: string\n}\n\nexport interface PiBridgeCollected {\n /** Repo-wide copilot instructions that were found (after import expansion). */\n copilotInstructions: Array<{ file: string; content: string }>\n /** Unscoped Claude rules (inlined statically). */\n unscopedRules: Array<{ file: string; content: string }>\n /** Path-scoped rules (lazy-attached, not inlined). */\n scopedRules: Array<PiBridgeScopedRule>\n /** User-global files found (capped, inlined). */\n userGlobal: Array<{ file: string; content: string }>\n /** Resolved `@` imports (appended once, deduped). */\n imports: Array<{ file: string; content: string }>\n /** Skipped files with reasons (for `/context`). */\n skipped: Array<{ file: string; reason: string }>\n}\n\nexport interface PiBridgeStats {\n staticFiles: number\n scopedRules: number\n imports: number\n skipped: number\n truncated: boolean\n}\n\nfunction byteLength(s: string): number {\n return Buffer.byteLength(s, \"utf8\")\n}\n\n/**\n * Truncate to a UTF-8 byte budget without splitting a code point, marker\n * included in the budget.\n *\n * Exported because the foreign-artifact bridge caps with the same measure Pi's\n * own limits are stated in, and `label` keeps the truncation marker honest\n * about which bridge did the cutting.\n */\nexport function capBytes(\n s: string,\n max: number,\n label = \"gh-router memory bridge\",\n): { text: string; truncated: boolean } {\n if (byteLength(s) <= max) return { text: s, truncated: false }\n // The marker is part of the budget, not extra: a caller that asserts \"≤ 8\n // KiB\" means the returned string, so the head is cut short enough for the\n // marker to fit inside `max`.\n const marker = `\\n…[truncated by ${label}]`\n const budget = Math.max(0, max - byteLength(marker))\n let low = 0\n let high = s.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n if (byteLength(s.slice(0, mid)) <= budget) low = mid + 1\n else high = mid\n }\n return { text: `${s.slice(0, Math.max(0, low - 1))}${marker}`, truncated: true }\n}\n\n/** Strip YAML frontmatter (`--- ... ---`) and return body + raw frontmatter. */\nexport function splitFrontmatter(raw: string): { frontmatter: string; body: string } {\n const normalized = raw.replace(/\\r\\n/g, \"\\n\")\n if (!normalized.startsWith(\"---\")) return { frontmatter: \"\", body: normalized }\n const end = normalized.indexOf(\"\\n---\", 3)\n if (end === -1) return { frontmatter: \"\", body: normalized }\n return {\n frontmatter: normalized.slice(3, end).trim(),\n body: normalized.slice(end + 4).replace(/^\\n/, \"\"),\n }\n}\n\n/**\n * Minimal frontmatter glob extraction for `paths:` / `applyTo:` / `globs:`.\n * Supports `key: \"glob\"`, `key: a, b`, and YAML lists. Case-insensitive keys.\n * Returns [] when no scoping key is present (unscoped rule).\n */\nexport function extractScopeGlobs(frontmatter: string): Array<string> {\n const out: Array<string> = []\n const lines = frontmatter.split(\"\\n\")\n let i = 0\n while (i < lines.length) {\n const line = lines[i] ?? \"\"\n const m = /^\\s*(paths|applyTo|globs)\\s*:\\s*(.*)$/i.exec(line)\n if (!m) {\n i++\n continue\n }\n const rest = (m[2] ?? \"\").trim()\n if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n for (const part of rest.slice(1, -1).split(\",\")) {\n const v = part.trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n }\n i++\n continue\n }\n if (rest && !rest.startsWith(\"|\") && !rest.startsWith(\">\")) {\n const v = rest.replace(/^[\"']|[\"']$/g, \"\").split(\"#\")[0]?.trim() ?? \"\"\n if (v) {\n for (const part of v.split(\",\")) {\n const p = part.trim()\n if (p) out.push(p)\n }\n }\n i++\n continue\n }\n // Block list on following indented lines (`- \"glob\"`).\n i++\n while (i < lines.length) {\n const item = lines[i] ?? \"\"\n const im = /^\\s+-\\s+(.+)$/.exec(item)\n if (!im) break\n const v = (im[1] ?? \"\").trim().replace(/^[\"']|[\"']$/g, \"\")\n if (v) out.push(v)\n i++\n }\n }\n return out\n}\n\n/** Convert a single glob to RegExp. `*` stays in-segment, `**` crosses. */\nfunction globToRegExp(glob: string): RegExp {\n const g = glob.trim().replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\")\n let re = \"\"\n let k = 0\n while (k < g.length) {\n const c = g[k]\n if (c === \"*\") {\n if (g[k + 1] === \"*\") {\n // `**/` → optional any-prefix; trailing `/**` → any suffix.\n if (g[k + 2] === \"/\") {\n re += \"(?:.*/)?\"\n k += 3\n } else {\n re += \".*\"\n k += 2\n }\n } else {\n re += \"[^/]*\"\n k += 1\n }\n continue\n }\n if (c === \"?\") {\n re += \"[^/]\"\n k += 1\n continue\n }\n if (\"+()|^$.{}[]\\\\\".includes(c ?? \"\")) re += `\\\\${c}`\n else re += c\n k += 1\n }\n // Slashless patterns (`*.ts`) match basename at any depth (gitignore-style).\n if (!g.includes(\"/\")) re = `(?:.*/)?${re}`\n return new RegExp(`^${re}$`)\n}\n\n/**\n * Does a touched file match any of the rule globs?\n * `touchedAbs` may be absolute or repo-relative; `ruleRoot` scopes\n * project-relative globs. Falls back to basename matching.\n */\nexport function ruleMatchesFile(\n globs: ReadonlyArray<string>,\n touchedAbs: string,\n ruleRoot: string,\n): boolean {\n if (globs.length === 0) return false\n const candidates = new Set<string>()\n const norm = touchedAbs.replace(/\\\\/g, \"/\")\n candidates.add(norm)\n const rel = path.relative(ruleRoot, touchedAbs).replace(/\\\\/g, \"/\")\n if (rel && !rel.startsWith(\"..\")) candidates.add(rel)\n candidates.add(path.basename(touchedAbs))\n for (const glob of globs) {\n let re: RegExp\n try {\n re = globToRegExp(glob)\n } catch {\n continue\n }\n for (const c of candidates) {\n if (re.test(c)) return true\n }\n }\n return false\n}\n\n/** Extract `@path` references (whole-line or trailing) ending in a text extension. */\nexport function extractAtImports(content: string): Array<string> {\n const refs: Array<string> = []\n const seen = new Set<string>()\n const pattern = /@([~.]?[\\w./\\\\-]+\\.(?:md|txt|yaml|yml|json|toml))(?:\\s|$)/g\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed.includes(\"@\")) continue\n // Skip fenced-code `@` mentions (commented-out imports must not expand).\n pattern.lastIndex = 0\n let m: RegExpExecArray | null\n while ((m = pattern.exec(trimmed)) !== null) {\n const ref = m[1] ?? \"\"\n if (ref && !seen.has(ref)) {\n seen.add(ref)\n refs.push(ref)\n }\n }\n }\n return refs\n}\n\n/**\n * Resolve `@` imports against an in-memory file map (pure, testable).\n * Depth-capped, cycle-safe, budget-capped. Returns appended bodies only\n * (base files are never re-appended by the caller).\n */\nexport function resolveImportsPure(\n baseFiles: ReadonlyArray<{ file: string; content: string }>,\n readFile: (absPath: string) => string | undefined,\n homeDir: string,\n maxDepth = PI_BRIDGE_IMPORT_MAX_DEPTH,\n maxFiles = PI_BRIDGE_IMPORT_MAX_FILES,\n): Array<{ file: string; content: string }> {\n const out: Array<{ file: string; content: string }> = []\n const visited = new Set<string>()\n for (const base of baseFiles) {\n try {\n visited.add(path.resolve(base.file))\n } catch {\n visited.add(base.file)\n }\n }\n const visit = (importerAbs: string, content: string, depth: number): void => {\n if (depth > maxDepth || out.length >= maxFiles) return\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(content)) {\n if (out.length >= maxFiles) return\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (visited.has(abs)) continue\n visited.add(abs)\n const body = readFile(abs)\n if (body === undefined) continue\n out.push({ file: abs, content: splitFrontmatter(body).body })\n visit(abs, body, depth + 1)\n }\n }\n for (const base of baseFiles) {\n let abs = base.file\n try {\n abs = path.resolve(base.file)\n } catch {\n // keep as-is\n }\n visit(abs, base.content, 1)\n }\n return out\n}\n\n/** Cap Claude auto-memory index the way Claude Code measures it. */\nexport function capMemoryIndex(raw: string): string {\n const lines = raw.split(\"\\n\").slice(0, PI_BRIDGE_MEMORY_INDEX_MAX_LINES)\n let text = lines.join(\"\\n\")\n if (byteLength(text) > PI_BRIDGE_MEMORY_INDEX_MAX_BYTES) {\n text = capBytes(text, PI_BRIDGE_MEMORY_INDEX_MAX_BYTES).text\n }\n return text\n}\n\n/** Redact likely secrets before persisting synthesized bridge content. */\nexport function redactSecrets(text: string): string {\n return text\n .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, \"[REDACTED private key]\")\n .replace(/(sk-(live|test)-[A-Za-z0-9_-]{8,})/g, \"[REDACTED]\")\n .replace(/(gh[pousr]_[A-Za-z0-9_]{8,})/g, \"[REDACTED]\")\n .replace(/(xox[baprs]-[A-Za-z0-9-]{8,})/g, \"[REDACTED]\")\n .replace(/eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}/g, \"[REDACTED jwt]\")\n}\n\nasync function readIfExists(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\n/**\n * Collect bridge inputs from disk (best-effort). Repo root is the cwd's\n * git top-level when resolvable, else cwd. Only reads files; never writes.\n */\nexport async function collectBridgeInputs(\n cwd = process.cwd(),\n homeDir = os.homedir(),\n): Promise<PiBridgeCollected> {\n const collected: PiBridgeCollected = {\n copilotInstructions: [],\n unscopedRules: [],\n scopedRules: [],\n userGlobal: [],\n imports: [],\n skipped: [],\n }\n // Repo root: walk up for `.git` (cheap, no subprocess).\n let repoRoot = cwd\n try {\n let dir = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(dir, \".git\"))\n repoRoot = dir\n break\n } catch {\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n } catch {\n repoRoot = cwd\n }\n\n // 1. Repo-wide Copilot instructions (+ `@` expansion later).\n const copilotFile = path.join(repoRoot, \".github\", \"copilot-instructions.md\")\n const copilotBody = await readIfExists(copilotFile)\n const baseForImports: Array<{ file: string; content: string }> = []\n if (copilotBody !== undefined) {\n collected.copilotInstructions.push({ file: copilotFile, content: splitFrontmatter(copilotBody).body })\n baseForImports.push({ file: copilotFile, content: copilotBody })\n }\n\n // 2. Path-specific Copilot instructions (applyTo).\n try {\n const dir = path.join(repoRoot, \".github\", \"instructions\")\n const entries = await fs.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".instructions.md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0 || globs.includes(\"**\") || globs.includes(\"**/*\")) {\n collected.unscopedRules.push({ file, content: body })\n } else {\n collected.scopedRules.push({ file, body, globs, source: \"copilot-instructions\" })\n }\n }\n } catch {\n // no instructions dir — not an error\n }\n\n // 3. Claude rules (nearest `.claude/rules` at-or-above cwd).\n try {\n let dir: string | null = null\n let walk = path.resolve(cwd)\n for (let depth = 0; depth < 12; depth++) {\n try {\n await fs.stat(path.join(walk, \".claude\", \"rules\"))\n dir = path.join(walk, \".claude\", \"rules\")\n break\n } catch {\n const parent = path.dirname(walk)\n if (parent === walk) break\n walk = parent\n }\n }\n if (dir) {\n const entries = await fs.readdir(dir)\n for (const name of entries.sort()) {\n if (!name.endsWith(\".md\")) continue\n const file = path.join(dir, name)\n const raw = await readIfExists(file)\n if (raw === undefined) continue\n const { frontmatter, body } = splitFrontmatter(raw)\n if (!body.trim()) {\n collected.skipped.push({ file, reason: \"empty after frontmatter strip\" })\n continue\n }\n const globs = extractScopeGlobs(frontmatter)\n if (globs.length === 0) collected.unscopedRules.push({ file, content: body })\n else collected.scopedRules.push({ file, body, globs, source: \"claude-rules\" })\n }\n }\n } catch {\n // unreadable rules dir — skip\n }\n\n // 4. Alternate project memory `./.claude/CLAUDE.md` (deduped later\n // against Pi-native context; approval-gated by the caller).\n const dotClaude = path.join(repoRoot, \".claude\", \"CLAUDE.md\")\n const dotBody = await readIfExists(dotClaude)\n if (dotBody !== undefined && dotBody.trim()) {\n collected.unscopedRules.push({ file: dotClaude, content: splitFrontmatter(dotBody).body })\n baseForImports.push({ file: dotClaude, content: dotBody })\n }\n\n // 5. User-global files (inlined, capped downstream).\n for (const file of [\n path.join(homeDir, \".claude\", \"CLAUDE.md\"),\n path.join(homeDir, \".copilot\", \"copilot-instructions.md\"),\n ]) {\n const raw = await readIfExists(file)\n if (raw !== undefined && raw.trim()) {\n collected.userGlobal.push({ file, content: splitFrontmatter(raw).body })\n baseForImports.push({ file, content: raw })\n }\n }\n\n // 6. `@` imports across everything collected so far.\n const fileMap = new Map<string, string>()\n for (const group of [collected.copilotInstructions, collected.unscopedRules, collected.userGlobal]) {\n for (const entry of group) {\n try {\n fileMap.set(path.resolve(entry.file), entry.content)\n } catch {\n fileMap.set(entry.file, entry.content)\n }\n }\n }\n // Async BFS over `@` imports (map first, disk fallback). Seeds `seen`\n // with base files so a self-import never re-appends the base body.\n const seen = new Set<string>()\n for (const b of baseForImports) {\n try {\n seen.add(path.resolve(b.file))\n } catch {\n seen.add(b.file)\n }\n }\n const queue: Array<{ importer: string; content: string; depth: number }> = baseForImports.map((b) => ({\n importer: b.file,\n content: b.content,\n depth: 1,\n }))\n while (queue.length > 0 && collected.imports.length < PI_BRIDGE_IMPORT_MAX_FILES) {\n const head = queue.shift()\n if (!head || head.depth > PI_BRIDGE_IMPORT_MAX_DEPTH) continue\n let importerAbs = head.importer\n try {\n importerAbs = path.resolve(head.importer)\n } catch {\n // keep\n }\n const baseDir = path.dirname(importerAbs)\n for (const ref of extractAtImports(head.content)) {\n if (collected.imports.length + seen.size >= PI_BRIDGE_IMPORT_MAX_FILES) break\n let expanded = ref\n if (expanded.startsWith(\"~\")) expanded = path.join(homeDir, expanded.slice(1))\n const abs = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded)\n if (seen.has(abs)) continue\n seen.add(abs)\n const hit = fileMap.get(abs) ?? (await readIfExists(abs))\n if (hit === undefined) {\n collected.skipped.push({ file: abs, reason: `import of ${head.importer} not found` })\n continue\n }\n const body = splitFrontmatter(hit).body\n collected.imports.push({ file: abs, content: body })\n queue.push({ importer: abs, content: hit, depth: head.depth + 1 })\n }\n }\n\n return collected\n}\n\n/** Build the static mirror `AGENTS.md` bridge section. */\nexport function buildMirrorBridgeSection(\n collected: PiBridgeCollected,\n opts: { repoRoot?: string } = {},\n): { section: string; stats: PiBridgeStats } {\n const parts: Array<string> = [PI_BRIDGE_FENCE_BEGIN, \"\", \"# gh-router memory bridge\", \"\"]\n let truncated = false\n\n const pushCapped = (title: string, file: string, content: string, budgetLeft: () => number): void => {\n // Strip NUL bytes: a literal U+0000 in synthesized context breaks\n // strict downstream JSON consumers (workflow-preflight parse errors).\n const body = content.replaceAll(\"\\0\", \"\").trim()\n if (!body) return\n const block = `## ${title}\\n<!-- source: ${file} -->\\n\\n${body}\\n`\n const capped = capBytes(block, Math.max(0, budgetLeft()))\n parts.push(capped.text, \"\")\n if (capped.truncated) truncated = true\n }\n let used = byteLength(parts.join(\"\\n\"))\n const budgetLeft = (): number => Math.max(0, PI_BRIDGE_STATIC_BUDGET_BYTES - used - 512)\n const account = (): void => {\n used = byteLength(parts.join(\"\\n\"))\n }\n\n for (const entry of collected.copilotInstructions) {\n pushCapped(\"Copilot repo instructions\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.unscopedRules) {\n pushCapped(\"Unscoped project rules\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.userGlobal) {\n pushCapped(\"User-global instructions\", entry.file, entry.content, budgetLeft)\n account()\n }\n for (const entry of collected.imports) {\n pushCapped(\"Imported context (@path)\", entry.file, entry.content, budgetLeft)\n account()\n }\n\n if (collected.scopedRules.length > 0) {\n parts.push(\n \"## Path-scoped rules (lazy)\",\n \"\",\n \"The following rule files apply only to matching paths and are attached\",\n \"when a matching file is read/edited/written (once per session):\",\n \"\",\n )\n for (const rule of collected.scopedRules) {\n parts.push(`- \\`${rule.file.replaceAll(\"\\0\", \"\")}\\` → \\`${rule.globs.join(\", \").replaceAll(\"\\0\", \"\")}\\` (${rule.source.replaceAll(\"\\0\", \"\")})`)\n }\n parts.push(\"\")\n account()\n }\n\n if (opts.repoRoot) parts.push(`<!-- repo: ${opts.repoRoot.replaceAll(\"\\0\", \"\")} -->`, \"\")\n parts.push(PI_BRIDGE_FENCE_END, \"\")\n const section = redactSecrets(parts.join(\"\\n\")).replaceAll(\"\\0\", \"\")\n return {\n section,\n stats: {\n staticFiles:\n collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,\n scopedRules: collected.scopedRules.length,\n imports: collected.imports.length,\n skipped: collected.skipped.length,\n truncated,\n },\n }\n}\n\n/**\n * Merge a bridge section into mirror `AGENTS.md`: append when absent,\n * replace the fenced block when present (idempotent across relaunches).\n */\nexport function mergeBridgeIntoAgentsMd(existing: string | undefined, section: string): string {\n const body = (existing ?? \"\").replace(/\\r\\n/g, \"\\n\")\n if (!body.trim()) return `${section}\\n`\n const begin = body.indexOf(PI_BRIDGE_FENCE_BEGIN)\n const end = body.indexOf(PI_BRIDGE_FENCE_END)\n if (begin !== -1 && end !== -1 && end > begin) {\n const after = body.slice(end + PI_BRIDGE_FENCE_END.length)\n return `${body.slice(0, begin)}${section}${after.startsWith(\"\\n\") ? after : `\\n${after}`}`\n }\n return `${body.endsWith(\"\\n\") ? body : `${body}\\n`}\\n${section}\\n`\n}\n\n/** Resolve the Claude auto-memory index path for a repo (on-demand read). */\nexport function claudeAutoMemoryIndex(homeDir: string, repoRoot: string): string {\n const slug = repoRoot.replace(/^\\//, \"\").replace(/\\//g, \"-\")\n return path.join(homeDir, \".claude\", \"projects\", slug || \"-\", \"memory\", \"MEMORY.md\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,gCAAgC;AAK7C,MAAa,wBAAwB;AACrC,MAAa,sBAAsB;AAoCnC,SAAS,WAAW,GAAmB;CACrC,OAAO,OAAO,WAAW,GAAG,MAAM;AACpC;;;;;;;;;AAUA,SAAgB,SACd,GACA,KACA,QAAQ,2BAC8B;CACtC,IAAI,WAAW,CAAC,KAAK,KAAK,OAAO;EAAE,MAAM;EAAG,WAAW;CAAM;CAI7D,MAAM,SAAS,oBAAoB,MAAM;CACzC,MAAM,SAAS,KAAK,IAAI,GAAG,MAAM,WAA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,KAAK,SAAS,WAAW,MAAM,EAAE,EAAE,OAAO,EAAE;CACxF,MAAM,KAAK,qBAAqB,EAAE;CAElC,OAAO;EACL,SAFc,cAAc,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,WAAW,MAAM,EAEzD;EACN,OAAO;GACL,aACE,UAAU,oBAAoB,SAAS,UAAU,cAAc,SAAS,UAAU,WAAW;GAC/F,aAAa,UAAU,YAAY;GACnC,SAAS,UAAU,QAAQ;GAC3B,SAAS,UAAU,QAAQ;GAC3B;EACF;CACF;AACF;;;;;AAMA,SAAgB,wBAAwB,UAA8B,SAAyB;CAC7F,MAAM,QAAQ,YAAY,GAAA,CAAI,QAAQ,SAAS,IAAI;CACnD,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO,GAAG,QAAQ;CACpC,MAAM,QAAQ,KAAK,QAAQ,qBAAqB;CAChD,MAAM,MAAM,KAAK,QAAQ,mBAAmB;CAC5C,IAAI,UAAU,MAAM,QAAQ,MAAM,MAAM,OAAO;EAC7C,MAAM,QAAQ,KAAK,MAAM,MAAM,EAA0B;EACzD,OAAO,GAAG,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,MAAM,WAAW,IAAI,IAAI,QAAQ,KAAK;CACnF;CACA,OAAO,GAAG,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,KAAK,IAAI,IAAI,QAAQ;AACjE"}
@@ -1,7 +1,7 @@
1
1
  import { t as PATHS } from "./paths-CVEO8jEH.js";
2
2
  import { a as parseBoolEnv, c as runCommandCapture, n as isWindowsScriptShim, r as killChildProcessTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
3
3
  import { E as extractZipMember, L as withInstallLock, T as extractTarGzMember } from "./service-backend-Cdgz6WPx.js";
4
- import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, Kn as collapsePathKeys, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-B1prNNMJ.js";
4
+ import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, Kn as collapsePathKeys, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-OWsSm6To.js";
5
5
  import { a as sweepRegistry } from "./lifecycle-Dh9y8OF1.js";
6
6
  import consola from "consola";
7
7
  import { existsSync } from "node:fs";
@@ -730,4 +730,4 @@ async function exposedCommands(binDir) {
730
730
  }
731
731
  export { STRIPPED_AUTH_ROUTING_ENV_KEYS as a, launchChild as i, buildCodexProviderConfigFlags as n, getCodexVersion as r, provisionToolbelt as t };
732
732
 
733
- //# sourceMappingURL=provision-DktDm-f0.js.map
733
+ //# sourceMappingURL=provision-DPL8aGe2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"provision-DktDm-f0.js","names":[],"sources":["../src/lib/process-guard/index.ts","../src/lib/stripped-env-keys.ts","../src/lib/launch.ts","../src/lib/toolbelt/provision.ts"],"sourcesContent":["/**\n * Crash-safe process guard (POSIX only).\n *\n * If the proxy dies WITHOUT running its own shutdown handlers (hard crash,\n * SIGKILL, OOM), nothing in `cleanup()` runs to reap the launched CLI's\n * process tree. This guard is the last-resort net for that case.\n *\n * Platform split:\n * - **Windows: no guard needed.** Node assigns each child to a Job\n * Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so when the proxy\n * dies (any cause) the OS tears down the whole descendant tree —\n * verified: force-killing a Node parent kills child AND grandchild.\n * `startProcessGuard` is a no-op on win32.\n * - **POSIX: a detached `node -e` reaper.** There is no job-object\n * equivalent (a killed parent's children reparent to init), so we\n * spawn a detached watchdog that learns of proxy death via an inherited\n * stdin PIPE EOF (the proxy holds the write end; the OS closes it on\n * proxy death) and reaps the CLI's process group.\n *\n * Never kill the WRONG process: if the child's PID/PGID was recycled after\n * the child exited, a blind `kill(-pid)` could hit an innocent group. The\n * reaper snapshots the child's process start-time at startup and, on proxy\n * death, kills ONLY if the live PID's start-time still matches. A mismatch\n * / unreadable probe → skip (fail-safe). We never trade an orphan-leak for\n * killing the user's work.\n *\n * The reaper is detached + unref'd so it survives the proxy's SIGKILL, and\n * self-exits once it has acted (or after a 24h cap) so it can never become\n * the orphan it exists to prevent. Opt out with\n * `GH_ROUTER_DISABLE_PROCESS_GUARD=1`.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\"\nimport process from \"node:process\"\n\nimport { parseBoolEnv } from \"../exec\"\n\n/**\n * Live reaper children, held so the GC can't collect the `ChildProcess`\n * (and with it the stdin write-end that is the proxy-death signal) while\n * the proxy runs. Entries self-remove on the reaper's exit. We do NOT\n * proactively kill these on graceful shutdown: when the proxy exits the OS\n * closes the stdin pipe, the reaper hits EOF, re-verifies the child's\n * identity, and reaps any survivor that ignored the graceful SIGTERM —\n * exactly the backstop we want.\n */\nconst _activeReapers = new Set<ChildProcess>()\n\n/** Guard is on by default; `GH_ROUTER_DISABLE_PROCESS_GUARD=1` opts out. */\nexport function processGuardEnabled(): boolean {\n return parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROCESS_GUARD) !== true\n}\n\n/**\n * Build the start-time-verified node reaper script (POSIX). PURE — `pid`\n * is our own integer. `detachedGroup` selects `kill(-pid)` (process group,\n * the detached CLI) vs `kill(pid)` on POSIX.\n *\n * Kept dependency-free (require'd builtins only) so it runs under `node -e`\n * with no module resolution against the dist bundle.\n */\nexport function buildNodeReaperScript(\n pid: number,\n detachedGroup: boolean,\n): string {\n const target = detachedGroup ? \"-PID\" : \"PID\"\n return `\nconst cp = require(\"node:child_process\");\nconst fs = require(\"node:fs\");\nconst PID = ${pid >>> 0};\nfunction startTime() {\n try {\n if (process.platform === \"linux\") {\n const stat = fs.readFileSync(\"/proc/\" + PID + \"/stat\", \"utf8\");\n const post = stat.slice(stat.lastIndexOf(\")\") + 1).trim().split(/\\\\s+/);\n return post[19] || null; // field 22 (starttime) = index 19 after comm\n }\n const out = cp.execFileSync(\"ps\", [\"-o\",\"lstart=\",\"-p\",String(PID)],\n { stdio: [\"ignore\",\"pipe\",\"ignore\"], timeout: 2000 }).toString().trim();\n return out || null;\n } catch { return null; }\n}\nfunction alive() { try { process.kill(PID, 0); return true; } catch { return false; } }\nfunction treeKill() {\n try { process.kill(${target}, \"SIGTERM\"); } catch {}\n // NOT unref'd: this must keep the loop alive to deliver the escalated\n // SIGKILL (the onDeath exit timer below stays alive past 500ms too).\n setTimeout(() => { try { process.kill(${target}, \"SIGKILL\"); } catch {} }, 500);\n}\nconst snap = (() => {\n // The child is definitely ours and alive at startup, so a null here is a\n // transient probe failure (e.g. a momentary 'ps' hiccup), NOT a real\n // identity loss. Retry a few times so a one-off failure can't silently\n // disable the guard for the rest of the run.\n for (let i = 0; i < 3; i++) { const s = startTime(); if (s !== null) return s; }\n return null;\n})();\nlet done = false;\nfunction onDeath() {\n if (done) return; done = true;\n // Re-verify identity: kill ONLY if the live PID is still our child.\n if (snap !== null && alive() && startTime() === snap) treeKill();\n // REF'd (NOT unref'd): stdin has closed, so an unref'd timer would let\n // the loop empty and the process exit immediately — dropping the 500ms\n // SIGKILL escalation. Keep the loop alive to deliver it, then exit.\n setTimeout(() => process.exit(0), 1500);\n}\nprocess.stdin.resume();\nprocess.stdin.on(\"end\", onDeath);\nprocess.stdin.on(\"close\", onDeath);\nprocess.stdin.on(\"error\", onDeath);\nconst cap = setTimeout(() => process.exit(0), 24*3600*1000); if (cap.unref) cap.unref();\n`.trim()\n}\n\n/**\n * Spawn the detached node reaper holding the stdin death-pipe. Always\n * `detached` so it outlives a force-kill of the proxy, and `unref`'d so it\n * never holds the proxy's event loop open. Returns null on spawn failure.\n */\nfunction spawnNodeReaper(pid: number, detachedGroup: boolean): ChildProcess | null {\n try {\n const child = spawn(\n process.execPath,\n [\"-e\", buildNodeReaperScript(pid, detachedGroup)],\n {\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n detached: true,\n windowsHide: true,\n shell: false,\n },\n )\n child.on(\"error\", () => {})\n child.stdin?.on(\"error\", () => {})\n // Hold a reference so the GC can't drop the ChildProcess (and its stdin\n // write-end, the proxy-death signal) mid-run; drop it on reaper exit.\n _activeReapers.add(child)\n child.once(\"exit\", () => _activeReapers.delete(child))\n child.unref()\n return child\n } catch {\n return null\n }\n}\n\n/**\n * Start the crash-safe guard for a launched CLI child. No-op on Windows\n * (Node's Job Object already reaps the tree on proxy death) and when\n * disabled / unspawnable. Fire-and-forget; never throws.\n */\nexport function startProcessGuard(child: ChildProcess): void {\n if (!processGuardEnabled()) return\n const pid = child.pid\n if (!pid) return\n // Windows: the runtime's KILL_ON_JOB_CLOSE job object is the crash net.\n if (process.platform === \"win32\") return\n // POSIX: the CLI is spawned detached (own group), so reap the group.\n spawnNodeReaper(pid, true)\n}\n","/**\n * Auth / routing / remote / wire-fingerprint environment keys that must never\n * reach a github-router-spawned Claude or Codex child — through ANY channel.\n *\n * Two channels carry these keys to a spawned agent, and both must be defended:\n * 1. The PARENT PROCESS ENV — a user's shell exports. Stripped by\n * `sanitizeParentEnv` (`src/lib/launch.ts`) before the proxy's overrides.\n * 2. The serve mirror `settings.json` `env` BLOCK — a user's own\n * `~/.claude/settings.json`, snapshot-mirrored and applied to the\n * SDK-spawned claude via `settingSources`. Stripped by\n * `sanitizeServeSettingsEnv` (`src/lib/mcp-permissions-settings.ts`).\n *\n * If any of these survived, a Bedrock/Vertex/gateway user's config would\n * re-route the session OFF the github-router proxy, inject real auth that wins\n * over the synthetic `.credentials.json`, or activate Claude Code's\n * unimplemented Bridge/remote code path. `CLAUDE_CODE_COORDINATOR_MODE` (a\n * toolset-stripper) is NOT here — it's serve-specific, added to the serve list\n * directly. `ANTHROPIC_SMALL_FAST_MODEL` is deliberately NOT stripped (users\n * legitimately rely on it; `resolveModel` translates unrecognized values).\n */\nexport const STRIPPED_AUTH_ROUTING_ENV_KEYS = [\n // Claude Code auth surface\n \"ANTHROPIC_API_KEY\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_BASE_URL\",\n \"ANTHROPIC_CUSTOM_HEADERS\",\n \"ANTHROPIC_MODEL\",\n \"CLAUDE_CODE_OAUTH_TOKEN\",\n // Alternate OAuth source (loads from an open file descriptor); stripping\n // prevents a third auth source alongside the synthetic .credentials.json.\n \"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR\",\n \"CLAUDE_CODE_USE_BEDROCK\",\n \"CLAUDE_CODE_USE_VERTEX\",\n \"CLAUDE_CODE_USE_FOUNDRY\",\n // Defense-in-depth: a parent- or settings-set CLAUDE_CONFIG_DIR would\n // redirect the session's config dir away from the router-owned mirror.\n \"CLAUDE_CONFIG_DIR\",\n // Claude Code Bridge / IDE remote-session surface — activates a remote code\n // path (POST /v1/code/sessions, /v1/environments/bridge, …) the proxy does\n // not implement. Stripping forces a local-only session.\n \"CLAUDE_BRIDGE_OAUTH_TOKEN\",\n \"CLAUDE_BRIDGE_BASE_URL\",\n \"CLAUDE_BRIDGE_SESSION_INGRESS_URL\",\n \"SESSION_INGRESS_URL\",\n \"CLAUDE_CODE_REMOTE\",\n \"CLAUDE_CODE_CONTAINER_ID\",\n \"CLAUDE_CODE_REMOTE_SESSION_ID\",\n \"CLAUDE_CODE_SESSION_ID\",\n // Emits `x-anthropic-additional-protection` — pure wire-fingerprint noise\n // that breaks the VS Code stealth posture.\n \"CLAUDE_CODE_ADDITIONAL_PROTECTION\",\n // Optional Bluebird MCP bearer override. The router may consume it, but the\n // spawned CLI and its descendant tools/MCPs must never inherit it.\n \"BLUEBIRD_TOKEN\",\n // Azure DevOps remote MCP bearer override. Same rule as BLUEBIRD_TOKEN:\n // the router may consume it, the spawned CLI and every tool/MCP under it\n // must never see it.\n \"ADO_MCP_TOKEN\",\n // Kusto (Azure Data Explorer) bearer override. Same rule.\n \"KUSTO_TOKEN\",\n // Cloud Agent Job API v2 bearer override. Same rule, and it matters more\n // here than anywhere else on this list: the Cloud Agent group can launch a\n // cloud agent that spends compute, so a bearer inherited by a spawned\n // CLI or one of its MCPs would be both a credential leak and a\n // capability leak.\n \"GH_ROUTER_CLOUDAGENT_TOKEN\",\n // Work IQ hosted MCP bearer override. The group reads the signed-in user's\n // entire Microsoft 365 estate, so a spawned CLI or one of its MCPs must never\n // inherit the credential that reaches it.\n \"WORKIQ_MCP_TOKEN\",\n // Codex CLI auth surface\n \"OPENAI_API_KEY\",\n \"OPENAI_BASE_URL\",\n \"CODEX_HOME\",\n // Pi coding-agent routing/auth surface. `PI_CODING_AGENT_DIR` would\n // redirect the session's agent dir away from the router-owned mirror;\n // provider keys would re-route Pi off the proxy or leak real auth.\n \"PI_CODING_AGENT_DIR\",\n \"PI_CODING_AGENT_SESSION_DIR\",\n \"OPENCODE_API_KEY\",\n // ai-or-die per-tab session-bind / artifact-review surface — must not leak\n // into a nested launch and hijack the parent tab's sidecar / bearer token.\n \"AIORDIE_CLAUDE_BIND\",\n \"AIORDIE_TOKEN\",\n \"AIORDIE_INSECURE_TLS\",\n] as const\n","import { execFileSync, spawn, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport type { Server } from \"srvx\"\n\nimport { resolveExecutable, killChildProcessTree } from \"./exec\"\nimport { DEFAULT_CODEX_MODEL } from \"./port\"\nimport { startProcessGuard } from \"./process-guard\"\nimport { STRIPPED_AUTH_ROUTING_ENV_KEYS } from \"./stripped-env-keys\"\nimport { collapsePathKeys } from \"./toolbelt/path-inject\"\nimport { sweepRegistry } from \"./worker-agent/lifecycle\"\n\n/**\n * Auth-related env keys we strip from the parent before spawning the child CLI.\n * The proxy provides its own values for everything we care about, so the child\n * behaves as if the user had no parent-env auth at all. The canonical list lives\n * in `./stripped-env-keys` (shared with serve's settings.json `env` strip).\n *\n * Why strip rather than override-with-empty-string: Claude Code emits \"Auth\n * conflict\" warnings whenever both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY\n * are present (any value); stripping suppresses it AND prevents an inherited\n * real key from leaking. Cloud-provider toggles + OAuth tokens are simpler\n * dropped than overridden — a missing var is unambiguously absent everywhere.\n */\nconst STRIPPED_PARENT_ENV_KEYS = STRIPPED_AUTH_ROUTING_ENV_KEYS\n\n/**\n * Strip auth-related keys from a parent-process env object. The result\n * is suitable to spread into a spawned child's env BEFORE the proxy's\n * explicit overrides, so the proxy is the only source of truth for\n * auth — and stale shell exports can't leak through.\n */\nexport function sanitizeParentEnv(\n parent: NodeJS.ProcessEnv,\n): NodeJS.ProcessEnv {\n const sanitized: NodeJS.ProcessEnv = { ...parent }\n for (const key of STRIPPED_PARENT_ENV_KEYS) {\n delete sanitized[key]\n }\n return sanitized\n}\n\nfunction commandExists(name: string): boolean {\n try {\n execFileSync(process.platform === \"win32\" ? \"where.exe\" : \"which\", [name], {\n stdio: \"ignore\",\n })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Whether the launcher can execute `executable`.\n *\n * `buildLaunchCommand` resolves the CLI to an ABSOLUTE path (anti-shadow).\n * `where.exe` (and POSIX `which`) reject a full path argument — `where`\n * returns \"Could not find files for the given pattern(s)\" for an absolute\n * path even when the file exists — so the where/which probe is only valid\n * for bare command names. For an absolute path (already resolved against\n * PATH and existence-checked by `resolveExecutable`), check the\n * filesystem directly. Without this split, every launch where the CLI is\n * installed fails with a spurious \"not found on PATH\".\n */\nexport function isExecutableAvailable(executable: string): boolean {\n if (path.isAbsolute(executable)) return existsSync(executable)\n return commandExists(executable)\n}\n\n/**\n * Provider-config flags (`-c model_providers.github_router=...`) that\n * point Codex at our proxy. Extracted from `buildCodexCmd` so the new\n * `codex mcp-server` MCP-config builder can reuse the exact same\n * provider definition — drift between the two paths would silently\n * break the MCP wiring.\n */\nexport function buildCodexProviderConfigFlags(serverUrl: string): Array<string> {\n return [\n \"-c\",\n `model_providers.github_router={name=\"github-router\",base_url=\"${serverUrl}/v1\",wire_api=\"responses\",env_key=\"OPENAI_API_KEY\"}`,\n \"-c\",\n \"model_provider=github_router\",\n ]\n}\n\n/**\n * Inspect the installed `codex` binary. Used by the codex-MCP wiring\n * in `claude.ts` to gate `--codex-cli`. Codex 0.129.0 introduced the\n * `mcp-server` subcommand; older versions don't expose it, so we\n * downgrade to the HTTP backend with a warning.\n */\nexport function getCodexVersion(): { ok: boolean; version?: string } {\n if (!commandExists(\"codex\")) return { ok: false }\n let raw: string\n try {\n raw = execFileSync(\"codex\", [\"--version\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim()\n } catch {\n return { ok: false }\n }\n // Output examples: \"codex-cli 0.129.0\", \"codex 0.130.1-dev\"\n const m = /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(raw)\n if (!m) return { ok: false, version: raw }\n const major = Number.parseInt(m[1], 10)\n const minor = Number.parseInt(m[2], 10)\n const version = `${m[1]}.${m[2]}.${m[3]}`\n // mcp-server requires codex >= 0.129.0\n const ok = major > 0 || (major === 0 && minor >= 129)\n return { ok, version }\n}\n\nexport interface LaunchTarget {\n kind: \"claude-code\" | \"codex\" | \"pi\"\n envVars: Record<string, string>\n extraArgs: string[]\n model?: string\n /**\n * Proxy URL the spawned child should target. Required for Codex 0.129+\n * which stopped honoring OPENAI_BASE_URL and now needs an explicit\n * `-c model_providers.<name>.base_url=...` argument. Set by the codex\n * subcommand from the same `serverUrl` it computed for env vars.\n */\n serverUrl?: string\n}\n\n/**\n * Codex 0.129.0 broke two things the launcher had been relying on:\n * (1) `--full-auto` was removed in favor of `--sandbox` + `--ask-for-approval`;\n * passing it now exits the child immediately with\n * `error: unexpected argument '--full-auto' found`.\n * (2) `OPENAI_BASE_URL` is silently ignored — Codex hardcodes\n * `https://api.openai.com/v1/responses` and 401s out without an\n * explicit `-c model_providers.<name>.base_url` override.\n *\n * `buildCodexCmd` builds the launch argv that works on Codex 0.129+ while\n * still being compatible with older versions that accept the same flags.\n */\nfunction buildCodexCmd(target: LaunchTarget): string[] {\n const cmd: string[] = [\"codex\"]\n if (target.serverUrl) {\n cmd.push(...buildCodexProviderConfigFlags(target.serverUrl))\n }\n cmd.push(\n \"--sandbox\",\n \"workspace-write\",\n \"--ask-for-approval\",\n \"on-request\",\n \"-m\",\n target.model ?? DEFAULT_CODEX_MODEL,\n ...target.extraArgs,\n )\n return cmd\n}\n\nexport function buildLaunchCommand(target: LaunchTarget): {\n cmd: string[]\n env: Record<string, string | undefined>\n} {\n // F10: don't force `--dangerously-skip-permissions` when the caller already\n // requested an explicit `--permission-mode` (e.g. ai-or-die's claude-bridge\n // appends one for a fleet create_session with permissionMode). The two flags\n // conflict — claude rejects them together — and the explicit mode must win.\n const wantsPermissionMode =\n target.kind === \"claude-code\" &&\n target.extraArgs.some((arg) => arg === \"--permission-mode\" || arg.startsWith(\"--permission-mode=\"))\n const cmd: string[] =\n target.kind === \"claude-code\"\n ? wantsPermissionMode\n ? [\"claude\", ...target.extraArgs]\n : [\"claude\", \"--dangerously-skip-permissions\", ...target.extraArgs]\n : target.kind === \"pi\"\n ? [\n \"pi\",\n \"--provider\",\n \"gh-router\",\n ...(target.model ? [\"--model\", target.model] : []),\n ...target.extraArgs,\n ]\n : buildCodexCmd(target)\n\n // Anti-shadow: resolve the top-level CLI to an ABSOLUTE path against\n // the clean parent PATH (excluding the cwd). The spawned child's env\n // prepends the toolbelt bin dir to PATH; without this, a stray\n // `claude.cmd`/`codex.cmd` in that dir — or in an untrusted repo's cwd\n // (Windows resolves cwd before PATH under shell:true) — could shadow\n // the real CLI. Resolving here means the toolbelt PATH only affects\n // the agent's OWN tool lookups, never which CLI we launch.\n const resolved = resolveExecutable(cmd[0], { env: process.env })\n if (resolved) cmd[0] = resolved\n\n const env = collapsePathKeys({\n ...sanitizeParentEnv(process.env),\n ...target.envVars,\n })\n return { cmd, env }\n}\n\n/**\n * Whether a resolved Windows executable must be launched through cmd.exe\n * (`shell:true`). Only batch shims (`.cmd`/`.bat`) need it — and even then\n * cmd.exe stays alive as the CLI's parent, so `taskkill /T` reaps the\n * whole tree. A real `.exe` (e.g. the native-installer `claude.exe`) is\n * spawned DIRECTLY so the CLI is the direct child, with no cmd.exe\n * intermediary to orphan its node/MCP grandchildren on a kill.\n */\nexport function windowsLaunchNeedsShell(executable: string): boolean {\n const ext = path.extname(executable).toLowerCase()\n return ext === \".cmd\" || ext === \".bat\"\n}\n\n/**\n * Forward a terminal resize to the detached child's process group.\n *\n * The kernel delivers `SIGWINCH` only to the FOREGROUND PROCESS GROUP of the\n * controlling terminal. The launcher spawns the CLI with POSIX `detached: true`\n * (so `kill(-pid)` can reap the whole subtree), which puts the CLI in its own\n * group — that group is never the terminal's foreground, so the CLI would never\n * learn that the window changed and would keep laying out for the old geometry.\n * Re-broadcasting the signal the launcher itself receives is the whole fix.\n *\n * Returns whether a signal was sent, which is all a test can observe without a\n * pty (the delivery path is kernel-side and is proven separately by a `pty.fork`\n * harness: an attached child gets `SIGWINCH`, a detached one gets nothing, and\n * `kill(-pid, \"SIGWINCH\")` delivers it).\n *\n * Windows has no `SIGWINCH` and no process groups; the console resizes the\n * child directly, so the guard is a hard `return`, not a fallback.\n */\nexport function forwardTerminalResize(pid: number | undefined): boolean {\n if (process.platform === \"win32\" || !pid) return false\n try {\n process.kill(-pid, \"SIGWINCH\")\n return true\n } catch {\n // group already gone, or signalling is refused in this sandbox\n return false\n }\n}\n\nexport function launchChild(\n target: LaunchTarget,\n server: Server,\n options: {\n onShutdown?: () => Promise<void> | void\n /**\n * Optional exit summary (e.g. the AIC session total). Called once from\n * `exit()`, after cleanup, on every shutdown path (natural child exit,\n * signal escalation, spawn error). Return undefined for no output.\n * Best-effort: throwing content is swallowed so shutdown never blocks.\n */\n onExitSummary?: () => string | undefined\n } = {},\n): void {\n const { cmd, env } = buildLaunchCommand(target)\n\n const executable = cmd[0]\n if (!isExecutableAvailable(executable)) {\n const msg = `\"${executable}\" not found on PATH. Install it first, then try again.`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n process.exit(1)\n }\n\n let child: ChildProcess\n try {\n if (process.platform === \"win32\") {\n if (windowsLaunchNeedsShell(cmd[0])) {\n // A batch shim genuinely needs cmd.exe. cmd.exe stays alive as the\n // CLI's parent for the shim's lifetime, so the tree-kill (taskkill\n // /T) and the crash guard both reap the whole tree through it. Use\n // the full command as a single string to avoid the DEP0190\n // deprecation warning about shell + args.\n const quoted = cmd.map((a) => (a.includes(\" \") ? `\"${a}\"` : a)).join(\" \")\n child = spawn(quoted, [], {\n env,\n stdio: \"inherit\",\n shell: true,\n })\n } else {\n // A real .exe (e.g. the native-installer claude.exe) needs no\n // shell. Spawning it directly makes the CLI the DIRECT child, so\n // child.kill()/taskkill and the crash guard target the real\n // process instead of a cmd.exe wrapper that would orphan its\n // node/MCP grandchildren.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n })\n }\n } else {\n // detached:true → the CLI leads its OWN process group, so cleanup()\n // can kill(-pgid) the whole tree (grandchildren included). We still\n // await its exit, so we do NOT unref(). Terminal Ctrl-C no longer\n // reaches the child directly — the signal handlers below forward it.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n detached: true,\n })\n }\n } catch (error) {\n const msg = `Failed to launch ${executable}: ${error instanceof Error ? error.message : String(error)}`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n server.close(true).catch(() => {})\n if (options.onShutdown) {\n void Promise.resolve(options.onShutdown()).catch(() => {})\n }\n process.exit(1)\n }\n\n // Crash-safe net: if the proxy dies WITHOUT running cleanup() (hard\n // crash, SIGKILL/taskkill, OOM). On Windows this is the OS's job —\n // Node's KILL_ON_JOB_CLOSE job object reaps the tree — so this is a\n // no-op there. On POSIX (no such mechanism) it spawns a detached reaper\n // that sees the proxy's stdin-pipe EOF, re-verifies the child's\n // identity, and reaps the group (also backstopping a graceful shutdown\n // where the child ignores SIGTERM and the proxy exits before the\n // escalation lands). Fire-and-forget; self-acts and self-exits.\n startProcessGuard(child)\n\n let cleaned = false\n let exiting = false\n // The code this process intends to exit with, set the moment the caller\n // knows it (the child's own status, or the synthetic 130 for a signal).\n // The shutdown fail-safe reads it: a teardown that outruns its budget is\n // still a shutdown, and reporting `1` there turns a CLI that exited 0\n // into a reported failure. Observed for real on Windows, where Pi's\n // per-launch mirror carries an npm tree large enough that\n // `server.close` + `onShutdown` can cross the budget: Pi exited 0, the\n // proxy reported 1 exactly 5.10s later.\n let intendedExitCode: number | null = null\n async function cleanup(): Promise<void> {\n if (cleaned) return\n cleaned = true\n\n // Arm the hard fail-safe FIRST, before any (potentially blocking) kill\n // or async teardown, so a wedged taskkill / server.close can't hang\n // shutdown indefinitely. It bounds the teardown's TIME, not the\n // reported status, so it exits with the code the caller already chose.\n const timeout = setTimeout(() => exit(intendedExitCode ?? 1), 5000)\n\n // Tree-kill the whole CLI subtree, not just the direct child. On\n // Windows taskkill /T reaps grandchildren; on POSIX kill(-pgid) reaps\n // the detached process group. (Replaces a plain child.kill() that\n // orphaned node/MCP grandchildren on Windows.) A SIGTERM-ignoring\n // survivor that outlives our exit is caught by the crash guard above.\n try {\n killChildProcessTree(child, {\n detachedGroup: process.platform !== \"win32\",\n })\n } catch {\n // Already exited / best-effort.\n }\n\n try {\n await server.close(true)\n } catch {\n // Server already closed\n }\n if (options.onShutdown) {\n try {\n await options.onShutdown()\n } catch {\n // Best-effort cleanup; shutdown must not be blocked by it.\n }\n }\n clearTimeout(timeout)\n }\n\n function exit(code: number): void {\n if (exiting) return\n exiting = true\n try {\n const summary = options.onExitSummary?.()\n if (summary) process.stderr.write(`\\n${summary}\\n`)\n } catch {\n // Best-effort summary; never block shutdown.\n }\n process.exit(code)\n }\n\n // On POSIX the CLI is in its own process group (detached), so terminal\n // Ctrl-C reaches only the proxy. Forward the signal to the child group\n // so the CLI's own interactive handler runs (e.g. Claude's \"press\n // Ctrl-C again to exit\"); let its natural exit drive shutdown and\n // escalate to a hard tree-kill only if it ignores us past a grace.\n let forwardGrace: NodeJS.Timeout | null = null\n const lastForwardAt: Record<\"SIGINT\" | \"SIGTERM\", number> = {\n SIGINT: 0,\n SIGTERM: 0,\n }\n const onSignal = (sig: \"SIGINT\" | \"SIGTERM\") => {\n if (process.platform !== \"win32\" && child.pid && !cleaned) {\n // Debounce PER SIGNAL a sub-second burst into ONE forward. The other\n // subsystem signal handlers (keep-awake/colbert/worker/browser)\n // re-raise the SAME signal to restore default-terminate, which\n // re-invokes us several times within milliseconds — without this the\n // child would receive a volley and Claude's \"press Ctrl-C again\"\n // guard would never see a single press. Per-signal so a SIGTERM right\n // after a SIGINT still forwards. A genuine second human Ctrl-C\n // (seconds later) falls outside the window and forwards again.\n const now = Date.now()\n if (now - lastForwardAt[sig] > 250) {\n lastForwardAt[sig] = now\n try {\n process.kill(-child.pid, sig)\n } catch {\n // group already gone — fall through to the grace escalation\n }\n }\n const graceMs = sig === \"SIGINT\" ? 10000 : 3000\n if (!forwardGrace) {\n forwardGrace = setTimeout(() => {\n intendedExitCode = 130\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }, graceMs)\n forwardGrace.unref?.()\n }\n return\n }\n // Windows: the console already delivered Ctrl-C to the direct child;\n // cleanup()'s taskkill /T is the escalation hammer.\n intendedExitCode = 130\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }\n process.on(\"SIGINT\", () => onSignal(\"SIGINT\"))\n process.on(\"SIGTERM\", () => onSignal(\"SIGTERM\"))\n // Terminal resize has the same detached-group problem as Ctrl-C, with a\n // different consequence: the CLI's full-screen UI keeps drawing for the old\n // geometry and never reflows (see `forwardTerminalResize`). No debounce and no\n // grace — a resize is not a termination request, it is idempotent state, and\n // the winnable failure mode is a missed resize, not a doubled one.\n process.on(\"SIGWINCH\", () => {\n if (cleaned) return\n forwardTerminalResize(child.pid)\n })\n\n child.on(\"exit\", (exitCode, signal) => {\n // When the spawned CLI exits we may be holding worker-agent\n // worktrees that the proxy will never get a chance to clean up\n // through the per-call finally (the proxy itself is about to\n // shut down). Drain them synchronously here — same sweep the\n // SIGINT/SIGTERM handlers use. No-op if no worker tools were\n // ever invoked (registry is null).\n try {\n sweepRegistry()\n } catch {\n // best-effort; don't let cleanup failures override the exit code\n }\n // When killed by a signal, exitCode is null — derive from signal number\n const code = exitCode ?? (signal ? 128 : 1)\n intendedExitCode = code\n cleanup().then(() => exit(code)).catch(() => exit(1))\n })\n child.on(\"error\", () => {\n cleanup().then(() => exit(1)).catch(() => exit(1))\n })\n}\n","/**\n * Toolbelt provisioner: materialize curated CLI tools into the durable\n * router `bin/` dir so the spawned agent can call them on PATH.\n *\n * Properties (all load-bearing):\n * - **Best-effort.** Every tool is isolated in try/catch; a failure\n * skips that one tool and never throws to the launcher.\n * - **Gap-fill.** A tool already on the user's PATH is NOT\n * materialized (and a stale copy is removed) so we never shadow the\n * user's own `jq`/`yq`/etc.\n * - **Verified.** The downloaded archive's SHA256 must match the\n * hardcoded manifest digest BEFORE extraction.\n * - **Safe extraction.** Only the expected regular-file binary is\n * pulled out; symlink/hardlink/device entries are rejected.\n * - **Concurrency-safe.** A cross-process lock serializes writers;\n * unique temp names + atomic rename avoid half-written binaries.\n * - **Integrity-pruned.** Unexpected files in `bin/` are removed each\n * launch so a prompt-injected agent can't plant a `git.cmd` that\n * shadows real tools in future sessions.\n */\n\nimport { randomBytes, createHash } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport {\n chmod,\n copyFile,\n link,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { isWindowsScriptShim, resolveExecutable, runCommandCapture } from \"../exec\"\nimport { PATHS } from \"../paths\"\nimport { withInstallLock } from \"../update-lock\"\n\nimport { extractTarGzMember, extractZipMember } from \"./extract\"\nimport { toolbeltEnabled, toolbeltSkipSet, vscodeRipgrepPath } from \"./index\"\nimport { assetFor, satisfiesMinVersion, TOOLBELT_TOOLS, type ToolAsset, type ToolSpec } from \"./manifest\"\n\n/** Per-download cap (bytes) — these binaries are a few MB at most. */\nconst MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024\nconst DOWNLOAD_TIMEOUT_MS = 30_000\n\nconst EXE_EXT = process.platform === \"win32\" ? \".exe\" : \"\"\n\n/**\n * Materialize the toolbelt. Returns the list of command names exposed\n * in `bin/` after provisioning. Best-effort; never throws.\n */\nexport async function provisionToolbelt(): Promise<string[]> {\n if (!toolbeltEnabled()) return []\n const binDir = PATHS.TOOLBELT_BIN_DIR\n try {\n await mkdir(binDir, { recursive: true })\n } catch (err) {\n consola.debug(\"toolbelt: could not create bin dir:\", err)\n return []\n }\n\n const skip = toolbeltSkipSet()\n\n // Serialize across concurrent proxies. If another process holds the\n // lock it is provisioning; we skip and just report current state.\n await withInstallLock(\"toolbelt.lock\", async () => {\n await pruneUnexpected(binDir)\n await provisionRg(binDir, skip).catch((err) =>\n consola.debug(\"toolbelt: rg skipped:\", err),\n )\n await Promise.all(\n TOOLBELT_TOOLS.map((spec) =>\n provisionTool(spec, binDir, skip).catch((err) =>\n consola.debug(`toolbelt: ${spec.command} skipped:`, err),\n ),\n ),\n )\n })\n\n return exposedCommands(binDir)\n}\n\n/** Names allowed to live in `bin/` (managed binaries + their sidecars). */\nfunction expectedFileNames(): Set<string> {\n const names = new Set<string>()\n const add = (base: string) => {\n names.add(base + EXE_EXT)\n names.add(`${base}${EXE_EXT}.sha256`)\n }\n add(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n add(spec.binBasename)\n for (const a of spec.aliases ?? []) add(a)\n }\n return names\n}\n\n/** Remove any file in `bin/` that isn't a managed binary or sidecar. */\nasync function pruneUnexpected(binDir: string): Promise<void> {\n const expected = expectedFileNames()\n let entries: string[]\n try {\n entries = await readdir(binDir)\n } catch {\n return\n }\n for (const name of entries) {\n if (name.endsWith(\".tmp\")) continue // in-flight temp from a peer\n if (!expected.has(name)) {\n await rm(path.join(binDir, name), { force: true }).catch(() => {})\n }\n }\n}\n\nasync function provisionRg(binDir: string, skip: Set<string>): Promise<void> {\n const dest = path.join(binDir, \"rg\" + EXE_EXT)\n const pathRg = resolveExecutable(\"rg\")\n if (skip.has(\"rg\") || (pathRg && !isWindowsScriptShim(pathRg))) {\n // User has a LAUNCHABLE rg (or skipped) — don't shadow it. code_search\n // uses its own resolver regardless. A Windows `.cmd` shim does not count:\n // the toolbelt's consumers spawn with `shell:false`, which cannot launch\n // one, so yielding to it would materialize nothing and leave every caller\n // with an EINVAL.\n await removeBin(dest)\n return\n }\n if (existsSync(dest)) return // already materialized\n const src = vscodeRipgrepPath()\n if (!src) return\n\n const tmp = tempName(dest)\n try {\n await link(src, tmp) // hardlink (same-volume fast path)\n } catch {\n await copyFile(src, tmp) // cross-volume (EXDEV) or other → copy\n }\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/**\n * Does the user's own copy on PATH satisfy `spec.minVersion`?\n *\n * Returns true when there is nothing to check (no minVersion), and — this\n * is the load-bearing part — ALSO returns true when the probe fails or the\n * output cannot be parsed. Gap-fill exists so we never shadow a user's\n * pinned or wrapper install, and an unreadable `--version` is not evidence\n * that their tool is inadequate. We only step in front of it on positive\n * proof that it is too old.\n */\nasync function pathCopyIsAdequate(spec: ToolSpec, resolved: string): Promise<boolean> {\n if (!spec.minVersion) return true\n try {\n // `runCommandCapture`, NOT `runManagedExeCapture`: on Windows a tool\n // installed via npm resolves to a `.cmd` shim, which cannot be spawned\n // with `shell:false` (it throws EINVAL). That is exactly how the\n // ast-grep case presented — the probe threw, we treated the version as\n // unknown, and yielded to the outdated copy anyway. runCommandCapture\n // goes through buildExecInvocation, which routes shims via cmd.exe.\n const res = await runCommandCapture([resolved, \"--version\"], {\n timeoutMs: VERSION_PROBE_TIMEOUT_MS,\n })\n const verdict = satisfiesMinVersion(`${res.stdout} ${res.stderr}`, spec.minVersion)\n if (verdict === undefined) return true\n if (!verdict) {\n consola.debug(\n `[toolbelt] ${spec.command} on PATH is older than ${spec.minVersion}; using the router-pinned build instead`,\n )\n }\n return verdict\n } catch {\n return true\n }\n}\n\n/** A `--version` call should be instant; this only bounds a hung binary. */\nconst VERSION_PROBE_TIMEOUT_MS = 5_000\n\nasync function provisionTool(\n spec: ToolSpec,\n binDir: string,\n skip: Set<string>,\n): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n const sidecar = `${dest}.sha256`\n const asset = assetFor(spec)\n\n if (skip.has(spec.command) || !asset) {\n await removeTool(spec, binDir)\n return\n }\n // Gap-fill: user already has it on PATH → remove ours, don't shadow.\n // Exception: a tool carrying `minVersion` is one this project's own code\n // depends on, so an older PATH copy is not \"good enough\" — it degrades\n // us silently. In that case we materialize ours anyway; the toolbelt bin\n // is prepended to the spawned agent's PATH and code_search checks the\n // router-owned paths first, so ours wins where it matters while the\n // user's shell keeps theirs.\n const onPath = resolveExecutable(spec.command)\n // A Windows `.cmd`/`.bat` copy is never adequate, whatever version it\n // reports. `pathCopyIsAdequate` may find it new enough, because its probe\n // goes through `buildExecInvocation` and CAN read a shim; every consumer of\n // the materialized tools instead spawns with `shell:false`, and\n // CreateProcess refuses a script with EINVAL. The observed case was a\n // globally npm-installed ast-grep 0.45.3: it satisfied `minVersion`, we\n // yielded to it, and `mode:\"ast\"` could not launch at all on the canonical\n // Windows host. Materializing ours is safe — the toolbelt bin dir is\n // prepended for agents and code search consults the router-owned paths\n // first, so the user's own shell keeps its copy untouched.\n if (onPath && !isWindowsScriptShim(onPath) && (await pathCopyIsAdequate(spec, onPath))) {\n await removeTool(spec, binDir)\n return\n }\n // Idempotent: present + sidecar matches → just ensure aliases exist.\n if (existsSync(dest) && (await sidecarMatches(sidecar, asset.sha256))) {\n await ensureAliases(spec, binDir, dest)\n return\n }\n\n const bytes = await downloadAndExtract(spec, asset)\n await atomicInstall(dest, bytes)\n await writeFile(sidecar, asset.sha256).catch(() => {})\n await ensureAliases(spec, binDir, dest)\n}\n\nasync function downloadAndExtract(\n spec: ToolSpec,\n asset: ToolAsset,\n): Promise<Buffer> {\n const data = await download(asset.url)\n const digest = createHash(\"sha256\").update(data).digest(\"hex\")\n if (digest !== asset.sha256) {\n throw new Error(\n `checksum mismatch for ${spec.command} (${asset.url}): expected ${asset.sha256}, got ${digest}`,\n )\n }\n if (asset.archive === \"raw\") return data\n const member =\n asset.archive === \"zip\"\n ? extractZipMember(data, spec.binBasename)\n : extractTarGzMember(data, spec.binBasename)\n if (!member) {\n throw new Error(`binary \"${spec.binBasename}\" not found in ${asset.url}`)\n }\n return member\n}\n\nasync function download(url: string): Promise<Buffer> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n redirect: \"follow\",\n headers: { \"User-Agent\": \"github-router-toolbelt\" },\n })\n if (!res.ok) throw new Error(`download ${url}: HTTP ${res.status}`)\n const buf = Buffer.from(await res.arrayBuffer())\n if (buf.length > MAX_DOWNLOAD_BYTES) {\n throw new Error(`download ${url}: exceeds ${MAX_DOWNLOAD_BYTES} bytes`)\n }\n return buf\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Write to a unique temp then atomically rename into place. */\nasync function atomicInstall(dest: string, bytes: Buffer): Promise<void> {\n const tmp = tempName(dest)\n await writeFile(tmp, bytes)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/** Rename tmp→dest, handling Windows replace-existing / in-use locks. */\nasync function commit(tmp: string, dest: string): Promise<void> {\n try {\n await rename(tmp, dest)\n } catch {\n // Windows: rename won't replace an existing/locked dest. Remove and\n // retry once; if that fails (in-use .exe), leave the existing copy.\n try {\n await rm(dest, { force: true })\n await rename(tmp, dest)\n } catch (err) {\n await rm(tmp, { force: true }).catch(() => {})\n throw err\n }\n }\n}\n\nasync function ensureAliases(\n spec: ToolSpec,\n binDir: string,\n dest: string,\n): Promise<void> {\n for (const alias of spec.aliases ?? []) {\n const ap = path.join(binDir, alias + EXE_EXT)\n if (existsSync(ap)) continue\n const tmp = tempName(ap)\n try {\n await copyFile(dest, tmp)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, ap)\n } catch (err) {\n consola.debug(`toolbelt: alias ${alias} skipped:`, err)\n }\n }\n}\n\nasync function removeTool(spec: ToolSpec, binDir: string): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n await removeBin(dest)\n for (const alias of spec.aliases ?? []) {\n await removeBin(path.join(binDir, alias + EXE_EXT))\n }\n}\n\nasync function removeBin(dest: string): Promise<void> {\n await rm(dest, { force: true }).catch(() => {})\n await rm(`${dest}.sha256`, { force: true }).catch(() => {})\n}\n\nasync function sidecarMatches(sidecar: string, sha256: string): Promise<boolean> {\n try {\n return (await readFile(sidecar, \"utf8\")).trim() === sha256\n } catch {\n return false\n }\n}\n\nfunction tempName(dest: string): string {\n return `${dest}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n}\n\n/** The command names currently exposed in `bin/`. */\nasync function exposedCommands(binDir: string): Promise<string[]> {\n let files: Set<string>\n try {\n files = new Set(await readdir(binDir))\n } catch {\n return []\n }\n const present = (base: string) => files.has(base + EXE_EXT)\n const out: string[] = []\n if (present(\"rg\")) out.push(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n if (present(spec.binBasename)) out.push(spec.command)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,iCAAiB,IAAI,IAAkB;;AAG7C,SAAgB,sBAA+B;CAC7C,OAAO,aAAa,QAAQ,IAAI,+BAA+B,MAAM;AACvE;;;;;;;;;AAUA,SAAgB,sBACd,KACA,eACQ;CACR,MAAM,SAAS,gBAAgB,SAAS;CACxC,OAAO;;;cAGK,QAAQ,EAAE;;;;;;;;;;;;;;;uBAeD,OAAO;;;0CAGY,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;EAyB/C,KAAK;AACP;;;;;;AAOA,SAAS,gBAAgB,KAAa,eAA6C;CACjF,IAAI;EACF,MAAM,QAAQ,MACZ,QAAQ,UACR,CAAC,MAAM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AAM,SAAS,KAAK,WAAW,CAAC,GACnC,MAAM,UAAU,KAAK,KAAK,QAAQ,QAAQ,OAAO,CAAC;AAEtD;AAEA,eAAe,UAAU,MAA6B;CACpD,MAAM,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CAC9C,MAAM,GAAG,GAAG,KAAK,UAAU,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;AAC5D;AAEA,eAAe,eAAe,SAAiB,QAAkC;CAC/E,IAAI;EACF,QAAQ,MAAM,SAAS,SAAS,MAAM,EAAA,CAAG,KAAK,MAAM;CACtD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,SAAS,MAAsB;CACtC,OAAO,GAAG,KAAK,GAAG,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;AAClE;;AAGA,eAAe,gBAAgB,QAAmC;CAChE,IAAI;CACJ,IAAI;EACF,QAAQ,IAAI,IAAI,MAAM,QAAQ,MAAM,CAAC;CACvC,QAAQ;EACN,OAAO,CAAC;CACV;CACA,MAAM,WAAW,SAAiB,MAAM,IAAI,OAAO,OAAO;CAC1D,MAAM,MAAgB,CAAC;CACvB,IAAI,QAAQ,IAAI,GAAG,IAAI,KAAK,IAAI;CAChC,KAAK,MAAM,QAAQ,gBACjB,IAAI,QAAQ,KAAK,WAAW,GAAG,IAAI,KAAK,KAAK,OAAO;CAEtD,OAAO;AACT"}
1
+ {"version":3,"file":"provision-DPL8aGe2.js","names":[],"sources":["../src/lib/process-guard/index.ts","../src/lib/stripped-env-keys.ts","../src/lib/launch.ts","../src/lib/toolbelt/provision.ts"],"sourcesContent":["/**\n * Crash-safe process guard (POSIX only).\n *\n * If the proxy dies WITHOUT running its own shutdown handlers (hard crash,\n * SIGKILL, OOM), nothing in `cleanup()` runs to reap the launched CLI's\n * process tree. This guard is the last-resort net for that case.\n *\n * Platform split:\n * - **Windows: no guard needed.** Node assigns each child to a Job\n * Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so when the proxy\n * dies (any cause) the OS tears down the whole descendant tree —\n * verified: force-killing a Node parent kills child AND grandchild.\n * `startProcessGuard` is a no-op on win32.\n * - **POSIX: a detached `node -e` reaper.** There is no job-object\n * equivalent (a killed parent's children reparent to init), so we\n * spawn a detached watchdog that learns of proxy death via an inherited\n * stdin PIPE EOF (the proxy holds the write end; the OS closes it on\n * proxy death) and reaps the CLI's process group.\n *\n * Never kill the WRONG process: if the child's PID/PGID was recycled after\n * the child exited, a blind `kill(-pid)` could hit an innocent group. The\n * reaper snapshots the child's process start-time at startup and, on proxy\n * death, kills ONLY if the live PID's start-time still matches. A mismatch\n * / unreadable probe → skip (fail-safe). We never trade an orphan-leak for\n * killing the user's work.\n *\n * The reaper is detached + unref'd so it survives the proxy's SIGKILL, and\n * self-exits once it has acted (or after a 24h cap) so it can never become\n * the orphan it exists to prevent. Opt out with\n * `GH_ROUTER_DISABLE_PROCESS_GUARD=1`.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\"\nimport process from \"node:process\"\n\nimport { parseBoolEnv } from \"../exec\"\n\n/**\n * Live reaper children, held so the GC can't collect the `ChildProcess`\n * (and with it the stdin write-end that is the proxy-death signal) while\n * the proxy runs. Entries self-remove on the reaper's exit. We do NOT\n * proactively kill these on graceful shutdown: when the proxy exits the OS\n * closes the stdin pipe, the reaper hits EOF, re-verifies the child's\n * identity, and reaps any survivor that ignored the graceful SIGTERM —\n * exactly the backstop we want.\n */\nconst _activeReapers = new Set<ChildProcess>()\n\n/** Guard is on by default; `GH_ROUTER_DISABLE_PROCESS_GUARD=1` opts out. */\nexport function processGuardEnabled(): boolean {\n return parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROCESS_GUARD) !== true\n}\n\n/**\n * Build the start-time-verified node reaper script (POSIX). PURE — `pid`\n * is our own integer. `detachedGroup` selects `kill(-pid)` (process group,\n * the detached CLI) vs `kill(pid)` on POSIX.\n *\n * Kept dependency-free (require'd builtins only) so it runs under `node -e`\n * with no module resolution against the dist bundle.\n */\nexport function buildNodeReaperScript(\n pid: number,\n detachedGroup: boolean,\n): string {\n const target = detachedGroup ? \"-PID\" : \"PID\"\n return `\nconst cp = require(\"node:child_process\");\nconst fs = require(\"node:fs\");\nconst PID = ${pid >>> 0};\nfunction startTime() {\n try {\n if (process.platform === \"linux\") {\n const stat = fs.readFileSync(\"/proc/\" + PID + \"/stat\", \"utf8\");\n const post = stat.slice(stat.lastIndexOf(\")\") + 1).trim().split(/\\\\s+/);\n return post[19] || null; // field 22 (starttime) = index 19 after comm\n }\n const out = cp.execFileSync(\"ps\", [\"-o\",\"lstart=\",\"-p\",String(PID)],\n { stdio: [\"ignore\",\"pipe\",\"ignore\"], timeout: 2000 }).toString().trim();\n return out || null;\n } catch { return null; }\n}\nfunction alive() { try { process.kill(PID, 0); return true; } catch { return false; } }\nfunction treeKill() {\n try { process.kill(${target}, \"SIGTERM\"); } catch {}\n // NOT unref'd: this must keep the loop alive to deliver the escalated\n // SIGKILL (the onDeath exit timer below stays alive past 500ms too).\n setTimeout(() => { try { process.kill(${target}, \"SIGKILL\"); } catch {} }, 500);\n}\nconst snap = (() => {\n // The child is definitely ours and alive at startup, so a null here is a\n // transient probe failure (e.g. a momentary 'ps' hiccup), NOT a real\n // identity loss. Retry a few times so a one-off failure can't silently\n // disable the guard for the rest of the run.\n for (let i = 0; i < 3; i++) { const s = startTime(); if (s !== null) return s; }\n return null;\n})();\nlet done = false;\nfunction onDeath() {\n if (done) return; done = true;\n // Re-verify identity: kill ONLY if the live PID is still our child.\n if (snap !== null && alive() && startTime() === snap) treeKill();\n // REF'd (NOT unref'd): stdin has closed, so an unref'd timer would let\n // the loop empty and the process exit immediately — dropping the 500ms\n // SIGKILL escalation. Keep the loop alive to deliver it, then exit.\n setTimeout(() => process.exit(0), 1500);\n}\nprocess.stdin.resume();\nprocess.stdin.on(\"end\", onDeath);\nprocess.stdin.on(\"close\", onDeath);\nprocess.stdin.on(\"error\", onDeath);\nconst cap = setTimeout(() => process.exit(0), 24*3600*1000); if (cap.unref) cap.unref();\n`.trim()\n}\n\n/**\n * Spawn the detached node reaper holding the stdin death-pipe. Always\n * `detached` so it outlives a force-kill of the proxy, and `unref`'d so it\n * never holds the proxy's event loop open. Returns null on spawn failure.\n */\nfunction spawnNodeReaper(pid: number, detachedGroup: boolean): ChildProcess | null {\n try {\n const child = spawn(\n process.execPath,\n [\"-e\", buildNodeReaperScript(pid, detachedGroup)],\n {\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n detached: true,\n windowsHide: true,\n shell: false,\n },\n )\n child.on(\"error\", () => {})\n child.stdin?.on(\"error\", () => {})\n // Hold a reference so the GC can't drop the ChildProcess (and its stdin\n // write-end, the proxy-death signal) mid-run; drop it on reaper exit.\n _activeReapers.add(child)\n child.once(\"exit\", () => _activeReapers.delete(child))\n child.unref()\n return child\n } catch {\n return null\n }\n}\n\n/**\n * Start the crash-safe guard for a launched CLI child. No-op on Windows\n * (Node's Job Object already reaps the tree on proxy death) and when\n * disabled / unspawnable. Fire-and-forget; never throws.\n */\nexport function startProcessGuard(child: ChildProcess): void {\n if (!processGuardEnabled()) return\n const pid = child.pid\n if (!pid) return\n // Windows: the runtime's KILL_ON_JOB_CLOSE job object is the crash net.\n if (process.platform === \"win32\") return\n // POSIX: the CLI is spawned detached (own group), so reap the group.\n spawnNodeReaper(pid, true)\n}\n","/**\n * Auth / routing / remote / wire-fingerprint environment keys that must never\n * reach a github-router-spawned Claude or Codex child — through ANY channel.\n *\n * Two channels carry these keys to a spawned agent, and both must be defended:\n * 1. The PARENT PROCESS ENV — a user's shell exports. Stripped by\n * `sanitizeParentEnv` (`src/lib/launch.ts`) before the proxy's overrides.\n * 2. The serve mirror `settings.json` `env` BLOCK — a user's own\n * `~/.claude/settings.json`, snapshot-mirrored and applied to the\n * SDK-spawned claude via `settingSources`. Stripped by\n * `sanitizeServeSettingsEnv` (`src/lib/mcp-permissions-settings.ts`).\n *\n * If any of these survived, a Bedrock/Vertex/gateway user's config would\n * re-route the session OFF the github-router proxy, inject real auth that wins\n * over the synthetic `.credentials.json`, or activate Claude Code's\n * unimplemented Bridge/remote code path. `CLAUDE_CODE_COORDINATOR_MODE` (a\n * toolset-stripper) is NOT here — it's serve-specific, added to the serve list\n * directly. `ANTHROPIC_SMALL_FAST_MODEL` is deliberately NOT stripped (users\n * legitimately rely on it; `resolveModel` translates unrecognized values).\n */\nexport const STRIPPED_AUTH_ROUTING_ENV_KEYS = [\n // Claude Code auth surface\n \"ANTHROPIC_API_KEY\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_BASE_URL\",\n \"ANTHROPIC_CUSTOM_HEADERS\",\n \"ANTHROPIC_MODEL\",\n \"CLAUDE_CODE_OAUTH_TOKEN\",\n // Alternate OAuth source (loads from an open file descriptor); stripping\n // prevents a third auth source alongside the synthetic .credentials.json.\n \"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR\",\n \"CLAUDE_CODE_USE_BEDROCK\",\n \"CLAUDE_CODE_USE_VERTEX\",\n \"CLAUDE_CODE_USE_FOUNDRY\",\n // Defense-in-depth: a parent- or settings-set CLAUDE_CONFIG_DIR would\n // redirect the session's config dir away from the router-owned mirror.\n \"CLAUDE_CONFIG_DIR\",\n // Claude Code Bridge / IDE remote-session surface — activates a remote code\n // path (POST /v1/code/sessions, /v1/environments/bridge, …) the proxy does\n // not implement. Stripping forces a local-only session.\n \"CLAUDE_BRIDGE_OAUTH_TOKEN\",\n \"CLAUDE_BRIDGE_BASE_URL\",\n \"CLAUDE_BRIDGE_SESSION_INGRESS_URL\",\n \"SESSION_INGRESS_URL\",\n \"CLAUDE_CODE_REMOTE\",\n \"CLAUDE_CODE_CONTAINER_ID\",\n \"CLAUDE_CODE_REMOTE_SESSION_ID\",\n \"CLAUDE_CODE_SESSION_ID\",\n // Emits `x-anthropic-additional-protection` — pure wire-fingerprint noise\n // that breaks the VS Code stealth posture.\n \"CLAUDE_CODE_ADDITIONAL_PROTECTION\",\n // Optional Bluebird MCP bearer override. The router may consume it, but the\n // spawned CLI and its descendant tools/MCPs must never inherit it.\n \"BLUEBIRD_TOKEN\",\n // Azure DevOps remote MCP bearer override. Same rule as BLUEBIRD_TOKEN:\n // the router may consume it, the spawned CLI and every tool/MCP under it\n // must never see it.\n \"ADO_MCP_TOKEN\",\n // Kusto (Azure Data Explorer) bearer override. Same rule.\n \"KUSTO_TOKEN\",\n // Cloud Agent Job API v2 bearer override. Same rule, and it matters more\n // here than anywhere else on this list: the Cloud Agent group can launch a\n // cloud agent that spends compute, so a bearer inherited by a spawned\n // CLI or one of its MCPs would be both a credential leak and a\n // capability leak.\n \"GH_ROUTER_CLOUDAGENT_TOKEN\",\n // Work IQ hosted MCP bearer override. The group reads the signed-in user's\n // entire Microsoft 365 estate, so a spawned CLI or one of its MCPs must never\n // inherit the credential that reaches it.\n \"WORKIQ_MCP_TOKEN\",\n // Codex CLI auth surface\n \"OPENAI_API_KEY\",\n \"OPENAI_BASE_URL\",\n \"CODEX_HOME\",\n // Pi coding-agent routing/auth surface. `PI_CODING_AGENT_DIR` would\n // redirect the session's agent dir away from the router-owned mirror;\n // provider keys would re-route Pi off the proxy or leak real auth.\n \"PI_CODING_AGENT_DIR\",\n \"PI_CODING_AGENT_SESSION_DIR\",\n \"OPENCODE_API_KEY\",\n // ai-or-die per-tab session-bind / artifact-review surface — must not leak\n // into a nested launch and hijack the parent tab's sidecar / bearer token.\n \"AIORDIE_CLAUDE_BIND\",\n \"AIORDIE_TOKEN\",\n \"AIORDIE_INSECURE_TLS\",\n] as const\n","import { execFileSync, spawn, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport type { Server } from \"srvx\"\n\nimport { resolveExecutable, killChildProcessTree } from \"./exec\"\nimport { DEFAULT_CODEX_MODEL } from \"./port\"\nimport { startProcessGuard } from \"./process-guard\"\nimport { STRIPPED_AUTH_ROUTING_ENV_KEYS } from \"./stripped-env-keys\"\nimport { collapsePathKeys } from \"./toolbelt/path-inject\"\nimport { sweepRegistry } from \"./worker-agent/lifecycle\"\n\n/**\n * Auth-related env keys we strip from the parent before spawning the child CLI.\n * The proxy provides its own values for everything we care about, so the child\n * behaves as if the user had no parent-env auth at all. The canonical list lives\n * in `./stripped-env-keys` (shared with serve's settings.json `env` strip).\n *\n * Why strip rather than override-with-empty-string: Claude Code emits \"Auth\n * conflict\" warnings whenever both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY\n * are present (any value); stripping suppresses it AND prevents an inherited\n * real key from leaking. Cloud-provider toggles + OAuth tokens are simpler\n * dropped than overridden — a missing var is unambiguously absent everywhere.\n */\nconst STRIPPED_PARENT_ENV_KEYS = STRIPPED_AUTH_ROUTING_ENV_KEYS\n\n/**\n * Strip auth-related keys from a parent-process env object. The result\n * is suitable to spread into a spawned child's env BEFORE the proxy's\n * explicit overrides, so the proxy is the only source of truth for\n * auth — and stale shell exports can't leak through.\n */\nexport function sanitizeParentEnv(\n parent: NodeJS.ProcessEnv,\n): NodeJS.ProcessEnv {\n const sanitized: NodeJS.ProcessEnv = { ...parent }\n for (const key of STRIPPED_PARENT_ENV_KEYS) {\n delete sanitized[key]\n }\n return sanitized\n}\n\nfunction commandExists(name: string): boolean {\n try {\n execFileSync(process.platform === \"win32\" ? \"where.exe\" : \"which\", [name], {\n stdio: \"ignore\",\n })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Whether the launcher can execute `executable`.\n *\n * `buildLaunchCommand` resolves the CLI to an ABSOLUTE path (anti-shadow).\n * `where.exe` (and POSIX `which`) reject a full path argument — `where`\n * returns \"Could not find files for the given pattern(s)\" for an absolute\n * path even when the file exists — so the where/which probe is only valid\n * for bare command names. For an absolute path (already resolved against\n * PATH and existence-checked by `resolveExecutable`), check the\n * filesystem directly. Without this split, every launch where the CLI is\n * installed fails with a spurious \"not found on PATH\".\n */\nexport function isExecutableAvailable(executable: string): boolean {\n if (path.isAbsolute(executable)) return existsSync(executable)\n return commandExists(executable)\n}\n\n/**\n * Provider-config flags (`-c model_providers.github_router=...`) that\n * point Codex at our proxy. Extracted from `buildCodexCmd` so the new\n * `codex mcp-server` MCP-config builder can reuse the exact same\n * provider definition — drift between the two paths would silently\n * break the MCP wiring.\n */\nexport function buildCodexProviderConfigFlags(serverUrl: string): Array<string> {\n return [\n \"-c\",\n `model_providers.github_router={name=\"github-router\",base_url=\"${serverUrl}/v1\",wire_api=\"responses\",env_key=\"OPENAI_API_KEY\"}`,\n \"-c\",\n \"model_provider=github_router\",\n ]\n}\n\n/**\n * Inspect the installed `codex` binary. Used by the codex-MCP wiring\n * in `claude.ts` to gate `--codex-cli`. Codex 0.129.0 introduced the\n * `mcp-server` subcommand; older versions don't expose it, so we\n * downgrade to the HTTP backend with a warning.\n */\nexport function getCodexVersion(): { ok: boolean; version?: string } {\n if (!commandExists(\"codex\")) return { ok: false }\n let raw: string\n try {\n raw = execFileSync(\"codex\", [\"--version\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim()\n } catch {\n return { ok: false }\n }\n // Output examples: \"codex-cli 0.129.0\", \"codex 0.130.1-dev\"\n const m = /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(raw)\n if (!m) return { ok: false, version: raw }\n const major = Number.parseInt(m[1], 10)\n const minor = Number.parseInt(m[2], 10)\n const version = `${m[1]}.${m[2]}.${m[3]}`\n // mcp-server requires codex >= 0.129.0\n const ok = major > 0 || (major === 0 && minor >= 129)\n return { ok, version }\n}\n\nexport interface LaunchTarget {\n kind: \"claude-code\" | \"codex\" | \"pi\"\n envVars: Record<string, string>\n extraArgs: string[]\n model?: string\n /**\n * Proxy URL the spawned child should target. Required for Codex 0.129+\n * which stopped honoring OPENAI_BASE_URL and now needs an explicit\n * `-c model_providers.<name>.base_url=...` argument. Set by the codex\n * subcommand from the same `serverUrl` it computed for env vars.\n */\n serverUrl?: string\n}\n\n/**\n * Codex 0.129.0 broke two things the launcher had been relying on:\n * (1) `--full-auto` was removed in favor of `--sandbox` + `--ask-for-approval`;\n * passing it now exits the child immediately with\n * `error: unexpected argument '--full-auto' found`.\n * (2) `OPENAI_BASE_URL` is silently ignored — Codex hardcodes\n * `https://api.openai.com/v1/responses` and 401s out without an\n * explicit `-c model_providers.<name>.base_url` override.\n *\n * `buildCodexCmd` builds the launch argv that works on Codex 0.129+ while\n * still being compatible with older versions that accept the same flags.\n */\nfunction buildCodexCmd(target: LaunchTarget): string[] {\n const cmd: string[] = [\"codex\"]\n if (target.serverUrl) {\n cmd.push(...buildCodexProviderConfigFlags(target.serverUrl))\n }\n cmd.push(\n \"--sandbox\",\n \"workspace-write\",\n \"--ask-for-approval\",\n \"on-request\",\n \"-m\",\n target.model ?? DEFAULT_CODEX_MODEL,\n ...target.extraArgs,\n )\n return cmd\n}\n\nexport function buildLaunchCommand(target: LaunchTarget): {\n cmd: string[]\n env: Record<string, string | undefined>\n} {\n // F10: don't force `--dangerously-skip-permissions` when the caller already\n // requested an explicit `--permission-mode` (e.g. ai-or-die's claude-bridge\n // appends one for a fleet create_session with permissionMode). The two flags\n // conflict — claude rejects them together — and the explicit mode must win.\n const wantsPermissionMode =\n target.kind === \"claude-code\" &&\n target.extraArgs.some((arg) => arg === \"--permission-mode\" || arg.startsWith(\"--permission-mode=\"))\n const cmd: string[] =\n target.kind === \"claude-code\"\n ? wantsPermissionMode\n ? [\"claude\", ...target.extraArgs]\n : [\"claude\", \"--dangerously-skip-permissions\", ...target.extraArgs]\n : target.kind === \"pi\"\n ? [\n \"pi\",\n \"--provider\",\n \"gh-router\",\n ...(target.model ? [\"--model\", target.model] : []),\n ...target.extraArgs,\n ]\n : buildCodexCmd(target)\n\n // Anti-shadow: resolve the top-level CLI to an ABSOLUTE path against\n // the clean parent PATH (excluding the cwd). The spawned child's env\n // prepends the toolbelt bin dir to PATH; without this, a stray\n // `claude.cmd`/`codex.cmd` in that dir — or in an untrusted repo's cwd\n // (Windows resolves cwd before PATH under shell:true) — could shadow\n // the real CLI. Resolving here means the toolbelt PATH only affects\n // the agent's OWN tool lookups, never which CLI we launch.\n const resolved = resolveExecutable(cmd[0], { env: process.env })\n if (resolved) cmd[0] = resolved\n\n const env = collapsePathKeys({\n ...sanitizeParentEnv(process.env),\n ...target.envVars,\n })\n return { cmd, env }\n}\n\n/**\n * Whether a resolved Windows executable must be launched through cmd.exe\n * (`shell:true`). Only batch shims (`.cmd`/`.bat`) need it — and even then\n * cmd.exe stays alive as the CLI's parent, so `taskkill /T` reaps the\n * whole tree. A real `.exe` (e.g. the native-installer `claude.exe`) is\n * spawned DIRECTLY so the CLI is the direct child, with no cmd.exe\n * intermediary to orphan its node/MCP grandchildren on a kill.\n */\nexport function windowsLaunchNeedsShell(executable: string): boolean {\n const ext = path.extname(executable).toLowerCase()\n return ext === \".cmd\" || ext === \".bat\"\n}\n\n/**\n * Forward a terminal resize to the detached child's process group.\n *\n * The kernel delivers `SIGWINCH` only to the FOREGROUND PROCESS GROUP of the\n * controlling terminal. The launcher spawns the CLI with POSIX `detached: true`\n * (so `kill(-pid)` can reap the whole subtree), which puts the CLI in its own\n * group — that group is never the terminal's foreground, so the CLI would never\n * learn that the window changed and would keep laying out for the old geometry.\n * Re-broadcasting the signal the launcher itself receives is the whole fix.\n *\n * Returns whether a signal was sent, which is all a test can observe without a\n * pty (the delivery path is kernel-side and is proven separately by a `pty.fork`\n * harness: an attached child gets `SIGWINCH`, a detached one gets nothing, and\n * `kill(-pid, \"SIGWINCH\")` delivers it).\n *\n * Windows has no `SIGWINCH` and no process groups; the console resizes the\n * child directly, so the guard is a hard `return`, not a fallback.\n */\nexport function forwardTerminalResize(pid: number | undefined): boolean {\n if (process.platform === \"win32\" || !pid) return false\n try {\n process.kill(-pid, \"SIGWINCH\")\n return true\n } catch {\n // group already gone, or signalling is refused in this sandbox\n return false\n }\n}\n\nexport function launchChild(\n target: LaunchTarget,\n server: Server,\n options: {\n onShutdown?: () => Promise<void> | void\n /**\n * Optional exit summary (e.g. the AIC session total). Called once from\n * `exit()`, after cleanup, on every shutdown path (natural child exit,\n * signal escalation, spawn error). Return undefined for no output.\n * Best-effort: throwing content is swallowed so shutdown never blocks.\n */\n onExitSummary?: () => string | undefined\n } = {},\n): void {\n const { cmd, env } = buildLaunchCommand(target)\n\n const executable = cmd[0]\n if (!isExecutableAvailable(executable)) {\n const msg = `\"${executable}\" not found on PATH. Install it first, then try again.`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n process.exit(1)\n }\n\n let child: ChildProcess\n try {\n if (process.platform === \"win32\") {\n if (windowsLaunchNeedsShell(cmd[0])) {\n // A batch shim genuinely needs cmd.exe. cmd.exe stays alive as the\n // CLI's parent for the shim's lifetime, so the tree-kill (taskkill\n // /T) and the crash guard both reap the whole tree through it. Use\n // the full command as a single string to avoid the DEP0190\n // deprecation warning about shell + args.\n const quoted = cmd.map((a) => (a.includes(\" \") ? `\"${a}\"` : a)).join(\" \")\n child = spawn(quoted, [], {\n env,\n stdio: \"inherit\",\n shell: true,\n })\n } else {\n // A real .exe (e.g. the native-installer claude.exe) needs no\n // shell. Spawning it directly makes the CLI the DIRECT child, so\n // child.kill()/taskkill and the crash guard target the real\n // process instead of a cmd.exe wrapper that would orphan its\n // node/MCP grandchildren.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n })\n }\n } else {\n // detached:true → the CLI leads its OWN process group, so cleanup()\n // can kill(-pgid) the whole tree (grandchildren included). We still\n // await its exit, so we do NOT unref(). Terminal Ctrl-C no longer\n // reaches the child directly — the signal handlers below forward it.\n child = spawn(cmd[0], cmd.slice(1), {\n env,\n stdio: \"inherit\",\n detached: true,\n })\n }\n } catch (error) {\n const msg = `Failed to launch ${executable}: ${error instanceof Error ? error.message : String(error)}`\n consola.error(msg)\n process.stderr.write(msg + \"\\n\")\n server.close(true).catch(() => {})\n if (options.onShutdown) {\n void Promise.resolve(options.onShutdown()).catch(() => {})\n }\n process.exit(1)\n }\n\n // Crash-safe net: if the proxy dies WITHOUT running cleanup() (hard\n // crash, SIGKILL/taskkill, OOM). On Windows this is the OS's job —\n // Node's KILL_ON_JOB_CLOSE job object reaps the tree — so this is a\n // no-op there. On POSIX (no such mechanism) it spawns a detached reaper\n // that sees the proxy's stdin-pipe EOF, re-verifies the child's\n // identity, and reaps the group (also backstopping a graceful shutdown\n // where the child ignores SIGTERM and the proxy exits before the\n // escalation lands). Fire-and-forget; self-acts and self-exits.\n startProcessGuard(child)\n\n let cleaned = false\n let exiting = false\n // The code this process intends to exit with, set the moment the caller\n // knows it (the child's own status, or the synthetic 130 for a signal).\n // The shutdown fail-safe reads it: a teardown that outruns its budget is\n // still a shutdown, and reporting `1` there turns a CLI that exited 0\n // into a reported failure. Observed for real on Windows, where Pi's\n // per-launch mirror carries an npm tree large enough that\n // `server.close` + `onShutdown` can cross the budget: Pi exited 0, the\n // proxy reported 1 exactly 5.10s later.\n let intendedExitCode: number | null = null\n async function cleanup(): Promise<void> {\n if (cleaned) return\n cleaned = true\n\n // Arm the hard fail-safe FIRST, before any (potentially blocking) kill\n // or async teardown, so a wedged taskkill / server.close can't hang\n // shutdown indefinitely. It bounds the teardown's TIME, not the\n // reported status, so it exits with the code the caller already chose.\n const timeout = setTimeout(() => exit(intendedExitCode ?? 1), 5000)\n\n // Tree-kill the whole CLI subtree, not just the direct child. On\n // Windows taskkill /T reaps grandchildren; on POSIX kill(-pgid) reaps\n // the detached process group. (Replaces a plain child.kill() that\n // orphaned node/MCP grandchildren on Windows.) A SIGTERM-ignoring\n // survivor that outlives our exit is caught by the crash guard above.\n try {\n killChildProcessTree(child, {\n detachedGroup: process.platform !== \"win32\",\n })\n } catch {\n // Already exited / best-effort.\n }\n\n try {\n await server.close(true)\n } catch {\n // Server already closed\n }\n if (options.onShutdown) {\n try {\n await options.onShutdown()\n } catch {\n // Best-effort cleanup; shutdown must not be blocked by it.\n }\n }\n clearTimeout(timeout)\n }\n\n function exit(code: number): void {\n if (exiting) return\n exiting = true\n try {\n const summary = options.onExitSummary?.()\n if (summary) process.stderr.write(`\\n${summary}\\n`)\n } catch {\n // Best-effort summary; never block shutdown.\n }\n process.exit(code)\n }\n\n // On POSIX the CLI is in its own process group (detached), so terminal\n // Ctrl-C reaches only the proxy. Forward the signal to the child group\n // so the CLI's own interactive handler runs (e.g. Claude's \"press\n // Ctrl-C again to exit\"); let its natural exit drive shutdown and\n // escalate to a hard tree-kill only if it ignores us past a grace.\n let forwardGrace: NodeJS.Timeout | null = null\n const lastForwardAt: Record<\"SIGINT\" | \"SIGTERM\", number> = {\n SIGINT: 0,\n SIGTERM: 0,\n }\n const onSignal = (sig: \"SIGINT\" | \"SIGTERM\") => {\n if (process.platform !== \"win32\" && child.pid && !cleaned) {\n // Debounce PER SIGNAL a sub-second burst into ONE forward. The other\n // subsystem signal handlers (keep-awake/colbert/worker/browser)\n // re-raise the SAME signal to restore default-terminate, which\n // re-invokes us several times within milliseconds — without this the\n // child would receive a volley and Claude's \"press Ctrl-C again\"\n // guard would never see a single press. Per-signal so a SIGTERM right\n // after a SIGINT still forwards. A genuine second human Ctrl-C\n // (seconds later) falls outside the window and forwards again.\n const now = Date.now()\n if (now - lastForwardAt[sig] > 250) {\n lastForwardAt[sig] = now\n try {\n process.kill(-child.pid, sig)\n } catch {\n // group already gone — fall through to the grace escalation\n }\n }\n const graceMs = sig === \"SIGINT\" ? 10000 : 3000\n if (!forwardGrace) {\n forwardGrace = setTimeout(() => {\n intendedExitCode = 130\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }, graceMs)\n forwardGrace.unref?.()\n }\n return\n }\n // Windows: the console already delivered Ctrl-C to the direct child;\n // cleanup()'s taskkill /T is the escalation hammer.\n intendedExitCode = 130\n cleanup().then(() => exit(130)).catch(() => exit(1))\n }\n process.on(\"SIGINT\", () => onSignal(\"SIGINT\"))\n process.on(\"SIGTERM\", () => onSignal(\"SIGTERM\"))\n // Terminal resize has the same detached-group problem as Ctrl-C, with a\n // different consequence: the CLI's full-screen UI keeps drawing for the old\n // geometry and never reflows (see `forwardTerminalResize`). No debounce and no\n // grace — a resize is not a termination request, it is idempotent state, and\n // the winnable failure mode is a missed resize, not a doubled one.\n process.on(\"SIGWINCH\", () => {\n if (cleaned) return\n forwardTerminalResize(child.pid)\n })\n\n child.on(\"exit\", (exitCode, signal) => {\n // When the spawned CLI exits we may be holding worker-agent\n // worktrees that the proxy will never get a chance to clean up\n // through the per-call finally (the proxy itself is about to\n // shut down). Drain them synchronously here — same sweep the\n // SIGINT/SIGTERM handlers use. No-op if no worker tools were\n // ever invoked (registry is null).\n try {\n sweepRegistry()\n } catch {\n // best-effort; don't let cleanup failures override the exit code\n }\n // When killed by a signal, exitCode is null — derive from signal number\n const code = exitCode ?? (signal ? 128 : 1)\n intendedExitCode = code\n cleanup().then(() => exit(code)).catch(() => exit(1))\n })\n child.on(\"error\", () => {\n cleanup().then(() => exit(1)).catch(() => exit(1))\n })\n}\n","/**\n * Toolbelt provisioner: materialize curated CLI tools into the durable\n * router `bin/` dir so the spawned agent can call them on PATH.\n *\n * Properties (all load-bearing):\n * - **Best-effort.** Every tool is isolated in try/catch; a failure\n * skips that one tool and never throws to the launcher.\n * - **Gap-fill.** A tool already on the user's PATH is NOT\n * materialized (and a stale copy is removed) so we never shadow the\n * user's own `jq`/`yq`/etc.\n * - **Verified.** The downloaded archive's SHA256 must match the\n * hardcoded manifest digest BEFORE extraction.\n * - **Safe extraction.** Only the expected regular-file binary is\n * pulled out; symlink/hardlink/device entries are rejected.\n * - **Concurrency-safe.** A cross-process lock serializes writers;\n * unique temp names + atomic rename avoid half-written binaries.\n * - **Integrity-pruned.** Unexpected files in `bin/` are removed each\n * launch so a prompt-injected agent can't plant a `git.cmd` that\n * shadows real tools in future sessions.\n */\n\nimport { randomBytes, createHash } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport {\n chmod,\n copyFile,\n link,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { isWindowsScriptShim, resolveExecutable, runCommandCapture } from \"../exec\"\nimport { PATHS } from \"../paths\"\nimport { withInstallLock } from \"../update-lock\"\n\nimport { extractTarGzMember, extractZipMember } from \"./extract\"\nimport { toolbeltEnabled, toolbeltSkipSet, vscodeRipgrepPath } from \"./index\"\nimport { assetFor, satisfiesMinVersion, TOOLBELT_TOOLS, type ToolAsset, type ToolSpec } from \"./manifest\"\n\n/** Per-download cap (bytes) — these binaries are a few MB at most. */\nconst MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024\nconst DOWNLOAD_TIMEOUT_MS = 30_000\n\nconst EXE_EXT = process.platform === \"win32\" ? \".exe\" : \"\"\n\n/**\n * Materialize the toolbelt. Returns the list of command names exposed\n * in `bin/` after provisioning. Best-effort; never throws.\n */\nexport async function provisionToolbelt(): Promise<string[]> {\n if (!toolbeltEnabled()) return []\n const binDir = PATHS.TOOLBELT_BIN_DIR\n try {\n await mkdir(binDir, { recursive: true })\n } catch (err) {\n consola.debug(\"toolbelt: could not create bin dir:\", err)\n return []\n }\n\n const skip = toolbeltSkipSet()\n\n // Serialize across concurrent proxies. If another process holds the\n // lock it is provisioning; we skip and just report current state.\n await withInstallLock(\"toolbelt.lock\", async () => {\n await pruneUnexpected(binDir)\n await provisionRg(binDir, skip).catch((err) =>\n consola.debug(\"toolbelt: rg skipped:\", err),\n )\n await Promise.all(\n TOOLBELT_TOOLS.map((spec) =>\n provisionTool(spec, binDir, skip).catch((err) =>\n consola.debug(`toolbelt: ${spec.command} skipped:`, err),\n ),\n ),\n )\n })\n\n return exposedCommands(binDir)\n}\n\n/** Names allowed to live in `bin/` (managed binaries + their sidecars). */\nfunction expectedFileNames(): Set<string> {\n const names = new Set<string>()\n const add = (base: string) => {\n names.add(base + EXE_EXT)\n names.add(`${base}${EXE_EXT}.sha256`)\n }\n add(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n add(spec.binBasename)\n for (const a of spec.aliases ?? []) add(a)\n }\n return names\n}\n\n/** Remove any file in `bin/` that isn't a managed binary or sidecar. */\nasync function pruneUnexpected(binDir: string): Promise<void> {\n const expected = expectedFileNames()\n let entries: string[]\n try {\n entries = await readdir(binDir)\n } catch {\n return\n }\n for (const name of entries) {\n if (name.endsWith(\".tmp\")) continue // in-flight temp from a peer\n if (!expected.has(name)) {\n await rm(path.join(binDir, name), { force: true }).catch(() => {})\n }\n }\n}\n\nasync function provisionRg(binDir: string, skip: Set<string>): Promise<void> {\n const dest = path.join(binDir, \"rg\" + EXE_EXT)\n const pathRg = resolveExecutable(\"rg\")\n if (skip.has(\"rg\") || (pathRg && !isWindowsScriptShim(pathRg))) {\n // User has a LAUNCHABLE rg (or skipped) — don't shadow it. code_search\n // uses its own resolver regardless. A Windows `.cmd` shim does not count:\n // the toolbelt's consumers spawn with `shell:false`, which cannot launch\n // one, so yielding to it would materialize nothing and leave every caller\n // with an EINVAL.\n await removeBin(dest)\n return\n }\n if (existsSync(dest)) return // already materialized\n const src = vscodeRipgrepPath()\n if (!src) return\n\n const tmp = tempName(dest)\n try {\n await link(src, tmp) // hardlink (same-volume fast path)\n } catch {\n await copyFile(src, tmp) // cross-volume (EXDEV) or other → copy\n }\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/**\n * Does the user's own copy on PATH satisfy `spec.minVersion`?\n *\n * Returns true when there is nothing to check (no minVersion), and — this\n * is the load-bearing part — ALSO returns true when the probe fails or the\n * output cannot be parsed. Gap-fill exists so we never shadow a user's\n * pinned or wrapper install, and an unreadable `--version` is not evidence\n * that their tool is inadequate. We only step in front of it on positive\n * proof that it is too old.\n */\nasync function pathCopyIsAdequate(spec: ToolSpec, resolved: string): Promise<boolean> {\n if (!spec.minVersion) return true\n try {\n // `runCommandCapture`, NOT `runManagedExeCapture`: on Windows a tool\n // installed via npm resolves to a `.cmd` shim, which cannot be spawned\n // with `shell:false` (it throws EINVAL). That is exactly how the\n // ast-grep case presented — the probe threw, we treated the version as\n // unknown, and yielded to the outdated copy anyway. runCommandCapture\n // goes through buildExecInvocation, which routes shims via cmd.exe.\n const res = await runCommandCapture([resolved, \"--version\"], {\n timeoutMs: VERSION_PROBE_TIMEOUT_MS,\n })\n const verdict = satisfiesMinVersion(`${res.stdout} ${res.stderr}`, spec.minVersion)\n if (verdict === undefined) return true\n if (!verdict) {\n consola.debug(\n `[toolbelt] ${spec.command} on PATH is older than ${spec.minVersion}; using the router-pinned build instead`,\n )\n }\n return verdict\n } catch {\n return true\n }\n}\n\n/** A `--version` call should be instant; this only bounds a hung binary. */\nconst VERSION_PROBE_TIMEOUT_MS = 5_000\n\nasync function provisionTool(\n spec: ToolSpec,\n binDir: string,\n skip: Set<string>,\n): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n const sidecar = `${dest}.sha256`\n const asset = assetFor(spec)\n\n if (skip.has(spec.command) || !asset) {\n await removeTool(spec, binDir)\n return\n }\n // Gap-fill: user already has it on PATH → remove ours, don't shadow.\n // Exception: a tool carrying `minVersion` is one this project's own code\n // depends on, so an older PATH copy is not \"good enough\" — it degrades\n // us silently. In that case we materialize ours anyway; the toolbelt bin\n // is prepended to the spawned agent's PATH and code_search checks the\n // router-owned paths first, so ours wins where it matters while the\n // user's shell keeps theirs.\n const onPath = resolveExecutable(spec.command)\n // A Windows `.cmd`/`.bat` copy is never adequate, whatever version it\n // reports. `pathCopyIsAdequate` may find it new enough, because its probe\n // goes through `buildExecInvocation` and CAN read a shim; every consumer of\n // the materialized tools instead spawns with `shell:false`, and\n // CreateProcess refuses a script with EINVAL. The observed case was a\n // globally npm-installed ast-grep 0.45.3: it satisfied `minVersion`, we\n // yielded to it, and `mode:\"ast\"` could not launch at all on the canonical\n // Windows host. Materializing ours is safe — the toolbelt bin dir is\n // prepended for agents and code search consults the router-owned paths\n // first, so the user's own shell keeps its copy untouched.\n if (onPath && !isWindowsScriptShim(onPath) && (await pathCopyIsAdequate(spec, onPath))) {\n await removeTool(spec, binDir)\n return\n }\n // Idempotent: present + sidecar matches → just ensure aliases exist.\n if (existsSync(dest) && (await sidecarMatches(sidecar, asset.sha256))) {\n await ensureAliases(spec, binDir, dest)\n return\n }\n\n const bytes = await downloadAndExtract(spec, asset)\n await atomicInstall(dest, bytes)\n await writeFile(sidecar, asset.sha256).catch(() => {})\n await ensureAliases(spec, binDir, dest)\n}\n\nasync function downloadAndExtract(\n spec: ToolSpec,\n asset: ToolAsset,\n): Promise<Buffer> {\n const data = await download(asset.url)\n const digest = createHash(\"sha256\").update(data).digest(\"hex\")\n if (digest !== asset.sha256) {\n throw new Error(\n `checksum mismatch for ${spec.command} (${asset.url}): expected ${asset.sha256}, got ${digest}`,\n )\n }\n if (asset.archive === \"raw\") return data\n const member =\n asset.archive === \"zip\"\n ? extractZipMember(data, spec.binBasename)\n : extractTarGzMember(data, spec.binBasename)\n if (!member) {\n throw new Error(`binary \"${spec.binBasename}\" not found in ${asset.url}`)\n }\n return member\n}\n\nasync function download(url: string): Promise<Buffer> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n redirect: \"follow\",\n headers: { \"User-Agent\": \"github-router-toolbelt\" },\n })\n if (!res.ok) throw new Error(`download ${url}: HTTP ${res.status}`)\n const buf = Buffer.from(await res.arrayBuffer())\n if (buf.length > MAX_DOWNLOAD_BYTES) {\n throw new Error(`download ${url}: exceeds ${MAX_DOWNLOAD_BYTES} bytes`)\n }\n return buf\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Write to a unique temp then atomically rename into place. */\nasync function atomicInstall(dest: string, bytes: Buffer): Promise<void> {\n const tmp = tempName(dest)\n await writeFile(tmp, bytes)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, dest)\n}\n\n/** Rename tmp→dest, handling Windows replace-existing / in-use locks. */\nasync function commit(tmp: string, dest: string): Promise<void> {\n try {\n await rename(tmp, dest)\n } catch {\n // Windows: rename won't replace an existing/locked dest. Remove and\n // retry once; if that fails (in-use .exe), leave the existing copy.\n try {\n await rm(dest, { force: true })\n await rename(tmp, dest)\n } catch (err) {\n await rm(tmp, { force: true }).catch(() => {})\n throw err\n }\n }\n}\n\nasync function ensureAliases(\n spec: ToolSpec,\n binDir: string,\n dest: string,\n): Promise<void> {\n for (const alias of spec.aliases ?? []) {\n const ap = path.join(binDir, alias + EXE_EXT)\n if (existsSync(ap)) continue\n const tmp = tempName(ap)\n try {\n await copyFile(dest, tmp)\n if (process.platform !== \"win32\") await chmod(tmp, 0o755).catch(() => {})\n await commit(tmp, ap)\n } catch (err) {\n consola.debug(`toolbelt: alias ${alias} skipped:`, err)\n }\n }\n}\n\nasync function removeTool(spec: ToolSpec, binDir: string): Promise<void> {\n const dest = path.join(binDir, spec.binBasename + EXE_EXT)\n await removeBin(dest)\n for (const alias of spec.aliases ?? []) {\n await removeBin(path.join(binDir, alias + EXE_EXT))\n }\n}\n\nasync function removeBin(dest: string): Promise<void> {\n await rm(dest, { force: true }).catch(() => {})\n await rm(`${dest}.sha256`, { force: true }).catch(() => {})\n}\n\nasync function sidecarMatches(sidecar: string, sha256: string): Promise<boolean> {\n try {\n return (await readFile(sidecar, \"utf8\")).trim() === sha256\n } catch {\n return false\n }\n}\n\nfunction tempName(dest: string): string {\n return `${dest}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n}\n\n/** The command names currently exposed in `bin/`. */\nasync function exposedCommands(binDir: string): Promise<string[]> {\n let files: Set<string>\n try {\n files = new Set(await readdir(binDir))\n } catch {\n return []\n }\n const present = (base: string) => files.has(base + EXE_EXT)\n const out: string[] = []\n if (present(\"rg\")) out.push(\"rg\")\n for (const spec of TOOLBELT_TOOLS) {\n if (present(spec.binBasename)) out.push(spec.command)\n }\n return out\n}\n"],"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,MAAgB,CAAC;CACvB,IAAI,QAAQ,IAAI,GAAG,IAAI,KAAK,IAAI;CAChC,KAAK,MAAM,QAAQ,gBACjB,IAAI,QAAQ,KAAK,WAAW,GAAG,IAAI,KAAK,KAAK,OAAO;CAEtD,OAAO;AACT"}
@@ -1,14 +1,14 @@
1
- import { $t as nativeSubagentModel, At as brainstormModel, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Jt as fleetToolsEnabled, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, T as availableToolCommands, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Xn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, an as standInToolEnabled, ar as resolveLeadSlugArg, c as enumerateInjectedMcpToolNames, en as resolveGeminiReviewModel, in as scribeModel, ir as pickClaudeDefault, jt as browseAgentEnabled, nn as reviewerModel, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, rn as scoutModel, sn as workiqToolsEnabled, tn as reviewerFastModel, w as buildEnv, xt as disposeAdoClients } from "./peer-mcp-personas-B1prNNMJ.js";
1
+ import { $t as nativeSubagentModel, At as brainstormModel, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Jt as fleetToolsEnabled, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, T as availableToolCommands, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Xn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, an as standInToolEnabled, ar as resolveLeadSlugArg, c as enumerateInjectedMcpToolNames, en as resolveGeminiReviewModel, in as scribeModel, ir as pickClaudeDefault, jt as browseAgentEnabled, nn as reviewerModel, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, rn as scoutModel, sn as workiqToolsEnabled, tn as reviewerFastModel, w as buildEnv, xt as disposeAdoClients } from "./peer-mcp-personas-OWsSm6To.js";
2
2
  import { c as disposeBluebirdClients } from "./bluebird-client-BasIdv5J.js";
3
- import { c as injectAllowRules, d as BUILTIN_SUBAGENT_DEFINITIONS, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, n as getInjectedSkills, o as SEAMLESS_BUILTIN_TOOLS, p as resolveCodexCliBackend, s as configureServeDefaultPermissionMode, t as injectAttributionSuppressionIntoSettingsFile, u as sanitizeServeSettingsEnv } from "./attribution-settings-CD0_yLqf.js";
3
+ import { c as injectAllowRules, d as BUILTIN_SUBAGENT_DEFINITIONS, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, n as getInjectedSkills, o as SEAMLESS_BUILTIN_TOOLS, p as resolveCodexCliBackend, s as configureServeDefaultPermissionMode, t as injectAttributionSuppressionIntoSettingsFile, u as sanitizeServeSettingsEnv } from "./attribution-settings-BWYL2b8N.js";
4
4
  import { c as runCommandCapture, r as killChildProcessTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
5
- import { U as resolveLaunchProfile, Z as runSelfUpdate, a as setupAndServe, b as injectModelPickerSettingsFile, i as parseSharedArgs, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake, y as stopKeepAwake } from "./server-setup-DjHNoWhQ.js";
5
+ import { U as resolveLaunchProfile, Z as runSelfUpdate, a as setupAndServe, b as injectModelPickerSettingsFile, i as parseSharedArgs, o as sharedServerArgs, t as getClaudeCodeEnvVars, v as startKeepAwake, y as stopKeepAwake } from "./server-setup-ClZdV33Q.js";
6
6
  import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-DMUnXVGT.js";
7
- import { r as getCodexVersion, t as provisionToolbelt } from "./provision-DktDm-f0.js";
7
+ import { r as getCodexVersion, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
8
8
  import { r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-CVEO8jEH.js";
9
- import { a as buildOperatingDefaultsDirective, c as prependOperatingDefaultsToMirroredClaudeMd, l as prependStyleDirectiveToMirroredClaudeMd, n as appendPeerAwarenessToMirroredClaudeMd, r as appendToolbeltAwarenessToMirroredClaudeMd } from "./claude-md-injection-C0EQfdJo.js";
9
+ import { a as buildOperatingDefaultsDirective, c as prependOperatingDefaultsToMirroredClaudeMd, l as prependStyleDirectiveToMirroredClaudeMd, n as appendPeerAwarenessToMirroredClaudeMd, r as appendToolbeltAwarenessToMirroredClaudeMd } from "./claude-md-injection-Biq_Xhve.js";
10
10
  import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-MhjK92wq.js";
11
- import { r as buildPromptSubmitHookCommand } from "./static-context-pack-DwC69_VA.js";
11
+ import { r as buildPromptSubmitHookCommand } from "./static-context-pack-CtnBwHSd.js";
12
12
  import { s as injectStopHookIntoSettingsFile } from "./stop-gate-hook-CBVLD8iB.js";
13
13
  import { t as state } from "./state-CCGDJ43X.js";
14
14
  import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-C7RtNOXv.js";
@@ -1604,4 +1604,4 @@ const serve = defineCommand({
1604
1604
  });
1605
1605
  export { serve };
1606
1606
 
1607
- //# sourceMappingURL=serve-CU3bV4e0.js.map
1607
+ //# sourceMappingURL=serve-zbQKfx1E.js.map