@carrieros/cli 0.3.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 +34 -13
- package/dist/commands/chat.js +3 -3
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +27 -12
- package/dist/commands/logout.js +1 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +8 -1
- package/dist/commands/update.js +79 -9
- package/dist/commands/usage.js +5 -5
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +274 -13
- package/dist/ide/tool-host.js +2 -2
- package/dist/main.js +0 -0
- package/dist/services/api.js +178 -12
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +113 -21
- 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 +67 -5
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +45 -17
- package/dist/services/device-auth.js +30 -5
- 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 +43 -12
- 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 +60 -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 +5 -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 +37 -12
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +299 -32
- package/dist/shell/shell-commands.js +46 -4
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +69 -7
- 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 +9 -2
- 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 +8 -5
package/dist/services/api.js
CHANGED
|
@@ -2,6 +2,11 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import axios, { isAxiosError } from "axios";
|
|
4
4
|
import FormData from "form-data";
|
|
5
|
+
import { ToolResultOutbox, toolResultScope, terminalToolRejection, resultHash, ToolDeliveryError } from "./tool-result-outbox.js";
|
|
6
|
+
import { recordMutationDelivery } from "./mutation-recovery.js";
|
|
7
|
+
import { reconstructMutationResults } from "./result-reconciliation.js";
|
|
8
|
+
import { reconcileMutationGroups } from "./mutation-groups.js";
|
|
9
|
+
import { errorLine } from "./output.js";
|
|
5
10
|
import { StreamError, consumeChatStream } from "./chat-stream.js";
|
|
6
11
|
/** Endpoints that work without a credential. Mirrors the /v1 router, where
|
|
7
12
|
* /health is mounted ABOVE the API-key gate and everything else below it. */
|
|
@@ -24,19 +29,26 @@ function readAll(stream) {
|
|
|
24
29
|
export class ApiError extends Error {
|
|
25
30
|
code;
|
|
26
31
|
status;
|
|
27
|
-
|
|
32
|
+
reason;
|
|
33
|
+
constructor(code, message, status,
|
|
34
|
+
/** The server's structured provider-failure reason (chat-stream.ts PROVIDER_ERROR_REASONS). */
|
|
35
|
+
reason) {
|
|
28
36
|
super(message);
|
|
29
37
|
this.code = code;
|
|
30
38
|
this.status = status;
|
|
39
|
+
this.reason = reason;
|
|
31
40
|
this.name = "ApiError";
|
|
32
41
|
}
|
|
33
42
|
}
|
|
34
43
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
44
|
+
* Coding tasks genuinely left mid-flight: an operation is still pending. A task
|
|
45
|
+
* that ended — its tests failed or never ran, or its change was later undone —
|
|
46
|
+
* showed its outcome at the time and stays in the conversation's task context;
|
|
47
|
+
* calling it "interrupted" on every start would be false and noisy.
|
|
39
48
|
*/
|
|
49
|
+
export function interruptedCodingTasks(tasks = []) {
|
|
50
|
+
return tasks.filter((t) => t.state !== "COMPLETED" && (t.pending_operations?.length ?? 0) > 0);
|
|
51
|
+
}
|
|
40
52
|
export class ApiClient {
|
|
41
53
|
baseUrl;
|
|
42
54
|
auth;
|
|
@@ -48,14 +60,17 @@ export class ApiClient {
|
|
|
48
60
|
constructor(baseUrl, auth) {
|
|
49
61
|
this.baseUrl = baseUrl;
|
|
50
62
|
this.auth = auth;
|
|
51
|
-
this.http = axios.create({ baseURL: baseUrl, timeout: 60_000 });
|
|
63
|
+
this.http = axios.create({ baseURL: baseUrl, timeout: 60_000, maxRedirects: 0 });
|
|
52
64
|
}
|
|
53
65
|
/** Current bearer token, whether from a provider or a legacy static key. */
|
|
54
66
|
token() {
|
|
55
|
-
return typeof this.auth === "string" ? this.auth : this.auth?.token();
|
|
67
|
+
return typeof this.auth === "string" ? this.auth : this.auth?.token(this.baseUrl);
|
|
56
68
|
}
|
|
57
|
-
async request(config, retry = true) {
|
|
69
|
+
async request(config, retry = true, resultScope) {
|
|
58
70
|
const token = this.token();
|
|
71
|
+
if (resultScope && token && toolResultScope(this.baseUrl, token) !== resultScope) {
|
|
72
|
+
throw new ApiError("TOOL_RESULT_SCOPE_CHANGED", "Tool result recovery requires its original session and scope.", 403);
|
|
73
|
+
}
|
|
59
74
|
// No credential at all — say so here rather than letting the request go out
|
|
60
75
|
// bare and come back as the server's MISSING_API_KEY, which reads like the
|
|
61
76
|
// user forgot to supply a key they were never meant to have. This happens
|
|
@@ -89,7 +104,7 @@ export class ApiClient {
|
|
|
89
104
|
this.auth.refresh) {
|
|
90
105
|
const renewed = await this.auth.refresh(token);
|
|
91
106
|
if (renewed)
|
|
92
|
-
return this.request(config, false);
|
|
107
|
+
return this.request(config, false, resultScope);
|
|
93
108
|
}
|
|
94
109
|
// The caller aborted (Ctrl+C during a turn). Distinct from a failure —
|
|
95
110
|
// callers render it as an interruption, not an error, and must never
|
|
@@ -139,6 +154,9 @@ export class ApiClient {
|
|
|
139
154
|
chat(body, signal) {
|
|
140
155
|
return this.request({ method: "POST", url: "/chat", data: body, signal });
|
|
141
156
|
}
|
|
157
|
+
chatAvailability(sessionId) {
|
|
158
|
+
return this.request({ method: "GET", url: "/chat/availability", params: sessionId ? { session_id: sessionId } : undefined });
|
|
159
|
+
}
|
|
142
160
|
/**
|
|
143
161
|
* The same turn as `chat()`, over POST /v1/chat/stream. Resolves to the same
|
|
144
162
|
* `ChatResult`, so callers render it identically; along the way it reports
|
|
@@ -149,6 +167,7 @@ export class ApiClient {
|
|
|
149
167
|
* server finished — and billed — a reply nobody was waiting for.
|
|
150
168
|
*/
|
|
151
169
|
async chatStream(body, handlers = {}, signal, retry = true) {
|
|
170
|
+
await this.recoverToolResults();
|
|
152
171
|
const token = this.token();
|
|
153
172
|
if (!token)
|
|
154
173
|
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
@@ -198,7 +217,7 @@ export class ApiClient {
|
|
|
198
217
|
}
|
|
199
218
|
catch (err) {
|
|
200
219
|
if (err instanceof StreamError)
|
|
201
|
-
throw new ApiError(err.code, err.message, err.status);
|
|
220
|
+
throw new ApiError(err.code, err.message, err.status, err.reason);
|
|
202
221
|
throw err;
|
|
203
222
|
}
|
|
204
223
|
}
|
|
@@ -207,8 +226,132 @@ export class ApiClient {
|
|
|
207
226
|
recordMutationAudit(payload) {
|
|
208
227
|
return this.request({ method: "POST", url: "/chat/mutation-audit", data: payload });
|
|
209
228
|
}
|
|
210
|
-
|
|
211
|
-
|
|
229
|
+
mutationRecoveryScope() {
|
|
230
|
+
const token = this.token();
|
|
231
|
+
return token ? toolResultScope(this.baseUrl, token) : undefined;
|
|
232
|
+
}
|
|
233
|
+
resultOutbox() {
|
|
234
|
+
const token = this.token(); // existing issuer validation runs before storage/replay
|
|
235
|
+
return token ? new ToolResultOutbox(toolResultScope(this.baseUrl, token)) : undefined;
|
|
236
|
+
}
|
|
237
|
+
async submitToolResult(payload) {
|
|
238
|
+
const outbox = this.resultOutbox();
|
|
239
|
+
if (!outbox)
|
|
240
|
+
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
241
|
+
const scope = path.basename(outbox.dir);
|
|
242
|
+
recordMutationDelivery(payload, scope, "ready");
|
|
243
|
+
outbox.put(payload);
|
|
244
|
+
recordMutationDelivery(payload, scope, "queued");
|
|
245
|
+
try {
|
|
246
|
+
const state = outbox.state(payload.tool_call_id);
|
|
247
|
+
if (['rejected', 'expired', 'unresolved'].includes(state))
|
|
248
|
+
throw new ToolDeliveryError('Result delivery is terminal or unresolved; no result was sent.');
|
|
249
|
+
if (state === 'acknowledged') {
|
|
250
|
+
outbox.remove(payload.tool_call_id);
|
|
251
|
+
return { tool_call_id: payload.tool_call_id, status: payload.ok ? 'completed' : 'failed', duplicate: true };
|
|
252
|
+
}
|
|
253
|
+
if (state === 'submitting') {
|
|
254
|
+
const known = await this.request({ method: 'GET', url: `/chat/tool-result/${encodeURIComponent(payload.tool_call_id)}` }, true, scope);
|
|
255
|
+
if (known.tool_call_id !== payload.tool_call_id) {
|
|
256
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
257
|
+
throw new ToolDeliveryError();
|
|
258
|
+
}
|
|
259
|
+
if (['completed', 'failed'].includes(known.status)) {
|
|
260
|
+
if (known.status !== (payload.ok ? 'completed' : 'failed') || known.result_hash !== resultHash(payload)) {
|
|
261
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
262
|
+
throw new ToolDeliveryError('Backend result conflicts with saved evidence.');
|
|
263
|
+
}
|
|
264
|
+
recordMutationDelivery(payload, scope, 'acknowledged');
|
|
265
|
+
outbox.mark(payload.tool_call_id, 'acknowledged');
|
|
266
|
+
outbox.remove(payload.tool_call_id);
|
|
267
|
+
return { tool_call_id: payload.tool_call_id, status: known.status, duplicate: true };
|
|
268
|
+
}
|
|
269
|
+
if (['expired', 'cancelled'].includes(known.status)) {
|
|
270
|
+
outbox.mark(payload.tool_call_id, known.status === 'expired' ? 'expired' : 'rejected');
|
|
271
|
+
recordMutationDelivery(payload, scope, 'rejected');
|
|
272
|
+
throw new ApiError('CLIENT_TOOL_TIMEOUT', 'Saved result is no longer accepted.', 410);
|
|
273
|
+
}
|
|
274
|
+
if (known.status !== 'pending') {
|
|
275
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
276
|
+
throw new ToolDeliveryError();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (outbox.expired(payload.tool_call_id)) {
|
|
280
|
+
outbox.mark(payload.tool_call_id, 'expired');
|
|
281
|
+
throw new ApiError('CLIENT_TOOL_TIMEOUT', 'Saved result exceeded its recovery lifetime.', 410);
|
|
282
|
+
}
|
|
283
|
+
outbox.mark(payload.tool_call_id, 'submitting');
|
|
284
|
+
const accepted = await this.request({ method: "POST", url: "/chat/tool-result", data: payload }, true, path.basename(outbox.dir));
|
|
285
|
+
if (accepted.tool_call_id !== payload.tool_call_id || accepted.status !== (payload.ok ? 'completed' : 'failed')) {
|
|
286
|
+
outbox.mark(payload.tool_call_id, 'unresolved');
|
|
287
|
+
throw new ToolDeliveryError('Backend acknowledgement does not match the saved result.');
|
|
288
|
+
}
|
|
289
|
+
recordMutationDelivery(payload, scope, "acknowledged");
|
|
290
|
+
outbox.mark(payload.tool_call_id, "acknowledged");
|
|
291
|
+
outbox.remove(payload.tool_call_id);
|
|
292
|
+
return accepted;
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
if (terminalToolRejection(error)) {
|
|
296
|
+
recordMutationDelivery(payload, scope, "rejected");
|
|
297
|
+
if (outbox.state(payload.tool_call_id) !== "expired")
|
|
298
|
+
outbox.mark(payload.tool_call_id, "rejected");
|
|
299
|
+
// Retain terminal payloads as evidence; pending() excludes them from retries.
|
|
300
|
+
}
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
async recoverToolResults() {
|
|
305
|
+
const outbox = this.resultOutbox();
|
|
306
|
+
if (!outbox)
|
|
307
|
+
return;
|
|
308
|
+
const recovery = reconcileMutationGroups(path.basename(outbox.dir));
|
|
309
|
+
// Only what needs the user's attention is shown; verified history stays quiet.
|
|
310
|
+
for (const report of recovery.reports)
|
|
311
|
+
if (["unresolved", "safely_recoverable"].includes(report.classification))
|
|
312
|
+
errorLine(report.message);
|
|
313
|
+
for (const group of recovery.groups)
|
|
314
|
+
if (!["COMPLETED", "ROLLED_BACK"].includes(group.state))
|
|
315
|
+
errorLine(group.message);
|
|
316
|
+
recovery.replay.push(...reconstructMutationResults(path.basename(outbox.dir), recovery.reports, recovery.groups));
|
|
317
|
+
for (const { payload, createdAt } of recovery.replay)
|
|
318
|
+
outbox.put(payload, createdAt);
|
|
319
|
+
for (const report of recovery.reports) {
|
|
320
|
+
if (report.operationId && report.classification === 'unresolved' &&
|
|
321
|
+
!recovery.replay.some(item => item.payload.tool_call_id === report.operationId && item.payload.ok === false) &&
|
|
322
|
+
!(report.reason === 'delivery_expired' && outbox.state(report.operationId) === 'submitting'))
|
|
323
|
+
outbox.mark(report.operationId, 'unresolved');
|
|
324
|
+
}
|
|
325
|
+
const { entries, expired } = outbox.pending();
|
|
326
|
+
if (expired)
|
|
327
|
+
errorLine(`${expired} saved tool result(s) expired before recovery. No tool was rerun.`);
|
|
328
|
+
for (const { payload } of entries) {
|
|
329
|
+
try {
|
|
330
|
+
await this.submitToolResult(payload);
|
|
331
|
+
outbox.remove(payload.tool_call_id);
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
if (!terminalToolRejection(error))
|
|
335
|
+
throw error;
|
|
336
|
+
errorLine("A saved tool result was rejected by the server (stale, cancelled or no longer owned). No tool was rerun.");
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async reportCodingTaskRecovery() {
|
|
341
|
+
try {
|
|
342
|
+
const history = await this.codingTaskRecoverySummaries();
|
|
343
|
+
for (const task of interruptedCodingTasks(history.tasks))
|
|
344
|
+
errorLine(`Coding task ${task.task_id}: ${task.message}`);
|
|
345
|
+
}
|
|
346
|
+
catch { /* Offline history is not evidence of completion; local recovery remains authoritative. */ }
|
|
347
|
+
}
|
|
348
|
+
/** This conversation's Task Context, or null when it has no recorded coding work for this device. */
|
|
349
|
+
async taskContext(sessionId) {
|
|
350
|
+
const data = await this.request({ method: "GET", url: "/chat/task-context", params: { session_id: sessionId } });
|
|
351
|
+
return data?.context ?? null;
|
|
352
|
+
}
|
|
353
|
+
async codingTaskRecoverySummaries() {
|
|
354
|
+
return this.request({ method: "GET", url: "/chat/coding-tasks" });
|
|
212
355
|
}
|
|
213
356
|
// ── Sessions / conversations ─────────────────────────────────────────────────
|
|
214
357
|
conversations(params) {
|
|
@@ -223,6 +366,14 @@ export class ApiClient {
|
|
|
223
366
|
createSession(title) {
|
|
224
367
|
return this.request({ method: "POST", url: "/sessions", data: { title } });
|
|
225
368
|
}
|
|
369
|
+
/**
|
|
370
|
+
* /compact: replace the conversation's earlier messages in the model's
|
|
371
|
+
* context with a deterministic summary of its state. Same session and task;
|
|
372
|
+
* the server deletes nothing and calls no model.
|
|
373
|
+
*/
|
|
374
|
+
compactSession(id, permissionMode) {
|
|
375
|
+
return this.request({ method: "POST", url: `/sessions/${id}/compact`, data: permissionMode ? { permission_mode: permissionMode } : {} });
|
|
376
|
+
}
|
|
226
377
|
deleteSession(id) {
|
|
227
378
|
return this.request({ method: "DELETE", url: `/sessions/${id}` });
|
|
228
379
|
}
|
|
@@ -270,4 +421,19 @@ export class ApiClient {
|
|
|
270
421
|
processFile(fileId) {
|
|
271
422
|
return this.request({ method: "POST", url: `/files/${fileId}/process` });
|
|
272
423
|
}
|
|
424
|
+
// ── Voice ────────────────────────────────────────────────────────────────────
|
|
425
|
+
/** Dictation: a WAV recording → text, with the web composer's Whisper model,
|
|
426
|
+
* credit gate and billing (POST /v1/voice/transcribe, CLI sessions only). */
|
|
427
|
+
transcribe(wavPath) {
|
|
428
|
+
const form = new FormData();
|
|
429
|
+
form.append("audio", fs.createReadStream(wavPath), { filename: "dictation.wav", contentType: "audio/wav" });
|
|
430
|
+
return this.request({
|
|
431
|
+
method: "POST",
|
|
432
|
+
url: "/voice/transcribe",
|
|
433
|
+
data: form,
|
|
434
|
+
headers: form.getHeaders(),
|
|
435
|
+
maxContentLength: Infinity,
|
|
436
|
+
maxBodyLength: Infinity
|
|
437
|
+
});
|
|
438
|
+
}
|
|
273
439
|
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { folderKey } from "./folder-key.js";
|
|
1
2
|
import crypto from "node:crypto";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
@@ -25,30 +26,102 @@ export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("h
|
|
|
25
26
|
* and an undo can prove it is reading the right one.
|
|
26
27
|
*/
|
|
27
28
|
export function repositoryKey(root) {
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
// Canonical (real path, case-folded on Windows): a repository opened through a
|
|
30
|
+
// symlink must find the same evidence its changes wrote. Unchanged for any
|
|
31
|
+
// root whose resolved path is already its real path.
|
|
32
|
+
return sha256(folderKey(root)).slice(0, 16);
|
|
30
33
|
}
|
|
31
34
|
/** One directory per repository root, keyed by a hash of its normalized path. */
|
|
32
|
-
function workspaceDir(root) {
|
|
35
|
+
export function workspaceDir(root) {
|
|
33
36
|
const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
|
|
34
37
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
35
38
|
return dir;
|
|
36
39
|
}
|
|
37
40
|
const journalFile = (root) => path.join(workspaceDir(root), "journal.json");
|
|
41
|
+
export class RecoveryStateError extends Error {
|
|
42
|
+
constructor(message = "Recovery state is unreadable or inconsistent. Existing evidence was preserved.") {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "RecoveryStateError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Waits between rename attempts while a Windows scanner or editor holds the target. */
|
|
48
|
+
export const RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80];
|
|
49
|
+
const LOCKED = new Set(["EPERM", "EBUSY", "EACCES"]);
|
|
50
|
+
/**
|
|
51
|
+
* renameSync that tolerates a transient Windows sharing lock (antivirus, the
|
|
52
|
+
* search indexer, an editor): EPERM/EBUSY/EACCES are retried a bounded number
|
|
53
|
+
* of times with a short backoff — on Windows only, where those codes mean a
|
|
54
|
+
* lock rather than a permission. Cancellation stops the retries. When they run
|
|
55
|
+
* out, the ORIGINAL error is thrown, so callers fail exactly as before.
|
|
56
|
+
*/
|
|
57
|
+
export function renameWithRetry(from, to, opts = {}) {
|
|
58
|
+
const rename = opts.rename ?? fs.renameSync;
|
|
59
|
+
const wait = opts.wait ?? ((ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms));
|
|
60
|
+
const retries = (opts.platform ?? process.platform) === "win32" ? RENAME_RETRY_DELAYS_MS : [];
|
|
61
|
+
for (let attempt = 0;; attempt++) {
|
|
62
|
+
try {
|
|
63
|
+
rename(from, to);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
const code = err.code ?? "";
|
|
68
|
+
if (!LOCKED.has(code) || attempt >= retries.length || opts.signal?.aborted)
|
|
69
|
+
throw err;
|
|
70
|
+
wait(retries[attempt]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Atomic publication with file fsync; directory fsync where supported. */
|
|
75
|
+
export function durableWrite(file, data) {
|
|
76
|
+
const tmp = `${file}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
77
|
+
try {
|
|
78
|
+
const fd = fs.openSync(tmp, "wx", 0o600);
|
|
79
|
+
try {
|
|
80
|
+
fs.writeFileSync(fd, data);
|
|
81
|
+
fs.fsyncSync(fd);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
renameWithRetry(tmp, file);
|
|
87
|
+
if (process.platform !== "win32") {
|
|
88
|
+
const dir = fs.openSync(path.dirname(file), "r");
|
|
89
|
+
try {
|
|
90
|
+
fs.fsyncSync(dir);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
fs.closeSync(dir);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
try {
|
|
99
|
+
fs.unlinkSync(tmp);
|
|
100
|
+
}
|
|
101
|
+
catch { /* absent after publication */ }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
38
104
|
export function readJournal(root) {
|
|
39
105
|
try {
|
|
40
|
-
const
|
|
41
|
-
|
|
106
|
+
const file = journalFile(root);
|
|
107
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 2 * 1024 * 1024)
|
|
108
|
+
throw new RecoveryStateError();
|
|
109
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
110
|
+
if (!Array.isArray(parsed) || parsed.some(e => !e || typeof e.operation_id !== "string" ||
|
|
111
|
+
typeof e.path !== "string" || typeof e.checkpoint_id !== "string" ||
|
|
112
|
+
!["EXECUTED", "ROLLED_BACK", "FAILED"].includes(e.status)) ||
|
|
113
|
+
new Set(parsed.map(e => e.operation_id)).size !== parsed.length)
|
|
114
|
+
throw new RecoveryStateError();
|
|
115
|
+
return parsed;
|
|
42
116
|
}
|
|
43
|
-
catch {
|
|
44
|
-
|
|
117
|
+
catch (err) {
|
|
118
|
+
if (err.code === "ENOENT")
|
|
119
|
+
return [];
|
|
120
|
+
throw new RecoveryStateError("Mutation journal is unreadable. It was preserved; history cannot be replaced or assumed empty.");
|
|
45
121
|
}
|
|
46
122
|
}
|
|
47
123
|
function writeJournal(root, entries) {
|
|
48
|
-
|
|
49
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
50
|
-
fs.writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 0o600 });
|
|
51
|
-
fs.renameSync(tmp, file);
|
|
124
|
+
durableWrite(journalFile(root), JSON.stringify(entries, null, 2));
|
|
52
125
|
}
|
|
53
126
|
export function newCheckpointId() {
|
|
54
127
|
return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
|
|
@@ -58,16 +131,100 @@ export function saveCheckpoint(root, checkpointId, original) {
|
|
|
58
131
|
if (original === null)
|
|
59
132
|
return; // nothing existed — undo means delete
|
|
60
133
|
const file = path.join(workspaceDir(root), `${checkpointId}.before`);
|
|
61
|
-
|
|
134
|
+
durableWrite(file, original);
|
|
62
135
|
}
|
|
63
136
|
export function loadCheckpoint(root, checkpointId) {
|
|
64
137
|
try {
|
|
65
|
-
|
|
138
|
+
if (!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(checkpointId))
|
|
139
|
+
return null;
|
|
140
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.before`);
|
|
141
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 1024 * 1024)
|
|
142
|
+
return null;
|
|
143
|
+
return fs.readFileSync(file);
|
|
66
144
|
}
|
|
67
145
|
catch {
|
|
68
146
|
return null;
|
|
69
147
|
}
|
|
70
148
|
}
|
|
149
|
+
export function saveRecoveryReceipt(root, checkpointId, metadata) {
|
|
150
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.recovery.json`);
|
|
151
|
+
if (fs.existsSync(file))
|
|
152
|
+
throw new RecoveryStateError();
|
|
153
|
+
durableWrite(file, JSON.stringify({ ...metadata, checkpoint_id: checkpointId, repository_key: repositoryKey(root) }));
|
|
154
|
+
}
|
|
155
|
+
export const MAX_RECOVERY_SCAN = 100;
|
|
156
|
+
export function recoveryReceipts(root) {
|
|
157
|
+
const receipts = [];
|
|
158
|
+
let problems = 0;
|
|
159
|
+
const dir = workspaceDir(root);
|
|
160
|
+
const names = [];
|
|
161
|
+
// Bound directory traversal, not only the number of parsed JSON records.
|
|
162
|
+
let visited = 0, bounded = false;
|
|
163
|
+
const directory = fs.opendirSync(dir);
|
|
164
|
+
try {
|
|
165
|
+
let entry;
|
|
166
|
+
while ((entry = directory.readSync()) !== null) {
|
|
167
|
+
if (++visited > MAX_RECOVERY_SCAN * 4) {
|
|
168
|
+
bounded = true;
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
if (entry.name.endsWith(".recovery.json"))
|
|
172
|
+
names.push(entry.name);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
directory.closeSync();
|
|
177
|
+
}
|
|
178
|
+
if (names.length > MAX_RECOVERY_SCAN)
|
|
179
|
+
bounded = true;
|
|
180
|
+
for (const name of names.slice(0, MAX_RECOVERY_SCAN)) {
|
|
181
|
+
try {
|
|
182
|
+
const file = path.join(dir, name);
|
|
183
|
+
if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 64 * 1024)
|
|
184
|
+
throw new RecoveryStateError();
|
|
185
|
+
const r = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
186
|
+
const hashValid = (exists, hash) => typeof exists === "boolean" &&
|
|
187
|
+
(exists ? typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash) : hash === null);
|
|
188
|
+
if ((r.group_id !== undefined && !/^grp_[a-f0-9]{32}$/.test(r.group_id)) ||
|
|
189
|
+
r.version !== 2 || r.approved !== true || r.repository_key !== repositoryKey(root) ||
|
|
190
|
+
typeof r.operation_id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(r.operation_id) || typeof r.repository_id !== "string" ||
|
|
191
|
+
typeof r.repository_name !== "string" || typeof r.path !== "string" ||
|
|
192
|
+
!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(r.checkpoint_id) || name !== `${r.checkpoint_id}.recovery.json` ||
|
|
193
|
+
!["create_file", "write_file", "edit_file", "delete_file", "revert_change"].includes(r.action) ||
|
|
194
|
+
!["prepared", "applied", "verified", "rolled_back", "unresolved"].includes(r.phase) ||
|
|
195
|
+
!["none", "ready", "queued", "acknowledged", "rejected"].includes(r.delivery) ||
|
|
196
|
+
typeof r.journal_persisted !== "boolean" || !Number.isFinite(Date.parse(r.created_at)) ||
|
|
197
|
+
!hashValid(r.before_exists, r.before_sha) || !hashValid(r.after_exists, r.after_sha) ||
|
|
198
|
+
(r.scope !== undefined && !/^[a-f0-9]{64}$/.test(r.scope)) ||
|
|
199
|
+
(r.result && (r.result.tool_call_id !== r.operation_id || typeof r.result.ok !== "boolean")) ||
|
|
200
|
+
(r.delivery !== "none" && !r.result))
|
|
201
|
+
throw new RecoveryStateError();
|
|
202
|
+
receipts.push(r);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
problems++;
|
|
206
|
+
} // No content, malformed paths or credentials in diagnostics.
|
|
207
|
+
}
|
|
208
|
+
const counts = new Map();
|
|
209
|
+
for (const r of receipts)
|
|
210
|
+
counts.set(r.operation_id, (counts.get(r.operation_id) ?? 0) + 1);
|
|
211
|
+
return { receipts: receipts.filter(r => {
|
|
212
|
+
if (counts.get(r.operation_id) > 1) {
|
|
213
|
+
problems++;
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
return true;
|
|
217
|
+
}), problems, bounded };
|
|
218
|
+
}
|
|
219
|
+
export function updateRecoveryReceipt(root, checkpointId, patch) {
|
|
220
|
+
const scan = recoveryReceipts(root);
|
|
221
|
+
const r = scan.receipts.find(e => e.checkpoint_id === checkpointId);
|
|
222
|
+
if (!r)
|
|
223
|
+
throw new RecoveryStateError();
|
|
224
|
+
if (r.result && patch.result && JSON.stringify(r.result) !== JSON.stringify(patch.result))
|
|
225
|
+
throw new RecoveryStateError();
|
|
226
|
+
durableWrite(path.join(workspaceDir(root), `${checkpointId}.recovery.json`), JSON.stringify({ ...r, ...patch }));
|
|
227
|
+
}
|
|
71
228
|
/** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
|
|
72
229
|
export function appendEntry(root, entry) {
|
|
73
230
|
const entries = [...readJournal(root), entry];
|
|
@@ -75,7 +232,12 @@ export function appendEntry(root, entry) {
|
|
|
75
232
|
writeJournal(root, entries);
|
|
76
233
|
for (const d of dropped) {
|
|
77
234
|
try {
|
|
78
|
-
|
|
235
|
+
const receipt = recoveryReceipts(root).receipts.find(r => r.checkpoint_id === d.checkpoint_id);
|
|
236
|
+
if (!receipt || receipt.group_id || !receipt.journal_persisted || !["verified", "rolled_back"].includes(receipt.phase) ||
|
|
237
|
+
(receipt.scope && !["acknowledged", "rejected"].includes(receipt.delivery)))
|
|
238
|
+
continue;
|
|
239
|
+
fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`), { force: true });
|
|
240
|
+
fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.recovery.json`), { force: true });
|
|
79
241
|
}
|
|
80
242
|
catch {
|
|
81
243
|
/* already gone */
|