@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
package/README.md CHANGED
@@ -34,6 +34,14 @@ npm install -g @carrieros/cli
34
34
  cos # or: carrieros
35
35
  ```
36
36
 
37
+ ### Windows installer (no Node.js needed)
38
+
39
+ Download `CarrierOS-Setup-<version>-x64.exe` from https://carrieros.ai/cli and
40
+ run it. It installs for your user only (no administrator rights), adds `cos` to
41
+ your PATH, and keeps your settings and sign-in in `%APPDATA%\CarrierOS` across
42
+ upgrades. Open a new terminal and run `cos`. Update with `cos update`;
43
+ uninstall from Settings → Apps. Details: [docs/PACKAGING.md](docs/PACKAGING.md).
44
+
37
45
  ### From source
38
46
 
39
47
  Working on the CLI itself, or testing an unreleased change:
@@ -124,8 +132,8 @@ cos login --url http://localhost:5000/v1
124
132
  Confirm the setup:
125
133
 
126
134
  ```bash
127
- cos doctor # config, connectivity, key checks
128
- cos whoami # workspace / project / account
135
+ cos doctor # config, connectivity, session checks
136
+ cos whoami # signed-in account
129
137
  ```
130
138
 
131
139
  ### 2. Open the interactive shell
@@ -245,7 +253,7 @@ cos sessions # list conversations
245
253
  cos history # transcript of the active session
246
254
  cos upload ./report.pdf # upload + index a file
247
255
  cos usage # requests, tokens, estimated cost
248
- cos logout # remove the key from this machine
256
+ cos logout # remove saved CLI credentials from this machine
249
257
  ```
250
258
 
251
259
  ---
@@ -254,11 +262,11 @@ cos logout # remove the key from this machine
254
262
 
255
263
  | Command | Endpoint(s) reused | Purpose |
256
264
  |---|---|---|
257
- | `login [--url] [--platform]` | `POST /platform/auth/device/{code,token}` | Browser device authorization; stores the issued session |
265
+ | `login [--url] [--platform]` | `POST /cli/auth/device/{code,token}` | User-owned browser device authorization; stores the issued CLI session |
258
266
  | `logout` | `POST /platform/auth/cli/logout` | Revoke the session server-side and clear it locally |
259
- | `whoami` | `POST /v1/auth/verify` | Show workspace / project / account |
267
+ | `whoami` | `POST /v1/auth/verify` | Show your signed-in account; `--details` includes API scope |
260
268
  | `version` | `GET /v1/health` | CLI + API versions |
261
- | `doctor` | `GET /v1/health`, `POST /v1/auth/verify` | Config, connectivity, key checks |
269
+ | `doctor` | `GET /v1/health`, `POST /v1/auth/verify` | Config, connectivity, session checks |
262
270
  | *(no command)* | `POST /v1/chat` | **Default** — the interactive Carrier OS shell |
263
271
  | `chat` | `POST /v1/chat` | Focused chat REPL with a persistent session |
264
272
  | `models` | `GET /v1/models/chat` | List provider models (GPT, Grok, Claude, …) |
@@ -327,7 +335,7 @@ src/
327
335
  - **Strong typing.** `strict` TypeScript with `noUnusedLocals/Parameters`; the
328
336
  entire `/v1` contract is typed in `types/index.ts`.
329
337
  - **Windows-first, clean UX.** `chalk` colors, `ora` spinners, `@inquirer/prompts`
330
- for the masked key prompt and session picker, and a small built-in
338
+ for interactive selections and the session picker, and a small built-in
331
339
  Markdown→ANSI renderer (no markdown dependency).
332
340
 
333
341
  Streaming is **simulated**: the API returns the full response, which the CLI
@@ -354,7 +362,7 @@ node dist/main.js version # CLI + API versions
354
362
 
355
363
  # Auth — opens the browser, approve there, the CLI finishes on its own
356
364
  node dist/main.js login --url http://localhost:5000/v1
357
- node dist/main.js whoami # workspace / project / account
365
+ node dist/main.js whoami # signed-in account
358
366
  node dist/main.js doctor # now: ✓ signed in
359
367
 
360
368
  # Chat + sessions
@@ -369,7 +377,7 @@ node dist/main.js upload ./somefile.pdf
369
377
  node dist/main.js files
370
378
  node dist/main.js usage
371
379
 
372
- node dist/main.js logout # key removed from this machine
380
+ node dist/main.js logout # saved CLI credentials removed from this machine
373
381
  ```
374
382
 
375
383
  **Negative checks**
@@ -382,9 +390,22 @@ node dist/main.js login --url http://localhost:1/v1 && node dist/main.js doctor
382
390
 
383
391
  ---
384
392
 
385
- ## Not in scope yet
393
+ ## Scope and current limitations
394
+
395
+ The CLI includes a repository-aware coding workflow. It can inspect a selected
396
+ repository, read files, propose approval-gated edits, and run separately
397
+ approved validation commands through its configured executor. File changes and
398
+ commands remain subject to the repository trust and review gates. This does not
399
+ guarantee that the agent can diagnose or fix every coding task, and a fresh
400
+ end-to-end live-model acceptance is still required for the current release.
401
+
402
+ The CLI does not provide multi-agent orchestration, an SDK, IDE integration,
403
+ plugins, or a marketplace. Native Windows executor acceptance has not yet been
404
+ completed. Browser sign-in and self-update are available through `cos login`
405
+ and `cos update`.
406
+
407
+ ### Advanced API scope
386
408
 
387
- No billing · no marketplace · no plugins · no agents · no SDK · no IDE
388
- integration · no repo awareness · no multi-agent · no `.exe` installers.
409
+ New `cos login` sessions belong directly to your CarrierOS website user and do not require a Developer Platform account, workspace, project, or API key. This checkout includes user-owned consumers for conversations, chat/streaming, files, supported memory reads, tools, models, usage and Admin attribution. These require the corresponding backend ownership migration and updated server; updating the CLI alone does not enable them. Unaudited `/search` and `/prompts` endpoints still return `CLI_USER_SESSION_NOT_ENABLED`. See the backend `docs/architecture/CLI_USER_DEVICE_SESSIONS.md` for verification and deployment limitations. Existing legacy sessions continue using their original validated scope and refresh endpoint; they are not automatically converted.
389
410
 
390
- Browser sign-in and self-update both landed — `cos login` and `cos update`.
411
+ For existing legacy/API credentials only, use `cos whoami --details`, `cos workspace list`, `cos workspace use <name-or-id>`, or `cos project use <name-or-id>` only when you need a different API scope. Switching workspaces automatically selects its default project. These commands do not select a local repository: use `/repo` or `/repos` for that. Local instruction files resolve from the selected repository root. Existing CLI settings remain user-level; API scope selection does not change their location. Project environment labels describe API projects; `CARRIEROS_API_URL` separately selects the backend endpoint.
@@ -5,7 +5,7 @@ import { clearActiveSession, listSessions } from "../services/session-resolver.j
5
5
  import { showContext } from "./context.js";
6
6
  import { showHistory } from "./history.js";
7
7
  import { newSession, pickSession, renderSessionList, switchTo } from "./sessions.js";
8
- import { chatTurn, chatTypeLabelShort, loadModels, loadModes, modeLabelShort, modelLabelShort, armWebSearch, isWebSearchStateArg, openSource, pickChatType, pickMode, pickModel, searchNow, setChatType, setFast, setHighPower, setMode, setModel, setWebSearch, showSources } from "../shell/shell-chat.js";
8
+ import { chatTurn, chatTypeLabelShort, loadModels, loadModes, modeLabelShort, modelLabelShort, armWebSearch, isWebSearchStateArg, openSource, pickChatType, pickMode, pickModel, searchNow, setChatType, setFast, setHighPower, setMode, setModel, setWebSearch, showSources, loadFastModel } from "../shell/shell-chat.js";
9
9
  /**
10
10
  * `cos chat` — a focused interactive REPL over POST /v1/chat. (The full
11
11
  * shell — `cos` with no command — is a superset with every slash command.)
@@ -39,7 +39,7 @@ export function registerChat(program, ctx) {
39
39
  export async function runChat(ctx, initialMessage) {
40
40
  const client = ctx.requireAuth();
41
41
  // Preload modes + models so the banner can show friendly labels (best-effort).
42
- await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => [])]);
42
+ await Promise.all([loadModels(client).catch(() => []), loadModes(client).catch(() => []), loadFastModel(client)]);
43
43
  printBanner(ctx.config.get("scope"), modeLabelShort(ctx), modelLabelShort(ctx));
44
44
  info(`${chatTypeLabelShort(ctx)} · type /chat to switch (carrier / standard)`);
45
45
  // A message passed on the command line (`cos chat "…"`) is sent immediately —
@@ -136,7 +136,7 @@ export async function runChat(ctx, initialMessage) {
136
136
  continue;
137
137
  }
138
138
  if (cmdWord === "/fast") {
139
- setFast(ctx, argStr);
139
+ await setFast(ctx, argStr, client);
140
140
  continue;
141
141
  }
142
142
  if (cmdWord === "/hipwr" || cmdWord === "/highpower") {
@@ -1,3 +1,5 @@
1
+ import { getPermissionMode, permissionModeExplanation, permissionModeLabel } from "../services/permission-mode.js";
2
+ import { taskSnapshot } from "../services/task-snapshot.js";
1
3
  import { ApiError } from "../services/api.js";
2
4
  import { errorLine, line, timeAgo } from "../services/output.js";
3
5
  import { ordinalOf } from "../services/session-resolver.js";
@@ -94,6 +96,8 @@ export async function showContext(ctx, client) {
94
96
  if (ctx.modeIsSelectable)
95
97
  row("Mode", c.value(modeLabelShort(ctx)));
96
98
  row("Model", c.value(modelLabelShort(ctx)));
99
+ const mode = getPermissionMode(ctx.config);
100
+ row("Permissions", c.value(permissionModeLabel(mode)) + c.dim(` · ${permissionModeExplanation(mode)}`));
97
101
  const on = [];
98
102
  if (ctx.fast)
99
103
  on.push("Fast");
@@ -126,6 +130,16 @@ export async function showContext(ctx, client) {
126
130
  /* memory is supplementary — a failure here shouldn't blank the view */
127
131
  }
128
132
  }
133
+ // ── The current coding task (the platform's Task Context) ────────────────
134
+ if (sessionId && typeof client.taskContext === "function") {
135
+ const snap = taskSnapshot(await client.taskContext(sessionId).catch(() => null));
136
+ if (snap) {
137
+ line();
138
+ line(" " + c.dim("Task"));
139
+ for (const [label, value] of taskSnapshotRows(snap))
140
+ row(label, value);
141
+ }
142
+ }
129
143
  // ── The local project ─────────────────────────────────────────────────────
130
144
  // Peek rather than build: /context is a status view, and it should not be the
131
145
  // thing that decides to walk a monorepo. When nothing has built a snapshot
@@ -158,3 +172,29 @@ export function contextUnavailable() {
158
172
  line(l);
159
173
  }
160
174
  }
175
+ /** The task snapshot as label/value rows — the same facts the IDE's /context card shows. */
176
+ export function taskSnapshotRows(t) {
177
+ const list = (items, total = items.length) => (items.length ? items.join(", ") + (total > items.length ? c.dim(` (+${total - items.length} more)`) : "") : c.dim("none"));
178
+ const rows = [
179
+ ["Task", c.value(t.title)],
180
+ ["Status", c.value(t.status) + (t.verified !== t.status ? c.dim(` · verified: ${t.verified}`) : "")],
181
+ ["Investigation", c.value(`${t.investigation.searches} searches · ${t.inspected.total} files read · ${t.investigation.symbols.length} symbols traced · ${t.investigation.relationships.length} relationships followed`)],
182
+ ["Inspected", list(t.inspected.files, t.inspected.total)],
183
+ ...(t.symptom ? [["Symptom", c.value(t.symptom)]] : []),
184
+ ...(t.executionPath.length ? [["Path", t.executionPath.join(c.dim(" → "))]] : []),
185
+ ["Root cause", t.rootCause ? c.value(t.rootCause) : c.dim("not established yet")],
186
+ ...(t.changeLocation ? [["Change at", c.value(t.changeLocation)]] : []),
187
+ ...(t.evidence.length ? [["Evidence", t.evidence.join("; ")]] : []),
188
+ ...(t.ruledOut.length ? [["Ruled out", t.ruledOut.join("; ")]] : []),
189
+ ...(t.plan ? [["Plan", c.value(t.plan)]] : []),
190
+ ["Modified", list(t.modified)],
191
+ ["Created", list(t.created)],
192
+ ["Deleted", list(t.deleted)],
193
+ ["Unresolved", t.unresolved.length ? c.warn(t.unresolved.join(", ") + " — may still be on disk; review before continuing") : c.dim("none")]
194
+ ];
195
+ if (t.pendingOperations.length)
196
+ rows.push(["Interrupted", c.warn(t.pendingOperations.join(", ") + " — never resumed automatically")]);
197
+ rows.push(["Corrections", t.corrections ? c.value(String(t.corrections)) + (t.lastCorrection ? c.dim(` · ${t.lastCorrection.slice(0, 80)}`) : "") : c.dim("none")]);
198
+ rows.push(["Tests", t.tests.length ? t.tests.map((r) => `${r.command} → ${r.outcome}`).join("; ") : c.dim("none run")]);
199
+ return rows;
200
+ }
@@ -1,10 +1,14 @@
1
+ import path from "node:path";
1
2
  import { ApiError } from "../services/api.js";
2
3
  import { cliVersion } from "../services/meta.js";
4
+ import { findPrebuiltHelper } from "../services/helper-bin.js";
5
+ import { isPackaged, isSignedRelease } from "../services/packaged.js";
3
6
  import { glyph, heading, line } from "../services/output.js";
4
7
  import { withSpinner } from "../services/spinner.js";
5
8
  import { discoverRootWithoutGit, refreshWorkspace } from "../services/workspace.js";
6
9
  import { isTrusted } from "../ui/trust.js";
7
- import { COMMANDS_OPT_IN_ENV } from "../services/client-tools.js";
10
+ import { COMMANDS_OPT_IN_ENV, localCommandsState } from "../services/client-tools.js";
11
+ import { executionContract } from "../services/execution-platform.js";
8
12
  function row(status, label, detail) {
9
13
  const g = status === "ok" ? glyph.ok : status === "warn" ? glyph.warn : glyph.err;
10
14
  line(` ${g} ${label.padEnd(20)} ${detail}`);
@@ -21,6 +25,16 @@ export function registerDoctor(program, ctx) {
21
25
  const client = ctx.client();
22
26
  const apiUrl = ctx.config.get("apiUrl") ?? "—";
23
27
  heading("Carrier OS — diagnostics");
28
+ // 0) Installation — only the packaged .exe has one to check. A helper that
29
+ // fails its baked hash is reported here rather than discovered mid-login.
30
+ if (isPackaged()) {
31
+ row("ok", "Installation", `v${cliVersion()} · ${path.dirname(process.execPath)}`);
32
+ row(isSignedRelease() ? "ok" : "warn", "Build", isSignedRelease() ? "signed release" : "unsigned build");
33
+ for (const helper of ["cos-dpapi", "cos-job-runner"]) {
34
+ const found = findPrebuiltHelper(helper);
35
+ row(found ? "ok" : "err", helper, found ? "verified" : "missing or damaged — reinstall Carrier OS");
36
+ }
37
+ }
24
38
  // 1) Configuration
25
39
  row("ok", "Configuration", `${ctx.config.file}`);
26
40
  row("ok", "Endpoint", apiUrl);
@@ -29,7 +43,7 @@ export function registerDoctor(program, ctx) {
29
43
  try {
30
44
  const health = await withSpinner("Pinging API…", () => client.health());
31
45
  apiVersion = health.version;
32
- row("ok", "API reachable", `${health.status} · ${health.version} · ${health.environment}`);
46
+ row("ok", "API reachable", [health.status, health.version, health.environment].filter(Boolean).join(" · "));
33
47
  }
34
48
  catch (err) {
35
49
  row("err", "API reachable", err instanceof ApiError ? err.message : "unreachable");
@@ -43,7 +57,7 @@ export function registerDoctor(program, ctx) {
43
57
  // 4) Session valid?
44
58
  try {
45
59
  const scope = await withSpinner("Verifying session…", () => client.verify());
46
- row("ok", "Session valid", `${scope.workspace.name} / ${scope.project.name}`);
60
+ row("ok", "Session valid", scope.user?.email ?? "CLI device session");
47
61
  }
48
62
  catch (err) {
49
63
  row("err", "Session valid", err instanceof ApiError ? `${err.message} (${err.code})` : "failed");
@@ -82,15 +96,16 @@ export function registerDoctor(program, ctx) {
82
96
  // of those is missing rather than just "off".
83
97
  const trusted = isTrusted(ctx.config, trustRoot) || isTrusted(ctx.config);
84
98
  row(trusted ? "ok" : "warn", "Folder trust", trusted ? `trusted: ${trustRoot}` : `not trusted: ${trustRoot}`);
85
- const optedIn = process.env[COMMANDS_OPT_IN_ENV] === "1";
86
- const commandState = !optedIn
87
- ? `off — set ${COMMANDS_OPT_IN_ENV}=1 in this terminal to offer them`
88
- : process.platform !== "win32"
89
- ? "off — local commands are Windows-only for now"
90
- : !trusted
91
- ? "off — this folder is not trusted"
92
- : "on for this terminal — every command still needs your approval";
93
- row(optedIn && trusted && process.platform === "win32" ? "ok" : "warn", "Local commands", commandState);
99
+ // The same check the shell uses to offer run_command, so the two agree
100
+ // on every platform (Windows Job Object; macOS/Linux isolated runtime).
101
+ const commands = localCommandsState(ctx, true);
102
+ const runtime = executionContract().backend === "docker-engine-v1" ? "isolated Linux container" : "Windows Job Object";
103
+ const commandState = !commands.enabled
104
+ ? `off — /settings commands on, or set ${COMMANDS_OPT_IN_ENV}=1 in this terminal`
105
+ : commands.blockedBy
106
+ ? `not active — ${commands.blockedBy}`
107
+ : `on (${runtime}) — every command still needs your approval`;
108
+ row(commands.enabled && !commands.blockedBy ? "ok" : "warn", "Local commands", commandState);
94
109
  // 7) Versions
95
110
  row("ok", "CLI version", cliVersion());
96
111
  row("ok", "API version", apiVersion);
@@ -14,6 +14,7 @@ export function registerLogout(program, ctx) {
14
14
  }
15
15
  const apiUrl = ctx.config.get("apiUrl") ?? DEFAULT_API_URL;
16
16
  const refreshToken = ctx.config.get("auth")?.refreshToken;
17
+ ctx.validateCredentialOrigin(apiUrl);
17
18
  if (refreshToken) {
18
19
  // Best-effort server revoke so the refresh token can't be reused.
19
20
  await withSpinner("Signing out…", () => logoutCliSession(apiUrl, refreshToken));
@@ -0,0 +1,77 @@
1
+ import { ApiError } from "../services/api.js";
2
+ import { errorLine, info, line, success } from "../services/output.js";
3
+ import { PERMISSION_MODES, getPermissionMode, parsePermissionMode, permissionModeExplanation, permissionModeLabel, setPermissionMode } from "../services/permission-mode.js";
4
+ import { withSpinner } from "../services/spinner.js";
5
+ import { c } from "../ui/colors.js";
6
+ import { pickFromList } from "../ui/select.js";
7
+ /** "Permission mode changed: Accept Edits" plus what it means. */
8
+ function confirm(mode) {
9
+ success(`Permission mode changed: ${permissionModeLabel(mode)}`);
10
+ line(" " + c.dim(permissionModeExplanation(mode)));
11
+ }
12
+ /**
13
+ * `/permissions` (and `/mode manual|plan|accept-edits`, `/plan`): show or set
14
+ * the session's permission mode. Bare in a terminal opens the picker; piped, it
15
+ * prints the current mode. Applies from the next message.
16
+ */
17
+ export async function runPermissions(ctx, arg) {
18
+ const current = getPermissionMode(ctx.config);
19
+ if (arg.trim()) {
20
+ const mode = parsePermissionMode(arg);
21
+ if (!mode) {
22
+ errorLine(`Unknown permission mode "${arg.trim()}". Use manual, plan, accept-edits or auto.`);
23
+ return;
24
+ }
25
+ if (mode === current) {
26
+ info(`Permission mode is already ${permissionModeLabel(mode)}.`);
27
+ return;
28
+ }
29
+ setPermissionMode(ctx.config, mode);
30
+ confirm(mode);
31
+ return;
32
+ }
33
+ if (!process.stdin.isTTY) {
34
+ line(`Permission mode: ${permissionModeLabel(current)} — ${permissionModeExplanation(current)}`);
35
+ return;
36
+ }
37
+ const chosen = parsePermissionMode(await pickFromList({
38
+ title: "Permission mode",
39
+ description: "Applies from your next message. Trust, freshness, checkpoints and recovery checks always run.",
40
+ choices: PERMISSION_MODES.map((m) => ({ value: m, label: permissionModeLabel(m) + (m === current ? " (current)" : ""), description: permissionModeExplanation(m) })),
41
+ initial: PERMISSION_MODES.indexOf(current)
42
+ }));
43
+ if (chosen && chosen !== current) {
44
+ setPermissionMode(ctx.config, chosen);
45
+ confirm(chosen);
46
+ }
47
+ }
48
+ const COMPACT_REASONS = {
49
+ NOTHING_TO_COMPACT: "Nothing new to compact since the last summary.",
50
+ RESTRUCTURING_DISABLED: "Chat restructuring is turned off in your preferences, so a summary would not be used. Turn it on in Settings → Performance to compact.",
51
+ BUSY: "An automatic context restructure is running for this conversation. Try /compact again in a moment.",
52
+ SESSION_NOT_FOUND: "This conversation is no longer available. Run /sessions to pick another."
53
+ };
54
+ /**
55
+ * `/compact`: replace the conversation's earlier messages in the model's
56
+ * context with a bounded summary of its state. Same conversation, same task,
57
+ * same permission mode; nothing is deleted locally or on the server.
58
+ */
59
+ export async function runCompact(ctx, client) {
60
+ const sessionId = ctx.config.get("sessionId");
61
+ if (!sessionId) {
62
+ info("No active conversation to compact. Start one, or resume one with /sessions.");
63
+ return;
64
+ }
65
+ try {
66
+ const r = await withSpinner("Compacting…", () => client.compactSession(sessionId, getPermissionMode(ctx.config)));
67
+ if (!r.compacted) {
68
+ info(COMPACT_REASONS[r.reason ?? ""] ?? "Nothing was compacted.");
69
+ return;
70
+ }
71
+ success(`Compacted ${r.messages ?? 0} earlier message${r.messages === 1 ? "" : "s"} into a summary (v${r.version}).`);
72
+ line(" " + c.dim(`Kept: ${r.task_context ? "the task, plan, inspected and changed files, tests, corrections, " : ""}your requests and the permission mode. Nothing was deleted — /context shows the task.`));
73
+ }
74
+ catch (err) {
75
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
76
+ }
77
+ }
@@ -11,7 +11,7 @@ import { screenActive } from "../ui/screen.js";
11
11
  * scope. `target` may be an id or a name; omit it for an interactive picker.
12
12
  */
13
13
  export function registerScope(program, ctx) {
14
- const workspace = program.command("workspace").description("Manage the active workspace");
14
+ const workspace = program.command("workspace").description("Advanced: manage API workspace scope (not local repositories)");
15
15
  workspace
16
16
  .command("list")
17
17
  .description("List your workspaces")
@@ -22,11 +22,11 @@ export function registerScope(program, ctx) {
22
22
  });
23
23
  workspace
24
24
  .command("use [target]")
25
- .description("Switch the active workspace (and pick a project in it)")
25
+ .description("Switch API workspace and automatically select its default project")
26
26
  .action(async (target) => {
27
27
  await useWorkspace(ctx, target);
28
28
  });
29
- const project = program.command("project").description("Manage the active project");
29
+ const project = program.command("project").description("Advanced: manage API project scope (not local repositories)");
30
30
  project
31
31
  .command("list")
32
32
  .description("List projects in the active workspace")
@@ -51,15 +51,16 @@ async function useWorkspace(ctx, target) {
51
51
  if (!ws)
52
52
  return unresolved("workspace", workspaces, activeWorkspaceId(ctx), (w) => `${w.name} ${dim(w.slug)}`);
53
53
  // A workspace switch needs a project in that workspace — pick its default, or
54
- // prompt when interactive.
54
+ // use the server-provided default ordering without a second prompt.
55
55
  const { projects } = await withSpinner("Loading projects…", () => listCliProjects(apiUrl, provider, ws.id));
56
56
  if (projects.length === 0) {
57
57
  errorLine(`Workspace "${ws.name}" has no projects. Create one in the dashboard first.`);
58
58
  process.exitCode = 1;
59
59
  return;
60
60
  }
61
- const proj = (await resolve(projects, undefined, `Select a project in ${ws.name}:`, (p) => `${p.name} (${p.environment})`)) ??
62
- projects[0];
61
+ // The API lists the default project first. Keep a valid current selection
62
+ // when reselecting the same workspace; otherwise use that server ordering.
63
+ const proj = projects.find((p) => p.id === activeProjectId(ctx)) ?? projects[0];
63
64
  await applyScope(ctx, apiUrl, provider, ws.id, proj.id);
64
65
  }
65
66
  async function useProject(ctx, target) {
@@ -97,6 +98,8 @@ async function resolve(items, target, message, labelFn) {
97
98
  return undefined;
98
99
  if (items.length === 0)
99
100
  return undefined;
101
+ if (items.length === 1)
102
+ return items[0];
100
103
  const id = await select({
101
104
  message,
102
105
  choices: items.map((i) => ({ name: labelFn(i), value: i.id }))
@@ -1,5 +1,6 @@
1
1
  import { ApiError } from "../services/api.js";
2
2
  import { errorLine, info, line, success, timeAgo } from "../services/output.js";
3
+ import { showTaskContext } from "../shell/task-context-view.js";
3
4
  import { clearActiveSession, listSessions, resolveSession, SessionRefError, setActiveSession } from "../services/session-resolver.js";
4
5
  import { withSpinner } from "../services/spinner.js";
5
6
  import { showHistory } from "./history.js";
@@ -117,6 +118,10 @@ export async function switchTo(ctx, client, ref) {
117
118
  // full context, so the person should too. Reuses /history's renderer, so
118
119
  // memory markers and clarification blocks render identically.
119
120
  await showHistory(ctx, client, s.session_id);
121
+ // Earlier coding work in that conversation, as context only (shell/task-context-view.ts).
122
+ if (typeof client.mutationRecoveryScope === "function") {
123
+ await showTaskContext(client, s.session_id);
124
+ }
120
125
  }
121
126
  catch (err) {
122
127
  reportRefError(err);
@@ -2,6 +2,7 @@ import { COMMANDS_OPT_IN_ENV, localCommandsState } from "../services/client-tool
2
2
  import { errorLine, line } from "../services/output.js";
3
3
  import { c } from "../ui/colors.js";
4
4
  import { sectionHeader } from "../ui/ui.js";
5
+ import { executionAdapter, executionPlatform } from "../services/execution-platform.js";
5
6
  /**
6
7
  * `cos settings` — the CLI's persisted behaviour settings, in one place.
7
8
  *
@@ -42,7 +43,13 @@ export function runSettings(ctx, argStr) {
42
43
  if (enable) {
43
44
  line(" " + c.ok("✓") + " " + c.value("Local commands enabled."));
44
45
  // Said plainly at the moment it is switched on: what a command can do.
45
- for (const l of LOCAL_COMMANDS_NOTICE)
46
+ const notice = executionAdapter(executionPlatform()) === "windows-job" ? LOCAL_COMMANDS_NOTICE : [
47
+ ...LOCAL_COMMANDS_NOTICE.slice(0, 3),
48
+ "Approved project code runs in a configured isolated Linux container.",
49
+ "Only the selected repository is mounted; network access is disabled.",
50
+ LOCAL_COMMANDS_NOTICE[5]
51
+ ];
52
+ for (const l of notice)
46
53
  line(" " + c.dim(l));
47
54
  }
48
55
  else {
@@ -1,6 +1,7 @@
1
1
  import { line } from "../services/output.js";
2
2
  import { withSpinner } from "../services/spinner.js";
3
- import { isPackaged, PACKAGED_DOWNLOAD_URL } from "../services/packaged.js";
3
+ import { isPackaged, isSignedRelease, PACKAGED_DOWNLOAD_URL } from "../services/packaged.js";
4
+ import { checkInstallerSignature, checkPackagedUpdate, downloadVerified, launchInstaller, updatesDir, UpdateError } from "../services/packaged-update.js";
4
5
  import { checkForUpdate, installLatest, isLinkedInstallation, PACKAGE_NAME, verifyInstallation } from "../services/update.js";
5
6
  import { c } from "../ui/colors.js";
6
7
  import { pickFromList } from "../ui/select.js";
@@ -72,14 +73,11 @@ function renderTerminalState(state) {
72
73
  * restarted: npm swaps files under a running Node, and re-execing through the
73
74
  * shim while the old process still holds handles is how partial installs occur.
74
75
  */
75
- export async function runUpdate() {
76
+ export async function runUpdate(opts = {}) {
76
77
  // The packaged executable has no npm to update through. Point at the download
77
78
  // rather than running an npm command that cannot exist in that environment.
78
79
  if (isPackaged()) {
79
- line();
80
- line(" " + c.dim("You're running the packaged Carrier OS CLI."));
81
- line(" " + c.dim("Download the latest build from ") + c.value(PACKAGED_DOWNLOAD_URL) + c.dim("."));
82
- line();
80
+ await runPackagedUpdate(opts.assumeYes === true);
83
81
  return;
84
82
  }
85
83
  const state = await withSpinner(c.dim("Checking for updates…"), async () => checkForUpdate());
@@ -105,7 +103,7 @@ export async function runUpdate() {
105
103
  versions(state.current, state.latest);
106
104
  line(" " + c.value("A new version is available."));
107
105
  line();
108
- const answer = await pickFromList({
106
+ const answer = opts.assumeYes ? "yes" : await pickFromList({
109
107
  title: "Update now?",
110
108
  description: "Runs " + MANUAL,
111
109
  choices: [
@@ -149,11 +147,83 @@ export async function runUpdate() {
149
147
  line(" " + c.dim("Restart Carrier OS CLI to use the new version."));
150
148
  line();
151
149
  }
150
+ /**
151
+ * The packaged (installer) update: check the release manifest, then — only
152
+ * after an explicit Yes — download, verify the checksum (and the signature on
153
+ * a signed build), hand the installer this PID and exit. The installer waits
154
+ * for this process to end before replacing cos.exe, so nothing is swapped
155
+ * underneath a running CLI. Every failure leaves the current version intact.
156
+ */
157
+ async function runPackagedUpdate(assumeYes) {
158
+ const state = await withSpinner(c.dim("Checking for updates…"), () => checkPackagedUpdate());
159
+ if (state.kind === "current") {
160
+ renderTerminalState({ kind: "current", current: state.current, latest: state.latest });
161
+ return;
162
+ }
163
+ if (state.kind === "ahead") {
164
+ heading();
165
+ versions(state.current, state.latest);
166
+ line(" " + c.ok("✓") + " " + c.value("You are running a newer version than the latest release."));
167
+ line(" " + c.dim("Nothing to do — this will not downgrade."));
168
+ line();
169
+ return;
170
+ }
171
+ if (state.kind === "unreachable") {
172
+ heading();
173
+ line(" " + c.err("✗") + " " + c.value("Could not check for the latest version."));
174
+ line();
175
+ line(" " + c.dim("Your current version: ") + c.value(state.current));
176
+ line(" " + c.dim(state.detail));
177
+ line(" " + c.dim("You can also download the installer from ") + c.value(PACKAGED_DOWNLOAD_URL) + c.dim("."));
178
+ line();
179
+ return;
180
+ }
181
+ const artifact = state.manifest.artifacts["win-x64-setup"];
182
+ heading();
183
+ versions(state.current, state.latest);
184
+ line(" " + c.value("A new version is available."));
185
+ line();
186
+ const answer = assumeYes ? "yes" : await pickFromList({
187
+ title: "Update now?",
188
+ description: `Downloads ${artifact.file} (${(artifact.size / 1024 / 1024).toFixed(1)} MB), verifies it, then installs it`,
189
+ choices: [
190
+ { value: "yes", label: "Yes", description: "Install v" + state.latest + " — Carrier OS closes while it updates" },
191
+ { value: "no", label: "No", description: "Stay on v" + state.current }
192
+ ],
193
+ initial: 0,
194
+ confirmOnNumber: true
195
+ });
196
+ if (answer !== "yes") {
197
+ line(" " + c.dim("Update cancelled."));
198
+ line();
199
+ return;
200
+ }
201
+ try {
202
+ const installer = await withSpinner(c.dim("Downloading and verifying…"), () => downloadVerified(artifact, updatesDir()));
203
+ const sig = checkInstallerSignature(installer, artifact, isSignedRelease());
204
+ const log = await launchInstaller(installer);
205
+ line();
206
+ line(" " + c.ok("✓") + " " + c.value(`Verified v${state.latest}`) + c.dim(sig.verified ? " (checksum + signature)" : " (checksum)"));
207
+ line(" " + c.dim("Installing now. Carrier OS will close; open a new terminal when it finishes."));
208
+ line(" " + c.dim("Installer log: ") + c.value(log));
209
+ line();
210
+ // The installer is waiting for this PID. Exit now so it can replace cos.exe.
211
+ process.exit(0);
212
+ }
213
+ catch (err) {
214
+ line();
215
+ line(" " + c.err("✗") + " " + c.value("Update failed."));
216
+ line(" " + c.dim(err instanceof UpdateError ? err.message : String(err?.message ?? err)));
217
+ line(" " + c.dim("Carrier OS CLI remains at v") + c.value(state.current) + c.dim("."));
218
+ line();
219
+ }
220
+ }
152
221
  export function registerUpdate(program, _ctx) {
153
222
  program
154
223
  .command("update")
155
224
  .description("Check for and install the latest Carrier OS CLI version")
156
- .action(async () => {
157
- await runUpdate();
225
+ .option("-y, --yes", "install an available update without asking (for scripts)")
226
+ .action(async (opts) => {
227
+ await runUpdate({ assumeYes: opts.yes === true });
158
228
  });
159
229
  }
@@ -1,7 +1,7 @@
1
1
  import { heading, line } from "../services/output.js";
2
2
  import { withSpinner } from "../services/spinner.js";
3
3
  import { c } from "../ui/colors.js";
4
- import { icon, sectionHeader, termWidth, visibleLen } from "../ui/ui.js";
4
+ import { formatCredits, icon, sectionHeader, termWidth, visibleLen } from "../ui/ui.js";
5
5
  /**
6
6
  * `cos usage` — requests, tokens and estimated cost for the current project,
7
7
  * plus the credit balance that decides whether you can keep going, from
@@ -20,7 +20,7 @@ export function registerUsage(program, ctx) {
20
20
  .action(async () => {
21
21
  const client = ctx.requireAuth();
22
22
  const usage = await withSpinner("Loading usage…", () => client.usage());
23
- heading(`Usage · project ${usage.project_id}`);
23
+ heading(usage.project_id ? `Usage · project ${usage.project_id}` : "CLI usage");
24
24
  renderActivity(usage);
25
25
  renderCredits(usage.credits);
26
26
  line();
@@ -121,9 +121,9 @@ export function renderCredits(credits) {
121
121
  line(" " + icon.warn + c.warn(" Out of credits — buy more or upgrade your plan to continue."));
122
122
  }
123
123
  // Per-model pools exist only on plans that define them; an empty list is a
124
- // normal state, not a failure.
124
+ // normal state, not a failure. An unlimited plan is never blocked by a pool, so "25 exhausted" would be false.
125
125
  const pools = credits.models ?? [];
126
- if (pools.length === 0)
126
+ if (pools.length === 0 || unlimited)
127
127
  return;
128
128
  const spent = (p) => p.status === "exceeded" || p.remaining <= 0;
129
129
  const available = pools.filter((p) => !spent(p)).sort((a, b) => b.remaining - a.remaining);
@@ -153,7 +153,7 @@ export function renderCredits(credits) {
153
153
  }
154
154
  /* ── Layout helpers ───────────────────────────────────────────────────────── */
155
155
  const num = (n) => n.toLocaleString("en-US");
156
- const dec = (n) => n.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
156
+ const dec = formatCredits;
157
157
  const tint = (s, color) => (color ? color(s) : s);
158
158
  /**
159
159
  * A label column plus right-aligned value columns. Every width is measured on