@carrieros/cli 0.2.0 → 0.3.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 (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -1,24 +1,170 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import os from "node:os";
3
4
  import path from "node:path";
4
- /** Production default; override at login with `--url` or via CARRIEROS_API_URL. */
5
- export const DEFAULT_API_URL = process.env.CARRIEROS_API_URL || "https://api.carrieros.ai/v1";
5
+ import { SealError, isSealed, seal, sealingAvailable, unseal } from "./secure-store.js";
6
+ /**
7
+ * A URL is safe to send credentials to only over HTTPS, or over HTTP to a
8
+ * loopback host (local dev). Anything else (a plain-HTTP remote host) would send
9
+ * bearer/refresh tokens in cleartext — reject it so a mistaken or hostile
10
+ * `--url` / env override can't exfiltrate credentials.
11
+ */
12
+ export function isSafeUrl(u) {
13
+ try {
14
+ const x = new URL(u);
15
+ if (x.protocol === "https:")
16
+ return true;
17
+ const loopback = ["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"];
18
+ return x.protocol === "http:" && loopback.includes(x.hostname);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ /** Production default; override at login with `--url` or via CARRIEROS_API_URL.
25
+ * An unsafe (plain-HTTP remote) env override is ignored in favour of the
26
+ * secure default rather than silently leaking tokens. */
27
+ const ENV_API_URL = (process.env.CARRIEROS_API_URL || "").trim();
28
+ export const DEFAULT_API_URL = ENV_API_URL && isSafeUrl(ENV_API_URL) ? ENV_API_URL : "https://api.carrieros.ai/v1";
29
+ /**
30
+ * Do two API base URLs point at the same server?
31
+ *
32
+ * Compared by ORIGIN (scheme + host + port), so `https://api.carrieros.ai/v1`
33
+ * and `https://api.carrieros.ai/v2` are the same server while
34
+ * `http://localhost:5000/v1` is not. Used to decide whether a rejection came
35
+ * from the server that issued the session — the only one whose "no" means the
36
+ * session is over. An unknown value on either side is NOT a match: not knowing
37
+ * who issued a session is a reason to leave it alone, not to delete it.
38
+ */
39
+ export function sameApiOrigin(a, b) {
40
+ if (!a || !b)
41
+ return false;
42
+ try {
43
+ return new URL(a).origin === new URL(b).origin;
44
+ }
45
+ catch {
46
+ return a === b;
47
+ }
48
+ }
6
49
  /**
7
50
  * ConfigStore — the single owner of on-disk CLI state. Everything the CLI
8
- * persists (API key, active session, cached scope, recent uploads) lives in one
9
- * JSON file so the rest of the app never touches the filesystem directly.
51
+ * persists (credentials, active session, cached scope, recent uploads) lives in
52
+ * one JSON file so the rest of the app never touches the filesystem directly.
10
53
  *
11
54
  * Windows-first: `%APPDATA%/CarrierOS/config.json`; falls back to
12
55
  * `~/.carrieros/config.json` on other platforms.
56
+ *
57
+ * WRITES ARE MERGES, NOT SNAPSHOTS. A `cos` process can live for hours (the
58
+ * shell) while another one signs in, and the in-memory copy it loaded at
59
+ * startup does not know about that. Writing that copy back — which is what
60
+ * saving a theme, a model, a session id or an update check used to do — served
61
+ * the whole file from a stale snapshot and silently deleted the credentials the
62
+ * other process had just written. Every write now re-reads the file, applies
63
+ * only what THIS call changes, and replaces the file atomically. A field is
64
+ * removed only when a caller asks for it to be removed, which is why logout
65
+ * still works and why nothing else can take `auth` with it.
13
66
  */
14
67
  export class ConfigStore {
15
68
  dir;
16
69
  file;
70
+ /** The config with credentials OPENED — what every caller reads. */
17
71
  data;
72
+ /**
73
+ * Why stored credentials could not be opened, when they could not: another
74
+ * Windows account, another machine, or a damaged blob. The CLI then behaves
75
+ * as signed out — it never crashes over it, and never deletes the blob, so
76
+ * `cos login` is the recovery and nothing is lost by trying.
77
+ */
78
+ credentialError = null;
18
79
  constructor() {
19
80
  this.dir = ConfigStore.resolveDir();
20
81
  this.file = path.join(this.dir, "config.json");
21
- this.data = this.read();
82
+ this.data = this.reveal(this.read());
83
+ this.protectPlaintextCredentials();
84
+ }
85
+ /**
86
+ * Credentials written before protection existed are still plaintext on disk.
87
+ * Seal them in place the first time a build that can protect them runs.
88
+ * Best-effort: a failure leaves the file exactly as it was.
89
+ */
90
+ protectPlaintextCredentials() {
91
+ const raw = this.read();
92
+ const plaintext = (typeof raw.auth?.accessToken === "string" && !isSealed(raw.auth.accessToken)) ||
93
+ (typeof raw.auth?.refreshToken === "string" && !isSealed(raw.auth.refreshToken)) ||
94
+ (typeof raw.secretKey === "string" && !isSealed(raw.secretKey));
95
+ if (!plaintext || !sealingAvailable())
96
+ return;
97
+ try {
98
+ this.commit({
99
+ ...(raw.auth ? { auth: this.data.auth } : {}),
100
+ ...(typeof raw.secretKey === "string" ? { secretKey: this.data.secretKey } : {})
101
+ });
102
+ }
103
+ catch {
104
+ /* leave the file as it was */
105
+ }
106
+ }
107
+ /**
108
+ * Seal the credential fields of a patch before it is written.
109
+ *
110
+ * Only these three are secrets; everything else in the file — the account
111
+ * email, the workspace, the issuing API — stays readable, so the prompt and
112
+ * an offline `whoami` never need to open anything. Where protection is not
113
+ * available (not Windows, or no C# compiler) the value is written as before:
114
+ * refusing to sign someone in would be worse, and the risk is documented.
115
+ */
116
+ conceal(patch) {
117
+ const canSeal = (v) => typeof v === "string" && v.length > 0 && !isSealed(v);
118
+ const out = { ...patch };
119
+ if (patch.auth && (canSeal(patch.auth.accessToken) || canSeal(patch.auth.refreshToken))) {
120
+ if (sealingAvailable()) {
121
+ out.auth = {
122
+ ...patch.auth,
123
+ accessToken: canSeal(patch.auth.accessToken) ? seal(patch.auth.accessToken) : patch.auth.accessToken,
124
+ refreshToken: canSeal(patch.auth.refreshToken) ? seal(patch.auth.refreshToken) : patch.auth.refreshToken
125
+ };
126
+ }
127
+ }
128
+ if (canSeal(patch.secretKey) && sealingAvailable())
129
+ out.secretKey = seal(patch.secretKey);
130
+ return out;
131
+ }
132
+ /** Open the credential fields of what is on disk, for the in-memory view. */
133
+ reveal(raw) {
134
+ const out = { ...raw };
135
+ const open = (v) => {
136
+ if (typeof v !== "string")
137
+ return undefined;
138
+ if (!isSealed(v))
139
+ return v;
140
+ try {
141
+ return unseal(v);
142
+ }
143
+ catch (err) {
144
+ this.credentialError =
145
+ err instanceof SealError ? err.message : "Stored credentials could not be opened.";
146
+ return undefined;
147
+ }
148
+ };
149
+ this.credentialError = null;
150
+ if (raw.auth) {
151
+ const accessToken = open(raw.auth.accessToken);
152
+ const refreshToken = open(raw.auth.refreshToken);
153
+ // A session is both halves or neither: half a session would sign the
154
+ // user in and then fail on the first refresh.
155
+ out.auth =
156
+ accessToken && refreshToken
157
+ ? { ...raw.auth, accessToken, refreshToken }
158
+ : undefined;
159
+ }
160
+ if (raw.secretKey !== undefined) {
161
+ const key = open(raw.secretKey);
162
+ if (key)
163
+ out.secretKey = key;
164
+ else
165
+ delete out.secretKey;
166
+ }
167
+ return out;
22
168
  }
23
169
  static resolveDir() {
24
170
  const appData = process.env.APPDATA;
@@ -35,10 +181,60 @@ export class ConfigStore {
35
181
  return { apiUrl: DEFAULT_API_URL };
36
182
  }
37
183
  }
38
- write() {
39
- fs.mkdirSync(this.dir, { recursive: true });
40
- // 0o600 = owner-only; a no-op on Windows ACLs but correct on POSIX.
41
- fs.writeFileSync(this.file, JSON.stringify(this.data, null, 2), { mode: 0o600 });
184
+ /**
185
+ * Apply a change on top of what is on disk NOW.
186
+ *
187
+ * `remove` is the only way a key leaves the file. Everything the caller did
188
+ * not mention survives, whoever wrote it and whenever — which is the property
189
+ * that keeps a session alive through an unrelated save from an older process.
190
+ */
191
+ commit(patch, remove = []) {
192
+ // Merge in DISK form: what is already there stays sealed, and the patch is
193
+ // sealed before it joins it. Plaintext credentials never reach the file.
194
+ const merged = { ...this.read(), ...this.conceal(patch) };
195
+ for (const key of remove)
196
+ delete merged[key];
197
+ this.write(merged);
198
+ this.data = this.reveal(merged);
199
+ }
200
+ /**
201
+ * Replace the file atomically: write a sibling temp file, then rename over
202
+ * the target. A crash or a full disk mid-write leaves the previous config
203
+ * intact instead of a truncated file that reads as "logged out".
204
+ */
205
+ write(data) {
206
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
207
+ const tmp = `${this.file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
208
+ try {
209
+ // `mode` on writeFileSync only applies when the file is CREATED — so a
210
+ // pre-existing file with looser perms would keep them. chmod after the
211
+ // write (and on the dir) to guarantee owner-only tokens. POSIX-only; a
212
+ // no-op on Windows ACLs, hence best-effort.
213
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
214
+ try {
215
+ fs.chmodSync(tmp, 0o600);
216
+ }
217
+ catch {
218
+ /* Windows / restricted FS — best effort */
219
+ }
220
+ fs.renameSync(tmp, this.file);
221
+ }
222
+ catch (err) {
223
+ try {
224
+ fs.unlinkSync(tmp);
225
+ }
226
+ catch {
227
+ /* already gone */
228
+ }
229
+ throw err;
230
+ }
231
+ try {
232
+ fs.chmodSync(this.file, 0o600);
233
+ fs.chmodSync(this.dir, 0o700);
234
+ }
235
+ catch {
236
+ /* Windows / restricted FS — best effort */
237
+ }
42
238
  }
43
239
  get all() {
44
240
  return this.data;
@@ -47,28 +243,57 @@ export class ConfigStore {
47
243
  return this.data[key];
48
244
  }
49
245
  set(key, value) {
50
- this.data[key] = value;
51
- this.write();
246
+ // `undefined` is how several callers say "forget this" (e.g. sessionId);
247
+ // it is removed from the file rather than written as a null.
248
+ if (value === undefined)
249
+ this.commit({}, [key]);
250
+ else
251
+ this.commit({ [key]: value });
52
252
  }
53
253
  update(patch) {
54
- this.data = { ...this.data, ...patch };
55
- this.write();
254
+ this.commit(patch);
255
+ }
256
+ /**
257
+ * Re-read the file, discarding the in-memory copy.
258
+ *
259
+ * Every write already goes straight to disk, so the only thing this can pick
260
+ * up is a change made by ANOTHER `cos` process — which is exactly the case
261
+ * token refresh needs: if a second terminal rotated the session, this process
262
+ * is holding a spent refresh token, and presenting it would look to the server
263
+ * like token theft.
264
+ */
265
+ reload() {
266
+ this.data = this.reveal(this.read());
56
267
  }
57
268
  get isAuthenticated() {
58
269
  // Device-flow session is the primary credential; a legacy key still counts.
59
270
  return Boolean(this.data.auth?.accessToken || this.data.secretKey);
60
271
  }
61
- /** Wipe credentials + derived state on logout (keeps apiUrl). */
272
+ /**
273
+ * Wipe credentials + derived state on logout (keeps apiUrl).
274
+ *
275
+ * The ONE place `auth` is removed. Everything else merges, so signing out is
276
+ * something a user asks for rather than something a save can do by accident.
277
+ * Title and ordinals are CACHES OF sessionId: dropping the id without them
278
+ * left the footer naming a conversation the CLI was no longer in, and
279
+ * `/memory 2` resolving against a stale numbering from a previous account.
280
+ */
62
281
  clearAuth() {
63
- delete this.data.auth;
64
- delete this.data.secretKey;
65
- delete this.data.sessionId;
66
- delete this.data.scope;
67
- this.write();
282
+ this.commit({}, [
283
+ "auth",
284
+ "secretKey",
285
+ "sessionId",
286
+ "sessionTitle",
287
+ "sessionOrdinals",
288
+ "memoryArtifactIds",
289
+ "scope",
290
+ "attachedFileIds"
291
+ ]);
68
292
  }
69
293
  addUpload(record) {
70
- const list = this.data.uploads ?? [];
71
- this.data.uploads = [record, ...list].slice(0, 25);
72
- this.write();
294
+ // Read-modify-write against the file, so an upload recorded by another
295
+ // process is not dropped by this one.
296
+ const list = this.read().uploads ?? [];
297
+ this.commit({ uploads: [record, ...list].slice(0, 25) });
73
298
  }
74
299
  }
@@ -1,5 +1,5 @@
1
- import { ApiClient } from "./api.js";
2
- import { DEFAULT_API_URL } from "./config.js";
1
+ import { ApiClient, ApiError } from "./api.js";
2
+ import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
3
3
  import { refreshCliSession } from "./device-auth.js";
4
4
  /**
5
5
  * Thrown by requireAuth when no key is configured. Unlike a process.exit, this
@@ -27,41 +27,154 @@ export class CommandContext {
27
27
  * mode mid-session updates this. It is never written to disk, so standalone
28
28
  * commands keep using the persisted `mode`. */
29
29
  overrideMode;
30
+ /** True while running inside the interactive `cos` shell (vs a one-shot
31
+ * standalone command). Commands use this to decide between interactive
32
+ * prompts (shell) and finish-and-return "next steps" output (standalone). */
33
+ _inShell = false;
34
+ get inShell() {
35
+ return this._inShell;
36
+ }
37
+ setInShell(v) {
38
+ this._inShell = v;
39
+ }
40
+ /** File ids attached to chat messages, sent as `file_ids` on /v1/chat so the
41
+ * model can read the file. PERSISTED in config (not just in-process) so a file
42
+ * uploaded via a standalone `cos upload` is still attached when the shell opens
43
+ * in a separate process. Populated by upload (auto-attach) and `/attach`,
44
+ * cleared by `/detach` or logout. */
45
+ get attachedFileIds() {
46
+ return this.config.get("attachedFileIds") ?? [];
47
+ }
48
+ /** Attach a file id (deduped) so it rides along on subsequent messages. */
49
+ attachFile(fileId) {
50
+ if (!fileId)
51
+ return;
52
+ const list = this.attachedFileIds;
53
+ if (!list.includes(fileId))
54
+ this.config.set("attachedFileIds", [...list, fileId]);
55
+ }
56
+ /** Drop all attachments (an explicit /detach or logout). */
57
+ clearAttachments() {
58
+ this.config.set("attachedFileIds", []);
59
+ }
30
60
  /** A client built from current config (anonymous if not logged in). */
31
61
  client() {
32
62
  return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.authProvider());
33
63
  }
64
+ /**
65
+ * The one refresh currently on the wire, shared by every request that needs it.
66
+ *
67
+ * Refresh tokens are single-use. The shell opens by loading models and modes
68
+ * in parallel, so when the stored access token has expired both requests get
69
+ * a 401 in the same instant — and each used to run its own refresh with the
70
+ * same token. The server let exactly one rotate and answered the other 409;
71
+ * the CLI read that 409 as a dead session and deleted the credentials the
72
+ * winner had just saved. The first message still went through on the fresh
73
+ * token held in memory, and the second found nothing on disk: "You're not
74
+ * signed in".
75
+ *
76
+ * Lives on the context rather than the provider because `client()` builds a
77
+ * new provider for every client, and the coordination has to span all of them.
78
+ */
79
+ refreshing = null;
34
80
  /**
35
81
  * The credential + silent-refresh strategy for every authenticated call.
36
- * Prefers the device-flow session; falls back to a legacy static key. On a
37
- * 401 it rotates the refresh token and persists the new pair; if the session
38
- * is dead it clears local auth so the next command prompts a fresh login.
82
+ * Prefers the device-flow session; falls back to a legacy static key.
39
83
  */
40
84
  authProvider() {
41
85
  return {
42
86
  token: () => this.config.get("auth")?.accessToken ?? this.config.get("secretKey"),
43
- refresh: async () => {
44
- const auth = this.config.get("auth");
45
- if (!auth?.refreshToken)
46
- return undefined;
47
- const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
48
- const renewed = await refreshCliSession(apiUrl, auth.refreshToken);
49
- if (!renewed) {
50
- this.config.clearAuth();
51
- return undefined;
52
- }
87
+ refresh: (failedToken) => {
88
+ this.refreshing ??= this.renewSession(failedToken).finally(() => {
89
+ this.refreshing = null;
90
+ });
91
+ return this.refreshing;
92
+ }
93
+ };
94
+ }
95
+ /**
96
+ * Renew the session, and clear local credentials ONLY when the server says it
97
+ * is finished.
98
+ *
99
+ * Before spending the refresh token this re-reads config from disk: another
100
+ * `cos` process (a second terminal, a standalone command alongside the shell)
101
+ * may already have rotated it, in which case the token held in memory is spent
102
+ * and presenting it trips the server's reuse detection — which revokes every
103
+ * device on the account. Adopting the rotated pair avoids asking at all.
104
+ */
105
+ async renewSession(failedToken) {
106
+ this.config.reload();
107
+ const auth = this.config.get("auth");
108
+ if (!auth?.refreshToken)
109
+ return undefined;
110
+ // Someone already renewed since this request went out — just retry with it.
111
+ if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
112
+ return auth.accessToken;
113
+ }
114
+ const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
115
+ const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
116
+ switch (outcome.kind) {
117
+ case "ok": {
118
+ const renewed = outcome.data;
53
119
  this.config.update({
54
120
  auth: {
55
121
  ...auth,
56
122
  accessToken: renewed.access_token,
57
123
  refreshToken: renewed.refresh_token,
124
+ // A server that rotated this session is the server that owns it —
125
+ // stamp sessions issued before the field existed.
126
+ apiUrl: auth.apiUrl ?? apiUrl,
58
127
  workspace: renewed.workspace ?? auth.workspace,
59
128
  project: renewed.project ?? auth.project
60
129
  }
61
130
  });
62
131
  return renewed.access_token;
63
132
  }
64
- };
133
+ case "dead":
134
+ // "This session is finished" is only true when it comes from the server
135
+ // that ISSUED the session. Pointing the CLI at a different API (a local
136
+ // dev server, a mistyped --url) gets the very same 401 from a server
137
+ // that has simply never heard of it — and acting on that is
138
+ // unrecoverable, because the refresh token exists nowhere else.
139
+ //
140
+ // Signing out is therefore something the CLI does only when it is sure,
141
+ // or something the user does explicitly with `cos logout`. A refresh
142
+ // token the server has already revoked grants nothing, so leaving one on
143
+ // disk costs nothing either.
144
+ if (sameApiOrigin(auth.apiUrl, apiUrl)) {
145
+ this.config.clearAuth();
146
+ return undefined;
147
+ }
148
+ throw new ApiError("SESSION_NOT_RENEWABLE", auth.apiUrl
149
+ ? `This session was issued by ${auth.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
150
+ `Point it back with \`cos login --url ${auth.apiUrl}\`, or run \`cos logout\` to sign in here.`
151
+ : `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
152
+ "run `cos logout` and sign in again.", 401);
153
+ case "busy": {
154
+ // A different process won the rotation; its tokens are about to land in
155
+ // the shared config. Give it a moment to write them rather than guessing.
156
+ const adopted = await this.awaitRotatedElsewhere(auth.refreshToken);
157
+ if (adopted)
158
+ return adopted;
159
+ throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
160
+ }
161
+ case "transient":
162
+ // The session may be perfectly healthy — never sign someone out because
163
+ // the API had a bad second.
164
+ throw new ApiError("REFRESH_UNAVAILABLE", "Couldn't renew your session right now. Try again in a moment.", outcome.status || 503);
165
+ }
166
+ }
167
+ /** Poll the shared config briefly for a refresh token rotated by another process. */
168
+ async awaitRotatedElsewhere(spentRefreshToken) {
169
+ for (let attempt = 0; attempt < 10; attempt += 1) {
170
+ await new Promise((r) => setTimeout(r, 100));
171
+ this.config.reload();
172
+ const auth = this.config.get("auth");
173
+ if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
174
+ return auth.accessToken;
175
+ }
176
+ }
177
+ return undefined;
65
178
  }
66
179
  /**
67
180
  * A client guaranteed to carry a key, or a clean exit with guidance. Use this
@@ -69,14 +182,35 @@ export class CommandContext {
69
182
  */
70
183
  requireAuth() {
71
184
  if (!this.config.isAuthenticated) {
72
- throw new AuthRequiredError();
185
+ // Say WHY when we know: credentials that exist but cannot be opened by
186
+ // this Windows account (copied from another machine or user, or damaged)
187
+ // are a different situation from never having signed in.
188
+ throw new AuthRequiredError(this.config.credentialError
189
+ ? `${this.config.credentialError} Run \`cos login\` to sign in again.`
190
+ : undefined);
73
191
  }
74
192
  return this.client();
75
193
  }
76
- /** Active Carrier mode: the session override if set (the shell), otherwise the
77
- * persisted default, falling back to "general" (the Carrier OS persona). */
194
+ /**
195
+ * Active Carrier mode. Mode belongs to the CHAT TYPE, not the session:
196
+ *
197
+ * carrier → always "general". Carrier Chat runs one mode, so this is
198
+ * derived rather than stored — nothing chosen in Standard can
199
+ * leak in, and nothing chosen here can leak back out.
200
+ * standard → the session override, else the persisted default, else "auto"
201
+ * (Standard is the only place Auto routing applies).
202
+ *
203
+ * Deriving it is what keeps a Carrier→Standard switch from stranding you in
204
+ * General: there is no carrier mode to carry over in the first place.
205
+ */
78
206
  get mode() {
79
- return this.overrideMode ?? this.config.get("mode") ?? "general";
207
+ if (this.chatType === "carrier")
208
+ return "general";
209
+ return this.overrideMode ?? this.config.get("mode") ?? "auto";
210
+ }
211
+ /** True when the active chat type lets the user choose a mode at all. */
212
+ get modeIsSelectable() {
213
+ return this.chatType !== "carrier";
80
214
  }
81
215
  /** Set the mode for this process only (interactive shell), without persisting. */
82
216
  setSessionMode(id) {
@@ -94,5 +228,116 @@ export class CommandContext {
94
228
  setChatType(type) {
95
229
  this.config.set("chatType", type);
96
230
  this.config.set("sessionId", undefined);
231
+ // Drop the session's mode override so the new chat type lands on its own
232
+ // default (carrier → General, standard → the saved mode or Auto) instead of
233
+ // inheriting a mode the user picked for the type they just left.
234
+ this.overrideMode = undefined;
235
+ }
236
+ /** Persisted web-search preference. `undefined` means "not chosen here" — the
237
+ * API then falls back to the workspace's admin toggle, which is what the web
238
+ * app does. `/websearch on|off` persists a choice that wins over that. */
239
+ get webSearch() {
240
+ return this.config.get("webSearch");
241
+ }
242
+ setWebSearch(on) {
243
+ this.config.set("webSearch", on);
244
+ }
245
+ /** One-shot arm from a bare `/websearch`: search the NEXT message, then go
246
+ * back to whatever the persisted preference was. Deliberately in-process —
247
+ * an armed turn that never got sent shouldn't survive into a new session. */
248
+ armed = false;
249
+ get webSearchArmed() {
250
+ return this.armed;
251
+ }
252
+ armWebSearch() {
253
+ this.armed = true;
254
+ }
255
+ disarmWebSearch() {
256
+ this.armed = false;
257
+ }
258
+ /** What to send as `web_search` on the next turn: forced on while armed,
259
+ * otherwise the persisted preference (undefined = follow the workspace). */
260
+ get effectiveWebSearch() {
261
+ return this.armed ? true : this.webSearch;
262
+ }
263
+ /**
264
+ * Fast mode — Llama via Groq instead of the selected model.
265
+ *
266
+ * STANDARD CHAT ONLY, mirroring the web's `isRestrictedType`: it forces
267
+ * fastMode off for `carrier`/`temp` conversations even when one has the flag
268
+ * stored. Deriving it here rather than clearing the setting means switching
269
+ * Carrier → Standard restores whatever the user last chose, instead of
270
+ * silently losing it on every round trip.
271
+ */
272
+ get fast() {
273
+ if (this.chatType !== "standard")
274
+ return false;
275
+ return this.config.get("fast") === true;
276
+ }
277
+ setFast(on) {
278
+ this.config.set("fast", on);
279
+ }
280
+ /** High Power (HIPWR) — the 4-pass refinement pipeline. Persisted, but the
281
+ * server still treats it as opt-in per request and admin-gated. */
282
+ get highPower() {
283
+ return this.config.get("highPower") === true;
284
+ }
285
+ setHighPower(on) {
286
+ this.config.set("highPower", on);
287
+ }
288
+ /** SIA clarification — ask before sending, rather than guessing at an
289
+ * ambiguous prompt. Off by default, like the web composer's toggle. */
290
+ get siaMode() {
291
+ // STANDARD CHAT ONLY, derived the same way `fast` is: Carrier Chat runs its
292
+ // own behaviour layer and the web shows no SIA control there. Deriving
293
+ // rather than clearing means a Carrier -> Standard switch restores whatever
294
+ // the user last chose instead of silently losing it.
295
+ if (this.chatType !== "standard")
296
+ return "off";
297
+ const stored = this.config.get("sia");
298
+ // Legacy booleans from before the mode existed: true meant "consult the
299
+ // backend", which is exactly what auto does now.
300
+ if (stored === true)
301
+ return "auto";
302
+ if (stored === false)
303
+ return "off";
304
+ return stored === "off" ? "off" : "auto"; // unset -> auto, the default
305
+ }
306
+ /** True when a turn should ask the backend whether clarification is needed. */
307
+ get sia() {
308
+ return this.siaMode === "auto";
309
+ }
310
+ setSiaMode(mode) {
311
+ this.config.set("sia", mode);
312
+ }
313
+ /**
314
+ * True while a main chat turn is rendering in the background.
315
+ *
316
+ * Runtime-only (never persisted): the shell sets it when it detaches a turn
317
+ * so commands that share the terminal — `/btw` — can tell who owns the
318
+ * transient region.
319
+ */
320
+ mainTurnRunning = false;
321
+ /**
322
+ * Credits this shell session's turns were actually debited, summed from the
323
+ * server's per-turn `credits_spent`. Runtime-only: "this session" means this
324
+ * process. Background context maintenance is billed separately on the server
325
+ * and is not a turn, so it is not in here — `/usage` reports it.
326
+ */
327
+ sessionCreditsSpent = 0;
328
+ /** Whether any turn this session reported its spend (older APIs do not). */
329
+ sessionSpendKnown = false;
330
+ /** Citations from the most recent turn that returned any, so /sources and
331
+ * /open can act on them after the answer has scrolled away. */
332
+ lastSearch = null;
333
+ recordSearch(sources) {
334
+ if (sources.length > 0)
335
+ this.lastSearch = { sources, at: Date.now() };
336
+ }
337
+ get lastSources() {
338
+ return this.lastSearch?.sources ?? [];
339
+ }
340
+ get lastSearchAt() {
341
+ return this.lastSearch?.at ?? null;
97
342
  }
98
343
  }