github-router 0.3.382 → 0.3.383
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/ado-tools-Ddv910Zl.js +1 -0
- package/dist/{aic-ledger-6GKI28nY.js → aic-ledger-Bz87EuHl.js} +3 -3
- package/dist/{aic-ledger-6GKI28nY.js.map → aic-ledger-Bz87EuHl.js.map} +1 -1
- package/dist/{aic-statusline-settings-wLL1l_Z6.js → aic-statusline-settings-dkVZbpRL.js} +2 -2
- package/dist/{aic-statusline-settings-wLL1l_Z6.js.map → aic-statusline-settings-dkVZbpRL.js.map} +1 -1
- package/dist/{attribution-settings-BhQmS2u9.js → attribution-settings-BcPiSoZe.js} +10 -10
- package/dist/{attribution-settings-BhQmS2u9.js.map → attribution-settings-BcPiSoZe.js.map} +1 -1
- package/dist/{auth-5TKcQbbH.js → auth-D9eTY_W6.js} +3 -3
- package/dist/{auth-5TKcQbbH.js.map → auth-D9eTY_W6.js.map} +1 -1
- package/dist/bin.js +21 -4
- package/dist/bin.js.map +1 -1
- package/dist/bluebird-client-CLXs7q-X.js +1 -0
- package/dist/{bluebird-client-BasIdv5J.js → bluebird-client-bykMZyn1.js} +2 -2
- package/dist/{bluebird-client-BasIdv5J.js.map → bluebird-client-bykMZyn1.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-DM39fdel.js → check-usage-BBaD35u4.js} +4 -4
- package/dist/{check-usage-DM39fdel.js.map → check-usage-BBaD35u4.js.map} +1 -1
- package/dist/{claude-B9Mw8x0M.js → claude-DOKuv2zZ.js} +28 -28
- package/dist/{claude-B9Mw8x0M.js.map → claude-DOKuv2zZ.js.map} +1 -1
- package/dist/{claude-md-injection-DiokMV4p.js → claude-md-injection-BadtN0-I.js} +4 -4
- package/dist/{claude-md-injection-DiokMV4p.js.map → claude-md-injection-BadtN0-I.js.map} +1 -1
- package/dist/{codex-DiybqRAO.js → codex-Dw_eBfXW.js} +9 -9
- package/dist/{codex-DiybqRAO.js.map → codex-Dw_eBfXW.js.map} +1 -1
- package/dist/{copilot-discount-DM98PuAF.js → copilot-discount-BSDefQRW.js} +2 -2
- package/dist/{copilot-discount-DM98PuAF.js.map → copilot-discount-BSDefQRW.js.map} +1 -1
- package/dist/{debug-Df0Kuzi3.js → debug-B8eRYH-c.js} +2 -2
- package/dist/{debug-Df0Kuzi3.js.map → debug-B8eRYH-c.js.map} +1 -1
- package/dist/engine-DPtLOUuj.js +1 -0
- package/dist/{exec-BC0MAnoA.js → exec-oCtz_dXO.js} +22 -5
- package/dist/exec-oCtz_dXO.js.map +1 -0
- package/dist/{gate-discovery-DCdds1gg.js → gate-discovery-DE_KTX2p.js} +6 -6
- package/dist/{gate-discovery-DCdds1gg.js.map → gate-discovery-DE_KTX2p.js.map} +1 -1
- package/dist/{get-copilot-usage-BZ6t2hFZ.js → get-copilot-usage-Dh9u7WeP.js} +2 -2
- package/dist/{get-copilot-usage-BZ6t2hFZ.js.map → get-copilot-usage-Dh9u7WeP.js.map} +1 -1
- package/dist/hooks.mjs +21 -4
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-DsK6VFs8.js → index-cmd-C4womtOS.js} +5 -5
- package/dist/{index-cmd-DsK6VFs8.js.map → index-cmd-C4womtOS.js.map} +1 -1
- package/dist/{internal-aic-status-CUZ7-trf.js → internal-aic-status-DSO2sR5u.js} +4 -4
- package/dist/{internal-aic-status-CUZ7-trf.js.map → internal-aic-status-DSO2sR5u.js.map} +1 -1
- package/dist/{internal-artifact-open-DRBg1PpV.js → internal-artifact-open-dlgqWieq.js} +2 -2
- package/dist/{internal-artifact-open-DRBg1PpV.js.map → internal-artifact-open-dlgqWieq.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js → internal-fast-dispatch-guard-5nCNht5y.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js.map → internal-fast-dispatch-guard-5nCNht5y.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-D6-Ees_6.js → internal-fast-dispatch-guard-DHm96Bj_.js} +1 -1
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js → internal-first-mate-guard-Bb9Stjy-.js} +3 -3
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js.map → internal-first-mate-guard-Bb9Stjy-.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BijeVpi9.js → internal-first-mate-guard-D6HMd9Iz.js} +1 -1
- package/dist/{internal-max-dispatch-guard-sjBGijoa.js → internal-max-dispatch-guard-C8kq4WNV.js} +2 -2
- package/dist/{internal-max-dispatch-guard-sjBGijoa.js.map → internal-max-dispatch-guard-C8kq4WNV.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-CXaZ5TTR.js → internal-max-dispatch-guard-CI17mrDJ.js} +1 -1
- package/dist/{internal-plan-review-bzqGNdtw.js → internal-plan-review-Bdga9wVP.js} +3 -3
- package/dist/{internal-plan-review-bzqGNdtw.js.map → internal-plan-review-Bdga9wVP.js.map} +1 -1
- package/dist/{internal-prompt-submit-DBmCOUfy.js → internal-prompt-submit-DKlHlcvK.js} +2 -2
- package/dist/{internal-prompt-submit-C_QigwLP.js → internal-prompt-submit-Daswp8ro.js} +5 -5
- package/dist/{internal-prompt-submit-C_QigwLP.js.map → internal-prompt-submit-Daswp8ro.js.map} +1 -1
- package/dist/{internal-rebrief-CjaEXHIo.js → internal-rebrief-D8O1J-_J.js} +5 -5
- package/dist/{internal-rebrief-CjaEXHIo.js.map → internal-rebrief-D8O1J-_J.js.map} +1 -1
- package/dist/{internal-session-bind-BL6hFRLO.js → internal-session-bind-0hQFrcWu.js} +2 -2
- package/dist/{internal-session-bind-BL6hFRLO.js.map → internal-session-bind-0hQFrcWu.js.map} +1 -1
- package/dist/{internal-stop-hook-CcXuDASI.js → internal-stop-hook-C3lLh-HY.js} +6 -6
- package/dist/{internal-stop-hook-CcXuDASI.js.map → internal-stop-hook-C3lLh-HY.js.map} +1 -1
- package/dist/{internal-stop-review-y8zjpK_3.js → internal-stop-review-Bnmzcqx5.js} +2 -2
- package/dist/{internal-stop-review-y8zjpK_3.js.map → internal-stop-review-Bnmzcqx5.js.map} +1 -1
- package/dist/{internal-worker-guard-DdyYBZR0.js → internal-worker-guard-LcPxDlbx.js} +2 -2
- package/dist/{internal-worker-guard-DdyYBZR0.js.map → internal-worker-guard-LcPxDlbx.js.map} +1 -1
- package/dist/{internal-workspace-header-BMKbO8yX.js → internal-workspace-header-BH53hBXO.js} +2 -2
- package/dist/{internal-workspace-header-BMKbO8yX.js.map → internal-workspace-header-BH53hBXO.js.map} +1 -1
- package/dist/{lifecycle-COZhARmE.js → lifecycle-BmoqtVj3.js} +2 -2
- package/dist/{lifecycle-COZhARmE.js.map → lifecycle-BmoqtVj3.js.map} +1 -1
- package/dist/lifecycle-CcNNfKbr.js +1 -0
- package/dist/lifecycle-CrImfxCd.js +1 -0
- package/dist/{lifecycle-BlC_kzNt.js → lifecycle-CwxOsp-U.js} +3 -3
- package/dist/{lifecycle-BlC_kzNt.js.map → lifecycle-CwxOsp-U.js.map} +1 -1
- package/dist/main.js +25 -25
- package/dist/{mcp-workspace-header-Bpa4BId8.js → mcp-workspace-header-lb7GV78v.js} +2 -2
- package/dist/{mcp-workspace-header-Bpa4BId8.js.map → mcp-workspace-header-lb7GV78v.js.map} +1 -1
- package/dist/{models-BDV-YLf2.js → models-BTCnhBCQ.js} +3 -3
- package/dist/{models-BDV-YLf2.js.map → models-BTCnhBCQ.js.map} +1 -1
- package/dist/{optional-DGAeyguL.js → optional-LUQJI6Vx.js} +216 -16
- package/dist/optional-LUQJI6Vx.js.map +1 -0
- package/dist/{orchestration-Bto5Nc1Y.js → orchestration-C_hyBL90.js} +3 -3
- package/dist/{orchestration-Bto5Nc1Y.js.map → orchestration-C_hyBL90.js.map} +1 -1
- package/dist/origin-9bOjyzvK.js +1 -0
- package/dist/{origin-BXtpcKP9.js → origin-B6GChVyp.js} +2 -2
- package/dist/{origin-BXtpcKP9.js.map → origin-B6GChVyp.js.map} +1 -1
- package/dist/{paths-DeFmYJhO.js → paths-CVXqt2tC.js} +3 -3
- package/dist/{paths-DeFmYJhO.js.map → paths-CVXqt2tC.js.map} +1 -1
- package/dist/paths-JIusmD6L.js +1 -0
- package/dist/{peer-mcp-personas-Ckbn70c5.js → peer-mcp-personas-Dgog_ZJ8.js} +16 -16
- package/dist/{peer-mcp-personas-Ckbn70c5.js.map → peer-mcp-personas-Dgog_ZJ8.js.map} +1 -1
- package/dist/{pi-D9IbxlSj.js → pi-BZhnf1kx.js} +17 -17
- package/dist/{pi-D9IbxlSj.js.map → pi-BZhnf1kx.js.map} +1 -1
- package/dist/{pi-version-check-BeBB0Ny9.js → pi-version-check-BRt9XFLj.js} +4 -4
- package/dist/{pi-version-check-BeBB0Ny9.js.map → pi-version-check-BRt9XFLj.js.map} +1 -1
- package/dist/pi-version-check-SH1X9u4H.js +1 -0
- package/dist/{plan-review-hook-D_yyjOgO.js → plan-review-hook-Dx3suYmK.js} +4 -4
- package/dist/{plan-review-hook-D_yyjOgO.js.map → plan-review-hook-Dx3suYmK.js.map} +1 -1
- package/dist/{provision-BY5pXtSG.js → provision-A1YSravb.js} +6 -6
- package/dist/{provision-BY5pXtSG.js.map → provision-A1YSravb.js.map} +1 -1
- package/dist/{rerank-cross-encoder-BhjImuwG.js → rerank-cross-encoder-uqRu-LOe.js} +2 -2
- package/dist/{rerank-cross-encoder-BhjImuwG.js.map → rerank-cross-encoder-uqRu-LOe.js.map} +1 -1
- package/dist/{self-invocation-Dnq4iVD6.js → self-invocation-CayD3y72.js} +2 -2
- package/dist/{self-invocation-Dnq4iVD6.js.map → self-invocation-CayD3y72.js.map} +1 -1
- package/dist/{serve-DPPh7goh.js → serve-Cv3S3PFR.js} +17 -17
- package/dist/{serve-DPPh7goh.js.map → serve-Cv3S3PFR.js.map} +1 -1
- package/dist/{server-setup-CVMUKERN.js → server-setup--CYeBD-Z.js} +12 -12
- package/dist/{server-setup-CVMUKERN.js.map → server-setup--CYeBD-Z.js.map} +1 -1
- package/dist/{service-backend-BdhWVRSz.js → service-backend-EgwiO_K-.js} +6 -6
- package/dist/{service-backend-BdhWVRSz.js.map → service-backend-EgwiO_K-.js.map} +1 -1
- package/dist/{start-B7z2Mg2B.js → start-CA0JsO56.js} +5 -5
- package/dist/{start-B7z2Mg2B.js.map → start-CA0JsO56.js.map} +1 -1
- package/dist/{static-context-pack-DdQpWwQN.js → static-context-pack-BIru_SKh.js} +3 -3
- package/dist/{static-context-pack-DdQpWwQN.js.map → static-context-pack-BIru_SKh.js.map} +1 -1
- package/dist/{stop-gate-hook-DBOj0TqL.js → stop-gate-hook-Ba_RvZAj.js} +4 -4
- package/dist/{stop-gate-hook-DBOj0TqL.js.map → stop-gate-hook-Ba_RvZAj.js.map} +1 -1
- package/dist/{stop-gate-policy-Bp2wGh_W.js → stop-gate-policy-gW0a0hds.js} +3 -3
- package/dist/{stop-gate-policy-Bp2wGh_W.js.map → stop-gate-policy-gW0a0hds.js.map} +1 -1
- package/dist/{token-Ygd7D32L.js → token-BCzbNu8O.js} +3 -3
- package/dist/{token-Ygd7D32L.js.map → token-BCzbNu8O.js.map} +1 -1
- package/dist/{token-CKPOBdO0.js → token-CxKcs3I_.js} +2 -2
- package/dist/{token-CKPOBdO0.js.map → token-CxKcs3I_.js.map} +1 -1
- package/dist/{update-T1L7yFon.js → update-CM1yUCJR.js} +4 -4
- package/dist/{update-T1L7yFon.js.map → update-CM1yUCJR.js.map} +1 -1
- package/dist/update-Cpg-tbJG.js +1 -0
- package/dist/{update-fEgWTrIx.js → update-ZqCRVU0a.js} +4 -4
- package/dist/{update-fEgWTrIx.js.map → update-ZqCRVU0a.js.map} +1 -1
- package/dist/{worker-dispatch-DBWKTMda.js → worker-dispatch-DHZAfPO2.js} +2 -2
- package/dist/{worker-dispatch-DBWKTMda.js.map → worker-dispatch-DHZAfPO2.js.map} +1 -1
- package/dist/{workiq-D5b7xlbr.js → workiq-CRBVCUA4.js} +2 -2
- package/dist/{workiq-D5b7xlbr.js.map → workiq-CRBVCUA4.js.map} +1 -1
- package/dist/{workiq-tools-3K9WKiQ2.js → workiq-tools-BsoHfdYi.js} +1 -1
- package/package.json +1 -1
- package/dist/ado-tools-CNEWS1kF.js +0 -1
- package/dist/bluebird-client-BvoMTmEv.js +0 -1
- package/dist/engine-DCR1lSsw.js +0 -1
- package/dist/exec-BC0MAnoA.js.map +0 -1
- package/dist/lifecycle-BOjgq9_l.js +0 -1
- package/dist/lifecycle-NQvr4flt.js +0 -1
- package/dist/optional-DGAeyguL.js.map +0 -1
- package/dist/origin-DbFUCiGp.js +0 -1
- package/dist/paths-CquOjytP.js +0 -1
- package/dist/pi-version-check-D5RvdLsG.js +0 -1
- package/dist/update-CB21YRKz.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as parseBoolEnv, c as runCommandCapture, s as resolveExecutable, u as runCommandVoid } from "./exec-
|
|
1
|
+
import { a as parseBoolEnv, c as runCommandCapture, s as resolveExecutable, u as runCommandVoid } from "./exec-oCtz_dXO.js";
|
|
2
2
|
import { t as withInstallLock } from "./update-lock-BmXx6QaR.js";
|
|
3
3
|
import { t as getPackageVersion } from "./version-CTqwKr26.js";
|
|
4
4
|
import consola from "consola";
|
|
@@ -333,10 +333,10 @@ async function runSelfUpdate(opts) {
|
|
|
333
333
|
if (!opts.selfUpdate) return;
|
|
334
334
|
if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return;
|
|
335
335
|
try {
|
|
336
|
-
const { classifyOrigin } = await import("./origin-
|
|
336
|
+
const { classifyOrigin } = await import("./origin-9bOjyzvK.js");
|
|
337
337
|
const origin = await classifyOrigin();
|
|
338
338
|
if (origin.origin === "npx" || origin.origin === "bunx") {
|
|
339
|
-
const { scheduleBackgroundSelfInstall } = await import("./update-
|
|
339
|
+
const { scheduleBackgroundSelfInstall } = await import("./update-Cpg-tbJG.js");
|
|
340
340
|
const detail = await scheduleBackgroundSelfInstall({ quiet: true });
|
|
341
341
|
consola.debug(`self-update: managed path: ${detail}`);
|
|
342
342
|
return;
|
|
@@ -548,4 +548,4 @@ function refreshPiInBackground(opts) {
|
|
|
548
548
|
}
|
|
549
549
|
export { isPiNewer as a, refreshPiInBackground as c, checkClaudeVersion as d, updateClaude as f, getInstalledPiVersion as i, resolvePiRegistry as l, PI_MIN_VERSION as n, meetsPiMinVersion as o, PI_NPM_PACKAGE as r, piRegistryArgs as s, PI_DEFAULT_REGISTRY as t, runSelfUpdate as u };
|
|
550
550
|
|
|
551
|
-
//# sourceMappingURL=pi-version-check-
|
|
551
|
+
//# sourceMappingURL=pi-version-check-BRt9XFLj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi-version-check-BeBB0Ny9.js","names":["NPM_PACKAGE","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow","getLatestVersion","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow"],"sources":["../src/lib/claude-version-check.ts","../src/lib/self-update.ts","../src/lib/pi-version-check.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport {\n resolveExecutable,\n runCommandCapture,\n runCommandVoid,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\n\nconst NPM_PACKAGE = \"@anthropic-ai/claude-code\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst CLAUDE_VERSION_TIMEOUT_MS = 3000\nconst NPM_INSTALL_TIMEOUT_MS = 120_000 // 2 min — npm install can be slow on cold caches\n\ninterface VersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-update-check\",\n )\n}\n\n/**\n * Read the throttle cache. Returns null on missing/corrupt file —\n * triggers a fresh check.\n */\nasync function readCache(): Promise<VersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as VersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: VersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n // Throttle cache is best-effort — a write failure means we'll re-check\n // on next launch. Not worth surfacing.\n consola.debug(\"Failed to write claude version-check cache:\", err)\n }\n}\n\n/** Check if it's been more than THROTTLE_HOURS since the last check. */\nfunction shouldCheckNow(cache: VersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `claude` version. Returns null if claude is not\n * on PATH or the version probe fails (e.g. older versions that don't\n * support `--version` cleanly).\n *\n * Windows-safe: `claude` is a `.cmd` shim that `execFile` cannot launch\n * directly. We resolve it to an absolute path (excluding the cwd, so a\n * planted `claude.cmd` in an untrusted repo can't run) and invoke it\n * through the shared exec helper.\n */\nasync function getInstalledVersion(): Promise<string | null> {\n const claudePath = resolveExecutable(\"claude\")\n if (!claudePath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [claudePath, \"--version\"],\n { timeoutMs: CLAUDE_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n // Output shape: \"2.1.139 (Claude Code)\\n\"\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/**\n * Fetch the latest version of @anthropic-ai/claude-code from the npm\n * registry. Returns null on network failure / npm unavailable.\n *\n * Windows-safe: `npm` is `npm.cmd`; resolved to an absolute path\n * (excluding cwd) before invocation.\n */\nasync function getLatestVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (only the leading X.Y.Z, no\n * pre-release / metadata handling — sufficient for npm-published\n * stable releases). Returns true if `latest` is strictly higher than\n * `installed`.\n */\nexport function isNewer(installed: string | null, latest: string | null): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\nexport interface VersionCheckResult {\n /** Whether claude is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-claude\"\n}\n\n/**\n * Run a version check (subject to throttle). Side-effect: updates the\n * throttle cache. Returns the comparison result.\n */\nexport async function checkClaudeVersion(opts: {\n noCheck?: boolean\n /** Bypass the throttle (used when the check is the user's main intent) */\n force?: boolean\n} = {}): Promise<VersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n return {\n installed: cache?.installedVersion !== null,\n installedVersion: cache?.installedVersion ?? null,\n latestVersion: cache?.latestVersion ?? null,\n needsUpdate: isNewer(\n cache?.installedVersion ?? null,\n cache?.latestVersion ?? null,\n ),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-claude\",\n }\n }\n\n const latestVersion = await getLatestVersion()\n // Update cache regardless of whether latest fetched (so we still\n // throttle if npm is offline).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isNewer(installedVersion, latestVersion),\n skipped: false,\n }\n}\n\n/**\n * Heuristic: did `claude update` fail because the subcommand does not\n * exist (a build predating `claude update`), as opposed to a transient\n * update error? We only npm-fall-back on this specific signal — falling\n * back on any failure would install a conflicting npm copy on\n * native-installer machines.\n *\n * Matches the usage/Commander-style \"unknown command\" messages CLIs emit\n * for an unrecognized subcommand. Deliberately narrow.\n */\nexport function looksLikeUnknownUpdateCommand(output: string): boolean {\n return /unknown command|unknown subcommand|unrecognized (sub)?command|invalid command|command not found|is not a (known|valid) command/i.test(\n output,\n )\n}\n\n/**\n * Update Claude Code to the latest version.\n *\n * Strategy (decided in the plan, corrected after a real-world false\n * negative): run `claude update` directly — it respects the user's\n * actual install method (native installer or npm), so it never creates a\n * conflicting second install, and it is NOT blocked by the\n * `DISABLE_AUTOUPDATER` the proxy sets in the *child* env (this runs from\n * the proxy's own env, and `claude update` is a manual command\n * unaffected by that flag).\n *\n * Only if `claude update` reports the subcommand is unknown (a build too\n * old to have it) do we fall back to `npm install -g\n * @anthropic-ai/claude-code@latest` with a VISIBLE warning. The earlier\n * `claude --help` capability probe was removed: it timed out / mismatched\n * on slow cold starts and wrongly forced the npm path every launch,\n * creating dual npm-global + native installs.\n *\n * Serialized across concurrent proxies via an install lock. Throws on\n * failure — the caller decides whether to warn and continue.\n */\nexport interface UpdateClaudeDeps {\n resolveExecutable: typeof resolveExecutable\n runCommandCapture: typeof runCommandCapture\n runCommandVoid: typeof runCommandVoid\n withInstallLock: typeof withInstallLock\n}\n\nexport async function updateClaude(\n latestVersion: string,\n deps: Partial<UpdateClaudeDeps> = {},\n): Promise<void> {\n const _resolve = deps.resolveExecutable ?? resolveExecutable\n const _capture = deps.runCommandCapture ?? runCommandCapture\n const _void = deps.runCommandVoid ?? runCommandVoid\n const _lock = deps.withInstallLock ?? withInstallLock\n\n const claudePath = _resolve(\"claude\")\n if (!claudePath) throw new Error(\"claude not found on PATH\")\n\n const ran = await _lock(\"claude-update.lock\", async () => {\n consola.info(`Updating Claude Code to ${latestVersion} via \\`claude update\\`...`)\n // Capture (not inherit) so we can detect an unknown-command signal;\n // echo the output afterward so the user still sees what happened.\n const { code, stdout, stderr } = await _capture([claudePath, \"update\"], {\n timeoutMs: NPM_INSTALL_TIMEOUT_MS,\n })\n const combined = `${stdout}${stderr}`\n const trimmed = combined.trim()\n if (trimmed) process.stdout.write(trimmed.endsWith(\"\\n\") ? trimmed : `${trimmed}\\n`)\n\n if (code === 0) {\n consola.success(`Claude Code updated to ${latestVersion}`)\n return\n }\n\n if (!looksLikeUnknownUpdateCommand(combined)) {\n throw new Error(`\\`claude update\\` exited with code ${code}`)\n }\n\n // Fallback: npm. Only reachable on installs too old to have\n // `claude update` at all.\n const npmPath = _resolve(\"npm\")\n if (!npmPath) {\n throw new Error(\n \"this Claude Code build predates `claude update` and npm is not on PATH; \" +\n `update manually: npm install -g ${NPM_PACKAGE}@latest`,\n )\n }\n consola.warn(\n \"This Claude Code build predates `claude update`; falling back to \" +\n `\\`npm install -g ${NPM_PACKAGE}@latest\\`.`,\n )\n const { code: npmCode, stderr: npmStderr } = await _void(\n [npmPath, \"install\", \"-g\", `${NPM_PACKAGE}@latest`, \"--silent\"],\n { timeoutMs: NPM_INSTALL_TIMEOUT_MS },\n )\n if (npmCode !== 0) {\n throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`)\n }\n consola.success(`${NPM_PACKAGE} updated to ${latestVersion}`)\n })\n\n if (!ran) {\n consola.debug(\"Claude Code update already in progress in another process; skipping.\")\n }\n}\n","/**\n * Self-update for the `github-router` proxy.\n *\n * The proxy is a *running* process, so updating its own global install\n * in place (`npm install -g github-router@latest`) deletes/overwrites\n * files the OS holds open — on Windows that fails deterministically\n * (EPERM/EBUSY) and can corrupt the install. So we never install in\n * place: when a newer version exists we spawn a **detached updater that\n * waits for this process to exit**, then installs. The update takes\n * effect on the next launch — no re-exec, no restart prompt.\n *\n * Best-effort throughout: every failure is swallowed to debug/warn and\n * never blocks startup. The startup probe is bounded and the install is\n * off the critical path (detached), so even a blackholed network can't\n * delay the proxy from serving.\n */\n\nimport { spawn } from \"node:child_process\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { isNewer } from \"./claude-version-check\"\nimport {\n parseBoolEnv,\n resolveExecutable,\n runCommandCapture,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\nimport { getPackageVersion } from \"./version\"\n\n// The published, installable package is the UNSCOPED name. The scoped\n// `@animeshkundu/github-router` is GitHub-Packages-only and must NOT be\n// used for `npm view` / `npm install` here.\nconst NPM_PACKAGE = \"github-router\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\n\ninterface SelfUpdateCache {\n checkedAt: string\n installedVersion: string | null\n latestVersion: string | null\n}\n\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n // Distinct from the Claude Code check's `last-update-check` so the\n // two throttles don't cross-suppress.\n \"last-self-update-check\",\n )\n}\n\nasync function readCache(): Promise<SelfUpdateCache | null> {\n try {\n const parsed = JSON.parse(\n await fs.readFile(cacheFilePath(), \"utf8\"),\n ) as SelfUpdateCache\n if (typeof parsed.checkedAt !== \"string\") return null\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: SelfUpdateCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 0o600 })\n } catch (err) {\n consola.debug(\"Failed to write self-update cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: SelfUpdateCache | null): boolean {\n if (!cache) return true\n const last = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(last)) return true\n return (Date.now() - last) / 1000 / 3600 >= THROTTLE_HOURS\n}\n\nasync function getLatestVersion(npmPath: string): Promise<string | null> {\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Spawn a detached process that waits for THIS proxy (pid) to exit,\n * then runs `npm install -g <spec>`. Fully detached and unref'd so it\n * outlives the proxy; output discarded.\n *\n * The waiter is a tiny inline Node script (Node is guaranteed present —\n * the proxy runs on it) that polls `process.kill(pid, 0)` until the\n * parent is gone, then execs npm. This avoids the Windows file-lock by\n * never touching the global install while the proxy holds it open.\n *\n * Shared by the proxy self-update (`github-router@latest`) and the Pi\n * background refresh (`@earendil-works/pi-coding-agent@<version>`):\n * both must update a global install without delaying startup, holding\n * shutdown, or racing each other (callers hold `withInstallLock`\n * before queueing).\n */\nexport function queueDetachedGlobalInstall(\n npmPath: string,\n spec: string,\n extraArgs: readonly string[] = [],\n): void {\n const parentPid = process.pid\n const installArgs = [\"install\", \"-g\", spec, ...extraArgs]\n // Inline waiter: poll until the parent disappears, then install.\n const waiter = `\n const pid = ${parentPid};\n const { spawn } = require(\"node:child_process\");\n function alive() { try { process.kill(pid, 0); return true } catch { return false } }\n const timer = setInterval(() => {\n if (alive()) return;\n clearInterval(timer);\n const args = [...${JSON.stringify(installArgs)}, \"--silent\"];\n const isWin = process.platform === \"win32\";\n const child = spawn(${JSON.stringify(npmPath)}, args, {\n stdio: \"ignore\", windowsHide: true, shell: isWin, detached: !isWin,\n });\n child.on(\"error\", () => process.exit(0));\n child.on(\"exit\", () => process.exit(0));\n // Safety: never hang forever.\n setTimeout(() => process.exit(0), 180000).unref();\n }, 500);\n // Safety cap on the wait itself (e.g. extremely long sessions still\n // eventually give up rather than leak the waiter).\n setTimeout(() => { clearInterval(timer); process.exit(0); }, 24 * 3600 * 1000).unref();\n `.trim()\n\n const child = spawn(process.execPath, [\"-e\", waiter], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n })\n child.unref()\n}\n\nfunction spawnDetachedUpdater(npmPath: string): void {\n queueDetachedGlobalInstall(npmPath, `${NPM_PACKAGE}@latest`)\n}\n\nexport interface RunSelfUpdateOpts {\n /** From `args[\"self-update\"]` (default true). */\n selfUpdate: boolean\n /** Bypass the throttle (used by tests / explicit forcing). */\n force?: boolean\n}\n\n/**\n * Probe npm for a newer `github-router` and, if found, queue a detached\n * post-exit update. Returns quickly; never throws. Call AFTER the\n * server is listening so the bounded probe can't delay binding.\n */\nexport async function runSelfUpdate(opts: RunSelfUpdateOpts): Promise<void> {\n if (!opts.selfUpdate) return\n if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return\n\n try {\n // WHICH update mechanism depends on who owns the tree we are running from,\n // and getting this wrong is not a style question:\n //\n // - `npx`/`bunx`: the tree is a disposable cache entry. `npm install -g`\n // from here would create a SECOND install the user never asked for (and\n // the next `npx` would still re-extract, so it would not even help). The\n // managed install is the whole point of this feature.\n // - `npm-global`: user decision 4 — that tree is its own owner. Keep the\n // detached post-exit waiter verbatim.\n // - `managed`: the bootstrap (and `github-router update`) maintain it; doing\n // it again here would double-schedule on every launch.\n // - `source`: never. A dev checkout must run its own code and must not gain\n // a global install as a side effect.\n //\n // `classifyOrigin` is imported lazily: it pulls `exec` and the managed state\n // module, and this function runs from every entry point including the tiny\n // bootstrap-adjacent paths.\n const { classifyOrigin } = await import(\"./managed-install/origin\")\n const origin = await classifyOrigin()\n\n if (origin.origin === \"npx\" || origin.origin === \"bunx\") {\n const { scheduleBackgroundSelfInstall } = await import(\"./managed-install/update\")\n const detail = await scheduleBackgroundSelfInstall({ quiet: true })\n consola.debug(`self-update: managed path: ${detail}`)\n return\n }\n if (origin.origin !== \"npm-global\") {\n consola.debug(`self-update: skipped for origin ${origin.origin} (${origin.detail})`)\n return\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) return\n\n const installed = getPackageVersion()\n if (installed === \"unknown\") return // can't compare; skip silently\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return // npm not on PATH; skip\n\n const latest = await getLatestVersion(npmPath)\n // Write the throttle BEFORE acting so concurrent/next launches back\n // off even if the install is still settling (optimistic lock).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion: installed,\n latestVersion: latest,\n })\n if (!latest || !isNewer(installed, latest)) return\n\n const queued = await withInstallLock(\"self-update.lock\", async () => {\n spawnDetachedUpdater(npmPath)\n })\n if (queued) {\n consola.info(\n `github-router ${installed} → ${latest} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Self-update check failed:\", err)\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { resolveExecutable, runCommandCapture } from \"./exec\"\nimport { queueDetachedGlobalInstall } from \"./self-update\"\nimport { withInstallLock } from \"./update-lock\"\n\nexport const PI_NPM_PACKAGE = \"@earendil-works/pi-coding-agent\"\n/**\n * Minimum Pi version the `pi` launcher supports.\n *\n * The floor is pinned to the first release whose `before_agent_start` event\n * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).\n * The generated extension's prompt hook stands down for non-user events using\n * that field, and without it the hook would fire on subagent and system turns\n * the user never typed, which is a wrong brief rather than a missing one.\n * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the\n * gate actually runs: the install probe, the background refresh, and this floor\n * check all sit inside `--update-check` (default on), so `--no-update-check`\n * (documented for offline/CI) skips the floor as well. That path is still\n * fail-closed rather than silently wrong: the generated extension's own shape\n * probe sees the missing `messageType`, warns once with the fix, and injects\n * nothing.\n */\nexport const PI_MIN_VERSION = \"1.3.0\"\n\n/**\n * Registry used for the PI PACKAGE ONLY.\n *\n * Pi must come from a registry that actually carries it. A corporate npm mirror\n * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and\n * the launcher then fail-closes on an upgrade command the user cannot satisfy\n * (their `npm install -g` resolves through the same lagging mirror). Pointing\n * the Pi probe and install at npmjs by default keeps the floor reachable;\n * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the\n * package. Everything else this repo installs still resolves through the user's\n * configured registry.\n */\nexport const PI_DEFAULT_REGISTRY = \"https://registry.npmjs.org/\"\n\n/**\n * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`\n * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a\n * warning otherwise, so a typo degrades to the working default rather than\n * bricking the launcher.\n */\nexport function resolvePiRegistry(): string {\n const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim()\n if (!raw) return PI_DEFAULT_REGISTRY\n if (!/^https?:\\/\\//i.test(raw)) {\n consola.warn(\n `Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`,\n )\n return PI_DEFAULT_REGISTRY\n }\n return raw.endsWith(\"/\") ? raw : `${raw}/`\n}\n\n/** `npm` args that pin an operation to the resolved Pi registry. */\nexport function piRegistryArgs(registry: string = resolvePiRegistry()): string[] {\n return [`--registry=${registry}`]\n}\n\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst PI_VERSION_TIMEOUT_MS = 3000\n\ninterface PiVersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-pi-update-check\",\n )\n}\n\nasync function readCache(): Promise<PiVersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as PiVersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: PiVersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n consola.debug(\"Failed to write pi version-check cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: PiVersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `pi` version. Returns null if pi is not on PATH\n * or the version probe fails.\n *\n * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path\n * (excluding the cwd) before invocation via the shared exec helper.\n */\nexport async function getInstalledPiVersion(): Promise<string | null> {\n const piPath = resolveExecutable(\"pi\")\n if (!piPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [piPath, \"--version\"],\n { timeoutMs: PI_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/** Fetch the latest Pi version from npm. Null on network/npm failure. */\nasync function getLatestPiVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [\n npmPath,\n \"view\",\n PI_NPM_PACKAGE,\n \"version\",\n \"--silent\",\n ...piRegistryArgs(),\n ],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (leading X.Y.Z only). True when\n * `latest` is strictly higher than `installed`.\n */\nexport function isPiNewer(\n installed: string | null,\n latest: string | null,\n): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */\nexport function meetsPiMinVersion(version: string | null): boolean {\n if (!version) return false\n return !isPiNewer(version, PI_MIN_VERSION)\n}\n\nexport interface PiVersionCheckResult {\n /** Whether pi is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** True if the installed version is below the supported floor */\n needsMinUpgrade: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-pi\"\n}\n\n/** Run a version check (subject to throttle). Side-effect: updates the cache. */\nexport async function checkPiVersion(opts: {\n noCheck?: boolean\n force?: boolean\n} = {}): Promise<PiVersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n const installedVersion = cache?.installedVersion ?? null\n const latestVersion = cache?.latestVersion ?? null\n return {\n installed: installedVersion !== null,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledPiVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: true,\n skipped: true,\n skipReason: \"no-pi\",\n }\n }\n\n const latestVersion = await getLatestPiVersion()\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: false,\n }\n}\n\n/*\n * `updatePi` / `ensurePiInstalled` used to live here: they ran\n * `npm install -g @earendil-works/pi-coding-agent@<v>` and then re-probed PATH.\n * They were removed deliberately, not refactored.\n *\n * Two reasons, both observed:\n *\n * 1. **They mutate a tree the user owns.** `-g` is not ours (user decision 4).\n * Rewriting it to satisfy `PI_MIN_VERSION` made the launcher's floor check a\n * silent `npm install -g` on every below-floor machine, which can break an\n * unrelated project pinned to the older Pi.\n * 2. **`-g` cannot be updated while it is in use.** On Windows that is `EPERM`;\n * everywhere it needs the detached post-exit waiter. The managed install\n * avoids the whole problem by publishing a new directory and swapping a file\n * pointer, so the below-floor repair path is now\n * `managed-install/pi-command.ts` → `ensureManagedInstall` (see\n * `resolvePiCommand`), and the explicit form is `github-router update --pi`.\n *\n * The user-owned `pi` still keeps its own channel: `refreshPiInBackground`\n * below queues the same detached `-g` install it always did.\n */\n\n/**\n * Fire-and-forget freshness refresh for a healthy Pi install. Never\n * blocks launch and never throws: on the throttled schedule it probes\n * npm for a newer Pi and, when one exists, queues a DETACHED post-exit\n * install (same pattern as the proxy self-update) so neither startup\n * nor the running session nor shutdown ever waits on npm. The\n * cross-process install lock serializes against concurrent launches;\n * every failure degrades to a debug log.\n *\n * Deliberately never touches a below-floor install: the floor is\n * enforced foreground by the launcher (fail-closed), and a background\n * task must not change what the running session validated.\n */\nexport function refreshPiInBackground(opts: { autoUpdate: boolean }): void {\n if (!opts.autoUpdate) return\n void (async () => {\n try {\n const cache = await readCache()\n if (!shouldCheckNow(cache)) return\n const installedVersion = await getInstalledPiVersion()\n if (!meetsPiMinVersion(installedVersion)) return\n const npmPath = resolveExecutable(\"npm\")\n const latestVersion = await getLatestPiVersion()\n // Optimistic throttle write: concurrent/next launches back off\n // even while the detached install is still settling.\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n if (!npmPath) return\n if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return\n const queued = await withInstallLock(\"pi-install.lock\", async () => {\n queueDetachedGlobalInstall(\n npmPath,\n `${PI_NPM_PACKAGE}@${latestVersion}`,\n piRegistryArgs(),\n )\n })\n if (queued) {\n consola.info(\n `Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Background Pi refresh failed:\", err)\n }\n })().catch((err) => {\n consola.debug(\"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AAgB,GAAG;GAC1C,MAAM,UAAU,kBAAkB,KAAK;GACvC,MAAM,gBAAgB,MAAM,mBAAmB;GAG/C,MAAM,WAAW;IACf,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;IAClC;IACA;GACF,CAAC;GACD,IAAI,CAAC,SAAS;GACd,IAAI,CAAC,iBAAiB,CAAC,UAAU,kBAAkB,aAAa,GAAG;GAQnE,IAAI,MAPiB,gBAAgB,mBAAmB,YAAY;IAClE,2BACE,SACA,mCAAqB,iBACrB,eAAe,CACjB;GACF,CAAC,GAEC,QAAQ,KACN,MAAM,iBAAiB,KAAK,cAAc,oDAC5C;EAEJ,SAAS,KAAK;GACZ,QAAQ,MAAM,iCAAiC,GAAG;EACpD;CACF,EAAA,CAAG,CAAC,CAAC,OAAO,QAAQ;EAClB,QAAQ,MAAM,iCAAiC,GAAG;CACpD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"pi-version-check-BRt9XFLj.js","names":["NPM_PACKAGE","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow","getLatestVersion","THROTTLE_HOURS","NPM_VIEW_TIMEOUT_MS","cacheFilePath","readCache","writeCache","shouldCheckNow"],"sources":["../src/lib/claude-version-check.ts","../src/lib/self-update.ts","../src/lib/pi-version-check.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport {\n resolveExecutable,\n runCommandCapture,\n runCommandVoid,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\n\nconst NPM_PACKAGE = \"@anthropic-ai/claude-code\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst CLAUDE_VERSION_TIMEOUT_MS = 3000\nconst NPM_INSTALL_TIMEOUT_MS = 120_000 // 2 min — npm install can be slow on cold caches\n\ninterface VersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-update-check\",\n )\n}\n\n/**\n * Read the throttle cache. Returns null on missing/corrupt file —\n * triggers a fresh check.\n */\nasync function readCache(): Promise<VersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as VersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: VersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n // Throttle cache is best-effort — a write failure means we'll re-check\n // on next launch. Not worth surfacing.\n consola.debug(\"Failed to write claude version-check cache:\", err)\n }\n}\n\n/** Check if it's been more than THROTTLE_HOURS since the last check. */\nfunction shouldCheckNow(cache: VersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `claude` version. Returns null if claude is not\n * on PATH or the version probe fails (e.g. older versions that don't\n * support `--version` cleanly).\n *\n * Windows-safe: `claude` is a `.cmd` shim that `execFile` cannot launch\n * directly. We resolve it to an absolute path (excluding the cwd, so a\n * planted `claude.cmd` in an untrusted repo can't run) and invoke it\n * through the shared exec helper.\n */\nasync function getInstalledVersion(): Promise<string | null> {\n const claudePath = resolveExecutable(\"claude\")\n if (!claudePath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [claudePath, \"--version\"],\n { timeoutMs: CLAUDE_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n // Output shape: \"2.1.139 (Claude Code)\\n\"\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/**\n * Fetch the latest version of @anthropic-ai/claude-code from the npm\n * registry. Returns null on network failure / npm unavailable.\n *\n * Windows-safe: `npm` is `npm.cmd`; resolved to an absolute path\n * (excluding cwd) before invocation.\n */\nasync function getLatestVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (only the leading X.Y.Z, no\n * pre-release / metadata handling — sufficient for npm-published\n * stable releases). Returns true if `latest` is strictly higher than\n * `installed`.\n */\nexport function isNewer(installed: string | null, latest: string | null): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\nexport interface VersionCheckResult {\n /** Whether claude is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-claude\"\n}\n\n/**\n * Run a version check (subject to throttle). Side-effect: updates the\n * throttle cache. Returns the comparison result.\n */\nexport async function checkClaudeVersion(opts: {\n noCheck?: boolean\n /** Bypass the throttle (used when the check is the user's main intent) */\n force?: boolean\n} = {}): Promise<VersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n return {\n installed: cache?.installedVersion !== null,\n installedVersion: cache?.installedVersion ?? null,\n latestVersion: cache?.latestVersion ?? null,\n needsUpdate: isNewer(\n cache?.installedVersion ?? null,\n cache?.latestVersion ?? null,\n ),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-claude\",\n }\n }\n\n const latestVersion = await getLatestVersion()\n // Update cache regardless of whether latest fetched (so we still\n // throttle if npm is offline).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isNewer(installedVersion, latestVersion),\n skipped: false,\n }\n}\n\n/**\n * Heuristic: did `claude update` fail because the subcommand does not\n * exist (a build predating `claude update`), as opposed to a transient\n * update error? We only npm-fall-back on this specific signal — falling\n * back on any failure would install a conflicting npm copy on\n * native-installer machines.\n *\n * Matches the usage/Commander-style \"unknown command\" messages CLIs emit\n * for an unrecognized subcommand. Deliberately narrow.\n */\nexport function looksLikeUnknownUpdateCommand(output: string): boolean {\n return /unknown command|unknown subcommand|unrecognized (sub)?command|invalid command|command not found|is not a (known|valid) command/i.test(\n output,\n )\n}\n\n/**\n * Update Claude Code to the latest version.\n *\n * Strategy (decided in the plan, corrected after a real-world false\n * negative): run `claude update` directly — it respects the user's\n * actual install method (native installer or npm), so it never creates a\n * conflicting second install, and it is NOT blocked by the\n * `DISABLE_AUTOUPDATER` the proxy sets in the *child* env (this runs from\n * the proxy's own env, and `claude update` is a manual command\n * unaffected by that flag).\n *\n * Only if `claude update` reports the subcommand is unknown (a build too\n * old to have it) do we fall back to `npm install -g\n * @anthropic-ai/claude-code@latest` with a VISIBLE warning. The earlier\n * `claude --help` capability probe was removed: it timed out / mismatched\n * on slow cold starts and wrongly forced the npm path every launch,\n * creating dual npm-global + native installs.\n *\n * Serialized across concurrent proxies via an install lock. Throws on\n * failure — the caller decides whether to warn and continue.\n */\nexport interface UpdateClaudeDeps {\n resolveExecutable: typeof resolveExecutable\n runCommandCapture: typeof runCommandCapture\n runCommandVoid: typeof runCommandVoid\n withInstallLock: typeof withInstallLock\n}\n\nexport async function updateClaude(\n latestVersion: string,\n deps: Partial<UpdateClaudeDeps> = {},\n): Promise<void> {\n const _resolve = deps.resolveExecutable ?? resolveExecutable\n const _capture = deps.runCommandCapture ?? runCommandCapture\n const _void = deps.runCommandVoid ?? runCommandVoid\n const _lock = deps.withInstallLock ?? withInstallLock\n\n const claudePath = _resolve(\"claude\")\n if (!claudePath) throw new Error(\"claude not found on PATH\")\n\n const ran = await _lock(\"claude-update.lock\", async () => {\n consola.info(`Updating Claude Code to ${latestVersion} via \\`claude update\\`...`)\n // Capture (not inherit) so we can detect an unknown-command signal;\n // echo the output afterward so the user still sees what happened.\n const { code, stdout, stderr } = await _capture([claudePath, \"update\"], {\n timeoutMs: NPM_INSTALL_TIMEOUT_MS,\n })\n const combined = `${stdout}${stderr}`\n const trimmed = combined.trim()\n if (trimmed) process.stdout.write(trimmed.endsWith(\"\\n\") ? trimmed : `${trimmed}\\n`)\n\n if (code === 0) {\n consola.success(`Claude Code updated to ${latestVersion}`)\n return\n }\n\n if (!looksLikeUnknownUpdateCommand(combined)) {\n throw new Error(`\\`claude update\\` exited with code ${code}`)\n }\n\n // Fallback: npm. Only reachable on installs too old to have\n // `claude update` at all.\n const npmPath = _resolve(\"npm\")\n if (!npmPath) {\n throw new Error(\n \"this Claude Code build predates `claude update` and npm is not on PATH; \" +\n `update manually: npm install -g ${NPM_PACKAGE}@latest`,\n )\n }\n consola.warn(\n \"This Claude Code build predates `claude update`; falling back to \" +\n `\\`npm install -g ${NPM_PACKAGE}@latest\\`.`,\n )\n const { code: npmCode, stderr: npmStderr } = await _void(\n [npmPath, \"install\", \"-g\", `${NPM_PACKAGE}@latest`, \"--silent\"],\n { timeoutMs: NPM_INSTALL_TIMEOUT_MS },\n )\n if (npmCode !== 0) {\n throw new Error(`npm install failed: ${npmStderr.trim() || `exit ${npmCode}`}`)\n }\n consola.success(`${NPM_PACKAGE} updated to ${latestVersion}`)\n })\n\n if (!ran) {\n consola.debug(\"Claude Code update already in progress in another process; skipping.\")\n }\n}\n","/**\n * Self-update for the `github-router` proxy.\n *\n * The proxy is a *running* process, so updating its own global install\n * in place (`npm install -g github-router@latest`) deletes/overwrites\n * files the OS holds open — on Windows that fails deterministically\n * (EPERM/EBUSY) and can corrupt the install. So we never install in\n * place: when a newer version exists we spawn a **detached updater that\n * waits for this process to exit**, then installs. The update takes\n * effect on the next launch — no re-exec, no restart prompt.\n *\n * Best-effort throughout: every failure is swallowed to debug/warn and\n * never blocks startup. The startup probe is bounded and the install is\n * off the critical path (detached), so even a blackholed network can't\n * delay the proxy from serving.\n */\n\nimport { spawn } from \"node:child_process\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { isNewer } from \"./claude-version-check\"\nimport {\n parseBoolEnv,\n resolveExecutable,\n runCommandCapture,\n} from \"./exec\"\nimport { withInstallLock } from \"./update-lock\"\nimport { getPackageVersion } from \"./version\"\n\n// The published, installable package is the UNSCOPED name. The scoped\n// `@animeshkundu/github-router` is GitHub-Packages-only and must NOT be\n// used for `npm view` / `npm install` here.\nconst NPM_PACKAGE = \"github-router\"\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\n\ninterface SelfUpdateCache {\n checkedAt: string\n installedVersion: string | null\n latestVersion: string | null\n}\n\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n // Distinct from the Claude Code check's `last-update-check` so the\n // two throttles don't cross-suppress.\n \"last-self-update-check\",\n )\n}\n\nasync function readCache(): Promise<SelfUpdateCache | null> {\n try {\n const parsed = JSON.parse(\n await fs.readFile(cacheFilePath(), \"utf8\"),\n ) as SelfUpdateCache\n if (typeof parsed.checkedAt !== \"string\") return null\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: SelfUpdateCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), { mode: 0o600 })\n } catch (err) {\n consola.debug(\"Failed to write self-update cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: SelfUpdateCache | null): boolean {\n if (!cache) return true\n const last = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(last)) return true\n return (Date.now() - last) / 1000 / 3600 >= THROTTLE_HOURS\n}\n\nasync function getLatestVersion(npmPath: string): Promise<string | null> {\n try {\n const { stdout, code } = await runCommandCapture(\n [npmPath, \"view\", NPM_PACKAGE, \"version\", \"--silent\"],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Spawn a detached process that waits for THIS proxy (pid) to exit,\n * then runs `npm install -g <spec>`. Fully detached and unref'd so it\n * outlives the proxy; output discarded.\n *\n * The waiter is a tiny inline Node script (Node is guaranteed present —\n * the proxy runs on it) that polls `process.kill(pid, 0)` until the\n * parent is gone, then execs npm. This avoids the Windows file-lock by\n * never touching the global install while the proxy holds it open.\n *\n * Shared by the proxy self-update (`github-router@latest`) and the Pi\n * background refresh (`@earendil-works/pi-coding-agent@<version>`):\n * both must update a global install without delaying startup, holding\n * shutdown, or racing each other (callers hold `withInstallLock`\n * before queueing).\n */\nexport function queueDetachedGlobalInstall(\n npmPath: string,\n spec: string,\n extraArgs: readonly string[] = [],\n): void {\n const parentPid = process.pid\n const installArgs = [\"install\", \"-g\", spec, ...extraArgs]\n // Inline waiter: poll until the parent disappears, then install.\n const waiter = `\n const pid = ${parentPid};\n const { spawn } = require(\"node:child_process\");\n function alive() { try { process.kill(pid, 0); return true } catch { return false } }\n const timer = setInterval(() => {\n if (alive()) return;\n clearInterval(timer);\n const args = [...${JSON.stringify(installArgs)}, \"--silent\"];\n const isWin = process.platform === \"win32\";\n const child = spawn(${JSON.stringify(npmPath)}, args, {\n stdio: \"ignore\", windowsHide: true, shell: isWin, detached: !isWin,\n });\n child.on(\"error\", () => process.exit(0));\n child.on(\"exit\", () => process.exit(0));\n // Safety: never hang forever.\n setTimeout(() => process.exit(0), 180000).unref();\n }, 500);\n // Safety cap on the wait itself (e.g. extremely long sessions still\n // eventually give up rather than leak the waiter).\n setTimeout(() => { clearInterval(timer); process.exit(0); }, 24 * 3600 * 1000).unref();\n `.trim()\n\n const child = spawn(process.execPath, [\"-e\", waiter], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n })\n child.unref()\n}\n\nfunction spawnDetachedUpdater(npmPath: string): void {\n queueDetachedGlobalInstall(npmPath, `${NPM_PACKAGE}@latest`)\n}\n\nexport interface RunSelfUpdateOpts {\n /** From `args[\"self-update\"]` (default true). */\n selfUpdate: boolean\n /** Bypass the throttle (used by tests / explicit forcing). */\n force?: boolean\n}\n\n/**\n * Probe npm for a newer `github-router` and, if found, queue a detached\n * post-exit update. Returns quickly; never throws. Call AFTER the\n * server is listening so the bounded probe can't delay binding.\n */\nexport async function runSelfUpdate(opts: RunSelfUpdateOpts): Promise<void> {\n if (!opts.selfUpdate) return\n if (parseBoolEnv(process.env.GH_ROUTER_NO_SELF_UPDATE) === true) return\n\n try {\n // WHICH update mechanism depends on who owns the tree we are running from,\n // and getting this wrong is not a style question:\n //\n // - `npx`/`bunx`: the tree is a disposable cache entry. `npm install -g`\n // from here would create a SECOND install the user never asked for (and\n // the next `npx` would still re-extract, so it would not even help). The\n // managed install is the whole point of this feature.\n // - `npm-global`: user decision 4 — that tree is its own owner. Keep the\n // detached post-exit waiter verbatim.\n // - `managed`: the bootstrap (and `github-router update`) maintain it; doing\n // it again here would double-schedule on every launch.\n // - `source`: never. A dev checkout must run its own code and must not gain\n // a global install as a side effect.\n //\n // `classifyOrigin` is imported lazily: it pulls `exec` and the managed state\n // module, and this function runs from every entry point including the tiny\n // bootstrap-adjacent paths.\n const { classifyOrigin } = await import(\"./managed-install/origin\")\n const origin = await classifyOrigin()\n\n if (origin.origin === \"npx\" || origin.origin === \"bunx\") {\n const { scheduleBackgroundSelfInstall } = await import(\"./managed-install/update\")\n const detail = await scheduleBackgroundSelfInstall({ quiet: true })\n consola.debug(`self-update: managed path: ${detail}`)\n return\n }\n if (origin.origin !== \"npm-global\") {\n consola.debug(`self-update: skipped for origin ${origin.origin} (${origin.detail})`)\n return\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) return\n\n const installed = getPackageVersion()\n if (installed === \"unknown\") return // can't compare; skip silently\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return // npm not on PATH; skip\n\n const latest = await getLatestVersion(npmPath)\n // Write the throttle BEFORE acting so concurrent/next launches back\n // off even if the install is still settling (optimistic lock).\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion: installed,\n latestVersion: latest,\n })\n if (!latest || !isNewer(installed, latest)) return\n\n const queued = await withInstallLock(\"self-update.lock\", async () => {\n spawnDetachedUpdater(npmPath)\n })\n if (queued) {\n consola.info(\n `github-router ${installed} → ${latest} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Self-update check failed:\", err)\n }\n}\n","import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { resolveExecutable, runCommandCapture } from \"./exec\"\nimport { queueDetachedGlobalInstall } from \"./self-update\"\nimport { withInstallLock } from \"./update-lock\"\n\nexport const PI_NPM_PACKAGE = \"@earendil-works/pi-coding-agent\"\n/**\n * Minimum Pi version the `pi` launcher supports.\n *\n * The floor is pinned to the first release whose `before_agent_start` event\n * carries the `messageType` discriminator (present at 1.3.0, absent at 1.1.0).\n * The generated extension's prompt hook stands down for non-user events using\n * that field, and without it the hook would fire on subagent and system turns\n * the user never typed, which is a wrong brief rather than a missing one.\n * Below-floor Pi hard-exits at the launcher (`src/pi.ts`), but only where the\n * gate actually runs: the install probe, the background refresh, and this floor\n * check all sit inside `--update-check` (default on), so `--no-update-check`\n * (documented for offline/CI) skips the floor as well. That path is still\n * fail-closed rather than silently wrong: the generated extension's own shape\n * probe sees the missing `messageType`, warns once with the fix, and injects\n * nothing.\n */\nexport const PI_MIN_VERSION = \"1.3.0\"\n\n/**\n * Registry used for the PI PACKAGE ONLY.\n *\n * Pi must come from a registry that actually carries it. A corporate npm mirror\n * can lag npmjs far enough that its `latest` sits below `PI_MIN_VERSION`, and\n * the launcher then fail-closes on an upgrade command the user cannot satisfy\n * (their `npm install -g` resolves through the same lagging mirror). Pointing\n * the Pi probe and install at npmjs by default keeps the floor reachable;\n * `GH_ROUTER_NPM_REGISTRY` overrides it for a mirror that does carry the\n * package. Everything else this repo installs still resolves through the user's\n * configured registry.\n */\nexport const PI_DEFAULT_REGISTRY = \"https://registry.npmjs.org/\"\n\n/**\n * Resolve the registry for Pi package operations. Accepts `GH_ROUTER_NPM_REGISTRY`\n * when it is an http(s) URL and falls back to `PI_DEFAULT_REGISTRY` with a\n * warning otherwise, so a typo degrades to the working default rather than\n * bricking the launcher.\n */\nexport function resolvePiRegistry(): string {\n const raw = process.env.GH_ROUTER_NPM_REGISTRY?.trim()\n if (!raw) return PI_DEFAULT_REGISTRY\n if (!/^https?:\\/\\//i.test(raw)) {\n consola.warn(\n `Ignoring GH_ROUTER_NPM_REGISTRY=${JSON.stringify(raw)}: expected an http(s) URL. Using ${PI_DEFAULT_REGISTRY}.`,\n )\n return PI_DEFAULT_REGISTRY\n }\n return raw.endsWith(\"/\") ? raw : `${raw}/`\n}\n\n/** `npm` args that pin an operation to the resolved Pi registry. */\nexport function piRegistryArgs(registry: string = resolvePiRegistry()): string[] {\n return [`--registry=${registry}`]\n}\n\nconst THROTTLE_HOURS = 1\nconst NPM_VIEW_TIMEOUT_MS = 5000\nconst PI_VERSION_TIMEOUT_MS = 3000\n\ninterface PiVersionCheckCache {\n /** ISO timestamp of last check */\n checkedAt: string\n /** Installed version at last check */\n installedVersion: string | null\n /** Latest version on npm at last check */\n latestVersion: string | null\n}\n\n/** Path to the throttle cache. Created on demand. Separate file from the Claude check. */\nfunction cacheFilePath(): string {\n return path.join(\n os.homedir(),\n \".local\",\n \"share\",\n \"github-router\",\n \"last-pi-update-check\",\n )\n}\n\nasync function readCache(): Promise<PiVersionCheckCache | null> {\n try {\n const raw = await fs.readFile(cacheFilePath(), \"utf8\")\n const parsed = JSON.parse(raw) as PiVersionCheckCache\n if (\n typeof parsed.checkedAt !== \"string\"\n || (parsed.installedVersion !== null\n && typeof parsed.installedVersion !== \"string\")\n || (parsed.latestVersion !== null\n && typeof parsed.latestVersion !== \"string\")\n ) {\n return null\n }\n return parsed\n } catch {\n return null\n }\n}\n\nasync function writeCache(cache: PiVersionCheckCache): Promise<void> {\n try {\n await fs.mkdir(path.dirname(cacheFilePath()), { recursive: true })\n await fs.writeFile(cacheFilePath(), JSON.stringify(cache), {\n mode: 0o600,\n })\n } catch (err) {\n consola.debug(\"Failed to write pi version-check cache:\", err)\n }\n}\n\nfunction shouldCheckNow(cache: PiVersionCheckCache | null): boolean {\n if (!cache) return true\n const lastCheck = new Date(cache.checkedAt).getTime()\n if (Number.isNaN(lastCheck)) return true\n const hoursSince = (Date.now() - lastCheck) / 1000 / 3600\n return hoursSince >= THROTTLE_HOURS\n}\n\n/**\n * Read the installed `pi` version. Returns null if pi is not on PATH\n * or the version probe fails.\n *\n * Windows-safe: `pi` may be a `.cmd` shim; resolved to an absolute path\n * (excluding the cwd) before invocation via the shared exec helper.\n */\nexport async function getInstalledPiVersion(): Promise<string | null> {\n const piPath = resolveExecutable(\"pi\")\n if (!piPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [piPath, \"--version\"],\n { timeoutMs: PI_VERSION_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const match = stdout.match(/(\\d+\\.\\d+\\.\\d+)/)\n return match ? match[1] : null\n } catch {\n return null\n }\n}\n\n/** Fetch the latest Pi version from npm. Null on network/npm failure. */\nasync function getLatestPiVersion(): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n try {\n const { stdout, code } = await runCommandCapture(\n [\n npmPath,\n \"view\",\n PI_NPM_PACKAGE,\n \"version\",\n \"--silent\",\n ...piRegistryArgs(),\n ],\n { timeoutMs: NPM_VIEW_TIMEOUT_MS },\n )\n if (code !== 0) return null\n const v = stdout.trim()\n return /^\\d+\\.\\d+\\.\\d+/.test(v) ? v : null\n } catch {\n return null\n }\n}\n\n/**\n * Compare two semver-shaped strings (leading X.Y.Z only). True when\n * `latest` is strictly higher than `installed`.\n */\nexport function isPiNewer(\n installed: string | null,\n latest: string | null,\n): boolean {\n if (!installed || !latest) return false\n const a = installed.split(\".\").map((n) => parseInt(n, 10))\n const b = latest.split(\".\").map((n) => parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = a[i] ?? 0\n const bv = b[i] ?? 0\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** True when `version` satisfies the minimum Pi floor (>= PI_MIN_VERSION). */\nexport function meetsPiMinVersion(version: string | null): boolean {\n if (!version) return false\n return !isPiNewer(version, PI_MIN_VERSION)\n}\n\nexport interface PiVersionCheckResult {\n /** Whether pi is on PATH at all */\n installed: boolean\n installedVersion: string | null\n latestVersion: string | null\n /** True if a newer version is available */\n needsUpdate: boolean\n /** True if the installed version is below the supported floor */\n needsMinUpgrade: boolean\n /** Whether the check was skipped (throttled or disabled) */\n skipped: boolean\n skipReason?: \"throttled\" | \"disabled\" | \"no-npm\" | \"no-pi\"\n}\n\n/** Run a version check (subject to throttle). Side-effect: updates the cache. */\nexport async function checkPiVersion(opts: {\n noCheck?: boolean\n force?: boolean\n} = {}): Promise<PiVersionCheckResult> {\n if (opts.noCheck) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: false,\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n const cache = await readCache()\n if (!opts.force && !shouldCheckNow(cache)) {\n const installedVersion = cache?.installedVersion ?? null\n const latestVersion = cache?.latestVersion ?? null\n return {\n installed: installedVersion !== null,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"throttled\",\n }\n }\n\n const installedVersion = await getInstalledPiVersion()\n if (installedVersion === null) {\n return {\n installed: false,\n installedVersion: null,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: true,\n skipped: true,\n skipReason: \"no-pi\",\n }\n }\n\n const latestVersion = await getLatestPiVersion()\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n\n if (latestVersion === null) {\n return {\n installed: true,\n installedVersion,\n latestVersion: null,\n needsUpdate: false,\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: true,\n skipReason: \"no-npm\",\n }\n }\n\n return {\n installed: true,\n installedVersion,\n latestVersion,\n needsUpdate: isPiNewer(installedVersion, latestVersion),\n needsMinUpgrade: !meetsPiMinVersion(installedVersion),\n skipped: false,\n }\n}\n\n/*\n * `updatePi` / `ensurePiInstalled` used to live here: they ran\n * `npm install -g @earendil-works/pi-coding-agent@<v>` and then re-probed PATH.\n * They were removed deliberately, not refactored.\n *\n * Two reasons, both observed:\n *\n * 1. **They mutate a tree the user owns.** `-g` is not ours (user decision 4).\n * Rewriting it to satisfy `PI_MIN_VERSION` made the launcher's floor check a\n * silent `npm install -g` on every below-floor machine, which can break an\n * unrelated project pinned to the older Pi.\n * 2. **`-g` cannot be updated while it is in use.** On Windows that is `EPERM`;\n * everywhere it needs the detached post-exit waiter. The managed install\n * avoids the whole problem by publishing a new directory and swapping a file\n * pointer, so the below-floor repair path is now\n * `managed-install/pi-command.ts` → `ensureManagedInstall` (see\n * `resolvePiCommand`), and the explicit form is `github-router update --pi`.\n *\n * The user-owned `pi` still keeps its own channel: `refreshPiInBackground`\n * below queues the same detached `-g` install it always did.\n */\n\n/**\n * Fire-and-forget freshness refresh for a healthy Pi install. Never\n * blocks launch and never throws: on the throttled schedule it probes\n * npm for a newer Pi and, when one exists, queues a DETACHED post-exit\n * install (same pattern as the proxy self-update) so neither startup\n * nor the running session nor shutdown ever waits on npm. The\n * cross-process install lock serializes against concurrent launches;\n * every failure degrades to a debug log.\n *\n * Deliberately never touches a below-floor install: the floor is\n * enforced foreground by the launcher (fail-closed), and a background\n * task must not change what the running session validated.\n */\nexport function refreshPiInBackground(opts: { autoUpdate: boolean }): void {\n if (!opts.autoUpdate) return\n void (async () => {\n try {\n const cache = await readCache()\n if (!shouldCheckNow(cache)) return\n const installedVersion = await getInstalledPiVersion()\n if (!meetsPiMinVersion(installedVersion)) return\n const npmPath = resolveExecutable(\"npm\")\n const latestVersion = await getLatestPiVersion()\n // Optimistic throttle write: concurrent/next launches back off\n // even while the detached install is still settling.\n await writeCache({\n checkedAt: new Date().toISOString(),\n installedVersion,\n latestVersion,\n })\n if (!npmPath) return\n if (!latestVersion || !isPiNewer(installedVersion, latestVersion)) return\n const queued = await withInstallLock(\"pi-install.lock\", async () => {\n queueDetachedGlobalInstall(\n npmPath,\n `${PI_NPM_PACKAGE}@${latestVersion}`,\n piRegistryArgs(),\n )\n })\n if (queued) {\n consola.info(\n `Pi ${installedVersion} → ${latestVersion} update queued; it takes effect on the next launch.`,\n )\n }\n } catch (err) {\n consola.debug(\"Background Pi refresh failed:\", err)\n }\n })().catch((err) => {\n consola.debug(\"Background Pi refresh failed:\", err)\n })\n}\n"],"mappings":";;;;;;;;;AAaA,MAAMA,gBAAc;AACpB,MAAMC,mBAAiB;AACvB,MAAMC,wBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,yBAAyB;;AAY/B,SAASC,kBAAwB;CAC/B,OAAO,KAAK,KACV,GAAG,QAAQ,GACX,UACA,SACA,iBACA,mBACF;AACF;;;;;AAMA,eAAeC,cAA+C;CAC5D,IAAI;EACF,MAAM,MAAM,MAAM,GAAG,SAASD,gBAAc,GAAG,MAAM;EACrD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,IACE,OAAO,OAAO,cAAc,YACxB,OAAO,qBAAqB,QAC3B,OAAO,OAAO,qBAAqB,YACpC,OAAO,kBAAkB,QACxB,OAAO,OAAO,kBAAkB,UAErC,OAAO;EAET,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAeE,aAAW,OAAyC;CACjE,IAAI;EACF,MAAM,GAAG,MAAM,KAAK,QAAQF,gBAAc,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;EACjE,MAAM,GAAG,UAAUA,gBAAc,GAAG,KAAK,UAAU,KAAK,GAAG,EACzD,MAAM,IACR,CAAC;CACH,SAAS,KAAK;EAGZ,QAAQ,MAAM,+CAA+C,GAAG;CAClE;AACF;;AAGA,SAASG,iBAAe,OAA0C;CAChE,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,YAAY,IAAI,KAAK,MAAM,SAAS,CAAC,CAAC,QAAQ;CACpD,IAAI,OAAO,MAAM,SAAS,GAAG,OAAO;CAEpC,QADoB,KAAK,IAAI,IAAI,aAAa,MAAO,QAChCL;AACvB;;;;;;;;;;;AAYA,eAAe,sBAA8C;CAC3D,MAAM,aAAa,kBAAkB,QAAQ;CAC7C,IAAI,CAAC,YAAY,O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I,CAAC,eAAe,MADA,UAAU,CACL,GAAG;GAC5B,MAAM,mBAAmB,MAAM,sBAAsB;GACrD,IAAI,CAAC,kBAAkB,gBAAgB,GAAG;GAC1C,MAAM,UAAU,kBAAkB,KAAK;GACvC,MAAM,gBAAgB,MAAM,mBAAmB;GAG/C,MAAM,WAAW;IACf,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;IAClC;IACA;GACF,CAAC;GACD,IAAI,CAAC,SAAS;GACd,IAAI,CAAC,iBAAiB,CAAC,UAAU,kBAAkB,aAAa,GAAG;GAQnE,IAAI,MAPiB,gBAAgB,mBAAmB,YAAY;IAClE,2BACE,SACA,mCAAqB,iBACrB,eAAe,CACjB;GACF,CAAC,GAEC,QAAQ,KACN,MAAM,iBAAiB,KAAK,cAAc,oDAC5C;EAEJ,SAAS,KAAK;GACZ,QAAQ,MAAM,iCAAiC,GAAG;EACpD;CACF,EAAA,CAAG,CAAC,CAAC,OAAO,QAAQ;EAClB,QAAQ,MAAM,iCAAiC,GAAG;CACpD,CAAC;AACH"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { l as resolvePiRegistry } from "./pi-version-check-BRt9XFLj.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as parseBoolEnv } from "./exec-
|
|
2
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
1
|
+
import { a as parseBoolEnv } from "./exec-oCtz_dXO.js";
|
|
2
|
+
import { t as buildSelfCommand } from "./self-invocation-CayD3y72.js";
|
|
3
3
|
import { n as callMcpTool } from "./hook-mcp-client-CYx10nlU.js";
|
|
4
|
-
import { s as isSubagentContext } from "./stop-gate-policy-
|
|
4
|
+
import { s as isSubagentContext } from "./stop-gate-policy-gW0a0hds.js";
|
|
5
5
|
import { promises } from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
@@ -154,4 +154,4 @@ function buildPlanReviewHookCommand(invocation) {
|
|
|
154
154
|
}
|
|
155
155
|
export { runPlanReview as a, planReviewEnabled as i, decidePlanReviewHook as n, filePlanReviewDebounce as r, buildPlanReviewHookCommand as t };
|
|
156
156
|
|
|
157
|
-
//# sourceMappingURL=plan-review-hook-
|
|
157
|
+
//# sourceMappingURL=plan-review-hook-Dx3suYmK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan-review-hook-D_yyjOgO.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAA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A2B,YAAoC;CAC7E,OAAO,iBAAiB,YAAY,sBAAsB;AAC5D"}
|
|
1
|
+
{"version":3,"file":"plan-review-hook-Dx3suYmK.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAAyB,QAAQ,KAAc;CAC/E,OAAO,aAAa,IAAI,6BAA6B,MAAM;AAC7D;;AAGA,SAAgB,uBAAuB,UAAkC;CACvE,MAAM,WAAW,QACfA,KAAS,KAAK,UAAU,oBAAoB,WAAW,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Capture, n as isWindowsScriptShim, r as killChildProcessTree, s as resolveExecutable, t as buildExecInvocation } from "./exec-
|
|
1
|
+
import { t as PATHS } from "./paths-CVXqt2tC.js";
|
|
2
|
+
import { a as parseBoolEnv, c as runCommandCapture, n as isWindowsScriptShim, r as killChildProcessTree, s as resolveExecutable, t as buildExecInvocation } from "./exec-oCtz_dXO.js";
|
|
3
3
|
import { t as withInstallLock } from "./update-lock-BmXx6QaR.js";
|
|
4
|
-
import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, Wn as collapsePathKeys, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-
|
|
5
|
-
import { a as sweepRegistry } from "./lifecycle-
|
|
6
|
-
import { E as extractZipMember, T as extractTarGzMember } from "./service-backend-
|
|
4
|
+
import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, Wn as collapsePathKeys, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-Dgog_ZJ8.js";
|
|
5
|
+
import { a as sweepRegistry } from "./lifecycle-BmoqtVj3.js";
|
|
6
|
+
import { E as extractZipMember, T as extractTarGzMember } from "./service-backend-EgwiO_K-.js";
|
|
7
7
|
import consola from "consola";
|
|
8
8
|
import { existsSync } from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
@@ -724,4 +724,4 @@ async function exposedCommands(binDir) {
|
|
|
724
724
|
}
|
|
725
725
|
export { STRIPPED_AUTH_ROUTING_ENV_KEYS as a, launchChild as i, buildCodexProviderConfigFlags as n, getCodexVersion as r, provisionToolbelt as t };
|
|
726
726
|
|
|
727
|
-
//# sourceMappingURL=provision-
|
|
727
|
+
//# sourceMappingURL=provision-A1YSravb.js.map
|