github-router 0.3.379 → 0.3.381

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 (165) hide show
  1. package/README.md +62 -0
  2. package/dist/ado-tools-CsfbnY8x.js +1 -0
  3. package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
  4. package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
  5. package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
  6. package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
  7. package/dist/atomic-file-Dif1kLKM.js +198 -0
  8. package/dist/atomic-file-Dif1kLKM.js.map +1 -0
  9. package/dist/{attribution-settings-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.js.map} +1 -1
  11. package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
  12. package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
  13. package/dist/bin.js +1479 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/browser-ext/manifest.json +1 -1
  16. package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
  17. package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
  18. package/dist/{claude-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.js.map} +1 -1
  20. package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
  21. package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
  22. package/dist/{codex-BG0pfud9.js → codex-50GzveCD.js} +8 -7
  23. package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.js.map} +1 -1
  24. package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
  25. package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
  26. package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
  27. package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
  28. package/dist/diagnostics-cXjCT_JQ.js +12 -0
  29. package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
  30. package/dist/engine-B6la_uIW.js +1 -0
  31. package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
  32. package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
  33. package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
  34. package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
  35. package/dist/hooks.mjs +13 -0
  36. package/dist/hooks.sha256 +1 -1
  37. package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
  38. package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
  39. package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
  40. package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
  41. package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
  42. package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
  43. package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
  44. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
  45. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
  46. package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
  47. package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
  48. package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
  49. package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
  50. package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
  51. package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
  52. package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
  53. package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
  54. package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
  55. package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
  56. package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
  57. package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
  58. package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
  59. package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
  60. package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
  61. package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
  62. package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
  63. package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
  64. package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
  65. package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
  66. package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
  67. package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
  68. package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
  69. package/dist/lib/tree-sitter-pool/worker.js +268 -21
  70. package/dist/lifecycle-BOjgq9_l.js +1 -0
  71. package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
  72. package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
  73. package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
  74. package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
  75. package/dist/lifecycle-NQvr4flt.js +1 -0
  76. package/dist/main.js +39 -24
  77. package/dist/main.js.map +1 -1
  78. package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
  79. package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
  80. package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
  81. package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
  82. package/dist/npm-env-H60tX76c.js +130 -0
  83. package/dist/npm-env-H60tX76c.js.map +1 -0
  84. package/dist/optional-DGAeyguL.js +586 -0
  85. package/dist/optional-DGAeyguL.js.map +1 -0
  86. package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
  87. package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
  88. package/dist/origin-BXtpcKP9.js +382 -0
  89. package/dist/origin-BXtpcKP9.js.map +1 -0
  90. package/dist/origin-DbFUCiGp.js +1 -0
  91. package/dist/paths-CquOjytP.js +1 -0
  92. package/dist/paths-DK_b2ihK.js +176 -0
  93. package/dist/paths-DK_b2ihK.js.map +1 -0
  94. package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
  95. package/dist/paths-DeFmYJhO.js.map +1 -0
  96. package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
  97. package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
  98. package/dist/{pi-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
  99. package/dist/pi-DVud9eQn.js.map +1 -0
  100. package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
  101. package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
  102. package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
  103. package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
  104. package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
  105. package/dist/pi-version-check-BeBB0Ny9.js +551 -0
  106. package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
  107. package/dist/pi-version-check-D5RvdLsG.js +1 -0
  108. package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
  109. package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
  110. package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
  111. package/dist/provision-BWtuDq_v.js.map +1 -0
  112. package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
  113. package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
  114. package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
  115. package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
  116. package/dist/{serve-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
  119. package/dist/server-setup-byIhjgOb.js.map +1 -0
  120. package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
  121. package/dist/service-backend-BdhWVRSz.js.map +1 -0
  122. package/dist/{start-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
  123. package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.js.map} +1 -1
  124. package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
  125. package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
  126. package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
  127. package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
  128. package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
  129. package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
  130. package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
  131. package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
  132. package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
  133. package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
  134. package/dist/update-CB21YRKz.js +1 -0
  135. package/dist/update-T1L7yFon.js +1548 -0
  136. package/dist/update-T1L7yFon.js.map +1 -0
  137. package/dist/update-fEgWTrIx.js +214 -0
  138. package/dist/update-fEgWTrIx.js.map +1 -0
  139. package/dist/update-lock-BeS_WmC8.js +1 -0
  140. package/dist/update-lock-BmXx6QaR.js +171 -0
  141. package/dist/update-lock-BmXx6QaR.js.map +1 -0
  142. package/dist/volatile-root-DQNNvQ7Z.js +50 -0
  143. package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
  144. package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
  145. package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
  146. package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
  147. package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
  148. package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
  149. package/package.json +16 -4
  150. package/dist/ado-tools-CRkyU51J.js +0 -1
  151. package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
  152. package/dist/engine-V46un8Xl.js +0 -1
  153. package/dist/lifecycle-BENRuuX6.js +0 -1
  154. package/dist/lifecycle-Dli9vGI2.js +0 -1
  155. package/dist/paths-Be9_ujQ3.js +0 -1
  156. package/dist/paths-CVEO8jEH.js.map +0 -1
  157. package/dist/pi-DmeBxzIo.js.map +0 -1
  158. package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
  159. package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
  160. package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
  161. package/dist/provision-DPL8aGe2.js.map +0 -1
  162. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  163. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  164. package/dist/server-setup-ClZdV33Q.js.map +0 -1
  165. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-version-check-BeBB0Ny9.js","names":["NPM_PACKAGE","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow","getLatestVersion","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow"],"sources":["../src/lib/claude-version-check.ts","../src/lib/self-update.ts","../src/lib/pi-version-check.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport {\n resolveExecutable,\n runCommandCapture,\n runCommandVoid,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\n\nconst NPM_PACKAGE = \"@anthropic-ai/claude-code\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst CLAUDE_VERSION_TIMEOUT_MS = 3000\nconst NPM_INSTALL_TIMEOUT_MS = 120_000 // 2 min — npm install can be slow on cold caches\n\ninterface VersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-update-check\",\n )\n}\n\n/**\n * Read the throttle cache. Returns null on missing/corrupt file —\n * triggers a fresh check.\n */\nasync function readCache(): Promise<VersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as VersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: VersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n // Throttle cache is best-effort — a write failure means we'll re-check\n // on next launch. Not worth surfacing.\n consola.debug(\"Failed to write claude version-check cache:\", err)\n }\n}\n\n/** Check if it's been more than THROTTLE_HOURS since the last check. */\nfunction shouldCheckNow(cache: VersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `claude` version. Returns null if claude is not\n * on PATH or the version probe fails (e.g. older versions that don't\n * support `--version` cleanly).\n *\n * Windows-safe: `claude` is a `.cmd` shim that `execFile` cannot launch\n * directly. We resolve it to an absolute path (excluding the cwd, so a\n * planted `claude.cmd` in an untrusted repo can't run) and invoke it\n * through the shared exec helper.\n */\nasync function getInstalledVersion(): Promise<string | null> {\n const claudePath = resolveExecutable(\"claude\")\n if (!claudePath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [claudePath, \"--version\"],\n { timeoutMs: CLAUDE_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n // Output shape: \"2.1.139 (Claude Code)\\n\"\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/**\n * Fetch the latest version of @anthropic-ai/claude-code from the npm\n * registry. Returns null on network failure / npm unavailable.\n *\n * Windows-safe: `npm` is `npm.cmd`; resolved to an absolute path\n * (excluding cwd) before invocation.\n */\nasync function getLatestVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (only the leading X.Y.Z, no\n * pre-release / metadata handling — sufficient for npm-published\n * stable releases). Returns true if `latest` is strictly higher than\n * `installed`.\n */\nexport function isNewer(installed: string | null, latest: string | null): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\nexport interface VersionCheckResult {\n /** Whether claude is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-claude\"\n}\n\n/**\n * Run a version check (subject to throttle). Side-effect: updates the\n * throttle cache. Returns the comparison result.\n */\nexport async function checkClaudeVersion(opts: {\n noCheck?: boolean\n /** Bypass the throttle (used when the check is the user's main intent) */\n force?: boolean\n} = {}): Promise<VersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n return {\n installed: cache?.installedVersion !== null,\n installedVersion: cache?.installedVersion ?? null,\n latestVersion: cache?.latestVersion ?? null,\n needsUpdate: isNewer(\n cache?.installedVersion ?? null,\n cache?.latestVersion ?? null,\n ),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-claude\",\n }\n }\n\n const latestVersion = await getLatestVersion()\n // Update cache regardless of whether latest fetched (so we still\n // throttle if npm is offline).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isNewer(installedVersion, latestVersion),\n skipped: false,\n }\n}\n\n/**\n * Heuristic: did `claude update` fail because the subcommand does not\n * exist (a build predating `claude update`), as opposed to a transient\n * update error? We only npm-fall-back on this specific signal — falling\n * back on any failure would install a conflicting npm copy on\n * native-installer machines.\n *\n * Matches the usage/Commander-style \"unknown command\" messages CLIs emit\n * for an unrecognized subcommand. Deliberately narrow.\n */\nexport function looksLikeUnknownUpdateCommand(output: string): boolean {\n return /unknown command|unknown subcommand|unrecognized (sub)?command|invalid command|command not found|is not a (known|valid) command/i.test(\n output,\n )\n}\n\n/**\n * Update Claude Code to the latest version.\n *\n * Strategy (decided in the plan, corrected after a real-world false\n * negative): run `claude update` directly — it respects the user's\n * actual install method (native installer or npm), so it never creates a\n * conflicting second install, and it is NOT blocked by the\n * `DISABLE_AUTOUPDATER` the proxy sets in the *child* env (this runs from\n * the proxy's own env, and `claude update` is a manual command\n * unaffected by that flag).\n *\n * Only if `claude update` reports the subcommand is unknown (a build too\n * old to have it) do we fall back to `npm install -g\n * @anthropic-ai/claude-code@latest` with a VISIBLE warning. The earlier\n * `claude --help` capability probe was removed: it timed out / mismatched\n * on slow cold starts and wrongly forced the npm path every launch,\n * creating dual npm-global + native installs.\n *\n * Serialized across concurrent proxies via an install lock. Throws on\n * failure — the caller decides whether to warn and continue.\n */\nexport interface UpdateClaudeDeps {\n resolveExecutable: typeof resolveExecutable\n runCommandCapture: typeof runCommandCapture\n runCommandVoid: typeof runCommandVoid\n withInstallLock: typeof withInstallLock\n}\n\nexport async function updateClaude(\n latestVersion: string,\n deps: Partial<UpdateClaudeDeps> = {},\n): Promise<void> {\n const _resolve = deps.resolveExecutable ?? resolveExecutable\n const _capture = deps.runCommandCapture ?? runCommandCapture\n const _void = deps.runCommandVoid ?? runCommandVoid\n const _lock = deps.withInstallLock ?? withInstallLock\n\n const claudePath = _resolve(\"claude\")\n if (!claudePath) throw new Error(\"claude not found on PATH\")\n\n const ran = await _lock(\"claude-update.lock\", async () => {\n consola.info(`Updating Claude Code to ${latestVersion} via \\`claude update\\`...`)\n // Capture (not inherit) so we can detect an unknown-command signal;\n // echo the output afterward so the user still sees what happened.\n const { code, stdout, stderr } = await _capture([claudePath, \"update\"], {\n timeoutMs: NPM_INSTALL_TIMEOUT_MS,\n })\n const combined = `${stdout}${stderr}`\n const trimmed = combined.trim()\n if (trimmed) process.stdout.write(trimmed.endsWith(\"\\n\") ? trimmed : `${trimmed}\\n`)\n\n if (code === 0) {\n consola.success(`Claude Code updated to ${latestVersion}`)\n return\n }\n\n if (!looksLikeUnknownUpdateCommand(combined)) {\n throw new Error(`\\`claude update\\` exited with code ${code}`)\n }\n\n // Fallback: npm. Only reachable on installs too old to have\n // `claude update` at all.\n const npmPath = _resolve(\"npm\")\n if (!npmPath) {\n throw new Error(\n \"this Claude Code build predates `claude update` and npm is not on PATH; \" +\n `update manually: npm install -g ${NPM_PACKAGE}@latest`,\n )\n }\n consola.warn(\n \"This Claude Code build predates `claude update`; falling back to \" +\n `\\`npm install -g ${NPM_PACKAGE}@latest\\`.`,\n )\n const { code: npmCode, stderr: npmStderr } = await _void(\n [npmPath, \"install\", \"-g\", `${NPM_PACKAGE}@latest`, \"--silent\"],\n { timeoutMs: NPM_INSTALL_TIMEOUT_MS },\n )\n if (npmCode !== 0) {\n throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`)\n }\n consola.success(`${NPM_PACKAGE} updated to ${latestVersion}`)\n })\n\n if (!ran) {\n consola.debug(\"Claude Code update already in progress in another process; skipping.\")\n }\n}\n","/**\n * Self-update for the `github-router` proxy.\n *\n * The proxy is a *running* process, so updating its own global install\n * in place (`npm install -g github-router@latest`) deletes/overwrites\n * files the OS holds open — on Windows that fails deterministically\n * (EPERM/EBUSY) and can corrupt the install. So we never install in\n * place: when a newer version exists we spawn a **detached updater that\n * waits for this process to exit**, then installs. The update takes\n * effect on the next launch — no re-exec, no restart prompt.\n *\n * Best-effort throughout: every failure is swallowed to debug/warn and\n * never blocks startup. The startup probe is bounded and the install is\n * off the critical path (detached), so even a blackholed network can't\n * delay the proxy from serving.\n */\n\nimport { spawn } from \"node:child_process\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { isNewer } from \"./claude-version-check\"\nimport {\n parseBoolEnv,\n resolveExecutable,\n runCommandCapture,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\nimport { getPackageVersion } from \"./version\"\n\n// The published, installable package is the UNSCOPED name. The scoped\n// `@animeshkundu/github-router` is GitHub-Packages-only and must NOT be\n// used for `npm view` / `npm install` here.\nconst NPM_PACKAGE = \"github-router\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\n\ninterface SelfUpdateCache {\n checkedAt: string\n installedVersion: string | null\n latestVersion: string | null\n}\n\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n // Distinct from the Claude Code check's `last-update-check` so the\n // two throttles don't cross-suppress.\n \"last-self-update-check\",\n )\n}\n\nasync function readCache(): Promise<SelfUpdateCache | null> {\n try {\n const parsed = JSON.parse(\n await fs.readFile(cacheFilePath(), \"utf8\"),\n ) as SelfUpdateCache\n if (typeof parsed.checkedAt !== \"string\") return null\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: SelfUpdateCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 0o600 })\n } catch (err) {\n consola.debug(\"Failed to write self-update cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: SelfUpdateCache | null): boolean {\n if (!cache) return true\n const last = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(last)) return true\n return (Date.now() - last) / 1000 / 3600 >= THROTTLE_HOURS\n}\n\nasync function getLatestVersion(npmPath: string): Promise<string | null> {\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Spawn a detached process that waits for THIS proxy (pid) to exit,\n * then runs `npm install -g <spec>`. Fully detached and unref'd so it\n * outlives the proxy; output discarded.\n *\n * The waiter is a tiny inline Node script (Node is guaranteed present —\n * the proxy runs on it) that polls `process.kill(pid, 0)` until the\n * parent is gone, then execs npm. This avoids the Windows file-lock by\n * never touching the global install while the proxy holds it open.\n *\n * Shared by the proxy self-update (`github-router@latest`) and the Pi\n * background refresh (`@earendil-works/pi-coding-agent@<version>`):\n * both must update a global install without delaying startup, holding\n * shutdown, or racing each other (callers hold `withInstallLock`\n * before queueing).\n */\nexport function queueDetachedGlobalInstall(\n npmPath: string,\n spec: string,\n extraArgs: readonly string[] = [],\n): void {\n const parentPid = process.pid\n const installArgs = [\"install\", \"-g\", spec, ...extraArgs]\n // Inline waiter: poll until the parent disappears, then install.\n const waiter = `\n const pid = ${parentPid};\n const { spawn } = require(\"node:child_process\");\n function alive() { try { process.kill(pid, 0); return true } catch { return false } }\n const timer = setInterval(() => {\n if (alive()) return;\n clearInterval(timer);\n const args = [...${JSON.stringify(installArgs)}, \"--silent\"];\n const isWin = process.platform === \"win32\";\n const child = spawn(${JSON.stringify(npmPath)}, args, {\n stdio: \"ignore\", windowsHide: true, shell: isWin, detached: !isWin,\n });\n child.on(\"error\", () => process.exit(0));\n child.on(\"exit\", () => process.exit(0));\n // Safety: never hang forever.\n setTimeout(() => process.exit(0), 180000).unref();\n }, 500);\n // Safety cap on the wait itself (e.g. extremely long sessions still\n // eventually give up rather than leak the waiter).\n setTimeout(() => { clearInterval(timer); process.exit(0); }, 24 * 3600 * 1000).unref();\n `.trim()\n\n const child = spawn(process.execPath, [\"-e\", waiter], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n })\n child.unref()\n}\n\nfunction spawnDetachedUpdater(npmPath: string): void {\n queueDetachedGlobalInstall(npmPath, `${NPM_PACKAGE}@latest`)\n}\n\nexport interface RunSelfUpdateOpts {\n /** From `args[\"self-update\"]` (default true). */\n selfUpdate: boolean\n /** Bypass the throttle (used by tests / explicit forcing). */\n force?: boolean\n}\n\n/**\n * Probe npm for a newer `github-router` and, if found, queue a detached\n * post-exit update. Returns quickly; never throws. Call AFTER the\n * server is listening so the bounded probe can't delay binding.\n */\nexport async function runSelfUpdate(opts: RunSelfUpdateOpts): Promise<void> {\n if (!opts.selfUpdate) return\n if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return\n\n try {\n // WHICH update mechanism depends on who owns the tree we are running from,\n // and getting this wrong is not a style question:\n //\n // - `npx`/`bunx`: the tree is a disposable cache entry. `npm install -g`\n // from here would create a SECOND install the user never asked for (and\n // the next `npx` would still re-extract, so it would not even help). The\n // managed install is the whole point of this feature.\n // - `npm-global`: user decision 4 — that tree is its own owner. Keep the\n // detached post-exit waiter verbatim.\n // - `managed`: the bootstrap (and `github-router update`) maintain it; doing\n // it again here would double-schedule on every launch.\n // - `source`: never. A dev checkout must run its own code and must not gain\n // a global install as a side effect.\n //\n // `classifyOrigin` is imported lazily: it pulls `exec` and the managed state\n // module, and this function runs from every entry point including the tiny\n // bootstrap-adjacent paths.\n const { classifyOrigin } = await import(\"./managed-install/origin\")\n const origin = await classifyOrigin()\n\n if (origin.origin === \"npx\" || origin.origin === \"bunx\") {\n const { scheduleBackgroundSelfInstall } = await import(\"./managed-install/update\")\n const detail = await scheduleBackgroundSelfInstall({ quiet: true })\n consola.debug(`self-update: managed path: ${detail}`)\n return\n }\n if (origin.origin !== \"npm-global\") {\n consola.debug(`self-update: skipped for origin ${origin.origin} (${origin.detail})`)\n return\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) return\n\n const installed = getPackageVersion()\n if (installed === \"unknown\") return // can't compare; skip silently\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return // npm not on PATH; skip\n\n const latest = await getLatestVersion(npmPath)\n // Write the throttle BEFORE acting so concurrent/next launches back\n // off even if the install is still settling (optimistic lock).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion: installed,\n latestVersion: latest,\n })\n if (!latest || !isNewer(installed, latest)) return\n\n const queued = await withInstallLock(\"self-update.lock\", async () => {\n spawnDetachedUpdater(npmPath)\n })\n if (queued) {\n consola.info(\n `github-router ${installed} → ${latest} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Self-update check failed:\", err)\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { resolveExecutable, runCommandCapture } from \"./exec\"\nimport { queueDetachedGlobalInstall } from \"./self-update\"\nimport { withInstallLock } from \"./update-lock\"\n\nexport const PI_NPM_PACKAGE = \"@earendil-works/pi-coding-agent\"\n/**\n * Minimum Pi version the `pi` launcher supports.\n *\n * The floor is pinned to the first release whose `before_agent_start` event\n * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).\n * The generated extension's prompt hook stands down for non-user events using\n * that field, and without it the hook would fire on subagent and system turns\n * the user never typed, which is a wrong brief rather than a missing one.\n * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the\n * gate actually runs: the install probe, the background refresh, and this floor\n * check all sit inside `--update-check` (default on), so `--no-update-check`\n * (documented for offline/CI) skips the floor as well. That path is still\n * fail-closed rather than silently wrong: the generated extension's own shape\n * probe sees the missing `messageType`, warns once with the fix, and injects\n * nothing.\n */\nexport const PI_MIN_VERSION = \"1.3.0\"\n\n/**\n * Registry used for the PI PACKAGE ONLY.\n *\n * Pi must come from a registry that actually carries it. A corporate npm mirror\n * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and\n * the launcher then fail-closes on an upgrade command the user cannot satisfy\n * (their `npm install -g` resolves through the same lagging mirror). Pointing\n * the Pi probe and install at npmjs by default keeps the floor reachable;\n * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the\n * package. Everything else this repo installs still resolves through the user's\n * configured registry.\n */\nexport const PI_DEFAULT_REGISTRY = \"https://registry.npmjs.org/\"\n\n/**\n * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`\n * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a\n * warning otherwise, so a typo degrades to the working default rather than\n * bricking the launcher.\n */\nexport function resolvePiRegistry(): string {\n const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim()\n if (!raw) return PI_DEFAULT_REGISTRY\n if (!/^https?:\\/\\//i.test(raw)) {\n consola.warn(\n `Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`,\n )\n return PI_DEFAULT_REGISTRY\n }\n return raw.endsWith(\"/\") ? raw : `${raw}/`\n}\n\n/** `npm` args that pin an operation to the resolved Pi registry. */\nexport function piRegistryArgs(registry: string = resolvePiRegistry()): string[] {\n return [`--registry=${registry}`]\n}\n\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst PI_VERSION_TIMEOUT_MS = 3000\n\ninterface PiVersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-pi-update-check\",\n )\n}\n\nasync function readCache(): Promise<PiVersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as PiVersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: PiVersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n consola.debug(\"Failed to write pi version-check cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: PiVersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `pi` version. Returns null if pi is not on PATH\n * or the version probe fails.\n *\n * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path\n * (excluding the cwd) before invocation via the shared exec helper.\n */\nexport async function getInstalledPiVersion(): Promise<string | null> {\n const piPath = resolveExecutable(\"pi\")\n if (!piPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [piPath, \"--version\"],\n { timeoutMs: PI_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/** Fetch the latest Pi version from npm. Null on network/npm failure. */\nasync function getLatestPiVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [\n npmPath,\n \"view\",\n PI_NPM_PACKAGE,\n \"version\",\n \"--silent\",\n ...piRegistryArgs(),\n ],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (leading X.Y.Z only). True when\n * `latest` is strictly higher than `installed`.\n */\nexport function isPiNewer(\n installed: string | null,\n latest: string | null,\n): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */\nexport function meetsPiMinVersion(version: string | null): boolean {\n if (!version) return false\n return !isPiNewer(version, PI_MIN_VERSION)\n}\n\nexport interface PiVersionCheckResult {\n /** Whether pi is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** True if the installed version is below the supported floor */\n needsMinUpgrade: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-pi\"\n}\n\n/** Run a version check (subject to throttle). Side-effect: updates the cache. */\nexport async function checkPiVersion(opts: {\n noCheck?: boolean\n force?: boolean\n} = {}): Promise<PiVersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n const installedVersion = cache?.installedVersion ?? null\n const latestVersion = cache?.latestVersion ?? null\n return {\n installed: installedVersion !== null,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledPiVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: true,\n skipped: true,\n skipReason: \"no-pi\",\n }\n }\n\n const latestVersion = await getLatestPiVersion()\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: false,\n }\n}\n\n/*\n * `updatePi` / `ensurePiInstalled` used to live here: they ran\n * `npm install -g @earendil-works/pi-coding-agent@<v>` and then re-probed PATH.\n * They were removed deliberately, not refactored.\n *\n * Two reasons, both observed:\n *\n * 1. **They mutate a tree the user owns.** `-g` is not ours (user decision 4).\n * Rewriting it to satisfy `PI_MIN_VERSION` made the launcher's floor check a\n * silent `npm install -g` on every below-floor machine, which can break an\n * unrelated project pinned to the older Pi.\n * 2. **`-g` cannot be updated while it is in use.** On Windows that is `EPERM`;\n * everywhere it needs the detached post-exit waiter. The managed install\n * avoids the whole problem by publishing a new directory and swapping a file\n * pointer, so the below-floor repair path is now\n * `managed-install/pi-command.ts` → `ensureManagedInstall` (see\n * `resolvePiCommand`), and the explicit form is `github-router update --pi`.\n *\n * The user-owned `pi` still keeps its own channel: `refreshPiInBackground`\n * below queues the same detached `-g` install it always did.\n */\n\n/**\n * Fire-and-forget freshness refresh for a healthy Pi install. Never\n * blocks launch and never throws: on the throttled schedule it probes\n * npm for a newer Pi and, when one exists, queues a DETACHED post-exit\n * install (same pattern as the proxy self-update) so neither startup\n * nor the running session nor shutdown ever waits on npm. The\n * cross-process install lock serializes against concurrent launches;\n * every failure degrades to a debug log.\n *\n * Deliberately never touches a below-floor install: the floor is\n * enforced foreground by the launcher (fail-closed), and a background\n * task must not change what the running session validated.\n */\nexport function refreshPiInBackground(opts: { autoUpdate: boolean }): void {\n if (!opts.autoUpdate) return\n void (async () => {\n try {\n const cache = await readCache()\n if (!shouldCheckNow(cache)) return\n const installedVersion = await getInstalledPiVersion()\n if (!meetsPiMinVersion(installedVersion)) return\n const npmPath = resolveExecutable(\"npm\")\n const latestVersion = await getLatestPiVersion()\n // Optimistic throttle write: concurrent/next launches back off\n // even while the detached install is still settling.\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n if (!npmPath) return\n if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return\n const queued = await withInstallLock(\"pi-install.lock\", async () => {\n queueDetachedGlobalInstall(\n npmPath,\n `${PI_NPM_PACKAGE}@${latestVersion}`,\n piRegistryArgs(),\n )\n })\n if (queued) {\n consola.info(\n `Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Background Pi refresh failed:\", err)\n }\n })().catch((err) => {\n consola.debug(\"Background Pi refresh failed:\", err)\n })\n}\n"],"mappings":";;;;;;;;;AAaA,MAAMA,gBAAc;AACpB,MAAMC,mBAAiB;AACvB,MAAMC,wBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,yBAAyB;;AAY/B,SAASC,kBAAwB;CAC/B,OAAO,KAAK,KACV,GAAG,QAAQ,GACX,UACA,SACA,iBACA,mBACF;AACF;;;;;AAMA,eAAeC,cAA+C;CAC5D,IAAI;EACF,MAAM,MAAM,MAAM,GAAG,SAASD,gBAAc,GAAG,MAAM;EACrD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,IACE,OAAO,OAAO,cAAc,YACxB,OAAO,qBAAqB,QAC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,MAAM,iCAAiC,GAAG;EACpD;CACF,EAAA,CAAG,CAAC,CAAC,OAAO,QAAQ;EAClB,QAAQ,MAAM,iCAAiC,GAAG;CACpD,CAAC;AACH"}
@@ -0,0 +1 @@
1
+ export { l as resolvePiRegistry } from "./pi-version-check-BeBB0Ny9.js";
@@ -1,7 +1,7 @@
1
1
  import { a as parseBoolEnv } from "./exec-BC0MAnoA.js";
2
- import { t as buildSelfCommand } from "./self-invocation-DMUnXVGT.js";
2
+ import { t as buildSelfCommand } from "./self-invocation-Dnq4iVD6.js";
3
3
  import { n as callMcpTool } from "./hook-mcp-client-CYx10nlU.js";
4
- import { s as isSubagentContext } from "./stop-gate-policy-BehNiNix.js";
4
+ import { s as isSubagentContext } from "./stop-gate-policy-Bp2wGh_W.js";
5
5
  import { promises } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { createHash } from "node:crypto";
@@ -154,4 +154,4 @@ function buildPlanReviewHookCommand(invocation) {
154
154
  }
155
155
  export { runPlanReview as a, planReviewEnabled as i, decidePlanReviewHook as n, filePlanReviewDebounce as r, buildPlanReviewHookCommand as t };
156
156
 
157
- //# sourceMappingURL=plan-review-hook-MhjK92wq.js.map
157
+ //# sourceMappingURL=plan-review-hook-D_yyjOgO.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"plan-review-hook-MhjK92wq.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAAyB,QAAQ,KAAc;CAC/E,OAAO,aAAa,IAAI,6BAA6B,MAAM;AAC7D;;AAGA,SAAgB,uBAAuB,UAAkC;CACvE,MAAM,WAAW,QACfA,KAAS,KAAK,UAAU,oBAAoB,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG;CAC3G,MAAM,WAAW,OAAO,QAAiC;EACvD,IAAI;GACF,QAAQ,MAAMC,SAAG,SAAS,QAAQ,GAAG,GAAG,MAAM,EAAA,CAAG,KAAK;EACxD,QAAQ;GACN,OAAO;EACT;CACF;CACA,OAAO;EACL,MAAM,aAAa,KAAK,UAAU;GAChC,IAAI,SAAS,WAAW,GAAG,OAAO;GAClC,OAAQ,MAAM,SAAS,GAAG,MAAO;EACnC;EACA,MAAM,aAAa,KAAK,UAAU;GAChC,MAAMA,SAAG,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;GAC5C,MAAMA,SAAG,UAAU,QAAQ,GAAG,GAAG,UAAU,EAAE,MAA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ACrB,MAAM,QAAQ,MAAM,QAAQ,KAAgC,CAC1D,QACA,IAAI,SAAoB,YAAY;GAClC,QAAQ,iBAAiB,QAAQ,SAAS,GAAG,SAAS;EACxD,CAAC,CACH,CAAC;EACD,IAAI,UAAU,aAAa,MAAM,WAAW,CAAC,mBAAmB,MAAM,IAAI,GAAG;EAE7E,MAAM,SAAS,kBAAkB,MAAM,IAAI;EAC3C,MAAM,WAAW,MAAM,MAAM,cAAc,KAAK,MAAM,SAAS,CAAC,CAAC,YAAY,IAAI;EACjF,MAAM,OAAO,YAAY,SAAS,KAAK,CAAC,CAAC,SAAS,IAAI,GAAG,SAAS,KAAK,EAAE,MAAM,WAAW;EAC1F,MAAM,MAAM,cAAc,MAAM,MAAM,WAAW,IAAI;CACvD,QAAQ,CAER,UAAU;EACR,IAAI,OAAO,aAAa,KAAK;EAC7B,WAAW,MAAM;CACnB;AACF;;AAGA,SAAgB,2BAA2B,YAAoC;CAC7E,OAAO,iBAAiB,YAAY,sBAAsB;AAC5D"}
1
+ {"version":3,"file":"plan-review-hook-D_yyjOgO.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAAyB,QAAQ,KAAc;CAC/E,OAAO,aAAa,IAAI,6BAA6B,MAAM;AAC7D;;AAGA,SAAgB,uBAAuB,UAAkC;CACvE,MAAM,WAAW,QACfA,KAAS,KAAK,UAAU,oBAAoB,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG;CAC3G,MAAM,WAAW,OAAO,QAAiC;EACvD,IAAI;GACF,QAAQ,MAAMC,SAAG,SAAS,QAAQ,GAAG,GAAG,MAAM,EAAA,CAAG,KAAK;EACxD,QAAQ;GACN,OAAO;EACT;CACF;CACA,OAAO;EACL,MAAM,aAAa,KAAK,UAAU;GAChC,IAAI,SAAS,WAAW,GAAG,OAAO;GAClC,OAAQ,MAAM,SAAS,GAAG,MAAO;EACnC;EACA,MAAM,aAAa,KAAK,UAAU;GAChC,MAAMA,SAAG,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;GAC5C,MAAMA,SAAG,UAAU,QAAQ,GAAG,GAAG,UAAU,EAAE,MAAM,IAAM,CAAC;EAC5D;CACF;AACF;AAEA,SAAS,YAAY,KAAkD;CACrE,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,IAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ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AAa,MAAM,WAAW,CAAC,mBAAmB,MAAM,IAAI,GAAG;EAE7E,MAAM,SAAS,kBAAkB,MAAM,IAAI;EAC3C,MAAM,WAAW,MAAM,MAAM,cAAc,KAAK,MAAM,SAAS,CAAC,CAAC,YAAY,IAAI;EACjF,MAAM,OAAO,YAAY,SAAS,KAAK,CAAC,CAAC,SAAS,IAAI,GAAG,SAAS,KAAK,EAAE,MAAM,WAAW;EAC1F,MAAM,MAAM,cAAc,MAAM,MAAM,WAAW,IAAI;CACvD,QAAQ,CAER,UAAU;EACR,IAAI,OAAO,aAAa,KAAK;EAC7B,WAAW,MAAM;CACnB;AACF;;AAGA,SAAgB,2BAA2B,YAAoC;CAC7E,OAAO,iBAAiB,YAAY,sBAAsB;AAC5D"}
@@ -1,8 +1,9 @@
1
- import { t as PATHS } from "./paths-CVEO8jEH.js";
2
- import { a as parseBoolEnv, c as runCommandCapture, n as isWindowsScriptShim, r as killChildProcessTree, s as resolveExecutable } from "./exec-BC0MAnoA.js";
3
- import { E as extractZipMember, L as withInstallLock, T as extractTarGzMember } from "./service-backend-Cdgz6WPx.js";
4
- import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, Kn as collapsePathKeys, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-OWsSm6To.js";
5
- import { a as sweepRegistry } from "./lifecycle-Dh9y8OF1.js";
1
+ import { t as PATHS } from "./paths-DeFmYJhO.js";
2
+ import { a as parseBoolEnv, c as runCommandCapture, n as isWindowsScriptShim, r as killChildProcessTree, s as resolveExecutable, t as buildExecInvocation } from "./exec-BC0MAnoA.js";
3
+ import { t as withInstallLock } from "./update-lock-BmXx6QaR.js";
4
+ import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, Kn as collapsePathKeys, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-Dny0r5Am.js";
5
+ import { a as sweepRegistry } from "./lifecycle-COZhARmE.js";
6
+ import { E as extractZipMember, T as extractTarGzMember } from "./service-backend-BdhWVRSz.js";
6
7
  import consola from "consola";
7
8
  import { existsSync } from "node:fs";
8
9
  import path from "node:path";
@@ -328,17 +329,21 @@ function buildCodexCmd(target) {
328
329
  }
329
330
  function buildLaunchCommand(target) {
330
331
  const wantsPermissionMode = target.kind === "claude-code" && target.extraArgs.some((arg) => arg === "--permission-mode" || arg.startsWith("--permission-mode="));
331
- const cmd = target.kind === "claude-code" ? wantsPermissionMode ? ["claude", ...target.extraArgs] : [
332
- "claude",
332
+ const base = target.execArgs ?? [];
333
+ const hasPrefix = base.length > 0;
334
+ const claudeHead = hasPrefix ? base : ["claude"];
335
+ const codexHead = hasPrefix ? base : ["codex"];
336
+ const cmd = target.kind === "claude-code" ? wantsPermissionMode ? [...claudeHead, ...target.extraArgs] : [
337
+ ...claudeHead,
333
338
  "--dangerously-skip-permissions",
334
339
  ...target.extraArgs
335
340
  ] : target.kind === "pi" ? [
336
- "pi",
341
+ ...hasPrefix ? base : ["pi"],
337
342
  "--provider",
338
343
  "gh-router",
339
344
  ...target.model ? ["--model", target.model] : [],
340
345
  ...target.extraArgs
341
- ] : buildCodexCmd(target);
346
+ ] : [...codexHead, ...buildCodexCmd(target).slice(1)];
342
347
  const resolved = resolveExecutable(cmd[0], { env: process.env });
343
348
  if (resolved) cmd[0] = resolved;
344
349
  return {
@@ -350,18 +355,6 @@ function buildLaunchCommand(target) {
350
355
  };
351
356
  }
352
357
  /**
353
- * Whether a resolved Windows executable must be launched through cmd.exe
354
- * (`shell:true`). Only batch shims (`.cmd`/`.bat`) need it — and even then
355
- * cmd.exe stays alive as the CLI's parent, so `taskkill /T` reaps the
356
- * whole tree. A real `.exe` (e.g. the native-installer `claude.exe`) is
357
- * spawned DIRECTLY so the CLI is the direct child, with no cmd.exe
358
- * intermediary to orphan its node/MCP grandchildren on a kill.
359
- */
360
- function windowsLaunchNeedsShell(executable) {
361
- const ext = path.extname(executable).toLowerCase();
362
- return ext === ".cmd" || ext === ".bat";
363
- }
364
- /**
365
358
  * Forward a terminal resize to the detached child's process group.
366
359
  *
367
360
  * The kernel delivers `SIGWINCH` only to the FOREGROUND PROCESS GROUP of the
@@ -397,24 +390,25 @@ function launchChild(target, server, options = {}) {
397
390
  process.stderr.write(msg + "\n");
398
391
  process.exit(1);
399
392
  }
393
+ let invocation;
394
+ try {
395
+ invocation = buildExecInvocation(cmd);
396
+ } catch (error) {
397
+ const msg = `Cannot launch ${executable}: ${error instanceof Error ? error.message : String(error)}\nThe argument came from this command line. On Windows a .cmd/.bat launcher (such as a store-installed pi) cannot pass '%' or '"' through cmd.exe — remove it from the arguments, or point --pi-path at a native .exe.`;
398
+ consola.error(msg);
399
+ process.stderr.write(msg + "\n");
400
+ server.close(true).catch(() => {});
401
+ if (options.onShutdown) Promise.resolve(options.onShutdown()).catch(() => {});
402
+ process.exit(1);
403
+ }
400
404
  let child;
401
405
  try {
402
- if (process.platform === "win32") {
403
- if (windowsLaunchNeedsShell(cmd[0])) {
404
- const quoted = cmd.map((a) => a.includes(" ") ? `"${a}"` : a).join(" ");
405
- child = spawn(quoted, [], {
406
- env,
407
- stdio: "inherit",
408
- shell: true
409
- });
410
- } else child = spawn(cmd[0], cmd.slice(1), {
411
- env,
412
- stdio: "inherit"
413
- });
414
- } else child = spawn(cmd[0], cmd.slice(1), {
406
+ child = spawn(invocation.command, invocation.args, {
415
407
  env,
416
408
  stdio: "inherit",
417
- detached: true
409
+ ...invocation.shell ? { shell: true } : {},
410
+ ...invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {},
411
+ ...process.platform === "win32" ? {} : { detached: true }
418
412
  });
419
413
  } catch (error) {
420
414
  const msg = `Failed to launch ${executable}: ${error instanceof Error ? error.message : String(error)}`;
@@ -730,4 +724,4 @@ async function exposedCommands(binDir) {
730
724
  }
731
725
  export { STRIPPED_AUTH_ROUTING_ENV_KEYS as a, launchChild as i, buildCodexProviderConfigFlags as n, getCodexVersion as r, provisionToolbelt as t };
732
726
 
733
- //# sourceMappingURL=provision-DPL8aGe2.js.map
727
+ //# sourceMappingURL=provision-BWtuDq_v.js.map
@@ -0,0 +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,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,SAAS;CAElC,gBAAgB,KAAK,IAAI;AAC3B;;;;;;;;;;;;;;;;;;;;;;AC1IA,MAAa,iCAAiC;CAE5C;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CAGA;CAIA;CACA;CACA;CACA;CACA;CACA;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C/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"}
@@ -0,0 +1,192 @@
1
+ import { a as optionalInstallDisabled, o as scheduleOptionalInstall, r as installedOptional } from "./optional-DGAeyguL.js";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ // src/lib/rerank-cross-encoder.ts
5
+ /**
6
+ * In-repo cross-encoder reranker over transformers.js.
7
+ *
8
+ * Replaces `flashrank-js`, which reached `@huggingface/transformers: ^3.0.0`
9
+ * transitively. Every 3.x transformers pins `onnxruntime-node@1.21.0` exactly,
10
+ * and 1.21's linux/x64 `postinstall` downloads CUDA binaries from
11
+ * `https://github.com/microsoft/onnxruntime/releases/download/v1.21.0/...` —
12
+ * a path that has returned 404 since 2026-11-17. npm treats a failed
13
+ * postinstall as a failed install, so `npx github-router@latest` and
14
+ * `npm install -g github-router` died in the install step on linux/x64 before
15
+ * the CLI ever ran.
16
+ *
17
+ * That could not be fixed from the consuming side: npm honours `overrides`
18
+ * only from the ROOT `package.json` (never from a dependency), and Bun's
19
+ * `trustedDependencies` gate has no npm equivalent — npm's own `allowScripts`
20
+ * is project-level, advisory, and explicitly unavailable to `npx`/`-g`. So the
21
+ * old chain was pinned correctly for this repo's own install and for nothing
22
+ * else. Owning the ~60 lines flashrank provided — load tokenizer + sequence
23
+ * classification model, score (query, doc) pairs, normalize, sort — against a
24
+ * DIRECT `@huggingface/transformers@^4` dependency is what removes ORT 1.21
25
+ * from every consumer tree.
26
+ *
27
+ * Behaviour is deliberately identical to the package it replaces:
28
+ * - the same two Hugging Face repos (`tiny`, `mini`) at the same `fp32`
29
+ * dtype, so a warm transformers cache keeps working and ranking does not
30
+ * shift;
31
+ * - the same score normalization (sigmoid for a single-logit regression
32
+ * head, softmax class-1 probability for a two-logit head);
33
+ * - the same 32-document batch size;
34
+ * - `rerank` returns `{ index, score }` sorted descending, each index
35
+ * mapping back to the caller's input array.
36
+ *
37
+ * transformers.js is imported DYNAMICALLY inside `createCrossEncoder` so this
38
+ * module stays dependency-free for the pure helpers (`normalizeScore`,
39
+ * `makeCrossEncoder`). `src/lib/rerank.ts` only ever imports this module from
40
+ * inside its lazily-started load chain, so a proxy boot never pays for ONNX.
41
+ */
42
+ /**
43
+ * The two FlashRank tiers, verbatim. `tiny` is ~4MB of weights and is used
44
+ * when searches are already queued (burst); `mini` is ~23MB and is the idle
45
+ * default. The dtype is load-bearing: `fp32` is the file set flashrank's
46
+ * `defaultDtype` selected, so an existing Hugging Face cache resolves to the
47
+ * same blobs instead of re-downloading a quantized sibling.
48
+ */
49
+ const RERANK_MODELS = {
50
+ tiny: {
51
+ huggingFaceId: "Xenova/ms-marco-TinyBERT-L-2-v2",
52
+ dtype: "fp32"
53
+ },
54
+ mini: {
55
+ huggingFaceId: "Xenova/ms-marco-MiniLM-L-6-v2",
56
+ dtype: "fp32"
57
+ }
58
+ };
59
+ const DEFAULT_BATCH_SIZE = 32;
60
+ function sigmoid(x) {
61
+ if (x >= 0) return 1 / (1 + Math.exp(-x));
62
+ const z = Math.exp(x);
63
+ return z / (1 + z);
64
+ }
65
+ function softmax(logits) {
66
+ if (logits.length === 0) return [];
67
+ let max = logits[0];
68
+ for (const l of logits) if (l > max) max = l;
69
+ const exps = logits.map((l) => Math.exp(l - max));
70
+ const sum = exps.reduce((a, b) => a + b, 0);
71
+ if (sum === 0) return new Array(logits.length).fill(1 / logits.length);
72
+ return exps.map((e) => e / sum);
73
+ }
74
+ /**
75
+ * Raw logits → one `[0,1]` score.
76
+ *
77
+ * MS MARCO cross-encoders ship in both head shapes: TinyBERT/MiniLM v2 here
78
+ * are single-logit regression heads (sigmoid), while BGE-style bilingual
79
+ * rerankers emit two class logits (softmax, take class 1). Anything wider
80
+ * than two logits is not a reranking head we know, so the first logit is
81
+ * passed through rather than invented into a probability.
82
+ */
83
+ function normalizeScore(logits) {
84
+ if (logits.length === 1) return sigmoid(logits[0]);
85
+ if (logits.length === 2) return softmax(logits)[1];
86
+ return logits[0] ?? 0;
87
+ }
88
+ /**
89
+ * Build an encoder around an already-loaded tokenizer/model pair.
90
+ *
91
+ * The seam exists so unit tests can exercise ordering, batching and
92
+ * normalization without ONNX — `createCrossEncoder` is the only caller that
93
+ * needs the real library.
94
+ */
95
+ function makeCrossEncoder(parts) {
96
+ let disposed = false;
97
+ return {
98
+ async rerank(input) {
99
+ if (disposed) throw new Error("rerank: cross-encoder has been disposed");
100
+ const topN = input.topN;
101
+ if (input.documents.length === 0 || topN === 0) return [];
102
+ const batchSize = Number.isInteger(input.batchSize) && input.batchSize > 0 ? input.batchSize : DEFAULT_BATCH_SIZE;
103
+ const scores = new Array(input.documents.length);
104
+ for (let start = 0; start < input.documents.length; start += batchSize) {
105
+ const chunk = input.documents.slice(start, start + batchSize);
106
+ const queries = new Array(chunk.length).fill(input.query);
107
+ const inputs = await parts.tokenizer(queries, {
108
+ text_pair: chunk,
109
+ padding: true,
110
+ truncation: true
111
+ });
112
+ const raw = (await parts.model(inputs)).logits.tolist();
113
+ const rows = Array.isArray(raw[0]) ? raw : raw.map((v) => [v]);
114
+ for (let i = 0; i < rows.length; i++) scores[start + i] = normalizeScore(rows[i]);
115
+ }
116
+ const ranked = scores.map((score, index) => ({
117
+ index,
118
+ score
119
+ }));
120
+ ranked.sort((a, b) => b.score - a.score);
121
+ return topN !== void 0 && topN < ranked.length ? ranked.slice(0, topN) : ranked;
122
+ },
123
+ async dispose() {
124
+ if (disposed) return;
125
+ disposed = true;
126
+ try {
127
+ await parts.model.dispose?.();
128
+ } catch {}
129
+ }
130
+ };
131
+ }
132
+ /**
133
+ * Load transformers.js, preferring the shared `<APP_DIR>/optional` copy.
134
+ *
135
+ * The package is an optional PEER (547 MB with its ONNX runtime), so it is
136
+ * normally absent from the installed tree and present once per machine under
137
+ * APP_DIR. Resolution order, and why:
138
+ *
139
+ * 1. `optional/` copy — the payload the on-demand installer published. It is
140
+ * versioned and shared across github-router versions, so a version bump does
141
+ * not re-download it.
142
+ * 2. The package tree's own `node_modules` — the developer checkout, and the
143
+ * `npm i -g` case where the peer resolved.
144
+ * 3. Bare specifier — last resort, so a hoisted layout still works.
145
+ *
146
+ * A failure to load is NOT an error here: `rerank.ts` treats a rejection from
147
+ * this function as "reranking unavailable" and keeps BM25F order, which is the
148
+ * documented degradation. What must not happen is a hang or a crash on the
149
+ * import, so each candidate is tried in turn.
150
+ */
151
+ async function loadTransformers() {
152
+ const load = async (specifier) => {
153
+ try {
154
+ return await import(
155
+ /* @vite-ignore */
156
+ specifier
157
+ );
158
+ } catch {
159
+ return null;
160
+ }
161
+ };
162
+ const shared = installedOptional("@huggingface/transformers");
163
+ if (shared) {
164
+ const entry = pathToFileURL(path.join(shared, "dist/transformers.node.mjs")).href;
165
+ const loaded = await load(entry);
166
+ if (loaded) return loaded;
167
+ }
168
+ const local = await load("@huggingface/transformers");
169
+ if (local) return local;
170
+ scheduleOptionalInstall("@huggingface/transformers", process.argv[1]);
171
+ if (optionalInstallDisabled()) throw new Error("@huggingface/transformers is not installed and GH_ROUTER_NO_OPTIONAL_INSTALL is set; reranking falls back to BM25F");
172
+ throw new Error("@huggingface/transformers is not installed; reranking falls back to BM25F (run `github-router update` to install it)");
173
+ }
174
+ /**
175
+ * Download (or load from the transformers cache) one model tier.
176
+ *
177
+ * Throws on a network/cache failure — callers treat that as "reranking
178
+ * unavailable" and keep BM25F order (see `src/lib/rerank.ts`, which never
179
+ * lets this rejection escape).
180
+ */
181
+ async function createCrossEncoder(model) {
182
+ const info = RERANK_MODELS[model];
183
+ const { AutoModelForSequenceClassification, AutoTokenizer } = await loadTransformers();
184
+ const [tokenizer, sequenceClassifier] = await Promise.all([AutoTokenizer.from_pretrained(info.huggingFaceId), AutoModelForSequenceClassification.from_pretrained(info.huggingFaceId, { dtype: info.dtype })]);
185
+ return makeCrossEncoder({
186
+ tokenizer,
187
+ model: sequenceClassifier
188
+ });
189
+ }
190
+ export { createCrossEncoder };
191
+
192
+ //# sourceMappingURL=rerank-cross-encoder-BhjImuwG.js.map