github-router 0.3.314 → 0.3.315
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/dist/{aic-ledger-Cx_Ubon3.js → aic-ledger-BS47yb_C.js} +66 -6
- package/dist/aic-ledger-BS47yb_C.js.map +1 -0
- package/dist/{attribution-settings-Btc5EZTj.js → attribution-settings-DXmmyuEE.js} +8 -8
- package/dist/{attribution-settings-Btc5EZTj.js.map → attribution-settings-DXmmyuEE.js.map} +1 -1
- package/dist/{auth-O_UG1ABO.js → auth-D8t41c5D.js} +3 -3
- package/dist/{auth-O_UG1ABO.js.map → auth-D8t41c5D.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-dicJOWML.js → check-usage-BpBKOjGZ.js} +4 -4
- package/dist/{check-usage-dicJOWML.js.map → check-usage-BpBKOjGZ.js.map} +1 -1
- package/dist/{claude-D0vuAqTV.js → claude-Cmmu3-cL.js} +30 -24
- package/dist/claude-Cmmu3-cL.js.map +1 -0
- package/dist/{codex-BNm9D0iJ.js → codex-DqTKKoEx.js} +5 -5
- package/dist/{codex-BNm9D0iJ.js.map → codex-DqTKKoEx.js.map} +1 -1
- package/dist/copilot-discount-IbXR5A28.js +220 -0
- package/dist/copilot-discount-IbXR5A28.js.map +1 -0
- package/dist/{debug-2PgImRnr.js → debug-CA7pg8V9.js} +2 -2
- package/dist/{debug-2PgImRnr.js.map → debug-CA7pg8V9.js.map} +1 -1
- package/dist/engine-b9XaKLp0.js +2 -0
- package/dist/{exec-y8C_MU8A.js → exec-COUT4QsS.js} +2 -2
- package/dist/{exec-y8C_MU8A.js.map → exec-COUT4QsS.js.map} +1 -1
- package/dist/{gate-discovery-CO2njGBB.js → gate-discovery-CPk6Z8yc.js} +6 -6
- package/dist/{gate-discovery-CO2njGBB.js.map → gate-discovery-CPk6Z8yc.js.map} +1 -1
- package/dist/{get-copilot-usage-Cjy8TiFf.js → get-copilot-usage-FSQE8szQ.js} +2 -2
- package/dist/{get-copilot-usage-Cjy8TiFf.js.map → get-copilot-usage-FSQE8szQ.js.map} +1 -1
- package/dist/hooks.mjs +489 -28
- package/dist/hooks.sha256 +1 -1
- package/dist/internal-aic-status-BN0xRLSF.js +432 -0
- package/dist/internal-aic-status-BN0xRLSF.js.map +1 -0
- package/dist/{internal-artifact-open-CxeIfsW_.js → internal-artifact-open-B3stUu74.js} +2 -2
- package/dist/{internal-artifact-open-CxeIfsW_.js.map → internal-artifact-open-B3stUu74.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-D8YNlnuQ.js → internal-fast-dispatch-guard-2QjUlhqO.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-19xQEouu.js → internal-fast-dispatch-guard-CAwYj_Yz.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-19xQEouu.js.map → internal-fast-dispatch-guard-CAwYj_Yz.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BuweUgjb.js → internal-first-mate-guard-B0rbLb0L.js} +3 -3
- package/dist/{internal-first-mate-guard-BuweUgjb.js.map → internal-first-mate-guard-B0rbLb0L.js.map} +1 -1
- package/dist/{internal-first-mate-guard-Nf1H0mCK.js → internal-first-mate-guard-VgnHBp0s.js} +1 -1
- package/dist/{internal-max-dispatch-guard-_Pp4LltM.js → internal-max-dispatch-guard-BzKsY9ze.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DZ7KLWxP.js → internal-max-dispatch-guard-l1NGYHtF.js} +2 -2
- package/dist/{internal-max-dispatch-guard-DZ7KLWxP.js.map → internal-max-dispatch-guard-l1NGYHtF.js.map} +1 -1
- package/dist/{internal-plan-review-DLduDz41.js → internal-plan-review-QUvNZmMR.js} +3 -3
- package/dist/{internal-plan-review-DLduDz41.js.map → internal-plan-review-QUvNZmMR.js.map} +1 -1
- package/dist/{internal-prompt-submit-DG94f8E-.js → internal-prompt-submit-fj5ccft_.js} +5 -5
- package/dist/{internal-prompt-submit-DG94f8E-.js.map → internal-prompt-submit-fj5ccft_.js.map} +1 -1
- package/dist/{internal-session-bind-D6Hpl-84.js → internal-session-bind-0Hmak8PR.js} +2 -2
- package/dist/{internal-session-bind-D6Hpl-84.js.map → internal-session-bind-0Hmak8PR.js.map} +1 -1
- package/dist/{internal-stop-hook-D56b6iVj.js → internal-stop-hook-BKiKYeda.js} +6 -6
- package/dist/{internal-stop-hook-D56b6iVj.js.map → internal-stop-hook-BKiKYeda.js.map} +1 -1
- package/dist/{internal-stop-review-DlKzZgFm.js → internal-stop-review-8v2llYDB.js} +2 -2
- package/dist/{internal-stop-review-DlKzZgFm.js.map → internal-stop-review-8v2llYDB.js.map} +1 -1
- package/dist/{internal-worker-guard-D7sfByyo.js → internal-worker-guard-BI4Pl0Ew.js} +2 -2
- package/dist/{internal-worker-guard-D7sfByyo.js.map → internal-worker-guard-BI4Pl0Ew.js.map} +1 -1
- package/dist/{internal-workspace-header-CU5OjLCB.js → internal-workspace-header-kg9FoNXK.js} +2 -2
- package/dist/{internal-workspace-header-CU5OjLCB.js.map → internal-workspace-header-kg9FoNXK.js.map} +1 -1
- package/dist/lifecycle-BpqAyaAj.js +2 -0
- package/dist/lifecycle-CL2WiyeQ.js +2 -0
- package/dist/{lifecycle-CtRA3Y7p.js → lifecycle-Cx1wVrLb.js} +3 -3
- package/dist/{lifecycle-CtRA3Y7p.js.map → lifecycle-Cx1wVrLb.js.map} +1 -1
- package/dist/{lifecycle-BCnarXJV.js → lifecycle-IwotwedG.js} +2 -2
- package/dist/{lifecycle-BCnarXJV.js.map → lifecycle-IwotwedG.js.map} +1 -1
- package/dist/main.js +20 -20
- package/dist/{mcp-workspace-header-B60WSR1Y.js → mcp-workspace-header-BYgWioLH.js} +2 -2
- package/dist/{mcp-workspace-header-B60WSR1Y.js.map → mcp-workspace-header-BYgWioLH.js.map} +1 -1
- package/dist/{models-COuMOfM6.js → models-DgLeb-Dv.js} +3 -3
- package/dist/{models-COuMOfM6.js.map → models-DgLeb-Dv.js.map} +1 -1
- package/dist/{orchestration-DjLA-lxB.js → orchestration-Dc3mO0G3.js} +3 -3
- package/dist/{orchestration-DjLA-lxB.js.map → orchestration-Dc3mO0G3.js.map} +1 -1
- package/dist/paths-BXXCVFvA.js +2 -0
- package/dist/{paths-De1Qh9Q9.js → paths-CMxlQEfQ.js} +3 -3
- package/dist/{paths-De1Qh9Q9.js.map → paths-CMxlQEfQ.js.map} +1 -1
- package/dist/{peer-mcp-personas-0_XU6nm9.js → peer-mcp-personas-CYWJSxPK.js} +11 -11
- package/dist/{peer-mcp-personas-0_XU6nm9.js.map → peer-mcp-personas-CYWJSxPK.js.map} +1 -1
- package/dist/{plan-review-hook-vL6BYmA8.js → plan-review-hook-BIMwWkh6.js} +4 -4
- package/dist/{plan-review-hook-vL6BYmA8.js.map → plan-review-hook-BIMwWkh6.js.map} +1 -1
- package/dist/{prompt-submit-hook-DfqufWC1.js → prompt-submit-hook-BcFpjHXg.js} +3 -3
- package/dist/{prompt-submit-hook-DfqufWC1.js.map → prompt-submit-hook-BcFpjHXg.js.map} +1 -1
- package/dist/{provision-DuCnZJj_.js → provision-AwSjt-vR.js} +5 -5
- package/dist/{provision-DuCnZJj_.js.map → provision-AwSjt-vR.js.map} +1 -1
- package/dist/{self-invocation-B84JCHps.js → self-invocation-cRl4RqfW.js} +2 -2
- package/dist/{self-invocation-B84JCHps.js.map → self-invocation-cRl4RqfW.js.map} +1 -1
- package/dist/{serve-DXFVR6A0.js → serve-BG2O6Slz.js} +13 -13
- package/dist/{serve-DXFVR6A0.js.map → serve-BG2O6Slz.js.map} +1 -1
- package/dist/{server-setup-CP8nGop3.js → server-setup-D7ABbEs1.js} +8 -8
- package/dist/{server-setup-CP8nGop3.js.map → server-setup-D7ABbEs1.js.map} +1 -1
- package/dist/{start-BHEjESCB.js → start-Dpwpnq99.js} +3 -3
- package/dist/{start-BHEjESCB.js.map → start-Dpwpnq99.js.map} +1 -1
- package/dist/{stop-gate-hook-BEU8qQrC.js → stop-gate-hook-BUCxa5Kc.js} +4 -4
- package/dist/{stop-gate-hook-BEU8qQrC.js.map → stop-gate-hook-BUCxa5Kc.js.map} +1 -1
- package/dist/{stop-gate-policy-qzqXfRxE.js → stop-gate-policy--bpyxxXU.js} +3 -3
- package/dist/{stop-gate-policy-qzqXfRxE.js.map → stop-gate-policy--bpyxxXU.js.map} +1 -1
- package/dist/{token-CCg-Ov5q.js → token-ClzS23Y2.js} +2 -2
- package/dist/{token-CCg-Ov5q.js.map → token-ClzS23Y2.js.map} +1 -1
- package/dist/{worker-dispatch-CH-NN5FW.js → worker-dispatch-DMIdrlsF.js} +2 -2
- package/dist/{worker-dispatch-CH-NN5FW.js.map → worker-dispatch-DMIdrlsF.js.map} +1 -1
- package/package.json +1 -1
- package/dist/aic-ledger-Cx_Ubon3.js.map +0 -1
- package/dist/claude-D0vuAqTV.js.map +0 -1
- package/dist/engine-DsVZuCrD.js +0 -2
- package/dist/internal-aic-status-C_swX3_7.js +0 -95
- package/dist/internal-aic-status-C_swX3_7.js.map +0 -1
- package/dist/lifecycle-B0USSJvd.js +0 -2
- package/dist/lifecycle-CQFjaQc0.js +0 -2
- package/dist/paths-DyX6SEnd.js +0 -2
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { r as aicTotalCredits } from "./aic-ledger-BS47yb_C.js";
|
|
2
|
+
//#region src/lib/copilot-discount.ts
|
|
3
|
+
/** USD value of one AI credit (GitHub's published conversion). */
|
|
4
|
+
const USD_PER_AIC_CREDIT = .01;
|
|
5
|
+
function row(factor, source) {
|
|
6
|
+
return {
|
|
7
|
+
factor,
|
|
8
|
+
source
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Static per-model discount factors, keyed by resolved (Copilot-side) model
|
|
13
|
+
* id — the same key the ledger's `perModel` uses. Derived Sep 2026 from the
|
|
14
|
+
* 28d / MTD / 7d / daily spend-dashboard windows vs portal rates.
|
|
15
|
+
*/
|
|
16
|
+
const DISCOUNT_FACTORS = Object.freeze({
|
|
17
|
+
"gpt-5.6-sol": row(.28, "0.27-0.29 across 28d/MTD/7d/pre/9-9; write-mix refuted"),
|
|
18
|
+
"claude-opus-5": row(.62, "0.61-0.64 across windows; 9/7 1.02 excluded as single-day artifact"),
|
|
19
|
+
"claude-sonnet-5": row(.66, "0.62-0.71 across windows"),
|
|
20
|
+
"gpt-5.3-codex": row(.6, "0.59-0.62 across windows"),
|
|
21
|
+
"gpt-5.4": row(.6, "single snapshot 0.598"),
|
|
22
|
+
"gemini-3.7-flash": row(.29, "September regime; pre-Sep 1.00x — volatile"),
|
|
23
|
+
"gpt-5.6-luna": row(1, "long-tier portal + writes, no discount"),
|
|
24
|
+
"grok-4.6": row(1, "portal default, six windows"),
|
|
25
|
+
"gemini-3.8-flash": row(1, "portal exact, six windows to the dollar")
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Clamp a factor to usable range. Non-finite or negative factors (corrupt
|
|
29
|
+
* table edit, bad injection) degrade to 1.0 — unfactored but never NaN,
|
|
30
|
+
* never negative on screen.
|
|
31
|
+
*/
|
|
32
|
+
function sanitizeFactor(raw) {
|
|
33
|
+
return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? raw : 1;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Session discounted USD from a ledger snapshot. Total function: never
|
|
37
|
+
* throws (guards non-finite/negative ledger values defensively — a corrupt
|
|
38
|
+
* snapshot must degrade the status line, not crash the hook).
|
|
39
|
+
*/
|
|
40
|
+
function discountedUsdForSnapshot(snapshot) {
|
|
41
|
+
return discountedUsdWithFactors(snapshot, DISCOUNT_FACTORS);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Factor-injectable core (exported for unit tests — e.g. proving a
|
|
45
|
+
* fat-finger factor can never overstate spend). `factors` falls back to
|
|
46
|
+
* 1.0 per model exactly like the table lookup.
|
|
47
|
+
*/
|
|
48
|
+
function discountedUsdWithFactors(snapshot, factors) {
|
|
49
|
+
const byModel = {};
|
|
50
|
+
let sum = 0;
|
|
51
|
+
for (const [model, entry] of Object.entries(snapshot.perModel)) {
|
|
52
|
+
const nano = typeof entry.nanoAiu === "number" && Number.isFinite(entry.nanoAiu) ? Math.max(0, entry.nanoAiu) : 0;
|
|
53
|
+
const factor = sanitizeFactor(factors[model]?.factor);
|
|
54
|
+
const usd = nano / 1e9 * USD_PER_AIC_CREDIT * factor;
|
|
55
|
+
byModel[model] = usd;
|
|
56
|
+
sum += usd;
|
|
57
|
+
}
|
|
58
|
+
const cap = aicTotalCredits(snapshot) * USD_PER_AIC_CREDIT;
|
|
59
|
+
if (!(sum > cap * (1 + 1e-9)) || sum <= 0) return {
|
|
60
|
+
total: sum,
|
|
61
|
+
byModel,
|
|
62
|
+
capped: false
|
|
63
|
+
};
|
|
64
|
+
const scale = cap / sum;
|
|
65
|
+
const scaled = {};
|
|
66
|
+
for (const [model, usd] of Object.entries(byModel)) scaled[model] = usd * scale;
|
|
67
|
+
return {
|
|
68
|
+
total: cap,
|
|
69
|
+
byModel: scaled,
|
|
70
|
+
capped: true
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Format table dollars: always cents (`~$` added by callers that want it). */
|
|
74
|
+
function formatTableUsd(usd) {
|
|
75
|
+
return usd.toFixed(2);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Beautiful per-model session cost table (plain text, no ANSI — it lands on
|
|
79
|
+
* stderr / logs). Columns mirror the spend dashboard: Uncached / Cached /
|
|
80
|
+
* [Write] / Cache% / Output / $. The Write column appears only when the
|
|
81
|
+
* session actually wrote cache. `Cache% = cache_read / (cache_read + input)`;
|
|
82
|
+
* writes are excluded (they are new tokens, not hits).
|
|
83
|
+
*/
|
|
84
|
+
function formatDiscountedCostTable(snapshot, discounted) {
|
|
85
|
+
const tokens = snapshot.tokensByModel ?? {};
|
|
86
|
+
const models = /* @__PURE__ */ new Set([...Object.keys(snapshot.perModel), ...Object.keys(tokens)]);
|
|
87
|
+
const rows = [];
|
|
88
|
+
for (const model of models) {
|
|
89
|
+
const t = tokens[model];
|
|
90
|
+
rows.push({
|
|
91
|
+
model,
|
|
92
|
+
uncached: t?.input ?? 0,
|
|
93
|
+
cached: t?.cache_read ?? 0,
|
|
94
|
+
writes: t?.cache_write ?? 0,
|
|
95
|
+
output: t?.output ?? 0,
|
|
96
|
+
usd: discounted.byModel[model] ?? 0
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (rows.length === 0) return "";
|
|
100
|
+
rows.sort((a, b) => b.usd - a.usd || a.model.localeCompare(b.model));
|
|
101
|
+
const showWrites = rows.some((r) => r.writes > 0);
|
|
102
|
+
const cachePct = (cached, uncached) => {
|
|
103
|
+
const denom = cached + uncached;
|
|
104
|
+
if (denom <= 0) return "—";
|
|
105
|
+
return `${(cached / denom * 100).toFixed(1)}%`;
|
|
106
|
+
};
|
|
107
|
+
const header = [
|
|
108
|
+
{
|
|
109
|
+
text: "Model",
|
|
110
|
+
align: "left"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
text: "Uncached",
|
|
114
|
+
align: "right"
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
text: "Cached",
|
|
118
|
+
align: "right"
|
|
119
|
+
}
|
|
120
|
+
];
|
|
121
|
+
if (showWrites) header.push({
|
|
122
|
+
text: "Write",
|
|
123
|
+
align: "right"
|
|
124
|
+
});
|
|
125
|
+
header.push({
|
|
126
|
+
text: "Cache%",
|
|
127
|
+
align: "right"
|
|
128
|
+
}, {
|
|
129
|
+
text: "Output",
|
|
130
|
+
align: "right"
|
|
131
|
+
}, {
|
|
132
|
+
text: "$",
|
|
133
|
+
align: "right"
|
|
134
|
+
});
|
|
135
|
+
const body = rows.map((r) => {
|
|
136
|
+
const cells = [
|
|
137
|
+
{
|
|
138
|
+
text: r.model,
|
|
139
|
+
align: "left"
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
text: formatCount(r.uncached),
|
|
143
|
+
align: "right"
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
text: formatCount(r.cached),
|
|
147
|
+
align: "right"
|
|
148
|
+
}
|
|
149
|
+
];
|
|
150
|
+
if (showWrites) cells.push({
|
|
151
|
+
text: formatCount(r.writes),
|
|
152
|
+
align: "right"
|
|
153
|
+
});
|
|
154
|
+
cells.push({
|
|
155
|
+
text: cachePct(r.cached, r.uncached),
|
|
156
|
+
align: "right"
|
|
157
|
+
}, {
|
|
158
|
+
text: formatCount(r.output),
|
|
159
|
+
align: "right"
|
|
160
|
+
}, {
|
|
161
|
+
text: `~$${formatTableUsd(r.usd)}`,
|
|
162
|
+
align: "right"
|
|
163
|
+
});
|
|
164
|
+
return cells;
|
|
165
|
+
});
|
|
166
|
+
const totalUncached = rows.reduce((n, r) => n + r.uncached, 0);
|
|
167
|
+
const totalCached = rows.reduce((n, r) => n + r.cached, 0);
|
|
168
|
+
const totalWrites = rows.reduce((n, r) => n + r.writes, 0);
|
|
169
|
+
const totalOutput = rows.reduce((n, r) => n + r.output, 0);
|
|
170
|
+
const totalCells = [
|
|
171
|
+
{
|
|
172
|
+
text: "Total",
|
|
173
|
+
align: "left"
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
text: formatCount(totalUncached),
|
|
177
|
+
align: "right"
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
text: formatCount(totalCached),
|
|
181
|
+
align: "right"
|
|
182
|
+
}
|
|
183
|
+
];
|
|
184
|
+
if (showWrites) totalCells.push({
|
|
185
|
+
text: formatCount(totalWrites),
|
|
186
|
+
align: "right"
|
|
187
|
+
});
|
|
188
|
+
totalCells.push({
|
|
189
|
+
text: cachePct(totalCached, totalUncached),
|
|
190
|
+
align: "right"
|
|
191
|
+
}, {
|
|
192
|
+
text: formatCount(totalOutput),
|
|
193
|
+
align: "right"
|
|
194
|
+
}, {
|
|
195
|
+
text: `~$${formatTableUsd(discounted.total)}`,
|
|
196
|
+
align: "right"
|
|
197
|
+
});
|
|
198
|
+
const widths = header.map((h, i) => {
|
|
199
|
+
let w = h.text.length;
|
|
200
|
+
for (const row of [...body, totalCells]) w = Math.max(w, row[i].text.length);
|
|
201
|
+
return w;
|
|
202
|
+
});
|
|
203
|
+
const render = (cells) => cells.map((c, i) => c.align === "left" ? c.text.padEnd(widths[i]) : c.text.padStart(widths[i])).join(" ");
|
|
204
|
+
return [
|
|
205
|
+
"Session cost (discounted actuals, ~$):",
|
|
206
|
+
render(header),
|
|
207
|
+
...body.map(render),
|
|
208
|
+
render(totalCells)
|
|
209
|
+
].join("\n");
|
|
210
|
+
}
|
|
211
|
+
/** Compact count for table cells: `999` → `999`, `15234` → `15.2k`. */
|
|
212
|
+
function formatCount(n) {
|
|
213
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
214
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
215
|
+
return `${n}`;
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
export { formatDiscountedCostTable as n, discountedUsdForSnapshot as t };
|
|
219
|
+
|
|
220
|
+
//# sourceMappingURL=copilot-discount-IbXR5A28.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-discount-IbXR5A28.js","names":[],"sources":["../src/lib/copilot-discount.ts"],"sourcesContent":["/**\n * Approximate discounted USD for a session, from static per-model discount\n * factors applied to the AIC ledger's billed nano-AIU.\n *\n * Background: GitHub's portal lists per-token rates, but the spend dashboard\n * bills several models well below portal (gpt-5.6-sol ≈ 0.28x, the Opus /\n * Sonnet / Codex cluster ≈ 0.6x, gemini-3.7-flash ≈ 0.29x since Sep 2026),\n * while Luna bills long-context portal tiers and Grok / 3.8-flash bill\n * portal-default exactly. No uniform per-lab factor exists (verified across\n * 28d / MTD / 7d / daily windows), so each model carries its own factor.\n *\n * The factors scale NANO-AIU, not tokens × portal rates: nano is already\n * tier-correct upstream (long-context tiers, cache writes), so no tier\n * engine or portal-rate table is needed here. Displayed total is capped:\n * `min(factored, totalCredits × $0.01)` — the cap can only ever lower the\n * number (all factors ≤ 1), so a typo like 2.8-instead-of-0.28 degrades to\n * the unfactored total rather than overstating spend.\n *\n * Staleness: rates move (3.7-flash flipped 1.00x → 0.29x overnight once\n * already). Re-derive monthly from the portal + spend dashboard; drift\n * degrades to cap-bound display, never to overstatement.\n */\n\nimport type { AicSnapshot } from \"./aic-ledger\"\nimport { aicTotalCredits } from \"./aic-ledger\"\n\n/** USD value of one AI credit (GitHub's published conversion). */\nexport const USD_PER_AIC_CREDIT = 0.01\n\nexport interface DiscountFactorRow {\n /** Multiply nano-implied USD by this. */\n factor: number\n /** Why this value: which snapshot window(s) it was derived from. */\n source: string\n}\n\nfunction row(factor: number, source: string): DiscountFactorRow {\n return { factor, source }\n}\n\n/**\n * Static per-model discount factors, keyed by resolved (Copilot-side) model\n * id — the same key the ledger's `perModel` uses. Derived Sep 2026 from the\n * 28d / MTD / 7d / daily spend-dashboard windows vs portal rates.\n */\nexport const DISCOUNT_FACTORS: Readonly<Record<string, DiscountFactorRow>> =\n Object.freeze({\n \"gpt-5.6-sol\": row(0.28, \"0.27-0.29 across 28d/MTD/7d/pre/9-9; write-mix refuted\"),\n \"claude-opus-5\": row(0.62, \"0.61-0.64 across windows; 9/7 1.02 excluded as single-day artifact\"),\n \"claude-sonnet-5\": row(0.66, \"0.62-0.71 across windows\"),\n \"gpt-5.3-codex\": row(0.60, \"0.59-0.62 across windows\"),\n \"gpt-5.4\": row(0.60, \"single snapshot 0.598\"),\n // Regime break: billed 1.00x pre-Sep, 0.29x since. Recheck FIRST at\n // every refresh — likeliest row to have moved again.\n \"gemini-3.7-flash\": row(0.29, \"September regime; pre-Sep 1.00x — volatile\"),\n // No discount: Luna's heat is long-context tiers + ~2% cache writes\n // (both already in nano); Grok / 3.8-flash bill portal-default exactly.\n \"gpt-5.6-luna\": row(1.0, \"long-tier portal + writes, no discount\"),\n \"grok-4.6\": row(1.0, \"portal default, six windows\"),\n \"gemini-3.8-flash\": row(1.0, \"portal exact, six windows to the dollar\"),\n })\n\n/** Discount factor for a model id; 1.0 (no discount) when unlisted. */\nexport function discountFactorFor(modelId: string): number {\n return sanitizeFactor(DISCOUNT_FACTORS[modelId]?.factor)\n}\n\n/**\n * Clamp a factor to usable range. Non-finite or negative factors (corrupt\n * table edit, bad injection) degrade to 1.0 — unfactored but never NaN,\n * never negative on screen.\n */\nfunction sanitizeFactor(raw: unknown): number {\n return typeof raw === \"number\" && Number.isFinite(raw) && raw >= 0 ? raw : 1.0\n}\n\nexport interface DiscountedUsd {\n /** Capped total actually displayed (`~$`). */\n total: number\n /** Per-model factored USD, scaled to the capped total when the cap binds. */\n byModel: Record<string, number>\n /** True when the cap (not the factors) decided the total. */\n capped: boolean\n}\n\n/**\n * Session discounted USD from a ledger snapshot. Total function: never\n * throws (guards non-finite/negative ledger values defensively — a corrupt\n * snapshot must degrade the status line, not crash the hook).\n */\nexport function discountedUsdForSnapshot(snapshot: AicSnapshot): DiscountedUsd {\n return discountedUsdWithFactors(snapshot, DISCOUNT_FACTORS)\n}\n\n/**\n * Factor-injectable core (exported for unit tests — e.g. proving a\n * fat-finger factor can never overstate spend). `factors` falls back to\n * 1.0 per model exactly like the table lookup.\n */\nexport function discountedUsdWithFactors(\n snapshot: AicSnapshot,\n factors: Readonly<Record<string, DiscountFactorRow>>,\n): DiscountedUsd {\n const byModel: Record<string, number> = {}\n let sum = 0\n for (const [model, entry] of Object.entries(snapshot.perModel)) {\n const nano =\n typeof entry.nanoAiu === \"number\" && Number.isFinite(entry.nanoAiu)\n ? Math.max(0, entry.nanoAiu)\n : 0\n const factor = sanitizeFactor(factors[model]?.factor)\n const usd = (nano / 1_000_000_000) * USD_PER_AIC_CREDIT * factor\n byModel[model] = usd\n sum += usd\n }\n const cap = aicTotalCredits(snapshot) * USD_PER_AIC_CREDIT\n // Relative epsilon: per-model float summation can exceed the cap by a\n // final-ulp hair without any factor being wrong — only bind on a real gap.\n if (!(sum > cap * (1 + 1e-9)) || sum <= 0) {\n return { total: sum, byModel, capped: false }\n }\n // Cap binds (fat-finger factor, volatile row, unknown-model overstatement):\n // scale rows down proportionally so the table still sums to its Total.\n const scale = cap / sum\n const scaled: Record<string, number> = {}\n for (const [model, usd] of Object.entries(byModel)) {\n scaled[model] = usd * scale\n }\n return { total: cap, byModel: scaled, capped: true }\n}\n\n/** Format table dollars: always cents (`~$` added by callers that want it). */\nexport function formatTableUsd(usd: number): string {\n return usd.toFixed(2)\n}\n\ninterface CostTableRow {\n model: string\n uncached: number\n cached: number\n writes: number\n output: number\n usd: number\n}\n\n/**\n * Beautiful per-model session cost table (plain text, no ANSI — it lands on\n * stderr / logs). Columns mirror the spend dashboard: Uncached / Cached /\n * [Write] / Cache% / Output / $. The Write column appears only when the\n * session actually wrote cache. `Cache% = cache_read / (cache_read + input)`;\n * writes are excluded (they are new tokens, not hits).\n */\nexport function formatDiscountedCostTable(\n snapshot: AicSnapshot,\n discounted: DiscountedUsd,\n): string {\n const tokens = snapshot.tokensByModel ?? {}\n const models = new Set([...Object.keys(snapshot.perModel), ...Object.keys(tokens)])\n const rows: Array<CostTableRow> = []\n for (const model of models) {\n const t = tokens[model]\n rows.push({\n model,\n uncached: t?.input ?? 0,\n cached: t?.cache_read ?? 0,\n writes: t?.cache_write ?? 0,\n output: t?.output ?? 0,\n usd: discounted.byModel[model] ?? 0,\n })\n }\n if (rows.length === 0) return \"\"\n rows.sort((a, b) => b.usd - a.usd || a.model.localeCompare(b.model))\n\n const showWrites = rows.some((r) => r.writes > 0)\n const cachePct = (cached: number, uncached: number): string => {\n const denom = cached + uncached\n if (denom <= 0) return \"—\"\n return `${((cached / denom) * 100).toFixed(1)}%`\n }\n\n type Cell = { text: string; align: \"left\" | \"right\" }\n const header: Array<Cell> = [\n { text: \"Model\", align: \"left\" },\n { text: \"Uncached\", align: \"right\" },\n { text: \"Cached\", align: \"right\" },\n ]\n if (showWrites) header.push({ text: \"Write\", align: \"right\" })\n header.push(\n { text: \"Cache%\", align: \"right\" },\n { text: \"Output\", align: \"right\" },\n { text: \"$\", align: \"right\" },\n )\n\n const body: Array<Array<Cell>> = rows.map((r) => {\n const cells: Array<Cell> = [\n { text: r.model, align: \"left\" },\n { text: formatCount(r.uncached), align: \"right\" },\n { text: formatCount(r.cached), align: \"right\" },\n ]\n if (showWrites) cells.push({ text: formatCount(r.writes), align: \"right\" })\n cells.push(\n { text: cachePct(r.cached, r.uncached), align: \"right\" },\n { text: formatCount(r.output), align: \"right\" },\n { text: `~$${formatTableUsd(r.usd)}`, align: \"right\" },\n )\n return cells\n })\n\n const totalUncached = rows.reduce((n, r) => n + r.uncached, 0)\n const totalCached = rows.reduce((n, r) => n + r.cached, 0)\n const totalWrites = rows.reduce((n, r) => n + r.writes, 0)\n const totalOutput = rows.reduce((n, r) => n + r.output, 0)\n const totalCells: Array<Cell> = [\n { text: \"Total\", align: \"left\" },\n { text: formatCount(totalUncached), align: \"right\" },\n { text: formatCount(totalCached), align: \"right\" },\n ]\n if (showWrites) {\n totalCells.push({ text: formatCount(totalWrites), align: \"right\" })\n }\n totalCells.push(\n { text: cachePct(totalCached, totalUncached), align: \"right\" },\n { text: formatCount(totalOutput), align: \"right\" },\n { text: `~$${formatTableUsd(discounted.total)}`, align: \"right\" },\n )\n\n const widths = header.map((h, i) => {\n let w = h.text.length\n for (const row of [...body, totalCells]) {\n w = Math.max(w, row[i].text.length)\n }\n return w\n })\n const render = (cells: Array<Cell>): string =>\n cells\n .map((c, i) =>\n c.align === \"left\" ? c.text.padEnd(widths[i]) : c.text.padStart(widths[i]),\n )\n .join(\" \")\n const lines = [\n \"Session cost (discounted actuals, ~$):\",\n render(header),\n ...body.map(render),\n render(totalCells),\n ]\n return lines.join(\"\\n\")\n}\n\n/** Compact count for table cells: `999` → `999`, `15234` → `15.2k`. */\nfunction formatCount(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`\n return `${n}`\n}\n"],"mappings":";;;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CAAQ,GACjD;EAAE,MAAM,KAAK,eAAe,WAAW,KAAK;EAAK,OAAO;CAAQ,CAClE;CAEA,MAAM,SAAS,OAAO,KAAK,GAAG,MAAM;EAClC,IAAI,IAAI,EAAE,KAAK;EACf,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,UAAU,GACpC,IAAI,KAAK,IAAI,GAAG,IAAI,EAAE,CAAC,KAAK,MAAM;EAEpC,OAAO;CACT,CAAC;CACD,MAAM,UAAU,UACd,MACG,KAAK,GAAG,MACP,EAAE,UAAU,SAAS,EAAE,KAAK,OAAO,OAAO,EAAE,IAAI,EAAE,KAAK,SAAS,OAAO,EAAE,CAC3E,CAAC,CACA,KAAK,IAAI;CAOd,OAAO;EALL;EACA,OAAO,MAAM;EACb,GAAG,KAAK,IAAI,MAAM;EAClB,OAAO,UAAU;CAER,CAAC,CAAC,KAAK,IAAI;AACxB;;AAGA,SAAS,YAAY,GAAmB;CACtC,IAAI,KAAK,KAAW,OAAO,IAAI,IAAI,IAAA,CAAW,QAAQ,CAAC,EAAE;CACzD,IAAI,KAAK,KAAM,OAAO,IAAI,IAAI,IAAA,CAAM,QAAQ,CAAC,EAAE;CAC/C,OAAO,GAAG;AACZ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as PATHS } from "./paths-
|
|
1
|
+
import { t as PATHS } from "./paths-CMxlQEfQ.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
import fs from "node:fs/promises";
|
|
@@ -78,4 +78,4 @@ const debug = defineCommand({
|
|
|
78
78
|
//#endregion
|
|
79
79
|
export { debug };
|
|
80
80
|
|
|
81
|
-
//# sourceMappingURL=debug-
|
|
81
|
+
//# sourceMappingURL=debug-CA7pg8V9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-
|
|
1
|
+
{"version":3,"file":"debug-CA7pg8V9.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\n\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = new URL(\"../package.json\", import.meta.url).pathname\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkTokenExists(): Promise<boolean> {\n try {\n const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkTokenExists(),\n ])\n\n return {\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`github-router debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;AA4BA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC,CAAC;EAMpE,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,CAAC;EACtD,UAAU,GAAG,SAAS;EACtB,MAAM,GAAG,KAAK;CAChB;AACF;AAEA,eAAe,mBAAqC;CAClD,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,MAAM,iBAAiB,EAAA,CACxC,OAAO,GAAG,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,MAAM,mBAAmB,MAAM,EAAA,CAClD,KAAK,CAAC,CAAC,SAAS;CACjC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,kBAAkB,GAClB,iBAAiB,CACnB,CAAC;CAED,OAAO;EACL;EACA,SAAS,eAAe;EACxB,OAAO;GACL,SAAS,MAAM;GACf,mBAAmB,MAAM;EAC3B;EACA;CACF;AACF;AAEA,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,MAAM,QAAQ;uBACT,KAAK,MAAM,kBAAkB;;gBAEpC,KAAK,cAAc,QAAQ,MAAM;AACjD;AAEA,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
|
|
@@ -545,6 +545,6 @@ function killChildProcessTree(child, opts = { detachedGroup: false }) {
|
|
|
545
545
|
}, graceMs).unref?.();
|
|
546
546
|
}
|
|
547
547
|
//#endregion
|
|
548
|
-
export {
|
|
548
|
+
export { parseIntEnv as a, runCommandVoid as c, parseBoolEnv as i, runManagedExeCapture as l, killChildProcessTree as n, resolveExecutable as o, killManagedTree as r, runCommandCapture as s, buildExecInvocation as t, spawnTaskkillBestEffort as u };
|
|
549
549
|
|
|
550
|
-
//# sourceMappingURL=exec-
|
|
550
|
+
//# sourceMappingURL=exec-COUT4QsS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec-y8C_MU8A.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 go through `cmd.exe` (`shell:true`). That in\n * turn opens two hazards 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}\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 → a single caret/argv-quoted command string + `shell:true`\n * + empty args array (the empty array avoids the DEP0190 warning\n * that fires when args and `shell:true` are combined). `cmd[0]`\n * should already be an absolute path from `resolveExecutable`.\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 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 /**\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 } = 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 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\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 // 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 reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Spawn `taskkill` best-effort, without any chance of taking the proxy down.\n *\n * Two things a bare `try { spawn(\"taskkill\", ...) } catch {}` gets wrong, both\n * of which this helper is the single place that fixes:\n *\n * 1. **The catch cannot catch.** `spawn` reports ENOENT / EPERM / EACCES by\n * emitting `'error'` ASYNCHRONOUSLY, so the surrounding `try` (which only\n * guards the synchronous throw) never sees it. An EventEmitter `'error'`\n * with no listener THROWS — which lands in the `uncaughtException` handler\n * in `~/main` and calls `process.exit(1)`. A best-effort child kill on a\n * timeout path could therefore kill the whole proxy. The listener must be\n * attached synchronously at the spawn site, which is why this is a helper\n * and not a convention.\n * 2. **The bare name is hijackable.** `CreateProcess`'s search order can\n * include the cwd, so `\"taskkill\"` may resolve to a planted binary;\n * `taskkillExe()` pins `System32\\taskkill.exe`.\n */\nexport function spawnTaskkillBestEffort(pid: number): boolean {\n try {\n const child = spawn(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n // Load-bearing: see (1) above. Without this an async spawn failure is an\n // uncaught exception, not a no-op. It is NOT a silent swallow, either —\n // the fallback below is what keeps a caller from hanging.\n //\n // (No logging here on purpose: this module has no logger import, and\n // taking one would pull a dependency into the lowest-level exec helper\n // that every other module builds on. The fallback is the observable\n // behavior that matters.)\n child.on(\"error\", () => {\n fallbackKill(pid)\n })\n return true\n } catch {\n // Synchronous spawn failure (bad argv shape).\n fallbackKill(pid)\n return false\n }\n}\n\n/**\n * Last-resort single-process kill when `taskkill` itself cannot run.\n *\n * Not a tree kill — grandchildren survive — but it is the difference between\n * \"the timed-out child dies and its `close` event settles the caller\" and \"the\n * caller waits forever\". `runInternal` resolves ONLY from `close`, so a timeout\n * whose kill never lands leaves that promise pending for the life of the\n * process, which is a worse failure than the crash `spawnTaskkillBestEffort`\n * was written to prevent. Best-effort by construction: ESRCH means the child\n * was already gone, which is the success case.\n */\nfunction fallbackKill(pid: number): void {\n try {\n process.kill(pid)\n } catch {\n // Already exited, or we lack permission — nothing further to try.\n }\n}\n\n/** Kill a process tree best-effort (taskkill /T on Windows). */\nfunction killTree(pid: number | undefined): void {\n if (!pid) return\n try {\n if (process.platform === \"win32\") {\n spawnTaskkillBestEffort(pid)\n } else {\n process.kill(pid, \"SIGTERM\")\n }\n } catch {\n // already gone\n }\n}\n\n/** Run a command and capture stdout/stderr. Rejects on spawn error. */\nexport function runCommandCapture(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command discarding output (still captures stderr for errors). */\nexport function runCommandVoid(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command with the child's stdout/stderr inherited to the user. */\nexport function runCommandInherit(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"inherit\", opts)\n}\n\nexport interface ManagedExeOpts extends RunOpts {\n /**\n * Hard cap on captured stdout bytes. On overflow the child is\n * tree-killed and the result carries `stdoutTruncated: true`. Defends\n * against a full-`CodeUnit` colgrep `--json` payload (source + 5\n * analysis layers per hit) bloating memory.\n */\n maxStdoutBytes?: number\n /**\n * When true, exceeding `maxStdoutBytes` does NOT tree-kill the child — it\n * sets `stdoutTruncated` and stops BUFFERING further stdout while still\n * draining the pipe (no backpressure). Use for a child whose kill is unsafe\n * (e.g. colgrep, which writes a non-atomic index — a byte-cap kill during\n * its result output could interrupt a write). The child runs to completion\n * (bounded by `timeoutMs` / `inactivityTimeoutMs`). Default false (kill).\n */\n truncateInsteadOfKill?: boolean\n /**\n * Called synchronously with the spawned child right after spawn\n * succeeds, BEFORE any output arrives. The colbert lifecycle ledger\n * uses this to register the child so a session-exit sweep can\n * tree-kill an orphan. Never throws into the runner.\n */\n onSpawn?: (child: ReturnType<typeof spawn>) => void\n /**\n * Inactivity (stall) watchdog. When set, a timer is armed for\n * `inactivityTimeoutMs` and RESET on every stdout/stderr data chunk. On\n * expiry (no output for the window) it consults `onInactivityCheck`: a\n * `true` return means \"still making progress via an out-of-band signal\"\n * (e.g. the colgrep index dir is still growing on disk even though the\n * process is silent on a non-TTY pipe) and the watchdog re-arms; a\n * `false`/absent return tree-kills the child and sets `stalled: true`.\n * This is the progress-based \"stuck\" detector that lets a long-but-\n * progressing build run to completion while still killing a hung one —\n * independent of the coarse total `timeoutMs` backstop.\n */\n inactivityTimeoutMs?: number\n /** External progress probe consulted when the inactivity timer fires.\n * Return `true` to re-arm (still progressing), `false`/throw to kill.\n * MUST be cheap + synchronous (called on a timer, not awaited). */\n onInactivityCheck?: () => boolean\n}\n\nexport interface ManagedExeResult extends RunResult {\n /** True iff stdout was truncated at `maxStdoutBytes` (child was killed). */\n stdoutTruncated: boolean\n /** True iff the inactivity watchdog killed the child (no progress). */\n stalled: boolean\n}\n\n/**\n * Run a **native executable** (a real `.exe`/Mach-O/ELF, NOT a `.cmd`\n * shim) capturing stdout/stderr, with `shell:false` on EVERY platform.\n *\n * Why a separate runner from `runCommandCapture`: that path routes\n * through `buildExecInvocation`, which on Windows builds a\n * `cmd.exe`-quoted command string and **throws on `%`** (`quoteWinArg`).\n * A workspace path can legally contain `%` (and `&`, `(`, `)`, `!`, …),\n * so the managed colgrep binary — which IS a native `.exe`, not a shim —\n * must bypass cmd.exe entirely. `spawn(absExe, args, {shell:false})`\n * resolves the `.exe` via CreateProcess directly: no cmd.exe, no\n * metacharacter hazard, no `%` refusal. POSIX was already `shell:false`.\n * This is what makes \"ANY absolute workspace\" hold on Windows.\n *\n * Lifecycle:\n * - `timeoutMs` → tree-kill on expiry (`taskkill /T /F` on Windows,\n * POSIX process-group `kill(-pgid)` so colgrep's rayon worker\n * children die too). `timedOut: true` in the result.\n * - `maxStdoutBytes` → tree-kill + `stdoutTruncated: true` once the\n * captured stdout exceeds the cap.\n * - `onSpawn(child)` → register the child with the caller's ledger.\n *\n * `command` MUST be an absolute path to the executable (the caller\n * resolves it; we never search PATH here — there is nothing to inject).\n */\nexport function runManagedExeCapture(\n command: string,\n args: ReadonlyArray<string>,\n opts: ManagedExeOpts = {},\n): Promise<ManagedExeResult> {\n const isWin = process.platform === \"win32\"\n return new Promise<ManagedExeResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, [...args], {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: false,\n windowsHide: true,\n // POSIX: new process group so we can kill the whole tree\n // (colgrep + rayon workers) with kill(-pgid). Windows uses\n // taskkill /T instead; `detached` there has no group semantics.\n detached: !isWin,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n try {\n opts.onSpawn?.(child)\n } catch {\n // ledger registration must never break the spawn\n }\n\n const chunks: Array<Buffer> = []\n let stdoutBytes = 0\n const stderrChunks: Array<Buffer> = []\n let stderrBytes = 0\n const STDERR_CAP = 64 * 1024\n let timedOut = false\n let stdoutTruncated = false\n let stalled = false\n let settled = false\n\n // Exactly one terminator wins: the first to fire records its reason and\n // tree-kills; later ones no-op. Keeps timedOut / stalled / stdoutTruncated\n // mutually exclusive and avoids a double tree-kill.\n let terminated = false\n const terminate = (reason: \"timeout\" | \"stall\" | \"truncate\"): void => {\n if (terminated) return\n terminated = true\n if (reason === \"timeout\") timedOut = true\n else if (reason === \"stall\") stalled = true\n else stdoutTruncated = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n killManagedTree(child, isWin)\n }\n\n const timer = opts.timeoutMs\n ? setTimeout(() => terminate(\"timeout\"), opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n // Inactivity (stall) watchdog. Re-arms itself: when the window elapses\n // with no output, consult the external progress probe — re-arm if it\n // says \"still progressing\" (e.g. the index dir grew), else kill + mark\n // stalled. Reset on every data chunk (a chatty process never stalls).\n let inactivityTimer: ReturnType<typeof setTimeout> | undefined\n const armInactivity = (): void => {\n if (opts.inactivityTimeoutMs === undefined || settled || terminated) return\n inactivityTimer = setTimeout(() => {\n if (settled) return\n // No probe → pure output-inactivity kill. A probe that THROWS is\n // inconclusive → don't kill (re-arm); the absolute timeoutMs backstop\n // still catches a genuinely wedged process.\n let progressing = false\n if (opts.onInactivityCheck) {\n try {\n progressing = opts.onInactivityCheck() === true\n } catch {\n progressing = true\n }\n }\n if (progressing) {\n armInactivity()\n return\n }\n terminate(\"stall\")\n }, opts.inactivityTimeoutMs)\n inactivityTimer?.unref?.()\n }\n const resetInactivity = (): void => {\n if (inactivityTimer) clearTimeout(inactivityTimer)\n armInactivity()\n }\n armInactivity()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n if (stdoutTruncated) return\n stdoutBytes += c.length\n if (\n opts.maxStdoutBytes !== undefined &&\n stdoutBytes > opts.maxStdoutBytes\n ) {\n stdoutTruncated = true\n // Default: tree-kill on overflow. Opt-in: keep the child alive and\n // just stop buffering (the data handler keeps firing + discarding via\n // the `if (stdoutTruncated) return` guard above, so the pipe drains\n // and the child never blocks on a full buffer).\n if (!opts.truncateInsteadOfKill) terminate(\"truncate\")\n return\n }\n chunks.push(c)\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n // Hard byte cap on stderr — append only the slice that fits so a\n // single huge chunk can't overshoot. Never logged raw (it can\n // embed source code from colgrep).\n if (stderrBytes >= STDERR_CAP) return\n const remaining = STDERR_CAP - stderrBytes\n const slice = c.length > remaining ? c.subarray(0, remaining) : c\n stderrChunks.push(slice)\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n resolve({\n stdout: Buffer.concat(chunks).toString(\"utf8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf8\"),\n code,\n timedOut,\n stdoutTruncated,\n // `RunResult.truncated` is the shared, runner-agnostic signal. Kept in\n // lockstep with `stdoutTruncated` (this runner's older, more specific\n // name, which callers already branch on) so a caller holding either\n // shape reads the same fact.\n truncated: stdoutTruncated,\n // This runner slices stderr to fit its own 64 KiB cap without tracking\n // whether it did, so report the honest thing rather than guess.\n stderrTruncated: stderrBytes >= STDERR_CAP,\n stalled,\n })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Tree-kill a managed child. Windows: `taskkill /T /F /PID` (whole\n * tree). POSIX: kill the process GROUP (`-pgid`) so colgrep's rayon\n * worker children die with the parent.\n *\n * `runManagedExeCapture` always spawns POSIX children `detached:true`\n * (their own process group), so the group kill is the correct and\n * sufficient primitive. We deliberately do NOT fall back to a positive-\n * pid `process.kill(pid)` when the group kill fails: by the time a kill\n * fires (timeout / byte-cap race), the child may have already exited and\n * its PID been recycled by an unrelated process — a positive-pid kill\n * would then target the wrong process. `ESRCH` (group already gone) is\n * the success case for our purposes; any other error is swallowed.\n */\nexport function killManagedTree(\n child: ReturnType<typeof spawn>,\n isWin: boolean = process.platform === \"win32\",\n): void {\n const pid = child.pid\n if (!pid) return\n try {\n if (isWin) {\n spawnTaskkillBestEffort(pid)\n } else {\n // Negative pid → the process group (we spawned detached). No\n // positive-pid fallback (PID-reuse hazard — see doc comment).\n process.kill(-pid, \"SIGKILL\")\n }\n } catch {\n // ESRCH (already gone) / EPERM — best-effort, nothing more to do.\n }\n}\n\n/**\n * Absolute path to Windows `taskkill.exe`. Bare `\"taskkill\"` would let\n * `CreateProcess`'s search order (which can include the cwd) run a planted\n * `taskkill.exe`; pinning the System32 path closes that hijack.\n */\nfunction taskkillExe(): string {\n const root =\n process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\"\n return path.join(root, \"System32\", \"taskkill.exe\")\n}\n\n/**\n * Tree-kill a child process on a SHUTDOWN/exit path, deterministically.\n *\n * Distinct from `killManagedTree` in two ways that matter when the proxy\n * is about to call `process.exit`:\n *\n * 1. **Windows uses `spawnSync`, not async `spawn`.** An async taskkill\n * may never issue before `process.exit` tears the event loop down;\n * the synchronous form guarantees the kill command has run. It is\n * time-bounded so a wedged taskkill can't hang shutdown.\n * 2. **POSIX honors `detachedGroup`.** The launched CLI is spawned\n * `detached:true` (its own process group) so `kill(-pid)` reaps the\n * whole group; other callers (e.g. ripgrep) are NOT detached, so\n * `child.kill()` on the positive pid is correct. A negative-pid kill\n * on a non-detached child would throw or hit the wrong target.\n *\n * Both branches escalate SIGTERM → SIGKILL after `graceMs` so a CLI that\n * traps SIGTERM still dies. The escalation timer is `.unref()`'d so it\n * never holds the event loop open. Errors are swallowed (already-gone /\n * EBUSY / ESRCH are the success case for our purposes).\n */\nexport function killChildProcessTree(\n child: ChildProcess,\n opts: { detachedGroup: boolean; graceMs?: number } = { detachedGroup: false },\n): void {\n const pid = child.pid\n if (!pid) return\n const graceMs = opts.graceMs ?? 500\n\n if (process.platform === \"win32\") {\n // /T = whole tree, /F = force. taskkill walks the live parent-PID\n // chain, so it reaps grandchildren regardless of the cmd.exe-vs-direct\n // spawn shape. Sync (completes before an imminent process.exit) and\n // time-bounded (a wedged taskkill must not hang shutdown).\n try {\n spawnSync(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n timeout: 5000,\n })\n } catch {\n // Already gone / EBUSY race — best-effort.\n }\n return\n }\n\n // POSIX: signal the group (detached) or the lone child (non-detached).\n const target = opts.detachedGroup ? -pid : pid\n try {\n process.kill(target, \"SIGTERM\")\n } catch {\n // ESRCH — already gone.\n }\n const t = setTimeout(() => {\n // For a lone (non-detached) child, skip escalation once it has exited\n // — its positive PID could have been recycled. For a process GROUP the\n // leader's exit does NOT mean the group is empty (a SIGTERM-ignoring\n // grandchild may survive), and the group id is only reused once the\n // group is fully gone, so always attempt the group SIGKILL (ESRCH when\n // already empty is the success case).\n if (\n !opts.detachedGroup &&\n (child.exitCode !== null || child.signalCode !== null)\n ) {\n return\n }\n try {\n process.kill(target, \"SIGKILL\")\n } catch {\n // Already dead.\n }\n }, graceMs)\n t.unref?.()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,aAAa,OAAgD;CAC3E,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,IAAI,MAAM,KAAK,CAAC,CAAC,YAAY;CACnC,IAAI,MAAM,OAAO,MAAM,UAAU,MAAM,SAAS,MAAM,MAAM,OAAO;CACnE,IAAI,MAAM,OAAO,MAAM,WAAW,MAAM,QAAQ,MAAM,SAAS,MAAM,IACnE,OAAO;AAGX;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,OAA+C;CACzE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,MAAM,M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UAAU,SAAS,OAAO,IAAI,CAAC;CAC1C,CAAC;AACH;;;;;;;;;;;;;;;AAgBA,SAAgB,gBACd,OACA,QAAiB,QAAQ,aAAa,SAChC;CACN,MAAM,MAAM,MAAM;CAClB,IAAI,CAAC,KAAK;CACV,IAAI;EACF,IAAI,OACF,wBAAwB,GAAG;OAI3B,QAAQ,KAAK,CAAC,KAAK,SAAS;CAEhC,QAAQ,CAER;AACF;;;;;;AAOA,SAAS,cAAsB;CAC7B,MAAM,OACJ,QAAQ,IAAI,cAAc,QAAQ,IAAI,UAAU;CAClD,OAAO,KAAK,KAAK,MAAM,YAAY,cAAc;AACnD;;;;;;;;;;;;;;;;;;;;;;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;CAoBA,iBAnB2B;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
|
+
{"version":3,"file":"exec-COUT4QsS.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 go through `cmd.exe` (`shell:true`). That in\n * turn opens two hazards 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}\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 → a single caret/argv-quoted command string + `shell:true`\n * + empty args array (the empty array avoids the DEP0190 warning\n * that fires when args and `shell:true` are combined). `cmd[0]`\n * should already be an absolute path from `resolveExecutable`.\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 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 /**\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 } = 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 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\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 // 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 reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Spawn `taskkill` best-effort, without any chance of taking the proxy down.\n *\n * Two things a bare `try { spawn(\"taskkill\", ...) } catch {}` gets wrong, both\n * of which this helper is the single place that fixes:\n *\n * 1. **The catch cannot catch.** `spawn` reports ENOENT / EPERM / EACCES by\n * emitting `'error'` ASYNCHRONOUSLY, so the surrounding `try` (which only\n * guards the synchronous throw) never sees it. An EventEmitter `'error'`\n * with no listener THROWS — which lands in the `uncaughtException` handler\n * in `~/main` and calls `process.exit(1)`. A best-effort child kill on a\n * timeout path could therefore kill the whole proxy. The listener must be\n * attached synchronously at the spawn site, which is why this is a helper\n * and not a convention.\n * 2. **The bare name is hijackable.** `CreateProcess`'s search order can\n * include the cwd, so `\"taskkill\"` may resolve to a planted binary;\n * `taskkillExe()` pins `System32\\taskkill.exe`.\n */\nexport function spawnTaskkillBestEffort(pid: number): boolean {\n try {\n const child = spawn(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n })\n // Load-bearing: see (1) above. Without this an async spawn failure is an\n // uncaught exception, not a no-op. It is NOT a silent swallow, either —\n // the fallback below is what keeps a caller from hanging.\n //\n // (No logging here on purpose: this module has no logger import, and\n // taking one would pull a dependency into the lowest-level exec helper\n // that every other module builds on. The fallback is the observable\n // behavior that matters.)\n child.on(\"error\", () => {\n fallbackKill(pid)\n })\n return true\n } catch {\n // Synchronous spawn failure (bad argv shape).\n fallbackKill(pid)\n return false\n }\n}\n\n/**\n * Last-resort single-process kill when `taskkill` itself cannot run.\n *\n * Not a tree kill — grandchildren survive — but it is the difference between\n * \"the timed-out child dies and its `close` event settles the caller\" and \"the\n * caller waits forever\". `runInternal` resolves ONLY from `close`, so a timeout\n * whose kill never lands leaves that promise pending for the life of the\n * process, which is a worse failure than the crash `spawnTaskkillBestEffort`\n * was written to prevent. Best-effort by construction: ESRCH means the child\n * was already gone, which is the success case.\n */\nfunction fallbackKill(pid: number): void {\n try {\n process.kill(pid)\n } catch {\n // Already exited, or we lack permission — nothing further to try.\n }\n}\n\n/** Kill a process tree best-effort (taskkill /T on Windows). */\nfunction killTree(pid: number | undefined): void {\n if (!pid) return\n try {\n if (process.platform === \"win32\") {\n spawnTaskkillBestEffort(pid)\n } else {\n process.kill(pid, \"SIGTERM\")\n }\n } catch {\n // already gone\n }\n}\n\n/** Run a command and capture stdout/stderr. Rejects on spawn error. */\nexport function runCommandCapture(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command discarding output (still captures stderr for errors). */\nexport function runCommandVoid(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"pipe\", opts)\n}\n\n/** Run a command with the child's stdout/stderr inherited to the user. */\nexport function runCommandInherit(\n cmd: string[],\n opts: RunOpts = {},\n): Promise<RunResult> {\n return runInternal(cmd, \"inherit\", opts)\n}\n\nexport interface ManagedExeOpts extends RunOpts {\n /**\n * Hard cap on captured stdout bytes. On overflow the child is\n * tree-killed and the result carries `stdoutTruncated: true`. Defends\n * against a full-`CodeUnit` colgrep `--json` payload (source + 5\n * analysis layers per hit) bloating memory.\n */\n maxStdoutBytes?: number\n /**\n * When true, exceeding `maxStdoutBytes` does NOT tree-kill the child — it\n * sets `stdoutTruncated` and stops BUFFERING further stdout while still\n * draining the pipe (no backpressure). Use for a child whose kill is unsafe\n * (e.g. colgrep, which writes a non-atomic index — a byte-cap kill during\n * its result output could interrupt a write). The child runs to completion\n * (bounded by `timeoutMs` / `inactivityTimeoutMs`). Default false (kill).\n */\n truncateInsteadOfKill?: boolean\n /**\n * Called synchronously with the spawned child right after spawn\n * succeeds, BEFORE any output arrives. The colbert lifecycle ledger\n * uses this to register the child so a session-exit sweep can\n * tree-kill an orphan. Never throws into the runner.\n */\n onSpawn?: (child: ReturnType<typeof spawn>) => void\n /**\n * Inactivity (stall) watchdog. When set, a timer is armed for\n * `inactivityTimeoutMs` and RESET on every stdout/stderr data chunk. On\n * expiry (no output for the window) it consults `onInactivityCheck`: a\n * `true` return means \"still making progress via an out-of-band signal\"\n * (e.g. the colgrep index dir is still growing on disk even though the\n * process is silent on a non-TTY pipe) and the watchdog re-arms; a\n * `false`/absent return tree-kills the child and sets `stalled: true`.\n * This is the progress-based \"stuck\" detector that lets a long-but-\n * progressing build run to completion while still killing a hung one —\n * independent of the coarse total `timeoutMs` backstop.\n */\n inactivityTimeoutMs?: number\n /** External progress probe consulted when the inactivity timer fires.\n * Return `true` to re-arm (still progressing), `false`/throw to kill.\n * MUST be cheap + synchronous (called on a timer, not awaited). */\n onInactivityCheck?: () => boolean\n}\n\nexport interface ManagedExeResult extends RunResult {\n /** True iff stdout was truncated at `maxStdoutBytes` (child was killed). */\n stdoutTruncated: boolean\n /** True iff the inactivity watchdog killed the child (no progress). */\n stalled: boolean\n}\n\n/**\n * Run a **native executable** (a real `.exe`/Mach-O/ELF, NOT a `.cmd`\n * shim) capturing stdout/stderr, with `shell:false` on EVERY platform.\n *\n * Why a separate runner from `runCommandCapture`: that path routes\n * through `buildExecInvocation`, which on Windows builds a\n * `cmd.exe`-quoted command string and **throws on `%`** (`quoteWinArg`).\n * A workspace path can legally contain `%` (and `&`, `(`, `)`, `!`, …),\n * so the managed colgrep binary — which IS a native `.exe`, not a shim —\n * must bypass cmd.exe entirely. `spawn(absExe, args, {shell:false})`\n * resolves the `.exe` via CreateProcess directly: no cmd.exe, no\n * metacharacter hazard, no `%` refusal. POSIX was already `shell:false`.\n * This is what makes \"ANY absolute workspace\" hold on Windows.\n *\n * Lifecycle:\n * - `timeoutMs` → tree-kill on expiry (`taskkill /T /F` on Windows,\n * POSIX process-group `kill(-pgid)` so colgrep's rayon worker\n * children die too). `timedOut: true` in the result.\n * - `maxStdoutBytes` → tree-kill + `stdoutTruncated: true` once the\n * captured stdout exceeds the cap.\n * - `onSpawn(child)` → register the child with the caller's ledger.\n *\n * `command` MUST be an absolute path to the executable (the caller\n * resolves it; we never search PATH here — there is nothing to inject).\n */\nexport function runManagedExeCapture(\n command: string,\n args: ReadonlyArray<string>,\n opts: ManagedExeOpts = {},\n): Promise<ManagedExeResult> {\n const isWin = process.platform === \"win32\"\n return new Promise<ManagedExeResult>((resolve, reject) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(command, [...args], {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n shell: false,\n windowsHide: true,\n // POSIX: new process group so we can kill the whole tree\n // (colgrep + rayon workers) with kill(-pgid). Windows uses\n // taskkill /T instead; `detached` there has no group semantics.\n detached: !isWin,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)))\n return\n }\n\n try {\n opts.onSpawn?.(child)\n } catch {\n // ledger registration must never break the spawn\n }\n\n const chunks: Array<Buffer> = []\n let stdoutBytes = 0\n const stderrChunks: Array<Buffer> = []\n let stderrBytes = 0\n const STDERR_CAP = 64 * 1024\n let timedOut = false\n let stdoutTruncated = false\n let stalled = false\n let settled = false\n\n // Exactly one terminator wins: the first to fire records its reason and\n // tree-kills; later ones no-op. Keeps timedOut / stalled / stdoutTruncated\n // mutually exclusive and avoids a double tree-kill.\n let terminated = false\n const terminate = (reason: \"timeout\" | \"stall\" | \"truncate\"): void => {\n if (terminated) return\n terminated = true\n if (reason === \"timeout\") timedOut = true\n else if (reason === \"stall\") stalled = true\n else stdoutTruncated = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n killManagedTree(child, isWin)\n }\n\n const timer = opts.timeoutMs\n ? setTimeout(() => terminate(\"timeout\"), opts.timeoutMs)\n : undefined\n timer?.unref?.()\n\n // Inactivity (stall) watchdog. Re-arms itself: when the window elapses\n // with no output, consult the external progress probe — re-arm if it\n // says \"still progressing\" (e.g. the index dir grew), else kill + mark\n // stalled. Reset on every data chunk (a chatty process never stalls).\n let inactivityTimer: ReturnType<typeof setTimeout> | undefined\n const armInactivity = (): void => {\n if (opts.inactivityTimeoutMs === undefined || settled || terminated) return\n inactivityTimer = setTimeout(() => {\n if (settled) return\n // No probe → pure output-inactivity kill. A probe that THROWS is\n // inconclusive → don't kill (re-arm); the absolute timeoutMs backstop\n // still catches a genuinely wedged process.\n let progressing = false\n if (opts.onInactivityCheck) {\n try {\n progressing = opts.onInactivityCheck() === true\n } catch {\n progressing = true\n }\n }\n if (progressing) {\n armInactivity()\n return\n }\n terminate(\"stall\")\n }, opts.inactivityTimeoutMs)\n inactivityTimer?.unref?.()\n }\n const resetInactivity = (): void => {\n if (inactivityTimer) clearTimeout(inactivityTimer)\n armInactivity()\n }\n armInactivity()\n\n child.stdout?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n if (stdoutTruncated) return\n stdoutBytes += c.length\n if (\n opts.maxStdoutBytes !== undefined &&\n stdoutBytes > opts.maxStdoutBytes\n ) {\n stdoutTruncated = true\n // Default: tree-kill on overflow. Opt-in: keep the child alive and\n // just stop buffering (the data handler keeps firing + discarding via\n // the `if (stdoutTruncated) return` guard above, so the pipe drains\n // and the child never blocks on a full buffer).\n if (!opts.truncateInsteadOfKill) terminate(\"truncate\")\n return\n }\n chunks.push(c)\n })\n child.stderr?.on(\"data\", (c: Buffer) => {\n resetInactivity()\n // Hard byte cap on stderr — append only the slice that fits so a\n // single huge chunk can't overshoot. Never logged raw (it can\n // embed source code from colgrep).\n if (stderrBytes >= STDERR_CAP) return\n const remaining = STDERR_CAP - stderrBytes\n const slice = c.length > remaining ? c.subarray(0, remaining) : c\n stderrChunks.push(slice)\n stderrBytes += slice.length\n })\n child.stdout?.on(\"error\", () => {})\n child.stderr?.on(\"error\", () => {})\n\n const finish = (code: number | null): void => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n resolve({\n stdout: Buffer.concat(chunks).toString(\"utf8\"),\n stderr: Buffer.concat(stderrChunks).toString(\"utf8\"),\n code,\n timedOut,\n stdoutTruncated,\n // `RunResult.truncated` is the shared, runner-agnostic signal. Kept in\n // lockstep with `stdoutTruncated` (this runner's older, more specific\n // name, which callers already branch on) so a caller holding either\n // shape reads the same fact.\n truncated: stdoutTruncated,\n // This runner slices stderr to fit its own 64 KiB cap without tracking\n // whether it did, so report the honest thing rather than guess.\n stderrTruncated: stderrBytes >= STDERR_CAP,\n stalled,\n })\n }\n\n child.on(\"error\", (err) => {\n if (settled) return\n settled = true\n if (timer) clearTimeout(timer)\n if (inactivityTimer) clearTimeout(inactivityTimer)\n reject(err)\n })\n child.on(\"close\", (code) => finish(code))\n })\n}\n\n/**\n * Tree-kill a managed child. Windows: `taskkill /T /F /PID` (whole\n * tree). POSIX: kill the process GROUP (`-pgid`) so colgrep's rayon\n * worker children die with the parent.\n *\n * `runManagedExeCapture` always spawns POSIX children `detached:true`\n * (their own process group), so the group kill is the correct and\n * sufficient primitive. We deliberately do NOT fall back to a positive-\n * pid `process.kill(pid)` when the group kill fails: by the time a kill\n * fires (timeout / byte-cap race), the child may have already exited and\n * its PID been recycled by an unrelated process — a positive-pid kill\n * would then target the wrong process. `ESRCH` (group already gone) is\n * the success case for our purposes; any other error is swallowed.\n */\nexport function killManagedTree(\n child: ReturnType<typeof spawn>,\n isWin: boolean = process.platform === \"win32\",\n): void {\n const pid = child.pid\n if (!pid) return\n try {\n if (isWin) {\n spawnTaskkillBestEffort(pid)\n } else {\n // Negative pid → the process group (we spawned detached). No\n // positive-pid fallback (PID-reuse hazard — see doc comment).\n process.kill(-pid, \"SIGKILL\")\n }\n } catch {\n // ESRCH (already gone) / EPERM — best-effort, nothing more to do.\n }\n}\n\n/**\n * Absolute path to Windows `taskkill.exe`. Bare `\"taskkill\"` would let\n * `CreateProcess`'s search order (which can include the cwd) run a planted\n * `taskkill.exe`; pinning the System32 path closes that hijack.\n */\nfunction taskkillExe(): string {\n const root =\n process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\"\n return path.join(root, \"System32\", \"taskkill.exe\")\n}\n\n/**\n * Tree-kill a child process on a SHUTDOWN/exit path, deterministically.\n *\n * Distinct from `killManagedTree` in two ways that matter when the proxy\n * is about to call `process.exit`:\n *\n * 1. **Windows uses `spawnSync`, not async `spawn`.** An async taskkill\n * may never issue before `process.exit` tears the event loop down;\n * the synchronous form guarantees the kill command has run. It is\n * time-bounded so a wedged taskkill can't hang shutdown.\n * 2. **POSIX honors `detachedGroup`.** The launched CLI is spawned\n * `detached:true` (its own process group) so `kill(-pid)` reaps the\n * whole group; other callers (e.g. ripgrep) are NOT detached, so\n * `child.kill()` on the positive pid is correct. A negative-pid kill\n * on a non-detached child would throw or hit the wrong target.\n *\n * Both branches escalate SIGTERM → SIGKILL after `graceMs` so a CLI that\n * traps SIGTERM still dies. The escalation timer is `.unref()`'d so it\n * never holds the event loop open. Errors are swallowed (already-gone /\n * EBUSY / ESRCH are the success case for our purposes).\n */\nexport function killChildProcessTree(\n child: ChildProcess,\n opts: { detachedGroup: boolean; graceMs?: number } = { detachedGroup: false },\n): void {\n const pid = child.pid\n if (!pid) return\n const graceMs = opts.graceMs ?? 500\n\n if (process.platform === \"win32\") {\n // /T = whole tree, /F = force. taskkill walks the live parent-PID\n // chain, so it reaps grandchildren regardless of the cmd.exe-vs-direct\n // spawn shape. Sync (completes before an imminent process.exit) and\n // time-bounded (a wedged taskkill must not hang shutdown).\n try {\n spawnSync(taskkillExe(), [\"/T\", \"/F\", \"/PID\", String(pid)], {\n stdio: \"ignore\",\n windowsHide: true,\n timeout: 5000,\n })\n } catch {\n // Already gone / EBUSY race — best-effort.\n }\n return\n }\n\n // POSIX: signal the group (detached) or the lone child (non-detached).\n const target = opts.detachedGroup ? -pid : pid\n try {\n process.kill(target, \"SIGTERM\")\n } catch {\n // ESRCH — already gone.\n }\n const t = setTimeout(() => {\n // For a lone (non-detached) child, skip escalation once it has exited\n // — its positive PID could have been recycled. For a process GROUP the\n // leader's exit does NOT mean the group is empty (a SIGTERM-ignoring\n // grandchild may survive), and the group id is only reused once the\n // group is fully gone, so always attempt the group SIGKILL (ESRCH when\n // already empty is the success case).\n if (\n !opts.detachedGroup &&\n (child.exitCode !== null || child.signalCode !== null)\n ) {\n return\n }\n try {\n process.kill(target, \"SIGKILL\")\n } catch {\n // Already dead.\n }\n }, graceMs)\n t.unref?.()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,aAAa,OAAgD;CAC3E,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,IAAI,MAAM,KAAK,CAAC,CAAC,YAAY;CACnC,IAAI,MAAM,OAAO,MAAM,UAAU,MAAM,SAAS,MAAM,MAAM,OAAO;CACnE,IAAI,MAAM,OAAO,MAAM,WAAW,MAAM,QAAQ,MAAM,SAAS,MAAM,IACnE,OAAO;AAGX;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,OAA+C;CACzE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,MAAM,MAAM,KAAK;CACvB,IAAI,QAAQ,IAAI,OAAO,KAAA;CACvB,MAAM,IAAI,OAAO,GAAG;CACpB,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,KAA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AI,CAAC,KAAK;CACV,IAAI;EACF,IAAI,OACF,wBAAwB,GAAG;OAI3B,QAAQ,KAAK,CAAC,KAAK,SAAS;CAEhC,QAAQ,CAER;AACF;;;;;;AAOA,SAAS,cAAsB;CAC7B,MAAM,OACJ,QAAQ,IAAI,cAAc,QAAQ,IAAI,UAAU;CAClD,OAAO,KAAK,KAAK,MAAM,YAAY,cAAc;AACnD;;;;;;;;;;;;;;;;;;;;;;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;CAoBA,iBAnB2B;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,7 +1,7 @@
|
|
|
1
|
-
import { t as PATHS } from "./paths-
|
|
2
|
-
import {
|
|
3
|
-
import { f as resolveSealedGate } from "./stop-gate-hook-
|
|
4
|
-
import { c as repoRoot, s as repoFingerprint } from "./stop-gate-policy
|
|
1
|
+
import { t as PATHS } from "./paths-CMxlQEfQ.js";
|
|
2
|
+
import { o as resolveExecutable } from "./exec-COUT4QsS.js";
|
|
3
|
+
import { f as resolveSealedGate } from "./stop-gate-hook-BUCxa5Kc.js";
|
|
4
|
+
import { c as repoRoot, s as repoFingerprint } from "./stop-gate-policy--bpyxxXU.js";
|
|
5
5
|
import { existsSync, promises } from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
@@ -606,7 +606,7 @@ async function discoverGateCommands(cwd, opts) {
|
|
|
606
606
|
if (files.length === 0) return null;
|
|
607
607
|
let result;
|
|
608
608
|
try {
|
|
609
|
-
const { runWorkerAgent } = await import("./engine-
|
|
609
|
+
const { runWorkerAgent } = await import("./engine-b9XaKLp0.js");
|
|
610
610
|
result = await runWorkerAgent({
|
|
611
611
|
mode: "explore",
|
|
612
612
|
workspace: root,
|
|
@@ -632,4 +632,4 @@ async function discoverGateCommands(cwd, opts) {
|
|
|
632
632
|
//#endregion
|
|
633
633
|
export { checksForDescriptor as a, writeDiscoveredGate as i, readDiscoveredGate as n, descriptorHash as o, sourcesHash as r, parseGateDescriptor as s, discoverGateCommands as t };
|
|
634
634
|
|
|
635
|
-
//# sourceMappingURL=gate-discovery-
|
|
635
|
+
//# sourceMappingURL=gate-discovery-CPk6Z8yc.js.map
|