@carrieros/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,94 @@
1
+ import { submitWithRetry } from "../services/client-tools.js";
2
+ import { createMutationCoordinator } from "../services/mutation-coordinator.js";
3
+ import { handleIdeToolCall, ideDeclaredMutationTools, ideDeclaredReadTools } from "./tool-host.js";
4
+ /**
5
+ * Run one IDE turn. Never throws: transport and stream failures come back as
6
+ * `result.error`, so the binding renders them without a second failure path.
7
+ */
8
+ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
9
+ const controller = new AbortController();
10
+ const abort = () => controller.abort();
11
+ if (externalSignal) {
12
+ if (externalSignal.aborted)
13
+ abort();
14
+ else
15
+ externalSignal.addEventListener("abort", abort, { once: true });
16
+ }
17
+ const signal = controller.signal;
18
+ // File-changing tools, gated exactly as the CLI gates them — trust plus a
19
+ // present approver (here, a live panel). Reads are gated on trust alone.
20
+ const mutationTools = ideDeclaredMutationTools(ctx, ports.approverPresent);
21
+ const mutations = mutationTools
22
+ ? createMutationCoordinator({
23
+ submit: (payload) => submitWithRetry(client, payload),
24
+ ui: {
25
+ review: (plans) => ports.reviewMutations(plans),
26
+ note: (lines) => ports.onMutationNote?.(lines),
27
+ cancelTurn: abort
28
+ }
29
+ })
30
+ : undefined;
31
+ const sessionId = ctx.config.get("sessionId");
32
+ const compose = ports.composeMessage ?? ((m) => m);
33
+ // What the model has said so far. It narrates as it works; commit each span at
34
+ // a tool boundary so a progress line lands above the activity it describes.
35
+ let streamed = "";
36
+ let shown = 0;
37
+ const say = (upTo = streamed) => {
38
+ const text = upTo.slice(shown);
39
+ shown = upTo.length;
40
+ if (text.trim())
41
+ ports.onAssistantText(text);
42
+ };
43
+ try {
44
+ const result = await client.chatStream({
45
+ mode: ctx.mode,
46
+ message: compose(message),
47
+ session_id: sessionId,
48
+ chat_type: ctx.chatType,
49
+ // Reads + editor context, and — only when an approver is present —
50
+ // the file-changing tools. Commands are not offered on this surface.
51
+ client_tools: ideDeclaredReadTools(ctx),
52
+ client_mutation_tools: mutationTools
53
+ }, {
54
+ onDelta: (delta) => {
55
+ if (signal.aborted)
56
+ return;
57
+ streamed += delta;
58
+ ports.onDelta?.(streamed.slice(shown));
59
+ },
60
+ onClientToolCall: (call) => {
61
+ // Whatever the model said before asking for this tool belongs above it.
62
+ say();
63
+ return handleIdeToolCall(ctx, client, call, {
64
+ editorState: ports.editorState,
65
+ resolveRepoForPath: ports.resolveRepoForPath,
66
+ toolUi: {
67
+ onStart: (label, tool) => ports.onToolStart?.(label, tool),
68
+ onDone: (label, ok, tool, detail) => ports.onToolEnd?.(label, ok, tool, detail),
69
+ mutations
70
+ }
71
+ });
72
+ }
73
+ }, signal);
74
+ // The final message — anything the model did not already narrate.
75
+ say(result.response);
76
+ if (result.session_id && result.session_id !== sessionId) {
77
+ ctx.config.set("sessionId", result.session_id);
78
+ }
79
+ return { response: result.response, sessionId: result.session_id ?? sessionId, applied: mutations?.applied ?? [] };
80
+ }
81
+ catch (err) {
82
+ const e = err;
83
+ return {
84
+ response: streamed,
85
+ sessionId,
86
+ applied: mutations?.applied ?? [],
87
+ error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed." }
88
+ };
89
+ }
90
+ finally {
91
+ if (externalSignal)
92
+ externalSignal.removeEventListener("abort", abort);
93
+ }
94
+ }
@@ -0,0 +1,109 @@
1
+ import { declaredClientTools, handleClientToolCall } from "../services/client-tools.js";
2
+ import { workspaceRoot } from "../services/local-files.js";
3
+ import { MUTATION_TOOL_NAMES } from "../services/mutations.js";
4
+ import { repositoryForPath } from "../services/workspace-registry.js";
5
+ import { isTrusted } from "../ui/trust.js";
6
+ import { executeIdeContextTool, isIdeContextTool } from "./editor-context.js";
7
+ const defaultResolver = (abs) => {
8
+ const repo = repositoryForPath(abs);
9
+ return repo ? { name: repo.name, root: repo.root } : null;
10
+ };
11
+ /**
12
+ * Handle one tool call from an IDE-driven turn. Never throws: every outcome,
13
+ * including a malformed editor-context call, becomes a submitted result so the
14
+ * backend turn can continue.
15
+ */
16
+ export async function handleIdeToolCall(ctx, client, call, deps) {
17
+ const id = typeof call?.tool_call_id === "string" ? call.tool_call_id : "";
18
+ if (!id)
19
+ return;
20
+ // Editor context is the only thing the IDE answers itself; everything else is
21
+ // the shared engine's job.
22
+ if (isIdeContextTool(call.name)) {
23
+ const started = Date.now();
24
+ const label = ideContextLabel(call);
25
+ deps.toolUi.onStart?.(label, call.name);
26
+ let payload;
27
+ try {
28
+ const res = executeIdeContextTool(call.name, (call.arguments ?? {}), deps.editorState(), deps.resolveRepoForPath ?? defaultResolver);
29
+ payload = res.ok
30
+ ? { tool_call_id: id, ok: true, result: (res.result ?? {}) }
31
+ : { tool_call_id: id, ok: false, error: res.error ?? { code: "IDE_TOOL_FAILED", message: "Failed." } };
32
+ }
33
+ catch (err) {
34
+ payload = { tool_call_id: id, ok: false, error: { code: "IDE_TOOL_FAILED", message: err.message ?? "Failed." } };
35
+ }
36
+ payload.duration_ms = Date.now() - started;
37
+ await client.submitToolResult(payload).catch(() => undefined);
38
+ deps.toolUi.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
39
+ return;
40
+ }
41
+ // Read / search / git / resolve / mutation / command — the shared engine,
42
+ // exactly as the CLI runs it. The host's toolUi carries its IDE coordinators.
43
+ await handleClientToolCall(ctx, client, call, deps.toolUi);
44
+ }
45
+ /** A short activity label for an editor-context call, for the chat panel. */
46
+ export function ideContextLabel(call) {
47
+ switch (call.name) {
48
+ case "get_active_file":
49
+ return "Checking the active file";
50
+ case "get_selection":
51
+ return "Reading your selection";
52
+ case "get_open_files":
53
+ return "Checking open files";
54
+ case "get_workspace_folders":
55
+ return "Checking the workspace";
56
+ case "get_diagnostics":
57
+ return "Reading diagnostics";
58
+ default:
59
+ return "Reading editor context";
60
+ }
61
+ }
62
+ /**
63
+ * The tools an IDE session declares to the backend: the CLI's read/git/resolve
64
+ * set (which the shared engine already gates on trust) plus the IDE
65
+ * editor-context tools. Mutation and command tools are declared separately by
66
+ * the host, exactly as the CLI does, so their approval UIs are wired.
67
+ */
68
+ export function ideReadTools(cliReadTools) {
69
+ if (!cliReadTools)
70
+ return undefined;
71
+ return [...cliReadTools, "get_active_file", "get_selection", "get_open_files", "get_workspace_folders", "get_diagnostics"];
72
+ }
73
+ /**
74
+ * The read/context tools an IDE turn offers, gated exactly as the CLI gates
75
+ * reads — folder trust — with the editor-context tools appended. Untrusted
76
+ * folder → no local tools at all, same as the terminal.
77
+ */
78
+ export function ideDeclaredReadTools(ctx) {
79
+ return ideReadTools(declaredClientTools(ctx));
80
+ }
81
+ /**
82
+ * The file-changing tools an IDE turn offers.
83
+ *
84
+ * The security rule is unchanged from the CLI's `declaredMutationTools`: folder
85
+ * trust is necessary but never sufficient — a change is only ever possible where
86
+ * a human can approve THAT change. The CLI proves an approver is present with
87
+ * `inScreen()` (the interactive terminal). The IDE cannot use that check —
88
+ * there is no terminal screen — so it substitutes the equivalent fact for its
89
+ * own surface: `approverPresent`, which the host sets true ONLY when a panel is
90
+ * live and will actually show the native diff + approval modal. The trust gate
91
+ * is identical; only the surface-presence proxy differs. If no approver is
92
+ * present, no mutation tools are declared, exactly as a piped CLI run offers
93
+ * none.
94
+ *
95
+ * Commands are deliberately NOT offered on the IDE surface in V1: the CLI's
96
+ * `run_command` depends on Windows Job Object containment wired to the terminal
97
+ * lifecycle and an explicit opt-in, and porting that containment to the IDE is a
98
+ * separate security review. Until then the IDE stays read + change only.
99
+ */
100
+ export function ideDeclaredMutationTools(ctx, approverPresent) {
101
+ if (!approverPresent)
102
+ return undefined;
103
+ try {
104
+ return isTrusted(ctx.config, workspaceRoot()) ? [...MUTATION_TOOL_NAMES] : undefined;
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
package/dist/main.js CHANGED
@@ -1,15 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, CommanderError } from "commander";
3
+ import { registerAttach } from "./commands/attach.js";
4
+ import { registerAuth } from "./commands/auth.js";
5
+ import { registerBtw } from "./commands/btw.js";
6
+ import { registerUpdate } from "./commands/update.js";
3
7
  import { registerChat } from "./commands/chat.js";
8
+ import { registerContext } from "./commands/context.js";
4
9
  import { registerDoctor } from "./commands/doctor.js";
5
10
  import { registerFiles } from "./commands/files.js";
6
11
  import { registerHelp } from "./commands/help.js";
7
12
  import { registerHistory } from "./commands/history.js";
13
+ import { registerMemory } from "./commands/memory.js";
8
14
  import { registerLogin } from "./commands/login.js";
9
15
  import { registerLogout } from "./commands/logout.js";
10
16
  import { registerModels } from "./commands/models.js";
11
17
  import { registerModes } from "./commands/modes.js";
12
18
  import { registerModeModel } from "./commands/mode-model.js";
19
+ import { registerRepo } from "./commands/repo.js";
20
+ import { registerRepos } from "./commands/repos.js";
21
+ import { registerSettings } from "./commands/settings.js";
22
+ import { registerReview } from "./commands/review.js";
23
+ import { attachConfig } from "./services/workspace-registry.js";
24
+ import { registerChanges } from "./commands/changes.js";
25
+ import { registerSearch } from "./commands/search.js";
26
+ import { registerScope } from "./commands/scope.js";
13
27
  import { registerSessions } from "./commands/sessions.js";
14
28
  import { registerUpload } from "./commands/upload.js";
15
29
  import { registerUsage } from "./commands/usage.js";
@@ -24,6 +38,8 @@ import { runShell } from "./shell/shell.js";
24
38
  import { loadAccent } from "./ui/theme.js";
25
39
  async function main() {
26
40
  const ctx = new CommandContext(new ConfigStore());
41
+ // Trust is per repository, so the registry has to be able to read it.
42
+ attachConfig(ctx.config);
27
43
  // Restore the saved accent color before anything renders.
28
44
  loadAccent(ctx.config.get("theme")?.accent);
29
45
  const program = new Command();
@@ -39,15 +55,28 @@ async function main() {
39
55
  // Phase A — auth & diagnostics
40
56
  registerLogin(program, ctx);
41
57
  registerLogout(program, ctx);
58
+ registerAuth(program, ctx);
42
59
  registerWhoami(program, ctx);
60
+ registerScope(program, ctx);
43
61
  registerVersion(program, ctx);
62
+ registerUpdate(program, ctx);
44
63
  registerDoctor(program, ctx);
45
- // Phase B — chat, sessions, history
64
+ registerRepo(program, ctx);
65
+ registerRepos(program, ctx);
66
+ registerSettings(program, ctx);
67
+ registerReview(program, ctx);
68
+ registerSearch(program, ctx);
69
+ registerChanges(program, ctx);
70
+ // Phase B — chat, sessions, history, context
46
71
  registerChat(program, ctx);
47
72
  registerSessions(program, ctx);
48
73
  registerHistory(program, ctx);
74
+ registerContext(program, ctx);
75
+ registerMemory(program, ctx);
76
+ registerBtw(program, ctx);
49
77
  // Phase C — files, usage, models, modes, guide
50
78
  registerUpload(program, ctx);
79
+ registerAttach(program, ctx);
51
80
  registerFiles(program, ctx);
52
81
  registerUsage(program, ctx);
53
82
  registerModels(program, ctx);
@@ -2,6 +2,24 @@ 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 { StreamError, consumeChatStream } from "./chat-stream.js";
6
+ /** Endpoints that work without a credential. Mirrors the /v1 router, where
7
+ * /health is mounted ABOVE the API-key gate and everything else below it. */
8
+ const PUBLIC_PATHS = new Set(["/health"]);
9
+ /** Collect a (small) response stream into a string — used for pre-stream errors. */
10
+ function readAll(stream) {
11
+ return new Promise((resolve) => {
12
+ const s = stream;
13
+ if (!s || typeof s.on !== "function")
14
+ return resolve(typeof stream === "string" ? stream : "");
15
+ let out = "";
16
+ s.on("data", (c) => {
17
+ out += typeof c === "string" ? c : c.toString("utf8");
18
+ });
19
+ s.on("end", () => resolve(out));
20
+ s.on("error", () => resolve(out));
21
+ });
22
+ }
5
23
  /** A typed, envelope-aware error surfaced by the API client. */
6
24
  export class ApiError extends Error {
7
25
  code;
@@ -21,18 +39,40 @@ export class ApiError extends Error {
21
39
  */
22
40
  export class ApiClient {
23
41
  baseUrl;
42
+ auth;
24
43
  http;
25
- constructor(baseUrl, secretKey) {
44
+ /**
45
+ * @param baseUrl the /v1 base
46
+ * @param auth an AuthProvider (device-flow) OR a legacy static key string.
47
+ */
48
+ constructor(baseUrl, auth) {
26
49
  this.baseUrl = baseUrl;
27
- this.http = axios.create({
28
- baseURL: baseUrl,
29
- timeout: 60_000,
30
- headers: secretKey ? { Authorization: `Bearer ${secretKey}` } : {}
31
- });
50
+ this.auth = auth;
51
+ this.http = axios.create({ baseURL: baseUrl, timeout: 60_000 });
52
+ }
53
+ /** Current bearer token, whether from a provider or a legacy static key. */
54
+ token() {
55
+ return typeof this.auth === "string" ? this.auth : this.auth?.token();
32
56
  }
33
- async request(config) {
57
+ async request(config, retry = true) {
58
+ const token = this.token();
59
+ // No credential at all — say so here rather than letting the request go out
60
+ // bare and come back as the server's MISSING_API_KEY, which reads like the
61
+ // user forgot to supply a key they were never meant to have. This happens
62
+ // whenever a dead refresh token makes authProvider.refresh clear local auth
63
+ // mid-session, so the shell can be running with the session already gone.
64
+ if (!token && !PUBLIC_PATHS.has(config.url ?? "")) {
65
+ throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
66
+ }
67
+ const withAuth = {
68
+ ...config,
69
+ headers: {
70
+ ...(config.headers ?? {}),
71
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
72
+ }
73
+ };
34
74
  try {
35
- const res = await this.http.request(config);
75
+ const res = await this.http.request(withAuth);
36
76
  const body = res.data;
37
77
  if (body?.success && body.data !== undefined)
38
78
  return body.data;
@@ -41,6 +81,22 @@ export class ApiClient {
41
81
  catch (err) {
42
82
  if (err instanceof ApiError)
43
83
  throw err;
84
+ // Silent refresh: on a 401, renew the token once and retry the request.
85
+ if (isAxiosError(err) &&
86
+ err.response?.status === 401 &&
87
+ retry &&
88
+ typeof this.auth === "object" &&
89
+ this.auth.refresh) {
90
+ const renewed = await this.auth.refresh(token);
91
+ if (renewed)
92
+ return this.request(config, false);
93
+ }
94
+ // The caller aborted (Ctrl+C during a turn). Distinct from a failure —
95
+ // callers render it as an interruption, not an error, and must never
96
+ // retry it.
97
+ if (isAxiosError(err) && (err.code === "ERR_CANCELED" || err.name === "CanceledError")) {
98
+ throw new ApiError("ABORTED", "Interrupted.", 0);
99
+ }
44
100
  if (isAxiosError(err)) {
45
101
  const status = err.response?.status;
46
102
  const body = err.response?.data;
@@ -48,9 +104,15 @@ export class ApiClient {
48
104
  if (body?.error?.code || body?.error?.message) {
49
105
  throw new ApiError(body.error.code || "REQUEST_FAILED", body.error.message || `Request failed (HTTP ${status}).`, status);
50
106
  }
51
- // Couldn't connect at all.
52
- if (["ECONNREFUSED", "ENOTFOUND", "ECONNABORTED", "ETIMEDOUT"].includes(err.code ?? "")) {
53
- throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${this.baseUrl}.`, 0);
107
+ // Couldn't connect, or the connection died mid-request. ECONNRESET is
108
+ // the one that matters in practice: the API restarting under a long
109
+ // turn drops the socket, and without it here that surfaced as a raw
110
+ // "read ECONNRESET / REQUEST_FAILED" with nothing to act on.
111
+ if (["ECONNREFUSED", "ENOTFOUND", "ECONNABORTED", "ETIMEDOUT", "ECONNRESET", "EPIPE"].includes(err.code ?? "")) {
112
+ const dropped = err.code === "ECONNRESET" || err.code === "EPIPE";
113
+ throw new ApiError("NETWORK_ERROR", dropped
114
+ ? "The connection to the API dropped mid-request."
115
+ : `Could not reach the API at ${this.baseUrl}.`, 0);
54
116
  }
55
117
  // Reached a server, but it didn't speak our envelope (wrong URL, proxy,
56
118
  // gateway page, …). Never surface an empty message.
@@ -73,8 +135,80 @@ export class ApiClient {
73
135
  return this.request({ method: "GET", url: "/models/chat" });
74
136
  }
75
137
  // ── Chat ────────────────────────────────────────────────────────────────────
76
- chat(body) {
77
- return this.request({ method: "POST", url: "/chat", data: body });
138
+ /** `signal` lets the caller abandon the request (Ctrl+C during a turn). */
139
+ chat(body, signal) {
140
+ return this.request({ method: "POST", url: "/chat", data: body, signal });
141
+ }
142
+ /**
143
+ * The same turn as `chat()`, over POST /v1/chat/stream. Resolves to the same
144
+ * `ChatResult`, so callers render it identically; along the way it reports
145
+ * answer deltas, progress and local tool requests through `handlers`.
146
+ *
147
+ * Aborting (Ctrl+C) actually stops the turn here: the server sees the socket
148
+ * close and cancels the model call, unlike the blocking endpoint, where the
149
+ * server finished — and billed — a reply nobody was waiting for.
150
+ */
151
+ async chatStream(body, handlers = {}, signal, retry = true) {
152
+ const token = this.token();
153
+ if (!token)
154
+ throw new ApiError("NOT_AUTHENTICATED", "You're not signed in.", 401);
155
+ let res;
156
+ try {
157
+ res = await this.http.request({
158
+ method: "POST",
159
+ url: "/chat/stream",
160
+ data: body,
161
+ signal,
162
+ responseType: "stream",
163
+ // No client-side timeout: a turn legitimately idles while a local tool
164
+ // runs, and the server's keep-alive pings hold the socket open.
165
+ timeout: 0,
166
+ headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
167
+ validateStatus: () => true
168
+ });
169
+ }
170
+ catch (err) {
171
+ if (isAxiosError(err) && (err.code === "ERR_CANCELED" || err.name === "CanceledError")) {
172
+ throw new ApiError("ABORTED", "Interrupted.", 0);
173
+ }
174
+ if (isAxiosError(err) && ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "ECONNRESET", "EPIPE"].includes(err.code ?? "")) {
175
+ throw new ApiError("NETWORK_ERROR", `Could not reach the API at ${this.baseUrl}.`, 0);
176
+ }
177
+ throw new ApiError("REQUEST_FAILED", err instanceof Error ? err.message : String(err));
178
+ }
179
+ // Anything but 200 is a plain JSON error sent before the stream opened.
180
+ if (res.status !== 200) {
181
+ const text = await readAll(res.data);
182
+ let env;
183
+ try {
184
+ env = JSON.parse(text);
185
+ }
186
+ catch {
187
+ env = undefined;
188
+ }
189
+ if (res.status === 401 && retry && typeof this.auth === "object" && this.auth.refresh) {
190
+ const renewed = await this.auth.refresh(token);
191
+ if (renewed)
192
+ return this.chatStream(body, handlers, signal, false);
193
+ }
194
+ throw new ApiError(env?.error?.code ?? `HTTP_${res.status}`, env?.error?.message ?? `Request failed (HTTP ${res.status}).`, res.status);
195
+ }
196
+ try {
197
+ return await consumeChatStream(res.data, handlers, signal);
198
+ }
199
+ catch (err) {
200
+ if (err instanceof StreamError)
201
+ throw new ApiError(err.code, err.message, err.status);
202
+ throw err;
203
+ }
204
+ }
205
+ /** Answer a `client_tool_call` (POST /v1/chat/tool-result). */
206
+ /** Record an undo the user ran with /undo, outside any turn. Metadata only. */
207
+ recordMutationAudit(payload) {
208
+ return this.request({ method: "POST", url: "/chat/mutation-audit", data: payload });
209
+ }
210
+ submitToolResult(payload) {
211
+ return this.request({ method: "POST", url: "/chat/tool-result", data: payload });
78
212
  }
79
213
  // ── Sessions / conversations ─────────────────────────────────────────────────
80
214
  conversations(params) {
@@ -92,6 +226,30 @@ export class ApiClient {
92
226
  deleteSession(id) {
93
227
  return this.request({ method: "DELETE", url: `/sessions/${id}` });
94
228
  }
229
+ /**
230
+ * A read-only side question about a session ("/btw"). Persists nothing: no
231
+ * message is stored and the conversation is untouched — which is why it is
232
+ * NOT `chat()`, since /v1/chat always writes both turns.
233
+ */
234
+ askAboutSession(sessionId, question, signal) {
235
+ return this.request({
236
+ method: "POST",
237
+ url: `/sessions/${sessionId}/ask`,
238
+ data: { question },
239
+ signal
240
+ });
241
+ }
242
+ // ── Memory (snapshots + restructures) ───────────────────────────────────────
243
+ /** One artifact, by the `artifact_id` carried on a transcript marker. */
244
+ memoryArtifact(id) {
245
+ return this.request({ method: "GET", url: `/memory/${id}` });
246
+ }
247
+ // ── SIA clarification ───────────────────────────────────────────────────────
248
+ /** Questions worth asking about an unsent prompt. Never throws for content
249
+ * reasons — the API answers `{skip:true}` when there's nothing to ask. */
250
+ siaQuestions(text) {
251
+ return this.request({ method: "POST", url: "/sia/questions", data: { text } });
252
+ }
95
253
  // ── Usage ────────────────────────────────────────────────────────────────────
96
254
  usage() {
97
255
  return this.request({ method: "GET", url: "/usage" });
@@ -0,0 +1,145 @@
1
+ /** Thrown for every way a stream can end other than `complete`. */
2
+ export class StreamError extends Error {
3
+ code;
4
+ status;
5
+ constructor(code, message, status = 0) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ this.name = "StreamError";
10
+ }
11
+ }
12
+ /** Map the server's `complete` payload onto the synchronous endpoint's shape. */
13
+ export function completeToResult(d) {
14
+ return {
15
+ id: d.message_id ?? null,
16
+ response: typeof d.content === "string" ? d.content : "",
17
+ session_id: d.session_id,
18
+ tokens_used: Number(d.tokens_used ?? 0) || 0,
19
+ cost_usd: typeof d.cost_usd === "number" ? d.cost_usd : undefined,
20
+ credits_remaining: typeof d.credits_remaining === "number" ? d.credits_remaining : null,
21
+ credits_unlimited: typeof d.credits_unlimited === "boolean" ? d.credits_unlimited : null,
22
+ credits_spent: typeof d.credits_spent === "number" ? d.credits_spent : null,
23
+ sources: Array.isArray(d.sources) ? d.sources : [],
24
+ web_search_used: d.web_search_used === true,
25
+ high_power_used: d.high_power_used === true,
26
+ speed: d.speed === "fast" ? "fast" : d.speed === "standard" ? "standard" : undefined,
27
+ model: typeof d.model === "string" ? d.model : undefined
28
+ };
29
+ }
30
+ /**
31
+ * Consume an SSE body until `complete`, `error`, `interrupted` or the socket
32
+ * ends. Frames are `data: {"type":…,"data":…}` separated by a blank line;
33
+ * `: ping` comments and the `[DONE]` sentinel carry nothing.
34
+ */
35
+ export function consumeChatStream(body, handlers = {}, signal) {
36
+ return new Promise((resolve, reject) => {
37
+ let buffer = "";
38
+ let settled = false;
39
+ const finish = (fn) => {
40
+ if (settled)
41
+ return;
42
+ settled = true;
43
+ signal?.removeEventListener?.("abort", onAbort);
44
+ fn();
45
+ };
46
+ function onAbort() {
47
+ finish(() => reject(new StreamError("ABORTED", "Interrupted.")));
48
+ try {
49
+ body.destroy?.();
50
+ }
51
+ catch {
52
+ /* already closed */
53
+ }
54
+ }
55
+ if (signal?.aborted) {
56
+ onAbort();
57
+ return;
58
+ }
59
+ signal?.addEventListener?.("abort", onAbort, { once: true });
60
+ const dispatch = (type, data) => {
61
+ switch (type) {
62
+ case "message_created":
63
+ handlers.onMessageCreated?.(data);
64
+ return;
65
+ case "chunk":
66
+ if (typeof data.delta === "string" && data.delta)
67
+ handlers.onDelta?.(data.delta);
68
+ return;
69
+ case "status":
70
+ case "tool_status":
71
+ if (typeof data.message === "string")
72
+ handlers.onStatus?.(type, data.message);
73
+ return;
74
+ case "client_tool_call": {
75
+ if (!handlers.onClientToolCall)
76
+ return;
77
+ // Never let a tool handler's failure — or its duration — stall the
78
+ // parser: the server keeps streaming while it waits for the result.
79
+ void Promise.resolve()
80
+ .then(() => handlers.onClientToolCall(data))
81
+ .catch(() => undefined);
82
+ return;
83
+ }
84
+ case "complete":
85
+ finish(() => resolve(completeToResult(data)));
86
+ return;
87
+ case "interrupted":
88
+ finish(() => reject(signal?.aborted
89
+ ? new StreamError("ABORTED", "Interrupted.")
90
+ : new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
91
+ return;
92
+ case "error":
93
+ finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.")));
94
+ return;
95
+ default:
96
+ return; // generation_type and anything newer: nothing to do
97
+ }
98
+ };
99
+ const drain = () => {
100
+ buffer = buffer.replace(/\r\n/g, "\n");
101
+ let sep = buffer.indexOf("\n\n");
102
+ while (sep !== -1) {
103
+ const block = buffer.slice(0, sep);
104
+ buffer = buffer.slice(sep + 2);
105
+ const payload = block
106
+ .split("\n")
107
+ .filter((l) => l.startsWith("data:"))
108
+ .map((l) => l.slice(5).replace(/^ /, ""))
109
+ .join("\n");
110
+ if (payload && payload !== "[DONE]") {
111
+ try {
112
+ const frame = JSON.parse(payload);
113
+ if (frame?.type)
114
+ dispatch(frame.type, frame.data ?? {});
115
+ }
116
+ catch {
117
+ /* a malformed frame is skipped, never fatal */
118
+ }
119
+ }
120
+ if (settled)
121
+ return;
122
+ sep = buffer.indexOf("\n\n");
123
+ }
124
+ };
125
+ body.setEncoding?.("utf8");
126
+ body.on("data", (chunk) => {
127
+ if (settled)
128
+ return;
129
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
130
+ drain();
131
+ });
132
+ body.on("end", () => {
133
+ if (settled)
134
+ return;
135
+ buffer += "\n\n";
136
+ drain();
137
+ finish(() => reject(new StreamError("STREAM_ENDED", "The connection closed before the response finished.")));
138
+ });
139
+ body.on("error", () => {
140
+ finish(() => reject(signal?.aborted
141
+ ? new StreamError("ABORTED", "Interrupted.")
142
+ : new StreamError("NETWORK_ERROR", "The connection to the API dropped mid-response.")));
143
+ });
144
+ });
145
+ }