@carrieros/cli-staging 0.0.0-stage → 0.4.1

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 (137) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +26 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +78 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +160 -0
  27. package/dist/commands/update.js +285 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +229 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +364 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +132 -0
  36. package/dist/services/api.js +441 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/auto-update.js +221 -0
  39. package/dist/services/chat-stream.js +168 -0
  40. package/dist/services/checkpoints.js +278 -0
  41. package/dist/services/client-tools.js +356 -0
  42. package/dist/services/code-intel.js +243 -0
  43. package/dist/services/code-symbols.js +94 -0
  44. package/dist/services/coding-workflow.js +554 -0
  45. package/dist/services/command-coordinator.js +273 -0
  46. package/dist/services/command-policy.js +434 -0
  47. package/dist/services/config.js +384 -0
  48. package/dist/services/container-runner.js +254 -0
  49. package/dist/services/container-supervisor.js +38 -0
  50. package/dist/services/context.js +416 -0
  51. package/dist/services/device-auth.js +288 -0
  52. package/dist/services/diff.js +196 -0
  53. package/dist/services/env-policy.js +108 -0
  54. package/dist/services/execution-platform.js +30 -0
  55. package/dist/services/file-detect.js +104 -0
  56. package/dist/services/file-resolver.js +199 -0
  57. package/dist/services/file-upload.js +126 -0
  58. package/dist/services/folder-key.js +22 -0
  59. package/dist/services/git-tools.js +429 -0
  60. package/dist/services/glob-match.js +164 -0
  61. package/dist/services/helper-bin.js +85 -0
  62. package/dist/services/ignore-rules.js +189 -0
  63. package/dist/services/instruction-resolver.js +54 -0
  64. package/dist/services/job-helper.js +328 -0
  65. package/dist/services/local-files.js +639 -0
  66. package/dist/services/local-tools.js +937 -0
  67. package/dist/services/login-flow.js +156 -0
  68. package/dist/services/meta.js +42 -0
  69. package/dist/services/mutation-coordinator.js +327 -0
  70. package/dist/services/mutation-groups.js +309 -0
  71. package/dist/services/mutation-recovery.js +159 -0
  72. package/dist/services/mutations.js +679 -0
  73. package/dist/services/open-url.js +68 -0
  74. package/dist/services/output.js +62 -0
  75. package/dist/services/packaged-update.js +403 -0
  76. package/dist/services/packaged.js +39 -0
  77. package/dist/services/permission-mode.js +78 -0
  78. package/dist/services/process-runner.js +412 -0
  79. package/dist/services/project-context.js +298 -0
  80. package/dist/services/redaction.js +201 -0
  81. package/dist/services/result-reconciliation.js +49 -0
  82. package/dist/services/secure-store.js +217 -0
  83. package/dist/services/session-resolver.js +115 -0
  84. package/dist/services/sia.js +51 -0
  85. package/dist/services/spinner.js +40 -0
  86. package/dist/services/supported-runtime.js +59 -0
  87. package/dist/services/task-context.js +212 -0
  88. package/dist/services/task-snapshot.js +38 -0
  89. package/dist/services/tool-result-outbox.js +195 -0
  90. package/dist/services/update.js +730 -0
  91. package/dist/services/workspace-registry.js +310 -0
  92. package/dist/services/workspace.js +580 -0
  93. package/dist/shell/shell-chat.js +1622 -0
  94. package/dist/shell/shell-commands.js +411 -0
  95. package/dist/shell/shell-prompt.js +110 -0
  96. package/dist/shell/shell-renderer.js +51 -0
  97. package/dist/shell/shell-router.js +37 -0
  98. package/dist/shell/shell.js +414 -0
  99. package/dist/shell/task-context-view.js +40 -0
  100. package/dist/staging.js +5 -0
  101. package/dist/types/index.js +6 -0
  102. package/dist/ui/agent-cards.js +111 -0
  103. package/dist/ui/agent-presentation.js +131 -0
  104. package/dist/ui/approval.js +111 -0
  105. package/dist/ui/banner.js +56 -0
  106. package/dist/ui/btw-overlay.js +230 -0
  107. package/dist/ui/change-review.js +334 -0
  108. package/dist/ui/chat-renderer.js +463 -0
  109. package/dist/ui/code-block.js +52 -0
  110. package/dist/ui/color-picker.js +100 -0
  111. package/dist/ui/colors.js +55 -0
  112. package/dist/ui/command-details.js +11 -0
  113. package/dist/ui/command-filter.js +92 -0
  114. package/dist/ui/command-item.js +6 -0
  115. package/dist/ui/command-palette.js +383 -0
  116. package/dist/ui/command-registry.js +128 -0
  117. package/dist/ui/command-renderer.js +55 -0
  118. package/dist/ui/command-review.js +187 -0
  119. package/dist/ui/composer-layout.js +74 -0
  120. package/dist/ui/conversation.js +450 -0
  121. package/dist/ui/interrupt.js +35 -0
  122. package/dist/ui/live.js +141 -0
  123. package/dist/ui/logo.js +58 -0
  124. package/dist/ui/markdown.js +205 -0
  125. package/dist/ui/message.js +21 -0
  126. package/dist/ui/screen-prompt.js +181 -0
  127. package/dist/ui/screen.js +297 -0
  128. package/dist/ui/select.js +284 -0
  129. package/dist/ui/sia-qa.js +213 -0
  130. package/dist/ui/spinner.js +23 -0
  131. package/dist/ui/sticky-stream.js +64 -0
  132. package/dist/ui/task-context-card.js +99 -0
  133. package/dist/ui/text-prompt.js +74 -0
  134. package/dist/ui/theme.js +80 -0
  135. package/dist/ui/trust.js +88 -0
  136. package/dist/ui/ui.js +101 -0
  137. package/package.json +33 -4
@@ -0,0 +1,730 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { cliVersion } from "./meta.js";
6
+ /**
7
+ * CLI update management over npm — the CLI's only distribution channel.
8
+ *
9
+ * Pure logic: version resolution, comparison, the linked-checkout guard and the
10
+ * install call. Nothing here prints; commands/update.ts owns every message, so
11
+ * the shell command and `cos update` render identically from one source.
12
+ *
13
+ * Deliberately NOT here: downloading anything, restarting the process, hot
14
+ * reloading, or writing into the installed package. npm performs the
15
+ * replacement; this only asks it to.
16
+ */
17
+ /** The only package this will ever install. Never built from user input. */
18
+ export const PACKAGE_NAME = "@carrieros/cli";
19
+ /** npm is invoked by name with an argument array, never through a shell, so no
20
+ * version string can be interpolated into a command line. */
21
+ const NPM_BIN = process.platform === "win32" ? "npm.cmd" : "npm";
22
+ /**
23
+ * Windows needs `shell: true` to launch npm at all — since the CVE-2024-27980
24
+ * hardening, Node refuses to spawn a .cmd directly and returns EINVAL. That is
25
+ * safe HERE only because every argument this file passes is a compile-time
26
+ * constant: no version string, path or user input is ever interpolated into a
27
+ * command line. Keep it that way.
28
+ */
29
+ const SPAWN_SHELL = process.platform === "win32";
30
+ /**
31
+ * Run npm and hand back the raw result.
32
+ *
33
+ * On Windows the command goes through a shell as ONE string: passing an args
34
+ * array alongside `shell: true` triggers Node's DEP0190 warning (args are
35
+ * concatenated, not escaped) and that warning would print into the user's
36
+ * terminal. Every argument here is a compile-time constant, so concatenation is
37
+ * safe — but that is exactly why nothing dynamic may ever be added to `args`.
38
+ */
39
+ function runNpm(args, timeout) {
40
+ const opts = { encoding: "utf8", timeout, windowsHide: true };
41
+ return SPAWN_SHELL
42
+ ? spawnSync([NPM_BIN, ...args].join(" "), { ...opts, shell: true })
43
+ : spawnSync(NPM_BIN, args, opts);
44
+ }
45
+ const VIEW_TIMEOUT_MS = 20000;
46
+ const INSTALL_TIMEOUT_MS = 180000;
47
+ export function getCurrentVersion() {
48
+ return cliVersion();
49
+ }
50
+ /**
51
+ * Compare semver numerically.
52
+ *
53
+ * Lexical comparison gets 0.10.0 vs 0.9.0 wrong — the case that appears the
54
+ * moment a project passes its ninth minor. Prereleases sort BELOW their release
55
+ * (1.0.0-rc.1 < 1.0.0). Numeric prerelease identifiers compare numerically and
56
+ * sort below nonnumeric identifiers. Build metadata does not affect precedence.
57
+ */
58
+ export function compareVersions(a, b) {
59
+ const parse = (v) => {
60
+ const normalized = String(v).trim().replace(/^v/, "");
61
+ if (!isVersionLike(normalized))
62
+ throw new Error(`Invalid version: ${v}`);
63
+ const version = normalized.split("+", 1)[0];
64
+ const dash = version.indexOf("-");
65
+ const core = dash === -1 ? version : version.slice(0, dash);
66
+ return {
67
+ nums: core.split(".").map((n) => BigInt(n)),
68
+ pre: dash === -1 ? [] : version.slice(dash + 1).split(".")
69
+ };
70
+ };
71
+ const x = parse(a);
72
+ const y = parse(b);
73
+ for (let i = 0; i < 3; i++) {
74
+ if (x.nums[i] !== y.nums[i])
75
+ return x.nums[i] < y.nums[i] ? -1 : 1;
76
+ }
77
+ if (!x.pre.length && !y.pre.length)
78
+ return 0;
79
+ if (!x.pre.length)
80
+ return 1;
81
+ if (!y.pre.length)
82
+ return -1;
83
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
84
+ const left = x.pre[i];
85
+ const right = y.pre[i];
86
+ if (left === undefined)
87
+ return -1;
88
+ if (right === undefined)
89
+ return 1;
90
+ if (left === right)
91
+ continue;
92
+ const leftNumeric = /^\d+$/.test(left);
93
+ const rightNumeric = /^\d+$/.test(right);
94
+ if (leftNumeric && rightNumeric)
95
+ return BigInt(left) < BigInt(right) ? -1 : 1;
96
+ if (leftNumeric !== rightNumeric)
97
+ return leftNumeric ? -1 : 1;
98
+ return left < right ? -1 : 1;
99
+ }
100
+ return 0;
101
+ }
102
+ /** Guards every version that reaches a comparison or a message. */
103
+ export function isVersionLike(v) {
104
+ if (typeof v !== "string")
105
+ return false;
106
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(v.trim());
107
+ return !!match && (!match[4] || match[4].split(".").every((id) => !/^\d+$/.test(id) || id === "0" || !id.startsWith("0")));
108
+ }
109
+ export function getLatestVersion() {
110
+ let res;
111
+ try {
112
+ res = runNpm(["view", PACKAGE_NAME, "version", "--json"], VIEW_TIMEOUT_MS);
113
+ }
114
+ catch (err) {
115
+ return { ok: false, reason: "failed", detail: err.message };
116
+ }
117
+ // ENOENT means npm is missing from PATH — a different problem from a
118
+ // registry failure, and it needs different advice.
119
+ if (res.error && res.error.code === "ENOENT") {
120
+ return { ok: false, reason: "no-npm", detail: "npm was not found on this system." };
121
+ }
122
+ if (res.error)
123
+ return { ok: false, reason: "failed", detail: res.error.message };
124
+ if (res.status !== 0) {
125
+ const first = String(res.stderr || res.stdout || "").trim().split("\n")[0];
126
+ return { ok: false, reason: "failed", detail: first || "npm exited with code " + res.status };
127
+ }
128
+ // --json yields a quoted string for one version, a bare string under some
129
+ // configs, and an array when several match. Accept all three.
130
+ const raw = String(res.stdout || "").trim();
131
+ let parsed = raw;
132
+ try {
133
+ parsed = JSON.parse(raw);
134
+ }
135
+ catch {
136
+ parsed = raw.replace(/^"|"$/g, "");
137
+ }
138
+ if (Array.isArray(parsed))
139
+ parsed = parsed[parsed.length - 1];
140
+ const version = typeof parsed === "string" ? parsed.trim() : "";
141
+ if (!isVersionLike(version)) {
142
+ return { ok: false, reason: "failed", detail: "Unexpected npm output: " + raw.slice(0, 80) };
143
+ }
144
+ return { ok: true, version };
145
+ }
146
+ export function checkForUpdate() {
147
+ const current = getCurrentVersion();
148
+ const latest = getLatestVersion();
149
+ if (!latest.ok) {
150
+ return latest.reason === "no-npm"
151
+ ? { kind: "no-npm", current }
152
+ : { kind: "unreachable", current, detail: latest.detail };
153
+ }
154
+ const cmp = compareVersions(current, latest.version);
155
+ if (cmp === 0)
156
+ return { kind: "current", current, latest: latest.version };
157
+ return cmp < 0
158
+ ? { kind: "available", current, latest: latest.version }
159
+ : { kind: "ahead", current, latest: latest.version };
160
+ }
161
+ /** Absolute path of the package this process runs from. */
162
+ export function packageRoot() {
163
+ try {
164
+ return path.resolve(fileURLToPath(new URL("../..", import.meta.url)));
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ function npmGlobalRoot() {
171
+ try {
172
+ const res = runNpm(["root", "-g"], VIEW_TIMEOUT_MS);
173
+ if (res.status !== 0)
174
+ return null;
175
+ const out = String(res.stdout || "").trim();
176
+ return out ? path.resolve(out) : null;
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ }
182
+ /** Windows paths differ only in case, so containment compares case-folded. */
183
+ function isInside(parent, child) {
184
+ const rel = path.relative(parent.toLowerCase(), child.toLowerCase());
185
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
186
+ }
187
+ /**
188
+ * True when the global package is a link to a working copy (npm link).
189
+ *
190
+ * MANDATORY GUARD: `npm i -g` against a linked install replaces the symlink and
191
+ * the developer silently loses the link to their checkout. Two independent
192
+ * signals, either conclusive:
193
+ * 1. the global package path is itself a symlink;
194
+ * 2. this process runs from outside the global npm root, so updating the
195
+ * global copy would not change what is executing anyway.
196
+ */
197
+ export function isLinkedInstallation() {
198
+ const globalRoot = npmGlobalRoot();
199
+ if (!globalRoot)
200
+ return false;
201
+ const installed = path.join(globalRoot, ...PACKAGE_NAME.split("/"));
202
+ try {
203
+ if (fs.lstatSync(installed).isSymbolicLink())
204
+ return true;
205
+ }
206
+ catch {
207
+ /* not installed globally — fall through to the location check */
208
+ }
209
+ const here = packageRoot();
210
+ return here ? !isInside(globalRoot, here) : false;
211
+ }
212
+ /**
213
+ * Install the latest published version.
214
+ *
215
+ * `install @latest`, never `npm update`: the intent is "give me the published
216
+ * latest", and update obeys semver ranges instead.
217
+ */
218
+ export function installLatest() {
219
+ let res;
220
+ try {
221
+ res = runNpm(["install", "-g", PACKAGE_NAME + "@latest"], INSTALL_TIMEOUT_MS);
222
+ }
223
+ catch (err) {
224
+ return { ok: false, detail: err.message, permission: false };
225
+ }
226
+ if (res.error) {
227
+ const code = res.error.code;
228
+ return {
229
+ ok: false,
230
+ detail: code === "ENOENT" ? "npm was not found on this system." : res.error.message,
231
+ permission: false
232
+ };
233
+ }
234
+ const output = (String(res.stdout || "") + "\n" + String(res.stderr || "")).trim();
235
+ if (res.status === 0)
236
+ return { ok: true, detail: output, permission: false };
237
+ return {
238
+ ok: false,
239
+ detail: lastMeaningfulLines(output) || "npm exited with code " + res.status,
240
+ permission: /EACCES|EPERM|permission denied|Access is denied/i.test(output)
241
+ };
242
+ }
243
+ /**
244
+ * What is on disk now.
245
+ *
246
+ * The running process cannot answer this — its own package.json is already read
247
+ * and the old modules stay loaded — so this reads the freshly installed
248
+ * package.json from the global root rather than trusting cliVersion().
249
+ */
250
+ export function verifyInstallation() {
251
+ const globalRoot = npmGlobalRoot();
252
+ if (!globalRoot)
253
+ return null;
254
+ try {
255
+ const pkg = path.join(globalRoot, ...PACKAGE_NAME.split("/"), "package.json");
256
+ const parsed = JSON.parse(fs.readFileSync(pkg, "utf8"));
257
+ return isVersionLike(parsed.version) ? parsed.version : null;
258
+ }
259
+ catch {
260
+ return null;
261
+ }
262
+ }
263
+ /** The last few actionable lines of npm output — enough to act on, not a wall. */
264
+ function lastMeaningfulLines(output, max = 6) {
265
+ return output
266
+ .split(/\r?\n/)
267
+ .map((l) => l.trim())
268
+ .filter((l) => l && !/^npm (notice|warn) /i.test(l))
269
+ .slice(-max)
270
+ .join("\n");
271
+ }
272
+ // ── Startup notice ───────────────────────────────────────────────────────────
273
+ // The banner renders once, and rewriting it later would mean mutating the
274
+ // screen engine mid-frame. So the notice is built from the PREVIOUS check and a
275
+ // fresh one runs afterwards, off the startup path — a new release is announced
276
+ // on the next launch, and startup is never delayed or failed by npm.
277
+ /** How long a cached result stays good. */
278
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
279
+ /** Notice line for the banner, or null when current / unknown. */
280
+ export function cachedUpdateNotice(cache) {
281
+ const latest = cache.get("latestCliVersion");
282
+ if (!isVersionLike(latest))
283
+ return null;
284
+ return compareVersions(getCurrentVersion(), latest) < 0
285
+ ? "Update available: v" + latest + " — run /update to upgrade."
286
+ : null;
287
+ }
288
+ /** True when the cached result is stale enough to re-check. */
289
+ export function shouldRefreshCheck(cache, now = Date.now()) {
290
+ const ok = cache.get("updateCheckAt") ?? 0;
291
+ const failed = cache.get("updateCheckErrorAt") ?? 0;
292
+ // A failure also starts the clock, so an offline machine retries once a day
293
+ // instead of shelling out to npm on every launch.
294
+ return now - Math.max(ok, failed) >= CHECK_INTERVAL_MS;
295
+ }
296
+ /**
297
+ * Refresh the cache. Call AFTER the shell is up — spawnSync blocks, so this
298
+ * must never sit between the user and their prompt.
299
+ */
300
+ export function refreshUpdateCache(cache, now = Date.now()) {
301
+ const latest = getLatestVersion();
302
+ if (latest.ok) {
303
+ cache.set("latestCliVersion", latest.version);
304
+ cache.set("updateCheckAt", now);
305
+ }
306
+ else {
307
+ // Recorded, never shown: a background check that fails is not the user's
308
+ // problem, and surfacing it every launch would be noise.
309
+ cache.set("updateCheckErrorAt", now);
310
+ }
311
+ }
312
+ // ── Channels, installation kinds, background installs ───────────────────────
313
+ // Everything below is async (child_process.spawn), so a check or install never
314
+ // blocks the composer, and takes its npm runner from one injectable seam so the
315
+ // tests never touch the real registry or a real global install.
316
+ /** npm dist-tags a CLI may follow. Never chosen from remote data. */
317
+ export const UPDATE_CHANNELS = ["latest", "beta", "next", "staging"];
318
+ export function isUpdateChannel(v) {
319
+ return typeof v === "string" && UPDATE_CHANNELS.includes(v);
320
+ }
321
+ /**
322
+ * Packages this CLI may ever install. The name comes from the CLI's OWN
323
+ * package.json, so the staging build (@carrieros/cli-staging) only ever updates
324
+ * itself and can never pull the production package over a staging install.
325
+ */
326
+ const ALLOWED_PACKAGES = new Set(["@carrieros/cli", "@carrieros/cli-staging"]);
327
+ export function packageName() {
328
+ try {
329
+ const pkgUrl = new URL("../../package.json", import.meta.url);
330
+ const name = JSON.parse(fs.readFileSync(fileURLToPath(pkgUrl), "utf8")).name;
331
+ if (name && ALLOWED_PACKAGES.has(name))
332
+ return name;
333
+ }
334
+ catch {
335
+ /* packaged executable: no package.json on disk */
336
+ }
337
+ return PACKAGE_NAME;
338
+ }
339
+ /** The isolated staging package must follow its own non-latest npm dist-tag. */
340
+ export function defaultUpdateChannel(name = packageName()) {
341
+ return name === "@carrieros/cli-staging" ? "staging" : "latest";
342
+ }
343
+ /** The manual command for a channel — what every failure message offers. */
344
+ export function manualUpdateCommand(channel = defaultUpdateChannel(), name = packageName()) {
345
+ return `npm install -g ${name}@${channel}`;
346
+ }
347
+ /** Output cap: npm can print a lot, and only the tail is ever shown. */
348
+ const MAX_OUTPUT = 64 * 1024;
349
+ const spawnNpm = (args, timeoutMs) => new Promise((resolve) => {
350
+ let stdout = "";
351
+ let stderr = "";
352
+ let settled = false;
353
+ const finish = (r) => {
354
+ if (!settled) {
355
+ settled = true;
356
+ resolve(r);
357
+ }
358
+ };
359
+ let child;
360
+ try {
361
+ // Same rule as runNpm: every argument is a constant, an allow-listed
362
+ // package name, a validated semver or an allow-listed dist-tag.
363
+ child = SPAWN_SHELL
364
+ ? spawn([NPM_BIN, ...args].join(" "), { shell: true, windowsHide: true, env: { ...process.env, CARRIEROS_UPDATING: "1" } })
365
+ : spawn(NPM_BIN, args, { windowsHide: true, env: { ...process.env, CARRIEROS_UPDATING: "1" } });
366
+ }
367
+ catch (err) {
368
+ finish({ status: null, stdout: "", stderr: "", error: err });
369
+ return;
370
+ }
371
+ const timer = setTimeout(() => {
372
+ child.kill();
373
+ finish({ status: null, stdout, stderr, error: Object.assign(new Error("npm timed out"), { code: "ETIMEDOUT" }) });
374
+ }, timeoutMs);
375
+ timer.unref?.();
376
+ child.stdout?.on("data", (d) => { if (stdout.length < MAX_OUTPUT)
377
+ stdout += String(d); });
378
+ child.stderr?.on("data", (d) => { if (stderr.length < MAX_OUTPUT)
379
+ stderr += String(d); });
380
+ child.on("error", (err) => { clearTimeout(timer); finish({ status: null, stdout, stderr, error: err }); });
381
+ child.on("close", (code) => { clearTimeout(timer); finish({ status: code, stdout, stderr }); });
382
+ });
383
+ let npmRunner = spawnNpm;
384
+ /** Test seam: replace npm with a fake. Passing null restores the real one. */
385
+ export function setNpmRunnerForTests(runner) {
386
+ npmRunner = runner ?? spawnNpm;
387
+ }
388
+ /**
389
+ * The version a channel currently points at, from the package's npm dist-tags.
390
+ * Only a well-formed semver is ever returned; anything else is a failure.
391
+ */
392
+ export async function fetchChannelVersion(channel = defaultUpdateChannel(), name = packageName()) {
393
+ if (!isUpdateChannel(channel))
394
+ return { ok: false, reason: "failed", detail: "Unknown update channel." };
395
+ const res = await npmRunner(["view", name, "dist-tags", "--json"], VIEW_TIMEOUT_MS);
396
+ if (res.error?.code === "ENOENT")
397
+ return { ok: false, reason: "no-npm", detail: "npm was not found on this system." };
398
+ if (res.error)
399
+ return { ok: false, reason: "failed", detail: res.error.code === "ETIMEDOUT" ? "The npm registry did not answer in time." : res.error.message };
400
+ if (res.status !== 0) {
401
+ const first = String(res.stderr || res.stdout || "").trim().split("\n")[0];
402
+ return { ok: false, reason: "failed", detail: first || "npm exited with code " + res.status };
403
+ }
404
+ let tags;
405
+ try {
406
+ tags = JSON.parse(String(res.stdout || "").trim());
407
+ }
408
+ catch {
409
+ return { ok: false, reason: "failed", detail: "Unexpected npm output." };
410
+ }
411
+ if (!tags || typeof tags !== "object" || Array.isArray(tags))
412
+ return { ok: false, reason: "failed", detail: "Unexpected npm output." };
413
+ const version = tags[channel];
414
+ if (version === undefined)
415
+ return { ok: false, reason: "no-channel", detail: `Nothing is published on the "${channel}" channel yet.` };
416
+ if (!isVersionLike(version))
417
+ return { ok: false, reason: "failed", detail: "The registry returned an invalid version." };
418
+ return { ok: true, version: version.trim() };
419
+ }
420
+ /** Current vs the channel's version, as one state for messages and decisions. */
421
+ export async function checkChannel(channel = defaultUpdateChannel(), current = getCurrentVersion()) {
422
+ const latest = await fetchChannelVersion(channel);
423
+ if (!latest.ok) {
424
+ if (latest.reason === "no-npm")
425
+ return { kind: "no-npm", current };
426
+ if (latest.reason === "no-channel")
427
+ return { kind: "no-channel", current, channel, detail: latest.detail };
428
+ return { kind: "unreachable", current, detail: latest.detail };
429
+ }
430
+ let cmp;
431
+ try {
432
+ cmp = compareVersions(current, latest.version);
433
+ }
434
+ catch {
435
+ return { kind: "unreachable", current, detail: "The installed version could not be read." };
436
+ }
437
+ if (cmp === 0)
438
+ return { kind: "current", current, latest: latest.version };
439
+ return cmp < 0 ? { kind: "available", current, latest: latest.version } : { kind: "ahead", current, latest: latest.version };
440
+ }
441
+ async function globalRootAsync() {
442
+ const res = await npmRunner(["root", "-g"], VIEW_TIMEOUT_MS);
443
+ if (res.error || res.status !== 0)
444
+ return null;
445
+ const out = String(res.stdout || "").trim();
446
+ // npm redacts strings that look like secrets in everything it prints —
447
+ // including a UUID-like folder in a path, shown as "***". A redacted path is
448
+ // not a path; never compare against it.
449
+ if (!out || out.includes("***"))
450
+ return null;
451
+ return path.resolve(out);
452
+ }
453
+ function realpathSafe(p) {
454
+ try {
455
+ return fs.realpathSync(p);
456
+ }
457
+ catch {
458
+ return path.resolve(p);
459
+ }
460
+ }
461
+ /**
462
+ * Where npm's global packages can live, computed without parsing npm output:
463
+ * an explicit NPM_CONFIG_PREFIX, npm's default prefix next to this Node, and
464
+ * the per-user Windows location.
465
+ */
466
+ export function globalRootCandidates(env = process.env, execPath = process.execPath, platform = process.platform) {
467
+ const nm = (prefix) => (platform === "win32" ? path.join(prefix, "node_modules") : path.join(prefix, "lib", "node_modules"));
468
+ const out = [];
469
+ const prefix = env.NPM_CONFIG_PREFIX || env.npm_config_prefix;
470
+ if (prefix)
471
+ out.push(nm(prefix));
472
+ out.push(platform === "win32" ? path.join(path.dirname(execPath), "node_modules") : nm(path.dirname(path.dirname(execPath))));
473
+ if (platform === "win32" && env.APPDATA)
474
+ out.push(path.join(env.APPDATA, "npm", "node_modules"));
475
+ return out;
476
+ }
477
+ /**
478
+ * The global root implied by the install layout itself: a global package sits
479
+ * at <prefix>/lib/node_modules/<pkg> with its launcher in <prefix>/bin (on
480
+ * Windows: <prefix>/node_modules/<pkg> with <prefix>/cos.cmd). A project
481
+ * dependency's launcher lives in node_modules/.bin instead, so the two cannot
482
+ * be confused.
483
+ */
484
+ export function layoutGlobalRoot(here, name = packageName(), platform = process.platform) {
485
+ const depth = name.split("/").length;
486
+ let nmDir = here;
487
+ for (let i = 0; i < depth; i++)
488
+ nmDir = path.dirname(nmDir);
489
+ if (path.basename(nmDir) !== "node_modules")
490
+ return null;
491
+ const bins = ["cos", "carrieros", "cos-staging"];
492
+ if (platform === "win32") {
493
+ const prefix = path.dirname(nmDir);
494
+ return bins.some((b) => fs.existsSync(path.join(prefix, b + ".cmd"))) ? nmDir : null;
495
+ }
496
+ const lib = path.dirname(nmDir);
497
+ if (path.basename(lib) !== "lib")
498
+ return null;
499
+ const prefix = path.dirname(lib);
500
+ return bins.some((b) => fs.existsSync(path.join(prefix, "bin", b))) ? nmDir : null;
501
+ }
502
+ export async function detectInstallation(opts = {}) {
503
+ if (opts.packaged)
504
+ return { kind: "packaged" };
505
+ const here = opts.here === undefined ? packageRoot() : opts.here;
506
+ if (!here)
507
+ return { kind: "unknown" };
508
+ const parts = here.split(/[\\/]+/);
509
+ if (parts.includes("_npx"))
510
+ return { kind: "npx" };
511
+ // Compare REAL paths: the launcher is usually a symlink, and /tmp-style
512
+ // aliases differ from what the module was loaded from.
513
+ const real = realpathSafe(here);
514
+ const npmRoot = await globalRootAsync();
515
+ const candidates = [...(npmRoot ? [npmRoot] : []), ...globalRootCandidates()];
516
+ const globalRoot = candidates.map(realpathSafe).find((root) => isInside(root, real)) ?? layoutGlobalRoot(real) ?? null;
517
+ if (globalRoot) {
518
+ const installed = path.join(globalRoot, ...packageName().split("/"));
519
+ try {
520
+ if (fs.lstatSync(installed).isSymbolicLink())
521
+ return { kind: "development", globalRoot };
522
+ }
523
+ catch {
524
+ /* fall through */
525
+ }
526
+ let writable = false;
527
+ try {
528
+ fs.accessSync(globalRoot, fs.constants.W_OK);
529
+ fs.accessSync(here, fs.constants.W_OK);
530
+ writable = true;
531
+ }
532
+ catch {
533
+ writable = false;
534
+ }
535
+ return { kind: "global", globalRoot, writable };
536
+ }
537
+ if (parts.includes("node_modules"))
538
+ return { kind: "local" };
539
+ return { kind: "development" };
540
+ }
541
+ /** The version on disk for the global install, read fresh (never cliVersion()). */
542
+ export function installedGlobalVersion(globalRoot, name = packageName()) {
543
+ try {
544
+ const parsed = JSON.parse(fs.readFileSync(path.join(globalRoot, ...name.split("/"), "package.json"), "utf8"));
545
+ return isVersionLike(parsed.version) ? parsed.version : null;
546
+ }
547
+ catch {
548
+ return null;
549
+ }
550
+ }
551
+ /**
552
+ * Install one EXACT version (never a moving tag), then read back what is on
553
+ * disk. Success means the expected version is installed, not that npm exited 0.
554
+ */
555
+ export async function installExactVersion(version, globalRoot, name = packageName()) {
556
+ if (!isVersionLike(version) || !ALLOWED_PACKAGES.has(name)) {
557
+ return { ok: false, detail: "Refused: unexpected package or version.", permission: false, installed: null };
558
+ }
559
+ const res = await npmRunner(["install", "-g", `${name}@${version}`], INSTALL_TIMEOUT_MS);
560
+ const output = (String(res.stdout || "") + "\n" + String(res.stderr || "")).trim();
561
+ if (res.error) {
562
+ return {
563
+ ok: false,
564
+ detail: res.error.code === "ENOENT" ? "npm was not found on this system." : res.error.message,
565
+ permission: false,
566
+ installed: null
567
+ };
568
+ }
569
+ if (res.status !== 0) {
570
+ return {
571
+ ok: false,
572
+ detail: lastMeaningfulLines(output) || "npm exited with code " + res.status,
573
+ permission: /EACCES|EPERM|permission denied|Access is denied/i.test(output),
574
+ installed: null
575
+ };
576
+ }
577
+ const root = globalRoot ?? (await globalRootAsync()) ?? globalRootCandidates().find((r) => fs.existsSync(path.join(r, ...name.split("/")))) ?? null;
578
+ const installed = root ? installedGlobalVersion(root, name) : null;
579
+ return installed === version
580
+ ? { ok: true, detail: output, permission: false, installed }
581
+ : { ok: false, detail: `npm finished but ${name}@${version} was not found on disk.`, permission: false, installed };
582
+ }
583
+ // ── Cross-process coordination ──────────────────────────────────────────────
584
+ function pidAlive(pid) {
585
+ if (!Number.isInteger(pid) || pid <= 0)
586
+ return false;
587
+ try {
588
+ process.kill(pid, 0);
589
+ return true;
590
+ }
591
+ catch (err) {
592
+ return err.code === "EPERM";
593
+ }
594
+ }
595
+ /** A stale lock (owner gone, or older than this) is taken over. */
596
+ const LOCK_STALE_MS = 30 * 60 * 1000;
597
+ /**
598
+ * One update at a time across every CLI window on the machine. The lock file
599
+ * holds the owning pid; a dead owner or an old lock is stale and replaced.
600
+ */
601
+ export function acquireUpdateLock(dir, pid = process.pid, now = Date.now()) {
602
+ const file = path.join(dir, "update.lock");
603
+ for (let attempt = 0; attempt < 2; attempt++) {
604
+ try {
605
+ fs.mkdirSync(dir, { recursive: true });
606
+ fs.writeFileSync(file, JSON.stringify({ pid, at: now }), { flag: "wx" });
607
+ return true;
608
+ }
609
+ catch (err) {
610
+ if (err.code !== "EEXIST")
611
+ return false;
612
+ try {
613
+ const held = JSON.parse(fs.readFileSync(file, "utf8"));
614
+ const stale = !pidAlive(Number(held.pid)) || now - Number(held.at ?? 0) > LOCK_STALE_MS;
615
+ if (!stale)
616
+ return false;
617
+ fs.rmSync(file, { force: true });
618
+ }
619
+ catch {
620
+ fs.rmSync(file, { force: true });
621
+ }
622
+ }
623
+ }
624
+ return false;
625
+ }
626
+ /** Hand the lock to another process (the detached installer) or rewrite it. */
627
+ export function transferUpdateLock(dir, pid, now = Date.now()) {
628
+ try {
629
+ fs.writeFileSync(path.join(dir, "update.lock"), JSON.stringify({ pid, at: now }));
630
+ }
631
+ catch {
632
+ /* best effort */
633
+ }
634
+ }
635
+ export function releaseUpdateLock(dir, pid = process.pid) {
636
+ const file = path.join(dir, "update.lock");
637
+ try {
638
+ const held = JSON.parse(fs.readFileSync(file, "utf8"));
639
+ if (Number(held.pid) === pid)
640
+ fs.rmSync(file, { force: true });
641
+ }
642
+ catch {
643
+ /* nothing held */
644
+ }
645
+ }
646
+ /** True while an update (in this or another process) holds the lock. */
647
+ export function updateInProgress(dir, now = Date.now()) {
648
+ try {
649
+ const held = JSON.parse(fs.readFileSync(path.join(dir, "update.lock"), "utf8"));
650
+ return pidAlive(Number(held.pid)) && now - Number(held.at ?? 0) <= LOCK_STALE_MS;
651
+ }
652
+ catch {
653
+ return false;
654
+ }
655
+ }
656
+ /**
657
+ * Live CLI windows on this machine. A background install replaces files on
658
+ * disk, so it waits until the last window has closed: no running CLI ever has
659
+ * its package swapped underneath it.
660
+ */
661
+ export function registerInstance(dir, pid = process.pid) {
662
+ const instances = path.join(dir, "instances");
663
+ const file = path.join(instances, String(pid));
664
+ try {
665
+ fs.mkdirSync(instances, { recursive: true });
666
+ fs.writeFileSync(file, String(Date.now()));
667
+ }
668
+ catch {
669
+ /* best effort */
670
+ }
671
+ return () => fs.rmSync(file, { force: true });
672
+ }
673
+ export function otherLiveInstances(dir, pid = process.pid) {
674
+ const instances = path.join(dir, "instances");
675
+ let names = [];
676
+ try {
677
+ names = fs.readdirSync(instances);
678
+ }
679
+ catch {
680
+ return 0;
681
+ }
682
+ let live = 0;
683
+ for (const name of names) {
684
+ const other = Number(name);
685
+ if (other === pid)
686
+ continue;
687
+ if (pidAlive(other))
688
+ live++;
689
+ else
690
+ fs.rmSync(path.join(instances, name), { force: true });
691
+ }
692
+ return live;
693
+ }
694
+ /** Start npm detached, output to a log file; returns its pid. */
695
+ const spawnDetachedNpm = (command, args, logFile) => {
696
+ let fd = null;
697
+ try {
698
+ fd = fs.openSync(logFile, "w");
699
+ const child = SPAWN_SHELL
700
+ ? spawn([command, ...args].join(" "), { shell: true, detached: true, windowsHide: true, stdio: ["ignore", fd, fd], env: { ...process.env, CARRIEROS_UPDATING: "1" } })
701
+ : spawn(command, args, { detached: true, windowsHide: true, stdio: ["ignore", fd, fd], env: { ...process.env, CARRIEROS_UPDATING: "1" } });
702
+ child.unref();
703
+ return child.pid ?? null;
704
+ }
705
+ catch {
706
+ return null;
707
+ }
708
+ finally {
709
+ if (fd !== null)
710
+ fs.closeSync(fd);
711
+ }
712
+ };
713
+ let detachedSpawner = spawnDetachedNpm;
714
+ export function setDetachedSpawnerForTests(spawner) {
715
+ detachedSpawner = spawner ?? spawnDetachedNpm;
716
+ }
717
+ /**
718
+ * Start the background install of an exact version, detached so it runs after
719
+ * this process has exited. The lock passes to the installer's pid, so no other
720
+ * window starts a second install while it runs.
721
+ */
722
+ export function startDetachedInstall(dir, version, name = packageName()) {
723
+ if (!isVersionLike(version) || !ALLOWED_PACKAGES.has(name))
724
+ return false;
725
+ const pid = detachedSpawner(NPM_BIN, ["install", "-g", `${name}@${version}`], path.join(dir, "update.log"));
726
+ if (!pid)
727
+ return false;
728
+ transferUpdateLock(dir, pid);
729
+ return true;
730
+ }