@carrieros/cli 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,9 +33,11 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
33
33
  // runs (or while a review is open) never changes what this turn may do.
34
34
  const permission = permissionPolicy(ports.permissionMode ?? "manual");
35
35
  const mutationTools = permission.changeTools ? ideDeclaredMutationTools(ctx, ports.approverPresent) : undefined;
36
- // Commands (tests): the CLI's own gate — opt-in, contained runtime, trusted
37
- // repository — with "approver present" meaning this panel can show the review.
38
- const commandTools = mutationTools && permission.commands && ports.commandsAllowed && ports.reviewCommand ? declaredCommandTools(ctx, ports.approverPresent) : undefined;
36
+ // Commands have their own gate, separate from file changes: CLI opt-in or
37
+ // Auto mode, contained runtime, trusted repository, and live panel decision UI.
38
+ const commandTools = permission.commands && ports.commandsAllowed && ports.reviewCommand
39
+ ? declaredCommandTools(ctx, ports.commandsAllowed && !!ports.reviewCommand, ports.permissionMode === "auto")
40
+ : undefined;
39
41
  const emit = (event) => {
40
42
  try {
41
43
  ports.onWorkflowEvent?.(event);
@@ -158,7 +160,7 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
158
160
  review: async (decision, reason, repository, operationId) => {
159
161
  if (signal.aborted)
160
162
  return "cancel";
161
- // Auto: a contained R0/R1 command is approved by the session's policy, and says so.
163
+ // Auto: locally admitted commands are approved by session policy, and say so.
162
164
  if (permission.approveCommandByPolicy(decision.tier)) {
163
165
  emit({ kind: "command_auto_approved", command: displayCommand(decision.program, decision.effectiveArgs), tier: decision.tier });
164
166
  return "approve";
@@ -194,7 +196,10 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
194
196
  // whether it is still the same repository and the same bytes. Context only.
195
197
  const taskFiles = workflow ? new TaskFileLedger() : undefined;
196
198
  const ownerScope = workflow ? client.mutationRecoveryScope() : undefined;
197
- const sessionId = ctx.config.get("sessionId");
199
+ const hasSessionOverride = Object.prototype.hasOwnProperty.call(ports, "sessionId");
200
+ const sessionId = hasSessionOverride ? ports.sessionId : ctx.config.get("sessionId");
201
+ const chatType = ports.chatType ?? ctx.chatType;
202
+ let resultSessionId = sessionId;
198
203
  const compose = ports.composeMessage ?? ((m) => m);
199
204
  // What the model has said so far. It narrates as it works; commit each span at
200
205
  // a tool boundary so a progress line lands above the activity it describes.
@@ -230,13 +235,16 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
230
235
  model: ctx.config.get("model") || undefined,
231
236
  message: compose(message),
232
237
  session_id: sessionId,
233
- chat_type: ctx.chatType,
238
+ chat_type: chatType,
239
+ file_ids: ports.fileIds?.length ? ports.fileIds : undefined,
240
+ ...(ports.webSearch === true ? { web_search: true } : {}),
234
241
  // Fast Mode and High Power, shared with the CLI's /fast and /hipwr.
235
242
  speed: ctx.fast ? "fast" : undefined,
236
243
  high_power: ctx.highPower ? true : undefined,
237
244
  // Reads + editor context; the file-changing tools only when an
238
245
  // approver is present; in coding mode also the workflow gate and the
239
- // command tool (each command still needs its own approval).
246
+ // command tool (Manual/Accept Edits review each command; Auto follows
247
+ // command policy without an individual prompt).
240
248
  client_tools: workflow && readTools ? [...readTools, "coding_workflow"] : readTools,
241
249
  client_mutation_tools: mutationTools,
242
250
  ...(commandTools ? { client_command_tools: commandTools } : {}),
@@ -282,11 +290,12 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
282
290
  workflow.interrupt();
283
291
  emitOutcome(workflow, outcome, mutations, emit);
284
292
  }
285
- if (result.session_id && result.session_id !== sessionId) {
293
+ resultSessionId = result.session_id ?? sessionId;
294
+ if (!hasSessionOverride && result.session_id && result.session_id !== sessionId) {
286
295
  ctx.config.set("sessionId", result.session_id);
287
296
  rememberPermissionMode(ctx.config);
288
297
  }
289
- return { response: result.response, sessionId: result.session_id ?? sessionId, applied: mutations?.applied ?? [] };
298
+ return { response: result.response, sessionId: resultSessionId, applied: mutations?.applied ?? [] };
290
299
  }
291
300
  catch (err) {
292
301
  if (workflow) {
@@ -296,7 +305,7 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
296
305
  const e = err;
297
306
  return {
298
307
  response: streamed,
299
- sessionId,
308
+ sessionId: resultSessionId,
300
309
  applied: mutations?.applied ?? [],
301
310
  error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed.", ...(e.reason ? { reason: e.reason } : {}) }
302
311
  };
@@ -307,7 +316,7 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
307
316
  // Hash what this turn read or changed, as it is on disk now, for the next
308
317
  // turn's freshness report — also after a failed or cancelled turn.
309
318
  taskFiles?.touchApplied(mutations?.applied ?? []);
310
- taskFiles?.commit(ownerScope, ctx.config.get("sessionId"));
319
+ taskFiles?.commit(ownerScope, resultSessionId);
311
320
  // However the turn ended, nothing it left open — a change review or a
312
321
  // command dialog — may still be approved and apply or run afterwards.
313
322
  controller.abort();
@@ -92,10 +92,10 @@ export function ideDeclaredReadTools(ctx) {
92
92
  * present, no mutation tools are declared, exactly as a piped CLI run offers
93
93
  * none.
94
94
  *
95
- * Commands are deliberately NOT offered on the IDE surface in V1: the CLI's
96
- * `run_command` depends on Windows Job Object containment wired to the terminal
97
- * lifecycle and an explicit opt-in, and porting that containment to the IDE is a
98
- * separate security review. Until then the IDE stays read + change only.
95
+ * Commands are offered only when the extension has a live command decision UI,
96
+ * the CLI opt-in or Auto mode enables them, the repository is trusted, and the
97
+ * shared executor reports the required containment adapter. The CLI's existing
98
+ * coordinator performs the actual policy and approval decision.
99
99
  */
100
100
  export function ideDeclaredMutationTools(ctx, approverPresent) {
101
101
  if (!approverPresent)
package/dist/main.js CHANGED
@@ -31,17 +31,26 @@ import { registerVersion } from "./commands/version.js";
31
31
  import { registerWhoami } from "./commands/whoami.js";
32
32
  import { ApiError } from "./services/api.js";
33
33
  import { ConfigStore } from "./services/config.js";
34
+ import { setClientIdentity, setClientReleaseChannel } from "./services/meta.js";
35
+ import { isPackaged } from "./services/packaged.js";
36
+ import { updateSettings } from "./services/auto-update.js";
34
37
  import { AuthRequiredError, CommandContext } from "./services/context.js";
35
38
  import { cliVersion } from "./services/meta.js";
36
39
  import { errorLine } from "./services/output.js";
37
40
  import { runShell } from "./shell/shell.js";
38
41
  import { loadAccent } from "./ui/theme.js";
39
42
  async function main() {
40
- const ctx = new CommandContext(new ConfigStore());
43
+ const stagingProfile = process.env.CARRIEROS_CLI_PROFILE === "staging";
44
+ const ctx = new CommandContext(new ConfigStore(stagingProfile
45
+ ? { fixedApiUrl: "https://api.carrieros.site/v1" }
46
+ : {}));
41
47
  // Trust is per repository, so the registry has to be able to read it.
42
48
  attachConfig(ctx.config);
43
49
  // Restore the saved accent color before anything renders.
44
50
  loadAccent(ctx.config.get("theme")?.accent);
51
+ // Identify this client on every API request (version + release channel).
52
+ setClientIdentity(isPackaged() ? "cli-exe" : "cli");
53
+ setClientReleaseChannel(updateSettings(ctx.config).channel);
45
54
  const program = new Command();
46
55
  program
47
56
  .name("cos")
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { clientHeaders } from "./meta.js";
2
3
  import path from "node:path";
3
4
  import axios, { isAxiosError } from "axios";
4
5
  import FormData from "form-data";
@@ -82,6 +83,7 @@ export class ApiClient {
82
83
  const withAuth = {
83
84
  ...config,
84
85
  headers: {
86
+ ...clientHeaders(),
85
87
  ...(config.headers ?? {}),
86
88
  ...(token ? { Authorization: `Bearer ${token}` } : {})
87
89
  }
@@ -182,7 +184,7 @@ export class ApiClient {
182
184
  // No client-side timeout: a turn legitimately idles while a local tool
183
185
  // runs, and the server's keep-alive pings hold the socket open.
184
186
  timeout: 0,
185
- headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
187
+ headers: { ...clientHeaders(), Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
186
188
  validateStatus: () => true
187
189
  });
188
190
  }
@@ -363,8 +365,8 @@ export class ApiClient {
363
365
  sessionMessages(id) {
364
366
  return this.request({ method: "GET", url: `/sessions/${id}/messages` });
365
367
  }
366
- createSession(title) {
367
- return this.request({ method: "POST", url: "/sessions", data: { title } });
368
+ createSession(title, chatType) {
369
+ return this.request({ method: "POST", url: "/sessions", data: { title, ...(chatType ? { chat_type: chatType } : {}) } });
368
370
  }
369
371
  /**
370
372
  * /compact: replace the conversation's earlier messages in the model's
@@ -0,0 +1,221 @@
1
+ import { cliVersion } from "./meta.js";
2
+ import { acquireUpdateLock, checkChannel, compareVersions, defaultUpdateChannel, detectInstallation, installedGlobalVersion, isUpdateChannel, manualUpdateCommand, otherLiveInstances, packageName, registerInstance, releaseUpdateLock, startDetachedInstall, updateInProgress } from "./update.js";
3
+ /**
4
+ * Automatic updates for the npm-installed CLI (Claude Code-style).
5
+ *
6
+ * • Checks the configured channel at startup (when the last check is older
7
+ * than the interval) and then every interval while the CLI runs. Checks are
8
+ * async, one at a time, and never block the composer.
9
+ * • A newer release on a writable global npm install is installed in the
10
+ * BACKGROUND WHEN YOU EXIT, by a detached `npm install -g <pkg>@<exact>`,
11
+ * and only if no other CLI window is still open — a running CLI never has
12
+ * its package replaced underneath it. The next launch verifies the result
13
+ * (it is running the new version, or it is not) and says so once.
14
+ * • Local, development, npx and unwritable installs are never modified; they
15
+ * get the right manual instruction, once per version.
16
+ * • Nothing here prints directly: notices go to `notify`, which the shell
17
+ * shows between turns, never in the middle of one.
18
+ *
19
+ * The Windows installer build has its own verified updater (packaged-update.ts)
20
+ * and is not handled here.
21
+ */
22
+ export const DEFAULT_CHECK_INTERVAL_HOURS = 6;
23
+ const MIN_INTERVAL_HOURS = 1;
24
+ const MAX_INTERVAL_HOURS = 168;
25
+ export function updateSettings(config) {
26
+ const hours = Number(config.get("updateCheckIntervalHours"));
27
+ const channel = config.get("updateChannel");
28
+ return {
29
+ autoUpdates: config.get("autoUpdates") !== false && process.env.CARRIEROS_DISABLE_AUTOUPDATE !== "1",
30
+ // A staging package always follows the staging tag. This prevents a stale
31
+ // or manually copied production preference from making it query the wrong
32
+ // channel or recommend the production package.
33
+ channel: packageName() === "@carrieros/cli-staging"
34
+ ? "staging"
35
+ : isUpdateChannel(channel) ? channel : defaultUpdateChannel(),
36
+ intervalHours: Number.isFinite(hours) && hours > 0
37
+ ? Math.min(MAX_INTERVAL_HOURS, Math.max(MIN_INTERVAL_HOURS, Math.round(hours)))
38
+ : DEFAULT_CHECK_INTERVAL_HOURS
39
+ };
40
+ }
41
+ export class AutoUpdater {
42
+ opts;
43
+ checking = null;
44
+ timer = null;
45
+ pending = null;
46
+ install = null;
47
+ unregister = null;
48
+ current;
49
+ installation;
50
+ now;
51
+ constructor(opts) {
52
+ this.opts = opts;
53
+ this.current = opts.current ?? cliVersion;
54
+ this.installation = opts.installation ?? (() => detectInstallation());
55
+ this.now = opts.now ?? Date.now;
56
+ }
57
+ /** The version that will be installed on exit, if any. */
58
+ get pendingVersion() {
59
+ return this.pending;
60
+ }
61
+ /** Begin: report the last background install, register this window, check. */
62
+ start() {
63
+ // Never run inside an update's own child process.
64
+ if (process.env.CARRIEROS_UPDATING === "1")
65
+ return;
66
+ this.unregister = registerInstance(this.opts.dir);
67
+ this.reportPreviousInstall();
68
+ const { intervalHours } = updateSettings(this.opts.config);
69
+ if (this.due(intervalHours))
70
+ setImmediate(() => void this.check());
71
+ // Not due for a fresh check: still act on the last result we know about, so
72
+ // an update skipped in an earlier session (another window was open, the
73
+ // folder was read-only…) is not forgotten until the next network check.
74
+ else
75
+ setImmediate(() => void this.actOnCached());
76
+ this.timer = setInterval(() => void this.check(), intervalHours * 3600_000);
77
+ this.timer.unref?.();
78
+ }
79
+ stop() {
80
+ if (this.timer)
81
+ clearInterval(this.timer);
82
+ this.timer = null;
83
+ this.unregister?.();
84
+ this.unregister = null;
85
+ }
86
+ due(intervalHours) {
87
+ const last = Math.max(this.opts.config.get("updateCheckAt") ?? 0, this.opts.config.get("updateCheckErrorAt") ?? 0);
88
+ return this.now() - last >= intervalHours * 3600_000;
89
+ }
90
+ /**
91
+ * The outcome of an install started when an earlier session exited. Verified
92
+ * by what is actually running now — never assumed from npm's exit code.
93
+ */
94
+ reportPreviousInstall() {
95
+ const pending = this.opts.config.get("pendingUpdate");
96
+ if (!pending)
97
+ return;
98
+ if (this.current() === pending.version) {
99
+ this.opts.notify(`CarrierOS CLI ${pending.version} has been installed successfully.`);
100
+ this.opts.config.set("pendingUpdate", undefined);
101
+ this.opts.config.set("updateFailedVersion", undefined);
102
+ return;
103
+ }
104
+ // Still running in the background: say nothing yet.
105
+ if (updateInProgress(this.opts.dir, this.now()))
106
+ return;
107
+ const channel = packageName() === "@carrieros/cli-staging"
108
+ ? "staging"
109
+ : isUpdateChannel(pending.channel) ? pending.channel : defaultUpdateChannel();
110
+ this.opts.notify(`CarrierOS CLI could not be updated automatically. You can update manually using: ${manualUpdateCommand(channel)}`);
111
+ // Not retried automatically: a failing install would otherwise repeat on every exit.
112
+ this.opts.config.set("updateFailedVersion", pending.version);
113
+ this.opts.config.set("pendingUpdate", undefined);
114
+ }
115
+ /** One check at a time; a call while one runs waits for that one. */
116
+ check() {
117
+ if (!this.checking) {
118
+ this.checking = this.runCheck().finally(() => {
119
+ this.checking = null;
120
+ });
121
+ }
122
+ return this.checking;
123
+ }
124
+ /** Act on the cached latest version, without contacting the registry. */
125
+ async actOnCached() {
126
+ const latest = this.opts.config.get("latestCliVersion");
127
+ const current = this.current();
128
+ if (!latest)
129
+ return;
130
+ try {
131
+ if (compareVersions(latest, current) <= 0)
132
+ return;
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ await this.act(latest, current);
138
+ }
139
+ async runCheck() {
140
+ const { channel } = updateSettings(this.opts.config);
141
+ let state;
142
+ try {
143
+ state = await checkChannel(channel, this.current());
144
+ }
145
+ catch {
146
+ this.opts.config.set("updateCheckErrorAt", this.now());
147
+ return;
148
+ }
149
+ if (state.kind === "unreachable" || state.kind === "no-npm" || state.kind === "no-channel") {
150
+ // Recorded, never shown: an offline registry is not the user's problem.
151
+ this.opts.config.set("updateCheckErrorAt", this.now());
152
+ return;
153
+ }
154
+ this.opts.config.set("latestCliVersion", state.latest);
155
+ this.opts.config.set("updateCheckAt", this.now());
156
+ if (state.kind !== "available")
157
+ return;
158
+ await this.act(state.latest, state.current);
159
+ }
160
+ /** A newer version is known: arrange the background install or tell the user how to update. */
161
+ async act(version, current) {
162
+ const { autoUpdates, channel } = updateSettings(this.opts.config);
163
+ const install = await this.installation().catch(() => ({ kind: "unknown" }));
164
+ this.install = install;
165
+ const name = packageName();
166
+ const failedBefore = this.opts.config.get("updateFailedVersion") === version;
167
+ if (autoUpdates && install.kind === "global" && install.writable && !failedBefore) {
168
+ this.pending = version;
169
+ this.notifyOnce(version, "auto", `CarrierOS CLI ${version} is available. You are currently using ${current}. It will be installed in the background when you exit.`);
170
+ return;
171
+ }
172
+ if (install.kind === "global" && !install.writable) {
173
+ this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Your global npm folder is not writable, so update manually: ${manualUpdateCommand(channel, name)}`);
174
+ return;
175
+ }
176
+ if (install.kind === "local") {
177
+ this.notifyOnce(version, "local", `CarrierOS CLI ${version} is available. This copy is a project dependency — update it with your package manager, e.g. npm install ${name}@${version}`);
178
+ return;
179
+ }
180
+ if (install.kind === "npx") {
181
+ this.notifyOnce(version, "npx", `CarrierOS CLI ${version} is available. Run npx ${name}@${channel} to use it.`);
182
+ return;
183
+ }
184
+ if (install.kind === "development")
185
+ return; // a checkout follows its own branch
186
+ this.notifyOnce(version, "manual", `CarrierOS CLI ${version} is available. Run /update to install it.`);
187
+ }
188
+ /** Each notice once per version and kind — across sessions. */
189
+ notifyOnce(version, kind, message) {
190
+ const key = `${version}:${kind}`;
191
+ if (this.opts.config.get("updateNoticeShown") === key)
192
+ return;
193
+ this.opts.config.set("updateNoticeShown", key);
194
+ this.opts.notify(message);
195
+ }
196
+ /**
197
+ * Leaving the CLI: start the pending background install. Skipped while
198
+ * another CLI window is open (it would have files replaced under it) or
199
+ * another update holds the lock; the next exit tries again.
200
+ */
201
+ onExit() {
202
+ this.stop();
203
+ const version = this.pending;
204
+ if (!version)
205
+ return false;
206
+ // Already on disk (e.g. /update ran during the session): nothing to do.
207
+ if (this.install?.globalRoot && installedGlobalVersion(this.install.globalRoot) === version)
208
+ return false;
209
+ if (otherLiveInstances(this.opts.dir) > 0)
210
+ return false;
211
+ if (!acquireUpdateLock(this.opts.dir, process.pid, this.now()))
212
+ return false;
213
+ const { channel } = updateSettings(this.opts.config);
214
+ if (!startDetachedInstall(this.opts.dir, version)) {
215
+ releaseUpdateLock(this.opts.dir);
216
+ return false;
217
+ }
218
+ this.opts.config.set("pendingUpdate", { version, channel, startedAt: this.now() });
219
+ return true;
220
+ }
221
+ }
@@ -64,27 +64,31 @@ export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
64
64
  *
65
65
  * Everything file changes require — the interactive screen and a trusted
66
66
  * folder — plus a configured platform containment adapter,
67
- * plus an explicit opt-in. The Windows path still runs project code with the
68
- * user's permissions; isolation does not make commands enabled by default.
67
+ * plus an explicit opt-in. In Auto mode that opt-in is the mode selection
68
+ * itself; an explicit `/settings commands off` remains a hard stop. The Windows
69
+ * path still runs project code with the user's permissions.
69
70
  */
70
- export function declaredCommandTools(ctx, approverPresent = inScreen()) {
71
- const state = localCommandsState(ctx, approverPresent);
71
+ export function declaredCommandTools(ctx, approverPresent = inScreen(), autoMode = false) {
72
+ const state = localCommandsState(ctx, approverPresent, autoMode);
72
73
  return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
73
74
  }
74
75
  /**
75
76
  * Whether local commands are on, why, and what (if anything) stops them.
76
77
  *
77
- * ON means the user chose it: the persisted `/settings commands on`, or the
78
- * original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in, which keeps working so nobody
79
- * who relied on it has to migrate. Even when ON, the tool is only offered in
80
- * the interactive shell, with the platform's containment prerequisite, in a
81
- * trusted repository. Runtime health is checked again before execution.
78
+ * ON means the user chose it: Auto mode, `/settings commands on`, or the
79
+ * original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in. An explicit persisted OFF is
80
+ * a hard stop. Even when ON, the tool is only offered in an interactive
81
+ * session, with platform containment and a trusted repository. Runtime health
82
+ * is checked again before execution.
82
83
  */
83
- export function localCommandsState(ctx, approverPresent = inScreen()) {
84
+ export function localCommandsState(ctx, approverPresent = inScreen(), autoMode = false) {
84
85
  const fromEnv = process.env[COMMANDS_OPT_IN_ENV] === "1";
85
- const fromSetting = ctx.config.get("localCommandsEnabled") === true;
86
- const enabled = fromEnv || fromSetting;
87
- const source = fromSetting ? "setting" : fromEnv ? "env" : null;
86
+ const localSetting = ctx.config.get("localCommandsEnabled");
87
+ const fromSetting = localSetting === true;
88
+ // Choosing Auto is itself an explicit command-execution opt-in. A persisted
89
+ // OFF is a deliberate kill switch and wins over Auto.
90
+ const enabled = localSetting !== false && (fromEnv || fromSetting || autoMode);
91
+ const source = !enabled ? null : fromSetting ? "setting" : fromEnv ? "env" : autoMode ? "auto" : null;
88
92
  let blockedBy = null;
89
93
  if (enabled) {
90
94
  try {
@@ -224,8 +224,8 @@ export class CodingWorkflow {
224
224
  const approvalRequired = actions.some(a => a.tool === "edit_file" || a.tool === "run_command");
225
225
  return { required: actions.length > 0, state: this.state, validation: this.validation(), missing_reads: missing, next_actions: actions, approval_required: approvalRequired,
226
226
  mutation_approval_complete: mutationApprovalComplete,
227
- ...(this.state === "ANALYZING_FAILURE" ? { guidance: this.analyzed ? "Read every listed missing_reads file completely in one parallel read batch where supported, then submit the corrective plan and invoke its mutation tool for a new diff review. Analysis invalidated earlier reads; do not ask for approval in prose." : "Invoke coding_workflow analyze now using the actual failed command evidence. Complete analysis before rereading files: analysis invalidates earlier reads. Then batch all listed fresh reads before corrective planning. Only the mutation tool opens correction approval; prose cannot request or grant it." } : {}),
228
- ...(!this.plan && ["TASK_RECEIVED", "INSPECTING"].includes(this.state) ? { guidance: "If the user asked for a code change: complete the listed reads, submit coding_workflow plan, then invoke the mutation tool — its diff review collects the user's approval, so never ask for permission or show a proposed diff in prose. If the user only asked a question, answer it directly without planning." } : {}),
227
+ ...(this.state === "ANALYZING_FAILURE" ? { guidance: this.analyzed ? "Read every listed missing_reads file completely in one parallel read batch where supported, then submit the corrective plan and present the correction through the file-change workflow for a new review. Analysis invalidated earlier reads; do not ask for approval in prose." : "Run coding_workflow analyze now using the actual failed command evidence. Complete analysis before rereading files: analysis invalidates earlier reads. Then batch all listed fresh reads before corrective planning. Present the correction for approval through the file-change workflow; prose cannot request or grant approval." } : {}),
228
+ ...(!this.plan && ["TASK_RECEIVED", "INSPECTING"].includes(this.state) ? { guidance: "If the user asked for a code change: complete the listed reads, submit coding_workflow plan, then present the concrete edit through the file-change workflow so its review collects the user's approval. Never ask for permission or show a proposed diff in prose. If the user only asked a question, answer it directly without planning." } : {}),
229
229
  ...(mutationApprovalComplete && actions.some(a => a.tool === "run_command") ? { guidance: "The mutations were already approved and verified applied. Invoke the listed run_command now; its existing command review collects command approval. Do not ask for the completed mutation approval again in prose." } : {}) };
230
230
  }
231
231
  async control(call) {
@@ -79,7 +79,7 @@ function validateConfig(value) {
79
79
  if (!value || typeof value !== "object" || Array.isArray(value))
80
80
  throw new ConfigReadError();
81
81
  const data = value;
82
- const strings = ["apiUrl", "platformUrl", "secretKey", "secretKeyApiUrl", "sessionId", "sessionTitle", "mode", "model", "latestCliVersion"];
82
+ const strings = ["apiUrl", "platformUrl", "secretKey", "secretKeyApiUrl", "sessionId", "sessionSelectionToken", "sessionTitle", "mode", "model", "latestCliVersion"];
83
83
  const booleans = ["webSearch", "fast", "highPower", "localCommandsEnabled", "projectContextPending"];
84
84
  const arrays = ["sessionOrdinals", "memoryArtifactIds", "attachedFileIds", "trustedFolders"];
85
85
  for (const key of strings)
@@ -112,6 +112,7 @@ export class ConfigStore {
112
112
  file;
113
113
  /** The config with credentials OPENED — what every caller reads. */
114
114
  data;
115
+ options;
115
116
  /**
116
117
  * Why stored credentials could not be opened, when they could not: another
117
118
  * Windows account, another machine, or a damaged blob. The CLI then behaves
@@ -119,9 +120,13 @@ export class ConfigStore {
119
120
  * `cos login` is the recovery and nothing is lost by trying.
120
121
  */
121
122
  credentialError = null;
122
- constructor() {
123
+ constructor(options = {}) {
124
+ this.options = options;
123
125
  this.dir = ConfigStore.resolveDir();
124
- this.file = path.join(this.dir, "config.json");
126
+ const fileName = options.fileName ?? "config.json";
127
+ if (path.basename(fileName) !== fileName || !fileName.endsWith(".json"))
128
+ throw new Error("Config filename must be a JSON file name.");
129
+ this.file = path.join(this.dir, fileName);
125
130
  this.data = this.reveal(this.read());
126
131
  this.protectPlaintextCredentials();
127
132
  }
@@ -217,24 +222,36 @@ export class ConfigStore {
217
222
  }
218
223
  static resolveDir() {
219
224
  const appData = process.env.APPDATA;
225
+ const profile = process.env.CARRIEROS_CLI_PROFILE === "staging" ? "staging" : undefined;
220
226
  if (appData)
221
- return path.join(appData, "CarrierOS");
222
- return path.join(os.homedir(), ".carrieros");
227
+ return path.join(appData, "CarrierOS", ...(profile ? [profile] : []));
228
+ return path.join(os.homedir(), ".carrieros", ...(profile ? [profile] : []));
223
229
  }
224
230
  read() {
231
+ const defaults = {
232
+ apiUrl: this.options.fixedApiUrl ?? this.options.defaultApiUrl ?? DEFAULT_API_URL,
233
+ ...(this.options.fixedPlatformUrl || this.options.defaultPlatformUrl
234
+ ? { platformUrl: this.options.fixedPlatformUrl ?? this.options.defaultPlatformUrl }
235
+ : {})
236
+ };
225
237
  let source;
226
238
  try {
227
239
  source = fs.readFileSync(this.file, "utf8");
228
240
  }
229
241
  catch (err) {
230
242
  if (err.code === "ENOENT")
231
- return { apiUrl: DEFAULT_API_URL };
243
+ return defaults;
232
244
  throw new ConfigReadError();
233
245
  }
234
246
  try {
235
247
  const parsed = JSON.parse(source);
236
248
  validateConfig(parsed);
237
- return { apiUrl: DEFAULT_API_URL, ...parsed };
249
+ return {
250
+ ...defaults,
251
+ ...parsed,
252
+ ...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
253
+ ...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
254
+ };
238
255
  }
239
256
  catch {
240
257
  // Never include the parser error: its source excerpt can contain tokens.
@@ -251,7 +268,12 @@ export class ConfigStore {
251
268
  commit(patch, remove = []) {
252
269
  // Merge in DISK form: what is already there stays sealed, and the patch is
253
270
  // sealed before it joins it. Plaintext credentials never reach the file.
254
- const merged = { ...this.read(), ...this.conceal(patch) };
271
+ const merged = {
272
+ ...this.read(),
273
+ ...this.conceal(patch),
274
+ ...(this.options.fixedApiUrl ? { apiUrl: this.options.fixedApiUrl } : {}),
275
+ ...(this.options.fixedPlatformUrl ? { platformUrl: this.options.fixedPlatformUrl } : {})
276
+ };
255
277
  for (const key of remove)
256
278
  delete merged[key];
257
279
  validateConfig(merged);
@@ -345,6 +367,7 @@ export class ConfigStore {
345
367
  "secretKey",
346
368
  "secretKeyApiUrl",
347
369
  "sessionId",
370
+ "sessionSelectionToken",
348
371
  "sessionTitle",
349
372
  "sessionOrdinals",
350
373
  "memoryArtifactIds",
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import { ApiClient, ApiError } from "./api.js";
2
3
  import { DEFAULT_API_URL, sameApiOrigin } from "./config.js";
3
4
  import { refreshCliSession } from "./device-auth.js";
@@ -20,8 +21,38 @@ export class AuthRequiredError extends Error {
20
21
  */
21
22
  export class CommandContext {
22
23
  config;
24
+ _sessionSelectionToken;
23
25
  constructor(config) {
24
26
  this.config = config;
27
+ this._sessionSelectionToken = config.get("sessionSelectionToken");
28
+ }
29
+ /** In-process generation for intentional changes to the shell's active chat. */
30
+ _sessionSelectionRevision = 0;
31
+ get sessionSelectionRevision() { return this._sessionSelectionRevision; }
32
+ get sessionSelectionToken() { return this._sessionSelectionToken; }
33
+ noteSessionSelectionChanged() {
34
+ this._sessionSelectionRevision += 1;
35
+ this._sessionSelectionToken = crypto.randomUUID();
36
+ this.config.set("sessionSelectionToken", this._sessionSelectionToken);
37
+ }
38
+ /**
39
+ * Record the ID returned by a turn only if the user has not selected or
40
+ * cleared another conversation while that turn was running. Reload first so
41
+ * a separate CLI process changing the shared active conversation is respected.
42
+ */
43
+ rememberTurnSession(id, expectedId, expectedRevision, expectedToken) {
44
+ this.config.reload();
45
+ const storedToken = this.config.get("sessionSelectionToken");
46
+ if (storedToken !== this._sessionSelectionToken) {
47
+ this._sessionSelectionToken = storedToken;
48
+ this._sessionSelectionRevision += 1;
49
+ }
50
+ if (this._sessionSelectionRevision !== expectedRevision || this._sessionSelectionToken !== expectedToken ||
51
+ storedToken !== expectedToken || this.config.get("sessionId") !== expectedId)
52
+ return false;
53
+ this.config.set("sessionId", id);
54
+ this.noteSessionSelectionChanged();
55
+ return true;
25
56
  }
26
57
  /** In-process mode override. The interactive shell always OPENS in the Carrier
27
58
  * OS mode (the core persona) regardless of the persisted default; setting the
@@ -158,13 +189,27 @@ export class CommandContext {
158
189
  // or something the user does explicitly with `cos logout`. A refresh
159
190
  // token the server has already revoked grants nothing, so leaving one on
160
191
  // disk costs nothing either.
161
- if (sameApiOrigin(auth.apiUrl, apiUrl)) {
192
+ // Another CLI process may have rotated the refresh token after our
193
+ // preflight reload but before this server answered. Re-read before
194
+ // treating 401 as logout; adopt a newer pair instead of deleting it.
195
+ this.config.reload();
196
+ const latest = this.config.get("auth");
197
+ if (latest?.refreshToken && latest.refreshToken !== auth.refreshToken) {
198
+ this.validateCredentialOrigin(apiUrl);
199
+ return latest.accessToken;
200
+ }
201
+ // An explicit logout may also have happened while refresh was in flight.
202
+ // Do not clear again or erase a subsequent sign-in.
203
+ if (!latest?.refreshToken)
204
+ return undefined;
205
+ if (sameApiOrigin(latest.apiUrl, apiUrl)) {
206
+ this.noteSessionSelectionChanged();
162
207
  this.config.clearAuth();
163
208
  return undefined;
164
209
  }
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.`
210
+ throw new ApiError("SESSION_NOT_RENEWABLE", latest.apiUrl
211
+ ? `This session was issued by ${latest.apiUrl}, but the CLI is pointed at ${apiUrl}. ` +
212
+ `Point it back with \`cos login --url ${latest.apiUrl}\`, or run \`cos logout\` to sign in here.`
168
213
  : `${apiUrl} would not renew this session. If you signed out elsewhere or changed API URL, ` +
169
214
  "run `cos logout` and sign in again.", 401);
170
215
  case "busy": {
@@ -238,11 +283,10 @@ export class CommandContext {
238
283
  setSessionMode(id) {
239
284
  this.overrideMode = id;
240
285
  }
241
- /** Active chat experience: "carrier" (flagship Carrier Chat) by default — you
242
- * always land in Carrier Chat, matching the web app. Persisted so a chosen
243
- * type survives across invocations; reset to carrier on login. */
286
+ /** Active chat experience: Standard by default. Persisted so an explicit
287
+ * choice survives across invocations; a fresh login starts in Standard. */
244
288
  get chatType() {
245
- return this.config.get("chatType") ?? "carrier";
289
+ return this.config.get("chatType") ?? "standard";
246
290
  }
247
291
  /** Switch chat type. Because a conversation's type is fixed at creation, this
248
292
  * clears the active session so the NEXT message starts a fresh conversation of
@@ -250,6 +294,7 @@ export class CommandContext {
250
294
  setChatType(type) {
251
295
  this.config.set("chatType", type);
252
296
  this.config.set("sessionId", undefined);
297
+ this.noteSessionSelectionChanged();
253
298
  // Drop the session's mode override so the new chat type lands on its own
254
299
  // default (carrier → General, standard → the saved mode or Auto) instead of
255
300
  // inheriting a mode the user picked for the type they just left.