@carrieros/cli 0.1.0 → 0.3.0

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 (104) hide show
  1. package/README.md +142 -57
  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 +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,108 @@
1
+ import { ApiError } from "./api.js";
2
+ import { withSpinner } from "./spinner.js";
3
+ /**
4
+ * The one place a session is looked up.
5
+ *
6
+ * `/sessions` prints an ordered list; every other session command then accepts
7
+ * the ordinal from that list ("2") as well as the raw id. Commands call
8
+ * `resolveSessionRef` and never do their own lookup, so the numbering can only
9
+ * ever mean one thing.
10
+ *
11
+ * The ordinal map is PERSISTED rather than held in memory: each standalone `cos`
12
+ * invocation is a separate process, so `cos sessions` followed by
13
+ * `cos session 2` would otherwise have nothing to resolve against.
14
+ */
15
+ /** A session id as the API issues them — anything else is treated as an ordinal. */
16
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ export function looksLikeSessionId(token) {
18
+ return UUID_RE.test(token.trim());
19
+ }
20
+ /** Thrown when a reference can't be turned into a session. Message is user-facing. */
21
+ export class SessionRefError extends Error {
22
+ hint;
23
+ constructor(message, hint) {
24
+ super(message);
25
+ this.hint = hint;
26
+ this.name = "SessionRefError";
27
+ }
28
+ }
29
+ /** Fetch a page of conversations and remember the order for ordinal lookups. */
30
+ export async function listSessions(ctx, client, opts = {}) {
31
+ const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
32
+ const fetch = () => client.conversations({ limit });
33
+ const { conversations, pagination } = opts.spinner === false
34
+ ? await fetch()
35
+ : await withSpinner("Loading sessions…", fetch);
36
+ ctx.config.set("sessionOrdinals", conversations.map((cv) => cv.session_id));
37
+ return { conversations, total: pagination.total };
38
+ }
39
+ /** The ordinal map from the last listing, or an empty array if there isn't one. */
40
+ export function currentOrdinals(ctx) {
41
+ return ctx.config.get("sessionOrdinals") ?? [];
42
+ }
43
+ /** 1-based position of a session in the last listing, or null. */
44
+ export function ordinalOf(ctx, sessionId) {
45
+ const i = currentOrdinals(ctx).indexOf(sessionId);
46
+ return i === -1 ? null : i + 1;
47
+ }
48
+ /**
49
+ * Turn a user-supplied reference into a session id.
50
+ *
51
+ * Accepts, in order of precedence:
52
+ * - a full session id → returned as-is (scripting, and every pre-existing
53
+ * `session use <uuid>` / `history <uuid>` call site)
54
+ * - an ordinal from the last `/sessions` listing
55
+ *
56
+ * A stale ordinal triggers ONE refresh before giving up, so the common case —
57
+ * listing in one process and acting in another, or acting after a deletion —
58
+ * resolves silently instead of making the user re-run `/sessions` by hand.
59
+ */
60
+ export async function resolveSessionRef(ctx, client, ref) {
61
+ const token = ref.trim();
62
+ if (!token)
63
+ throw new SessionRefError("No session given.", "Run /sessions to see the list.");
64
+ if (looksLikeSessionId(token))
65
+ return token;
66
+ const n = Number(token);
67
+ if (!Number.isInteger(n) || n < 1) {
68
+ throw new SessionRefError(`"${token}" is not a session number or id.`, "Run /sessions to see the numbered list.");
69
+ }
70
+ const fromCache = currentOrdinals(ctx)[n - 1];
71
+ if (fromCache)
72
+ return fromCache;
73
+ // Nothing cached (or the list was shorter) — refresh once, then decide.
74
+ const { conversations } = await listSessions(ctx, client, { spinner: false });
75
+ const refreshed = conversations[n - 1]?.session_id;
76
+ if (refreshed)
77
+ return refreshed;
78
+ throw new SessionRefError(conversations.length === 0
79
+ ? `Session ${n} is no longer available.`
80
+ : `Session ${n} is no longer available. There ${conversations.length === 1 ? "is" : "are"} ${conversations.length}.`, "Run /sessions to refresh the list.");
81
+ }
82
+ /** Resolve a reference AND load the session, so callers get a verified title. */
83
+ export async function resolveSession(ctx, client, ref) {
84
+ const id = await resolveSessionRef(ctx, client, ref);
85
+ try {
86
+ const s = await client.session(id);
87
+ return { session_id: s.session_id, title: s.title, message_count: s.message_count };
88
+ }
89
+ catch (err) {
90
+ // A 404 here means the id resolved but the conversation is gone (deleted in
91
+ // another window, or no longer in this project) — say that, not "not found".
92
+ if (err instanceof ApiError && err.status === 404) {
93
+ throw new SessionRefError("That session is no longer available.", "Run /sessions to refresh the list.");
94
+ }
95
+ throw err;
96
+ }
97
+ }
98
+ /** Remember the active session and its title so the footer can name it. */
99
+ export function setActiveSession(ctx, id, title) {
100
+ ctx.config.set("sessionId", id);
101
+ if (title !== undefined)
102
+ ctx.config.set("sessionTitle", title);
103
+ }
104
+ /** Forget the active session (a fresh conversation starts on the next message). */
105
+ export function clearActiveSession(ctx) {
106
+ ctx.config.set("sessionId", undefined);
107
+ ctx.config.set("sessionTitle", undefined);
108
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * SIA answer merging — the CLI half of the website's lib/sia/answer-merger.ts.
3
+ *
4
+ * Clarification answers are not sent as a separate field: they are appended to
5
+ * the prompt itself, and the merged string is what /v1/chat stores as the user
6
+ * message. Both clients therefore have to agree on the marker EXACTLY. If this
7
+ * string drifts by one character, a conversation started in the CLI renders its
8
+ * raw marker on the website (and vice-versa), because the reader below is the
9
+ * only thing that splits the block back off for display.
10
+ */
11
+ /** Verbatim from the website. Do not "tidy" the whitespace. */
12
+ const SIA_MARKER = "\n\n[Clarification Context]\n";
13
+ /** snake_case key → "Snake Case", the label shown in the appended block. */
14
+ function formatKey(key) {
15
+ return key.replace(/_/g, " ").replace(/\b\w/g, (ch) => ch.toUpperCase());
16
+ }
17
+ /**
18
+ * Append the answers to the prompt. Returns the original untouched when nothing
19
+ * was answered, so a skipped Q&A is indistinguishable from SIA being off.
20
+ */
21
+ export function buildStructuredIntent(original, answers) {
22
+ const entries = Object.entries(answers).filter(([, v]) => v !== null && v !== undefined && v !== "");
23
+ if (entries.length === 0)
24
+ return original;
25
+ const lines = entries.map(([key, value]) => {
26
+ const display = typeof value === "boolean" ? (value ? "Yes" : "No") : String(value);
27
+ return `${formatKey(key)}: ${display}`;
28
+ });
29
+ return `${original}${SIA_MARKER}${lines.join("\n")}`;
30
+ }
31
+ /**
32
+ * Split a stored message back into the typed prompt and its clarification
33
+ * items, or null when there is no block. Used when replaying a transcript —
34
+ * including transcripts written by the website.
35
+ */
36
+ export function parseSiaContext(content) {
37
+ const idx = content.indexOf(SIA_MARKER);
38
+ if (idx === -1)
39
+ return null;
40
+ const displayPrompt = content.slice(0, idx).trim();
41
+ const items = content
42
+ .slice(idx + SIA_MARKER.length)
43
+ .trim()
44
+ .split("\n")
45
+ .filter((l) => l.includes(": "))
46
+ .map((l) => {
47
+ const at = l.indexOf(": ");
48
+ return { label: l.slice(0, at), value: l.slice(at + 2) };
49
+ });
50
+ return items.length > 0 ? { displayPrompt, items } : null;
51
+ }
@@ -1,9 +1,31 @@
1
1
  import ora from "ora";
2
+ import { screenActive, screenTransient } from "../ui/screen.js";
3
+ const FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
2
4
  /**
3
5
  * Run an async task under a spinner. The spinner is always stopped afterwards
4
- * (success or throw) so it can never be left spinning on an error path.
6
+ * (success or throw) so it can never be left spinning on an error path. Inside
7
+ * the interactive shell the spinner renders as a transient line above the pinned
8
+ * composer (via the screen engine) instead of writing to stdout directly.
5
9
  */
6
10
  export async function withSpinner(text, fn) {
11
+ if (screenActive()) {
12
+ const state = { text };
13
+ let i = 0;
14
+ const paint = () => screenTransient([" " + FRAMES[i % FRAMES.length] + " " + state.text]);
15
+ paint();
16
+ const timer = setInterval(() => {
17
+ i++;
18
+ paint();
19
+ }, 80);
20
+ timer.unref?.();
21
+ try {
22
+ return await fn(state);
23
+ }
24
+ finally {
25
+ clearInterval(timer);
26
+ screenTransient([]); // clear the spinner line; real output follows via line()
27
+ }
28
+ }
7
29
  // discardStdin:false — otherwise ora grabs/pauses stdin while spinning, which
8
30
  // corrupts the interactive shell's readline and makes it exit after one turn.
9
31
  const spinner = ora({ text, color: "cyan", discardStdin: false }).start();
@@ -0,0 +1,286 @@
1
+ import { 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); identifiers compare as strings, which covers -rc.N and
56
+ * -beta.N without taking on a semver dependency.
57
+ */
58
+ export function compareVersions(a, b) {
59
+ const parse = (v) => {
60
+ const [core, ...rest] = String(v).trim().replace(/^v/, "").split("-");
61
+ const nums = core.split(".").map((n) => Number.parseInt(n, 10) || 0);
62
+ while (nums.length < 3)
63
+ nums.push(0);
64
+ return { nums, pre: rest.join("-") };
65
+ };
66
+ const x = parse(a);
67
+ const y = parse(b);
68
+ for (let i = 0; i < 3; i++) {
69
+ if (x.nums[i] !== y.nums[i])
70
+ return x.nums[i] < y.nums[i] ? -1 : 1;
71
+ }
72
+ if (x.pre === y.pre)
73
+ return 0;
74
+ if (!x.pre)
75
+ return 1;
76
+ if (!y.pre)
77
+ return -1;
78
+ return x.pre < y.pre ? -1 : 1;
79
+ }
80
+ /** Guards every version that reaches a comparison or a message. */
81
+ export function isVersionLike(v) {
82
+ return typeof v === "string" && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(v.trim());
83
+ }
84
+ export function getLatestVersion() {
85
+ let res;
86
+ try {
87
+ res = runNpm(["view", PACKAGE_NAME, "version", "--json"], VIEW_TIMEOUT_MS);
88
+ }
89
+ catch (err) {
90
+ return { ok: false, reason: "failed", detail: err.message };
91
+ }
92
+ // ENOENT means npm is missing from PATH — a different problem from a
93
+ // registry failure, and it needs different advice.
94
+ if (res.error && res.error.code === "ENOENT") {
95
+ return { ok: false, reason: "no-npm", detail: "npm was not found on this system." };
96
+ }
97
+ if (res.error)
98
+ return { ok: false, reason: "failed", detail: res.error.message };
99
+ if (res.status !== 0) {
100
+ const first = String(res.stderr || res.stdout || "").trim().split("\n")[0];
101
+ return { ok: false, reason: "failed", detail: first || "npm exited with code " + res.status };
102
+ }
103
+ // --json yields a quoted string for one version, a bare string under some
104
+ // configs, and an array when several match. Accept all three.
105
+ const raw = String(res.stdout || "").trim();
106
+ let parsed = raw;
107
+ try {
108
+ parsed = JSON.parse(raw);
109
+ }
110
+ catch {
111
+ parsed = raw.replace(/^"|"$/g, "");
112
+ }
113
+ if (Array.isArray(parsed))
114
+ parsed = parsed[parsed.length - 1];
115
+ const version = typeof parsed === "string" ? parsed.trim() : "";
116
+ if (!isVersionLike(version)) {
117
+ return { ok: false, reason: "failed", detail: "Unexpected npm output: " + raw.slice(0, 80) };
118
+ }
119
+ return { ok: true, version };
120
+ }
121
+ export function checkForUpdate() {
122
+ const current = getCurrentVersion();
123
+ const latest = getLatestVersion();
124
+ if (!latest.ok) {
125
+ return latest.reason === "no-npm"
126
+ ? { kind: "no-npm", current }
127
+ : { kind: "unreachable", current, detail: latest.detail };
128
+ }
129
+ const cmp = compareVersions(current, latest.version);
130
+ if (cmp === 0)
131
+ return { kind: "current", current, latest: latest.version };
132
+ return cmp < 0
133
+ ? { kind: "available", current, latest: latest.version }
134
+ : { kind: "ahead", current, latest: latest.version };
135
+ }
136
+ /** Absolute path of the package this process runs from. */
137
+ export function packageRoot() {
138
+ try {
139
+ return path.resolve(fileURLToPath(new URL("../..", import.meta.url)));
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ function npmGlobalRoot() {
146
+ try {
147
+ const res = runNpm(["root", "-g"], VIEW_TIMEOUT_MS);
148
+ if (res.status !== 0)
149
+ return null;
150
+ const out = String(res.stdout || "").trim();
151
+ return out ? path.resolve(out) : null;
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ }
157
+ /** Windows paths differ only in case, so containment compares case-folded. */
158
+ function isInside(parent, child) {
159
+ const rel = path.relative(parent.toLowerCase(), child.toLowerCase());
160
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
161
+ }
162
+ /**
163
+ * True when the global package is a link to a working copy (npm link).
164
+ *
165
+ * MANDATORY GUARD: `npm i -g` against a linked install replaces the symlink and
166
+ * the developer silently loses the link to their checkout. Two independent
167
+ * signals, either conclusive:
168
+ * 1. the global package path is itself a symlink;
169
+ * 2. this process runs from outside the global npm root, so updating the
170
+ * global copy would not change what is executing anyway.
171
+ */
172
+ export function isLinkedInstallation() {
173
+ const globalRoot = npmGlobalRoot();
174
+ if (!globalRoot)
175
+ return false;
176
+ const installed = path.join(globalRoot, ...PACKAGE_NAME.split("/"));
177
+ try {
178
+ if (fs.lstatSync(installed).isSymbolicLink())
179
+ return true;
180
+ }
181
+ catch {
182
+ /* not installed globally — fall through to the location check */
183
+ }
184
+ const here = packageRoot();
185
+ return here ? !isInside(globalRoot, here) : false;
186
+ }
187
+ /**
188
+ * Install the latest published version.
189
+ *
190
+ * `install @latest`, never `npm update`: the intent is "give me the published
191
+ * latest", and update obeys semver ranges instead.
192
+ */
193
+ export function installLatest() {
194
+ let res;
195
+ try {
196
+ res = runNpm(["install", "-g", PACKAGE_NAME + "@latest"], INSTALL_TIMEOUT_MS);
197
+ }
198
+ catch (err) {
199
+ return { ok: false, detail: err.message, permission: false };
200
+ }
201
+ if (res.error) {
202
+ const code = res.error.code;
203
+ return {
204
+ ok: false,
205
+ detail: code === "ENOENT" ? "npm was not found on this system." : res.error.message,
206
+ permission: false
207
+ };
208
+ }
209
+ const output = (String(res.stdout || "") + "\n" + String(res.stderr || "")).trim();
210
+ if (res.status === 0)
211
+ return { ok: true, detail: output, permission: false };
212
+ return {
213
+ ok: false,
214
+ detail: lastMeaningfulLines(output) || "npm exited with code " + res.status,
215
+ permission: /EACCES|EPERM|permission denied|Access is denied/i.test(output)
216
+ };
217
+ }
218
+ /**
219
+ * What is on disk now.
220
+ *
221
+ * The running process cannot answer this — its own package.json is already read
222
+ * and the old modules stay loaded — so this reads the freshly installed
223
+ * package.json from the global root rather than trusting cliVersion().
224
+ */
225
+ export function verifyInstallation() {
226
+ const globalRoot = npmGlobalRoot();
227
+ if (!globalRoot)
228
+ return null;
229
+ try {
230
+ const pkg = path.join(globalRoot, ...PACKAGE_NAME.split("/"), "package.json");
231
+ const parsed = JSON.parse(fs.readFileSync(pkg, "utf8"));
232
+ return isVersionLike(parsed.version) ? parsed.version : null;
233
+ }
234
+ catch {
235
+ return null;
236
+ }
237
+ }
238
+ /** The last few actionable lines of npm output — enough to act on, not a wall. */
239
+ function lastMeaningfulLines(output, max = 6) {
240
+ return output
241
+ .split(/\r?\n/)
242
+ .map((l) => l.trim())
243
+ .filter((l) => l && !/^npm (notice|warn) /i.test(l))
244
+ .slice(-max)
245
+ .join("\n");
246
+ }
247
+ // ── Startup notice ───────────────────────────────────────────────────────────
248
+ // The banner renders once, and rewriting it later would mean mutating the
249
+ // screen engine mid-frame. So the notice is built from the PREVIOUS check and a
250
+ // fresh one runs afterwards, off the startup path — a new release is announced
251
+ // on the next launch, and startup is never delayed or failed by npm.
252
+ /** How long a cached result stays good. */
253
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
254
+ /** Notice line for the banner, or null when current / unknown. */
255
+ export function cachedUpdateNotice(cache) {
256
+ const latest = cache.get("latestCliVersion");
257
+ if (!isVersionLike(latest))
258
+ return null;
259
+ return compareVersions(getCurrentVersion(), latest) < 0
260
+ ? "Update available: v" + latest + " — run /update to upgrade."
261
+ : null;
262
+ }
263
+ /** True when the cached result is stale enough to re-check. */
264
+ export function shouldRefreshCheck(cache, now = Date.now()) {
265
+ const ok = cache.get("updateCheckAt") ?? 0;
266
+ const failed = cache.get("updateCheckErrorAt") ?? 0;
267
+ // A failure also starts the clock, so an offline machine retries once a day
268
+ // instead of shelling out to npm on every launch.
269
+ return now - Math.max(ok, failed) >= CHECK_INTERVAL_MS;
270
+ }
271
+ /**
272
+ * Refresh the cache. Call AFTER the shell is up — spawnSync blocks, so this
273
+ * must never sit between the user and their prompt.
274
+ */
275
+ export function refreshUpdateCache(cache, now = Date.now()) {
276
+ const latest = getLatestVersion();
277
+ if (latest.ok) {
278
+ cache.set("latestCliVersion", latest.version);
279
+ cache.set("updateCheckAt", now);
280
+ }
281
+ else {
282
+ // Recorded, never shown: a background check that fails is not the user's
283
+ // problem, and surfacing it every launch would be noise.
284
+ cache.set("updateCheckErrorAt", now);
285
+ }
286
+ }