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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-fEgWTrIx.js","names":[],"sources":["../src/update.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * `github-router update` — bring the managed install up to date, on demand.\n *\n * The user-facing half of `lib/managed-install/update.ts`. Deliberately keeps\n * citty's surface tiny and does the reporting itself, because the interesting\n * outcomes are not exit-code-shaped: \"another process is installing\", \"the\n * registry did not answer\", \"installed, but `~/.local/bin` is not on PATH\" are\n * all successes-with-a-note, and burying them behind a non-zero exit would make\n * `update` unusable in a script or a shell profile.\n *\n * `--quiet` exists for the detached background child (`scheduleBackgroundSelfInstall`),\n * whose stdio is `ignore` anyway but whose ARGV is visible in `ps`, and for anyone\n * wiring this into a cron job.\n */\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { PI_MIN_VERSION } from \"./lib/pi-version-check\"\nimport { readPointer } from \"./lib/managed-install/pointer\"\nimport {\n OPTIONAL_PACKAGES,\n type OptionalPackage,\n ensureOptionalPackage,\n isOptionalPackage,\n optionalInstallDisabled,\n} from \"./lib/managed-install/optional\"\nimport { managedInstallDisabled } from \"./lib/managed-install/npm-env\"\nimport {\n checkForUpdate,\n currentManagedVersion,\n runManagedUpdate,\n type UpdateReport,\n} from \"./lib/managed-install/update\"\nimport type { ManagedKind } from \"./lib/managed-install/paths\"\n\nexport interface RunUpdateOptions {\n self: boolean\n pi: boolean\n check: boolean\n version?: string\n force: boolean\n quiet: boolean\n /** Also install the heavy optional payloads (default on, `--no-optional`). */\n optional?: boolean\n /**\n * Install the optional payloads and nothing else.\n *\n * This is what the on-demand path spawns (`scheduleOptionalInstall`): a rerank\n * or a structural search that found no payload wants THAT payload, not a\n * self-update, and definitely not a managed Pi appearing on a developer's\n * source checkout as a side effect of a search.\n */\n optionalOnly?: boolean\n /**\n * Install only this optional payload (`--optional-pkg <name>`).\n *\n * What `scheduleOptionalInstall` passes: a structural-search miss wants the\n * grammar set, and must not start a 547 MB ONNX download as a side effect.\n */\n optionalPkg?: OptionalPackage\n}\n\n/**\n * Which kinds to act on.\n *\n * Bare `update` maintains both, which is the useful default for the user's stated\n * goal (\"my install should just stay current\"). `--self`/`--pi` narrow it, and an\n * explicit `--version` implies `--self` so `update --version 1.2.3` never\n * accidentally re-pins Pi.\n */\nexport function resolveKinds(opts: Pick<RunUpdateOptions, \"self\" | \"pi\" | \"version\">): Array<ManagedKind> {\n if (opts.self && opts.pi) return [\"self\", \"pi\"]\n if (opts.self) return [\"self\"]\n if (opts.pi) return [\"pi\"]\n if (opts.version) return [\"self\"]\n return [\"self\", \"pi\"]\n}\n\nfunction printCheck(kind: ManagedKind, report: UpdateReport[\"check\"]): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const installed = report.installedVersion ?? \"not installed\"\n if (!report.targetVersion) {\n // `npm view` failed. Saying \"0.3.379 → unknown\" presents a network failure as\n // \"maybe there is a newer one\", which in a cron job is indistinguishable from\n // a real pending update. Say the thing that is actually true, and exit\n // non-zero (the caller counts a null target as a failure).\n consola.warn(`${label}: ${installed}; could not determine the latest version (npm view failed)`)\n return\n }\n if (report.upToDate) {\n consola.info(`${label}: ${installed} (up to date)`)\n return\n }\n consola.info(`${label}: ${installed} → ${report.targetVersion}`)\n}\n\n/** First non-empty line of a multi-line diagnostic. */\nfunction firstLine(text: string | undefined): string | null {\n if (!text) return null\n const line = text.split(/\\r?\\n/).find((part) => part.trim().length > 0)\n return line ? line.trim() : null\n}\n\nfunction printOutcome(kind: ManagedKind, report: UpdateReport): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const outcome = report.outcome\n if (!outcome) return\n switch (outcome.kind) {\n case \"installed\":\n case \"adopted\":\n consola.success(\n `${label} ${outcome.version} ${outcome.kind === \"adopted\" ? \"adopted\" : \"installed\"} at ${outcome.entryPath ?? \"\"}`,\n )\n if (report.launcher) {\n consola.info(\n report.launcher.written\n ? `Launcher installed: ${report.launcher.path}`\n : `Launcher up to date: ${report.launcher.path}`,\n )\n }\n for (const shim of report.shims ?? []) {\n if (shim.outcome === \"refused\") {\n consola.warn(`Left ${shim.path} alone (not written by github-router).`)\n }\n }\n if (report.pathHint) {\n // Printed as info, not warn: nothing is broken, the command just is not\n // reachable by name yet. One copy-pasteable line, no rc editing.\n consola.info(report.pathHint)\n }\n if (report.gc && report.gc.removedVersions.length > 0) {\n consola.debug(`${label}: removed old versions ${report.gc.removedVersions.join(\", \")}`)\n }\n return\n case \"disabled\":\n consola.info(`${label}: managed install is disabled (${outcome.detail ?? \"GH_ROUTER_NO_MANAGED_INSTALL\"}).`)\n return\n case \"locked\":\n consola.warn(`${label}: ${outcome.detail ?? \"another install is in progress\"}`)\n return\n case \"no-npm\":\n consola.warn(`${label}: ${outcome.detail ?? \"npm not found on PATH\"}`)\n return\n case \"backoff\":\n consola.warn(`${label}: ${firstLine(outcome.detail) ?? \"backing off after a failed attempt\"}`)\n return\n case \"failed\":\n // The detail embeds npm's stderr. Print its first line as the message and\n // the rest at debug, so a broken registry is one readable sentence on the\n // console instead of a wall of npm internals ending mid-filename — while\n // still being available under --verbose.\n consola.error(`${label}: ${firstLine(outcome.detail) ?? \"install failed\"}`)\n if (outcome.detail && outcome.detail.includes(\"\\n\")) consola.debug(outcome.detail)\n return\n }\n}\n\nexport async function runUpdate(opts: RunUpdateOptions): Promise<number> {\n let kinds = opts.optionalOnly ? [] : resolveKinds(opts)\n let failures = 0\n\n if (kinds.length > 0 && managedInstallDisabled()) {\n // `--check` would otherwise print \"not installed → 0.3.379\" on a machine\n // where the managed layer is switched OFF, which reads as an update that is\n // about to happen and never will.\n if (!opts.quiet) {\n consola.info(\n \"managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL), so there is nothing to install or check for github-router/Pi.\",\n )\n }\n // NOT `return 0`: the optional payloads have their own, unrelated off switch\n // (`GH_ROUTER_NO_OPTIONAL_INSTALL`). Returning here would make a bare\n // `github-router update` on a machine with the managed layer disabled skip\n // reranking/grammar payloads that the user never opted out of — the two\n // switches are documented as independent, so they must behave that way.\n kinds = []\n }\n\n for (const kind of kinds) {\n if (opts.check) {\n const report = await checkForUpdate(kind, { version: opts.version, force: opts.force })\n if (!opts.quiet) printCheck(kind, report)\n // \"Could not find out\" is a FAILURE for anything that parses the exit code\n // (a cron job, a CI step, a wrapper script). Printing a warning and exiting\n // 0 makes a broken registry indistinguishable from \"you are up to date\".\n if (report.targetVersion === null) failures += 1\n continue\n }\n const report = await runManagedUpdate({\n kind,\n version: opts.version,\n force: opts.force,\n check: false,\n })\n if (!opts.quiet) printOutcome(kind, report)\n if (report.outcome?.kind === \"failed\") failures += 1\n }\n\n if (opts.check && opts.optionalOnly) {\n // Both halves of this combination are silently empty: `--optional-only` makes\n // `kinds` empty, and `--check` skips the optional block. Left alone the\n // command prints nothing and exits 0, which reads as \"everything is fine\".\n if (!opts.quiet) {\n consola.warn(\n \"--check does not inspect the optional payloads (they are installed on demand), so --check --optional-only has nothing to report.\",\n )\n }\n return failures === 0 ? 0 : 1\n }\n\n if (opts.optional !== false && !opts.check && !optionalInstallDisabled()) {\n // Optional payloads are the difference between a 66 MB and a 586 MB install,\n // so they are NOT installed with the package. `update` is where a user asks\n // for the whole thing, and where a failure is visible instead of silently\n // degrading search quality. A failure here is a WARNING, never a non-zero\n // exit: reranking and structural search both have documented fallbacks.\n const wanted: ReadonlyArray<OptionalPackage> =\n opts.optionalPkg === undefined ? OPTIONAL_PACKAGES : [opts.optionalPkg]\n const results = []\n for (const pkg of wanted) {\n const result = await ensureOptionalPackage(pkg, { force: opts.force })\n results.push({ pkg, ...result })\n }\n for (const result of results) {\n if (result.dir) {\n if (!opts.quiet) consola.success(`${result.pkg} ready at ${result.dir}`)\n } else if (!opts.quiet) {\n consola.warn(`${result.pkg} unavailable: ${result.detail ?? \"unknown error\"}`)\n }\n }\n }\n\n return failures === 0 ? 0 : 1\n}\n\n/**\n * A bare `update` may also be the FIRST thing a user runs after `npm i -g`, in\n * which case there is nothing managed yet and the honest answer is \"here is where\n * it would go\". `checkForUpdate` already reports that as \"not installed → latest\",\n * so nothing extra is needed; the pointer read below is only for the debug line.\n */\nexport const update = defineCommand({\n meta: {\n name: \"update\",\n description: `Install or refresh the managed github-router/Pi payload (Pi floor ${PI_MIN_VERSION})`,\n },\n args: {\n self: {\n type: \"boolean\",\n default: false,\n description: \"Update github-router only\",\n },\n pi: {\n type: \"boolean\",\n default: false,\n description: \"Update the managed Pi only\",\n },\n check: {\n type: \"boolean\",\n default: false,\n description: \"Report what would change; install nothing\",\n },\n version: {\n type: \"string\",\n description: \"Install an exact version instead of npm's latest\",\n },\n force: {\n type: \"boolean\",\n default: false,\n description: \"Ignore the failure backoff and reinstall even if the version matches\",\n },\n quiet: {\n type: \"boolean\",\n default: false,\n description: \"Only report problems (used by the background self-install)\",\n },\n \"optional-only\": {\n type: \"boolean\",\n default: false,\n description:\n \"Install the heavy optional payloads and nothing else (internal: what a rerank or structural search spawns on demand)\",\n },\n \"optional-pkg\": {\n type: \"string\",\n description: `Install only this optional payload (${OPTIONAL_PACKAGES.join(\", \")}). Internal: used by --optional-only spawns so a grammar miss does not download the ONNX runtime.`,\n },\n optional: {\n type: \"boolean\",\n default: true,\n description:\n \"Also install the heavy optional payloads (transformers/ONNX for reranking, tree-sitter grammars) into the shared optional dir. --no-optional skips them; reranking then falls back to BM25F and structural ranking to the regex heuristic.\",\n },\n },\n async run({ args }) {\n // Validate BEFORE any work. An unknown name must not degrade to \"install\n // everything\": for this pair that means a 547 MB ONNX download triggered by\n // a typo, and it must not degrade to \"install nothing\" either, which would\n // look like success.\n const rawOptionalPkg = args[\"optional-pkg\"]\n if (\n rawOptionalPkg !== undefined\n && !(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg))\n ) {\n consola.error(\n `--optional-pkg must be one of: ${OPTIONAL_PACKAGES.join(\", \")} (got ${JSON.stringify(rawOptionalPkg)}).`,\n )\n process.exitCode = 2\n return\n }\n\n const pointer = await readPointer(\"self\", { verifyEntry: false })\n consola.debug(\n `managed: live self version ${pointer?.version ?? \"none\"} (live pointer ${await currentManagedVersion(\"self\") ?? \"none\"})`,\n )\n const code = await runUpdate({\n self: args.self,\n pi: args.pi,\n check: args.check,\n version: typeof args.version === \"string\" ? args.version : undefined,\n force: args.force,\n quiet: args.quiet,\n optional: args.optional,\n optionalOnly: args[\"optional-only\"],\n ...(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg)\n ? { optionalPkg: rawOptionalPkg }\n : {}),\n })\n process.exitCode = code\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,aAAa,MAA6E;CACxG,IAAI,KAAK,QAAQ,KAAK,IAAI,OAAO,CAAC,QAAQ,IAAI;CAC9C,IAAI,KAAK,MAAM,OAAO,CAAC,MAAM;CAC7B,IAAI,KAAK,IAAI,OAAO,CAAC,IAAI;CACzB,IAAI,KAAK,SAAS,OAAO,CAAC,MAAM;CAChC,OAAO,CAAC,QAAQ,IAAI;AACtB;AAEA,SAAS,WAAW,MAAmB,QAAqC;CAC1E,MAAM,QAAQ,SAAS,OAAO,OAAO;CACrC,MAAM,YAAY,OAAO,oBAAoB;CAC7C,IAAI,CAAC,O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AI,EAAE,QAAQ,KAAK,UAAU,cAAc,EAAE,GACxG;GACA,QAAQ,WAAW;GACnB;EACF;EAEA,MAAM,UAAU,MAAM,YAAY,QAAQ,EAAE,aAAa,MAAM,CAAC;EAChE,QAAQ,MACN,8BAA8B,SAAS,WAAW,OAAO,iBAAiB,MAAM,sBAAsB,MAAM,KAAK,OAAO,EAC1H;EACA,MAAM,OAAO,MAAM,UAAU;GAC3B,MAAM,KAAK;GACX,IAAI,KAAK;GACT,OAAO,KAAK;GACZ,SAAS,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU,KAAA;GAC3D,OAAO,KAAK;GACZ,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,cAAc,KAAK;GACnB,GAAI,OAAO,mBAAmB,YAAY,kBAAkB,cAAc,IACtE,EAAE,aAAa,eAAe,IAC9B,CAAC;EACP,CAAC;EACD,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"update-ZqCRVU0a.js","names":[],"sources":["../src/update.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * `github-router update` — bring the managed install up to date, on demand.\n *\n * The user-facing half of `lib/managed-install/update.ts`. Deliberately keeps\n * citty's surface tiny and does the reporting itself, because the interesting\n * outcomes are not exit-code-shaped: \"another process is installing\", \"the\n * registry did not answer\", \"installed, but `~/.local/bin` is not on PATH\" are\n * all successes-with-a-note, and burying them behind a non-zero exit would make\n * `update` unusable in a script or a shell profile.\n *\n * `--quiet` exists for the detached background child (`scheduleBackgroundSelfInstall`),\n * whose stdio is `ignore` anyway but whose ARGV is visible in `ps`, and for anyone\n * wiring this into a cron job.\n */\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { PI_MIN_VERSION } from \"./lib/pi-version-check\"\nimport { readPointer } from \"./lib/managed-install/pointer\"\nimport {\n OPTIONAL_PACKAGES,\n type OptionalPackage,\n ensureOptionalPackage,\n isOptionalPackage,\n optionalInstallDisabled,\n} from \"./lib/managed-install/optional\"\nimport { managedInstallDisabled } from \"./lib/managed-install/npm-env\"\nimport {\n checkForUpdate,\n currentManagedVersion,\n runManagedUpdate,\n type UpdateReport,\n} from \"./lib/managed-install/update\"\nimport type { ManagedKind } from \"./lib/managed-install/paths\"\n\nexport interface RunUpdateOptions {\n self: boolean\n pi: boolean\n check: boolean\n version?: string\n force: boolean\n quiet: boolean\n /** Also install the heavy optional payloads (default on, `--no-optional`). */\n optional?: boolean\n /**\n * Install the optional payloads and nothing else.\n *\n * This is what the on-demand path spawns (`scheduleOptionalInstall`): a rerank\n * or a structural search that found no payload wants THAT payload, not a\n * self-update, and definitely not a managed Pi appearing on a developer's\n * source checkout as a side effect of a search.\n */\n optionalOnly?: boolean\n /**\n * Install only this optional payload (`--optional-pkg <name>`).\n *\n * What `scheduleOptionalInstall` passes: a structural-search miss wants the\n * grammar set, and must not start a 547 MB ONNX download as a side effect.\n */\n optionalPkg?: OptionalPackage\n}\n\n/**\n * Which kinds to act on.\n *\n * Bare `update` maintains both, which is the useful default for the user's stated\n * goal (\"my install should just stay current\"). `--self`/`--pi` narrow it, and an\n * explicit `--version` implies `--self` so `update --version 1.2.3` never\n * accidentally re-pins Pi.\n */\nexport function resolveKinds(opts: Pick<RunUpdateOptions, \"self\" | \"pi\" | \"version\">): Array<ManagedKind> {\n if (opts.self && opts.pi) return [\"self\", \"pi\"]\n if (opts.self) return [\"self\"]\n if (opts.pi) return [\"pi\"]\n if (opts.version) return [\"self\"]\n return [\"self\", \"pi\"]\n}\n\nfunction printCheck(kind: ManagedKind, report: UpdateReport[\"check\"]): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const installed = report.installedVersion ?? \"not installed\"\n if (!report.targetVersion) {\n // `npm view` failed. Saying \"0.3.379 → unknown\" presents a network failure as\n // \"maybe there is a newer one\", which in a cron job is indistinguishable from\n // a real pending update. Say the thing that is actually true, and exit\n // non-zero (the caller counts a null target as a failure).\n consola.warn(`${label}: ${installed}; could not determine the latest version (npm view failed)`)\n return\n }\n if (report.upToDate) {\n consola.info(`${label}: ${installed} (up to date)`)\n return\n }\n consola.info(`${label}: ${installed} → ${report.targetVersion}`)\n}\n\n/** First non-empty line of a multi-line diagnostic. */\nfunction firstLine(text: string | undefined): string | null {\n if (!text) return null\n const line = text.split(/\\r?\\n/).find((part) => part.trim().length > 0)\n return line ? line.trim() : null\n}\n\nfunction printOutcome(kind: ManagedKind, report: UpdateReport): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const outcome = report.outcome\n if (!outcome) return\n switch (outcome.kind) {\n case \"installed\":\n case \"adopted\":\n consola.success(\n `${label} ${outcome.version} ${outcome.kind === \"adopted\" ? \"adopted\" : \"installed\"} at ${outcome.entryPath ?? \"\"}`,\n )\n if (report.launcher) {\n consola.info(\n report.launcher.written\n ? `Launcher installed: ${report.launcher.path}`\n : `Launcher up to date: ${report.launcher.path}`,\n )\n }\n for (const shim of report.shims ?? []) {\n if (shim.outcome === \"refused\") {\n consola.warn(`Left ${shim.path} alone (not written by github-router).`)\n }\n }\n if (report.pathHint) {\n // Printed as info, not warn: nothing is broken, the command just is not\n // reachable by name yet. One copy-pasteable line, no rc editing.\n consola.info(report.pathHint)\n }\n if (report.gc && report.gc.removedVersions.length > 0) {\n consola.debug(`${label}: removed old versions ${report.gc.removedVersions.join(\", \")}`)\n }\n return\n case \"disabled\":\n consola.info(`${label}: managed install is disabled (${outcome.detail ?? \"GH_ROUTER_NO_MANAGED_INSTALL\"}).`)\n return\n case \"locked\":\n consola.warn(`${label}: ${outcome.detail ?? \"another install is in progress\"}`)\n return\n case \"no-npm\":\n consola.warn(`${label}: ${outcome.detail ?? \"npm not found on PATH\"}`)\n return\n case \"backoff\":\n consola.warn(`${label}: ${firstLine(outcome.detail) ?? \"backing off after a failed attempt\"}`)\n return\n case \"failed\":\n // The detail embeds npm's stderr. Print its first line as the message and\n // the rest at debug, so a broken registry is one readable sentence on the\n // console instead of a wall of npm internals ending mid-filename — while\n // still being available under --verbose.\n consola.error(`${label}: ${firstLine(outcome.detail) ?? \"install failed\"}`)\n if (outcome.detail && outcome.detail.includes(\"\\n\")) consola.debug(outcome.detail)\n return\n }\n}\n\nexport async function runUpdate(opts: RunUpdateOptions): Promise<number> {\n let kinds = opts.optionalOnly ? [] : resolveKinds(opts)\n let failures = 0\n\n if (kinds.length > 0 && managedInstallDisabled()) {\n // `--check` would otherwise print \"not installed → 0.3.379\" on a machine\n // where the managed layer is switched OFF, which reads as an update that is\n // about to happen and never will.\n if (!opts.quiet) {\n consola.info(\n \"managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL), so there is nothing to install or check for github-router/Pi.\",\n )\n }\n // NOT `return 0`: the optional payloads have their own, unrelated off switch\n // (`GH_ROUTER_NO_OPTIONAL_INSTALL`). Returning here would make a bare\n // `github-router update` on a machine with the managed layer disabled skip\n // reranking/grammar payloads that the user never opted out of — the two\n // switches are documented as independent, so they must behave that way.\n kinds = []\n }\n\n for (const kind of kinds) {\n if (opts.check) {\n const report = await checkForUpdate(kind, { version: opts.version, force: opts.force })\n if (!opts.quiet) printCheck(kind, report)\n // \"Could not find out\" is a FAILURE for anything that parses the exit code\n // (a cron job, a CI step, a wrapper script). Printing a warning and exiting\n // 0 makes a broken registry indistinguishable from \"you are up to date\".\n if (report.targetVersion === null) failures += 1\n continue\n }\n const report = await runManagedUpdate({\n kind,\n version: opts.version,\n force: opts.force,\n check: false,\n })\n if (!opts.quiet) printOutcome(kind, report)\n if (report.outcome?.kind === \"failed\") failures += 1\n }\n\n if (opts.check && opts.optionalOnly) {\n // Both halves of this combination are silently empty: `--optional-only` makes\n // `kinds` empty, and `--check` skips the optional block. Left alone the\n // command prints nothing and exits 0, which reads as \"everything is fine\".\n if (!opts.quiet) {\n consola.warn(\n \"--check does not inspect the optional payloads (they are installed on demand), so --check --optional-only has nothing to report.\",\n )\n }\n return failures === 0 ? 0 : 1\n }\n\n if (opts.optional !== false && !opts.check && !optionalInstallDisabled()) {\n // Optional payloads are the difference between a 66 MB and a 586 MB install,\n // so they are NOT installed with the package. `update` is where a user asks\n // for the whole thing, and where a failure is visible instead of silently\n // degrading search quality. A failure here is a WARNING, never a non-zero\n // exit: reranking and structural search both have documented fallbacks.\n const wanted: ReadonlyArray<OptionalPackage> =\n opts.optionalPkg === undefined ? OPTIONAL_PACKAGES : [opts.optionalPkg]\n const results = []\n for (const pkg of wanted) {\n const result = await ensureOptionalPackage(pkg, { force: opts.force })\n results.push({ pkg, ...result })\n }\n for (const result of results) {\n if (result.dir) {\n if (!opts.quiet) consola.success(`${result.pkg} ready at ${result.dir}`)\n } else if (!opts.quiet) {\n consola.warn(`${result.pkg} unavailable: ${result.detail ?? \"unknown error\"}`)\n }\n }\n }\n\n return failures === 0 ? 0 : 1\n}\n\n/**\n * A bare `update` may also be the FIRST thing a user runs after `npm i -g`, in\n * which case there is nothing managed yet and the honest answer is \"here is where\n * it would go\". `checkForUpdate` already reports that as \"not installed → latest\",\n * so nothing extra is needed; the pointer read below is only for the debug line.\n */\nexport const update = defineCommand({\n meta: {\n name: \"update\",\n description: `Install or refresh the managed github-router/Pi payload (Pi floor ${PI_MIN_VERSION})`,\n },\n args: {\n self: {\n type: \"boolean\",\n default: false,\n description: \"Update github-router only\",\n },\n pi: {\n type: \"boolean\",\n default: false,\n description: \"Update the managed Pi only\",\n },\n check: {\n type: \"boolean\",\n default: false,\n description: \"Report what would change; install nothing\",\n },\n version: {\n type: \"string\",\n description: \"Install an exact version instead of npm's latest\",\n },\n force: {\n type: \"boolean\",\n default: false,\n description: \"Ignore the failure backoff and reinstall even if the version matches\",\n },\n quiet: {\n type: \"boolean\",\n default: false,\n description: \"Only report problems (used by the background self-install)\",\n },\n \"optional-only\": {\n type: \"boolean\",\n default: false,\n description:\n \"Install the heavy optional payloads and nothing else (internal: what a rerank or structural search spawns on demand)\",\n },\n \"optional-pkg\": {\n type: \"string\",\n description: `Install only this optional payload (${OPTIONAL_PACKAGES.join(\", \")}). Internal: used by --optional-only spawns so a grammar miss does not download the ONNX runtime.`,\n },\n optional: {\n type: \"boolean\",\n default: true,\n description:\n \"Also install the heavy optional payloads (transformers/ONNX for reranking, tree-sitter grammars) into the shared optional dir. --no-optional skips them; reranking then falls back to BM25F and structural ranking to the regex heuristic.\",\n },\n },\n async run({ args }) {\n // Validate BEFORE any work. An unknown name must not degrade to \"install\n // everything\": for this pair that means a 547 MB ONNX download triggered by\n // a typo, and it must not degrade to \"install nothing\" either, which would\n // look like success.\n const rawOptionalPkg = args[\"optional-pkg\"]\n if (\n rawOptionalPkg !== undefined\n && !(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg))\n ) {\n consola.error(\n `--optional-pkg must be one of: ${OPTIONAL_PACKAGES.join(\", \")} (got ${JSON.stringify(rawOptionalPkg)}).`,\n )\n process.exitCode = 2\n return\n }\n\n const pointer = await readPointer(\"self\", { verifyEntry: false })\n consola.debug(\n `managed: live self version ${pointer?.version ?? \"none\"} (live pointer ${await currentManagedVersion(\"self\") ?? \"none\"})`,\n )\n const code = await runUpdate({\n self: args.self,\n pi: args.pi,\n check: args.check,\n version: typeof args.version === \"string\" ? args.version : undefined,\n force: args.force,\n quiet: args.quiet,\n optional: args.optional,\n optionalOnly: args[\"optional-only\"],\n ...(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg)\n ? { optionalPkg: rawOptionalPkg }\n : {}),\n })\n process.exitCode = code\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,aAAa,MAA6E;CACxG,IAAI,KAAK,QAAQ,KAAK,IAAI,OAAO,CAAC,QAAQ,IAAI;CAC9C,IAAI,KAAK,MAAM,OAAO,CAAC,MAAM;CAC7B,IAAI,KAAK,IAAI,OAAO,CAAC,IAAI;CACzB,IAAI,KAAK,SAAS,OAAO,CAAC,MAAM;CAChC,OAAO,CAAC,QAAQ,IAAI;AACtB;AAEA,SAAS,WAAW,MAAmB,QAAqC;CAC1E,MAAM,QAAQ,SAAS,OAA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AAkB,cAAc,IAC3E;GACA,QAAQ,MACN,kCAAkC,kBAAkB,KAAK,IAAI,EAAE,QAAQ,KAAK,UAAU,cAAc,EAAE,GACxG;GACA,QAAQ,WAAW;GACnB;EACF;EAEA,MAAM,UAAU,MAAM,YAAY,QAAQ,EAAE,aAAa,MAAM,CAAC;EAChE,QAAQ,MACN,8BAA8B,SAAS,WAAW,OAAO,iBAAiB,MAAM,sBAAsB,MAAM,KAAK,OAAO,EAC1H;EACA,MAAM,OAAO,MAAM,UAAU;GAC3B,MAAM,KAAK;GACX,IAAI,KAAK;GACT,OAAO,KAAK;GACZ,SAAS,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU,KAAA;GAC3D,OAAO,KAAK;GACZ,OAAO,KAAK;GACZ,UAAU,KAAK;GACf,cAAc,KAAK;GACnB,GAAI,OAAO,mBAAmB,YAAY,kBAAkB,cAAc,IACtE,EAAE,aAAa,eAAe,IAC9B,CAAC;EACP,CAAC;EACD,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-CayD3y72.js";
|
|
2
2
|
// src/lib/worker-dispatch.ts
|
|
3
3
|
/**
|
|
4
4
|
* Frozen contract for the NON-BLOCKING workers surface.
|
|
@@ -248,4 +248,4 @@ Object.freeze({
|
|
|
248
248
|
});
|
|
249
249
|
export { dispatcherAgentName as a, dispatcherTools as c, decideWorkerGuard as i, guardToolMatcher as l, activeDispatchModes as n, dispatcherDescription as o, buildWorkerGuardHookCommand as r, dispatcherPrompt as s, ALL_WORKER_DISPATCH_MODES as t, parseModesCsv as u };
|
|
250
250
|
|
|
251
|
-
//# sourceMappingURL=worker-dispatch-
|
|
251
|
+
//# sourceMappingURL=worker-dispatch-DHZAfPO2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-dispatch-DBWKTMda.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI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AM,QAAQ,IAAI,IAAY,yBAAyB;CACvD,MAAM,MAAM,IACT,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,QAAQ,MAAM,MAAM,IAAI,CAAC,CAAC;CAC7B,OAAO,IAAI,SAAS,IAAI,MAAM,CAAC,GAAG,iBAAiB;AACrD;AAuC0F,OAAO,OAAO;CACtG,0BAA0B,OAAO,OAAO;EACtC,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,kBAAkB,OAAO,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;AACH,CAAC"}
|
|
1
|
+
{"version":3,"file":"worker-dispatch-DHZAfPO2.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,MAAsD;CACxF,OAAO,KAAK,SAAS,CAAC,GAAG,mBAAmB,kBAAkB,IAAI,CAAC,GAAG,iBAAiB;AACzF;AAEA,SAAS,YAAY,GAAmB;CACtC,OAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;;;;;;;;AASA,SAAgB,iBAAiB,YAAoB,OAAkD;CACrG,MAAM,MAAM,MAAM,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CACrD,OAAO,SAAS,YAAY,UAAU,EAAE,KAAK,IAAI;AACnD;;;AAIA,SAAgB,oBACd,UACA,YACA,OAC2B;CAC3B,MAAM,SAAS,QAAQ,WAAW;CAClC,IAAI,CAAC,SAAS,WAAW,MAAM,GAAG,OAAO;CACzC,MAAM,OAAO,SAAS,MAAM,OAAO,MAAM;CACzC,OAAQ,MAAgC,SAAS,IAAI,IAAK,OAA8B;AAC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;AACH,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as readWorkiqTokenFile, c as workiqTokenPath, n as WorkiqAuthError, o as runLoopbackAuth, p as WORKIQ_TOKEN_ENV, r as deleteWorkiqTokenFile, s as workiqTenant, t as AUTH_REMEDY } from "./token-
|
|
1
|
+
import { a as readWorkiqTokenFile, c as workiqTokenPath, n as WorkiqAuthError, o as runLoopbackAuth, p as WORKIQ_TOKEN_ENV, r as deleteWorkiqTokenFile, s as workiqTenant, t as AUTH_REMEDY } from "./token-BCzbNu8O.js";
|
|
2
2
|
import { defineCommand, showUsage } from "citty";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
// src/workiq.ts
|
|
@@ -140,4 +140,4 @@ const workiq = defineCommand({
|
|
|
140
140
|
});
|
|
141
141
|
export { workiq };
|
|
142
142
|
|
|
143
|
-
//# sourceMappingURL=workiq-
|
|
143
|
+
//# sourceMappingURL=workiq-CRBVCUA4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workiq-
|
|
1
|
+
{"version":3,"file":"workiq-CRBVCUA4.js","names":[],"sources":["../src/workiq.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * `github-router workiq` — manage the durable Work IQ sign-in.\n *\n * The proxy itself never prompts: `--workiq` provisioning calls\n * `ensureWorkiqToken()`, and a missing or dead login downgrades the group with\n * a pointer at `workiq auth` rather than stalling a launch. So this command is\n * the one interactive surface, and it is deliberately separate from any\n * command that starts a server.\n *\n * Nothing here prints a token. `auth` reports the account and the expiry,\n * `status` reports the same plus the file path, and both report the access\n * token only as the SHA-256 fingerprint prefix the refresh path already logs.\n */\n\nimport { defineCommand, showUsage } from \"citty\"\nimport consola from \"consola\"\n\nimport {\n AUTH_REMEDY,\n WorkiqAuthError,\n deleteWorkiqTokenFile,\n readWorkiqTokenFile,\n runLoopbackAuth,\n workiqTenant,\n workiqTokenPath,\n} from \"./lib/workiq/token\"\nimport { WORKIQ_TOKEN_ENV } from \"./lib/workiq/constants\"\n\ninterface RunWorkiqAuthOptions {\n tenant?: string\n loginHint?: string\n}\n\nexport async function runWorkiqAuth(options: RunWorkiqAuthOptions = {}): Promise<void> {\n try {\n const file = await runLoopbackAuth({\n ...(options.tenant ? { tenant: options.tenant } : {}),\n ...(options.loginHint ? { loginHint: options.loginHint } : {}),\n })\n consola.info(`Token file: ${workiqTokenPath()}`)\n consola.info(`Expires: ${new Date(file.expiresAtMs).toISOString()} (refreshes automatically)`)\n } catch (err) {\n if (err instanceof WorkiqAuthError) {\n consola.error(err.message)\n if (err.errorCode === \"invalid_grant\" || err.errorCode === \"interaction_required\") {\n consola.info(\"The refresh token is no longer valid. Sign in again to replace it.\")\n }\n process.exitCode = 1\n return\n }\n throw err\n }\n}\n\ninterface WorkiqStatus {\n signedIn: boolean\n tokenPath: string\n account?: string\n expiresAt?: string\n expired?: boolean\n scope?: string\n tenant?: string\n clientId?: string\n /** Set when `WORKIQ_MCP_TOKEN` short-circuits the file entirely. */\n envBearer?: boolean\n}\n\nasync function collectStatus(): Promise<WorkiqStatus> {\n const tokenPath = workiqTokenPath()\n const envBearer = Boolean(process.env[WORKIQ_TOKEN_ENV]?.trim())\n const file = await readWorkiqTokenFile(tokenPath)\n if (!file) return { signedIn: false, tokenPath, ...(envBearer ? { envBearer } : {}) }\n return {\n signedIn: true,\n tokenPath,\n ...(file.account ? { account: file.account } : {}),\n expiresAt: new Date(file.expiresAtMs).toISOString(),\n expired: file.expiresAtMs <= Date.now(),\n scope: file.scope,\n tenant: file.tenant,\n clientId: file.clientId,\n ...(envBearer ? { envBearer } : {}),\n }\n}\n\nexport async function runWorkiqStatus(options: { json: boolean }): Promise<void> {\n const status = await collectStatus()\n if (options.json) {\n console.log(JSON.stringify(status, null, 2))\n if (!status.signedIn) process.exitCode = 1\n return\n }\n if (!status.signedIn) {\n consola.warn(\"Not signed in to Work IQ.\")\n consola.info(AUTH_REMEDY)\n if (status.envBearer) consola.info(\"(WORKIQ_MCP_TOKEN is set, so the proxy uses that bearer.)\")\n process.exitCode = 1\n return\n }\n consola.info(`Account: ${status.account ?? \"(unknown)\"}`)\n consola.info(`Expires: ${status.expiresAt}${status.expired ? \" (expired; refreshes on next use)\" : \"\"}`)\n consola.info(`Tenant: ${status.tenant}`)\n consola.info(`Scope: ${status.scope}`)\n consola.info(`Token file: ${status.tokenPath}`)\n if (status.envBearer) {\n consola.info(`Note: ${WORKIQ_TOKEN_ENV} is set, so the proxy uses that bearer instead of this file.`)\n }\n}\n\nexport async function runWorkiqLogout(): Promise<void> {\n const removed = await deleteWorkiqTokenFile()\n if (removed) consola.success(`Work IQ sign-in removed (${workiqTokenPath()}).`)\n else consola.info(\"No Work IQ sign-in to remove.\")\n}\n\nconst auth = defineCommand({\n meta: {\n name: \"auth\",\n description: \"Sign in to Work IQ through the browser and store the refresh token\",\n },\n args: {\n tenant: {\n type: \"string\",\n description: `Entra tenant segment (default: ${workiqTenant()})`,\n },\n \"login-hint\": {\n type: \"string\",\n description: \"Account name to pre-select in the sign-in page\",\n },\n },\n run({ args }) {\n return runWorkiqAuth({\n ...(args.tenant ? { tenant: args.tenant } : {}),\n ...(args[\"login-hint\"] ? { loginHint: args[\"login-hint\"] } : {}),\n })\n },\n})\n\nconst status = defineCommand({\n meta: {\n name: \"status\",\n description: \"Print the stored Work IQ sign-in without revealing the token\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output status as JSON\",\n },\n },\n run({ args }) {\n return runWorkiqStatus({ json: args.json })\n },\n})\n\nconst logout = defineCommand({\n meta: {\n name: \"logout\",\n description: \"Delete the stored Work IQ sign-in\",\n },\n run() {\n return runWorkiqLogout()\n },\n})\n\nexport const workiq = defineCommand({\n meta: {\n name: \"workiq\",\n description: \"Manage the Work IQ (Microsoft 365) sign-in used by the workiq MCP group\",\n },\n subCommands: { auth, status, logout },\n run({ rawArgs }) {\n // A bare `github-router workiq` prints usage rather than silently doing\n // nothing; the default citty path would exit 0 with no output.\n if (rawArgs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B,EAAE,MAAM,KAAK,KAAK,CAAC;CAC5C;AACF,CAAC;AAED,MAAM,SAAS,cAAc;CAC3B,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,OAAO,gBAAgB;CACzB;AACF,CAAC;AAED,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,aAAa;EAAE;EAAM;EAAQ;CAAO;CACpC,IAAI,EAAE,WAAW;EAGf,IAAI,QAAQ,WAAW,GAAG,OAAO,UAAU,MAAM;CAEnD;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { gt as disposeWorkiqClients } from "./peer-mcp-personas-
|
|
1
|
+
export { gt as disposeWorkiqClients } from "./peer-mcp-personas-Dgog_ZJ8.js";
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { xt as disposeAdoClients } from "./peer-mcp-personas-Ckbn70c5.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { c as disposeBluebirdClients } from "./bluebird-client-BasIdv5J.js";
|
package/dist/engine-DCR1lSsw.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { C as runWorkerAgent } from "./peer-mcp-personas-Ckbn70c5.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"exec-BC0MAnoA.js","names":[],"sources":["../src/lib/exec.ts"],"sourcesContent":["/**\n * Windows-safe, injection-safe command execution helpers.\n *\n * Why this module exists: on Windows, npm-installed CLIs (`claude`,\n * `npm`, `codex`) are `.cmd`/`.bat` shims. Node's `execFile`/`spawn`\n * with `shell:false` cannot launch them (CreateProcess only resolves\n * `.exe`), so callers must invoke `cmd.exe` explicitly. Using\n * `shell:true` delegates quoting back to the runtime and breaks absolute shim\n * paths containing spaces, so this module builds one verified `/s /c`\n * envelope and asks CreateProcess to pass it verbatim. That opens two hazards\n * this module closes:\n *\n * 1. **Metacharacter injection** (`& | < > ^ ( ) ! %`). A naive\n * \"quote only tokens with spaces\" scheme lets `pkg@latest&calc`\n * run `calc` as a second command. `buildExecInvocation` applies\n * real cmd.exe quoting (argv-quote + caret-escape) and fails\n * closed on `%` (which cannot be reliably escaped on the cmd\n * command line).\n *\n * 2. **CWD shadowing.** `cmd.exe` resolves a bare `npm` from the\n * current directory before PATH, so an untrusted repo can plant\n * `npm.cmd`. `resolveExecutable` resolves to an absolute path\n * against PATH only (honoring PATHEXT), never the cwd, so callers\n * spawn the real binary by absolute path.\n *\n * All runners are best-effort and timeout-bounded; callers wrap in\n * try/catch and never let an update/probe failure block launch.\n */\n\nimport { spawn, spawnSync, type ChildProcess } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\n/**\n * Parse a boolean-ish env value. Returns `undefined` when unset or\n * unrecognized so callers can apply their own default. Accepts\n * `1|true|yes|on` (true) and `0|false|no|off|<empty>` (false),\n * case-insensitive. The single shared parser for all new `GH_ROUTER_*`\n * flags so on/off semantics don't drift per call site.\n */\nexport function parseBoolEnv(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined\n const v = value.trim().toLowerCase()\n if (v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\") return true\n if (v === \"0\" || v === \"false\" || v === \"no\" || v === \"off\" || v === \"\") {\n return false\n }\n return undefined\n}\n\n/**\n * Parse a positive-integer env value. Returns `undefined` when unset, empty, or\n * not a clean positive integer, so callers apply their own default.\n *\n * The single shared parser for numeric `GH_ROUTER_*` knobs, and it deliberately\n * uses `Number()` rather than `parseInt()`. `parseInt` stops at the first\n * character it cannot consume, so it silently truncates instead of rejecting:\n * `\"3e5\"` becomes 3, `\"300_000\"` becomes 300, `\"60000ms\"` becomes 60000. For a\n * timeout or a concurrency cap that is the worst possible failure — a user who\n * writes `GH_ROUTER_STOP_GATE_TIMEOUT_MS=3e5` intending five minutes gets three\n * MILLISECONDS, and the resulting instant failure looks like a product bug\n * rather than a typo. Falling back to the documented default is strictly safer\n * than honouring a number the user never meant.\n *\n * Found by a cross-lab reviewer during a capability audit, at three shipped call\n * sites, while three separate local helpers in this repo already parsed the same\n * shape correctly and one of them documented this exact hazard. That is the\n * argument for one shared parser rather than a fourth copy.\n */\nexport function parseIntEnv(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const raw = value.trim()\n if (raw === \"\") return undefined\n const n = Number(raw)\n if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return undefined\n return n\n}\n\n/** Read the PATH value from an env object, case-insensitively. */\nfunction pathValueOf(env: NodeJS.ProcessEnv): string {\n for (const key of Object.keys(env)) {\n if (key.toLowerCase() === \"path\") return env[key] ?? \"\"\n }\n return \"\"\n}\n\nexport interface ResolveExecutableOpts {\n env?: NodeJS.ProcessEnv\n platform?: NodeJS.Platform\n /** Directory to treat as \"current dir\" and exclude from resolution. */\n cwd?: string\n}\n\n/**\n * Resolve an executable name to an absolute path against PATH, honoring\n * `PATHEXT` on Windows and **excluding the current working directory**.\n *\n * Returns `null` when unresolved — callers treat that as \"tool absent\"\n * and skip (best-effort). Spawning the returned absolute path means\n * `cmd.exe`'s implicit cwd-first lookup never applies, closing the\n * planted-`npm.cmd` vector.\n */\nexport function resolveExecutable(\n name: string,\n opts: ResolveExecutableOpts = {},\n): string | null {\n const platform = opts.platform ?? process.platform\n const env = opts.env ?? process.env\n // Defensive: some test harnesses mock `node:process` without `cwd`.\n // Absent a usable cwd we simply skip the cwd-exclusion guard (the\n // returned absolute path already bypasses cmd.exe's cwd-first lookup).\n const cwdRaw =\n opts.cwd ?? (typeof process.cwd === \"function\" ? process.cwd() : undefined)\n const resolvedCwd = cwdRaw ? path.resolve(cwdRaw) : null\n\n const dirs = pathValueOf(env)\n .split(path.delimiter)\n // Drop empty entries and a literal \".\" — both denote the cwd on\n // Windows, which we explicitly refuse to resolve against.\n .filter((d) => d.length > 0 && d !== \".\")\n\n const isWin = platform === \"win32\"\n\n // POSIX: an explicit path component → resolve directly.\n if (!isWin && name.includes(\"/\")) {\n return existsSync(name) ? path.resolve(name) : null\n }\n // Windows: an explicit path component (with a separator) → direct.\n if (isWin && (name.includes(\"\\\\\") || name.includes(\"/\"))) {\n return existsSync(name) ? path.resolve(name) : null\n }\n\n const exts =\n isWin && path.extname(name) === \"\"\n ? (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim())\n .filter(Boolean)\n : [\"\"]\n\n for (const dir of dirs) {\n // Belt-and-suspenders: never resolve against the cwd even if it is\n // listed explicitly in PATH.\n if (resolvedCwd && path.resolve(dir) === resolvedCwd) continue\n for (const ext of exts) {\n const candidate = path.join(dir, name + ext)\n if (existsSync(candidate)) return candidate\n }\n }\n return null\n}\n\n/**\n * Quote one argument for a `cmd.exe /c \"<line>\"` command line so the\n * target program receives it verbatim and no `cmd.exe` metacharacter\n * retains shell meaning.\n *\n * Two phases (the canonical Windows approach — Colascione / Rust std):\n * 1. **argv quoting** so `CommandLineToArgvW` in the target parses\n * the token as one argument (double-quote, backslash-escape).\n * 2. **caret-escaping** every `cmd.exe` metacharacter — including the\n * quotes from phase 1 — so `cmd.exe` is never in quote-mode, strips\n * the carets, and hands the argv-quoted string to the program.\n *\n * `%` is special: it cannot be reliably escaped on the `cmd.exe`\n * *command line* (caret does not stop `%VAR%` expansion there). Rather\n * than mis-escape, we **throw** — our callers never pass `%`, so this\n * fails closed on the one unescapable injection vector.\n */\nexport function quoteWinArg(arg: string): string {\n if (arg.includes(\"%\")) {\n throw new Error(\n \"buildExecInvocation: argument contains '%', which cannot be safely \" +\n \"escaped on the Windows command line; refusing to build the command.\",\n )\n }\n\n // Phase 1 — argv quoting.\n let quoted: string\n if (arg.length > 0 && !/[ \\t\\n\\v\"&|<>()^!]/.test(arg)) {\n quoted = arg\n } else {\n let s = '\"'\n let backslashes = 0\n for (const ch of arg) {\n if (ch === \"\\\\\") {\n backslashes++\n } else if (ch === '\"') {\n s += \"\\\\\".repeat(backslashes * 2 + 1) + '\"'\n backslashes = 0\n } else {\n s += \"\\\\\".repeat(backslashes) + ch\n backslashes = 0\n }\n }\n s += \"\\\\\".repeat(backslashes * 2) + '\"'\n quoted = s\n }\n\n // Phase 2 — caret-escape all cmd.exe metacharacters (and the carets\n // themselves). cmd strips these; the program sees the phase-1 string.\n return quoted.replace(/[()!^\"<>&|]/g, \"^$&\")\n}\n\nexport interface ExecInvocation {\n command: string\n args: string[]\n shell: boolean\n /** Pass our already-quoted cmd.exe payload directly to CreateProcess. */\n windowsVerbatimArguments?: boolean\n}\n\nfunction assertSafeBatchToken(value: string, kind: \"executable\" | \"argument\"): void {\n const hasControl = [...value].some((char) => char.charCodeAt(0) < 0x20)\n if (hasControl || value.includes('\"') || value.includes(\"%\")) {\n throw new Error(\n `buildExecInvocation: ${kind} contains a character that cannot be `\n + \"safely passed through cmd.exe; refusing to build the command.\",\n )\n }\n}\n\nfunction quoteBatchArg(arg: string): string {\n assertSafeBatchToken(arg, \"argument\")\n // `/s` removes the envelope's outer quotes before cmd parses this token.\n // Quotes keep spaces, parentheses, and `!` (with /v:OFF) literal; the four\n // always-active operators and the caret itself still need caret escaping.\n return `\"${arg.replaceAll(\"^\", \"^^\").replace(/[&|<>]/g, \"^$&\")}\"`\n}\n\nfunction windowsCmdExe(): string {\n const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT\n return systemRoot\n ? path.win32.join(systemRoot, \"System32\", \"cmd.exe\")\n : (process.env.ComSpec ?? \"cmd.exe\")\n}\n\n/**\n * Is this a Windows batch script rather than a real executable?\n *\n * The distinction is load-bearing for every caller that spawns with\n * `shell:false`: CreateProcess only resolves `.exe`/`.com`, so a `.cmd`/`.bat`\n * path throws `EINVAL` at spawn time even though `resolveExecutable` returned\n * it happily. `buildExecInvocation` is the one helper that can use such a\n * path, because it routes it through `cmd.exe`; anywhere else a shim is\n * indistinguishable from a missing binary, and code that treats it as present\n * gets a failure it did not predict.\n *\n * The observed case: ast-grep installed globally through npm. `resolveAstGrep`\n * returned `ast-grep.cmd`, `runManagedExeCapture` threw `EINVAL`, and\n * `mode:\"ast\"` could not run on the canonical Windows host while the version\n * probe (which DOES go through `buildExecInvocation`) read the shim as a\n * perfectly adequate 0.45.3.\n */\nexport function isWindowsScriptShim(resolved: string): boolean {\n if (process.platform !== \"win32\") return false\n return /\\.(cmd|bat)$/i.test(resolved)\n}\n\n/**\n * Build the platform-correct `spawn` invocation for a command given as\n * an argv array. Pure / unit-testable (no spawn).\n *\n * - win32 native executables (`.exe`/`.com`) → direct spawn with split\n * argv. This avoids cmd.exe quoting and correctly handles absolute paths\n * containing spaces (for example `C:\\\\Program Files\\\\Git\\\\...\\\\git.exe`).\n * - win32 batch shims (`.cmd`/`.bat`) → explicit cmd.exe with `shell:false`\n * and one verbatim `/s /c` envelope. Every token is quoted, so shell\n * metacharacters are data; `%`, quotes, and controls fail closed.\n * - unresolved win32 bare commands retain the legacy quoted `shell:true`\n * path. Normal callers resolve first, so this is only a compatibility\n * fallback.\n * - posix → `(cmd[0], cmd.slice(1))` with `shell:false` — no shell,\n * no injection surface.\n */\nexport function buildExecInvocation(\n cmd: string[],\n platform: NodeJS.Platform = process.platform,\n): ExecInvocation {\n if (cmd.length === 0) throw new Error(\"buildExecInvocation: empty command\")\n if (platform === \"win32\") {\n const ext = path.extname(cmd[0]).toLowerCase()\n if (ext === \".exe\" || ext === \".com\") {\n return { command: cmd[0], args: cmd.slice(1), shell: false }\n }\n if (ext === \".cmd\" || ext === \".bat\") {\n if (!path.win32.isAbsolute(cmd[0])) {\n throw new Error(\n \"buildExecInvocation: Windows batch executable must be an absolute path\",\n )\n }\n assertSafeBatchToken(cmd[0], \"executable\")\n const line = `\"\"${cmd[0]}\"${cmd\n .slice(1)\n .map((arg) => ` ${quoteBatchArg(arg)}`)\n .join(\"\")}\"`\n return {\n command: windowsCmdExe(),\n args: [\"/d\", \"/s\", \"/v:OFF\", \"/c\", line],\n shell: false,\n windowsVerbatimArguments: true,\n }\n }\n return { command: cmd.map(quoteWinArg).join(\" \"), args: [], shell: true }\n }\n return { command: cmd[0], args: cmd.slice(1), shell: false }\n}\n\nexport interface RunOpts {\n cwd?: string\n /** Hard timeout in ms; the process tree is killed on expiry. */\n timeoutMs?: number\n /** Extra env to merge over the parent env for the child. */\n env?: NodeJS.ProcessEnv\n /** Abort the command and kill its process tree when the signal fires. */\n signal?: AbortSignal\n /**\n * Byte ceiling on captured stdout. Defaults to {@link DEFAULT_CAPTURE_CAP}.\n *\n * On overflow we STOP BUFFERING but deliberately do NOT kill the child, and\n * the result is reported as a normal completion with `truncated: true`. That\n * asymmetry against `runManagedExeCapture` (which tree-kills on overflow) is\n * load-bearing: callers here read the exit CODE as a verdict —\n * `~/lib/orchestration/live-exec` maps `code ?? 1` onto a FAILED GATE — so\n * killing the child would turn \"this command printed a lot\" into \"typecheck\n * failed\". Truncation is a capture-side limit, never a command outcome.\n *\n * The data handler keeps firing and discarding after the cap, so the pipe\n * drains and the child never blocks writing into a full buffer.\n */\n maxStdoutBytes?: number\n}\n\n/**\n * Default stdout capture ceiling.\n *\n * A `timeoutMs` is NOT a memory bound: `git diff HEAD` on a repo with a large\n * generated file happily emits hundreds of MB inside a 5s window, and every\n * byte was being concatenated onto one JS string. 16 MiB matches the worker\n * layer's `GH_ROUTER_WORKER_MAX_TOOL_BYTES` so the two capture paths agree on\n * what \"too much output to be useful\" means.\n */\nexport const DEFAULT_CAPTURE_CAP = 16 * 1024 * 1024\n\n/** Same ceiling shape for stderr, which only ever feeds diagnostics. */\nconst CAPTURE_STDERR_CAP = 64 * 1024\n\nexport interface RunResult {\n stdout: string\n stderr: string\n /** Exit code; `null` when killed by signal/timeout. */\n code: number | null\n timedOut: boolean\n /**\n * True when stdout exceeded the cap and was cut short. The command itself\n * still ran to completion — check this, never `code`, to detect truncation.\n */\n truncated: boolean\n /**\n * True when stderr exceeded its 64 KiB ceiling and was cut short.\n *\n * Reported separately from `truncated` because it means something different\n * to a caller: stdout truncation loses DATA, stderr truncation loses a\n * DIAGNOSTIC. A failing compiler often puts the root error at the tail of a\n * long stderr, so a caller that surfaces stderr to a human needs to know it\n * is looking at a prefix rather than the whole story.\n */\n stderrTruncated: boolean\n}\n\nfunction runInternal(\n cmd: string[],\n stdoutMode: \"pipe\" | \"inherit\" | \"ignore\",\n opts: RunOpts,\n): Promise<RunResult> {\n const { command, args, shell, windowsVerbatimArguments } =\n buildExecInvocation(cmd)\n return new Promise<RunResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell,\n windowsVerbatimArguments,\n windowsHide: true,\n stdio: [\n \"ignore\",\n stdoutMode,\n stdoutMode === \"inherit\" ? \"inherit\" : \"pipe\",\n ],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n // Buffer BYTES and decode once at the end (or incrementally through a\n // streaming decoder). The previous `stdout += chunk.toString(\"utf8\")` per\n // chunk corrupted any multi-byte character that straddled a chunk\n // boundary — a 3-byte `→` split 1/2 decoded as two replacement chars, so\n // captured diffs and command output silently mangled non-ASCII.\n const stdoutDecoder = new TextDecoder()\n const stderrDecoder = new TextDecoder()\n let stdout = \"\"\n let stderr = \"\"\n let stdoutBytes = 0\n let stderrBytes = 0\n let truncated = false\n let stderrTruncated = false\n let timedOut = false\n let settled = false\n const maxStdoutBytes = opts.maxStdoutBytes ?? DEFAULT_CAPTURE_CAP\n\n const timer = opts.timeoutMs\n ? setTimeout(() => {\n timedOut = true\n killTree(child.pid)\n }, opts.timeoutMs)\n : undefined\n timer?.unref?.()\n const onAbort = () => killTree(child.pid)\n if (opts.signal?.aborted) onAbort()\n else opts.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n // Past the cap: keep draining the pipe, stop growing the string. The\n // child is intentionally left alive (see `maxStdoutBytes` docs).\n if (truncated) return\n const room = maxStdoutBytes - stdoutBytes\n if (c.length > room) {\n // Append only the slice that fits, then stop. `stream: true` lets the\n // decoder hold a partial code point back rather than emit U+FFFD, so a\n // cap landing mid-character truncates cleanly instead of corrupting.\n if (room > 0) {\n stdout += stdoutDecoder.decode(c.subarray(0, room), { stream: true })\n stdoutBytes += room\n }\n truncated = true\n return\n }\n stdout += stdoutDecoder.decode(c, { stream: true })\n stdoutBytes += c.length\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n // Already full: this chunk is dropped entirely, which is truncation just\n // as much as a partial slice is. Flagging only the slicing chunk missed\n // the common case where the cap lands on a chunk boundary and every\n // subsequent chunk returns here.\n if (stderrBytes >= CAPTURE_STDERR_CAP) {\n stderrTruncated = true\n return\n }\n const room = CAPTURE_STDERR_CAP - stderrBytes\n const slice = c.length > room ? c.subarray(0, room) : c\n if (slice.length < c.length) stderrTruncated = true\n stderr += stderrDecoder.decode(slice, { stream: true })\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n // Flush the decoders' held-back bytes.\n //\n // NOT flushed on the truncated path: the cap deliberately cuts mid-byte-\n // sequence, so the decoder is holding a partial code point we chose to\n // drop. Flushing it would emit U+FFFD — turning a clean truncation into\n // apparent corruption, which is the exact failure this fix removes.\n // Un-truncated output has no such intent, so a trailing partial there IS\n // malformed input and should surface as U+FFFD rather than vanish.\n if (!truncated) stdout += stdoutDecoder.decode()\n if (!stderrTruncated) stderr += stderrDecoder.decode()\n resolve({ stdout, stderr, code, timedOut, truncated, stderrTruncated })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n opts.signal?.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Spawn `taskkill` best-effort, without any chance of taking the proxy down.\n *\n * Two things a bare `try { spawn(\"taskkill\", ...) } catch {}` gets wrong, both\n * of which this helper is the single place that fixes:\n *\n * 1. **The catch cannot catch.** `spawn` reports ENOENT / EPERM / EACCES by\n * emitting `'error'` ASYNCHRONOUSLY, so the surrounding `try` (which only\n * guards the synchronous throw) never sees it. An EventEmitter `'error'`\n * with no listener THROWS — which lands in the `uncaughtException` handler\n * in `~/main` and calls `process.exit(1)`. A best-effort child kill on a\n * timeout path could therefore kill the whole proxy. The listener must be\n * attached synchronously at the spawn site, which is why this is a helper\n * and not a convention.\n * 2. **The bare name is hijackable.** `CreateProcess`'s search order can\n * include the cwd, so `\"taskkill\"` may resolve to a planted binary;\n * `taskkillExe()` pins `System32\\taskkill.exe`.\n */\nexport function spawnTaskkillBestEffort(pid: number): boolean {\n try {\n const child = spawn(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n // Load-bearing: see (1) above. Without this an async spawn failure is an\n // uncaught exception, not a no-op. It is NOT a silent swallow, either —\n // the fallback below is what keeps a caller from hanging.\n //\n // (No logging here on purpose: this module has no logger import, and\n // taking one would pull a dependency into the lowest-level exec helper\n // that every other module builds on. The fallback is the observable\n // behavior that matters.)\n child.on(\"error\", () => {\n fallbackKill(pid)\n })\n return true\n } catch {\n // Synchronous spawn failure (bad argv shape).\n fallbackKill(pid)\n return false\n }\n}\n\n/**\n * Last-resort single-process kill when `taskkill` itself cannot run.\n *\n * Not a tree kill — grandchildren survive — but it is the difference between\n * \"the timed-out child dies and its `close` event settles the caller\" and \"the\n * caller waits forever\". `runInternal` resolves ONLY from `close`, so a timeout\n * whose kill never lands leaves that promise pending for the life of the\n * process, which is a worse failure than the crash `spawnTaskkillBestEffort`\n * was written to prevent. Best-effort by construction: ESRCH means the child\n * was already gone, which is the success case.\n */\nfunction fallbackKill(pid: number): void {\n try {\n process.kill(pid)\n } catch {\n // Already exited, or we lack permission — nothing further to try.\n }\n}\n\n/** Kill a process tree best-effort (taskkill /T on Windows). */\nfunction killTree(pid: number | undefined): void {\n if (!pid) return\n try {\n if (process.platform === \"win32\") {\n spawnTaskkillBestEffort(pid)\n } else {\n process.kill(pid, \"SIGTERM\")\n }\n } catch {\n // already gone\n }\n}\n\n/** Run a command and capture stdout/stderr. Rejects on spawn error. */\nexport function runCommandCapture(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command discarding output (still captures stderr for errors). */\nexport function runCommandVoid(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command with the child's stdout/stderr inherited to the user. */\nexport function runCommandInherit(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"inherit\", opts)\n}\n\nexport interface ManagedExeOpts extends RunOpts {\n /**\n * Hard cap on captured stdout bytes. On overflow the child is\n * tree-killed and the result carries `stdoutTruncated: true`. Defends\n * against a full-`CodeUnit` colgrep `--json` payload (source + 5\n * analysis layers per hit) bloating memory.\n */\n maxStdoutBytes?: number\n /**\n * When true, exceeding `maxStdoutBytes` does NOT tree-kill the child — it\n * sets `stdoutTruncated` and stops BUFFERING further stdout while still\n * draining the pipe (no backpressure). Use for a child whose kill is unsafe\n * (e.g. colgrep, which writes a non-atomic index — a byte-cap kill during\n * its result output could interrupt a write). The child runs to completion\n * (bounded by `timeoutMs` / `inactivityTimeoutMs`). Default false (kill).\n */\n truncateInsteadOfKill?: boolean\n /**\n * Called synchronously with the spawned child right after spawn\n * succeeds, BEFORE any output arrives. The colbert lifecycle ledger\n * uses this to register the child so a session-exit sweep can\n * tree-kill an orphan. Never throws into the runner.\n */\n onSpawn?: (child: ReturnType<typeof spawn>) => void\n /**\n * Inactivity (stall) watchdog. When set, a timer is armed for\n * `inactivityTimeoutMs` and RESET on every stdout/stderr data chunk. On\n * expiry (no output for the window) it consults `onInactivityCheck`: a\n * `true` return means \"still making progress via an out-of-band signal\"\n * (e.g. the colgrep index dir is still growing on disk even though the\n * process is silent on a non-TTY pipe) and the watchdog re-arms; a\n * `false`/absent return tree-kills the child and sets `stalled: true`.\n * This is the progress-based \"stuck\" detector that lets a long-but-\n * progressing build run to completion while still killing a hung one —\n * independent of the coarse total `timeoutMs` backstop.\n */\n inactivityTimeoutMs?: number\n /** External progress probe consulted when the inactivity timer fires.\n * Return `true` to re-arm (still progressing), `false`/throw to kill.\n * MUST be cheap + synchronous (called on a timer, not awaited). */\n onInactivityCheck?: () => boolean\n}\n\nexport interface ManagedExeResult extends RunResult {\n /** True iff stdout was truncated at `maxStdoutBytes` (child was killed). */\n stdoutTruncated: boolean\n /** True iff the inactivity watchdog killed the child (no progress). */\n stalled: boolean\n}\n\n/**\n * Run a **native executable** (a real `.exe`/Mach-O/ELF, NOT a `.cmd`\n * shim) capturing stdout/stderr, with `shell:false` on EVERY platform.\n *\n * Why a separate runner from `runCommandCapture`: that path routes\n * through `buildExecInvocation`, which on Windows builds a\n * `cmd.exe`-quoted command string and **throws on `%`** (`quoteWinArg`).\n * A workspace path can legally contain `%` (and `&`, `(`, `)`, `!`, …),\n * so the managed colgrep binary — which IS a native `.exe`, not a shim —\n * must bypass cmd.exe entirely. `spawn(absExe, args, {shell:false})`\n * resolves the `.exe` via CreateProcess directly: no cmd.exe, no\n * metacharacter hazard, no `%` refusal. POSIX was already `shell:false`.\n * This is what makes \"ANY absolute workspace\" hold on Windows.\n *\n * Lifecycle:\n * - `timeoutMs` → tree-kill on expiry (`taskkill /T /F` on Windows,\n * POSIX process-group `kill(-pgid)` so colgrep's rayon worker\n * children die too). `timedOut: true` in the result.\n * - `maxStdoutBytes` → tree-kill + `stdoutTruncated: true` once the\n * captured stdout exceeds the cap.\n * - `onSpawn(child)` → register the child with the caller's ledger.\n *\n * `command` MUST be an absolute path to the executable (the caller\n * resolves it; we never search PATH here — there is nothing to inject).\n */\nexport function runManagedExeCapture(\n command: string,\n args: ReadonlyArray<string>,\n opts: ManagedExeOpts = {},\n): Promise<ManagedExeResult> {\n const isWin = process.platform === \"win32\"\n return new Promise<ManagedExeResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, [...args], {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: false,\n windowsHide: true,\n // POSIX: new process group so we can kill the whole tree\n // (colgrep + rayon workers) with kill(-pgid). Windows uses\n // taskkill /T instead; `detached` there has no group semantics.\n detached: !isWin,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n try {\n opts.onSpawn?.(child)\n } catch {\n // ledger registration must never break the spawn\n }\n\n const chunks: Array<Buffer> = []\n let stdoutBytes = 0\n const stderrChunks: Array<Buffer> = []\n let stderrBytes = 0\n const STDERR_CAP = 64 * 1024\n let timedOut = false\n let stdoutTruncated = false\n let stalled = false\n let settled = false\n\n // Exactly one terminator wins: the first to fire records its reason and\n // tree-kills; later ones no-op. Keeps timedOut / stalled / stdoutTruncated\n // mutually exclusive and avoids a double tree-kill.\n let terminated = false\n const terminate = (reason: \"timeout\" | \"stall\" | \"truncate\"): void => {\n if (terminated) return\n terminated = true\n if (reason === \"timeout\") timedOut = true\n else if (reason === \"stall\") stalled = true\n else stdoutTruncated = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n killManagedTree(child, isWin)\n }\n\n const timer = opts.timeoutMs\n ? setTimeout(() => terminate(\"timeout\"), opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n // Inactivity (stall) watchdog. Re-arms itself: when the window elapses\n // with no output, consult the external progress probe — re-arm if it\n // says \"still progressing\" (e.g. the index dir grew), else kill + mark\n // stalled. Reset on every data chunk (a chatty process never stalls).\n let inactivityTimer: ReturnType<typeof setTimeout> | undefined\n const armInactivity = (): void => {\n if (opts.inactivityTimeoutMs === undefined || settled || terminated) return\n inactivityTimer = setTimeout(() => {\n if (settled) return\n // No probe → pure output-inactivity kill. A probe that THROWS is\n // inconclusive → don't kill (re-arm); the absolute timeoutMs backstop\n // still catches a genuinely wedged process.\n let progressing = false\n if (opts.onInactivityCheck) {\n try {\n progressing = opts.onInactivityCheck() === true\n } catch {\n progressing = true\n }\n }\n if (progressing) {\n armInactivity()\n return\n }\n terminate(\"stall\")\n }, opts.inactivityTimeoutMs)\n inactivityTimer?.unref?.()\n }\n const resetInactivity = (): void => {\n if (inactivityTimer) clearTimeout(inactivityTimer)\n armInactivity()\n }\n armInactivity()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n if (stdoutTruncated) return\n stdoutBytes += c.length\n if (\n opts.maxStdoutBytes !== undefined &&\n stdoutBytes > opts.maxStdoutBytes\n ) {\n stdoutTruncated = true\n // Default: tree-kill on overflow. Opt-in: keep the child alive and\n // just stop buffering (the data handler keeps firing + discarding via\n // the `if (stdoutTruncated) return` guard above, so the pipe drains\n // and the child never blocks on a full buffer).\n if (!opts.truncateInsteadOfKill) terminate(\"truncate\")\n return\n }\n chunks.push(c)\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n // Hard byte cap on stderr — append only the slice that fits so a\n // single huge chunk can't overshoot. Never logged raw (it can\n // embed source code from colgrep).\n if (stderrBytes >= STDERR_CAP) return\n const remaining = STDERR_CAP - stderrBytes\n const slice = c.length > remaining ? c.subarray(0, remaining) : c\n stderrChunks.push(slice)\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n resolve({\n stdout: Buffer.concat(chunks).toString(\"utf8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf8\"),\n code,\n timedOut,\n stdoutTruncated,\n // `RunResult.truncated` is the shared, runner-agnostic signal. Kept in\n // lockstep with `stdoutTruncated` (this runner's older, more specific\n // name, which callers already branch on) so a caller holding either\n // shape reads the same fact.\n truncated: stdoutTruncated,\n // This runner slices stderr to fit its own 64 KiB cap without tracking\n // whether it did, so report the honest thing rather than guess.\n stderrTruncated: stderrBytes >= STDERR_CAP,\n stalled,\n })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Tree-kill a managed child. Windows: `taskkill /T /F /PID` (whole\n * tree). POSIX: kill the process GROUP (`-pgid`) so colgrep's rayon\n * worker children die with the parent.\n *\n * `runManagedExeCapture` always spawns POSIX children `detached:true`\n * (their own process group), so the group kill is the correct and\n * sufficient primitive. We deliberately do NOT fall back to a positive-\n * pid `process.kill(pid)` when the group kill fails: by the time a kill\n * fires (timeout / byte-cap race), the child may have already exited and\n * its PID been recycled by an unrelated process — a positive-pid kill\n * would then target the wrong process. `ESRCH` (group already gone) is\n * the success case for our purposes; any other error is swallowed.\n */\nexport function killManagedTree(\n child: ReturnType<typeof spawn>,\n isWin: boolean = process.platform === \"win32\",\n): void {\n const pid = child.pid\n if (!pid) return\n try {\n if (isWin) {\n spawnTaskkillBestEffort(pid)\n } else {\n // Negative pid → the process group (we spawned detached). No\n // positive-pid fallback (PID-reuse hazard — see doc comment).\n process.kill(-pid, \"SIGKILL\")\n }\n } catch {\n // ESRCH (already gone) / EPERM — best-effort, nothing more to do.\n }\n}\n\n/**\n * Absolute path to Windows `taskkill.exe`. Bare `\"taskkill\"` would let\n * `CreateProcess`'s search order (which can include the cwd) run a planted\n * `taskkill.exe`; pinning the System32 path closes that hijack.\n */\nfunction taskkillExe(): string {\n const root =\n process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\"\n return path.join(root, \"System32\", \"taskkill.exe\")\n}\n\n/**\n * Tree-kill a child process on a SHUTDOWN/exit path, deterministically.\n *\n * Distinct from `killManagedTree` in two ways that matter when the proxy\n * is about to call `process.exit`:\n *\n * 1. **Windows uses `spawnSync`, not async `spawn`.** An async taskkill\n * may never issue before `process.exit` tears the event loop down;\n * the synchronous form guarantees the kill command has run. It is\n * time-bounded so a wedged taskkill can't hang shutdown.\n * 2. **POSIX honors `detachedGroup`.** The launched CLI is spawned\n * `detached:true` (its own process group) so `kill(-pid)` reaps the\n * whole group; other callers (e.g. ripgrep) are NOT detached, so\n * `child.kill()` on the positive pid is correct. A negative-pid kill\n * on a non-detached child would throw or hit the wrong target.\n *\n * Both branches escalate SIGTERM → SIGKILL after `graceMs` so a CLI that\n * traps SIGTERM still dies. The escalation timer is `.unref()`'d so it\n * never holds the event loop open. Errors are swallowed (already-gone /\n * EBUSY / ESRCH are the success case for our purposes).\n */\nexport function killChildProcessTree(\n child: ChildProcess,\n opts: { detachedGroup: boolean; graceMs?: number } = { detachedGroup: false },\n): void {\n const pid = child.pid\n if (!pid) return\n const graceMs = opts.graceMs ?? 500\n\n if (process.platform === \"win32\") {\n // /T = whole tree, /F = force. taskkill walks the live parent-PID\n // chain, so it reaps grandchildren regardless of the cmd.exe-vs-direct\n // spawn shape. Sync (completes before an imminent process.exit) and\n // time-bounded (a wedged taskkill must not hang shutdown).\n try {\n spawnSync(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n timeout: 5000,\n })\n } catch {\n // Already gone / EBUSY race — best-effort.\n }\n return\n }\n\n // POSIX: signal the group (detached) or the lone child (non-detached).\n const target = opts.detachedGroup ? -pid : pid\n try {\n process.kill(target, \"SIGTERM\")\n } catch {\n // ESRCH — already gone.\n }\n const t = setTimeout(() => {\n // For a lone (non-detached) child, skip escalation once it has exited\n // — its positive PID could have been recycled. For a process GROUP the\n // leader's exit does NOT mean the group is empty (a SIGTERM-ignoring\n // grandchild may survive), and the group id is only reused once the\n // group is fully gone, so always attempt the group SIGKILL (ESRCH when\n // already empty is the success case).\n if (\n !opts.detachedGroup &&\n (child.exitCode !== null || child.signalCode !== null)\n ) {\n return\n }\n try {\n process.kill(target, \"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;;;;;;;;;;;;AAuBA,SAAgB,qBACd,OACA,OAAqD,EAAE,eAAe,MAAM,GACtE;CACN,MAAM,MAAM,MAAM;CAClB,IAAI,CAAC,KAAK;CACV,MAAM,UAAU,KAAK,WAAW;CAEhC,IAAI,QAAQ,aAAa,SAAS;EAKhC,IAAI;GACF,UAAU,YAAY,GAAG;IAAC;IAAM;IAAM;IAAQ,OAAO,GAAG;GAAC,GAAG;IAC1D,OAAO;IACP,aAAa;IACb,SAAS;GACX,CAAC;EACH,QAAQ,CAER;EACA;CACF;CAGA,MAAM,SAAS,KAAK,gBAAgB,CAAC,MAAM;CAC3C,IAAI;EACF,QAAQ,KAAK,QAAQ,SAAS;CAChC,QAAQ,CAER;CACU,iBAAiB;EAOzB,IACE,CAAC,KAAK,kBACL,MAAM,aAAa,QAAQ,MAAM,eAAe,OAEjD;EAEF,IAAI;GACF,QAAQ,KAAK,QAAQ,SAAS;EAChC,QAAQ,CAER;CACF,GAAG,OACH,CAAC,CAAC,QAAQ;AACZ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { o as sweepStaleColbertMetaAtBoot } from "./lifecycle-BlC_kzNt.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { o as sweepStaleWorktreesAtBoot } from "./lifecycle-COZhARmE.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"optional-DGAeyguL.js","names":["fs"],"sources":["../src/lib/managed-install/optional.ts"],"sourcesContent":["/**\n * On-demand install of the heavy optional payloads.\n *\n * `@huggingface/transformers` (~547 MB with its ONNX runtime) and\n * `tree-sitter-wasms` (~49 MB of grammars) are the entire difference between a\n * 66 MB install and a 586 MB one. The plan moves them to **optional** peers so\n * nobody pays for them at install time — which has one blunt consequence that\n * must be stated plainly: **optional peers are installed for nobody**, at any\n * depth, by npm and by bun alike (measured). So \"optional\" cannot mean \"the\n * usual install will bring it\"; it has to mean \"we install it the first time\n * something actually needs it\".\n *\n * Three rules shape this file:\n *\n * 1. **One copy per machine, shared across versions.** The payload lands in\n * `<APP_DIR>/optional/<pkg>@<version>/`, never inside a managed version dir:\n * those are per-version and GC keeps two, so an in-tree copy would be 1.1 GB\n * and would be re-fetched on every bump.\n * 2. **Failure is always allowed.** Reranking falls back to BM25F and structural\n * ranking to the regex heuristic; both already warn for exactly this case.\n * Nothing here may ever make a search or a chat request fail.\n * 3. **Off the hot path.** Resolution (is a usable copy present?) is a couple of\n * `stat`s against a bounded directory listing, and it is synchronous because\n * both consumers are. Installation is a separate, throttled, detached child;\n * the request that noticed the gap proceeds without it.\n *\n * Supply-chain posture matches the managed installer: exact version, scrubbed\n * npm env, `--ignore-scripts`, `--no-global`, provenance from the lockfile.\n */\n\nimport fs from \"node:fs/promises\"\nimport { existsSync, readdirSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { writeFileAtomic, readFileWithRetry } from \"../atomic-file\"\nimport { parseBoolEnv, resolveExecutable, runCommandCapture } from \"../exec\"\nimport { buildNpmEnv } from \"./npm-env\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport { VERSION_RE, isTransientName, isVersionName, optionalRoot, randomHex } from \"./paths\"\n\n/** The packages that may be installed on demand. */\nexport const OPTIONAL_PACKAGES = [\"@huggingface/transformers\", \"tree-sitter-wasms\"] as const\nexport type OptionalPackage = (typeof OPTIONAL_PACKAGES)[number]\n\n/**\n * Entry file that must exist for a copy to count as installed.\n *\n * A package directory alone is not enough: an interrupted `npm install` can\n * leave `node_modules/<pkg>` in place with its payload missing, and an\n * on-demand install is precisely the kind that gets interrupted (the user\n * quits, the machine sleeps). These are the exact files the two consumers load.\n */\nexport const OPTIONAL_REQUIRED_FILE: Readonly<Record<OptionalPackage, string>> = {\n \"@huggingface/transformers\": \"dist/transformers.node.mjs\",\n // The filename must be the one the package actually ships:\n // `tree-sitter-wasms@0.1.13/out/tree-sitter-typescript.wasm`. A wrong name\n // here is not a loud failure — the install SUCCEEDS, `completeAt` then refuses\n // the payload, structural ranking silently keeps using the regex fallback,\n // and the package state backs off for an hour pretending npm broke.\n \"tree-sitter-wasms\": \"out/tree-sitter-typescript.wasm\",\n}\n\n/**\n * The peer range each payload must satisfy, mirroring `package.json`.\n *\n * On-demand installation used to take whatever `npm view <pkg> version` said,\n * which is unbounded: the day transformers 5.x ships, every machine fetches a\n * major the router has never run — and `completeAt` refusing the payload turns\n * that into a one-hour backoff that hides the cause. Bounding the query\n * (`npm view <pkg>@<range> version`) makes npm do the range arithmetic, so the\n * answer is by construction compatible. `tests/optional-payload-manifest.test.ts`\n * asserts this table still matches `package.json#peerDependencies`.\n */\nexport const OPTIONAL_VERSION_RANGE: Readonly<Record<OptionalPackage, string>> = {\n \"@huggingface/transformers\": \"^4.3.2\",\n \"tree-sitter-wasms\": \"^0.1.13\",\n}\n\n/** `<pkg>` → the directory name used under `optional/` (`@scope/name` is unsafe). */\nfunction sanitized(pkg: string): string {\n return pkg.replace(\"/\", \"__\")\n}\n\n/**\n * Test seam: what a slot actually installs.\n *\n * The install mechanics (staging, verify, publish-by-rename, provenance, GC) are\n * identical for a 547 MB ONNX payload and for a 6 KB package with no scripts, but\n * only one of them can run in a test. Overriding via a seam keeps ONE code path\n * instead of a re-implementation in the test that could pass while production\n * breaks. Nothing in `src/` calls the setters.\n */\ninterface OptionalSubject {\n packageName: string\n requiredFile: string\n version: string | null\n /** Peer range to resolve within; the real table by default. */\n range: string | null\n}\nconst subjects = new Map<OptionalPackage, OptionalSubject>()\n\nfunction subjectFor(pkg: OptionalPackage): OptionalSubject {\n return (\n subjects.get(pkg) ?? {\n packageName: pkg,\n requiredFile: OPTIONAL_REQUIRED_FILE[pkg],\n version: null,\n range: OPTIONAL_VERSION_RANGE[pkg],\n }\n )\n}\n\n/** @internal — point one slot at a throwaway package. */\nexport function __setOptionalTestSubject(input: {\n pkg: OptionalPackage\n packageName: string\n requiredFile: string\n version?: string\n}): void {\n subjects.set(input.pkg, {\n packageName: input.packageName,\n requiredFile: input.requiredFile,\n version: input.version ?? null,\n // A test stand-in (`is-number`) has its own version, so bind it to itself\n // rather than to the real package's peer range.\n range: input.version ? input.version : null,\n })\n}\n\n/** @internal — restore the real subjects. */\nexport function __resetOptionalTestSubject(): void {\n subjects.clear()\n}\n\n/**\n * True when the user disabled on-demand payloads.\n *\n * Uses the shared `parseBoolEnv`, not a local `raw === \"1\" || raw === \"true\"`:\n * `GH_ROUTER_NO_OPTIONAL_INSTALL=TRUE` or `=yes` used to be unrecognised and\n * silently *enabled* a 547 MB download, which is the worst possible way for an\n * off switch to fail.\n */\nexport function optionalInstallDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_NO_OPTIONAL_INSTALL) === true\n}\n\n/** The `node_modules/<pkg>` directory inside an installed optional copy. */\nfunction payloadDir(target: string, pkg: OptionalPackage): string {\n return path.join(target, \"node_modules\", ...subjectFor(pkg).packageName.split(\"/\"))\n}\n\n/** Is `target` a complete payload? */\nfunction completeAt(target: string, pkg: OptionalPackage): boolean {\n const dir = payloadDir(target, pkg)\n return (\n existsSync(path.join(dir, \"package.json\"))\n && existsSync(path.join(dir, subjectFor(pkg).requiredFile))\n )\n}\n\n/**\n * A usable installed copy of `pkg`, preferring the NEWEST version present.\n *\n * Synchronous on purpose: `resolveGrammarRoot()` and the rerank loader are\n * called from synchronous contexts, and a promise here would force an `await`\n * onto a path that must stay cheap. The listing is small (one entry per\n * installed version, typically one).\n *\n * Returns the package directory (the thing a consumer imports from), not the\n * `optional/<pkg>@<ver>` prefix.\n */\nexport function installedOptional(pkg: OptionalPackage): string | null {\n const [newest] = completeTargets(pkg)\n return newest ? payloadDir(newest, pkg) : null\n}\n\n/**\n * Every COMPLETE `<root>/<pkg>@<version>` target dir, newest version first.\n *\n * Split out of `installedOptional` because two callers need the target dir\n * itself rather than the package dir inside it: the upgrade check (\"is the\n * version we just resolved already here?\") and the GC protection list (\"spare\n * the copy this process is using\").\n */\nfunction completeTargets(pkg: OptionalPackage): Array<string> {\n const root = optionalRoot()\n let names: Array<string>\n try {\n names = readdirSync(root)\n } catch {\n return []\n }\n const prefix = `${sanitized(pkg)}@`\n const candidates = names\n .filter((name) => name.startsWith(prefix) && !name.startsWith(\".\"))\n .map((name) => ({ name, version: name.slice(prefix.length) }))\n .filter((entry) => isVersionName(entry.version))\n // Newest first: a stale older copy must never shadow a fresh one.\n .sort((a, b) => compareVersions(b.version, a.version))\n\n const out: Array<string> = []\n for (const candidate of candidates) {\n const target = path.join(root, candidate.name)\n if (completeAt(target, pkg)) out.push(target)\n }\n return out\n}\n\n/** Where `pkg@version` would live. */\nexport function optionalTarget(pkg: OptionalPackage, version: string): string {\n return path.join(optionalRoot(), `${sanitized(pkg)}@${version}`)\n}\n\n/** `payloadDir` for exactly `pkg@version`, or null when that copy is not complete. */\nfunction installedOptionalTarget(pkg: OptionalPackage, version: string): string | null {\n const target = optionalTarget(pkg, version)\n return completeAt(target, pkg) ? payloadDir(target, pkg) : null\n}\n\n// ---------------------------------------------------------------------------\n// Backoff + GC state\n// ---------------------------------------------------------------------------\n\n/**\n * `optional/install-state.json`.\n *\n * Separate from `m/<kind>/install-state.json` because the lifecycles are\n * separate: pruning the managed tree must never reset (or inherit) a failing\n * optional install's ladder, and the optional ladder is per PACKAGE.\n */\ninterface OptionalState {\n packages?: Partial<\n Record<\n OptionalPackage,\n {\n lastAttemptAt?: string\n lastSuccessAt?: string\n consecutiveFailures?: number\n nextAttemptAt?: string\n lastError?: string\n version?: string\n }\n >\n >\n}\n\nconst BACKOFF_HOURS = [1, 6, 24] as const\nconst KEEP_OPTIONAL_VERSIONS = 2\nconst OPTIONAL_FLOOR_MS = 30 * 24 * 60 * 60_000\n\nfunction statePath(): string {\n return path.join(optionalRoot(), \"install-state.json\")\n}\n\nasync function readState(): Promise<OptionalState> {\n try {\n const raw = await readFileWithRetry(statePath(), { retryMissing: false })\n const parsed = JSON.parse(raw) as OptionalState\n return typeof parsed === \"object\" && parsed !== null ? parsed : {}\n } catch {\n return {}\n }\n}\n\nasync function patchState(\n pkg: OptionalPackage,\n patch: Partial<NonNullable<OptionalState[\"packages\"]>[OptionalPackage] & object>,\n): Promise<void> {\n try {\n const state = await readState()\n const next: OptionalState = {\n ...state,\n packages: { ...(state.packages ?? {}), [pkg]: { ...(state.packages?.[pkg] ?? {}), ...patch } },\n }\n // `undefined` means delete — how a success clears the ladder.\n for (const [key, value] of Object.entries(next.packages?.[pkg] ?? {})) {\n if (value === undefined) delete (next.packages![pkg] as Record<string, unknown>)[key]\n }\n await fs.mkdir(optionalRoot(), { recursive: true })\n await writeFileAtomic(statePath(), `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o644 })\n } catch (err) {\n reportManagedDiagnostic(\"debug\", `optional: could not write state: ${String(err)}`)\n }\n}\n\nfunction nextAttemptAtFor(failures: number): string {\n const index = Math.min(Math.max(failures, 1), BACKOFF_HOURS.length) - 1\n return new Date(Date.now() + (BACKOFF_HOURS[index] ?? 24) * 3_600_000).toISOString()\n}\n\n/**\n * Whether an attempt may start — a RESERVATION is not a backoff.\n *\n * `nextAttemptAt` is written before every attempt so two processes cannot both\n * download a 500 MB payload, and it is also the ladder's output. Conflating them\n * makes `github-router update` (issued while an on-demand install is still\n * running, seconds after it reserved) report \"backing off after a failed\n * tree-sitter-wasms install\" when nothing had failed. With `consecutiveFailures`\n * still 0 the window is a reservation, so re-attempting is allowed; the loser of\n * the rename race adopts the winner's payload.\n */\nasync function mayAttemptNow(pkg: OptionalPackage): Promise<boolean> {\n const entry = (await readState()).packages?.[pkg]\n if ((entry?.consecutiveFailures ?? 0) === 0) return true\n if (!entry?.nextAttemptAt) return true\n const next = new Date(entry.nextAttemptAt).getTime()\n return Number.isNaN(next) ? true : Date.now() >= next\n}\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nexport interface EnsureOptionalResult {\n /** The `node_modules/<pkg>` directory when usable, else null. */\n dir: string | null\n detail?: string\n installed?: boolean\n}\n\n/**\n * Make sure `pkg` is installed and return its directory.\n *\n * Fail-open and throttled: a failure is remembered on the standard ladder, so a\n * permanently offline machine does not spawn an npm process per search.\n */\nexport async function ensureOptionalPackage(\n pkg: OptionalPackage,\n opts: { signal?: AbortSignal; force?: boolean; registry?: string } = {},\n): Promise<EnsureOptionalResult> {\n if (optionalInstallDisabled()) {\n return { dir: null, detail: \"GH_ROUTER_NO_OPTIONAL_INSTALL is set\" }\n }\n if (!opts.force && !(await mayAttemptNow(pkg))) {\n return { dir: null, detail: `backing off after a failed ${pkg} install` }\n }\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) {\n // No npm is not a reason to refuse a payload that is already installed.\n const existing = installedOptional(pkg)\n return existing ? { dir: existing } : { dir: null, detail: \"npm is not on PATH\" }\n }\n\n // Resolve FIRST, then compare against what is installed.\n //\n // The obvious order — \"anything installed? return it\" — makes the payload\n // permanently un-upgradable: the first install wins forever, `update` keeps\n // reporting the stale copy \"ready\", and a fix for a broken payload can never\n // reach a machine that already has one. `installedOptional` prefers the newest\n // copy but cannot know whether a NEWER version exists.\n const version = await resolveOptionalVersion(pkg, opts.registry)\n // A payload dir, so it can be returned as-is (wrapping it in `payloadDir` again\n // produced `<pkg>/node_modules/<pkg>/node_modules/<pkg>`).\n const existing = version ? installedOptionalTarget(pkg, version) : installedOptional(pkg)\n if (existing && !opts.force) return { dir: existing }\n\n if (!version) {\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n consecutiveFailures: 1,\n nextAttemptAt: nextAttemptAtFor(1),\n lastError: \"could not resolve a version to install\",\n })\n return { dir: null, detail: `could not resolve a version for ${pkg}` }\n }\n\n const target = optionalTarget(pkg, version)\n // A concurrent install may have published it while we resolved.\n if (completeAt(target, pkg)) return { dir: payloadDir(target, pkg), installed: false }\n\n // The newest copy this machine already had, captured BEFORE the install so GC\n // can be told to spare it (see the `gcOptional` call below). A running process\n // may have it memory-mapped: the ONNX runtime is loaded lazily, so \"this\n // process installed the newer one\" says nothing about whether it is still\n // reading the older one.\n const [previousTarget] = completeTargets(pkg)\n\n // Reservation only, with the ladder value keyed on the REAL failure count: a\n // first attempt has `consecutiveFailures` 0, which `mayAttemptNow` treats as\n // \"not a backoff\".\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n nextAttemptAt: nextAttemptAtFor((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0),\n })\n\n try {\n await installInto(pkg, version, target, npmPath, opts.registry, opts.signal)\n await patchState(pkg, {\n lastSuccessAt: new Date().toISOString(),\n consecutiveFailures: 0,\n nextAttemptAt: undefined,\n lastError: undefined,\n version,\n })\n // Protect BOTH the copy this process was already using (a rerank that has the\n // ONNX runtime loaded memory-maps files from it) and the one just installed.\n // GC removes by age + rank, and \"rank\" cannot see a running\n // process: on POSIX an `fs.rm` of a mapped directory SUCCEEDS (`EBUSY` only\n // rescues Windows), so the next lazy load in that process dies. Protecting\n // these two names is the whole of what this process can know; the 30-day\n // floor and keep-2 rule cover the rest.\n const protect = [path.basename(target)]\n if (previousTarget) protect.push(previousTarget)\n await gcOptional(Date.now(), protect).catch(() => {})\n return { dir: payloadDir(target, pkg), installed: true }\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n const failures = ((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0) + 1\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n consecutiveFailures: failures,\n nextAttemptAt: nextAttemptAtFor(failures),\n lastError: detail,\n })\n return { dir: null, detail }\n }\n}\n\n/**\n * Install `pkg@version` into `target` via a staging sibling.\n *\n * Same publish discipline as the managed installer (build in `.staging-*`,\n * verify the entry, rename into place) and for the same reason: the target may\n * be read concurrently by a running request, and a half-written payload that\n * passes a directory-existence check is worse than no payload.\n */\nasync function installInto(\n pkg: OptionalPackage,\n version: string,\n target: string,\n npmPath: string,\n registry?: string,\n signal?: AbortSignal,\n): Promise<void> {\n const root = optionalRoot()\n await fs.mkdir(root, { recursive: true })\n const staging = path.join(root, `.staging-${process.pid}-${randomHex()}`)\n // Not `recursive`: the name is unique, so an EEXIST means a leftover tree from\n // a same-pid attempt, and installing into it would let an INHERITED copy pass\n // the completeness check below. Fail and let the caller retry.\n await fs.mkdir(staging)\n try {\n const pkgJson = {\n name: `gh-router-optional-${sanitized(pkg)}`,\n private: true,\n version: \"0.0.0\",\n dependencies: { [subjectFor(pkg).packageName]: version },\n }\n await writeFileAtomic(path.join(staging, \"package.json\"), `${JSON.stringify(pkgJson, null, 2)}\\n`, {\n mode: 0o644,\n })\n\n const overrides: NodeJS.ProcessEnv = {}\n if (registry) overrides.npm_config_registry = registry\n const { env } = buildNpmEnv(process.env, overrides)\n\n reportManagedDiagnostic(\"info\", `Installing optional ${pkg}@${version} (one-time)…`)\n const { code, stderr } = await runCommandCapture(\n [\n npmPath,\n \"install\",\n \"--no-global\",\n \"--no-dry-run\",\n \"--include=optional\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--no-fund\",\n \"--loglevel=error\",\n ...(registry ? [`--registry=${registry}`] : []),\n ],\n { cwd: staging, env, timeoutMs: 30 * 60_000, signal },\n )\n if (code !== 0) {\n throw new Error(`npm install ${pkg}@${version} failed (exit ${code}): ${stderr.slice(0, 400)}`)\n }\n if (!completeAt(staging, pkg)) {\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but ${subjectFor(pkg).requiredFile} is missing`,\n )\n }\n // The required file existing is not the same as the right version being\n // installed: a stale tree, a mirror serving another tarball, or a `--omit`\n // config that slipped through all look complete. The rename below publishes\n // this directory, so verify identity before that.\n try {\n const declared = (\n JSON.parse(await fs.readFile(path.join(payloadDir(staging, pkg), \"package.json\"), \"utf8\")) as {\n version?: unknown\n }\n ).version\n if (declared !== version) {\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but its package.json declares ${JSON.stringify(declared)}; refusing to publish it`,\n )\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"refusing to publish\")) throw err\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but its package.json is unreadable: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n )\n }\n const packages = await harvestProvenance(staging)\n await writeFileAtomic(\n path.join(staging, \".installed.json\"),\n `${JSON.stringify({ version, packages, installedAt: new Date().toISOString() }, null, 2)}\\n`,\n { mode: 0o644 },\n )\n\n try {\n await fs.rename(staging, target)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n const clash =\n code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\"\n if (!clash) throw err\n // Somebody published it first. Adopt theirs if it is complete.\n if (completeAt(target, pkg)) return\n const aside = path.join(root, `.trash-${randomHex()}`)\n let movedAside = false\n try {\n await fs.rename(target, aside)\n movedAside = true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err\n }\n try {\n await fs.rename(staging, target)\n } catch (err) {\n // Put the incomplete-but-present tree back rather than leaving the\n // package with NO copy at all: `installedOptional` refuses it either way,\n // but a single retry can repair it in place, and a missing directory\n // cannot be compared or resumed.\n if (movedAside) await fs.rename(aside, target).catch(() => {})\n throw err\n }\n }\n } finally {\n await fs.rm(staging, { recursive: true, force: true }).catch(() => {})\n }\n}\n\n/** `{ \"<pkg>@<ver>\": { resolved, integrity } }` from the prefix lockfile. */\nasync function harvestProvenance(\n prefix: string,\n): Promise<Record<string, { resolved?: string; integrity?: string }>> {\n const out: Record<string, { resolved?: string; integrity?: string }> = {}\n try {\n const raw = await fs.readFile(path.join(prefix, \"package-lock.json\"), \"utf8\")\n const parsed = JSON.parse(raw) as {\n packages?: Record<string, { version?: string; resolved?: string; integrity?: string; link?: boolean }>\n }\n for (const [key, entry] of Object.entries(parsed.packages ?? {})) {\n if (!key.startsWith(\"node_modules/\") || entry.link || !entry.version) continue\n const name = key.slice(\"node_modules/\".length)\n // Top-level only; the transitive tree is reproducible from the registry\n // once the root tarball's integrity is pinned.\n if (name.includes(\"node_modules/\")) continue\n out[`${name}@${entry.version}`] = {\n ...(entry.resolved ? { resolved: entry.resolved } : {}),\n ...(entry.integrity ? { integrity: entry.integrity } : {}),\n }\n }\n } catch {\n // No lockfile: provenance is diagnostics, never a gate.\n }\n return out\n}\n\n/** Newest published version of `pkg`, or null. */\nasync function resolveOptionalVersion(\n pkg: OptionalPackage,\n registry?: string,\n): Promise<string | null> {\n const pinned = subjectFor(pkg).version\n if (pinned) return pinned\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n const subject = subjectFor(pkg)\n // With a range, npm does the range arithmetic and `--json` gives every match\n // newest-last; without one (a test stand-in) the spec is the bare name.\n const spec = subject.range ? `${subject.packageName}@${subject.range}` : subject.packageName\n try {\n const args = [npmPath, \"view\", spec, \"version\", \"--json\", \"--silent\"]\n if (registry) args.push(`--registry=${registry}`)\n const { stdout, code } = await runCommandCapture(args, { timeoutMs: 8000 })\n if (code !== 0) return null\n const value = lastVersionFromJson(stdout)\n return value && VERSION_RE.test(value) ? value : null\n } catch {\n return null\n }\n}\n\n/**\n * The newest version in `npm view … --json` output, or null.\n *\n * The output is a bare `\"1.2.3\"` when the spec matches exactly one version and\n * an ARRAY when a range matches several — and `npm view left-pad@^1.0.0 version`\n * prints the array newest-LAST, so the last element is the answer in both cases.\n * Parsing it as JSON rather than taking the last LINE is what makes a range with\n * a hundred matches work; the old line-based read returned `\"1.3.0\"` (with the\n * quotes) and the version regex then rejected it.\n */\nfunction lastVersionFromJson(stdout: string): string | null {\n const text = stdout.trim()\n if (!text) return null\n try {\n const parsed = JSON.parse(text) as unknown\n if (typeof parsed === \"string\") return parsed\n if (Array.isArray(parsed)) {\n for (let i = parsed.length - 1; i >= 0; i--) {\n const entry = parsed[i]\n if (typeof entry === \"string\") return entry\n }\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Compare dotted versions on the leading three components. */\nexport function compareVersions(a: string, b: string): number {\n const pa = a.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n const pb = b.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = Number.isNaN(pa[i]) ? 0 : (pa[i] ?? 0)\n const bv = Number.isNaN(pb[i]) ? 0 : (pb[i] ?? 0)\n if (av !== bv) return av - bv\n }\n return 0\n}\n\n/**\n * Keep the newest `KEEP_OPTIONAL_VERSIONS` copies per package and sweep\n * abandoned staging/trash dirs.\n *\n * Deliberately more conservative than the managed GC (30-day floor, keep 2, and\n * never remove the only copy of a package): each copy is up to 547 MB, so\n * deleting the wrong one is expensive to undo.\n *\n * `protect` is the caller's knowledge of what is IN USE — directory names under\n * the optional root that must survive this sweep. Nothing on disk records which\n * copy a running process has loaded, and the two rules here cannot infer it: a\n * process that has been up for weeks holds an old version that ranks below the\n * two newest and is past the floor, and on POSIX `fs.rm` of a memory-mapped\n * payload SUCCEEDS (`EBUSY` only saves Windows). The next lazy load in that\n * process would then fail. The installer passes the copy it just wrote and the\n * one it replaced.\n */\nexport async function gcOptional(\n now = Date.now(),\n protect: ReadonlyArray<string> = [],\n): Promise<{\n removed: Array<string>\n removedTransient: Array<string>\n}> {\n const root = optionalRoot()\n let names: Array<string>\n try {\n names = await fs.readdir(root)\n } catch {\n return { removed: [], removedTransient: [] }\n }\n\n const removed: Array<string> = []\n const removedTransient: Array<string> = []\n\n // Bucket by package, carrying mtime so \"newest\" is by time, not by the order\n // the filesystem happened to hand back.\n const versions = new Map<string, Array<{ name: string; mtimeMs: number }>>()\n\n for (const name of names) {\n const full = path.join(root, name)\n let mtimeMs: number\n try {\n mtimeMs = (await fs.stat(full)).mtimeMs\n } catch {\n continue\n }\n // Same shapes as the managed GC (`paths.ts`): a user file that merely\n // starts with `.staging-` is not one of our abandoned attempts.\n if (isTransientName(name)) {\n if (now - mtimeMs > 60 * 60_000) {\n await fs.rm(full, { recursive: true, force: true }).catch(() => {})\n removedTransient.push(name)\n }\n continue\n }\n const match = /^(.+?)@(.+)$/.exec(name)\n if (!match) continue\n if (!isVersionName(match[2]!)) continue\n const bucket = versions.get(match[1]!) ?? []\n bucket.push({ name, mtimeMs })\n versions.set(match[1]!, bucket)\n }\n\n const spared = new Set(protect)\n for (const entries of versions.values()) {\n // Newest first, then keep the first N. Everything from index N on is a\n // removal CANDIDATE, still subject to the age floor and the protect list.\n entries.sort((a, b) => b.mtimeMs - a.mtimeMs)\n for (const entry of entries.slice(KEEP_OPTIONAL_VERSIONS)) {\n if (spared.has(entry.name)) continue\n if (now - entry.mtimeMs < OPTIONAL_FLOOR_MS) continue\n await fs.rm(path.join(root, entry.name), { recursive: true, force: true })\n .then(() => removed.push(entry.name))\n .catch(() => {\n // EBUSY on Windows (a loaded ONNX runtime): retried on the next pass.\n })\n }\n }\n return { removed, removedTransient }\n}\n\n// ---------------------------------------------------------------------------\n// Entry points used by the launcher / update\n// ---------------------------------------------------------------------------\n\n/**\n * Install ONE payload, whichever a caller asked for by name.\n *\n * Separate entry point from `ensureOptionalPackage` because the argument comes\n * from a command line: an unknown name must be a reported no-op, never a crash\n * and never \"install everything because the filter matched nothing\".\n */\nexport function isOptionalPackage(name: string): name is OptionalPackage {\n return (OPTIONAL_PACKAGES as ReadonlyArray<string>).includes(name)\n}\n\n/**\n * Install both payloads, reporting what happened.\n *\n * Called from `github-router update` (foreground, where a failure is visible)\n * and never from a request path.\n */\nexport async function ensureOptionalPackages(\n opts: { registry?: string; signal?: AbortSignal; force?: boolean } = {},\n): Promise<Array<{ pkg: OptionalPackage; dir: string | null; detail?: string }>> {\n const out: Array<{ pkg: OptionalPackage; dir: string | null; detail?: string }> = []\n for (const pkg of OPTIONAL_PACKAGES) {\n const result = await ensureOptionalPackage(pkg, opts)\n out.push({ pkg, dir: result.dir, ...(result.detail ? { detail: result.detail } : {}) })\n }\n return out\n}\n\n/** Set by {@link scheduleOptionalInstall}; one detached child per process. */\nlet scheduledInProcess = false\n\n/**\n * Detached, best-effort install for a launch that noticed a gap.\n *\n * Detached because the spawn cost of two npm installs (minutes on a cold cache)\n * must never be attributed to the command the user actually ran — and a search\n * that triggered this proceeds on its BM25F fallback regardless.\n */\nexport function scheduleOptionalInstall(\n pkg: OptionalPackage,\n argv1: string | undefined = process.argv[1],\n): boolean {\n if (optionalInstallDisabled()) return false\n if (typeof argv1 !== \"string\" || argv1.length === 0) return false\n // Once per process. The callers are on request paths (a rerank, a structural\n // search), and for an agent a \"request path\" means per turn: spawning a\n // detached node process on every one of them would be worse than the missing\n // payload. Cross-process throttling is the backoff in `install-state.json`;\n // this flag only stops the same process from re-spawning what it already\n // started.\n if (scheduledInProcess) return false\n scheduledInProcess = true\n const missing = pkg\n void (async () => {\n try {\n // Dynamic on purpose: modules that only ever RESOLVE a payload (the\n // rerank loader, the grammar resolver) should not pull\n // `node:child_process` into their import graph.\n const { spawn } = await import(\"node:child_process\")\n // `--optional-only --optional-pkg <pkg>`: the caller is a feature that found\n // no payload, so installing THAT payload is the whole request. Not a\n // self-update, not a managed Pi appearing on a source checkout because a\n // search was slow, and — the part that is easy to get wrong — not the OTHER\n // payload either: a structural-search miss must not start a 547 MB ONNX\n // download because both slots share one flag.\n const child = spawn(\n process.execPath,\n [argv1, \"update\", \"--quiet\", \"--optional-only\", \"--optional-pkg\", missing],\n {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, GH_ROUTER_MANAGED_BACKGROUND: \"1\" },\n },\n )\n child.on(\"error\", () => {})\n child.unref()\n } catch {\n // Never fatal: the next launch (or an explicit `update`) tries again.\n }\n })()\n return true\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,oBAAoB,CAAC,6BAA6B,mBAAmB;;;;;;;;;AAWlF,MAAa,yBAAoE;CAC/E,6BAA6B;CAM7B,qBAAqB;AACvB;;;;;;;;;;;;AAaA,MAAa,yBAAoE;CAC/E,6BAA6B;CAC7B,qBAAqB;AACvB;;AAGA,SAAS,UAAU,KAAqB;CACtC,OAAO,IAAI,QAAQ,KAAK,IAAI;AAC9B;AAkBA,MAAM,2BAAW,IAAI,IAAsC;AAE3D,SAAS,WAAW,KAAuC;CACzD,OACE,SA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;AACnE;;AAoBA,IAAI,qBAAqB;;;;;;;;AASzB,SAAgB,wBACd,KACA,QAA4B,QAAQ,KAAK,IAChC;CACT,IAAI,wBAAwB,GAAG,OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,OAAO;CAO5D,IAAI,oBAAoB,OAAO;CAC/B,qBAAqB;CACrB,MAAM,UAAU;CAChB,CAAM,YAAY;EAChB,IAAI;GAIF,MAAM,EAAE,UAAU,MAAM,OAAO;GAO/B,MAAM,QAAQ,MACZ,QAAQ,UACR;IAAC;IAAO;IAAU;IAAW;IAAmB;IAAkB;GAAO,GACzE;IACE,UAAU;IACV,OAAO;IACP,aAAa;IACb,KAAK;KAAE,GAAG,QAAQ;KAAK,8BAA8B;IAAI;GAC3D,CACF;GACA,MAAM,GAAG,eAAe,CAAC,CAAC;GAC1B,MAAM,MAAM;EACd,QAAQ,CAER;CACF,EAAA,CAAG;CACH,OAAO;AACT"}
|
package/dist/origin-DbFUCiGp.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { n as classifyOrigin } from "./origin-BXtpcKP9.js";
|
package/dist/paths-CquOjytP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as PATHS } from "./paths-DeFmYJhO.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { l as resolvePiRegistry } from "./pi-version-check-BeBB0Ny9.js";
|
package/dist/update-CB21YRKz.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { s as scheduleBackgroundSelfInstall } from "./update-T1L7yFon.js";
|