github-router 0.3.381 → 0.3.383

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 (149) hide show
  1. package/README.md +6 -0
  2. package/dist/ado-tools-Ddv910Zl.js +1 -0
  3. package/dist/{aic-ledger-6GKI28nY.js → aic-ledger-Bz87EuHl.js} +3 -3
  4. package/dist/{aic-ledger-6GKI28nY.js.map → aic-ledger-Bz87EuHl.js.map} +1 -1
  5. package/dist/{aic-statusline-settings-wLL1l_Z6.js → aic-statusline-settings-dkVZbpRL.js} +2 -2
  6. package/dist/{aic-statusline-settings-wLL1l_Z6.js.map → aic-statusline-settings-dkVZbpRL.js.map} +1 -1
  7. package/dist/{attribution-settings-BEwSkdhK.js → attribution-settings-BcPiSoZe.js} +27 -30
  8. package/dist/{attribution-settings-BEwSkdhK.js.map → attribution-settings-BcPiSoZe.js.map} +1 -1
  9. package/dist/{auth-5TKcQbbH.js → auth-D9eTY_W6.js} +3 -3
  10. package/dist/{auth-5TKcQbbH.js.map → auth-D9eTY_W6.js.map} +1 -1
  11. package/dist/bin.js +21 -4
  12. package/dist/bin.js.map +1 -1
  13. package/dist/bluebird-client-CLXs7q-X.js +1 -0
  14. package/dist/{bluebird-client-BasIdv5J.js → bluebird-client-bykMZyn1.js} +2 -2
  15. package/dist/{bluebird-client-BasIdv5J.js.map → bluebird-client-bykMZyn1.js.map} +1 -1
  16. package/dist/browser-ext/manifest.json +1 -1
  17. package/dist/{check-usage-DM39fdel.js → check-usage-BBaD35u4.js} +4 -4
  18. package/dist/{check-usage-DM39fdel.js.map → check-usage-BBaD35u4.js.map} +1 -1
  19. package/dist/{claude-CkrhHkPQ.js → claude-DOKuv2zZ.js} +29 -29
  20. package/dist/{claude-CkrhHkPQ.js.map → claude-DOKuv2zZ.js.map} +1 -1
  21. package/dist/{claude-md-injection-DNMDcw1W.js → claude-md-injection-BadtN0-I.js} +17 -8
  22. package/dist/claude-md-injection-BadtN0-I.js.map +1 -0
  23. package/dist/{codex-50GzveCD.js → codex-Dw_eBfXW.js} +9 -9
  24. package/dist/{codex-50GzveCD.js.map → codex-Dw_eBfXW.js.map} +1 -1
  25. package/dist/{copilot-discount-DM98PuAF.js → copilot-discount-BSDefQRW.js} +2 -2
  26. package/dist/{copilot-discount-DM98PuAF.js.map → copilot-discount-BSDefQRW.js.map} +1 -1
  27. package/dist/{debug-Df0Kuzi3.js → debug-B8eRYH-c.js} +2 -2
  28. package/dist/{debug-Df0Kuzi3.js.map → debug-B8eRYH-c.js.map} +1 -1
  29. package/dist/engine-DPtLOUuj.js +1 -0
  30. package/dist/{exec-BC0MAnoA.js → exec-oCtz_dXO.js} +22 -5
  31. package/dist/exec-oCtz_dXO.js.map +1 -0
  32. package/dist/{gate-discovery-2ILpM2fi.js → gate-discovery-DE_KTX2p.js} +6 -6
  33. package/dist/{gate-discovery-2ILpM2fi.js.map → gate-discovery-DE_KTX2p.js.map} +1 -1
  34. package/dist/{get-copilot-usage-BZ6t2hFZ.js → get-copilot-usage-Dh9u7WeP.js} +2 -2
  35. package/dist/{get-copilot-usage-BZ6t2hFZ.js.map → get-copilot-usage-Dh9u7WeP.js.map} +1 -1
  36. package/dist/hooks.mjs +21 -4
  37. package/dist/hooks.sha256 +1 -1
  38. package/dist/{index-cmd-DsK6VFs8.js → index-cmd-C4womtOS.js} +5 -5
  39. package/dist/{index-cmd-DsK6VFs8.js.map → index-cmd-C4womtOS.js.map} +1 -1
  40. package/dist/{internal-aic-status-CUZ7-trf.js → internal-aic-status-DSO2sR5u.js} +4 -4
  41. package/dist/{internal-aic-status-CUZ7-trf.js.map → internal-aic-status-DSO2sR5u.js.map} +1 -1
  42. package/dist/{internal-artifact-open-DRBg1PpV.js → internal-artifact-open-dlgqWieq.js} +2 -2
  43. package/dist/{internal-artifact-open-DRBg1PpV.js.map → internal-artifact-open-dlgqWieq.js.map} +1 -1
  44. package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js → internal-fast-dispatch-guard-5nCNht5y.js} +2 -2
  45. package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js.map → internal-fast-dispatch-guard-5nCNht5y.js.map} +1 -1
  46. package/dist/{internal-fast-dispatch-guard-D6-Ees_6.js → internal-fast-dispatch-guard-DHm96Bj_.js} +1 -1
  47. package/dist/{internal-first-mate-guard-DsEEsLKJ.js → internal-first-mate-guard-Bb9Stjy-.js} +3 -3
  48. package/dist/{internal-first-mate-guard-DsEEsLKJ.js.map → internal-first-mate-guard-Bb9Stjy-.js.map} +1 -1
  49. package/dist/{internal-first-mate-guard-BijeVpi9.js → internal-first-mate-guard-D6HMd9Iz.js} +1 -1
  50. package/dist/{internal-max-dispatch-guard-4RLca1i5.js → internal-max-dispatch-guard-C8kq4WNV.js} +3 -3
  51. package/dist/{internal-max-dispatch-guard-4RLca1i5.js.map → internal-max-dispatch-guard-C8kq4WNV.js.map} +1 -1
  52. package/dist/{internal-max-dispatch-guard-DeEfWqfP.js → internal-max-dispatch-guard-CI17mrDJ.js} +1 -1
  53. package/dist/{internal-plan-review-bzqGNdtw.js → internal-plan-review-Bdga9wVP.js} +3 -3
  54. package/dist/{internal-plan-review-bzqGNdtw.js.map → internal-plan-review-Bdga9wVP.js.map} +1 -1
  55. package/dist/{internal-prompt-submit-ZBhH-SQ1.js → internal-prompt-submit-DKlHlcvK.js} +2 -2
  56. package/dist/{internal-prompt-submit-BZ2-CExM.js → internal-prompt-submit-Daswp8ro.js} +5 -5
  57. package/dist/{internal-prompt-submit-BZ2-CExM.js.map → internal-prompt-submit-Daswp8ro.js.map} +1 -1
  58. package/dist/{internal-rebrief-BIWbN7Sr.js → internal-rebrief-D8O1J-_J.js} +5 -5
  59. package/dist/{internal-rebrief-BIWbN7Sr.js.map → internal-rebrief-D8O1J-_J.js.map} +1 -1
  60. package/dist/{internal-session-bind-BL6hFRLO.js → internal-session-bind-0hQFrcWu.js} +2 -2
  61. package/dist/{internal-session-bind-BL6hFRLO.js.map → internal-session-bind-0hQFrcWu.js.map} +1 -1
  62. package/dist/{internal-stop-hook-cDF1MuJZ.js → internal-stop-hook-C3lLh-HY.js} +6 -6
  63. package/dist/{internal-stop-hook-cDF1MuJZ.js.map → internal-stop-hook-C3lLh-HY.js.map} +1 -1
  64. package/dist/{internal-stop-review-y8zjpK_3.js → internal-stop-review-Bnmzcqx5.js} +2 -2
  65. package/dist/{internal-stop-review-y8zjpK_3.js.map → internal-stop-review-Bnmzcqx5.js.map} +1 -1
  66. package/dist/{internal-worker-guard-DdyYBZR0.js → internal-worker-guard-LcPxDlbx.js} +2 -2
  67. package/dist/{internal-worker-guard-DdyYBZR0.js.map → internal-worker-guard-LcPxDlbx.js.map} +1 -1
  68. package/dist/{internal-workspace-header-BMKbO8yX.js → internal-workspace-header-BH53hBXO.js} +2 -2
  69. package/dist/{internal-workspace-header-BMKbO8yX.js.map → internal-workspace-header-BH53hBXO.js.map} +1 -1
  70. package/dist/{lifecycle-COZhARmE.js → lifecycle-BmoqtVj3.js} +2 -2
  71. package/dist/{lifecycle-COZhARmE.js.map → lifecycle-BmoqtVj3.js.map} +1 -1
  72. package/dist/lifecycle-CcNNfKbr.js +1 -0
  73. package/dist/lifecycle-CrImfxCd.js +1 -0
  74. package/dist/{lifecycle-BlC_kzNt.js → lifecycle-CwxOsp-U.js} +3 -3
  75. package/dist/{lifecycle-BlC_kzNt.js.map → lifecycle-CwxOsp-U.js.map} +1 -1
  76. package/dist/main.js +25 -25
  77. package/dist/{max-profile-contract-DbHwiLTx.js → max-profile-contract-CEn8hKb3.js} +60 -60
  78. package/dist/{max-profile-contract-DbHwiLTx.js.map → max-profile-contract-CEn8hKb3.js.map} +1 -1
  79. package/dist/{mcp-workspace-header-Bpa4BId8.js → mcp-workspace-header-lb7GV78v.js} +2 -2
  80. package/dist/{mcp-workspace-header-Bpa4BId8.js.map → mcp-workspace-header-lb7GV78v.js.map} +1 -1
  81. package/dist/{models-BDV-YLf2.js → models-BTCnhBCQ.js} +3 -3
  82. package/dist/{models-BDV-YLf2.js.map → models-BTCnhBCQ.js.map} +1 -1
  83. package/dist/{optional-DGAeyguL.js → optional-LUQJI6Vx.js} +216 -16
  84. package/dist/optional-LUQJI6Vx.js.map +1 -0
  85. package/dist/{orchestration-Bto5Nc1Y.js → orchestration-C_hyBL90.js} +3 -3
  86. package/dist/{orchestration-Bto5Nc1Y.js.map → orchestration-C_hyBL90.js.map} +1 -1
  87. package/dist/origin-9bOjyzvK.js +1 -0
  88. package/dist/{origin-BXtpcKP9.js → origin-B6GChVyp.js} +2 -2
  89. package/dist/{origin-BXtpcKP9.js.map → origin-B6GChVyp.js.map} +1 -1
  90. package/dist/{paths-DeFmYJhO.js → paths-CVXqt2tC.js} +3 -3
  91. package/dist/{paths-DeFmYJhO.js.map → paths-CVXqt2tC.js.map} +1 -1
  92. package/dist/paths-JIusmD6L.js +1 -0
  93. package/dist/{peer-mcp-personas-Dny0r5Am.js → peer-mcp-personas-Dgog_ZJ8.js} +54 -54
  94. package/dist/{peer-mcp-personas-Dny0r5Am.js.map → peer-mcp-personas-Dgog_ZJ8.js.map} +1 -1
  95. package/dist/{pi-DVud9eQn.js → pi-BZhnf1kx.js} +95 -35
  96. package/dist/pi-BZhnf1kx.js.map +1 -0
  97. package/dist/{pi-version-check-BeBB0Ny9.js → pi-version-check-BRt9XFLj.js} +4 -4
  98. package/dist/{pi-version-check-BeBB0Ny9.js.map → pi-version-check-BRt9XFLj.js.map} +1 -1
  99. package/dist/pi-version-check-SH1X9u4H.js +1 -0
  100. package/dist/{plan-review-hook-D_yyjOgO.js → plan-review-hook-Dx3suYmK.js} +4 -4
  101. package/dist/{plan-review-hook-D_yyjOgO.js.map → plan-review-hook-Dx3suYmK.js.map} +1 -1
  102. package/dist/{provision-BWtuDq_v.js → provision-A1YSravb.js} +6 -6
  103. package/dist/{provision-BWtuDq_v.js.map → provision-A1YSravb.js.map} +1 -1
  104. package/dist/{rerank-cross-encoder-BhjImuwG.js → rerank-cross-encoder-uqRu-LOe.js} +2 -2
  105. package/dist/{rerank-cross-encoder-BhjImuwG.js.map → rerank-cross-encoder-uqRu-LOe.js.map} +1 -1
  106. package/dist/{self-invocation-Dnq4iVD6.js → self-invocation-CayD3y72.js} +2 -2
  107. package/dist/{self-invocation-Dnq4iVD6.js.map → self-invocation-CayD3y72.js.map} +1 -1
  108. package/dist/{serve-B8Igr9Q0.js → serve-Cv3S3PFR.js} +17 -17
  109. package/dist/{serve-B8Igr9Q0.js.map → serve-Cv3S3PFR.js.map} +1 -1
  110. package/dist/{server-setup-byIhjgOb.js → server-setup--CYeBD-Z.js} +14 -14
  111. package/dist/{server-setup-byIhjgOb.js.map → server-setup--CYeBD-Z.js.map} +1 -1
  112. package/dist/{service-backend-BdhWVRSz.js → service-backend-EgwiO_K-.js} +6 -6
  113. package/dist/{service-backend-BdhWVRSz.js.map → service-backend-EgwiO_K-.js.map} +1 -1
  114. package/dist/{start-7CiQIl0r.js → start-CA0JsO56.js} +5 -5
  115. package/dist/{start-7CiQIl0r.js.map → start-CA0JsO56.js.map} +1 -1
  116. package/dist/{static-context-pack-BKFelEbM.js → static-context-pack-BIru_SKh.js} +142 -142
  117. package/dist/{static-context-pack-BKFelEbM.js.map → static-context-pack-BIru_SKh.js.map} +1 -1
  118. package/dist/{stop-gate-hook-DBOj0TqL.js → stop-gate-hook-Ba_RvZAj.js} +4 -4
  119. package/dist/{stop-gate-hook-DBOj0TqL.js.map → stop-gate-hook-Ba_RvZAj.js.map} +1 -1
  120. package/dist/{stop-gate-policy-Bp2wGh_W.js → stop-gate-policy-gW0a0hds.js} +3 -3
  121. package/dist/{stop-gate-policy-Bp2wGh_W.js.map → stop-gate-policy-gW0a0hds.js.map} +1 -1
  122. package/dist/{token-Ygd7D32L.js → token-BCzbNu8O.js} +3 -3
  123. package/dist/{token-Ygd7D32L.js.map → token-BCzbNu8O.js.map} +1 -1
  124. package/dist/{token-CKPOBdO0.js → token-CxKcs3I_.js} +2 -2
  125. package/dist/{token-CKPOBdO0.js.map → token-CxKcs3I_.js.map} +1 -1
  126. package/dist/{update-T1L7yFon.js → update-CM1yUCJR.js} +4 -4
  127. package/dist/{update-T1L7yFon.js.map → update-CM1yUCJR.js.map} +1 -1
  128. package/dist/update-Cpg-tbJG.js +1 -0
  129. package/dist/{update-fEgWTrIx.js → update-ZqCRVU0a.js} +4 -4
  130. package/dist/{update-fEgWTrIx.js.map → update-ZqCRVU0a.js.map} +1 -1
  131. package/dist/{worker-dispatch-DBWKTMda.js → worker-dispatch-DHZAfPO2.js} +2 -2
  132. package/dist/{worker-dispatch-DBWKTMda.js.map → worker-dispatch-DHZAfPO2.js.map} +1 -1
  133. package/dist/{workiq-D5b7xlbr.js → workiq-CRBVCUA4.js} +2 -2
  134. package/dist/{workiq-D5b7xlbr.js.map → workiq-CRBVCUA4.js.map} +1 -1
  135. package/dist/{workiq-tools-DdiQ2DOW.js → workiq-tools-BsoHfdYi.js} +1 -1
  136. package/package.json +1 -1
  137. package/dist/ado-tools-CsfbnY8x.js +0 -1
  138. package/dist/bluebird-client-BvoMTmEv.js +0 -1
  139. package/dist/claude-md-injection-DNMDcw1W.js.map +0 -1
  140. package/dist/engine-B6la_uIW.js +0 -1
  141. package/dist/exec-BC0MAnoA.js.map +0 -1
  142. package/dist/lifecycle-BOjgq9_l.js +0 -1
  143. package/dist/lifecycle-NQvr4flt.js +0 -1
  144. package/dist/optional-DGAeyguL.js.map +0 -1
  145. package/dist/origin-DbFUCiGp.js +0 -1
  146. package/dist/paths-CquOjytP.js +0 -1
  147. package/dist/pi-DVud9eQn.js.map +0 -1
  148. package/dist/pi-version-check-D5RvdLsG.js +0 -1
  149. package/dist/update-CB21YRKz.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"provision-BWtuDq_v.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 { buildExecInvocation, 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 * Explicit argv prefix for the CLI, when the launcher resolved one itself.\n *\n * A managed Pi is `node <payload>/dist/bundle/cli.js`, so \"the CLI is one\n * token\" no longer holds for Pi. When present these tokens replace the\n * leading command (`[\"pi\"]`), and the kind's own flags plus `extraArgs` are\n * appended exactly as before — the resolver chooses WHICH executable, never\n * what the launcher asks it to do. Absent keeps every existing caller\n * byte-identical, which is why the `-g`/PATH paths are untouched by this.\n */\n execArgs?: 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 // `execArgs` REPLACES the leading command — it does not prefix it. The\n // distinction matters: a prefix would leave a bare `claude`/`codex` token in\n // the argv, and `resolveExecutable` below would happily rewrite it to some\n // OTHER binary on PATH, giving the child two executables' worth of arguments.\n // Exactly one of the two is ever used.\n const base: string[] = target.execArgs ?? []\n const hasPrefix = base.length > 0\n const claudeHead: string[] = hasPrefix ? base : [\"claude\"]\n const codexHead: string[] = hasPrefix ? base : [\"codex\"]\n const cmd: string[] =\n target.kind === \"claude-code\"\n ? wantsPermissionMode\n ? [...claudeHead, ...target.extraArgs]\n : [...claudeHead, \"--dangerously-skip-permissions\", ...target.extraArgs]\n : target.kind === \"pi\"\n ? [\n ...(hasPrefix ? base : [\"pi\"]),\n \"--provider\",\n \"gh-router\",\n ...(target.model ? [\"--model\", target.model] : []),\n ...target.extraArgs,\n ]\n : [...codexHead, ...buildCodexCmd(target).slice(1)]\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 // ONE place decides how argv becomes a spawn, and it is the same one\n // `runCommandCapture` uses. This used to be hand-rolled here: a `shell: true`\n // string join on Windows that treated `\"` as an escaper (it is not, for\n // cmd.exe). A managed Pi makes the argv longer — `node <absolute payload\n // path> …` — so a spaced install path is now the common case rather than a\n // corner case, and `buildExecInvocation` is what gets the `.cmd`/`/s /c`/caret\n // rules right.\n //\n // It can also REFUSE (win32 batch shims cannot carry `%` or `\"` through\n // cmd.exe). That refusal is separate from a spawn failure and gets its own\n // message: the token came from the user's own command line (a `--model` with a\n // `%`, a repo path with a quote), so \"Failed to launch pi\" would send them\n // looking at the wrong thing entirely.\n let invocation\n try {\n invocation = buildExecInvocation(cmd)\n } catch (error) {\n const msg =\n `Cannot launch ${executable}: ${error instanceof Error ? error.message : String(error)}`\n + `\\nThe argument came from this command line. On Windows a .cmd/.bat launcher `\n + `(such as a store-installed pi) cannot pass '%' or '\"' through cmd.exe — `\n + `remove it from the arguments, or point --pi-path at a native .exe.`\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 let child: ChildProcess\n try {\n // `detached:true` on POSIX → the CLI leads its OWN process group, so\n // cleanup() can kill(-pgid) the whole tree (grandchildren included). We\n // still 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(invocation.command, invocation.args, {\n env,\n stdio: \"inherit\",\n ...(invocation.shell ? { shell: true } : {}),\n ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),\n ...(process.platform === \"win32\" ? {} : { detached: true }),\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,SAAg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,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-A1YSravb.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 { buildExecInvocation, 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 * Explicit argv prefix for the CLI, when the launcher resolved one itself.\n *\n * A managed Pi is `node <payload>/dist/bundle/cli.js`, so \"the CLI is one\n * token\" no longer holds for Pi. When present these tokens replace the\n * leading command (`[\"pi\"]`), and the kind's own flags plus `extraArgs` are\n * appended exactly as before — the resolver chooses WHICH executable, never\n * what the launcher asks it to do. Absent keeps every existing caller\n * byte-identical, which is why the `-g`/PATH paths are untouched by this.\n */\n execArgs?: 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 // `execArgs` REPLACES the leading command — it does not prefix it. The\n // distinction matters: a prefix would leave a bare `claude`/`codex` token in\n // the argv, and `resolveExecutable` below would happily rewrite it to some\n // OTHER binary on PATH, giving the child two executables' worth of arguments.\n // Exactly one of the two is ever used.\n const base: string[] = target.execArgs ?? []\n const hasPrefix = base.length > 0\n const claudeHead: string[] = hasPrefix ? base : [\"claude\"]\n const codexHead: string[] = hasPrefix ? base : [\"codex\"]\n const cmd: string[] =\n target.kind === \"claude-code\"\n ? wantsPermissionMode\n ? [...claudeHead, ...target.extraArgs]\n : [...claudeHead, \"--dangerously-skip-permissions\", ...target.extraArgs]\n : target.kind === \"pi\"\n ? [\n ...(hasPrefix ? base : [\"pi\"]),\n \"--provider\",\n \"gh-router\",\n ...(target.model ? [\"--model\", target.model] : []),\n ...target.extraArgs,\n ]\n : [...codexHead, ...buildCodexCmd(target).slice(1)]\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 // ONE place decides how argv becomes a spawn, and it is the same one\n // `runCommandCapture` uses. This used to be hand-rolled here: a `shell: true`\n // string join on Windows that treated `\"` as an escaper (it is not, for\n // cmd.exe). A managed Pi makes the argv longer — `node <absolute payload\n // path> …` — so a spaced install path is now the common case rather than a\n // corner case, and `buildExecInvocation` is what gets the `.cmd`/`/s /c`/caret\n // rules right.\n //\n // It can also REFUSE (win32 batch shims cannot carry `%` or `\"` through\n // cmd.exe). That refusal is separate from a spawn failure and gets its own\n // message: the token came from the user's own command line (a `--model` with a\n // `%`, a repo path with a quote), so \"Failed to launch pi\" would send them\n // looking at the wrong thing entirely.\n let invocation\n try {\n invocation = buildExecInvocation(cmd)\n } catch (error) {\n const msg =\n `Cannot launch ${executable}: ${error instanceof Error ? error.message : String(error)}`\n + `\\nThe argument came from this command line. On Windows a .cmd/.bat launcher `\n + `(such as a store-installed pi) cannot pass '%' or '\"' through cmd.exe — `\n + `remove it from the arguments, or point --pi-path at a native .exe.`\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 let child: ChildProcess\n try {\n // `detached:true` on POSIX → the CLI leads its OWN process group, so\n // cleanup() can kill(-pgid) the whole tree (grandchildren included). We\n // still 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(invocation.command, invocation.args, {\n env,\n stdio: \"inherit\",\n ...(invocation.shell ? { shell: true } : {}),\n ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),\n ...(process.platform === \"win32\" ? {} : { detached: true }),\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,sBAAsB,KAAK,aAAa,CAAC,GAChD;GACE,OAAO;IAAC;IAAQ;IAAU;GAAQ;GAClC,UAAU;GACV,aAAa;GACb,OAAO;EACT,CACF;EACA,MAAM,GAAG,eAAe,CAAC,CAAC;EAC1B,MAAM,OAAO,GAAG,eAAe,CAAC,CAAC;EAGjC,eAAe,IAAI,KAAK;EACxB,MAAM,KAAK,cAAc,eAAe,OAAO,KAAK,CAAC;EACrD,MAAM,MAAM;EACZ,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAgB,kBAAkB,OAA2B;CAC3D,IAAI,CAAC,oBAAoB,GAAG;CAC5B,MAAM,MAAM,MAAM;CAClB,IAAI,CAAC,KAAK;CAEV,IAAI,QAAQ,aAAa,S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AK,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,4 +1,4 @@
1
- import { a as optionalInstallDisabled, o as scheduleOptionalInstall, r as installedOptional } from "./optional-DGAeyguL.js";
1
+ import { a as optionalInstallDisabled, o as scheduleOptionalInstall, r as installedOptional } from "./optional-LUQJI6Vx.js";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  // src/lib/rerank-cross-encoder.ts
@@ -189,4 +189,4 @@ async function createCrossEncoder(model) {
189
189
  }
190
190
  export { createCrossEncoder };
191
191
 
192
- //# sourceMappingURL=rerank-cross-encoder-BhjImuwG.js.map
192
+ //# sourceMappingURL=rerank-cross-encoder-uqRu-LOe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rerank-cross-encoder-BhjImuwG.js","names":[],"sources":["../src/lib/rerank-cross-encoder.ts"],"sourcesContent":["/**\n * In-repo cross-encoder reranker over transformers.js.\n *\n * Replaces `flashrank-js`, which reached `@huggingface/transformers: ^3.0.0`\n * transitively. Every 3.x transformers pins `onnxruntime-node@1.21.0` exactly,\n * and 1.21's linux/x64 `postinstall` downloads CUDA binaries from\n * `https://github.com/microsoft/onnxruntime/releases/download/v1.21.0/...` —\n * a path that has returned 404 since 2026-11-17. npm treats a failed\n * postinstall as a failed install, so `npx github-router@latest` and\n * `npm install -g github-router` died in the install step on linux/x64 before\n * the CLI ever ran.\n *\n * That could not be fixed from the consuming side: npm honours `overrides`\n * only from the ROOT `package.json` (never from a dependency), and Bun's\n * `trustedDependencies` gate has no npm equivalent — npm's own `allowScripts`\n * is project-level, advisory, and explicitly unavailable to `npx`/`-g`. So the\n * old chain was pinned correctly for this repo's own install and for nothing\n * else. Owning the ~60 lines flashrank provided — load tokenizer + sequence\n * classification model, score (query, doc) pairs, normalize, sort — against a\n * DIRECT `@huggingface/transformers@^4` dependency is what removes ORT 1.21\n * from every consumer tree.\n *\n * Behaviour is deliberately identical to the package it replaces:\n * - the same two Hugging Face repos (`tiny`, `mini`) at the same `fp32`\n * dtype, so a warm transformers cache keeps working and ranking does not\n * shift;\n * - the same score normalization (sigmoid for a single-logit regression\n * head, softmax class-1 probability for a two-logit head);\n * - the same 32-document batch size;\n * - `rerank` returns `{ index, score }` sorted descending, each index\n * mapping back to the caller's input array.\n *\n * transformers.js is imported DYNAMICALLY inside `createCrossEncoder` so this\n * module stays dependency-free for the pure helpers (`normalizeScore`,\n * `makeCrossEncoder`). `src/lib/rerank.ts` only ever imports this module from\n * inside its lazily-started load chain, so a proxy boot never pays for ONNX.\n */\n\nimport path from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\n\nimport {\n installedOptional,\n optionalInstallDisabled,\n scheduleOptionalInstall,\n} from \"~/lib/managed-install/optional\"\n\nexport type RerankModel = \"tiny\" | \"mini\"\n\n/**\n * The two FlashRank tiers, verbatim. `tiny` is ~4MB of weights and is used\n * when searches are already queued (burst); `mini` is ~23MB and is the idle\n * default. The dtype is load-bearing: `fp32` is the file set flashrank's\n * `defaultDtype` selected, so an existing Hugging Face cache resolves to the\n * same blobs instead of re-downloading a quantized sibling.\n */\nexport const RERANK_MODELS = {\n tiny: { huggingFaceId: \"Xenova/ms-marco-TinyBERT-L-2-v2\", dtype: \"fp32\" },\n mini: { huggingFaceId: \"Xenova/ms-marco-MiniLM-L-6-v2\", dtype: \"fp32\" },\n} as const\n\nconst DEFAULT_BATCH_SIZE = 32\n\n/** Minimal structural view of transformers.js's callable tokenizer. */\nexport type CrossEncoderTokenizer = (\n texts: ReadonlyArray<string>,\n options: {\n text_pair: ReadonlyArray<string>\n padding: boolean\n truncation: boolean\n },\n) => Promise<unknown>\n\n/** Minimal structural view of transformers.js's callable model. */\nexport type CrossEncoderModel = {\n (inputs: unknown): Promise<{ logits: { tolist: () => unknown } }>\n dispose?: () => Promise<void> | void\n}\n\nexport interface RerankInput {\n query: string\n documents: ReadonlyArray<string>\n /** Omit for the full sorted permutation; `0` means \"no results\". */\n topN?: number\n batchSize?: number\n}\n\nexport interface CrossEncoder {\n rerank(input: RerankInput): Promise<Array<{ index: number; score: number }>>\n dispose: () => Promise<void>\n}\n\nexport function sigmoid(x: number): number {\n if (x >= 0) {\n const z = Math.exp(-x)\n return 1 / (1 + z)\n }\n const z = Math.exp(x)\n return z / (1 + z)\n}\n\nexport function softmax(logits: ReadonlyArray<number>): Array<number> {\n if (logits.length === 0) return []\n let max = logits[0]\n for (const l of logits) if (l > max) max = l\n const exps = logits.map((l) => Math.exp(l - max))\n const sum = exps.reduce((a, b) => a + b, 0)\n if (sum === 0) return new Array<number>(logits.length).fill(1 / logits.length)\n return exps.map((e) => e / sum)\n}\n\n/**\n * Raw logits → one `[0,1]` score.\n *\n * MS MARCO cross-encoders ship in both head shapes: TinyBERT/MiniLM v2 here\n * are single-logit regression heads (sigmoid), while BGE-style bilingual\n * rerankers emit two class logits (softmax, take class 1). Anything wider\n * than two logits is not a reranking head we know, so the first logit is\n * passed through rather than invented into a probability.\n */\nexport function normalizeScore(logits: ReadonlyArray<number>): number {\n if (logits.length === 1) return sigmoid(logits[0])\n if (logits.length === 2) return softmax(logits)[1]\n return logits[0] ?? 0\n}\n\n/**\n * Build an encoder around an already-loaded tokenizer/model pair.\n *\n * The seam exists so unit tests can exercise ordering, batching and\n * normalization without ONNX — `createCrossEncoder` is the only caller that\n * needs the real library.\n */\nexport function makeCrossEncoder(parts: {\n tokenizer: CrossEncoderTokenizer\n model: CrossEncoderModel\n}): CrossEncoder {\n let disposed = false\n return {\n async rerank(input) {\n if (disposed) throw new Error(\"rerank: cross-encoder has been disposed\")\n const topN = input.topN\n if (input.documents.length === 0 || topN === 0) return []\n const batchSize =\n Number.isInteger(input.batchSize) && (input.batchSize as number) > 0\n ? (input.batchSize as number)\n : DEFAULT_BATCH_SIZE\n\n const scores = new Array<number>(input.documents.length)\n for (let start = 0; start < input.documents.length; start += batchSize) {\n const chunk = input.documents.slice(start, start + batchSize)\n const queries = new Array<string>(chunk.length).fill(input.query)\n const inputs = await parts.tokenizer(queries, {\n text_pair: chunk,\n padding: true,\n truncation: true,\n })\n const output = await parts.model(inputs)\n const raw = output.logits.tolist() as Array<number | Array<number>>\n const rows = Array.isArray(raw[0])\n ? (raw as Array<Array<number>>)\n : (raw as Array<number>).map((v) => [v])\n for (let i = 0; i < rows.length; i++) {\n scores[start + i] = normalizeScore(rows[i])\n }\n }\n\n const ranked = scores.map((score, index) => ({ index, score }))\n ranked.sort((a, b) => b.score - a.score)\n return topN !== undefined && topN < ranked.length\n ? ranked.slice(0, topN)\n : ranked\n },\n async dispose() {\n if (disposed) return\n disposed = true\n try {\n await parts.model.dispose?.()\n } catch {\n // best effort: a failed native teardown must not fail the caller\n }\n },\n }\n}\n\n/**\n * Load transformers.js, preferring the shared `<APP_DIR>/optional` copy.\n *\n * The package is an optional PEER (547 MB with its ONNX runtime), so it is\n * normally absent from the installed tree and present once per machine under\n * APP_DIR. Resolution order, and why:\n *\n * 1. `optional/` copy — the payload the on-demand installer published. It is\n * versioned and shared across github-router versions, so a version bump does\n * not re-download it.\n * 2. The package tree's own `node_modules` — the developer checkout, and the\n * `npm i -g` case where the peer resolved.\n * 3. Bare specifier — last resort, so a hoisted layout still works.\n *\n * A failure to load is NOT an error here: `rerank.ts` treats a rejection from\n * this function as \"reranking unavailable\" and keeps BM25F order, which is the\n * documented degradation. What must not happen is a hang or a crash on the\n * import, so each candidate is tried in turn.\n */\nasync function loadTransformers(): Promise<{\n AutoModelForSequenceClassification: {\n from_pretrained: (id: string, options?: Record<string, unknown>) => Promise<unknown>\n }\n AutoTokenizer: { from_pretrained: (id: string) => Promise<unknown> }\n}> {\n type TransformersModule = Awaited<typeof import(\"@huggingface/transformers\")>\n const load = async (specifier: string): Promise<TransformersModule | null> => {\n try {\n return (await import(/* @vite-ignore */ specifier)) as TransformersModule\n } catch {\n return null\n }\n }\n\n const shared = installedOptional(\"@huggingface/transformers\")\n if (shared) {\n const entry = pathToFileURL(path.join(shared, \"dist/transformers.node.mjs\")).href\n const loaded = await load(entry)\n if (loaded) return loaded as unknown as Awaited<ReturnType<typeof loadTransformers>>\n }\n\n const local = await load(\"@huggingface/transformers\")\n if (local) return local as unknown as Awaited<ReturnType<typeof loadTransformers>>\n\n // Nothing installed: ask for it once, in the background, and fail the way an\n // absent payload has always failed. This is the \"on demand\" half of the\n // optional payload — `github-router update` installs it upfront, and a machine\n // that never asked for it gets it the first time a search actually wants it.\n // The spawn is unref'd and once-per-process, so this costs one process on one\n // turn and BM25F order on that same turn.\n scheduleOptionalInstall(\"@huggingface/transformers\", process.argv[1])\n if (optionalInstallDisabled()) {\n throw new Error(\n \"@huggingface/transformers is not installed and GH_ROUTER_NO_OPTIONAL_INSTALL is set; reranking falls back to BM25F\",\n )\n }\n throw new Error(\n \"@huggingface/transformers is not installed; reranking falls back to BM25F (run `github-router update` to install it)\",\n )\n}\n\n/**\n * Download (or load from the transformers cache) one model tier.\n *\n * Throws on a network/cache failure — callers treat that as \"reranking\n * unavailable\" and keep BM25F order (see `src/lib/rerank.ts`, which never\n * lets this rejection escape).\n */\nexport async function createCrossEncoder(model: RerankModel): Promise<CrossEncoder> {\n const info = RERANK_MODELS[model]\n const transformers = await loadTransformers()\n const { AutoModelForSequenceClassification, AutoTokenizer } = transformers\n // The dtype rides only on the model: it selects which ONNX file of the repo\n // is fetched. transformers.js ignores it for tokenizers, and its\n // `PretrainedTokenizerOptions` type rejects the key outright, so passing a\n // shared options object would not typecheck.\n const [tokenizer, sequenceClassifier] = await Promise.all([\n AutoTokenizer.from_pretrained(info.huggingFaceId),\n AutoModelForSequenceClassification.from_pretrained(info.huggingFaceId, {\n dtype: info.dtype,\n }),\n ])\n return makeCrossEncoder({\n tokenizer: tokenizer as unknown as CrossEncoderTokenizer,\n model: sequenceClassifier as unknown as CrossEncoderModel,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAa,gBAAgB;CAC3B,MAAM;EAAE,eAAe;EAAmC,OAAO;CAAO;CACxE,MAAM;EAAE,eAAe;EAAiC,OAAO;CAAO;AACxE;AAEA,MAAM,qBAAqB;AA+B3B,SAAgB,QAAQ,GAAmB;CACzC,IAAI,KAAK,GAEP,OAAO,KAAK,IADF,KAAK,IAAI,CAAC,CACJ;CAElB,MAAM,IAAI,KAAK,IAAI,CAAC;CACpB,OAAO,KAAK,IAAI;AAClB;AAEA,SAAgB,QAAQ,QAA8C;CACpE,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;CACjC,IAAI,MAAM,OAAO;CACjB,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,KAAK,MAAM;CAC3C,MAAM,OAAO,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAG,CAAC;CAChD,MAAM,MAAM,KAAK,QAAQ,GAAG,MAAM,IAAI,GAAG,CAAC;CAC1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oder.ts"],"sourcesContent":["/**\n * In-repo cross-encoder reranker over transformers.js.\n *\n * Replaces `flashrank-js`, which reached `@huggingface/transformers: ^3.0.0`\n * transitively. Every 3.x transformers pins `onnxruntime-node@1.21.0` exactly,\n * and 1.21's linux/x64 `postinstall` downloads CUDA binaries from\n * `https://github.com/microsoft/onnxruntime/releases/download/v1.21.0/...` —\n * a path that has returned 404 since 2026-11-17. npm treats a failed\n * postinstall as a failed install, so `npx github-router@latest` and\n * `npm install -g github-router` died in the install step on linux/x64 before\n * the CLI ever ran.\n *\n * That could not be fixed from the consuming side: npm honours `overrides`\n * only from the ROOT `package.json` (never from a dependency), and Bun's\n * `trustedDependencies` gate has no npm equivalent — npm's own `allowScripts`\n * is project-level, advisory, and explicitly unavailable to `npx`/`-g`. So the\n * old chain was pinned correctly for this repo's own install and for nothing\n * else. Owning the ~60 lines flashrank provided — load tokenizer + sequence\n * classification model, score (query, doc) pairs, normalize, sort — against a\n * DIRECT `@huggingface/transformers@^4` dependency is what removes ORT 1.21\n * from every consumer tree.\n *\n * Behaviour is deliberately identical to the package it replaces:\n * - the same two Hugging Face repos (`tiny`, `mini`) at the same `fp32`\n * dtype, so a warm transformers cache keeps working and ranking does not\n * shift;\n * - the same score normalization (sigmoid for a single-logit regression\n * head, softmax class-1 probability for a two-logit head);\n * - the same 32-document batch size;\n * - `rerank` returns `{ index, score }` sorted descending, each index\n * mapping back to the caller's input array.\n *\n * transformers.js is imported DYNAMICALLY inside `createCrossEncoder` so this\n * module stays dependency-free for the pure helpers (`normalizeScore`,\n * `makeCrossEncoder`). `src/lib/rerank.ts` only ever imports this module from\n * inside its lazily-started load chain, so a proxy boot never pays for ONNX.\n */\n\nimport path from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\n\nimport {\n installedOptional,\n optionalInstallDisabled,\n scheduleOptionalInstall,\n} from \"~/lib/managed-install/optional\"\n\nexport type RerankModel = \"tiny\" | \"mini\"\n\n/**\n * The two FlashRank tiers, verbatim. `tiny` is ~4MB of weights and is used\n * when searches are already queued (burst); `mini` is ~23MB and is the idle\n * default. The dtype is load-bearing: `fp32` is the file set flashrank's\n * `defaultDtype` selected, so an existing Hugging Face cache resolves to the\n * same blobs instead of re-downloading a quantized sibling.\n */\nexport const RERANK_MODELS = {\n tiny: { huggingFaceId: \"Xenova/ms-marco-TinyBERT-L-2-v2\", dtype: \"fp32\" },\n mini: { huggingFaceId: \"Xenova/ms-marco-MiniLM-L-6-v2\", dtype: \"fp32\" },\n} as const\n\nconst DEFAULT_BATCH_SIZE = 32\n\n/** Minimal structural view of transformers.js's callable tokenizer. */\nexport type CrossEncoderTokenizer = (\n texts: ReadonlyArray<string>,\n options: {\n text_pair: ReadonlyArray<string>\n padding: boolean\n truncation: boolean\n },\n) => Promise<unknown>\n\n/** Minimal structural view of transformers.js's callable model. */\nexport type CrossEncoderModel = {\n (inputs: unknown): Promise<{ logits: { tolist: () => unknown } }>\n dispose?: () => Promise<void> | void\n}\n\nexport interface RerankInput {\n query: string\n documents: ReadonlyArray<string>\n /** Omit for the full sorted permutation; `0` means \"no results\". */\n topN?: number\n batchSize?: number\n}\n\nexport interface CrossEncoder {\n rerank(input: RerankInput): Promise<Array<{ index: number; score: number }>>\n dispose: () => Promise<void>\n}\n\nexport function sigmoid(x: number): number {\n if (x >= 0) {\n const z = Math.exp(-x)\n return 1 / (1 + z)\n }\n const z = Math.exp(x)\n return z / (1 + z)\n}\n\nexport function softmax(logits: ReadonlyArray<number>): Array<number> {\n if (logits.length === 0) return []\n let max = logits[0]\n for (const l of logits) if (l > max) max = l\n const exps = logits.map((l) => Math.exp(l - max))\n const sum = exps.reduce((a, b) => a + b, 0)\n if (sum === 0) return new Array<number>(logits.length).fill(1 / logits.length)\n return exps.map((e) => e / sum)\n}\n\n/**\n * Raw logits → one `[0,1]` score.\n *\n * MS MARCO cross-encoders ship in both head shapes: TinyBERT/MiniLM v2 here\n * are single-logit regression heads (sigmoid), while BGE-style bilingual\n * rerankers emit two class logits (softmax, take class 1). Anything wider\n * than two logits is not a reranking head we know, so the first logit is\n * passed through rather than invented into a probability.\n */\nexport function normalizeScore(logits: ReadonlyArray<number>): number {\n if (logits.length === 1) return sigmoid(logits[0])\n if (logits.length === 2) return softmax(logits)[1]\n return logits[0] ?? 0\n}\n\n/**\n * Build an encoder around an already-loaded tokenizer/model pair.\n *\n * The seam exists so unit tests can exercise ordering, batching and\n * normalization without ONNX — `createCrossEncoder` is the only caller that\n * needs the real library.\n */\nexport function makeCrossEncoder(parts: {\n tokenizer: CrossEncoderTokenizer\n model: CrossEncoderModel\n}): CrossEncoder {\n let disposed = false\n return {\n async rerank(input) {\n if (disposed) throw new Error(\"rerank: cross-encoder has been disposed\")\n const topN = input.topN\n if (input.documents.length === 0 || topN === 0) return []\n const batchSize =\n Number.isInteger(input.batchSize) && (input.batchSize as number) > 0\n ? (input.batchSize as number)\n : DEFAULT_BATCH_SIZE\n\n const scores = new Array<number>(input.documents.length)\n for (let start = 0; start < input.documents.length; start += batchSize) {\n const chunk = input.documents.slice(start, start + batchSize)\n const queries = new Array<string>(chunk.length).fill(input.query)\n const inputs = await parts.tokenizer(queries, {\n text_pair: chunk,\n padding: true,\n truncation: true,\n })\n const output = await parts.model(inputs)\n const raw = output.logits.tolist() as Array<number | Array<number>>\n const rows = Array.isArray(raw[0])\n ? (raw as Array<Array<number>>)\n : (raw as Array<number>).map((v) => [v])\n for (let i = 0; i < rows.length; i++) {\n scores[start + i] = normalizeScore(rows[i])\n }\n }\n\n const ranked = scores.map((score, index) => ({ index, score }))\n ranked.sort((a, b) => b.score - a.score)\n return topN !== undefined && topN < ranked.length\n ? ranked.slice(0, topN)\n : ranked\n },\n async dispose() {\n if (disposed) return\n disposed = true\n try {\n await parts.model.dispose?.()\n } catch {\n // best effort: a failed native teardown must not fail the caller\n }\n },\n }\n}\n\n/**\n * Load transformers.js, preferring the shared `<APP_DIR>/optional` copy.\n *\n * The package is an optional PEER (547 MB with its ONNX runtime), so it is\n * normally absent from the installed tree and present once per machine under\n * APP_DIR. Resolution order, and why:\n *\n * 1. `optional/` copy — the payload the on-demand installer published. It is\n * versioned and shared across github-router versions, so a version bump does\n * not re-download it.\n * 2. The package tree's own `node_modules` — the developer checkout, and the\n * `npm i -g` case where the peer resolved.\n * 3. Bare specifier — last resort, so a hoisted layout still works.\n *\n * A failure to load is NOT an error here: `rerank.ts` treats a rejection from\n * this function as \"reranking unavailable\" and keeps BM25F order, which is the\n * documented degradation. What must not happen is a hang or a crash on the\n * import, so each candidate is tried in turn.\n */\nasync function loadTransformers(): Promise<{\n AutoModelForSequenceClassification: {\n from_pretrained: (id: string, options?: Record<string, unknown>) => Promise<unknown>\n }\n AutoTokenizer: { from_pretrained: (id: string) => Promise<unknown> }\n}> {\n type TransformersModule = Awaited<typeof import(\"@huggingface/transformers\")>\n const load = async (specifier: string): Promise<TransformersModule | null> => {\n try {\n return (await import(/* @vite-ignore */ specifier)) as TransformersModule\n } catch {\n return null\n }\n }\n\n const shared = installedOptional(\"@huggingface/transformers\")\n if (shared) {\n const entry = pathToFileURL(path.join(shared, \"dist/transformers.node.mjs\")).href\n const loaded = await load(entry)\n if (loaded) return loaded as unknown as Awaited<ReturnType<typeof loadTransformers>>\n }\n\n const local = await load(\"@huggingface/transformers\")\n if (local) return local as unknown as Awaited<ReturnType<typeof loadTransformers>>\n\n // Nothing installed: ask for it once, in the background, and fail the way an\n // absent payload has always failed. This is the \"on demand\" half of the\n // optional payload — `github-router update` installs it upfront, and a machine\n // that never asked for it gets it the first time a search actually wants it.\n // The spawn is unref'd and once-per-process, so this costs one process on one\n // turn and BM25F order on that same turn.\n scheduleOptionalInstall(\"@huggingface/transformers\", process.argv[1])\n if (optionalInstallDisabled()) {\n throw new Error(\n \"@huggingface/transformers is not installed and GH_ROUTER_NO_OPTIONAL_INSTALL is set; reranking falls back to BM25F\",\n )\n }\n throw new Error(\n \"@huggingface/transformers is not installed; reranking falls back to BM25F (run `github-router update` to install it)\",\n )\n}\n\n/**\n * Download (or load from the transformers cache) one model tier.\n *\n * Throws on a network/cache failure — callers treat that as \"reranking\n * unavailable\" and keep BM25F order (see `src/lib/rerank.ts`, which never\n * lets this rejection escape).\n */\nexport async function createCrossEncoder(model: RerankModel): Promise<CrossEncoder> {\n const info = RERANK_MODELS[model]\n const transformers = await loadTransformers()\n const { AutoModelForSequenceClassification, AutoTokenizer } = transformers\n // The dtype rides only on the model: it selects which ONNX file of the repo\n // is fetched. transformers.js ignores it for tokenizers, and its\n // `PretrainedTokenizerOptions` type rejects the key outright, so passing a\n // shared options object would not typecheck.\n const [tokenizer, sequenceClassifier] = await Promise.all([\n AutoTokenizer.from_pretrained(info.huggingFaceId),\n AutoModelForSequenceClassification.from_pretrained(info.huggingFaceId, {\n dtype: info.dtype,\n }),\n ])\n return makeCrossEncoder({\n tokenizer: tokenizer as unknown as CrossEncoderTokenizer,\n model: sequenceClassifier as unknown as CrossEncoderModel,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAa,gBAAgB;CAC3B,MAAM;EAAE,eAAe;EAAmC,OAAO;CAAO;CACxE,MAAM;EAAE,eAAe;EAAiC,OAAO;CAAO;AACxE;AAEA,MAAM,qBAAqB;AA+B3B,SAAgB,QAAQ,GAAmB;CACzC,IAAI,KAAK,GAEP,OAAO,KAAK,IADF,KAAK,IAAI,CAAC,CACJ;CAElB,MAAM,IAAI,KAAK,IAAI,CAAC;CACpB,OAAO,KAAK,IAAI;AAClB;AAEA,SAAgB,QAAQ,QAA8C;CACpE,IAAI,OAAO,WAAW,GAAG,OAAO,CAAC;CACjC,IAAI,MAAM,OAAO;CACjB,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,KAAK,MAAM;CAC3C,MAAM,OAAO,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAG,CAAC;CAChD,MAAM,MAAM,KAAK,QAAQ,GAAG,MAAM,IAAI,GAAG,CAAC;CAC1C,IAAI,QAAQ,GAA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./paths-DeFmYJhO.js";
2
+ import { t as PATHS } from "./paths-CVXqt2tC.js";
3
3
  import { t as isUnderVolatileRoot } from "./volatile-root-DQNNvQ7Z.js";
4
4
  import consola from "consola";
5
5
  import { chmodSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
@@ -348,4 +348,4 @@ function currentPackageRoot() {
348
348
  }
349
349
  export { hookLauncherDegradedWarning as n, resolveSelfInvocation as r, buildSelfCommand as t };
350
350
 
351
- //# sourceMappingURL=self-invocation-Dnq4iVD6.js.map
351
+ //# sourceMappingURL=self-invocation-CayD3y72.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"self-invocation-Dnq4iVD6.js","names":[],"sources":["../src/lib/hook-launcher/provision.ts","../src/lib/hook-launcher/self-invocation.ts"],"sourcesContent":["/**\n * Publish the self-contained hook launcher (`dist/hooks.mjs`) to a stable,\n * content-addressed path under `<APP_DIR>/hooks/`.\n *\n * Why this exists: `github-router claude` persists Claude Code hook commands\n * into a settings.json that outlives the process that wrote it, built from\n * `process.argv[1]`. Under `bunx` that path is inside `$TMPDIR`, and macOS's\n * per-user temp reaper deletes files there (keeping the directory skeleton) —\n * so `node <tmp>/…/dist/main.js` died on its first bare import with\n * `ERR_MODULE_NOT_FOUND` and EVERY hook in a long-running session failed until\n * the tree happened to be re-extracted. `bunx pkg@latest` also re-extracts in\n * place whenever npm's `latest` advances, so a live session's hooks could\n * silently start executing a different version's code.\n *\n * Deliberate departures from `provisionBrowserAssets()`, which this otherwise\n * mirrors:\n *\n * - **Content-addressed, immutable names.** The digest IS the filename, so a\n * new build never overwrites an old launcher and there is nothing to\n * garbage-collect. Version-keyed names would need GC, and GC across\n * concurrent proxies is a race: proxy N deleting N+1's launcher (or the\n * reverse) breaks a live session's hooks. At ~1.5 MB, keeping stale\n * launchers costs less than the race would.\n *\n * - **The source is verified before it is published.** Hashing the bytes\n * read from `dist/hooks.mjs` only identifies those bytes; it does not\n * prove they are a complete artifact. A concurrent in-place `bunx`\n * extraction can hand over a truncated file, which content-addressing\n * would happily preserve forever under its own hash. The build writes a\n * `dist/hooks.sha256` sidecar and we publish only on a match.\n *\n * - **Failures are not latched.** A transient `EBUSY` (Windows antivirus, a\n * concurrent reader) must not disable provisioning for the process\n * lifetime, so only success is cached.\n *\n * Never throws: the caller degrades to `process.argv[1]` with a visible\n * warning rather than failing the launch.\n */\n\nimport { createHash } from \"node:crypto\"\nimport {\n chmodSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"../paths\"\n\n/** Sidecar written by `scripts/stamp-hooks-digest.ts` next to the bundle. */\nconst DIGEST_SIDECAR = \"hooks.sha256\"\n\n/** Basename of the built launcher bundle. */\nconst BUNDLE_NAME = \"hooks.mjs\"\n\n/**\n * Publish retries. A rename can lose a race with another proxy publishing the\n * same digest, or hit a Windows sharing violation while an antivirus scanner\n * holds the temp file. Both clear in milliseconds.\n */\nconst PUBLISH_ATTEMPTS = 3\n\nlet _published: string | undefined\nlet _inFlight: Promise<string | undefined> | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetHookLauncherForTests(): void {\n _published = undefined\n _inFlight = undefined\n}\n\n/**\n * Resolve the built bundle that sits beside the running code.\n *\n * In a built layout every chunk lives in `dist/`, so a sibling lookup finds\n * `dist/hooks.mjs`. Running from source it resolves to\n * `src/lib/hook-launcher/hooks.mjs`, which does not exist — which is exactly\n * the wanted behaviour: a `bun run dev` session must keep using\n * `process.argv[1]` rather than silently adopting a stale bundle from some\n * earlier build.\n */\nfunction bundledLauncherPath(): string | undefined {\n try {\n return path.join(path.dirname(fileURLToPath(import.meta.url)), BUNDLE_NAME)\n } catch {\n return undefined\n }\n}\n\nfunction sha256(buf: Buffer): string {\n return createHash(\"sha256\").update(buf).digest(\"hex\")\n}\n\n/**\n * Read the build's expected digest. Absent or malformed means \"cannot verify\",\n * which is treated as a refusal to publish rather than as permission to skip\n * the check — an unverified source is the one thing content-addressing cannot\n * recover from.\n */\nfunction expectedDigest(bundlePath: string): string | undefined {\n try {\n const raw = readFileSync(\n path.join(path.dirname(bundlePath), DIGEST_SIDECAR),\n \"utf8\",\n ).trim()\n return /^[0-9a-f]{64}$/.test(raw) ? raw : undefined\n } catch {\n return undefined\n }\n}\n\n/** True when `target` already holds exactly the bytes its name claims. */\nfunction targetIsValid(target: string, digest: string): boolean {\n try {\n return sha256(readFileSync(target)) === digest\n } catch {\n return false\n }\n}\n\n/**\n * Write `bytes` to `target` via a unique same-directory temp file plus a\n * rename, so a crash mid-write can never leave a partial file under the name\n * a hook command points at.\n *\n * The target is never deleted first: on Windows that would open a window where\n * a concurrently-launching session finds no launcher at all. A rename onto an\n * existing path can fail there, so a losing racer validates what the winner\n * wrote and accepts it.\n */\nfunction publish(target: string, bytes: Buffer, digest: string): boolean {\n // Checked once up front rather than per attempt: validation re-hashes ~1.5 MB\n // and the retries exist for rename contention, which revalidating cannot fix.\n if (targetIsValid(target, digest)) return true\n for (let attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) {\n const tmp = `${target}.${process.pid}-${attempt}.tmp`\n try {\n writeFileSync(tmp, bytes, { mode: 0o600 })\n renameSync(tmp, target)\n return true\n } catch {\n try {\n rmSync(tmp, { force: true })\n } catch {\n // Best-effort. A Windows sharing violation can strand the temp file;\n // `sweepStaleLaunchers` reaps it later rather than leaking 1.5 MB.\n }\n }\n }\n return targetIsValid(target, digest)\n}\n\n/** A stranded publish temp is dead well inside this. */\nconst TMP_MAX_AGE_MS = 24 * 60 * 60 * 1000\n\n/**\n * Launchers older than this are reaped. Generous on purpose — see the residual\n * risk in `sweepStaleLaunchers`.\n */\nconst LAUNCHER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/**\n * Reap stranded publish temps and long-unused launchers.\n *\n * Without this the directory grows by ~1.5 MB per shipped version forever, and\n * this project ships a patch release per PR with self-update on by default.\n *\n * The immutable content-addressed naming exists to avoid a GC race, so the\n * sweep is built to not reintroduce one: it never touches the digest THIS\n * launch resolved, and every launch refreshes its own launcher's mtime, so a\n * file survives for as long as some proxy keeps launching against it. Residual\n * risk, stated plainly: a single proxy running continuously for more than 30\n * days without relaunching could have its launcher reaped by a newer proxy.\n * That is bounded and far rarer than the unbounded growth it prevents, but it\n * is not zero — a PID-liveness marker would close it if it ever bites.\n */\nfunction sweepStaleLaunchers(dir: string, keep: string): void {\n const now = Date.now()\n let entries: Array<string>\n try {\n entries = readdirSync(dir)\n } catch {\n return\n }\n for (const name of entries) {\n if (name === path.basename(keep)) continue\n const isTmp = name.endsWith(\".tmp\")\n // Strict shape match, like sweepAgedWorkerDiffs: this directory is ours,\n // but a name-shape check means a false positive can only ever cost a file\n // the next launch regenerates.\n const isLauncher = /^hooks-[0-9a-f]{64}\\.mjs$/.test(name)\n if (!isTmp && !isLauncher) continue\n const target = path.join(dir, name)\n try {\n const age = now - statSync(target).mtimeMs\n if (age > (isTmp ? TMP_MAX_AGE_MS : LAUNCHER_MAX_AGE_MS)) {\n rmSync(target, { force: true })\n }\n } catch {\n /* best-effort */\n }\n }\n}\n\n/**\n * Materialize the launcher and return its stable absolute path, or undefined\n * when it could not be published (running from source, bundle missing or\n * unverifiable, filesystem refusing the write).\n *\n * Single-flight so the startup call and any lazy caller collapse to one run.\n */\nexport function provisionHookLauncher(): Promise<string | undefined> {\n if (_published) return Promise.resolve(_published)\n if (_inFlight) return _inFlight\n _inFlight = Promise.resolve()\n .then(() => provisionImpl())\n .then((result) => {\n // Cache SUCCESS only. Latching a transient failure would disable the\n // stable launcher for the whole process lifetime.\n if (result) _published = result\n return result\n })\n .finally(() => {\n _inFlight = undefined\n })\n return _inFlight\n}\n\nfunction provisionImpl(): string | undefined {\n const bundlePath = bundledLauncherPath()\n if (!bundlePath) return undefined\n return publishLauncherFrom(bundlePath)\n}\n\n/**\n * Verify and publish one specific bundle. Split out from the source resolution\n * above so the publication semantics are testable: running from source,\n * `bundledLauncherPath()` deliberately points at a file that does not exist,\n * which is the right behaviour but leaves nothing to exercise.\n *\n * @internal — production callers go through `provisionHookLauncher()`.\n */\nexport function publishLauncherFrom(bundlePath: string): string | undefined {\n try {\n let bytes: Buffer\n try {\n bytes = readFileSync(bundlePath)\n } catch {\n // Running from source, or the package tree was reaped out from under us.\n // Either way there is nothing to publish; a launcher published by an\n // earlier launch still stands.\n return undefined\n }\n\n const digest = sha256(bytes)\n const expected = expectedDigest(bundlePath)\n if (!expected) {\n // \"Cannot verify\" and \"verified bad\" both mean do-not-publish. Treating\n // an absent sidecar as permission would delete the integrity check in\n // exactly the degraded conditions it exists for.\n consola.debug(\n \"[hook-launcher] no digest sidecar beside the bundle; not publishing\",\n )\n return undefined\n }\n if (expected !== digest) {\n // The classic cause is reading mid-`bunx`-re-extraction. Publishing here\n // would freeze a torn bundle under a stable name forever, because\n // content-addressing gives a truncated file its own perfectly valid hash.\n consola.debug(\n \"[hook-launcher] bundle digest does not match the build; not publishing\",\n )\n return undefined\n }\n\n const dir = PATHS.HOOK_LAUNCHER_DIR\n // 0o700 / 0o600, matching the convention for the runtime dir in paths.ts.\n // This is not incidental hygiene: the published file is EXECUTED by node on\n // every prompt of every session, so a group- or world-writable path here\n // would let a local attacker swap the launcher and run code inside the\n // user's agent. chmod is best-effort — it is a no-op on Windows, where the\n // ACL inherited from APP_DIR governs.\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n try {\n chmodSync(dir, 0o700)\n } catch {\n /* best-effort: Windows, or a dir we do not own */\n }\n const target = path.join(dir, `hooks-${digest}.mjs`)\n if (!publish(target, bytes, digest)) return undefined\n\n // Mark this launcher as still in use before sweeping, so a long-lived\n // install that keeps relaunching against an old version is never reaped by\n // a newer proxy's sweep.\n try {\n const now = new Date()\n utimesSync(target, now, now)\n } catch {\n /* best-effort */\n }\n sweepStaleLaunchers(dir, target)\n return target\n } catch (err) {\n consola.debug(\"[hook-launcher] provisioning skipped:\", err)\n return undefined\n }\n}\n","/**\n * How this process names ITSELF in a command string that gets persisted to\n * disk and executed later by someone else.\n *\n * Every Claude Code hook, the MCP `headersHelper`, and the worker-guard are\n * registered as shell commands inside a settings.json that outlives the\n * process that wrote it. They were built from `(process.execPath,\n * process.argv[1])`, which under `bunx` points into `$TMPDIR` — a directory\n * macOS reaps and `bunx pkg@latest` re-extracts in place. A persisted command\n * pointing there stops working mid-session (see\n * `src/lib/hook-launcher/provision.ts` for the failure in full).\n *\n * So the pair is resolved ONCE per launch, through the stable relocated\n * launcher when one can be published, and every builder composes its command\n * from that single answer.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG } from \"../package-root\"\nimport { PATHS } from \"../paths\"\n// Re-exported so existing importers (and the tests that pin its\n// resolved-vs-unresolved behaviour) keep working; the implementation moved to\n// `../volatile-root` so the bootstrap bundle can use it without this module's\n// dependency graph.\nimport { isUnderVolatileRoot } from \"../volatile-root\"\n\nexport { isUnderVolatileRoot }\nimport { provisionHookLauncher } from \"./provision\"\n\n/** The binary + script + package root a persisted command should name. */\nexport interface SelfInvocation {\n /** The node/bun binary to exec. */\n execPath: string\n /** Script to pass to it, omitted for a packaged single-file build. */\n scriptPath?: string\n /**\n * The github-router package root, baked in only when `scriptPath` is the\n * relocated launcher. From `<APP_DIR>/hooks/` nothing can derive it: the\n * pre-existing walk in `browser-mcp/native-host-installer.ts` falls back to\n * `process.cwd()`, which would silently resolve to the USER'S WORKSPACE.\n */\n packageRoot?: string\n}\n\nfunction quote(s: string): string {\n return `\"${s}\"`\n}\n\n/**\n * Compose a persisted command string: the binary, the script when it differs\n * from the binary, the baked package root when there is one, then the args.\n *\n * Every builder in the codebase routes through here so the three parts cannot\n * drift apart — and so a future part is added in one place, not eleven.\n */\nexport function buildSelfCommand(inv: SelfInvocation, args: string): string {\n const parts = [quote(inv.execPath)]\n if (inv.scriptPath && inv.scriptPath !== inv.execPath) {\n parts.push(quote(inv.scriptPath))\n }\n if (inv.packageRoot) {\n parts.push(PACKAGE_ROOT_FLAG, quote(inv.packageRoot))\n }\n if (args) parts.push(args)\n return parts.join(\" \")\n}\n\n/** The invocation describing the currently running entrypoint, unrelocated. */\nexport function currentInvocation(): SelfInvocation {\n return { execPath: process.execPath, scriptPath: process.argv[1] }\n}\n\nlet _resolved: SelfInvocation | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetSelfInvocationForTests(): void {\n _resolved = undefined\n}\n\n/**\n * Resolve the invocation to bake into every persisted command this launch\n * writes. Awaited BEFORE the settings are written, never fire-and-forget: a\n * command persisted while provisioning is still pending would name the very\n * temp path this exists to avoid, and the session would stay broken however\n * well provisioning later went.\n *\n * Falls back to the running entrypoint if the launcher cannot be published, so\n * a provisioning failure degrades rather than breaking a launch. The caller is\n * responsible for surfacing that fallback — see `hookLauncherDegradedWarning`.\n */\nexport async function resolveSelfInvocation(): Promise<SelfInvocation> {\n if (_resolved) return _resolved\n const launcher = await provisionHookLauncher()\n _resolved =\n launcher ?\n {\n execPath: process.execPath,\n scriptPath: launcher,\n packageRoot: currentPackageRoot(),\n }\n : currentInvocation()\n return _resolved\n}\n\n/**\n * A human-facing warning when this launch is about to persist hook commands\n * pointing into a directory the OS may reap — the exact configuration that\n * produced the original bug.\n *\n * Returns the message rather than logging it, mirroring\n * `colbertDegradedWarning`: `claude` and `codex` call `enableFileLogging()`,\n * which redirects `consola.warn` to the error log, so a warning logged here\n * would be invisible on the one path where it matters most. The caller writes\n * it to stderr next to the readiness line instead.\n *\n * Silent when running from source, which has no bundle to publish and is not a\n * degraded state.\n */\nexport function hookLauncherDegradedWarning(\n inv: SelfInvocation,\n): string | null {\n if (!inv.scriptPath) return null\n // Our own published launcher is checked FIRST, and is authoritative: we know\n // we published it, so it can never warrant the \"could not publish\" message\n // below even if APP_DIR itself sits somewhere unusual.\n if (inv.scriptPath.startsWith(PATHS.HOOK_LAUNCHER_DIR)) {\n if (inv.packageRoot) return null\n // Relocated but rootless. Today this only degrades `--version` inside the\n // launcher, because nothing in the hook graph consumes the package root for\n // anything else. It is reported anyway because it is a trap rather than a\n // bug: the day a hook subcommand pulls in code_search or the browser\n // installer, `packageRoot()` falls through to `process.cwd()` and starts\n // resolving against the user's REPO with no signal at all.\n return (\n \"Hook launcher published without a package root; hook version reporting \"\n + \"will be degraded. This usually means the install tree is partially \"\n + \"missing — reinstall github-router.\"\n )\n }\n if (isUnderVolatileRoot(inv.scriptPath)) {\n return (\n \"Hook commands point into a temporary directory and will stop working \"\n + \"when the OS reaps it (the stable launcher could not be published). \"\n + \"Reinstall with `npm install -g github-router` to avoid this.\"\n )\n }\n return null\n}\n\n/**\n * The package root of the RUNNING code, derived while we are still inside the\n * package tree — the one moment it is knowable without guessing.\n *\n * The name is checked, not just the presence of a package.json: this value is\n * baked into a persisted command and consumed by `packageRoot()` as the\n * highest-priority source, so handing it the WRONG root would be worse than\n * handing it none. Matches `findPackageRoot()` in\n * `browser-mcp/native-host-installer.ts`, whose fallbacks this supersedes.\n */\nfunction currentPackageRoot(): string | undefined {\n const entry = typeof process.argv[1] === \"string\" ? process.argv[1] : undefined\n if (!entry) return undefined\n let cur = path.dirname(entry)\n for (let i = 0; i < 10; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(path.join(cur, \"package.json\"), \"utf8\"),\n ) as { name?: unknown }\n if (typeof pkg.name === \"string\" && pkg.name.includes(\"github-router\")) {\n return cur\n }\n } catch {\n // Not here, or unreadable; walk up.\n }\n const parent = path.dirname(cur)\n if (parent === cur) break\n cur = parent\n }\n return undefined\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,MAAM,iBAAiB;;AAGvB,MAAM,cAAc;;;;;;AAOpB,MAAM,mBAAmB;AAEzB,IAAI;AACJ,IAAI;;;;;;;;;;;AAkBJ,SAAS,sBAA0C;CACjD,IAAI;EACF,O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QAAQ,OAAO,QAAQ,KAAK,OAAO,WAAW,QAAQ,KAAK,KAAK,KAAA;CACtE,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,IAAI;GACF,MAAM,MAAM,KAAK,MACf,aAAa,KAAK,KAAK,KAAK,cAAc,GAAG,MAAM,CACrD;GACA,IAAI,OAAO,IAAI,SAAS,YAAY,IAAI,KAAK,SAAS,eAAe,GACnE,OAAO;EAEX,QAAQ,CAER;EACA,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK;EACpB,MAAM;CACR;AAEF"}
1
+ {"version":3,"file":"self-invocation-CayD3y72.js","names":[],"sources":["../src/lib/hook-launcher/provision.ts","../src/lib/hook-launcher/self-invocation.ts"],"sourcesContent":["/**\n * Publish the self-contained hook launcher (`dist/hooks.mjs`) to a stable,\n * content-addressed path under `<APP_DIR>/hooks/`.\n *\n * Why this exists: `github-router claude` persists Claude Code hook commands\n * into a settings.json that outlives the process that wrote it, built from\n * `process.argv[1]`. Under `bunx` that path is inside `$TMPDIR`, and macOS's\n * per-user temp reaper deletes files there (keeping the directory skeleton) —\n * so `node <tmp>/…/dist/main.js` died on its first bare import with\n * `ERR_MODULE_NOT_FOUND` and EVERY hook in a long-running session failed until\n * the tree happened to be re-extracted. `bunx pkg@latest` also re-extracts in\n * place whenever npm's `latest` advances, so a live session's hooks could\n * silently start executing a different version's code.\n *\n * Deliberate departures from `provisionBrowserAssets()`, which this otherwise\n * mirrors:\n *\n * - **Content-addressed, immutable names.** The digest IS the filename, so a\n * new build never overwrites an old launcher and there is nothing to\n * garbage-collect. Version-keyed names would need GC, and GC across\n * concurrent proxies is a race: proxy N deleting N+1's launcher (or the\n * reverse) breaks a live session's hooks. At ~1.5 MB, keeping stale\n * launchers costs less than the race would.\n *\n * - **The source is verified before it is published.** Hashing the bytes\n * read from `dist/hooks.mjs` only identifies those bytes; it does not\n * prove they are a complete artifact. A concurrent in-place `bunx`\n * extraction can hand over a truncated file, which content-addressing\n * would happily preserve forever under its own hash. The build writes a\n * `dist/hooks.sha256` sidecar and we publish only on a match.\n *\n * - **Failures are not latched.** A transient `EBUSY` (Windows antivirus, a\n * concurrent reader) must not disable provisioning for the process\n * lifetime, so only success is cached.\n *\n * Never throws: the caller degrades to `process.argv[1]` with a visible\n * warning rather than failing the launch.\n */\n\nimport { createHash } from \"node:crypto\"\nimport {\n chmodSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"../paths\"\n\n/** Sidecar written by `scripts/stamp-hooks-digest.ts` next to the bundle. */\nconst DIGEST_SIDECAR = \"hooks.sha256\"\n\n/** Basename of the built launcher bundle. */\nconst BUNDLE_NAME = \"hooks.mjs\"\n\n/**\n * Publish retries. A rename can lose a race with another proxy publishing the\n * same digest, or hit a Windows sharing violation while an antivirus scanner\n * holds the temp file. Both clear in milliseconds.\n */\nconst PUBLISH_ATTEMPTS = 3\n\nlet _published: string | undefined\nlet _inFlight: Promise<string | undefined> | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetHookLauncherForTests(): void {\n _published = undefined\n _inFlight = undefined\n}\n\n/**\n * Resolve the built bundle that sits beside the running code.\n *\n * In a built layout every chunk lives in `dist/`, so a sibling lookup finds\n * `dist/hooks.mjs`. Running from source it resolves to\n * `src/lib/hook-launcher/hooks.mjs`, which does not exist — which is exactly\n * the wanted behaviour: a `bun run dev` session must keep using\n * `process.argv[1]` rather than silently adopting a stale bundle from some\n * earlier build.\n */\nfunction bundledLauncherPath(): string | undefined {\n try {\n return path.join(path.dirname(fileURLToPath(import.meta.url)), BUNDLE_NAME)\n } catch {\n return undefined\n }\n}\n\nfunction sha256(buf: Buffer): string {\n return createHash(\"sha256\").update(buf).digest(\"hex\")\n}\n\n/**\n * Read the build's expected digest. Absent or malformed means \"cannot verify\",\n * which is treated as a refusal to publish rather than as permission to skip\n * the check — an unverified source is the one thing content-addressing cannot\n * recover from.\n */\nfunction expectedDigest(bundlePath: string): string | undefined {\n try {\n const raw = readFileSync(\n path.join(path.dirname(bundlePath), DIGEST_SIDECAR),\n \"utf8\",\n ).trim()\n return /^[0-9a-f]{64}$/.test(raw) ? raw : undefined\n } catch {\n return undefined\n }\n}\n\n/** True when `target` already holds exactly the bytes its name claims. */\nfunction targetIsValid(target: string, digest: string): boolean {\n try {\n return sha256(readFileSync(target)) === digest\n } catch {\n return false\n }\n}\n\n/**\n * Write `bytes` to `target` via a unique same-directory temp file plus a\n * rename, so a crash mid-write can never leave a partial file under the name\n * a hook command points at.\n *\n * The target is never deleted first: on Windows that would open a window where\n * a concurrently-launching session finds no launcher at all. A rename onto an\n * existing path can fail there, so a losing racer validates what the winner\n * wrote and accepts it.\n */\nfunction publish(target: string, bytes: Buffer, digest: string): boolean {\n // Checked once up front rather than per attempt: validation re-hashes ~1.5 MB\n // and the retries exist for rename contention, which revalidating cannot fix.\n if (targetIsValid(target, digest)) return true\n for (let attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) {\n const tmp = `${target}.${process.pid}-${attempt}.tmp`\n try {\n writeFileSync(tmp, bytes, { mode: 0o600 })\n renameSync(tmp, target)\n return true\n } catch {\n try {\n rmSync(tmp, { force: true })\n } catch {\n // Best-effort. A Windows sharing violation can strand the temp file;\n // `sweepStaleLaunchers` reaps it later rather than leaking 1.5 MB.\n }\n }\n }\n return targetIsValid(target, digest)\n}\n\n/** A stranded publish temp is dead well inside this. */\nconst TMP_MAX_AGE_MS = 24 * 60 * 60 * 1000\n\n/**\n * Launchers older than this are reaped. Generous on purpose — see the residual\n * risk in `sweepStaleLaunchers`.\n */\nconst LAUNCHER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/**\n * Reap stranded publish temps and long-unused launchers.\n *\n * Without this the directory grows by ~1.5 MB per shipped version forever, and\n * this project ships a patch release per PR with self-update on by default.\n *\n * The immutable content-addressed naming exists to avoid a GC race, so the\n * sweep is built to not reintroduce one: it never touches the digest THIS\n * launch resolved, and every launch refreshes its own launcher's mtime, so a\n * file survives for as long as some proxy keeps launching against it. Residual\n * risk, stated plainly: a single proxy running continuously for more than 30\n * days without relaunching could have its launcher reaped by a newer proxy.\n * That is bounded and far rarer than the unbounded growth it prevents, but it\n * is not zero — a PID-liveness marker would close it if it ever bites.\n */\nfunction sweepStaleLaunchers(dir: string, keep: string): void {\n const now = Date.now()\n let entries: Array<string>\n try {\n entries = readdirSync(dir)\n } catch {\n return\n }\n for (const name of entries) {\n if (name === path.basename(keep)) continue\n const isTmp = name.endsWith(\".tmp\")\n // Strict shape match, like sweepAgedWorkerDiffs: this directory is ours,\n // but a name-shape check means a false positive can only ever cost a file\n // the next launch regenerates.\n const isLauncher = /^hooks-[0-9a-f]{64}\\.mjs$/.test(name)\n if (!isTmp && !isLauncher) continue\n const target = path.join(dir, name)\n try {\n const age = now - statSync(target).mtimeMs\n if (age > (isTmp ? TMP_MAX_AGE_MS : LAUNCHER_MAX_AGE_MS)) {\n rmSync(target, { force: true })\n }\n } catch {\n /* best-effort */\n }\n }\n}\n\n/**\n * Materialize the launcher and return its stable absolute path, or undefined\n * when it could not be published (running from source, bundle missing or\n * unverifiable, filesystem refusing the write).\n *\n * Single-flight so the startup call and any lazy caller collapse to one run.\n */\nexport function provisionHookLauncher(): Promise<string | undefined> {\n if (_published) return Promise.resolve(_published)\n if (_inFlight) return _inFlight\n _inFlight = Promise.resolve()\n .then(() => provisionImpl())\n .then((result) => {\n // Cache SUCCESS only. Latching a transient failure would disable the\n // stable launcher for the whole process lifetime.\n if (result) _published = result\n return result\n })\n .finally(() => {\n _inFlight = undefined\n })\n return _inFlight\n}\n\nfunction provisionImpl(): string | undefined {\n const bundlePath = bundledLauncherPath()\n if (!bundlePath) return undefined\n return publishLauncherFrom(bundlePath)\n}\n\n/**\n * Verify and publish one specific bundle. Split out from the source resolution\n * above so the publication semantics are testable: running from source,\n * `bundledLauncherPath()` deliberately points at a file that does not exist,\n * which is the right behaviour but leaves nothing to exercise.\n *\n * @internal — production callers go through `provisionHookLauncher()`.\n */\nexport function publishLauncherFrom(bundlePath: string): string | undefined {\n try {\n let bytes: Buffer\n try {\n bytes = readFileSync(bundlePath)\n } catch {\n // Running from source, or the package tree was reaped out from under us.\n // Either way there is nothing to publish; a launcher published by an\n // earlier launch still stands.\n return undefined\n }\n\n const digest = sha256(bytes)\n const expected = expectedDigest(bundlePath)\n if (!expected) {\n // \"Cannot verify\" and \"verified bad\" both mean do-not-publish. Treating\n // an absent sidecar as permission would delete the integrity check in\n // exactly the degraded conditions it exists for.\n consola.debug(\n \"[hook-launcher] no digest sidecar beside the bundle; not publishing\",\n )\n return undefined\n }\n if (expected !== digest) {\n // The classic cause is reading mid-`bunx`-re-extraction. Publishing here\n // would freeze a torn bundle under a stable name forever, because\n // content-addressing gives a truncated file its own perfectly valid hash.\n consola.debug(\n \"[hook-launcher] bundle digest does not match the build; not publishing\",\n )\n return undefined\n }\n\n const dir = PATHS.HOOK_LAUNCHER_DIR\n // 0o700 / 0o600, matching the convention for the runtime dir in paths.ts.\n // This is not incidental hygiene: the published file is EXECUTED by node on\n // every prompt of every session, so a group- or world-writable path here\n // would let a local attacker swap the launcher and run code inside the\n // user's agent. chmod is best-effort — it is a no-op on Windows, where the\n // ACL inherited from APP_DIR governs.\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n try {\n chmodSync(dir, 0o700)\n } catch {\n /* best-effort: Windows, or a dir we do not own */\n }\n const target = path.join(dir, `hooks-${digest}.mjs`)\n if (!publish(target, bytes, digest)) return undefined\n\n // Mark this launcher as still in use before sweeping, so a long-lived\n // install that keeps relaunching against an old version is never reaped by\n // a newer proxy's sweep.\n try {\n const now = new Date()\n utimesSync(target, now, now)\n } catch {\n /* best-effort */\n }\n sweepStaleLaunchers(dir, target)\n return target\n } catch (err) {\n consola.debug(\"[hook-launcher] provisioning skipped:\", err)\n return undefined\n }\n}\n","/**\n * How this process names ITSELF in a command string that gets persisted to\n * disk and executed later by someone else.\n *\n * Every Claude Code hook, the MCP `headersHelper`, and the worker-guard are\n * registered as shell commands inside a settings.json that outlives the\n * process that wrote it. They were built from `(process.execPath,\n * process.argv[1])`, which under `bunx` points into `$TMPDIR` — a directory\n * macOS reaps and `bunx pkg@latest` re-extracts in place. A persisted command\n * pointing there stops working mid-session (see\n * `src/lib/hook-launcher/provision.ts` for the failure in full).\n *\n * So the pair is resolved ONCE per launch, through the stable relocated\n * launcher when one can be published, and every builder composes its command\n * from that single answer.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG } from \"../package-root\"\nimport { PATHS } from \"../paths\"\n// Re-exported so existing importers (and the tests that pin its\n// resolved-vs-unresolved behaviour) keep working; the implementation moved to\n// `../volatile-root` so the bootstrap bundle can use it without this module's\n// dependency graph.\nimport { isUnderVolatileRoot } from \"../volatile-root\"\n\nexport { isUnderVolatileRoot }\nimport { provisionHookLauncher } from \"./provision\"\n\n/** The binary + script + package root a persisted command should name. */\nexport interface SelfInvocation {\n /** The node/bun binary to exec. */\n execPath: string\n /** Script to pass to it, omitted for a packaged single-file build. */\n scriptPath?: string\n /**\n * The github-router package root, baked in only when `scriptPath` is the\n * relocated launcher. From `<APP_DIR>/hooks/` nothing can derive it: the\n * pre-existing walk in `browser-mcp/native-host-installer.ts` falls back to\n * `process.cwd()`, which would silently resolve to the USER'S WORKSPACE.\n */\n packageRoot?: string\n}\n\nfunction quote(s: string): string {\n return `\"${s}\"`\n}\n\n/**\n * Compose a persisted command string: the binary, the script when it differs\n * from the binary, the baked package root when there is one, then the args.\n *\n * Every builder in the codebase routes through here so the three parts cannot\n * drift apart — and so a future part is added in one place, not eleven.\n */\nexport function buildSelfCommand(inv: SelfInvocation, args: string): string {\n const parts = [quote(inv.execPath)]\n if (inv.scriptPath && inv.scriptPath !== inv.execPath) {\n parts.push(quote(inv.scriptPath))\n }\n if (inv.packageRoot) {\n parts.push(PACKAGE_ROOT_FLAG, quote(inv.packageRoot))\n }\n if (args) parts.push(args)\n return parts.join(\" \")\n}\n\n/** The invocation describing the currently running entrypoint, unrelocated. */\nexport function currentInvocation(): SelfInvocation {\n return { execPath: process.execPath, scriptPath: process.argv[1] }\n}\n\nlet _resolved: SelfInvocation | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetSelfInvocationForTests(): void {\n _resolved = undefined\n}\n\n/**\n * Resolve the invocation to bake into every persisted command this launch\n * writes. Awaited BEFORE the settings are written, never fire-and-forget: a\n * command persisted while provisioning is still pending would name the very\n * temp path this exists to avoid, and the session would stay broken however\n * well provisioning later went.\n *\n * Falls back to the running entrypoint if the launcher cannot be published, so\n * a provisioning failure degrades rather than breaking a launch. The caller is\n * responsible for surfacing that fallback — see `hookLauncherDegradedWarning`.\n */\nexport async function resolveSelfInvocation(): Promise<SelfInvocation> {\n if (_resolved) return _resolved\n const launcher = await provisionHookLauncher()\n _resolved =\n launcher ?\n {\n execPath: process.execPath,\n scriptPath: launcher,\n packageRoot: currentPackageRoot(),\n }\n : currentInvocation()\n return _resolved\n}\n\n/**\n * A human-facing warning when this launch is about to persist hook commands\n * pointing into a directory the OS may reap — the exact configuration that\n * produced the original bug.\n *\n * Returns the message rather than logging it, mirroring\n * `colbertDegradedWarning`: `claude` and `codex` call `enableFileLogging()`,\n * which redirects `consola.warn` to the error log, so a warning logged here\n * would be invisible on the one path where it matters most. The caller writes\n * it to stderr next to the readiness line instead.\n *\n * Silent when running from source, which has no bundle to publish and is not a\n * degraded state.\n */\nexport function hookLauncherDegradedWarning(\n inv: SelfInvocation,\n): string | null {\n if (!inv.scriptPath) return null\n // Our own published launcher is checked FIRST, and is authoritative: we know\n // we published it, so it can never warrant the \"could not publish\" message\n // below even if APP_DIR itself sits somewhere unusual.\n if (inv.scriptPath.startsWith(PATHS.HOOK_LAUNCHER_DIR)) {\n if (inv.packageRoot) return null\n // Relocated but rootless. Today this only degrades `--version` inside the\n // launcher, because nothing in the hook graph consumes the package root for\n // anything else. It is reported anyway because it is a trap rather than a\n // bug: the day a hook subcommand pulls in code_search or the browser\n // installer, `packageRoot()` falls through to `process.cwd()` and starts\n // resolving against the user's REPO with no signal at all.\n return (\n \"Hook launcher published without a package root; hook version reporting \"\n + \"will be degraded. This usually means the install tree is partially \"\n + \"missing — reinstall github-router.\"\n )\n }\n if (isUnderVolatileRoot(inv.scriptPath)) {\n return (\n \"Hook commands point into a temporary directory and will stop working \"\n + \"when the OS reaps it (the stable launcher could not be published). \"\n + \"Reinstall with `npm install -g github-router` to avoid this.\"\n )\n }\n return null\n}\n\n/**\n * The package root of the RUNNING code, derived while we are still inside the\n * package tree — the one moment it is knowable without guessing.\n *\n * The name is checked, not just the presence of a package.json: this value is\n * baked into a persisted command and consumed by `packageRoot()` as the\n * highest-priority source, so handing it the WRONG root would be worse than\n * handing it none. Matches `findPackageRoot()` in\n * `browser-mcp/native-host-installer.ts`, whose fallbacks this supersedes.\n */\nfunction currentPackageRoot(): string | undefined {\n const entry = typeof process.argv[1] === \"string\" ? process.argv[1] : undefined\n if (!entry) return undefined\n let cur = path.dirname(entry)\n for (let i = 0; i < 10; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(path.join(cur, \"package.json\"), \"utf8\"),\n ) as { name?: unknown }\n if (typeof pkg.name === \"string\" && pkg.name.includes(\"github-router\")) {\n return cur\n }\n } catch {\n // Not here, or unreadable; walk up.\n }\n const parent = path.dirname(cur)\n if (parent === cur) break\n cur = parent\n }\n return undefined\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,MAAM,iBAAiB;;AAGvB,MAAM,cAAc;;;;;;AAOpB,MAAM,mBAAmB;AAEzB,IAAI;AACJ,IAAI;;;;;;;;;;;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;;;;;;;AAYA,SAAS,qBAAyC;CAChD,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,WAAW,QAAQ,KAAK,KAAK,KAAA;CACtE,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,IAAI;GACF,MAAM,MAAM,KAAK,MACf,aAAa,KAAK,KAAK,KAAK,cAAc,GAAG,MAAM,CACrD;GACA,IAAI,OAAO,IAAI,SAAS,YAAY,IAAI,KAAK,SAAS,eAAe,GACnE,OAAO;EAEX,QAAQ,CAER;EACA,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK;EACpB,MAAM;CACR;AAEF"}
@@ -1,21 +1,21 @@
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-Dny0r5Am.js";
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-BEwSkdhK.js";
4
- import { c as runCommandCapture, r as killChildProcessTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
5
- import { R as resolveLaunchProfile, a as setupAndServe, h as injectModelPickerSettingsFile, i as parseSharedArgs, m as stopKeepAwake, o as sharedServerArgs, p as startKeepAwake, t as getClaudeCodeEnvVars } from "./server-setup-byIhjgOb.js";
6
- import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-Dnq4iVD6.js";
7
- import { r as getCodexVersion, t as provisionToolbelt } from "./provision-BWtuDq_v.js";
8
- import { r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-DeFmYJhO.js";
9
- import { a as buildOperatingDefaultsDirective, c as prependOperatingDefaultsToMirroredClaudeMd, l as prependStyleDirectiveToMirroredClaudeMd, n as appendPeerAwarenessToMirroredClaudeMd, r as appendToolbeltAwarenessToMirroredClaudeMd } from "./claude-md-injection-DNMDcw1W.js";
10
- import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-D_yyjOgO.js";
11
- import { r as buildPromptSubmitHookCommand } from "./static-context-pack-BKFelEbM.js";
12
- import { s as injectStopHookIntoSettingsFile } from "./stop-gate-hook-DBOj0TqL.js";
1
+ import { $t as nativeSubagentModel, At as brainstormModel, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Jn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Jt as fleetToolsEnabled, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, T as availableToolCommands, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, an as standInToolEnabled, c as enumerateInjectedMcpToolNames, en as resolveGeminiReviewModel, in as scribeModel, jt as browseAgentEnabled, nn as reviewerModel, nr as pickClaudeDefault, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, rn as scoutModel, rr as resolveLeadSlugArg, sn as workiqToolsEnabled, tn as reviewerFastModel, w as buildEnv, xt as disposeAdoClients } from "./peer-mcp-personas-Dgog_ZJ8.js";
2
+ import { c as disposeBluebirdClients } from "./bluebird-client-bykMZyn1.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-BcPiSoZe.js";
4
+ import { c as runCommandCapture, r as killChildProcessTree, s as resolveExecutable } from "./exec-oCtz_dXO.js";
5
+ import { R as resolveLaunchProfile, a as setupAndServe, h as injectModelPickerSettingsFile, i as parseSharedArgs, m as stopKeepAwake, o as sharedServerArgs, p as startKeepAwake, t as getClaudeCodeEnvVars } from "./server-setup--CYeBD-Z.js";
6
+ import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-CayD3y72.js";
7
+ import { r as getCodexVersion, t as provisionToolbelt } from "./provision-A1YSravb.js";
8
+ import { r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-CVXqt2tC.js";
9
+ import { i as appendToolbeltAwarenessToMirroredClaudeMd, l as prependOperatingDefaultsToMirroredClaudeMd, o as buildOperatingDefaultsDirective, r as appendPeerAwarenessToMirroredClaudeMd, u as prependStyleDirectiveToMirroredClaudeMd } from "./claude-md-injection-BadtN0-I.js";
10
+ import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-Dx3suYmK.js";
11
+ import { r as buildPromptSubmitHookCommand } from "./static-context-pack-BIru_SKh.js";
12
+ import { s as injectStopHookIntoSettingsFile } from "./stop-gate-hook-Ba_RvZAj.js";
13
13
  import { t as state } from "./state-CCGDJ43X.js";
14
- import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-DBWKTMda.js";
14
+ import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-DHZAfPO2.js";
15
15
  import { t as getPackageVersion } from "./version-CTqwKr26.js";
16
- import { u as runSelfUpdate } from "./pi-version-check-BeBB0Ny9.js";
17
- import { P as warmTreeSitterPool } from "./service-backend-BdhWVRSz.js";
18
- import { f as resolveModel, h as getGitHubUser } from "./token-CKPOBdO0.js";
16
+ import { u as runSelfUpdate } from "./pi-version-check-BRt9XFLj.js";
17
+ import { P as warmTreeSitterPool } from "./service-backend-EgwiO_K-.js";
18
+ import { f as resolveModel, h as getGitHubUser } from "./token-CxKcs3I_.js";
19
19
  import { defineCommand } from "citty";
20
20
  import consola from "consola";
21
21
  import fs from "node:fs";
@@ -1605,4 +1605,4 @@ const serve = defineCommand({
1605
1605
  });
1606
1606
  export { serve };
1607
1607
 
1608
- //# sourceMappingURL=serve-B8Igr9Q0.js.map
1608
+ //# sourceMappingURL=serve-Cv3S3PFR.js.map