@carrieros/cli 0.3.0 → 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 (89) hide show
  1. package/README.md +89 -15
  2. package/dist/commands/chat.js +6 -6
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +34 -14
  5. package/dist/commands/logout.js +2 -0
  6. package/dist/commands/permissions.js +78 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +83 -10
  10. package/dist/commands/update.js +177 -51
  11. package/dist/commands/usage.js +10 -8
  12. package/dist/commands/version.js +1 -3
  13. package/dist/commands/whoami.js +12 -9
  14. package/dist/ide/editor-context.js +115 -12
  15. package/dist/ide/ide-session.js +288 -18
  16. package/dist/ide/tool-host.js +6 -6
  17. package/dist/main.js +10 -1
  18. package/dist/services/api.js +183 -15
  19. package/dist/services/auth-origin.js +20 -0
  20. package/dist/services/auto-update.js +221 -0
  21. package/dist/services/chat-stream.js +26 -3
  22. package/dist/services/checkpoints.js +176 -14
  23. package/dist/services/client-tools.js +123 -27
  24. package/dist/services/code-intel.js +243 -0
  25. package/dist/services/code-symbols.js +94 -0
  26. package/dist/services/coding-workflow.js +554 -0
  27. package/dist/services/command-coordinator.js +85 -12
  28. package/dist/services/command-policy.js +34 -4
  29. package/dist/services/config.js +96 -11
  30. package/dist/services/container-runner.js +254 -0
  31. package/dist/services/container-supervisor.js +38 -0
  32. package/dist/services/context.js +98 -25
  33. package/dist/services/device-auth.js +33 -6
  34. package/dist/services/execution-platform.js +30 -0
  35. package/dist/services/file-resolver.js +1 -1
  36. package/dist/services/folder-key.js +22 -0
  37. package/dist/services/git-tools.js +181 -0
  38. package/dist/services/helper-bin.js +56 -35
  39. package/dist/services/instruction-resolver.js +54 -0
  40. package/dist/services/job-helper.js +31 -10
  41. package/dist/services/local-files.js +148 -26
  42. package/dist/services/local-tools.js +540 -35
  43. package/dist/services/login-flow.js +44 -13
  44. package/dist/services/meta.js +27 -0
  45. package/dist/services/mutation-coordinator.js +186 -20
  46. package/dist/services/mutation-groups.js +309 -0
  47. package/dist/services/mutation-recovery.js +159 -0
  48. package/dist/services/mutations.js +264 -78
  49. package/dist/services/packaged-update.js +403 -0
  50. package/dist/services/packaged.js +15 -0
  51. package/dist/services/permission-mode.js +78 -0
  52. package/dist/services/process-runner.js +7 -1
  53. package/dist/services/project-context.js +4 -4
  54. package/dist/services/result-reconciliation.js +49 -0
  55. package/dist/services/secure-store.js +21 -1
  56. package/dist/services/session-resolver.js +7 -0
  57. package/dist/services/supported-runtime.js +59 -0
  58. package/dist/services/task-context.js +212 -0
  59. package/dist/services/task-snapshot.js +38 -0
  60. package/dist/services/tool-result-outbox.js +195 -0
  61. package/dist/services/update.js +457 -13
  62. package/dist/services/workspace-registry.js +4 -3
  63. package/dist/services/workspace.js +8 -1
  64. package/dist/shell/shell-chat.js +320 -34
  65. package/dist/shell/shell-commands.js +47 -5
  66. package/dist/shell/shell-prompt.js +21 -11
  67. package/dist/shell/shell-renderer.js +1 -1
  68. package/dist/shell/shell.js +107 -20
  69. package/dist/shell/task-context-view.js +40 -0
  70. package/dist/ui/agent-cards.js +111 -0
  71. package/dist/ui/agent-presentation.js +131 -0
  72. package/dist/ui/approval.js +46 -16
  73. package/dist/ui/banner.js +31 -87
  74. package/dist/ui/change-review.js +293 -46
  75. package/dist/ui/chat-renderer.js +6 -6
  76. package/dist/ui/colors.js +9 -9
  77. package/dist/ui/command-details.js +11 -0
  78. package/dist/ui/command-palette.js +27 -10
  79. package/dist/ui/command-registry.js +11 -4
  80. package/dist/ui/command-review.js +77 -28
  81. package/dist/ui/composer-layout.js +26 -20
  82. package/dist/ui/conversation.js +77 -25
  83. package/dist/ui/live.js +1 -1
  84. package/dist/ui/screen.js +19 -11
  85. package/dist/ui/select.js +6 -0
  86. package/dist/ui/task-context-card.js +99 -0
  87. package/dist/ui/trust.js +7 -12
  88. package/dist/ui/ui.js +23 -0
  89. package/package.json +9 -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":
@@ -162,7 +188,7 @@ export async function handleSlash(ctx, program, client, input) {
162
188
  return STAY;
163
189
  // One command: checks, and offers to install when something newer exists.
164
190
  case "update":
165
- await runUpdate();
191
+ await runUpdate({ config: ctx.config, busy: ctx.mainTurnRunning === true });
166
192
  return STAY;
167
193
  case "sources":
168
194
  showSources(ctx);
@@ -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";
@@ -11,8 +14,9 @@ import { setCommandScope } from "../ui/command-item.js";
11
14
  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
- import { cachedUpdateNotice, refreshUpdateCache, shouldRefreshCheck } from "../services/update.js";
15
- import { chatTypeLabel, loadModels, loadModes } from "./shell-chat.js";
17
+ import { cachedUpdateNotice, shouldRefreshCheck } from "../services/update.js";
18
+ import { AutoUpdater } from "../services/auto-update.js";
19
+ import { chatTypeLabel, loadModels, loadModes, showCarrierMaintenance, syncChatAvailability, loadFastModel } from "./shell-chat.js";
16
20
  import { CARET, buildFooter } from "./shell-prompt.js";
17
21
  import { dispatchLine, isMainTurn } from "./shell-router.js";
18
22
  import { printWelcome, renderWelcomeBack } from "./shell-renderer.js";
@@ -39,6 +43,8 @@ export async function runShell(ctx, program) {
39
43
  return; // user chose /exit or Ctrl+C
40
44
  }
41
45
  const client = ctx.requireAuth();
46
+ await client.recoverToolResults();
47
+ await client.reportCodingTaskRecovery();
42
48
  // Mark that we're inside the interactive shell — commands (e.g. upload) use
43
49
  // this to prompt interactively here vs. print finish-and-return output when
44
50
  // run standalone (cos upload).
@@ -48,7 +54,7 @@ export async function runShell(ctx, program) {
48
54
  // General here would override that and strand Standard users in General.
49
55
  // Preload the mode + model lists so the prompt/banner can show friendly labels
50
56
  // (e.g. the "Carrier OS" mode name rather than the raw id).
51
- await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => [])]);
57
+ await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => []), loadFastModel(client)]);
52
58
  // Enter TUI mode: pin the composer to the bottom of the terminal and give the
53
59
  // transcript its own scrolling region above it (Claude-style). From here, all
54
60
  // output flows into the transcript via the screen engine.
@@ -60,7 +66,9 @@ export async function runShell(ctx, program) {
60
66
  // startScreen() has since switched to the alternate buffer, which hides them.
61
67
  // Update notice comes from the PREVIOUS check — reading the cache is a
62
68
  // property lookup, so the banner is never waiting on npm.
63
- const notice = cachedUpdateNotice(ctx.config);
69
+ // The installed .exe keeps its banner notice; npm installs are announced by
70
+ // the AutoUpdater instead, once per version, between turns.
71
+ const notice = isPackaged() ? cachedUpdateNotice(ctx.config) : null;
64
72
  renderWelcomeBanner(ctx, notice ? { notices: [notice] } : undefined);
65
73
  if (inWorkspaceMode()) {
66
74
  line(" " +
@@ -73,18 +81,66 @@ export async function runShell(ctx, program) {
73
81
  c.dim(" to switch"));
74
82
  }
75
83
  line();
76
- // Refresh for NEXT launch, once a day, after the shell is already usable.
77
- // setImmediate keeps the blocking npm call off the startup path; a failure is
78
- // recorded and never shown.
79
- if (shouldRefreshCheck(ctx.config)) {
80
- setImmediate(() => {
81
- try {
82
- refreshUpdateCache(ctx.config);
83
- }
84
- catch {
85
- /* never let an update check affect the session */
86
- }
87
- });
84
+ try {
85
+ const availability = await syncChatAvailability(ctx, client);
86
+ if (ctx.chatType === "carrier" && availability.carrier_chat_maintenance)
87
+ showCarrierMaintenance();
88
+ }
89
+ catch {
90
+ ctx.carrierMaintenance = null;
91
+ line(" " + c.warn("⚠") + " " + c.dim("Carrier Chat status is unavailable. Sending will wait until it can be checked."));
92
+ }
93
+ // Keep the locked composer in sync while the shell sits open. The server
94
+ // remains the authority at send time; this poll only updates presentation.
95
+ let pollingAvailability = false;
96
+ const availabilityTimer = setInterval(() => {
97
+ if (pollingAvailability)
98
+ return;
99
+ pollingAvailability = true;
100
+ const previous = ctx.carrierMaintenance;
101
+ void syncChatAvailability(ctx, client).then((state) => {
102
+ if (ctx.chatType !== "carrier" || previous === state.carrier_chat_maintenance)
103
+ return;
104
+ if (state.carrier_chat_maintenance)
105
+ showCarrierMaintenance();
106
+ else
107
+ line(" " + c.warn("⚠") + " " + c.dim("Carrier Chat is available again."));
108
+ }).catch(() => {
109
+ ctx.carrierMaintenance = null;
110
+ }).finally(() => { pollingAvailability = false; });
111
+ }, 10_000);
112
+ availabilityTimer.unref();
113
+ // Restarted into a remembered conversation with earlier coding work: show
114
+ // what was being done, as context only. No approval, mutation or command is
115
+ // restored — anything still needed is proposed and approved again.
116
+ await showTaskContext(client, ctx.config.get("sessionId"));
117
+ // Update notices wait until no turn is running, so a check that finishes
118
+ // mid-answer never prints into the middle of it.
119
+ const updateNotices = [];
120
+ let mainRunningForNotices = () => false;
121
+ const flushUpdateNotices = () => {
122
+ if (mainRunningForNotices())
123
+ return;
124
+ while (updateNotices.length)
125
+ line(" " + c.dim("ⓘ " + updateNotices.shift()));
126
+ };
127
+ // The installed .exe has no npm: it reads the release manifest, once a day,
128
+ // asynchronously. npm installs use the AutoUpdater: an async check at startup
129
+ // (when due) and on its interval, and a background install on exit.
130
+ let autoUpdater = null;
131
+ if (isPackaged()) {
132
+ if (shouldRefreshCheck(ctx.config)) {
133
+ setImmediate(() => void refreshPackagedUpdateCache(ctx.config).catch(() => undefined));
134
+ }
135
+ }
136
+ else {
137
+ try {
138
+ autoUpdater = new AutoUpdater({ config: ctx.config, dir: ctx.config.dir, notify: (m) => { updateNotices.push(m); flushUpdateNotices(); } });
139
+ autoUpdater.start();
140
+ }
141
+ catch {
142
+ autoUpdater = null; /* never let updates affect the session */
143
+ }
88
144
  }
89
145
  // Interactive loop driven by the composer/reader. Each iteration reads one
90
146
  // line (with the slash palette overlay, the dim status footer, and a
@@ -104,6 +160,7 @@ export async function runShell(ctx, program) {
104
160
  let mainTask = null;
105
161
  let mainAbort = null;
106
162
  const mainRunning = () => mainTask !== null;
163
+ mainRunningForNotices = mainRunning;
107
164
  /**
108
165
  * One message typed while a turn is still answering.
109
166
  *
@@ -129,6 +186,7 @@ export async function runShell(ctx, program) {
129
186
  mainTask = null;
130
187
  mainAbort = null;
131
188
  ctx.mainTurnRunning = false;
189
+ flushUpdateNotices();
132
190
  if (queued !== null) {
133
191
  const next = queued;
134
192
  queued = null;
@@ -146,23 +204,52 @@ export async function runShell(ctx, program) {
146
204
  };
147
205
  // Leaving the shell: restore cooked mode + a visible cursor (the reader keeps
148
206
  // raw mode on for the session), then print the farewell.
207
+ //
208
+ // Leaving must also let the process END. A turn still running (a /exit typed
209
+ // while a reply streams, or a queued message) is cancelled through its own
210
+ // existing signal, so the stream, any command review and the coordinators'
211
+ // cleanup all run on the normal cancellation path. Then stdin is released:
212
+ // the composer resumed it for the whole session, and a flowing TTY stream
213
+ // keeps Node's event loop alive forever — the cause of `cos` lingering after
214
+ // "See you soon" with the terminal still owned by it.
149
215
  const leave = () => {
216
+ clearInterval(availabilityTimer);
217
+ queued = null;
218
+ cancelMainTurn();
150
219
  stopScreen(); // drop the pinned composer + scroll region before the farewell
151
220
  if (process.stdin.isTTY)
152
221
  process.stdin.setRawMode(false);
153
- process.stdout.write("\x1b[?25h");
222
+ if (process.stdout.isTTY && process.env.TERM !== "dumb")
223
+ process.stdout.write("\x1b[?25h");
154
224
  renderExit(ctx.config.get("sessionId"));
225
+ // A release found during the session installs now, detached, after this
226
+ // process (and every other CLI window) has gone.
227
+ try {
228
+ if (autoUpdater?.onExit())
229
+ line(" " + c.dim("Installing CarrierOS CLI " + autoUpdater.pendingVersion + " in the background — it will be ready next time."));
230
+ }
231
+ catch {
232
+ /* never block leaving */
233
+ }
234
+ process.stdin.removeAllListeners("keypress");
235
+ process.stdin.removeAllListeners("data");
236
+ process.stdin.pause();
155
237
  };
156
238
  for (;;) {
157
- const placeholder = conversationStarted ? COMPACT_PLACEHOLDER : WELCOME_PLACEHOLDER;
239
+ flushUpdateNotices();
240
+ const placeholder = ctx.chatType === "carrier" && ctx.carrierMaintenance !== false
241
+ ? ctx.carrierMaintenance === true
242
+ ? "Carrier Chat is under maintenance · /switch standard"
243
+ : "Carrier Chat status unavailable · /switch standard"
244
+ : conversationStarted ? COMPACT_PLACEHOLDER : WELCOME_PLACEHOLDER;
158
245
  // One Ctrl+C swaps the status footer for a dim "again to exit" hint beneath
159
246
  // 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);
247
+ const footer = () => sigintArmed ? " " + c.dim("Press Ctrl-C again to exit") : buildFooter(ctx);
161
248
  // Keep the palette in step with the chat type — /switch mid-session must
162
249
  // add or remove the commands that only apply to one experience (e.g. /fast
163
250
  // is Standard-only), the same way the web shows or hides its toggles.
164
251
  setCommandScope(ctx.chatType);
165
- const res = await readCommand(CARET, history, footer, placeholder);
252
+ const res = await readCommand(CARET, history, footer, placeholder, () => ctx.chatType === "carrier" && ctx.carrierMaintenance !== false);
166
253
  if (res.type === "exit") {
167
254
  leave();
168
255
  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
+ }