github-router 0.3.379 → 0.3.381

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.
Files changed (165) hide show
  1. package/README.md +62 -0
  2. package/dist/ado-tools-CsfbnY8x.js +1 -0
  3. package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
  4. package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
  5. package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
  6. package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
  7. package/dist/atomic-file-Dif1kLKM.js +198 -0
  8. package/dist/atomic-file-Dif1kLKM.js.map +1 -0
  9. package/dist/{attribution-settings-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.js.map} +1 -1
  11. package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
  12. package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
  13. package/dist/bin.js +1479 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/browser-ext/manifest.json +1 -1
  16. package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
  17. package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
  18. package/dist/{claude-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.js.map} +1 -1
  20. package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
  21. package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
  22. package/dist/{codex-BG0pfud9.js → codex-50GzveCD.js} +8 -7
  23. package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.js.map} +1 -1
  24. package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
  25. package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
  26. package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
  27. package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
  28. package/dist/diagnostics-cXjCT_JQ.js +12 -0
  29. package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
  30. package/dist/engine-B6la_uIW.js +1 -0
  31. package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
  32. package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
  33. package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
  34. package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
  35. package/dist/hooks.mjs +13 -0
  36. package/dist/hooks.sha256 +1 -1
  37. package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
  38. package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
  39. package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
  40. package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
  41. package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
  42. package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
  43. package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
  44. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
  45. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
  46. package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
  47. package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
  48. package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
  49. package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
  50. package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
  51. package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
  52. package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
  53. package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
  54. package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
  55. package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
  56. package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
  57. package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
  58. package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
  59. package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
  60. package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
  61. package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
  62. package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
  63. package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
  64. package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
  65. package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
  66. package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
  67. package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
  68. package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
  69. package/dist/lib/tree-sitter-pool/worker.js +268 -21
  70. package/dist/lifecycle-BOjgq9_l.js +1 -0
  71. package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
  72. package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
  73. package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
  74. package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
  75. package/dist/lifecycle-NQvr4flt.js +1 -0
  76. package/dist/main.js +39 -24
  77. package/dist/main.js.map +1 -1
  78. package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
  79. package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
  80. package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
  81. package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
  82. package/dist/npm-env-H60tX76c.js +130 -0
  83. package/dist/npm-env-H60tX76c.js.map +1 -0
  84. package/dist/optional-DGAeyguL.js +586 -0
  85. package/dist/optional-DGAeyguL.js.map +1 -0
  86. package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
  87. package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
  88. package/dist/origin-BXtpcKP9.js +382 -0
  89. package/dist/origin-BXtpcKP9.js.map +1 -0
  90. package/dist/origin-DbFUCiGp.js +1 -0
  91. package/dist/paths-CquOjytP.js +1 -0
  92. package/dist/paths-DK_b2ihK.js +176 -0
  93. package/dist/paths-DK_b2ihK.js.map +1 -0
  94. package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
  95. package/dist/paths-DeFmYJhO.js.map +1 -0
  96. package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
  97. package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
  98. package/dist/{pi-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
  99. package/dist/pi-DVud9eQn.js.map +1 -0
  100. package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
  101. package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
  102. package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
  103. package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
  104. package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
  105. package/dist/pi-version-check-BeBB0Ny9.js +551 -0
  106. package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
  107. package/dist/pi-version-check-D5RvdLsG.js +1 -0
  108. package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
  109. package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
  110. package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
  111. package/dist/provision-BWtuDq_v.js.map +1 -0
  112. package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
  113. package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
  114. package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
  115. package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
  116. package/dist/{serve-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
  119. package/dist/server-setup-byIhjgOb.js.map +1 -0
  120. package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
  121. package/dist/service-backend-BdhWVRSz.js.map +1 -0
  122. package/dist/{start-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
  123. package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.js.map} +1 -1
  124. package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
  125. package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
  126. package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
  127. package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
  128. package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
  129. package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
  130. package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
  131. package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
  132. package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
  133. package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
  134. package/dist/update-CB21YRKz.js +1 -0
  135. package/dist/update-T1L7yFon.js +1548 -0
  136. package/dist/update-T1L7yFon.js.map +1 -0
  137. package/dist/update-fEgWTrIx.js +214 -0
  138. package/dist/update-fEgWTrIx.js.map +1 -0
  139. package/dist/update-lock-BeS_WmC8.js +1 -0
  140. package/dist/update-lock-BmXx6QaR.js +171 -0
  141. package/dist/update-lock-BmXx6QaR.js.map +1 -0
  142. package/dist/volatile-root-DQNNvQ7Z.js +50 -0
  143. package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
  144. package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
  145. package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
  146. package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
  147. package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
  148. package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
  149. package/package.json +16 -4
  150. package/dist/ado-tools-CRkyU51J.js +0 -1
  151. package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
  152. package/dist/engine-V46un8Xl.js +0 -1
  153. package/dist/lifecycle-BENRuuX6.js +0 -1
  154. package/dist/lifecycle-Dli9vGI2.js +0 -1
  155. package/dist/paths-Be9_ujQ3.js +0 -1
  156. package/dist/paths-CVEO8jEH.js.map +0 -1
  157. package/dist/pi-DmeBxzIo.js.map +0 -1
  158. package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
  159. package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
  160. package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
  161. package/dist/provision-DPL8aGe2.js.map +0 -1
  162. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  163. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  164. package/dist/server-setup-ClZdV33Q.js.map +0 -1
  165. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
@@ -0,0 +1,586 @@
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-BC0MAnoA.js";
3
+ import { t as buildNpmEnv } from "./npm-env-H60tX76c.js";
4
+ import { t as reportManagedDiagnostic } from "./diagnostics-cXjCT_JQ.js";
5
+ import { g as randomHex, l as isTransientName, m as optionalRoot, r as VERSION_RE, u as isVersionName } from "./paths-DK_b2ihK.js";
6
+ import { existsSync, readdirSync } from "node:fs";
7
+ import path from "node:path";
8
+ import fs$1 from "node:fs/promises";
9
+ // src/lib/managed-install/optional.ts
10
+ /**
11
+ * On-demand install of the heavy optional payloads.
12
+ *
13
+ * `@huggingface/transformers` (~547 MB with its ONNX runtime) and
14
+ * `tree-sitter-wasms` (~49 MB of grammars) are the entire difference between a
15
+ * 66 MB install and a 586 MB one. The plan moves them to **optional** peers so
16
+ * nobody pays for them at install time — which has one blunt consequence that
17
+ * must be stated plainly: **optional peers are installed for nobody**, at any
18
+ * depth, by npm and by bun alike (measured). So "optional" cannot mean "the
19
+ * usual install will bring it"; it has to mean "we install it the first time
20
+ * something actually needs it".
21
+ *
22
+ * Three rules shape this file:
23
+ *
24
+ * 1. **One copy per machine, shared across versions.** The payload lands in
25
+ * `<APP_DIR>/optional/<pkg>@<version>/`, never inside a managed version dir:
26
+ * those are per-version and GC keeps two, so an in-tree copy would be 1.1 GB
27
+ * and would be re-fetched on every bump.
28
+ * 2. **Failure is always allowed.** Reranking falls back to BM25F and structural
29
+ * ranking to the regex heuristic; both already warn for exactly this case.
30
+ * Nothing here may ever make a search or a chat request fail.
31
+ * 3. **Off the hot path.** Resolution (is a usable copy present?) is a couple of
32
+ * `stat`s against a bounded directory listing, and it is synchronous because
33
+ * both consumers are. Installation is a separate, throttled, detached child;
34
+ * the request that noticed the gap proceeds without it.
35
+ *
36
+ * Supply-chain posture matches the managed installer: exact version, scrubbed
37
+ * npm env, `--ignore-scripts`, `--no-global`, provenance from the lockfile.
38
+ */
39
+ /** The packages that may be installed on demand. */
40
+ const OPTIONAL_PACKAGES = ["@huggingface/transformers", "tree-sitter-wasms"];
41
+ /**
42
+ * Entry file that must exist for a copy to count as installed.
43
+ *
44
+ * A package directory alone is not enough: an interrupted `npm install` can
45
+ * leave `node_modules/<pkg>` in place with its payload missing, and an
46
+ * on-demand install is precisely the kind that gets interrupted (the user
47
+ * quits, the machine sleeps). These are the exact files the two consumers load.
48
+ */
49
+ const OPTIONAL_REQUIRED_FILE = {
50
+ "@huggingface/transformers": "dist/transformers.node.mjs",
51
+ "tree-sitter-wasms": "out/tree-sitter-typescript.wasm"
52
+ };
53
+ /**
54
+ * The peer range each payload must satisfy, mirroring `package.json`.
55
+ *
56
+ * On-demand installation used to take whatever `npm view <pkg> version` said,
57
+ * which is unbounded: the day transformers 5.x ships, every machine fetches a
58
+ * major the router has never run — and `completeAt` refusing the payload turns
59
+ * that into a one-hour backoff that hides the cause. Bounding the query
60
+ * (`npm view <pkg>@<range> version`) makes npm do the range arithmetic, so the
61
+ * answer is by construction compatible. `tests/optional-payload-manifest.test.ts`
62
+ * asserts this table still matches `package.json#peerDependencies`.
63
+ */
64
+ const OPTIONAL_VERSION_RANGE = {
65
+ "@huggingface/transformers": "^4.3.2",
66
+ "tree-sitter-wasms": "^0.1.13"
67
+ };
68
+ /** `<pkg>` → the directory name used under `optional/` (`@scope/name` is unsafe). */
69
+ function sanitized(pkg) {
70
+ return pkg.replace("/", "__");
71
+ }
72
+ const subjects = /* @__PURE__ */ new Map();
73
+ function subjectFor(pkg) {
74
+ return subjects.get(pkg) ?? {
75
+ packageName: pkg,
76
+ requiredFile: OPTIONAL_REQUIRED_FILE[pkg],
77
+ version: null,
78
+ range: OPTIONAL_VERSION_RANGE[pkg]
79
+ };
80
+ }
81
+ /**
82
+ * True when the user disabled on-demand payloads.
83
+ *
84
+ * Uses the shared `parseBoolEnv`, not a local `raw === "1" || raw === "true"`:
85
+ * `GH_ROUTER_NO_OPTIONAL_INSTALL=TRUE` or `=yes` used to be unrecognised and
86
+ * silently *enabled* a 547 MB download, which is the worst possible way for an
87
+ * off switch to fail.
88
+ */
89
+ function optionalInstallDisabled(env = process.env) {
90
+ return parseBoolEnv(env.GH_ROUTER_NO_OPTIONAL_INSTALL) === true;
91
+ }
92
+ /** The `node_modules/<pkg>` directory inside an installed optional copy. */
93
+ function payloadDir(target, pkg) {
94
+ return path.join(target, "node_modules", ...subjectFor(pkg).packageName.split("/"));
95
+ }
96
+ /** Is `target` a complete payload? */
97
+ function completeAt(target, pkg) {
98
+ const dir = payloadDir(target, pkg);
99
+ return existsSync(path.join(dir, "package.json")) && existsSync(path.join(dir, subjectFor(pkg).requiredFile));
100
+ }
101
+ /**
102
+ * A usable installed copy of `pkg`, preferring the NEWEST version present.
103
+ *
104
+ * Synchronous on purpose: `resolveGrammarRoot()` and the rerank loader are
105
+ * called from synchronous contexts, and a promise here would force an `await`
106
+ * onto a path that must stay cheap. The listing is small (one entry per
107
+ * installed version, typically one).
108
+ *
109
+ * Returns the package directory (the thing a consumer imports from), not the
110
+ * `optional/<pkg>@<ver>` prefix.
111
+ */
112
+ function installedOptional(pkg) {
113
+ const [newest] = completeTargets(pkg);
114
+ return newest ? payloadDir(newest, pkg) : null;
115
+ }
116
+ /**
117
+ * Every COMPLETE `<root>/<pkg>@<version>` target dir, newest version first.
118
+ *
119
+ * Split out of `installedOptional` because two callers need the target dir
120
+ * itself rather than the package dir inside it: the upgrade check ("is the
121
+ * version we just resolved already here?") and the GC protection list ("spare
122
+ * the copy this process is using").
123
+ */
124
+ function completeTargets(pkg) {
125
+ const root = optionalRoot();
126
+ let names;
127
+ try {
128
+ names = readdirSync(root);
129
+ } catch {
130
+ return [];
131
+ }
132
+ const prefix = `${sanitized(pkg)}@`;
133
+ const candidates = names.filter((name) => name.startsWith(prefix) && !name.startsWith(".")).map((name) => ({
134
+ name,
135
+ version: name.slice(prefix.length)
136
+ })).filter((entry) => isVersionName(entry.version)).sort((a, b) => compareVersions(b.version, a.version));
137
+ const out = [];
138
+ for (const candidate of candidates) {
139
+ const target = path.join(root, candidate.name);
140
+ if (completeAt(target, pkg)) out.push(target);
141
+ }
142
+ return out;
143
+ }
144
+ /** Where `pkg@version` would live. */
145
+ function optionalTarget(pkg, version) {
146
+ return path.join(optionalRoot(), `${sanitized(pkg)}@${version}`);
147
+ }
148
+ /** `payloadDir` for exactly `pkg@version`, or null when that copy is not complete. */
149
+ function installedOptionalTarget(pkg, version) {
150
+ const target = optionalTarget(pkg, version);
151
+ return completeAt(target, pkg) ? payloadDir(target, pkg) : null;
152
+ }
153
+ const BACKOFF_HOURS = [
154
+ 1,
155
+ 6,
156
+ 24
157
+ ];
158
+ const KEEP_OPTIONAL_VERSIONS = 2;
159
+ const OPTIONAL_FLOOR_MS = 2592e6;
160
+ function statePath() {
161
+ return path.join(optionalRoot(), "install-state.json");
162
+ }
163
+ async function readState() {
164
+ try {
165
+ const raw = await readFileWithRetry(statePath(), { retryMissing: false });
166
+ const parsed = JSON.parse(raw);
167
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
168
+ } catch {
169
+ return {};
170
+ }
171
+ }
172
+ async function patchState(pkg, patch) {
173
+ try {
174
+ const state = await readState();
175
+ const next = {
176
+ ...state,
177
+ packages: {
178
+ ...state.packages ?? {},
179
+ [pkg]: {
180
+ ...state.packages?.[pkg] ?? {},
181
+ ...patch
182
+ }
183
+ }
184
+ };
185
+ for (const [key, value] of Object.entries(next.packages?.[pkg] ?? {})) if (value === void 0) delete next.packages[pkg][key];
186
+ await fs$1.mkdir(optionalRoot(), { recursive: true });
187
+ await writeFileAtomic(statePath(), `${JSON.stringify(next, null, 2)}\n`, { mode: 420 });
188
+ } catch (err) {
189
+ reportManagedDiagnostic("debug", `optional: could not write state: ${String(err)}`);
190
+ }
191
+ }
192
+ function nextAttemptAtFor(failures) {
193
+ const index = Math.min(Math.max(failures, 1), BACKOFF_HOURS.length) - 1;
194
+ return new Date(Date.now() + (BACKOFF_HOURS[index] ?? 24) * 36e5).toISOString();
195
+ }
196
+ /**
197
+ * Whether an attempt may start — a RESERVATION is not a backoff.
198
+ *
199
+ * `nextAttemptAt` is written before every attempt so two processes cannot both
200
+ * download a 500 MB payload, and it is also the ladder's output. Conflating them
201
+ * makes `github-router update` (issued while an on-demand install is still
202
+ * running, seconds after it reserved) report "backing off after a failed
203
+ * tree-sitter-wasms install" when nothing had failed. With `consecutiveFailures`
204
+ * still 0 the window is a reservation, so re-attempting is allowed; the loser of
205
+ * the rename race adopts the winner's payload.
206
+ */
207
+ async function mayAttemptNow(pkg) {
208
+ const entry = (await readState()).packages?.[pkg];
209
+ if ((entry?.consecutiveFailures ?? 0) === 0) return true;
210
+ if (!entry?.nextAttemptAt) return true;
211
+ const next = new Date(entry.nextAttemptAt).getTime();
212
+ return Number.isNaN(next) ? true : Date.now() >= next;
213
+ }
214
+ /**
215
+ * Make sure `pkg` is installed and return its directory.
216
+ *
217
+ * Fail-open and throttled: a failure is remembered on the standard ladder, so a
218
+ * permanently offline machine does not spawn an npm process per search.
219
+ */
220
+ async function ensureOptionalPackage(pkg, opts = {}) {
221
+ if (optionalInstallDisabled()) return {
222
+ dir: null,
223
+ detail: "GH_ROUTER_NO_OPTIONAL_INSTALL is set"
224
+ };
225
+ if (!opts.force && !await mayAttemptNow(pkg)) return {
226
+ dir: null,
227
+ detail: `backing off after a failed ${pkg} install`
228
+ };
229
+ const npmPath = resolveExecutable("npm");
230
+ if (!npmPath) {
231
+ const existing = installedOptional(pkg);
232
+ return existing ? { dir: existing } : {
233
+ dir: null,
234
+ detail: "npm is not on PATH"
235
+ };
236
+ }
237
+ const version = await resolveOptionalVersion(pkg, opts.registry);
238
+ const existing = version ? installedOptionalTarget(pkg, version) : installedOptional(pkg);
239
+ if (existing && !opts.force) return { dir: existing };
240
+ if (!version) {
241
+ await patchState(pkg, {
242
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
243
+ consecutiveFailures: 1,
244
+ nextAttemptAt: nextAttemptAtFor(1),
245
+ lastError: "could not resolve a version to install"
246
+ });
247
+ return {
248
+ dir: null,
249
+ detail: `could not resolve a version for ${pkg}`
250
+ };
251
+ }
252
+ const target = optionalTarget(pkg, version);
253
+ if (completeAt(target, pkg)) return {
254
+ dir: payloadDir(target, pkg),
255
+ installed: false
256
+ };
257
+ const [previousTarget] = completeTargets(pkg);
258
+ await patchState(pkg, {
259
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
260
+ nextAttemptAt: nextAttemptAtFor((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0)
261
+ });
262
+ try {
263
+ await installInto(pkg, version, target, npmPath, opts.registry, opts.signal);
264
+ await patchState(pkg, {
265
+ lastSuccessAt: (/* @__PURE__ */ new Date()).toISOString(),
266
+ consecutiveFailures: 0,
267
+ nextAttemptAt: void 0,
268
+ lastError: void 0,
269
+ version
270
+ });
271
+ const protect = [path.basename(target)];
272
+ if (previousTarget) protect.push(previousTarget);
273
+ await gcOptional(Date.now(), protect).catch(() => {});
274
+ return {
275
+ dir: payloadDir(target, pkg),
276
+ installed: true
277
+ };
278
+ } catch (err) {
279
+ const detail = err instanceof Error ? err.message : String(err);
280
+ const failures = ((await readState()).packages?.[pkg]?.consecutiveFailures ?? 0) + 1;
281
+ await patchState(pkg, {
282
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
283
+ consecutiveFailures: failures,
284
+ nextAttemptAt: nextAttemptAtFor(failures),
285
+ lastError: detail
286
+ });
287
+ return {
288
+ dir: null,
289
+ detail
290
+ };
291
+ }
292
+ }
293
+ /**
294
+ * Install `pkg@version` into `target` via a staging sibling.
295
+ *
296
+ * Same publish discipline as the managed installer (build in `.staging-*`,
297
+ * verify the entry, rename into place) and for the same reason: the target may
298
+ * be read concurrently by a running request, and a half-written payload that
299
+ * passes a directory-existence check is worse than no payload.
300
+ */
301
+ async function installInto(pkg, version, target, npmPath, registry, signal) {
302
+ const root = optionalRoot();
303
+ await fs$1.mkdir(root, { recursive: true });
304
+ const staging = path.join(root, `.staging-${process.pid}-${randomHex()}`);
305
+ await fs$1.mkdir(staging);
306
+ try {
307
+ const pkgJson = {
308
+ name: `gh-router-optional-${sanitized(pkg)}`,
309
+ private: true,
310
+ version: "0.0.0",
311
+ dependencies: { [subjectFor(pkg).packageName]: version }
312
+ };
313
+ await writeFileAtomic(path.join(staging, "package.json"), `${JSON.stringify(pkgJson, null, 2)}\n`, { mode: 420 });
314
+ const overrides = {};
315
+ if (registry) overrides.npm_config_registry = registry;
316
+ const { env } = buildNpmEnv(process.env, overrides);
317
+ reportManagedDiagnostic("info", `Installing optional ${pkg}@${version} (one-time)…`);
318
+ const { code, stderr } = await runCommandCapture([
319
+ npmPath,
320
+ "install",
321
+ "--no-global",
322
+ "--no-dry-run",
323
+ "--include=optional",
324
+ "--ignore-scripts",
325
+ "--no-audit",
326
+ "--no-fund",
327
+ "--loglevel=error",
328
+ ...registry ? [`--registry=${registry}`] : []
329
+ ], {
330
+ cwd: staging,
331
+ env,
332
+ timeoutMs: 18e5,
333
+ signal
334
+ });
335
+ if (code !== 0) throw new Error(`npm install ${pkg}@${version} failed (exit ${code}): ${stderr.slice(0, 400)}`);
336
+ if (!completeAt(staging, pkg)) throw new Error(`${subjectFor(pkg).packageName}@${version} installed but ${subjectFor(pkg).requiredFile} is missing`);
337
+ try {
338
+ const declared = JSON.parse(await fs$1.readFile(path.join(payloadDir(staging, pkg), "package.json"), "utf8")).version;
339
+ if (declared !== version) throw new Error(`${subjectFor(pkg).packageName}@${version} installed but its package.json declares ${JSON.stringify(declared)}; refusing to publish it`);
340
+ } catch (err) {
341
+ if (err instanceof Error && err.message.includes("refusing to publish")) throw err;
342
+ throw new Error(`${subjectFor(pkg).packageName}@${version} installed but its package.json is unreadable: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
343
+ }
344
+ const packages = await harvestProvenance(staging);
345
+ await writeFileAtomic(path.join(staging, ".installed.json"), `${JSON.stringify({
346
+ version,
347
+ packages,
348
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
349
+ }, null, 2)}\n`, { mode: 420 });
350
+ try {
351
+ await fs$1.rename(staging, target);
352
+ } catch (err) {
353
+ const code = err.code;
354
+ if (!(code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM" || code === "EACCES")) throw err;
355
+ if (completeAt(target, pkg)) return;
356
+ const aside = path.join(root, `.trash-${randomHex()}`);
357
+ let movedAside = false;
358
+ try {
359
+ await fs$1.rename(target, aside);
360
+ movedAside = true;
361
+ } catch (err) {
362
+ if (err.code !== "ENOENT") throw err;
363
+ }
364
+ try {
365
+ await fs$1.rename(staging, target);
366
+ } catch (err) {
367
+ if (movedAside) await fs$1.rename(aside, target).catch(() => {});
368
+ throw err;
369
+ }
370
+ }
371
+ } finally {
372
+ await fs$1.rm(staging, {
373
+ recursive: true,
374
+ force: true
375
+ }).catch(() => {});
376
+ }
377
+ }
378
+ /** `{ "<pkg>@<ver>": { resolved, integrity } }` from the prefix lockfile. */
379
+ async function harvestProvenance(prefix) {
380
+ const out = {};
381
+ try {
382
+ const raw = await fs$1.readFile(path.join(prefix, "package-lock.json"), "utf8");
383
+ const parsed = JSON.parse(raw);
384
+ for (const [key, entry] of Object.entries(parsed.packages ?? {})) {
385
+ if (!key.startsWith("node_modules/") || entry.link || !entry.version) continue;
386
+ const name = key.slice(13);
387
+ if (name.includes("node_modules/")) continue;
388
+ out[`${name}@${entry.version}`] = {
389
+ ...entry.resolved ? { resolved: entry.resolved } : {},
390
+ ...entry.integrity ? { integrity: entry.integrity } : {}
391
+ };
392
+ }
393
+ } catch {}
394
+ return out;
395
+ }
396
+ /** Newest published version of `pkg`, or null. */
397
+ async function resolveOptionalVersion(pkg, registry) {
398
+ const pinned = subjectFor(pkg).version;
399
+ if (pinned) return pinned;
400
+ const npmPath = resolveExecutable("npm");
401
+ if (!npmPath) return null;
402
+ const subject = subjectFor(pkg);
403
+ const spec = subject.range ? `${subject.packageName}@${subject.range}` : subject.packageName;
404
+ try {
405
+ const args = [
406
+ npmPath,
407
+ "view",
408
+ spec,
409
+ "version",
410
+ "--json",
411
+ "--silent"
412
+ ];
413
+ if (registry) args.push(`--registry=${registry}`);
414
+ const { stdout, code } = await runCommandCapture(args, { timeoutMs: 8e3 });
415
+ if (code !== 0) return null;
416
+ const value = lastVersionFromJson(stdout);
417
+ return value && VERSION_RE.test(value) ? value : null;
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+ /**
423
+ * The newest version in `npm view … --json` output, or null.
424
+ *
425
+ * The output is a bare `"1.2.3"` when the spec matches exactly one version and
426
+ * an ARRAY when a range matches several — and `npm view left-pad@^1.0.0 version`
427
+ * prints the array newest-LAST, so the last element is the answer in both cases.
428
+ * Parsing it as JSON rather than taking the last LINE is what makes a range with
429
+ * a hundred matches work; the old line-based read returned `"1.3.0"` (with the
430
+ * quotes) and the version regex then rejected it.
431
+ */
432
+ function lastVersionFromJson(stdout) {
433
+ const text = stdout.trim();
434
+ if (!text) return null;
435
+ try {
436
+ const parsed = JSON.parse(text);
437
+ if (typeof parsed === "string") return parsed;
438
+ if (Array.isArray(parsed)) for (let i = parsed.length - 1; i >= 0; i--) {
439
+ const entry = parsed[i];
440
+ if (typeof entry === "string") return entry;
441
+ }
442
+ return null;
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
447
+ /** Compare dotted versions on the leading three components. */
448
+ function compareVersions(a, b) {
449
+ const pa = a.split(/[.+-]/).map((n) => Number.parseInt(n, 10));
450
+ const pb = b.split(/[.+-]/).map((n) => Number.parseInt(n, 10));
451
+ for (let i = 0; i < 3; i++) {
452
+ const av = Number.isNaN(pa[i]) ? 0 : pa[i] ?? 0;
453
+ const bv = Number.isNaN(pb[i]) ? 0 : pb[i] ?? 0;
454
+ if (av !== bv) return av - bv;
455
+ }
456
+ return 0;
457
+ }
458
+ /**
459
+ * Keep the newest `KEEP_OPTIONAL_VERSIONS` copies per package and sweep
460
+ * abandoned staging/trash dirs.
461
+ *
462
+ * Deliberately more conservative than the managed GC (30-day floor, keep 2, and
463
+ * never remove the only copy of a package): each copy is up to 547 MB, so
464
+ * deleting the wrong one is expensive to undo.
465
+ *
466
+ * `protect` is the caller's knowledge of what is IN USE — directory names under
467
+ * the optional root that must survive this sweep. Nothing on disk records which
468
+ * copy a running process has loaded, and the two rules here cannot infer it: a
469
+ * process that has been up for weeks holds an old version that ranks below the
470
+ * two newest and is past the floor, and on POSIX `fs.rm` of a memory-mapped
471
+ * payload SUCCEEDS (`EBUSY` only saves Windows). The next lazy load in that
472
+ * process would then fail. The installer passes the copy it just wrote and the
473
+ * one it replaced.
474
+ */
475
+ async function gcOptional(now = Date.now(), protect = []) {
476
+ const root = optionalRoot();
477
+ let names;
478
+ try {
479
+ names = await fs$1.readdir(root);
480
+ } catch {
481
+ return {
482
+ removed: [],
483
+ removedTransient: []
484
+ };
485
+ }
486
+ const removed = [];
487
+ const removedTransient = [];
488
+ const versions = /* @__PURE__ */ new Map();
489
+ for (const name of names) {
490
+ const full = path.join(root, name);
491
+ let mtimeMs;
492
+ try {
493
+ mtimeMs = (await fs$1.stat(full)).mtimeMs;
494
+ } catch {
495
+ continue;
496
+ }
497
+ if (isTransientName(name)) {
498
+ if (now - mtimeMs > 36e5) {
499
+ await fs$1.rm(full, {
500
+ recursive: true,
501
+ force: true
502
+ }).catch(() => {});
503
+ removedTransient.push(name);
504
+ }
505
+ continue;
506
+ }
507
+ const match = /^(.+?)@(.+)$/.exec(name);
508
+ if (!match) continue;
509
+ if (!isVersionName(match[2])) continue;
510
+ const bucket = versions.get(match[1]) ?? [];
511
+ bucket.push({
512
+ name,
513
+ mtimeMs
514
+ });
515
+ versions.set(match[1], bucket);
516
+ }
517
+ const spared = new Set(protect);
518
+ for (const entries of versions.values()) {
519
+ entries.sort((a, b) => b.mtimeMs - a.mtimeMs);
520
+ for (const entry of entries.slice(KEEP_OPTIONAL_VERSIONS)) {
521
+ if (spared.has(entry.name)) continue;
522
+ if (now - entry.mtimeMs < OPTIONAL_FLOOR_MS) continue;
523
+ await fs$1.rm(path.join(root, entry.name), {
524
+ recursive: true,
525
+ force: true
526
+ }).then(() => removed.push(entry.name)).catch(() => {});
527
+ }
528
+ }
529
+ return {
530
+ removed,
531
+ removedTransient
532
+ };
533
+ }
534
+ /**
535
+ * Install ONE payload, whichever a caller asked for by name.
536
+ *
537
+ * Separate entry point from `ensureOptionalPackage` because the argument comes
538
+ * from a command line: an unknown name must be a reported no-op, never a crash
539
+ * and never "install everything because the filter matched nothing".
540
+ */
541
+ function isOptionalPackage(name) {
542
+ return OPTIONAL_PACKAGES.includes(name);
543
+ }
544
+ /** Set by {@link scheduleOptionalInstall}; one detached child per process. */
545
+ let scheduledInProcess = false;
546
+ /**
547
+ * Detached, best-effort install for a launch that noticed a gap.
548
+ *
549
+ * Detached because the spawn cost of two npm installs (minutes on a cold cache)
550
+ * must never be attributed to the command the user actually ran — and a search
551
+ * that triggered this proceeds on its BM25F fallback regardless.
552
+ */
553
+ function scheduleOptionalInstall(pkg, argv1 = process.argv[1]) {
554
+ if (optionalInstallDisabled()) return false;
555
+ if (typeof argv1 !== "string" || argv1.length === 0) return false;
556
+ if (scheduledInProcess) return false;
557
+ scheduledInProcess = true;
558
+ const missing = pkg;
559
+ (async () => {
560
+ try {
561
+ const { spawn } = await import("node:child_process");
562
+ const child = spawn(process.execPath, [
563
+ argv1,
564
+ "update",
565
+ "--quiet",
566
+ "--optional-only",
567
+ "--optional-pkg",
568
+ missing
569
+ ], {
570
+ detached: true,
571
+ stdio: "ignore",
572
+ windowsHide: true,
573
+ env: {
574
+ ...process.env,
575
+ GH_ROUTER_MANAGED_BACKGROUND: "1"
576
+ }
577
+ });
578
+ child.on("error", () => {});
579
+ child.unref();
580
+ } catch {}
581
+ })();
582
+ return true;
583
+ }
584
+ export { optionalInstallDisabled as a, isOptionalPackage as i, ensureOptionalPackage as n, scheduleOptionalInstall as o, installedOptional as r, OPTIONAL_PACKAGES as t };
585
+
586
+ //# sourceMappingURL=optional-DGAeyguL.js.map