@carrieros/cli-staging 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.
@@ -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
+ }
@@ -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)
@@ -367,6 +367,7 @@ export class ConfigStore {
367
367
  "secretKey",
368
368
  "secretKeyApiUrl",
369
369
  "sessionId",
370
+ "sessionSelectionToken",
370
371
  "sessionTitle",
371
372
  "sessionOrdinals",
372
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.
@@ -1,7 +1,7 @@
1
1
  import os from "node:os";
2
2
  import axios, { isAxiosError } from "axios";
3
3
  import { ApiError } from "./api.js";
4
- import { cliVersion } from "./meta.js";
4
+ import { cliVersion, clientHeaders } from "./meta.js";
5
5
  import { openUrl } from "./open-url.js";
6
6
  import { sleep } from "./spinner.js";
7
7
  /**
@@ -142,6 +142,7 @@ async function envelopePost(url, body, headers) {
142
142
  headers: {
143
143
  "Content-Type": "application/json",
144
144
  "User-Agent": cliUserAgent(),
145
+ ...clientHeaders(),
145
146
  ...(headers ?? {})
146
147
  },
147
148
  timeout: 30_000,
@@ -253,6 +254,7 @@ async function authedRequest(apiUrl, method, path, provider, body, retry = true)
253
254
  data: body,
254
255
  headers: {
255
256
  "Content-Type": "application/json",
257
+ ...clientHeaders(),
256
258
  ...(token ? { Authorization: `Bearer ${token}` } : {})
257
259
  },
258
260
  timeout: 30_000,
@@ -96,7 +96,7 @@ async function renderAuthorized(ctx, tokens, apiUrl) {
96
96
  }
97
97
  return scope;
98
98
  }
99
- /** Save the issued tokens + a cached scope; land in Carrier Chat by default.
99
+ /** Save the issued tokens + a cached scope; land in Standard chat by default.
100
100
  * (Unchanged behaviour — persistence + a verify to confirm the token works.) */
101
101
  export async function persistSession(ctx, tokens, issuer) {
102
102
  ctx.config.update({
@@ -111,8 +111,8 @@ export async function persistSession(ctx, tokens, issuer) {
111
111
  }
112
112
  });
113
113
  // A conversation keeps its type forever. Reset the saved session too: a
114
- // previous Standard session must not resume under the new Carrier label.
115
- ctx.setChatType("carrier");
114
+ // previous conversation must not resume under a different account.
115
+ ctx.setChatType("standard");
116
116
  ctx.config.set("sessionTitle", undefined);
117
117
  let scope;
118
118
  try {
@@ -13,3 +13,30 @@ export function cliVersion() {
13
13
  return "0.0.0";
14
14
  }
15
15
  }
16
+ /**
17
+ * Which client is talking to the API, sent on every request:
18
+ *
19
+ * X-CarrierOS-Client: cli/0.4.1 | cli-exe/0.4.1 | vscode/0.2.1
20
+ * X-CarrierOS-Channel: latest | beta | next | staging (when known)
21
+ *
22
+ * Only the client kind, its version and its release channel — never a path,
23
+ * user name, token or anything else from the machine. Servers that do not read
24
+ * these headers ignore them, so older APIs are unaffected.
25
+ */
26
+ let clientKind = "cli";
27
+ let clientVersionOverride = null;
28
+ let releaseChannel = null;
29
+ /** Set once at startup: "cli-exe" for the packaged build, "vscode" for the extension. */
30
+ export function setClientIdentity(kind, version) {
31
+ clientKind = kind;
32
+ clientVersionOverride = version && /^[0-9A-Za-z.+-]{1,64}$/.test(version) ? version : null;
33
+ }
34
+ export function setClientReleaseChannel(channel) {
35
+ releaseChannel = channel && /^(latest|beta|next|staging)$/.test(channel) ? channel : null;
36
+ }
37
+ export function clientHeaders() {
38
+ return {
39
+ "X-CarrierOS-Client": `${clientKind}/${clientVersionOverride ?? cliVersion()}`,
40
+ ...(releaseChannel ? { "X-CarrierOS-Channel": releaseChannel } : {})
41
+ };
42
+ }
@@ -99,6 +99,7 @@ export async function resolveSession(ctx, client, ref) {
99
99
  /** Remember the active session and its title so the footer can name it. */
100
100
  export function setActiveSession(ctx, id, title) {
101
101
  ctx.config.set("sessionId", id);
102
+ ctx.noteSessionSelectionChanged();
102
103
  if (title !== undefined)
103
104
  ctx.config.set("sessionTitle", title);
104
105
  // Resuming: the conversation's own permission mode. Approvals are never restored.
@@ -108,6 +109,7 @@ export function setActiveSession(ctx, id, title) {
108
109
  export function clearActiveSession(ctx) {
109
110
  ctx.config.set("sessionId", undefined);
110
111
  ctx.config.set("sessionTitle", undefined);
112
+ ctx.noteSessionSelectionChanged();
111
113
  // A new task never inherits Accept Edits authority or Plan state.
112
114
  resetPermissionMode(ctx.config);
113
115
  }