@carrieros/cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +170 -64
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Trusted PID 1 code, supplied by the CLI, never read from the repository.
3
+ * Project code runs under a different UID and cannot stop the heartbeat monitor.
4
+ * Exiting PID 1 tears down the PID namespace, including setsid/orphan descendants.
5
+ * The first input line is private control data, not inherited by project code.
6
+ */
7
+ export const CONTAINER_SUPERVISOR = String.raw `
8
+ const {spawn}=require('node:child_process');
9
+ const readline=require('node:readline');
10
+ let request, child, finished=false, last=Date.now();
11
+ function finish(result) {
12
+ if(finished)return;
13
+ finished=true;
14
+ setTimeout(()=>process.exit(0),100);
15
+ if(request) process.stderr.write('\n'+request.marker+JSON.stringify(result)+'\n',()=>process.exit(0));
16
+ else process.exit(125);
17
+ }
18
+ const watchdog=setInterval(()=>{
19
+ if(Date.now()-last>2500) finish({kind:'lease_lost',code:null,signal:null});
20
+ },100);
21
+ const input=readline.createInterface({input:process.stdin});
22
+ input.on('line',line=>{
23
+ if(request) { if(line==='heartbeat')last=Date.now(); return; }
24
+ try {
25
+ request=JSON.parse(line);
26
+ if(!Number.isInteger(request.uid)||request.uid<=0||!Number.isInteger(request.gid)||request.gid<=0)throw Error();
27
+ last=Date.now();
28
+ setTimeout(()=>finish({kind:'timeout',code:null,signal:null}),request.timeoutMs);
29
+ child=spawn(request.program,request.args,{
30
+ cwd:request.cwd,env:request.env,uid:request.uid,gid:request.gid,
31
+ stdio:['ignore','inherit','inherit']
32
+ });
33
+ child.once('error',error=>finish({kind:error&&error.code==='ENOENT'?'not_installed':'start_failed',code:null,signal:null}));
34
+ child.once('exit',(code,signal)=>finish({kind:'exit',code,signal}));
35
+ } catch { finish({kind:'start_failed',code:null,signal:null}); }
36
+ });
37
+ input.on('close',()=>finish({kind:'lease_lost',code:null,signal:null}));
38
+ `;
@@ -1,6 +1,7 @@
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
+ import { assertCredentialOrigin } from "./auth-origin.js";
4
5
  /**
5
6
  * Thrown by requireAuth when no key is configured. Unlike a process.exit, this
6
7
  * can be caught — so the interactive shell can keep running after a failed
@@ -27,41 +28,175 @@ export class CommandContext {
27
28
  * mode mid-session updates this. It is never written to disk, so standalone
28
29
  * commands keep using the persisted `mode`. */
29
30
  overrideMode;
31
+ /** True while running inside the interactive `cos` shell (vs a one-shot
32
+ * standalone command). Commands use this to decide between interactive
33
+ * prompts (shell) and finish-and-return "next steps" output (standalone). */
34
+ _inShell = false;
35
+ get inShell() {
36
+ return this._inShell;
37
+ }
38
+ setInShell(v) {
39
+ this._inShell = v;
40
+ }
41
+ /** File ids attached to chat messages, sent as `file_ids` on /v1/chat so the
42
+ * model can read the file. PERSISTED in config (not just in-process) so a file
43
+ * uploaded via a standalone `cos upload` is still attached when the shell opens
44
+ * in a separate process. Populated by upload (auto-attach) and `/attach`,
45
+ * cleared by `/detach` or logout. */
46
+ get attachedFileIds() {
47
+ return this.config.get("attachedFileIds") ?? [];
48
+ }
49
+ /** Attach a file id (deduped) so it rides along on subsequent messages. */
50
+ attachFile(fileId) {
51
+ if (!fileId)
52
+ return;
53
+ const list = this.attachedFileIds;
54
+ if (!list.includes(fileId))
55
+ this.config.set("attachedFileIds", [...list, fileId]);
56
+ }
57
+ /** Drop all attachments (an explicit /detach or logout). */
58
+ clearAttachments() {
59
+ this.config.set("attachedFileIds", []);
60
+ }
30
61
  /** A client built from current config (anonymous if not logged in). */
31
62
  client() {
32
- return new ApiClient(this.config.get("apiUrl") ?? DEFAULT_API_URL, this.authProvider());
63
+ const apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL;
64
+ return new ApiClient(apiUrl, this.authProvider(apiUrl));
33
65
  }
34
66
  /**
35
- * 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.
67
+ * The one refresh currently on the wire, shared by every request that needs it.
68
+ *
69
+ * Refresh tokens are single-use. The shell opens by loading models and modes
70
+ * in parallel, so when the stored access token has expired both requests get
71
+ * a 401 in the same instant — and each used to run its own refresh with the
72
+ * same token. The server let exactly one rotate and answered the other 409;
73
+ * the CLI read that 409 as a dead session and deleted the credentials the
74
+ * winner had just saved. The first message still went through on the fresh
75
+ * token held in memory, and the second found nothing on disk: "You're not
76
+ * signed in".
77
+ *
78
+ * Lives on the context rather than the provider because `client()` builds a
79
+ * new provider for every client, and the coordination has to span all of them.
39
80
  */
40
- authProvider() {
81
+ refreshing = null;
82
+ /** Check configured and actual destinations before exposing saved credentials. */
83
+ validateCredentialOrigin(destination = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
84
+ const auth = this.config.get("auth");
85
+ if (!auth?.accessToken && !auth?.refreshToken && !this.config.get("secretKey"))
86
+ return;
87
+ const issuer = auth?.accessToken || auth?.refreshToken ? auth.apiUrl : this.config.get("secretKeyApiUrl");
88
+ assertCredentialOrigin(issuer, this.config.get("apiUrl") ?? DEFAULT_API_URL);
89
+ assertCredentialOrigin(issuer, destination);
90
+ }
91
+ /** Credential + silent-refresh strategy, bound to the client's API base. */
92
+ authProvider(apiUrl = this.config.get("apiUrl") ?? DEFAULT_API_URL) {
41
93
  return {
42
- token: () => this.config.get("auth")?.accessToken ?? this.config.get("secretKey"),
43
- refresh: async () => {
94
+ token: (destination = apiUrl) => {
95
+ this.validateCredentialOrigin(destination);
44
96
  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
- }
97
+ if (auth?.accessToken)
98
+ return auth.accessToken;
99
+ const key = this.config.get("secretKey");
100
+ if (key)
101
+ assertCredentialOrigin(this.config.get("secretKeyApiUrl"), destination);
102
+ return key;
103
+ },
104
+ refresh: async (failedToken) => {
105
+ this.validateCredentialOrigin(apiUrl);
106
+ this.refreshing ??= this.renewSession(apiUrl, failedToken).finally(() => {
107
+ this.refreshing = null;
108
+ });
109
+ return this.refreshing;
110
+ }
111
+ };
112
+ }
113
+ /**
114
+ * Renew the session, and clear local credentials ONLY when the server says it
115
+ * is finished.
116
+ *
117
+ * Before spending the refresh token this re-reads config from disk: another
118
+ * `cos` process (a second terminal, a standalone command alongside the shell)
119
+ * may already have rotated it, in which case the token held in memory is spent
120
+ * and presenting it trips the server's reuse detection — which revokes every
121
+ * device on the account. Adopting the rotated pair avoids asking at all.
122
+ */
123
+ async renewSession(apiUrl, failedToken) {
124
+ this.config.reload();
125
+ const auth = this.config.get("auth");
126
+ if (!auth?.refreshToken)
127
+ return undefined;
128
+ this.validateCredentialOrigin(apiUrl);
129
+ // Someone already renewed since this request went out — just retry with it.
130
+ if (failedToken && auth.accessToken && auth.accessToken !== failedToken) {
131
+ return auth.accessToken;
132
+ }
133
+ const outcome = await refreshCliSession(apiUrl, auth.refreshToken);
134
+ switch (outcome.kind) {
135
+ case "ok": {
136
+ const renewed = outcome.data;
53
137
  this.config.update({
54
138
  auth: {
55
139
  ...auth,
56
140
  accessToken: renewed.access_token,
57
141
  refreshToken: renewed.refresh_token,
142
+ // Preserve the issuer that was validated before the exchange.
143
+ apiUrl: auth.apiUrl,
58
144
  workspace: renewed.workspace ?? auth.workspace,
59
145
  project: renewed.project ?? auth.project
60
146
  }
61
147
  });
62
148
  return renewed.access_token;
63
149
  }
64
- };
150
+ case "dead":
151
+ // "This session is finished" is only true when it comes from the server
152
+ // that ISSUED the session. Pointing the CLI at a different API (a local
153
+ // dev server, a mistyped --url) gets the very same 401 from a server
154
+ // that has simply never heard of it — and acting on that is
155
+ // unrecoverable, because the refresh token exists nowhere else.
156
+ //
157
+ // Signing out is therefore something the CLI does only when it is sure,
158
+ // or something the user does explicitly with `cos logout`. A refresh
159
+ // token the server has already revoked grants nothing, so leaving one on
160
+ // disk costs nothing either.
161
+ if (sameApiOrigin(auth.apiUrl, apiUrl)) {
162
+ this.config.clearAuth();
163
+ return undefined;
164
+ }
165
+ throw new ApiError("SESSION_NOT_RENEWABLE", auth.apiUrl
166
+ ? `This session was issued by ${auth.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
167
+ `Point it back with \`cos login --url ${auth.apiUrl}\`, or run \`cos logout\` to sign in here.`
168
+ : `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
169
+ "run `cos logout` and sign in again.", 401);
170
+ case "busy": {
171
+ // A different process won the rotation; its tokens are about to land in
172
+ // the shared config. Give it a moment to write them rather than guessing.
173
+ const adopted = await this.awaitRotatedElsewhere(auth.refreshToken, apiUrl);
174
+ if (adopted)
175
+ return adopted;
176
+ throw new ApiError("SESSION_BUSY", "Your session is being renewed by another Carrier OS window. Try again in a moment.", 409);
177
+ }
178
+ case "unsupported":
179
+ // Retrying cannot help: this API build has no route for the session.
180
+ throw new ApiError("SESSION_ENDPOINT_MISSING", `${apiUrl} can't renew Carrier OS sign-in sessions — it may be running an older API version. ` +
181
+ "Point Carrier OS at the API that signed you in, or run `cos logout` and sign in again.", 404);
182
+ case "transient":
183
+ // The session may be perfectly healthy — never sign someone out because
184
+ // the API had a bad second.
185
+ throw new ApiError("REFRESH_UNAVAILABLE", "Couldn't renew your session right now. Try again in a moment.", outcome.status || 503);
186
+ }
187
+ }
188
+ /** Poll the shared config briefly for a refresh token rotated by another process. */
189
+ async awaitRotatedElsewhere(spentRefreshToken, apiUrl) {
190
+ for (let attempt = 0; attempt < 10; attempt += 1) {
191
+ await new Promise((r) => setTimeout(r, 100));
192
+ this.config.reload();
193
+ const auth = this.config.get("auth");
194
+ this.validateCredentialOrigin(apiUrl);
195
+ if (auth?.refreshToken && auth.refreshToken !== spentRefreshToken && auth.accessToken) {
196
+ return auth.accessToken;
197
+ }
198
+ }
199
+ return undefined;
65
200
  }
66
201
  /**
67
202
  * A client guaranteed to carry a key, or a clean exit with guidance. Use this
@@ -69,14 +204,35 @@ export class CommandContext {
69
204
  */
70
205
  requireAuth() {
71
206
  if (!this.config.isAuthenticated) {
72
- throw new AuthRequiredError();
207
+ // Say WHY when we know: credentials that exist but cannot be opened by
208
+ // this Windows account (copied from another machine or user, or damaged)
209
+ // are a different situation from never having signed in.
210
+ throw new AuthRequiredError(this.config.credentialError
211
+ ? `${this.config.credentialError} Run \`cos login\` to sign in again.`
212
+ : undefined);
73
213
  }
74
214
  return this.client();
75
215
  }
76
- /** Active Carrier mode: the session override if set (the shell), otherwise the
77
- * persisted default, falling back to "general" (the Carrier OS persona). */
216
+ /**
217
+ * Active Carrier mode. Mode belongs to the CHAT TYPE, not the session:
218
+ *
219
+ * carrier → always "general". Carrier Chat runs one mode, so this is
220
+ * derived rather than stored — nothing chosen in Standard can
221
+ * leak in, and nothing chosen here can leak back out.
222
+ * standard → the session override, else the persisted default, else "auto"
223
+ * (Standard is the only place Auto routing applies).
224
+ *
225
+ * Deriving it is what keeps a Carrier→Standard switch from stranding you in
226
+ * General: there is no carrier mode to carry over in the first place.
227
+ */
78
228
  get mode() {
79
- return this.overrideMode ?? this.config.get("mode") ?? "general";
229
+ if (this.chatType === "carrier")
230
+ return "general";
231
+ return this.overrideMode ?? this.config.get("mode") ?? "auto";
232
+ }
233
+ /** True when the active chat type lets the user choose a mode at all. */
234
+ get modeIsSelectable() {
235
+ return this.chatType !== "carrier";
80
236
  }
81
237
  /** Set the mode for this process only (interactive shell), without persisting. */
82
238
  setSessionMode(id) {
@@ -94,5 +250,122 @@ export class CommandContext {
94
250
  setChatType(type) {
95
251
  this.config.set("chatType", type);
96
252
  this.config.set("sessionId", undefined);
253
+ // Drop the session's mode override so the new chat type lands on its own
254
+ // default (carrier → General, standard → the saved mode or Auto) instead of
255
+ // inheriting a mode the user picked for the type they just left.
256
+ this.overrideMode = undefined;
257
+ }
258
+ /** Persisted web-search preference. `undefined` means "not chosen here" — the
259
+ * API then falls back to the workspace's admin toggle, which is what the web
260
+ * app does. `/websearch on|off` persists a choice that wins over that. */
261
+ get webSearch() {
262
+ return this.config.get("webSearch");
263
+ }
264
+ setWebSearch(on) {
265
+ this.config.set("webSearch", on);
266
+ }
267
+ /** One-shot arm from a bare `/websearch`: search the NEXT message, then go
268
+ * back to whatever the persisted preference was. Deliberately in-process —
269
+ * an armed turn that never got sent shouldn't survive into a new session. */
270
+ armed = false;
271
+ get webSearchArmed() {
272
+ return this.armed;
273
+ }
274
+ armWebSearch() {
275
+ this.armed = true;
276
+ }
277
+ disarmWebSearch() {
278
+ this.armed = false;
279
+ }
280
+ /** What to send as `web_search` on the next turn: forced on while armed,
281
+ * otherwise the persisted preference (undefined = follow the workspace). */
282
+ get effectiveWebSearch() {
283
+ return this.armed ? true : this.webSearch;
284
+ }
285
+ /**
286
+ * Fast mode — Llama via Groq instead of the selected model.
287
+ *
288
+ * STANDARD CHAT ONLY, mirroring the web's `isRestrictedType`: it forces
289
+ * fastMode off for `carrier`/`temp` conversations even when one has the flag
290
+ * stored. Deriving it here rather than clearing the setting means switching
291
+ * Carrier → Standard restores whatever the user last chose, instead of
292
+ * silently losing it on every round trip.
293
+ */
294
+ get fast() {
295
+ if (this.chatType !== "standard")
296
+ return false;
297
+ return this.config.get("fast") === true;
298
+ }
299
+ setFast(on) {
300
+ this.config.set("fast", on);
301
+ }
302
+ /** High Power (HIPWR) — the 4-pass refinement pipeline. Persisted, but the
303
+ * server still treats it as opt-in per request and admin-gated. */
304
+ get highPower() {
305
+ return this.config.get("highPower") === true;
306
+ }
307
+ setHighPower(on) {
308
+ this.config.set("highPower", on);
309
+ }
310
+ /** SIA clarification — ask before sending, rather than guessing at an
311
+ * ambiguous prompt. Off by default, like the web composer's toggle. */
312
+ get siaMode() {
313
+ // STANDARD CHAT ONLY, derived the same way `fast` is: Carrier Chat runs its
314
+ // own behaviour layer and the web shows no SIA control there. Deriving
315
+ // rather than clearing means a Carrier -> Standard switch restores whatever
316
+ // the user last chose instead of silently losing it.
317
+ if (this.chatType !== "standard")
318
+ return "off";
319
+ const stored = this.config.get("sia");
320
+ // Legacy booleans from before the mode existed: true meant "consult the
321
+ // backend", which is exactly what auto does now.
322
+ if (stored === true)
323
+ return "auto";
324
+ if (stored === false)
325
+ return "off";
326
+ // Unset is OFF, as the web composer's toggle is. Defaulting to auto put
327
+ // clarifying questions in front of every coding task ("should the subtotal
328
+ // include discounts?") before the agent had even read the repository.
329
+ return stored === "auto" ? "auto" : "off";
330
+ }
331
+ /** True when a turn should ask the backend whether clarification is needed. */
332
+ get sia() {
333
+ return this.siaMode === "auto";
334
+ }
335
+ setSiaMode(mode) {
336
+ this.config.set("sia", mode);
337
+ }
338
+ /**
339
+ * True while a main chat turn is rendering in the background.
340
+ *
341
+ * Runtime-only (never persisted): the shell sets it when it detaches a turn
342
+ * so commands that share the terminal — `/btw` — can tell who owns the
343
+ * transient region.
344
+ */
345
+ mainTurnRunning = false;
346
+ /** Read-only Admin Panel Carrier Chat switch, refreshed by the shell. Null
347
+ * means it could not yet be verified; the send gate checks again. */
348
+ carrierMaintenance = null;
349
+ /**
350
+ * Credits this shell session's turns were actually debited, summed from the
351
+ * server's per-turn `credits_spent`. Runtime-only: "this session" means this
352
+ * process. Background context maintenance is billed separately on the server
353
+ * and is not a turn, so it is not in here — `/usage` reports it.
354
+ */
355
+ sessionCreditsSpent = 0;
356
+ /** Whether any turn this session reported its spend (older APIs do not). */
357
+ sessionSpendKnown = false;
358
+ /** Citations from the most recent turn that returned any, so /sources and
359
+ * /open can act on them after the answer has scrolled away. */
360
+ lastSearch = null;
361
+ recordSearch(sources) {
362
+ if (sources.length > 0)
363
+ this.lastSearch = { sources, at: Date.now() };
364
+ }
365
+ get lastSources() {
366
+ return this.lastSearch?.sources ?? [];
367
+ }
368
+ get lastSearchAt() {
369
+ return this.lastSearch?.at ?? null;
97
370
  }
98
371
  }
@@ -1,8 +1,8 @@
1
- import { spawn } from "node:child_process";
2
1
  import os from "node:os";
3
2
  import axios, { isAxiosError } from "axios";
4
3
  import { ApiError } from "./api.js";
5
4
  import { cliVersion } from "./meta.js";
5
+ import { openUrl } from "./open-url.js";
6
6
  import { sleep } from "./spinner.js";
7
7
  /**
8
8
  * device-auth — the transport for the OAuth 2.0 Device Authorization (RFC 8628)
@@ -20,21 +20,50 @@ export function platformAuthBase(apiUrl) {
20
20
  const origin = trimmed.replace(/\/v\d+$/i, ""); // drop a trailing /v1
21
21
  return `${origin}/api/platform/auth`;
22
22
  }
23
- /** Local platform default (dev convenience): when the API is on localhost, the
24
- * browser step should open the local platform (typically :3002) rather than the
25
- * production URL the API returns when PLATFORM_FRONTEND_URL isn't set. Override
26
- * the port with CARRIEROS_PLATFORM_URL. Returns undefined for non-local APIs. */
27
- export function localPlatformDefault(apiUrl) {
23
+ /** Dedicated user-owned CLI auth endpoints; existing sessions retain their issuer. */
24
+ export function userCliAuthBase(apiUrl) {
25
+ return platformAuthBase(apiUrl).replace(/\/platform\/auth$/, "/cli/auth");
26
+ }
27
+ /** Unverified claims select an endpoint only; the server authenticates the token.
28
+ * Both choices stay on the configured, origin-validated API. */
29
+ export function cliSessionAuthBase(apiUrl, token) {
28
30
  try {
29
- const host = new URL(apiUrl).hostname;
30
- if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
31
- return "http://localhost:3002";
32
- }
31
+ const claims = JSON.parse(Buffer.from((token ?? "").split(".")[1], "base64url").toString("utf8"));
32
+ if (claims.realm === "carrier-cli")
33
+ return userCliAuthBase(apiUrl);
34
+ }
35
+ catch { /* legacy and opaque credentials retain their original endpoint */ }
36
+ return platformAuthBase(apiUrl);
37
+ }
38
+ /** Is this URL pointing at the machine we are running on? */
39
+ function isLoopback(url) {
40
+ try {
41
+ const host = new URL(url).hostname;
42
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
33
43
  }
34
44
  catch {
35
- /* not a parseable URL — no local default */
45
+ return false;
36
46
  }
37
- return undefined;
47
+ }
48
+ /**
49
+ * Local authorization-site default (dev convenience).
50
+ *
51
+ * The browser step happens on the MAIN Carrier OS site now, so against a local
52
+ * API this opens the local main site (:3000) rather than the production URL the
53
+ * API returns when CLI_AUTHORIZE_URL / FRONTEND_URL aren't set.
54
+ *
55
+ * It deliberately stands down when the API already returned a loopback URL: an
56
+ * API that IS configured knows where its authorization page lives — possibly on
57
+ * a different port than this guess — and overriding it would send the browser
58
+ * somewhere with no such page. The guess only covers a local API that handed
59
+ * back a production URL.
60
+ *
61
+ * Override with CARRIEROS_PLATFORM_URL or `--platform`.
62
+ */
63
+ export function localAuthorizeDefault(apiUrl, verificationUri) {
64
+ if (verificationUri && isLoopback(verificationUri))
65
+ return undefined;
66
+ return isLoopback(apiUrl) ? "http://localhost:3000" : undefined;
38
67
  }
39
68
  /** Swap the origin (scheme + host) of a URL, preserving its path + query. Lets
40
69
  * the CLI point the browser at a local platform during development without the
@@ -91,20 +120,14 @@ export function cliUserAgent() {
91
120
  return `CarrierOS-CLI/${cliVersion()} (${osName()}; ${clientName()})`;
92
121
  }
93
122
  /** Open a URL in the user's default browser, cross-platform, with no extra deps.
94
- * Best-effort: if it fails the caller still shows the URL to open manually. */
123
+ * Best-effort: if it fails the caller still shows the URL to open manually.
124
+ *
125
+ * Goes through the same checked, shell-free opener as every other link: the
126
+ * URL comes from the server, and a `cmd /c start` here would let a `&` in it
127
+ * run a second command. */
95
128
  export function openBrowser(url) {
96
129
  try {
97
- if (process.platform === "win32") {
98
- // `start` is a cmd builtin; the empty "" is the window title (avoids the
99
- // URL being consumed as the title when it contains spaces/&).
100
- spawn("cmd", ["/c", "start", "", url], { stdio: "ignore", detached: true }).unref();
101
- }
102
- else if (process.platform === "darwin") {
103
- spawn("open", [url], { stdio: "ignore", detached: true }).unref();
104
- }
105
- else {
106
- spawn("xdg-open", [url], { stdio: "ignore", detached: true }).unref();
107
- }
130
+ openUrl(url);
108
131
  return true;
109
132
  }
110
133
  catch {
@@ -122,6 +145,7 @@ async function envelopePost(url, body, headers) {
122
145
  ...(headers ?? {})
123
146
  },
124
147
  timeout: 30_000,
148
+ maxRedirects: 0,
125
149
  validateStatus: () => true
126
150
  });
127
151
  return { status: res.status, body: res.data };
@@ -162,13 +186,19 @@ async function pollOnce(authBase, deviceCode) {
162
186
  }
163
187
  /** Step 2 (loop) — poll until approved, denied, expired, or timed out. Calls
164
188
  * `onTick` between polls so the caller can animate a spinner. */
165
- export async function pollForToken(authBase, start, onTick) {
189
+ export async function pollForToken(authBase, start, onTick,
190
+ /** Stops polling: an approval that arrives after it is never used. */
191
+ signal) {
166
192
  let intervalMs = Math.max(1, start.interval || 5) * 1000;
167
193
  const deadline = Date.now() + Math.max(1, start.expires_in || 600) * 1000;
168
194
  while (Date.now() < deadline) {
169
195
  onTick?.();
170
196
  await sleep(intervalMs);
197
+ if (signal?.aborted)
198
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
171
199
  const outcome = await pollOnce(authBase, start.device_code);
200
+ if (signal?.aborted)
201
+ throw new ApiError("SIGN_IN_CANCELLED", "Sign-in cancelled.");
172
202
  switch (outcome.kind) {
173
203
  case "approved":
174
204
  return outcome.data;
@@ -187,21 +217,27 @@ export async function pollForToken(authBase, start, onTick) {
187
217
  }
188
218
  throw new ApiError("TIMEOUT", "Timed out waiting for approval. Run `cos login` again.");
189
219
  }
190
- /** Silently exchange a refresh token for a new session (rotation). Returns null
191
- * if the session is no longer valid (caller should clear + re-login). */
220
+ /** Exchange a refresh token for a new session (rotation). Never clears anything
221
+ * itself — the caller decides, from the outcome, whether the session is over. */
192
222
  export async function refreshCliSession(apiUrl, refreshToken) {
193
- const authBase = platformAuthBase(apiUrl);
194
- const { body } = await envelopePost(`${authBase}/cli/refresh`, {
223
+ const authBase = cliSessionAuthBase(apiUrl, refreshToken);
224
+ const { status, body } = await envelopePost(`${authBase}/cli/refresh`, {
195
225
  refresh_token: refreshToken
196
226
  });
197
227
  if (body?.success && body.data)
198
- return body.data;
199
- return null;
228
+ return { kind: "ok", data: body.data };
229
+ if (status === 401)
230
+ return { kind: "dead" };
231
+ if (status === 409)
232
+ return { kind: "busy" };
233
+ if (status === 404)
234
+ return { kind: "unsupported" };
235
+ return { kind: "transient", status };
200
236
  }
201
237
  /** Best-effort server-side logout (revokes the refresh token). Never throws. */
202
238
  export async function logoutCliSession(apiUrl, refreshToken) {
203
239
  try {
204
- await envelopePost(`${platformAuthBase(apiUrl)}/cli/logout`, { refresh_token: refreshToken });
240
+ await envelopePost(`${cliSessionAuthBase(apiUrl, refreshToken)}/cli/logout`, { refresh_token: refreshToken });
205
241
  }
206
242
  catch {
207
243
  /* offline logout is fine — the local credentials are cleared regardless */
@@ -209,8 +245,8 @@ export async function logoutCliSession(apiUrl, refreshToken) {
209
245
  }
210
246
  // ── Authenticated /cli/* management (bearer access token, refresh-on-401) ─────
211
247
  async function authedRequest(apiUrl, method, path, provider, body, retry = true) {
212
- const url = `${platformAuthBase(apiUrl)}${path}`;
213
- const token = provider.token();
248
+ const token = provider.token(apiUrl);
249
+ const url = `${cliSessionAuthBase(apiUrl, token)}${path}`;
214
250
  const res = await axios.request({
215
251
  url,
216
252
  method,
@@ -220,10 +256,11 @@ async function authedRequest(apiUrl, method, path, provider, body, retry = true)
220
256
  ...(token ? { Authorization: `Bearer ${token}` } : {})
221
257
  },
222
258
  timeout: 30_000,
259
+ maxRedirects: 0,
223
260
  validateStatus: () => true
224
261
  });
225
262
  if (res.status === 401 && retry && provider.refresh) {
226
- const renewed = await provider.refresh();
263
+ const renewed = await provider.refresh(token);
227
264
  if (renewed)
228
265
  return authedRequest(apiUrl, method, path, provider, body, false);
229
266
  }