@carrieros/cli-staging 0.0.0-stage → 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 +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +25 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- 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 +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +100 -0
- package/dist/commands/update.js +229 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +227 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +360 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +126 -0
- package/dist/services/api.js +439 -0
- 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 +356 -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 +383 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +371 -0
- package/dist/services/device-auth.js +286 -0
- 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 +156 -0
- package/dist/services/meta.js +15 -0
- 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 +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -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/spinner.js +40 -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 +1619 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +389 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- 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 +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import axios, { isAxiosError } from "axios";
|
|
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";
|
|
10
|
+
import { StreamError, consumeChatStream } from "./chat-stream.js";
|
|
11
|
+
/** Endpoints that work without a credential. Mirrors the /v1 router, where
|
|
12
|
+
* /health is mounted ABOVE the API-key gate and everything else below it. */
|
|
13
|
+
const PUBLIC_PATHS = new Set(["/health"]);
|
|
14
|
+
/** Collect a (small) response stream into a string — used for pre-stream errors. */
|
|
15
|
+
function readAll(stream) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
const s = stream;
|
|
18
|
+
if (!s || typeof s.on !== "function")
|
|
19
|
+
return resolve(typeof stream === "string" ? stream : "");
|
|
20
|
+
let out = "";
|
|
21
|
+
s.on("data", (c) => {
|
|
22
|
+
out += typeof c === "string" ? c : c.toString("utf8");
|
|
23
|
+
});
|
|
24
|
+
s.on("end", () => resolve(out));
|
|
25
|
+
s.on("error", () => resolve(out));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** A typed, envelope-aware error surfaced by the API client. */
|
|
29
|
+
export class ApiError extends Error {
|
|
30
|
+
code;
|
|
31
|
+
status;
|
|
32
|
+
reason;
|
|
33
|
+
constructor(code, message, status,
|
|
34
|
+
/** The server's structured provider-failure reason (chat-stream.ts PROVIDER_ERROR_REASONS). */
|
|
35
|
+
reason) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.status = status;
|
|
39
|
+
this.reason = reason;
|
|
40
|
+
this.name = "ApiError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
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.
|
|
48
|
+
*/
|
|
49
|
+
export function interruptedCodingTasks(tasks = []) {
|
|
50
|
+
return tasks.filter((t) => t.state !== "COMPLETED" && (t.pending_operations?.length ?? 0) > 0);
|
|
51
|
+
}
|
|
52
|
+
export class ApiClient {
|
|
53
|
+
baseUrl;
|
|
54
|
+
auth;
|
|
55
|
+
http;
|
|
56
|
+
/**
|
|
57
|
+
* @param baseUrl the /v1 base
|
|
58
|
+
* @param auth an AuthProvider (device-flow) OR a legacy static key string.
|
|
59
|
+
*/
|
|
60
|
+
constructor(baseUrl, auth) {
|
|
61
|
+
this.baseUrl = baseUrl;
|
|
62
|
+
this.auth = auth;
|
|
63
|
+
this.http = axios.create({ baseURL: baseUrl, timeout: 60_000, maxRedirects: 0 });
|
|
64
|
+
}
|
|
65
|
+
/** Current bearer token, whether from a provider or a legacy static key. */
|
|
66
|
+
token() {
|
|
67
|
+
return typeof this.auth === "string" ? this.auth : this.auth?.token(this.baseUrl);
|
|
68
|
+
}
|
|
69
|
+
async request(config, retry = true, resultScope) {
|
|
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
|
+
}
|
|
74
|
+
// No credential at all — say so here rather than letting the request go out
|
|
75
|
+
// bare and come back as the server's MISSING_API_KEY, which reads like the
|
|
76
|
+
// user forgot to supply a key they were never meant to have. This happens
|
|
77
|
+
// whenever a dead refresh token makes authProvider.refresh clear local auth
|
|
78
|
+
// mid-session, so the shell can be running with the session already gone.
|
|
79
|
+
if (!token && !PUBLIC_PATHS.has(config.url ?? "")) {
|
|
80
|
+
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
81
|
+
}
|
|
82
|
+
const withAuth = {
|
|
83
|
+
...config,
|
|
84
|
+
headers: {
|
|
85
|
+
...(config.headers ?? {}),
|
|
86
|
+
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
try {
|
|
90
|
+
const res = await this.http.request(withAuth);
|
|
91
|
+
const body = res.data;
|
|
92
|
+
if (body?.success && body.data !== undefined)
|
|
93
|
+
return body.data;
|
|
94
|
+
throw new ApiError(body?.error?.code ?? "REQUEST_FAILED", body?.error?.message ?? "Request failed.", res.status);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
if (err instanceof ApiError)
|
|
98
|
+
throw err;
|
|
99
|
+
// Silent refresh: on a 401, renew the token once and retry the request.
|
|
100
|
+
if (isAxiosError(err) &&
|
|
101
|
+
err.response?.status === 401 &&
|
|
102
|
+
retry &&
|
|
103
|
+
typeof this.auth === "object" &&
|
|
104
|
+
this.auth.refresh) {
|
|
105
|
+
const renewed = await this.auth.refresh(token);
|
|
106
|
+
if (renewed)
|
|
107
|
+
return this.request(config, false, resultScope);
|
|
108
|
+
}
|
|
109
|
+
// The caller aborted (Ctrl+C during a turn). Distinct from a failure —
|
|
110
|
+
// callers render it as an interruption, not an error, and must never
|
|
111
|
+
// retry it.
|
|
112
|
+
if (isAxiosError(err) && (err.code === "ERR_CANCELED" || err.name === "CanceledError")) {
|
|
113
|
+
throw new ApiError("ABORTED", "Interrupted.", 0);
|
|
114
|
+
}
|
|
115
|
+
if (isAxiosError(err)) {
|
|
116
|
+
const status = err.response?.status;
|
|
117
|
+
const body = err.response?.data;
|
|
118
|
+
// Standard envelope error from the API.
|
|
119
|
+
if (body?.error?.code || body?.error?.message) {
|
|
120
|
+
throw new ApiError(body.error.code || "REQUEST_FAILED", body.error.message || `Request failed (HTTP ${status}).`, status);
|
|
121
|
+
}
|
|
122
|
+
// Couldn't connect, or the connection died mid-request. ECONNRESET is
|
|
123
|
+
// the one that matters in practice: the API restarting under a long
|
|
124
|
+
// turn drops the socket, and without it here that surfaced as a raw
|
|
125
|
+
// "read ECONNRESET / REQUEST_FAILED" with nothing to act on.
|
|
126
|
+
if (["ECONNREFUSED", "ENOTFOUND", "ECONNABORTED", "ETIMEDOUT", "ECONNRESET", "EPIPE"].includes(err.code ?? "")) {
|
|
127
|
+
const dropped = err.code === "ECONNRESET" || err.code === "EPIPE";
|
|
128
|
+
throw new ApiError("NETWORK_ERROR", dropped
|
|
129
|
+
? "The connection to the API dropped mid-request."
|
|
130
|
+
: `Could not reach the API at ${this.baseUrl}.`, 0);
|
|
131
|
+
}
|
|
132
|
+
// Reached a server, but it didn't speak our envelope (wrong URL, proxy,
|
|
133
|
+
// gateway page, …). Never surface an empty message.
|
|
134
|
+
throw new ApiError(status ? `HTTP_${status}` : "REQUEST_FAILED", err.message || (status ? `Request failed (HTTP ${status}).` : "Request failed."), status);
|
|
135
|
+
}
|
|
136
|
+
throw new ApiError("UNKNOWN", err instanceof Error ? err.message : String(err));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// ── Auth / meta ─────────────────────────────────────────────────────────────
|
|
140
|
+
health() {
|
|
141
|
+
return this.request({ method: "GET", url: "/health" });
|
|
142
|
+
}
|
|
143
|
+
verify() {
|
|
144
|
+
return this.request({ method: "POST", url: "/auth/verify" });
|
|
145
|
+
}
|
|
146
|
+
models() {
|
|
147
|
+
return this.request({ method: "GET", url: "/models" });
|
|
148
|
+
}
|
|
149
|
+
chatModels() {
|
|
150
|
+
return this.request({ method: "GET", url: "/models/chat" });
|
|
151
|
+
}
|
|
152
|
+
// ── Chat ────────────────────────────────────────────────────────────────────
|
|
153
|
+
/** `signal` lets the caller abandon the request (Ctrl+C during a turn). */
|
|
154
|
+
chat(body, signal) {
|
|
155
|
+
return this.request({ method: "POST", url: "/chat", data: body, signal });
|
|
156
|
+
}
|
|
157
|
+
chatAvailability(sessionId) {
|
|
158
|
+
return this.request({ method: "GET", url: "/chat/availability", params: sessionId ? { session_id: sessionId } : undefined });
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The same turn as `chat()`, over POST /v1/chat/stream. Resolves to the same
|
|
162
|
+
* `ChatResult`, so callers render it identically; along the way it reports
|
|
163
|
+
* answer deltas, progress and local tool requests through `handlers`.
|
|
164
|
+
*
|
|
165
|
+
* Aborting (Ctrl+C) actually stops the turn here: the server sees the socket
|
|
166
|
+
* close and cancels the model call, unlike the blocking endpoint, where the
|
|
167
|
+
* server finished — and billed — a reply nobody was waiting for.
|
|
168
|
+
*/
|
|
169
|
+
async chatStream(body, handlers = {}, signal, retry = true) {
|
|
170
|
+
await this.recoverToolResults();
|
|
171
|
+
const token = this.token();
|
|
172
|
+
if (!token)
|
|
173
|
+
throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
|
|
174
|
+
let res;
|
|
175
|
+
try {
|
|
176
|
+
res = await this.http.request({
|
|
177
|
+
method: "POST",
|
|
178
|
+
url: "/chat/stream",
|
|
179
|
+
data: body,
|
|
180
|
+
signal,
|
|
181
|
+
responseType: "stream",
|
|
182
|
+
// No client-side timeout: a turn legitimately idles while a local tool
|
|
183
|
+
// runs, and the server's keep-alive pings hold the socket open.
|
|
184
|
+
timeout: 0,
|
|
185
|
+
headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
|
|
186
|
+
validateStatus: () => true
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (isAxiosError(err) && (err.code === "ERR_CANCELED" || err.name === "CanceledError")) {
|
|
191
|
+
throw new ApiError("ABORTED", "Interrupted.", 0);
|
|
192
|
+
}
|
|
193
|
+
if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNRESET", "EPIPE"].includes(err.code ?? "")) {
|
|
194
|
+
throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${this.baseUrl}.`, 0);
|
|
195
|
+
}
|
|
196
|
+
throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
|
|
197
|
+
}
|
|
198
|
+
// Anything but 200 is a plain JSON error sent before the stream opened.
|
|
199
|
+
if (res.status !== 200) {
|
|
200
|
+
const text = await readAll(res.data);
|
|
201
|
+
let env;
|
|
202
|
+
try {
|
|
203
|
+
env = JSON.parse(text);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
env = undefined;
|
|
207
|
+
}
|
|
208
|
+
if (res.status === 401 && retry && typeof this.auth === "object" && this.auth.refresh) {
|
|
209
|
+
const renewed = await this.auth.refresh(token);
|
|
210
|
+
if (renewed)
|
|
211
|
+
return this.chatStream(body, handlers, signal, false);
|
|
212
|
+
}
|
|
213
|
+
throw new ApiError(env?.error?.code ?? `HTTP_${res.status}`, env?.error?.message ?? `Request failed (HTTP ${res.status}).`, res.status);
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
return await consumeChatStream(res.data, handlers, signal);
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
if (err instanceof StreamError)
|
|
220
|
+
throw new ApiError(err.code, err.message, err.status, err.reason);
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Answer a `client_tool_call` (POST /v1/chat/tool-result). */
|
|
225
|
+
/** Record an undo the user ran with /undo, outside any turn. Metadata only. */
|
|
226
|
+
recordMutationAudit(payload) {
|
|
227
|
+
return this.request({ method: "POST", url: "/chat/mutation-audit", data: payload });
|
|
228
|
+
}
|
|
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" });
|
|
355
|
+
}
|
|
356
|
+
// ── Sessions / conversations ─────────────────────────────────────────────────
|
|
357
|
+
conversations(params) {
|
|
358
|
+
return this.request({ method: "GET", url: "/conversations", params });
|
|
359
|
+
}
|
|
360
|
+
session(id) {
|
|
361
|
+
return this.request({ method: "GET", url: `/sessions/${id}` });
|
|
362
|
+
}
|
|
363
|
+
sessionMessages(id) {
|
|
364
|
+
return this.request({ method: "GET", url: `/sessions/${id}/messages` });
|
|
365
|
+
}
|
|
366
|
+
createSession(title) {
|
|
367
|
+
return this.request({ method: "POST", url: "/sessions", data: { title } });
|
|
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
|
+
}
|
|
377
|
+
deleteSession(id) {
|
|
378
|
+
return this.request({ method: "DELETE", url: `/sessions/${id}` });
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* A read-only side question about a session ("/btw"). Persists nothing: no
|
|
382
|
+
* message is stored and the conversation is untouched — which is why it is
|
|
383
|
+
* NOT `chat()`, since /v1/chat always writes both turns.
|
|
384
|
+
*/
|
|
385
|
+
askAboutSession(sessionId, question, signal) {
|
|
386
|
+
return this.request({
|
|
387
|
+
method: "POST",
|
|
388
|
+
url: `/sessions/${sessionId}/ask`,
|
|
389
|
+
data: { question },
|
|
390
|
+
signal
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
// ── Memory (snapshots + restructures) ───────────────────────────────────────
|
|
394
|
+
/** One artifact, by the `artifact_id` carried on a transcript marker. */
|
|
395
|
+
memoryArtifact(id) {
|
|
396
|
+
return this.request({ method: "GET", url: `/memory/${id}` });
|
|
397
|
+
}
|
|
398
|
+
// ── SIA clarification ───────────────────────────────────────────────────────
|
|
399
|
+
/** Questions worth asking about an unsent prompt. Never throws for content
|
|
400
|
+
* reasons — the API answers `{skip:true}` when there's nothing to ask. */
|
|
401
|
+
siaQuestions(text) {
|
|
402
|
+
return this.request({ method: "POST", url: "/sia/questions", data: { text } });
|
|
403
|
+
}
|
|
404
|
+
// ── Usage ────────────────────────────────────────────────────────────────────
|
|
405
|
+
usage() {
|
|
406
|
+
return this.request({ method: "GET", url: "/usage" });
|
|
407
|
+
}
|
|
408
|
+
// ── Files ────────────────────────────────────────────────────────────────────
|
|
409
|
+
async uploadFile(filePath) {
|
|
410
|
+
const form = new FormData();
|
|
411
|
+
form.append("file", fs.createReadStream(filePath), path.basename(filePath));
|
|
412
|
+
return this.request({
|
|
413
|
+
method: "POST",
|
|
414
|
+
url: "/files",
|
|
415
|
+
data: form,
|
|
416
|
+
headers: form.getHeaders(),
|
|
417
|
+
maxContentLength: Infinity,
|
|
418
|
+
maxBodyLength: Infinity
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
processFile(fileId) {
|
|
422
|
+
return this.request({ method: "POST", url: `/files/${fileId}/process` });
|
|
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
|
+
}
|
|
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
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
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
|
+
}
|
|
18
|
+
export class StreamError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
status;
|
|
21
|
+
reason;
|
|
22
|
+
constructor(code, message, status = 0, reason) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.reason = reason;
|
|
27
|
+
this.name = "StreamError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Map the server's `complete` payload onto the synchronous endpoint's shape. */
|
|
31
|
+
export function completeToResult(d) {
|
|
32
|
+
return {
|
|
33
|
+
id: d.message_id ?? null,
|
|
34
|
+
response: typeof d.content === "string" ? d.content : "",
|
|
35
|
+
session_id: d.session_id,
|
|
36
|
+
tokens_used: Number(d.tokens_used ?? 0) || 0,
|
|
37
|
+
cost_usd: typeof d.cost_usd === "number" ? d.cost_usd : undefined,
|
|
38
|
+
credits_remaining: typeof d.credits_remaining === "number" ? d.credits_remaining : null,
|
|
39
|
+
credits_unlimited: typeof d.credits_unlimited === "boolean" ? d.credits_unlimited : null,
|
|
40
|
+
credits_spent: typeof d.credits_spent === "number" ? d.credits_spent : null,
|
|
41
|
+
sources: Array.isArray(d.sources) ? d.sources : [],
|
|
42
|
+
web_search_used: d.web_search_used === true,
|
|
43
|
+
high_power_used: d.high_power_used === true,
|
|
44
|
+
speed: d.speed === "fast" ? "fast" : d.speed === "standard" ? "standard" : undefined,
|
|
45
|
+
model: typeof d.model === "string" ? d.model : undefined
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Consume an SSE body until `complete`, `error`, `interrupted` or the socket
|
|
50
|
+
* ends. Frames are `data: {"type":…,"data":…}` separated by a blank line;
|
|
51
|
+
* `: ping` comments and the `[DONE]` sentinel carry nothing.
|
|
52
|
+
*/
|
|
53
|
+
export function consumeChatStream(body, handlers = {}, signal) {
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
let buffer = "";
|
|
56
|
+
let settled = false;
|
|
57
|
+
const finish = (fn) => {
|
|
58
|
+
if (settled)
|
|
59
|
+
return;
|
|
60
|
+
settled = true;
|
|
61
|
+
signal?.removeEventListener?.("abort", onAbort);
|
|
62
|
+
fn();
|
|
63
|
+
};
|
|
64
|
+
function onAbort() {
|
|
65
|
+
finish(() => reject(new StreamError("ABORTED", "Interrupted.")));
|
|
66
|
+
try {
|
|
67
|
+
body.destroy?.();
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
/* already closed */
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (signal?.aborted) {
|
|
74
|
+
onAbort();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
signal?.addEventListener?.("abort", onAbort, { once: true });
|
|
78
|
+
const dispatch = (type, data) => {
|
|
79
|
+
switch (type) {
|
|
80
|
+
case "message_created":
|
|
81
|
+
handlers.onMessageCreated?.(data);
|
|
82
|
+
return;
|
|
83
|
+
case "chunk":
|
|
84
|
+
if (typeof data.delta === "string" && data.delta)
|
|
85
|
+
handlers.onDelta?.(data.delta);
|
|
86
|
+
return;
|
|
87
|
+
case "status":
|
|
88
|
+
case "tool_status":
|
|
89
|
+
if (typeof data.message === "string")
|
|
90
|
+
handlers.onStatus?.(type, data.message);
|
|
91
|
+
return;
|
|
92
|
+
case "client_tool_call": {
|
|
93
|
+
if (!handlers.onClientToolCall)
|
|
94
|
+
return;
|
|
95
|
+
// Never let a tool handler's failure — or its duration — stall the
|
|
96
|
+
// parser: the server keeps streaming while it waits for the result.
|
|
97
|
+
void Promise.resolve()
|
|
98
|
+
.then(() => handlers.onClientToolCall(data))
|
|
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
|
+
});
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
case "complete":
|
|
108
|
+
finish(() => resolve(completeToResult(data)));
|
|
109
|
+
return;
|
|
110
|
+
case "interrupted":
|
|
111
|
+
finish(() => reject(signal?.aborted
|
|
112
|
+
? new StreamError("ABORTED", "Interrupted.")
|
|
113
|
+
: new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
|
|
114
|
+
return;
|
|
115
|
+
case "error":
|
|
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))));
|
|
117
|
+
return;
|
|
118
|
+
default:
|
|
119
|
+
return; // generation_type and anything newer: nothing to do
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const drain = () => {
|
|
123
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
124
|
+
let sep = buffer.indexOf("\n\n");
|
|
125
|
+
while (sep !== -1) {
|
|
126
|
+
const block = buffer.slice(0, sep);
|
|
127
|
+
buffer = buffer.slice(sep + 2);
|
|
128
|
+
const payload = block
|
|
129
|
+
.split("\n")
|
|
130
|
+
.filter((l) => l.startsWith("data:"))
|
|
131
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
132
|
+
.join("\n");
|
|
133
|
+
if (payload && payload !== "[DONE]") {
|
|
134
|
+
try {
|
|
135
|
+
const frame = JSON.parse(payload);
|
|
136
|
+
if (frame?.type)
|
|
137
|
+
dispatch(frame.type, frame.data ?? {});
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
/* a malformed frame is skipped, never fatal */
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (settled)
|
|
144
|
+
return;
|
|
145
|
+
sep = buffer.indexOf("\n\n");
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
body.setEncoding?.("utf8");
|
|
149
|
+
body.on("data", (chunk) => {
|
|
150
|
+
if (settled)
|
|
151
|
+
return;
|
|
152
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
153
|
+
drain();
|
|
154
|
+
});
|
|
155
|
+
body.on("end", () => {
|
|
156
|
+
if (settled)
|
|
157
|
+
return;
|
|
158
|
+
buffer += "\n\n";
|
|
159
|
+
drain();
|
|
160
|
+
finish(() => reject(new StreamError("STREAM_ENDED", "The connection closed before the response finished.")));
|
|
161
|
+
});
|
|
162
|
+
body.on("error", () => {
|
|
163
|
+
finish(() => reject(signal?.aborted
|
|
164
|
+
? new StreamError("ABORTED", "Interrupted.")
|
|
165
|
+
: new StreamError("NETWORK_ERROR", "The connection to the API dropped mid-response.")));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|