github-router 0.3.378 → 0.3.380

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) 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-BR5Umj2L.js → attribution-settings-BJ1fjX7V.js} +10 -10
  10. package/dist/{attribution-settings-BR5Umj2L.js.map → attribution-settings-BJ1fjX7V.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--4O3wHRq.js → claude-BWwkOMi3.js} +26 -25
  19. package/dist/{claude--4O3wHRq.js.map → claude-BWwkOMi3.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-DHRMLpSo.js → codex-C6ix3BaY.js} +8 -7
  23. package/dist/{codex-DHRMLpSo.js.map → codex-C6ix3BaY.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-B0EFY6l7.js → pi-YhoA26wi.js} +718 -119
  99. package/dist/pi-YhoA26wi.js.map +1 -0
  100. package/dist/pi-foreign-artifacts-CNt6wQ1P.js +660 -0
  101. package/dist/pi-foreign-artifacts-CNt6wQ1P.js.map +1 -0
  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-C13q-9w0.js → serve-DrHAX2Bh.js} +15 -14
  117. package/dist/{serve-C13q-9w0.js.map → serve-DrHAX2Bh.js.map} +1 -1
  118. package/dist/{server-setup-CptI7SUT.js → server-setup-DLwejgVA.js} +12 -638
  119. package/dist/server-setup-DLwejgVA.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-DioCGjM8.js → start-DvV3Lbwy.js} +5 -4
  123. package/dist/{start-DioCGjM8.js.map → start-DvV3Lbwy.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-B0EFY6l7.js.map +0 -1
  158. package/dist/pi-memory-bridge-Dvj1T3e3.js +0 -403
  159. package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
  160. package/dist/provision-DPL8aGe2.js.map +0 -1
  161. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  162. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  163. package/dist/server-setup-CptI7SUT.js.map +0 -1
  164. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
@@ -0,0 +1,1548 @@
1
+ import { c as runCommandCapture, s as resolveExecutable } from "./exec-BC0MAnoA.js";
2
+ import { i as writeFileAtomic, n as readFileWithRetry } from "./atomic-file-Dif1kLKM.js";
3
+ import { n as withInstallLockResult } from "./update-lock-BmXx6QaR.js";
4
+ import { n as managedInstallDisabled, t as buildNpmEnv } from "./npm-env-H60tX76c.js";
5
+ import { t as reportManagedDiagnostic } from "./diagnostics-cXjCT_JQ.js";
6
+ import { _ as shimPath, a as cliBinDir, b as versionDir, c as installedMarkerPath, d as launcherPath, f as managedRoot, h as pointerPath, n as TRASH_RE, o as entryRelativeFor, p as npmPackageFor, t as STAGING_RE, u as isVersionName, v as stagingDir, y as trashDir } from "./paths-DK_b2ihK.js";
7
+ import { c as nextAttemptAtFor, l as patchInstallState, n as classifyOrigin, r as describeOrigin, s as mayAttemptNow, u as readInstallState } from "./origin-BXtpcKP9.js";
8
+ import consola from "consola";
9
+ import { realpathSync } from "node:fs";
10
+ import path from "node:path";
11
+ import fs$1 from "node:fs/promises";
12
+ import { spawn } from "node:child_process";
13
+ /**
14
+ * Reject an entry that would point at the bootstrap or escape the version dir.
15
+ *
16
+ * This is not paranoia about our own writer: the pointer is a plain file in a
17
+ * user-writable directory, and the launcher `import()`s whatever it names. A
18
+ * relative entry that climbs out (`../../..`) or is absolute would turn a
19
+ * corrupt pointer into arbitrary code execution on the next launch.
20
+ */
21
+ function isSafeEntry(entry) {
22
+ if (entry.length === 0) return false;
23
+ if (path.isAbsolute(entry) || entry.startsWith("/") || /^[A-Za-z]:/.test(entry)) return false;
24
+ const normalized = entry.replace(/\\/g, "/");
25
+ if (normalized.split("/").some((segment) => segment === "..")) return false;
26
+ if (normalized === "dist/bin.js" || normalized.endsWith(`/dist/bin.js`)) return false;
27
+ return true;
28
+ }
29
+ function kindOf(value) {
30
+ return value === "self" || value === "pi" ? value : null;
31
+ }
32
+ function nonEmptyString(value) {
33
+ return typeof value === "string" && value.length > 0 ? value : void 0;
34
+ }
35
+ /**
36
+ * Parse + validate a pointer body. Returns `null` for anything unusable, which
37
+ * every caller must treat identically to "no managed install".
38
+ */
39
+ function parsePointer(raw, kind) {
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(raw);
43
+ } catch {
44
+ return null;
45
+ }
46
+ if (typeof parsed !== "object" || parsed === null) return null;
47
+ if (parsed.schemaVersion !== 1) return null;
48
+ if (kindOf(parsed.kind) !== kind) return null;
49
+ const version = nonEmptyString(parsed.version);
50
+ if (!version) return null;
51
+ if (version.includes("/") || version.includes("\\") || version === "." || version === "..") return null;
52
+ const entry = nonEmptyString(parsed.entry) ?? entryRelativeFor(kind);
53
+ if (!isSafeEntry(entry)) return null;
54
+ return {
55
+ schemaVersion: 1,
56
+ kind,
57
+ version,
58
+ entry,
59
+ entryPath: path.join(versionDir(kind, version), entry),
60
+ runtimeHint: nonEmptyString(parsed.runtimeHint),
61
+ registry: nonEmptyString(parsed.registry),
62
+ installedAt: nonEmptyString(parsed.installedAt)
63
+ };
64
+ }
65
+ /**
66
+ * Read the pointer with the reason it was not usable.
67
+ *
68
+ * This is the primitive; `readPointer` is the ergonomic form for callers whose
69
+ * only decision is "run the payload or not". GC must use this one.
70
+ */
71
+ async function readPointerDetailed(kind, opts = {}) {
72
+ const file = pointerPath(kind);
73
+ let raw;
74
+ try {
75
+ raw = await readFileWithRetry(file, { retryMissing: false });
76
+ } catch (err) {
77
+ if (err.code === "ENOENT") return {
78
+ status: "absent",
79
+ pointer: null
80
+ };
81
+ onReadError(kind, err);
82
+ return {
83
+ status: "unreadable",
84
+ pointer: null
85
+ };
86
+ }
87
+ const pointer = parsePointer(raw, kind);
88
+ if (!pointer) {
89
+ onInvalid(kind, file);
90
+ return {
91
+ status: "absent",
92
+ pointer: null
93
+ };
94
+ }
95
+ if (opts.verifyEntry === false) return {
96
+ status: "ok",
97
+ pointer
98
+ };
99
+ try {
100
+ if (!(await fs$1.stat(pointer.entryPath)).isFile()) {
101
+ onMissingEntry(kind, pointer);
102
+ return {
103
+ status: "absent",
104
+ pointer: null
105
+ };
106
+ }
107
+ } catch {
108
+ onMissingEntry(kind, pointer);
109
+ return {
110
+ status: "absent",
111
+ pointer: null
112
+ };
113
+ }
114
+ return {
115
+ status: "ok",
116
+ pointer
117
+ };
118
+ }
119
+ /**
120
+ * Read the pointer, or `null`.
121
+ *
122
+ * A missing file is the normal first-run answer. Any other read error is a
123
+ * debug-level event, never a throw: a launch must not die because the pointer
124
+ * is unreadable, and the caller's fallback (run from the current tree) is always
125
+ * correct. The entry is stat'd by default, so a pointer to a GC'd or
126
+ * half-published payload is also reported as absent.
127
+ *
128
+ * Callers that DESTROY something based on this answer must use
129
+ * `readPointerDetailed` instead — see `PointerReadStatus`.
130
+ */
131
+ async function readPointer(kind, opts = {}) {
132
+ return (await readPointerDetailed(kind, opts)).pointer;
133
+ }
134
+ /**
135
+ * Write the pointer atomically.
136
+ *
137
+ * Temp + fsync + rename, with a bounded retry through a transient Windows lock
138
+ * (`atomic-file`).
139
+ *
140
+ * `atomic-file`'s exhausted-rename fallback re-reads the destination and accepts
141
+ * a byte-for-byte match as success. For a pointer that is not the "did I win?"
142
+ * question being swept under the rug: the body carries `version` + `installedAt`,
143
+ * so identical bytes mean the other writer published the SAME version at the
144
+ * same instant, and reporting success is correct. Two writers naming DIFFERENT
145
+ * versions can never byte-match, so the caller still learns who won.
146
+ */
147
+ async function writePointer(params) {
148
+ const entry = params.entry ?? entryRelativeFor(params.kind);
149
+ if (!isSafeEntry(entry)) throw new Error(`refusing to write an unsafe managed entry: ${entry}`);
150
+ const body = {
151
+ schemaVersion: 1,
152
+ kind: params.kind,
153
+ version: params.version,
154
+ entry,
155
+ ...params.runtimeHint ? { runtimeHint: params.runtimeHint } : {},
156
+ ...params.registry ? { registry: params.registry } : {},
157
+ installedAt: params.installedAt ?? (/* @__PURE__ */ new Date()).toISOString()
158
+ };
159
+ const file = pointerPath(params.kind);
160
+ await fs$1.mkdir(path.dirname(file), { recursive: true });
161
+ await writeFileAtomic(file, `${JSON.stringify(body, null, 2)}\n`, { mode: 420 });
162
+ return {
163
+ schemaVersion: 1,
164
+ kind: params.kind,
165
+ version: params.version,
166
+ entry,
167
+ entryPath: path.join(versionDir(params.kind, params.version), entry),
168
+ runtimeHint: params.runtimeHint,
169
+ registry: params.registry,
170
+ installedAt: body.installedAt
171
+ };
172
+ }
173
+ /** Remove the pointer (used by `update --force` and by tests). */
174
+ async function removePointer(kind) {
175
+ await fs$1.rm(pointerPath(kind), { force: true });
176
+ }
177
+ function onReadError(kind, err) {
178
+ reportManagedDiagnostic("debug", `managed[${kind}]: could not read current.json (${err instanceof Error ? err.message : String(err)}); treating as no managed install`);
179
+ }
180
+ function onInvalid(kind, file) {
181
+ reportManagedDiagnostic("warn", `managed[${kind}]: ${file} is not a valid pointer (schema/kind/entry); ignoring it. \`github-router update\` will rewrite it.`);
182
+ }
183
+ function onMissingEntry(kind, pointer) {
184
+ reportManagedDiagnostic("debug", `managed[${kind}]: pointer names ${pointer.version} but ${pointer.entryPath} is missing; treating as no managed install`);
185
+ }
186
+ async function readInstalledMarker(kind, version) {
187
+ try {
188
+ const raw = await readFileWithRetry(installedMarkerPath(kind, version), { retryMissing: false });
189
+ const parsed = JSON.parse(raw);
190
+ if (typeof parsed !== "object" || parsed === null) return null;
191
+ if (parsed.version !== version) return null;
192
+ return parsed;
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+ // src/lib/managed-install/install.ts
198
+ /**
199
+ * The managed installer: put one exact package version into
200
+ * `<APP_DIR>/m/<kind>/<version>/` and point `current.json` at it.
201
+ *
202
+ * The whole design is driven by three measured facts:
203
+ *
204
+ * 1. **`npx github-router@latest` re-extracts ~586 MB per published version**
205
+ * (16 releases in 31 days; `~/.npm/_npx` was 2.5 GB across 25 directories).
206
+ * Re-extraction, not re-download, is the 3 s cost — the tarball is cached.
207
+ * 2. **A live npm tree must never be mutated in place.** On Windows
208
+ * `npm install` over files a process holds open fails `EPERM`/`EBUSY`; this
209
+ * is why the `-g` path uses a detached post-exit waiter. So publishing is
210
+ * `rename()` of a fully-built sibling directory, which is atomic and touches
211
+ * nothing the running process has open.
212
+ * 3. **npm exits 0 on several env-driven no-ops** (`dry_run`, `global`,
213
+ * `workspaces`, `omit`). See `npm-env.ts` for the table. Verifying the
214
+ * entry file is therefore mandatory, not defensive.
215
+ *
216
+ * The staging directory lives INSIDE `<kind>/` on purpose: `rename` must be
217
+ * same-directory (no `EXDEV`, and people symlink node_modules-heavy dirs onto
218
+ * other volumes), and a `.`-prefixed name is what GC uses to tell a leftover
219
+ * attempt from a version.
220
+ */
221
+ /** Ceiling for one install. A cold 66 MB install is ~10 s; a slow mirror is minutes. */
222
+ const INSTALL_TIMEOUT_MS = 6e5;
223
+ /**
224
+ * Make `version` available and (optionally) live for `kind`.
225
+ *
226
+ * Idempotent and safe to run concurrently across processes: the second caller
227
+ * loses the lock, or loses the `rename` race and adopts the winner's payload.
228
+ */
229
+ async function ensureManagedInstall(opts) {
230
+ const { kind, version } = opts;
231
+ if (managedInstallDisabled()) return {
232
+ kind: "disabled",
233
+ version: null,
234
+ detail: "GH_ROUTER_NO_MANAGED_INSTALL is set"
235
+ };
236
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) return {
237
+ kind: "failed",
238
+ version: null,
239
+ detail: `invalid version "${version}"`
240
+ };
241
+ const npmPath = resolveExecutable("npm");
242
+ if (!npmPath) return {
243
+ kind: "no-npm",
244
+ version: null,
245
+ detail: "npm is not on PATH, so the managed install is unavailable; this launch runs from the current tree."
246
+ };
247
+ const state = await readInstallState(kind);
248
+ if (!opts.force && !mayAttemptNow(state)) return {
249
+ kind: "backoff",
250
+ version: null,
251
+ detail: `last attempt failed (${firstLine(state.lastError) ?? "unknown error"}); next try after ${state.nextAttemptAt}`
252
+ };
253
+ const reservation = nextAttemptAtFor((state.consecutiveFailures ?? 0) + 1);
254
+ await patchInstallState(kind, {
255
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
256
+ nextAttemptAt: reservation
257
+ });
258
+ const lock = await withInstallLockResult(`managed-${kind}.lock`, async () => {
259
+ if (await probeVersion(kind, version)) {
260
+ await activate(kind, version, opts.activate !== false);
261
+ return;
262
+ }
263
+ await installInto(kind, version, npmPath, opts.registry, opts.signal);
264
+ await activate(kind, version, opts.activate !== false);
265
+ });
266
+ if (lock.outcome === "failed") {
267
+ const lastError = errorText(lock.error);
268
+ const fresh = await readInstallState(kind);
269
+ if (fresh.lastSuccessAt !== state.lastSuccessAt) return {
270
+ kind: "failed",
271
+ version: null,
272
+ detail: lastError,
273
+ error: lock.error
274
+ };
275
+ const failures = (fresh.consecutiveFailures ?? 0) + 1;
276
+ await patchInstallState(kind, {
277
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
278
+ consecutiveFailures: failures,
279
+ nextAttemptAt: nextAttemptAtFor(failures),
280
+ lastError
281
+ });
282
+ return {
283
+ kind: "failed",
284
+ version: null,
285
+ detail: lastError,
286
+ error: lock.error
287
+ };
288
+ }
289
+ if (lock.outcome === "skipped") {
290
+ if ((await readInstallState(kind)).nextAttemptAt === reservation) await patchInstallState(kind, { nextAttemptAt: state.nextAttemptAt });
291
+ return {
292
+ kind: "locked",
293
+ version: null,
294
+ detail: "another github-router process is installing; retry shortly"
295
+ };
296
+ }
297
+ const live = await readPointer(kind, { verifyEntry: false });
298
+ const alreadySucceeded = (await readInstallState(kind)).lastSuccessAt !== void 0 && live?.version === version;
299
+ const stateWritten = await patchInstallState(kind, {
300
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
301
+ lastSuccessAt: (/* @__PURE__ */ new Date()).toISOString(),
302
+ consecutiveFailures: 0,
303
+ nextAttemptAt: void 0,
304
+ lastError: void 0
305
+ });
306
+ return {
307
+ kind: alreadySucceeded ? "adopted" : "installed",
308
+ version,
309
+ entryPath: live?.version === version ? live.entryPath : versionEntry(kind, version),
310
+ ...stateWritten ? {} : { detail: "installed, but install-state.json could not be written; the next launch may think the previous attempt failed" }
311
+ };
312
+ }
313
+ /**
314
+ * Publish `version` as the live payload.
315
+ *
316
+ * Reads the pointer back rather than trusting its own write: if a concurrent
317
+ * `update` published a different version first, the pointer is the winner and
318
+ * this call must not claim otherwise.
319
+ */
320
+ async function activate(kind, version, activateIt) {
321
+ const marker = await readInstalledMarker(kind, version);
322
+ if (!activateIt) return;
323
+ await writePointer({
324
+ kind,
325
+ version,
326
+ entry: entryRelativeFor(kind),
327
+ runtimeHint: process.execPath,
328
+ registry: marker?.registry,
329
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
330
+ });
331
+ }
332
+ /** The payload entry inside a published version dir. */
333
+ function versionEntry(kind, version) {
334
+ return path.join(versionDir(kind, version), entryRelativeFor(kind));
335
+ }
336
+ /**
337
+ * Is `version` already a complete payload?
338
+ *
339
+ * Both conditions are required. The marker alone is not enough (a killed
340
+ * `npm install` leaves whatever it got so far, and the marker is written by us
341
+ * only after verification), and the entry alone is not enough (a half-installed
342
+ * tree can contain the entry file while its dependencies are missing).
343
+ */
344
+ async function probeVersion(kind, version) {
345
+ const entryPath = versionEntry(kind, version);
346
+ if (!await readInstalledMarker(kind, version)) return null;
347
+ try {
348
+ if (!(await fs$1.stat(entryPath)).isFile()) return null;
349
+ } catch {
350
+ return null;
351
+ }
352
+ return {
353
+ version,
354
+ entryPath
355
+ };
356
+ }
357
+ /**
358
+ * Do the install and publish it.
359
+ *
360
+ * Everything happens in a fresh `.staging-<pid>-<rand>` sibling:
361
+ *
362
+ * 1. private `package.json` with an EXACT dependency (a range would make
363
+ * `adopt` and `npm view` disagree about what is live),
364
+ * 2. `npm install` with `cwd` = staging and a scrubbed env,
365
+ * 3. verify the entry, harvest provenance from `package-lock.json`, write the
366
+ * marker INSIDE staging,
367
+ * 4. `rename(staging → <version>)`, then verify again through the final path.
368
+ *
369
+ * The marker lands before the rename so a crash can never leave a
370
+ * complete-looking version dir without one — and a crash before the rename
371
+ * leaves only a `.staging-*` dir, which GC sweeps.
372
+ */
373
+ async function installInto(kind, version, npmPath, registry, signal) {
374
+ const root = managedRoot(kind);
375
+ await fs$1.mkdir(root, {
376
+ recursive: true,
377
+ mode: 448
378
+ });
379
+ const pkgName = npmPackageFor(kind);
380
+ const staging = stagingDir(kind);
381
+ await fs$1.mkdir(staging, { mode: 448 });
382
+ try {
383
+ const pkgJson = {
384
+ name: `gh-router-managed-${kind}`,
385
+ private: true,
386
+ version: "0.0.0",
387
+ dependencies: { [pkgName]: version }
388
+ };
389
+ await writeFileAtomic(path.join(staging, "package.json"), `${JSON.stringify(pkgJson, null, 2)}\n`, { mode: 420 });
390
+ const overrides = {};
391
+ if (registry) overrides.npm_config_registry = registry;
392
+ const scrub = buildNpmEnv(process.env, overrides);
393
+ reportManagedDiagnostic("debug", `managed[${kind}]: npm env kept=${scrub.kept.length} dropped=${scrub.dropped.join(",") || "none"}`);
394
+ reportManagedDiagnostic("info", `Installing ${pkgName}@${version} (one-time per version)…`);
395
+ const { code, stderr } = await runCommandCapture([
396
+ npmPath,
397
+ "install",
398
+ "--no-global",
399
+ "--no-dry-run",
400
+ "--include=optional",
401
+ "--ignore-scripts",
402
+ "--no-audit",
403
+ "--no-fund",
404
+ "--loglevel=error",
405
+ ...registry ? [`--registry=${registry}`] : []
406
+ ], {
407
+ cwd: staging,
408
+ env: scrub.env,
409
+ timeoutMs: INSTALL_TIMEOUT_MS,
410
+ signal
411
+ });
412
+ if (code !== 0) throw new Error(`npm install ${pkgName}@${version} failed (exit ${code}). This usually means no network, a corporate proxy, or a registry that does not carry the version.\n${stderr.slice(0, 600)}`);
413
+ await assertFile(path.join(staging, entryRelativeFor(kind)), `${pkgName}@${version} installed but its entry is missing`);
414
+ await assertInstalledVersion(path.join(staging, "node_modules", pkgName), pkgName, version);
415
+ const marker = {
416
+ version,
417
+ installedAt: (/* @__PURE__ */ new Date()).toISOString(),
418
+ runtime: process.execPath,
419
+ packages: await harvestProvenance(staging)
420
+ };
421
+ const resolvedRegistry = firstRegistry(marker) ?? registry;
422
+ if (resolvedRegistry) marker.registry = resolvedRegistry;
423
+ await writeFileAtomic(stagingMarkerPath(staging), `${JSON.stringify(marker, null, 2)}\n`, { mode: 420 });
424
+ if (await publishTo(staging, versionDir(kind, version), kind) === "raced") {
425
+ if (!await probeVersion(kind, version)) throw new Error(`another process published ${pkgName}@${version} incompletely; retry`);
426
+ }
427
+ await assertFile(versionEntry(kind, version), `${pkgName}@${version} published without its entry`);
428
+ } finally {
429
+ await fs$1.rm(staging, {
430
+ recursive: true,
431
+ force: true
432
+ }).catch(() => {});
433
+ }
434
+ }
435
+ /**
436
+ * `rename(staging → target)`, moving a corrupt existing tree aside first.
437
+ *
438
+ * Rename onto an existing non-empty directory is `ENOTEMPTY` on POSIX and
439
+ * `EPERM`/`EEXIST` on Windows — the exact `npm error code ENOTEMPTY` failure
440
+ * Claude Code's updater hit. Renaming the loser aside to a fresh name always
441
+ * works, so the published path is never a partially-overwritten tree.
442
+ */
443
+ async function publishTo(staging, target, kind) {
444
+ try {
445
+ await fs$1.rename(staging, target);
446
+ return "published";
447
+ } catch (err) {
448
+ const code = err.code;
449
+ if (code !== "ENOTEMPTY" && code !== "EEXIST" && code !== "EPERM" && code !== "EACCES") throw err;
450
+ }
451
+ if (await probeVersion(kind, path.basename(target))) return "raced";
452
+ const aside = trashDir(kind);
453
+ let movedAside = false;
454
+ try {
455
+ await fs$1.rename(target, aside);
456
+ movedAside = true;
457
+ } catch (err) {
458
+ if (err.code !== "ENOENT") throw err;
459
+ }
460
+ try {
461
+ await fs$1.rename(staging, target);
462
+ return "published";
463
+ } catch (err) {
464
+ const code = err.code;
465
+ if (code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM" || code === "EACCES") return "raced";
466
+ let restored = false;
467
+ if (movedAside) restored = await fs$1.rename(aside, target).then(() => true, () => false);
468
+ if (!restored) {
469
+ const live = await readPointer(kind, { verifyEntry: false });
470
+ if (live && live.version === path.basename(target)) await removePointer(kind).catch(() => {});
471
+ }
472
+ throw err;
473
+ }
474
+ }
475
+ /**
476
+ * Assert `dir`'s `package.json` declares `version`.
477
+ *
478
+ * Deliberately a THROW, not a warning: the caller writes the marker (which
479
+ * certifies completeness forever) immediately after this, so "close enough" here
480
+ * means a wrong or incomplete payload becomes the live one.
481
+ */
482
+ async function assertInstalledVersion(dir, pkgName, version) {
483
+ const manifestPath = path.join(dir, "package.json");
484
+ let declared;
485
+ try {
486
+ declared = JSON.parse(await fs$1.readFile(manifestPath, "utf8")).version;
487
+ } catch {
488
+ throw new Error(`${pkgName}@${version} installed but ${manifestPath} is missing or unreadable`);
489
+ }
490
+ if (declared !== version) throw new Error(`${pkgName}@${version} installed but its package.json declares ${JSON.stringify(declared)}; refusing to publish it`);
491
+ }
492
+ /** The `.installed.json` path inside a staging dir (same name the final dir uses). */
493
+ function stagingMarkerPath(staging) {
494
+ return path.join(staging, ".installed.json");
495
+ }
496
+ /** `{ "<pkg>@<version>": { resolved, integrity } }` from the prefix lockfile. */
497
+ async function harvestProvenance(prefix) {
498
+ const out = {};
499
+ try {
500
+ const raw = await fs$1.readFile(path.join(prefix, "package-lock.json"), "utf8");
501
+ const parsed = JSON.parse(raw);
502
+ for (const [key, entry] of Object.entries(parsed.packages ?? {})) {
503
+ if (!key.startsWith("node_modules/") || entry.link) continue;
504
+ const name = key.slice(13);
505
+ if (name.includes("node_modules/")) continue;
506
+ if (!entry.version) continue;
507
+ out[`${name}@${entry.version}`] = {
508
+ ...entry.resolved ? { resolved: entry.resolved } : {},
509
+ ...entry.integrity ? { integrity: entry.integrity } : {}
510
+ };
511
+ }
512
+ } catch {}
513
+ return out;
514
+ }
515
+ /**
516
+ * The registry a payload actually came from, derived from a tarball URL.
517
+ *
518
+ * NOT `new URL(resolved).origin`: a corporate mirror keeps its path
519
+ * (`https://nexus.example/repository/npm-group/github-router/-/github-router-1.2.3.tgz`),
520
+ * and truncating to the origin writes `https://nexus.example/` into `current.json`
521
+ * and `install-state.json` as "the registry this install used". Anyone — a support
522
+ * thread, a future reader, `update --check` — who then fetches from it gets a 404.
523
+ *
524
+ * The npm registry layout makes the answer exact: everything before the
525
+ * `<pkg>/-/<pkg>-<version>.tgz` segment is the registry. When that shape is not
526
+ * recognisable, prefer no answer over a wrong one.
527
+ */
528
+ function registryFromResolved(resolved) {
529
+ try {
530
+ const url = new URL(resolved);
531
+ const marker = url.pathname.lastIndexOf("/-/");
532
+ if (marker <= 0) return void 0;
533
+ const basePath = url.pathname.slice(0, marker + 1);
534
+ return `${url.origin}${basePath}`;
535
+ } catch {
536
+ return;
537
+ }
538
+ }
539
+ function firstRegistry(marker) {
540
+ for (const entry of Object.values(marker.packages ?? {})) {
541
+ if (!entry.resolved) continue;
542
+ const registry = registryFromResolved(entry.resolved);
543
+ if (registry) return registry;
544
+ }
545
+ }
546
+ async function assertFile(file, message) {
547
+ try {
548
+ if ((await fs$1.stat(file)).isFile()) return;
549
+ } catch {}
550
+ throw new Error(message);
551
+ }
552
+ function errorText(err) {
553
+ if (err instanceof Error) return err.message.slice(0, 800);
554
+ return String(err).slice(0, 800);
555
+ }
556
+ /** First non-empty line of a multi-line diagnostic, or null. */
557
+ function firstLine(text) {
558
+ if (!text) return null;
559
+ const line = text.split(/\r?\n/).find((part) => part.trim().length > 0);
560
+ return line ? line.trim() : null;
561
+ }
562
+ /**
563
+ * Sweep leftover attempts and old payloads.
564
+ *
565
+ * Non-blocking and best-effort by contract: every removal error is swallowed
566
+ * (`EBUSY` on Windows is normal while a virus scanner holds a file) and retried
567
+ * on the next boot. The rules:
568
+ *
569
+ * - `.staging-*` / `.trash-*` older than an hour: delete.
570
+ * - a `<version>` dir: delete only if it is NOT the pointer's, NOT one of the
571
+ * two newest, AND older than the 7-day floor.
572
+ *
573
+ * The floor exists because a live session's hooks name its payload dir
574
+ * (`--package-root`), so a version can be in use long after the pointer moved
575
+ * on. Bounding that at a week is the deliberate trade recorded in the plan.
576
+ */
577
+ async function gcManaged(kind, now = Date.now()) {
578
+ const report = {
579
+ removedStaging: [],
580
+ removedTrash: [],
581
+ removedTransient: [],
582
+ removedVersions: [],
583
+ kept: []
584
+ };
585
+ const root = managedRoot(kind);
586
+ let names;
587
+ try {
588
+ names = await fs$1.readdir(root);
589
+ } catch {
590
+ return report;
591
+ }
592
+ const pointerRead = await readPointerDetailed(kind, { verifyEntry: false });
593
+ if (pointerRead.status === "unreadable") return report;
594
+ const live = pointerRead.pointer;
595
+ const versions = [];
596
+ for (const name of names) {
597
+ const full = path.join(root, name);
598
+ if (STAGING_RE.test(name)) {
599
+ const age = await ageMs(full, now);
600
+ if (age !== null && age > 36e5) {
601
+ if (await removeDir(full)) report.removedStaging.push(name);
602
+ }
603
+ continue;
604
+ }
605
+ if (TRASH_RE.test(name)) {
606
+ const age = await ageMs(full, now);
607
+ if (age !== null && age > 36e5) {
608
+ if (await removeDir(full)) report.removedTrash.push(name);
609
+ }
610
+ continue;
611
+ }
612
+ if (name.endsWith(".tmp")) {
613
+ const age = await ageMs(full, now);
614
+ if (age !== null && age > 36e5) {
615
+ if (await removeFile(full)) report.removedTransient.push(name);
616
+ }
617
+ continue;
618
+ }
619
+ if (!isVersionName(name)) continue;
620
+ const age = await ageMs(full, now) ?? 0;
621
+ versions.push({
622
+ name,
623
+ modifiedAt: now - age,
624
+ age
625
+ });
626
+ }
627
+ versions.sort((a, b) => a.modifiedAt === b.modifiedAt ? compareVersions(b.name, a.name) : b.modifiedAt - a.modifiedAt);
628
+ const protectedNames = /* @__PURE__ */ new Set();
629
+ if (live) protectedNames.add(live.version);
630
+ for (const entry of versions.slice(0, 2)) protectedNames.add(entry.name);
631
+ for (const entry of versions) {
632
+ if (protectedNames.has(entry.name)) {
633
+ report.kept.push({
634
+ name: entry.name,
635
+ reason: "newest-or-live"
636
+ });
637
+ continue;
638
+ }
639
+ if (entry.age < 6048e5) {
640
+ report.kept.push({
641
+ name: entry.name,
642
+ reason: "within-7-day-floor"
643
+ });
644
+ continue;
645
+ }
646
+ if (await removeDir(path.join(root, entry.name))) report.removedVersions.push(entry.name);
647
+ else report.kept.push({
648
+ name: entry.name,
649
+ reason: "removal-failed"
650
+ });
651
+ }
652
+ return report;
653
+ }
654
+ async function ageMs(full, now) {
655
+ try {
656
+ return now - (await fs$1.stat(full)).mtimeMs;
657
+ } catch {
658
+ return null;
659
+ }
660
+ }
661
+ async function removeFile(full) {
662
+ try {
663
+ await fs$1.rm(full, { force: true });
664
+ return true;
665
+ } catch (err) {
666
+ reportManagedDiagnostic("debug", `managed: could not remove ${full}: ${String(err)}`);
667
+ return false;
668
+ }
669
+ }
670
+ async function removeDir(full) {
671
+ try {
672
+ await fs$1.rm(full, {
673
+ recursive: true,
674
+ force: true
675
+ });
676
+ return true;
677
+ } catch (err) {
678
+ reportManagedDiagnostic("debug", `managed: could not remove ${full}: ${String(err)}`);
679
+ return false;
680
+ }
681
+ }
682
+ function compareVersions(a, b) {
683
+ const pa = a.split(/[.+-]/).map((n) => Number.parseInt(n, 10));
684
+ const pb = b.split(/[.+-]/).map((n) => Number.parseInt(n, 10));
685
+ for (let i = 0; i < 3; i++) {
686
+ const av = Number.isNaN(pa[i]) ? 0 : pa[i] ?? 0;
687
+ const bv = Number.isNaN(pb[i]) ? 0 : pb[i] ?? 0;
688
+ if (av !== bv) return av - bv;
689
+ }
690
+ return 0;
691
+ }
692
+ // src/lib/managed-install/launcher.ts
693
+ /**
694
+ * The stable launcher: `<APP_DIR>/m/<kind>/launcher.mjs`.
695
+ *
696
+ * This file is the entire point of the managed layout. Shims (and anything else
697
+ * that wants a version-independent path) exec THIS, and it figures out which
698
+ * concrete payload is live by reading `current.json` and re-execing it. It is
699
+ * written once and never swapped, so a shim baked onto PATH years ago keeps
700
+ * working across every future version — which is exactly the property
701
+ * `claude`'s native installer has and `npx` does not.
702
+ *
703
+ * It is generated as SOURCE TEXT rather than built as a bundle entry, and that
704
+ * is deliberate:
705
+ *
706
+ * - it must survive when the package tree it came from is deleted (that is the
707
+ * `bunx`/`npx` case this feature exists for), so it cannot carry a single
708
+ * non-`node:` import;
709
+ * - it is ~150 lines of self-contained logic, so a build entry would add a
710
+ * fourth bundle, a sidecar digest, and a publish step for no benefit;
711
+ * - `tests/isolated/managed-launcher.test.ts` runs the real emitted file under
712
+ * the real `node`, on every platform CI has, which pins behaviour harder than
713
+ * a typecheck would.
714
+ *
715
+ * What it must never do: resolve the version itself, install anything, or touch
716
+ * the network. Every failure has to be a message plus a non-zero exit, because
717
+ * the caller is a shell or a hook with no way to recover.
718
+ */
719
+ /**
720
+ * Marker line every generated file carries.
721
+ *
722
+ * `shim.ts` uses the same idea for its guards: a file is only ever overwritten
723
+ * if it contains this marker, so a user's own script that happens to sit at the
724
+ * same path is never clobbered. Keep the two constants in sync — `LAUNCHER_BODY`
725
+ * includes it as a comment, and `hasManagedMarker()` is the reader.
726
+ */
727
+ const MANAGED_MARKER = "github-router-managed-file";
728
+ function hasManagedMarker(content) {
729
+ return content.includes(MANAGED_MARKER);
730
+ }
731
+ /**
732
+ * The launcher program.
733
+ *
734
+ * Constraints on the body (all enforced by tests):
735
+ * - no top-level import other than `node:` builtins;
736
+ * - no reference to `github-router` package code;
737
+ * - must run on Node 20 and on bun.
738
+ */
739
+ const LAUNCHER_BODY = String.raw`
740
+ // ${MANAGED_MARKER} — generated by \`github-router update\`. Do not edit.
741
+ // Resolves <dir>/current.json and re-execs the payload it names.
742
+ import { spawn } from "node:child_process"
743
+ import { readFileSync, existsSync, statSync, writeSync } from "node:fs"
744
+ import { dirname, join, isAbsolute } from "node:path"
745
+ import { fileURLToPath } from "node:url"
746
+
747
+ const here = dirname(fileURLToPath(import.meta.url))
748
+ // Test seams, gated behind an explicit opt-in. Ungated they are a footgun with a
749
+ // security edge: a stale GH_ROUTER_MANAGED_ENTRY in a user's environment would
750
+ // execute an ARBITRARY file on every launch (it bypasses the traversal/absolute
751
+ // checks below, which is the whole point of an override), and a stale
752
+ // GH_ROUTER_MANAGED_DRY_RUN would make every hook exit 0 having printed JSON
753
+ // instead of doing its work — a success that means nothing.
754
+ const TEST_SEAMS = process.env.GH_ROUTER_MANAGED_TEST === "1"
755
+ const ENTRY_OVERRIDE = TEST_SEAMS ? process.env.GH_ROUTER_MANAGED_ENTRY : undefined
756
+ const DRY_RUN = TEST_SEAMS && process.env.GH_ROUTER_MANAGED_DRY_RUN === "1"
757
+
758
+ function fail(message, code) {
759
+ // writeSync, not process.stderr.write: on a PIPE stderr is asynchronous, and
760
+ // process.exit tears the loop down before the bytes reach the reader — so a
761
+ // hook or a CI step saw a bare exit 78 with no explanation, which is precisely
762
+ // the case this message exists for.
763
+ try {
764
+ writeSync(2, "github-router: " + message + "\n")
765
+ } catch {
766
+ // Best effort: still exit with the code.
767
+ }
768
+ process.exit(typeof code === "number" ? code : 1)
769
+ }
770
+
771
+ function readPointer() {
772
+ const file = join(here, "current.json")
773
+ let raw
774
+ try {
775
+ raw = readFileSync(file, "utf8")
776
+ } catch (err) {
777
+ if (err && err.code === "ENOENT") {
778
+ fail(
779
+ "no managed install is active (" + file + " is missing).\n" +
780
+ " Run: github-router update\n" +
781
+ " Or reinstall: npm install -g github-router",
782
+ 78
783
+ )
784
+ }
785
+ fail("could not read " + file + ": " + (err && err.message ? err.message : String(err)))
786
+ }
787
+ let parsed
788
+ try {
789
+ parsed = JSON.parse(raw)
790
+ } catch {
791
+ fail(file + " is not valid JSON. Run: github-router update")
792
+ }
793
+ if (!parsed || typeof parsed !== "object") fail(file + " is not a pointer object. Run: github-router update")
794
+ if (parsed.schemaVersion !== 1) {
795
+ fail(
796
+ "unsupported pointer schema " + String(parsed.schemaVersion) + ". This launcher is too old for the installed layout; reinstall github-router.",
797
+ 78
798
+ )
799
+ }
800
+ if (typeof parsed.version !== "string" || typeof parsed.entry !== "string") {
801
+ fail(file + " is missing its version/entry fields. Run: github-router update")
802
+ }
803
+ // A version string becomes a path segment: never let it climb out.
804
+ if (parsed.version.indexOf("/") >= 0 || parsed.version.indexOf("\\") >= 0 || parsed.version.indexOf("..") >= 0) {
805
+ fail(file + " names an invalid version. Run: github-router update")
806
+ }
807
+ // The entry becomes an argv the runtime executes. Absolute paths and
808
+ // traversal are refused for the same reason the writer refuses them.
809
+ if (isAbsolute(parsed.entry) || parsed.entry.split(/[\\/]/).indexOf("..") >= 0) {
810
+ fail(file + " names an unsafe entry. Run: github-router update")
811
+ }
812
+ return parsed
813
+ }
814
+
815
+ /**
816
+ * Pick the runtime for the payload.
817
+ *
818
+ * Order: whatever is already running this launcher, then the pointer's
819
+ * \`runtimeHint\`, then \`node\` on PATH.
820
+ *
821
+ * \`process.execPath\` comes first because it is the only candidate whose version
822
+ * we can check for free: spawning \`node --version\` on every launch is a real
823
+ * cost, and this file runs on every CLI invocation a session makes. That check
824
+ * matters when a \`bunx\` user's bun reports a node-compat major below the
825
+ * payload's floor — rare, but it is the difference between a clear engine error
826
+ * and a mystery crash.
827
+ *
828
+ * \`runtimeHint\` is only a FALLBACK, never authoritative: nvm/fnm/volta/brew
829
+ * delete the previous interpreter on every upgrade, so trusting a recorded
830
+ * absolute path is exactly how a launcher "stops working after a node upgrade".
831
+ */
832
+ function isFile(candidate) {
833
+ try {
834
+ return typeof candidate === "string" && candidate.length > 0 && statSync(candidate).isFile()
835
+ } catch {
836
+ return false
837
+ }
838
+ }
839
+
840
+ function runningNodeMajor() {
841
+ const running = process.versions && process.versions.node
842
+ if (!running) return null
843
+ const major = Number(String(running).split(".")[0])
844
+ return Number.isNaN(major) ? null : major
845
+ }
846
+
847
+ /** \`engines.node\` major from the PAYLOAD's package.json, or null. */
848
+ function enginesNodeMajor(entryPath) {
849
+ let dir = dirname(entryPath)
850
+ for (let i = 0; i < 6; i++) {
851
+ const candidate = join(dir, "package.json")
852
+ if (existsSync(candidate)) {
853
+ try {
854
+ const pkg = JSON.parse(readFileSync(candidate, "utf8"))
855
+ if (pkg && typeof pkg.name === "string") {
856
+ const range = pkg.engines && pkg.engines.node
857
+ if (typeof range !== "string") return null
858
+ const match = range.match(/(\d+)/)
859
+ return match ? Number(match[1]) : null
860
+ }
861
+ } catch {
862
+ // Keep walking.
863
+ }
864
+ }
865
+ const parent = dirname(dir)
866
+ if (parent === dir) break
867
+ dir = parent
868
+ }
869
+ return null
870
+ }
871
+
872
+ function chooseRuntime(pointer, entryPath) {
873
+ const minMajor = enginesNodeMajor(entryPath)
874
+ const mine = runningNodeMajor()
875
+ // Unknown floor or unknown running version: do not filter, keep the runtime
876
+ // the user chose. A wrong guess here is worse than an engine mismatch.
877
+ const mineOk = minMajor === null || mine === null || mine >= minMajor
878
+ if (mineOk && isFile(process.execPath)) return process.execPath
879
+
880
+ if (isFile(pointer.runtimeHint)) return pointer.runtimeHint
881
+
882
+ const pathEnv = process.env.PATH || ""
883
+ const sep = process.platform === "win32" ? ";" : ":"
884
+ const names = process.platform === "win32" ? ["node.exe", "node"] : ["node"]
885
+ for (const dir of pathEnv.split(sep)) {
886
+ if (!dir) continue
887
+ for (const name of names) {
888
+ const candidate = join(dir, name)
889
+ if (isFile(candidate)) return candidate
890
+ }
891
+ }
892
+ // Nothing better: let the spawn fail with its own message.
893
+ return process.execPath
894
+ }
895
+
896
+ const pointer = readPointer()
897
+ const versionDir = join(here, pointer.version)
898
+ const entryPath = ENTRY_OVERRIDE || join(versionDir, pointer.entry)
899
+
900
+ if (!existsSync(entryPath)) {
901
+ fail(
902
+ "the live payload is missing: " + entryPath + "\n" +
903
+ " The install is incomplete. Run: github-router update",
904
+ 78
905
+ )
906
+ }
907
+
908
+ if (DRY_RUN) {
909
+ // Test/diagnostic hook: report what WOULD run, without running it. Used by
910
+ // the managed-install e2e test to prove a launch landed on the managed tree
911
+ // without parsing debug logs.
912
+ process.stdout.write(JSON.stringify({ version: pointer.version, entryPath }) + "\n")
913
+ process.exit(0)
914
+ }
915
+
916
+ const runtime = chooseRuntime(pointer, entryPath)
917
+
918
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"]
919
+ const SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 }
920
+ // Registered BEFORE the spawn: a signal that arrives between \`spawn\` returning
921
+ // and the handler being installed kills this launcher with the default
922
+ // disposition and leaves the payload running with nobody forwarding to it.
923
+ let child = null
924
+ for (const signal of SIGNALS) {
925
+ try {
926
+ process.on(signal, () => {
927
+ try {
928
+ if (child) child.kill(signal)
929
+ } catch {
930
+ // already gone
931
+ }
932
+ })
933
+ } catch {
934
+ // Platform without this signal.
935
+ }
936
+ }
937
+
938
+ try {
939
+ child = spawn(runtime, [entryPath, ...process.argv.slice(2)], {
940
+ stdio: "inherit",
941
+ windowsHide: true,
942
+ env: process.env,
943
+ })
944
+ } catch (err) {
945
+ fail("could not start " + runtime + ": " + (err && err.message ? err.message : String(err)))
946
+ }
947
+
948
+ child.on("error", (err) => {
949
+ fail("could not start " + runtime + ": " + (err && err.message ? err.message : String(err)))
950
+ })
951
+
952
+ child.on("exit", (code, signal) => {
953
+ if (signal) {
954
+ // Mirror the child's fate so a supervisor (systemd, a CI runner, a hook
955
+ // wrapper) sees a signal death rather than a generic exit 1.
956
+ //
957
+ // The forwarding handlers above MUST go first: Node does not re-raise a
958
+ // signal that has a listener, so leaving them installed makes the re-raise a
959
+ // no-op that falls through to exit 0 — an interrupted launch reports success.
960
+ // 128+n is also set, for a signal that cannot be re-raised at all.
961
+ for (const name of SIGNALS) process.removeAllListeners(name)
962
+ process.exitCode = 128 + (SIGNAL_NUMBERS[signal] || 0)
963
+ try {
964
+ process.kill(process.pid, signal)
965
+ } catch {
966
+ process.exit(process.exitCode)
967
+ }
968
+ return
969
+ }
970
+ process.exit(typeof code === "number" ? code : 1)
971
+ })
972
+ `.trimStart();
973
+ /** The exact bytes written to `launcher.mjs` for `kind`. */
974
+ function launcherSource() {
975
+ return LAUNCHER_BODY.endsWith("\n") ? LAUNCHER_BODY : `${LAUNCHER_BODY}\n`;
976
+ }
977
+ /**
978
+ * Write the launcher if it is absent or stale.
979
+ *
980
+ * Content-checked, not existence-checked: a future release can improve the
981
+ * launcher (a new signal, a new runtime rule) and have it take effect on the
982
+ * next run of any version, without a migration step. It is safe to rewrite
983
+ * because nothing holds this file open — the shims exec it and the process
984
+ * exits when the payload does — and `writeFileAtomic` means a concurrent launch
985
+ * sees either the old bytes or the new bytes, never a truncation.
986
+ */
987
+ async function ensureLauncher(kind) {
988
+ const file = launcherPath(kind);
989
+ const desired = launcherSource();
990
+ try {
991
+ if (await fs$1.readFile(file, "utf8") === desired) return {
992
+ path: file,
993
+ written: false
994
+ };
995
+ } catch {}
996
+ await fs$1.mkdir(managedRoot(kind), { recursive: true });
997
+ try {
998
+ await writeFileAtomic(file, desired, { mode: 493 });
999
+ } catch (err) {
1000
+ consola.warn(`Could not write the managed launcher ${file}:`, err);
1001
+ return {
1002
+ path: file,
1003
+ written: false
1004
+ };
1005
+ }
1006
+ return {
1007
+ path: file,
1008
+ written: true
1009
+ };
1010
+ }
1011
+ // src/lib/managed-install/shim.ts
1012
+ /**
1013
+ * PATH shims for the managed install.
1014
+ *
1015
+ * The launcher (`<APP_DIR>/m/<kind>/launcher.mjs`) is the stable thing; a shim is
1016
+ * just the name a shell can type. Two rules make these safe to write:
1017
+ *
1018
+ * 1. **Marker-required.** A file is only overwritten if it carries
1019
+ * `MANAGED_MARKER`. Anything else is left alone with a warning, because the
1020
+ * alternative is deleting a user's own `github-router` script — the
1021
+ * `lstat`-then-refuse discipline already used for `.github-router-managed`
1022
+ * (`src/lib/paths.ts:786-812`).
1023
+ * 2. **Never in `PATHS.TOOLBELT_BIN_DIR`.** `pruneUnexpected`
1024
+ * (`src/lib/toolbelt/provision.ts:96-110`) deletes anything not in its
1025
+ * manifest, so a shim placed there is deleted on the next launch — a bug that
1026
+ * only shows up on the second run.
1027
+ *
1028
+ * The directory is `<APP_DIR>/cli-bin` (`paths.ts` → `cliBinDir`), NOT
1029
+ * `~/.local/bin`: the app dir is the one location the router already owns and
1030
+ * GC already understands, and writing into `~/.local/bin` would mean guessing
1031
+ * whether that directory belongs to us. The consequence is that the directory is
1032
+ * usually NOT on PATH, so `update` prints one copy-pasteable line (`pathHint`)
1033
+ * instead of editing a shell rc file we cannot verify.
1034
+ *
1035
+ * The shims intentionally do NOT hardcode a runtime. They exec the launcher with
1036
+ * whatever `node`/`bun` the shell resolves, so a future nvm switch keeps working
1037
+ * and there is no baked interpreter path to go stale.
1038
+ */
1039
+ /** The command names we own. `github-router` for self, `pi` only when managed. */
1040
+ function shimBases(kind) {
1041
+ return kind === "self" ? ["github-router"] : ["pi"];
1042
+ }
1043
+ /**
1044
+ * POSIX shim body.
1045
+ *
1046
+ * `exec` (not a subshell) so the payload inherits the caller's stdio, exit
1047
+ * status, and signal disposition — a hook that runs
1048
+ * `github-router internal-…` must see the child's exit code directly.
1049
+ *
1050
+ * The runtime is chosen by trying the launcher's own candidates rather than
1051
+ * hardcoding: `command -v node` then `command -v bun`. If neither exists the
1052
+ * message names the missing dependency instead of failing with "not found".
1053
+ */
1054
+ function posixShim(launcher) {
1055
+ return `#!/bin/sh
1056
+ # ${MANAGED_MARKER} — generated by \`github-router update\`. Do not edit.
1057
+ # Re-run \`github-router update\` to refresh; deleting this file is safe.
1058
+ set -e
1059
+ LAUNCHER="${launcher}"
1060
+ if [ ! -f "$LAUNCHER" ]; then
1061
+ echo "github-router: the managed launcher is missing ($LAUNCHER)." >&2
1062
+ echo " Reinstall: npm install -g github-router" >&2
1063
+ exit 78
1064
+ fi
1065
+ for RUNTIME in node bun; do
1066
+ if command -v "$RUNTIME" >/dev/null 2>&1; then
1067
+ exec "$RUNTIME" "$LAUNCHER" "$@"
1068
+ fi
1069
+ done
1070
+ echo "github-router: neither node nor bun is on PATH." >&2
1071
+ echo " Install Node.js 20+ (https://nodejs.org) and try again." >&2
1072
+ exit 127
1073
+ `;
1074
+ }
1075
+ /**
1076
+ * Windows `.cmd` shim.
1077
+ *
1078
+ * `%~dp0` is deliberately NOT used: the shim lives in `<APP_DIR>\\cli-bin` while
1079
+ * the launcher lives in `<APP_DIR>\\m\\<kind>`, so the absolute path is baked in
1080
+ * (and rewritten by `github-router update` if the app dir ever moves).
1081
+ *
1082
+ * `where` (not `which`) is the Windows lookup, and `>nul 2>nul` keeps a missing
1083
+ * candidate from printing. `%*` forwards the original argv verbatim, which is
1084
+ * what `buildExecInvocation`'s quoting expects downstream.
1085
+ */
1086
+ function cmdShim(launcher) {
1087
+ return `@echo off\r
1088
+ rem ${MANAGED_MARKER} - generated by github-router update. Do not edit.\r
1089
+ setlocal\r
1090
+ set "LAUNCHER=${launcher}"\r
1091
+ if not exist "%LAUNCHER%" (\r
1092
+ echo github-router: the managed launcher is missing ^("%LAUNCHER%^). 1>&2\r
1093
+ echo Reinstall: npm install -g github-router 1>&2\r
1094
+ exit /b 78\r
1095
+ )\r
1096
+ rem %ERRORLEVEL% inside a ( ) block is expanded when the BLOCK is parsed, so a\r
1097
+ rem 'where node && ( node .. & exit /b %ERRORLEVEL% )' would report where's status\r
1098
+ rem instead of the launcher's, so every Windows hook would look successful. The\r
1099
+ rem goto-based flow instead of blocks: each %ERRORLEVEL% below is on its own line,\r
1100
+ rem expanded at execution, after the child has exited. Delayed expansion is not an\r
1101
+ rem option here — it would mangle '!' in forwarded arguments.\r
1102
+ where node >nul 2>nul\r
1103
+ if not errorlevel 1 goto :gh_shim_node\r
1104
+ where bun >nul 2>nul\r
1105
+ if not errorlevel 1 goto :gh_shim_bun\r
1106
+ echo github-router: neither node nor bun is on PATH. 1>&2\r
1107
+ echo Install Node.js 20+ ^(https://nodejs.org^) and try again. 1>&2\r
1108
+ exit /b 127\r
1109
+ :gh_shim_node\r
1110
+ node "%LAUNCHER%" %*\r
1111
+ exit /b %ERRORLEVEL%\r
1112
+ :gh_shim_bun\r
1113
+ bun "%LAUNCHER%" %*\r
1114
+ exit /b %ERRORLEVEL%\r
1115
+ `;
1116
+ }
1117
+ /**
1118
+ * PowerShell shim.
1119
+ *
1120
+ * Present because a `.cmd` is invisible to a bare `github-router` in PowerShell
1121
+ * only in theory (PATHEXT covers it) but fails in practice under constrained
1122
+ * execution policies that block `.cmd`. `$LASTEXITCODE` is propagated explicitly
1123
+ * — PowerShell would otherwise return 0 for a failed native command, turning a
1124
+ * hook failure into a success.
1125
+ */
1126
+ function ps1Shim(launcher) {
1127
+ return `# ${MANAGED_MARKER} - generated by github-router update. Do not edit.
1128
+ $ErrorActionPreference = "Stop"
1129
+ $Launcher = '${launcher.replace(/'/g, "''")}'
1130
+ if (-not (Test-Path -LiteralPath $Launcher)) {
1131
+ [Console]::Error.WriteLine("github-router: the managed launcher is missing ($Launcher).")
1132
+ [Console]::Error.WriteLine(" Reinstall: npm install -g github-router")
1133
+ exit 78
1134
+ }
1135
+ foreach ($Runtime in @("node", "bun")) {
1136
+ $cmd = Get-Command $Runtime -ErrorAction SilentlyContinue
1137
+ if ($cmd) {
1138
+ & $cmd.Source $Launcher @args
1139
+ exit $LASTEXITCODE
1140
+ }
1141
+ }
1142
+ [Console]::Error.WriteLine("github-router: neither node nor bun is on PATH.")
1143
+ [Console]::Error.WriteLine(" Install Node.js 20+ (https://nodejs.org) and try again.")
1144
+ exit 127
1145
+ `;
1146
+ }
1147
+ /** The exact files `ensureShims` should own for `kind` on this platform. */
1148
+ function shimBodies(kind, launcher = launcherPath(kind), platform = process.platform) {
1149
+ const out = [];
1150
+ for (const base of shimBases(kind)) if (platform === "win32") {
1151
+ out.push({
1152
+ path: shimPath(base, platform),
1153
+ content: cmdShim(launcher),
1154
+ mode: 420
1155
+ });
1156
+ out.push({
1157
+ path: shimPath(base, platform).replace(/\.cmd$/, ".ps1"),
1158
+ content: ps1Shim(launcher),
1159
+ mode: 420
1160
+ });
1161
+ } else out.push({
1162
+ path: shimPath(base, platform),
1163
+ content: posixShim(launcher),
1164
+ mode: 493
1165
+ });
1166
+ return out;
1167
+ }
1168
+ /**
1169
+ * Write (or refresh) the shims.
1170
+ *
1171
+ * Refusal is per-file and non-fatal: one file we do not own must not stop the
1172
+ * other from being written, and it must not fail an update — the payload is
1173
+ * already live by the time this runs.
1174
+ */
1175
+ async function ensureShims(kind, launcher = launcherPath(kind), platform = process.platform) {
1176
+ const results = [];
1177
+ for (const body of shimBodies(kind, launcher, platform)) results.push(await writeShim(body));
1178
+ return results;
1179
+ }
1180
+ async function writeShim(body) {
1181
+ const existing = await readIfExists(body.path);
1182
+ if (existing !== null && !hasManagedMarker(existing)) {
1183
+ consola.warn(`Refusing to overwrite ${body.path}: it exists and was not written by github-router. Move it aside if you want the managed shim there.`);
1184
+ return {
1185
+ path: body.path,
1186
+ outcome: "refused"
1187
+ };
1188
+ }
1189
+ if (existing === body.content) {
1190
+ const mode = await fs$1.stat(body.path).then((st) => st.mode & 511, () => null);
1191
+ if (process.platform !== "win32" && (mode === null || (mode & body.mode) !== body.mode)) {
1192
+ await fs$1.chmod(body.path, body.mode).catch(() => {});
1193
+ return {
1194
+ path: body.path,
1195
+ outcome: "updated"
1196
+ };
1197
+ }
1198
+ return {
1199
+ path: body.path,
1200
+ outcome: "unchanged"
1201
+ };
1202
+ }
1203
+ await fs$1.mkdir(path.dirname(body.path), {
1204
+ recursive: true,
1205
+ mode: 493
1206
+ });
1207
+ try {
1208
+ await writeFileAtomic(body.path, body.content, { mode: body.mode });
1209
+ } catch (err) {
1210
+ consola.warn(`Could not write shim ${body.path}:`, err);
1211
+ return {
1212
+ path: body.path,
1213
+ outcome: "refused"
1214
+ };
1215
+ }
1216
+ await fs$1.chmod(body.path, body.mode).catch(() => {});
1217
+ return {
1218
+ path: body.path,
1219
+ outcome: existing === null ? "written" : "updated"
1220
+ };
1221
+ }
1222
+ async function readIfExists(file) {
1223
+ try {
1224
+ if (!(await fs$1.lstat(file)).isFile()) return "";
1225
+ return await fs$1.readFile(file, "utf8");
1226
+ } catch {
1227
+ return null;
1228
+ }
1229
+ }
1230
+ /** Absolute path of the directory the shims live in. */
1231
+ function shimDir() {
1232
+ return cliBinDir();
1233
+ }
1234
+ /**
1235
+ * Whether `dir` is already on `PATH`.
1236
+ *
1237
+ * Compares resolved forms: `/var/…` vs `/private/var/…` on macOS and a
1238
+ * case-insensitive Windows path would both otherwise report "not on PATH" for a
1239
+ * directory that is.
1240
+ */
1241
+ function isOnPath(dir, env = process.env, platform = process.platform) {
1242
+ const raw = env.PATH ?? env.Path ?? env.path ?? "";
1243
+ const sep = platform === "win32" ? ";" : ":";
1244
+ const target = canonicalPath(dir, platform);
1245
+ return raw.split(sep).some((entry) => entry.length > 0 && canonicalPath(entry, platform) === target);
1246
+ }
1247
+ function canonicalPath(value, platform) {
1248
+ const trimmed = value.replace(/[/\\]+$/, "");
1249
+ if (platform === "win32") return trimmed.toLowerCase();
1250
+ try {
1251
+ return realpathSync(trimmed);
1252
+ } catch {
1253
+ return trimmed;
1254
+ }
1255
+ }
1256
+ /**
1257
+ * One actionable line when the shim directory is not on PATH, else `null`.
1258
+ *
1259
+ * Returned rather than logged for the same reason as
1260
+ * `hookLauncherDegradedWarning`: `claude`/`codex` redirect `consola` to the error
1261
+ * log, so a warning logged deep inside update is invisible exactly where it
1262
+ * matters. The CLI prints it next to the readiness line.
1263
+ */
1264
+ function pathHint(dir = shimDir(), env = process.env, platform = process.platform) {
1265
+ if (isOnPath(dir, env, platform)) return null;
1266
+ if (platform === "win32") return `Add ${dir} to PATH to run \`github-router\` from any shell.\n Windows: Settings > System > About > Advanced system settings > Environment Variables,\n edit "User variables" PATH and add: ${dir}`;
1267
+ return `Add ${dir} to PATH to run \`github-router\` from any shell:\n export PATH="${dir}:$PATH"`;
1268
+ }
1269
+ /**
1270
+ * Whether `candidate` is our own shim (vs a user's real install).
1271
+ *
1272
+ * Pi precedence needs this: a `pi` on PATH that is *our* shim must not be
1273
+ * treated as the user's own Pi, or the managed install would shadow itself.
1274
+ * Detected by the marker line, never by basename — a user's `~/bin/pi` is
1275
+ * theirs.
1276
+ */
1277
+ async function isOurShim(candidate) {
1278
+ const content = await readIfExists(candidate);
1279
+ return content !== null && hasManagedMarker(content);
1280
+ }
1281
+ // src/lib/managed-install/update.ts
1282
+ /**
1283
+ * "What version should be live, and how do I get there?"
1284
+ *
1285
+ * The installer (`install.ts`) knows how to put an exact version on disk; this
1286
+ * module knows which exact version to ask for and how often to ask. Three
1287
+ * decisions here were forced by measurement, not taste:
1288
+ *
1289
+ * 1. **The installed version is authoritative, never the requested one.** A
1290
+ * corporate mirror, `min-release-age`, or a `latest` tag pointing at an older
1291
+ * release all make `npm view` disagree with what the tarball actually is. If
1292
+ * the update loop trusted its own request, it would queue the same install
1293
+ * forever: request `1.2.4`, get `1.2.3`, pointer still says `1.2.3`, next hour
1294
+ * request `1.2.4` again. So after an install we re-read the pointer and adopt
1295
+ * whatever landed.
1296
+ * 2. **A version already on disk is adopted without npm.** That covers
1297
+ * `update --version <v>` for a version that is present, a lost/restored
1298
+ * pointer, and the second of two racing installers. `rename` onto a non-empty
1299
+ * directory is `ENOTEMPTY`, so this is also what keeps the common case from
1300
+ * ever reaching a rename at all.
1301
+ * 3. **Background work is throttled and detached.** A launch must never wait on
1302
+ * npm, and a short-lived command (`--version`) must not be held open by an
1303
+ * install either. So the background path is a DETACHED child running
1304
+ * `update --self --quiet`, unref'd, with its own throttle in
1305
+ * `install-state.json`.
1306
+ */
1307
+ /** 5 s is enough for `npm view` and short enough not to notice. */
1308
+ const NPM_VIEW_TIMEOUT_MS = 8e3;
1309
+ /**
1310
+ * Registry for a kind.
1311
+ *
1312
+ * Pi has its own resolution rule (`resolvePiRegistry()`), and it is not a detail
1313
+ * we can inherit here: a lagging corporate mirror below `PI_MIN_VERSION` makes
1314
+ * the floor unreachable, which was a real install loop. `self` uses the user's
1315
+ * configured registry, which is what they expect for the router itself.
1316
+ */
1317
+ async function registryFor(kind) {
1318
+ if (kind === "pi") {
1319
+ const { resolvePiRegistry } = await import("./pi-version-check-D5RvdLsG.js");
1320
+ return resolvePiRegistry();
1321
+ }
1322
+ return null;
1323
+ }
1324
+ /** `npm view <pkg> version`, or `null` when npm is absent/offline. */
1325
+ async function fetchLatestVersion(kind) {
1326
+ const npmPath = resolveExecutable("npm");
1327
+ if (!npmPath) return null;
1328
+ const registry = await registryFor(kind);
1329
+ const args = [
1330
+ npmPath,
1331
+ "view",
1332
+ npmPackageFor(kind),
1333
+ "version",
1334
+ "--silent"
1335
+ ];
1336
+ if (registry) args.push(`--registry=${registry}`);
1337
+ try {
1338
+ const { stdout, code } = await runCommandCapture(args, { timeoutMs: NPM_VIEW_TIMEOUT_MS });
1339
+ if (code !== 0) return null;
1340
+ const value = stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
1341
+ return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(value) ? value : null;
1342
+ } catch {
1343
+ return null;
1344
+ }
1345
+ }
1346
+ /** What is live right now for `kind`, if anything. */
1347
+ async function currentManagedVersion(kind) {
1348
+ return (await readPointer(kind, { verifyEntry: false }))?.version ?? null;
1349
+ }
1350
+ /**
1351
+ * Compute the desired state without changing anything.
1352
+ *
1353
+ * `--check` uses this, and so does the background path (to decide whether to
1354
+ * spawn at all): a launch that only needs to know "am I current" must not write
1355
+ * the pointer, install a launcher, or touch npm's tree.
1356
+ */
1357
+ async function checkForUpdate(kind, opts = {}) {
1358
+ const pointer = await readPointer(kind, { verifyEntry: false });
1359
+ const installedVersion = pointer?.version ?? null;
1360
+ const latestVersion = opts.version ?? await fetchLatestVersion(kind);
1361
+ const targetVersion = opts.version ?? latestVersion;
1362
+ const marker = installedVersion ? await readInstalledMarker(kind, installedVersion) : null;
1363
+ return {
1364
+ kind,
1365
+ installedVersion,
1366
+ latestVersion,
1367
+ targetVersion,
1368
+ upToDate: targetVersion !== null && installedVersion !== null && targetVersion === installedVersion && await readPointer(kind) !== null,
1369
+ registry: marker?.registry ?? await registryFor(kind),
1370
+ entryPath: pointer?.entryPath ?? null
1371
+ };
1372
+ }
1373
+ /**
1374
+ * Bring `kind` up to date: install (or adopt) the target version, publish the
1375
+ * pointer, then make the stable surface point at it.
1376
+ *
1377
+ * Order matters and is deliberate: the payload and pointer land FIRST, and the
1378
+ * launcher/shims are refreshed after. A launcher written before a failed install
1379
+ * would still be correct (it reads the pointer), but a shim written before the
1380
+ * pointer exists would advertise a managed install that is not there.
1381
+ */
1382
+ async function runManagedUpdate(opts) {
1383
+ const registry = await registryFor(opts.kind);
1384
+ const check = await checkForUpdate(opts.kind, {
1385
+ version: opts.version,
1386
+ force: opts.force
1387
+ });
1388
+ if (opts.check) return { check };
1389
+ const target = check.targetVersion;
1390
+ if (!target) return {
1391
+ check,
1392
+ outcome: {
1393
+ kind: "failed",
1394
+ version: null,
1395
+ detail: "could not determine a version to install (npm view failed). Check your connection/registry, or pass --version."
1396
+ }
1397
+ };
1398
+ const outcome = await ensureManagedInstall({
1399
+ kind: opts.kind,
1400
+ version: target,
1401
+ force: opts.force,
1402
+ registry: registry ?? void 0,
1403
+ signal: opts.signal
1404
+ });
1405
+ const gc = await gcUnderLock(opts.kind);
1406
+ if (outcome.kind !== "installed" && outcome.kind !== "adopted") return {
1407
+ check,
1408
+ outcome,
1409
+ gc
1410
+ };
1411
+ const launcher = await ensureLauncher(opts.kind);
1412
+ const shims = await ensureShims(opts.kind, launcherPath(opts.kind));
1413
+ return {
1414
+ check: {
1415
+ ...check,
1416
+ installedVersion: outcome.version ?? check.installedVersion,
1417
+ upToDate: true
1418
+ },
1419
+ outcome,
1420
+ launcher,
1421
+ shims,
1422
+ pathHint: pathHint(),
1423
+ gc
1424
+ };
1425
+ }
1426
+ /**
1427
+ * Sweep a kind's directory, but only while holding the install lock.
1428
+ *
1429
+ * Two reasons for the lock, not one: it guarantees we never delete a
1430
+ * `.staging-*` that a live install is writing into (those are inside the 1 h TTL
1431
+ * anyway, but a slow corporate install can exceed that), and it guarantees we
1432
+ * never delete a version dir in the window between `rename` publishing it and
1433
+ * the pointer being written. Both are `skipped` conditions rather than errors —
1434
+ * the lock holder sweeps after itself.
1435
+ */
1436
+ async function gcUnderLock(kind) {
1437
+ const empty = {
1438
+ removedVersions: [],
1439
+ removedStaging: [],
1440
+ removedTransient: []
1441
+ };
1442
+ let captured = empty;
1443
+ try {
1444
+ const { withInstallLockResult } = await import("./update-lock-BeS_WmC8.js");
1445
+ return (await withInstallLockResult(`managed-${kind}.lock`, async () => {
1446
+ const report = await gcManaged(kind);
1447
+ captured = {
1448
+ removedVersions: report.removedVersions,
1449
+ removedStaging: report.removedStaging,
1450
+ removedTransient: report.removedTransient
1451
+ };
1452
+ })).outcome === "ran" ? captured : empty;
1453
+ } catch {
1454
+ return empty;
1455
+ }
1456
+ }
1457
+ /**
1458
+ * The background entry point for the bootstrap: "install self if it is not
1459
+ * installed, and refresh it when a launch notices a newer one".
1460
+ *
1461
+ * Returns a short description of what it decided, which the bootstrap logs at
1462
+ * debug level. Never throws and never blocks: the actual install is a DETACHED
1463
+ * child, so even `github-router --version` exits immediately.
1464
+ */
1465
+ async function scheduleBackgroundSelfInstall(opts = {}) {
1466
+ if (managedInstallDisabled()) return "managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL)";
1467
+ const origin = await classifyOrigin();
1468
+ if (origin.origin !== "npx" && origin.origin !== "bunx") return `origin is ${describeOrigin(origin.origin)}; managed install not engaged`;
1469
+ const state = await readInstallState("self");
1470
+ if (!mayAttemptNow(state)) return `backing off until ${state.nextAttemptAt} after: ${state.lastError ?? "previous failure"}`;
1471
+ const installed = (await readPointer("self"))?.version ?? null;
1472
+ const latest = await fetchLatestVersion("self");
1473
+ if (latest && installed === latest) return `already at ${installed}`;
1474
+ await patchInstallState("self", {
1475
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
1476
+ lastOrigin: origin.origin
1477
+ });
1478
+ const entry = process.argv[1];
1479
+ if (typeof entry !== "string" || entry.length === 0) return "no argv[1]; cannot spawn the updater";
1480
+ spawnDetachedUpdater(entry, [
1481
+ "update",
1482
+ "--self",
1483
+ "--no-optional",
1484
+ ...opts.quiet === false ? [] : ["--quiet"]
1485
+ ]);
1486
+ return latest ? `queued install of ${latest}` : "no published version visible; launch will run from the current tree";
1487
+ }
1488
+ /**
1489
+ * The Pi twin of `scheduleBackgroundSelfInstall`.
1490
+ *
1491
+ * Tighter on purpose: this only ever refreshes a payload that is already live
1492
+ * (an install with nothing on disk is the launcher's foreground job, where a
1493
+ * failure can be reported to the user), and it never writes a pointer — the
1494
+ * detached `update --pi` child does that under the install lock.
1495
+ */
1496
+ async function scheduleBackgroundPiInstall() {
1497
+ if (managedInstallDisabled()) return "managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL)";
1498
+ const pointer = await readPointer("pi", { verifyEntry: false });
1499
+ if (!pointer) return "no managed Pi yet";
1500
+ const state = await readInstallState("pi");
1501
+ if (!mayAttemptNow(state)) return `backing off until ${state.nextAttemptAt} after: ${state.lastError ?? "previous failure"}`;
1502
+ const latest = await fetchLatestVersion("pi");
1503
+ if (latest && pointer.version === latest) return `already at ${pointer.version}`;
1504
+ await patchInstallState("pi", { lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString() });
1505
+ const entry = process.argv[1];
1506
+ if (typeof entry !== "string" || entry.length === 0) return "no argv[1]; cannot spawn the updater";
1507
+ spawnDetachedUpdater(entry, [
1508
+ "update",
1509
+ "--pi",
1510
+ "--quiet",
1511
+ "--no-optional"
1512
+ ]);
1513
+ return latest ? `queued install of ${latest}` : "no published Pi version visible";
1514
+ }
1515
+ /**
1516
+ * Spawn a detached `node <entry> <args…>` that outlives this process.
1517
+ *
1518
+ * Detached and unref'd on purpose. The alternative — doing the install in-process
1519
+ * — holds the event loop open, so `github-router --version` would sit there for a
1520
+ * minute waiting on npm. A detached child keeps the promise "launch is never
1521
+ * delayed by an update", and if it is killed mid-install the staging dir is
1522
+ * swept by GC an hour later.
1523
+ *
1524
+ * `stdio: "ignore"` because the parent's stdio may be a Claude Code hook pipe;
1525
+ * writing the child's chatter there would corrupt a hook payload.
1526
+ */
1527
+ function spawnDetachedUpdater(entry, args) {
1528
+ try {
1529
+ const child = spawn(process.execPath, [entry, ...args], {
1530
+ detached: true,
1531
+ stdio: "ignore",
1532
+ windowsHide: true,
1533
+ env: {
1534
+ ...process.env,
1535
+ GH_ROUTER_MANAGED_BACKGROUND: "1"
1536
+ }
1537
+ });
1538
+ child.on("error", () => {});
1539
+ child.unref();
1540
+ return true;
1541
+ } catch (err) {
1542
+ consola.debug("Could not spawn the background managed install:", err);
1543
+ return false;
1544
+ }
1545
+ }
1546
+ export { runManagedUpdate as a, spawnDetachedUpdater as c, readPointer as d, registryFor as i, isOurShim as l, currentManagedVersion as n, scheduleBackgroundPiInstall as o, fetchLatestVersion as r, scheduleBackgroundSelfInstall as s, checkForUpdate as t, ensureManagedInstall as u };
1547
+
1548
+ //# sourceMappingURL=update-T1L7yFon.js.map