@carrieros/cli-staging 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +6 -2
  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 +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +26 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +78 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +160 -0
  27. package/dist/commands/update.js +285 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +229 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +364 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +132 -0
  36. package/dist/services/api.js +441 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/auto-update.js +221 -0
  39. package/dist/services/chat-stream.js +168 -0
  40. package/dist/services/checkpoints.js +278 -0
  41. package/dist/services/client-tools.js +356 -0
  42. package/dist/services/code-intel.js +243 -0
  43. package/dist/services/code-symbols.js +94 -0
  44. package/dist/services/coding-workflow.js +554 -0
  45. package/dist/services/command-coordinator.js +273 -0
  46. package/dist/services/command-policy.js +434 -0
  47. package/dist/services/config.js +384 -0
  48. package/dist/services/container-runner.js +254 -0
  49. package/dist/services/container-supervisor.js +38 -0
  50. package/dist/services/context.js +416 -0
  51. package/dist/services/device-auth.js +288 -0
  52. package/dist/services/diff.js +196 -0
  53. package/dist/services/env-policy.js +108 -0
  54. package/dist/services/execution-platform.js +30 -0
  55. package/dist/services/file-detect.js +104 -0
  56. package/dist/services/file-resolver.js +199 -0
  57. package/dist/services/file-upload.js +126 -0
  58. package/dist/services/folder-key.js +22 -0
  59. package/dist/services/git-tools.js +429 -0
  60. package/dist/services/glob-match.js +164 -0
  61. package/dist/services/helper-bin.js +85 -0
  62. package/dist/services/ignore-rules.js +189 -0
  63. package/dist/services/instruction-resolver.js +54 -0
  64. package/dist/services/job-helper.js +328 -0
  65. package/dist/services/local-files.js +639 -0
  66. package/dist/services/local-tools.js +937 -0
  67. package/dist/services/login-flow.js +156 -0
  68. package/dist/services/meta.js +42 -0
  69. package/dist/services/mutation-coordinator.js +327 -0
  70. package/dist/services/mutation-groups.js +309 -0
  71. package/dist/services/mutation-recovery.js +159 -0
  72. package/dist/services/mutations.js +679 -0
  73. package/dist/services/open-url.js +68 -0
  74. package/dist/services/output.js +62 -0
  75. package/dist/services/packaged-update.js +403 -0
  76. package/dist/services/packaged.js +39 -0
  77. package/dist/services/permission-mode.js +78 -0
  78. package/dist/services/process-runner.js +412 -0
  79. package/dist/services/project-context.js +298 -0
  80. package/dist/services/redaction.js +201 -0
  81. package/dist/services/result-reconciliation.js +49 -0
  82. package/dist/services/secure-store.js +217 -0
  83. package/dist/services/session-resolver.js +115 -0
  84. package/dist/services/sia.js +51 -0
  85. package/dist/services/spinner.js +40 -0
  86. package/dist/services/supported-runtime.js +59 -0
  87. package/dist/services/task-context.js +212 -0
  88. package/dist/services/task-snapshot.js +38 -0
  89. package/dist/services/tool-result-outbox.js +195 -0
  90. package/dist/services/update.js +730 -0
  91. package/dist/services/workspace-registry.js +310 -0
  92. package/dist/services/workspace.js +580 -0
  93. package/dist/shell/shell-chat.js +1622 -0
  94. package/dist/shell/shell-commands.js +411 -0
  95. package/dist/shell/shell-prompt.js +110 -0
  96. package/dist/shell/shell-renderer.js +51 -0
  97. package/dist/shell/shell-router.js +37 -0
  98. package/dist/shell/shell.js +414 -0
  99. package/dist/shell/task-context-view.js +40 -0
  100. package/dist/staging.js +5 -0
  101. package/dist/types/index.js +6 -0
  102. package/dist/ui/agent-cards.js +111 -0
  103. package/dist/ui/agent-presentation.js +131 -0
  104. package/dist/ui/approval.js +111 -0
  105. package/dist/ui/banner.js +56 -0
  106. package/dist/ui/btw-overlay.js +230 -0
  107. package/dist/ui/change-review.js +334 -0
  108. package/dist/ui/chat-renderer.js +463 -0
  109. package/dist/ui/code-block.js +52 -0
  110. package/dist/ui/color-picker.js +100 -0
  111. package/dist/ui/colors.js +55 -0
  112. package/dist/ui/command-details.js +11 -0
  113. package/dist/ui/command-filter.js +92 -0
  114. package/dist/ui/command-item.js +6 -0
  115. package/dist/ui/command-palette.js +383 -0
  116. package/dist/ui/command-registry.js +128 -0
  117. package/dist/ui/command-renderer.js +55 -0
  118. package/dist/ui/command-review.js +187 -0
  119. package/dist/ui/composer-layout.js +74 -0
  120. package/dist/ui/conversation.js +450 -0
  121. package/dist/ui/interrupt.js +35 -0
  122. package/dist/ui/live.js +141 -0
  123. package/dist/ui/logo.js +58 -0
  124. package/dist/ui/markdown.js +205 -0
  125. package/dist/ui/message.js +21 -0
  126. package/dist/ui/screen-prompt.js +181 -0
  127. package/dist/ui/screen.js +297 -0
  128. package/dist/ui/select.js +284 -0
  129. package/dist/ui/sia-qa.js +213 -0
  130. package/dist/ui/spinner.js +23 -0
  131. package/dist/ui/sticky-stream.js +64 -0
  132. package/dist/ui/task-context-card.js +99 -0
  133. package/dist/ui/text-prompt.js +74 -0
  134. package/dist/ui/theme.js +80 -0
  135. package/dist/ui/trust.js +88 -0
  136. package/dist/ui/ui.js +101 -0
  137. package/package.json +33 -4
@@ -0,0 +1,463 @@
1
+ import { line } from "../services/output.js";
2
+ import { sleep } from "../services/spinner.js";
3
+ import { c } from "./colors.js";
4
+ import { contentWidth } from "./composer-layout.js";
5
+ import { renderMarkdown } from "./markdown.js";
6
+ import { renderUserMessage } from "./message.js";
7
+ import { thinking } from "./spinner.js";
8
+ import { formatCredits } from "./ui.js";
9
+ /**
10
+ * Presentation layer for the conversation, styled after Claude Code:
11
+ * ❯ <your message> (full-width bar — see message.ts)
12
+ * ● <assistant reply> (dot marker, continuation indented)
13
+ * ✳ Brewed for 3s (dim completion footer)
14
+ * The chat logic only emits events (renderUserMessage / startThinking /
15
+ * streamAssistant / renderComplete / renderError), keeping rendering separate.
16
+ */
17
+ export { renderUserMessage };
18
+ // Thinking phrases that cycle while Carrier is responding — the same set the web
19
+ // chat animates through. Rotated so a different one leads each turn.
20
+ const THINKING_PHRASES = [
21
+ "Thinking",
22
+ "Processing",
23
+ "Analyzing",
24
+ "Computing",
25
+ "Reasoning",
26
+ "Synthesizing",
27
+ "Exploring",
28
+ "Connecting dots",
29
+ "Deep dive",
30
+ "Unraveling",
31
+ "Decoding",
32
+ "Pattern matching",
33
+ "Quantum thinking",
34
+ "Neural pathways",
35
+ "Emerging insights"
36
+ ];
37
+ let phraseIndex = 0;
38
+ let tipIndex = 0;
39
+ /**
40
+ * Completion footers, rotated like the thinking phrases so a long session
41
+ * doesn't read as the same line stamped over and over.
42
+ *
43
+ * Each entry carries its own preposition — "Baked FOR 3s" but "Generated IN
44
+ * 3s" — because a shared connector makes half the list ungrammatical. "in"
45
+ * suits verbs about producing a result, "for" verbs about time spent.
46
+ */
47
+ const COMPLETION_PHRASES = [
48
+ "Generated in",
49
+ "Brewed for",
50
+ "Baked for",
51
+ "Churned for",
52
+ "Simmered for",
53
+ "Percolated for",
54
+ "Distilled in",
55
+ "Composed in",
56
+ "Crafted in",
57
+ "Forged in",
58
+ "Assembled in",
59
+ "Synthesized in"
60
+ ];
61
+ let completionIndex = 0;
62
+ /** Completion footer text, Claude-style: "Brewed for 1.2s". Advances the
63
+ * rotation, so call it once per finished turn. */
64
+ function completionLabel(seconds, spend) {
65
+ const phrase = COMPLETION_PHRASES[completionIndex % COMPLETION_PHRASES.length];
66
+ completionIndex++;
67
+ return `${phrase} ${Math.max(0.1, seconds).toFixed(1)}s${spendSuffix(spend)}`;
68
+ }
69
+ /** Format a number with thousands separators, trimming pointless decimals. */
70
+ /**
71
+ * " · 412.60 credits left"
72
+ *
73
+ * Balance only. Tokens and dollar cost are still returned by the API (and used
74
+ * for request logging), but three numbers on a completion line is a bill, not a
75
+ * status — the one that answers "can I keep going?" is what's left.
76
+ *
77
+ * Omitted entirely when the API didn't send it, rather than shown as 0: an
78
+ * older API build has no balance field, and a wrong number is worse than none
79
+ * when it's money.
80
+ */
81
+ export function spendSuffix(spend) {
82
+ // An unlimited account's balance is a running total of real spend, not a
83
+ // limit — so "3,600 credits overdrawn" is true and alarming and answers the
84
+ // wrong question. What such an account wants to know is what THIS session
85
+ // cost. The balance itself is unchanged and still shown by /usage.
86
+ if (spend?.unlimited === true) {
87
+ return typeof spend.sessionSpent === "number"
88
+ ? ` · Unlimited · session ${formatCredits(spend.sessionSpent)} credits`
89
+ : " · Unlimited";
90
+ }
91
+ const credits = spend?.creditsRemaining;
92
+ if (typeof credits !== "number")
93
+ return "";
94
+ // A negative balance is an overdraft, not "-556 left" — say what it is.
95
+ return credits < 0
96
+ ? ` · ${formatCredits(Math.abs(credits))} credits overdrawn`
97
+ : ` · ${formatCredits(credits)} credits left`;
98
+ }
99
+ // Rotating tips shown beneath the spinner while Carrier is responding — a chance
100
+ // to surface a handy shortcut, the way Claude Code does.
101
+ const TIPS = [
102
+ "Type / to browse commands.",
103
+ "Switch the model any time with /model.",
104
+ "Use /mode to change how Carrier responds.",
105
+ "Press ↑ to reuse a previous message.",
106
+ "Run /clear to start a fresh conversation.",
107
+ "Give Carrier context by attaching files with /upload.",
108
+ "Check your usage and limits with /usage.",
109
+ "Tab completes the highlighted command."
110
+ ];
111
+ /** Start the thinking spinner: a phrase that cycles through THINKING_PHRASES
112
+ * every ~1.5s, with a rotating tip on the line beneath. Returns a stop handle. */
113
+ export function startThinking() {
114
+ const tip = TIPS[tipIndex % TIPS.length];
115
+ tipIndex++;
116
+ let idx = phraseIndex % THINKING_PHRASES.length;
117
+ phraseIndex++;
118
+ const label = (i) => c.dim(`${THINKING_PHRASES[i]}…`) + "\n " + c.dim(`└ Tip: ${tip}`);
119
+ const spinner = thinking(label(idx));
120
+ const timer = setInterval(() => {
121
+ idx = (idx + 1) % THINKING_PHRASES.length;
122
+ spinner.setText(label(idx));
123
+ }, 1500);
124
+ timer.unref?.(); // don't keep the process alive on the cycling timer
125
+ return {
126
+ stop: () => {
127
+ clearInterval(timer);
128
+ spinner.stop();
129
+ }
130
+ };
131
+ }
132
+ // ── Sticky-composer variants: same visuals, but rendered around a pinned input
133
+ // bar so the composer never disappears while a turn is processing ──────────
134
+ const FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
135
+ /** Cycle the thinking spinner + tip into the live region above the pinned bar.
136
+ * Returns a stop handle (the caller clears the region afterwards). */
137
+ export function startThinkingLive(live) {
138
+ const tip = TIPS[tipIndex % TIPS.length];
139
+ tipIndex++;
140
+ let idx = phraseIndex % THINKING_PHRASES.length;
141
+ phraseIndex++;
142
+ let frame = 0;
143
+ let ticks = 0;
144
+ const paint = () => live.setStatus([
145
+ " " + c.brand(FRAMES[frame % FRAMES.length]) + " " + c.dim(`${THINKING_PHRASES[idx]}…`),
146
+ " " + c.dim(`└ Tip: ${tip}`)
147
+ ]);
148
+ paint();
149
+ const timer = setInterval(() => {
150
+ frame++;
151
+ ticks++;
152
+ if (ticks % 18 === 0)
153
+ idx = (idx + 1) % THINKING_PHRASES.length; // advance phrase ~1.5s
154
+ paint();
155
+ }, 80);
156
+ timer.unref?.();
157
+ return { stop: () => clearInterval(timer) };
158
+ }
159
+ // Word-streaming reveal. The API returns the full answer at once (no backend
160
+ // SSE), so we surface it progressively — word by word at a natural cadence — so
161
+ // it reads like Claude typing the response in, rather than one instant block.
162
+ const STREAM_DELAY = 22; // ms between words
163
+ // SGR colour runs plus OSC strings (\x1b] … BEL / ST). OSC carries a payload —
164
+ // a hyperlink's URL, a title — that occupies no columns, so a regex that only
165
+ // knows SGR silently over-counts the width of any line containing one.
166
+ const ANSI = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;]*m/g;
167
+ const stripAnsi = (s) => s.replace(ANSI, "");
168
+ /** Styled prefix of `s` showing its first `n` visible characters (ANSI kept). */
169
+ function ansiSlice(s, n) {
170
+ let out = "";
171
+ let vis = 0;
172
+ let i = 0;
173
+ while (i < s.length && vis < n) {
174
+ const m = s[i] === "\x1b" ? /^\x1b\[[0-9;]*m/.exec(s.slice(i)) : null;
175
+ if (m) {
176
+ out += m[0];
177
+ i += m[0].length;
178
+ }
179
+ else {
180
+ out += s[i];
181
+ vis++;
182
+ i++;
183
+ }
184
+ }
185
+ while (i < s.length && s[i] === "\x1b") {
186
+ const m = /^\x1b\[[0-9;]*m/.exec(s.slice(i));
187
+ if (!m)
188
+ break;
189
+ out += m[0];
190
+ i += m[0].length;
191
+ }
192
+ return out + "\x1b[0m";
193
+ }
194
+ /** Cumulative visible-char counts at each word boundary of a styled line. */
195
+ function wordStops(styled) {
196
+ const visible = stripAnsi(styled);
197
+ const stops = [];
198
+ const re = /\S+\s*/g;
199
+ let m;
200
+ while ((m = re.exec(visible)) !== null)
201
+ stops.push(m.index + m[0].length);
202
+ if (!stops.length || stops[stops.length - 1] < visible.length)
203
+ stops.push(visible.length);
204
+ return stops;
205
+ }
206
+ const CURSOR = "▋"; // streaming caret shown at the end of the in-progress line
207
+ /** Claude-style lead-in for an assistant reply: a soft theme-light dot before the
208
+ * first line, with continuation lines indented to align under the text. */
209
+ const LEAD = (i) => (i === 0 ? c.accentLight("●") + " " : " ");
210
+ /** Stream the answer above a PINNED input bar via a scroll region (flicker-free):
211
+ * led by a neutral dot, each line revealed word-by-word on the bottom content
212
+ * row (with the streaming cursor) before scrolling up to the next. */
213
+ export async function streamAssistantSticky(sticky, text) {
214
+ const md = renderMarkdown(text);
215
+ while (md.length && md[0].trim() === "")
216
+ md.shift();
217
+ while (md.length && md[md.length - 1].trim() === "")
218
+ md.pop();
219
+ for (let i = 0; i < md.length; i++) {
220
+ sticky.scroll();
221
+ const raw = md[i];
222
+ const full = MARGIN + LEAD(i) + raw;
223
+ if (raw.trim()) {
224
+ for (const n of wordStops(full)) {
225
+ sticky.setLine(ansiSlice(full, n) + c.dim(CURSOR));
226
+ await sleep(STREAM_DELAY);
227
+ }
228
+ }
229
+ sticky.setLine(full); // final line, cursor gone
230
+ }
231
+ sticky.scroll(); // trailing blank
232
+ }
233
+ /** Completion footer on the scroll region: ● Brewed for 1.2s */
234
+ export function renderCompleteSticky(sticky, seconds) {
235
+ sticky.scroll();
236
+ sticky.setLine(MARGIN + c.dim(`● ${completionLabel(seconds)}`));
237
+ sticky.scroll();
238
+ }
239
+ /** Stream the assistant's answer above the pinned bar, led by a neutral dot
240
+ * (Claude-style), word by word with a streaming cursor. Each in-progress line
241
+ * lives in the transient status region (so the cursor can trail it) and is
242
+ * promoted to permanent once fully revealed. */
243
+ export async function streamAssistantLive(live, text) {
244
+ const md = renderMarkdown(text);
245
+ while (md.length && md[0].trim() === "")
246
+ md.shift();
247
+ while (md.length && md[md.length - 1].trim() === "")
248
+ md.pop();
249
+ for (let i = 0; i < md.length; i++) {
250
+ // No name header — the reply is led by a neutral dot (Claude-style).
251
+ const full = MARGIN + LEAD(i) + md[i];
252
+ if (md[i].trim()) {
253
+ for (const n of wordStops(full)) {
254
+ live.setStatus([ansiSlice(full, n) + c.dim(CURSOR)]);
255
+ await sleep(STREAM_DELAY);
256
+ }
257
+ }
258
+ live.setStatus([full]); // final line, cursor gone
259
+ live.commitStatus(); // lock the finished line in place (no flicker)
260
+ }
261
+ live.commit([""]); // single trailing blank
262
+ }
263
+ /** Dim completion footer committed above the pinned bar: ● Brewed for 1.2s */
264
+ export function renderCompleteLive(live, seconds, spend) {
265
+ live.commit([MARGIN + c.dim(`● ${completionLabel(seconds, spend)}`), ""]);
266
+ }
267
+ /** Error block committed above the pinned bar. */
268
+ export function renderErrorLive(live, title, detail, hintCmd) {
269
+ const out = ["", ` ${c.err("×")} ${c.err.bold(title)}`, "", " " + c.value(detail)];
270
+ if (hintCmd)
271
+ out.push("", " " + c.dim("Run ") + c.cmd(hintCmd) + c.dim(" to continue."));
272
+ out.push("");
273
+ live.commit(out);
274
+ }
275
+ /** Stream the assistant's answer led by a neutral dot (Claude-style), word by
276
+ * word with a streaming cursor in a TTY (in-place line rewrite); plain when piped. */
277
+ export async function streamAssistant(text) {
278
+ const md = renderMarkdown(text);
279
+ while (md.length && md[0].trim() === "")
280
+ md.shift();
281
+ while (md.length && md[md.length - 1].trim() === "")
282
+ md.pop();
283
+ const tty = process.stdout.isTTY && process.env.TERM !== "dumb";
284
+ if (tty)
285
+ process.stdout.write("\x1b[?25l"); // hide the caret; ▋ is the cursor
286
+ for (let i = 0; i < md.length; i++) {
287
+ const full = MARGIN + LEAD(i) + md[i];
288
+ if (tty && md[i].trim()) {
289
+ for (const n of wordStops(full)) {
290
+ process.stdout.write("\r\x1b[K" + ansiSlice(full, n) + c.dim(CURSOR));
291
+ await sleep(STREAM_DELAY);
292
+ }
293
+ process.stdout.write("\r\x1b[K" + full + "\n");
294
+ }
295
+ else {
296
+ line(full);
297
+ }
298
+ }
299
+ if (tty)
300
+ process.stdout.write("\x1b[?25h");
301
+ line(); // single trailing blank
302
+ }
303
+ /** Dim completion footer: ● Brewed for 1.2s */
304
+ export function renderComplete(seconds, spend) {
305
+ line(MARGIN + c.dim(`● ${completionLabel(seconds, spend)}`));
306
+ line();
307
+ }
308
+ // ── Web-search citations ─────────────────────────────────────────────────────
309
+ // The web app renders these as hoverable chips. A terminal can't hover, so the
310
+ // list is numbered and the numbers are addressable: /open 2, /sources.
311
+ //
312
+ // Publisher leads, not the URL. Raw article URLs are long, visually noisy, and
313
+ // (for Google News results) not even human-readable — so the domain is shown
314
+ // bare and the full URL is attached as a terminal hyperlink where that works.
315
+ /** Citations shown inline under an answer before collapsing into a count. */
316
+ const INLINE_SOURCES = 4;
317
+ /** Indent under the "[n] " marker that title/domain lines sit at. */
318
+ const CITE_INDENT = " ";
319
+ /**
320
+ * Clip to the composer's content column.
321
+ *
322
+ * The screen engine writes one transcript line per terminal row and does no
323
+ * wrap accounting, so a line wider than the column steals a second row and
324
+ * shifts everything below it — which is how a URL tail ends up floating above
325
+ * the prompt. Titles and URLs are the only unbounded strings in the transcript,
326
+ * so they get clipped here. Plain text in, styled after, so this never has to
327
+ * count escape sequences.
328
+ */
329
+ function fit(text, indent = CITE_INDENT.length) {
330
+ const max = Math.max(8, contentWidth() - indent);
331
+ return text.length <= max ? text : text.slice(0, max - 1) + "…";
332
+ }
333
+ /** Bare hostname for a citation — "bbc.com", never "www.bbc.com/path?utm=…". */
334
+ export function sourceDomain(s) {
335
+ try {
336
+ return new URL(s.url).hostname.replace(/^www\./, "");
337
+ }
338
+ catch {
339
+ return s.url;
340
+ }
341
+ }
342
+ /** Publisher name for a citation — the API's `source`, else the domain. */
343
+ export function sourceLabel(s) {
344
+ return s.source?.trim() || sourceDomain(s);
345
+ }
346
+ /**
347
+ * One citation: publisher, then title, then domain — publisher first because
348
+ * that is what tells you whether to trust the line. `tail` carries the domain
349
+ * inline; the full list overrides it with the complete URL.
350
+ */
351
+ function citation(s, i, tail) {
352
+ const marker = `[${i + 1}] `;
353
+ const head = `${MARGIN}${c.dim(`[${i + 1}]`)} ${c.value(fit(sourceLabel(s), marker.length))}`;
354
+ const tailLine = `${MARGIN}${CITE_INDENT}${c.dim(fit(tail))}`;
355
+ const title = s.title?.trim();
356
+ if (!title)
357
+ return [head, tailLine];
358
+ return [head, `${MARGIN}${CITE_INDENT}${c.dim(fit(title))}`, tailLine];
359
+ }
360
+ /** The compact block printed under an answer: first few, then a pointer. */
361
+ function sourceLines(sources) {
362
+ if (sources.length === 0)
363
+ return [];
364
+ const shown = sources.slice(0, INLINE_SOURCES);
365
+ const out = ["", MARGIN + c.dim(`Sources · ${sources.length}`), ""];
366
+ shown.forEach((s, i) => {
367
+ out.push(...citation(s, i, sourceDomain(s)));
368
+ out.push(""); // one blank between entries so the block scans as a list
369
+ });
370
+ const hidden = sources.length - shown.length;
371
+ if (hidden > 0)
372
+ out.push(`${MARGIN}${c.dim(`+ ${hidden} more · `)}${c.cmd("/sources")}`, "");
373
+ return out;
374
+ }
375
+ /** Numbered citation list printed under the answer. No-op without sources. */
376
+ export function renderSources(sources) {
377
+ for (const l of sourceLines(sources))
378
+ line(l);
379
+ }
380
+ /** Citation list committed above the pinned composer bar. */
381
+ export function renderSourcesLive(live, sources) {
382
+ const out = sourceLines(sources);
383
+ if (out.length)
384
+ live.commit(out);
385
+ }
386
+ /** The full list, every entry — `/sources`. Printed outside a turn. */
387
+ export function renderAllSources(sources, agoLabel) {
388
+ line();
389
+ line(MARGIN + c.title(`Sources · ${sources.length}`) + (agoLabel ? c.dim(` ${agoLabel}`) : ""));
390
+ line();
391
+ // The full list is where someone goes to copy a link, so the tail is the
392
+ // complete URL here even though the compact block deliberately hides it.
393
+ sources.forEach((s, i) => {
394
+ for (const l of citation(s, i, s.url))
395
+ line(l);
396
+ line();
397
+ });
398
+ line(MARGIN + c.dim("Open one with ") + c.cmd("/open <n>"));
399
+ line();
400
+ }
401
+ // ── Memory-engine markers ────────────────────────────────────────────────────
402
+ // The engine compresses a growing conversation on its own. The web draws two
403
+ // deliberately different marks and this mirrors that weighting: a snapshot is
404
+ // routine short-term housekeeping (muted, hairline rules), a restructure is a
405
+ // long-term rebuild that COSTS the account money (themed, heavier rule). Both
406
+ // carry the number you pass to `/memory <n>`.
407
+ function centred(inner, rule, char) {
408
+ const width = Math.max(20, contentWidth() - MARGIN.length);
409
+ const visible = inner.replace(ANSI, "").length;
410
+ const side = Math.max(2, Math.floor((width - visible - 2) / 2));
411
+ const bar = char.repeat(side);
412
+ return `${MARGIN}${rule(bar)} ${inner} ${rule(bar)}`;
413
+ }
414
+ /** `──── ⛁ Memory snapshot 3 · 229 tok ────` — understated, like the web. */
415
+ export function memoryMarkerLine(m) {
416
+ const n = m.number ?? "?";
417
+ const tok = m.tokens ? c.dim(` · ${m.tokens.toLocaleString()} tok`) : "";
418
+ const ref = m.index ? c.dim(` [${m.index}]`) : "";
419
+ if (m.failed) {
420
+ const label = c.warn(`! ${m.kind === "snapshot" ? "Snapshot" : "Restructure"} ${n} failed`);
421
+ return centred(label + ref, c.dim, "─");
422
+ }
423
+ if (m.kind === "restructure") {
424
+ // Themed and heavier — this one was billed.
425
+ return centred(c.brand(`⟐ Chat restructured v${n}`) + tok + ref, c.brand, "─");
426
+ }
427
+ return centred(c.dim(`⛁ Memory snapshot ${n}`) + tok + ref, c.dim, "─");
428
+ }
429
+ /** Completion footer for a turn that searched: ✓ Web search · 5 sources · 3.2s */
430
+ export function searchCompletionLine(sourceCount, seconds) {
431
+ const secs = seconds < 10 ? seconds.toFixed(1) : Math.round(seconds).toString();
432
+ const plural = sourceCount === 1 ? "source" : "sources";
433
+ return MARGIN + c.ok("✓") + c.dim(` Web search · ${sourceCount} ${plural} · ${secs}s`);
434
+ }
435
+ /** A premium error block: × Title / detail / hint. */
436
+ export function renderError(title, detail, hintCmd,
437
+ /** "warn" for states the user can act on (out of credits) rather than
438
+ * failures — red reads as "something broke", which this isn't. */
439
+ tone = "error") {
440
+ const mark = tone === "warn" ? c.warn("⚠") : c.err("×");
441
+ const heading = tone === "warn" ? c.warn.bold(title) : c.err.bold(title);
442
+ line();
443
+ line(` ${mark} ${heading}`);
444
+ line();
445
+ line(" " + c.value(detail));
446
+ if (hintCmd) {
447
+ line();
448
+ line(" " + c.dim("Run ") + c.cmd(hintCmd) + c.dim(" to continue."));
449
+ }
450
+ line();
451
+ }
452
+ /** Farewell shown on exit — with a resume hint when a session is in flight. */
453
+ export function renderExit(sessionId) {
454
+ line();
455
+ if (sessionId) {
456
+ line(MARGIN + c.dim("Resume this session with:"));
457
+ line(MARGIN + c.cmd(`cos session use ${sessionId}`));
458
+ line();
459
+ }
460
+ line(MARGIN + c.dim("Thanks for using Carrier OS. See you soon."));
461
+ line();
462
+ }
463
+ const MARGIN = " ";
@@ -0,0 +1,52 @@
1
+ import { c } from "./colors.js";
2
+ /**
3
+ * Renders a fenced code block as a subtle, rounded left-framed section with a
4
+ * language label and light syntax highlighting. No ASCII boxes — a single
5
+ * rounded gutter for a premium, uncluttered look. Returns col-0 lines; callers
6
+ * add any base indent.
7
+ */
8
+ const LANG_LABEL = {
9
+ ts: "TypeScript",
10
+ tsx: "TypeScript",
11
+ typescript: "TypeScript",
12
+ js: "JavaScript",
13
+ jsx: "JavaScript",
14
+ javascript: "JavaScript",
15
+ py: "Python",
16
+ python: "Python",
17
+ json: "JSON",
18
+ sh: "Shell",
19
+ bash: "Shell",
20
+ shell: "Shell",
21
+ go: "Go",
22
+ rs: "Rust",
23
+ rust: "Rust",
24
+ sql: "SQL",
25
+ html: "HTML",
26
+ css: "CSS",
27
+ yaml: "YAML",
28
+ yml: "YAML",
29
+ md: "Markdown"
30
+ };
31
+ export function renderCodeBlock(code, lang) {
32
+ const label = LANG_LABEL[lang.toLowerCase()] ?? (lang || "code");
33
+ const lines = code.replace(/\n+$/, "").split("\n");
34
+ const out = [c.rule("╭─ ") + c.accent(label)];
35
+ for (const l of lines)
36
+ out.push(c.rule("│ ") + highlight(l));
37
+ out.push(c.rule("╰─"));
38
+ return out;
39
+ }
40
+ const KEYWORDS = /\b(function|const|let|var|return|if|else|for|while|switch|case|break|continue|import|from|export|default|class|extends|new|await|async|try|catch|finally|throw|typeof|instanceof|def|lambda|print|public|private|protected|static|void|int|float|double|str|string|bool|boolean|true|false|null|None|nil|undefined|this|self|package|func|type|struct|interface|enum|select|where|and|or|not)\b/g;
41
+ /** Tokenizer-free, cross-language light highlighting (keywords, strings, comments). */
42
+ export function highlight(text) {
43
+ const t = text.replace(/\t/g, " ");
44
+ const comment = t.match(/^(\s*)((\/\/|#|--).*)$/);
45
+ if (comment)
46
+ return comment[1] + c.dim(comment[2]);
47
+ // Split on string literals so keywords inside strings aren't recolored.
48
+ const parts = t.split(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)/g);
49
+ return parts
50
+ .map((p, i) => (i % 2 === 1 ? c.arg(p) : p.replace(KEYWORDS, (m) => c.cmd(m))))
51
+ .join("");
52
+ }
@@ -0,0 +1,100 @@
1
+ import * as readline from "node:readline";
2
+ import chalk from "chalk";
3
+ import { c } from "./colors.js";
4
+ import { resumeScreen, screenActive, suspendScreen } from "./screen.js";
5
+ import { THEME_ORDER, accentHex, accentName, setAccent } from "./theme.js";
6
+ /**
7
+ * Claude-style inline /color selector. Renders on a single line:
8
+ *
9
+ * ❯ /color red │ blue │ [ green ] │ yellow │ …
10
+ *
11
+ * ← → (also Tab / Ctrl+B / Ctrl+F) move; Home/End jump; Enter confirms; Esc
12
+ * cancels. The accent live-previews as you move (the whole UI re-themes because
13
+ * colors read the accent dynamically); Esc restores the previous accent.
14
+ *
15
+ * Resolves the chosen color, or null on cancel.
16
+ */
17
+ /**
18
+ * Claude-style confirmation printed after the accent changes: a filled swatch
19
+ * in the new color, dim body text, and the color name shown in that very color
20
+ * so the change is visible, not just described.
21
+ *
22
+ * ● Accent color set to green
23
+ */
24
+ export function confirmColor(name) {
25
+ const hex = accentHex(name);
26
+ const swatch = chalk.hex(hex)("●");
27
+ const label = chalk.hex(hex).bold(name);
28
+ process.stdout.write(`\n ${swatch} ${chalk.dim("Accent color set to")} ${label}\n\n`);
29
+ }
30
+ export function pickColor() {
31
+ const stdin = process.stdin;
32
+ const stdout = process.stdout;
33
+ if (!stdin.isTTY)
34
+ return Promise.resolve(null);
35
+ const options = [...THEME_ORDER];
36
+ const original = accentName();
37
+ let sel = Math.max(0, options.indexOf(original));
38
+ return new Promise((resolve) => {
39
+ // Suspend the persistent-composer engine so the inline selector owns its
40
+ // line, then repaint the transcript + composer once a color is chosen.
41
+ const suspended = screenActive();
42
+ if (suspended)
43
+ suspendScreen();
44
+ stdin.removeAllListeners("keypress");
45
+ readline.emitKeypressEvents(stdin);
46
+ if (!stdin.isRaw)
47
+ stdin.setRawMode(true);
48
+ stdin.resume();
49
+ stdout.write("\x1b[?25l"); // hide cursor while navigating
50
+ const render = () => {
51
+ setAccent(options[sel]); // live preview
52
+ readline.cursorTo(stdout, 0);
53
+ readline.clearLine(stdout, 0);
54
+ const opts = options
55
+ .map((name, i) => i === sel
56
+ ? chalk.bgHex(accentHex(name)).black.bold(` ${name} `)
57
+ : c.dim(` ${name} `))
58
+ .join(c.dim("│"));
59
+ stdout.write(c.brand("❯") + c.dim(" /color ") + opts);
60
+ };
61
+ const done = (result) => {
62
+ if (result === null)
63
+ setAccent(original); // restore on cancel
64
+ readline.cursorTo(stdout, 0);
65
+ readline.clearLine(stdout, 0);
66
+ stdout.write("\x1b[?25h");
67
+ stdin.removeListener("keypress", onKey);
68
+ if (suspended)
69
+ resumeScreen(); // repaint the pinned composer + transcript
70
+ resolve(result);
71
+ };
72
+ const onKey = (_s, key) => {
73
+ if (!key)
74
+ return;
75
+ if (key.name === "left" || (key.ctrl && key.name === "b")) {
76
+ sel = (sel - 1 + options.length) % options.length;
77
+ return render();
78
+ }
79
+ if (key.name === "right" || key.name === "tab" || (key.ctrl && key.name === "f")) {
80
+ sel = (sel + 1) % options.length;
81
+ return render();
82
+ }
83
+ if (key.name === "home") {
84
+ sel = 0;
85
+ return render();
86
+ }
87
+ if (key.name === "end") {
88
+ sel = options.length - 1;
89
+ return render();
90
+ }
91
+ if (key.name === "return" || key.name === "enter")
92
+ return done(options[sel]);
93
+ if (key.name === "escape" || (key.ctrl && (key.name === "c" || key.name === "d"))) {
94
+ return done(null);
95
+ }
96
+ };
97
+ stdin.on("keypress", onKey);
98
+ render();
99
+ });
100
+ }
@@ -0,0 +1,55 @@
1
+ import chalk from "chalk";
2
+ import { accentHex, accentLightHex, BRAND_HEX } from "./theme.js";
3
+ /**
4
+ * Carrier OS design system — the single source of truth for color. Every piece
5
+ * of CLI output pulls from here, so the whole tool stays consistent. All color
6
+ * goes through Chalk, which auto-detects terminal support (and honors NO_COLOR).
7
+ *
8
+ * The `brand` / `neural` / `sel` accents are getters that read the LIVE accent
9
+ * from the theme manager, so a runtime /color change re-themes the entire UI
10
+ * without recreating anything. Everything else is a fixed neutral (white / dim /
11
+ * status) that never changes with the accent.
12
+ */
13
+ export const c = {
14
+ // Brand — dynamic accent (follows /color at runtime)
15
+ get brand() {
16
+ return chalk.hex(accentHex());
17
+ },
18
+ get neural() {
19
+ return chalk.hex(accentHex());
20
+ },
21
+ get accentLight() {
22
+ return chalk.hex(accentLightHex());
23
+ }, // soft, light tint of the accent (assistant lead dot)
24
+ brandFixed: chalk.hex(BRAND_HEX), // fixed brand green — wordmark + prompt marker, never follows /color
25
+ wordmark: chalk.whiteBright.bold, // CARRIER block logo (never recolored)
26
+ // Text
27
+ title: chalk.bold, // section titles / headings
28
+ value: chalk, // primary values
29
+ dim: chalk.dim, // secondary text
30
+ subtitle: chalk.dim,
31
+ label: chalk.dim, // metadata labels
32
+ hint: chalk.dim, // help hint text
33
+ rule: chalk.dim, // separators / rules
34
+ placeholder: chalk.dim.italic, // composer placeholder (fades into the background)
35
+ // Interactive
36
+ get cmd() { return chalk.hex(accentHex()); }, // slash commands
37
+ get key() { return chalk.hex(accentHex()); }, // keybindings / command keys
38
+ get accent() { return chalk.hex(accentHex()); },
39
+ get sel() {
40
+ return chalk.bgHex(accentHex()).black.bold;
41
+ }, // selected palette bar (accent background)
42
+ group: chalk.dim.bold, // palette group headers
43
+ // Command arguments
44
+ arg: chalk, // ids / values (mode, model)
45
+ file: chalk, // file paths
46
+ // SIA / clarification — deliberately not the yellow the turn-shape chips use,
47
+ // because it isn't one: Fast and HIPWR change how the answer is produced,
48
+ // while this changes the question before it's asked.
49
+ get magic() { return chalk.hex(accentHex()); },
50
+ // Status
51
+ ok: chalk.green,
52
+ warn: chalk.yellow,
53
+ get info() { return chalk.hex(accentHex()); },
54
+ err: chalk.red
55
+ };
@@ -0,0 +1,11 @@
1
+ import { stripControl } from "./conversation.js";
2
+ // Ephemeral display cache only. The existing result/outbox owns durable evidence.
3
+ const last = new WeakMap();
4
+ export function rememberCommandDetails(ctx, scope, output) {
5
+ last.set(ctx, { scope, output: stripControl(output) });
6
+ }
7
+ export function commandDetails(ctx, scope) {
8
+ const entry = last.get(ctx);
9
+ return entry?.scope === scope ? ["Command output (existing bounded, redacted result)", ...entry.output.split("\n")] : ["No command output available for this session and repository."];
10
+ }
11
+ export function clearCommandDetails(ctx) { last.delete(ctx); }