@carrieros/cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +170 -64
  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 +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  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/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,334 @@
1
+ import { c } from "./colors.js";
2
+ import { MARGIN, contentWidth, visibleWidth } from "./composer-layout.js";
3
+ import { clip, stripControl, wrapText } from "./conversation.js";
4
+ import { approvalCard, cardHeader, statusTrack } from "./agent-cards.js";
5
+ /**
6
+ * How a proposed file change is shown before anyone approves it.
7
+ *
8
+ * Source-control style: a summary of every file in the group, then each file
9
+ * with its operation, status and reason, then its hunks with old and new line
10
+ * numbers. Committed to the transcript rather than drawn in the prompt, so it
11
+ * stays on screen as the record of what was approved and a long one can be
12
+ * scrolled back to (PgUp/PgDn). Every changed line is shown in full — long
13
+ * lines wrap under the gutter, never clip — so the decision is made on the
14
+ * whole change. Signs (`+`/`-`) and gutters carry the meaning without color,
15
+ * so a terminal without color, or a copied transcript, reads the same.
16
+ *
17
+ * Everything here is display. The text comes from the plan the mutation layer
18
+ * computed from the current bytes on disk; the limits that decide whether a
19
+ * change is reviewable at all (size, sensitive files, containment) live there.
20
+ */
21
+ const ACTION = {
22
+ create_file: "create",
23
+ write_file: "overwrite",
24
+ edit_file: "edit",
25
+ delete_file: "delete",
26
+ revert_change: "revert"
27
+ };
28
+ /** Source-control status letter for the summary list. */
29
+ const STATUS = {
30
+ create_file: "A",
31
+ write_file: "M",
32
+ edit_file: "M",
33
+ delete_file: "D",
34
+ revert_change: "R"
35
+ };
36
+ /**
37
+ * The reviewed diff as numbered lines, parsed from the plan's unified text.
38
+ *
39
+ * Numbers come from the hunk headers the diff engine wrote, so they are the
40
+ * real line numbers of the current file (old) and the proposed file (new).
41
+ */
42
+ export function numberedLines(unified) {
43
+ const out = [];
44
+ let oldLine = 0;
45
+ let newLine = 0;
46
+ for (const raw of unified.split("\n")) {
47
+ if (raw.startsWith("+++") || raw.startsWith("---"))
48
+ continue;
49
+ const h = raw.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
50
+ if (h) {
51
+ // A zero-length side is written as "start-1,0"; the next line on that side is start.
52
+ oldLine = Number(h[2] === "0" ? Number(h[1]) + 1 : h[1]);
53
+ newLine = Number(h[4] === "0" ? Number(h[3]) + 1 : h[3]);
54
+ out.push({ kind: "hunk", text: raw });
55
+ continue;
56
+ }
57
+ if (!raw && out.length === 0)
58
+ continue;
59
+ const op = raw[0];
60
+ const text = raw.slice(1);
61
+ if (op === "-")
62
+ out.push({ kind: "-", oldLine: oldLine++, text });
63
+ else if (op === "+")
64
+ out.push({ kind: "+", newLine: newLine++, text });
65
+ else if (op === " ")
66
+ out.push({ kind: " ", oldLine: oldLine++, newLine: newLine++, text });
67
+ }
68
+ return out;
69
+ }
70
+ /** Split display text into chunks of at most `width` columns, by code point. */
71
+ function chunks(text, width) {
72
+ const w = Math.max(8, width);
73
+ if (visibleWidth(text) <= w)
74
+ return [text];
75
+ const out = [];
76
+ let cur = "";
77
+ for (const ch of text) {
78
+ if (visibleWidth(cur + ch) > w) {
79
+ out.push(cur);
80
+ cur = "";
81
+ }
82
+ cur += ch;
83
+ }
84
+ if (cur || !out.length)
85
+ out.push(cur);
86
+ return out;
87
+ }
88
+ /** Hunk lines with a two-column gutter: sign, old number, new number, rule, code. */
89
+ function hunkLines(plan) {
90
+ const lines = numberedLines(plan.unified);
91
+ const widest = lines.reduce((n, l) => Math.max(n, l.oldLine ?? 0, l.newLine ?? 0), 0);
92
+ const w = Math.max(2, String(widest).length);
93
+ const room = contentWidth() - INDENT.length - (w * 2 + 6) + 1;
94
+ const out = [];
95
+ for (const l of lines) {
96
+ if (l.kind === "hunk") {
97
+ out.push(INDENT + c.accent(clip(safe(l.text), contentWidth() - INDENT.length + 1)));
98
+ continue;
99
+ }
100
+ const oldNo = l.oldLine === undefined ? "".padStart(w) : String(l.oldLine).padStart(w);
101
+ const newNo = l.newLine === undefined ? "".padStart(w) : String(l.newLine).padStart(w);
102
+ const sign = l.kind === " " ? " " : l.kind;
103
+ const paint = l.kind === "+" ? c.ok : l.kind === "-" ? c.err : c.dim;
104
+ // Tabs and control bytes would misalign the gutter; show them visibly.
105
+ const text = safe(l.text).replace(/\t/g, " ");
106
+ const parts = chunks(text, room);
107
+ parts.forEach((part, i) => {
108
+ const gutter = i === 0 ? `${sign} ${oldNo} ${newNo} │ ` : ` ${"".padStart(w)} ${"".padStart(w)} ┆ `;
109
+ out.push(INDENT + paint(gutter + part));
110
+ });
111
+ }
112
+ return out;
113
+ }
114
+ export function riskOf(plan) {
115
+ if (plan.name === "delete_file")
116
+ return "high";
117
+ if (plan.name === "create_file")
118
+ return "low";
119
+ return "medium";
120
+ }
121
+ const safe = stripControl;
122
+ const INDENT = MARGIN + " ";
123
+ const inner = () => Math.max(24, contentWidth() - 4);
124
+ /** Explanatory text, wrapped to the terminal at the given indent. */
125
+ const notes = (indent, text) => wrapText(text, Math.max(16, contentWidth() - indent.length - 1)).map((l) => indent + c.dim(l));
126
+ function planLines(plan, index, total, activeRoot) {
127
+ const risk = riskOf(plan);
128
+ const riskLabel = risk.toUpperCase();
129
+ const riskText = risk === "high" ? c.err(riskLabel) : risk === "medium" ? c.warn(riskLabel) : c.dim(riskLabel);
130
+ const counter = total > 1 ? `${index + 1}/${total} ` : "";
131
+ const hunks = plan.diff.hunks.length;
132
+ const out = [""];
133
+ // WHICH repository, ABOVE the path — a change can target a repository that is
134
+ // not the active one, so the name is part of what is being approved and must
135
+ // be read before the path it qualifies.
136
+ if (plan.repositoryName)
137
+ out.push(MARGIN + c.dim("Repository ") + c.value(safe(plan.repositoryName)));
138
+ // File boundary: the path (and its position in the group), never clipped —
139
+ // it is what is being approved.
140
+ const head = counter + safe(plan.rel);
141
+ for (const part of chunks(head, contentWidth() - MARGIN.length - 1))
142
+ out.push(MARGIN + c.file(part));
143
+ // The full location is part of what is approved: wrapped, never clipped.
144
+ if (plan.repositoryRoot && plan.repositoryRoot !== activeRoot) {
145
+ chunks(safe(plan.repositoryRoot), contentWidth() - INDENT.length - 10).forEach((part, i) => out.push(INDENT + c.dim(i === 0 ? "Location " : " ") + part));
146
+ }
147
+ if (plan.reverts)
148
+ out.push(INDENT + c.dim(`undoes ${plan.reverts}`));
149
+ out.push("");
150
+ if (plan.name === "delete_file") {
151
+ out.push(INDENT + c.err(`The whole file (${plan.diff.removed} lines) will be removed.`));
152
+ }
153
+ out.push(...hunkLines(plan));
154
+ if (plan.lineEndings) {
155
+ const { before, after } = plan.lineEndings;
156
+ out.push(INDENT + c.warn(`${plan.diff.hunks.length ? "Also changes" : "Changes only"} the line endings: ${before} → ${after}.`));
157
+ }
158
+ else if (plan.diff.hunks.length === 0)
159
+ out.push(INDENT + c.dim("(no line changes)"));
160
+ out.push("");
161
+ // Reason, the operation ID (the one the receipt, journal, audit events and
162
+ // Admin activity already use) and the risk: what the person is deciding on.
163
+ const field = (label, value, paint = c.value) => wrapText(value, Math.max(12, inner() - 14)).map((l, i) => INDENT + c.dim((i === 0 ? label : "").padEnd(14)) + paint(l));
164
+ out.push(...field("Reason", safe(plan.reason), c.dim));
165
+ out.push(...field("Operation ID", safe(plan.operationId)));
166
+ out.push(INDENT + c.dim("Risk".padEnd(14)) + riskText);
167
+ out.push(...field("Change", `${ACTION[plan.name] ?? "change"} · +${plan.diff.added} −${plan.diff.removed} · ${hunks} ${hunks === 1 ? "hunk" : "hunks"}`, c.dim));
168
+ return out;
169
+ }
170
+ /** The changed-files list: one row per file in the reviewed group, all expanded below. */
171
+ function fileList(plans) {
172
+ const added = plans.reduce((n, p) => n + p.diff.added, 0);
173
+ const removed = plans.reduce((n, p) => n + p.diff.removed, 0);
174
+ const pathWidth = Math.max(8, Math.min(48, contentWidth() - 24, plans.reduce((n, p) => Math.max(n, visibleWidth(safe(p.rel))), 0)));
175
+ return [
176
+ MARGIN + c.value(`${plans.length} file${plans.length === 1 ? "" : "s"} changed`) + c.dim(" · ") + c.ok(`+${added}`) + " " + c.err(`−${removed}`),
177
+ ...(plans.length > 1
178
+ ? plans.map((p) => INDENT + c.dim("▾ ") + c.warn(STATUS[p.name] ?? "M") + " " + c.file(clip(safe(p.rel), pathWidth).padEnd(pathWidth)) + c.dim(` +${p.diff.added} −${p.diff.removed}`))
179
+ : [])
180
+ ];
181
+ }
182
+ export function renderGroup(plans, correction = false, remaining = 0, activeRoot) {
183
+ const files = plans.length;
184
+ const detail = correction
185
+ ? `New diff from fresh reads after the failed validation — the earlier approval does not cover it. Nothing has been written yet (${files} file${files === 1 ? "" : "s"}).`
186
+ : `Nothing has been written yet (${files} file${files === 1 ? "" : "s"}). Tests run only after their own approval.`;
187
+ return [
188
+ ...cardHeader(correction ? "CORRECTIVE CHANGE" : "PROPOSED CHANGE", c.title),
189
+ ...(plans.length > 1 ? fileList(plans) : []),
190
+ ...plans.flatMap((p, i) => planLines(p, i, plans.length, activeRoot)),
191
+ ...(remaining ? ["", ...notes(MARGIN, `${remaining} other planned file${remaining === 1 ? "" : "s"} still require review.`)] : []),
192
+ ...approvalCard(correction ? "correction" : "change", detail, []),
193
+ ...notes(MARGIN, "PgUp/PgDn scrolls the diff."),
194
+ ""
195
+ ];
196
+ }
197
+ /** The card shown when an approved diff no longer matches the file on disk. */
198
+ export function renderNoLongerValid(rels) {
199
+ return [
200
+ ...cardHeader("⚠ CHANGE INVALIDATED", c.warn),
201
+ ...rels.flatMap((rel) => wrapText(`${safe(rel)} changed after this proposal.`, Math.max(16, contentWidth() - MARGIN.length - 1)).map((l) => MARGIN + c.value(l))),
202
+ ...notes(MARGIN, "The approved diff is no longer based on the current file. No files were modified by it."),
203
+ ...notes(MARGIN, "A fresh proposal and a new approval are required."),
204
+ ""
205
+ ];
206
+ }
207
+ /** The card shown when the person declines a proposed change. */
208
+ export function renderChangeRejected(plans) {
209
+ return [
210
+ ...cardHeader("CHANGE REJECTED", c.warn),
211
+ MARGIN + c.value("No files were modified."),
212
+ ...plans.map((p) => INDENT + c.file(safe(p.rel)) + c.dim(` · ${safe(p.operationId)}`)),
213
+ ""
214
+ ];
215
+ }
216
+ /**
217
+ * After a planned validation fails: what failed, and what happens next. Built
218
+ * from the workflow's own validation projection — the command identity and
219
+ * exit status it recorded — plus the counts the command result card read from
220
+ * the actual output. Never from model text.
221
+ */
222
+ export function renderValidationFailed(snapshot, counts = "", failure) {
223
+ const validation = Array.isArray(snapshot.validation) ? snapshot.validation : [];
224
+ const tests = Array.isArray(snapshot.tests) ? snapshot.tests : [];
225
+ const failed = validation.filter((v) => v.status === "FAILED");
226
+ const failedCount = /(\d+) failed/.exec(counts)?.[1];
227
+ const out = [...cardHeader("✗ VALIDATION FAILED", c.err)];
228
+ if (failedCount)
229
+ out.push(MARGIN + c.err(`✗ ${failedCount} test${failedCount === "1" ? "" : "s"} failed`));
230
+ else if (counts)
231
+ out.push(MARGIN + c.dim(safe(counts)));
232
+ if (failure?.name)
233
+ out.push(...wrapText(safe(failure.name), inner()).map((l) => MARGIN + c.value(l)));
234
+ if (failure?.expected)
235
+ out.push(MARGIN + c.dim("Expected: ") + c.ok(clip(safe(failure.expected), Math.max(8, inner() - 12))));
236
+ if (failure?.received)
237
+ out.push(MARGIN + c.dim("Received: ") + c.err(clip(safe(failure.received), Math.max(8, inner() - 12))));
238
+ for (const v of failed) {
239
+ const args = Array.isArray(v.args) ? v.args.filter((a) => typeof a === "string") : [];
240
+ const exit = tests.find((t) => t.id === v.operation_id)?.exit;
241
+ out.push(MARGIN + c.dim(clip(safe([String(v.program ?? ""), ...args].join(" ")), inner() - 16) + ` · exit ${exit ?? "unknown"}`));
242
+ }
243
+ out.push(...notes(MARGIN, "A correction, if any, is a new diff with its own approval."), "");
244
+ return out;
245
+ }
246
+ /**
247
+ * The coordinator's applied-change confirmations, laid out as an "applying"
248
+ * block. Display only: the coordinator's own text is parsed, never changed, and
249
+ * anything that is not an apply confirmation is shown as it was sent.
250
+ */
251
+ const APPLIED_LINE = /^✓\s+(\S+)\s+(.+?)\s+\(\+(\d+)\s+−(\d+)\)\s+·\s+Applied\s+·\s+(\S+)$/;
252
+ export function renderChangeSummary(lines) {
253
+ const applied = lines.map((l) => APPLIED_LINE.exec(stripControl(l).trim())).filter((m) => !!m);
254
+ const other = lines.filter((l) => !APPLIED_LINE.test(stripControl(l).trim()));
255
+ const out = [];
256
+ if (applied.length) {
257
+ out.push("", MARGIN + c.title(applied.length === 1 ? "Applying change…" : `Applying ${applied.length} changes…`));
258
+ for (const [, verb, rel, added, removed] of applied) {
259
+ const what = verb === "Deleted" ? "File deleted" : verb === "Created" ? "File created" : "File updated";
260
+ const counts = ` +${added} −${removed}`;
261
+ const oneLine = `${MARGIN} ✓ ${what} · ${rel}${counts}`;
262
+ if (visibleWidth(oneLine) <= contentWidth() - 1) {
263
+ out.push(MARGIN + " " + c.ok("✓ ") + c.value(what) + c.dim(" · ") + c.file(rel) + c.dim(counts));
264
+ }
265
+ else {
266
+ // A long path wraps on its own lines rather than running off the edge.
267
+ out.push(MARGIN + " " + c.ok("✓ ") + c.value(what) + c.dim(counts));
268
+ for (const part of chunks(rel, contentWidth() - MARGIN.length - 5))
269
+ out.push(MARGIN + " " + c.file(part));
270
+ }
271
+ }
272
+ out.push(MARGIN + " " + c.ok("✓ ") + c.value(applied.length === 1 ? "Mutation completed" : "Mutations completed"));
273
+ for (const m of applied)
274
+ out.push(MARGIN + " " + c.dim("Operation ID: ") + c.value(m[5]));
275
+ }
276
+ for (const l of other)
277
+ out.push(MARGIN + (l.includes("✓") ? c.ok(l.trim()) : c.warn(l.trim())));
278
+ return out;
279
+ }
280
+ /** Bounded display projection of existing coordinator events, never an authority. */
281
+ export class ActiveChangeView {
282
+ snapshot;
283
+ paint;
284
+ entries = new Map();
285
+ lastActive;
286
+ constructor(snapshot, paint) {
287
+ this.snapshot = snapshot;
288
+ this.paint = paint;
289
+ }
290
+ review(plans) {
291
+ for (const plan of plans)
292
+ this.entries.set(plan.operationId, { plan: { ...plan }, status: "awaiting approval" });
293
+ while (this.entries.size > 8)
294
+ this.entries.delete(this.entries.keys().next().value);
295
+ this.refresh();
296
+ }
297
+ decision(plans, answer) {
298
+ for (const plan of plans) {
299
+ const entry = this.entries.get(plan.operationId);
300
+ if (entry)
301
+ entry.status = answer === "approve" ? "approved; awaiting verified result" : answer === "reject" ? "rejected" : answer;
302
+ }
303
+ this.refresh();
304
+ }
305
+ result(payload) {
306
+ const entry = this.entries.get(payload.tool_call_id);
307
+ if (entry)
308
+ entry.status = payload.ok ? "applied" : payload.error?.code === "MUTATION_REJECTED" ? "rejected" : payload.error?.code === "STALE_FILE" ? "invalidated" : payload.error?.code ?? "unresolved";
309
+ this.refresh();
310
+ }
311
+ commandStatus(value) { void value; this.refresh(); }
312
+ refresh() {
313
+ const state = this.snapshot();
314
+ // The status track appears once there is a coding plan; ordinary
315
+ // questions never get one. It is a projection of CodingWorkflow state.
316
+ if (!state.plan && !this.entries.size)
317
+ return;
318
+ const current = String(state.state ?? "");
319
+ if (!["FAILED", "CANCELLED", "UNRESOLVED"].includes(current))
320
+ this.lastActive = current;
321
+ const lines = [statusTrack(state, this.lastActive)];
322
+ const entries = [...this.entries.values()];
323
+ // Verification is the workflow's: shown only once a change is applied.
324
+ const validation = Array.isArray(state.validation) ? state.validation : [];
325
+ const verification = !validation.length ? "" : validation.every(v => v.status === "PASSED") ? "verification passed" : validation.some(v => v.status === "FAILED") ? "verification failed" : "verification pending";
326
+ for (const { plan, status } of entries.slice(-2)) {
327
+ lines.push(MARGIN + c.file(safe(plan.rel)) + c.dim(` · ${safe(status)}${status === "applied" && verification ? ` · ${verification}` : ""}`));
328
+ }
329
+ if (entries.length > 2)
330
+ lines.push(MARGIN + c.dim(`+${entries.length - 2} earlier changes · PgUp for reviews`));
331
+ this.paint(lines.map(l => clip(l, contentWidth())));
332
+ }
333
+ clear() { this.entries.clear(); this.lastActive = undefined; this.paint([]); }
334
+ }
@@ -1,9 +1,11 @@
1
1
  import { line } from "../services/output.js";
2
2
  import { sleep } from "../services/spinner.js";
3
3
  import { c } from "./colors.js";
4
+ import { contentWidth } from "./composer-layout.js";
4
5
  import { renderMarkdown } from "./markdown.js";
5
6
  import { renderUserMessage } from "./message.js";
6
7
  import { thinking } from "./spinner.js";
8
+ import { formatCredits } from "./ui.js";
7
9
  /**
8
10
  * Presentation layer for the conversation, styled after Claude Code:
9
11
  * ❯ <your message> (full-width bar — see message.ts)
@@ -34,9 +36,65 @@ const THINKING_PHRASES = [
34
36
  ];
35
37
  let phraseIndex = 0;
36
38
  let tipIndex = 0;
37
- /** Completion footer text, Claude-style: "Generated in 1.2s". */
38
- function completionLabel(seconds) {
39
- return `Generated in ${Math.max(0.1, seconds).toFixed(1)}s`;
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`;
40
98
  }
41
99
  // Rotating tips shown beneath the spinner while Carrier is responding — a chance
42
100
  // to surface a handy shortcut, the way Claude Code does.
@@ -102,7 +160,10 @@ export function startThinkingLive(live) {
102
160
  // SSE), so we surface it progressively — word by word at a natural cadence — so
103
161
  // it reads like Claude typing the response in, rather than one instant block.
104
162
  const STREAM_DELAY = 22; // ms between words
105
- const ANSI = /\x1b\[[0-9;]*m/g;
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;
106
167
  const stripAnsi = (s) => s.replace(ANSI, "");
107
168
  /** Styled prefix of `s` showing its first `n` visible characters (ANSI kept). */
108
169
  function ansiSlice(s, n) {
@@ -169,7 +230,7 @@ export async function streamAssistantSticky(sticky, text) {
169
230
  }
170
231
  sticky.scroll(); // trailing blank
171
232
  }
172
- /** Completion footer on the scroll region: ● Generated in 1.2s */
233
+ /** Completion footer on the scroll region: ● Brewed for 1.2s */
173
234
  export function renderCompleteSticky(sticky, seconds) {
174
235
  sticky.scroll();
175
236
  sticky.setLine(MARGIN + c.dim(`● ${completionLabel(seconds)}`));
@@ -199,9 +260,9 @@ export async function streamAssistantLive(live, text) {
199
260
  }
200
261
  live.commit([""]); // single trailing blank
201
262
  }
202
- /** Dim completion footer committed above the pinned bar: ● Generated in 1.2s */
203
- export function renderCompleteLive(live, seconds) {
204
- live.commit([MARGIN + c.dim(`● ${completionLabel(seconds)}`), ""]);
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)}`), ""]);
205
266
  }
206
267
  /** Error block committed above the pinned bar. */
207
268
  export function renderErrorLive(live, title, detail, hintCmd) {
@@ -219,7 +280,7 @@ export async function streamAssistant(text) {
219
280
  md.shift();
220
281
  while (md.length && md[md.length - 1].trim() === "")
221
282
  md.pop();
222
- const tty = process.stdout.isTTY;
283
+ const tty = process.stdout.isTTY && process.env.TERM !== "dumb";
223
284
  if (tty)
224
285
  process.stdout.write("\x1b[?25l"); // hide the caret; ▋ is the cursor
225
286
  for (let i = 0; i < md.length; i++) {
@@ -239,15 +300,147 @@ export async function streamAssistant(text) {
239
300
  process.stdout.write("\x1b[?25h");
240
301
  line(); // single trailing blank
241
302
  }
242
- /** Dim completion footer: ● Generated in 1.2s */
243
- export function renderComplete(seconds) {
244
- line(MARGIN + c.dim(`● ${completionLabel(seconds)}`));
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}`) : ""));
245
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`);
246
434
  }
247
435
  /** A premium error block: × Title / detail / hint. */
248
- export function renderError(title, detail, hintCmd) {
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);
249
442
  line();
250
- line(` ${c.err("×")} ${c.err.bold(title)}`);
443
+ line(` ${mark} ${heading}`);
251
444
  line();
252
445
  line(" " + c.value(detail));
253
446
  if (hintCmd) {
package/dist/ui/colors.js CHANGED
@@ -24,8 +24,8 @@ export const c = {
24
24
  brandFixed: chalk.hex(BRAND_HEX), // fixed brand green — wordmark + prompt marker, never follows /color
25
25
  wordmark: chalk.whiteBright.bold, // CARRIER block logo (never recolored)
26
26
  // Text
27
- title: chalk.whiteBright.bold, // section titles / headings
28
- value: chalk.white, // primary values
27
+ title: chalk.bold, // section titles / headings
28
+ value: chalk, // primary values
29
29
  dim: chalk.dim, // secondary text
30
30
  subtitle: chalk.dim,
31
31
  label: chalk.dim, // metadata labels
@@ -33,19 +33,23 @@ export const c = {
33
33
  rule: chalk.dim, // separators / rules
34
34
  placeholder: chalk.dim.italic, // composer placeholder (fades into the background)
35
35
  // Interactive
36
- cmd: chalk.cyan, // slash commands
37
- key: chalk.cyan, // keybindings / command keys
38
- accent: chalk.cyan,
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
39
  get sel() {
40
40
  return chalk.bgHex(accentHex()).black.bold;
41
41
  }, // selected palette bar (accent background)
42
42
  group: chalk.dim.bold, // palette group headers
43
43
  // Command arguments
44
- arg: chalk.green, // ids / values (mode, model)
45
- file: chalk.yellow, // file paths
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()); },
46
50
  // Status
47
51
  ok: chalk.green,
48
52
  warn: chalk.yellow,
49
- info: chalk.cyan,
53
+ get info() { return chalk.hex(accentHex()); },
50
54
  err: chalk.red
51
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); }