github-router 0.3.378 → 0.3.380
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -0
- package/dist/ado-tools-CsfbnY8x.js +1 -0
- package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
- package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
- package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
- package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
- package/dist/atomic-file-Dif1kLKM.js +198 -0
- package/dist/atomic-file-Dif1kLKM.js.map +1 -0
- package/dist/{attribution-settings-BR5Umj2L.js → attribution-settings-BJ1fjX7V.js} +10 -10
- package/dist/{attribution-settings-BR5Umj2L.js.map → attribution-settings-BJ1fjX7V.js.map} +1 -1
- package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
- package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
- package/dist/bin.js +1479 -0
- package/dist/bin.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
- package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
- package/dist/{claude--4O3wHRq.js → claude-BWwkOMi3.js} +26 -25
- package/dist/{claude--4O3wHRq.js.map → claude-BWwkOMi3.js.map} +1 -1
- package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
- package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
- package/dist/{codex-DHRMLpSo.js → codex-C6ix3BaY.js} +8 -7
- package/dist/{codex-DHRMLpSo.js.map → codex-C6ix3BaY.js.map} +1 -1
- package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
- package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
- package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
- package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
- package/dist/diagnostics-cXjCT_JQ.js +12 -0
- package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
- package/dist/engine-B6la_uIW.js +1 -0
- package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
- package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
- package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
- package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
- package/dist/hooks.mjs +13 -0
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
- package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
- package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
- package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
- package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
- package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
- package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
- package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
- package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
- package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
- package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
- package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
- package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
- package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
- package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
- package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
- package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
- package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
- package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
- package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
- package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
- package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
- package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
- package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
- package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +268 -21
- package/dist/lifecycle-BOjgq9_l.js +1 -0
- package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
- package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
- package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
- package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
- package/dist/lifecycle-NQvr4flt.js +1 -0
- package/dist/main.js +39 -24
- package/dist/main.js.map +1 -1
- package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
- package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
- package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
- package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
- package/dist/npm-env-H60tX76c.js +130 -0
- package/dist/npm-env-H60tX76c.js.map +1 -0
- package/dist/optional-DGAeyguL.js +586 -0
- package/dist/optional-DGAeyguL.js.map +1 -0
- package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
- package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
- package/dist/origin-BXtpcKP9.js +382 -0
- package/dist/origin-BXtpcKP9.js.map +1 -0
- package/dist/origin-DbFUCiGp.js +1 -0
- package/dist/paths-CquOjytP.js +1 -0
- package/dist/paths-DK_b2ihK.js +176 -0
- package/dist/paths-DK_b2ihK.js.map +1 -0
- package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
- package/dist/paths-DeFmYJhO.js.map +1 -0
- package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
- package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
- package/dist/{pi-B0EFY6l7.js → pi-YhoA26wi.js} +718 -119
- package/dist/pi-YhoA26wi.js.map +1 -0
- package/dist/pi-foreign-artifacts-CNt6wQ1P.js +660 -0
- package/dist/pi-foreign-artifacts-CNt6wQ1P.js.map +1 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
- package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
- package/dist/pi-version-check-BeBB0Ny9.js +551 -0
- package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
- package/dist/pi-version-check-D5RvdLsG.js +1 -0
- package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
- package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
- package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
- package/dist/provision-BWtuDq_v.js.map +1 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
- package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
- package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
- package/dist/{serve-C13q-9w0.js → serve-DrHAX2Bh.js} +15 -14
- package/dist/{serve-C13q-9w0.js.map → serve-DrHAX2Bh.js.map} +1 -1
- package/dist/{server-setup-CptI7SUT.js → server-setup-DLwejgVA.js} +12 -638
- package/dist/server-setup-DLwejgVA.js.map +1 -0
- package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
- package/dist/service-backend-BdhWVRSz.js.map +1 -0
- package/dist/{start-DioCGjM8.js → start-DvV3Lbwy.js} +5 -4
- package/dist/{start-DioCGjM8.js.map → start-DvV3Lbwy.js.map} +1 -1
- package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
- package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
- package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
- package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
- package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
- package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
- package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
- package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
- package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
- package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
- package/dist/update-CB21YRKz.js +1 -0
- package/dist/update-T1L7yFon.js +1548 -0
- package/dist/update-T1L7yFon.js.map +1 -0
- package/dist/update-fEgWTrIx.js +214 -0
- package/dist/update-fEgWTrIx.js.map +1 -0
- package/dist/update-lock-BeS_WmC8.js +1 -0
- package/dist/update-lock-BmXx6QaR.js +171 -0
- package/dist/update-lock-BmXx6QaR.js.map +1 -0
- package/dist/volatile-root-DQNNvQ7Z.js +50 -0
- package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
- package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
- package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
- package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
- package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
- package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
- package/package.json +16 -4
- package/dist/ado-tools-CRkyU51J.js +0 -1
- package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
- package/dist/engine-V46un8Xl.js +0 -1
- package/dist/lifecycle-BENRuuX6.js +0 -1
- package/dist/lifecycle-Dli9vGI2.js +0 -1
- package/dist/paths-Be9_ujQ3.js +0 -1
- package/dist/paths-CVEO8jEH.js.map +0 -1
- package/dist/pi-B0EFY6l7.js.map +0 -1
- package/dist/pi-memory-bridge-Dvj1T3e3.js +0 -403
- package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
- package/dist/provision-DPL8aGe2.js.map +0 -1
- package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
- package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
- package/dist/server-setup-CptI7SUT.js.map +0 -1
- package/dist/service-backend-Cdgz6WPx.js.map +0 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { i as appDir } from "./paths-DK_b2ihK.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { mkdir, open, readFile, rm, stat, utimes } from "node:fs/promises";
|
|
4
|
+
// src/lib/update-lock.ts
|
|
5
|
+
/**
|
|
6
|
+
* Cross-process install lock for the auto-update / self-update / managed-install
|
|
7
|
+
* paths.
|
|
8
|
+
*
|
|
9
|
+
* Multiple concurrent `github-router` launches must not install at the same
|
|
10
|
+
* time. For the `-g` path that matters because Windows' global `node_modules`
|
|
11
|
+
* and `.cmd` shim rewrite is fragile and concurrent writers corrupt it; for the
|
|
12
|
+
* managed path it matters because two installers would race to publish the same
|
|
13
|
+
* version and both write the pointer.
|
|
14
|
+
*
|
|
15
|
+
* An `O_EXCL` lockfile guarantees exactly one holder; everyone else either
|
|
16
|
+
* skips or waits, and the caller is told which.
|
|
17
|
+
*
|
|
18
|
+
* ### Why this file changed
|
|
19
|
+
*
|
|
20
|
+
* The original version had three defects the managed installer would have
|
|
21
|
+
* inherited:
|
|
22
|
+
*
|
|
23
|
+
* 1. **`STALE_LOCK_MS = 10 min` with the comment "10 min > the 120 s install
|
|
24
|
+
* timeout".** The premise was already wrong (CloudCLI's install allows 10
|
|
25
|
+
* minutes, `serve/cloudcli.ts:150`) and a cold 586 MB npm install over a
|
|
26
|
+
* corporate link is slower still. A second launch could therefore *steal* a
|
|
27
|
+
* live lock and start a competing install. Fixed by heart-beating the mtime
|
|
28
|
+
* while `fn` runs: staleness now means "the holder stopped touching it",
|
|
29
|
+
* not "the holder is taking a while".
|
|
30
|
+
* 2. **The lock path was hardcoded** to `~/.local/share/github-router/<name>`,
|
|
31
|
+
* duplicating `PATHS.APP_DIR` and ignoring the app-dir override tests and the
|
|
32
|
+
* managed layout need. It now resolves through `appDir()`.
|
|
33
|
+
* 3. **"Held" was indistinguishable from "ran and did nothing"** — both returned
|
|
34
|
+
* `false`. A caller that skipped silently could not report why, and the
|
|
35
|
+
* managed installer genuinely needs to say "another install is in progress".
|
|
36
|
+
* `withInstallLock` still returns a boolean (so every existing caller is
|
|
37
|
+
* unchanged) and a new `InstallLockResult`-returning entry point carries the
|
|
38
|
+
* distinction.
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* A lock whose mtime has not moved for this long belongs to a dead holder.
|
|
42
|
+
*
|
|
43
|
+
* Safe to make generous *because* of the heartbeat: a live holder refreshes the
|
|
44
|
+
* mtime every `HEARTBEAT_INTERVAL_MS`, so this only has to exceed the interval,
|
|
45
|
+
* not the operation's duration.
|
|
46
|
+
*/
|
|
47
|
+
const STALE_LOCK_MS = 6e5;
|
|
48
|
+
/** How often a holder proves it is alive by touching the lock file. */
|
|
49
|
+
const HEARTBEAT_INTERVAL_MS = 3e4;
|
|
50
|
+
function lockPath(name) {
|
|
51
|
+
return path.join(appDir(), name);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Run `fn` while holding an exclusive lockfile named `name` under the app dir.
|
|
55
|
+
*
|
|
56
|
+
* Returns `true` if the lock was acquired and `fn` ran, `false` if another
|
|
57
|
+
* process already holds it (the caller skips). A lock left by a crashed process
|
|
58
|
+
* is stolen once its mtime is older than the staleness window, so an updater can
|
|
59
|
+
* never be wedged permanently.
|
|
60
|
+
*
|
|
61
|
+
* Kept as the primary entry point so the existing callers (`pi-version-check`,
|
|
62
|
+
* `colbert`, `toolbelt`, `self-update`) need no change. New code that has
|
|
63
|
+
* something to say about *why* it did not run should use
|
|
64
|
+
* `withInstallLockResult`.
|
|
65
|
+
*/
|
|
66
|
+
async function withInstallLock(name, fn, opts = {}) {
|
|
67
|
+
return (await withInstallLockResult(name, fn, opts)).outcome === "ran";
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* `withInstallLock`, but reporting whether `fn` ran, was skipped, or failed.
|
|
71
|
+
*
|
|
72
|
+
* The lock file is created with `flag: "wx"` (O_CREAT | O_EXCL) so exactly one
|
|
73
|
+
* of any number of concurrent attempts wins. Its handle is closed immediately
|
|
74
|
+
* and ownership is expressed by the file's existence plus its mtime: that is
|
|
75
|
+
* what makes the heartbeat meaningful (a holder proves liveness by touching the
|
|
76
|
+
* file it owns) and what makes a crashed holder recoverable.
|
|
77
|
+
*/
|
|
78
|
+
async function withInstallLockResult(name, fn, opts = {}) {
|
|
79
|
+
const p = lockPath(name);
|
|
80
|
+
const staleMs = opts.staleMs ?? STALE_LOCK_MS;
|
|
81
|
+
const heartbeatMs = opts.heartbeatMs ?? HEARTBEAT_INTERVAL_MS;
|
|
82
|
+
let acquired = await tryCreateLock(p);
|
|
83
|
+
if (!acquired.handle) {
|
|
84
|
+
if (acquired.code !== "EEXIST") return {
|
|
85
|
+
outcome: "failed",
|
|
86
|
+
error: lockCreateError(p, acquired)
|
|
87
|
+
};
|
|
88
|
+
if (!await isStale(p, staleMs)) return { outcome: "skipped" };
|
|
89
|
+
await rm(p, { force: true }).catch(() => {});
|
|
90
|
+
acquired = await tryCreateLock(p);
|
|
91
|
+
if (!acquired.handle) return acquired.code === "EEXIST" ? { outcome: "skipped" } : {
|
|
92
|
+
outcome: "failed",
|
|
93
|
+
error: lockCreateError(p, acquired)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
|
|
97
|
+
const ownsLock = async () => {
|
|
98
|
+
try {
|
|
99
|
+
return (await readFile(p, "utf8")).trim() === token;
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
try {
|
|
105
|
+
await acquired.handle.writeFile(token, "utf8");
|
|
106
|
+
} catch {}
|
|
107
|
+
let heartbeat;
|
|
108
|
+
if (heartbeatMs > 0) {
|
|
109
|
+
heartbeat = setInterval(() => {
|
|
110
|
+
(async () => {
|
|
111
|
+
if (!await ownsLock()) {
|
|
112
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const now = /* @__PURE__ */ new Date();
|
|
116
|
+
await utimes(p, now, now).catch(() => {});
|
|
117
|
+
})();
|
|
118
|
+
}, heartbeatMs);
|
|
119
|
+
heartbeat.unref?.();
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
await acquired.handle.close().catch(() => {});
|
|
123
|
+
await fn();
|
|
124
|
+
return { outcome: "ran" };
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return {
|
|
127
|
+
outcome: "failed",
|
|
128
|
+
error
|
|
129
|
+
};
|
|
130
|
+
} finally {
|
|
131
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
132
|
+
if (await ownsLock()) await rm(p, { force: true }).catch(() => {});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function isStale(p, staleMs) {
|
|
136
|
+
try {
|
|
137
|
+
const s = await stat(p);
|
|
138
|
+
return Date.now() - s.mtimeMs > staleMs;
|
|
139
|
+
} catch {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The error handed to the caller when the lock could NOT be created.
|
|
145
|
+
*
|
|
146
|
+
* Carries the original `code` (and `cause`) so the caller can act on the reason
|
|
147
|
+
* — `install.ts` reports `ENOTDIR`/`EACCES` as its own failure — instead of
|
|
148
|
+
* re-deriving it from a message string.
|
|
149
|
+
*/
|
|
150
|
+
function lockCreateError(p, attempt) {
|
|
151
|
+
const err = new Error(`could not create the install lock ${p}: ${attempt.detail ?? attempt.code ?? "unknown error"}`, attempt.cause ? { cause: attempt.cause } : void 0);
|
|
152
|
+
if (attempt.code) err.code = attempt.code;
|
|
153
|
+
return err;
|
|
154
|
+
}
|
|
155
|
+
async function tryCreateLock(p) {
|
|
156
|
+
try {
|
|
157
|
+
await mkdir(path.dirname(p), { recursive: true }).catch(() => {});
|
|
158
|
+
return { handle: await open(p, "wx") };
|
|
159
|
+
} catch (err) {
|
|
160
|
+
const code = err.code;
|
|
161
|
+
return {
|
|
162
|
+
handle: null,
|
|
163
|
+
...code ? { code } : {},
|
|
164
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
165
|
+
cause: err
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
export { withInstallLockResult as n, withInstallLock as t };
|
|
170
|
+
|
|
171
|
+
//# sourceMappingURL=update-lock-BmXx6QaR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-lock-BmXx6QaR.js","names":[],"sources":["../src/lib/update-lock.ts"],"sourcesContent":["/**\n * Cross-process install lock for the auto-update / self-update / managed-install\n * paths.\n *\n * Multiple concurrent `github-router` launches must not install at the same\n * time. For the `-g` path that matters because Windows' global `node_modules`\n * and `.cmd` shim rewrite is fragile and concurrent writers corrupt it; for the\n * managed path it matters because two installers would race to publish the same\n * version and both write the pointer.\n *\n * An `O_EXCL` lockfile guarantees exactly one holder; everyone else either\n * skips or waits, and the caller is told which.\n *\n * ### Why this file changed\n *\n * The original version had three defects the managed installer would have\n * inherited:\n *\n * 1. **`STALE_LOCK_MS = 10 min` with the comment \"10 min > the 120 s install\n * timeout\".** The premise was already wrong (CloudCLI's install allows 10\n * minutes, `serve/cloudcli.ts:150`) and a cold 586 MB npm install over a\n * corporate link is slower still. A second launch could therefore *steal* a\n * live lock and start a competing install. Fixed by heart-beating the mtime\n * while `fn` runs: staleness now means \"the holder stopped touching it\",\n * not \"the holder is taking a while\".\n * 2. **The lock path was hardcoded** to `~/.local/share/github-router/<name>`,\n * duplicating `PATHS.APP_DIR` and ignoring the app-dir override tests and the\n * managed layout need. It now resolves through `appDir()`.\n * 3. **\"Held\" was indistinguishable from \"ran and did nothing\"** — both returned\n * `false`. A caller that skipped silently could not report why, and the\n * managed installer genuinely needs to say \"another install is in progress\".\n * `withInstallLock` still returns a boolean (so every existing caller is\n * unchanged) and a new `InstallLockResult`-returning entry point carries the\n * distinction.\n */\n\nimport { mkdir, open, readFile, rm, stat, utimes } from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { appDir } from \"./managed-install/paths\"\n\n/**\n * A lock whose mtime has not moved for this long belongs to a dead holder.\n *\n * Safe to make generous *because* of the heartbeat: a live holder refreshes the\n * mtime every `HEARTBEAT_INTERVAL_MS`, so this only has to exceed the interval,\n * not the operation's duration.\n */\nconst STALE_LOCK_MS = 10 * 60 * 1000\n\n/** How often a holder proves it is alive by touching the lock file. */\nconst HEARTBEAT_INTERVAL_MS = 30 * 1000\n\nfunction lockPath(name: string): string {\n return path.join(appDir(), name)\n}\n\nexport interface InstallLockOptions {\n /** Millisecond staleness window. Tests shorten it; production uses the default. */\n staleMs?: number\n /** Heartbeat period. `0` disables it (tests). */\n heartbeatMs?: number\n}\n\n/**\n * How a `withInstallLockResult` attempt ended.\n *\n * - `ran` — this process held the lock and `fn` completed.\n * - `skipped` — another live process holds it; `fn` did not run.\n * - `failed` — the lock was acquired but `fn` threw. The lock is released, and\n * the error is available to the caller to report.\n */\nexport type InstallLockOutcome = \"ran\" | \"skipped\" | \"failed\"\n\nexport interface InstallLockResult {\n outcome: InstallLockOutcome\n /** Present when `outcome === \"failed\"`. */\n error?: unknown\n}\n\n/**\n * Run `fn` while holding an exclusive lockfile named `name` under the app dir.\n *\n * Returns `true` if the lock was acquired and `fn` ran, `false` if another\n * process already holds it (the caller skips). A lock left by a crashed process\n * is stolen once its mtime is older than the staleness window, so an updater can\n * never be wedged permanently.\n *\n * Kept as the primary entry point so the existing callers (`pi-version-check`,\n * `colbert`, `toolbelt`, `self-update`) need no change. New code that has\n * something to say about *why* it did not run should use\n * `withInstallLockResult`.\n */\nexport async function withInstallLock(\n name: string,\n fn: () => Promise<void>,\n opts: InstallLockOptions = {},\n): Promise<boolean> {\n const result = await withInstallLockResult(name, fn, opts)\n return result.outcome === \"ran\"\n}\n\n/**\n * `withInstallLock`, but reporting whether `fn` ran, was skipped, or failed.\n *\n * The lock file is created with `flag: \"wx\"` (O_CREAT | O_EXCL) so exactly one\n * of any number of concurrent attempts wins. Its handle is closed immediately\n * and ownership is expressed by the file's existence plus its mtime: that is\n * what makes the heartbeat meaningful (a holder proves liveness by touching the\n * file it owns) and what makes a crashed holder recoverable.\n */\nexport async function withInstallLockResult(\n name: string,\n fn: () => Promise<void>,\n opts: InstallLockOptions = {},\n): Promise<InstallLockResult> {\n const p = lockPath(name)\n const staleMs = opts.staleMs ?? STALE_LOCK_MS\n const heartbeatMs = opts.heartbeatMs ?? HEARTBEAT_INTERVAL_MS\n\n let acquired = await tryCreateLock(p)\n if (!acquired.handle) {\n // A create failure that is not EEXIST is NOT \"somebody else has it\": a\n // read-only or otherwise unusable app dir, EACCES, ENOSPC, a path that is a\n // directory. Reporting those as `skipped` makes `update` say \"another\n // github-router process is installing; retry shortly\" forever, about a\n // process that does not exist — the mystery-bug class this file exists to\n // remove. Say what actually failed instead.\n if (acquired.code !== \"EEXIST\") {\n return { outcome: \"failed\", error: lockCreateError(p, acquired) }\n }\n if (!(await isStale(p, staleMs))) return { outcome: \"skipped\" }\n await rm(p, { force: true }).catch(() => {})\n acquired = await tryCreateLock(p)\n if (!acquired.handle) {\n return acquired.code === \"EEXIST\"\n ? { outcome: \"skipped\" }\n : { outcome: \"failed\", error: lockCreateError(p, acquired) }\n }\n }\n\n // Ownership token. Written into the file so this holder can tell its OWN lock\n // from one a thief installed after stealing a \"stale\" one (a laptop that\n // suspends mid-install ages the mtime past the window, and another launch\n // legitimately steals it). Without the token the original holder's `finally`\n // deletes the new holder's lock and its heartbeat keeps the new holder's file\n // alive — three installers instead of one.\n const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`\n const ownsLock = async (): Promise<boolean> => {\n try {\n return (await readFile(p, \"utf8\")).trim() === token\n } catch {\n return false\n }\n }\n try {\n await acquired.handle.writeFile(token, \"utf8\")\n } catch {\n // A lock we cannot stamp cannot be safely released; not fatal, just no\n // ownership check (the old behaviour).\n }\n\n let heartbeat: ReturnType<typeof setInterval> | undefined\n if (heartbeatMs > 0) {\n heartbeat = setInterval(() => {\n void (async () => {\n // Proof of life, but only for a lock this process still owns.\n if (!(await ownsLock())) {\n if (heartbeat) clearInterval(heartbeat)\n return\n }\n const now = new Date()\n // Best effort. A failed touch means the filesystem is unhappy, not that\n // this process stopped: the staleness window is 20× the interval, so a\n // few lost beats are harmless.\n await utimes(p, now, now).catch(() => {})\n })()\n }, heartbeatMs)\n heartbeat.unref?.()\n }\n\n try {\n await acquired.handle.close().catch(() => {})\n await fn()\n return { outcome: \"ran\" }\n } catch (error) {\n return { outcome: \"failed\", error }\n } finally {\n if (heartbeat) clearInterval(heartbeat)\n // Release only OUR lock. If it was stolen and re-created, `rm` here would\n // delete the thief's file and let a fourth process start.\n if (await ownsLock()) await rm(p, { force: true }).catch(() => {})\n }\n}\n\nasync function isStale(p: string, staleMs: number): Promise<boolean> {\n try {\n const s = await stat(p)\n return Date.now() - s.mtimeMs > staleMs\n } catch {\n // Disappeared between create-attempt and stat — try once more.\n return true\n }\n}\n\n/**\n * The error handed to the caller when the lock could NOT be created.\n *\n * Carries the original `code` (and `cause`) so the caller can act on the reason\n * — `install.ts` reports `ENOTDIR`/`EACCES` as its own failure — instead of\n * re-deriving it from a message string.\n */\nfunction lockCreateError(p: string, attempt: LockCreateAttempt): Error {\n const err = new Error(\n `could not create the install lock ${p}: ${attempt.detail ?? attempt.code ?? \"unknown error\"}`,\n attempt.cause ? { cause: attempt.cause } : undefined,\n )\n if (attempt.code) (err as NodeJS.ErrnoException).code = attempt.code\n return err\n}\n\ninterface LockCreateAttempt {\n handle: Awaited<ReturnType<typeof open>> | null\n /** Node error code, when the attempt failed. `EEXIST` means a live holder. */\n code?: string\n detail?: string\n cause?: unknown\n}\n\nasync function tryCreateLock(p: string): Promise<LockCreateAttempt> {\n try {\n // The app dir is not guaranteed to exist: the managed installer creates\n // `<APP_DIR>/m/<kind>` for its own state, but the `-g`/toolbelt/colbert\n // lock holders may run first on a fresh machine (or under a\n // `GH_ROUTER_APP_DIR` that has never been created). Without this, `open`\n // fails `ENOENT`, `isStale` then reads as \"disappeared => stale\", and the\n // installer reports `skipped` forever — an unexplainable \"another install is\n // in progress\" with no other process on the machine.\n // Failure here is NOT reported on its own: `open` below fails for the same\n // reason and with a more specific code (ENOTDIR rather than a bare `mkdir`\n // EEXIST when the app dir is, say, a path under a regular file). Whatever\n // `open` says is what the caller gets to act on.\n await mkdir(path.dirname(p), { recursive: true }).catch(() => {})\n // \"wx\" = O_CREAT | O_EXCL — fails if the file already exists.\n return { handle: await open(p, \"wx\") }\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n return {\n handle: null,\n ...(code ? { code } : {}),\n detail: err instanceof Error ? err.message : String(err),\n cause: err,\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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CACvC,SAAS,KAAK;EACZ,MAAM,OAAQ,IAA8B;EAC5C,OAAO;GACL,QAAQ;GACR,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;GACvB,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACvD,OAAO;EACT;CACF;AACF"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
// src/lib/volatile-root.ts
|
|
5
|
+
/**
|
|
6
|
+
* "Could the OS delete this path while we are not looking?"
|
|
7
|
+
*
|
|
8
|
+
* One predicate, two consumers with the same question and different stakes:
|
|
9
|
+
*
|
|
10
|
+
* - `hook-launcher/self-invocation.ts` asks it about a PERSISTED hook command, so
|
|
11
|
+
* the answer drives a user-facing warning;
|
|
12
|
+
* - `managed-install/origin.ts` asks it about the running code, so the answer
|
|
13
|
+
* drives "is this tree disposable enough to replace with the managed install".
|
|
14
|
+
*
|
|
15
|
+
* It lives alone here because `origin.ts` is imported by the bootstrap bundle
|
|
16
|
+
* (`dist/bin.js`), which must not pull `consola`, `PATHS`, or the hook-launcher
|
|
17
|
+
* provisioning graph just to compare two path prefixes. Hence: `node:` builtins
|
|
18
|
+
* only, no logging, no app state.
|
|
19
|
+
*
|
|
20
|
+
* Why it cannot be a bare prefix test: `os.tmpdir()` reports `/var/folders/…` on
|
|
21
|
+
* macOS while a process sees `/private/var/folders/…`, so a single-form compare
|
|
22
|
+
* silently never matches. Both sides are therefore compared in resolved AND
|
|
23
|
+
* unresolved form, and `realpath` failure (a path that does not exist, which is
|
|
24
|
+
* the normal case for a hook command that has not run yet) must not change the
|
|
25
|
+
* answer.
|
|
26
|
+
*/
|
|
27
|
+
function realpathIfPossible(file) {
|
|
28
|
+
try {
|
|
29
|
+
return realpathSync(file);
|
|
30
|
+
} catch {
|
|
31
|
+
return file;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Whether `target` sits under a directory the OS is entitled to clean out from
|
|
36
|
+
* under a running session: the per-user temp dir on every platform, which is
|
|
37
|
+
* where `bunx` (unlike `npx`, which uses a cache under `$HOME`) installs.
|
|
38
|
+
*/
|
|
39
|
+
function isUnderVolatileRoot(target) {
|
|
40
|
+
try {
|
|
41
|
+
const prefixes = /* @__PURE__ */ new Set();
|
|
42
|
+
for (const root of [os.tmpdir(), realpathIfPossible(os.tmpdir())]) prefixes.add(root.endsWith(path.sep) ? root : root + path.sep);
|
|
43
|
+
return [target, realpathIfPossible(target)].some((candidate) => [...prefixes].some((prefix) => candidate.startsWith(prefix)));
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export { realpathIfPossible as n, isUnderVolatileRoot as t };
|
|
49
|
+
|
|
50
|
+
//# sourceMappingURL=volatile-root-DQNNvQ7Z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"volatile-root-DQNNvQ7Z.js","names":[],"sources":["../src/lib/volatile-root.ts"],"sourcesContent":["/**\n * \"Could the OS delete this path while we are not looking?\"\n *\n * One predicate, two consumers with the same question and different stakes:\n *\n * - `hook-launcher/self-invocation.ts` asks it about a PERSISTED hook command, so\n * the answer drives a user-facing warning;\n * - `managed-install/origin.ts` asks it about the running code, so the answer\n * drives \"is this tree disposable enough to replace with the managed install\".\n *\n * It lives alone here because `origin.ts` is imported by the bootstrap bundle\n * (`dist/bin.js`), which must not pull `consola`, `PATHS`, or the hook-launcher\n * provisioning graph just to compare two path prefixes. Hence: `node:` builtins\n * only, no logging, no app state.\n *\n * Why it cannot be a bare prefix test: `os.tmpdir()` reports `/var/folders/…` on\n * macOS while a process sees `/private/var/folders/…`, so a single-form compare\n * silently never matches. Both sides are therefore compared in resolved AND\n * unresolved form, and `realpath` failure (a path that does not exist, which is\n * the normal case for a hook command that has not run yet) must not change the\n * answer.\n */\n\nimport { realpathSync } from \"node:fs\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nexport function realpathIfPossible(file: string): string {\n try {\n return realpathSync(file)\n } catch {\n return file\n }\n}\n\n/**\n * Whether `target` sits under a directory the OS is entitled to clean out from\n * under a running session: the per-user temp dir on every platform, which is\n * where `bunx` (unlike `npx`, which uses a cache under `$HOME`) installs.\n */\nexport function isUnderVolatileRoot(target: string): boolean {\n try {\n const prefixes = new Set<string>()\n for (const root of [os.tmpdir(), realpathIfPossible(os.tmpdir())]) {\n prefixes.add(root.endsWith(path.sep) ? root : root + path.sep)\n }\n const targets = [target, realpathIfPossible(target)]\n return targets.some((candidate) => [...prefixes].some((prefix) => candidate.startsWith(prefix)))\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,mBAAmB,MAAsB;CACvD,IAAI;EACF,OAAO,aAAa,IAAI;CAC1B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,SAAgB,oBAAoB,QAAyB;CAC3D,IAAI;EACF,MAAM,2BAAW,IAAI,IAAY;EACjC,KAAK,MAAM,QAAQ,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,OAAO,CAAC,CAAC,GAC9D,SAAS,IAAI,KAAK,SAAS,KAAK,GAAG,IAAI,OAAO,OAAO,KAAK,GAAG;EAG/D,OAAO,CADU,QAAQ,mBAAmB,MAAM,CACrC,CAAC,CAAC,MAAM,cAAc,CAAC,GAAG,QAAQ,CAAC,CAAC,MAAM,WAAW,UAAU,WAAW,MAAM,CAAC,CAAC;CACjG,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-Dnq4iVD6.js";
|
|
2
2
|
// src/lib/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-DBWKTMda.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-dispatch-C7RtNOXv.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): S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ASA,SAAgB,gBAAgB,OAA2B,YAAmC;CAC5F,OAAO,CAAC,QAAQ,WAAW,IAAI;AACjC;;;;;;;;;;;AAYA,SAAgB,4BACd,YACA,YACA,OACQ;CACR,MAAM,KAAK,MAAsB,IAAI,EAAE;CACvC,MAAM,OAAO,uCAAuC,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,KAAK,GAAG,CAAC;CAC9F,OAAO,iBAAiB,YAAY,IAAI;AAC1C;;AAGA,SAAgB,cAAc,KAAoD;CAChF,IAAI,CAAC,KAAK,OAAO,CAAC,GAAG,iBAAiB;CACtC,MAAM,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-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;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,SAAg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;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,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-Ygd7D32L.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-D5b7xlbr.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workiq-
|
|
1
|
+
{"version":3,"file":"workiq-D5b7xlbr.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.length === 0) return showUsage(workiq)\n return undefined\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,eAAsB,cAAc,UAAgC,CAAC,GAAkB;CACrF,IAAI;EACF,MAAM,OAAO,MAAM,gBAAgB;GACjC,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;GACnD,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC9D,CAAC;EACD,QAAQ,KAAK,eAAe,gBAAgB,GAAG;EAC/C,QAAQ,KAAK,YAAY,IAAI,KAAK,KAAK,WAAW,CAAC,CAAC,YAAY,EAAE,2BAA2B;CAC/F,SAAS,KAAK;EACZ,IAAI,eAAe,iBAAiB;GAClC,QAAQ,MAAM,IAAI,OAAO;GACzB,IAAI,IAAI,cAAc,mBAAmB,IAAI,cAAc,wBACzD,QAAQ,KAAK,oEAAoE;GAEnF,QAAQ,WAAW;GACnB;EACF;EACA,MAAM;CACR;AACF;AAeA,eAAe,gBAAuC;CACpD,MAAM,YAAY,gBAAgB;CAClC,MAAM,YAAY,QAAQ,QAAQ,IAAI,iBAAiB,EAAE,KAAK,CAAC;CAC/D,MAAM,OAAO,MAAM,oBAAoB,SAAS;CAChD,IAAI,CAAC,MAAM,OAAO;EAAE,UAAU;EAAO;EAAW,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CAAG;CACp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;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,cAAc;GACnB,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC7C,GAAI,KAAK,gBAAgB,EAAE,WAAW,KAAK,cAAc,IAAI,CAAC;EAChE,CAAC;CACH;AACF,CAAC;AAED,MAAM,SAAS,cAAc;CAC3B,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,gBAAgB,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-Dny0r5Am.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "github-router",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.380",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints.",
|
|
6
6
|
"keywords": [
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"author": "animeshkundu",
|
|
23
23
|
"type": "module",
|
|
24
24
|
"bin": {
|
|
25
|
-
"github-router": "dist/
|
|
25
|
+
"github-router": "dist/bin.js"
|
|
26
26
|
},
|
|
27
27
|
"files": [
|
|
28
28
|
"dist",
|
|
@@ -61,7 +61,6 @@
|
|
|
61
61
|
"*": "bun run lint --fix"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@huggingface/transformers": "^4.3.2",
|
|
65
64
|
"@vscode/ripgrep": "^1.18.0",
|
|
66
65
|
"citty": "^0.2.2",
|
|
67
66
|
"clipboardy": "^5.3.2",
|
|
@@ -73,7 +72,6 @@
|
|
|
73
72
|
"partial-json": "0.1.7",
|
|
74
73
|
"proxy-from-env": "^2.1.0",
|
|
75
74
|
"srvx": "^1.0.8",
|
|
76
|
-
"tree-sitter-wasms": "^0.1.13",
|
|
77
75
|
"typebox": "1.3.27",
|
|
78
76
|
"undici": "^8.12.4",
|
|
79
77
|
"web-tree-sitter": "0.25.10",
|
|
@@ -81,8 +79,21 @@
|
|
|
81
79
|
"yaml": "2.9.1",
|
|
82
80
|
"zod": "^4.6.7"
|
|
83
81
|
},
|
|
82
|
+
"peerDependencies": {
|
|
83
|
+
"@huggingface/transformers": "^4.3.2",
|
|
84
|
+
"tree-sitter-wasms": "^0.1.13"
|
|
85
|
+
},
|
|
86
|
+
"peerDependenciesMeta": {
|
|
87
|
+
"@huggingface/transformers": {
|
|
88
|
+
"optional": true
|
|
89
|
+
},
|
|
90
|
+
"tree-sitter-wasms": {
|
|
91
|
+
"optional": true
|
|
92
|
+
}
|
|
93
|
+
},
|
|
84
94
|
"devDependencies": {
|
|
85
95
|
"@eslint/js": "^10.0.1",
|
|
96
|
+
"@huggingface/transformers": "^4.3.2",
|
|
86
97
|
"@types/bun": "^1.4.4",
|
|
87
98
|
"@types/proxy-from-env": "^1.0.4",
|
|
88
99
|
"@types/ws": "^8.18.2",
|
|
@@ -93,6 +104,7 @@
|
|
|
93
104
|
"playwright": "^1.65.1",
|
|
94
105
|
"prettier-plugin-packagejson": "^3.1.0",
|
|
95
106
|
"simple-git-hooks": "^2.14.0",
|
|
107
|
+
"tree-sitter-wasms": "^0.1.13",
|
|
96
108
|
"tsdown": "^0.23.7",
|
|
97
109
|
"typescript": "^5.9.3",
|
|
98
110
|
"typescript-eslint": "^8.73.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { xt as disposeAdoClients } from "./peer-mcp-personas-OWsSm6To.js";
|