@carrieros/cli 0.3.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 (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -1,3 +1,6 @@
1
+ import { commandDetails } from "../ui/command-details.js";
2
+ import { workspaceRoot } from "../services/local-files.js";
3
+ import { line } from "../services/output.js";
1
4
  import { CommanderError } from "commander";
2
5
  import { ApiError } from "../services/api.js";
3
6
  import { AuthRequiredError } from "../services/context.js";
@@ -16,11 +19,14 @@ import { listMemory, showArtifact } from "../commands/memory.js";
16
19
  import { showHistory } from "../commands/history.js";
17
20
  import { deleteSession, newSession, pickSession, switchTo } from "../commands/sessions.js";
18
21
  import { clearActiveSession } from "../services/session-resolver.js";
22
+ import { runCompact, runPermissions } from "../commands/permissions.js";
23
+ import { parsePermissionMode } from "../services/permission-mode.js";
19
24
  import { visibleCommands } from "../ui/command-item.js";
20
25
  import { confirmColor, pickColor } from "../ui/color-picker.js";
21
26
  import { pickFromList } from "../ui/select.js";
22
27
  import { isThemeColor, setAccent, THEME_ORDER } from "../ui/theme.js";
23
- import { armWebSearch, chatTurn, isWebSearchStateArg, openSource, pickChatType, pickMode, pickModel, searchNow, setChatType, setFast, setHighPower, setSia, setMode, setModel, setWebSearch, showSources } from "./shell-chat.js";
28
+ import { armWebSearch, chatTurn, isWebSearchStateArg, openSource, pickChatType, pickMode, pickModel, searchNow, setChatType, setFast, setHighPower, setSia, setMode, setModel, setWebSearch, showSources, fastInEffect } from "./shell-chat.js";
29
+ import { c } from "../ui/colors.js";
24
30
  import { buildFooter } from "./shell-prompt.js";
25
31
  import { printShellHelp } from "./shell-renderer.js";
26
32
  const STAY = { exit: false };
@@ -61,6 +67,10 @@ export async function handleSlash(ctx, program, client, input) {
61
67
  case "exit":
62
68
  case "quit":
63
69
  return { exit: true };
70
+ case "details":
71
+ for (const row of commandDetails(ctx, JSON.stringify([client.mutationRecoveryScope(), ctx.config.get("sessionId"), workspaceRoot()])))
72
+ line(row);
73
+ return STAY;
64
74
  case "help":
65
75
  // In a TTY, /help is an arrow-navigable menu (Enter runs the picked
66
76
  // command); piped/non-interactive falls back to the static list.
@@ -120,7 +130,23 @@ export async function handleSlash(ctx, program, client, input) {
120
130
  await pickModel(ctx, client);
121
131
  return STAY;
122
132
  case "mode":
123
- await setMode(ctx, client, argStr);
133
+ // `/mode manual|plan|accept-edits` is the permission mode; any other
134
+ // argument (general, code, …) is the Carrier chat mode, as before.
135
+ // "auto" stays the chat mode's Auto here — the Auto PERMISSION mode is
136
+ // `/permissions auto`, so an existing `/mode auto` never grants change authority.
137
+ if (parsePermissionMode(argStr) && parsePermissionMode(argStr) !== "auto")
138
+ await runPermissions(ctx, argStr);
139
+ else
140
+ await setMode(ctx, client, argStr);
141
+ return STAY;
142
+ case "permissions":
143
+ await runPermissions(ctx, argStr);
144
+ return STAY;
145
+ case "plan":
146
+ await runPermissions(ctx, "plan");
147
+ return STAY;
148
+ case "compact":
149
+ await runCompact(ctx, client);
124
150
  return STAY;
125
151
  case "model":
126
152
  await setModel(ctx, client, argStr);
@@ -144,7 +170,7 @@ export async function handleSlash(ctx, program, client, input) {
144
170
  }
145
171
  // Turn shaping. Bare toggles; an explicit on|off sets.
146
172
  case "fast":
147
- setFast(ctx, argStr);
173
+ await setFast(ctx, argStr, client);
148
174
  return STAY;
149
175
  case "hipwr":
150
176
  case "highpower":
@@ -180,9 +206,12 @@ export async function handleSlash(ctx, program, client, input) {
180
206
  case "new":
181
207
  await newSession(ctx, argStr.trim());
182
208
  return STAY;
209
+ // A new task: the current one stays in history (/sessions), with its audit
210
+ // and recovery records; attachments, Plan and Accept Edits do not carry over.
183
211
  case "clear":
184
212
  clearActiveSession(ctx);
185
- info("Cleared. Your next message starts a fresh session.");
213
+ ctx.clearAttachments();
214
+ info("New task. Your next message starts it — the previous one is kept in /sessions; permissions are back to Manual.");
186
215
  return STAY;
187
216
  case "context":
188
217
  if ((rest[0] ?? "").toLowerCase() === "project") {
@@ -278,6 +307,7 @@ export async function handleSlash(ctx, program, client, input) {
278
307
  // on just forces a second command. Matches /modes and /models, which are
279
308
  // both pickers. Piped output, or an explicit flag like `-n 50`, still gets
280
309
  // the plain printed list.
310
+ case "resume":
281
311
  case "sessions":
282
312
  if (rest.length === 0 && process.stdin.isTTY)
283
313
  await pickSession(ctx, client);
@@ -289,6 +319,8 @@ export async function handleSlash(ctx, program, client, input) {
289
319
  await showHistory(ctx, client, rest[0]);
290
320
  return STAY;
291
321
  case "upload":
322
+ if (refuseFilesInFastMode(ctx))
323
+ return STAY;
292
324
  if (rest.length === 0) {
293
325
  errorLine("Usage: /upload <file>");
294
326
  return STAY;
@@ -297,6 +329,8 @@ export async function handleSlash(ctx, program, client, input) {
297
329
  await route(program, ["upload", ...rest]);
298
330
  return STAY;
299
331
  case "attach": {
332
+ if (refuseFilesInFastMode(ctx))
333
+ return STAY;
300
334
  const uploads = ctx.config.get("uploads") ?? [];
301
335
  let target = rest[0];
302
336
  if (!target) {
@@ -367,3 +401,11 @@ async function runHelpMenu(ctx, program, client) {
367
401
  return STAY; // Esc, or avoid reopening
368
402
  return handleSlash(ctx, program, client, chosen);
369
403
  }
404
+ /** Fast Mode's model can't read files — as the web disables its paperclip. True when refused. */
405
+ function refuseFilesInFastMode(ctx) {
406
+ if (!fastInEffect(ctx))
407
+ return false;
408
+ errorLine("Fast mode can't read files — its model is text-only.");
409
+ line(" " + c.dim("Run ") + c.cmd("/fast off") + c.dim(" to attach files."));
410
+ return true;
411
+ }
@@ -1,14 +1,14 @@
1
- import chalk from "chalk";
1
+ import { getPermissionMode, permissionModeLabel } from "../services/permission-mode.js";
2
2
  import { attachedFilenames } from "../services/file-upload.js";
3
3
  import { branchLabel, peekWorkspace } from "../services/workspace.js";
4
4
  import { activeRepository, inWorkspaceMode, peekRepositoryDetails } from "../services/workspace-registry.js";
5
5
  import { c } from "../ui/colors.js";
6
6
  import { modeLabelShort, modelLabelShort, turnShapeLabels, webSearchLabelShort } from "./shell-chat.js";
7
7
  /** The green caret the shell prompt uses (non-TTY fallback). */
8
- export const CARET = c.brand("❯") + " ";
8
+ export const CARET = c.brand("›") + " ";
9
9
  /** Light purple used for the "Standard chat" footer label (distinct from the
10
10
  * accent-green Carrier Chat label). */
11
- const STANDARD_LABEL = chalk.hex("#c4a7ff");
11
+ const STANDARD_LABEL = c.value;
12
12
  /**
13
13
  * The dim status footer shown directly beneath the input box, Claude-style:
14
14
  * ‖ Carrier OS chat · Grok 4.1 Fast
@@ -16,6 +16,10 @@ const STANDARD_LABEL = chalk.hex("#c4a7ff");
16
16
  * while the palette is open.
17
17
  */
18
18
  export function buildFooter(ctx) {
19
+ if (ctx.chatType === "carrier" && ctx.carrierMaintenance !== false) {
20
+ const state = ctx.carrierMaintenance === true ? "Carrier Chat paused" : "Carrier Chat status unavailable";
21
+ return repoPart() + c.dim(" · ") + c.warn(state) + c.dim(" · /switch standard");
22
+ }
19
23
  const mode = modeLabelShort(ctx);
20
24
  const model = modelLabelShort(ctx);
21
25
  // The leading token reflects the CHAT TYPE:
@@ -25,7 +29,7 @@ export function buildFooter(ctx) {
25
29
  // since Standard chat is where modes actually vary.
26
30
  const isStandard = ctx.chatType === "standard";
27
31
  const label = isStandard ? "Standard" : "Carrier OS";
28
- const paintLabel = isStandard ? STANDARD_LABEL : c.brandFixed;
32
+ const paintLabel = isStandard ? STANDARD_LABEL : c.brand;
29
33
  const dot = c.dim(" · ");
30
34
  // Show the active mode ONLY in standard chat: "Standard chat · Code · Grok".
31
35
  const modePart = isStandard ? dot + c.value(mode) : "";
@@ -36,7 +40,7 @@ export function buildFooter(ctx) {
36
40
  // can't see the workspace toggle, so claiming a state there would be a lie,
37
41
  // and "off" is the quiet baseline that needs no chip.
38
42
  const webLabel = webSearchLabelShort(ctx);
39
- const webPart = webLabel ? dot + c.accent(`🌐 ${webLabel}`) : "";
43
+ const webPart = webLabel ? dot + c.accent(webLabel) : "";
40
44
  // Turn-shaping toggles (Fast, HIPWR) — shown only when on, so the default
41
45
  // footer stays quiet and an enabled one actually stands out.
42
46
  // Already coloured by turnShapeLabels — each chip carries its own meaning.
@@ -59,11 +63,15 @@ export function buildFooter(ctx) {
59
63
  // Attachment indicator: one file shows its name, several show a compact count.
60
64
  const names = attachedFilenames(ctx);
61
65
  const attach = names.length === 1
62
- ? dot + c.accent(`📎 ${names[0]}`)
66
+ ? dot + c.accent(`Attached: ${names[0]}`)
63
67
  : names.length > 1
64
- ? dot + c.accent(`📎 ${names.length} attached`)
68
+ ? dot + c.accent(`${names.length} attached`)
65
69
  : "";
66
- return " " + c.dim("‖ ") + context + convo + shapePart + webPart + attach + repoPart();
70
+ // Permission mode: always shown, so what the next message may do is never a guess.
71
+ const permission = getPermissionMode(ctx.config);
72
+ const paintPermission = permission === "auto" ? c.err : permission === "accept_edits" ? c.warn : permission === "plan" ? c.accent : c.dim;
73
+ const permissionPart = dot + paintPermission(permissionModeLabel(permission));
74
+ return repoPart() + c.dim(" · ") + (ctx.mainTurnRunning ? c.dim("Working · Ctrl+C stops") + permissionPart : context + permissionPart + convo + shapePart + webPart + attach);
67
75
  }
68
76
  /**
69
77
  * Where you are on disk, trailing the footer: "my-app · main".
@@ -83,16 +91,18 @@ function repoPart() {
83
91
  if (inWorkspaceMode()) {
84
92
  const active = activeRepository();
85
93
  const details = peekRepositoryDetails(active);
86
- const branch = details?.branch ? ` · ${clip(details.branch, 20)}` : "";
94
+ const branch = (process.stdout.columns ?? 80) >= 80 && details?.branch ? ` · ${clip(details.branch, 20)}` : "";
87
95
  return " " + c.dim(`${clip(active.name, 24)}${branch}`);
88
96
  }
89
97
  const ws = peekWorkspace();
90
- if (!ws || ws.repository.state !== "detected")
98
+ if (!ws)
91
99
  return "";
100
+ if (ws.repository.state !== "detected")
101
+ return " " + c.dim(clip(ws.project.name, 24));
92
102
  const branch = branchLabel(ws.repository);
93
103
  if (!branch)
94
104
  return "";
95
- return " " + c.dim(`${clip(ws.project.name, 20)} · ${clip(branch, 22)}`);
105
+ return " " + c.dim(`${clip(ws.project.name, 20)}${(process.stdout.columns ?? 80) >= 80 ? ` · ${clip(branch, 22)}` : ""}`);
96
106
  }
97
107
  /** Trim a title to keep the footer on one row. */
98
108
  function clip(s, max) {
@@ -23,7 +23,7 @@ export function renderWelcomeBack(_scope, developerName) {
23
23
  line(" " + c.brand("│") + chalk.bold(inner) + c.brand("│"));
24
24
  line(" " + c.brand("└" + rule + "┘"));
25
25
  line();
26
- kv("Developer", developerName);
26
+ kv("User", developerName);
27
27
  line();
28
28
  }
29
29
  export function printShellHelp() {
@@ -1,8 +1,11 @@
1
1
  import readline from "node:readline";
2
2
  import { confirm } from "@inquirer/prompts";
3
3
  import { DEFAULT_API_URL } from "../services/config.js";
4
+ import { isPackaged } from "../services/packaged.js";
5
+ import { refreshPackagedUpdateCache } from "../services/packaged-update.js";
4
6
  import { deviceLogin, renderLoginFailure } from "../services/login-flow.js";
5
7
  import { line } from "../services/output.js";
8
+ import { showTaskContext } from "./task-context-view.js";
6
9
  import { renderWelcomeBanner } from "../ui/banner.js";
7
10
  import { renderExit } from "../ui/chat-renderer.js";
8
11
  import { c } from "../ui/colors.js";
@@ -12,7 +15,7 @@ import { startScreen, stopScreen, screenScrollToBottom } from "../ui/screen.js";
12
15
  import { ensureWorkspaceTrust } from "../ui/trust.js";
13
16
  import { activeRepository, inWorkspaceMode, listRepositories } from "../services/workspace-registry.js";
14
17
  import { cachedUpdateNotice, refreshUpdateCache, shouldRefreshCheck } from "../services/update.js";
15
- import { chatTypeLabel, loadModels, loadModes } from "./shell-chat.js";
18
+ import { chatTypeLabel, loadModels, loadModes, showCarrierMaintenance, syncChatAvailability, loadFastModel } from "./shell-chat.js";
16
19
  import { CARET, buildFooter } from "./shell-prompt.js";
17
20
  import { dispatchLine, isMainTurn } from "./shell-router.js";
18
21
  import { printWelcome, renderWelcomeBack } from "./shell-renderer.js";
@@ -39,6 +42,8 @@ export async function runShell(ctx, program) {
39
42
  return; // user chose /exit or Ctrl+C
40
43
  }
41
44
  const client = ctx.requireAuth();
45
+ await client.recoverToolResults();
46
+ await client.reportCodingTaskRecovery();
42
47
  // Mark that we're inside the interactive shell — commands (e.g. upload) use
43
48
  // this to prompt interactively here vs. print finish-and-return output when
44
49
  // run standalone (cos upload).
@@ -48,7 +53,7 @@ export async function runShell(ctx, program) {
48
53
  // General here would override that and strand Standard users in General.
49
54
  // Preload the mode + model lists so the prompt/banner can show friendly labels
50
55
  // (e.g. the "Carrier OS" mode name rather than the raw id).
51
- await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => [])]);
56
+ await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => []), loadFastModel(client)]);
52
57
  // Enter TUI mode: pin the composer to the bottom of the terminal and give the
53
58
  // transcript its own scrolling region above it (Claude-style). From here, all
54
59
  // output flows into the transcript via the screen engine.
@@ -73,13 +78,51 @@ export async function runShell(ctx, program) {
73
78
  c.dim(" to switch"));
74
79
  }
75
80
  line();
81
+ try {
82
+ const availability = await syncChatAvailability(ctx, client);
83
+ if (ctx.chatType === "carrier" && availability.carrier_chat_maintenance)
84
+ showCarrierMaintenance();
85
+ }
86
+ catch {
87
+ ctx.carrierMaintenance = null;
88
+ line(" " + c.warn("⚠") + " " + c.dim("Carrier Chat status is unavailable. Sending will wait until it can be checked."));
89
+ }
90
+ // Keep the locked composer in sync while the shell sits open. The server
91
+ // remains the authority at send time; this poll only updates presentation.
92
+ let pollingAvailability = false;
93
+ const availabilityTimer = setInterval(() => {
94
+ if (pollingAvailability)
95
+ return;
96
+ pollingAvailability = true;
97
+ const previous = ctx.carrierMaintenance;
98
+ void syncChatAvailability(ctx, client).then((state) => {
99
+ if (ctx.chatType !== "carrier" || previous === state.carrier_chat_maintenance)
100
+ return;
101
+ if (state.carrier_chat_maintenance)
102
+ showCarrierMaintenance();
103
+ else
104
+ line(" " + c.warn("⚠") + " " + c.dim("Carrier Chat is available again."));
105
+ }).catch(() => {
106
+ ctx.carrierMaintenance = null;
107
+ }).finally(() => { pollingAvailability = false; });
108
+ }, 10_000);
109
+ availabilityTimer.unref();
110
+ // Restarted into a remembered conversation with earlier coding work: show
111
+ // what was being done, as context only. No approval, mutation or command is
112
+ // restored — anything still needed is proposed and approved again.
113
+ await showTaskContext(client, ctx.config.get("sessionId"));
76
114
  // Refresh for NEXT launch, once a day, after the shell is already usable.
77
115
  // setImmediate keeps the blocking npm call off the startup path; a failure is
78
116
  // recorded and never shown.
79
117
  if (shouldRefreshCheck(ctx.config)) {
80
118
  setImmediate(() => {
81
119
  try {
82
- refreshUpdateCache(ctx.config);
120
+ // The installed .exe has no npm: it reads the release manifest instead,
121
+ // asynchronously, so it never blocks the composer.
122
+ if (isPackaged())
123
+ void refreshPackagedUpdateCache(ctx.config).catch(() => undefined);
124
+ else
125
+ refreshUpdateCache(ctx.config);
83
126
  }
84
127
  catch {
85
128
  /* never let an update check affect the session */
@@ -146,23 +189,42 @@ export async function runShell(ctx, program) {
146
189
  };
147
190
  // Leaving the shell: restore cooked mode + a visible cursor (the reader keeps
148
191
  // raw mode on for the session), then print the farewell.
192
+ //
193
+ // Leaving must also let the process END. A turn still running (a /exit typed
194
+ // while a reply streams, or a queued message) is cancelled through its own
195
+ // existing signal, so the stream, any command review and the coordinators'
196
+ // cleanup all run on the normal cancellation path. Then stdin is released:
197
+ // the composer resumed it for the whole session, and a flowing TTY stream
198
+ // keeps Node's event loop alive forever — the cause of `cos` lingering after
199
+ // "See you soon" with the terminal still owned by it.
149
200
  const leave = () => {
201
+ clearInterval(availabilityTimer);
202
+ queued = null;
203
+ cancelMainTurn();
150
204
  stopScreen(); // drop the pinned composer + scroll region before the farewell
151
205
  if (process.stdin.isTTY)
152
206
  process.stdin.setRawMode(false);
153
- process.stdout.write("\x1b[?25h");
207
+ if (process.stdout.isTTY && process.env.TERM !== "dumb")
208
+ process.stdout.write("\x1b[?25h");
154
209
  renderExit(ctx.config.get("sessionId"));
210
+ process.stdin.removeAllListeners("keypress");
211
+ process.stdin.removeAllListeners("data");
212
+ process.stdin.pause();
155
213
  };
156
214
  for (;;) {
157
- const placeholder = conversationStarted ? COMPACT_PLACEHOLDER : WELCOME_PLACEHOLDER;
215
+ const placeholder = ctx.chatType === "carrier" && ctx.carrierMaintenance !== false
216
+ ? ctx.carrierMaintenance === true
217
+ ? "Carrier Chat is under maintenance · /switch standard"
218
+ : "Carrier Chat status unavailable · /switch standard"
219
+ : conversationStarted ? COMPACT_PLACEHOLDER : WELCOME_PLACEHOLDER;
158
220
  // One Ctrl+C swaps the status footer for a dim "again to exit" hint beneath
159
221
  // the bar (no separate info line); a second Ctrl+C quits.
160
- const footer = sigintArmed ? " " + c.dim("Press Ctrl-C again to exit") : buildFooter(ctx);
222
+ const footer = () => sigintArmed ? " " + c.dim("Press Ctrl-C again to exit") : buildFooter(ctx);
161
223
  // Keep the palette in step with the chat type — /switch mid-session must
162
224
  // add or remove the commands that only apply to one experience (e.g. /fast
163
225
  // is Standard-only), the same way the web shows or hides its toggles.
164
226
  setCommandScope(ctx.chatType);
165
- const res = await readCommand(CARET, history, footer, placeholder);
227
+ const res = await readCommand(CARET, history, footer, placeholder, () => ctx.chatType === "carrier" && ctx.carrierMaintenance !== false);
166
228
  if (res.type === "exit") {
167
229
  leave();
168
230
  return;
@@ -0,0 +1,40 @@
1
+ import { repositoryContext, repositoryState } from "../services/task-context.js";
2
+ import { renderTaskContextCard } from "../ui/task-context-card.js";
3
+ import { line } from "../services/output.js";
4
+ /** This conversation's Task Context, or null; never delays the caller by more than a moment. */
5
+ export async function fetchTaskContext(client, sessionId) {
6
+ if (typeof client.taskContext !== "function")
7
+ return null;
8
+ let timer;
9
+ try {
10
+ return await Promise.race([
11
+ client.taskContext(sessionId).catch(() => null),
12
+ new Promise((resolve) => { timer = setTimeout(() => resolve(null), 2500); timer.unref?.(); })
13
+ ]);
14
+ }
15
+ finally {
16
+ clearTimeout(timer);
17
+ }
18
+ }
19
+ /**
20
+ * Show the TASK CONTEXT card for a conversation that has recorded coding work
21
+ * — on resume, and when the shell restarts into a remembered session. Context
22
+ * only: it restores nothing that could write a file or run a command.
23
+ */
24
+ export async function showTaskContext(client, sessionId) {
25
+ if (!sessionId)
26
+ return false;
27
+ const context = await fetchTaskContext(client, sessionId);
28
+ if (!context?.current)
29
+ return false;
30
+ const scope = client.mutationRecoveryScope();
31
+ // Verify, before anything is shown as continuing: the repository this CLI is
32
+ // in now, and whether it is the one the earlier work used; file freshness for
33
+ // the files that work touched.
34
+ const repo = repositoryContext(scope, sessionId);
35
+ const state = repo?.same_repository === false ? [] : repositoryState(scope, sessionId);
36
+ for (const l of renderTaskContextCard(context, state, repo))
37
+ line(l);
38
+ line();
39
+ return true;
40
+ }
@@ -0,0 +1,111 @@
1
+ import { c } from "./colors.js";
2
+ import { MARGIN, contentWidth, visibleWidth } from "./composer-layout.js";
3
+ import { clip, stripControl, wrapText } from "./conversation.js";
4
+ /**
5
+ * Small, shared building blocks for the coding-agent cards: a titled section,
6
+ * a labelled field, the approval card and the one-line workflow status track.
7
+ *
8
+ * Presentation only. Every value shown comes from an existing source of truth
9
+ * — the CodingWorkflow snapshot, the mutation plan the MutationCoordinator
10
+ * reviews, the command PolicyDecision, the recorded results. Nothing here
11
+ * decides, approves, or keeps state of its own. Layout adapts to the terminal
12
+ * width (no fixed widths), wraps rather than clips anything a decision depends
13
+ * on, and reads the same without color.
14
+ */
15
+ export const INDENT = MARGIN + " ";
16
+ const safe = stripControl;
17
+ /** Width a card's text may use at the current terminal width. */
18
+ export const cardWidth = () => Math.max(20, contentWidth() - INDENT.length - 1);
19
+ /** A divider sized to the terminal, never wider than a comfortable card. */
20
+ export const rule = () => MARGIN + c.dim("─".repeat(Math.max(8, Math.min(contentWidth() - 1, 48))));
21
+ /** `TITLE` and its divider. `right` is optional, shown when it fits. */
22
+ export function cardHeader(title, paint = c.title, right = "") {
23
+ const head = paint(title);
24
+ const room = contentWidth() - 1 - visibleWidth(title) - 2;
25
+ const tail = right && visibleWidth(right) <= room ? " ".repeat(Math.max(2, room - visibleWidth(right) + 2)) + right : "";
26
+ return ["", MARGIN + head + tail, rule()];
27
+ }
28
+ /** `Label` on its own line, the value(s) indented beneath — the card's field shape. */
29
+ export function cardField(label, values, paint = c.value) {
30
+ const list = (Array.isArray(values) ? values : [values]).filter((v) => v !== undefined && v !== null && String(v).trim() !== "");
31
+ if (!list.length)
32
+ return [];
33
+ const out = [MARGIN + c.dim(label)];
34
+ for (const value of list)
35
+ for (const line of wrapText(safe(String(value)), cardWidth()))
36
+ out.push(INDENT + paint(line));
37
+ return out;
38
+ }
39
+ /** One `Label value` line, for compact metadata (clipped only when it is metadata). */
40
+ export function metaLine(label, value) {
41
+ return MARGIN + c.dim(label + " ") + c.value(clip(safe(value), Math.max(8, cardWidth() - label.length)));
42
+ }
43
+ /**
44
+ * What is waiting for the person, with the keys that answer it. The keys are
45
+ * the existing approval contract (y/Y + Enter approves; n, Enter, Esc decline;
46
+ * Ctrl+C stops the turn) — this card only names them; the prompt below it is
47
+ * still the one that reads them.
48
+ */
49
+ export function approvalCard(kind, detail, operationIds) {
50
+ const verb = kind === "command" ? "Approve command" : kind === "correction" ? "Approve correction" : "Approve change";
51
+ const out = [""];
52
+ // The approval state leads the line, so what is pending is never ambiguous.
53
+ for (const [i, line] of wrapText(`Awaiting approval — ${safe(detail)}`, cardWidth()).entries()) {
54
+ out.push(MARGIN + (i === 0 && line.startsWith("Awaiting approval") ? c.warn("Awaiting approval") + c.dim(line.slice("Awaiting approval".length)) : c.dim(line)));
55
+ }
56
+ out.push(MARGIN + c.key("[ y ]") + " " + c.value(verb) + " " + c.key("[ n ]") + " " + c.value("Reject"));
57
+ if (operationIds.length) {
58
+ const label = operationIds.length === 1 ? "Operation: " : "Operations: ";
59
+ for (const line of wrapText(label + operationIds.join(", "), cardWidth()))
60
+ out.push(MARGIN + c.dim(line));
61
+ }
62
+ return out;
63
+ }
64
+ // ── Status track ─────────────────────────────────────────────────────────────
65
+ // A projection of the EXISTING CodingWorkflow state (snapshot.state) onto the
66
+ // stages a person thinks in. It is not a second state machine: it holds no
67
+ // state, and every stage it shows is derived from the snapshot it is given.
68
+ const STAGES = ["Investigate", "Plan", "Review", "Apply", "Test", "Done"];
69
+ const STAGE_OF = {
70
+ TASK_RECEIVED: 0, INSPECTING: 0,
71
+ PLANNING: 1, CAPABILITY_CHECK: 1, READING: 1,
72
+ PROPOSING: 2, AWAITING_APPROVAL: 2, CORRECTIVE_PROPOSAL: 2, CORRECTIVE_APPROVAL: 2,
73
+ APPLYING: 3, REAPPLYING: 3,
74
+ TESTING: 4, RETESTING: 4, ANALYZING_FAILURE: 4,
75
+ COMPLETED: 5
76
+ };
77
+ /**
78
+ * `✓ Investigate › ✓ Plan › ● Review › ○ Apply › ○ Test › ○ Done`.
79
+ * `lastActive` is the stage the workflow was in before it stopped (the caller
80
+ * passes the last state it saw), so a stop is marked where it happened.
81
+ */
82
+ export function statusTrack(snapshot, lastActive) {
83
+ const state = String(snapshot.state ?? "");
84
+ const corrections = Number(snapshot.corrections) || 0;
85
+ const stopped = ["FAILED", "CANCELLED", "UNRESOLVED"].includes(state);
86
+ const at = stopped ? STAGE_OF[lastActive ?? ""] ?? 0 : STAGE_OF[state] ?? 0;
87
+ const done = state === "COMPLETED";
88
+ const marks = STAGES.map((name, i) => {
89
+ let label = name;
90
+ if (i === 4 && state === "ANALYZING_FAILURE")
91
+ return c.err("✕") + " " + c.dim("Test") + c.dim(" › ") + c.warn("●") + " " + c.value("Analyze");
92
+ if (done || i < at)
93
+ return c.ok("✓") + " " + c.dim(label);
94
+ if (i === at) {
95
+ if (stopped)
96
+ return (state === "CANCELLED" ? c.warn("⊘") : c.err("✕")) + " " + c.value(label);
97
+ if (i === 5)
98
+ label = "Done";
99
+ return c.warn("●") + " " + c.value(label);
100
+ }
101
+ return c.dim("○ " + label);
102
+ });
103
+ const suffix = corrections ? c.dim(` · correction ${corrections}`) : "";
104
+ const full = marks.join(c.dim(" › ")) + suffix;
105
+ if (visibleWidth(full) <= contentWidth() - 1)
106
+ return MARGIN + full;
107
+ // Narrow terminal: the current stage and progress, nothing secondary.
108
+ const current = done ? "Done" : STAGES[Math.min(at, 5)];
109
+ const icon = done ? c.ok("✓") : stopped ? c.err("✕") : c.warn("●");
110
+ return MARGIN + icon + " " + c.value(current) + c.dim(` · ${done ? 6 : at + 1}/6`) + suffix;
111
+ }
@@ -0,0 +1,131 @@
1
+ import path from 'node:path';
2
+ import { c } from './colors.js';
3
+ import { MARGIN, contentWidth } from './composer-layout.js';
4
+ import { clip, stripControl, wrapText } from './conversation.js';
5
+ import { INDENT, cardField, cardHeader, cardWidth } from './agent-cards.js';
6
+ import { displayCommand } from '../services/command-policy.js';
7
+ export const ACTIVITY = {
8
+ IDLE: 'Ready', THINKING: 'Thinking', INSPECTING: 'Inspecting repository', SEARCHING: 'Searching repository', READING: 'Reading files', PLANNING: 'Creating plan', PROPOSAL_READY: 'Change proposed', WAITING_FOR_MUTATION_APPROVAL: 'Waiting for change approval', APPLYING: 'Applying changes', VALIDATION_PENDING: 'Validation pending', WAITING_FOR_COMMAND_APPROVAL: 'Waiting for command approval', RUNNING_COMMAND: 'Running command', ANALYZING_FAILURE: 'Analyzing failure', CORRECTION_PROPOSED: 'Correction proposed', WAITING_FOR_CORRECTION_APPROVAL: 'Waiting for correction approval', RETESTING: 'Retesting', COMPLETED: 'Completed', FAILED: 'Failed', CANCELLED: 'Cancelled', UNRESOLVED: 'Unresolved'
9
+ };
10
+ export function workflowActivity(snapshot) {
11
+ const state = String(snapshot.state), correction = Number(snapshot.corrections) > 0;
12
+ if (state === 'COMPLETED')
13
+ return 'Validation passed · awaiting completion';
14
+ if (state === 'READING')
15
+ return correction ? 'Preparing correction' : 'Preparing changes';
16
+ if (state === 'APPLYING' || state === 'REAPPLYING') {
17
+ const validation = snapshot.validation;
18
+ if (validation?.some(v => v.status === 'PENDING_REVIEW'))
19
+ return correction ? 'Retest required' : 'Validation pending';
20
+ return correction ? 'Applying correction' : 'Applying changes';
21
+ }
22
+ const names = { TASK_RECEIVED: 'Thinking', INSPECTING: 'Inspecting repository', PLANNING: 'Creating plan', CAPABILITY_CHECK: 'Checking execution capability', READING: correction ? 'Preparing correction' : 'Preparing changes', PROPOSING: 'Change proposed', AWAITING_APPROVAL: 'Waiting for change approval', APPLYING: correction ? 'Applying correction' : 'Applying changes', TESTING: 'Running validation', ANALYZING_FAILURE: 'Analyzing failure', CORRECTIVE_PROPOSAL: 'Correction proposed', CORRECTIVE_APPROVAL: 'Waiting for correction approval', REAPPLYING: 'Applying correction', RETESTING: 'Retesting', COMPLETED: 'Completed', FAILED: 'Failed', CANCELLED: 'Cancelled', UNRESOLVED: 'Unresolved' };
23
+ return names[state] ?? 'Working';
24
+ }
25
+ const commandLabel = (t) => typeof t.program === 'string' ? `${displayCommand(t.program, Array.isArray(t.args) ? t.args.map(String) : [])}${t.cwd && t.cwd !== '.' ? ` · ${t.cwd}` : ''}` : '';
26
+ /** The recorded analysis text, from the workflow's own "Failure analysis (…): …" line. */
27
+ export function analysisExplanation(lines) {
28
+ const m = /^Failure analysis \(([^)]+)\):\s*([\s\S]*)$/.exec(stripControl(lines.join(' ')));
29
+ return { classification: m?.[1] ?? 'recorded', explanation: m?.[2] ?? stripControl(lines.join(' ')) };
30
+ }
31
+ /**
32
+ * The PLAN card: the workflow's own structured plan (snapshot.plan), not a copy.
33
+ * "Root cause" appears only where the workflow recorded one — the failure
34
+ * analysis behind a corrective plan. An initial plan has no such field, so it
35
+ * shows the planned expected behavior instead of inventing a cause.
36
+ */
37
+ export function renderAgentPlan(snapshot, opts = {}) {
38
+ const plan = snapshot.plan;
39
+ if (!plan)
40
+ return [];
41
+ const corrective = Number(snapshot.corrections) > 0;
42
+ const rows = [...cardHeader(corrective ? 'CORRECTIVE PLAN' : 'PLAN', c.title)];
43
+ rows.push(...cardField('Task', clip(stripControl(plan.summary), 240)));
44
+ const inv = plan.investigation;
45
+ if (corrective && opts.rootCause)
46
+ rows.push(...cardField('Root cause', clip(stripControl(opts.rootCause), 240)));
47
+ else if (inv) {
48
+ // The investigation the workflow verified, symptom first: where it shows, why, where to change.
49
+ rows.push(...cardField('Symptom', clip(stripControl(inv.symptom), 200), c.dim));
50
+ rows.push(...cardField('Path', inv.execution_path.slice(0, 8).map(s => s.symbol ? `${s.path} · ${s.symbol}` : s.path), c.file));
51
+ rows.push(...cardField('Root cause', clip(stripControl(inv.root_cause), 240)));
52
+ rows.push(...cardField('Change at', `${inv.change_location.path}${inv.change_location.symbol ? ` · ${inv.change_location.symbol}` : ''}`, c.file));
53
+ if (inv.evidence?.length)
54
+ rows.push(...cardField('Evidence', inv.evidence.slice(0, 4).map(e => clip(stripControl(`${e.path}${e.lines ? `:${e.lines}` : ''} — ${e.note}`), 160)), c.dim));
55
+ if (inv.ruled_out?.length)
56
+ rows.push(...cardField('Ruled out', inv.ruled_out.slice(0, 4).map(r => clip(stripControl(`${r.path} — ${r.reason}`), 160)), c.dim));
57
+ }
58
+ else if (plan.expected)
59
+ rows.push(...cardField('Expected', clip(stripControl(plan.expected), 200), c.dim));
60
+ rows.push(...cardField('Files', plan.files.slice(0, 8).map(f => f.path), c.file));
61
+ if (plan.files.length > 8)
62
+ rows.push(INDENT + c.dim(`+${plan.files.length - 8} more planned files`));
63
+ rows.push(...cardField('Validation', plan.tests.slice(0, 3).map(t => commandLabel(t)).filter(Boolean)));
64
+ if (plan.risks)
65
+ rows.push(...cardField('Risk', clip(stripControl(plan.risks), 160), c.dim));
66
+ rows.push('');
67
+ return rows;
68
+ }
69
+ /**
70
+ * The analysis the workflow recorded after a failed validation — classification
71
+ * and the stated evidence, as recorded by coding_workflow(analyze). It is the
72
+ * tool's input, shown as an operational record, not hidden reasoning.
73
+ */
74
+ export function renderFailureAnalysis(lines) {
75
+ const { classification, explanation } = analysisExplanation(lines);
76
+ const out = ['', MARGIN + c.title('Analyzing failure…'), MARGIN + ' ' + c.ok('✓ ') + c.value('Failure evidence captured') + c.dim(` · ${classification}`)];
77
+ for (const line of wrapText(explanation, cardWidth() - 2))
78
+ out.push(INDENT + ' ' + c.dim(line));
79
+ out.push(MARGIN + c.dim('Fresh reads and a new plan come next; any correction needs its own approval.'), '');
80
+ return out;
81
+ }
82
+ /** Called only after the shell's existing interrupt/acknowledged-finish guard. */
83
+ export function renderAgentOutcome(snapshot, ctx = {}) {
84
+ if (!snapshot.plan)
85
+ return [];
86
+ const plan = snapshot.plan;
87
+ const state = String(snapshot.state), files = Array.isArray(snapshot.files) ? snapshot.files.map(String) : [];
88
+ const validation = (snapshot.validation ?? []);
89
+ const corrections = Number(snapshot.corrections) || 0;
90
+ const applied = ctx.applied ?? [];
91
+ // A person's "no" is a decision, not a failure (the workflow still records
92
+ // FAILED), and an invalidated change is a safety stop. Each already has its
93
+ // own card at the moment it happened (CHANGE REJECTED / CHANGE INVALIDATED),
94
+ // so the turn ends there — no second card, and never "Failed".
95
+ if (ctx.declined && applied.length === 0)
96
+ return [];
97
+ const changed = files.length ? files : [...new Set(applied.map(a => a.rel))];
98
+ const commands = validation.map(t => commandLabel(t) + (t.status ? ` — ${t.status === 'PASSED' ? 'passed' : t.status === 'FAILED' ? 'failed' : 'not completed'}` : '')).filter(Boolean);
99
+ if (state === 'COMPLETED') {
100
+ // The validation counts arrive as "3 passed · 0 failed"; one fact per line.
101
+ const counts = (ctx.validationCounts ?? '').split(' · ').filter(Boolean);
102
+ const changes = `${changed.length} file${changed.length === 1 ? '' : 's'} modified${applied.length > changed.length ? ` · ${applied.length} approved changes` : ''}`;
103
+ return [...cardHeader('✓ COMPLETED', c.ok),
104
+ ...cardField('Task', clip(stripControl(ctx.task ?? plan.summary), 200)),
105
+ ...cardField('Changes', changes),
106
+ ...cardField('Validation', [...validation.map(commandLabel).filter(Boolean), ...counts]),
107
+ ...cardField('Corrections', String(corrections)),
108
+ ...cardField('Files modified', changed.slice(0, 8), c.file),
109
+ ...(changed.length > 8 ? [INDENT + c.dim(`+${changed.length - 8} more`)] : []),
110
+ ...cardField('Operation IDs', applied.map(a => a.operationId), c.dim),
111
+ '', MARGIN + c.ok('✓ ') + c.value(validation.length && validation.every(v => v.status === 'PASSED') ? 'The issue has been fixed and verified.' : 'The task completed.'), ''];
112
+ }
113
+ const title = state === 'CANCELLED' ? '⊘ CANCELLED' : state === 'FAILED' ? '✗ FAILED' : '! UNRESOLVED';
114
+ const reason = state === 'CANCELLED' ? 'The turn stopped. Review retained changes before continuing.' : state === 'FAILED' ? 'The workflow stopped. Review the step above, then start a new task.' : 'Required validation or acknowledgment is incomplete. Nothing resumes automatically.';
115
+ return [...cardHeader(title, state === 'CANCELLED' ? c.warn : c.err), ...wrapText(reason, cardWidth()).map(l => MARGIN + c.dim(l)),
116
+ ...cardField('Applied', applied.map(a => `${a.rel} · +${a.added} −${a.removed} · ${a.operationId}`), c.file),
117
+ ...cardField('Validation', commands), ''];
118
+ }
119
+ export function toolActivity(name, args, root) {
120
+ // A search is named by what it looks for; its directory only narrows it.
121
+ if (name === 'search_files' && typeof args.query === 'string')
122
+ return clip(`Searching ${stripControl(args.query)}${typeof args.path === 'string' && args.path ? ` in ${stripControl(args.path)}` : ''}`, contentWidth() - 6);
123
+ if (name === 'find_symbol' && typeof args.name === 'string')
124
+ return clip(`Finding definition ${stripControl(args.name)}`, contentWidth() - 6);
125
+ if (name === 'find_references' && typeof args.name === 'string')
126
+ return clip(`Finding usages ${stripControl(args.name)}`, contentWidth() - 6);
127
+ const raw = String(args.path ?? args.query ?? args.pattern ?? args.reference ?? args.revision ?? '');
128
+ const value = path.isAbsolute(raw) && !path.relative(root, raw).startsWith('..') ? path.relative(root, raw) : raw;
129
+ const labels = { read_file: 'Reading', search_files: 'Searching', list_files: 'Inspecting repository', find_files: 'Finding files', git_log: 'Reading history', git_blame: 'Reading blame', git_show: 'Reading commit', git_status: 'Inspecting repository', git_diff: 'Inspecting changes', resolve_local_file: 'Finding file', code_outline: 'Outlining', coding_workflow: args.action === 'analyze' ? 'Analyzing failure' : args.action === 'plan' ? 'Creating plan' : 'Checking workflow', run_command: 'Preparing command', edit_file: 'Preparing change', write_file: 'Preparing change', create_file: 'Preparing change', delete_file: 'Preparing deletion', revert_change: 'Preparing revert' };
130
+ return clip(`${labels[name] ?? 'Inspecting'}${value ? ' ' + stripControl(value) : ''}`, contentWidth() - 6);
131
+ }