github-router 0.3.379 → 0.3.380

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-BJ1fjX7V.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BJ1fjX7V.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-BWwkOMi3.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.js.map → claude-BWwkOMi3.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-C6ix3BaY.js} +8 -7
  23. package/dist/{codex-BG0pfud9.js.map → codex-C6ix3BaY.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-YhoA26wi.js} +383 -88
  99. package/dist/pi-YhoA26wi.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-DrHAX2Bh.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-DrHAX2Bh.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.js → server-setup-DLwejgVA.js} +12 -638
  119. package/dist/server-setup-DLwejgVA.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-DvV3Lbwy.js} +5 -4
  123. package/dist/{start-mnedD5cH.js.map → start-DvV3Lbwy.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":"bin.js","names":["process"],"sources":["../src/lib/exec.ts","../src/lib/volatile-root.ts","../src/lib/managed-install/diagnostics.ts","../src/lib/atomic-file.ts","../src/lib/managed-install/paths.ts","../src/lib/managed-install/state.ts","../src/lib/managed-install/origin.ts","../src/lib/managed-install/pointer.ts","../src/lib/managed-install/npm-env.ts","../src/lib/managed-install/bootstrap.ts","../src/bin.ts"],"sourcesContent":["/**\n * Windows-safe, injection-safe command execution helpers.\n *\n * Why this module exists: on Windows, npm-installed CLIs (`claude`,\n * `npm`, `codex`) are `.cmd`/`.bat` shims. Node's `execFile`/`spawn`\n * with `shell:false` cannot launch them (CreateProcess only resolves\n * `.exe`), so callers must invoke `cmd.exe` explicitly. Using\n * `shell:true` delegates quoting back to the runtime and breaks absolute shim\n * paths containing spaces, so this module builds one verified `/s /c`\n * envelope and asks CreateProcess to pass it verbatim. That opens two hazards\n * this module closes:\n *\n * 1. **Metacharacter injection** (`& | < > ^ ( ) ! %`). A naive\n * \"quote only tokens with spaces\" scheme lets `pkg@latest&calc`\n * run `calc` as a second command. `buildExecInvocation` applies\n * real cmd.exe quoting (argv-quote + caret-escape) and fails\n * closed on `%` (which cannot be reliably escaped on the cmd\n * command line).\n *\n * 2. **CWD shadowing.** `cmd.exe` resolves a bare `npm` from the\n * current directory before PATH, so an untrusted repo can plant\n * `npm.cmd`. `resolveExecutable` resolves to an absolute path\n * against PATH only (honoring PATHEXT), never the cwd, so callers\n * spawn the real binary by absolute path.\n *\n * All runners are best-effort and timeout-bounded; callers wrap in\n * try/catch and never let an update/probe failure block launch.\n */\n\nimport { spawn, spawnSync, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\n/**\n * Parse a boolean-ish env value. Returns `undefined` when unset or\n * unrecognized so callers can apply their own default. Accepts\n * `1|true|yes|on` (true) and `0|false|no|off|<empty>` (false),\n * case-insensitive. The single shared parser for all new `GH_ROUTER_*`\n * flags so on/off semantics don't drift per call site.\n */\nexport function parseBoolEnv(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined\n const v = value.trim().toLowerCase()\n if (v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\") return true\n if (v === \"0\" || v === \"false\" || v === \"no\" || v === \"off\" || v === \"\") {\n return false\n }\n return undefined\n}\n\n/**\n * Parse a positive-integer env value. Returns `undefined` when unset, empty, or\n * not a clean positive integer, so callers apply their own default.\n *\n * The single shared parser for numeric `GH_ROUTER_*` knobs, and it deliberately\n * uses `Number()` rather than `parseInt()`. `parseInt` stops at the first\n * character it cannot consume, so it silently truncates instead of rejecting:\n * `\"3e5\"` becomes 3, `\"300_000\"` becomes 300, `\"60000ms\"` becomes 60000. For a\n * timeout or a concurrency cap that is the worst possible failure — a user who\n * writes `GH_ROUTER_STOP_GATE_TIMEOUT_MS=3e5` intending five minutes gets three\n * MILLISECONDS, and the resulting instant failure looks like a product bug\n * rather than a typo. Falling back to the documented default is strictly safer\n * than honouring a number the user never meant.\n *\n * Found by a cross-lab reviewer during a capability audit, at three shipped call\n * sites, while three separate local helpers in this repo already parsed the same\n * shape correctly and one of them documented this exact hazard. That is the\n * argument for one shared parser rather than a fourth copy.\n */\nexport function parseIntEnv(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const raw = value.trim()\n if (raw === \"\") return undefined\n const n = Number(raw)\n if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return undefined\n return n\n}\n\n/** Read the PATH value from an env object, case-insensitively. */\nfunction pathValueOf(env: NodeJS.ProcessEnv): string {\n for (const key of Object.keys(env)) {\n if (key.toLowerCase() === \"path\") return env[key] ?? \"\"\n }\n return \"\"\n}\n\nexport interface ResolveExecutableOpts {\n env?: NodeJS.ProcessEnv\n platform?: NodeJS.Platform\n /** Directory to treat as \"current dir\" and exclude from resolution. */\n cwd?: string\n}\n\n/**\n * Resolve an executable name to an absolute path against PATH, honoring\n * `PATHEXT` on Windows and **excluding the current working directory**.\n *\n * Returns `null` when unresolved — callers treat that as \"tool absent\"\n * and skip (best-effort). Spawning the returned absolute path means\n * `cmd.exe`'s implicit cwd-first lookup never applies, closing the\n * planted-`npm.cmd` vector.\n */\nexport function resolveExecutable(\n name: string,\n opts: ResolveExecutableOpts = {},\n): string | null {\n const platform = opts.platform ?? process.platform\n const env = opts.env ?? process.env\n // Defensive: some test harnesses mock `node:process` without `cwd`.\n // Absent a usable cwd we simply skip the cwd-exclusion guard (the\n // returned absolute path already bypasses cmd.exe's cwd-first lookup).\n const cwdRaw =\n opts.cwd ?? (typeof process.cwd === \"function\" ? process.cwd() : undefined)\n const resolvedCwd = cwdRaw ? path.resolve(cwdRaw) : null\n\n const dirs = pathValueOf(env)\n .split(path.delimiter)\n // Drop empty entries and a literal \".\" — both denote the cwd on\n // Windows, which we explicitly refuse to resolve against.\n .filter((d) => d.length > 0 && d !== \".\")\n\n const isWin = platform === \"win32\"\n\n // POSIX: an explicit path component → resolve directly.\n if (!isWin && name.includes(\"/\")) {\n return existsSync(name) ? path.resolve(name) : null\n }\n // Windows: an explicit path component (with a separator) → direct.\n if (isWin && (name.includes(\"\\\\\") || name.includes(\"/\"))) {\n return existsSync(name) ? path.resolve(name) : null\n }\n\n const exts =\n isWin && path.extname(name) === \"\"\n ? (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim())\n .filter(Boolean)\n : [\"\"]\n\n for (const dir of dirs) {\n // Belt-and-suspenders: never resolve against the cwd even if it is\n // listed explicitly in PATH.\n if (resolvedCwd && path.resolve(dir) === resolvedCwd) continue\n for (const ext of exts) {\n const candidate = path.join(dir, name + ext)\n if (existsSync(candidate)) return candidate\n }\n }\n return null\n}\n\n/**\n * Quote one argument for a `cmd.exe /c \"<line>\"` command line so the\n * target program receives it verbatim and no `cmd.exe` metacharacter\n * retains shell meaning.\n *\n * Two phases (the canonical Windows approach — Colascione / Rust std):\n * 1. **argv quoting** so `CommandLineToArgvW` in the target parses\n * the token as one argument (double-quote, backslash-escape).\n * 2. **caret-escaping** every `cmd.exe` metacharacter — including the\n * quotes from phase 1 — so `cmd.exe` is never in quote-mode, strips\n * the carets, and hands the argv-quoted string to the program.\n *\n * `%` is special: it cannot be reliably escaped on the `cmd.exe`\n * *command line* (caret does not stop `%VAR%` expansion there). Rather\n * than mis-escape, we **throw** — our callers never pass `%`, so this\n * fails closed on the one unescapable injection vector.\n */\nexport function quoteWinArg(arg: string): string {\n if (arg.includes(\"%\")) {\n throw new Error(\n \"buildExecInvocation: argument contains '%', which cannot be safely \" +\n \"escaped on the Windows command line; refusing to build the command.\",\n )\n }\n\n // Phase 1 — argv quoting.\n let quoted: string\n if (arg.length > 0 && !/[ \\t\\n\\v\"&|<>()^!]/.test(arg)) {\n quoted = arg\n } else {\n let s = '\"'\n let backslashes = 0\n for (const ch of arg) {\n if (ch === \"\\\\\") {\n backslashes++\n } else if (ch === '\"') {\n s += \"\\\\\".repeat(backslashes * 2 + 1) + '\"'\n backslashes = 0\n } else {\n s += \"\\\\\".repeat(backslashes) + ch\n backslashes = 0\n }\n }\n s += \"\\\\\".repeat(backslashes * 2) + '\"'\n quoted = s\n }\n\n // Phase 2 — caret-escape all cmd.exe metacharacters (and the carets\n // themselves). cmd strips these; the program sees the phase-1 string.\n return quoted.replace(/[()!^\"<>&|]/g, \"^$&\")\n}\n\nexport interface ExecInvocation {\n command: string\n args: string[]\n shell: boolean\n /** Pass our already-quoted cmd.exe payload directly to CreateProcess. */\n windowsVerbatimArguments?: boolean\n}\n\nfunction assertSafeBatchToken(value: string, kind: \"executable\" | \"argument\"): void {\n const hasControl = [...value].some((char) => char.charCodeAt(0) < 0x20)\n if (hasControl || value.includes('\"') || value.includes(\"%\")) {\n throw new Error(\n `buildExecInvocation: ${kind} contains a character that cannot be `\n + \"safely passed through cmd.exe; refusing to build the command.\",\n )\n }\n}\n\nfunction quoteBatchArg(arg: string): string {\n assertSafeBatchToken(arg, \"argument\")\n // `/s` removes the envelope's outer quotes before cmd parses this token.\n // Quotes keep spaces, parentheses, and `!` (with /v:OFF) literal; the four\n // always-active operators and the caret itself still need caret escaping.\n return `\"${arg.replaceAll(\"^\", \"^^\").replace(/[&|<>]/g, \"^$&\")}\"`\n}\n\nfunction windowsCmdExe(): string {\n const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT\n return systemRoot\n ? path.win32.join(systemRoot, \"System32\", \"cmd.exe\")\n : (process.env.ComSpec ?? \"cmd.exe\")\n}\n\n/**\n * Is this a Windows batch script rather than a real executable?\n *\n * The distinction is load-bearing for every caller that spawns with\n * `shell:false`: CreateProcess only resolves `.exe`/`.com`, so a `.cmd`/`.bat`\n * path throws `EINVAL` at spawn time even though `resolveExecutable` returned\n * it happily. `buildExecInvocation` is the one helper that can use such a\n * path, because it routes it through `cmd.exe`; anywhere else a shim is\n * indistinguishable from a missing binary, and code that treats it as present\n * gets a failure it did not predict.\n *\n * The observed case: ast-grep installed globally through npm. `resolveAstGrep`\n * returned `ast-grep.cmd`, `runManagedExeCapture` threw `EINVAL`, and\n * `mode:\"ast\"` could not run on the canonical Windows host while the version\n * probe (which DOES go through `buildExecInvocation`) read the shim as a\n * perfectly adequate 0.45.3.\n */\nexport function isWindowsScriptShim(resolved: string): boolean {\n if (process.platform !== \"win32\") return false\n return /\\.(cmd|bat)$/i.test(resolved)\n}\n\n/**\n * Build the platform-correct `spawn` invocation for a command given as\n * an argv array. Pure / unit-testable (no spawn).\n *\n * - win32 native executables (`.exe`/`.com`) → direct spawn with split\n * argv. This avoids cmd.exe quoting and correctly handles absolute paths\n * containing spaces (for example `C:\\\\Program Files\\\\Git\\\\...\\\\git.exe`).\n * - win32 batch shims (`.cmd`/`.bat`) → explicit cmd.exe with `shell:false`\n * and one verbatim `/s /c` envelope. Every token is quoted, so shell\n * metacharacters are data; `%`, quotes, and controls fail closed.\n * - unresolved win32 bare commands retain the legacy quoted `shell:true`\n * path. Normal callers resolve first, so this is only a compatibility\n * fallback.\n * - posix → `(cmd[0], cmd.slice(1))` with `shell:false` — no shell,\n * no injection surface.\n */\nexport function buildExecInvocation(\n cmd: string[],\n platform: NodeJS.Platform = process.platform,\n): ExecInvocation {\n if (cmd.length === 0) throw new Error(\"buildExecInvocation: empty command\")\n if (platform === \"win32\") {\n const ext = path.extname(cmd[0]).toLowerCase()\n if (ext === \".exe\" || ext === \".com\") {\n return { command: cmd[0], args: cmd.slice(1), shell: false }\n }\n if (ext === \".cmd\" || ext === \".bat\") {\n if (!path.win32.isAbsolute(cmd[0])) {\n throw new Error(\n \"buildExecInvocation: Windows batch executable must be an absolute path\",\n )\n }\n assertSafeBatchToken(cmd[0], \"executable\")\n const line = `\"\"${cmd[0]}\"${cmd\n .slice(1)\n .map((arg) => ` ${quoteBatchArg(arg)}`)\n .join(\"\")}\"`\n return {\n command: windowsCmdExe(),\n args: [\"/d\", \"/s\", \"/v:OFF\", \"/c\", line],\n shell: false,\n windowsVerbatimArguments: true,\n }\n }\n return { command: cmd.map(quoteWinArg).join(\" \"), args: [], shell: true }\n }\n return { command: cmd[0], args: cmd.slice(1), shell: false }\n}\n\nexport interface RunOpts {\n cwd?: string\n /** Hard timeout in ms; the process tree is killed on expiry. */\n timeoutMs?: number\n /** Extra env to merge over the parent env for the child. */\n env?: NodeJS.ProcessEnv\n /** Abort the command and kill its process tree when the signal fires. */\n signal?: AbortSignal\n /**\n * Byte ceiling on captured stdout. Defaults to {@link DEFAULT_CAPTURE_CAP}.\n *\n * On overflow we STOP BUFFERING but deliberately do NOT kill the child, and\n * the result is reported as a normal completion with `truncated: true`. That\n * asymmetry against `runManagedExeCapture` (which tree-kills on overflow) is\n * load-bearing: callers here read the exit CODE as a verdict —\n * `~/lib/orchestration/live-exec` maps `code ?? 1` onto a FAILED GATE — so\n * killing the child would turn \"this command printed a lot\" into \"typecheck\n * failed\". Truncation is a capture-side limit, never a command outcome.\n *\n * The data handler keeps firing and discarding after the cap, so the pipe\n * drains and the child never blocks writing into a full buffer.\n */\n maxStdoutBytes?: number\n}\n\n/**\n * Default stdout capture ceiling.\n *\n * A `timeoutMs` is NOT a memory bound: `git diff HEAD` on a repo with a large\n * generated file happily emits hundreds of MB inside a 5s window, and every\n * byte was being concatenated onto one JS string. 16 MiB matches the worker\n * layer's `GH_ROUTER_WORKER_MAX_TOOL_BYTES` so the two capture paths agree on\n * what \"too much output to be useful\" means.\n */\nexport const DEFAULT_CAPTURE_CAP = 16 * 1024 * 1024\n\n/** Same ceiling shape for stderr, which only ever feeds diagnostics. */\nconst CAPTURE_STDERR_CAP = 64 * 1024\n\nexport interface RunResult {\n stdout: string\n stderr: string\n /** Exit code; `null` when killed by signal/timeout. */\n code: number | null\n timedOut: boolean\n /**\n * True when stdout exceeded the cap and was cut short. The command itself\n * still ran to completion — check this, never `code`, to detect truncation.\n */\n truncated: boolean\n /**\n * True when stderr exceeded its 64 KiB ceiling and was cut short.\n *\n * Reported separately from `truncated` because it means something different\n * to a caller: stdout truncation loses DATA, stderr truncation loses a\n * DIAGNOSTIC. A failing compiler often puts the root error at the tail of a\n * long stderr, so a caller that surfaces stderr to a human needs to know it\n * is looking at a prefix rather than the whole story.\n */\n stderrTruncated: boolean\n}\n\nfunction runInternal(\n cmd: string[],\n stdoutMode: \"pipe\" | \"inherit\" | \"ignore\",\n opts: RunOpts,\n): Promise<RunResult> {\n const { command, args, shell, windowsVerbatimArguments } =\n buildExecInvocation(cmd)\n return new Promise<RunResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell,\n windowsVerbatimArguments,\n windowsHide: true,\n stdio: [\n \"ignore\",\n stdoutMode,\n stdoutMode === \"inherit\" ? \"inherit\" : \"pipe\",\n ],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // Buffer BYTES and decode once at the end (or incrementally through a\n // streaming decoder). The previous `stdout += chunk.toString(\"utf8\")` per\n // chunk corrupted any multi-byte character that straddled a chunk\n // boundary — a 3-byte `→` split 1/2 decoded as two replacement chars, so\n // captured diffs and command output silently mangled non-ASCII.\n const stdoutDecoder = new TextDecoder()\n const stderrDecoder = new TextDecoder()\n let stdout = \"\"\n let stderr = \"\"\n let stdoutBytes = 0\n let stderrBytes = 0\n let truncated = false\n let stderrTruncated = false\n let timedOut = false\n let settled = false\n const maxStdoutBytes = opts.maxStdoutBytes ?? DEFAULT_CAPTURE_CAP\n\n const timer = opts.timeoutMs\n ? setTimeout(() => {\n timedOut = true\n killTree(child.pid)\n }, opts.timeoutMs)\n : undefined\n timer?.unref?.()\n const onAbort = () => killTree(child.pid)\n if (opts.signal?.aborted) onAbort()\n else opts.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n // Past the cap: keep draining the pipe, stop growing the string. The\n // child is intentionally left alive (see `maxStdoutBytes` docs).\n if (truncated) return\n const room = maxStdoutBytes - stdoutBytes\n if (c.length > room) {\n // Append only the slice that fits, then stop. `stream: true` lets the\n // decoder hold a partial code point back rather than emit U+FFFD, so a\n // cap landing mid-character truncates cleanly instead of corrupting.\n if (room > 0) {\n stdout += stdoutDecoder.decode(c.subarray(0, room), { stream: true })\n stdoutBytes += room\n }\n truncated = true\n return\n }\n stdout += stdoutDecoder.decode(c, { stream: true })\n stdoutBytes += c.length\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n // Already full: this chunk is dropped entirely, which is truncation just\n // as much as a partial slice is. Flagging only the slicing chunk missed\n // the common case where the cap lands on a chunk boundary and every\n // subsequent chunk returns here.\n if (stderrBytes >= CAPTURE_STDERR_CAP) {\n stderrTruncated = true\n return\n }\n const room = CAPTURE_STDERR_CAP - stderrBytes\n const slice = c.length > room ? c.subarray(0, room) : c\n if (slice.length < c.length) stderrTruncated = true\n stderr += stderrDecoder.decode(slice, { stream: true })\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n // Flush the decoders' held-back bytes.\n //\n // NOT flushed on the truncated path: the cap deliberately cuts mid-byte-\n // sequence, so the decoder is holding a partial code point we chose to\n // drop. Flushing it would emit U+FFFD — turning a clean truncation into\n // apparent corruption, which is the exact failure this fix removes.\n // Un-truncated output has no such intent, so a trailing partial there IS\n // malformed input and should surface as U+FFFD rather than vanish.\n if (!truncated) stdout += stdoutDecoder.decode()\n if (!stderrTruncated) stderr += stderrDecoder.decode()\n resolve({ stdout, stderr, code, timedOut, truncated, stderrTruncated })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Spawn `taskkill` best-effort, without any chance of taking the proxy down.\n *\n * Two things a bare `try { spawn(\"taskkill\", ...) } catch {}` gets wrong, both\n * of which this helper is the single place that fixes:\n *\n * 1. **The catch cannot catch.** `spawn` reports ENOENT / EPERM / EACCES by\n * emitting `'error'` ASYNCHRONOUSLY, so the surrounding `try` (which only\n * guards the synchronous throw) never sees it. An EventEmitter `'error'`\n * with no listener THROWS — which lands in the `uncaughtException` handler\n * in `~/main` and calls `process.exit(1)`. A best-effort child kill on a\n * timeout path could therefore kill the whole proxy. The listener must be\n * attached synchronously at the spawn site, which is why this is a helper\n * and not a convention.\n * 2. **The bare name is hijackable.** `CreateProcess`'s search order can\n * include the cwd, so `\"taskkill\"` may resolve to a planted binary;\n * `taskkillExe()` pins `System32\\taskkill.exe`.\n */\nexport function spawnTaskkillBestEffort(pid: number): boolean {\n try {\n const child = spawn(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n // Load-bearing: see (1) above. Without this an async spawn failure is an\n // uncaught exception, not a no-op. It is NOT a silent swallow, either —\n // the fallback below is what keeps a caller from hanging.\n //\n // (No logging here on purpose: this module has no logger import, and\n // taking one would pull a dependency into the lowest-level exec helper\n // that every other module builds on. The fallback is the observable\n // behavior that matters.)\n child.on(\"error\", () => {\n fallbackKill(pid)\n })\n return true\n } catch {\n // Synchronous spawn failure (bad argv shape).\n fallbackKill(pid)\n return false\n }\n}\n\n/**\n * Last-resort single-process kill when `taskkill` itself cannot run.\n *\n * Not a tree kill — grandchildren survive — but it is the difference between\n * \"the timed-out child dies and its `close` event settles the caller\" and \"the\n * caller waits forever\". `runInternal` resolves ONLY from `close`, so a timeout\n * whose kill never lands leaves that promise pending for the life of the\n * process, which is a worse failure than the crash `spawnTaskkillBestEffort`\n * was written to prevent. Best-effort by construction: ESRCH means the child\n * was already gone, which is the success case.\n */\nfunction fallbackKill(pid: number): void {\n try {\n process.kill(pid)\n } catch {\n // Already exited, or we lack permission — nothing further to try.\n }\n}\n\n/** Kill a process tree best-effort (taskkill /T on Windows). */\nfunction killTree(pid: number | undefined): void {\n if (!pid) return\n try {\n if (process.platform === \"win32\") {\n spawnTaskkillBestEffort(pid)\n } else {\n process.kill(pid, \"SIGTERM\")\n }\n } catch {\n // already gone\n }\n}\n\n/** Run a command and capture stdout/stderr. Rejects on spawn error. */\nexport function runCommandCapture(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command discarding output (still captures stderr for errors). */\nexport function runCommandVoid(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command with the child's stdout/stderr inherited to the user. */\nexport function runCommandInherit(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"inherit\", opts)\n}\n\nexport interface ManagedExeOpts extends RunOpts {\n /**\n * Hard cap on captured stdout bytes. On overflow the child is\n * tree-killed and the result carries `stdoutTruncated: true`. Defends\n * against a full-`CodeUnit` colgrep `--json` payload (source + 5\n * analysis layers per hit) bloating memory.\n */\n maxStdoutBytes?: number\n /**\n * When true, exceeding `maxStdoutBytes` does NOT tree-kill the child — it\n * sets `stdoutTruncated` and stops BUFFERING further stdout while still\n * draining the pipe (no backpressure). Use for a child whose kill is unsafe\n * (e.g. colgrep, which writes a non-atomic index — a byte-cap kill during\n * its result output could interrupt a write). The child runs to completion\n * (bounded by `timeoutMs` / `inactivityTimeoutMs`). Default false (kill).\n */\n truncateInsteadOfKill?: boolean\n /**\n * Called synchronously with the spawned child right after spawn\n * succeeds, BEFORE any output arrives. The colbert lifecycle ledger\n * uses this to register the child so a session-exit sweep can\n * tree-kill an orphan. Never throws into the runner.\n */\n onSpawn?: (child: ReturnType<typeof spawn>) => void\n /**\n * Inactivity (stall) watchdog. When set, a timer is armed for\n * `inactivityTimeoutMs` and RESET on every stdout/stderr data chunk. On\n * expiry (no output for the window) it consults `onInactivityCheck`: a\n * `true` return means \"still making progress via an out-of-band signal\"\n * (e.g. the colgrep index dir is still growing on disk even though the\n * process is silent on a non-TTY pipe) and the watchdog re-arms; a\n * `false`/absent return tree-kills the child and sets `stalled: true`.\n * This is the progress-based \"stuck\" detector that lets a long-but-\n * progressing build run to completion while still killing a hung one —\n * independent of the coarse total `timeoutMs` backstop.\n */\n inactivityTimeoutMs?: number\n /** External progress probe consulted when the inactivity timer fires.\n * Return `true` to re-arm (still progressing), `false`/throw to kill.\n * MUST be cheap + synchronous (called on a timer, not awaited). */\n onInactivityCheck?: () => boolean\n}\n\nexport interface ManagedExeResult extends RunResult {\n /** True iff stdout was truncated at `maxStdoutBytes` (child was killed). */\n stdoutTruncated: boolean\n /** True iff the inactivity watchdog killed the child (no progress). */\n stalled: boolean\n}\n\n/**\n * Run a **native executable** (a real `.exe`/Mach-O/ELF, NOT a `.cmd`\n * shim) capturing stdout/stderr, with `shell:false` on EVERY platform.\n *\n * Why a separate runner from `runCommandCapture`: that path routes\n * through `buildExecInvocation`, which on Windows builds a\n * `cmd.exe`-quoted command string and **throws on `%`** (`quoteWinArg`).\n * A workspace path can legally contain `%` (and `&`, `(`, `)`, `!`, …),\n * so the managed colgrep binary — which IS a native `.exe`, not a shim —\n * must bypass cmd.exe entirely. `spawn(absExe, args, {shell:false})`\n * resolves the `.exe` via CreateProcess directly: no cmd.exe, no\n * metacharacter hazard, no `%` refusal. POSIX was already `shell:false`.\n * This is what makes \"ANY absolute workspace\" hold on Windows.\n *\n * Lifecycle:\n * - `timeoutMs` → tree-kill on expiry (`taskkill /T /F` on Windows,\n * POSIX process-group `kill(-pgid)` so colgrep's rayon worker\n * children die too). `timedOut: true` in the result.\n * - `maxStdoutBytes` → tree-kill + `stdoutTruncated: true` once the\n * captured stdout exceeds the cap.\n * - `onSpawn(child)` → register the child with the caller's ledger.\n *\n * `command` MUST be an absolute path to the executable (the caller\n * resolves it; we never search PATH here — there is nothing to inject).\n */\nexport function runManagedExeCapture(\n command: string,\n args: ReadonlyArray<string>,\n opts: ManagedExeOpts = {},\n): Promise<ManagedExeResult> {\n const isWin = process.platform === \"win32\"\n return new Promise<ManagedExeResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, [...args], {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: false,\n windowsHide: true,\n // POSIX: new process group so we can kill the whole tree\n // (colgrep + rayon workers) with kill(-pgid). Windows uses\n // taskkill /T instead; `detached` there has no group semantics.\n detached: !isWin,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n try {\n opts.onSpawn?.(child)\n } catch {\n // ledger registration must never break the spawn\n }\n\n const chunks: Array<Buffer> = []\n let stdoutBytes = 0\n const stderrChunks: Array<Buffer> = []\n let stderrBytes = 0\n const STDERR_CAP = 64 * 1024\n let timedOut = false\n let stdoutTruncated = false\n let stalled = false\n let settled = false\n\n // Exactly one terminator wins: the first to fire records its reason and\n // tree-kills; later ones no-op. Keeps timedOut / stalled / stdoutTruncated\n // mutually exclusive and avoids a double tree-kill.\n let terminated = false\n const terminate = (reason: \"timeout\" | \"stall\" | \"truncate\"): void => {\n if (terminated) return\n terminated = true\n if (reason === \"timeout\") timedOut = true\n else if (reason === \"stall\") stalled = true\n else stdoutTruncated = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n killManagedTree(child, isWin)\n }\n\n const timer = opts.timeoutMs\n ? setTimeout(() => terminate(\"timeout\"), opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n // Inactivity (stall) watchdog. Re-arms itself: when the window elapses\n // with no output, consult the external progress probe — re-arm if it\n // says \"still progressing\" (e.g. the index dir grew), else kill + mark\n // stalled. Reset on every data chunk (a chatty process never stalls).\n let inactivityTimer: ReturnType<typeof setTimeout> | undefined\n const armInactivity = (): void => {\n if (opts.inactivityTimeoutMs === undefined || settled || terminated) return\n inactivityTimer = setTimeout(() => {\n if (settled) return\n // No probe → pure output-inactivity kill. A probe that THROWS is\n // inconclusive → don't kill (re-arm); the absolute timeoutMs backstop\n // still catches a genuinely wedged process.\n let progressing = false\n if (opts.onInactivityCheck) {\n try {\n progressing = opts.onInactivityCheck() === true\n } catch {\n progressing = true\n }\n }\n if (progressing) {\n armInactivity()\n return\n }\n terminate(\"stall\")\n }, opts.inactivityTimeoutMs)\n inactivityTimer?.unref?.()\n }\n const resetInactivity = (): void => {\n if (inactivityTimer) clearTimeout(inactivityTimer)\n armInactivity()\n }\n armInactivity()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n if (stdoutTruncated) return\n stdoutBytes += c.length\n if (\n opts.maxStdoutBytes !== undefined &&\n stdoutBytes > opts.maxStdoutBytes\n ) {\n stdoutTruncated = true\n // Default: tree-kill on overflow. Opt-in: keep the child alive and\n // just stop buffering (the data handler keeps firing + discarding via\n // the `if (stdoutTruncated) return` guard above, so the pipe drains\n // and the child never blocks on a full buffer).\n if (!opts.truncateInsteadOfKill) terminate(\"truncate\")\n return\n }\n chunks.push(c)\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n // Hard byte cap on stderr — append only the slice that fits so a\n // single huge chunk can't overshoot. Never logged raw (it can\n // embed source code from colgrep).\n if (stderrBytes >= STDERR_CAP) return\n const remaining = STDERR_CAP - stderrBytes\n const slice = c.length > remaining ? c.subarray(0, remaining) : c\n stderrChunks.push(slice)\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n resolve({\n stdout: Buffer.concat(chunks).toString(\"utf8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf8\"),\n code,\n timedOut,\n stdoutTruncated,\n // `RunResult.truncated` is the shared, runner-agnostic signal. Kept in\n // lockstep with `stdoutTruncated` (this runner's older, more specific\n // name, which callers already branch on) so a caller holding either\n // shape reads the same fact.\n truncated: stdoutTruncated,\n // This runner slices stderr to fit its own 64 KiB cap without tracking\n // whether it did, so report the honest thing rather than guess.\n stderrTruncated: stderrBytes >= STDERR_CAP,\n stalled,\n })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Tree-kill a managed child. Windows: `taskkill /T /F /PID` (whole\n * tree). POSIX: kill the process GROUP (`-pgid`) so colgrep's rayon\n * worker children die with the parent.\n *\n * `runManagedExeCapture` always spawns POSIX children `detached:true`\n * (their own process group), so the group kill is the correct and\n * sufficient primitive. We deliberately do NOT fall back to a positive-\n * pid `process.kill(pid)` when the group kill fails: by the time a kill\n * fires (timeout / byte-cap race), the child may have already exited and\n * its PID been recycled by an unrelated process — a positive-pid kill\n * would then target the wrong process. `ESRCH` (group already gone) is\n * the success case for our purposes; any other error is swallowed.\n */\nexport function killManagedTree(\n child: ReturnType<typeof spawn>,\n isWin: boolean = process.platform === \"win32\",\n): void {\n const pid = child.pid\n if (!pid) return\n try {\n if (isWin) {\n spawnTaskkillBestEffort(pid)\n } else {\n // Negative pid → the process group (we spawned detached). No\n // positive-pid fallback (PID-reuse hazard — see doc comment).\n process.kill(-pid, \"SIGKILL\")\n }\n } catch {\n // ESRCH (already gone) / EPERM — best-effort, nothing more to do.\n }\n}\n\n/**\n * Absolute path to Windows `taskkill.exe`. Bare `\"taskkill\"` would let\n * `CreateProcess`'s search order (which can include the cwd) run a planted\n * `taskkill.exe`; pinning the System32 path closes that hijack.\n */\nfunction taskkillExe(): string {\n const root =\n process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\"\n return path.join(root, \"System32\", \"taskkill.exe\")\n}\n\n/**\n * Tree-kill a child process on a SHUTDOWN/exit path, deterministically.\n *\n * Distinct from `killManagedTree` in two ways that matter when the proxy\n * is about to call `process.exit`:\n *\n * 1. **Windows uses `spawnSync`, not async `spawn`.** An async taskkill\n * may never issue before `process.exit` tears the event loop down;\n * the synchronous form guarantees the kill command has run. It is\n * time-bounded so a wedged taskkill can't hang shutdown.\n * 2. **POSIX honors `detachedGroup`.** The launched CLI is spawned\n * `detached:true` (its own process group) so `kill(-pid)` reaps the\n * whole group; other callers (e.g. ripgrep) are NOT detached, so\n * `child.kill()` on the positive pid is correct. A negative-pid kill\n * on a non-detached child would throw or hit the wrong target.\n *\n * Both branches escalate SIGTERM → SIGKILL after `graceMs` so a CLI that\n * traps SIGTERM still dies. The escalation timer is `.unref()`'d so it\n * never holds the event loop open. Errors are swallowed (already-gone /\n * EBUSY / ESRCH are the success case for our purposes).\n */\nexport function killChildProcessTree(\n child: ChildProcess,\n opts: { detachedGroup: boolean; graceMs?: number } = { detachedGroup: false },\n): void {\n const pid = child.pid\n if (!pid) return\n const graceMs = opts.graceMs ?? 500\n\n if (process.platform === \"win32\") {\n // /T = whole tree, /F = force. taskkill walks the live parent-PID\n // chain, so it reaps grandchildren regardless of the cmd.exe-vs-direct\n // spawn shape. Sync (completes before an imminent process.exit) and\n // time-bounded (a wedged taskkill must not hang shutdown).\n try {\n spawnSync(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n timeout: 5000,\n })\n } catch {\n // Already gone / EBUSY race — best-effort.\n }\n return\n }\n\n // POSIX: signal the group (detached) or the lone child (non-detached).\n const target = opts.detachedGroup ? -pid : pid\n try {\n process.kill(target, \"SIGTERM\")\n } catch {\n // ESRCH — already gone.\n }\n const t = setTimeout(() => {\n // For a lone (non-detached) child, skip escalation once it has exited\n // — its positive PID could have been recycled. For a process GROUP the\n // leader's exit does NOT mean the group is empty (a SIGTERM-ignoring\n // grandchild may survive), and the group id is only reused once the\n // group is fully gone, so always attempt the group SIGKILL (ESRCH when\n // already empty is the success case).\n if (\n !opts.detachedGroup &&\n (child.exitCode !== null || child.signalCode !== null)\n ) {\n return\n }\n try {\n process.kill(target, \"SIGKILL\")\n } catch {\n // Already dead.\n }\n }, graceMs)\n t.unref?.()\n}\n","/**\n * \"Could the OS delete this path while we are not looking?\"\n *\n * One predicate, two consumers with the same question and different stakes:\n *\n * - `hook-launcher/self-invocation.ts` asks it about a PERSISTED hook command, so\n * the answer drives a user-facing warning;\n * - `managed-install/origin.ts` asks it about the running code, so the answer\n * drives \"is this tree disposable enough to replace with the managed install\".\n *\n * It lives alone here because `origin.ts` is imported by the bootstrap bundle\n * (`dist/bin.js`), which must not pull `consola`, `PATHS`, or the hook-launcher\n * provisioning graph just to compare two path prefixes. Hence: `node:` builtins\n * only, no logging, no app state.\n *\n * Why it cannot be a bare prefix test: `os.tmpdir()` reports `/var/folders/…` on\n * macOS while a process sees `/private/var/folders/…`, so a single-form compare\n * silently never matches. Both sides are therefore compared in resolved AND\n * unresolved form, and `realpath` failure (a path that does not exist, which is\n * the normal case for a hook command that has not run yet) must not change the\n * answer.\n */\n\nimport { realpathSync } from \"node:fs\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nexport function realpathIfPossible(file: string): string {\n try {\n return realpathSync(file)\n } catch {\n return file\n }\n}\n\n/**\n * Whether `target` sits under a directory the OS is entitled to clean out from\n * under a running session: the per-user temp dir on every platform, which is\n * where `bunx` (unlike `npx`, which uses a cache under `$HOME`) installs.\n */\nexport function isUnderVolatileRoot(target: string): boolean {\n try {\n const prefixes = new Set<string>()\n for (const root of [os.tmpdir(), realpathIfPossible(os.tmpdir())]) {\n prefixes.add(root.endsWith(path.sep) ? root : root + path.sep)\n }\n const targets = [target, realpathIfPossible(target)]\n return targets.some((candidate) => [...prefixes].some((prefix) => candidate.startsWith(prefix)))\n } catch {\n return false\n }\n}\n","/**\n * Diagnostics sink for the managed-install layer.\n *\n * Why not `consola` directly: this layer is imported by `dist/bin.js`, which is a\n * separate bundle from `dist/main.js`. Both bundles would carry their own copy of\n * `consola`, and the bin copy's instance is a different object with different\n * configuration than the one `main.ts` configures — so a message logged through it\n * could go to a different reporter, or to none. The bin bundle also has to stay\n * cheap: it runs before anything else and must not pull a logging stack for one\n * debug line.\n *\n * So the layer takes a sink. `main.ts` installs the consola-backed one at startup\n * (`setManagedDiagnosticReporter`), and everything else is a no-op. Nothing in\n * this module is on a hot path.\n */\n\nexport type ManagedDiagnosticLevel = \"debug\" | \"warn\" | \"info\"\n\nexport type ManagedDiagnostic = (level: ManagedDiagnosticLevel, message: string) => void\n\nlet reporter: ManagedDiagnostic | undefined\n\n/** Install the process-wide reporter. Called once from `main.ts`. */\nexport function setManagedDiagnosticReporter(next: ManagedDiagnostic | undefined): void {\n reporter = next\n}\n\nexport function reportManagedDiagnostic(level: ManagedDiagnosticLevel, message: string): void {\n reporter?.(level, message)\n}\n","/**\n * Atomic file replacement, shared by every durable pointer this codebase keeps\n * on disk (credentials, settings, the managed-install pointer).\n *\n * Why a module: the same three-step dance — write a pretend temp beside the\n * destination, `rename` over it, retry through a transient Windows lock — had\n * been re-implemented four times (`token.ts`, `cloudagent-hook-settings.ts`,\n * `claude-md-injection.ts`, `first-mate/durable-store.ts`) with slightly\n * different retry lists. The managed installer adds a fifth and, unlike the\n * others, runs it unattended in the middle of an update where a `EPERM` is the\n * difference between \"updated\" and \"silently did nothing\". So it lives here and\n * the four existing callers keep their behaviour by delegating.\n *\n * The invariants every writer here guarantees:\n *\n * - **no partial destination.** A reader sees either the old bytes or the new\n * bytes. `writeFile` at the destination truncates first, so a crash, a full\n * disk, or a kill leaves a truncated file — for `current.json` that means a\n * launch that cannot resolve its own payload.\n * - **durability.** The file is `fsync`ed before the rename and the parent\n * directory after it, so a power loss cannot leave the rename in the journal\n * with the content still in page cache. (`fsync` on a directory is a no-op\n * on Windows, which is fine: `MoveFileExW` already journals the metadata.)\n * - **no symlink following.** Temp names come from `randomBytes` and are\n * created with `flag: \"wx\"`, so an attacker who pre-places a symlink at a\n * predictable temp name gets `EEXIST` instead of a write through their link.\n * - **no copy fallback.** A failed rename throws. `copyFile` follows the\n * destination, which reintroduces exactly the symlink/hardlink escape the\n * `wx` flag exists to prevent.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\n\n/**\n * Backoff for a transient Windows rename failure.\n *\n * On Windows `fs.rename` over an existing destination transiently fails with\n * `EPERM` / `EBUSY` / `EACCES` when anything else holds the destination open\n * for a moment — antivirus, the search indexer, a backup agent, an editor.\n * Nothing is wrong and the handle closes microseconds later, but without a\n * retry a scan landing on the wrong millisecond costs the user a launch.\n *\n * `server-setup`'s `claude` settings write, the credential write and the\n * CLAUDE.md injection all use this same list; keeping one copy means a future\n * Windows behaviour change is diagnosed once, not four times.\n */\nexport const RENAME_RETRY_DELAYS_MS = [50, 200, 500] as const\n\n/**\n * Error codes worth retrying on read. A reader racing a rename can observe\n * `ENOENT` (the destination name is briefly unlinked on some filesystems,\n * notably when a network client replays the operation) and can observe the\n * Windows lock codes while the writer's handle is still open.\n */\nconst TRANSIENT_READ_CODES = new Set([\"EPERM\", \"EBUSY\", \"EACCES\", \"ENOENT\"])\n\nfunction errorCode(err: unknown): string | undefined {\n const code = (err as NodeJS.ErrnoException | undefined)?.code\n return typeof code === \"string\" ? code : undefined\n}\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms)\n })\n\nexport interface RenameWithRetryOpts {\n /**\n * When set, a final failure re-reads the destination and treats a match with\n * this content as success. Use it when two writers can legitimately produce\n * identical bytes (the CLAUDE.md snippet, a settings JSON body): the losing\n * racer then does not report a spurious failure.\n *\n * Leave it undefined when the destination is a *pointer* whose value differs\n * per writer — there, a mismatched read back means somebody else won and the\n * caller genuinely needs to know.\n */\n acceptedContent?: string\n /** Override the retry list (tests). */\n delaysMs?: readonly number[]\n /**\n * Called with the last rename error when every attempt fails.\n *\n * The error cannot be part of this function's return value without changing\n * every caller's shape, and swallowing it costs real diagnosability: the\n * CLAUDE.md injection warns about \"rename failed after 4 attempts\" and the\n * single most useful field in that warning is WHY (EPERM from a virus\n * scanner reads very differently from EACCES from a permission mistake).\n */\n onExhausted?: (err: unknown) => void\n}\n\n/**\n * `rename(from, to)` with bounded retry through a transient Windows lock.\n *\n * Returns `true` when the rename landed (or the destination already held\n * `acceptedContent`). Returns `false` — never throws — when retries are\n * exhausted and the destination does not match; the caller decides whether that\n * is fatal (`writeFileAtomic` treats it as fatal).\n *\n * `from` is NOT cleaned up on failure: a caller holding a temp path may want to\n * inspect it, and every caller here either retries or unlinks in its own\n * `finally`. The one exception is `writeFileAtomic`, which owns its temp.\n */\nexport async function renameWithRetry(\n from: string,\n to: string,\n opts: RenameWithRetryOpts = {},\n): Promise<boolean> {\n const delays = opts.delaysMs ?? RENAME_RETRY_DELAYS_MS\n let lastErr: unknown\n for (let attempt = 0; attempt <= delays.length; attempt++) {\n try {\n await fs.rename(from, to)\n return true\n } catch (err) {\n lastErr = err\n if (attempt < delays.length) await sleep(delays[attempt]!)\n }\n }\n\n if (opts.acceptedContent !== undefined) {\n try {\n const observed = await fs.readFile(to, \"utf8\")\n if (observed === opts.acceptedContent) return true\n } catch {\n // Fall through to the failure result.\n }\n }\n\n // Not swallowed silently: every caller in this repo either warns or throws.\n // `console.debug` would be invisible under the CLI's consola setup, so the\n // error is handed to the caller to report with its own context.\n opts.onExhausted?.(lastErr)\n return false\n}\n\n/** `fsync` a directory, ignoring platforms/filesystems that refuse. */\nasync function fsyncDir(dir: string): Promise<void> {\n // Windows cannot open a directory as a handle; `MoveFileExW` already\n // journals the metadata there, so a failure is expected and not an error.\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined\n try {\n handle = await fs.open(dir, \"r\")\n await handle.sync()\n } catch {\n // Best effort: durability here is a belt, not the braces.\n } finally {\n await handle?.close().catch(() => {})\n }\n}\n\n/** `fsync` an open file handle, ignoring failures on exotic filesystems. */\nasync function fsyncFile(handle: Awaited<ReturnType<typeof fs.open>>): Promise<void> {\n try {\n await handle.sync()\n } catch {\n // Best effort, same reasoning as `fsyncDir`.\n }\n}\n\nexport interface WriteFileAtomicOpts {\n /** Destination mode. Carried by the rename on POSIX; ignored on Windows. */\n mode?: number\n /**\n * Text written to the destination. Passing a string lets a failing rename\n * verify whether a racer already landed the same bytes.\n */\n acceptedContent?: string\n /** Override the retry list (tests). */\n delaysMs?: readonly number[]\n}\n\n/**\n * Replace `filePath` with `data` atomically: temp + fsync + rename + fsync(dir).\n *\n * Throws on failure, having removed its temp file. Never leaves a partially\n * written destination and never writes through a pre-placed symlink.\n *\n * The temp file is created in the SAME directory as the destination — a\n * cross-directory temp would make the rename a cross-device copy (`EXDEV`) on\n * any setup with a separate mount for the parent, and would stop being atomic.\n */\nexport async function writeFileAtomic(\n filePath: string,\n data: string | Uint8Array,\n opts: WriteFileAtomicOpts = {},\n): Promise<void> {\n const tmp = `${filePath}.${process.pid}.${randomBytes(8).toString(\"hex\")}.tmp`\n let handle: Awaited<ReturnType<typeof fs.open>> | undefined\n try {\n // `writeFile` + `flag:\"wx\"` rather than `open` + `handle.writeFile`: the two\n // are the same O_CREAT|O_EXCL write, and this shape is what the credential\n // tests inject failures through. (Writing through a partial-then-throw mock\n // is the only way to prove the destination survives a mid-write crash.)\n await fs.writeFile(tmp, data, { mode: opts.mode ?? 0o600, flag: \"wx\" })\n // Re-open for `fsync`: durability needs the flush to happen AFTER the write,\n // and a read handle can be `fsync`ed on POSIX and Windows alike.\n handle = await fs.open(tmp, \"r\")\n await fsyncFile(handle)\n const closedHandle = handle\n handle = undefined\n await closedHandle.close()\n\n const accepted =\n opts.acceptedContent\n ?? (typeof data === \"string\" ? data : undefined)\n const renamed = await renameWithRetry(tmp, filePath, {\n acceptedContent: accepted,\n delaysMs: opts.delaysMs,\n })\n if (!renamed) {\n throw new Error(\n `atomic write failed: could not rename ${tmp} over ${filePath} after ${(opts.delaysMs ?? RENAME_RETRY_DELAYS_MS).length + 1} attempts`,\n )\n }\n await fsyncDir(/** same directory as the destination */ dirnameOf(filePath))\n return\n } catch (err) {\n await handle?.close().catch(() => {})\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n}\n\n/**\n * `path.dirname` without importing `node:path` at module scope.\n *\n * The launcher this module's output is inlined into runs before any bundler\n * chunk is available, and a stray `node:path` import is one more thing the\n * inlining recipe has to keep external. A local split is exact for the paths\n * here (always absolute) and cannot drift from `dirname` for them.\n */\nfunction dirnameOf(p: string): string {\n const idx = Math.max(p.lastIndexOf(\"/\"), p.lastIndexOf(\"\\\\\"))\n if (idx <= 0) return \".\"\n return p.slice(0, idx)\n}\n\n/**\n * Read a file, retrying briefly through a racing rename.\n *\n * A reader that lands between the writer's `rename` and the OS finishing the\n * directory update can see `ENOENT`; a Windows reader can see `EBUSY` while the\n * writer's handle is still closing. Both clear within the retry window. A\n * persistent failure still propagates: callers must not treat \"could not read\"\n * as \"absent\" when their decision depends on it.\n *\n * `retryMissing` defaults to `true` because the readers that existed first (the\n * credential files) race a writer that replaces them constantly. Set it to\n * `false` for a file whose absence is a *normal state* — the managed pointer on\n * first run — where retrying would put 750 ms of latency in front of every\n * launch for no benefit. (Measured: the first version of `readPointer` cost\n * 760 ms per call on a machine with no managed install.)\n */\nexport async function readFileWithRetry(\n filePath: string,\n opts: { delaysMs?: readonly number[]; retryMissing?: boolean } = {},\n): Promise<string> {\n const delays = opts.delaysMs ?? RENAME_RETRY_DELAYS_MS\n const retryMissing = opts.retryMissing ?? true\n let lastErr: unknown\n for (let attempt = 0; attempt <= delays.length; attempt++) {\n try {\n return await fs.readFile(filePath, \"utf8\")\n } catch (err) {\n lastErr = err\n const code = errorCode(err)\n const retryable =\n code !== undefined\n && TRANSIENT_READ_CODES.has(code)\n && (retryMissing || code !== \"ENOENT\")\n if (!retryable) throw err\n if (attempt < delays.length) await sleep(delays[attempt]!)\n }\n }\n throw lastErr\n}\n","/**\n * Filesystem layout for the managed install.\n *\n * `npx github-router@latest` re-extracts a ~586 MB tree for every published\n * version (measured: 16 releases in 31 days), so the router wants the Claude\n * Code shape instead: install once into a per-user prefix, keep versioned\n * payloads side by side, and let a pointer decide which one runs. This module is\n * only the NAMES — no I/O — so it can be imported by the standalone launcher,\n * the CLI, and tests without pulling in npm or the app graph.\n *\n * ```\n * <APP_DIR>/m/<kind>/\n * current.json the only mutable pointer (atomic file rename)\n * launcher.mjs stable path, written once, never swapped\n * install-state.json lastAttemptAt / failures / cache\n * <version>/package.json generated { private: true, dependencies: … }\n * <version>/node_modules/… immutable payload\n * <version>/.installed.json {version, resolved, integrity, installedAt, runtime}\n * .staging-<pid>-<rand>/ npm --prefix target, renamed away on publish\n * .trash-<rand>/ rename-aside target for a corrupt version\n * <APP_DIR>/optional/<pkg>@<version>/ shared heavy payload (§8 of the plan)\n * <APP_DIR>/cli-bin/github-router… shims\n * ```\n *\n * Two naming decisions are load-bearing and must not drift:\n *\n * 1. **`<version>` is the version dir name directly under `<kind>`**, not under a\n * `versions/` level. Windows `MAX_PATH` applies per file, and an installed\n * npm tree already carries ~139 characters of relative path; the\n * `versions/<v>` form pushes a Pi payload past 260 for an 18-character\n * username (measured 264 vs 249). See the plan's §7 table.\n * 2. **Every transient name starts with `.`**. That single rule is the GC\n * contract: anything `readdir` returns that starts with `.` is never a\n * version, so a killed install can never be mistaken for one.\n */\n\nimport os from \"node:os\"\nimport path from \"node:path\"\n\n/** Kinds of payload the router keeps installed. */\nexport type ManagedKind = \"self\" | \"pi\"\n\n/**\n * The app-data root. Mirrors `PATHS.APP_DIR` (`src/lib/paths.ts:9`) but is\n * resolved independently: the launcher runs before the app graph loads (and\n * must not import `consola` or `cloudagent-hook-settings`), and tests need to\n * relocate it without touching the real `~/.local/share`.\n */\nexport function appDir(): string {\n const override = process.env.GH_ROUTER_APP_DIR?.trim()\n if (override && path.isAbsolute(override)) return override\n return path.join(os.homedir(), \".local\", \"share\", \"github-router\")\n}\n\nexport function managedRoot(kind: ManagedKind): string {\n return path.join(appDir(), \"m\", kind)\n}\n\nexport function pointerPath(kind: ManagedKind): string {\n return path.join(managedRoot(kind), \"current.json\")\n}\n\n/**\n * The launcher's path never changes across versions — that is its whole job.\n *\n * `.mjs`, not `.js`, for the same reason the hooks bundle chose `.mjs`\n * (`tsdown.config.ts`): this file sits in a directory with no governing\n * `package.json`, so on Node 20 / 22.0-22.6 a `.js` name is parsed as CommonJS\n * and dies on its first `import`. `import.meta` and top-level await are in the\n * body, so the name has to say ESM on every runtime.\n */\nexport function launcherPath(kind: ManagedKind): string {\n return path.join(managedRoot(kind), \"launcher.mjs\")\n}\n\nexport function installStatePath(kind: ManagedKind): string {\n return path.join(managedRoot(kind), \"install-state.json\")\n}\n\n/** A concrete installed payload. `dirName` is what `readdir` reports. */\nexport function versionDir(kind: ManagedKind, version: string): string {\n return path.join(managedRoot(kind), version)\n}\n\nexport function installedMarkerPath(kind: ManagedKind, version: string): string {\n return path.join(versionDir(kind, version), \".installed.json\")\n}\n\n/**\n * A private, per-attempt npm prefix.\n *\n * Inside `<kind>/` on purpose: `rename()` must stay same-directory, because a\n * cross-device rename is `EXDEV` and stops being atomic, and because people do\n * symlink such directories onto a roomier volume. The `.` prefix keeps GC from\n * ever counting it as a version; the pid makes a dead installer's leftover\n * identifiable without reading anything.\n */\nexport function stagingDir(kind: ManagedKind, pid = process.pid, rand = randomHex()): string {\n return path.join(managedRoot(kind), `.staging-${pid}-${rand}`)\n}\n\n/** Where a corrupt version dir is moved aside to before a re-publish. */\nexport function trashDir(kind: ManagedKind, rand = randomHex()): string {\n return path.join(managedRoot(kind), `.trash-${rand}`)\n}\n\n/** Shims live outside `APP_DIR/bin`, which the toolbelt prunes. */\nexport function cliBinDir(): string {\n return path.join(appDir(), \"cli-bin\")\n}\n\nexport function shimPath(base: string, platform: NodeJS.Platform = process.platform): string {\n const name = platform === \"win32\" ? `${base}.cmd` : base\n return path.join(cliBinDir(), name)\n}\n\n/**\n * Root for the shared heavy payloads (`@huggingface/transformers`,\n * `tree-sitter-wasms`).\n *\n * Outside `m/<kind>/<version>/` on purpose: those are per-version and GC keeps\n * two of them, so an in-tree copy of a 547 MB model runtime would be 1.1 GB and\n * would be re-downloaded on every version bump. Here it exists once per machine.\n */\nexport function optionalRoot(): string {\n return path.join(appDir(), \"optional\")\n}\n\n/**\n * Name shapes GC recognises, defined once.\n *\n * `install.ts` and `optional.ts` both sweep `.staging-*`/`.trash-*` leftovers and\n * both classify `<version>` dirs. They matched these inline before, which meant\n * the transient-name contract (`paths.ts`'s own doc block calls the leading dot\n * load-bearing) was stated in three places and could drift in two of them.\n *\n * The version shape is deliberately strict: semver-ish triples, no leading dot\n * and no prerelease-only names, so a stray `README`, `.DS_Store` or lock file is\n * never mistaken for a payload.\n */\nexport const STAGING_RE = /^\\.staging-\\d+-[0-9a-f]+$/\nexport const TRASH_RE = /^\\.trash-[0-9a-f]+$/\nexport const VERSION_RE = /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$/\n\nexport function isVersionName(name: string): boolean {\n return VERSION_RE.test(name)\n}\n\nexport function isTransientName(name: string): boolean {\n return name.startsWith(\".\") && (STAGING_RE.test(name) || TRASH_RE.test(name))\n}\n\nexport function randomHex(): string {\n // `randomBytes` is not imported at module scope: the launcher this module is\n // inlined into runs before any bundler chunk resolves, and `node:crypto` is\n // one more external the inlining recipe has to keep. `Math.random` is\n // adequate here — the value only has to be unique among sibling attempts,\n // and the pid is already part of the name.\n return Math.floor(Math.random() * 0x100000000)\n .toString(16)\n .padStart(8, \"0\")\n}\n\n/**\n * Relative entry path for a kind, once its package is installed.\n *\n * `self` names the APP entry (`dist/main.js`), never the published bin\n * (`dist/bin.js`). That is not cosmetic: the bin IS the bootstrap, so a pointer\n * derived from the bin map would re-exec the bootstrap, which reads the same\n * pointer, forever. `pointer.isSafeEntry` refuses it as a second line of defence.\n */\nexport const ENTRY_RELATIVE: Readonly<Record<ManagedKind, string>> = {\n self: \"node_modules/github-router/dist/main.js\",\n pi: \"node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js\",\n}\n\n/** The npm package each kind installs. */\nexport const NPM_PACKAGE: Readonly<Record<ManagedKind, string>> = {\n self: \"github-router\",\n pi: \"@earendil-works/pi-coding-agent\",\n}\n\n/**\n * Test seams for the two constants above.\n *\n * The installer's interesting behaviour (staging, publish-by-rename, provenance,\n * GC) is identical for a 6 KB package with no install scripts and for the real\n * 66 MB payload, so the end-to-end test installs a tiny one. Without these the\n * test would either need the network and a minute per case, or would have to\n * re-implement the layout — which is exactly the duplicated-logic trap that\n * makes a test pass while production breaks.\n *\n * Not part of the public surface: nothing in `src/` calls them.\n */\nlet entryOverride: Partial<Record<ManagedKind, string>> = {}\nlet packageOverride: Partial<Record<ManagedKind, string>> = {}\n\nexport function entryRelativeFor(kind: ManagedKind): string {\n return entryOverride[kind] ?? ENTRY_RELATIVE[kind]\n}\n\nexport function npmPackageFor(kind: ManagedKind): string {\n return packageOverride[kind] ?? NPM_PACKAGE[kind]\n}\n\n/** @internal — point the installer at a throwaway package for a test. */\nexport function __setManagedTestTarget(\n kind: ManagedKind,\n target: { entry?: string; package?: string },\n): void {\n if (target.entry !== undefined) entryOverride = { ...entryOverride, [kind]: target.entry }\n if (target.package !== undefined) packageOverride = { ...packageOverride, [kind]: target.package }\n}\n\n/** @internal — restore the real targets between test cases. */\nexport function __resetManagedTestTarget(): void {\n entryOverride = {}\n packageOverride = {}\n}\n","/**\n * `install-state.json`: the managed installer's memory across launches.\n *\n * Three separate concerns share one small file because they are written at the\n * same moments and a second file would be a second thing to keep consistent:\n *\n * - **backoff** (`lastAttemptAt`, `consecutiveFailures`, `nextAttemptAt`,\n * `lastError`), so a failing registry is retried on a ladder instead of on\n * every launch;\n * - **the cached npm cache path**, because `NPM_CONFIG_CACHE` is routinely moved\n * and probing it costs a subprocess on every CLI invocation.\n *\n * There is deliberately no `registry` field. It used to be written here, was\n * never read (`update --check` takes provenance from the version dir's\n * `.installed.json`, which is per-install rather than per-machine), and never\n * cleared — so it reported one old install's registry forever. A field nobody\n * reads is a lie waiting to be trusted; `InstallState` ignores unknown keys, so\n * dropping it cannot break an existing file.\n *\n * Lives here rather than in `install.ts` because `origin.ts` needs it and must not\n * import the installer: the installer pulls `consola`, and `origin.ts` is on the\n * bootstrap's path. Nothing here logs.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { readFileWithRetry, writeFileAtomic } from \"../atomic-file\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport { type ManagedKind, installStatePath, managedRoot } from \"./paths\"\n\n/** Backoff ladder for a failed install, in hours. The last entry repeats. */\nexport const BACKOFF_HOURS = [1, 6, 24] as const\n\n/** Version dirs kept besides the pointer's (newest first). */\nexport const KEEP_VERSIONS = 2\n\n/** Age floor before an old version may be deleted, in ms. */\nexport const VERSION_FLOOR_MS = 7 * 24 * 60 * 60_000\n\n/** Abandoned `.staging-*`/`.trash-*` dirs older than this are swept. */\nexport const TRANSIENT_TTL_MS = 60 * 60_000\n\nexport interface InstallState {\n lastAttemptAt?: string\n lastSuccessAt?: string\n consecutiveFailures?: number\n nextAttemptAt?: string\n lastError?: string\n /** Cached `npm config get cache`, because `NPM_CONFIG_CACHE` moves routinely. */\n npmCache?: string\n /**\n * Cached answers from the two npm probes, keyed by the RUNTIME that produced\n * them.\n *\n * Keyed, not plain, because both answers are runtime-dependent under a version\n * manager: `npm root -g` is `~/.nvm/versions/node/<v>/lib/node_modules`, so a\n * bare cached string would send an nvm user's next launch to the previous\n * node's global tree. `process.execPath` changes exactly when that matters.\n */\n npmProbe?: {\n runtime: string\n globalRoot?: string\n cacheRoot?: string\n }\n /** Origin classification result of the last launch, for diagnostics. */\n lastOrigin?: string\n}\n\nexport async function readInstallState(kind: ManagedKind): Promise<InstallState> {\n try {\n const raw = await readFileWithRetry(installStatePath(kind), { retryMissing: false })\n const parsed = JSON.parse(raw) as InstallState\n return typeof parsed === \"object\" && parsed !== null ? parsed : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Write state. Returns `false` on failure instead of throwing — this file is an\n * optimisation, never a gate — but never silently: a failed write is reported,\n * because the CALLER's next launch is what pays for it. The expensive case is the\n * success patch: if that one fails, the ladder from a previous failure is still\n * on disk, and every launch for the next 1–24 h reports \"last attempt failed\"\n * on a machine that is perfectly up to date.\n */\nexport async function writeInstallState(kind: ManagedKind, state: InstallState): Promise<boolean> {\n try {\n await fs.mkdir(managedRoot(kind), { recursive: true })\n await writeFileAtomic(installStatePath(kind), `${JSON.stringify(state, null, 2)}\\n`, {\n mode: 0o644,\n })\n return true\n } catch (err) {\n reportManagedDiagnostic(\n \"warn\",\n `managed[${kind}]: could not write ${installStatePath(kind)} (${\n err instanceof Error ? err.message : String(err)\n }). The next launch may re-attempt or back off as if the previous attempt had failed.`,\n )\n return false\n }\n}\n\n/**\n * Read-modify-write a patch onto the CURRENT on-disk state.\n *\n * Not `writeInstallState({...staleSnapshot, ...patch})`: the callers that hold a\n * snapshot across an install (which can take minutes) would otherwise clobber\n * fields another process — or a `npmProbes()` probe earlier in this one — wrote\n * in the meantime. The observable version of that bug is subtle and expensive: the\n * cache/global-root memo disappears, and every launch pays a 250 ms npm probe\n * again.\n *\n * KNOWN LIMIT, stated because suppressing it would need a real lock on the file:\n * the read and the write are not atomic together, so two processes patching\n * DIFFERENT keys in the same instant can lose one of them (\"last writer wins for\n * the whole file\"). Callers hold the install lock for anything that must not be\n * lost, and every other writer writes a self-healing value: a lost `npmProbe` is\n * re-derived on the next launch, a lost `lastOrigin` is cosmetic. Do not add a\n * field whose loss changes a decision without also holding the lock.\n */\nexport async function patchInstallState(\n kind: ManagedKind,\n patch: Partial<InstallState>,\n): Promise<boolean> {\n const current = await readInstallState(kind)\n const next: InstallState = { ...current, ...patch }\n // An explicit `undefined` in the patch means DELETE, the same convention as\n // `buildNpmEnv`'s overrides: `nextAttemptAt: undefined` clears the backoff.\n for (const key of Object.keys(patch) as Array<keyof InstallState>) {\n if (patch[key] === undefined) delete next[key]\n }\n return writeInstallState(kind, next)\n}\n\n/**\n * Whether the backoff window has expired.\n *\n * `nextAttemptAt` is written BEFORE an attempt (optimistic), so two launches\n * racing on the same failing registry do not both hammer npm.\n */\nexport function installAllowedNow(state: InstallState, now = Date.now()): boolean {\n if (!state.nextAttemptAt) return true\n const next = new Date(state.nextAttemptAt).getTime()\n if (Number.isNaN(next)) return true\n return now >= next\n}\n\n/**\n * Whether an attempt may start, distinguishing a RESERVATION from a BACKOFF.\n *\n * `nextAttemptAt` is written optimistically before every attempt so two launches\n * cannot both run npm, and it is also the backoff ladder's output. Those two\n * meanings must not be conflated: a reservation (`consecutiveFailures` still 0)\n * is not evidence of failure, so treating it as one makes an explicit\n * `github-router update` issued right after a launch that merely *scheduled* an\n * install print \"last attempt failed (unknown error)\" and do nothing. The install\n * lock — not this window — is what serialises attempts, so re-attempting a\n * reservation is cheap: the loser exits immediately.\n *\n * A crash mid-install also leaves a bare reservation, and retrying it is the\n * correct repair (the leftover `.staging-*` is swept by GC).\n */\nexport function mayAttemptNow(state: InstallState, now = Date.now()): boolean {\n if ((state.consecutiveFailures ?? 0) === 0) return true\n return installAllowedNow(state, now)\n}\n\nexport function nextAttemptAtFor(failures: number, now = Date.now()): string {\n const index = Math.min(Math.max(failures, 1), BACKOFF_HOURS.length) - 1\n const hours = BACKOFF_HOURS[index] ?? 24\n return new Date(now + hours * 60 * 60_000).toISOString()\n}\n\n/** Dotted-path helpers for tests that need the file's location. */\nexport function installStateFile(kind: ManagedKind): string {\n return path.join(managedRoot(kind), \"install-state.json\")\n}\n","/**\n * Where did this process start from?\n *\n * The bootstrap (`dist/bin.js`) has to answer one question before it does\n * anything else: *is the tree I am running from a disposable copy?* If it is\n * (`npx`, `bunx`), adopting the managed install is the whole point of the\n * feature. If it is not (`npm i -g`, a git checkout, or already managed), the\n * bootstrap must be a pure pass-through — user decision 4 is explicit that a\n * global install stays its own owner and must never be duplicated.\n *\n * Classification is deliberately **positive** and **fail-safe**: each branch\n * needs evidence (a realpath under a known root, a `.git` marker), and the\n * default answer is `unknown`, which every caller treats as `source` — no adopt,\n * no install, no background work. A wrong `npx` answer costs the user a 66 MB\n * install they did not want; a wrong `source` answer costs nothing.\n *\n * Cost matters here in a way it does not elsewhere: this runs on EVERY CLI\n * invocation. So every probe is bounded, cached in-process, and the two that\n * spawn (`npm root -g`, `npm config get cache`) are cached across runs in\n * `install-state.json` — `NPM_CONFIG_CACHE` moving is rare enough that one\n * stale read is worth avoiding 300 ms on every launch.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport { resolveExecutable, runCommandCapture } from \"../exec\"\nimport { isUnderVolatileRoot, realpathIfPossible } from \"../volatile-root\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport { patchInstallState, readInstallState } from \"./state\"\nimport { type ManagedKind, appDir, managedRoot } from \"./paths\"\n\nexport type InstallOrigin = \"managed\" | \"npm-global\" | \"npx\" | \"bunx\" | \"source\" | \"unknown\"\n\nexport interface OriginInfo {\n origin: InstallOrigin\n /** Realpath of the running package root, when it could be determined. */\n packageRoot?: string\n /** One-line reason, for `--debug` and for the \"why did nothing happen\" question. */\n detail: string\n}\n\n/** Timeout for the two npm probes. A cold `npm root -g` can take ~300 ms. */\nconst PROBE_TIMEOUT_MS = 5000\n\nlet cached: OriginInfo | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetOriginForTests(): void {\n cached = undefined\n}\n\n/** The running package root: the directory holding `package.json` for this code. */\nexport function currentPackageRoot(): string | undefined {\n return findPackageRoot(process.argv[1])\n}\n\n/** Walk up from `entry` to the `github-router` package root. */\nexport function findPackageRoot(entry: string | undefined): string | undefined {\n if (typeof entry !== \"string\" || entry.length === 0) return undefined\n let cur = path.dirname(realpathIfPossible(entry))\n for (let i = 0; i < 10; i++) {\n try {\n const pkg = JSON.parse(readFileSync(path.join(cur, \"package.json\"), \"utf8\")) as {\n name?: unknown\n }\n // Exact names, not a substring: `not-github-router` and\n // `@someone/github-router-helper` are different packages, and adopting\n // based on a substring would let a look-alike tree claim the origin.\n if (pkg.name === \"github-router\" || pkg.name === \"@animeshkundu/github-router\") return cur\n } catch {\n // Not here; keep walking.\n }\n const parent = path.dirname(cur)\n if (parent === cur) break\n cur = parent\n }\n return undefined\n}\n\n/**\n * Normalized, separator-trailing form so prefix tests cannot match `/foo` in\n * `/foobar`.\n *\n * Lowercased on Windows: NTFS is case-insensitive, so `C:\\Users\\X\\AppData\\npm`\n * (what `npm root -g` reports) and `c:\\users\\x\\appdata\\npm\\node_modules\\…`\n * (what a launcher spawned from a differently-cased PATH entry sees) are the same\n * directory and must compare equal. A case-sensitive compare would classify a\n * global install as `unknown` — and `unknown` means \"never adopt, never install\",\n * so the failure is a silent absence of the feature on that machine.\n */\nfunction asPrefix(dir: string): string {\n const resolved = realpathIfPossible(dir)\n const withSep = resolved.endsWith(path.sep) ? resolved : `${resolved}${path.sep}`\n return process.platform === \"win32\" ? withSep.toLowerCase() : withSep\n}\n\nfunction normalizeForCompare(value: string): string {\n return process.platform === \"win32\" ? value.toLowerCase() : value\n}\n\nfunction isUnder(target: string, root: string): boolean {\n if (!root) return false\n const prefix = asPrefix(root)\n // Resolve both sides: macOS reports /var/... while a process sees\n // /private/var/..., and a symlinked APP_DIR is normal on Linux setups.\n for (const candidate of [target, realpathIfPossible(target)]) {\n if (normalizeForCompare(candidate).startsWith(prefix)) return true\n if (normalizeForCompare(realpathIfPossible(candidate)).startsWith(prefix)) return true\n }\n return false\n}\n\n/** One `npm config get <key>` probe, bounded and never throwing. */\nasync function npmConfigValue(args: Array<string>): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture([npmPath, ...args], {\n timeoutMs: PROBE_TIMEOUT_MS,\n })\n if (code !== 0) return null\n const value = stdout.trim().split(/\\r?\\n/).pop()?.trim()\n return value && path.isAbsolute(value) ? value : null\n } catch {\n return null\n }\n}\n\ninterface NpmProbes {\n globalRoot: string | null\n cacheRoot: string | null\n}\n\n/**\n * Resolve (and memoise) both npm probes.\n *\n * Cached in-process for the life of this process and across runs in\n * `install-state.json`, keyed by `process.execPath`. The key matters: under nvm\n * the global root IS per-node-version, so an unkeyed cache would point the next\n * launch at a tree that node version no longer owns.\n *\n * One probe run per cache miss, not one per query: `classifyEntry` needs both,\n * and each is a ~250 ms subprocess.\n */\nasync function npmProbes(kind: ManagedKind = \"self\"): Promise<NpmProbes> {\n const runtime = process.execPath\n const state = await readInstallState(kind)\n const cached = state.npmProbe\n if (cached?.runtime === runtime && cached.globalRoot && cached.cacheRoot) {\n return { globalRoot: cached.globalRoot, cacheRoot: cached.cacheRoot }\n }\n const [globalRoot, cacheRoot] = await Promise.all([\n cached?.runtime === runtime && cached.globalRoot\n ? Promise.resolve(cached.globalRoot)\n : npmConfigValue([\"root\", \"-g\"]),\n cached?.runtime === runtime && cached.cacheRoot\n ? Promise.resolve(cached.cacheRoot)\n : npmConfigValue([\"config\", \"get\", \"cache\"]),\n ])\n if (globalRoot || cacheRoot) {\n await patchInstallState(kind, {\n // Keep the flat field for older readers/messages.\n ...(cacheRoot ? { npmCache: cacheRoot } : {}),\n npmProbe: {\n runtime,\n ...(globalRoot ? { globalRoot } : {}),\n ...(cacheRoot ? { cacheRoot } : {}),\n },\n })\n }\n return { globalRoot, cacheRoot }\n}\n\n/**\n * Classify this process's install origin.\n *\n * Order is significant and cheapest-first:\n *\n * 1. `managed` — a realpath under our own version dir. This must come first and\n * short-circuit the pointer read, or a managed payload would adopt itself.\n * 2. `npm-global` — under `npm root -g`. User decision 4: never duplicated.\n * 3. `npx` — under `<npm cache>/_npx`.\n * 4. `source` — a `.git` beside the package root. Deliberately ahead of the\n * volatility heuristic: a checkout in `/tmp` is still the developer's code.\n * 5. `bunx` — under a `.bunx-*` root, or any other volatile temp root.\n * 6. `unknown` — everything else, including \"the package root could not be\n * found\". Treated exactly like `source` by every caller.\n */\nexport async function classifyOrigin(): Promise<OriginInfo> {\n if (cached) return cached\n const info = await classifyEntry(process.argv[1])\n cached = info\n return info\n}\n\n/**\n * Classify an arbitrary entry path.\n *\n * Extracted from `classifyOrigin` so the matrix is testable without respawning\n * the test runner with a doctored argv: the classification is pure with respect\n * to `entry`, and the only impurity (two npm probes) is already injectable via\n * the process PATH and the install-state cache.\n */\nexport async function classifyEntry(entry: string | undefined): Promise<OriginInfo> {\n if (typeof entry !== \"string\" || entry.length === 0) {\n return { origin: \"unknown\", detail: \"no argv[1]; cannot tell where this code lives\" }\n }\n const packageRoot = findPackageRoot(entry)\n const probe = packageRoot ?? path.dirname(realpathIfPossible(entry))\n\n if (isUnder(probe, managedRootOf(\"self\")) || isUnder(probe, managedRootOf(\"pi\"))) {\n return { origin: \"managed\", packageRoot, detail: `running from the managed tree (${probe})` }\n }\n\n const { globalRoot, cacheRoot } = await npmProbes()\n if (globalRoot && isUnder(probe, globalRoot)) {\n return {\n origin: \"npm-global\",\n packageRoot,\n detail: `running from the global install ${globalRoot}`,\n }\n }\n\n if (cacheRoot && isUnder(probe, path.join(cacheRoot, \"_npx\"))) {\n return { origin: \"npx\", packageRoot, detail: `running from the npx cache ${path.join(cacheRoot, \"_npx\")}` }\n }\n\n // A `.git` beside the package root is STRONGER evidence than \"this path is in\n // a temp dir\": a developer who cloned the repo into /tmp and runs it there is\n // running their own code and must not be silently switched onto a managed\n // build. So source is checked before the volatility heuristic.\n if (hasGitAncestor(packageRoot ?? probe)) {\n return { origin: \"source\", packageRoot, detail: `running from a git checkout (${packageRoot ?? probe})` }\n }\n\n // `bunx` no longer materialises a `.bunx-*` temp tree: current bun resolves\n // into its shared cache (`~/.bun/install/cache`, or `$BUN_INSTALL/cache`) and\n // executes from there. `isUnderVolatileRoot` does NOT cover that directory —\n // it is under $HOME, not the temp dir — so without this the most common modern\n // `bunx github-router` classified as `unknown`, which means \"never adopt, never\n // install\": the managed layer simply never engaged for bun users.\n if (isUnderBunCache(probe)) {\n return { origin: \"bunx\", packageRoot, detail: `running from the bun cache (${BUN_CACHE_HINT})` }\n }\n\n if (probe.includes(`${path.sep}.bunx-`) || isUnderVolatileRoot(probe)) {\n return { origin: \"bunx\", packageRoot, detail: `running from a volatile bunx/temp tree (${probe})` }\n }\n\n // A tree we cannot place. Refusing to act is the safe direction: the worst\n // outcome is that the managed install simply does not engage.\n reportManagedDiagnostic(\"debug\", `managed: unrecognised install origin at ${probe}`)\n return { origin: \"unknown\", packageRoot, detail: `unrecognised origin (${probe})` }\n}\n\n/**\n * Whether a `.git` sits at or above `dir`.\n *\n * \"Above\" matters: in a checkout the package.json IS the repo root, but a\n * monorepo/workspace has the package in a subdirectory with `.git` above it, and\n * a `git worktree` checkout puts `.git` in the parent with a pointer file. All\n * three are the developer's own code.\n *\n * Bounded and non-recursive past the filesystem root; `existsSync` rather than a\n * stat-only check so a `.git` FILE (worktree/submodule) counts too.\n */\nfunction hasGitAncestor(dir: string): boolean {\n let cur = dir\n for (let i = 0; i < 6; i++) {\n if (existsSync(path.join(cur, \".git\"))) return true\n const parent = path.dirname(cur)\n if (parent === cur) return false\n cur = parent\n }\n return false\n}\n\n/** Where a `bunx` tree lands, for the diagnostic string. */\nconst BUN_CACHE_HINT = \"$BUN_INSTALL/cache (or ~/.bun/install/cache)\"\n\n/**\n * Whether `dir` is inside bun's shared install cache.\n *\n * Both the cache root and its parent are tested, because bun's layout has been\n * `install/cache/<pkg>@<ver>@@@1` and, in older versions, a sibling directory.\n * Case-insensitive on Windows for the same reason `asPrefix` is.\n */\nfunction isUnderBunCache(dir: string): boolean {\n const candidates = [process.env.BUN_INSTALL, process.env.BUN_INSTALL_CACHE_DIR].filter(\n (value): value is string => typeof value === \"string\" && value.length > 0,\n )\n const roots = new Set<string>()\n for (const base of candidates) {\n roots.add(path.join(base, \"cache\"))\n roots.add(path.join(base, \"install\", \"cache\"))\n }\n const home = os.homedir()\n if (home) {\n // The CACHE only, deliberately. `~/.bun/install/global` is where `bun add -g`\n // puts a user's own global install, and user decision 4 is that a global\n // install is never duplicated — classifying it as `bunx` would silently swap\n // the binary a user installed for a managed one.\n roots.add(path.join(home, \".bun\", \"install\", \"cache\"))\n }\n for (const root of roots) {\n // Both spellings, like every other prefix test in this file: a caller may\n // hand us a resolved path and a PATH/cache root that is not (or vice versa).\n if (isUnder(dir, root) || isUnder(realpathIfPossible(dir), realpathIfPossible(root))) return true\n }\n return false\n}\n\nfunction managedRootOf(kind: ManagedKind): string {\n return managedRoot(kind)\n}\n\n/**\n * Whether this origin should adopt an existing managed install.\n *\n * Kept as its own function so the policy is one line to read and one line to\n * change: only the disposable-copy origins adopt. `npm-global` and `source`\n * never do (their trees are the owner's), and `unknown` never does.\n */\nexport function shouldAdoptFor(origin: InstallOrigin): boolean {\n return origin === \"npx\" || origin === \"bunx\"\n}\n\n/** Whether this origin should kick off a managed install in the background. */\nexport function shouldInstallFor(origin: InstallOrigin): boolean {\n return origin === \"npx\" || origin === \"bunx\"\n}\n\n/** Human name for the origin, for the `update`/`--debug` output. */\nexport function describeOrigin(origin: InstallOrigin): string {\n switch (origin) {\n case \"managed\":\n return \"managed install\"\n case \"npm-global\":\n return \"npm global install\"\n case \"npx\":\n return \"npx cache\"\n case \"bunx\":\n return \"bunx temporary tree\"\n case \"source\":\n return \"source checkout\"\n case \"unknown\":\n return \"unrecognised\"\n }\n}\n\n/** The app dir, exposed for messages. */\nexport function managedAppDir(): string {\n return appDir()\n}\n","/**\n * The managed-install pointer: `m/<kind>/current.json`.\n *\n * This is the ONE mutable thing in the layout, and every design constraint here\n * comes from a measured failure:\n *\n * - **It is a file, not a directory or a junction.** On Windows,\n * `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` cannot replace a directory or a\n * reparse point, so swapping a live `current/` directory works on first\n * install and fails `EPERM` on every update — and the `rmdir` + `rename`\n * fallback is non-atomic across exactly the window the ~13 per-turn\n * `internal-*` hooks fire. A file-over-file rename is supported everywhere.\n * - **A bad pointer must never be fatal.** A launch that cannot resolve its\n * payload must fall back to \"no managed install\" and run from whatever tree it\n * already has. So every parse failure, unknown schema version, missing field,\n * and missing entry resolves to `null`, and the caller treats that as absent.\n * - **Readers retry through a racing rename**, so the pointer is read via\n * `readFileWithRetry` rather than raw `readFile`: a reader can legitimately see\n * `ENOENT`/`EBUSY` for a microsecond after a writer's rename.\n *\n * ### What the pointer must NOT say\n *\n * The published bin is the bootstrap (`dist/bin.js`), so anything that resolves\n * \"the bin target from package.json\" would write a pointer to the bootstrap and\n * exec itself in a loop. `entry` is therefore the **app entry**, checked against\n * the installed tree, and `resolvePointer` refuses a pointer whose entry is the\n * bootstrap.\n *\n * ### `runtimeHint` is a hint\n *\n * Recording an absolute `node` path as authoritative is the \"`claude` vanished\n * after a node upgrade\" bug: nvm/fnm/volta/brew all delete the previous\n * interpreter, and a shim written once would then fail forever. The pointer\n * records what ran the install for diagnostics and fallback, and the launcher\n * resolves the runtime at run time.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { readFileWithRetry, writeFileAtomic } from \"../atomic-file\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport {\n type ManagedKind,\n entryRelativeFor,\n installedMarkerPath,\n pointerPath,\n versionDir,\n} from \"./paths\"\n\nexport const POINTER_SCHEMA_VERSION = 1\n\n/** The bootstrap entry, never a valid payload entry. */\nexport const BOOTSTRAP_ENTRY = \"dist/bin.js\"\n\nexport interface ManagedPointer {\n schemaVersion: number\n kind: ManagedKind\n version: string\n /** Path INSIDE the version dir, e.g. `node_modules/github-router/dist/main.js`. */\n entry: string\n /** Absolute path of the payload entry, derived; never trusted from disk alone. */\n entryPath: string\n /** The runtime that performed the install. Diagnostics + last-resort fallback. */\n runtimeHint?: string\n registry?: string\n installedAt?: string\n}\n\n/** On-disk shape. Kept separate so validation is explicit about optionality. */\ninterface PointerFile {\n schemaVersion?: unknown\n kind?: unknown\n version?: unknown\n entry?: unknown\n runtimeHint?: unknown\n registry?: unknown\n installedAt?: unknown\n}\n\nexport interface WritePointerParams {\n kind: ManagedKind\n version: string\n /** Relative entry. Defaults to the kind's known entry. */\n entry?: string\n runtimeHint?: string\n registry?: string\n installedAt?: string\n}\n\n/**\n * Reject an entry that would point at the bootstrap or escape the version dir.\n *\n * This is not paranoia about our own writer: the pointer is a plain file in a\n * user-writable directory, and the launcher `import()`s whatever it names. A\n * relative entry that climbs out (`../../..`) or is absolute would turn a\n * corrupt pointer into arbitrary code execution on the next launch.\n */\nexport function isSafeEntry(entry: string): boolean {\n if (entry.length === 0) return false\n if (path.isAbsolute(entry) || entry.startsWith(\"/\") || /^[A-Za-z]:/.test(entry)) return false\n // Reject both separators regardless of platform: a pointer written on POSIX\n // can be read by a Windows install (roaming profile) and vice versa.\n const normalized = entry.replace(/\\\\/g, \"/\")\n if (normalized.split(\"/\").some((segment) => segment === \"..\")) return false\n if (normalized === BOOTSTRAP_ENTRY || normalized.endsWith(`/${BOOTSTRAP_ENTRY}`)) return false\n return true\n}\n\nfunction kindOf(value: unknown): ManagedKind | null {\n return value === \"self\" || value === \"pi\" ? value : null\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined\n}\n\n/**\n * Parse + validate a pointer body. Returns `null` for anything unusable, which\n * every caller must treat identically to \"no managed install\".\n */\nexport function parsePointer(raw: string, kind: ManagedKind): ManagedPointer | null {\n let parsed: PointerFile\n try {\n parsed = JSON.parse(raw) as PointerFile\n } catch {\n return null\n }\n if (typeof parsed !== \"object\" || parsed === null) return null\n if (parsed.schemaVersion !== POINTER_SCHEMA_VERSION) return null\n if (kindOf(parsed.kind) !== kind) return null\n const version = nonEmptyString(parsed.version)\n if (!version) return null\n // A version string reaches a path join; refuse separators outright rather\n // than reasoning about whether a crafted name can escape the root.\n if (version.includes(\"/\") || version.includes(\"\\\\\") || version === \".\" || version === \"..\") {\n return null\n }\n const entry = nonEmptyString(parsed.entry) ?? entryRelativeFor(kind)\n if (!isSafeEntry(entry)) return null\n\n return {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind,\n version,\n entry,\n entryPath: path.join(versionDir(kind, version), entry),\n runtimeHint: nonEmptyString(parsed.runtimeHint),\n registry: nonEmptyString(parsed.registry),\n installedAt: nonEmptyString(parsed.installedAt),\n }\n}\n\n/**\n * Why a pointer read produced no pointer.\n *\n * `absent` and `unreadable` MUST be distinguishable, and the distinction is not\n * academic: GC treats \"no pointer\" as \"nothing is live, so an old version dir may\n * be deleted\". A transient `EPERM`/`EBUSY` (a virus scanner holding the file, a\n * torn read on a network home) reported as `absent` would let GC delete the very\n * tree the pointer names — unrecoverable without reinstalling, and it happens\n * precisely on the machines that are already unhappy.\n *\n * - `ok` — a complete pointer.\n * - `absent` — no pointer file, or one whose body is unusable.\n * - `unreadable` — the read failed for a reason other than ENOENT.\n */\nexport type PointerReadStatus = \"ok\" | \"absent\" | \"unreadable\"\n\nexport interface PointerReadResult {\n status: PointerReadStatus\n pointer: ManagedPointer | null\n}\n\n/**\n * Read the pointer with the reason it was not usable.\n *\n * This is the primitive; `readPointer` is the ergonomic form for callers whose\n * only decision is \"run the payload or not\". GC must use this one.\n */\nexport async function readPointerDetailed(\n kind: ManagedKind,\n opts: { verifyEntry?: boolean } = {},\n): Promise<PointerReadResult> {\n const file = pointerPath(kind)\n let raw: string\n try {\n // `retryMissing: false`: a missing pointer is the normal first-run state, so\n // waiting out the retry window would tax every launch that has no managed\n // install yet (measured 760 ms before this flag existed).\n raw = await readFileWithRetry(file, { retryMissing: false })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { status: \"absent\", pointer: null }\n }\n onReadError(kind, err)\n return { status: \"unreadable\", pointer: null }\n }\n const pointer = parsePointer(raw, kind)\n if (!pointer) {\n onInvalid(kind, file)\n return { status: \"absent\", pointer: null }\n }\n if (opts.verifyEntry === false) return { status: \"ok\", pointer }\n\n try {\n const stat = await fs.stat(pointer.entryPath)\n if (!stat.isFile()) {\n onMissingEntry(kind, pointer)\n return { status: \"absent\", pointer: null }\n }\n } catch {\n onMissingEntry(kind, pointer)\n return { status: \"absent\", pointer: null }\n }\n return { status: \"ok\", pointer }\n}\n\n/**\n * Read the pointer, or `null`.\n *\n * A missing file is the normal first-run answer. Any other read error is a\n * debug-level event, never a throw: a launch must not die because the pointer\n * is unreadable, and the caller's fallback (run from the current tree) is always\n * correct. The entry is stat'd by default, so a pointer to a GC'd or\n * half-published payload is also reported as absent.\n *\n * Callers that DESTROY something based on this answer must use\n * `readPointerDetailed` instead — see `PointerReadStatus`.\n */\nexport async function readPointer(\n kind: ManagedKind,\n opts: { verifyEntry?: boolean } = {},\n): Promise<ManagedPointer | null> {\n return (await readPointerDetailed(kind, opts)).pointer\n}\n\n/**\n * Write the pointer atomically.\n *\n * Temp + fsync + rename, with a bounded retry through a transient Windows lock\n * (`atomic-file`).\n *\n * `atomic-file`'s exhausted-rename fallback re-reads the destination and accepts\n * a byte-for-byte match as success. For a pointer that is not the \"did I win?\"\n * question being swept under the rug: the body carries `version` + `installedAt`,\n * so identical bytes mean the other writer published the SAME version at the\n * same instant, and reporting success is correct. Two writers naming DIFFERENT\n * versions can never byte-match, so the caller still learns who won.\n */\nexport async function writePointer(params: WritePointerParams): Promise<ManagedPointer> {\n const entry = params.entry ?? entryRelativeFor(params.kind)\n if (!isSafeEntry(entry)) {\n throw new Error(`refusing to write an unsafe managed entry: ${entry}`)\n }\n const body = {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind: params.kind,\n version: params.version,\n entry,\n ...(params.runtimeHint ? { runtimeHint: params.runtimeHint } : {}),\n ...(params.registry ? { registry: params.registry } : {}),\n installedAt: params.installedAt ?? new Date().toISOString(),\n }\n const file = pointerPath(params.kind)\n await fs.mkdir(path.dirname(file), { recursive: true })\n await writeFileAtomic(file, `${JSON.stringify(body, null, 2)}\\n`, { mode: 0o644 })\n return {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind: params.kind,\n version: params.version,\n entry,\n entryPath: path.join(versionDir(params.kind, params.version), entry),\n runtimeHint: params.runtimeHint,\n registry: params.registry,\n installedAt: body.installedAt,\n }\n}\n\n/** Remove the pointer (used by `update --force` and by tests). */\nexport async function removePointer(kind: ManagedKind): Promise<void> {\n await fs.rm(pointerPath(kind), { force: true })\n}\n\n// ---------------------------------------------------------------------------\n// Reporting\n//\n// The pointer is read by the bootstrap (`dist/bin.js`) and by the launcher path,\n// both of which must stay importable without `consola` — two bundles would mean\n// two instances and two configurations. Messages go through the sink instead;\n// see `diagnostics.ts`.\n// ---------------------------------------------------------------------------\n\nfunction onReadError(kind: ManagedKind, err: unknown): void {\n reportManagedDiagnostic(\n \"debug\",\n `managed[${kind}]: could not read current.json (${\n err instanceof Error ? err.message : String(err)\n }); treating as no managed install`,\n )\n}\n\nfunction onInvalid(kind: ManagedKind, file: string): void {\n reportManagedDiagnostic(\n \"warn\",\n `managed[${kind}]: ${file} is not a valid pointer (schema/kind/entry); ignoring it. \\`github-router update\\` will rewrite it.`,\n )\n}\n\nfunction onMissingEntry(kind: ManagedKind, pointer: ManagedPointer): void {\n reportManagedDiagnostic(\n \"debug\",\n `managed[${kind}]: pointer names ${pointer.version} but ${pointer.entryPath} is missing; treating as no managed install`,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Installed-marker bookkeeping\n// ---------------------------------------------------------------------------\n\nexport interface InstalledMarker {\n version: string\n /** `{ \"pkg@version\": { resolved, integrity } }` for provenance. */\n packages?: Record<string, { resolved?: string; integrity?: string }>\n installedAt?: string\n runtime?: string\n registry?: string\n}\n\n/**\n * Write `<version>/.installed.json`.\n *\n * Publishing is rename-then-pointer, so this marker is the only thing that says\n * \"this directory is a COMPLETE payload\". `install.ts` writes it after the\n * rename, inside the version dir; `update` reads it to decide adopt-vs-install.\n */\nexport async function writeInstalledMarker(\n kind: ManagedKind,\n marker: InstalledMarker,\n): Promise<void> {\n const file = installedMarkerPath(kind, marker.version)\n await writeFileAtomic(file, `${JSON.stringify(marker, null, 2)}\\n`, { mode: 0o644 })\n}\n\nexport async function readInstalledMarker(\n kind: ManagedKind,\n version: string,\n): Promise<InstalledMarker | null> {\n try {\n // A missing marker is a normal state (not installed yet), so do not wait\n // out the retry window for it.\n const raw = await readFileWithRetry(installedMarkerPath(kind, version), {\n retryMissing: false,\n })\n const parsed = JSON.parse(raw) as InstalledMarker\n if (typeof parsed !== \"object\" || parsed === null) return null\n if (parsed.version !== version) return null\n return parsed\n } catch {\n return null\n }\n}\n","/**\n * Environment scrubbing for npm children we spawn.\n *\n * `npm_config_*` in the environment is *configuration*, not advice: npm's\n * `loadEnv` (`lib/index.js` in `@npmcli/config`) turns every non-empty\n * `npm_config_<key>` into the same setting a `.npmrc` line or a CLI flag would\n * produce, with the lowest precedence but full effect. Measured against npm\n * 11.20.0 on a fresh prefix with one pinned dependency:\n *\n * | inherited env | result of `npm install` |\n * |-----------------------------------|--------------------------------|\n * | `npm_config_global=true` | installs into `<prefix>/lib/node_modules`, `node_modules/` stays empty |\n * | `npm_config_dry_run=true` | exit 0, **nothing installed** |\n * | `npm_config_workspaces=true` | `ENOWORKSPACES`, exit 0, nothing installed |\n * | `npm_config_omit=optional` | platform packages silently missing (`@vscode/ripgrep-darwin-arm64`), so `rg` is unresolvable at run time |\n * | `npm_config_location=global` | as `global` |\n * | `npm_config_prefix=/elsewhere` | as `global` for symlinked trees |\n * | `npm_config_allow_scripts=<pkg>` | `EALLOWSCRIPTS` (see below) |\n *\n * Every one of those is a *successful* npm run. A managed install that trusted\n * the exit code would publish an empty or incomplete payload and then point\n * `current.json` at it — the class of failure that only shows up as \"the router\n * is broken on that one machine\".\n *\n * `npm_config_allow_scripts` is the sharper case and is handled separately by\n * every caller as `\"\"` (the rule at `src/lib/server-setup.ts:1838`): a non-empty\n * env-sourced allow-scripts value makes npm throw `EALLOWSCRIPTS` for any\n * project-scoped install. Emptying it is not a policy change — npm treats `''`\n * as \"not set\" and falls through to the `.npmrc` cascade, which is where the\n * operator put it.\n *\n * So: keep the *connection* and *identity* settings a user legitimately needs\n * (registry, proxies, TLS, auth tokens, cache location, retry budget), drop\n * everything that changes *what gets installed where*. Anything dropped is\n * stated in the debug log so a support thread can see why an install behaved\n * differently from the user's shell.\n */\n\n/**\n * `npm_config_*` keys we keep.\n *\n * Note what is deliberately ABSENT: `prefix`, `global`, `location`, `omit`,\n * `include`, `dry_run`, `workspaces`, `link`, `install_links`, `only`,\n * `production`, `before`, `allow_scripts`, `loglevel`. Those are the ones that\n * redirect, skip, or refuse the install.\n */\nconst KEEP_SIMPLE_KEYS = new Set([\n \"_auth\",\n \"always_auth\",\n \"ca\",\n \"cafile\",\n \"cache\",\n \"cert\",\n \"fetch_retries\",\n \"fetch_retry_maxtimeout\",\n \"fetch_retry_mintimeout\",\n \"fetch_timeout\",\n \"globalconfig\",\n \"https_proxy\",\n \"http_proxy\",\n \"key\",\n \"local_address\",\n \"maxsockets\",\n \"no_proxy\",\n \"noproxy\",\n \"otp\",\n \"proxy\",\n \"registry\",\n \"strict_ssl\",\n \"userconfig\",\n])\n\n/**\n * `//host/path/:_authToken` — a nerf-dart key. npm stores per-registry\n * credentials under this shape and `loadEnv` deliberately does not normalize it,\n * so it must be matched as a prefix rather than a name.\n */\nconst NERF_DART_RE = /^\\/\\/.*:(_authToken|_auth|username|_password|email)$/i\n\nexport interface NpmEnvScrubResult {\n env: NodeJS.ProcessEnv\n /** Keys that were removed, for the debug log. Never includes values. */\n dropped: Array<string>\n /** Keys that were kept, so a support thread can see what applied. */\n kept: Array<string>\n}\n\n/**\n * Build a child env for an npm invocation.\n *\n * `overrides` are applied last and win, so a caller can pin `npm_config_registry`\n * for Pi (`resolvePiRegistry()`) without fighting the cascade.\n *\n * The result fully REPLACES the child env (`runCommandCapture` uses\n * `opts.env ?? process.env`), so anything not copied here is genuinely absent\n * rather than merged back in from the parent.\n */\nexport function buildNpmEnv(\n base: NodeJS.ProcessEnv = process.env,\n overrides: NodeJS.ProcessEnv = {},\n): NpmEnvScrubResult {\n const env: NodeJS.ProcessEnv = {}\n const dropped: Array<string> = []\n const kept: Array<string> = []\n\n for (const [key, value] of Object.entries(base)) {\n if (value === undefined) continue\n // npm itself skips empty values, so keeping them is harmless but noisy.\n if (!/^npm_config_/i.test(key)) {\n env[key] = value\n continue\n }\n if (value === \"\") {\n env[key] = value\n continue\n }\n const bare = key.slice(\"npm_config_\".length).toLowerCase()\n const isKept = NERF_DART_RE.test(key.slice(\"npm_config_\".length)) || KEEP_SIMPLE_KEYS.has(bare)\n if (isKept) {\n env[key] = value\n kept.push(key)\n } else {\n dropped.push(key)\n }\n }\n\n // Null an inherited allow-scripts policy for this child. See the module doc.\n env.npm_config_allow_scripts = \"\"\n\n for (const [key, value] of Object.entries(overrides)) {\n if (value === undefined) delete env[key]\n else env[key] = value\n }\n\n return { env, dropped, kept }\n}\n\n/**\n * Whether a managed install may run at all in this process.\n *\n * `GH_ROUTER_NO_MANAGED_INSTALL` is the user's off switch (documented in the\n * plan); `ghRouterNoManagedInstall()` is the only place that reads it so the\n * bootstrap, the CLI, and the tests cannot disagree about its spelling.\n */\nexport function managedInstallDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.GH_ROUTER_NO_MANAGED_INSTALL?.trim().toLowerCase()\n return raw === \"1\" || raw === \"true\" || raw === \"yes\" || raw === \"on\"\n}\n","/**\n * The bootstrap decision: \"run me, or hand off?\"\n *\n * `dist/bin.js` is the published `bin`, so it runs on EVERY invocation — including\n * the ~13 per-turn Claude Code hooks. That makes this file's job narrow and its\n * cost budget tight: decide in a few milliseconds, then get out of the way.\n *\n * The decision itself is pure (`decideBootstrap` takes its inputs, returns a\n * plan), because the alternative — asserting behaviour by spawning the real CLI\n * and parsing logs — cannot reach the interesting cases (a managed pointer whose\n * payload was reaped, a re-exec that must preserve a signal death).\n *\n * ### Why re-exec instead of adopting in-process\n *\n * `main.ts` prints the banner (`:45`) and computes the version (`:16`) at module\n * scope, so an in-process adoption could only happen *after* the npx copy had\n * already evaluated citty/consola and printed its own banner: two banners, two\n * module graphs, and duplicated singletons (`state.ts`, `mcp-inflight.ts`, the\n * keep-awake refcount, the launch registry). Rewriting `argv[1]` first is worse —\n * it mutates a global before a fallible import, leaving argv pointing into the\n * managed tree while npx code runs.\n *\n * Re-exec makes `argv[1]` correct by construction, so `packageRoot()`,\n * `currentInvocation()`, and the self-respawn sites need no changes at all. The\n * cost is one extra runtime start (~40 ms) against a solved 3 s problem.\n *\n * ### The three things that must NOT re-exec\n *\n * - **`internal-*` subcommands.** They run per turn; an extra hop each time is a\n * fifth of a second per turn, and they must run the code the session already\n * validated rather than whatever is live now.\n * - **`update`.** It is the repair tool. Bootstrapping it would make a broken\n * pointer unrepairable, and the background child re-entering this file would\n * spawn itself forever.\n * - **A missing/nonexistent payload.** Falling back to the current tree is always\n * correct; re-exec into a hole is not.\n */\n\nimport path from \"node:path\"\n\nimport { classifyEntry, shouldAdoptFor } from \"./origin\"\nimport { readPointer } from \"./pointer\"\nimport { mayAttemptNow, patchInstallState, readInstallState } from \"./state\"\nimport { managedInstallDisabled } from \"./npm-env\"\n\nexport type BootstrapPlan =\n /** Run this tree's `main.js` (the normal case for every origin but npx/bunx). */\n | { action: \"passthrough\"; reason: string }\n /** Hand off to the managed payload at `entryPath`. */\n | { action: \"reexec\"; entryPath: string; version: string; reason: string }\n /** Run this tree, and queue a background install for the next launch. */\n | { action: \"schedule\"; reason: string; updaterEntry: string }\n\n/**\n * Subcommands that must never take the hand-off path.\n *\n * `internal-*` is a prefix, not a list: a new hook subcommand added to\n * `main.ts` should inherit the rule without editing this file.\n */\nfunction mustRunInline(subcommand: string | undefined): string | null {\n if (!subcommand) return null\n if (subcommand.startsWith(\"internal-\")) return \"internal hook (per-turn hot path)\"\n if (subcommand === \"update\") return \"update is the repair tool\"\n return null\n}\n\nexport interface BootstrapInputs {\n argv: readonly string[]\n env?: NodeJS.ProcessEnv\n /** Injected so tests need not manipulate `process.argv`. */\n entry?: string\n}\n\n/**\n * Decide what `dist/bin.js` should do, given the argv it was started with.\n *\n * Returns `passthrough` for every origin that owns its own tree (`npm-global`,\n * `source`, `managed`, `unknown`): user decision 4 is that a global install is\n * never duplicated, and a dev checkout must run its own code.\n */\nexport async function decideBootstrap(inputs: BootstrapInputs): Promise<BootstrapPlan> {\n const env = inputs.env ?? process.env\n const argv = inputs.argv\n // The first non-flag token is the subcommand, which is exactly what citty does\n // (`findSubCommandIndex`): the ROOT command declares no `args`, so there is no\n // global flag that takes a value and no value can be mistaken for a name. A\n // value flag added to the root would have to be taught here too — this mirrors\n // citty rather than guessing, because guessing wrong disables the hand-off.\n //\n // `--` ends option parsing (citty stops there as well), so anything after it is\n // an operand: `github-router -- update` must not be read as the repair command.\n const terminator = argv.indexOf(\"--\")\n const positional = terminator >= 0 ? argv.slice(0, terminator) : argv\n const subcommand = positional.find((arg) => !arg.startsWith(\"-\"))\n\n if (managedInstallDisabled(env)) {\n return { action: \"passthrough\", reason: \"GH_ROUTER_NO_MANAGED_INSTALL is set\" }\n }\n if (argv.includes(\"--no-managed-install\")) {\n return { action: \"passthrough\", reason: \"--no-managed-install\" }\n }\n // The detached child this file spawns must not bootstrap again, or it would\n // classify the same npx tree, see the same missing pointer, and spawn forever.\n if (env.GH_ROUTER_MANAGED_BACKGROUND === \"1\") {\n return { action: \"passthrough\", reason: \"background child; bootstrap already decided\" }\n }\n const inline = mustRunInline(subcommand)\n if (inline) return { action: \"passthrough\", reason: inline }\n\n // Classify the entry that is actually running, not `process.argv[1]`: they are\n // the same in production (this file IS argv[1]), but keeping it explicit is\n // what makes the matrix testable without respawning the runner.\n const entry = inputs.entry ?? argvEntry()\n const origin = await classifyEntry(entry)\n // `managed` short-circuits BEFORE the pointer is read, so a mis-pointed\n // pointer can never cost an exec loop — which is exactly the failure a\n // \"resolve bin from package.json\" design would have produced, since the bin\n // is this file.\n if (origin.origin === \"managed\") {\n return { action: \"passthrough\", reason: \"already running from the managed tree\" }\n }\n if (!shouldAdoptFor(origin.origin)) {\n return { action: \"passthrough\", reason: `origin is ${origin.origin}; this tree owns itself` }\n }\n\n const pointer = await readPointer(\"self\")\n if (pointer) {\n return {\n action: \"reexec\",\n entryPath: pointer.entryPath,\n version: pointer.version,\n reason: `managed ${pointer.version} is live`,\n }\n }\n\n if (!entry) return { action: \"passthrough\", reason: \"no argv[1]; cannot schedule an install\" }\n\n const state = await readInstallState(\"self\")\n if (!mayAttemptNow(state)) {\n return {\n action: \"passthrough\",\n reason: `managed install backing off until ${state.nextAttemptAt}`,\n }\n }\n return { action: \"schedule\", reason: \"no managed install yet\", updaterEntry: entry }\n}\n\n/** `process.argv[1]` when it looks usable. */\nexport function argvEntry(): string | undefined {\n const entry = process.argv[1]\n return typeof entry === \"string\" && entry.length > 0 && path.isAbsolute(entry) ? entry : undefined\n}\n\n/**\n * Reserve a background attempt and stamp the origin.\n *\n * Written BEFORE the spawn (optimistic) so a second `npx github-router@latest`\n * a minute later sees the reservation and waits, instead of starting a competing\n * npm install over the same prefix.\n *\n * Deliberately NOT `nextAttemptAt`: a reservation must never become a backoff\n * window, or a spawn that fails outright (ENOMEM, a deleted `process.execPath`)\n * would silence the next launch for an hour without npm ever having run. The\n * cheap-and-honest split is: this file records only that an attempt was QUEUED\n * (`lastAttemptAt`, `lastOrigin`), and the child records success or failure when\n * it has something real to report. Stamp-per-spawn would move the write after the\n * spawn it is supposed to guard (a rival launch can win that window), and buys\n * nothing the model above does not already give.\n */\nexport async function reserveBackgroundAttempt(origin: string): Promise<void> {\n // A PATCH, never `{...snapshot, ...}`: this runs after an `npm view` that can\n // take seconds, and spreading a stale snapshot would resurrect fields another\n // process cleared meanwhile (`npmProbe` — losing it costs a 250 ms subprocess\n // on every later launch).\n await patchInstallState(\"self\", {\n lastAttemptAt: new Date().toISOString(),\n lastOrigin: origin,\n })\n}\n\n/**\n * The argv the detached background child runs. Exported so a test can pin it.\n *\n * `--no-optional` is deliberate: the optional payloads are up to 547 MB, and a\n * detached child that the user never sees must not start downloading them. They\n * are installed by an explicit `github-router update` (or on demand, from the\n * feature that needs one).\n */\nexport const BACKGROUND_UPDATE_ARGS = [\"update\", \"--self\", \"--quiet\", \"--no-optional\"] as const\n","#!/usr/bin/env node\n\n/**\n * The published `bin` entry — `dist/bin.js`.\n *\n * Runs on every invocation, including the ~13 per-turn Claude Code hooks, so it\n * must be cheap and must never change behaviour for a tree that owns itself.\n * `lib/managed-install/bootstrap.ts` holds the whole decision (and its rationale);\n * this file only executes the plan.\n *\n * Two mechanical constraints on the code below:\n *\n * 1. **`main.js` is imported DYNAMICALLY and by a computed specifier.** A static\n * `import \"./main.js\"` would be folded into this bundle by tsdown, which would\n * make `dist/bin.js` the entire 40 MB app and defeat the point of a bootstrap\n * that can hand off before the app graph loads. The computed string keeps it a\n * runtime import.\n * 2. **Nothing here throws.** A bootstrap failure must degrade to \"run this\n * tree\", never to \"the CLI is broken\". Every step is wrapped, and the fallback\n * is always `import` of this tree's own entry.\n */\n\nimport { spawn } from \"node:child_process\"\n\nimport {\n BACKGROUND_UPDATE_ARGS,\n argvEntry,\n decideBootstrap,\n reserveBackgroundAttempt,\n} from \"./lib/managed-install/bootstrap\"\nimport { classifyOrigin } from \"./lib/managed-install/origin\"\n\n/** `SIGINT`→2 etc., for the 128+n convention when a re-raise is not possible. */\nconst SIGNAL_NUMBERS: Record<string, number> = {\n SIGHUP: 1,\n SIGINT: 2,\n SIGTERM: 15,\n}\n\n/**\n * Run this tree's real entry.\n *\n * The specifier is built at RUNTIME from `import.meta.url`, and that is not\n * decoration: a literal `import(\"./main.js\")` — or even `./${\"main\"}.js`, which\n * rolldown folds statically — is inlined by the bundler, which turns\n * `dist/bin.js` into a second copy of the whole app (measured: 13.4 MB and the\n * full tree-sitter/transformers graph). A `URL` is opaque to the bundler, so the\n * import stays a real runtime module load and `dist/bin.js` stays a few KB.\n */\nasync function runThisTree(): Promise<void> {\n const specifier = new URL(\"./main.js\", import.meta.url).href\n await import(specifier)\n}\n\n/**\n * Hand off to the managed payload.\n *\n * Re-exec rather than in-process adoption: `main.ts` prints its banner and reads\n * its version at module scope, so adopting after this module has already been\n * evaluated would print two banners and evaluate two module graphs. `stdio:\n * \"inherit\"` keeps the caller's pipes (a hook's stdout IS its payload), and the\n * child's exit code and signal are propagated verbatim so a supervisor sees the\n * real outcome.\n */\nasync function handOff(entryPath: string, version: string): Promise<void> {\n const SIGNALS = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const\n const dropForwarders = (): void => {\n for (const name of SIGNALS) process.removeAllListeners(name)\n }\n\n // Forwarders FIRST, before the spawn: a signal delivered between `spawn`\n // returning and the handler being installed kills this process with the default\n // disposition and orphans the payload, which for a hook means a child that keeps\n // running after its parent is gone.\n let child: ReturnType<typeof spawn> | null = null\n for (const signal of SIGNALS) {\n process.on(signal, () => {\n try {\n child?.kill(signal)\n } catch {\n // already gone\n }\n })\n }\n\n try {\n child = spawn(process.execPath, [entryPath, ...process.argv.slice(2)], {\n stdio: \"inherit\",\n windowsHide: true,\n // Diagnostic marker only — nothing branches on it. It answers \"was this\n // process started by the bootstrap or straight from the payload?\" in a bug\n // report, which is otherwise indistinguishable once the banner is printed.\n env: { ...process.env, GH_ROUTER_MANAGED_HANDOFF: version },\n })\n } catch (err) {\n dropForwarders()\n throw err\n }\n\n await new Promise<void>((resolve, reject) => {\n // A hand-off that never started must leave NO forwarders behind either: the\n // caller's fallback (`runThisTree`) would then run with SIGINT/SIGTERM\n // absorbed by a handler whose child is gone, so Ctrl-C would do nothing and\n // the process would exit 0 — the same hazard as the re-raise below.\n child.on(\"error\", (err) => {\n dropForwarders()\n reject(err)\n })\n child.on(\"exit\", (code, signal) => {\n // It exits once. Leaving the forwarders installed after a normal exit makes\n // the rest of this process deaf to Ctrl-C for no reason.\n dropForwarders()\n if (signal) {\n // Mirror a signal death so the caller can distinguish \"crashed\" from\n // \"exited 1\". Shells expect 128+signal, so set that too in case the\n // re-raise cannot happen (a signal with no default action, or a\n // platform that refuses).\n\n process.exitCode = 128 + (SIGNAL_NUMBERS[signal] ?? 0)\n try {\n process.kill(process.pid, signal)\n return\n } catch {\n resolve()\n return\n }\n }\n process.exitCode = typeof code === \"number\" ? code : 1\n resolve()\n })\n })\n}\n\n/**\n * Queue the background install.\n *\n * Detached and unref'd: this launch must not be delayed by, or kept alive for, an\n * npm install. The child is `node <this entry> update --self --quiet`, which\n * reaches the same code with `GH_ROUTER_MANAGED_BACKGROUND=1` so it cannot recurse\n * into another spawn.\n */\nfunction scheduleBackgroundInstall(entry: string): void {\n try {\n const child = spawn(process.execPath, [entry, ...BACKGROUND_UPDATE_ARGS], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, GH_ROUTER_MANAGED_BACKGROUND: \"1\" },\n })\n child.on(\"error\", () => {})\n child.unref()\n } catch {\n // Never fatal: the next launch tries again.\n }\n}\n\nasync function main(): Promise<void> {\n let plan\n try {\n plan = await decideBootstrap({ argv: process.argv.slice(2), entry: argvEntry() })\n } catch {\n // Any failure in classification means \"do not get clever\".\n await runThisTree()\n return\n }\n\n if (plan.action === \"reexec\") {\n try {\n await handOff(plan.entryPath, plan.version)\n return\n } catch {\n // A payload that cannot be started is a broken install, not a broken\n // launch: run this tree instead and let the next background attempt fix it.\n await runThisTree()\n return\n }\n }\n\n if (plan.action === \"schedule\") {\n // Reserve BEFORE spawning so a second concurrent launch backs off instead of\n // starting a competing install over the same prefix. Best effort.\n try {\n const origin = await classifyOrigin()\n await reserveBackgroundAttempt(origin.origin)\n } catch {\n // Reservation is an optimisation; the install itself re-checks its lock.\n }\n scheduleBackgroundInstall(plan.updaterEntry)\n }\n\n await runThisTree()\n}\n\n/**\n * Top-level guard.\n *\n * `runThisTree` is the one thing that must happen; if the bootstrap itself is\n * broken (an unreadable app dir, a corrupt state file that somehow throws), the\n * user still gets a working CLI. Deliberately `console.error` rather than\n * `consola`: the app graph has not loaded yet and pulling it in here would\n * reintroduce the double-instance hazard.\n */\nmain().catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err)\n console.error(`github-router: bootstrap fell back to this tree (${message})`)\n process.exitCode = 1\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAS,YAAY,KAAgC;CACnD,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,IAAI,YAAY,MAAM,QAAQ,OAAO,IAAI,QAAQ;CAEvD,OAAO;AACT;;;;;;;;;;AAkBA,SAAgB,kBACd,MACA,OAA8B,CAAC,GAChB;CACf,MAAM,WAAW,KAAK,YAAYA,UAAQ;CAC1C,MAAM,MAAM,KAAK,OAAOA,UAAQ;CAIhC,MAAM,SACJ,KAAK,QAAQ,OAAOA,UAAQ,QAAQ,aAAaA,UAAQ,IAAI,IAAI,KAAA;CACnE,MAAM,cAAc,SAAS,KAAK,QAAQ,MAAM,IAAI;CAEpD,MAAM,OAAO,YAAY,GAAG,CAAC,CAC1B,MAAM,KAAK,SAAS,CAAC,CAGrB,QAAQ,MAAM,EAAE,SAAS,KAAK,MAAM,GAAG;CAE1C,MAAM,QAAQ,aAAa;CAG3B,IAAI,CAAC,SAAS,KAAK,SAAS,GAAG,GAC7B,OAAO,WAAW,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI;CAGjD,IAAI,UAAU,KAAK,SAAS,IAAI,K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AI;EACF,OAAO,MAAM,gBAAgB;GAAE,MAAM,QAAQ,KAAK,MAAM,CAAC;GAAG,OAAO,UAAU;EAAE,CAAC;CAClF,QAAQ;EAEN,MAAM,YAAY;EAClB;CACF;CAEA,IAAI,KAAK,WAAW,UAClB,IAAI;EACF,MAAM,QAAQ,KAAK,WAAW,KAAK,OAAO;EAC1C;CACF,QAAQ;EAGN,MAAM,YAAY;EAClB;CACF;CAGF,IAAI,KAAK,WAAW,YAAY;EAG9B,IAAI;GAEF,MAAM,0BAAyB,MADV,eAAe,EACL,CAAO,MAAM;EAC9C,QAAQ,CAER;EACA,0BAA0B,KAAK,YAAY;CAC7C;CAEA,MAAM,YAAY;AACpB;;;;;;;;;;AAWA,KAAK,CAAC,CAAC,OAAO,QAAiB;CAC7B,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,QAAQ,MAAM,oDAAoD,QAAQ,EAAE;CAC5E,QAAQ,WAAW;AACrB,CAAC"}
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "name": "github-router browser bridge",
4
4
  "short_name": "gh-router-browser",
5
- "version": "0.3.379",
5
+ "version": "0.3.380",
6
6
  "description": "Bridge between Claude (via github-router /mcp) and the browser. Implements tab control, navigation, clicks, form fill, downloads, screenshots, devtools eval. Blocks navigation to chrome://settings.",
7
7
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqJElxuBlonBS3TVW9FJN0mGTtShB3L1hoaYf6k39SOr1ogGYmF90EjRxy1i21k9wQQjPf26bcBu/9X67KrQjQV0uB38CaNukgiSeoLjfptN811u+PJHx6BP+jx3Qa6/3VenNPxHC8WEU0GXql8QSjIHEyCwKb6fMASXOK94JyB5Ywov2x8mt/+9ncqBBBMVzf6r5Sagy4PL1XnryLsuADD/vOEkPet8wXgH/Oj7v5tTsQQZ7U1JT51PoDs2BFnXc5v3TkVgZwd32k3ONh+nkDw1Hof+4zwUGOyJE6eMrlYzRlKM4Qxdf9JpavQvqfieAbTRWcyKeclnHeoIfE7cDBQIDAQAB",
8
8
  "background": {
@@ -1,6 +1,6 @@
1
- import { i as ensurePaths } from "./paths-CVEO8jEH.js";
2
- import { r as setupGitHubToken } from "./token-CPzYxU4Y.js";
3
- import { t as getCopilotUsage } from "./get-copilot-usage-CKg42gSH.js";
1
+ import { i as ensurePaths } from "./paths-DeFmYJhO.js";
2
+ import { r as setupGitHubToken } from "./token-CKPOBdO0.js";
3
+ import { t as getCopilotUsage } from "./get-copilot-usage-BZ6t2hFZ.js";
4
4
  import { defineCommand } from "citty";
5
5
  import consola from "consola";
6
6
  // src/check-usage.ts
@@ -39,4 +39,4 @@ const checkUsage = defineCommand({
39
39
  });
40
40
  export { checkUsage };
41
41
 
42
- //# sourceMappingURL=check-usage-BlIWDuV2.js.map
42
+ //# sourceMappingURL=check-usage-DM39fdel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"check-usage-BlIWDuV2.js","names":[],"sources":["../src/check-usage.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupGitHubToken } from \"./lib/token\"\nimport {\n getCopilotUsage,\n type QuotaDetail,\n} from \"./services/github/get-copilot-usage\"\n\nexport const checkUsage = defineCommand({\n meta: {\n name: \"check-usage\",\n description: \"Show current GitHub Copilot usage/quota information\",\n },\n async run() {\n await ensurePaths()\n await setupGitHubToken()\n try {\n const usage = await getCopilotUsage()\n const premium = usage.quota_snapshots.premium_interactions\n const premiumTotal = premium.entitlement\n const premiumUsed = premiumTotal - premium.remaining\n const premiumPercentUsed =\n premiumTotal > 0 ? (premiumUsed / premiumTotal) * 100 : 0\n const premiumPercentRemaining = premium.percent_remaining\n\n // Helper to summarize a quota snapshot\n function summarizeQuota(name: string, snap: QuotaDetail | undefined) {\n if (!snap) return `${name}: N/A`\n const total = snap.entitlement\n const used = total - snap.remaining\n const percentUsed = total > 0 ? (used / total) * 100 : 0\n const percentRemaining = snap.percent_remaining\n return `${name}: ${used}/${total} used (${percentUsed.toFixed(1)}% used, ${percentRemaining.toFixed(1)}% remaining)`\n }\n\n const premiumLine = `Premium: ${premiumUsed}/${premiumTotal} used (${premiumPercentUsed.toFixed(1)}% used, ${premiumPercentRemaining.toFixed(1)}% remaining)`\n const chatLine = summarizeQuota(\"Chat\", usage.quota_snapshots.chat)\n const completionsLine = summarizeQuota(\n \"Completions\",\n usage.quota_snapshots.completions,\n )\n\n consola.box(\n `Copilot Usage (plan: ${usage.copilot_plan})\\n`\n + `Quota resets: ${usage.quota_reset_date}\\n`\n + `\\nQuotas:\\n`\n + ` ${premiumLine}\\n`\n + ` ${chatLine}\\n`\n + ` ${completionsLine}`,\n )\n } catch (err) {\n consola.error(\"Failed to fetch Copilot usage:\", err)\n process.exit(1)\n }\n },\n})\n"],"mappings":";;;;;;AAUA,MAAa,aAAa,cAAc;CACtC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,MAAM;EACV,MAAM,YAAY;EAClB,MAAM,iBAAiB;EACvB,IAAI;GACF,MAAM,QAAQ,MAAM,gBAAgB;GACpC,MAAM,UAAU,MAAM,gBAAgB;GACtC,MAAM,eAAe,QAAQ;GAC7B,MAAM,cAAc,eAAe,QAAQ;GAC3C,MAAM,qBACJ,eAAe,IAAK,cAAc,eAAgB,MAAM;GAC1D,MAAM,0BAA0B,QAAQ;GAGxC,SAAS,eAAe,MAAc,MAA+B;IACnE,IAAI,CAAC,MAAM,OAAO,GAAG,KAAK;IAC1B,MAAM,QAAQ,KAAK;IACnB,MAAM,OAAO,QAAQ,KAAK;IAC1B,MAAM,cAAc,QAAQ,IAAK,OAAO,QAAS,MAAM;IACvD,MAAM,mBAAmB,KAAK;IAC9B,OAAO,GAAG,KAAK,IAAI,KAAK,GAAG,MAAM,SAAS,YAAY,QAAQ,CAAC,EAAE,UAAU,iBAAiB,QAAQ,CAAC,EAAE;GACzG;GAEA,MAAM,cAAc,YAAY,YAAY,GAAG,aAAa,SAAS,mBAAmB,QAAQ,CAAC,EAAE,UAAU,wBAAwB,QAAQ,CAAC,EAAE;GAChJ,MAAM,WAAW,eAAe,QAAQ,MAAM,gBAAgB,IAAI;GAClE,MAAM,kBAAkB,eACtB,eACA,MAAM,gBAAgB,WACxB;GAEA,QAAQ,IACN,wBAAwB,MAAM,aAAa,mBACtB,MAAM,iBAAiB,iBAEnC,YAAY,MACZ,SAAS,MACT,iBACX;EACF,SAAS,KAAK;GACZ,QAAQ,MAAM,kCAAkC,GAAG;GACnD,QAAQ,KAAK,CAAC;EAChB;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"check-usage-DM39fdel.js","names":[],"sources":["../src/check-usage.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupGitHubToken } from \"./lib/token\"\nimport {\n getCopilotUsage,\n type QuotaDetail,\n} from \"./services/github/get-copilot-usage\"\n\nexport const checkUsage = defineCommand({\n meta: {\n name: \"check-usage\",\n description: \"Show current GitHub Copilot usage/quota information\",\n },\n async run() {\n await ensurePaths()\n await setupGitHubToken()\n try {\n const usage = await getCopilotUsage()\n const premium = usage.quota_snapshots.premium_interactions\n const premiumTotal = premium.entitlement\n const premiumUsed = premiumTotal - premium.remaining\n const premiumPercentUsed =\n premiumTotal > 0 ? (premiumUsed / premiumTotal) * 100 : 0\n const premiumPercentRemaining = premium.percent_remaining\n\n // Helper to summarize a quota snapshot\n function summarizeQuota(name: string, snap: QuotaDetail | undefined) {\n if (!snap) return `${name}: N/A`\n const total = snap.entitlement\n const used = total - snap.remaining\n const percentUsed = total > 0 ? (used / total) * 100 : 0\n const percentRemaining = snap.percent_remaining\n return `${name}: ${used}/${total} used (${percentUsed.toFixed(1)}% used, ${percentRemaining.toFixed(1)}% remaining)`\n }\n\n const premiumLine = `Premium: ${premiumUsed}/${premiumTotal} used (${premiumPercentUsed.toFixed(1)}% used, ${premiumPercentRemaining.toFixed(1)}% remaining)`\n const chatLine = summarizeQuota(\"Chat\", usage.quota_snapshots.chat)\n const completionsLine = summarizeQuota(\n \"Completions\",\n usage.quota_snapshots.completions,\n )\n\n consola.box(\n `Copilot Usage (plan: ${usage.copilot_plan})\\n`\n + `Quota resets: ${usage.quota_reset_date}\\n`\n + `\\nQuotas:\\n`\n + ` ${premiumLine}\\n`\n + ` ${chatLine}\\n`\n + ` ${completionsLine}`,\n )\n } catch (err) {\n consola.error(\"Failed to fetch Copilot usage:\", err)\n process.exit(1)\n }\n },\n})\n"],"mappings":";;;;;;AAUA,MAAa,aAAa,cAAc;CACtC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,MAAM;EACV,MAAM,YAAY;EAClB,MAAM,iBAAiB;EACvB,IAAI;GACF,MAAM,QAAQ,MAAM,gBAAgB;GACpC,MAAM,UAAU,MAAM,gBAAgB;GACtC,MAAM,eAAe,QAAQ;GAC7B,MAAM,cAAc,eAAe,QAAQ;GAC3C,MAAM,qBACJ,eAAe,IAAK,cAAc,eAAgB,MAAM;GAC1D,MAAM,0BAA0B,QAAQ;GAGxC,SAAS,eAAe,MAAc,MAA+B;IACnE,IAAI,CAAC,MAAM,OAAO,GAAG,KAAK;IAC1B,MAAM,QAAQ,KAAK;IACnB,MAAM,OAAO,QAAQ,KAAK;IAC1B,MAAM,cAAc,QAAQ,IAAK,OAAO,QAAS,MAAM;IACvD,MAAM,mBAAmB,KAAK;IAC9B,OAAO,GAAG,KAAK,IAAI,KAAK,GAAG,MAAM,SAAS,YAAY,QAAQ,CAAC,EAAE,UAAU,iBAAiB,QAAQ,CAAC,EAAE;GACzG;GAEA,MAAM,cAAc,YAAY,YAAY,GAAG,aAAa,SAAS,mBAAmB,QAAQ,CAAC,EAAE,UAAU,wBAAwB,QAAQ,CAAC,EAAE;GAChJ,MAAM,WAAW,eAAe,QAAQ,MAAM,gBAAgB,IAAI;GAClE,MAAM,kBAAkB,eACtB,eACA,MAAM,gBAAgB,WACxB;GAEA,QAAQ,IACN,wBAAwB,MAAM,aAAa,mBACtB,MAAM,iBAAiB,iBAEnC,YAAY,MACZ,SAAS,MACT,iBACX;EACF,SAAS,KAAK;GACZ,QAAQ,MAAM,kCAAkC,GAAG;GACnD,QAAQ,KAAK,CAAC;EAChB;CACF;AACF,CAAC"}
@@ -1,29 +1,30 @@
1
- import { $ as updateClaude, B as formatFastPrerequisiteFailure, G as validateCheap1mProfilePrerequisites, H as profileDescriptor, I as formatBalancedPrerequisiteFailure, J as validateFastProfilePrerequisites, K as validateCheapProfilePrerequisites, L as formatCheap1mPrerequisiteFailure, Q as checkClaudeVersion, R as formatCheapPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, X as validateMaxProfileLaunch, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, a as setupAndServe, b as injectModelPickerSettingsFile, i as parseSharedArgs, o as sharedServerArgs, q as validateCheapestProfilePrerequisites, s as LAUNCH_SECRET_HEADER, t as getClaudeCodeEnvVars, v as startKeepAwake, x as listModelsForEndpoint, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-ClZdV33Q.js";
2
- import { a as buildArtifactReviewSkill, c as injectAllowRules, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, p as resolveCodexCliBackend, r as injectedSkillsForLaunch, t as injectAttributionSuppressionIntoSettingsFile } from "./attribution-settings-BWYL2b8N.js";
3
- import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-DMUnXVGT.js";
4
- import { i as launchChild, r as getCodexVersion, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
5
- import { d as writeArtifactCredsToMirror, f as writeLaunchBoundSyntheticCredential, o as purgeNonRouterAgentsFromMirror, r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-CVEO8jEH.js";
6
- import { d as stopGateId, i as captureLaunchBaseline, l as purgeNonRouterHooksForPinnedProfile, n as buildSessionBindHookCommand, r as buildStopHookCommand, s as injectStopHookIntoSettingsFile, t as buildArtifactOpenHookCommand, u as stopGateDisabled } from "./stop-gate-hook-CBVLD8iB.js";
7
- import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-MhjK92wq.js";
8
- import { d as stopGateEnabledForRepo, l as repoFingerprint, p as trustRepo, t as fileBaselineStore, u as repoRoot } from "./stop-gate-policy-BehNiNix.js";
9
- import { a as checksForDescriptor, i as writeDiscoveredGate, n as readDiscoveredGate, o as descriptorHash, r as sourcesHash, s as parseGateDescriptor, t as discoverGateCommands } from "./gate-discovery-DjH9YXoN.js";
10
- import { t as liveExec } from "./orchestration-B93jxrWI.js";
1
+ import { d as checkClaudeVersion, f as updateClaude, u as runSelfUpdate } from "./pi-version-check-BeBB0Ny9.js";
2
+ import { a as buildArtifactReviewSkill, c as injectAllowRules, f as injectPeerMcpIntoMirror, g as writePeerMcpRuntimeFiles, h as workersKeyOf, i as writeInjectedSkill, l as planModeAllowRules, m as resolveGroupKeysFromMirror, p as resolveCodexCliBackend, r as injectedSkillsForLaunch, t as injectAttributionSuppressionIntoSettingsFile } from "./attribution-settings-BJ1fjX7V.js";
3
+ import { A as formatCheap1mPrerequisiteFailure, B as validateCheapestProfilePrerequisites, F as profileDescriptor, H as validateLocalProfilePrerequisites, I as resolveLaunchProfile, L as validateBalancedProfilePrerequisites, M as formatCheapestPrerequisiteFailure, N as formatFastPrerequisiteFailure, P as formatLocalPrerequisiteFailure, R as validateCheap1mProfilePrerequisites, U as validateMaxProfileLaunch, V as validateFastProfilePrerequisites, a as setupAndServe, d as startKeepAwake, f as stopKeepAwake, h as enableFileLogging, i as parseSharedArgs, j as formatCheapPrerequisiteFailure, k as formatBalancedPrerequisiteFailure, m as listModelsForEndpoint, o as sharedServerArgs, p as injectModelPickerSettingsFile, s as LAUNCH_SECRET_HEADER, t as getClaudeCodeEnvVars, z as validateCheapProfilePrerequisites } from "./server-setup-DLwejgVA.js";
4
+ import { n as hookLauncherDegradedWarning, r as resolveSelfInvocation } from "./self-invocation-Dnq4iVD6.js";
5
+ import { i as launchChild, r as getCodexVersion, t as provisionToolbelt } from "./provision-BWtuDq_v.js";
6
+ import { d as writeArtifactCredsToMirror, f as writeLaunchBoundSyntheticCredential, o as purgeNonRouterAgentsFromMirror, r as ensureClaudeConfigMirror, s as removeOwnClaudeConfigMirror, t as PATHS } from "./paths-DeFmYJhO.js";
7
+ import { d as stopGateId, i as captureLaunchBaseline, l as purgeNonRouterHooksForPinnedProfile, n as buildSessionBindHookCommand, r as buildStopHookCommand, s as injectStopHookIntoSettingsFile, t as buildArtifactOpenHookCommand, u as stopGateDisabled } from "./stop-gate-hook-DBOj0TqL.js";
8
+ import { i as planReviewEnabled, t as buildPlanReviewHookCommand } from "./plan-review-hook-D_yyjOgO.js";
9
+ import { d as stopGateEnabledForRepo, l as repoFingerprint, p as trustRepo, t as fileBaselineStore, u as repoRoot } from "./stop-gate-policy-Bp2wGh_W.js";
10
+ import { a as checksForDescriptor, i as writeDiscoveredGate, n as readDiscoveredGate, o as descriptorHash, r as sourcesHash, s as parseGateDescriptor, t as discoverGateCommands } from "./gate-discovery-2ILpM2fi.js";
11
+ import { t as liveExec } from "./orchestration-Bto5Nc1Y.js";
11
12
  import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-CYx10nlU.js";
12
- import { C as localContractFor, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, g as displayModelName, j as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, p as cheapestContractFor, r as buildPromptSubmitHookCommand, v as isCheapestFamily, x as isPinnedLaunchProfile } from "./static-context-pack-CtnBwHSd.js";
13
- import { i as assertShapingInstalled, n as buildFirstMateGuardHookCommand, t as FIRST_MATE_GUARD_MATCHER } from "./internal-first-mate-guard-4Yro9xNM.js";
14
- import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-C7RtNOXv.js";
15
- import { r as FAST_DISPATCH_TOOL_MATCHER, t as buildFastDispatchGuardHookCommand } from "./internal-fast-dispatch-guard-PDdlkPU3.js";
16
- import { i as assertMaxDispatchGuardInstalled, r as MAX_DISPATCH_TOOL_MATCHER, t as buildMaxDispatchGuardHookCommand } from "./internal-max-dispatch-guard-0teaxIc1.js";
13
+ import { C as localContractFor, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, g as displayModelName, j as CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL, p as cheapestContractFor, r as buildPromptSubmitHookCommand, v as isCheapestFamily, x as isPinnedLaunchProfile } from "./static-context-pack-BKFelEbM.js";
14
+ import { i as assertShapingInstalled, n as buildFirstMateGuardHookCommand, t as FIRST_MATE_GUARD_MATCHER } from "./internal-first-mate-guard-DsEEsLKJ.js";
15
+ import { l as guardToolMatcher, n as activeDispatchModes, r as buildWorkerGuardHookCommand } from "./worker-dispatch-DBWKTMda.js";
16
+ import { r as FAST_DISPATCH_TOOL_MATCHER, t as buildFastDispatchGuardHookCommand } from "./internal-fast-dispatch-guard-ZeS9u0A3.js";
17
+ import { i as assertMaxDispatchGuardInstalled, r as MAX_DISPATCH_TOOL_MATCHER, t as buildMaxDispatchGuardHookCommand } from "./internal-max-dispatch-guard-4RLca1i5.js";
17
18
  import { _ as maxReviewerModel, c as formatMaxPrerequisiteFailure, f as maxCodexReviewerModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, m as maxGrokModel, o as MAX_PROFILE_NATIVE_EFFORTS, p as maxGeminiModel, v as maxSonnetModel } from "./max-profile-contract-DbHwiLTx.js";
18
- import { $t as nativeSubagentModel, At as brainstormModel, Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Ft as cheapOracleModel, Gt as fastPlanModel, Hn as semanticSearchOptedIn, Ht as fastAstraModel, It as cheapReviewerModel, Jt as fleetToolsEnabled, Kt as fastReviewerModel, Lt as cheapestAdvisorModel, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Ot as balancedOracleModel, Pt as cheapAdvisorModel, Qt as kustoToolsEnabled, Rt as cheapestOracleModel, Sn as unregisterLaunch, T as availableToolCommands, Tt as adoToolsEnabled, Un as shouldUseInsecureTls, Ut as fastGeneralPurposeModel, Vn as provisionAndIndexColbert, Vt as fastAdvisorModel, Wt as fastOracleModel, Xn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, _r as CHEAP_PROFILE_NATIVE_MODELS, an as standInToolEnabled, ar as resolveLeadSlugArg, bn as registerLaunch, en as resolveGeminiReviewModel, fn as configureLocalEgress, in as scribeModel, ir as pickClaudeDefault, jt as browseAgentEnabled, kt as balancedReviewerModel, mr as CHEAP_PROFILE_MODELS, nn as reviewerModel, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, pn as localBaseUrl, pr as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, qt as fastScoutModel, r as agentNamesForToolAllowlist, rn as scoutModel, rr as isBudgetClaudeLead, s as buildPeerAwarenessSummary, sn as workiqToolsEnabled, tn as reviewerFastModel, yn as launchBoundAccessToken, zt as cheapestReviewerModel } from "./peer-mcp-personas-OWsSm6To.js";
19
+ import { $t as nativeSubagentModel, At as brainstormModel, Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, E as buildToolbeltAwareness, Et as agentToolsEnabled, Ft as cheapOracleModel, Gt as fastPlanModel, Hn as semanticSearchOptedIn, Ht as fastAstraModel, It as cheapReviewerModel, Jt as fleetToolsEnabled, Kt as fastReviewerModel, Lt as cheapestAdvisorModel, Mn as provisionBrowserAssets, Mt as browserCompoundToolsEnabled, Nt as browserToolsEnabled, Ot as balancedOracleModel, Pt as cheapAdvisorModel, Qt as kustoToolsEnabled, Rt as cheapestOracleModel, Sn as unregisterLaunch, T as availableToolCommands, Tt as adoToolsEnabled, Un as shouldUseInsecureTls, Ut as fastGeneralPurposeModel, Vn as provisionAndIndexColbert, Vt as fastAdvisorModel, Wt as fastOracleModel, Xn as DEFAULT_CLAUDE_MODEL_FALLBACKS, Xt as generalPurposeFastModel, Yt as geminiAvailable, Zt as implementerFastModel, _r as CHEAP_PROFILE_NATIVE_MODELS, an as standInToolEnabled, ar as resolveLeadSlugArg, bn as registerLaunch, en as resolveGeminiReviewModel, fn as configureLocalEgress, in as scribeModel, ir as pickClaudeDefault, jt as browseAgentEnabled, kt as balancedReviewerModel, mr as CHEAP_PROFILE_MODELS, nn as reviewerModel, o as buildPeerAwarenessSnippet, on as workerToolsEnabled, pn as localBaseUrl, pr as CHEAP_PROFILE_ADVISOR_CLIENT_MODEL, qt as fastScoutModel, r as agentNamesForToolAllowlist, rn as scoutModel, rr as isBudgetClaudeLead, s as buildPeerAwarenessSummary, sn as workiqToolsEnabled, tn as reviewerFastModel, yn as launchBoundAccessToken, zt as cheapestReviewerModel } from "./peer-mcp-personas-Dny0r5Am.js";
19
20
  import { a as parseBoolEnv } from "./exec-BC0MAnoA.js";
20
- import { a as injectAicStatusLineIntoSettingsFile, i as buildAicStatusHookCommand, r as AIC_USER_STATUSLINE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-BKveu679.js";
21
- import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-CeSXqTEE.js";
22
- import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-UXC6NQbN.js";
23
- import { a as buildOperatingDefaultsDirective, c as prependOperatingDefaultsToMirroredClaudeMd, i as buildOperatingDefaultsDigest, l as prependStyleDirectiveToMirroredClaudeMd, n as appendPeerAwarenessToMirroredClaudeMd, r as appendToolbeltAwarenessToMirroredClaudeMd, s as prependArtifactPanelDirectiveToMirroredClaudeMd } from "./claude-md-injection-Biq_Xhve.js";
24
- import { P as warmTreeSitterPool } from "./service-backend-Cdgz6WPx.js";
21
+ import { a as injectAicStatusLineIntoSettingsFile, i as buildAicStatusHookCommand, r as AIC_USER_STATUSLINE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-wLL1l_Z6.js";
22
+ import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-6GKI28nY.js";
23
+ import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-DM98PuAF.js";
24
+ import { a as buildOperatingDefaultsDirective, c as prependOperatingDefaultsToMirroredClaudeMd, i as buildOperatingDefaultsDigest, l as prependStyleDirectiveToMirroredClaudeMd, n as appendPeerAwarenessToMirroredClaudeMd, r as appendToolbeltAwarenessToMirroredClaudeMd, s as prependArtifactPanelDirectiveToMirroredClaudeMd } from "./claude-md-injection-DNMDcw1W.js";
25
+ import { P as warmTreeSitterPool } from "./service-backend-BdhWVRSz.js";
25
26
  import { t as state } from "./state-CCGDJ43X.js";
26
- import { f as resolveModel } from "./token-CPzYxU4Y.js";
27
+ import { f as resolveModel } from "./token-CKPOBdO0.js";
27
28
  import { t as FAST_PROFILE_ADVISOR_CLIENT_MODEL } from "./fast-profile-contract-BLnKg0Ay.js";
28
29
  import { defineCommand } from "citty";
29
30
  import consola from "consola";
@@ -576,9 +577,9 @@ const claude = defineCommand({
576
577
  await stopKeepAwake();
577
578
  const { disposeBluebirdClients } = await import("./bluebird-client-BvoMTmEv.js");
578
579
  await disposeBluebirdClients();
579
- const { disposeAdoClients } = await import("./ado-tools-CRkyU51J.js");
580
+ const { disposeAdoClients } = await import("./ado-tools-CsfbnY8x.js");
580
581
  await disposeAdoClients();
581
- const { disposeWorkiqClients } = await import("./workiq-tools-DL6rC4bP.js");
582
+ const { disposeWorkiqClients } = await import("./workiq-tools-DdiQ2DOW.js");
582
583
  await disposeWorkiqClients();
583
584
  await removeOwnClaudeConfigMirror();
584
585
  await removeAicLedgerFile();
@@ -1189,4 +1190,4 @@ const claude = defineCommand({
1189
1190
  });
1190
1191
  export { claude };
1191
1192
 
1192
- //# sourceMappingURL=claude-CSuIdaLV.js.map
1193
+ //# sourceMappingURL=claude-BWwkOMi3.js.map