github-router 0.3.379 → 0.3.381
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -0
- package/dist/ado-tools-CsfbnY8x.js +1 -0
- package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
- package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
- package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
- package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
- package/dist/atomic-file-Dif1kLKM.js +198 -0
- package/dist/atomic-file-Dif1kLKM.js.map +1 -0
- package/dist/{attribution-settings-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
- package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.js.map} +1 -1
- package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
- package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
- package/dist/bin.js +1479 -0
- package/dist/bin.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
- package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
- package/dist/{claude-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
- package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.js.map} +1 -1
- package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
- package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
- package/dist/{codex-BG0pfud9.js → codex-50GzveCD.js} +8 -7
- package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.js.map} +1 -1
- package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
- package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
- package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
- package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
- package/dist/diagnostics-cXjCT_JQ.js +12 -0
- package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
- package/dist/engine-B6la_uIW.js +1 -0
- package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
- package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
- package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
- package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
- package/dist/hooks.mjs +13 -0
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
- package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
- package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
- package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
- package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
- package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
- package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
- package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
- package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
- package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
- package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
- package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
- package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
- package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
- package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
- package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
- package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
- package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
- package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
- package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
- package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
- package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
- package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
- package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
- package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +268 -21
- package/dist/lifecycle-BOjgq9_l.js +1 -0
- package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
- package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
- package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
- package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
- package/dist/lifecycle-NQvr4flt.js +1 -0
- package/dist/main.js +39 -24
- package/dist/main.js.map +1 -1
- package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
- package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
- package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
- package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
- package/dist/npm-env-H60tX76c.js +130 -0
- package/dist/npm-env-H60tX76c.js.map +1 -0
- package/dist/optional-DGAeyguL.js +586 -0
- package/dist/optional-DGAeyguL.js.map +1 -0
- package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
- package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
- package/dist/origin-BXtpcKP9.js +382 -0
- package/dist/origin-BXtpcKP9.js.map +1 -0
- package/dist/origin-DbFUCiGp.js +1 -0
- package/dist/paths-CquOjytP.js +1 -0
- package/dist/paths-DK_b2ihK.js +176 -0
- package/dist/paths-DK_b2ihK.js.map +1 -0
- package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
- package/dist/paths-DeFmYJhO.js.map +1 -0
- package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
- package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
- package/dist/{pi-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
- package/dist/pi-DVud9eQn.js.map +1 -0
- package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
- package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
- package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
- package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
- package/dist/pi-version-check-BeBB0Ny9.js +551 -0
- package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
- package/dist/pi-version-check-D5RvdLsG.js +1 -0
- package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
- package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
- package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
- package/dist/provision-BWtuDq_v.js.map +1 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
- package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
- package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
- package/dist/{serve-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
- package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
- package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
- package/dist/server-setup-byIhjgOb.js.map +1 -0
- package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
- package/dist/service-backend-BdhWVRSz.js.map +1 -0
- package/dist/{start-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
- package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.js.map} +1 -1
- package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
- package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
- package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
- package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
- package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
- package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
- package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
- package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
- package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
- package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
- package/dist/update-CB21YRKz.js +1 -0
- package/dist/update-T1L7yFon.js +1548 -0
- package/dist/update-T1L7yFon.js.map +1 -0
- package/dist/update-fEgWTrIx.js +214 -0
- package/dist/update-fEgWTrIx.js.map +1 -0
- package/dist/update-lock-BeS_WmC8.js +1 -0
- package/dist/update-lock-BmXx6QaR.js +171 -0
- package/dist/update-lock-BmXx6QaR.js.map +1 -0
- package/dist/volatile-root-DQNNvQ7Z.js +50 -0
- package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
- package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
- package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
- package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
- package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
- package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
- package/package.json +16 -4
- package/dist/ado-tools-CRkyU51J.js +0 -1
- package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
- package/dist/engine-V46un8Xl.js +0 -1
- package/dist/lifecycle-BENRuuX6.js +0 -1
- package/dist/lifecycle-Dli9vGI2.js +0 -1
- package/dist/paths-Be9_ujQ3.js +0 -1
- package/dist/paths-CVEO8jEH.js.map +0 -1
- package/dist/pi-DmeBxzIo.js.map +0 -1
- package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
- package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
- package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
- package/dist/provision-DPL8aGe2.js.map +0 -1
- package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
- package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
- package/dist/server-setup-ClZdV33Q.js.map +0 -1
- package/dist/service-backend-Cdgz6WPx.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-vjHAFCaY.js","names":[],"sources":["../src/lib/colbert/lifecycle.ts"],"sourcesContent":["/**\n * ColBERT sidecar lifecycle: in-memory PID ledger for the short-lived\n * `colgrep` children this proxy spawns, signal-handler tree-kill on\n * exit, and a boot-time metadata reclassification sweep.\n *\n * Because colgrep is CLI-per-invocation (no daemon), the lifecycle\n * problem is **process tracking + cancellation + boot/exit sweep**, NOT\n * keep-alive. Modeled on `worker-agent/lifecycle.ts` (PID ledger + boot\n * sweep + per-proxy-run instance UUID) and `exec.ts`'s tree-kill.\n *\n * Three cooperating layers (none sufficient alone):\n * 1. Per-call cleanup — the runner's `finally` force-kills the child\n * it spawned (handled in runner.ts).\n * 2. Session-end signal sweep (this file) — SIGINT/SIGTERM/exit kill\n * every still-tracked child of THIS run.\n * 3. Boot-time sweep (`sweepStaleColbertMetaAtBoot`) — reclassifies\n * `.gh-router-meta/*.json` entries whose `buildPid` is dead from\n * `building` → `failed`. It NEVER issues a kill to a PID from a\n * prior boot (a reused PID may belong to an unrelated process);\n * only the in-memory ledger (this run's spawns) is ever killed.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { killManagedTree } from \"../exec\"\nimport { PATHS } from \"../paths\"\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID (mirrors worker-agent/lifecycle.ts)\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Written into the\n * sidecar metadata `ownerInstanceId` so the boot sweep can tell \"this\n * proxy's still-live build\" from \"a stranded `building` entry from a\n * prior proxy whose PID got recycled\" (Docker PID-1 across restarts).\n */\nexport function getColbertInstanceUuid(): string {\n if (_instanceUuid === null) _instanceUuid = randomUUID()\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetColbertInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// In-memory PID ledger of THIS run's live colgrep children\n// ---------------------------------------------------------------------\n\ntype TrackedChild = ReturnType<typeof spawn>\n\nconst _liveChildren = new Set<TrackedChild>()\n\n/**\n * Register a freshly-spawned colgrep child so the exit sweep can reap\n * it. The runner also removes it on natural close via `untrackChild`.\n */\nexport function trackChild(child: TrackedChild): void {\n _liveChildren.add(child)\n child.once(\"close\", () => _liveChildren.delete(child))\n child.once(\"error\", () => _liveChildren.delete(child))\n}\n\n/** Remove a child from the ledger (e.g. after a clean per-call kill). */\nexport function untrackChild(child: TrackedChild): void {\n _liveChildren.delete(child)\n}\n\n/** Count of live tracked children (test/diagnostic). */\nexport function liveChildCount(): number {\n return _liveChildren.size\n}\n\n/**\n * Synchronous best-effort tree-kill of every tracked child. Called from\n * the signal/exit handlers. After killing, the set is cleared so a\n * second call is a no-op.\n */\nexport function sweepLiveChildren(): void {\n const isWin = process.platform === \"win32\"\n for (const child of _liveChildren) {\n try {\n killManagedTree(child, isWin)\n } catch {\n // already gone\n }\n }\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers (mirror worker-agent/lifecycle.ts re-raise pattern)\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Wire SIGINT/SIGTERM/exit handlers that tree-kill every tracked\n * colgrep child. Idempotent — subsequent calls are a no-op (we never\n * leak listeners). The signal handlers re-raise after sweeping so Node's\n * default terminate-on-signal behavior is restored (otherwise attaching\n * a listener cancels the default and Ctrl-C would clean but not exit).\n */\nexport function registerColbertExitHandlers(): void {\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepLiveChildren()\n _sigintHandler = () => {\n sweepLiveChildren()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepLiveChildren()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n process.on(\"exit\", _exitHandler)\n}\n\n/** Test-only: unregister handlers + reset module state. */\nexport function __unregisterColbertExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Boot-time metadata reclassification sweep\n// ---------------------------------------------------------------------\n\n/**\n * True iff `pid` names a live process. `process.kill(pid, 0)` probes\n * existence without signalling; `EPERM` means the process exists but is\n * owned by another user (still alive). Exported so the per-query freshness\n * verdict can mirror the boot sweep's liveness check.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. Walks `.gh-router-meta/*.json`; any entry stuck in\n * `status:\"building\"` whose `buildPid` is DEAD is a crashed-build\n * escapee → reset to `status:\"failed\"` so the next search re-kicks a\n * build instead of routing to a never-finishing one.\n *\n * It NEVER kills anything: a live PID matching a stale `buildPid` from a\n * prior boot may be a recycled PID belonging to an unrelated process, so\n * the boot sweep only RECLASSIFIES metadata. The in-memory ledger (this\n * run's spawns) is the only thing the SIGINT/SIGTERM handler ever kills.\n *\n * Best-effort; never throws (wrapped by the caller in `ensurePaths`).\n */\nexport async function sweepStaleColbertMetaAtBoot(): Promise<void> {\n const metaDir = PATHS.COLBERT_META_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(metaDir)\n } catch {\n return // no meta dir yet — nothing to sweep\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue\n const file = path.join(metaDir, name)\n let meta: Record<string, unknown>\n try {\n meta = JSON.parse(await fs.readFile(file, \"utf8\")) as Record<string, unknown>\n } catch {\n continue // corrupt — leave it; index-store re-derives on next access\n }\n if (meta.status !== \"building\") continue\n const buildPid = typeof meta.buildPid === \"number\" ? meta.buildPid : 0\n if (buildPid > 0 && isPidAlive(buildPid)) {\n // A live PID — could be ours (this run re-kicked) or a recycled\n // unrelated PID. Either way: never kill from the boot sweep. Leave\n // the entry; the runner's own ownership check governs.\n continue\n }\n // Dead build PID → reclassify to failed (atomic temp+rename). Stamp the\n // crash class so the per-query self-heal treats it as transient (re-kick)\n // rather than operator-actionable.\n meta.status = \"failed\"\n meta.failureClass = \"crashed\"\n const tmp = `${file}.${process.pid}.tmp`\n try {\n await fs.writeFile(tmp, JSON.stringify(meta, null, 2))\n await fs.rename(tmp, file)\n } catch {\n await fs.rm(tmp, { force: true }).catch(() => {})\n }\n }\n await sweepColbertStore()\n}\n\n/** An orphan stub younger than this may be a build that just started. */\nconst ORPHAN_GRACE_MS = 60 * 60 * 1000\n\n/**\n * Reclaim disk in the colgrep store, ordered so it cannot destroy good data.\n *\n * This runs AFTER the identity fix in this same release, which matters: the\n * scanner that decides \"unreachable\" is the one that was wrong. Under the old\n * comparison a perfectly healthy index looked unreachable, and a sweep written\n * against that scanner would have deleted it. Everything below therefore\n * leans on evidence that does not depend on our path matching at all.\n *\n * Three rules, in increasing order of caution:\n *\n * 1. ORPHAN STUB — no `project.json` AND an empty-or-absent `index/` AND\n * older than the grace window. All three required. A dir with a\n * `project.json` is real data and is never touched by this rule; a dir\n * with shards is never touched even without one. Deleted outright,\n * because there is provably nothing in it.\n *\n * 2. DEAD META — a sidecar whose `workspace` no longer exists on disk. Pure\n * bookkeeping, never index data. (48 such entries had accumulated on the\n * machine where this was diagnosed; nothing ever reaped them.)\n *\n * 3. QUARANTINE, NEVER DIRECT DELETE, for anything holding real bytes. A\n * dir with a `project.json` is left alone entirely, however unreachable\n * it looks. Reclaiming those would mean deleting real index data on our\n * own inference about what colgrep would use — and this incident is the\n * proof that such inference can be wrong. If it is ever added it must\n * rename first and delete only after a retention window, so the whole\n * period stays reversible.\n *\n * Skips any dir with a live lock owner or an in-flight init, and logs a\n * one-line count so the accumulation is observable rather than silent.\n */\nexport async function sweepColbertStore(): Promise<void> {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(indicesDir)\n } catch {\n return\n }\n\n const now = Date.now()\n let orphans = 0\n let deadMeta = 0\n\n for (const name of names) {\n if (name === \".gh-router-meta\") continue\n // Quarantined husks are owned by the corrupt-repair path, which deletes\n // them out of band. Never race it.\n if (name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n try {\n const st = await fs.stat(dir)\n if (!st.isDirectory()) continue\n // A live build claims its dir with a `.lock`; another proxy may own it.\n if (await exists(path.join(dir, \".lock\"))) continue\n // Real index data — leave it. Reclaiming this needs quarantine-first\n // semantics, not a boot-time `rm`.\n if (await exists(path.join(dir, \"project.json\"))) continue\n // Anything with shards is real work in progress, even mid-build.\n let indexEntries: Array<string> = []\n try {\n indexEntries = await fs.readdir(path.join(dir, \"index\"))\n } catch {\n /* absent index/ is the orphan shape */\n }\n if (indexEntries.length > 0) continue\n if (now - st.mtimeMs < ORPHAN_GRACE_MS) continue\n await fs.rm(dir, { recursive: true, force: true })\n orphans++\n } catch {\n // Vanished mid-sweep or unreadable — skip.\n }\n }\n\n // Dead sidecars: the workspace they describe is gone.\n try {\n const metaDir = PATHS.COLBERT_META_DIR\n for (const f of await fs.readdir(metaDir)) {\n if (!f.endsWith(\".json\")) continue\n const file = path.join(metaDir, f)\n try {\n const meta = JSON.parse(await fs.readFile(file, \"utf8\")) as {\n workspace?: string\n status?: string\n }\n const ws = meta.workspace\n if (typeof ws !== \"string\" || ws.length === 0) continue\n // Never reap a live build's bookkeeping.\n if (meta.status === \"building\") continue\n // Nor an entry this very sweep just reclassified. The reclassification\n // pass above rewrites `building` + dead-PID to `failed` so the runner\n // can self-heal; deleting it in the same pass would erase that state\n // before anything could act on it. Only reap entries that have been\n // settled for a while.\n const stMeta = await fs.stat(file).catch(() => null)\n if (stMeta && now - stMeta.mtimeMs < ORPHAN_GRACE_MS) continue\n if (await exists(ws)) continue\n await fs.rm(file, { force: true })\n deadMeta++\n } catch {\n // Corrupt/unreadable — leave it; index-store re-derives on next access.\n }\n }\n } catch {\n // No meta dir yet.\n }\n\n if (orphans > 0 || deadMeta > 0) {\n consola.debug(\n `colbert: store sweep reclaimed ${orphans} orphan index dir(s), ${deadMeta} dead metadata entr(ies)`,\n )\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.stat(p)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;AAqCA,IAAI,gBAA+B;;;;;;;AAQnC,SAAgB,yBAAiC;CAC/C,IAAI,kBAAkB,MAAM,gBAAgB,WAAW;CACvD,OAAO;AACT;AAaA,MAAM,gCAAgB,IAAI,IAAkB;;;;;AAM5C,SAAgB,WAAW,OAA2B;CACpD,cAAc,IAAI,KAAK;CACvB,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;CACrD,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;AACvD;;AAGA,SAAgB,aAAa,OAA2B;CACtD,cAAc,OAAO,KAAK;AAC5B;;;;;;AAYA,SAAgB,oBAA0B;CACxC,MAAM,QAAQ,QAAQ,aAAa;CACnC,KAAK,MAAM,SAAS,eAClB,IAAI;EACF,gBAAgB,OAAO,KAAK;CAC9B,QAAQ,CAER;CAEF,cAAc,MAAM;AACtB;AAMA,IAAI,cAAc;AAClB,IAAI,eAAoC;AACxC,IAAI,iBAAsC;AAC1C,IAAI,kBAAuC;;;;;;;;AAS3C,SAAgB,8BAAoC;CAClD,IAAI,aAAa;CACjB,cAAc;CACd,qBAAqB,kBAAkB;CACvC,uBAAuB;EACrB,kBAAkB;EAClB,IAAI,gBAAgB,QAAQ,IAAI,UAAU,cAAc;EACxD,QAAQ,KAAK,QAAQ,KAAK,QAAQ;CACpC;CACA,wBAAwB;EACtB,kBAAkB;EAClB,IAAI,iBAAiB,QAAQ,IAAI,WAAW,eAAe;EAC3D,QAAQ,KAAK,QAAQ,KAAK,SAAS;CACrC;CACA,QAAQ,GAAG,UAAU,cAAc;CACnC,QAAQ,GAAG,WAAW,eAAe;CACrC,QAAQ,GAAG,QAAQ,YAAY;AACjC;;;;;;;AA8BA,SAAgB,WAAW,KAAs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AC;IACjC;GACF,QAAQ,CAER;EACF;CACF,QAAQ,CAER;CAEA,IAAI,UAAU,KAAK,WAAW,GAC5B,QAAQ,MACN,kCAAkC,QAAQ,wBAAwB,SAAS,yBAC7E;AAEJ;AAEA,eAAe,OAAO,GAA6B;CACjD,IAAI;EACF,MAAM,GAAG,KAAK,CAAC;EACf,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"lifecycle-BlC_kzNt.js","names":[],"sources":["../src/lib/colbert/lifecycle.ts"],"sourcesContent":["/**\n * ColBERT sidecar lifecycle: in-memory PID ledger for the short-lived\n * `colgrep` children this proxy spawns, signal-handler tree-kill on\n * exit, and a boot-time metadata reclassification sweep.\n *\n * Because colgrep is CLI-per-invocation (no daemon), the lifecycle\n * problem is **process tracking + cancellation + boot/exit sweep**, NOT\n * keep-alive. Modeled on `worker-agent/lifecycle.ts` (PID ledger + boot\n * sweep + per-proxy-run instance UUID) and `exec.ts`'s tree-kill.\n *\n * Three cooperating layers (none sufficient alone):\n * 1. Per-call cleanup — the runner's `finally` force-kills the child\n * it spawned (handled in runner.ts).\n * 2. Session-end signal sweep (this file) — SIGINT/SIGTERM/exit kill\n * every still-tracked child of THIS run.\n * 3. Boot-time sweep (`sweepStaleColbertMetaAtBoot`) — reclassifies\n * `.gh-router-meta/*.json` entries whose `buildPid` is dead from\n * `building` → `failed`. It NEVER issues a kill to a PID from a\n * prior boot (a reused PID may belong to an unrelated process);\n * only the in-memory ledger (this run's spawns) is ever killed.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { killManagedTree } from \"../exec\"\nimport { PATHS } from \"../paths\"\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID (mirrors worker-agent/lifecycle.ts)\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Written into the\n * sidecar metadata `ownerInstanceId` so the boot sweep can tell \"this\n * proxy's still-live build\" from \"a stranded `building` entry from a\n * prior proxy whose PID got recycled\" (Docker PID-1 across restarts).\n */\nexport function getColbertInstanceUuid(): string {\n if (_instanceUuid === null) _instanceUuid = randomUUID()\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetColbertInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// In-memory PID ledger of THIS run's live colgrep children\n// ---------------------------------------------------------------------\n\ntype TrackedChild = ReturnType<typeof spawn>\n\nconst _liveChildren = new Set<TrackedChild>()\n\n/**\n * Register a freshly-spawned colgrep child so the exit sweep can reap\n * it. The runner also removes it on natural close via `untrackChild`.\n */\nexport function trackChild(child: TrackedChild): void {\n _liveChildren.add(child)\n child.once(\"close\", () => _liveChildren.delete(child))\n child.once(\"error\", () => _liveChildren.delete(child))\n}\n\n/** Remove a child from the ledger (e.g. after a clean per-call kill). */\nexport function untrackChild(child: TrackedChild): void {\n _liveChildren.delete(child)\n}\n\n/** Count of live tracked children (test/diagnostic). */\nexport function liveChildCount(): number {\n return _liveChildren.size\n}\n\n/**\n * Synchronous best-effort tree-kill of every tracked child. Called from\n * the signal/exit handlers. After killing, the set is cleared so a\n * second call is a no-op.\n */\nexport function sweepLiveChildren(): void {\n const isWin = process.platform === \"win32\"\n for (const child of _liveChildren) {\n try {\n killManagedTree(child, isWin)\n } catch {\n // already gone\n }\n }\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers (mirror worker-agent/lifecycle.ts re-raise pattern)\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Wire SIGINT/SIGTERM/exit handlers that tree-kill every tracked\n * colgrep child. Idempotent — subsequent calls are a no-op (we never\n * leak listeners). The signal handlers re-raise after sweeping so Node's\n * default terminate-on-signal behavior is restored (otherwise attaching\n * a listener cancels the default and Ctrl-C would clean but not exit).\n */\nexport function registerColbertExitHandlers(): void {\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepLiveChildren()\n _sigintHandler = () => {\n sweepLiveChildren()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepLiveChildren()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n process.on(\"exit\", _exitHandler)\n}\n\n/** Test-only: unregister handlers + reset module state. */\nexport function __unregisterColbertExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Boot-time metadata reclassification sweep\n// ---------------------------------------------------------------------\n\n/**\n * True iff `pid` names a live process. `process.kill(pid, 0)` probes\n * existence without signalling; `EPERM` means the process exists but is\n * owned by another user (still alive). Exported so the per-query freshness\n * verdict can mirror the boot sweep's liveness check.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. Walks `.gh-router-meta/*.json`; any entry stuck in\n * `status:\"building\"` whose `buildPid` is DEAD is a crashed-build\n * escapee → reset to `status:\"failed\"` so the next search re-kicks a\n * build instead of routing to a never-finishing one.\n *\n * It NEVER kills anything: a live PID matching a stale `buildPid` from a\n * prior boot may be a recycled PID belonging to an unrelated process, so\n * the boot sweep only RECLASSIFIES metadata. The in-memory ledger (this\n * run's spawns) is the only thing the SIGINT/SIGTERM handler ever kills.\n *\n * Best-effort; never throws (wrapped by the caller in `ensurePaths`).\n */\nexport async function sweepStaleColbertMetaAtBoot(): Promise<void> {\n const metaDir = PATHS.COLBERT_META_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(metaDir)\n } catch {\n return // no meta dir yet — nothing to sweep\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue\n const file = path.join(metaDir, name)\n let meta: Record<string, unknown>\n try {\n meta = JSON.parse(await fs.readFile(file, \"utf8\")) as Record<string, unknown>\n } catch {\n continue // corrupt — leave it; index-store re-derives on next access\n }\n if (meta.status !== \"building\") continue\n const buildPid = typeof meta.buildPid === \"number\" ? meta.buildPid : 0\n if (buildPid > 0 && isPidAlive(buildPid)) {\n // A live PID — could be ours (this run re-kicked) or a recycled\n // unrelated PID. Either way: never kill from the boot sweep. Leave\n // the entry; the runner's own ownership check governs.\n continue\n }\n // Dead build PID → reclassify to failed (atomic temp+rename). Stamp the\n // crash class so the per-query self-heal treats it as transient (re-kick)\n // rather than operator-actionable.\n meta.status = \"failed\"\n meta.failureClass = \"crashed\"\n const tmp = `${file}.${process.pid}.tmp`\n try {\n await fs.writeFile(tmp, JSON.stringify(meta, null, 2))\n await fs.rename(tmp, file)\n } catch {\n await fs.rm(tmp, { force: true }).catch(() => {})\n }\n }\n await sweepColbertStore()\n}\n\n/** An orphan stub younger than this may be a build that just started. */\nconst ORPHAN_GRACE_MS = 60 * 60 * 1000\n\n/**\n * Reclaim disk in the colgrep store, ordered so it cannot destroy good data.\n *\n * This runs AFTER the identity fix in this same release, which matters: the\n * scanner that decides \"unreachable\" is the one that was wrong. Under the old\n * comparison a perfectly healthy index looked unreachable, and a sweep written\n * against that scanner would have deleted it. Everything below therefore\n * leans on evidence that does not depend on our path matching at all.\n *\n * Three rules, in increasing order of caution:\n *\n * 1. ORPHAN STUB — no `project.json` AND an empty-or-absent `index/` AND\n * older than the grace window. All three required. A dir with a\n * `project.json` is real data and is never touched by this rule; a dir\n * with shards is never touched even without one. Deleted outright,\n * because there is provably nothing in it.\n *\n * 2. DEAD META — a sidecar whose `workspace` no longer exists on disk. Pure\n * bookkeeping, never index data. (48 such entries had accumulated on the\n * machine where this was diagnosed; nothing ever reaped them.)\n *\n * 3. QUARANTINE, NEVER DIRECT DELETE, for anything holding real bytes. A\n * dir with a `project.json` is left alone entirely, however unreachable\n * it looks. Reclaiming those would mean deleting real index data on our\n * own inference about what colgrep would use — and this incident is the\n * proof that such inference can be wrong. If it is ever added it must\n * rename first and delete only after a retention window, so the whole\n * period stays reversible.\n *\n * Skips any dir with a live lock owner or an in-flight init, and logs a\n * one-line count so the accumulation is observable rather than silent.\n */\nexport async function sweepColbertStore(): Promise<void> {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(indicesDir)\n } catch {\n return\n }\n\n const now = Date.now()\n let orphans = 0\n let deadMeta = 0\n\n for (const name of names) {\n if (name === \".gh-router-meta\") continue\n // Quarantined husks are owned by the corrupt-repair path, which deletes\n // them out of band. Never race it.\n if (name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n try {\n const st = await fs.stat(dir)\n if (!st.isDirectory()) continue\n // A live build claims its dir with a `.lock`; another proxy may own it.\n if (await exists(path.join(dir, \".lock\"))) continue\n // Real index data — leave it. Reclaiming this needs quarantine-first\n // semantics, not a boot-time `rm`.\n if (await exists(path.join(dir, \"project.json\"))) continue\n // Anything with shards is real work in progress, even mid-build.\n let indexEntries: Array<string> = []\n try {\n indexEntries = await fs.readdir(path.join(dir, \"index\"))\n } catch {\n /* absent index/ is the orphan shape */\n }\n if (indexEntries.length > 0) continue\n if (now - st.mtimeMs < ORPHAN_GRACE_MS) continue\n await fs.rm(dir, { recursive: true, force: true })\n orphans++\n } catch {\n // Vanished mid-sweep or unreadable — skip.\n }\n }\n\n // Dead sidecars: the workspace they describe is gone.\n try {\n const metaDir = PATHS.COLBERT_META_DIR\n for (const f of await fs.readdir(metaDir)) {\n if (!f.endsWith(\".json\")) continue\n const file = path.join(metaDir, f)\n try {\n const meta = JSON.parse(await fs.readFile(file, \"utf8\")) as {\n workspace?: string\n status?: string\n }\n const ws = meta.workspace\n if (typeof ws !== \"string\" || ws.length === 0) continue\n // Never reap a live build's bookkeeping.\n if (meta.status === \"building\") continue\n // Nor an entry this very sweep just reclassified. The reclassification\n // pass above rewrites `building` + dead-PID to `failed` so the runner\n // can self-heal; deleting it in the same pass would erase that state\n // before anything could act on it. Only reap entries that have been\n // settled for a while.\n const stMeta = await fs.stat(file).catch(() => null)\n if (stMeta && now - stMeta.mtimeMs < ORPHAN_GRACE_MS) continue\n if (await exists(ws)) continue\n await fs.rm(file, { force: true })\n deadMeta++\n } catch {\n // Corrupt/unreadable — leave it; index-store re-derives on next access.\n }\n }\n } catch {\n // No meta dir yet.\n }\n\n if (orphans > 0 || deadMeta > 0) {\n consola.debug(\n `colbert: store sweep reclaimed ${orphans} orphan index dir(s), ${deadMeta} dead metadata entr(ies)`,\n )\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.stat(p)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;AAqCA,IAAI,gBAA+B;;;;;;;AAQnC,SAAgB,yBAAiC;CAC/C,IAAI,kBAAkB,MAAM,gBAAgB,WAAW;CACvD,OAAO;AACT;AAaA,MAAM,gCAAgB,IAAI,IAAkB;;;;;AAM5C,SAAgB,WAAW,OAA2B;CACpD,cAAc,IAAI,KAAK;CACvB,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;CACrD,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;AACvD;;AAGA,SAAgB,aAAa,OAA2B;CACtD,cAAc,OAAO,KAAK;AAC5B;;;;;;AAYA,SAAgB,oBAA0B;CACxC,MAAM,QAAQ,QAAQ,aAAa;CACn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AG,GAAG,KAAK;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACjD;EACF,QAAQ,CAER;CACF;CAGA,IAAI;EACF,MAAM,UAAU,MAAM;EACtB,KAAK,MAAM,KAAK,MAAM,GAAG,QAAQ,OAAO,GAAG;GACzC,IAAI,CAAC,EAAE,SAAS,OAAO,GAAG;GAC1B,MAAM,OAAO,KAAK,KAAK,SAAS,CAAC;GACjC,IAAI;IACF,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,SAAS,MAAM,MAAM,CAAC;IAIvD,MAAM,KAAK,KAAK;IAChB,IAAI,OAAO,OAAO,YAAY,GAAG,WAAW,GAAG;IAE/C,IAAI,KAAK,WAAW,YAAY;IAMhC,MAAM,SAAS,MAAM,GAAG,KAAK,IAAI,CAAC,CAAC,YAAY,IAAI;IACnD,IAAI,UAAU,MAAM,OAAO,UAAU,iBAAiB;IACtD,IAAI,MAAM,OAAO,EAAE,GAAG;IACtB,MAAM,GAAG,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;IACjC;GACF,QAAQ,CAER;EACF;CACF,QAAQ,CAER;CAEA,IAAI,UAAU,KAAK,WAAW,GAC5B,QAAQ,MACN,kCAAkC,QAAQ,wBAAwB,SAAS,yBAC7E;AAEJ;AAEA,eAAe,OAAO,GAA6B;CACjD,IAAI;EACF,MAAM,GAAG,KAAK,CAAC;EACf,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-
|
|
1
|
+
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-DeFmYJhO.js";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
4
|
import fs from "node:fs/promises";
|
|
@@ -326,4 +326,4 @@ async function sweepStaleWorktreesAtBoot() {
|
|
|
326
326
|
}
|
|
327
327
|
export { sweepRegistry as a, registerExitHandlers as i, getInstanceUuid as n, sweepStaleWorktreesAtBoot as o, recordWorkerRepo as r, WorktreeRegistry as t };
|
|
328
328
|
|
|
329
|
-
//# sourceMappingURL=lifecycle-
|
|
329
|
+
//# sourceMappingURL=lifecycle-COZhARmE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-Dh9y8OF1.js","names":[],"sources":["../src/lib/worker-agent/lifecycle.ts"],"sourcesContent":["/**\n * Lifecycle plumbing for worker worktrees: in-memory registry, signal\n * handlers, ledger of repos touched, and the boot-time PID+instance\n * safety net.\n *\n * Plan: see `plans/we-have-added-a-dreamy-tide.md` (\"Worktree mode\" →\n * \"Cleanup paths\"). Three layers cooperate, none of them sufficient\n * alone:\n *\n * 1. Per-call cleanup (`engine.ts` finally block invoking\n * `WorktreeHandle.remove()`) — covers the happy path.\n *\n * 2. Session-end signal sweep (this file, registered via\n * `registerExitHandlers`) — covers Ctrl+C, service-manager stop,\n * and (in `github-router claude` mode) the spawned child's exit.\n * Synchronous `execFileSync` is intentional: exit handlers can't\n * reliably await async work.\n *\n * 3. Boot-time PID+instance sweep (`sweepStaleWorktreesAtBoot`) —\n * covers SIGKILL, OOM, container restart. Walks the ledger of\n * repos this proxy has touched and removes worktree dirs whose\n * `<pid>` is dead OR whose `<instance>` UUID doesn't match the\n * current proxy's UUID.\n *\n * Ledger writes are ATOMIC (temp + rename) per peer review — a\n * concurrent-RMW corruption would silently strand worktrees because\n * the boot sweep can't find their repo roots.\n */\n\nimport { execFileSync } from \"node:child_process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { PATHS, writeRuntimeFileSecure } from \"../paths\"\n\n/**\n * Same regex worktree.ts uses for its per-call age sweep — kept in\n * sync intentionally. `<pid>-<uuid>-<8hex>` strictly.\n */\nconst WORKTREE_DIR_NAME_RE =\n /^(\\d+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-([0-9a-f]{8})$/\n\n/**\n * Cap on the ledger: how many repos we remember across boots, and how\n * old an entry may be before it's pruned. Both are belt-and-suspenders\n * — the per-call age sweep is the primary guard against accumulation\n * inside any single repo.\n */\nconst LEDGER_MAX_ENTRIES = 100\nconst LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\nexport interface WorktreeRegistryEntry {\n repoRoot: string\n dir: string\n branch: string\n}\n\n/**\n * Set-like in-memory registry of worktrees this proxy created. Engine\n * passes it to `createWorktree` so per-call cleanup deletes the entry\n * on success; the signal handlers walk what's left at shutdown.\n *\n * Not a bare `Set` because we want to expose only the operations we\n * actually use, and we want a stable testable surface.\n */\nexport class WorktreeRegistry {\n private readonly entries = new Set<WorktreeRegistryEntry>()\n\n add(entry: WorktreeRegistryEntry): void {\n this.entries.add(entry)\n }\n delete(entry: WorktreeRegistryEntry): void {\n this.entries.delete(entry)\n }\n has(entry: WorktreeRegistryEntry): boolean {\n return this.entries.has(entry)\n }\n values(): IterableIterator<WorktreeRegistryEntry> {\n return this.entries.values()\n }\n get size(): number {\n return this.entries.size\n }\n clear(): void {\n this.entries.clear()\n }\n}\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Used in worktree\n * dir/branch names so the boot sweep can reliably distinguish \"this\n * proxy's still-live worktrees\" from \"stranded dirs from a prior\n * proxy that happens to have a recycled PID\" — Docker PID-1 across\n * container restarts is the classic case (peer-review HIGH finding).\n */\nexport function getInstanceUuid(): string {\n if (_instanceUuid === null) {\n _instanceUuid = randomUUID()\n }\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers + sweepRegistry\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _activeRegistry: WorktreeRegistry | null = null\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Synchronous cleanup of every registry entry. Best-effort:\n * `execFileSync` failures are swallowed (the dir may have been\n * removed already, or git may not be on PATH any more in some\n * environments). After a successful removal we drop the entry from\n * the registry so a second call is a true no-op.\n *\n * Synchronous on purpose — exit handlers can't reliably await async\n * work; the process would die before the promise settled.\n */\nexport function sweepRegistry(): void {\n if (!_activeRegistry) return\n // Snapshot the values first so we can mutate the underlying set\n // during iteration without skipping entries.\n const snapshot = [..._activeRegistry.values()]\n for (const entry of snapshot) {\n try {\n // `-C entry.repoRoot` is load-bearing: without it git resolves\n // the worktree path relative to the proxy's cwd (which is the\n // user's launch dir, typically NOT inside the target repo), and\n // fails with `fatal: '<path>' is not a working tree`. The E2E\n // boot-sweep test (worker-agent-boot-sweep.test.ts) is what\n // caught the missing flag.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", entry.dir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // Already gone, EBUSY, or git not on PATH — best effort.\n }\n try {\n execFileSync(\"git\", [\"-C\", entry.repoRoot, \"branch\", \"-D\", entry.branch], {\n stdio: \"ignore\",\n timeout: 5_000,\n windowsHide: true,\n })\n } catch {\n // Same as above.\n }\n _activeRegistry.delete(entry)\n }\n}\n\n/**\n * Windows ConPTY / node-pty signal behavior:\n *\n * When a ConPTY host (VS Code terminal, Windows Terminal, node-pty) closes\n * the pseudo-console, the ConPTY layer sends CTRL_CLOSE_EVENT to the\n * process group. Node.js translates this into SIGINT (NOT SIGTERM). The\n * process has a ~5-second window before forced termination.\n *\n * Implication: the SIGTERM handler below may NEVER fire in node-pty\n * environments. This is by design — the three-layer cleanup architecture\n * ensures coverage:\n * 1. Per-call cleanup (engine.ts finally block) — happy path\n * 2. SIGINT handler (this file) — ConPTY close, Ctrl+C\n * 3. `exit` handler (this file) — unconditional, fires on any exit\n * 4. Boot-time PID+instance sweep (sweepStaleWorktreesAtBoot) — crash recovery\n *\n * Layers 1+2+3 cover ConPTY; layer 4 covers SIGKILL/OOM/container restart.\n */\n\n/**\n * Wire up SIGINT/SIGTERM/exit handlers that walk the registry and\n * remove every entry. Idempotent: subsequent calls swap the registry\n * pointer but do NOT register additional process listeners (otherwise\n * we'd leak listeners on every `runWorkerAgent`).\n *\n * Signal handlers re-raise the signal after sweeping. Naively running\n * the sweep on SIGINT/SIGTERM and returning would *suppress* the\n * signal: Node defaults to terminating the process on these, but only\n * if no user listener is attached. Once we attach a listener, the\n * default action is cancelled and the process keeps running — which\n * means Ctrl-C would clean worktrees but not actually exit, leaving\n * orphan processes in dev. The `process.kill(pid, sig)` re-raise\n * after removing our own listener restores the default behaviour\n * (the second delivery now hits an empty listener list, so Node\n * terminates with the conventional `128 + signum` exit code).\n */\nexport function registerExitHandlers(registry: WorktreeRegistry): void {\n _activeRegistry = registry\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepRegistry()\n _sigintHandler = () => {\n sweepRegistry()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepRegistry()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n // `exit` handlers can only run synchronous code — exactly what\n // sweepRegistry does. Async work here would never complete.\n process.on(\"exit\", _exitHandler)\n}\n\n/**\n * Test-only: unregister the handlers and reset module state. Tests\n * that want to verify `registerExitHandlers` semantics must clean up\n * after themselves or future tests in the same process inherit the\n * (now stale) registry pointer.\n */\nexport function __unregisterExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _activeRegistry = null\n}\n\n// ---------------------------------------------------------------------\n// Ledger: which repos has this proxy touched?\n// ---------------------------------------------------------------------\n\ninterface LedgerEntry {\n repoRoot: string\n lastSeenMs: number\n}\n\ninterface LedgerFile {\n entries: Array<LedgerEntry>\n}\n\nfunction ledgerPath(): string {\n return path.join(PATHS.APP_DIR, \"worker-repos.json\")\n}\n\nasync function readLedger(): Promise<LedgerFile> {\n let raw: string\n try {\n raw = await fs.readFile(ledgerPath(), \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { entries: [] }\n }\n return { entries: [] }\n }\n try {\n const parsed = JSON.parse(raw) as Partial<LedgerFile>\n if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] }\n const cleaned: Array<LedgerEntry> = []\n for (const e of parsed.entries) {\n if (\n e &&\n typeof e === \"object\" &&\n typeof (e as LedgerEntry).repoRoot === \"string\" &&\n typeof (e as LedgerEntry).lastSeenMs === \"number\"\n ) {\n cleaned.push({\n repoRoot: (e as LedgerEntry).repoRoot,\n lastSeenMs: (e as LedgerEntry).lastSeenMs,\n })\n }\n }\n return { entries: cleaned }\n } catch {\n // Corrupted JSON — start fresh rather than crashing the proxy.\n return { entries: [] }\n }\n}\n\n/**\n * Per-process serializer for ledger writes. Multiple concurrent\n * `recordWorkerRepo` calls (legitimate: several workers may start at\n * once) would otherwise race read-modify-write on the JSON file. Each\n * call chains onto the previous so the on-disk sequence is\n * deterministic from this process's perspective.\n *\n * Cross-process safety is provided by the atomic temp+rename below,\n * which makes the final state of the file always be a well-formed\n * full snapshot from ONE writer — never a partial write or\n * interleaved JSON.\n */\nlet _ledgerChain: Promise<void> = Promise.resolve()\n\n/**\n * Append `repoRoot` to the ledger (or update its `lastSeenMs`).\n * Atomic temp+rename per peer review.\n */\nexport function recordWorkerRepo(repoRoot: string): Promise<void> {\n const next = _ledgerChain.then(async () => {\n await fs.mkdir(PATHS.APP_DIR, { recursive: true })\n const current = await readLedger()\n // Dedup: drop any existing entry for this root before appending\n // the fresh one so the array doesn't grow unbounded with repeats.\n const filtered = current.entries.filter((e) => e.repoRoot !== repoRoot)\n filtered.push({ repoRoot, lastSeenMs: Date.now() })\n // Prune by age and cap entry count (newest wins).\n const now = Date.now()\n const pruned = filtered\n .filter((e) => now - e.lastSeenMs < LEDGER_MAX_AGE_MS)\n .slice(-LEDGER_MAX_ENTRIES)\n const ledger: LedgerFile = { entries: pruned }\n\n // Atomic temp+rename. The temp filename is unique per call\n // (PID + 8 random hex chars) so concurrent processes don't\n // collide on the temp name; the final `rename` is atomic on\n // POSIX and on Windows (both with same filesystem).\n const tmp = `${ledgerPath()}.tmp.${process.pid}.${randomBytes(4).toString(\n \"hex\",\n )}`\n try {\n await writeRuntimeFileSecure(tmp, JSON.stringify(ledger, null, 2))\n await fs.rename(tmp, ledgerPath())\n } catch (err) {\n // Clean up the temp file if rename failed midway.\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n })\n // Swallow chain-internal errors so one failed write doesn't poison\n // the chain for every subsequent caller. Each call still sees its\n // own rejection (we return `next`, not the catch-handler chain).\n _ledgerChain = next.catch(() => undefined)\n return next\n}\n\nfunction isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n // EPERM = process exists but we can't signal it — still alive\n // for our purposes (we just need to know whether to clean up).\n if (code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. For every repo we recorded in the ledger,\n * enumerate `<repoRoot>/.git/worker-worktrees/` (the conventional\n * location — for repos already inside a worktree, the actual\n * `git-common-dir` may differ, in which case we'll miss this batch\n * and the per-call age sweep will catch them within 7 days) and\n * remove dirs that aren't owned by THIS proxy.\n *\n * Ownership rule: dir is \"ours\" iff its embedded PID is alive AND\n * its embedded UUID equals `getInstanceUuid()`. Either condition\n * failing → remove.\n */\nexport async function sweepStaleWorktreesAtBoot(): Promise<void> {\n const ledger = await readLedger()\n if (ledger.entries.length === 0) return\n const currentUuid = getInstanceUuid()\n for (const entry of ledger.entries) {\n const parent = path.join(entry.repoRoot, \".git\", \"worker-worktrees\")\n let names: Array<string>\n try {\n names = await fs.readdir(parent)\n } catch {\n continue\n }\n for (const name of names) {\n const m = WORKTREE_DIR_NAME_RE.exec(name)\n if (!m) continue\n const pid = Number.parseInt(m[1], 10)\n const uuid = m[2]\n const isOurs = isPidAlive(pid) && uuid === currentUuid\n if (isOurs) continue\n\n const fullDir = path.join(parent, name)\n const branch = `worker/${pid}-${uuid}-${m[3]}`\n try {\n // `-C entry.repoRoot` is load-bearing here too — see the\n // matching comment in `sweepRegistry`. The boot sweep runs\n // BEFORE any worker tool has set cwd, so the proxy's cwd is\n // the user's launch dir, which is almost never inside the\n // target repo.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", fullDir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"branch\", \"-D\", branch],\n { stdio: \"ignore\", timeout: 5_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n await fs.rm(fullDir, { recursive: true, force: true })\n } catch {\n // ignore — git may have removed it already\n }\n }\n }\n}\n\n/** Test-only: clear the ledger file (does NOT remove on-disk worktrees). */\nexport async function __clearLedgerForTests(): Promise<void> {\n await fs.unlink(ledgerPath()).catch(() => {})\n}\n\n/** Test-only: read the ledger as a plain array (no side effects). */\nexport async function __readLedgerForTests(): Promise<Array<LedgerEntry>> {\n return (await readLedger()).entries\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,uBACJ;AASF,MAAM,oBAAoB;;;;;;;;;AAgB1B,IAAa,mBAAb,MA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R,MAAM,MAAM,OAAO,SAAS,EAAE,IAAI,EAAE;GACpC,MAAM,OAAO,EAAE;GAEf,IADe,WAAW,GAAG,KAAK,SAAS,aAC/B;GAEZ,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI;GACtC,MAAM,SAAS,UAAU,IAAI,GAAG,KAAK,GAAG,EAAE;GAC1C,IAAI;IAMF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAY;KAAU;KAAW;IAAO,GAC/D;KAAE,OAAO;KAAU,SAAS;KAAQ,aAAa;IAAK,CACxD;GACF,QAAQ,CAER;GACA,IAAI;IACF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAU;KAAM;IAAM,GAC7C;KAAE,OAAO;KAAU,SAAS;KAAO,aAAa;IAAK,CACvD;GACF,QAAQ,CAER;GACA,IAAI;IACF,MAAM,GAAG,GAAG,SAAS;KAAE,WAAW;KAAM,OAAO;IAAK,CAAC;GACvD,QAAQ,CAER;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"lifecycle-COZhARmE.js","names":[],"sources":["../src/lib/worker-agent/lifecycle.ts"],"sourcesContent":["/**\n * Lifecycle plumbing for worker worktrees: in-memory registry, signal\n * handlers, ledger of repos touched, and the boot-time PID+instance\n * safety net.\n *\n * Plan: see `plans/we-have-added-a-dreamy-tide.md` (\"Worktree mode\" →\n * \"Cleanup paths\"). Three layers cooperate, none of them sufficient\n * alone:\n *\n * 1. Per-call cleanup (`engine.ts` finally block invoking\n * `WorktreeHandle.remove()`) — covers the happy path.\n *\n * 2. Session-end signal sweep (this file, registered via\n * `registerExitHandlers`) — covers Ctrl+C, service-manager stop,\n * and (in `github-router claude` mode) the spawned child's exit.\n * Synchronous `execFileSync` is intentional: exit handlers can't\n * reliably await async work.\n *\n * 3. Boot-time PID+instance sweep (`sweepStaleWorktreesAtBoot`) —\n * covers SIGKILL, OOM, container restart. Walks the ledger of\n * repos this proxy has touched and removes worktree dirs whose\n * `<pid>` is dead OR whose `<instance>` UUID doesn't match the\n * current proxy's UUID.\n *\n * Ledger writes are ATOMIC (temp + rename) per peer review — a\n * concurrent-RMW corruption would silently strand worktrees because\n * the boot sweep can't find their repo roots.\n */\n\nimport { execFileSync } from \"node:child_process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { PATHS, writeRuntimeFileSecure } from \"../paths\"\n\n/**\n * Same regex worktree.ts uses for its per-call age sweep — kept in\n * sync intentionally. `<pid>-<uuid>-<8hex>` strictly.\n */\nconst WORKTREE_DIR_NAME_RE =\n /^(\\d+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-([0-9a-f]{8})$/\n\n/**\n * Cap on the ledger: how many repos we remember across boots, and how\n * old an entry may be before it's pruned. Both are belt-and-suspenders\n * — the per-call age sweep is the primary guard against accumulation\n * inside any single repo.\n */\nconst LEDGER_MAX_ENTRIES = 100\nconst LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\nexport interface WorktreeRegistryEntry {\n repoRoot: string\n dir: string\n branch: string\n}\n\n/**\n * Set-like in-memory registry of worktrees this proxy created. Engine\n * passes it to `createWorktree` so per-call cleanup deletes the entry\n * on success; the signal handlers walk what's left at shutdown.\n *\n * Not a bare `Set` because we want to expose only the operations we\n * actually use, and we want a stable testable surface.\n */\nexport class WorktreeRegistry {\n private readonly entries = new Set<WorktreeRegistryEntry>()\n\n add(entry: WorktreeRegistryEntry): void {\n this.entries.add(entry)\n }\n delete(entry: WorktreeRegistryEntry): void {\n this.entries.delete(entry)\n }\n has(entry: WorktreeRegistryEntry): boolean {\n return this.entries.has(entry)\n }\n values(): IterableIterator<WorktreeRegistryEntry> {\n return this.entries.values()\n }\n get size(): number {\n return this.entries.size\n }\n clear(): void {\n this.entries.clear()\n }\n}\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Used in worktree\n * dir/branch names so the boot sweep can reliably distinguish \"this\n * proxy's still-live worktrees\" from \"stranded dirs from a prior\n * proxy that happens to have a recycled PID\" — Docker PID-1 across\n * container restarts is the classic case (peer-review HIGH finding).\n */\nexport function getInstanceUuid(): string {\n if (_instanceUuid === null) {\n _instanceUuid = randomUUID()\n }\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers + sweepRegistry\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _activeRegistry: WorktreeRegistry | null = null\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Synchronous cleanup of every registry entry. Best-effort:\n * `execFileSync` failures are swallowed (the dir may have been\n * removed already, or git may not be on PATH any more in some\n * environments). After a successful removal we drop the entry from\n * the registry so a second call is a true no-op.\n *\n * Synchronous on purpose — exit handlers can't reliably await async\n * work; the process would die before the promise settled.\n */\nexport function sweepRegistry(): void {\n if (!_activeRegistry) return\n // Snapshot the values first so we can mutate the underlying set\n // during iteration without skipping entries.\n const snapshot = [..._activeRegistry.values()]\n for (const entry of snapshot) {\n try {\n // `-C entry.repoRoot` is load-bearing: without it git resolves\n // the worktree path relative to the proxy's cwd (which is the\n // user's launch dir, typically NOT inside the target repo), and\n // fails with `fatal: '<path>' is not a working tree`. The E2E\n // boot-sweep test (worker-agent-boot-sweep.test.ts) is what\n // caught the missing flag.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", entry.dir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // Already gone, EBUSY, or git not on PATH — best effort.\n }\n try {\n execFileSync(\"git\", [\"-C\", entry.repoRoot, \"branch\", \"-D\", entry.branch], {\n stdio: \"ignore\",\n timeout: 5_000,\n windowsHide: true,\n })\n } catch {\n // Same as above.\n }\n _activeRegistry.delete(entry)\n }\n}\n\n/**\n * Windows ConPTY / node-pty signal behavior:\n *\n * When a ConPTY host (VS Code terminal, Windows Terminal, node-pty) closes\n * the pseudo-console, the ConPTY layer sends CTRL_CLOSE_EVENT to the\n * process group. Node.js translates this into SIGINT (NOT SIGTERM). The\n * process has a ~5-second window before forced termination.\n *\n * Implication: the SIGTERM handler below may NEVER fire in node-pty\n * environments. This is by design — the three-layer cleanup architecture\n * ensures coverage:\n * 1. Per-call cleanup (engine.ts finally block) — happy path\n * 2. SIGINT handler (this file) — ConPTY close, Ctrl+C\n * 3. `exit` handler (this file) — unconditional, fires on any exit\n * 4. Boot-time PID+instance sweep (sweepStaleWorktreesAtBoot) — crash recovery\n *\n * Layers 1+2+3 cover ConPTY; layer 4 covers SIGKILL/OOM/container restart.\n */\n\n/**\n * Wire up SIGINT/SIGTERM/exit handlers that walk the registry and\n * remove every entry. Idempotent: subsequent calls swap the registry\n * pointer but do NOT register additional process listeners (otherwise\n * we'd leak listeners on every `runWorkerAgent`).\n *\n * Signal handlers re-raise the signal after sweeping. Naively running\n * the sweep on SIGINT/SIGTERM and returning would *suppress* the\n * signal: Node defaults to terminating the process on these, but only\n * if no user listener is attached. Once we attach a listener, the\n * default action is cancelled and the process keeps running — which\n * means Ctrl-C would clean worktrees but not actually exit, leaving\n * orphan processes in dev. The `process.kill(pid, sig)` re-raise\n * after removing our own listener restores the default behaviour\n * (the second delivery now hits an empty listener list, so Node\n * terminates with the conventional `128 + signum` exit code).\n */\nexport function registerExitHandlers(registry: WorktreeRegistry): void {\n _activeRegistry = registry\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepRegistry()\n _sigintHandler = () => {\n sweepRegistry()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepRegistry()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n // `exit` handlers can only run synchronous code — exactly what\n // sweepRegistry does. Async work here would never complete.\n process.on(\"exit\", _exitHandler)\n}\n\n/**\n * Test-only: unregister the handlers and reset module state. Tests\n * that want to verify `registerExitHandlers` semantics must clean up\n * after themselves or future tests in the same process inherit the\n * (now stale) registry pointer.\n */\nexport function __unregisterExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _activeRegistry = null\n}\n\n// ---------------------------------------------------------------------\n// Ledger: which repos has this proxy touched?\n// ---------------------------------------------------------------------\n\ninterface LedgerEntry {\n repoRoot: string\n lastSeenMs: number\n}\n\ninterface LedgerFile {\n entries: Array<LedgerEntry>\n}\n\nfunction ledgerPath(): string {\n return path.join(PATHS.APP_DIR, \"worker-repos.json\")\n}\n\nasync function readLedger(): Promise<LedgerFile> {\n let raw: string\n try {\n raw = await fs.readFile(ledgerPath(), \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { entries: [] }\n }\n return { entries: [] }\n }\n try {\n const parsed = JSON.parse(raw) as Partial<LedgerFile>\n if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] }\n const cleaned: Array<LedgerEntry> = []\n for (const e of parsed.entries) {\n if (\n e &&\n typeof e === \"object\" &&\n typeof (e as LedgerEntry).repoRoot === \"string\" &&\n typeof (e as LedgerEntry).lastSeenMs === \"number\"\n ) {\n cleaned.push({\n repoRoot: (e as LedgerEntry).repoRoot,\n lastSeenMs: (e as LedgerEntry).lastSeenMs,\n })\n }\n }\n return { entries: cleaned }\n } catch {\n // Corrupted JSON — start fresh rather than crashing the proxy.\n return { entries: [] }\n }\n}\n\n/**\n * Per-process serializer for ledger writes. Multiple concurrent\n * `recordWorkerRepo` calls (legitimate: several workers may start at\n * once) would otherwise race read-modify-write on the JSON file. Each\n * call chains onto the previous so the on-disk sequence is\n * deterministic from this process's perspective.\n *\n * Cross-process safety is provided by the atomic temp+rename below,\n * which makes the final state of the file always be a well-formed\n * full snapshot from ONE writer — never a partial write or\n * interleaved JSON.\n */\nlet _ledgerChain: Promise<void> = Promise.resolve()\n\n/**\n * Append `repoRoot` to the ledger (or update its `lastSeenMs`).\n * Atomic temp+rename per peer review.\n */\nexport function recordWorkerRepo(repoRoot: string): Promise<void> {\n const next = _ledgerChain.then(async () => {\n await fs.mkdir(PATHS.APP_DIR, { recursive: true })\n const current = await readLedger()\n // Dedup: drop any existing entry for this root before appending\n // the fresh one so the array doesn't grow unbounded with repeats.\n const filtered = current.entries.filter((e) => e.repoRoot !== repoRoot)\n filtered.push({ repoRoot, lastSeenMs: Date.now() })\n // Prune by age and cap entry count (newest wins).\n const now = Date.now()\n const pruned = filtered\n .filter((e) => now - e.lastSeenMs < LEDGER_MAX_AGE_MS)\n .slice(-LEDGER_MAX_ENTRIES)\n const ledger: LedgerFile = { entries: pruned }\n\n // Atomic temp+rename. The temp filename is unique per call\n // (PID + 8 random hex chars) so concurrent processes don't\n // collide on the temp name; the final `rename` is atomic on\n // POSIX and on Windows (both with same filesystem).\n const tmp = `${ledgerPath()}.tmp.${process.pid}.${randomBytes(4).toString(\n \"hex\",\n )}`\n try {\n await writeRuntimeFileSecure(tmp, JSON.stringify(ledger, null, 2))\n await fs.rename(tmp, ledgerPath())\n } catch (err) {\n // Clean up the temp file if rename failed midway.\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n })\n // Swallow chain-internal errors so one failed write doesn't poison\n // the chain for every subsequent caller. Each call still sees its\n // own rejection (we return `next`, not the catch-handler chain).\n _ledgerChain = next.catch(() => undefined)\n return next\n}\n\nfunction isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n // EPERM = process exists but we can't signal it — still alive\n // for our purposes (we just need to know whether to clean up).\n if (code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. For every repo we recorded in the ledger,\n * enumerate `<repoRoot>/.git/worker-worktrees/` (the conventional\n * location — for repos already inside a worktree, the actual\n * `git-common-dir` may differ, in which case we'll miss this batch\n * and the per-call age sweep will catch them within 7 days) and\n * remove dirs that aren't owned by THIS proxy.\n *\n * Ownership rule: dir is \"ours\" iff its embedded PID is alive AND\n * its embedded UUID equals `getInstanceUuid()`. Either condition\n * failing → remove.\n */\nexport async function sweepStaleWorktreesAtBoot(): Promise<void> {\n const ledger = await readLedger()\n if (ledger.entries.length === 0) return\n const currentUuid = getInstanceUuid()\n for (const entry of ledger.entries) {\n const parent = path.join(entry.repoRoot, \".git\", \"worker-worktrees\")\n let names: Array<string>\n try {\n names = await fs.readdir(parent)\n } catch {\n continue\n }\n for (const name of names) {\n const m = WORKTREE_DIR_NAME_RE.exec(name)\n if (!m) continue\n const pid = Number.parseInt(m[1], 10)\n const uuid = m[2]\n const isOurs = isPidAlive(pid) && uuid === currentUuid\n if (isOurs) continue\n\n const fullDir = path.join(parent, name)\n const branch = `worker/${pid}-${uuid}-${m[3]}`\n try {\n // `-C entry.repoRoot` is load-bearing here too — see the\n // matching comment in `sweepRegistry`. The boot sweep runs\n // BEFORE any worker tool has set cwd, so the proxy's cwd is\n // the user's launch dir, which is almost never inside the\n // target repo.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", fullDir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"branch\", \"-D\", branch],\n { stdio: \"ignore\", timeout: 5_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n await fs.rm(fullDir, { recursive: true, force: true })\n } catch {\n // ignore — git may have removed it already\n }\n }\n }\n}\n\n/** Test-only: clear the ledger file (does NOT remove on-disk worktrees). */\nexport async function __clearLedgerForTests(): Promise<void> {\n await fs.unlink(ledgerPath()).catch(() => {})\n}\n\n/** Test-only: read the ledger as a plain array (no side effects). */\nexport async function __readLedgerForTests(): Promise<Array<LedgerEntry>> {\n return (await readLedger()).entries\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,uBACJ;AASF,MAAM,oBAAoB;;;;;;;;;AAgB1B,IAAa,mBAAb,MAA8B;CACX,0BAAU,IAAI,IAA2B;CAE1D,IAAI,OAAoC;EACtC,KAAK,QAAQ,IAAI,KAAK;CACxB;CACA,OAAO,OAAoC;EACzC,KAAK,QAAQ,OAAO,KAAK;CAC3B;CACA,IAAI,OAAuC;EACzC,OAAO,KAAK,QAAQ,IAAI,KAAK;CAC/B;CACA,SAAkD;EAChD,OAAO,KAAK,QAAQ,OAAO;CAC7B;CACA,IAAI,OAAe;EACjB,OAAO,KAAK,QAAQ;CACtB;CACA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;AACF;AAMA,IAAI,gBAA+B;;;;;;;;AASnC,SAAgB,kBAA0B;CACxC,IAAI,kBAAkB,MACpB,gBAAgB,WAAW;CAE7B,OAAO;AACT;AAWA,IAAI,cAAc;AAClB,IAAI,kBAA2C;AAC/C,IAAI,eAAoC;AACxC,IAAI,iBAAsC;AAC1C,IAAI,kBAAuC;;;;;;;;;;;AAY3C,SAAgB,gBAAsB;CACpC,IAAI,CAAC,iBAAiB;CAGtB,MAAM,WAAW,CAAC,GAAG,gBAAgB,OAAO,CAAC;CAC7C,KAAK,MAAM,SAAS,UAAU;EAC5B,IAAI;GAOF,aACE,OACA;IAAC;IAAM,MAAM;IAAU;IAAY;IAAU;IAAW,MAAM;GAAG,GACjE;IA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OAAO;EAC7B,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,eAAsB,4BAA2C;CAC/D,MAAM,SAAS,MAAM,WAAW;CAChC,IAAI,OAAO,QAAQ,WAAW,GAAG;CACjC,MAAM,cAAc,gBAAgB;CACpC,KAAK,MAAM,SAAS,OAAO,SAAS;EAClC,MAAM,SAAS,KAAK,KAAK,MAAM,UAAU,QAAQ,kBAAkB;EACnE,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,GAAG,QAAQ,MAAM;EACjC,QAAQ;GACN;EACF;EACA,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,IAAI,qBAAqB,KAAK,IAAI;GACxC,IAAI,CAAC,GAAG;GACR,MAAM,MAAM,OAAO,SAAS,EAAE,IAAI,EAAE;GACpC,MAAM,OAAO,EAAE;GAEf,IADe,WAAW,GAAG,KAAK,SAAS,aAC/B;GAEZ,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI;GACtC,MAAM,SAAS,UAAU,IAAI,GAAG,KAAK,GAAG,EAAE;GAC1C,IAAI;IAMF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAY;KAAU;KAAW;IAAO,GAC/D;KAAE,OAAO;KAAU,SAAS;KAAQ,aAAa;IAAK,CACxD;GACF,QAAQ,CAER;GACA,IAAI;IACF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAU;KAAM;IAAM,GAC7C;KAAE,OAAO;KAAU,SAAS;KAAO,aAAa;IAAK,CACvD;GACF,QAAQ,CAER;GACA,IAAI;IACF,MAAM,GAAG,GAAG,SAAS;KAAE,WAAW;KAAM,OAAO;IAAK,CAAC;GACvD,QAAQ,CAER;EACF;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { o as sweepStaleWorktreesAtBoot } from "./lifecycle-COZhARmE.js";
|
package/dist/main.js
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { n as setManagedDiagnosticReporter } from "./diagnostics-cXjCT_JQ.js";
|
|
2
3
|
import { t as getPackageVersion } from "./version-CTqwKr26.js";
|
|
3
4
|
import { defineCommand, runMain, showUsage } from "citty";
|
|
4
5
|
import consola from "consola";
|
|
5
6
|
// src/main.ts
|
|
7
|
+
/**
|
|
8
|
+
* Point the managed-install layer's diagnostic sink at consola.
|
|
9
|
+
*
|
|
10
|
+
* That layer is also imported by `dist/bin.js`, a separate bundle, so it cannot
|
|
11
|
+
* import consola itself without ending up with a second, differently-configured
|
|
12
|
+
* instance writing to a different place. The bootstrap leaves the sink empty (its
|
|
13
|
+
* messages are deliberately silent); once the real CLI is running, they go here.
|
|
14
|
+
*/
|
|
15
|
+
setManagedDiagnosticReporter((level, message) => {
|
|
16
|
+
if (level === "warn") consola.warn(message);
|
|
17
|
+
else if (level === "info") consola.info(message);
|
|
18
|
+
else consola.debug(message);
|
|
19
|
+
});
|
|
6
20
|
process.on("unhandledRejection", (error) => {
|
|
7
21
|
consola.error("Unhandled rejection:", error);
|
|
8
22
|
});
|
|
@@ -46,30 +60,31 @@ const main = defineCommand({
|
|
|
46
60
|
description: "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints."
|
|
47
61
|
},
|
|
48
62
|
subCommands: {
|
|
49
|
-
auth: () => import("./auth-
|
|
50
|
-
start: () => import("./start-
|
|
51
|
-
claude: () => import("./claude-
|
|
52
|
-
codex: () => import("./codex-
|
|
53
|
-
pi: () => import("./pi-
|
|
54
|
-
workiq: () => import("./workiq-
|
|
55
|
-
serve: () => import("./serve-
|
|
56
|
-
models: () => import("./models-
|
|
57
|
-
"check-usage": () => import("./check-usage-
|
|
58
|
-
index: () => import("./index-cmd-
|
|
59
|
-
debug: () => import("./debug-
|
|
60
|
-
|
|
61
|
-
"internal-
|
|
62
|
-
"internal-
|
|
63
|
-
"internal-
|
|
64
|
-
"internal-
|
|
65
|
-
"internal-
|
|
66
|
-
"internal-
|
|
67
|
-
"internal-
|
|
68
|
-
"internal-
|
|
69
|
-
"internal-
|
|
70
|
-
"internal-
|
|
71
|
-
"internal-
|
|
72
|
-
"internal-
|
|
63
|
+
auth: () => import("./auth-5TKcQbbH.js").then((m) => m.auth),
|
|
64
|
+
start: () => import("./start-7CiQIl0r.js").then((m) => m.start),
|
|
65
|
+
claude: () => import("./claude-CkrhHkPQ.js").then((m) => m.claude),
|
|
66
|
+
codex: () => import("./codex-50GzveCD.js").then((m) => m.codex),
|
|
67
|
+
pi: () => import("./pi-DVud9eQn.js").then((m) => m.pi),
|
|
68
|
+
workiq: () => import("./workiq-D5b7xlbr.js").then((m) => m.workiq),
|
|
69
|
+
serve: () => import("./serve-B8Igr9Q0.js").then((m) => m.serve),
|
|
70
|
+
models: () => import("./models-BDV-YLf2.js").then((m) => m.models),
|
|
71
|
+
"check-usage": () => import("./check-usage-DM39fdel.js").then((m) => m.checkUsage),
|
|
72
|
+
index: () => import("./index-cmd-DsK6VFs8.js").then((m) => m.indexCmd),
|
|
73
|
+
debug: () => import("./debug-Df0Kuzi3.js").then((m) => m.debug),
|
|
74
|
+
update: () => import("./update-fEgWTrIx.js").then((m) => m.update),
|
|
75
|
+
"internal-stop-hook": () => import("./internal-stop-hook-cDF1MuJZ.js").then((m) => m.internalStopHook),
|
|
76
|
+
"internal-prompt-submit": () => import("./internal-prompt-submit-ZBhH-SQ1.js").then((m) => m.internalPromptSubmit),
|
|
77
|
+
"internal-stop-review": () => import("./internal-stop-review-y8zjpK_3.js").then((m) => m.internalStopReview),
|
|
78
|
+
"internal-plan-review": () => import("./internal-plan-review-bzqGNdtw.js").then((m) => m.internalPlanReview),
|
|
79
|
+
"internal-rebrief": () => import("./internal-rebrief-BIWbN7Sr.js").then((m) => m.internalRebrief),
|
|
80
|
+
"internal-session-bind": () => import("./internal-session-bind-BL6hFRLO.js").then((m) => m.internalSessionBind),
|
|
81
|
+
"internal-workspace-header": () => import("./internal-workspace-header-BMKbO8yX.js").then((m) => m.internalWorkspaceHeader),
|
|
82
|
+
"internal-artifact-open": () => import("./internal-artifact-open-DRBg1PpV.js").then((m) => m.internalArtifactOpen),
|
|
83
|
+
"internal-first-mate-guard": () => import("./internal-first-mate-guard-BijeVpi9.js").then((m) => m.internalFirstMateGuard),
|
|
84
|
+
"internal-worker-guard": () => import("./internal-worker-guard-DdyYBZR0.js").then((m) => m.internalWorkerGuard),
|
|
85
|
+
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-D6-Ees_6.js").then((m) => m.internalFastDispatchGuard),
|
|
86
|
+
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-DeEfWqfP.js").then((m) => m.internalMaxDispatchGuard),
|
|
87
|
+
"internal-aic-status": () => import("./internal-aic-status-CUZ7-trf.js").then((m) => m.internalAicStatus)
|
|
73
88
|
}
|
|
74
89
|
});
|
|
75
90
|
/**
|
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","names":[],"sources":["../src/main.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand, runMain, showUsage } from \"citty\"\nimport consola from \"consola\"\n\nimport { getPackageVersion } from \"./lib/version\"\n\nprocess.on(\"unhandledRejection\", (error) => {\n consola.error(\"Unhandled rejection:\", error)\n})\n\nprocess.on(\"uncaughtException\", (error) => {\n consola.error(\"Uncaught exception:\", error)\n process.exit(1)\n})\n\nconst version = getPackageVersion()\n\n// Always surface the running version on stderr so crash reports\n// identify which build is in use. Suppressed only for `--version`\n// (citty's built-in handler prints just the bare version number, and\n// a banner above it is redundant). `-v` is NOT special-cased: citty\n// doesn't treat it as `--version`, so users typing `-v` still get\n// the banner — which is the closest thing to \"show me the version\".\nconst argv = process.argv.slice(2)\nconst isVersionFlag = argv.includes(\"--version\")\n// Suppress the banner for the internal hooks: their stdout/stderr is consumed by\n// Claude Code (the Stop hook's stderr is the block message; the prompt-submit\n// hook's stdout is injected context), so it must stay clean. `internal-stop-review`\n// and `internal-plan-review` are detached/background with no consumer, but stay\n// quiet for the same reason.\nconst isInternalHook =\n argv[0] === \"internal-stop-hook\"\n || argv[0] === \"internal-prompt-submit\"\n || argv[0] === \"internal-stop-review\"\n || argv[0] === \"internal-plan-review\"\n || argv[0] === \"internal-rebrief\"\n || argv[0] === \"internal-session-bind\"\n || argv[0] === \"internal-workspace-header\"\n || argv[0] === \"internal-artifact-open\"\n || argv[0] === \"internal-first-mate-guard\"\n || argv[0] === \"internal-worker-guard\"\n || argv[0] === \"internal-fast-dispatch-guard\"\n || argv[0] === \"internal-aic-status\"\nif (!isVersionFlag && !isInternalHook) {\n consola.info(`github-router v${version}`)\n}\n\n/**\n * Subcommands are LAZY THUNKS, not static imports.\n *\n * citty resolves only the named entry (`_findSubCommand` → `resolveValue`), so\n * running one subcommand no longer evaluates the other 17 module graphs. That\n * matters because several of these are per-turn Claude Code hooks — the\n * `UserPromptSubmit`, `Stop` and `PreToolUse` handlers registered by\n * `src/claude.ts` each spawn a FRESH `node dist/main.js <sub>` process, so any\n * import-time cost lands in the user's interactive loop on every prompt.\n * `internal-worker-guard`, for instance, needs three modules but was loading\n * the entire claude/serve/MCP graph plus the Pi vendor runtime.\n *\n * Safe because the import-time side effects in this codebase\n * (`assertMcpToolSurfaceConsistent` in `server.ts`, the tree-sitter grammar\n * preload, the worktree/session exit-handler registrations, the first-mate\n * allowlist assertion) are reachable ONLY from claude/codex/serve/start, and\n * all four reach all of them independently — no subcommand relies on another's\n * module being loaded. Verified by an AST walk of the runtime import graph.\n *\n * `--help` is the one path that still resolves everything: citty's\n * `renderUsage` reads each subcommand's meta to print descriptions. That is\n * not latency-critical, and `resolveHelpTarget` below resolves only the single\n * subcommand when help is scoped to one.\n */\nconst main = defineCommand({\n meta: {\n name: \"github-router\",\n version,\n description:\n \"A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.\",\n },\n subCommands: {\n auth: () => import(\"./auth\").then((m) => m.auth),\n start: () => import(\"./start\").then((m) => m.start),\n claude: () => import(\"./claude\").then((m) => m.claude),\n codex: () => import(\"./codex\").then((m) => m.codex),\n pi: () => import(\"./pi\").then((m) => m.pi),\n workiq: () => import(\"./workiq\").then((m) => m.workiq),\n serve: () => import(\"./serve\").then((m) => m.serve),\n models: () => import(\"./models\").then((m) => m.models),\n \"check-usage\": () => import(\"./check-usage\").then((m) => m.checkUsage),\n index: () => import(\"./index-cmd\").then((m) => m.indexCmd),\n debug: () => import(\"./debug\").then((m) => m.debug),\n \"internal-stop-hook\": () =>\n import(\"./internal-stop-hook\").then((m) => m.internalStopHook),\n \"internal-prompt-submit\": () =>\n import(\"./internal-prompt-submit\").then((m) => m.internalPromptSubmit),\n \"internal-stop-review\": () =>\n import(\"./internal-stop-review\").then((m) => m.internalStopReview),\n \"internal-plan-review\": () =>\n import(\"./internal-plan-review\").then((m) => m.internalPlanReview),\n \"internal-rebrief\": () =>\n import(\"./internal-rebrief\").then((m) => m.internalRebrief),\n \"internal-session-bind\": () =>\n import(\"./internal-session-bind\").then((m) => m.internalSessionBind),\n \"internal-workspace-header\": () =>\n import(\"./internal-workspace-header\").then(\n (m) => m.internalWorkspaceHeader,\n ),\n \"internal-artifact-open\": () =>\n import(\"./internal-artifact-open\").then((m) => m.internalArtifactOpen),\n \"internal-first-mate-guard\": () =>\n import(\"./internal-first-mate-guard\").then(\n (m) => m.internalFirstMateGuard,\n ),\n \"internal-worker-guard\": () =>\n import(\"./internal-worker-guard\").then((m) => m.internalWorkerGuard),\n \"internal-fast-dispatch-guard\": () =>\n import(\"./internal-fast-dispatch-guard\").then((m) => m.internalFastDispatchGuard),\n \"internal-max-dispatch-guard\": () =>\n import(\"./internal-max-dispatch-guard\").then((m) => m.internalMaxDispatchGuard),\n \"internal-aic-status\": () =>\n import(\"./internal-aic-status\").then((m) => m.internalAicStatus),\n },\n})\n\n/**\n * Print usage ourselves and let the process DRAIN, instead of letting citty\n * hard-exit while stdout is still queued.\n *\n * citty's `runMain` calls `process.exit(0)` immediately after `showUsage`\n * resolves (citty 0.2.2 dist/index.mjs:389; 0.1.6 does the same, so this is\n * not an upgrade regression). On Windows a PIPE-backed stdout is async, so the\n * usage text is still in a libuv handle when the hard exit tears the loop down\n * and node aborts:\n * `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), file src\\win\\async.c`\n * — after printing the help the user asked for.\n *\n * `--version` is unaffected: citty's version branch has no `process.exit()`\n * and drains naturally. That asymmetry is why this survived so long — the\n * cheapest smoke test passes while every `--help` path aborts. Node 22 on\n * Windows tolerated it; node 24 does not, and release.yml publishes with\n * node 24.\n *\n * Forcing `_handle.setBlocking(true)` first was tried and does NOT fix it —\n * the abort still reproduces through a pipe. The only reliable fix is to not\n * hard-exit at all, which is the same resolution the internal hooks already\n * use (`process.exitCode = 0`, never `process.exit()`), guarded by the tests\n * in this repo's internal-hooks-crash suite.\n *\n * Only the help path is intercepted; everything else still goes through citty\n * so argument parsing, subcommand dispatch and error handling stay citty's.\n */\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"])\n\nasync function resolveHelpTarget(): Promise<{\n cmd: Parameters<typeof showUsage>[0]\n parent?: Parameters<typeof showUsage>[1]\n}> {\n // First non-flag token is the subcommand, matching citty's own resolution\n // for our single-level command tree.\n const name = argv.find((arg) => !arg.startsWith(\"-\"))\n const table = main.subCommands as Record<string, unknown> | undefined\n const entry = name ? table?.[name] : undefined\n if (!entry) return { cmd: main }\n // citty allows a subcommand to be a value, a promise, or a thunk.\n const resolved = typeof entry === \"function\" ? await entry() : await entry\n return {\n cmd: resolved as Parameters<typeof showUsage>[0],\n parent: main as Parameters<typeof showUsage>[1],\n }\n}\n\nif (argv.some((arg) => HELP_FLAGS.has(arg))) {\n const { cmd, parent } = await resolveHelpTarget()\n await showUsage(cmd, parent)\n // Signal success WITHOUT tearing the loop down — node drains stdout and\n // exits 0 on its own.\n process.exitCode = 0\n} else {\n await runMain(main)\n}\n"],"mappings":";;;;;AAOA,QAAQ,GAAG,uBAAuB,UAAU;CAC1C,QAAQ,MAAM,wBAAwB,KAAK;AAC7C,CAAC;A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,GAAG;CAC3C,MAAM,EAAE,KAAK,WAAW,MAAM,kBAAkB;CAChD,MAAM,UAAU,KAAK,MAAM;CAG3B,QAAQ,WAAW;AACrB,OACE,MAAM,QAAQ,IAAI"}
|
|
1
|
+
{"version":3,"file":"main.js","names":[],"sources":["../src/main.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand, runMain, showUsage } from \"citty\"\nimport consola from \"consola\"\n\nimport { setManagedDiagnosticReporter } from \"./lib/managed-install/diagnostics\"\nimport { getPackageVersion } from \"./lib/version\"\n\n/**\n * Point the managed-install layer's diagnostic sink at consola.\n *\n * That layer is also imported by `dist/bin.js`, a separate bundle, so it cannot\n * import consola itself without ending up with a second, differently-configured\n * instance writing to a different place. The bootstrap leaves the sink empty (its\n * messages are deliberately silent); once the real CLI is running, they go here.\n */\nsetManagedDiagnosticReporter((level, message) => {\n if (level === \"warn\") consola.warn(message)\n else if (level === \"info\") consola.info(message)\n else consola.debug(message)\n})\n\nprocess.on(\"unhandledRejection\", (error) => {\n consola.error(\"Unhandled rejection:\", error)\n})\n\nprocess.on(\"uncaughtException\", (error) => {\n consola.error(\"Uncaught exception:\", error)\n process.exit(1)\n})\n\nconst version = getPackageVersion()\n\n// Always surface the running version on stderr so crash reports\n// identify which build is in use. Suppressed only for `--version`\n// (citty's built-in handler prints just the bare version number, and\n// a banner above it is redundant). `-v` is NOT special-cased: citty\n// doesn't treat it as `--version`, so users typing `-v` still get\n// the banner — which is the closest thing to \"show me the version\".\nconst argv = process.argv.slice(2)\nconst isVersionFlag = argv.includes(\"--version\")\n// Suppress the banner for the internal hooks: their stdout/stderr is consumed by\n// Claude Code (the Stop hook's stderr is the block message; the prompt-submit\n// hook's stdout is injected context), so it must stay clean. `internal-stop-review`\n// and `internal-plan-review` are detached/background with no consumer, but stay\n// quiet for the same reason.\nconst isInternalHook =\n argv[0] === \"internal-stop-hook\"\n || argv[0] === \"internal-prompt-submit\"\n || argv[0] === \"internal-stop-review\"\n || argv[0] === \"internal-plan-review\"\n || argv[0] === \"internal-rebrief\"\n || argv[0] === \"internal-session-bind\"\n || argv[0] === \"internal-workspace-header\"\n || argv[0] === \"internal-artifact-open\"\n || argv[0] === \"internal-first-mate-guard\"\n || argv[0] === \"internal-worker-guard\"\n || argv[0] === \"internal-fast-dispatch-guard\"\n || argv[0] === \"internal-aic-status\"\nif (!isVersionFlag && !isInternalHook) {\n consola.info(`github-router v${version}`)\n}\n\n/**\n * Subcommands are LAZY THUNKS, not static imports.\n *\n * citty resolves only the named entry (`_findSubCommand` → `resolveValue`), so\n * running one subcommand no longer evaluates the other 17 module graphs. That\n * matters because several of these are per-turn Claude Code hooks — the\n * `UserPromptSubmit`, `Stop` and `PreToolUse` handlers registered by\n * `src/claude.ts` each spawn a FRESH `node dist/main.js <sub>` process, so any\n * import-time cost lands in the user's interactive loop on every prompt.\n * `internal-worker-guard`, for instance, needs three modules but was loading\n * the entire claude/serve/MCP graph plus the Pi vendor runtime.\n *\n * Safe because the import-time side effects in this codebase\n * (`assertMcpToolSurfaceConsistent` in `server.ts`, the tree-sitter grammar\n * preload, the worktree/session exit-handler registrations, the first-mate\n * allowlist assertion) are reachable ONLY from claude/codex/serve/start, and\n * all four reach all of them independently — no subcommand relies on another's\n * module being loaded. Verified by an AST walk of the runtime import graph.\n *\n * `--help` is the one path that still resolves everything: citty's\n * `renderUsage` reads each subcommand's meta to print descriptions. That is\n * not latency-critical, and `resolveHelpTarget` below resolves only the single\n * subcommand when help is scoped to one.\n */\nconst main = defineCommand({\n meta: {\n name: \"github-router\",\n version,\n description:\n \"A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.\",\n },\n subCommands: {\n auth: () => import(\"./auth\").then((m) => m.auth),\n start: () => import(\"./start\").then((m) => m.start),\n claude: () => import(\"./claude\").then((m) => m.claude),\n codex: () => import(\"./codex\").then((m) => m.codex),\n pi: () => import(\"./pi\").then((m) => m.pi),\n workiq: () => import(\"./workiq\").then((m) => m.workiq),\n serve: () => import(\"./serve\").then((m) => m.serve),\n models: () => import(\"./models\").then((m) => m.models),\n \"check-usage\": () => import(\"./check-usage\").then((m) => m.checkUsage),\n index: () => import(\"./index-cmd\").then((m) => m.indexCmd),\n debug: () => import(\"./debug\").then((m) => m.debug),\n update: () => import(\"./update\").then((m) => m.update),\n \"internal-stop-hook\": () =>\n import(\"./internal-stop-hook\").then((m) => m.internalStopHook),\n \"internal-prompt-submit\": () =>\n import(\"./internal-prompt-submit\").then((m) => m.internalPromptSubmit),\n \"internal-stop-review\": () =>\n import(\"./internal-stop-review\").then((m) => m.internalStopReview),\n \"internal-plan-review\": () =>\n import(\"./internal-plan-review\").then((m) => m.internalPlanReview),\n \"internal-rebrief\": () =>\n import(\"./internal-rebrief\").then((m) => m.internalRebrief),\n \"internal-session-bind\": () =>\n import(\"./internal-session-bind\").then((m) => m.internalSessionBind),\n \"internal-workspace-header\": () =>\n import(\"./internal-workspace-header\").then(\n (m) => m.internalWorkspaceHeader,\n ),\n \"internal-artifact-open\": () =>\n import(\"./internal-artifact-open\").then((m) => m.internalArtifactOpen),\n \"internal-first-mate-guard\": () =>\n import(\"./internal-first-mate-guard\").then(\n (m) => m.internalFirstMateGuard,\n ),\n \"internal-worker-guard\": () =>\n import(\"./internal-worker-guard\").then((m) => m.internalWorkerGuard),\n \"internal-fast-dispatch-guard\": () =>\n import(\"./internal-fast-dispatch-guard\").then((m) => m.internalFastDispatchGuard),\n \"internal-max-dispatch-guard\": () =>\n import(\"./internal-max-dispatch-guard\").then((m) => m.internalMaxDispatchGuard),\n \"internal-aic-status\": () =>\n import(\"./internal-aic-status\").then((m) => m.internalAicStatus),\n },\n})\n\n/**\n * Print usage ourselves and let the process DRAIN, instead of letting citty\n * hard-exit while stdout is still queued.\n *\n * citty's `runMain` calls `process.exit(0)` immediately after `showUsage`\n * resolves (citty 0.2.2 dist/index.mjs:389; 0.1.6 does the same, so this is\n * not an upgrade regression). On Windows a PIPE-backed stdout is async, so the\n * usage text is still in a libuv handle when the hard exit tears the loop down\n * and node aborts:\n * `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), file src\\win\\async.c`\n * — after printing the help the user asked for.\n *\n * `--version` is unaffected: citty's version branch has no `process.exit()`\n * and drains naturally. That asymmetry is why this survived so long — the\n * cheapest smoke test passes while every `--help` path aborts. Node 22 on\n * Windows tolerated it; node 24 does not, and release.yml publishes with\n * node 24.\n *\n * Forcing `_handle.setBlocking(true)` first was tried and does NOT fix it —\n * the abort still reproduces through a pipe. The only reliable fix is to not\n * hard-exit at all, which is the same resolution the internal hooks already\n * use (`process.exitCode = 0`, never `process.exit()`), guarded by the tests\n * in this repo's internal-hooks-crash suite.\n *\n * Only the help path is intercepted; everything else still goes through citty\n * so argument parsing, subcommand dispatch and error handling stay citty's.\n */\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"])\n\nasync function resolveHelpTarget(): Promise<{\n cmd: Parameters<typeof showUsage>[0]\n parent?: Parameters<typeof showUsage>[1]\n}> {\n // First non-flag token is the subcommand, matching citty's own resolution\n // for our single-level command tree.\n const name = argv.find((arg) => !arg.startsWith(\"-\"))\n const table = main.subCommands as Record<string, unknown> | undefined\n const entry = name ? table?.[name] : undefined\n if (!entry) return { cmd: main }\n // citty allows a subcommand to be a value, a promise, or a thunk.\n const resolved = typeof entry === \"function\" ? await entry() : await entry\n return {\n cmd: resolved as Parameters<typeof showUsage>[0],\n parent: main as Parameters<typeof showUsage>[1],\n }\n}\n\nif (argv.some((arg) => HELP_FLAGS.has(arg))) {\n const { cmd, parent } = await resolveHelpTarget()\n await showUsage(cmd, parent)\n // Signal success WITHOUT tearing the loop down — node drains stdout and\n // exits 0 on its own.\n process.exitCode = 0\n} else {\n await runMain(main)\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,8BAA8B,OAAO,YAAY;CAC/C,IAAI,UAAU,QAAQ,QAAQ,KAAK,OAAO;MACrC,IAAI,UAAU,QAAQ,QAAQ,KAAK,OAAO;MAC1C,QAAQ,MAAM,OAAO;A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AAK;CAG/B,OAAO;EACL,KAFe,OAAO,UAAU,aAAa,MAAM,MAAM,IAAI,MAAM;EAGnE,QAAQ;CACV;AACF;AAEA,IAAI,KAAK,MAAM,QAAQ,WAAW,IAAI,GAAG,CAAC,GAAG;CAC3C,MAAM,EAAE,KAAK,WAAW,MAAM,kBAAkB;CAChD,MAAM,UAAU,KAAK,MAAM;CAG3B,QAAQ,WAAW;AACrB,OACE,MAAM,QAAQ,IAAI"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-Dnq4iVD6.js";
|
|
2
2
|
// src/lib/mcp-workspace-header.ts
|
|
3
3
|
/** Header the per-session MCP headersHelper emits, carrying the calling Claude
|
|
4
4
|
* session's working directory. The /mcp handler uses it as the default
|
|
@@ -16,4 +16,4 @@ function buildWorkspaceHeaderHelperCommand(invocation) {
|
|
|
16
16
|
}
|
|
17
17
|
export { buildWorkspaceHeaderHelperCommand as n, buildWorkspaceHeaderJson as r, MCP_WORKSPACE_HEADER as t };
|
|
18
18
|
|
|
19
|
-
//# sourceMappingURL=mcp-workspace-header-
|
|
19
|
+
//# sourceMappingURL=mcp-workspace-header-Bpa4BId8.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-workspace-header-
|
|
1
|
+
{"version":3,"file":"mcp-workspace-header-Bpa4BId8.js","names":[],"sources":["../src/lib/mcp-workspace-header.ts"],"sourcesContent":["import { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** Header the per-session MCP headersHelper emits, carrying the calling Claude\n * session's working directory. The /mcp handler uses it as the default\n * `workspace` for repo-scoped tools so a machine-wide `serve` targets the\n * active repo, not the proxy launch cwd. */\nexport const MCP_WORKSPACE_HEADER = \"X-GH-Workspace\"\n\n/** stdout JSON the headersHelper prints; Claude merges it into the connection\n * headers. `cwd` is the helper's own process cwd = the session's project dir. */\nexport function buildWorkspaceHeaderJson(cwd: string): string {\n return JSON.stringify({ [MCP_WORKSPACE_HEADER]: cwd })\n}\n\n/** Command string Claude runs as the headersHelper. */\nexport function buildWorkspaceHeaderHelperCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-workspace-header\")\n}\n"],"mappings":";;;;;;AAMA,MAAa,uBAAuB;;;AAIpC,SAAgB,yBAAyB,KAAqB;CAC5D,OAAO,KAAK,UAAU,GAAG,uBAAuB,IAAI,CAAC;AACvD;;AAGA,SAAgB,kCAAkC,YAAoC;CACpF,OAAO,iBAAiB,YAAY,2BAA2B;AACjE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as ensurePaths } from "./paths-
|
|
2
|
-
import { m as getModels, r as setupGitHubToken, t as setupCopilotToken } from "./token-
|
|
1
|
+
import { i as ensurePaths } from "./paths-DeFmYJhO.js";
|
|
2
|
+
import { m as getModels, r as setupGitHubToken, t as setupCopilotToken } from "./token-CKPOBdO0.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import consola from "consola";
|
|
5
5
|
// src/models.ts
|
|
@@ -159,4 +159,4 @@ function formatTokens(n) {
|
|
|
159
159
|
}
|
|
160
160
|
export { models };
|
|
161
161
|
|
|
162
|
-
//# sourceMappingURL=models-
|
|
162
|
+
//# sourceMappingURL=models-BDV-YLf2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models-B6nH1sS6.js","names":[],"sources":["../src/models.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupCopilotToken, setupGitHubToken, type StopCopilotTokenRefresh } from \"./lib/token\"\nimport { getModels, type Model } from \"./services/copilot/get-models\"\n\nexport const models = defineCommand({\n meta: {\n name: \"models\",\n description:\n \"List available GitHub Copilot models and their capabilities. Pass an optional pattern to filter (case-insensitive substring match on id, name, vendor, family).\",\n },\n args: {\n pattern: {\n type: \"positional\",\n required: false,\n description:\n \"Substring to filter models by (matches id, name, vendor, or family).\",\n },\n json: {\n type: \"boolean\",\n default: false,\n description: \"Emit raw JSON instead of the pretty layout.\",\n },\n },\n async run({ args }) {\n await ensurePaths()\n await setupGitHubToken()\n // One-shot command: stop the background refresh loop before returning, so\n // the timer is never what decides whether this process exits. (It is also\n // `unref()`d, so this is belt-and-braces — but ownership stays explicit.)\n let stopRefresh: StopCopilotTokenRefresh | undefined\n try {\n stopRefresh = await setupCopilotToken()\n } catch (err) {\n consola.error(\"Failed to obtain Copilot token:\", err)\n process.exit(1)\n }\n\n try {\n let catalog: Awaited<ReturnType<typeof getModels>>\n try {\n catalog = await getModels()\n } catch (err) {\n consola.error(\"Failed to fetch Copilot model catalog:\", err)\n process.exit(1)\n }\n\n const all = catalog.data\n const pattern = args.pattern?.toString().trim()\n const filtered = pattern ? filterModels(all, pattern) : all\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(filtered, null, 2)}\\n`)\n return\n }\n\n if (filtered.length === 0) {\n consola.warn(\n `No models matched \"${pattern}\". ${all.length} models available — try a different substring or run without an argument to list everything.`,\n )\n process.exit(1)\n }\n\n const grouped = groupByVendor(filtered)\n const lines: Array<string> = []\n const header = pattern\n ? `${filtered.length}/${all.length} models match \"${pattern}\"`\n : `${all.length} models available`\n lines.push(header)\n lines.push(\"\")\n for (const [vendor, list] of grouped) {\n lines.push(`▾ ${vendor} (${list.length})`)\n for (const model of list) {\n lines.push(...formatModel(model))\n }\n lines.push(\"\")\n }\n process.stdout.write(lines.join(\"\\n\"))\n } finally {\n stopRefresh?.()\n }\n },\n})\n\nfunction filterModels(models: Array<Model>, pattern: string): Array<Model> {\n const needle = pattern.toLowerCase()\n return models.filter((m) => {\n const haystack = [\n m.id,\n m.name,\n m.vendor,\n m.capabilities.family,\n m.capabilities.type,\n m.model_picker_category ?? \"\",\n ]\n .join(\" \")\n .toLowerCase()\n return haystack.includes(needle)\n })\n}\n\nfunction groupByVendor(models: Array<Model>): Array<[string, Array<Model>]> {\n const map = new Map<string, Array<Model>>()\n for (const m of models) {\n const key = m.vendor || \"(unknown vendor)\"\n const bucket = map.get(key)\n if (bucket) bucket.push(m)\n else map.set(key, [m])\n }\n // Stable vendor order: alphabetical for predictability.\n return [...map.entries()].sort(([a], [b]) => a.localeCompare(b))\n}\n\n/**\n * Test-only exports. Not part of the public CLI surface — kept out of\n * the default export so they don't show up in IDE autocomplete on\n * `import { ... } from \"github-router/models\"` consumers.\n */\nexport const __testing = { filterModels, groupByVendor, formatModel, formatTokens }\n\nfunction formatModel(model: Model): Array<string> {\n const lines: Array<string> = []\n const tags: Array<string> = []\n if (model.preview) tags.push(\"preview\")\n if (model.is_chat_default) tags.push(\"chat-default\")\n if (model.is_chat_fallback) tags.push(\"chat-fallback\")\n if (model.billing?.is_premium) tags.push(\"premium\")\n if (model.billing?.restricted_to?.length) {\n tags.push(`restricted:${model.billing.restricted_to.join(\"/\")}`)\n }\n if (model.policy && model.policy.state !== \"enabled\") {\n tags.push(`policy:${model.policy.state}`)\n }\n const tagStr = tags.length > 0 ? ` [${tags.join(\", \")}]` : \"\"\n lines.push(` • ${model.id}${tagStr}`)\n if (model.name && model.name !== model.id) {\n lines.push(` name: ${model.name}`)\n }\n const meta: Array<string> = [\n `family: ${model.capabilities.family}`,\n `type: ${model.capabilities.type}`,\n ]\n if (model.capabilities.tokenizer) {\n meta.push(`tokenizer: ${model.capabilities.tokenizer}`)\n }\n if (model.version) {\n meta.push(`version: ${model.version}`)\n }\n lines.push(` ${meta.join(\" · \")}`)\n\n const limits = model.capabilities.limits\n const limitParts: Array<string> = []\n if (limits) {\n if (limits.max_context_window_tokens) {\n limitParts.push(`ctx ${formatTokens(limits.max_context_window_tokens)}`)\n } else if (limits.max_prompt_tokens) {\n limitParts.push(`prompt ${formatTokens(limits.max_prompt_tokens)}`)\n }\n if (limits.max_output_tokens) {\n limitParts.push(`out ${formatTokens(limits.max_output_tokens)}`)\n }\n if (\n limits.max_non_streaming_output_tokens\n && limits.max_non_streaming_output_tokens !== limits.max_output_tokens\n ) {\n limitParts.push(\n `out-non-stream ${formatTokens(limits.max_non_streaming_output_tokens)}`,\n )\n }\n if (limits.max_inputs) limitParts.push(`inputs ${limits.max_inputs}`)\n if (limits.vision?.max_prompt_images) {\n limitParts.push(`images ${limits.vision.max_prompt_images}`)\n }\n }\n if (limitParts.length > 0) {\n lines.push(` limits: ${limitParts.join(\" · \")}`)\n }\n\n const supports = model.capabilities.supports\n const supportFlags: Array<string> = []\n if (supports) {\n if (supports.tool_calls) supportFlags.push(\"tools\")\n if (supports.parallel_tool_calls) supportFlags.push(\"parallel-tools\")\n if (supports.streaming) supportFlags.push(\"streaming\")\n if (supports.vision) supportFlags.push(\"vision\")\n if (supports.structured_outputs) supportFlags.push(\"structured-outputs\")\n if (supports.dimensions) supportFlags.push(\"dimensions\")\n if (supports.adaptive_thinking) {\n const min = supports.min_thinking_budget\n const max = supports.max_thinking_budget\n const range\n = min !== undefined && max !== undefined\n ? `(${formatTokens(min)}-${formatTokens(max)})`\n : \"\"\n supportFlags.push(`adaptive-thinking${range}`)\n }\n if (supports.reasoning_effort && supports.reasoning_effort.length > 0) {\n supportFlags.push(`reasoning:${supports.reasoning_effort.join(\"/\")}`)\n }\n }\n if (supportFlags.length > 0) {\n lines.push(` supports: ${supportFlags.join(\", \")}`)\n }\n\n if (model.supported_endpoints && model.supported_endpoints.length > 0) {\n lines.push(` endpoints: ${model.supported_endpoints.join(\", \")}`)\n }\n if (model.billing) {\n const billParts: Array<string> = []\n if (model.billing.is_premium) billParts.push(\"premium\")\n if (typeof model.billing.multiplier === \"number\") {\n billParts.push(`×${model.billing.multiplier}`)\n }\n if (billParts.length > 0) {\n lines.push(` billing: ${billParts.join(\" \")}`)\n }\n }\n return lines\n}\n\n/**\n * Format a token count in a compact human-readable form: `1024` →\n * `1k`, `4096` → `4k`, `131072` → `128k`, `1048576` → `1M`. Prefer\n * binary multiples (mebi, kibi) since Claude Code / Copilot context\n * windows are reported in binary units (`1M context` = 1024 × 1024\n * tokens). Fall back to decimal (`64k` for `64000`) when the value\n * is a clean decimal multiple but not binary.\n */\nfunction formatTokens(n: number): string {\n if (n >= 1_048_576 && n % 1_048_576 === 0) return `${n / 1_048_576}M`\n if (n >= 1024 && n % 1024 === 0) return `${n / 1024}k`\n if (n >= 1_000_000 && n % 1_000_000 === 0) return `${n / 1_000_000}M`\n if (n >= 1000 && n % 1000 === 0) return `${n / 1000}k`\n return `${n}`\n}\n"],"mappings":";;;;;AAOA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aACE;CACJ;CACA,MAAM;EACJ,SAAS;GACP,MAAM;GACN,UAAU;GACV,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,MAAM,YAAY;EAClB,MAAM,iBAAiB;EAIvB,IAAI;EACJ,IAAI;GACF,cAAc,MAAM,kBAAkB;EACxC,SAAS,KAAK;GACZ,QAAQ,MAAM,mCAAmC,GAAG;GACpD,QAAQ,KAAK,CAAC;EAChB;EAEA,IAAI;GACF,IAAI;GACJ,IAAI;IACF,UAAU,MAAM,UAAU;GAC5B,SAAS,KAAK;IACZ,QAAQ,MAAM,0CAA0C,GAAG;IAC3D,QAAQ,KAAK,CAAC;GAChB;GAEA,MAAM,MAAM,QAAQ;GACpB,MAAM,UAAU,KAAK,SAAS,SAAS,CAAC,CAAC,KAAK;GAC9C,MAAM,WAAW,UAAU,aAAa,KAAK,OAAO,IAAI;GAExD,IAAI,KAAK,MAAM;IACb,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,GAAG;IAC7D;GACF;GAEA,IAAI,SAAS,WAAW,GAAG;IACzB,QAAQ,KACN,sBAAsB,QAAQ,KAAK,IAAI,OAAO,6FAChD;IACA,QAAQ,KAAK,CAAC;GAChB;GAEA,MAAM,UAAU,cAAc,QAAQ;GACtC,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AAUA,SAAS,aAAa,GAAmB;CACvC,IAAI,KAAK,WAAa,IAAI,YAAc,GAAG,OAAO,GAAG,IAAI,QAAU;CACnE,IAAI,KAAK,QAAQ,IAAI,SAAS,GAAG,OAAO,GAAG,IAAI,KAAK;CACpD,IAAI,KAAK,OAAa,IAAI,QAAc,GAAG,OAAO,GAAG,IAAI,IAAU;CACnE,IAAI,KAAK,OAAQ,IAAI,QAAS,GAAG,OAAO,GAAG,IAAI,IAAK;CACpD,OAAO,GAAG;AACZ"}
|
|
1
|
+
{"version":3,"file":"models-BDV-YLf2.js","names":[],"sources":["../src/models.ts"],"sourcesContent":["import { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { ensurePaths } from \"./lib/paths\"\nimport { setupCopilotToken, setupGitHubToken, type StopCopilotTokenRefresh } from \"./lib/token\"\nimport { getModels, type Model } from \"./services/copilot/get-models\"\n\nexport const models = defineCommand({\n meta: {\n name: \"models\",\n description:\n \"List available GitHub Copilot models and their capabilities. Pass an optional pattern to filter (case-insensitive substring match on id, name, vendor, family).\",\n },\n args: {\n pattern: {\n type: \"positional\",\n required: false,\n description:\n \"Substring to filter models by (matches id, name, vendor, or family).\",\n },\n json: {\n type: \"boolean\",\n default: false,\n description: \"Emit raw JSON instead of the pretty layout.\",\n },\n },\n async run({ args }) {\n await ensurePaths()\n await setupGitHubToken()\n // One-shot command: stop the background refresh loop before returning, so\n // the timer is never what decides whether this process exits. (It is also\n // `unref()`d, so this is belt-and-braces — but ownership stays explicit.)\n let stopRefresh: StopCopilotTokenRefresh | undefined\n try {\n stopRefresh = await setupCopilotToken()\n } catch (err) {\n consola.error(\"Failed to obtain Copilot token:\", err)\n process.exit(1)\n }\n\n try {\n let catalog: Awaited<ReturnType<typeof getModels>>\n try {\n catalog = await getModels()\n } catch (err) {\n consola.error(\"Failed to fetch Copilot model catalog:\", err)\n process.exit(1)\n }\n\n const all = catalog.data\n const pattern = args.pattern?.toString().trim()\n const filtered = pattern ? filterModels(all, pattern) : all\n\n if (args.json) {\n process.stdout.write(`${JSON.stringify(filtered, null, 2)}\\n`)\n return\n }\n\n if (filtered.length === 0) {\n consola.warn(\n `No models matched \"${pattern}\". ${all.length} models available — try a different substring or run without an argument to list everything.`,\n )\n process.exit(1)\n }\n\n const grouped = groupByVendor(filtered)\n const lines: Array<string> = []\n const header = pattern\n ? `${filtered.length}/${all.length} models match \"${pattern}\"`\n : `${all.length} models available`\n lines.push(header)\n lines.push(\"\")\n for (const [vendor, list] of grouped) {\n lines.push(`▾ ${vendor} (${list.length})`)\n for (const model of list) {\n lines.push(...formatModel(model))\n }\n lines.push(\"\")\n }\n process.stdout.write(lines.join(\"\\n\"))\n } finally {\n stopRefresh?.()\n }\n },\n})\n\nfunction filterModels(models: Array<Model>, pattern: string): Array<Model> {\n const needle = pattern.toLowerCase()\n return models.filter((m) => {\n const haystack = [\n m.id,\n m.name,\n m.vendor,\n m.capabilities.family,\n m.capabilities.type,\n m.model_picker_category ?? \"\",\n ]\n .join(\" \")\n .toLowerCase()\n return haystack.includes(needle)\n })\n}\n\nfunction groupByVendor(models: Array<Model>): Array<[string, Array<Model>]> {\n const map = new Map<string, Array<Model>>()\n for (const m of models) {\n const key = m.vendor || \"(unknown vendor)\"\n const bucket = map.get(key)\n if (bucket) bucket.push(m)\n else map.set(key, [m])\n }\n // Stable vendor order: alphabetical for predictability.\n return [...map.entries()].sort(([a], [b]) => a.localeCompare(b))\n}\n\n/**\n * Test-only exports. Not part of the public CLI surface — kept out of\n * the default export so they don't show up in IDE autocomplete on\n * `import { ... } from \"github-router/models\"` consumers.\n */\nexport const __testing = { filterModels, groupByVendor, formatModel, formatTokens }\n\nfunction formatModel(model: Model): Array<string> {\n const lines: Array<string> = []\n const tags: Array<string> = []\n if (model.preview) tags.push(\"preview\")\n if (model.is_chat_default) tags.push(\"chat-default\")\n if (model.is_chat_fallback) tags.push(\"chat-fallback\")\n if (model.billing?.is_premium) tags.push(\"premium\")\n if (model.billing?.restricted_to?.length) {\n tags.push(`restricted:${model.billing.restricted_to.join(\"/\")}`)\n }\n if (model.policy && model.policy.state !== \"enabled\") {\n tags.push(`policy:${model.policy.state}`)\n }\n const tagStr = tags.length > 0 ? ` [${tags.join(\", \")}]` : \"\"\n lines.push(` • ${model.id}${tagStr}`)\n if (model.name && model.name !== model.id) {\n lines.push(` name: ${model.name}`)\n }\n const meta: Array<string> = [\n `family: ${model.capabilities.family}`,\n `type: ${model.capabilities.type}`,\n ]\n if (model.capabilities.tokenizer) {\n meta.push(`tokenizer: ${model.capabilities.tokenizer}`)\n }\n if (model.version) {\n meta.push(`version: ${model.version}`)\n }\n lines.push(` ${meta.join(\" · \")}`)\n\n const limits = model.capabilities.limits\n const limitParts: Array<string> = []\n if (limits) {\n if (limits.max_context_window_tokens) {\n limitParts.push(`ctx ${formatTokens(limits.max_context_window_tokens)}`)\n } else if (limits.max_prompt_tokens) {\n limitParts.push(`prompt ${formatTokens(limits.max_prompt_tokens)}`)\n }\n if (limits.max_output_tokens) {\n limitParts.push(`out ${formatTokens(limits.max_output_tokens)}`)\n }\n if (\n limits.max_non_streaming_output_tokens\n && limits.max_non_streaming_output_tokens !== limits.max_output_tokens\n ) {\n limitParts.push(\n `out-non-stream ${formatTokens(limits.max_non_streaming_output_tokens)}`,\n )\n }\n if (limits.max_inputs) limitParts.push(`inputs ${limits.max_inputs}`)\n if (limits.vision?.max_prompt_images) {\n limitParts.push(`images ${limits.vision.max_prompt_images}`)\n }\n }\n if (limitParts.length > 0) {\n lines.push(` limits: ${limitParts.join(\" · \")}`)\n }\n\n const supports = model.capabilities.supports\n const supportFlags: Array<string> = []\n if (supports) {\n if (supports.tool_calls) supportFlags.push(\"tools\")\n if (supports.parallel_tool_calls) supportFlags.push(\"parallel-tools\")\n if (supports.streaming) supportFlags.push(\"streaming\")\n if (supports.vision) supportFlags.push(\"vision\")\n if (supports.structured_outputs) supportFlags.push(\"structured-outputs\")\n if (supports.dimensions) supportFlags.push(\"dimensions\")\n if (supports.adaptive_thinking) {\n const min = supports.min_thinking_budget\n const max = supports.max_thinking_budget\n const range\n = min !== undefined && max !== undefined\n ? `(${formatTokens(min)}-${formatTokens(max)})`\n : \"\"\n supportFlags.push(`adaptive-thinking${range}`)\n }\n if (supports.reasoning_effort && supports.reasoning_effort.length > 0) {\n supportFlags.push(`reasoning:${supports.reasoning_effort.join(\"/\")}`)\n }\n }\n if (supportFlags.length > 0) {\n lines.push(` supports: ${supportFlags.join(\", \")}`)\n }\n\n if (model.supported_endpoints && model.supported_endpoints.length > 0) {\n lines.push(` endpoints: ${model.supported_endpoints.join(\", \")}`)\n }\n if (model.billing) {\n const billParts: Array<string> = []\n if (model.billing.is_premium) billParts.push(\"premium\")\n if (typeof model.billing.multiplier === \"number\") {\n billParts.push(`×${model.billing.multiplier}`)\n }\n if (billParts.length > 0) {\n lines.push(` billing: ${billParts.join(\" \")}`)\n }\n }\n return lines\n}\n\n/**\n * Format a token count in a compact human-readable form: `1024` →\n * `1k`, `4096` → `4k`, `131072` → `128k`, `1048576` → `1M`. Prefer\n * binary multiples (mebi, kibi) since Claude Code / Copilot context\n * windows are reported in binary units (`1M context` = 1024 × 1024\n * tokens). Fall back to decimal (`64k` for `64000`) when the value\n * is a clean decimal multiple but not binary.\n */\nfunction formatTokens(n: number): string {\n if (n >= 1_048_576 && n % 1_048_576 === 0) return `${n / 1_048_576}M`\n if (n >= 1024 && n % 1024 === 0) return `${n / 1024}k`\n if (n >= 1_000_000 && n % 1_000_000 === 0) return `${n / 1_000_000}M`\n if (n >= 1000 && n % 1000 === 0) return `${n / 1000}k`\n return `${n}`\n}\n"],"mappings":";;;;;AAOA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aACE;CACJ;CACA,MAAM;EACJ,SAAS;GACP,MAAM;GACN,UAAU;GACV,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,SAAS;GACT,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,MAAM,YAAY;EAClB,M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AAA,IAC3B,IAAI,aAAa,GAAG,EAAE,GAAG,aAAa,GAAG,EAAE,KAC3C;GACN,aAAa,KAAK,oBAAoB,OAAO;EAC/C;EACA,IAAI,SAAS,oBAAoB,SAAS,iBAAiB,SAAS,GAClE,aAAa,KAAK,aAAa,SAAS,iBAAiB,KAAK,GAAG,GAAG;CAExE;CACA,IAAI,aAAa,SAAS,GACxB,MAAM,KAAK,mBAAmB,aAAa,KAAK,IAAI,GAAG;CAGzD,IAAI,MAAM,uBAAuB,MAAM,oBAAoB,SAAS,GAClE,MAAM,KAAK,oBAAoB,MAAM,oBAAoB,KAAK,IAAI,GAAG;CAEvE,IAAI,MAAM,SAAS;EACjB,MAAM,YAA2B,CAAC;EAClC,IAAI,MAAM,QAAQ,YAAY,UAAU,KAAK,SAAS;EACtD,IAAI,OAAO,MAAM,QAAQ,eAAe,UACtC,UAAU,KAAK,IAAI,MAAM,QAAQ,YAAY;EAE/C,IAAI,UAAU,SAAS,GACrB,MAAM,KAAK,kBAAkB,UAAU,KAAK,GAAG,GAAG;CAEtD;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAS,aAAa,GAAmB;CACvC,IAAI,KAAK,WAAa,IAAI,YAAc,GAAG,OAAO,GAAG,IAAI,QAAU;CACnE,IAAI,KAAK,QAAQ,IAAI,SAAS,GAAG,OAAO,GAAG,IAAI,KAAK;CACpD,IAAI,KAAK,OAAa,IAAI,QAAc,GAAG,OAAO,GAAG,IAAI,IAAU;CACnE,IAAI,KAAK,OAAQ,IAAI,QAAS,GAAG,OAAO,GAAG,IAAI,IAAK;CACpD,OAAO,GAAG;AACZ"}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// src/lib/managed-install/npm-env.ts
|
|
2
|
+
/**
|
|
3
|
+
* Environment scrubbing for npm children we spawn.
|
|
4
|
+
*
|
|
5
|
+
* `npm_config_*` in the environment is *configuration*, not advice: npm's
|
|
6
|
+
* `loadEnv` (`lib/index.js` in `@npmcli/config`) turns every non-empty
|
|
7
|
+
* `npm_config_<key>` into the same setting a `.npmrc` line or a CLI flag would
|
|
8
|
+
* produce, with the lowest precedence but full effect. Measured against npm
|
|
9
|
+
* 11.20.0 on a fresh prefix with one pinned dependency:
|
|
10
|
+
*
|
|
11
|
+
* | inherited env | result of `npm install` |
|
|
12
|
+
* |-----------------------------------|--------------------------------|
|
|
13
|
+
* | `npm_config_global=true` | installs into `<prefix>/lib/node_modules`, `node_modules/` stays empty |
|
|
14
|
+
* | `npm_config_dry_run=true` | exit 0, **nothing installed** |
|
|
15
|
+
* | `npm_config_workspaces=true` | `ENOWORKSPACES`, exit 0, nothing installed |
|
|
16
|
+
* | `npm_config_omit=optional` | platform packages silently missing (`@vscode/ripgrep-darwin-arm64`), so `rg` is unresolvable at run time |
|
|
17
|
+
* | `npm_config_location=global` | as `global` |
|
|
18
|
+
* | `npm_config_prefix=/elsewhere` | as `global` for symlinked trees |
|
|
19
|
+
* | `npm_config_allow_scripts=<pkg>` | `EALLOWSCRIPTS` (see below) |
|
|
20
|
+
*
|
|
21
|
+
* Every one of those is a *successful* npm run. A managed install that trusted
|
|
22
|
+
* the exit code would publish an empty or incomplete payload and then point
|
|
23
|
+
* `current.json` at it — the class of failure that only shows up as "the router
|
|
24
|
+
* is broken on that one machine".
|
|
25
|
+
*
|
|
26
|
+
* `npm_config_allow_scripts` is the sharper case and is handled separately by
|
|
27
|
+
* every caller as `""` (the rule at `src/lib/server-setup.ts:1838`): a non-empty
|
|
28
|
+
* env-sourced allow-scripts value makes npm throw `EALLOWSCRIPTS` for any
|
|
29
|
+
* project-scoped install. Emptying it is not a policy change — npm treats `''`
|
|
30
|
+
* as "not set" and falls through to the `.npmrc` cascade, which is where the
|
|
31
|
+
* operator put it.
|
|
32
|
+
*
|
|
33
|
+
* So: keep the *connection* and *identity* settings a user legitimately needs
|
|
34
|
+
* (registry, proxies, TLS, auth tokens, cache location, retry budget), drop
|
|
35
|
+
* everything that changes *what gets installed where*. Anything dropped is
|
|
36
|
+
* stated in the debug log so a support thread can see why an install behaved
|
|
37
|
+
* differently from the user's shell.
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* `npm_config_*` keys we keep.
|
|
41
|
+
*
|
|
42
|
+
* Note what is deliberately ABSENT: `prefix`, `global`, `location`, `omit`,
|
|
43
|
+
* `include`, `dry_run`, `workspaces`, `link`, `install_links`, `only`,
|
|
44
|
+
* `production`, `before`, `allow_scripts`, `loglevel`. Those are the ones that
|
|
45
|
+
* redirect, skip, or refuse the install.
|
|
46
|
+
*/
|
|
47
|
+
const KEEP_SIMPLE_KEYS = /* @__PURE__ */ new Set([
|
|
48
|
+
"_auth",
|
|
49
|
+
"always_auth",
|
|
50
|
+
"ca",
|
|
51
|
+
"cafile",
|
|
52
|
+
"cache",
|
|
53
|
+
"cert",
|
|
54
|
+
"fetch_retries",
|
|
55
|
+
"fetch_retry_maxtimeout",
|
|
56
|
+
"fetch_retry_mintimeout",
|
|
57
|
+
"fetch_timeout",
|
|
58
|
+
"globalconfig",
|
|
59
|
+
"https_proxy",
|
|
60
|
+
"http_proxy",
|
|
61
|
+
"key",
|
|
62
|
+
"local_address",
|
|
63
|
+
"maxsockets",
|
|
64
|
+
"no_proxy",
|
|
65
|
+
"noproxy",
|
|
66
|
+
"otp",
|
|
67
|
+
"proxy",
|
|
68
|
+
"registry",
|
|
69
|
+
"strict_ssl",
|
|
70
|
+
"userconfig"
|
|
71
|
+
]);
|
|
72
|
+
/**
|
|
73
|
+
* `//host/path/:_authToken` — a nerf-dart key. npm stores per-registry
|
|
74
|
+
* credentials under this shape and `loadEnv` deliberately does not normalize it,
|
|
75
|
+
* so it must be matched as a prefix rather than a name.
|
|
76
|
+
*/
|
|
77
|
+
const NERF_DART_RE = /^\/\/.*:(_authToken|_auth|username|_password|email)$/i;
|
|
78
|
+
/**
|
|
79
|
+
* Build a child env for an npm invocation.
|
|
80
|
+
*
|
|
81
|
+
* `overrides` are applied last and win, so a caller can pin `npm_config_registry`
|
|
82
|
+
* for Pi (`resolvePiRegistry()`) without fighting the cascade.
|
|
83
|
+
*
|
|
84
|
+
* The result fully REPLACES the child env (`runCommandCapture` uses
|
|
85
|
+
* `opts.env ?? process.env`), so anything not copied here is genuinely absent
|
|
86
|
+
* rather than merged back in from the parent.
|
|
87
|
+
*/
|
|
88
|
+
function buildNpmEnv(base = process.env, overrides = {}) {
|
|
89
|
+
const env = {};
|
|
90
|
+
const dropped = [];
|
|
91
|
+
const kept = [];
|
|
92
|
+
for (const [key, value] of Object.entries(base)) {
|
|
93
|
+
if (value === void 0) continue;
|
|
94
|
+
if (!/^npm_config_/i.test(key)) {
|
|
95
|
+
env[key] = value;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (value === "") {
|
|
99
|
+
env[key] = value;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const bare = key.slice(11).toLowerCase();
|
|
103
|
+
if (NERF_DART_RE.test(key.slice(11)) || KEEP_SIMPLE_KEYS.has(bare)) {
|
|
104
|
+
env[key] = value;
|
|
105
|
+
kept.push(key);
|
|
106
|
+
} else dropped.push(key);
|
|
107
|
+
}
|
|
108
|
+
env.npm_config_allow_scripts = "";
|
|
109
|
+
for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
|
|
110
|
+
else env[key] = value;
|
|
111
|
+
return {
|
|
112
|
+
env,
|
|
113
|
+
dropped,
|
|
114
|
+
kept
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Whether a managed install may run at all in this process.
|
|
119
|
+
*
|
|
120
|
+
* `GH_ROUTER_NO_MANAGED_INSTALL` is the user's off switch (documented in the
|
|
121
|
+
* plan); `ghRouterNoManagedInstall()` is the only place that reads it so the
|
|
122
|
+
* bootstrap, the CLI, and the tests cannot disagree about its spelling.
|
|
123
|
+
*/
|
|
124
|
+
function managedInstallDisabled(env = process.env) {
|
|
125
|
+
const raw = env.GH_ROUTER_NO_MANAGED_INSTALL?.trim().toLowerCase();
|
|
126
|
+
return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
|
|
127
|
+
}
|
|
128
|
+
export { managedInstallDisabled as n, buildNpmEnv as t };
|
|
129
|
+
|
|
130
|
+
//# sourceMappingURL=npm-env-H60tX76c.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"npm-env-H60tX76c.js","names":[],"sources":["../src/lib/managed-install/npm-env.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAM,eAAe;;;;;;;;;;;AAoBrB,SAAgB,YACd,OAA0B,QAAQ,KAClC,YAA+B,CAAC,GACb;CACnB,MAAM,MAAyB,CAAC;CAChC,MAAM,UAAyB,CAAC;CAChC,MAAM,OAAsB,CAAC;CAE7B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ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