@carrieros/cli 0.3.0 → 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.
- package/README.md +89 -15
- package/dist/commands/chat.js +6 -6
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +34 -14
- package/dist/commands/logout.js +2 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +83 -10
- package/dist/commands/update.js +177 -51
- package/dist/commands/usage.js +10 -8
- package/dist/commands/version.js +1 -3
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +288 -18
- package/dist/ide/tool-host.js +6 -6
- package/dist/main.js +10 -1
- package/dist/services/api.js +183 -15
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +123 -27
- 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 +85 -12
- package/dist/services/command-policy.js +34 -4
- package/dist/services/config.js +96 -11
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +98 -25
- package/dist/services/device-auth.js +33 -6
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-resolver.js +1 -1
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +181 -0
- package/dist/services/helper-bin.js +56 -35
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +31 -10
- package/dist/services/local-files.js +148 -26
- package/dist/services/local-tools.js +540 -35
- package/dist/services/login-flow.js +44 -13
- package/dist/services/meta.js +27 -0
- package/dist/services/mutation-coordinator.js +186 -20
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +264 -78
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +15 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +7 -1
- package/dist/services/project-context.js +4 -4
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +21 -1
- package/dist/services/session-resolver.js +7 -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 +457 -13
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +320 -34
- package/dist/shell/shell-commands.js +47 -5
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +107 -20
- package/dist/shell/task-context-view.js +40 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +46 -16
- package/dist/ui/banner.js +31 -87
- package/dist/ui/change-review.js +293 -46
- package/dist/ui/chat-renderer.js +6 -6
- package/dist/ui/colors.js +9 -9
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-palette.js +27 -10
- package/dist/ui/command-registry.js +11 -4
- package/dist/ui/command-review.js +77 -28
- package/dist/ui/composer-layout.js +26 -20
- package/dist/ui/conversation.js +77 -25
- package/dist/ui/live.js +1 -1
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +6 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/trust.js +7 -12
- package/dist/ui/ui.js +23 -0
- package/package.json +9 -5
package/dist/services/api.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { clientHeaders } from "./meta.js";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import axios, { isAxiosError } from "axios";
|
|
4
5
|
import FormData from "form-data";
|
|
6
|
+
import { ToolResultOutbox, toolResultScope, terminalToolRejection, resultHash, ToolDeliveryError } from "./tool-result-outbox.js";
|
|
7
|
+
import { recordMutationDelivery } from "./mutation-recovery.js";
|
|
8
|
+
import { reconstructMutationResults } from "./result-reconciliation.js";
|
|
9
|
+
import { reconcileMutationGroups } from "./mutation-groups.js";
|
|
10
|
+
import { errorLine } from "./output.js";
|
|
5
11
|
import { StreamError, consumeChatStream } from "./chat-stream.js";
|
|
6
12
|
/** Endpoints that work without a credential. Mirrors the /v1 router, where
|
|
7
13
|
* /health is mounted ABOVE the API-key gate and everything else below it. */
|
|
@@ -24,19 +30,26 @@ function readAll(stream) {
|
|
|
24
30
|
export class ApiError extends Error {
|
|
25
31
|
code;
|
|
26
32
|
status;
|
|
27
|
-
|
|
33
|
+
reason;
|
|
34
|
+
constructor(code, message, status,
|
|
35
|
+
/** The server's structured provider-failure reason (chat-stream.ts PROVIDER_ERROR_REASONS). */
|
|
36
|
+
reason) {
|
|
28
37
|
super(message);
|
|
29
38
|
this.code = code;
|
|
30
39
|
this.status = status;
|
|
40
|
+
this.reason = reason;
|
|
31
41
|
this.name = "ApiError";
|
|
32
42
|
}
|
|
33
43
|
}
|
|
34
44
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
45
|
+
* Coding tasks genuinely left mid-flight: an operation is still pending. A task
|
|
46
|
+
* that ended — its tests failed or never ran, or its change was later undone —
|
|
47
|
+
* showed its outcome at the time and stays in the conversation's task context;
|
|
48
|
+
* calling it "interrupted" on every start would be false and noisy.
|
|
39
49
|
*/
|
|
50
|
+
export function interruptedCodingTasks(tasks = []) {
|
|
51
|
+
return tasks.filter((t) => t.state !== "COMPLETED" && (t.pending_operations?.length ?? 0) > 0);
|
|
52
|
+
}
|
|
40
53
|
export class ApiClient {
|
|
41
54
|
baseUrl;
|
|
42
55
|
auth;
|
|
@@ -48,14 +61,17 @@ export class ApiClient {
|
|
|
48
61
|
constructor(baseUrl, auth) {
|
|
49
62
|
this.baseUrl = baseUrl;
|
|
50
63
|
this.auth = auth;
|
|
51
|
-
this.http = axios.create({ baseURL: baseUrl, timeout: 60_000 });
|
|
64
|
+
this.http = axios.create({ baseURL: baseUrl, timeout: 60_000, maxRedirects: 0 });
|
|
52
65
|
}
|
|
53
66
|
/** Current bearer token, whether from a provider or a legacy static key. */
|
|
54
67
|
token() {
|
|
55
|
-
return typeof this.auth === "string" ? this.auth : this.auth?.token();
|
|
68
|
+
return typeof this.auth === "string" ? this.auth : this.auth?.token(this.baseUrl);
|
|
56
69
|
}
|
|
57
|
-
async request(config, retry = true) {
|
|
70
|
+
async request(config, retry = true, resultScope) {
|
|
58
71
|
const token = this.token();
|
|
72
|
+
if (resultScope && token && toolResultScope(this.baseUrl, token) !== resultScope) {
|
|
73
|
+
throw new ApiError("TOOL_RESULT_SCOPE_CHANGED", "Tool result recovery requires its original session and scope.", 403);
|
|
74
|
+
}
|
|
59
75
|
// No credential at all — say so here rather than letting the request go out
|
|
60
76
|
// bare and come back as the server's MISSING_API_KEY, which reads like the
|
|
61
77
|
// user forgot to supply a key they were never meant to have. This happens
|
|
@@ -67,6 +83,7 @@ export class ApiClient {
|
|
|
67
83
|
const withAuth = {
|
|
68
84
|
...config,
|
|
69
85
|
headers: {
|
|
86
|
+
...clientHeaders(),
|
|
70
87
|
...(config.headers ?? {}),
|
|
71
88
|
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
72
89
|
}
|
|
@@ -89,7 +106,7 @@ export class ApiClient {
|
|
|
89
106
|
this.auth.refresh) {
|
|
90
107
|
const renewed = await this.auth.refresh(token);
|
|
91
108
|
if (renewed)
|
|
92
|
-
return this.request(config, false);
|
|
109
|
+
return this.request(config, false, resultScope);
|
|
93
110
|
}
|
|
94
111
|
// The caller aborted (Ctrl+C during a turn). Distinct from a failure —
|
|
95
112
|
// callers render it as an interruption, not an error, and must never
|
|
@@ -139,6 +156,9 @@ export class ApiClient {
|
|
|
139
156
|
chat(body, signal) {
|
|
140
157
|
return this.request({ method: "POST", url: "/chat", data: body, signal });
|
|
141
158
|
}
|
|
159
|
+
chatAvailability(sessionId) {
|
|
160
|
+
return this.request({ method: "GET", url: "/chat/availability", params: sessionId ? { session_id: sessionId } : undefined });
|
|
161
|
+
}
|
|
142
162
|
/**
|
|
143
163
|
* The same turn as `chat()`, over POST /v1/chat/stream. Resolves to the same
|
|
144
164
|
* `ChatResult`, so callers render it identically; along the way it reports
|
|
@@ -149,6 +169,7 @@ export class ApiClient {
|
|
|
149
169
|
* server finished — and billed — a reply nobody was waiting for.
|
|
150
170
|
*/
|
|
151
171
|
async chatStream(body, handlers = {}, signal, retry = true) {
|
|
172
|
+
await this.recoverToolResults();
|
|
152
173
|
const token = this.token();
|
|
153
174
|
if (!token)
|
|
154
175
|
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
@@ -163,7 +184,7 @@ export class ApiClient {
|
|
|
163
184
|
// No client-side timeout: a turn legitimately idles while a local tool
|
|
164
185
|
// runs, and the server's keep-alive pings hold the socket open.
|
|
165
186
|
timeout: 0,
|
|
166
|
-
headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
|
|
187
|
+
headers: { ...clientHeaders(), Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
|
|
167
188
|
validateStatus: () => true
|
|
168
189
|
});
|
|
169
190
|
}
|
|
@@ -198,7 +219,7 @@ export class ApiClient {
|
|
|
198
219
|
}
|
|
199
220
|
catch (err) {
|
|
200
221
|
if (err instanceof StreamError)
|
|
201
|
-
throw new ApiError(err.code, err.message, err.status);
|
|
222
|
+
throw new ApiError(err.code, err.message, err.status, err.reason);
|
|
202
223
|
throw err;
|
|
203
224
|
}
|
|
204
225
|
}
|
|
@@ -207,8 +228,132 @@ export class ApiClient {
|
|
|
207
228
|
recordMutationAudit(payload) {
|
|
208
229
|
return this.request({ method: "POST", url: "/chat/mutation-audit", data: payload });
|
|
209
230
|
}
|
|
210
|
-
|
|
211
|
-
|
|
231
|
+
mutationRecoveryScope() {
|
|
232
|
+
const token = this.token();
|
|
233
|
+
return token ? toolResultScope(this.baseUrl, token) : undefined;
|
|
234
|
+
}
|
|
235
|
+
resultOutbox() {
|
|
236
|
+
const token = this.token(); // existing issuer validation runs before storage/replay
|
|
237
|
+
return token ? new ToolResultOutbox(toolResultScope(this.baseUrl, token)) : undefined;
|
|
238
|
+
}
|
|
239
|
+
async submitToolResult(payload) {
|
|
240
|
+
const outbox = this.resultOutbox();
|
|
241
|
+
if (!outbox)
|
|
242
|
+
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
243
|
+
const scope = path.basename(outbox.dir);
|
|
244
|
+
recordMutationDelivery(payload, scope, "ready");
|
|
245
|
+
outbox.put(payload);
|
|
246
|
+
recordMutationDelivery(payload, scope, "queued");
|
|
247
|
+
try {
|
|
248
|
+
const state = outbox.state(payload.tool_call_id);
|
|
249
|
+
if (['rejected', 'expired', 'unresolved'].includes(state))
|
|
250
|
+
throw new ToolDeliveryError('Result delivery is terminal or unresolved; no result was sent.');
|
|
251
|
+
if (state === 'acknowledged') {
|
|
252
|
+
outbox.remove(payload.tool_call_id);
|
|
253
|
+
return { tool_call_id: payload.tool_call_id, status: payload.ok ? 'completed' : 'failed', duplicate: true };
|
|
254
|
+
}
|
|
255
|
+
if (state === 'submitting') {
|
|
256
|
+
const known = await this.request({ method: 'GET', url: `/chat/tool-result/${encodeURIComponent(payload.tool_call_id)}` }, true, scope);
|
|
257
|
+
if (known.tool_call_id !== payload.tool_call_id) {
|
|
258
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
259
|
+
throw new ToolDeliveryError();
|
|
260
|
+
}
|
|
261
|
+
if (['completed', 'failed'].includes(known.status)) {
|
|
262
|
+
if (known.status !== (payload.ok ? 'completed' : 'failed') || known.result_hash !== resultHash(payload)) {
|
|
263
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
264
|
+
throw new ToolDeliveryError('Backend result conflicts with saved evidence.');
|
|
265
|
+
}
|
|
266
|
+
recordMutationDelivery(payload, scope, 'acknowledged');
|
|
267
|
+
outbox.mark(payload.tool_call_id, 'acknowledged');
|
|
268
|
+
outbox.remove(payload.tool_call_id);
|
|
269
|
+
return { tool_call_id: payload.tool_call_id, status: known.status, duplicate: true };
|
|
270
|
+
}
|
|
271
|
+
if (['expired', 'cancelled'].includes(known.status)) {
|
|
272
|
+
outbox.mark(payload.tool_call_id, known.status === 'expired' ? 'expired' : 'rejected');
|
|
273
|
+
recordMutationDelivery(payload, scope, 'rejected');
|
|
274
|
+
throw new ApiError('CLIENT_TOOL_TIMEOUT', 'Saved result is no longer accepted.', 410);
|
|
275
|
+
}
|
|
276
|
+
if (known.status !== 'pending') {
|
|
277
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
278
|
+
throw new ToolDeliveryError();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (outbox.expired(payload.tool_call_id)) {
|
|
282
|
+
outbox.mark(payload.tool_call_id, 'expired');
|
|
283
|
+
throw new ApiError('CLIENT_TOOL_TIMEOUT', 'Saved result exceeded its recovery lifetime.', 410);
|
|
284
|
+
}
|
|
285
|
+
outbox.mark(payload.tool_call_id, 'submitting');
|
|
286
|
+
const accepted = await this.request({ method: "POST", url: "/chat/tool-result", data: payload }, true, path.basename(outbox.dir));
|
|
287
|
+
if (accepted.tool_call_id !== payload.tool_call_id || accepted.status !== (payload.ok ? 'completed' : 'failed')) {
|
|
288
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
289
|
+
throw new ToolDeliveryError('Backend acknowledgement does not match the saved result.');
|
|
290
|
+
}
|
|
291
|
+
recordMutationDelivery(payload, scope, "acknowledged");
|
|
292
|
+
outbox.mark(payload.tool_call_id, "acknowledged");
|
|
293
|
+
outbox.remove(payload.tool_call_id);
|
|
294
|
+
return accepted;
|
|
295
|
+
}
|
|
296
|
+
catch (error) {
|
|
297
|
+
if (terminalToolRejection(error)) {
|
|
298
|
+
recordMutationDelivery(payload, scope, "rejected");
|
|
299
|
+
if (outbox.state(payload.tool_call_id) !== "expired")
|
|
300
|
+
outbox.mark(payload.tool_call_id, "rejected");
|
|
301
|
+
// Retain terminal payloads as evidence; pending() excludes them from retries.
|
|
302
|
+
}
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async recoverToolResults() {
|
|
307
|
+
const outbox = this.resultOutbox();
|
|
308
|
+
if (!outbox)
|
|
309
|
+
return;
|
|
310
|
+
const recovery = reconcileMutationGroups(path.basename(outbox.dir));
|
|
311
|
+
// Only what needs the user's attention is shown; verified history stays quiet.
|
|
312
|
+
for (const report of recovery.reports)
|
|
313
|
+
if (["unresolved", "safely_recoverable"].includes(report.classification))
|
|
314
|
+
errorLine(report.message);
|
|
315
|
+
for (const group of recovery.groups)
|
|
316
|
+
if (!["COMPLETED", "ROLLED_BACK"].includes(group.state))
|
|
317
|
+
errorLine(group.message);
|
|
318
|
+
recovery.replay.push(...reconstructMutationResults(path.basename(outbox.dir), recovery.reports, recovery.groups));
|
|
319
|
+
for (const { payload, createdAt } of recovery.replay)
|
|
320
|
+
outbox.put(payload, createdAt);
|
|
321
|
+
for (const report of recovery.reports) {
|
|
322
|
+
if (report.operationId && report.classification === 'unresolved' &&
|
|
323
|
+
!recovery.replay.some(item => item.payload.tool_call_id === report.operationId && item.payload.ok === false) &&
|
|
324
|
+
!(report.reason === 'delivery_expired' && outbox.state(report.operationId) === 'submitting'))
|
|
325
|
+
outbox.mark(report.operationId, 'unresolved');
|
|
326
|
+
}
|
|
327
|
+
const { entries, expired } = outbox.pending();
|
|
328
|
+
if (expired)
|
|
329
|
+
errorLine(`${expired} saved tool result(s) expired before recovery. No tool was rerun.`);
|
|
330
|
+
for (const { payload } of entries) {
|
|
331
|
+
try {
|
|
332
|
+
await this.submitToolResult(payload);
|
|
333
|
+
outbox.remove(payload.tool_call_id);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (!terminalToolRejection(error))
|
|
337
|
+
throw error;
|
|
338
|
+
errorLine("A saved tool result was rejected by the server (stale, cancelled or no longer owned). No tool was rerun.");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
async reportCodingTaskRecovery() {
|
|
343
|
+
try {
|
|
344
|
+
const history = await this.codingTaskRecoverySummaries();
|
|
345
|
+
for (const task of interruptedCodingTasks(history.tasks))
|
|
346
|
+
errorLine(`Coding task ${task.task_id}: ${task.message}`);
|
|
347
|
+
}
|
|
348
|
+
catch { /* Offline history is not evidence of completion; local recovery remains authoritative. */ }
|
|
349
|
+
}
|
|
350
|
+
/** This conversation's Task Context, or null when it has no recorded coding work for this device. */
|
|
351
|
+
async taskContext(sessionId) {
|
|
352
|
+
const data = await this.request({ method: "GET", url: "/chat/task-context", params: { session_id: sessionId } });
|
|
353
|
+
return data?.context ?? null;
|
|
354
|
+
}
|
|
355
|
+
async codingTaskRecoverySummaries() {
|
|
356
|
+
return this.request({ method: "GET", url: "/chat/coding-tasks" });
|
|
212
357
|
}
|
|
213
358
|
// ── Sessions / conversations ─────────────────────────────────────────────────
|
|
214
359
|
conversations(params) {
|
|
@@ -220,8 +365,16 @@ export class ApiClient {
|
|
|
220
365
|
sessionMessages(id) {
|
|
221
366
|
return this.request({ method: "GET", url: `/sessions/${id}/messages` });
|
|
222
367
|
}
|
|
223
|
-
createSession(title) {
|
|
224
|
-
return this.request({ method: "POST", url: "/sessions", data: { title } });
|
|
368
|
+
createSession(title, chatType) {
|
|
369
|
+
return this.request({ method: "POST", url: "/sessions", data: { title, ...(chatType ? { chat_type: chatType } : {}) } });
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* /compact: replace the conversation's earlier messages in the model's
|
|
373
|
+
* context with a deterministic summary of its state. Same session and task;
|
|
374
|
+
* the server deletes nothing and calls no model.
|
|
375
|
+
*/
|
|
376
|
+
compactSession(id, permissionMode) {
|
|
377
|
+
return this.request({ method: "POST", url: `/sessions/${id}/compact`, data: permissionMode ? { permission_mode: permissionMode } : {} });
|
|
225
378
|
}
|
|
226
379
|
deleteSession(id) {
|
|
227
380
|
return this.request({ method: "DELETE", url: `/sessions/${id}` });
|
|
@@ -270,4 +423,19 @@ export class ApiClient {
|
|
|
270
423
|
processFile(fileId) {
|
|
271
424
|
return this.request({ method: "POST", url: `/files/${fileId}/process` });
|
|
272
425
|
}
|
|
426
|
+
// ── Voice ────────────────────────────────────────────────────────────────────
|
|
427
|
+
/** Dictation: a WAV recording → text, with the web composer's Whisper model,
|
|
428
|
+
* credit gate and billing (POST /v1/voice/transcribe, CLI sessions only). */
|
|
429
|
+
transcribe(wavPath) {
|
|
430
|
+
const form = new FormData();
|
|
431
|
+
form.append("audio", fs.createReadStream(wavPath), { filename: "dictation.wav", contentType: "audio/wav" });
|
|
432
|
+
return this.request({
|
|
433
|
+
method: "POST",
|
|
434
|
+
url: "/voice/transcribe",
|
|
435
|
+
data: form,
|
|
436
|
+
headers: form.getHeaders(),
|
|
437
|
+
maxContentLength: Infinity,
|
|
438
|
+
maxBodyLength: Infinity
|
|
439
|
+
});
|
|
440
|
+
}
|
|
273
441
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ApiError } from "./api.js";
|
|
2
|
+
import { isSafeUrl, sameApiOrigin } from "./config.js";
|
|
3
|
+
function validCredentialUrl(value) {
|
|
4
|
+
if (typeof value !== "string" || !value || !isSafeUrl(value))
|
|
5
|
+
return false;
|
|
6
|
+
const url = new URL(value);
|
|
7
|
+
return !url.username && !url.password;
|
|
8
|
+
}
|
|
9
|
+
/** Fail closed before exposing a saved credential to a transport. */
|
|
10
|
+
export function assertCredentialOrigin(issuer, destination) {
|
|
11
|
+
if (!validCredentialUrl(destination)) {
|
|
12
|
+
throw new ApiError("API_URL_INVALID", "The configured API URL is invalid or unsafe. No credentials were sent; your saved session is unchanged.");
|
|
13
|
+
}
|
|
14
|
+
if (!validCredentialUrl(issuer)) {
|
|
15
|
+
throw new ApiError("SESSION_ISSUER_INVALID", "The saved credential has no valid issuer. Sign in again with `cos login` to establish its origin. No credentials were sent; your saved session is unchanged.");
|
|
16
|
+
}
|
|
17
|
+
if (!sameApiOrigin(issuer, destination)) {
|
|
18
|
+
throw new ApiError("SESSION_ORIGIN_MISMATCH", "The API origin does not match the saved credential's issuer. Restore the issuing API URL or sign in again with `cos login`. No credentials were sent; your saved session is unchanged.");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { cliVersion } from "./meta.js";
|
|
2
|
+
import { acquireUpdateLock, checkChannel, compareVersions, defaultUpdateChannel, detectInstallation, installedGlobalVersion, isUpdateChannel, manualUpdateCommand, otherLiveInstances, packageName, registerInstance, releaseUpdateLock, startDetachedInstall, updateInProgress } from "./update.js";
|
|
3
|
+
/**
|
|
4
|
+
* Automatic updates for the npm-installed CLI (Claude Code-style).
|
|
5
|
+
*
|
|
6
|
+
* • Checks the configured channel at startup (when the last check is older
|
|
7
|
+
* than the interval) and then every interval while the CLI runs. Checks are
|
|
8
|
+
* async, one at a time, and never block the composer.
|
|
9
|
+
* • A newer release on a writable global npm install is installed in the
|
|
10
|
+
* BACKGROUND WHEN YOU EXIT, by a detached `npm install -g <pkg>@<exact>`,
|
|
11
|
+
* and only if no other CLI window is still open — a running CLI never has
|
|
12
|
+
* its package replaced underneath it. The next launch verifies the result
|
|
13
|
+
* (it is running the new version, or it is not) and says so once.
|
|
14
|
+
* • Local, development, npx and unwritable installs are never modified; they
|
|
15
|
+
* get the right manual instruction, once per version.
|
|
16
|
+
* • Nothing here prints directly: notices go to `notify`, which the shell
|
|
17
|
+
* shows between turns, never in the middle of one.
|
|
18
|
+
*
|
|
19
|
+
* The Windows installer build has its own verified updater (packaged-update.ts)
|
|
20
|
+
* and is not handled here.
|
|
21
|
+
*/
|
|
22
|
+
export const DEFAULT_CHECK_INTERVAL_HOURS = 6;
|
|
23
|
+
const MIN_INTERVAL_HOURS = 1;
|
|
24
|
+
const MAX_INTERVAL_HOURS = 168;
|
|
25
|
+
export function updateSettings(config) {
|
|
26
|
+
const hours = Number(config.get("updateCheckIntervalHours"));
|
|
27
|
+
const channel = config.get("updateChannel");
|
|
28
|
+
return {
|
|
29
|
+
autoUpdates: config.get("autoUpdates") !== false && process.env.CARRIEROS_DISABLE_AUTOUPDATE !== "1",
|
|
30
|
+
// A staging package always follows the staging tag. This prevents a stale
|
|
31
|
+
// or manually copied production preference from making it query the wrong
|
|
32
|
+
// channel or recommend the production package.
|
|
33
|
+
channel: packageName() === "@carrieros/cli-staging"
|
|
34
|
+
? "staging"
|
|
35
|
+
: isUpdateChannel(channel) ? channel : defaultUpdateChannel(),
|
|
36
|
+
intervalHours: Number.isFinite(hours) && hours > 0
|
|
37
|
+
? Math.min(MAX_INTERVAL_HOURS, Math.max(MIN_INTERVAL_HOURS, Math.round(hours)))
|
|
38
|
+
: DEFAULT_CHECK_INTERVAL_HOURS
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export class AutoUpdater {
|
|
42
|
+
opts;
|
|
43
|
+
checking = null;
|
|
44
|
+
timer = null;
|
|
45
|
+
pending = null;
|
|
46
|
+
install = null;
|
|
47
|
+
unregister = null;
|
|
48
|
+
current;
|
|
49
|
+
installation;
|
|
50
|
+
now;
|
|
51
|
+
constructor(opts) {
|
|
52
|
+
this.opts = opts;
|
|
53
|
+
this.current = opts.current ?? cliVersion;
|
|
54
|
+
this.installation = opts.installation ?? (() => detectInstallation());
|
|
55
|
+
this.now = opts.now ?? Date.now;
|
|
56
|
+
}
|
|
57
|
+
/** The version that will be installed on exit, if any. */
|
|
58
|
+
get pendingVersion() {
|
|
59
|
+
return this.pending;
|
|
60
|
+
}
|
|
61
|
+
/** Begin: report the last background install, register this window, check. */
|
|
62
|
+
start() {
|
|
63
|
+
// Never run inside an update's own child process.
|
|
64
|
+
if (process.env.CARRIEROS_UPDATING === "1")
|
|
65
|
+
return;
|
|
66
|
+
this.unregister = registerInstance(this.opts.dir);
|
|
67
|
+
this.reportPreviousInstall();
|
|
68
|
+
const { intervalHours } = updateSettings(this.opts.config);
|
|
69
|
+
if (this.due(intervalHours))
|
|
70
|
+
setImmediate(() => void this.check());
|
|
71
|
+
// Not due for a fresh check: still act on the last result we know about, so
|
|
72
|
+
// an update skipped in an earlier session (another window was open, the
|
|
73
|
+
// folder was read-only…) is not forgotten until the next network check.
|
|
74
|
+
else
|
|
75
|
+
setImmediate(() => void this.actOnCached());
|
|
76
|
+
this.timer = setInterval(() => void this.check(), intervalHours * 3600_000);
|
|
77
|
+
this.timer.unref?.();
|
|
78
|
+
}
|
|
79
|
+
stop() {
|
|
80
|
+
if (this.timer)
|
|
81
|
+
clearInterval(this.timer);
|
|
82
|
+
this.timer = null;
|
|
83
|
+
this.unregister?.();
|
|
84
|
+
this.unregister = null;
|
|
85
|
+
}
|
|
86
|
+
due(intervalHours) {
|
|
87
|
+
const last = Math.max(this.opts.config.get("updateCheckAt") ?? 0, this.opts.config.get("updateCheckErrorAt") ?? 0);
|
|
88
|
+
return this.now() - last >= intervalHours * 3600_000;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The outcome of an install started when an earlier session exited. Verified
|
|
92
|
+
* by what is actually running now — never assumed from npm's exit code.
|
|
93
|
+
*/
|
|
94
|
+
reportPreviousInstall() {
|
|
95
|
+
const pending = this.opts.config.get("pendingUpdate");
|
|
96
|
+
if (!pending)
|
|
97
|
+
return;
|
|
98
|
+
if (this.current() === pending.version) {
|
|
99
|
+
this.opts.notify(`CarrierOS CLI ${pending.version} has been installed successfully.`);
|
|
100
|
+
this.opts.config.set("pendingUpdate", undefined);
|
|
101
|
+
this.opts.config.set("updateFailedVersion", undefined);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
// Still running in the background: say nothing yet.
|
|
105
|
+
if (updateInProgress(this.opts.dir, this.now()))
|
|
106
|
+
return;
|
|
107
|
+
const channel = packageName() === "@carrieros/cli-staging"
|
|
108
|
+
? "staging"
|
|
109
|
+
: isUpdateChannel(pending.channel) ? pending.channel : defaultUpdateChannel();
|
|
110
|
+
this.opts.notify(`CarrierOS CLI could not be updated automatically. You can update manually using: ${manualUpdateCommand(channel)}`);
|
|
111
|
+
// Not retried automatically: a failing install would otherwise repeat on every exit.
|
|
112
|
+
this.opts.config.set("updateFailedVersion", pending.version);
|
|
113
|
+
this.opts.config.set("pendingUpdate", undefined);
|
|
114
|
+
}
|
|
115
|
+
/** One check at a time; a call while one runs waits for that one. */
|
|
116
|
+
check() {
|
|
117
|
+
if (!this.checking) {
|
|
118
|
+
this.checking = this.runCheck().finally(() => {
|
|
119
|
+
this.checking = null;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return this.checking;
|
|
123
|
+
}
|
|
124
|
+
/** Act on the cached latest version, without contacting the registry. */
|
|
125
|
+
async actOnCached() {
|
|
126
|
+
const latest = this.opts.config.get("latestCliVersion");
|
|
127
|
+
const current = this.current();
|
|
128
|
+
if (!latest)
|
|
129
|
+
return;
|
|
130
|
+
try {
|
|
131
|
+
if (compareVersions(latest, current) <= 0)
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
await this.act(latest, current);
|
|
138
|
+
}
|
|
139
|
+
async runCheck() {
|
|
140
|
+
const { channel } = updateSettings(this.opts.config);
|
|
141
|
+
let state;
|
|
142
|
+
try {
|
|
143
|
+
state = await checkChannel(channel, this.current());
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
this.opts.config.set("updateCheckErrorAt", this.now());
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (state.kind === "unreachable" || state.kind === "no-npm" || state.kind === "no-channel") {
|
|
150
|
+
// Recorded, never shown: an offline registry is not the user's problem.
|
|
151
|
+
this.opts.config.set("updateCheckErrorAt", this.now());
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
this.opts.config.set("latestCliVersion", state.latest);
|
|
155
|
+
this.opts.config.set("updateCheckAt", this.now());
|
|
156
|
+
if (state.kind !== "available")
|
|
157
|
+
return;
|
|
158
|
+
await this.act(state.latest, state.current);
|
|
159
|
+
}
|
|
160
|
+
/** A newer version is known: arrange the background install or tell the user how to update. */
|
|
161
|
+
async act(version, current) {
|
|
162
|
+
const { autoUpdates, channel } = updateSettings(this.opts.config);
|
|
163
|
+
const install = await this.installation().catch(() => ({ kind: "unknown" }));
|
|
164
|
+
this.install = install;
|
|
165
|
+
const name = packageName();
|
|
166
|
+
const failedBefore = this.opts.config.get("updateFailedVersion") === version;
|
|
167
|
+
if (autoUpdates && install.kind === "global" && install.writable && !failedBefore) {
|
|
168
|
+
this.pending = version;
|
|
169
|
+
this.notifyOnce(version, "auto", `CarrierOS CLI ${version} is available. You are currently using ${current}. It will be installed in the background when you exit.`);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (install.kind === "global" && !install.writable) {
|
|
173
|
+
this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Your global npm folder is not writable, so update manually: ${manualUpdateCommand(channel, name)}`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (install.kind === "local") {
|
|
177
|
+
this.notifyOnce(version, "local", `CarrierOS CLI ${version} is available. This copy is a project dependency — update it with your package manager, e.g. npm install ${name}@${version}`);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (install.kind === "npx") {
|
|
181
|
+
this.notifyOnce(version, "npx", `CarrierOS CLI ${version} is available. Run npx ${name}@${channel} to use it.`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (install.kind === "development")
|
|
185
|
+
return; // a checkout follows its own branch
|
|
186
|
+
this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Run /update to install it.`);
|
|
187
|
+
}
|
|
188
|
+
/** Each notice once per version and kind — across sessions. */
|
|
189
|
+
notifyOnce(version, kind, message) {
|
|
190
|
+
const key = `${version}:${kind}`;
|
|
191
|
+
if (this.opts.config.get("updateNoticeShown") === key)
|
|
192
|
+
return;
|
|
193
|
+
this.opts.config.set("updateNoticeShown", key);
|
|
194
|
+
this.opts.notify(message);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Leaving the CLI: start the pending background install. Skipped while
|
|
198
|
+
* another CLI window is open (it would have files replaced under it) or
|
|
199
|
+
* another update holds the lock; the next exit tries again.
|
|
200
|
+
*/
|
|
201
|
+
onExit() {
|
|
202
|
+
this.stop();
|
|
203
|
+
const version = this.pending;
|
|
204
|
+
if (!version)
|
|
205
|
+
return false;
|
|
206
|
+
// Already on disk (e.g. /update ran during the session): nothing to do.
|
|
207
|
+
if (this.install?.globalRoot && installedGlobalVersion(this.install.globalRoot) === version)
|
|
208
|
+
return false;
|
|
209
|
+
if (otherLiveInstances(this.opts.dir) > 0)
|
|
210
|
+
return false;
|
|
211
|
+
if (!acquireUpdateLock(this.opts.dir, process.pid, this.now()))
|
|
212
|
+
return false;
|
|
213
|
+
const { channel } = updateSettings(this.opts.config);
|
|
214
|
+
if (!startDetachedInstall(this.opts.dir, version)) {
|
|
215
|
+
releaseUpdateLock(this.opts.dir);
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
this.opts.config.set("pendingUpdate", { version, channel, startedAt: this.now() });
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -1,11 +1,29 @@
|
|
|
1
1
|
/** Thrown for every way a stream can end other than `complete`. */
|
|
2
|
+
/**
|
|
3
|
+
* The server's structured provider-failure reasons (`reason` on a stream
|
|
4
|
+
* `error`), so a surface can tell them apart without reading the message.
|
|
5
|
+
* Anything else the server sends is dropped, never shown.
|
|
6
|
+
*/
|
|
7
|
+
export const PROVIDER_ERROR_REASONS = {
|
|
8
|
+
rate_limited: "Rate limited",
|
|
9
|
+
quota_daily: "Quota exhausted",
|
|
10
|
+
provider_credits: "Credits exhausted",
|
|
11
|
+
provider_request_failed: "Provider error",
|
|
12
|
+
provider_config: "Configuration error",
|
|
13
|
+
provider_auth: "Authentication error"
|
|
14
|
+
};
|
|
15
|
+
export function providerErrorReason(value) {
|
|
16
|
+
return typeof value === "string" && Object.hasOwn(PROVIDER_ERROR_REASONS, value) ? value : undefined;
|
|
17
|
+
}
|
|
2
18
|
export class StreamError extends Error {
|
|
3
19
|
code;
|
|
4
20
|
status;
|
|
5
|
-
|
|
21
|
+
reason;
|
|
22
|
+
constructor(code, message, status = 0, reason) {
|
|
6
23
|
super(message);
|
|
7
24
|
this.code = code;
|
|
8
25
|
this.status = status;
|
|
26
|
+
this.reason = reason;
|
|
9
27
|
this.name = "StreamError";
|
|
10
28
|
}
|
|
11
29
|
}
|
|
@@ -78,7 +96,12 @@ export function consumeChatStream(body, handlers = {}, signal) {
|
|
|
78
96
|
// parser: the server keeps streaming while it waits for the result.
|
|
79
97
|
void Promise.resolve()
|
|
80
98
|
.then(() => handlers.onClientToolCall(data))
|
|
81
|
-
.catch(() =>
|
|
99
|
+
.catch((error) => {
|
|
100
|
+
if (error?.code === "TOOL_RESULT_DELIVERY_FAILED") {
|
|
101
|
+
finish(() => reject(new StreamError("TOOL_RESULT_DELIVERY_FAILED", "Tool result delivery failed. Saved results will be retried before the next chat; tools are not rerun.")));
|
|
102
|
+
body.destroy?.();
|
|
103
|
+
}
|
|
104
|
+
});
|
|
82
105
|
return;
|
|
83
106
|
}
|
|
84
107
|
case "complete":
|
|
@@ -90,7 +113,7 @@ export function consumeChatStream(body, handlers = {}, signal) {
|
|
|
90
113
|
: new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
|
|
91
114
|
return;
|
|
92
115
|
case "error":
|
|
93
|
-
finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.")));
|
|
116
|
+
finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.", 0, providerErrorReason(data.reason))));
|
|
94
117
|
return;
|
|
95
118
|
default:
|
|
96
119
|
return; // generation_type and anything newer: nothing to do
|