github-router 0.3.381 → 0.3.383
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/ado-tools-Ddv910Zl.js +1 -0
- package/dist/{aic-ledger-6GKI28nY.js → aic-ledger-Bz87EuHl.js} +3 -3
- package/dist/{aic-ledger-6GKI28nY.js.map → aic-ledger-Bz87EuHl.js.map} +1 -1
- package/dist/{aic-statusline-settings-wLL1l_Z6.js → aic-statusline-settings-dkVZbpRL.js} +2 -2
- package/dist/{aic-statusline-settings-wLL1l_Z6.js.map → aic-statusline-settings-dkVZbpRL.js.map} +1 -1
- package/dist/{attribution-settings-BEwSkdhK.js → attribution-settings-BcPiSoZe.js} +27 -30
- package/dist/{attribution-settings-BEwSkdhK.js.map → attribution-settings-BcPiSoZe.js.map} +1 -1
- package/dist/{auth-5TKcQbbH.js → auth-D9eTY_W6.js} +3 -3
- package/dist/{auth-5TKcQbbH.js.map → auth-D9eTY_W6.js.map} +1 -1
- package/dist/bin.js +21 -4
- package/dist/bin.js.map +1 -1
- package/dist/bluebird-client-CLXs7q-X.js +1 -0
- package/dist/{bluebird-client-BasIdv5J.js → bluebird-client-bykMZyn1.js} +2 -2
- package/dist/{bluebird-client-BasIdv5J.js.map → bluebird-client-bykMZyn1.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-DM39fdel.js → check-usage-BBaD35u4.js} +4 -4
- package/dist/{check-usage-DM39fdel.js.map → check-usage-BBaD35u4.js.map} +1 -1
- package/dist/{claude-CkrhHkPQ.js → claude-DOKuv2zZ.js} +29 -29
- package/dist/{claude-CkrhHkPQ.js.map → claude-DOKuv2zZ.js.map} +1 -1
- package/dist/{claude-md-injection-DNMDcw1W.js → claude-md-injection-BadtN0-I.js} +17 -8
- package/dist/claude-md-injection-BadtN0-I.js.map +1 -0
- package/dist/{codex-50GzveCD.js → codex-Dw_eBfXW.js} +9 -9
- package/dist/{codex-50GzveCD.js.map → codex-Dw_eBfXW.js.map} +1 -1
- package/dist/{copilot-discount-DM98PuAF.js → copilot-discount-BSDefQRW.js} +2 -2
- package/dist/{copilot-discount-DM98PuAF.js.map → copilot-discount-BSDefQRW.js.map} +1 -1
- package/dist/{debug-Df0Kuzi3.js → debug-B8eRYH-c.js} +2 -2
- package/dist/{debug-Df0Kuzi3.js.map → debug-B8eRYH-c.js.map} +1 -1
- package/dist/engine-DPtLOUuj.js +1 -0
- package/dist/{exec-BC0MAnoA.js → exec-oCtz_dXO.js} +22 -5
- package/dist/exec-oCtz_dXO.js.map +1 -0
- package/dist/{gate-discovery-2ILpM2fi.js → gate-discovery-DE_KTX2p.js} +6 -6
- package/dist/{gate-discovery-2ILpM2fi.js.map → gate-discovery-DE_KTX2p.js.map} +1 -1
- package/dist/{get-copilot-usage-BZ6t2hFZ.js → get-copilot-usage-Dh9u7WeP.js} +2 -2
- package/dist/{get-copilot-usage-BZ6t2hFZ.js.map → get-copilot-usage-Dh9u7WeP.js.map} +1 -1
- package/dist/hooks.mjs +21 -4
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-DsK6VFs8.js → index-cmd-C4womtOS.js} +5 -5
- package/dist/{index-cmd-DsK6VFs8.js.map → index-cmd-C4womtOS.js.map} +1 -1
- package/dist/{internal-aic-status-CUZ7-trf.js → internal-aic-status-DSO2sR5u.js} +4 -4
- package/dist/{internal-aic-status-CUZ7-trf.js.map → internal-aic-status-DSO2sR5u.js.map} +1 -1
- package/dist/{internal-artifact-open-DRBg1PpV.js → internal-artifact-open-dlgqWieq.js} +2 -2
- package/dist/{internal-artifact-open-DRBg1PpV.js.map → internal-artifact-open-dlgqWieq.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js → internal-fast-dispatch-guard-5nCNht5y.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-ZeS9u0A3.js.map → internal-fast-dispatch-guard-5nCNht5y.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-D6-Ees_6.js → internal-fast-dispatch-guard-DHm96Bj_.js} +1 -1
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js → internal-first-mate-guard-Bb9Stjy-.js} +3 -3
- package/dist/{internal-first-mate-guard-DsEEsLKJ.js.map → internal-first-mate-guard-Bb9Stjy-.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BijeVpi9.js → internal-first-mate-guard-D6HMd9Iz.js} +1 -1
- package/dist/{internal-max-dispatch-guard-4RLca1i5.js → internal-max-dispatch-guard-C8kq4WNV.js} +3 -3
- package/dist/{internal-max-dispatch-guard-4RLca1i5.js.map → internal-max-dispatch-guard-C8kq4WNV.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-DeEfWqfP.js → internal-max-dispatch-guard-CI17mrDJ.js} +1 -1
- package/dist/{internal-plan-review-bzqGNdtw.js → internal-plan-review-Bdga9wVP.js} +3 -3
- package/dist/{internal-plan-review-bzqGNdtw.js.map → internal-plan-review-Bdga9wVP.js.map} +1 -1
- package/dist/{internal-prompt-submit-ZBhH-SQ1.js → internal-prompt-submit-DKlHlcvK.js} +2 -2
- package/dist/{internal-prompt-submit-BZ2-CExM.js → internal-prompt-submit-Daswp8ro.js} +5 -5
- package/dist/{internal-prompt-submit-BZ2-CExM.js.map → internal-prompt-submit-Daswp8ro.js.map} +1 -1
- package/dist/{internal-rebrief-BIWbN7Sr.js → internal-rebrief-D8O1J-_J.js} +5 -5
- package/dist/{internal-rebrief-BIWbN7Sr.js.map → internal-rebrief-D8O1J-_J.js.map} +1 -1
- package/dist/{internal-session-bind-BL6hFRLO.js → internal-session-bind-0hQFrcWu.js} +2 -2
- package/dist/{internal-session-bind-BL6hFRLO.js.map → internal-session-bind-0hQFrcWu.js.map} +1 -1
- package/dist/{internal-stop-hook-cDF1MuJZ.js → internal-stop-hook-C3lLh-HY.js} +6 -6
- package/dist/{internal-stop-hook-cDF1MuJZ.js.map → internal-stop-hook-C3lLh-HY.js.map} +1 -1
- package/dist/{internal-stop-review-y8zjpK_3.js → internal-stop-review-Bnmzcqx5.js} +2 -2
- package/dist/{internal-stop-review-y8zjpK_3.js.map → internal-stop-review-Bnmzcqx5.js.map} +1 -1
- package/dist/{internal-worker-guard-DdyYBZR0.js → internal-worker-guard-LcPxDlbx.js} +2 -2
- package/dist/{internal-worker-guard-DdyYBZR0.js.map → internal-worker-guard-LcPxDlbx.js.map} +1 -1
- package/dist/{internal-workspace-header-BMKbO8yX.js → internal-workspace-header-BH53hBXO.js} +2 -2
- package/dist/{internal-workspace-header-BMKbO8yX.js.map → internal-workspace-header-BH53hBXO.js.map} +1 -1
- package/dist/{lifecycle-COZhARmE.js → lifecycle-BmoqtVj3.js} +2 -2
- package/dist/{lifecycle-COZhARmE.js.map → lifecycle-BmoqtVj3.js.map} +1 -1
- package/dist/lifecycle-CcNNfKbr.js +1 -0
- package/dist/lifecycle-CrImfxCd.js +1 -0
- package/dist/{lifecycle-BlC_kzNt.js → lifecycle-CwxOsp-U.js} +3 -3
- package/dist/{lifecycle-BlC_kzNt.js.map → lifecycle-CwxOsp-U.js.map} +1 -1
- package/dist/main.js +25 -25
- package/dist/{max-profile-contract-DbHwiLTx.js → max-profile-contract-CEn8hKb3.js} +60 -60
- package/dist/{max-profile-contract-DbHwiLTx.js.map → max-profile-contract-CEn8hKb3.js.map} +1 -1
- package/dist/{mcp-workspace-header-Bpa4BId8.js → mcp-workspace-header-lb7GV78v.js} +2 -2
- package/dist/{mcp-workspace-header-Bpa4BId8.js.map → mcp-workspace-header-lb7GV78v.js.map} +1 -1
- package/dist/{models-BDV-YLf2.js → models-BTCnhBCQ.js} +3 -3
- package/dist/{models-BDV-YLf2.js.map → models-BTCnhBCQ.js.map} +1 -1
- package/dist/{optional-DGAeyguL.js → optional-LUQJI6Vx.js} +216 -16
- package/dist/optional-LUQJI6Vx.js.map +1 -0
- package/dist/{orchestration-Bto5Nc1Y.js → orchestration-C_hyBL90.js} +3 -3
- package/dist/{orchestration-Bto5Nc1Y.js.map → orchestration-C_hyBL90.js.map} +1 -1
- package/dist/origin-9bOjyzvK.js +1 -0
- package/dist/{origin-BXtpcKP9.js → origin-B6GChVyp.js} +2 -2
- package/dist/{origin-BXtpcKP9.js.map → origin-B6GChVyp.js.map} +1 -1
- package/dist/{paths-DeFmYJhO.js → paths-CVXqt2tC.js} +3 -3
- package/dist/{paths-DeFmYJhO.js.map → paths-CVXqt2tC.js.map} +1 -1
- package/dist/paths-JIusmD6L.js +1 -0
- package/dist/{peer-mcp-personas-Dny0r5Am.js → peer-mcp-personas-Dgog_ZJ8.js} +54 -54
- package/dist/{peer-mcp-personas-Dny0r5Am.js.map → peer-mcp-personas-Dgog_ZJ8.js.map} +1 -1
- package/dist/{pi-DVud9eQn.js → pi-BZhnf1kx.js} +95 -35
- package/dist/pi-BZhnf1kx.js.map +1 -0
- package/dist/{pi-version-check-BeBB0Ny9.js → pi-version-check-BRt9XFLj.js} +4 -4
- package/dist/{pi-version-check-BeBB0Ny9.js.map → pi-version-check-BRt9XFLj.js.map} +1 -1
- package/dist/pi-version-check-SH1X9u4H.js +1 -0
- package/dist/{plan-review-hook-D_yyjOgO.js → plan-review-hook-Dx3suYmK.js} +4 -4
- package/dist/{plan-review-hook-D_yyjOgO.js.map → plan-review-hook-Dx3suYmK.js.map} +1 -1
- package/dist/{provision-BWtuDq_v.js → provision-A1YSravb.js} +6 -6
- package/dist/{provision-BWtuDq_v.js.map → provision-A1YSravb.js.map} +1 -1
- package/dist/{rerank-cross-encoder-BhjImuwG.js → rerank-cross-encoder-uqRu-LOe.js} +2 -2
- package/dist/{rerank-cross-encoder-BhjImuwG.js.map → rerank-cross-encoder-uqRu-LOe.js.map} +1 -1
- package/dist/{self-invocation-Dnq4iVD6.js → self-invocation-CayD3y72.js} +2 -2
- package/dist/{self-invocation-Dnq4iVD6.js.map → self-invocation-CayD3y72.js.map} +1 -1
- package/dist/{serve-B8Igr9Q0.js → serve-Cv3S3PFR.js} +17 -17
- package/dist/{serve-B8Igr9Q0.js.map → serve-Cv3S3PFR.js.map} +1 -1
- package/dist/{server-setup-byIhjgOb.js → server-setup--CYeBD-Z.js} +14 -14
- package/dist/{server-setup-byIhjgOb.js.map → server-setup--CYeBD-Z.js.map} +1 -1
- package/dist/{service-backend-BdhWVRSz.js → service-backend-EgwiO_K-.js} +6 -6
- package/dist/{service-backend-BdhWVRSz.js.map → service-backend-EgwiO_K-.js.map} +1 -1
- package/dist/{start-7CiQIl0r.js → start-CA0JsO56.js} +5 -5
- package/dist/{start-7CiQIl0r.js.map → start-CA0JsO56.js.map} +1 -1
- package/dist/{static-context-pack-BKFelEbM.js → static-context-pack-BIru_SKh.js} +142 -142
- package/dist/{static-context-pack-BKFelEbM.js.map → static-context-pack-BIru_SKh.js.map} +1 -1
- package/dist/{stop-gate-hook-DBOj0TqL.js → stop-gate-hook-Ba_RvZAj.js} +4 -4
- package/dist/{stop-gate-hook-DBOj0TqL.js.map → stop-gate-hook-Ba_RvZAj.js.map} +1 -1
- package/dist/{stop-gate-policy-Bp2wGh_W.js → stop-gate-policy-gW0a0hds.js} +3 -3
- package/dist/{stop-gate-policy-Bp2wGh_W.js.map → stop-gate-policy-gW0a0hds.js.map} +1 -1
- package/dist/{token-Ygd7D32L.js → token-BCzbNu8O.js} +3 -3
- package/dist/{token-Ygd7D32L.js.map → token-BCzbNu8O.js.map} +1 -1
- package/dist/{token-CKPOBdO0.js → token-CxKcs3I_.js} +2 -2
- package/dist/{token-CKPOBdO0.js.map → token-CxKcs3I_.js.map} +1 -1
- package/dist/{update-T1L7yFon.js → update-CM1yUCJR.js} +4 -4
- package/dist/{update-T1L7yFon.js.map → update-CM1yUCJR.js.map} +1 -1
- package/dist/update-Cpg-tbJG.js +1 -0
- package/dist/{update-fEgWTrIx.js → update-ZqCRVU0a.js} +4 -4
- package/dist/{update-fEgWTrIx.js.map → update-ZqCRVU0a.js.map} +1 -1
- package/dist/{worker-dispatch-DBWKTMda.js → worker-dispatch-DHZAfPO2.js} +2 -2
- package/dist/{worker-dispatch-DBWKTMda.js.map → worker-dispatch-DHZAfPO2.js.map} +1 -1
- package/dist/{workiq-D5b7xlbr.js → workiq-CRBVCUA4.js} +2 -2
- package/dist/{workiq-D5b7xlbr.js.map → workiq-CRBVCUA4.js.map} +1 -1
- package/dist/{workiq-tools-DdiQ2DOW.js → workiq-tools-BsoHfdYi.js} +1 -1
- package/package.json +1 -1
- package/dist/ado-tools-CsfbnY8x.js +0 -1
- package/dist/bluebird-client-BvoMTmEv.js +0 -1
- package/dist/claude-md-injection-DNMDcw1W.js.map +0 -1
- package/dist/engine-B6la_uIW.js +0 -1
- package/dist/exec-BC0MAnoA.js.map +0 -1
- package/dist/lifecycle-BOjgq9_l.js +0 -1
- package/dist/lifecycle-NQvr4flt.js +0 -1
- package/dist/optional-DGAeyguL.js.map +0 -1
- package/dist/origin-DbFUCiGp.js +0 -1
- package/dist/paths-CquOjytP.js +0 -1
- package/dist/pi-DVud9eQn.js.map +0 -1
- package/dist/pi-version-check-D5RvdLsG.js +0 -1
- package/dist/update-CB21YRKz.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as writeFileAtomic, n as readFileWithRetry } from "./atomic-file-Dif1kLKM.js";
|
|
2
|
-
import { a as parseBoolEnv, c as runCommandCapture, s as resolveExecutable } from "./exec-
|
|
2
|
+
import { a as parseBoolEnv, c as runCommandCapture, s as resolveExecutable } from "./exec-oCtz_dXO.js";
|
|
3
3
|
import { t as buildNpmEnv } from "./npm-env-H60tX76c.js";
|
|
4
4
|
import { t as reportManagedDiagnostic } from "./diagnostics-cXjCT_JQ.js";
|
|
5
5
|
import { g as randomHex, l as isTransientName, m as optionalRoot, r as VERSION_RE, u as isVersionName } from "./paths-DK_b2ihK.js";
|
|
@@ -150,6 +150,8 @@ function installedOptionalTarget(pkg, version) {
|
|
|
150
150
|
const target = optionalTarget(pkg, version);
|
|
151
151
|
return completeAt(target, pkg) ? payloadDir(target, pkg) : null;
|
|
152
152
|
}
|
|
153
|
+
/** Current `OptionalState` schema; see the field's doc block. */
|
|
154
|
+
const OPTIONAL_STATE_SCHEMA = 2;
|
|
153
155
|
const BACKOFF_HOURS = [
|
|
154
156
|
1,
|
|
155
157
|
6,
|
|
@@ -164,16 +166,81 @@ async function readState() {
|
|
|
164
166
|
try {
|
|
165
167
|
const raw = await readFileWithRetry(statePath(), { retryMissing: false });
|
|
166
168
|
const parsed = JSON.parse(raw);
|
|
167
|
-
|
|
169
|
+
if (typeof parsed !== "object" || parsed === null) return {};
|
|
170
|
+
return migrateState(parsed);
|
|
168
171
|
} catch {
|
|
169
172
|
return {};
|
|
170
173
|
}
|
|
171
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Retire a ladder this build did not write, keeping everything still valid.
|
|
177
|
+
*
|
|
178
|
+
* `consecutiveFailures` + `nextAttemptAt` are a claim about THIS build's ability
|
|
179
|
+
* to install the package. When an older build failed for a reason the build
|
|
180
|
+
* itself caused — the `^`-range quoting bug made `npm view` reject every spec
|
|
181
|
+
* before a byte was downloaded — that claim is wrong after the fix, and the only
|
|
182
|
+
* thing the inherited ladder does is keep the payload uninstalled for at least
|
|
183
|
+
* an hour per startup. So a schema this build does not recognise drops exactly
|
|
184
|
+
* those fields (plus the error text that described the old failure);
|
|
185
|
+
* `lastAttemptAt`, `lastSuccessAt` and `version` are kept because they describe
|
|
186
|
+
* what is on disk, not why an attempt failed.
|
|
187
|
+
*
|
|
188
|
+
* Unrecognised covers BOTH directions, and that is deliberate. A newer schema
|
|
189
|
+
* means a newer build invented these numbers for semantics this build cannot
|
|
190
|
+
* read (a downgrade, a pinned launch dir, a rollback); guessing would either
|
|
191
|
+
* suppress a payload for hours or re-attempt a download every launch. Dropping
|
|
192
|
+
* the ladder errs toward one early attempt, which for an optional payload is the
|
|
193
|
+
* cheap mistake. The paired rule is in `patchState`: every write stamps exactly
|
|
194
|
+
* `OPTIONAL_STATE_SCHEMA`, because the ladder next to the stamp was produced by
|
|
195
|
+
* this build's semantics — keeping a newer number would mislabel it.
|
|
196
|
+
*
|
|
197
|
+
* Pure and exercised through `ensureOptionalPackage`, the only caller: the state
|
|
198
|
+
* file is the only input, and dropping `consecutiveFailures` is what
|
|
199
|
+
* `mayAttemptNow` already treats as "not a backoff".
|
|
200
|
+
*/
|
|
201
|
+
function migrateState(state) {
|
|
202
|
+
if ((state.schemaVersion ?? 1) === OPTIONAL_STATE_SCHEMA) return state;
|
|
203
|
+
const packages = {};
|
|
204
|
+
for (const [pkg, entry] of Object.entries(state.packages ?? {})) {
|
|
205
|
+
if (!entry || typeof entry !== "object") continue;
|
|
206
|
+
const kept = {};
|
|
207
|
+
if (entry.lastAttemptAt !== void 0) kept.lastAttemptAt = entry.lastAttemptAt;
|
|
208
|
+
if (entry.lastSuccessAt !== void 0) kept.lastSuccessAt = entry.lastSuccessAt;
|
|
209
|
+
if (entry.version !== void 0) kept.version = entry.version;
|
|
210
|
+
packages[pkg] = kept;
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
schemaVersion: OPTIONAL_STATE_SCHEMA,
|
|
214
|
+
packages
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Persist a schema migration the moment an attempt starts.
|
|
219
|
+
*
|
|
220
|
+
* `readState` migrates in memory, which alone is enough to let an attempt through
|
|
221
|
+
* — and that is the load-bearing part. This write is for the two paths that never
|
|
222
|
+
* patch state afterwards: a payload already installed, and `npm` missing. Left
|
|
223
|
+
* alone, those machines would carry the old ladder in the file forever, so a human
|
|
224
|
+
* reading `install-state.json` (or a support thread) would keep seeing a failure
|
|
225
|
+
* that this build no longer produces.
|
|
226
|
+
*
|
|
227
|
+
* Not load-bearing also means not worth losing a concurrent update over: the write
|
|
228
|
+
* is built from the newest read, and `migrateState` is idempotent.
|
|
229
|
+
*/
|
|
230
|
+
async function persistMigratedState() {
|
|
231
|
+
try {
|
|
232
|
+
const parsed = JSON.parse(await readFileWithRetry(statePath(), { retryMissing: false }));
|
|
233
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
234
|
+
if ((parsed.schemaVersion ?? 1) === OPTIONAL_STATE_SCHEMA) return;
|
|
235
|
+
await writeFileAtomic(statePath(), `${JSON.stringify(migrateState(parsed), null, 2)}\n`, { mode: 420 });
|
|
236
|
+
} catch {}
|
|
237
|
+
}
|
|
172
238
|
async function patchState(pkg, patch) {
|
|
173
239
|
try {
|
|
174
240
|
const state = await readState();
|
|
175
241
|
const next = {
|
|
176
242
|
...state,
|
|
243
|
+
schemaVersion: OPTIONAL_STATE_SCHEMA,
|
|
177
244
|
packages: {
|
|
178
245
|
...state.packages ?? {},
|
|
179
246
|
[pkg]: {
|
|
@@ -194,6 +261,31 @@ function nextAttemptAtFor(failures) {
|
|
|
194
261
|
return new Date(Date.now() + (BACKOFF_HOURS[index] ?? 24) * 36e5).toISOString();
|
|
195
262
|
}
|
|
196
263
|
/**
|
|
264
|
+
* When the next attempt is due, and how to skip the wait.
|
|
265
|
+
*
|
|
266
|
+
* The ladder exists so a broken registry or an offline laptop does not spawn npm
|
|
267
|
+
* on every launch, and it climbs 1h -> 6h -> 24h. That is the right default, but a
|
|
268
|
+
* message that only says "backing off" hides two things the reader needs: WHEN it
|
|
269
|
+
* will try again, and that `--force` skips the wait entirely. Without them a user
|
|
270
|
+
* whose payload is missing for a day has no way to tell a broken install from a
|
|
271
|
+
* deliberate cooldown, and no way to test a fix.
|
|
272
|
+
*/
|
|
273
|
+
function backoffHint(failures) {
|
|
274
|
+
const at = Date.parse(nextAttemptAtFor(failures));
|
|
275
|
+
return `next attempt ${new Date(at).toISOString().replace(".000Z", "Z")}, --force retries now`;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* The same hint for the guard's early return, derived from what is on disk.
|
|
279
|
+
*
|
|
280
|
+
* Nothing from the environment is interpolated here, only a timestamp this module
|
|
281
|
+
* itself wrote.
|
|
282
|
+
*/
|
|
283
|
+
async function backoffDetail(pkg) {
|
|
284
|
+
const entry = (await readState()).packages?.[pkg];
|
|
285
|
+
const at = entry?.nextAttemptAt ? Date.parse(entry.nextAttemptAt) : NaN;
|
|
286
|
+
return `backing off after a failed ${pkg} install (next attempt ${Number.isNaN(at) ? "later" : new Date(at).toISOString().replace(".000Z", "Z")}); --force retries now`;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
197
289
|
* Whether an attempt may start — a RESERVATION is not a backoff.
|
|
198
290
|
*
|
|
199
291
|
* `nextAttemptAt` is written before every attempt so two processes cannot both
|
|
@@ -222,9 +314,10 @@ async function ensureOptionalPackage(pkg, opts = {}) {
|
|
|
222
314
|
dir: null,
|
|
223
315
|
detail: "GH_ROUTER_NO_OPTIONAL_INSTALL is set"
|
|
224
316
|
};
|
|
317
|
+
await persistMigratedState();
|
|
225
318
|
if (!opts.force && !await mayAttemptNow(pkg)) return {
|
|
226
319
|
dir: null,
|
|
227
|
-
detail:
|
|
320
|
+
detail: await backoffDetail(pkg)
|
|
228
321
|
};
|
|
229
322
|
const npmPath = resolveExecutable("npm");
|
|
230
323
|
if (!npmPath) {
|
|
@@ -234,19 +327,26 @@ async function ensureOptionalPackage(pkg, opts = {}) {
|
|
|
234
327
|
detail: "npm is not on PATH"
|
|
235
328
|
};
|
|
236
329
|
}
|
|
237
|
-
const
|
|
330
|
+
const resolved = await resolveOptionalVersion(pkg, opts.registry);
|
|
331
|
+
const version = resolved.version;
|
|
238
332
|
const existing = version ? installedOptionalTarget(pkg, version) : installedOptional(pkg);
|
|
239
|
-
if (existing && !opts.force)
|
|
333
|
+
if (existing && !opts.force) {
|
|
334
|
+
if (!version && resolved.detail) reportManagedDiagnostic("debug", `optional: ${pkg} is installed but its version could not be resolved: ${resolved.detail}`);
|
|
335
|
+
return { dir: existing };
|
|
336
|
+
}
|
|
240
337
|
if (!version) {
|
|
338
|
+
const failures = ((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0) + 1;
|
|
339
|
+
const detail = resolved.detail ?? `could not resolve a version for ${pkg}`;
|
|
241
340
|
await patchState(pkg, {
|
|
242
341
|
lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
243
|
-
consecutiveFailures:
|
|
244
|
-
nextAttemptAt: nextAttemptAtFor(
|
|
245
|
-
lastError:
|
|
342
|
+
consecutiveFailures: failures,
|
|
343
|
+
nextAttemptAt: nextAttemptAtFor(failures),
|
|
344
|
+
lastError: detail,
|
|
345
|
+
...existing ? {} : { version: void 0 }
|
|
246
346
|
});
|
|
247
347
|
return {
|
|
248
348
|
dir: null,
|
|
249
|
-
detail:
|
|
349
|
+
detail: `${detail} (${backoffHint(failures)})`
|
|
250
350
|
};
|
|
251
351
|
}
|
|
252
352
|
const target = optionalTarget(pkg, version);
|
|
@@ -393,12 +493,24 @@ async function harvestProvenance(prefix) {
|
|
|
393
493
|
} catch {}
|
|
394
494
|
return out;
|
|
395
495
|
}
|
|
396
|
-
/**
|
|
496
|
+
/**
|
|
497
|
+
* Newest published version of `pkg`, or a `detail` explaining why there is none.
|
|
498
|
+
*
|
|
499
|
+
* The `detail` is not cosmetic. This resolution step is the one that fails for a
|
|
500
|
+
* reason the user cannot see: a registry that cannot answer, or — the case that
|
|
501
|
+
* shipped — an argv that reached npm corrupted, so `npm view` exited non-zero
|
|
502
|
+
* and said `EINVALIDTAGNAME` while the caller reported a generic "could not
|
|
503
|
+
* resolve a version". Carrying npm's own error code and summary through turns a
|
|
504
|
+
* silent, unactionable backoff into a diagnosis.
|
|
505
|
+
*/
|
|
397
506
|
async function resolveOptionalVersion(pkg, registry) {
|
|
398
507
|
const pinned = subjectFor(pkg).version;
|
|
399
|
-
if (pinned) return pinned;
|
|
508
|
+
if (pinned) return { version: pinned };
|
|
400
509
|
const npmPath = resolveExecutable("npm");
|
|
401
|
-
if (!npmPath) return
|
|
510
|
+
if (!npmPath) return {
|
|
511
|
+
version: null,
|
|
512
|
+
detail: "npm is not on PATH"
|
|
513
|
+
};
|
|
402
514
|
const subject = subjectFor(pkg);
|
|
403
515
|
const spec = subject.range ? `${subject.packageName}@${subject.range}` : subject.packageName;
|
|
404
516
|
try {
|
|
@@ -411,15 +523,103 @@ async function resolveOptionalVersion(pkg, registry) {
|
|
|
411
523
|
"--silent"
|
|
412
524
|
];
|
|
413
525
|
if (registry) args.push(`--registry=${registry}`);
|
|
414
|
-
const { stdout, code } = await runCommandCapture(args, { timeoutMs: 8e3 });
|
|
415
|
-
if (code !== 0)
|
|
526
|
+
const { stdout, stderr, code } = await runCommandCapture(args, { timeoutMs: 8e3 });
|
|
527
|
+
if (code !== 0) {
|
|
528
|
+
const why = npmFailureDetail(stdout, stderr);
|
|
529
|
+
return {
|
|
530
|
+
version: null,
|
|
531
|
+
detail: `npm view ${spec} ${why ? `failed (exit ${code}): ${why}` : `failed (exit ${code}) with no message`}`
|
|
532
|
+
};
|
|
533
|
+
}
|
|
416
534
|
const value = lastVersionFromJson(stdout);
|
|
417
|
-
|
|
535
|
+
if (value && VERSION_RE.test(value)) return { version: value };
|
|
536
|
+
return {
|
|
537
|
+
version: null,
|
|
538
|
+
detail: `npm view ${spec} returned ${sanitizeDiagnostic(JSON.stringify(stdout.trim().slice(0, 120)))}`
|
|
539
|
+
};
|
|
540
|
+
} catch (err) {
|
|
541
|
+
return {
|
|
542
|
+
version: null,
|
|
543
|
+
detail: `npm view ${spec} failed: ${sanitizeDiagnostic(err instanceof Error ? err.message : String(err))}`
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Why `npm view` failed, in one readable line.
|
|
549
|
+
*
|
|
550
|
+
* Under `--json` npm does NOT put that sentence on stderr. It writes a JSON error
|
|
551
|
+
* ENVELOPE to stdout and leaves stderr empty:
|
|
552
|
+
*
|
|
553
|
+
* {"error":{"code":"EINVALIDTAGNAME","summary":"Invalid tag name \"^^0.1.13\" …"}}
|
|
554
|
+
*
|
|
555
|
+
* so reading the first line of either stream yields `"{"` — measured, for the very
|
|
556
|
+
* failure this branch exists to explain. Parsing the envelope is what makes the
|
|
557
|
+
* message carry `EINVALIDTAGNAME` and the bad spec instead of a brace; the
|
|
558
|
+
* line-based read stays as the fallback for a non-JSON failure (a crashed npm, a
|
|
559
|
+
* proxy error page, a spawn-level message on stderr).
|
|
560
|
+
*/
|
|
561
|
+
function npmFailureDetail(stdout, stderr) {
|
|
562
|
+
for (const stream of [stdout, stderr]) {
|
|
563
|
+
const error = parseJson(stream)?.error;
|
|
564
|
+
if (error && typeof error === "object") {
|
|
565
|
+
const { code, summary } = error;
|
|
566
|
+
const parts = [code, summary].filter((part) => typeof part === "string");
|
|
567
|
+
if (parts.length > 0) return sanitizeDiagnostic(parts.join(" "));
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return sanitizeDiagnostic(firstLine(stderr || stdout));
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Make a third-party diagnostic safe to store and print.
|
|
574
|
+
*
|
|
575
|
+
* `lastError` is written to `optional/install-state.json` (mode 0644) and echoed
|
|
576
|
+
* to the terminal by `update`. The text comes from npm, which comes from whatever
|
|
577
|
+
* registry answered, so it is untrusted input, and there are three concrete shapes
|
|
578
|
+
* it can take:
|
|
579
|
+
*
|
|
580
|
+
* - **ANSI/control characters.** A registry behind a corporate proxy can answer
|
|
581
|
+
* with a coloured or framed error page, and an escape sequence replayed into a
|
|
582
|
+
* terminal can rewrite the line the user is reading. Whole sequences are
|
|
583
|
+
* removed, then any remaining control byte and any zero-width/bidi override:
|
|
584
|
+
* nothing here is worth preserving, and the `npm view --json` output that
|
|
585
|
+
* matters is parsed before it reaches this function.
|
|
586
|
+
* - **A URL with credentials.** `resolveOptionalVersion` passes
|
|
587
|
+
* `--registry=<url>`, and npm echoes the request URL on 401/404 — so a
|
|
588
|
+
* `https://user:token@mirror` registry would land in a world-readable file and
|
|
589
|
+
* on the terminal. Userinfo is replaced wholesale rather than partly kept,
|
|
590
|
+
* because a redactor that preserves "the useful part" of a secret is one regex
|
|
591
|
+
* bug away from leaking it.
|
|
592
|
+
* - **Length.** A megabyte of proxy HTML does not belong in a state file.
|
|
593
|
+
*
|
|
594
|
+
* Deliberately local rather than `sanitizeTransportText` from `../upstream-retry`:
|
|
595
|
+
* that module imports `consola`, and this layer is documented as the one that must
|
|
596
|
+
* not (see `./paths`, `./diagnostics`), because it is reachable from the bin bundle
|
|
597
|
+
* and from request paths.
|
|
598
|
+
*/
|
|
599
|
+
function sanitizeDiagnostic(text) {
|
|
600
|
+
const flat = text.replace(/\u009b/g, "\x1B[").replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\|(?=\u001b)|$)/g, "").replace(/\u001b[[\]()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g, "").replace(/\u001b[\s\S]/g, "").replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g, "").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi, "$1[REDACTED]@");
|
|
601
|
+
return flat.length > 300 ? `${flat.slice(0, 300)}…` : flat;
|
|
602
|
+
}
|
|
603
|
+
/** `JSON.parse` that returns null instead of throwing on the non-JSON cases above. */
|
|
604
|
+
function parseJson(text) {
|
|
605
|
+
try {
|
|
606
|
+
return JSON.parse(text);
|
|
418
607
|
} catch {
|
|
419
608
|
return null;
|
|
420
609
|
}
|
|
421
610
|
}
|
|
422
611
|
/**
|
|
612
|
+
* First non-empty line of a diagnostic, trimmed.
|
|
613
|
+
*
|
|
614
|
+
* Both streams are candidates because npm's choice is not stable across versions
|
|
615
|
+
* and subcommands, and neither is guaranteed. Used only as the non-JSON fallback
|
|
616
|
+
* now — see `npmFailureDetail` for why the first line of `--json` output is not a
|
|
617
|
+
* diagnosis.
|
|
618
|
+
*/
|
|
619
|
+
function firstLine(text) {
|
|
620
|
+
return text.split(/\r?\n/).find((part) => part.trim().length > 0)?.trim() ?? "";
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
423
623
|
* The newest version in `npm view … --json` output, or null.
|
|
424
624
|
*
|
|
425
625
|
* The output is a bare `"1.2.3"` when the spec matches exactly one version and
|
|
@@ -583,4 +783,4 @@ function scheduleOptionalInstall(pkg, argv1 = process.argv[1]) {
|
|
|
583
783
|
}
|
|
584
784
|
export { optionalInstallDisabled as a, isOptionalPackage as i, ensureOptionalPackage as n, scheduleOptionalInstall as o, installedOptional as r, OPTIONAL_PACKAGES as t };
|
|
585
785
|
|
|
586
|
-
//# sourceMappingURL=optional-
|
|
786
|
+
//# sourceMappingURL=optional-LUQJI6Vx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"optional-LUQJI6Vx.js","names":["fs"],"sources":["../src/lib/managed-install/optional.ts"],"sourcesContent":["/**\n * On-demand install of the heavy optional payloads.\n *\n * `@huggingface/transformers` (~547 MB with its ONNX runtime) and\n * `tree-sitter-wasms` (~49 MB of grammars) are the entire difference between a\n * 66 MB install and a 586 MB one. The plan moves them to **optional** peers so\n * nobody pays for them at install time — which has one blunt consequence that\n * must be stated plainly: **optional peers are installed for nobody**, at any\n * depth, by npm and by bun alike (measured). So \"optional\" cannot mean \"the\n * usual install will bring it\"; it has to mean \"we install it the first time\n * something actually needs it\".\n *\n * Three rules shape this file:\n *\n * 1. **One copy per machine, shared across versions.** The payload lands in\n * `<APP_DIR>/optional/<pkg>@<version>/`, never inside a managed version dir:\n * those are per-version and GC keeps two, so an in-tree copy would be 1.1 GB\n * and would be re-fetched on every bump.\n * 2. **Failure is always allowed.** Reranking falls back to BM25F and structural\n * ranking to the regex heuristic; both already warn for exactly this case.\n * Nothing here may ever make a search or a chat request fail.\n * 3. **Off the hot path.** Resolution (is a usable copy present?) is a couple of\n * `stat`s against a bounded directory listing, and it is synchronous because\n * both consumers are. Installation is a separate, throttled, detached child;\n * the request that noticed the gap proceeds without it.\n *\n * Supply-chain posture matches the managed installer: exact version, scrubbed\n * npm env, `--ignore-scripts`, `--no-global`, provenance from the lockfile.\n */\n\nimport fs from \"node:fs/promises\"\nimport { existsSync, readdirSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { writeFileAtomic, readFileWithRetry } from \"../atomic-file\"\nimport { parseBoolEnv, resolveExecutable, runCommandCapture } from \"../exec\"\nimport { buildNpmEnv } from \"./npm-env\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport { VERSION_RE, isTransientName, isVersionName, optionalRoot, randomHex } from \"./paths\"\n\n/** The packages that may be installed on demand. */\nexport const OPTIONAL_PACKAGES = [\"@huggingface/transformers\", \"tree-sitter-wasms\"] as const\nexport type OptionalPackage = (typeof OPTIONAL_PACKAGES)[number]\n\n/**\n * Entry file that must exist for a copy to count as installed.\n *\n * A package directory alone is not enough: an interrupted `npm install` can\n * leave `node_modules/<pkg>` in place with its payload missing, and an\n * on-demand install is precisely the kind that gets interrupted (the user\n * quits, the machine sleeps). These are the exact files the two consumers load.\n */\nexport const OPTIONAL_REQUIRED_FILE: Readonly<Record<OptionalPackage, string>> = {\n \"@huggingface/transformers\": \"dist/transformers.node.mjs\",\n // The filename must be the one the package actually ships:\n // `tree-sitter-wasms@0.1.13/out/tree-sitter-typescript.wasm`. A wrong name\n // here is not a loud failure — the install SUCCEEDS, `completeAt` then refuses\n // the payload, structural ranking silently keeps using the regex fallback,\n // and the package state backs off for an hour pretending npm broke.\n \"tree-sitter-wasms\": \"out/tree-sitter-typescript.wasm\",\n}\n\n/**\n * The peer range each payload must satisfy, mirroring `package.json`.\n *\n * On-demand installation used to take whatever `npm view <pkg> version` said,\n * which is unbounded: the day transformers 5.x ships, every machine fetches a\n * major the router has never run — and `completeAt` refusing the payload turns\n * that into a one-hour backoff that hides the cause. Bounding the query\n * (`npm view <pkg>@<range> version`) makes npm do the range arithmetic, so the\n * answer is by construction compatible. `tests/optional-payload-manifest.test.ts`\n * asserts this table still matches `package.json#peerDependencies`.\n */\nexport const OPTIONAL_VERSION_RANGE: Readonly<Record<OptionalPackage, string>> = {\n \"@huggingface/transformers\": \"^4.3.2\",\n \"tree-sitter-wasms\": \"^0.1.13\",\n}\n\n/** `<pkg>` → the directory name used under `optional/` (`@scope/name` is unsafe). */\nfunction sanitized(pkg: string): string {\n return pkg.replace(\"/\", \"__\")\n}\n\n/**\n * Test seam: what a slot actually installs.\n *\n * The install mechanics (staging, verify, publish-by-rename, provenance, GC) are\n * identical for a 547 MB ONNX payload and for a 6 KB package with no scripts, but\n * only one of them can run in a test. Overriding via a seam keeps ONE code path\n * instead of a re-implementation in the test that could pass while production\n * breaks. Nothing in `src/` calls the setters.\n */\ninterface OptionalSubject {\n packageName: string\n requiredFile: string\n version: string | null\n /** Peer range to resolve within; the real table by default. */\n range: string | null\n}\nconst subjects = new Map<OptionalPackage, OptionalSubject>()\n\nfunction subjectFor(pkg: OptionalPackage): OptionalSubject {\n return (\n subjects.get(pkg) ?? {\n packageName: pkg,\n requiredFile: OPTIONAL_REQUIRED_FILE[pkg],\n version: null,\n range: OPTIONAL_VERSION_RANGE[pkg],\n }\n )\n}\n\n/** @internal — point one slot at a throwaway package. */\nexport function __setOptionalTestSubject(input: {\n pkg: OptionalPackage\n packageName: string\n requiredFile: string\n version?: string\n}): void {\n subjects.set(input.pkg, {\n packageName: input.packageName,\n requiredFile: input.requiredFile,\n version: input.version ?? null,\n // A test stand-in (`is-number`) has its own version, so bind it to itself\n // rather than to the real package's peer range.\n range: input.version ? input.version : null,\n })\n}\n\n/** @internal — restore the real subjects. */\nexport function __resetOptionalTestSubject(): void {\n subjects.clear()\n}\n\n/**\n * True when the user disabled on-demand payloads.\n *\n * Uses the shared `parseBoolEnv`, not a local `raw === \"1\" || raw === \"true\"`:\n * `GH_ROUTER_NO_OPTIONAL_INSTALL=TRUE` or `=yes` used to be unrecognised and\n * silently *enabled* a 547 MB download, which is the worst possible way for an\n * off switch to fail.\n */\nexport function optionalInstallDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_NO_OPTIONAL_INSTALL) === true\n}\n\n/** The `node_modules/<pkg>` directory inside an installed optional copy. */\nfunction payloadDir(target: string, pkg: OptionalPackage): string {\n return path.join(target, \"node_modules\", ...subjectFor(pkg).packageName.split(\"/\"))\n}\n\n/** Is `target` a complete payload? */\nfunction completeAt(target: string, pkg: OptionalPackage): boolean {\n const dir = payloadDir(target, pkg)\n return (\n existsSync(path.join(dir, \"package.json\"))\n && existsSync(path.join(dir, subjectFor(pkg).requiredFile))\n )\n}\n\n/**\n * A usable installed copy of `pkg`, preferring the NEWEST version present.\n *\n * Synchronous on purpose: `resolveGrammarRoot()` and the rerank loader are\n * called from synchronous contexts, and a promise here would force an `await`\n * onto a path that must stay cheap. The listing is small (one entry per\n * installed version, typically one).\n *\n * Returns the package directory (the thing a consumer imports from), not the\n * `optional/<pkg>@<ver>` prefix.\n */\nexport function installedOptional(pkg: OptionalPackage): string | null {\n const [newest] = completeTargets(pkg)\n return newest ? payloadDir(newest, pkg) : null\n}\n\n/**\n * Every COMPLETE `<root>/<pkg>@<version>` target dir, newest version first.\n *\n * Split out of `installedOptional` because two callers need the target dir\n * itself rather than the package dir inside it: the upgrade check (\"is the\n * version we just resolved already here?\") and the GC protection list (\"spare\n * the copy this process is using\").\n */\nfunction completeTargets(pkg: OptionalPackage): Array<string> {\n const root = optionalRoot()\n let names: Array<string>\n try {\n names = readdirSync(root)\n } catch {\n return []\n }\n const prefix = `${sanitized(pkg)}@`\n const candidates = names\n .filter((name) => name.startsWith(prefix) && !name.startsWith(\".\"))\n .map((name) => ({ name, version: name.slice(prefix.length) }))\n .filter((entry) => isVersionName(entry.version))\n // Newest first: a stale older copy must never shadow a fresh one.\n .sort((a, b) => compareVersions(b.version, a.version))\n\n const out: Array<string> = []\n for (const candidate of candidates) {\n const target = path.join(root, candidate.name)\n if (completeAt(target, pkg)) out.push(target)\n }\n return out\n}\n\n/** Where `pkg@version` would live. */\nexport function optionalTarget(pkg: OptionalPackage, version: string): string {\n return path.join(optionalRoot(), `${sanitized(pkg)}@${version}`)\n}\n\n/** `payloadDir` for exactly `pkg@version`, or null when that copy is not complete. */\nfunction installedOptionalTarget(pkg: OptionalPackage, version: string): string | null {\n const target = optionalTarget(pkg, version)\n return completeAt(target, pkg) ? payloadDir(target, pkg) : null\n}\n\n// ---------------------------------------------------------------------------\n// Backoff + GC state\n// ---------------------------------------------------------------------------\n\n/**\n * `optional/install-state.json`.\n *\n * Separate from `m/<kind>/install-state.json` because the lifecycles are\n * separate: pruning the managed tree must never reset (or inherit) a failing\n * optional install's ladder, and the optional ladder is per PACKAGE.\n */\ninterface OptionalState {\n /**\n * Schema of this file, so a poisoned ladder written by an older build can be\n * retired instead of waited out.\n *\n * Absent means 1 (the only schema that ever shipped without a number). Bump on\n * every change that makes an existing `consecutiveFailures`/`nextAttemptAt`\n * pair mean something different: a bug that failed the install for a reason\n * the user could not influence (the Windows `^`-range quoting bug in\n * `lib/exec.ts`) left every machine on a 1h -> 6h -> 24h ladder that no code\n * change can climb, because the recorded failure is re-read as a fresh one. A\n * reader that sees an older schema drops the ladder fields and treats the\n * package as having no recorded failure.\n */\n schemaVersion?: number\n packages?: Partial<\n Record<\n OptionalPackage,\n {\n lastAttemptAt?: string\n lastSuccessAt?: string\n consecutiveFailures?: number\n nextAttemptAt?: string\n lastError?: string\n version?: string\n }\n >\n >\n}\n\n/** Current `OptionalState` schema; see the field's doc block. */\nconst OPTIONAL_STATE_SCHEMA = 2\n\nconst BACKOFF_HOURS = [1, 6, 24] as const\nconst KEEP_OPTIONAL_VERSIONS = 2\nconst OPTIONAL_FLOOR_MS = 30 * 24 * 60 * 60_000\n\nfunction statePath(): string {\n return path.join(optionalRoot(), \"install-state.json\")\n}\n\nasync function readState(): Promise<OptionalState> {\n try {\n const raw = await readFileWithRetry(statePath(), { retryMissing: false })\n const parsed = JSON.parse(raw) as OptionalState\n if (typeof parsed !== \"object\" || parsed === null) return {}\n return migrateState(parsed)\n } catch {\n return {}\n }\n}\n\n/**\n * Retire a ladder this build did not write, keeping everything still valid.\n *\n * `consecutiveFailures` + `nextAttemptAt` are a claim about THIS build's ability\n * to install the package. When an older build failed for a reason the build\n * itself caused — the `^`-range quoting bug made `npm view` reject every spec\n * before a byte was downloaded — that claim is wrong after the fix, and the only\n * thing the inherited ladder does is keep the payload uninstalled for at least\n * an hour per startup. So a schema this build does not recognise drops exactly\n * those fields (plus the error text that described the old failure);\n * `lastAttemptAt`, `lastSuccessAt` and `version` are kept because they describe\n * what is on disk, not why an attempt failed.\n *\n * Unrecognised covers BOTH directions, and that is deliberate. A newer schema\n * means a newer build invented these numbers for semantics this build cannot\n * read (a downgrade, a pinned launch dir, a rollback); guessing would either\n * suppress a payload for hours or re-attempt a download every launch. Dropping\n * the ladder errs toward one early attempt, which for an optional payload is the\n * cheap mistake. The paired rule is in `patchState`: every write stamps exactly\n * `OPTIONAL_STATE_SCHEMA`, because the ladder next to the stamp was produced by\n * this build's semantics — keeping a newer number would mislabel it.\n *\n * Pure and exercised through `ensureOptionalPackage`, the only caller: the state\n * file is the only input, and dropping `consecutiveFailures` is what\n * `mayAttemptNow` already treats as \"not a backoff\".\n */\nfunction migrateState(state: OptionalState): OptionalState {\n if ((state.schemaVersion ?? 1) === OPTIONAL_STATE_SCHEMA) return state\n const packages: OptionalState[\"packages\"] = {}\n for (const [pkg, entry] of Object.entries(state.packages ?? {})) {\n if (!entry || typeof entry !== \"object\") continue\n // Rebuild rather than destructure-with-rest: `no-unused-vars` rejects the\n // `_failures`/`_next`/`_error` bindings an omit-by-rest would create, and this\n // also drops unknown keys from a hand-edited file.\n const kept: NonNullable<OptionalState[\"packages\"]>[OptionalPackage] = {}\n if (entry.lastAttemptAt !== undefined) kept.lastAttemptAt = entry.lastAttemptAt\n if (entry.lastSuccessAt !== undefined) kept.lastSuccessAt = entry.lastSuccessAt\n if (entry.version !== undefined) kept.version = entry.version\n packages[pkg as OptionalPackage] = kept\n }\n return { schemaVersion: OPTIONAL_STATE_SCHEMA, packages }\n}\n\n/**\n * Persist a schema migration the moment an attempt starts.\n *\n * `readState` migrates in memory, which alone is enough to let an attempt through\n * — and that is the load-bearing part. This write is for the two paths that never\n * patch state afterwards: a payload already installed, and `npm` missing. Left\n * alone, those machines would carry the old ladder in the file forever, so a human\n * reading `install-state.json` (or a support thread) would keep seeing a failure\n * that this build no longer produces.\n *\n * Not load-bearing also means not worth losing a concurrent update over: the write\n * is built from the newest read, and `migrateState` is idempotent.\n */\nasync function persistMigratedState(): Promise<void> {\n try {\n // One read, then migrate what was read. Re-reading to compare first (the\n // original shape) bought nothing: `writeFileAtomic` gives atomic REPLACE, not\n // isolation, so a `patchState` can still land between the last read and the\n // write. Building the write from the newest read is the most a lock-free writer\n // can do, and the migration is idempotent, so the only field a race can lose is\n // `lastAttemptAt`-class metadata that describes an attempt this build already\n // dropped the verdict for.\n const parsed = JSON.parse(await readFileWithRetry(statePath(), { retryMissing: false })) as OptionalState\n if (typeof parsed !== \"object\" || parsed === null) return\n if ((parsed.schemaVersion ?? 1) === OPTIONAL_STATE_SCHEMA) return\n await writeFileAtomic(statePath(), `${JSON.stringify(migrateState(parsed), null, 2)}\\n`, {\n mode: 0o644,\n })\n } catch {\n // No file (first run) or unparseable: a write here would create noise, not state.\n }\n}\n\nasync function patchState(\n pkg: OptionalPackage,\n patch: Partial<NonNullable<OptionalState[\"packages\"]>[OptionalPackage] & object>,\n): Promise<void> {\n try {\n const state = await readState()\n const next: OptionalState = {\n // Keep any top-level key this build does not know about. Today the file holds\n // only `schemaVersion` + `packages`, but dropping an unknown key on every\n // write is a silent deletion waiting for the first future field (the same\n // self-healing rule `managed-install/state.ts` follows).\n ...state,\n // Exactly this build's schema, never a higher one: an unrecognised schema\n // was just migrated (its ladder dropped), so the entry being written now is\n // produced by these semantics and must be labelled accordingly. Keeping a\n // newer number would let a later build trust a ladder it did not write.\n schemaVersion: OPTIONAL_STATE_SCHEMA,\n packages: { ...(state.packages ?? {}), [pkg]: { ...(state.packages?.[pkg] ?? {}), ...patch } },\n }\n // `undefined` means delete — how a success clears the ladder.\n for (const [key, value] of Object.entries(next.packages?.[pkg] ?? {})) {\n if (value === undefined) delete (next.packages![pkg] as Record<string, unknown>)[key]\n }\n await fs.mkdir(optionalRoot(), { recursive: true })\n await writeFileAtomic(statePath(), `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o644 })\n } catch (err) {\n reportManagedDiagnostic(\"debug\", `optional: could not write state: ${String(err)}`)\n }\n}\n\nfunction nextAttemptAtFor(failures: number): string {\n const index = Math.min(Math.max(failures, 1), BACKOFF_HOURS.length) - 1\n return new Date(Date.now() + (BACKOFF_HOURS[index] ?? 24) * 3_600_000).toISOString()\n}\n\n/**\n * When the next attempt is due, and how to skip the wait.\n *\n * The ladder exists so a broken registry or an offline laptop does not spawn npm\n * on every launch, and it climbs 1h -> 6h -> 24h. That is the right default, but a\n * message that only says \"backing off\" hides two things the reader needs: WHEN it\n * will try again, and that `--force` skips the wait entirely. Without them a user\n * whose payload is missing for a day has no way to tell a broken install from a\n * deliberate cooldown, and no way to test a fix.\n */\nfunction backoffHint(failures: number): string {\n const at = Date.parse(nextAttemptAtFor(failures))\n return `next attempt ${new Date(at).toISOString().replace(\".000Z\", \"Z\")}, --force retries now`\n}\n\n/**\n * The same hint for the guard's early return, derived from what is on disk.\n *\n * Nothing from the environment is interpolated here, only a timestamp this module\n * itself wrote.\n */\nasync function backoffDetail(pkg: OptionalPackage): Promise<string> {\n const entry = (await readState()).packages?.[pkg]\n const at = entry?.nextAttemptAt ? Date.parse(entry.nextAttemptAt) : Number.NaN\n const when = Number.isNaN(at) ? \"later\" : new Date(at).toISOString().replace(\".000Z\", \"Z\")\n return `backing off after a failed ${pkg} install (next attempt ${when}); --force retries now`\n}\n\n/**\n * Whether an attempt may start — a RESERVATION is not a backoff.\n *\n * `nextAttemptAt` is written before every attempt so two processes cannot both\n * download a 500 MB payload, and it is also the ladder's output. Conflating them\n * makes `github-router update` (issued while an on-demand install is still\n * running, seconds after it reserved) report \"backing off after a failed\n * tree-sitter-wasms install\" when nothing had failed. With `consecutiveFailures`\n * still 0 the window is a reservation, so re-attempting is allowed; the loser of\n * the rename race adopts the winner's payload.\n */\nasync function mayAttemptNow(pkg: OptionalPackage): Promise<boolean> {\n const entry = (await readState()).packages?.[pkg]\n if ((entry?.consecutiveFailures ?? 0) === 0) return true\n if (!entry?.nextAttemptAt) return true\n const next = new Date(entry.nextAttemptAt).getTime()\n return Number.isNaN(next) ? true : Date.now() >= next\n}\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nexport interface EnsureOptionalResult {\n /** The `node_modules/<pkg>` directory when usable, else null. */\n dir: string | null\n detail?: string\n installed?: boolean\n}\n\n/**\n * Make sure `pkg` is installed and return its directory.\n *\n * Fail-open and throttled: a failure is remembered on the standard ladder, so a\n * permanently offline machine does not spawn an npm process per search.\n */\nexport async function ensureOptionalPackage(\n pkg: OptionalPackage,\n opts: { signal?: AbortSignal; force?: boolean; registry?: string } = {},\n): Promise<EnsureOptionalResult> {\n if (optionalInstallDisabled()) {\n return { dir: null, detail: \"GH_ROUTER_NO_OPTIONAL_INSTALL is set\" }\n }\n // Persist a schema migration before the guard can short-circuit on it: a stale\n // ladder must not survive by being read and then abandoned.\n await persistMigratedState()\n if (!opts.force && !(await mayAttemptNow(pkg))) {\n return { dir: null, detail: await backoffDetail(pkg) }\n }\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) {\n // No npm is not a reason to refuse a payload that is already installed.\n const existing = installedOptional(pkg)\n return existing ? { dir: existing } : { dir: null, detail: \"npm is not on PATH\" }\n }\n\n // Resolve FIRST, then compare against what is installed.\n //\n // The obvious order — \"anything installed? return it\" — makes the payload\n // permanently un-upgradable: the first install wins forever, `update` keeps\n // reporting the stale copy \"ready\", and a fix for a broken payload can never\n // reach a machine that already has one. `installedOptional` prefers the newest\n // copy but cannot know whether a NEWER version exists.\n const resolved = await resolveOptionalVersion(pkg, opts.registry)\n const version = resolved.version\n // A payload dir, so it can be returned as-is (wrapping it in `payloadDir` again\n // produced `<pkg>/node_modules/<pkg>/node_modules/<pkg>`).\n const existing = version ? installedOptionalTarget(pkg, version) : installedOptional(pkg)\n if (existing && !opts.force) {\n // Resolution failing while a usable payload is on disk is a DIFFERENT situation\n // from having nothing to install, and it used to be silent: the early return\n // skipped the failure branch entirely, so `update` said \"ready\" while every\n // future upgrade would fail at the first step. Reported at debug because the\n // user's payload works; not recorded on the ladder because an attempt that\n // delivered a working payload did not fail.\n if (!version && resolved.detail) {\n reportManagedDiagnostic(\n \"debug\",\n `optional: ${pkg} is installed but its version could not be resolved: ${resolved.detail}`,\n )\n }\n return { dir: existing }\n }\n\n if (!version) {\n // Ladder the RESOLUTION failure too. It used to hard-set\n // `consecutiveFailures: 1` on every attempt, which pinned the package at the\n // bottom rung of the ladder forever: a machine whose `npm view` was broken by\n // something we fixed could never climb out, and a genuinely offline machine\n // was retried hourly instead of backing off.\n const failures = ((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0) + 1\n const detail = resolved.detail ?? `could not resolve a version for ${pkg}`\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n consecutiveFailures: failures,\n nextAttemptAt: nextAttemptAtFor(failures),\n lastError: detail,\n // Clear a stale success version so the state cannot read as healthy — but\n // only when nothing is on disk. `--force` reaches this branch with a working\n // payload installed (`existing` was computed above and the early return was\n // skipped), and erasing the version recorded for a payload that IS there is a\n // lie the next reader has to work around.\n ...(existing ? {} : { version: undefined }),\n })\n return { dir: null, detail: `${detail} (${backoffHint(failures)})` }\n }\n\n const target = optionalTarget(pkg, version)\n // A concurrent install may have published it while we resolved.\n if (completeAt(target, pkg)) return { dir: payloadDir(target, pkg), installed: false }\n\n // The newest copy this machine already had, captured BEFORE the install so GC\n // can be told to spare it (see the `gcOptional` call below). A running process\n // may have it memory-mapped: the ONNX runtime is loaded lazily, so \"this\n // process installed the newer one\" says nothing about whether it is still\n // reading the older one.\n const [previousTarget] = completeTargets(pkg)\n\n // Reservation only, with the ladder value keyed on the REAL failure count: a\n // first attempt has `consecutiveFailures` 0, which `mayAttemptNow` treats as\n // \"not a backoff\".\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n nextAttemptAt: nextAttemptAtFor((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0),\n })\n\n try {\n await installInto(pkg, version, target, npmPath, opts.registry, opts.signal)\n await patchState(pkg, {\n lastSuccessAt: new Date().toISOString(),\n consecutiveFailures: 0,\n nextAttemptAt: undefined,\n lastError: undefined,\n version,\n })\n // Protect BOTH the copy this process was already using (a rerank that has the\n // ONNX runtime loaded memory-maps files from it) and the one just installed.\n // GC removes by age + rank, and \"rank\" cannot see a running\n // process: on POSIX an `fs.rm` of a mapped directory SUCCEEDS (`EBUSY` only\n // rescues Windows), so the next lazy load in that process dies. Protecting\n // these two names is the whole of what this process can know; the 30-day\n // floor and keep-2 rule cover the rest.\n const protect = [path.basename(target)]\n if (previousTarget) protect.push(previousTarget)\n await gcOptional(Date.now(), protect).catch(() => {})\n return { dir: payloadDir(target, pkg), installed: true }\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n const failures = ((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0) + 1\n await patchState(pkg, {\n lastAttemptAt: new Date().toISOString(),\n consecutiveFailures: failures,\n nextAttemptAt: nextAttemptAtFor(failures),\n lastError: detail,\n })\n return { dir: null, detail }\n }\n}\n\n/**\n * Install `pkg@version` into `target` via a staging sibling.\n *\n * Same publish discipline as the managed installer (build in `.staging-*`,\n * verify the entry, rename into place) and for the same reason: the target may\n * be read concurrently by a running request, and a half-written payload that\n * passes a directory-existence check is worse than no payload.\n */\nasync function installInto(\n pkg: OptionalPackage,\n version: string,\n target: string,\n npmPath: string,\n registry?: string,\n signal?: AbortSignal,\n): Promise<void> {\n const root = optionalRoot()\n await fs.mkdir(root, { recursive: true })\n const staging = path.join(root, `.staging-${process.pid}-${randomHex()}`)\n // Not `recursive`: the name is unique, so an EEXIST means a leftover tree from\n // a same-pid attempt, and installing into it would let an INHERITED copy pass\n // the completeness check below. Fail and let the caller retry.\n await fs.mkdir(staging)\n try {\n const pkgJson = {\n name: `gh-router-optional-${sanitized(pkg)}`,\n private: true,\n version: \"0.0.0\",\n dependencies: { [subjectFor(pkg).packageName]: version },\n }\n await writeFileAtomic(path.join(staging, \"package.json\"), `${JSON.stringify(pkgJson, null, 2)}\\n`, {\n mode: 0o644,\n })\n\n const overrides: NodeJS.ProcessEnv = {}\n if (registry) overrides.npm_config_registry = registry\n const { env } = buildNpmEnv(process.env, overrides)\n\n reportManagedDiagnostic(\"info\", `Installing optional ${pkg}@${version} (one-time)…`)\n const { code, stderr } = await runCommandCapture(\n [\n npmPath,\n \"install\",\n \"--no-global\",\n \"--no-dry-run\",\n \"--include=optional\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--no-fund\",\n \"--loglevel=error\",\n ...(registry ? [`--registry=${registry}`] : []),\n ],\n { cwd: staging, env, timeoutMs: 30 * 60_000, signal },\n )\n if (code !== 0) {\n throw new Error(`npm install ${pkg}@${version} failed (exit ${code}): ${stderr.slice(0, 400)}`)\n }\n if (!completeAt(staging, pkg)) {\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but ${subjectFor(pkg).requiredFile} is missing`,\n )\n }\n // The required file existing is not the same as the right version being\n // installed: a stale tree, a mirror serving another tarball, or a `--omit`\n // config that slipped through all look complete. The rename below publishes\n // this directory, so verify identity before that.\n try {\n const declared = (\n JSON.parse(await fs.readFile(path.join(payloadDir(staging, pkg), \"package.json\"), \"utf8\")) as {\n version?: unknown\n }\n ).version\n if (declared !== version) {\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but its package.json declares ${JSON.stringify(declared)}; refusing to publish it`,\n )\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"refusing to publish\")) throw err\n throw new Error(\n `${subjectFor(pkg).packageName}@${version} installed but its package.json is unreadable: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n )\n }\n const packages = await harvestProvenance(staging)\n await writeFileAtomic(\n path.join(staging, \".installed.json\"),\n `${JSON.stringify({ version, packages, installedAt: new Date().toISOString() }, null, 2)}\\n`,\n { mode: 0o644 },\n )\n\n try {\n await fs.rename(staging, target)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n const clash =\n code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\"\n if (!clash) throw err\n // Somebody published it first. Adopt theirs if it is complete.\n if (completeAt(target, pkg)) return\n const aside = path.join(root, `.trash-${randomHex()}`)\n let movedAside = false\n try {\n await fs.rename(target, aside)\n movedAside = true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err\n }\n try {\n await fs.rename(staging, target)\n } catch (err) {\n // Put the incomplete-but-present tree back rather than leaving the\n // package with NO copy at all: `installedOptional` refuses it either way,\n // but a single retry can repair it in place, and a missing directory\n // cannot be compared or resumed.\n if (movedAside) await fs.rename(aside, target).catch(() => {})\n throw err\n }\n }\n } finally {\n await fs.rm(staging, { recursive: true, force: true }).catch(() => {})\n }\n}\n\n/** `{ \"<pkg>@<ver>\": { resolved, integrity } }` from the prefix lockfile. */\nasync function harvestProvenance(\n prefix: string,\n): Promise<Record<string, { resolved?: string; integrity?: string }>> {\n const out: Record<string, { resolved?: string; integrity?: string }> = {}\n try {\n const raw = await fs.readFile(path.join(prefix, \"package-lock.json\"), \"utf8\")\n const parsed = JSON.parse(raw) as {\n packages?: Record<string, { version?: string; resolved?: string; integrity?: string; link?: boolean }>\n }\n for (const [key, entry] of Object.entries(parsed.packages ?? {})) {\n if (!key.startsWith(\"node_modules/\") || entry.link || !entry.version) continue\n const name = key.slice(\"node_modules/\".length)\n // Top-level only; the transitive tree is reproducible from the registry\n // once the root tarball's integrity is pinned.\n if (name.includes(\"node_modules/\")) continue\n out[`${name}@${entry.version}`] = {\n ...(entry.resolved ? { resolved: entry.resolved } : {}),\n ...(entry.integrity ? { integrity: entry.integrity } : {}),\n }\n }\n } catch {\n // No lockfile: provenance is diagnostics, never a gate.\n }\n return out\n}\n\n/**\n * Newest published version of `pkg`, or a `detail` explaining why there is none.\n *\n * The `detail` is not cosmetic. This resolution step is the one that fails for a\n * reason the user cannot see: a registry that cannot answer, or — the case that\n * shipped — an argv that reached npm corrupted, so `npm view` exited non-zero\n * and said `EINVALIDTAGNAME` while the caller reported a generic \"could not\n * resolve a version\". Carrying npm's own error code and summary through turns a\n * silent, unactionable backoff into a diagnosis.\n */\nasync function resolveOptionalVersion(\n pkg: OptionalPackage,\n registry?: string,\n): Promise<{ version: string | null; detail?: string }> {\n const pinned = subjectFor(pkg).version\n if (pinned) return { version: pinned }\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return { version: null, detail: \"npm is not on PATH\" }\n const subject = subjectFor(pkg)\n // With a range, npm does the range arithmetic and `--json` gives every match\n // newest-last; without one (a test stand-in) the spec is the bare name.\n const spec = subject.range ? `${subject.packageName}@${subject.range}` : subject.packageName\n try {\n const args = [npmPath, \"view\", spec, \"version\", \"--json\", \"--silent\"]\n if (registry) args.push(`--registry=${registry}`)\n const { stdout, stderr, code } = await runCommandCapture(args, { timeoutMs: 8000 })\n if (code !== 0) {\n const why = npmFailureDetail(stdout, stderr)\n // A silent failure (npm killed by a signal, a wrapper that exits without a\n // word) would otherwise produce `failed (exit 1): ` with a dangling colon.\n const reason = why ? `failed (exit ${code}): ${why}` : `failed (exit ${code}) with no message`\n return { version: null, detail: `npm view ${spec} ${reason}` }\n }\n const value = lastVersionFromJson(stdout)\n if (value && VERSION_RE.test(value)) return { version: value }\n const seen = sanitizeDiagnostic(JSON.stringify(stdout.trim().slice(0, 120)))\n return { version: null, detail: `npm view ${spec} returned ${seen}` }\n } catch (err) {\n const why = err instanceof Error ? err.message : String(err)\n return { version: null, detail: `npm view ${spec} failed: ${sanitizeDiagnostic(why)}` }\n }\n}\n\n/**\n * Why `npm view` failed, in one readable line.\n *\n * Under `--json` npm does NOT put that sentence on stderr. It writes a JSON error\n * ENVELOPE to stdout and leaves stderr empty:\n *\n * {\"error\":{\"code\":\"EINVALIDTAGNAME\",\"summary\":\"Invalid tag name \\\"^^0.1.13\\\" …\"}}\n *\n * so reading the first line of either stream yields `\"{\"` — measured, for the very\n * failure this branch exists to explain. Parsing the envelope is what makes the\n * message carry `EINVALIDTAGNAME` and the bad spec instead of a brace; the\n * line-based read stays as the fallback for a non-JSON failure (a crashed npm, a\n * proxy error page, a spawn-level message on stderr).\n */\nfunction npmFailureDetail(stdout: string, stderr: string): string {\n for (const stream of [stdout, stderr]) {\n const parsed = parseJson(stream)\n const error = (parsed as { error?: unknown } | null)?.error\n if (error && typeof error === \"object\") {\n const { code, summary } = error as { code?: unknown; summary?: unknown }\n const parts = [code, summary].filter((part): part is string => typeof part === \"string\")\n if (parts.length > 0) return sanitizeDiagnostic(parts.join(\" \"))\n }\n }\n return sanitizeDiagnostic(firstLine(stderr || stdout))\n}\n\n/**\n * Make a third-party diagnostic safe to store and print.\n *\n * `lastError` is written to `optional/install-state.json` (mode 0644) and echoed\n * to the terminal by `update`. The text comes from npm, which comes from whatever\n * registry answered, so it is untrusted input, and there are three concrete shapes\n * it can take:\n *\n * - **ANSI/control characters.** A registry behind a corporate proxy can answer\n * with a coloured or framed error page, and an escape sequence replayed into a\n * terminal can rewrite the line the user is reading. Whole sequences are\n * removed, then any remaining control byte and any zero-width/bidi override:\n * nothing here is worth preserving, and the `npm view --json` output that\n * matters is parsed before it reaches this function.\n * - **A URL with credentials.** `resolveOptionalVersion` passes\n * `--registry=<url>`, and npm echoes the request URL on 401/404 — so a\n * `https://user:token@mirror` registry would land in a world-readable file and\n * on the terminal. Userinfo is replaced wholesale rather than partly kept,\n * because a redactor that preserves \"the useful part\" of a secret is one regex\n * bug away from leaking it.\n * - **Length.** A megabyte of proxy HTML does not belong in a state file.\n *\n * Deliberately local rather than `sanitizeTransportText` from `../upstream-retry`:\n * that module imports `consola`, and this layer is documented as the one that must\n * not (see `./paths`, `./diagnostics`), because it is reachable from the bin bundle\n * and from request paths.\n */\nfunction sanitizeDiagnostic(text: string): string {\n const flat = text\n // Normalise the C1 single-byte CSI (`\\u009b`) to its two-byte form first, so\n // the CSI rule below has one shape to handle. Without this the control pass\n // turned it into a space and left `31mcyan` behind — measured.\n .replace(/\\u009b/g, \"\\u001b[\")\n // Whole ANSI escape sequences first, not just the ESC byte. Removing only\n // `\\x1b` leaves the parameters behind as printable text — measured, a\n // coloured `npm ERR!` came out as `[31mE401 for …[0m`, which is uglier than\n // what it replaced and still leaks terminal framing into a state file. CSI\n // (`ESC [ … final`), OSC (`ESC ] … BEL|ST`) and the two-byte forms cover what\n // a registry, a proxy error page or a progress bar can emit.\n //\n // The OSC body stops at BEL, at ST, at end-of-string, or at the LOOKAHEAD of\n // another ESC. That last alternative is the one that matters: an OSC with no\n // terminator is common in truncated npm output, and the naive alternation\n // either matched it not at all (leaving `ESC]8;;url`, which the CSI rule then\n // turned into `ttps://…` with its head eaten) or, with a fully lazy `[\\s\\S]*?`,\n // swallowed every later escape on the line as well.\n // eslint-disable-next-line no-control-regex -- matching escape sequences IS the point.\n .replace(/\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\|(?=\\u001b)|$)/g, \"\")\n // eslint-disable-next-line no-control-regex -- as above.\n .replace(/\\u001b[[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]/g, \"\")\n // Whatever ESC is left introduces a sequence this build does not model (an\n // SSC/DCS, or a truncated one). Drop the ESC and the character after it, the\n // same way a terminal consumes a two-byte function: leaving the bare ESC is\n // the one outcome that must never survive, since it makes the FOLLOWING text\n // a control sequence again on display.\n // eslint-disable-next-line no-control-regex -- as above.\n .replace(/\\u001b[\\s\\S]/g, \"\")\n // Zero-width and bidirectional overrides. These are not control bytes, so the\n // next pass misses them, and they are the cheap way to make one line READ as\n // another in a terminal or an editor (a U+202E turns the rest of the line\n // around). Nothing a registry has to say needs them.\n .replace(/[\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2064\\u2066-\\u2069\\ufeff]/g, \"\")\n // Anything left that a terminal would execute or a JSON reader would choke\n // on: C0/C1, and the two Unicode line separators that are not `\\n`.\n // eslint-disable-next-line no-control-regex -- as above.\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n // Greedy up to the LAST `@` before the path, not the first. A URL can legally\n // carry more than one: `https://a@b:c@host/x` redacted non-greedily kept\n // `b:c` in clear, which is exactly the half of a credential worth stealing.\n .replace(/([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/?#]*@/gi, \"$1[REDACTED]@\")\n return flat.length > 300 ? `${flat.slice(0, 300)}…` : flat\n}\n\n/** `JSON.parse` that returns null instead of throwing on the non-JSON cases above. */\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return null\n }\n}\n\n/**\n * First non-empty line of a diagnostic, trimmed.\n *\n * Both streams are candidates because npm's choice is not stable across versions\n * and subcommands, and neither is guaranteed. Used only as the non-JSON fallback\n * now — see `npmFailureDetail` for why the first line of `--json` output is not a\n * diagnosis.\n */\nfunction firstLine(text: string): string {\n return text.split(/\\r?\\n/).find((part) => part.trim().length > 0)?.trim() ?? \"\"\n}\n\n/**\n * The newest version in `npm view … --json` output, or null.\n *\n * The output is a bare `\"1.2.3\"` when the spec matches exactly one version and\n * an ARRAY when a range matches several — and `npm view left-pad@^1.0.0 version`\n * prints the array newest-LAST, so the last element is the answer in both cases.\n * Parsing it as JSON rather than taking the last LINE is what makes a range with\n * a hundred matches work; the old line-based read returned `\"1.3.0\"` (with the\n * quotes) and the version regex then rejected it.\n */\nfunction lastVersionFromJson(stdout: string): string | null {\n const text = stdout.trim()\n if (!text) return null\n try {\n const parsed = JSON.parse(text) as unknown\n if (typeof parsed === \"string\") return parsed\n if (Array.isArray(parsed)) {\n for (let i = parsed.length - 1; i >= 0; i--) {\n const entry = parsed[i]\n if (typeof entry === \"string\") return entry\n }\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Compare dotted versions on the leading three components. */\nexport function compareVersions(a: string, b: string): number {\n const pa = a.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n const pb = b.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = Number.isNaN(pa[i]) ? 0 : (pa[i] ?? 0)\n const bv = Number.isNaN(pb[i]) ? 0 : (pb[i] ?? 0)\n if (av !== bv) return av - bv\n }\n return 0\n}\n\n/**\n * Keep the newest `KEEP_OPTIONAL_VERSIONS` copies per package and sweep\n * abandoned staging/trash dirs.\n *\n * Deliberately more conservative than the managed GC (30-day floor, keep 2, and\n * never remove the only copy of a package): each copy is up to 547 MB, so\n * deleting the wrong one is expensive to undo.\n *\n * `protect` is the caller's knowledge of what is IN USE — directory names under\n * the optional root that must survive this sweep. Nothing on disk records which\n * copy a running process has loaded, and the two rules here cannot infer it: a\n * process that has been up for weeks holds an old version that ranks below the\n * two newest and is past the floor, and on POSIX `fs.rm` of a memory-mapped\n * payload SUCCEEDS (`EBUSY` only saves Windows). The next lazy load in that\n * process would then fail. The installer passes the copy it just wrote and the\n * one it replaced.\n */\nexport async function gcOptional(\n now = Date.now(),\n protect: ReadonlyArray<string> = [],\n): Promise<{\n removed: Array<string>\n removedTransient: Array<string>\n}> {\n const root = optionalRoot()\n let names: Array<string>\n try {\n names = await fs.readdir(root)\n } catch {\n return { removed: [], removedTransient: [] }\n }\n\n const removed: Array<string> = []\n const removedTransient: Array<string> = []\n\n // Bucket by package, carrying mtime so \"newest\" is by time, not by the order\n // the filesystem happened to hand back.\n const versions = new Map<string, Array<{ name: string; mtimeMs: number }>>()\n\n for (const name of names) {\n const full = path.join(root, name)\n let mtimeMs: number\n try {\n mtimeMs = (await fs.stat(full)).mtimeMs\n } catch {\n continue\n }\n // Same shapes as the managed GC (`paths.ts`): a user file that merely\n // starts with `.staging-` is not one of our abandoned attempts.\n if (isTransientName(name)) {\n if (now - mtimeMs > 60 * 60_000) {\n await fs.rm(full, { recursive: true, force: true }).catch(() => {})\n removedTransient.push(name)\n }\n continue\n }\n const match = /^(.+?)@(.+)$/.exec(name)\n if (!match) continue\n if (!isVersionName(match[2]!)) continue\n const bucket = versions.get(match[1]!) ?? []\n bucket.push({ name, mtimeMs })\n versions.set(match[1]!, bucket)\n }\n\n const spared = new Set(protect)\n for (const entries of versions.values()) {\n // Newest first, then keep the first N. Everything from index N on is a\n // removal CANDIDATE, still subject to the age floor and the protect list.\n entries.sort((a, b) => b.mtimeMs - a.mtimeMs)\n for (const entry of entries.slice(KEEP_OPTIONAL_VERSIONS)) {\n if (spared.has(entry.name)) continue\n if (now - entry.mtimeMs < OPTIONAL_FLOOR_MS) continue\n await fs.rm(path.join(root, entry.name), { recursive: true, force: true })\n .then(() => removed.push(entry.name))\n .catch(() => {\n // EBUSY on Windows (a loaded ONNX runtime): retried on the next pass.\n })\n }\n }\n return { removed, removedTransient }\n}\n\n// ---------------------------------------------------------------------------\n// Entry points used by the launcher / update\n// ---------------------------------------------------------------------------\n\n/**\n * Install ONE payload, whichever a caller asked for by name.\n *\n * Separate entry point from `ensureOptionalPackage` because the argument comes\n * from a command line: an unknown name must be a reported no-op, never a crash\n * and never \"install everything because the filter matched nothing\".\n */\nexport function isOptionalPackage(name: string): name is OptionalPackage {\n return (OPTIONAL_PACKAGES as ReadonlyArray<string>).includes(name)\n}\n\n/**\n * Install both payloads, reporting what happened.\n *\n * Called from `github-router update` (foreground, where a failure is visible)\n * and never from a request path.\n */\nexport async function ensureOptionalPackages(\n opts: { registry?: string; signal?: AbortSignal; force?: boolean } = {},\n): Promise<Array<{ pkg: OptionalPackage; dir: string | null; detail?: string }>> {\n const out: Array<{ pkg: OptionalPackage; dir: string | null; detail?: string }> = []\n for (const pkg of OPTIONAL_PACKAGES) {\n const result = await ensureOptionalPackage(pkg, opts)\n out.push({ pkg, dir: result.dir, ...(result.detail ? { detail: result.detail } : {}) })\n }\n return out\n}\n\n/** Set by {@link scheduleOptionalInstall}; one detached child per process. */\nlet scheduledInProcess = false\n\n/**\n * Detached, best-effort install for a launch that noticed a gap.\n *\n * Detached because the spawn cost of two npm installs (minutes on a cold cache)\n * must never be attributed to the command the user actually ran — and a search\n * that triggered this proceeds on its BM25F fallback regardless.\n */\nexport function scheduleOptionalInstall(\n pkg: OptionalPackage,\n argv1: string | undefined = process.argv[1],\n): boolean {\n if (optionalInstallDisabled()) return false\n if (typeof argv1 !== \"string\" || argv1.length === 0) return false\n // Once per process. The callers are on request paths (a rerank, a structural\n // search), and for an agent a \"request path\" means per turn: spawning a\n // detached node process on every one of them would be worse than the missing\n // payload. Cross-process throttling is the backoff in `install-state.json`;\n // this flag only stops the same process from re-spawning what it already\n // started.\n if (scheduledInProcess) return false\n scheduledInProcess = true\n const missing = pkg\n void (async () => {\n try {\n // Dynamic on purpose: modules that only ever RESOLVE a payload (the\n // rerank loader, the grammar resolver) should not pull\n // `node:child_process` into their import graph.\n const { spawn } = await import(\"node:child_process\")\n // `--optional-only --optional-pkg <pkg>`: the caller is a feature that found\n // no payload, so installing THAT payload is the whole request. Not a\n // self-update, not a managed Pi appearing on a source checkout because a\n // search was slow, and — the part that is easy to get wrong — not the OTHER\n // payload either: a structural-search miss must not start a 547 MB ONNX\n // download because both slots share one flag.\n const child = spawn(\n process.execPath,\n [argv1, \"update\", \"--quiet\", \"--optional-only\", \"--optional-pkg\", missing],\n {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, GH_ROUTER_MANAGED_BACKGROUND: \"1\" },\n },\n )\n child.on(\"error\", () => {})\n child.unref()\n } catch {\n // Never fatal: the next launch (or an explicit `update`) tries again.\n }\n })()\n return true\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,oBAAoB,CAAC,6BAA6B,mBAAmB;;;;;;;;;AAWlF,MAAa,yBAAoE;CAC/E,6BAA6B;CAM7B,qBAAqB;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OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,OAAO;CAO5D,IAAI,oBAAoB,OAAO;CAC/B,qBAAqB;CACrB,MAAM,UAAU;CAChB,CAAM,YAAY;EAChB,IAAI;GAIF,MAAM,EAAE,UAAU,MAAM,OAAO;GAO/B,MAAM,QAAQ,MACZ,QAAQ,UACR;IAAC;IAAO;IAAU;IAAW;IAAmB;IAAkB;GAAO,GACzE;IACE,UAAU;IACV,OAAO;IACP,aAAa;IACb,KAAK;KAAE,GAAG,QAAQ;KAAK,8BAA8B;IAAI;GAC3D,CACF;GACA,MAAM,GAAG,eAAe,CAAC,CAAC;GAC1B,MAAM,MAAM;EACd,QAAQ,CAER;CACF,EAAA,CAAG;CACH,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import "./stop-gate-hook-
|
|
2
|
-
import { c as runCommandCapture, o as parseIntEnv } from "./exec-
|
|
1
|
+
import "./stop-gate-hook-Ba_RvZAj.js";
|
|
2
|
+
import { c as runCommandCapture, o as parseIntEnv } from "./exec-oCtz_dXO.js";
|
|
3
3
|
// src/lib/orchestration/live-exec.ts
|
|
4
4
|
/**
|
|
5
5
|
* Live `ExecFn` for the gate runner — runs the kernel's SEALED gate command in a
|
|
@@ -35,4 +35,4 @@ const liveExec = async ({ command, cwd }) => {
|
|
|
35
35
|
};
|
|
36
36
|
export { liveExec as t };
|
|
37
37
|
|
|
38
|
-
//# sourceMappingURL=orchestration-
|
|
38
|
+
//# sourceMappingURL=orchestration-C_hyBL90.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestration-
|
|
1
|
+
{"version":3,"file":"orchestration-C_hyBL90.js","names":[],"sources":["../src/lib/orchestration/live-exec.ts"],"sourcesContent":["/**\n * Live `ExecFn` for the gate runner — runs the kernel's SEALED gate command in a\n * workspace via the project's Windows-safe exec helper (`runCommandCapture` →\n * `buildExecInvocation`, which handles cmd.exe quoting on Windows). Only the\n * kernel's sealed gate commands flow through here (tests/types/lint/build),\n * never a producer-authored string, so a simple whitespace split into argv is\n * safe for these fixed commands. A command that can't run (spawn error / killed)\n * counts as a non-zero exit, never a throw — the gate runner treats it as\n * not-passed.\n *\n * This is the one piece of the gate engine that touches a real subprocess; it is\n * model-free and cross-platform, so it is exercised directly in CI (unlike the\n * worker/worktree/model adapters, which need the gated E2E harness).\n */\n\nimport { runCommandCapture } from \"~/lib/exec\"\n\nimport { type ExecFn } from \"./gate-runner\"\nimport { parseIntEnv } from \"../exec\"\n\n/** Per-command wall-clock cap so a hung gate command (watch-mode test, a process\n * waiting on stdin, a stale lockfile) is tree-killed instead of hanging the\n * caller forever. Generous (a real typecheck/test/lint can take minutes) but\n * bounded; override with GH_ROUTER_GATE_CMD_TIMEOUT_MS. A timeout kills the\n * command (code null) which the gate runner treats as not-passed. */\nconst CMD_TIMEOUT_MS =\n parseIntEnv(process.env.GH_ROUTER_GATE_CMD_TIMEOUT_MS) ?? 600_000\n\nexport const liveExec: ExecFn = async ({ command, cwd }) => {\n const argv = command.trim().split(/\\s+/).filter(Boolean)\n if (argv.length === 0) return { exitCode: 1 }\n try {\n const r = await runCommandCapture(argv, { cwd, timeoutMs: CMD_TIMEOUT_MS })\n // `code` is null when killed by signal/timeout → treat as a failed gate.\n return { exitCode: r.code ?? 1 }\n } catch {\n return { exitCode: 1 }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,iBACJ,YAAY,QAAQ,IAAI,6BAA6B,KAAK;AAE5D,MAAa,WAAmB,OAAO,EAAE,SAAS,UAAU;CAC1D,MAAM,OAAO,QAAQ,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO;CACvD,IAAI,KAAK,WAAW,GAAG,OAAO,EAAE,UAAU,EAAE;CAC5C,IAAI;EAGF,OAAO,EAAE,WAAU,MAFH,kBAAkB,MAAM;GAAE;GAAK,WAAW;EAAe,CAAC,EAAA,CAErD,QAAQ,EAAE;CACjC,QAAQ;EACN,OAAO,EAAE,UAAU,EAAE;CACvB;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { n as classifyOrigin } from "./origin-B6GChVyp.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as runCommandCapture, s as resolveExecutable } from "./exec-
|
|
1
|
+
import { c as runCommandCapture, s as resolveExecutable } from "./exec-oCtz_dXO.js";
|
|
2
2
|
import { n as realpathIfPossible, t as isUnderVolatileRoot } from "./volatile-root-DQNNvQ7Z.js";
|
|
3
3
|
import { t as reportManagedDiagnostic } from "./diagnostics-cXjCT_JQ.js";
|
|
4
4
|
import { i as writeFileAtomic, n as readFileWithRetry } from "./atomic-file-Dif1kLKM.js";
|
|
@@ -379,4 +379,4 @@ function describeOrigin(origin) {
|
|
|
379
379
|
}
|
|
380
380
|
export { TRANSIENT_TTL_MS as a, nextAttemptAtFor as c, findPackageRoot as i, patchInstallState as l, classifyOrigin as n, VERSION_FLOOR_MS as o, describeOrigin as r, mayAttemptNow as s, classifyEntry as t, readInstallState as u };
|
|
381
381
|
|
|
382
|
-
//# sourceMappingURL=origin-
|
|
382
|
+
//# sourceMappingURL=origin-B6GChVyp.js.map
|