@carrieros/cli 0.2.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 (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -1,11 +1,31 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import chalk from "chalk";
2
4
  import { ApiError } from "../services/api.js";
3
- import { capitalize, errorLine, info, line } from "../services/output.js";
5
+ import { capitalize, errorLine, info, line, success } from "../services/output.js";
6
+ import { detectLocalFiles } from "../services/file-detect.js";
7
+ import { fileTypeLabel, formatSize, uploadAndAttach, UploadError } from "../services/file-upload.js";
4
8
  import { sleep, withSpinner } from "../services/spinner.js";
5
- import { chatActivitySteps, startActivity } from "../ui/activity.js";
6
- import { renderComplete, renderCompleteLive, renderError, renderUserMessage, startThinking, streamAssistant, streamAssistantLive } from "../ui/chat-renderer.js";
9
+ import { c } from "../ui/colors.js";
10
+ import { renderProjectBrief, workspaceContextHint } from "../services/project-context.js";
11
+ import { declaredClientTools, declaredCommandTools, declaredMutationTools, handleClientToolCall, submitWithRetry } from "../services/client-tools.js";
12
+ import { APPROVAL_TIMEOUT_MS } from "../services/mutations.js";
13
+ import { createRenderer, toolKind, toolSummary } from "../ui/conversation.js";
14
+ import { watchForInterrupt } from "../ui/interrupt.js";
15
+ import { renderChangeSummary, renderGroup } from "../ui/change-review.js";
16
+ import { approveInScreen } from "../ui/screen-prompt.js";
17
+ import { createMutationCoordinator } from "../services/mutation-coordinator.js";
18
+ import { createCommandCoordinator } from "../services/command-coordinator.js";
19
+ import { displayCommand } from "../services/command-policy.js";
20
+ import { workspaceRoot } from "../services/local-files.js";
21
+ import { renderCommandReview, renderCommandSummary } from "../ui/command-review.js";
22
+ import { checkUrl, openUrl } from "../services/open-url.js";
23
+ import { renderAllSources, renderComplete, memoryMarkerLine, renderCompleteLive, renderError, renderSources, renderSourcesLive, renderUserMessage, searchCompletionLine, startThinking, streamAssistant } from "../ui/chat-renderer.js";
7
24
  import { startLiveComposer } from "../ui/live.js";
8
25
  import { pickFromList } from "../ui/select.js";
26
+ import { clarifyIntent } from "../ui/sia-qa.js";
27
+ import { parseSiaContext } from "../services/sia.js";
28
+ import { isMemoryMarker } from "../types/index.js";
9
29
  // Shared by the `chat` command REPL and the interactive shell so chat, mode and
10
30
  // model logic lives in exactly one place (no duplicated business logic).
11
31
  export const AUTO_LABEL = "Auto (mode default)";
@@ -28,59 +48,402 @@ export function modelLabelShort(ctx) {
28
48
  return "Auto";
29
49
  return modelCache?.find((m) => m.id === id)?.label ?? id;
30
50
  }
31
- /** Friendly label for the active Carrier mode — its display name (e.g. "Carrier
32
- * OS"), not the raw id. Falls back to a capitalized id until modes are loaded. */
51
+ /** Display name for a mode. The default mode's API name is "Carrier OS" (that's
52
+ * the Carrier-chat brand), but in a MODE context we show it as "General" so it
53
+ * reads as one mode among the others (Reasoning, Code, …). */
54
+ export function modeName(m) {
55
+ return m.id === "general" ? "General" : capitalize(m.name);
56
+ }
57
+ /** Friendly label for the active Carrier mode — "General" for the default, else
58
+ * its display name. Falls back to a capitalized id until modes are loaded. */
33
59
  export function modeLabelShort(ctx) {
34
60
  const id = ctx.mode;
61
+ if (id === "general")
62
+ return "General";
35
63
  return modeCache?.find((m) => m.id === id)?.name ?? capitalize(id);
36
64
  }
37
65
  function reportError(err) {
38
66
  errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
39
67
  }
68
+ /**
69
+ * The next step for each error the API can return.
70
+ *
71
+ * The API already sends human wording (utils/chatErrors.js), so the CLI's job is
72
+ * not to restate the problem — it's to say what to DO about it, which only the
73
+ * client knows because only the client has the commands. A code with no obvious
74
+ * next step maps to nothing rather than filler advice.
75
+ */
76
+ const ERROR_HINTS = {
77
+ INVALID_API_KEY: "/login",
78
+ NO_ACCOUNT: "/login",
79
+ AUTH_ERROR: "/login",
80
+ // Client-side: no credential was stored at all (never signed in, or a dead
81
+ // refresh token cleared the session mid-run).
82
+ NOT_AUTHENTICATED: "/login",
83
+ // Server-side counterpart, if a request ever leaves without the header.
84
+ MISSING_API_KEY: "/login",
85
+ // Context overflow: a new conversation is the one reliable fix, and a
86
+ // roomier model is the other.
87
+ MCAI_BLOCKED: "/new",
88
+ SESSION_NOT_FOUND: "/sessions",
89
+ // Out of credit on this model — pick another rather than retrying into the
90
+ // same wall. (The server substitutes when it can; this is when it couldn't.)
91
+ PROVIDER_EXHAUSTED: "/model",
92
+ USAGE_LIMIT_REACHED: "/usage",
93
+ // Wallet empty — /usage is where the balance and spend live.
94
+ INSUFFICIENT_CREDITS: "/usage",
95
+ };
96
+ /**
97
+ * The abort signal for a turn, and how to stop listening for it.
98
+ *
99
+ * THERE IS ONE OWNER OF STDIN. When the caller supplies a signal — the shell
100
+ * does, because its composer keeps reading while the turn runs — the turn must
101
+ * NOT attach its own stdin listener, or two consumers fight over every
102
+ * keystroke. Standalone `cos chat` has no composer, so there it still watches
103
+ * stdin itself for Ctrl+C.
104
+ */
105
+ function turnAbort(external) {
106
+ const controller = new AbortController();
107
+ if (external) {
108
+ // Linked rather than reused, so the turn itself can also stop (Ctrl+C at a
109
+ // change approval) without reaching into the shell's controller.
110
+ const forward = () => controller.abort();
111
+ if (external.aborted)
112
+ controller.abort();
113
+ else
114
+ external.addEventListener("abort", forward, { once: true });
115
+ return {
116
+ signal: controller.signal,
117
+ abort: () => controller.abort(),
118
+ stopWatching: () => external.removeEventListener("abort", forward)
119
+ };
120
+ }
121
+ const stop = watchForInterrupt(() => controller.abort());
122
+ return { signal: controller.signal, abort: () => controller.abort(), stopWatching: stop };
123
+ }
124
+ /**
125
+ * What a turn cost, taken from the response rather than computed here.
126
+ *
127
+ * The CLI never estimates spend: the model can be substituted when a provider
128
+ * is out of credit, so any local arithmetic would price the wrong model. Fields
129
+ * the API didn't send are simply omitted from the footer.
130
+ */
131
+ /**
132
+ * Add a finished turn's real debit to the session total.
133
+ *
134
+ * Separate from rendering on purpose: a turn that searched the web prints a
135
+ * different footer and never builds a TurnSpend, and its credits must still
136
+ * count toward "this session".
137
+ */
138
+ function recordTurnSpend(ctx, result) {
139
+ if (typeof result.credits_spent === "number") {
140
+ ctx.sessionCreditsSpent += result.credits_spent;
141
+ ctx.sessionSpendKnown = true;
142
+ }
143
+ }
144
+ function spendOf(result, ctx) {
145
+ return {
146
+ tokens: result.tokens_used,
147
+ costUsd: result.cost_usd,
148
+ creditsRemaining: result.credits_remaining ?? undefined,
149
+ unlimited: result.credits_unlimited ?? undefined,
150
+ sessionSpent: ctx?.sessionSpendKnown ? ctx.sessionCreditsSpent : undefined
151
+ };
152
+ }
153
+ /** True when the turn was cancelled by the user rather than failing. */
154
+ function wasAborted(err) {
155
+ return err instanceof ApiError && err.code === "ABORTED";
156
+ }
157
+ /**
158
+ * Ctrl+C during a turn. Deliberately NOT an error block — the user did this on
159
+ * purpose, so it gets one quiet line and the prompt back.
160
+ *
161
+ * Chat now streams, and closing the stream cancels the model call server-side,
162
+ * so the old "the turn may still be charged" warning would overstate it. What
163
+ * was already generated (and any input already processed) is still recorded —
164
+ * the server keeps the partial answer — so the note says the reply stopped, not
165
+ * that nothing happened.
166
+ */
167
+ function renderInterrupted() {
168
+ line(" " + c.warn("✗") + " " + c.dim("Cancelled — anything generated so far is kept in the session."));
169
+ line();
170
+ }
171
+ /**
172
+ * Codes that all mean the same thing to a person: you are not signed in. They
173
+ * differ only in WHERE that was discovered — locally before the request, or by
174
+ * the API after it — which is an implementation detail, not something to show.
175
+ */
176
+ const SIGNED_OUT = new Set(["NOT_AUTHENTICATED", "MISSING_API_KEY", "INVALID_API_KEY"]);
177
+ function errorTitle(err) {
178
+ return SIGNED_OUT.has(err.code) ? "You're not signed in" : err.message;
179
+ }
180
+ /**
181
+ * The API already sends human wording, so the default is just to name the code
182
+ * for support. The exceptions are the failures where the code tells the user
183
+ * nothing they can act on.
184
+ */
185
+ function errorDetail(err) {
186
+ if (SIGNED_OUT.has(err.code)) {
187
+ return "Your session has expired, or you haven't signed in on this machine yet.";
188
+ }
189
+ // Network failures are about the endpoint, not the request — name it, since
190
+ // a wrong --url is the usual cause and no amount of retrying fixes it.
191
+ if (err.code === "NETWORK_ERROR")
192
+ return "Check the API is running, then try again.";
193
+ if (err.code === "INSUFFICIENT_CREDITS") {
194
+ return "Nothing was charged for this message.";
195
+ }
196
+ return `Error code: ${err.code}`;
197
+ }
198
+ /** Render an API failure with its cause and the command that addresses it. */
199
+ function renderApiError(err) {
200
+ if (wasAborted(err)) {
201
+ renderInterrupted();
202
+ return;
203
+ }
204
+ if (!(err instanceof ApiError)) {
205
+ renderError("Something went wrong", err.message);
206
+ return;
207
+ }
208
+ // Running out of credits is a state to act on, not a fault — a red × made a
209
+ // billing prompt look like a crash.
210
+ const tone = err.code === "INSUFFICIENT_CREDITS" ? "warn" : "error";
211
+ renderError(errorTitle(err), errorDetail(err), ERROR_HINTS[err.code], tone);
212
+ }
213
+ /**
214
+ * Cache a newly-created conversation's title for the footer. Best-effort and
215
+ * deliberately un-awaited — a title is cosmetic, so it must never delay a reply
216
+ * or surface an error of its own.
217
+ */
218
+ /**
219
+ * Say so when a different model answered than the one selected.
220
+ *
221
+ * The API substitutes a working model when the requested provider has run out
222
+ * of credit. That's the right behaviour — an answer beats a 404 — but it must
223
+ * never be silent, or the footer keeps claiming a model that didn't reply and
224
+ * the cost lands on a different line item than expected.
225
+ */
226
+ function noteModelSubstitution(ctx, answered) {
227
+ if (!answered)
228
+ return null;
229
+ // Fast mode and Auto MODE both hand model choice to the backend, so a
230
+ // different answering model is expected routing — not the model you picked
231
+ // being unavailable. Reporting it as unavailability was alarming and wrong:
232
+ // in Auto, your selection is a preference the router may override by design.
233
+ const delegated = ctx.fast || ctx.mode === "auto";
234
+ const asked = delegated ? "" : currentModelId(ctx);
235
+ if (!asked || asked === answered)
236
+ return null;
237
+ const label = modelCache?.find((m) => m.id === answered)?.label ?? answered;
238
+ const askedLabel = modelCache?.find((m) => m.id === asked)?.label ?? asked;
239
+ return `${askedLabel} was unavailable — answered with ${label}.`;
240
+ }
241
+ async function learnSessionTitle(ctx, client, sessionId) {
242
+ try {
243
+ const s = await client.session(sessionId);
244
+ // Guard against a race: the user may have switched conversations while this
245
+ // was in flight, and overwriting the title then would mislabel the footer.
246
+ if (ctx.config.get("sessionId") === sessionId && s.title) {
247
+ ctx.config.set("sessionTitle", s.title);
248
+ }
249
+ }
250
+ catch {
251
+ /* cosmetic only — leave the footer unnamed */
252
+ }
253
+ }
254
+ /**
255
+ * Echo the prompt the way the user wrote it.
256
+ *
257
+ * When SIA has run, the string being sent carries an appended
258
+ * `[Clarification Context]` block — machine payload the model reads, not
259
+ * something to show raw. The website splits it the same way when rendering the
260
+ * transcript, so this keeps the two clients showing the same conversation.
261
+ */
262
+ function renderPrompt(message, alreadyEchoed = false) {
263
+ const parsed = parseSiaContext(message);
264
+ if (!parsed) {
265
+ if (!alreadyEchoed)
266
+ renderUserMessage(message);
267
+ return;
268
+ }
269
+ if (!alreadyEchoed)
270
+ renderUserMessage(parsed.displayPrompt);
271
+ renderSiaContext(message);
272
+ }
273
+ /** The clarification answers SIA added, as dim continuation lines. */
274
+ function renderSiaContext(message) {
275
+ const parsed = parseSiaContext(message);
276
+ if (!parsed)
277
+ return;
278
+ for (const item of parsed.items) {
279
+ line(" " + c.dim("↳ " + item.label + ": ") + c.value(item.value));
280
+ }
281
+ line();
282
+ }
40
283
  /**
41
284
  * Send one chat turn using the config's current mode + model, and render it.
42
285
  * When `opts.footer` is supplied (the interactive shell), the input bar stays
43
286
  * pinned at the bottom and the response streams above it; otherwise (the plain
44
287
  * `chat` REPL) output just prints inline.
45
288
  */
289
+ /**
290
+ * Prefix the outgoing message with the project brief when one is armed.
291
+ *
292
+ * Applied to the REQUEST and not to the prompt: the brief is context for the
293
+ * model, not something the user typed, so it must never turn up in the echoed
294
+ * transcript or in the history the composer scrolls through.
295
+ *
296
+ * Cleared after a single send. The conversation keeps it in history from then
297
+ * on, so re-sending it every turn would pay for the same tokens repeatedly and
298
+ * push the real message further from the model's attention.
299
+ *
300
+ * Never allowed to break a turn: if the walk fails for any reason the message
301
+ * goes out exactly as it would have before.
302
+ */
303
+ function withProjectContext(ctx, message) {
304
+ try {
305
+ // The opt-in brief already lists the workspace repositories, so send it when
306
+ // pending; otherwise attach the lightweight always-on workspace context so
307
+ // the model still knows the repositories exist. In single-repository mode
308
+ // workspaceContextHint() is null, so nothing is added (unchanged behaviour).
309
+ if (ctx.config.get("projectContextPending") === true) {
310
+ const brief = renderProjectBrief();
311
+ ctx.config.set("projectContextPending", false);
312
+ return `${brief}\n\n${message}`;
313
+ }
314
+ const ws = workspaceContextHint();
315
+ return ws ? `${ws}\n\n${message}` : message;
316
+ }
317
+ catch {
318
+ return message;
319
+ }
320
+ }
46
321
  export async function chatTurn(ctx, client, message, opts = {}) {
322
+ // SIA rewrites the prompt, so it has to resolve before EITHER render path
323
+ // starts — the merged text is what gets echoed, sent and stored. A read-only
324
+ // task (a review) is fixed, not an ambiguous request, so it never clarifies.
325
+ let echoed = false;
326
+ if (ctx.sia && !opts.readOnly && !opts.sendAs && process.stdin.isTTY) {
327
+ // Echo BEFORE the questions. On the web the prompt stays sitting in the
328
+ // composer while the overlay opens beneath it, so it is always in view;
329
+ // in a terminal the questions would otherwise be the first thing on screen
330
+ // with no sign of what they are even about.
331
+ renderUserMessage(message);
332
+ echoed = true;
333
+ const result = await clarifyIntent(client, message);
334
+ if (result.cancelled) {
335
+ line();
336
+ line(" " + c.warn("⊘") + " " + c.dim("Cancelled — nothing sent."));
337
+ line();
338
+ return;
339
+ }
340
+ message = result.prompt;
341
+ }
47
342
  const useLiveBar = opts.footer !== undefined && process.stdout.isTTY;
48
343
  if (useLiveBar) {
49
- await chatTurnLive(ctx, client, message, opts.footer ?? "");
344
+ await chatTurnLive(ctx, client, message, opts.footer ?? "", opts.webSearch, echoed, opts.signal, { readOnly: opts.readOnly, sendAs: opts.sendAs });
50
345
  return;
51
346
  }
52
347
  const mode = ctx.mode;
53
348
  const model = currentModelId(ctx);
54
- renderUserMessage(message);
349
+ // An explicit override (a one-shot `/websearch <query>`) beats the armed flag
350
+ // and the persisted preference, and leaves both untouched.
351
+ const webSearch = opts.webSearch ?? ctx.effectiveWebSearch;
352
+ renderPrompt(message, echoed);
55
353
  const started = Date.now();
56
- const spinner = startThinking();
354
+ let spinner = startThinking();
355
+ const { signal, stopWatching } = turnAbort(opts.signal);
57
356
  try {
58
357
  const sessionId = ctx.config.get("sessionId");
59
- const result = await client.chat({
358
+ const attached = ctx.attachedFileIds;
359
+ const result = await client.chatStream({
60
360
  mode,
61
- message,
361
+ message: opts.sendAs ?? withProjectContext(ctx, message),
62
362
  session_id: sessionId,
63
363
  model: model || undefined,
64
- chat_type: ctx.chatType
65
- });
364
+ chat_type: ctx.chatType,
365
+ web_search: webSearch,
366
+ speed: ctx.fast ? "fast" : undefined,
367
+ high_power: ctx.highPower ? true : undefined,
368
+ file_ids: attached.length ? attached : undefined,
369
+ client_tools: declaredClientTools(ctx)
370
+ }, {
371
+ // A local tool step is committed as its own quiet line; the spinner is
372
+ // paused around it so the two never draw over each other.
373
+ // (non-live path declares only read tools already — read-only by construction)
374
+ onClientToolCall: (call) => handleClientToolCall(ctx, client, call, {
375
+ onStart: (label) => {
376
+ spinner.stop();
377
+ line(" " + c.dim(`● ${label}`));
378
+ spinner = startThinking();
379
+ }
380
+ })
381
+ }, signal);
66
382
  spinner.stop();
383
+ // A bare /websearch arms exactly one turn — spend it whether or not the
384
+ // turn ended up searching, so the footer never lies about what's pending.
385
+ if (opts.webSearch === undefined)
386
+ ctx.disarmWebSearch();
67
387
  // Persist the session so the conversation continues across turns/invocations.
68
388
  if (result.session_id && result.session_id !== sessionId) {
69
389
  ctx.config.set("sessionId", result.session_id);
390
+ // The chat response carries no title, and the backend generates one from
391
+ // the first message — fetch it once, in the background, so the footer can
392
+ // name the conversation without delaying the reply. Failure is silent:
393
+ // the footer simply stays unnamed.
394
+ void learnSessionTitle(ctx, client, result.session_id);
70
395
  }
396
+ const sources = result.sources ?? [];
397
+ ctx.recordSearch(sources);
71
398
  await streamAssistant(result.response);
72
- renderComplete((Date.now() - started) / 1000);
73
- }
74
- catch (err) {
75
- spinner.stop();
76
- if (err instanceof ApiError) {
77
- const hint = err.code === "INVALID_API_KEY" || err.code === "NO_ACCOUNT" ? "/login" : undefined;
78
- renderError(err.message, `Error code: ${err.code}`, hint);
399
+ const swapped = noteModelSubstitution(ctx, result.model);
400
+ if (swapped)
401
+ line(" " + c.warn("!") + " " + c.dim(swapped));
402
+ renderSources(sources);
403
+ recordTurnSpend(ctx, result);
404
+ const elapsed = (Date.now() - started) / 1000;
405
+ // One footer per turn: the search line already carries the duration, so
406
+ // printing the generic one underneath would just repeat it.
407
+ if (sources.length > 0) {
408
+ line(searchCompletionLine(sources.length, elapsed));
409
+ line();
79
410
  }
80
411
  else {
81
- renderError("Something went wrong", err.message);
412
+ renderComplete(elapsed, spendOf(result, ctx));
413
+ void showNewMemoryMarkers(ctx, client, result.session_id);
82
414
  }
83
415
  }
416
+ catch (err) {
417
+ spinner.stop();
418
+ renderApiError(err);
419
+ }
420
+ finally {
421
+ // Always detach, so the composer's own Ctrl+C (arm-then-exit) works again.
422
+ stopWatching();
423
+ }
424
+ }
425
+ /** What the prompt asks, in the plan's own terms. */
426
+ function approvalQuestion(plans) {
427
+ if (plans.length > 1)
428
+ return `Apply all ${plans.length} changes?`;
429
+ switch (plans[0]?.name) {
430
+ case "revert_change":
431
+ return "Undo this change?";
432
+ case "delete_file":
433
+ return "Delete this file?";
434
+ case "create_file":
435
+ return "Create this file?";
436
+ default:
437
+ return "Apply this change?";
438
+ }
439
+ }
440
+ /** "Running the project tests" reads better than the argv on an activity line. */
441
+ function commandActivityLabel(d) {
442
+ if (d.script)
443
+ return `Running the ${d.script.name} script`;
444
+ if (d.program === "git")
445
+ return `Checking git ${d.args[0] ?? "status"}`;
446
+ return `Running ${d.program}`;
84
447
  }
85
448
  /**
86
449
  * chatTurn with the sticky bottom input bar + an activity timeline. The turn
@@ -89,55 +452,192 @@ export async function chatTurn(ctx, client, message, opts = {}) {
89
452
  * front so the timeline overlays the genuine wait (adding no latency), then the
90
453
  * timeline collapses and the answer streams in word-by-word.
91
454
  */
92
- async function chatTurnLive(ctx, client, message, footer) {
455
+ async function chatTurnLive(ctx, client, message, footer, webSearchOverride,
456
+ /** The prompt was already echoed above the SIA questions — print only the
457
+ * answers, so it doesn't appear twice. */
458
+ alreadyEchoed = false,
459
+ /** Supplied by the shell, which owns stdin and therefore owns Ctrl+C. */
460
+ externalSignal,
461
+ /** A read-only turn declares no mutation/command tools; sendAs overrides the payload. */
462
+ turnOpts = {}) {
93
463
  const mode = ctx.mode;
94
464
  const model = currentModelId(ctx);
95
465
  const sessionId = ctx.config.get("sessionId");
96
- renderUserMessage(message);
466
+ const webSearch = webSearchOverride ?? ctx.effectiveWebSearch;
97
467
  const live = startLiveComposer(footer);
98
- const activity = startActivity(live);
468
+ // One owner for everything this turn draws: the user's message, activity,
469
+ // approval cards, command output and the answer (see ui/conversation.ts).
470
+ const ui = createRenderer(live);
471
+ if (!alreadyEchoed)
472
+ ui.user(message);
473
+ renderSiaContext(message);
99
474
  const started = Date.now();
475
+ // Ctrl+C aborts the request. The activity timeline is a client-side animation
476
+ // over a real await, so cancelling has to cut the HTTP call — stopping the
477
+ // spinner alone would leave the turn running invisibly.
478
+ const { signal, abort, stopWatching } = turnAbort(externalSignal);
479
+ // One prompt at a time: a file-change review and a command approval in the
480
+ // same step would otherwise both try to own the keyboard.
481
+ let terminal = Promise.resolve();
482
+ const withTerminal = (fn) => {
483
+ const run = terminal.then(fn, fn);
484
+ terminal = run.catch(() => undefined);
485
+ return run;
486
+ };
487
+ /**
488
+ * What the assistant has said so far.
489
+ *
490
+ * The model narrates as it works — a line before it reads something, another
491
+ * before it runs the tests — and those lines are the conversation. Text is
492
+ * committed at each boundary (a tool call, or the end of the turn), so a
493
+ * progress message lands ABOVE the activity it describes instead of arriving
494
+ * after everything as one block.
495
+ */
496
+ let streamed = "";
497
+ let shown = 0;
498
+ const say = (upTo = streamed) => {
499
+ const text = upTo.slice(shown);
500
+ shown = upTo.length;
501
+ if (text.trim())
502
+ ui.assistant(text);
503
+ };
504
+ // A read-only turn (a review) offers NEITHER mutation nor command tools, so
505
+ // the model cannot change files or run commands whatever the prompt says.
506
+ const mutationTools = turnOpts.readOnly ? undefined : declaredMutationTools(ctx);
507
+ const mutations = mutationTools
508
+ ? createMutationCoordinator({
509
+ submit: (payload) => submitWithRetry(client, payload),
510
+ ui: {
511
+ review: (plans) => withTerminal(() => ui.borrow(async () => {
512
+ ui.stepEnd();
513
+ ui.commit(renderGroup(plans));
514
+ const question = approvalQuestion(plans);
515
+ return approveInScreen({ question, timeoutMs: APPROVAL_TIMEOUT_MS, signal });
516
+ })),
517
+ note: (lines) => ui.commit([...renderChangeSummary(lines), ""]),
518
+ cancelTurn: abort
519
+ }
520
+ })
521
+ : undefined;
522
+ const commandTools = turnOpts.readOnly ? undefined : declaredCommandTools(ctx);
523
+ let commands;
524
+ if (commandTools) {
525
+ const auth = ctx.config.get("auth");
526
+ commands = createCommandCoordinator({
527
+ root: workspaceRoot(),
528
+ signal,
529
+ withTerminal,
530
+ cliSecrets: [auth?.accessToken, auth?.refreshToken, ctx.config.get("secretKey")].filter((v) => typeof v === "string"),
531
+ submit: (payload) => submitWithRetry(client, payload),
532
+ ui: {
533
+ review: (decision, reason, repository) => ui.borrow(async () => {
534
+ ui.stepEnd();
535
+ ui.commit(renderCommandReview(decision, reason, repository));
536
+ return approveInScreen({ question: "Run this command?", timeoutMs: APPROVAL_TIMEOUT_MS, signal });
537
+ }),
538
+ started: (decision) => ui.commandStarted(commandActivityLabel(decision), displayCommand(decision.program, decision.effectiveArgs)),
539
+ output: (_stream, text) => ui.commandOutput(text),
540
+ finished: ({ decision, result, errorCode, message: detail }) => {
541
+ ui.commandEnded();
542
+ ui.commit([...renderCommandSummary(decision, result, errorCode, detail), ""]);
543
+ ui.status("thinking", "Working");
544
+ },
545
+ cancelTurn: abort
546
+ }
547
+ });
548
+ }
100
549
  // request_started + request_sent: fire the real call immediately, then the
101
550
  // brief client-side steps play over the actual wait. Settle it eagerly so a
102
551
  // rejection during the steps is never an unhandled rejection.
552
+ const attached = ctx.attachedFileIds;
553
+ // Deltas are consumed as they arrive, but the answer is still rendered by the
554
+ // formatted renderer once complete — it needs the whole text to lay out
555
+ // markdown, and rendering half a code fence would reflow the screen. What the
556
+ // stream buys here is truth in the timeline: a real "writing" phase, and each
557
+ // local tool step shown as it happens instead of a guessed label.
103
558
  const settled = client
104
- .chat({ mode, message, session_id: sessionId, model: model || undefined, chat_type: ctx.chatType })
559
+ .chatStream({
560
+ mode,
561
+ message: turnOpts.sendAs ?? withProjectContext(ctx, message),
562
+ session_id: sessionId,
563
+ model: model || undefined,
564
+ chat_type: ctx.chatType,
565
+ web_search: webSearch,
566
+ speed: ctx.fast ? "fast" : undefined,
567
+ high_power: ctx.highPower ? true : undefined,
568
+ file_ids: attached.length ? attached : undefined,
569
+ client_tools: declaredClientTools(ctx),
570
+ client_mutation_tools: mutationTools,
571
+ client_command_tools: commandTools
572
+ }, {
573
+ onDelta: (delta) => {
574
+ if (signal.aborted)
575
+ return;
576
+ streamed += delta;
577
+ ui.writing(streamed.slice(shown));
578
+ },
579
+ onClientToolCall: (call) => {
580
+ // Whatever the model said before asking for this tool belongs above it.
581
+ say();
582
+ return handleClientToolCall(ctx, client, call, {
583
+ onStart: (label, tool) => ui.toolStart(label, toolKind(tool)),
584
+ onDone: (label, ok, tool, detail) => ui.toolEnd(label, toolKind(tool), toolSummary(tool, ok, detail), ok),
585
+ mutations,
586
+ commands
587
+ });
588
+ }
589
+ }, signal)
105
590
  .then((r) => ({ ok: true, r }))
106
591
  .catch((e) => ({ ok: false, e }));
107
592
  try {
108
- const steps = chatActivitySteps(capitalize(mode));
109
- for (let i = 0; i < steps.length - 1; i++) {
110
- activity.step(steps[i]); // request_started → mode_selected → request_sent
111
- await sleep(190);
112
- }
113
- activity.step(steps[steps.length - 1]); // waiting — spins over the real await
593
+ // One honest line instead of a scripted checklist: the turn is waiting on
594
+ // the model until something real (a tool call, a delta) says otherwise.
595
+ ui.status("thinking", webSearch === true ? "Searching the web" : ctx.highPower ? "Thinking (high power)" : "Thinking");
114
596
  const outcome = await settled;
115
- activity.done();
116
- activity.stop();
117
- live.setStatus([]); // collapse the activity checklist before the answer
597
+ ui.stepEnd();
598
+ ui.stop(); // the live region is done; what remains is committed below
118
599
  if (!outcome.ok)
119
600
  throw outcome.e;
120
601
  const result = outcome.r;
602
+ if (webSearchOverride === undefined)
603
+ ctx.disarmWebSearch(); // spend the one-shot arm
121
604
  if (result.session_id && result.session_id !== sessionId) {
122
605
  ctx.config.set("sessionId", result.session_id);
606
+ // The chat response carries no title, and the backend generates one from
607
+ // the first message — fetch it once, in the background, so the footer can
608
+ // name the conversation without delaying the reply. Failure is silent:
609
+ // the footer simply stays unnamed.
610
+ void learnSessionTitle(ctx, client, result.session_id);
123
611
  }
124
612
  // Stream the answer in the SAME pinned composer so the reply sits directly
125
613
  // beneath the user's message (contiguous — no gap), with the input bar
126
614
  // staying visible the whole time. Finished lines commit above the bar.
127
- await streamAssistantLive(live, result.response); // header → stream → each line locked
128
- renderCompleteLive(live, (Date.now() - started) / 1000);
615
+ const sources = result.sources ?? [];
616
+ ctx.recordSearch(sources);
617
+ say(result.response); // the final message — anything not already narrated
618
+ const swapped = noteModelSubstitution(ctx, result.model);
619
+ if (swapped)
620
+ live.commit([" " + c.warn("!") + " " + c.dim(swapped)]);
621
+ renderSourcesLive(live, sources);
622
+ recordTurnSpend(ctx, result);
623
+ const elapsed = (Date.now() - started) / 1000;
624
+ // One footer per turn — see chatTurn.
625
+ if (sources.length > 0)
626
+ live.commit([searchCompletionLine(sources.length, elapsed), ""]);
627
+ else
628
+ renderCompleteLive(live, elapsed, spendOf(result, ctx));
629
+ void showNewMemoryMarkers(ctx, client, result.session_id);
129
630
  live.stop();
130
631
  }
131
632
  catch (err) {
132
- activity.stop();
633
+ ui.stepEnd();
634
+ ui.stop();
133
635
  live.stop();
134
- if (err instanceof ApiError) {
135
- const hint = err.code === "INVALID_API_KEY" || err.code === "NO_ACCOUNT" ? "/login" : undefined;
136
- renderError(err.message, `Error code: ${err.code}`, hint);
137
- }
138
- else {
139
- renderError("Something went wrong", err.message);
140
- }
636
+ renderApiError(err);
637
+ }
638
+ finally {
639
+ // Always detach, so the composer's own Ctrl+C (arm-then-exit) works again.
640
+ stopWatching();
141
641
  }
142
642
  }
143
643
  // ── Chat type (Carrier Chat vs Standard) ──────────────────────────────────────
@@ -162,8 +662,8 @@ export function setChatType(ctx, arg) {
162
662
  const on = t === ctx.chatType;
163
663
  const label = on ? chalk.bold(chatTypeLabel(t)) : chatTypeLabel(t);
164
664
  const desc = t === "carrier"
165
- ? "Flagship Carrier OS chat — full persona, 128k context, memory."
166
- : "Plain chat — Carrier persona without the app-instruction layer.";
665
+ ? "Flagship Carrier OS chat - full persona, 128k context, memory."
666
+ : "Plain chat - Carrier persona without the app-instruction layer.";
167
667
  line(` ${on ? chalk.green("►") : " "} ${label.padEnd(15)} ${chalk.dim(desc)}`);
168
668
  }
169
669
  line();
@@ -219,6 +719,339 @@ export async function pickChatType(ctx) {
219
719
  ctx.setChatType(next);
220
720
  info(`Switched to ${chatTypeLabel(next)}. A new conversation starts on your next message.`);
221
721
  }
722
+ // ── Web search ────────────────────────────────────────────────────────────────
723
+ // A capability of chat, not a separate tool. Three ways in, deliberately:
724
+ // /websearch arm the NEXT message, then fall back automatically
725
+ // /websearch <query> search right now, changing no state at all
726
+ // /websearch on|off a standing preference, persisted like mode/model
727
+ // Left unset the API follows the workspace's admin toggle (what the web does).
728
+ const WEB_SEARCH_NOTE = "Carrier still skips the search for code, math and timeless questions, and whenever files are attached.";
729
+ /**
730
+ * Footer label — null when there's nothing worth asserting (workspace default,
731
+ * or explicitly off).
732
+ *
733
+ * Armed and always-on share one label: the chip vanishing after a single turn
734
+ * is already what tells you the arm was one-shot, so a separate word for it
735
+ * would only add noise to the line you read most often.
736
+ */
737
+ export function webSearchLabelShort(ctx) {
738
+ return ctx.webSearchArmed || ctx.webSearch === true ? "Websearch" : null;
739
+ }
740
+ /** "2m ago" / "just now" for the last search, or null if there hasn't been one. */
741
+ export function lastSearchAgo(ctx) {
742
+ const at = ctx.lastSearchAt;
743
+ if (at === null)
744
+ return null;
745
+ const mins = Math.floor((Date.now() - at) / 60_000);
746
+ if (mins < 1)
747
+ return "just now";
748
+ if (mins < 60)
749
+ return `${mins}m ago`;
750
+ const hours = Math.floor(mins / 60);
751
+ return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
752
+ }
753
+ const ON_WORDS = ["on", "yes", "true", "enable", "enabled"];
754
+ const OFF_WORDS = ["off", "no", "false", "disable", "disabled"];
755
+ const AUTO_WORDS = ["auto", "default", "workspace"];
756
+ /** True when the argument is a state word rather than a search query. */
757
+ export function isWebSearchStateArg(arg) {
758
+ const raw = arg.trim().toLowerCase();
759
+ if (!raw)
760
+ return true;
761
+ return (ON_WORDS.includes(raw) ||
762
+ OFF_WORDS.includes(raw) ||
763
+ AUTO_WORDS.includes(raw) ||
764
+ raw === "status");
765
+ }
766
+ /** `/websearch` with no argument — arm the next message. */
767
+ export function armWebSearch(ctx) {
768
+ if (ctx.webSearch === true) {
769
+ info("Web search is already on for every message. /websearch off to stop.");
770
+ return;
771
+ }
772
+ ctx.armWebSearch();
773
+ line();
774
+ line(" " + c.ok("✓") + " " + c.title("Web search enabled"));
775
+ line();
776
+ line(" " + c.dim("Scope ") + c.value("your next message"));
777
+ line(" " + c.dim("Mode ") + c.value("live web"));
778
+ line();
779
+ line(" " + c.dim(WEB_SEARCH_NOTE));
780
+ line();
781
+ }
782
+ /** `/websearch on|off|auto|status`. */
783
+ export function setWebSearch(ctx, arg) {
784
+ const raw = arg.trim().toLowerCase();
785
+ if (!raw || raw === "status") {
786
+ showWebSearchStatus(ctx);
787
+ return;
788
+ }
789
+ if (AUTO_WORDS.includes(raw)) {
790
+ ctx.disarmWebSearch();
791
+ ctx.config.set("webSearch", undefined);
792
+ info("Web search follows your workspace default.");
793
+ return;
794
+ }
795
+ if (ON_WORDS.includes(raw)) {
796
+ ctx.disarmWebSearch(); // a standing preference supersedes the one-shot arm
797
+ ctx.setWebSearch(true);
798
+ info(`Web search on for every message. ${WEB_SEARCH_NOTE}`);
799
+ return;
800
+ }
801
+ if (OFF_WORDS.includes(raw)) {
802
+ ctx.disarmWebSearch();
803
+ ctx.setWebSearch(false);
804
+ info("Web search off.");
805
+ return;
806
+ }
807
+ errorLine(`Unknown value "${arg.trim()}". Use /websearch on, off, auto, or status.`);
808
+ }
809
+ /** `/websearch status` — the current state and what the last search returned. */
810
+ export function showWebSearchStatus(ctx) {
811
+ const status = ctx.webSearchArmed
812
+ ? "Armed"
813
+ : ctx.webSearch === true
814
+ ? "Enabled"
815
+ : ctx.webSearch === false
816
+ ? "Disabled"
817
+ : "Workspace default";
818
+ const scope = ctx.webSearchArmed
819
+ ? "next message only"
820
+ : ctx.webSearch === true
821
+ ? "every message"
822
+ : ctx.webSearch === false
823
+ ? "never"
824
+ : "decided by your workspace";
825
+ const ago = lastSearchAgo(ctx);
826
+ const rows = [
827
+ ["Status", status],
828
+ ["Scope", scope],
829
+ ["Last search", ago ?? "none this session"]
830
+ ];
831
+ if (ago)
832
+ rows.push(["Results", `${ctx.lastSources.length} sources`]);
833
+ line();
834
+ line(" " + c.title("Web search"));
835
+ line();
836
+ for (const [k, v] of rows)
837
+ line(" " + c.dim(k.padEnd(13)) + c.value(v));
838
+ line();
839
+ // Point at the state they're NOT in — a "turn it on" hint under a status that
840
+ // already says Enabled is just noise.
841
+ line(" " +
842
+ (ctx.webSearch === true
843
+ ? c.dim("Stop with ") + c.cmd("/websearch off")
844
+ : c.dim("Turn on with ") + c.cmd("/websearch on")));
845
+ line(" " + c.dim("Search once with ") + c.cmd("/websearch <query>"));
846
+ if (ago)
847
+ line(" " + c.dim("Revisit results with ") + c.cmd("/sources"));
848
+ line();
849
+ }
850
+ /** `/websearch <query>` — one search now, leaving every setting untouched. */
851
+ export async function searchNow(ctx, client, query, footer) {
852
+ await chatTurn(ctx, client, query, { footer, webSearch: true });
853
+ }
854
+ /** `/sources` — the full citation list from the most recent search. */
855
+ export function showSources(ctx) {
856
+ const sources = ctx.lastSources;
857
+ if (sources.length === 0) {
858
+ info("No sources yet. Ask something with web search on, then run /sources.");
859
+ return;
860
+ }
861
+ renderAllSources(sources, lastSearchAgo(ctx));
862
+ }
863
+ /** `/open <n>` — open citation n from the last search in the default browser. */
864
+ export function openSource(ctx, arg) {
865
+ const sources = ctx.lastSources;
866
+ if (sources.length === 0) {
867
+ info("No sources yet. Ask something with web search on, then run /open <n>.");
868
+ return;
869
+ }
870
+ const n = Number.parseInt(arg.trim(), 10);
871
+ if (!Number.isInteger(n) || n < 1 || n > sources.length) {
872
+ errorLine(`Pick a source between 1 and ${sources.length}. Run /sources to see them.`);
873
+ return;
874
+ }
875
+ const target = sources[n - 1];
876
+ // Check before announcing, so a refused URL never prints "Opening…" first.
877
+ const checked = checkUrl(target.url);
878
+ if (!checked.ok) {
879
+ errorLine(checked.reason);
880
+ return;
881
+ }
882
+ // Print the URL as well: on a headless box the spawn quietly no-ops, and this
883
+ // line is then the whole answer rather than a silent failure.
884
+ line();
885
+ line(" " + c.dim(`Opening [${n}] `) + c.value(target.source?.trim() || "source"));
886
+ line(" " + c.dim(checked.url));
887
+ line();
888
+ openUrl(checked.url);
889
+ }
890
+ // ── Fast mode & High Power ────────────────────────────────────────────────────
891
+ // Two turn-shaping toggles that sit alongside mode/model, mirroring the web
892
+ // composer. Fast shortens the pipeline; High Power runs HIPWR's 4-pass
893
+ // refinement (EXPANSION → HARDENING → ARCHITECTURE → FINALIZATION).
894
+ /** Modes HIPWR is compatible with — the same set the web composer allows. */
895
+ const HIPWR_MODES = ["auto", "summary", "reasoning", "research"];
896
+ /** Parse an on/off word. Returns null when it isn't one. */
897
+ function onOff(arg) {
898
+ const raw = arg.trim().toLowerCase();
899
+ if (!raw)
900
+ return null;
901
+ if (["on", "yes", "true", "enable", "enabled"].includes(raw))
902
+ return true;
903
+ if (["off", "no", "false", "disable", "disabled"].includes(raw))
904
+ return false;
905
+ return null;
906
+ }
907
+ /** `/fast` toggles, `/fast on|off` sets. */
908
+ export function setFast(ctx, arg) {
909
+ const raw = arg.trim();
910
+ const next = raw ? onOff(raw) : !ctx.fast;
911
+ if (next === null) {
912
+ errorLine(`Unknown value "${raw}". Use /fast on or /fast off.`);
913
+ return;
914
+ }
915
+ // Standard chat only, matching the web — it hides the toggle entirely for
916
+ // Carrier Chat and Quick Chat. Fast mode swaps the provider for Groq/Llama,
917
+ // which the Carrier persona isn't tuned for. Refuse here rather than letting
918
+ // the server silently downgrade the turn to standard.
919
+ if (next && ctx.chatType === "carrier") {
920
+ errorLine("Fast mode is Standard chat only — Carrier Chat always uses its own models.");
921
+ line(" " + c.dim("Run ") + c.cmd("/switch standard") + c.dim(" first."));
922
+ return;
923
+ }
924
+ ctx.setFast(next);
925
+ info(next
926
+ ? "Fast mode on — Llama via Groq, quicker replies, less refinement."
927
+ : "Fast mode off — standard pipeline depth.");
928
+ }
929
+ /** `/hipwr` toggles, `/hipwr on|off` sets. Warns when the mode won't run it. */
930
+ export function setHighPower(ctx, arg) {
931
+ const raw = arg.trim();
932
+ const next = raw ? onOff(raw) : !ctx.highPower;
933
+ if (next === null) {
934
+ errorLine(`Unknown value "${raw}". Use /hipwr on or /hipwr off.`);
935
+ return;
936
+ }
937
+ ctx.setHighPower(next);
938
+ if (!next) {
939
+ info("High Power off.");
940
+ return;
941
+ }
942
+ line();
943
+ line(" " + c.ok("✓") + " " + c.title("High Power enabled"));
944
+ line();
945
+ line(" " + c.dim("Pipeline ") + c.value("4-pass refinement"));
946
+ line(" " + c.dim("Passes ") + c.dim("expansion → hardening → architecture → finalization"));
947
+ line();
948
+ // Say so up front rather than letting the user wonder why nothing changed:
949
+ // the engine silently declines HIPWR outside these modes.
950
+ if (!HIPWR_MODES.includes(ctx.mode)) {
951
+ line(" " +
952
+ c.warn("!") +
953
+ c.dim(` ${capitalize(ctx.mode)} mode doesn't run High Power. `) +
954
+ c.dim("Switch to ") +
955
+ c.value(HIPWR_MODES.join(", ")) +
956
+ c.dim("."));
957
+ line();
958
+ }
959
+ line(" " + c.dim("Trivial messages skip it regardless — it's for substantial work."));
960
+ line();
961
+ }
962
+ /**
963
+ * Footer chips for the turn-shaping toggles, in the order they're applied.
964
+ *
965
+ * Icons match the web's composer so the same capability reads the same in both
966
+ * places: Zap for fast mode, Flame for High Power (chat-input.tsx).
967
+ */
968
+ /**
969
+ * Footer chips for whatever is switched on, already coloured — SIA gets its own
970
+ * colour rather than the shared yellow, so the footer distinguishes "shapes the
971
+ * answer" (Fast, HIPWR) from "shapes the question" (SIA).
972
+ */
973
+ export function turnShapeLabels(ctx) {
974
+ const out = [];
975
+ if (ctx.fast)
976
+ out.push(c.warn("⚡ Fast"));
977
+ if (ctx.highPower)
978
+ out.push(c.warn("🔥 HIPWR"));
979
+ // ✦ (U+2726), not the ✨ emoji: emoji carry their own colour, so the chip
980
+ // ignored c.magic and rendered yellow — and it is double-width, which the
981
+ // footer's width maths counts as one column.
982
+ // SIA is deliberately NOT shown. Auto is the default and it acts only when
983
+ // the backend judges a prompt ambiguous, so a permanent chip advertises
984
+ // something that usually does nothing — unlike Fast and HIPWR, which change
985
+ // every turn. `/sia status` reports the state when it is actually in question.
986
+ return out;
987
+ }
988
+ /** `/sia` toggles, `/sia on|off` sets. */
989
+ const SIA_BLURB = {
990
+ auto: "Auto — Carrier OS asks only when a prompt is genuinely ambiguous.",
991
+ off: "Off — prompts are sent exactly as typed."
992
+ };
993
+ /** Print the current state. Says plainly when the chat type ignores it. */
994
+ export function showSiaStatus(ctx) {
995
+ line();
996
+ line(" " + c.title("SIA"));
997
+ if (ctx.chatType !== "standard") {
998
+ line(" " + c.dim("Not used in Carrier Chat — it runs its own behaviour layer."));
999
+ line(" " + c.dim("Your Standard setting is remembered and restored on ") + c.cmd("/switch standard"));
1000
+ line();
1001
+ return;
1002
+ }
1003
+ line(" " + c.dim("Mode: ") + c.value(capitalize(ctx.siaMode)));
1004
+ line(" " + c.dim(SIA_BLURB[ctx.siaMode]));
1005
+ line();
1006
+ }
1007
+ /**
1008
+ * `/sia` picks, `/sia auto|off|status` sets or shows.
1009
+ *
1010
+ * There is no "on": the backend already decides whether a prompt needs
1011
+ * clarification (/v1/sia/questions answers `skip` for anything clear enough),
1012
+ * and it has no way to be told "ask anyway". An "on" that behaved exactly like
1013
+ * auto would be a label promising something the API cannot do — so `/sia on` is
1014
+ * accepted as an alias and reported honestly as Auto.
1015
+ */
1016
+ export async function setSia(ctx, arg) {
1017
+ const raw = arg.trim().toLowerCase();
1018
+ if (raw === "status")
1019
+ return showSiaStatus(ctx);
1020
+ if (ctx.chatType !== "standard") {
1021
+ errorLine("SIA is Standard chat only — Carrier Chat runs its own behaviour layer.");
1022
+ line(" " + c.dim("Run ") + c.cmd("/switch standard") + c.dim(" first."));
1023
+ return;
1024
+ }
1025
+ let next = null;
1026
+ if (!raw) {
1027
+ const picked = await pickFromList({
1028
+ title: "SIA",
1029
+ description: "Clarifying questions before an ambiguous prompt is sent.",
1030
+ choices: [
1031
+ { value: "auto", label: "Auto", description: SIA_BLURB.auto, current: ctx.siaMode === "auto" },
1032
+ { value: "off", label: "Off", description: SIA_BLURB.off, current: ctx.siaMode === "off" }
1033
+ ],
1034
+ initial: ctx.siaMode === "off" ? 1 : 0,
1035
+ stacked: true
1036
+ });
1037
+ if (picked === null)
1038
+ return; // Esc — leave the setting alone
1039
+ next = picked;
1040
+ }
1041
+ else if (raw === "auto" || raw === "on") {
1042
+ next = "auto";
1043
+ }
1044
+ else if (raw === "off") {
1045
+ next = "off";
1046
+ }
1047
+ if (next === null) {
1048
+ errorLine(`Unknown value "${raw}". Use /sia auto, /sia off, or /sia status.`);
1049
+ return;
1050
+ }
1051
+ ctx.setSiaMode(next);
1052
+ // "on" is an accepted alias, so say which state it actually landed in.
1053
+ info(`SIA ${capitalize(next)} — ${SIA_BLURB[next].replace(/^\w+ — /, "")}`);
1054
+ }
222
1055
  // ── Carrier modes (behavior) ──────────────────────────────────────────────────
223
1056
  export async function showModes(ctx, client) {
224
1057
  try {
@@ -243,21 +1076,88 @@ export async function setMode(ctx, client, arg) {
243
1076
  await pickMode(ctx, client);
244
1077
  return;
245
1078
  }
1079
+ if (!ctx.modeIsSelectable) {
1080
+ info("Carrier Chat always uses the General mode. Switch to Standard chat to pick another.");
1081
+ return;
1082
+ }
246
1083
  try {
247
1084
  const modes = await loadModes(client);
248
- if (!modes.some((m) => m.id === id)) {
1085
+ // "auto" is a routing option rather than a mode the API lists, so accept it
1086
+ // explicitly — it's the Standard-chat default and must stay selectable.
1087
+ if (id !== "auto" && !modes.some((m) => m.id === id)) {
249
1088
  errorLine(`Unknown mode "${id}". Type /modes to see the options.`);
250
1089
  return;
251
1090
  }
252
1091
  ctx.config.set("mode", id);
253
1092
  ctx.setSessionMode(id); // reflect immediately in the shell (over the session default)
254
- const name = modes.find((m) => m.id === id)?.name ?? capitalize(id);
1093
+ const name = id === "auto" ? "Auto" : (modes.find((m) => m.id === id)?.name ?? capitalize(id));
255
1094
  info(`Mode changed to ${name} (applies to your next message).`);
256
1095
  }
257
1096
  catch (err) {
258
1097
  reportError(err);
259
1098
  }
260
1099
  }
1100
+ /**
1101
+ * Chat entry for the interactive shell. If the message begins with (or quotes) a
1102
+ * local file path, upload + attach it silently and strip the path — the model
1103
+ * only ever sees the cleaned prompt + file_ids, never a Windows path. Otherwise
1104
+ * it's a normal chat turn. Thin client: upload/attach only, no parsing.
1105
+ */
1106
+ export async function chatInputWithFiles(ctx, client, input, footer, signal) {
1107
+ const { files, prompt, rejected } = detectLocalFiles(input);
1108
+ for (const r of rejected) {
1109
+ line(" " + c.warn("!") + " " + c.dim(`Not attached — outside this project: ${r}`));
1110
+ }
1111
+ if (files.length === 0) {
1112
+ await chatTurn(ctx, client, input, { footer, signal });
1113
+ return;
1114
+ }
1115
+ // Progressive, Claude-Code-style flow (in the transcript, no raw logs).
1116
+ line();
1117
+ line(c.dim(` Detected local file${files.length > 1 ? "s" : ""}`));
1118
+ line();
1119
+ for (const f of files) {
1120
+ const name = path.basename(f);
1121
+ let size = 0;
1122
+ try {
1123
+ size = fs.statSync(f).size;
1124
+ }
1125
+ catch {
1126
+ /* shown without size */
1127
+ }
1128
+ line(" " + c.value(name) + c.dim(` ${fileTypeLabel(name)} • ${formatSize(size)}`));
1129
+ }
1130
+ line();
1131
+ let anyAttached = false;
1132
+ for (const f of files) {
1133
+ try {
1134
+ const r = await uploadAndAttach(ctx, client, f, {
1135
+ onUploading: () => line(c.dim(" Uploading…")),
1136
+ onUploaded: () => success(" Uploaded"),
1137
+ onProcessing: () => line(c.dim(" Preparing document…"))
1138
+ });
1139
+ anyAttached = true;
1140
+ if (r.wasAttached)
1141
+ success(` ${r.filename} already attached`);
1142
+ else
1143
+ success(` Attached ${r.filename}`);
1144
+ }
1145
+ catch (err) {
1146
+ errorLine(" " + (err instanceof UploadError ? err.message : err.message));
1147
+ }
1148
+ }
1149
+ line();
1150
+ if (!anyAttached)
1151
+ return; // nothing usable was attached — don't send a bare prompt
1152
+ if (!prompt) {
1153
+ // File(s) attached but no question — NEVER auto-send. Just tell them it's
1154
+ // ready; the footer shows what's attached and they can type when ready.
1155
+ line(" " + c.dim("Ready. Ask anything about it."));
1156
+ line();
1157
+ return;
1158
+ }
1159
+ await chatTurn(ctx, client, prompt, { footer, signal });
1160
+ }
261
1161
  /** Arrow-key picker for the Carrier mode (↑/↓ + Enter; Esc/Ctrl+C cancels). */
262
1162
  export async function pickMode(ctx, client) {
263
1163
  let modes;
@@ -268,23 +1168,39 @@ export async function pickMode(ctx, client) {
268
1168
  reportError(err);
269
1169
  return;
270
1170
  }
1171
+ // Carrier chat only ever uses the General mode; the other modes (Reasoning,
1172
+ // Code, Research, …) apply to Standard chat, which ALSO gets an "Auto" option
1173
+ // that lets Carrier pick the best mode from the message intent.
1174
+ const AUTO = {
1175
+ id: "auto",
1176
+ name: "Auto",
1177
+ description: "Let Carrier pick the best mode from your message intent."
1178
+ };
1179
+ const visible = ctx.modeIsSelectable ? [AUTO, ...modes] : modes.filter((m) => m.id === "general");
271
1180
  const chosen = await pickFromList({
272
- title: "Select a Carrier mode",
273
- description: "Changes how Carrier responds. Applies to your next message.",
274
- initial: Math.max(0, modes.findIndex((m) => m.id === ctx.mode)),
275
- choices: modes.map((m) => ({
1181
+ title: ctx.chatType === "carrier" ? "Carrier mode" : "Select a mode",
1182
+ description: ctx.chatType === "carrier"
1183
+ ? "Carrier chat uses the General mode. Switch to Standard chat (/switch) for other modes."
1184
+ : "Changes how Carrier responds. Applies to your next message.",
1185
+ initial: Math.max(0, visible.findIndex((m) => m.id === ctx.mode)),
1186
+ choices: visible.map((m) => ({
276
1187
  value: m.id,
277
- label: capitalize(m.name),
1188
+ label: modeName(m),
278
1189
  description: m.description,
279
1190
  current: m.id === ctx.mode
280
1191
  }))
281
1192
  });
282
1193
  if (chosen == null)
283
1194
  return; // Esc / Ctrl+C — leave the mode unchanged
1195
+ // Carrier Chat has exactly one entry, so a "selection" there changes nothing —
1196
+ // and must NOT be written, or picking General in Carrier would silently become
1197
+ // the Standard-chat mode the next time you switch.
1198
+ if (!ctx.modeIsSelectable)
1199
+ return;
284
1200
  ctx.config.set("mode", chosen);
285
1201
  ctx.setSessionMode(chosen); // reflect immediately in the shell (over the session default)
286
- const name = modes.find((m) => m.id === chosen)?.name ?? capitalize(chosen);
287
- info(`Mode changed to ${name} (applies to your next message).`);
1202
+ const picked = modes.find((m) => m.id === chosen);
1203
+ info(`Mode changed to ${picked ? modeName(picked) : capitalize(chosen)} (applies to your next message).`);
288
1204
  }
289
1205
  // ── Provider models (the LLM behind a turn) ───────────────────────────────────
290
1206
  export async function showModels(ctx, client) {
@@ -297,8 +1213,10 @@ export async function showModels(ctx, client) {
297
1213
  line(` ${autoOn ? chalk.green("►") : " "} ${(autoOn ? chalk.bold(AUTO_LABEL) : AUTO_LABEL).padEnd(28)}`);
298
1214
  for (const m of models) {
299
1215
  const on = m.id === active;
300
- const label = on ? chalk.bold(m.label) : m.label;
301
- line(` ${on ? chalk.green("►") : " "} ${label.padEnd(28)} ${chalk.dim(m.id)}`);
1216
+ const down = m.available === false;
1217
+ const label = on ? chalk.bold(m.label) : down ? chalk.dim(m.label) : m.label;
1218
+ const note = down ? chalk.dim(`${m.id} — provider out of credit`) : chalk.dim(m.id);
1219
+ line(` ${on ? chalk.green("►") : " "} ${label.padEnd(28)} ${note}`);
302
1220
  }
303
1221
  line();
304
1222
  }
@@ -324,6 +1242,12 @@ export async function setModel(ctx, client, arg) {
324
1242
  errorLine(`Unknown model "${id}". Type /models to see the options.`);
325
1243
  return;
326
1244
  }
1245
+ if (currentModelId(ctx) === match.id) {
1246
+ // Picking what is already selected changed nothing — saying "changed"
1247
+ // makes the user doubt what state they are in.
1248
+ info(`Already using ${match.label}.`);
1249
+ return;
1250
+ }
327
1251
  ctx.config.set("model", match.id);
328
1252
  info(`Model changed to ${match.label} (applies to your next message).`);
329
1253
  }
@@ -349,7 +1273,14 @@ export async function pickModel(ctx, client) {
349
1273
  description: "Use the current mode's default model",
350
1274
  current: current === ""
351
1275
  },
352
- ...models.map((m) => ({ value: m.id, label: m.label, description: m.id, current: m.id === current }))
1276
+ // Unavailable models stay selectable — the API substitutes a working one and
1277
+ // tells you which answered — but they're labelled so the choice is informed.
1278
+ ...models.map((m) => ({
1279
+ value: m.id,
1280
+ label: m.available === false ? `${m.label} (unavailable)` : m.label,
1281
+ description: m.available === false ? `${m.id} — provider out of credit` : m.id,
1282
+ current: m.id === current
1283
+ }))
353
1284
  ];
354
1285
  const chosen = await pickFromList({
355
1286
  title: "Select a model",
@@ -363,3 +1294,43 @@ export async function pickModel(ctx, client) {
363
1294
  const label = chosen ? (models.find((m) => m.id === chosen)?.label ?? chosen) : AUTO_LABEL;
364
1295
  info(`Model changed to ${label} (applies to your next message).`);
365
1296
  }
1297
+ // ── Live memory markers ──────────────────────────────────────────────────────
1298
+ // The engine writes snapshots/restructures AFTER a turn returns (measured at
1299
+ // ~6s), so the chat response cannot carry them. The CLI keeps no local
1300
+ // transcript — thin client, backend owns conversation state — so the only way
1301
+ // to notice one is to ask. One lightweight fetch per turn, off the render path.
1302
+ /** Markers already shown, per session, for this process. */
1303
+ const seenMarkers = new Map();
1304
+ /** How long to wait for the engine to finish writing before looking. */
1305
+ const MARKER_SETTLE_MS = 1500;
1306
+ /**
1307
+ * Show any memory markers created by the turn that just finished.
1308
+ *
1309
+ * The first sighting of a session only records a baseline — resuming a
1310
+ * conversation with twelve existing markers must not dump all twelve into the
1311
+ * transcript. Everything is best-effort: a failure here must never touch the
1312
+ * answer the user already has.
1313
+ */
1314
+ async function showNewMemoryMarkers(ctx, client, sessionId) {
1315
+ try {
1316
+ await sleep(MARKER_SETTLE_MS);
1317
+ const { messages } = await client.sessionMessages(sessionId);
1318
+ const markers = messages.filter(isMemoryMarker);
1319
+ // Numbering must match /history — position among ALL markers, 1-based — so
1320
+ // `/memory <n>` resolves the same way from either place.
1321
+ ctx.config.set("memoryArtifactIds", markers.map((m) => m.artifact_id ?? ""));
1322
+ const seen = seenMarkers.get(sessionId);
1323
+ seenMarkers.set(sessionId, markers.length);
1324
+ if (seen === undefined)
1325
+ return; // baseline only — nothing is "new" yet
1326
+ for (let i = seen; i < markers.length; i++) {
1327
+ line();
1328
+ line(memoryMarkerLine({ ...markers[i], index: i + 1 }));
1329
+ }
1330
+ if (markers.length > seen)
1331
+ line();
1332
+ }
1333
+ catch {
1334
+ /* the turn already succeeded — never surface a failure from this */
1335
+ }
1336
+ }