@carrieros/cli 0.2.0 → 0.4.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.
- package/README.md +170 -64
- package/dist/commands/attach.js +45 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +81 -15
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +63 -3
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +1 -0
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +31 -7
- package/dist/commands/logout.js +1 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +39 -3
- package/dist/commands/modes.js +4 -1
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +224 -65
- package/dist/commands/settings.js +94 -0
- package/dist/commands/update.js +229 -0
- package/dist/commands/upload.js +204 -31
- package/dist/commands/usage.js +213 -17
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +355 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +26 -1
- package/dist/services/api.js +315 -15
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +352 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +311 -24
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +296 -23
- package/dist/services/device-auth.js +72 -35
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +55 -17
- package/dist/services/meta.js +3 -1
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +5 -2
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +60 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +113 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +311 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1297 -59
- package/dist/shell/shell-commands.js +243 -12
- package/dist/shell/shell-prompt.js +94 -11
- package/dist/shell/shell-renderer.js +8 -20
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +252 -22
- package/dist/shell/task-context-view.js +40 -0
- package/dist/types/index.js +3 -1
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +31 -48
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +207 -14
- package/dist/ui/colors.js +12 -8
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +26 -5
- package/dist/ui/command-palette.js +44 -14
- package/dist/ui/command-registry.js +92 -10
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +48 -1
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +4 -2
- package/dist/ui/markdown.js +63 -9
- package/dist/ui/message.js +14 -31
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +191 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +27 -1
- package/package.json +18 -4
- package/dist/ui/activity.js +0 -77
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const LIST = 6;
|
|
2
|
+
export function taskSnapshot(context) {
|
|
3
|
+
const t = context?.current;
|
|
4
|
+
if (!t)
|
|
5
|
+
return null;
|
|
6
|
+
const files = t.changes.files ?? { created: [], modified: [], deleted: [] };
|
|
7
|
+
const runs = t.validation.runs;
|
|
8
|
+
return {
|
|
9
|
+
title: t.title,
|
|
10
|
+
repository: t.repository,
|
|
11
|
+
status: t.workflow_state ?? t.verified_state,
|
|
12
|
+
verified: t.verified_state,
|
|
13
|
+
plan: t.plan.summary,
|
|
14
|
+
inspected: { files: t.investigation.files.slice(0, LIST), total: t.investigation.files.length + t.investigation.files_omitted },
|
|
15
|
+
investigation: {
|
|
16
|
+
searches: t.investigation.searches.length + t.investigation.searches_omitted,
|
|
17
|
+
symbols: (t.investigation.symbols_traced ?? []).slice(0, LIST),
|
|
18
|
+
relationships: (t.investigation.relationships ?? []).slice(0, LIST),
|
|
19
|
+
outlines: t.investigation.outlines ?? 0
|
|
20
|
+
},
|
|
21
|
+
rootCause: t.root_cause,
|
|
22
|
+
symptom: t.plan.investigation?.symptom ?? null,
|
|
23
|
+
changeLocation: t.plan.investigation?.change_location ?? null,
|
|
24
|
+
executionPath: (t.plan.investigation?.execution_path ?? []).slice(0, 8),
|
|
25
|
+
evidence: (t.plan.investigation?.evidence ?? []).slice(0, 4).map((e) => `${e.path ?? "?"}${e.lines ? `:${e.lines}` : ""}${e.note ? ` — ${e.note}` : ""}`),
|
|
26
|
+
ruledOut: (t.plan.investigation?.ruled_out ?? []).slice(0, 4).map((r) => `${r.path ?? "?"}${r.reason ? ` — ${r.reason}` : ""}`),
|
|
27
|
+
modified: files.modified.slice(0, LIST),
|
|
28
|
+
created: files.created.slice(0, LIST),
|
|
29
|
+
deleted: files.deleted.slice(0, LIST),
|
|
30
|
+
unresolved: [...new Set(t.changes.items.filter((c) => c.outcome === "unresolved").map((c) => c.path ?? "?"))].slice(0, LIST),
|
|
31
|
+
pendingOperations: t.pending_operations.slice(0, LIST),
|
|
32
|
+
corrections: t.corrections_total,
|
|
33
|
+
lastCorrection: t.corrections.at(-1)?.explanation ?? null,
|
|
34
|
+
tests: runs.slice(-LIST).map((r) => ({ command: r.command ?? "test", outcome: r.outcome })),
|
|
35
|
+
passed: runs.filter((r) => r.outcome === "passed").length,
|
|
36
|
+
failed: runs.filter((r) => r.outcome === "failed").length
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { ConfigStore } from "./config.js";
|
|
5
|
+
import { isSealed, seal, sealingAvailable, sealingRequired, unseal } from "./secure-store.js";
|
|
6
|
+
const TTL = 16 * 60 * 1000; // Recovery never extends the server's deadline.
|
|
7
|
+
const MAX_ENTRIES = 100;
|
|
8
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
9
|
+
const hash = (s) => crypto.createHash("sha256").update(s).digest("hex");
|
|
10
|
+
export class ToolDeliveryError extends Error {
|
|
11
|
+
code = "TOOL_RESULT_DELIVERY_FAILED";
|
|
12
|
+
constructor(message = "Tool result delivery failed. Any saved result will be retried before the next chat; the tool will not be rerun.") { super(message); this.name = "ToolDeliveryError"; }
|
|
13
|
+
}
|
|
14
|
+
/** Only routing metadata, never credentials, goes into the directory name.
|
|
15
|
+
* JWT claims are NOT authorization: the server still enforces every binding. */
|
|
16
|
+
export function toolResultScope(apiUrl, token) {
|
|
17
|
+
let identity = hash(token); // legacy/opaque credentials: exact token only
|
|
18
|
+
try {
|
|
19
|
+
const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
|
|
20
|
+
if (claims.realm === 'carrier-cli' && claims.typ === 'cli_access' &&
|
|
21
|
+
['sub', 'uid', 'sid'].every(k => typeof claims[k] === 'string' && claims[k].length > 0) &&
|
|
22
|
+
claims.sub === claims.uid && Number.isSafeInteger(claims.sv) && claims.sv >= 0 &&
|
|
23
|
+
claims.wsid == null && claims.pid == null && claims.developer_account_id == null) {
|
|
24
|
+
// Version the new realm without changing the legacy hash or moving files.
|
|
25
|
+
// Access-token renewal retains the session; a new login never inherits it.
|
|
26
|
+
identity = ['user-cli', 2, claims.uid, claims.sid, claims.sv];
|
|
27
|
+
}
|
|
28
|
+
else if (claims.realm !== 'carrier-cli' && claims.typ === 'cli_access' && ['sub', 'uid', 'sid'].every(k => typeof claims[k] === 'string') &&
|
|
29
|
+
['wsid', 'pid'].every(k => typeof claims[k] === 'string' || claims[k] === null)) {
|
|
30
|
+
identity = [claims.sub, claims.uid, claims.sid, claims.wsid, claims.pid, claims.tv ?? 0];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch { /* opaque credentials stay bound to their exact token */ }
|
|
34
|
+
return hash(JSON.stringify([new URL(apiUrl).origin, identity]));
|
|
35
|
+
}
|
|
36
|
+
/** Same canonical payload identity as the backend; transport timing is excluded. */
|
|
37
|
+
export function resultHash(payload) {
|
|
38
|
+
const canonical = (v) => Array.isArray(v) ? `[${v.map(canonical).join(",")}]`
|
|
39
|
+
: v && typeof v === "object" ? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
|
|
40
|
+
: JSON.stringify(v ?? null);
|
|
41
|
+
return hash(canonical(payload.ok ? { ok: true, result: payload.result } : { ok: false,
|
|
42
|
+
error: { code: payload.error.code.slice(0, 64), message: String(payload.error.message ?? "").slice(0, 500) } }));
|
|
43
|
+
}
|
|
44
|
+
/** Completed results only. Never stores executable work or starts an agent turn. */
|
|
45
|
+
export class ToolResultOutbox {
|
|
46
|
+
dir;
|
|
47
|
+
constructor(scope) {
|
|
48
|
+
this.dir = path.join(ConfigStore.resolveDir(), 'tool-result-outbox', scope);
|
|
49
|
+
}
|
|
50
|
+
file(id) { return path.join(this.dir, hash(id) + '.json'); }
|
|
51
|
+
read(file) {
|
|
52
|
+
try {
|
|
53
|
+
if (fs.statSync(file).size > MAX_BYTES * 2)
|
|
54
|
+
throw new Error();
|
|
55
|
+
const stored = fs.readFileSync(file, 'utf8');
|
|
56
|
+
const entry = JSON.parse(isSealed(stored) ? unseal(stored) : stored);
|
|
57
|
+
if (entry.version !== 1 || !Number.isFinite(entry.createdAt) || !entry.payload ||
|
|
58
|
+
typeof entry.payload.tool_call_id !== 'string' || typeof entry.payload.ok !== 'boolean' ||
|
|
59
|
+
this.file(entry.payload.tool_call_id) !== file)
|
|
60
|
+
throw new Error();
|
|
61
|
+
return entry;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new ToolDeliveryError('Saved tool result is unreadable. It was preserved; recovery cannot continue.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
put(payload, createdAt = Date.now()) {
|
|
68
|
+
try {
|
|
69
|
+
const serialized = JSON.stringify(payload);
|
|
70
|
+
if (Buffer.byteLength(serialized) > MAX_BYTES)
|
|
71
|
+
throw new ToolDeliveryError('Tool result exceeds the recovery storage limit. Nothing was submitted.');
|
|
72
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
73
|
+
const file = this.file(payload.tool_call_id);
|
|
74
|
+
// A completed payload may have been removed, but its durable identity
|
|
75
|
+
// remains authoritative. Validate it before publishing any new bytes.
|
|
76
|
+
if (fs.existsSync(file + '.state')) {
|
|
77
|
+
this.state(payload.tool_call_id); // validates the marker and existing payload
|
|
78
|
+
const marker = JSON.parse(fs.readFileSync(file + '.state', 'utf8'));
|
|
79
|
+
if (!marker.hash || marker.hash !== resultHash(payload)) {
|
|
80
|
+
throw new ToolDeliveryError('Saved delivery identity conflicts with this result. Original evidence was preserved.');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (fs.existsSync(file)) {
|
|
84
|
+
if (JSON.stringify(this.read(file).payload) !== serialized)
|
|
85
|
+
throw new ToolDeliveryError('A different result is already saved for this tool call. The original was preserved.');
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (fs.readdirSync(this.dir).filter(f => f.endsWith('.json')).length >= MAX_ENTRIES)
|
|
89
|
+
throw new ToolDeliveryError('Tool result recovery storage is full. Pending results were preserved.');
|
|
90
|
+
if (!Number.isFinite(createdAt) || createdAt > Date.now())
|
|
91
|
+
throw new ToolDeliveryError();
|
|
92
|
+
const entry = JSON.stringify({ version: 1, createdAt, payload });
|
|
93
|
+
if (sealingRequired() && !sealingAvailable())
|
|
94
|
+
throw new ToolDeliveryError('Secure tool result storage is unavailable. Nothing was submitted.');
|
|
95
|
+
const data = sealingAvailable() ? seal(entry) : entry;
|
|
96
|
+
const tmp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
|
|
97
|
+
try {
|
|
98
|
+
const fd = fs.openSync(tmp, 'wx', 0o600);
|
|
99
|
+
try {
|
|
100
|
+
fs.writeFileSync(fd, data);
|
|
101
|
+
fs.fsyncSync(fd);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
fs.closeSync(fd);
|
|
105
|
+
}
|
|
106
|
+
// Link publishes without overwriting another process's immutable result.
|
|
107
|
+
try {
|
|
108
|
+
fs.linkSync(tmp, file);
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
if (e.code !== 'EEXIST')
|
|
112
|
+
throw e;
|
|
113
|
+
if (JSON.stringify(this.read(file).payload) !== serialized)
|
|
114
|
+
throw new ToolDeliveryError('A different result is already saved for this tool call.');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
try {
|
|
119
|
+
fs.unlinkSync(tmp);
|
|
120
|
+
}
|
|
121
|
+
catch { /* interrupted before creation */ }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
if (e instanceof ToolDeliveryError)
|
|
126
|
+
throw e;
|
|
127
|
+
throw new ToolDeliveryError('Could not safely save the tool result for recovery. Nothing was submitted.');
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
expired(id) { return Date.now() - this.read(this.file(id)).createdAt > TTL; }
|
|
131
|
+
state(id) {
|
|
132
|
+
const file = this.file(id) + '.state';
|
|
133
|
+
if (!fs.existsSync(file))
|
|
134
|
+
return 'pending';
|
|
135
|
+
try {
|
|
136
|
+
const stat = fs.lstatSync(file);
|
|
137
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096)
|
|
138
|
+
throw new Error();
|
|
139
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
140
|
+
if (value.id !== id || !['pending', 'submitting', 'acknowledged', 'rejected', 'expired', 'unresolved'].includes(value.state))
|
|
141
|
+
throw new Error();
|
|
142
|
+
if (value.hash && fs.existsSync(this.file(id)) && resultHash(this.read(this.file(id)).payload) !== value.hash)
|
|
143
|
+
throw new Error();
|
|
144
|
+
return value.state;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw new ToolDeliveryError('Saved delivery state is unreadable; evidence was preserved.');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
mark(id, state) {
|
|
151
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
152
|
+
const file = this.file(id) + '.state', tmp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
|
|
153
|
+
try {
|
|
154
|
+
const payloadHash = fs.existsSync(this.file(id)) ? resultHash(this.read(this.file(id)).payload) : null;
|
|
155
|
+
const fd = fs.openSync(tmp, 'wx', 0o600);
|
|
156
|
+
try {
|
|
157
|
+
fs.writeFileSync(fd, JSON.stringify({ id, state, hash: payloadHash }));
|
|
158
|
+
fs.fsyncSync(fd);
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
fs.closeSync(fd);
|
|
162
|
+
}
|
|
163
|
+
fs.renameSync(tmp, file);
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
try {
|
|
167
|
+
fs.unlinkSync(tmp);
|
|
168
|
+
}
|
|
169
|
+
catch { }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
remove(id) { fs.rmSync(this.file(id), { force: true }); }
|
|
173
|
+
pending() {
|
|
174
|
+
if (!fs.existsSync(this.dir))
|
|
175
|
+
return { entries: [], expired: 0 };
|
|
176
|
+
const entries = [];
|
|
177
|
+
let expired = 0;
|
|
178
|
+
for (const name of fs.readdirSync(this.dir).filter(f => f.endsWith('.json'))) {
|
|
179
|
+
const entry = this.read(path.join(this.dir, name));
|
|
180
|
+
const state = this.state(entry.payload.tool_call_id);
|
|
181
|
+
if (['acknowledged', 'rejected', 'expired', 'unresolved'].includes(state))
|
|
182
|
+
continue;
|
|
183
|
+
if (Date.now() - entry.createdAt > TTL && state !== 'submitting') {
|
|
184
|
+
this.mark(entry.payload.tool_call_id, 'expired');
|
|
185
|
+
expired++;
|
|
186
|
+
}
|
|
187
|
+
else
|
|
188
|
+
entries.push(entry);
|
|
189
|
+
}
|
|
190
|
+
return { entries, expired };
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
export function terminalToolRejection(error) {
|
|
194
|
+
return [400, 403, 404, 409, 410, 413, 422].includes(error?.status ?? 0);
|
|
195
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
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). 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
|
+
}
|