@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.
@@ -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
+ }
@@ -4,12 +4,30 @@ const EXPLAIN = {
4
4
  manual: "Every file change and every command asks for your approval.",
5
5
  plan: "Investigate and plan only. No file changes or commands are available.",
6
6
  accept_edits: "File changes can be applied without individual approval. Commands still require approval.",
7
- auto: "File changes and test commands run without asking. A command that writes files or installs packages still asks."
7
+ auto: "File changes and commands admitted by local policy run without individual prompts. Trust, command policy and runtime checks still apply."
8
8
  };
9
9
  /** Sessions whose mode is remembered for resume; older entries are dropped. */
10
10
  const REMEMBERED = 50;
11
11
  export const permissionModeLabel = (m) => LABELS[m];
12
12
  export const permissionModeExplanation = (m) => EXPLAIN[m];
13
+ /** Explain the local file-change gates truthfully in the model context. */
14
+ export function localEditPolicyHint(mode, workspaceTrusted, fileChangesEnabled) {
15
+ if (mode === "plan")
16
+ return null;
17
+ if (!workspaceTrusted) {
18
+ return `[LOCAL EDIT STATUS] The user selected ${permissionModeLabel(mode)}, but this VS Code workspace is in Restricted Mode. Do not mention internal tools or session capabilities. Explain simply that VS Code must trust this workspace before Carrier OS can make file changes, and ask the user to trust it using VS Code's Workspace Trust controls, then retry. Do not imply that the selected permission mode overrides workspace trust.`;
19
+ }
20
+ if (!fileChangesEnabled) {
21
+ return `[LOCAL EDIT STATUS] The user selected ${permissionModeLabel(mode)}, but file changes are disabled in Carrier OS settings. Do not mention internal tools or session capabilities. Explain simply that file changes are turned off, and tell the user to open VS Code Settings (Ctrl/Cmd+,), search for "Carrier OS: Enable File Changes", enable it, and retry. Do not imply that the selected permission mode overrides this setting.`;
22
+ }
23
+ if (mode === "auto") {
24
+ return "[LOCAL EDIT POLICY] The user selected Auto. For requested code changes, inspect the relevant files and submit the concrete edit through the available file-change workflow; do not answer with patch instructions alone. The local coordinator applies admitted changes under Auto policy without an individual diff prompt, while workspace trust, freshness, containment, checkpoints, recovery and cancellation checks still apply.";
25
+ }
26
+ if (mode === "accept_edits") {
27
+ return "[LOCAL EDIT POLICY] The user selected Accept Edits. For requested code changes, inspect the relevant files and submit the concrete edit through the available file-change workflow; do not answer with patch instructions alone. File edits apply under this mode without an individual prompt; commands still use their separate approval and execution gates.";
28
+ }
29
+ return "[LOCAL EDIT POLICY] The user selected Manual. For requested code changes, inspect the relevant files and submit the concrete edit through the available file-change workflow; it opens the required diff review. Do not replace the review with a prose patch or prose approval question.";
30
+ }
13
31
  /** "accept-edits", "Accept Edits", "accept_edits", "acceptedits" → accept_edits; unknown → undefined. */
14
32
  export function parsePermissionMode(value) {
15
33
  const v = typeof value === "string" ? value.trim().toLowerCase().replace(/[\s-]+/g, "_") : "";
@@ -55,6 +73,6 @@ export function permissionPolicy(mode) {
55
73
  changeTools: mode !== "plan",
56
74
  commands: mode !== "plan",
57
75
  approveEditsByPolicy: mode === "accept_edits" || mode === "auto",
58
- approveCommandByPolicy: (tier) => mode === "auto" && (tier === "R0" || tier === "R1")
76
+ approveCommandByPolicy: () => mode === "auto"
59
77
  };
60
78
  }
@@ -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
  }
@@ -1,4 +1,4 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
@@ -309,3 +309,422 @@ export function refreshUpdateCache(cache, now = Date.now()) {
309
309
  cache.set("updateCheckErrorAt", now);
310
310
  }
311
311
  }
312
+ // ── Channels, installation kinds, background installs ───────────────────────
313
+ // Everything below is async (child_process.spawn), so a check or install never
314
+ // blocks the composer, and takes its npm runner from one injectable seam so the
315
+ // tests never touch the real registry or a real global install.
316
+ /** npm dist-tags a CLI may follow. Never chosen from remote data. */
317
+ export const UPDATE_CHANNELS = ["latest", "beta", "next", "staging"];
318
+ export function isUpdateChannel(v) {
319
+ return typeof v === "string" && UPDATE_CHANNELS.includes(v);
320
+ }
321
+ /**
322
+ * Packages this CLI may ever install. The name comes from the CLI's OWN
323
+ * package.json, so the staging build (@carrieros/cli-staging) only ever updates
324
+ * itself and can never pull the production package over a staging install.
325
+ */
326
+ const ALLOWED_PACKAGES = new Set(["@carrieros/cli", "@carrieros/cli-staging"]);
327
+ export function packageName() {
328
+ try {
329
+ const pkgUrl = new URL("../../package.json", import.meta.url);
330
+ const name = JSON.parse(fs.readFileSync(fileURLToPath(pkgUrl), "utf8")).name;
331
+ if (name && ALLOWED_PACKAGES.has(name))
332
+ return name;
333
+ }
334
+ catch {
335
+ /* packaged executable: no package.json on disk */
336
+ }
337
+ return PACKAGE_NAME;
338
+ }
339
+ /** The isolated staging package must follow its own non-latest npm dist-tag. */
340
+ export function defaultUpdateChannel(name = packageName()) {
341
+ return name === "@carrieros/cli-staging" ? "staging" : "latest";
342
+ }
343
+ /** The manual command for a channel — what every failure message offers. */
344
+ export function manualUpdateCommand(channel = defaultUpdateChannel(), name = packageName()) {
345
+ return `npm install -g ${name}@${channel}`;
346
+ }
347
+ /** Output cap: npm can print a lot, and only the tail is ever shown. */
348
+ const MAX_OUTPUT = 64 * 1024;
349
+ const spawnNpm = (args, timeoutMs) => new Promise((resolve) => {
350
+ let stdout = "";
351
+ let stderr = "";
352
+ let settled = false;
353
+ const finish = (r) => {
354
+ if (!settled) {
355
+ settled = true;
356
+ resolve(r);
357
+ }
358
+ };
359
+ let child;
360
+ try {
361
+ // Same rule as runNpm: every argument is a constant, an allow-listed
362
+ // package name, a validated semver or an allow-listed dist-tag.
363
+ child = SPAWN_SHELL
364
+ ? spawn([NPM_BIN, ...args].join(" "), { shell: true, windowsHide: true, env: { ...process.env, CARRIEROS_UPDATING: "1" } })
365
+ : spawn(NPM_BIN, args, { windowsHide: true, env: { ...process.env, CARRIEROS_UPDATING: "1" } });
366
+ }
367
+ catch (err) {
368
+ finish({ status: null, stdout: "", stderr: "", error: err });
369
+ return;
370
+ }
371
+ const timer = setTimeout(() => {
372
+ child.kill();
373
+ finish({ status: null, stdout, stderr, error: Object.assign(new Error("npm timed out"), { code: "ETIMEDOUT" }) });
374
+ }, timeoutMs);
375
+ timer.unref?.();
376
+ child.stdout?.on("data", (d) => { if (stdout.length < MAX_OUTPUT)
377
+ stdout += String(d); });
378
+ child.stderr?.on("data", (d) => { if (stderr.length < MAX_OUTPUT)
379
+ stderr += String(d); });
380
+ child.on("error", (err) => { clearTimeout(timer); finish({ status: null, stdout, stderr, error: err }); });
381
+ child.on("close", (code) => { clearTimeout(timer); finish({ status: code, stdout, stderr }); });
382
+ });
383
+ let npmRunner = spawnNpm;
384
+ /** Test seam: replace npm with a fake. Passing null restores the real one. */
385
+ export function setNpmRunnerForTests(runner) {
386
+ npmRunner = runner ?? spawnNpm;
387
+ }
388
+ /**
389
+ * The version a channel currently points at, from the package's npm dist-tags.
390
+ * Only a well-formed semver is ever returned; anything else is a failure.
391
+ */
392
+ export async function fetchChannelVersion(channel = defaultUpdateChannel(), name = packageName()) {
393
+ if (!isUpdateChannel(channel))
394
+ return { ok: false, reason: "failed", detail: "Unknown update channel." };
395
+ const res = await npmRunner(["view", name, "dist-tags", "--json"], VIEW_TIMEOUT_MS);
396
+ if (res.error?.code === "ENOENT")
397
+ return { ok: false, reason: "no-npm", detail: "npm was not found on this system." };
398
+ if (res.error)
399
+ return { ok: false, reason: "failed", detail: res.error.code === "ETIMEDOUT" ? "The npm registry did not answer in time." : res.error.message };
400
+ if (res.status !== 0) {
401
+ const first = String(res.stderr || res.stdout || "").trim().split("\n")[0];
402
+ return { ok: false, reason: "failed", detail: first || "npm exited with code " + res.status };
403
+ }
404
+ let tags;
405
+ try {
406
+ tags = JSON.parse(String(res.stdout || "").trim());
407
+ }
408
+ catch {
409
+ return { ok: false, reason: "failed", detail: "Unexpected npm output." };
410
+ }
411
+ if (!tags || typeof tags !== "object" || Array.isArray(tags))
412
+ return { ok: false, reason: "failed", detail: "Unexpected npm output." };
413
+ const version = tags[channel];
414
+ if (version === undefined)
415
+ return { ok: false, reason: "no-channel", detail: `Nothing is published on the "${channel}" channel yet.` };
416
+ if (!isVersionLike(version))
417
+ return { ok: false, reason: "failed", detail: "The registry returned an invalid version." };
418
+ return { ok: true, version: version.trim() };
419
+ }
420
+ /** Current vs the channel's version, as one state for messages and decisions. */
421
+ export async function checkChannel(channel = defaultUpdateChannel(), current = getCurrentVersion()) {
422
+ const latest = await fetchChannelVersion(channel);
423
+ if (!latest.ok) {
424
+ if (latest.reason === "no-npm")
425
+ return { kind: "no-npm", current };
426
+ if (latest.reason === "no-channel")
427
+ return { kind: "no-channel", current, channel, detail: latest.detail };
428
+ return { kind: "unreachable", current, detail: latest.detail };
429
+ }
430
+ let cmp;
431
+ try {
432
+ cmp = compareVersions(current, latest.version);
433
+ }
434
+ catch {
435
+ return { kind: "unreachable", current, detail: "The installed version could not be read." };
436
+ }
437
+ if (cmp === 0)
438
+ return { kind: "current", current, latest: latest.version };
439
+ return cmp < 0 ? { kind: "available", current, latest: latest.version } : { kind: "ahead", current, latest: latest.version };
440
+ }
441
+ async function globalRootAsync() {
442
+ const res = await npmRunner(["root", "-g"], VIEW_TIMEOUT_MS);
443
+ if (res.error || res.status !== 0)
444
+ return null;
445
+ const out = String(res.stdout || "").trim();
446
+ // npm redacts strings that look like secrets in everything it prints —
447
+ // including a UUID-like folder in a path, shown as "***". A redacted path is
448
+ // not a path; never compare against it.
449
+ if (!out || out.includes("***"))
450
+ return null;
451
+ return path.resolve(out);
452
+ }
453
+ function realpathSafe(p) {
454
+ try {
455
+ return fs.realpathSync(p);
456
+ }
457
+ catch {
458
+ return path.resolve(p);
459
+ }
460
+ }
461
+ /**
462
+ * Where npm's global packages can live, computed without parsing npm output:
463
+ * an explicit NPM_CONFIG_PREFIX, npm's default prefix next to this Node, and
464
+ * the per-user Windows location.
465
+ */
466
+ export function globalRootCandidates(env = process.env, execPath = process.execPath, platform = process.platform) {
467
+ const nm = (prefix) => (platform === "win32" ? path.join(prefix, "node_modules") : path.join(prefix, "lib", "node_modules"));
468
+ const out = [];
469
+ const prefix = env.NPM_CONFIG_PREFIX || env.npm_config_prefix;
470
+ if (prefix)
471
+ out.push(nm(prefix));
472
+ out.push(platform === "win32" ? path.join(path.dirname(execPath), "node_modules") : nm(path.dirname(path.dirname(execPath))));
473
+ if (platform === "win32" && env.APPDATA)
474
+ out.push(path.join(env.APPDATA, "npm", "node_modules"));
475
+ return out;
476
+ }
477
+ /**
478
+ * The global root implied by the install layout itself: a global package sits
479
+ * at <prefix>/lib/node_modules/<pkg> with its launcher in <prefix>/bin (on
480
+ * Windows: <prefix>/node_modules/<pkg> with <prefix>/cos.cmd). A project
481
+ * dependency's launcher lives in node_modules/.bin instead, so the two cannot
482
+ * be confused.
483
+ */
484
+ export function layoutGlobalRoot(here, name = packageName(), platform = process.platform) {
485
+ const depth = name.split("/").length;
486
+ let nmDir = here;
487
+ for (let i = 0; i < depth; i++)
488
+ nmDir = path.dirname(nmDir);
489
+ if (path.basename(nmDir) !== "node_modules")
490
+ return null;
491
+ const bins = ["cos", "carrieros", "cos-staging"];
492
+ if (platform === "win32") {
493
+ const prefix = path.dirname(nmDir);
494
+ return bins.some((b) => fs.existsSync(path.join(prefix, b + ".cmd"))) ? nmDir : null;
495
+ }
496
+ const lib = path.dirname(nmDir);
497
+ if (path.basename(lib) !== "lib")
498
+ return null;
499
+ const prefix = path.dirname(lib);
500
+ return bins.some((b) => fs.existsSync(path.join(prefix, "bin", b))) ? nmDir : null;
501
+ }
502
+ export async function detectInstallation(opts = {}) {
503
+ if (opts.packaged)
504
+ return { kind: "packaged" };
505
+ const here = opts.here === undefined ? packageRoot() : opts.here;
506
+ if (!here)
507
+ return { kind: "unknown" };
508
+ const parts = here.split(/[\\/]+/);
509
+ if (parts.includes("_npx"))
510
+ return { kind: "npx" };
511
+ // Compare REAL paths: the launcher is usually a symlink, and /tmp-style
512
+ // aliases differ from what the module was loaded from.
513
+ const real = realpathSafe(here);
514
+ const npmRoot = await globalRootAsync();
515
+ const candidates = [...(npmRoot ? [npmRoot] : []), ...globalRootCandidates()];
516
+ const globalRoot = candidates.map(realpathSafe).find((root) => isInside(root, real)) ?? layoutGlobalRoot(real) ?? null;
517
+ if (globalRoot) {
518
+ const installed = path.join(globalRoot, ...packageName().split("/"));
519
+ try {
520
+ if (fs.lstatSync(installed).isSymbolicLink())
521
+ return { kind: "development", globalRoot };
522
+ }
523
+ catch {
524
+ /* fall through */
525
+ }
526
+ let writable = false;
527
+ try {
528
+ fs.accessSync(globalRoot, fs.constants.W_OK);
529
+ fs.accessSync(here, fs.constants.W_OK);
530
+ writable = true;
531
+ }
532
+ catch {
533
+ writable = false;
534
+ }
535
+ return { kind: "global", globalRoot, writable };
536
+ }
537
+ if (parts.includes("node_modules"))
538
+ return { kind: "local" };
539
+ return { kind: "development" };
540
+ }
541
+ /** The version on disk for the global install, read fresh (never cliVersion()). */
542
+ export function installedGlobalVersion(globalRoot, name = packageName()) {
543
+ try {
544
+ const parsed = JSON.parse(fs.readFileSync(path.join(globalRoot, ...name.split("/"), "package.json"), "utf8"));
545
+ return isVersionLike(parsed.version) ? parsed.version : null;
546
+ }
547
+ catch {
548
+ return null;
549
+ }
550
+ }
551
+ /**
552
+ * Install one EXACT version (never a moving tag), then read back what is on
553
+ * disk. Success means the expected version is installed, not that npm exited 0.
554
+ */
555
+ export async function installExactVersion(version, globalRoot, name = packageName()) {
556
+ if (!isVersionLike(version) || !ALLOWED_PACKAGES.has(name)) {
557
+ return { ok: false, detail: "Refused: unexpected package or version.", permission: false, installed: null };
558
+ }
559
+ const res = await npmRunner(["install", "-g", `${name}@${version}`], INSTALL_TIMEOUT_MS);
560
+ const output = (String(res.stdout || "") + "\n" + String(res.stderr || "")).trim();
561
+ if (res.error) {
562
+ return {
563
+ ok: false,
564
+ detail: res.error.code === "ENOENT" ? "npm was not found on this system." : res.error.message,
565
+ permission: false,
566
+ installed: null
567
+ };
568
+ }
569
+ if (res.status !== 0) {
570
+ return {
571
+ ok: false,
572
+ detail: lastMeaningfulLines(output) || "npm exited with code " + res.status,
573
+ permission: /EACCES|EPERM|permission denied|Access is denied/i.test(output),
574
+ installed: null
575
+ };
576
+ }
577
+ const root = globalRoot ?? (await globalRootAsync()) ?? globalRootCandidates().find((r) => fs.existsSync(path.join(r, ...name.split("/")))) ?? null;
578
+ const installed = root ? installedGlobalVersion(root, name) : null;
579
+ return installed === version
580
+ ? { ok: true, detail: output, permission: false, installed }
581
+ : { ok: false, detail: `npm finished but ${name}@${version} was not found on disk.`, permission: false, installed };
582
+ }
583
+ // ── Cross-process coordination ──────────────────────────────────────────────
584
+ function pidAlive(pid) {
585
+ if (!Number.isInteger(pid) || pid <= 0)
586
+ return false;
587
+ try {
588
+ process.kill(pid, 0);
589
+ return true;
590
+ }
591
+ catch (err) {
592
+ return err.code === "EPERM";
593
+ }
594
+ }
595
+ /** A stale lock (owner gone, or older than this) is taken over. */
596
+ const LOCK_STALE_MS = 30 * 60 * 1000;
597
+ /**
598
+ * One update at a time across every CLI window on the machine. The lock file
599
+ * holds the owning pid; a dead owner or an old lock is stale and replaced.
600
+ */
601
+ export function acquireUpdateLock(dir, pid = process.pid, now = Date.now()) {
602
+ const file = path.join(dir, "update.lock");
603
+ for (let attempt = 0; attempt < 2; attempt++) {
604
+ try {
605
+ fs.mkdirSync(dir, { recursive: true });
606
+ fs.writeFileSync(file, JSON.stringify({ pid, at: now }), { flag: "wx" });
607
+ return true;
608
+ }
609
+ catch (err) {
610
+ if (err.code !== "EEXIST")
611
+ return false;
612
+ try {
613
+ const held = JSON.parse(fs.readFileSync(file, "utf8"));
614
+ const stale = !pidAlive(Number(held.pid)) || now - Number(held.at ?? 0) > LOCK_STALE_MS;
615
+ if (!stale)
616
+ return false;
617
+ fs.rmSync(file, { force: true });
618
+ }
619
+ catch {
620
+ fs.rmSync(file, { force: true });
621
+ }
622
+ }
623
+ }
624
+ return false;
625
+ }
626
+ /** Hand the lock to another process (the detached installer) or rewrite it. */
627
+ export function transferUpdateLock(dir, pid, now = Date.now()) {
628
+ try {
629
+ fs.writeFileSync(path.join(dir, "update.lock"), JSON.stringify({ pid, at: now }));
630
+ }
631
+ catch {
632
+ /* best effort */
633
+ }
634
+ }
635
+ export function releaseUpdateLock(dir, pid = process.pid) {
636
+ const file = path.join(dir, "update.lock");
637
+ try {
638
+ const held = JSON.parse(fs.readFileSync(file, "utf8"));
639
+ if (Number(held.pid) === pid)
640
+ fs.rmSync(file, { force: true });
641
+ }
642
+ catch {
643
+ /* nothing held */
644
+ }
645
+ }
646
+ /** True while an update (in this or another process) holds the lock. */
647
+ export function updateInProgress(dir, now = Date.now()) {
648
+ try {
649
+ const held = JSON.parse(fs.readFileSync(path.join(dir, "update.lock"), "utf8"));
650
+ return pidAlive(Number(held.pid)) && now - Number(held.at ?? 0) <= LOCK_STALE_MS;
651
+ }
652
+ catch {
653
+ return false;
654
+ }
655
+ }
656
+ /**
657
+ * Live CLI windows on this machine. A background install replaces files on
658
+ * disk, so it waits until the last window has closed: no running CLI ever has
659
+ * its package swapped underneath it.
660
+ */
661
+ export function registerInstance(dir, pid = process.pid) {
662
+ const instances = path.join(dir, "instances");
663
+ const file = path.join(instances, String(pid));
664
+ try {
665
+ fs.mkdirSync(instances, { recursive: true });
666
+ fs.writeFileSync(file, String(Date.now()));
667
+ }
668
+ catch {
669
+ /* best effort */
670
+ }
671
+ return () => fs.rmSync(file, { force: true });
672
+ }
673
+ export function otherLiveInstances(dir, pid = process.pid) {
674
+ const instances = path.join(dir, "instances");
675
+ let names = [];
676
+ try {
677
+ names = fs.readdirSync(instances);
678
+ }
679
+ catch {
680
+ return 0;
681
+ }
682
+ let live = 0;
683
+ for (const name of names) {
684
+ const other = Number(name);
685
+ if (other === pid)
686
+ continue;
687
+ if (pidAlive(other))
688
+ live++;
689
+ else
690
+ fs.rmSync(path.join(instances, name), { force: true });
691
+ }
692
+ return live;
693
+ }
694
+ /** Start npm detached, output to a log file; returns its pid. */
695
+ const spawnDetachedNpm = (command, args, logFile) => {
696
+ let fd = null;
697
+ try {
698
+ fd = fs.openSync(logFile, "w");
699
+ const child = SPAWN_SHELL
700
+ ? spawn([command, ...args].join(" "), { shell: true, detached: true, windowsHide: true, stdio: ["ignore", fd, fd], env: { ...process.env, CARRIEROS_UPDATING: "1" } })
701
+ : spawn(command, args, { detached: true, windowsHide: true, stdio: ["ignore", fd, fd], env: { ...process.env, CARRIEROS_UPDATING: "1" } });
702
+ child.unref();
703
+ return child.pid ?? null;
704
+ }
705
+ catch {
706
+ return null;
707
+ }
708
+ finally {
709
+ if (fd !== null)
710
+ fs.closeSync(fd);
711
+ }
712
+ };
713
+ let detachedSpawner = spawnDetachedNpm;
714
+ export function setDetachedSpawnerForTests(spawner) {
715
+ detachedSpawner = spawner ?? spawnDetachedNpm;
716
+ }
717
+ /**
718
+ * Start the background install of an exact version, detached so it runs after
719
+ * this process has exited. The lock passes to the installer's pid, so no other
720
+ * window starts a second install while it runs.
721
+ */
722
+ export function startDetachedInstall(dir, version, name = packageName()) {
723
+ if (!isVersionLike(version) || !ALLOWED_PACKAGES.has(name))
724
+ return false;
725
+ const pid = detachedSpawner(NPM_BIN, ["install", "-g", `${name}@${version}`], path.join(dir, "update.log"));
726
+ if (!pid)
727
+ return false;
728
+ transferUpdateLock(dir, pid);
729
+ return true;
730
+ }
@@ -19,7 +19,7 @@ import { fileTypeLabel, formatSize, uploadAndAttach, UploadError } from "../serv
19
19
  import { sleep, withSpinner } from "../services/spinner.js";
20
20
  import { c } from "../ui/colors.js";
21
21
  import { renderProjectBrief, workspaceContextHint } from "../services/project-context.js";
22
- import { declaredClientTools, declaredCommandTools, declaredMutationTools, handleClientToolCall, submitWithRetry } from "../services/client-tools.js";
22
+ import { declaredClientTools, declaredCommandTools, declaredMutationTools, handleClientToolCall, localCommandsState, submitWithRetry } from "../services/client-tools.js";
23
23
  import { APPROVAL_TIMEOUT_MS } from "../services/mutations.js";
24
24
  import { createRenderer, toolKind, toolSummary } from "../ui/conversation.js";
25
25
  import { watchForInterrupt } from "../ui/interrupt.js";
@@ -119,6 +119,9 @@ const ERROR_HINTS = {
119
119
  // Context overflow: a new conversation is the one reliable fix, and a
120
120
  // roomier model is the other.
121
121
  MCAI_BLOCKED: "/new",
122
+ // The model's context limit cannot be verified (a server configuration
123
+ // gap): another model is the fix, not a shorter message.
124
+ MCAI_UNVERIFIED: "/model",
122
125
  SESSION_NOT_FOUND: "/sessions",
123
126
  CARRIER_CHAT_MAINTENANCE: "/switch standard",
124
127
  // Out of credit on this model — pick another rather than retrying into the
@@ -228,6 +231,9 @@ function errorDetail(err) {
228
231
  if (err.code === "INSUFFICIENT_CREDITS") {
229
232
  return "Nothing was charged for this message.";
230
233
  }
234
+ if (err.code === "TASK_TOO_LARGE_FOR_MODEL") {
235
+ return "Try splitting the coding work into smaller steps and send them one at a time.";
236
+ }
231
237
  // The server's structured reason names the kind of provider failure.
232
238
  return err.reason ? `${PROVIDER_ERROR_REASONS[err.reason]} · Error code: ${err.code}` : `Error code: ${err.code}`;
233
239
  }
@@ -587,9 +593,22 @@ turnOpts = {}) {
587
593
  // the model cannot change files or run commands whatever the prompt says.
588
594
  // Plan mode uses the same gate. The mode is fixed for the turn, so switching
589
595
  // it while a review is open never changes what this turn may do.
590
- const permission = permissionPolicy(getPermissionMode(ctx.config));
596
+ const permissionMode = getPermissionMode(ctx.config);
597
+ const permission = permissionPolicy(permissionMode);
591
598
  const mutationTools = turnOpts.readOnly || !permission.changeTools ? undefined : declaredMutationTools(ctx);
592
- const commandTools = turnOpts.readOnly || !permission.commands ? undefined : declaredCommandTools(ctx);
599
+ const commandTools = turnOpts.readOnly || !permission.commands ? undefined : declaredCommandTools(ctx, undefined, permissionMode === "auto");
600
+ const commandState = localCommandsState(ctx, undefined, permissionMode === "auto");
601
+ const commandHint = turnOpts.readOnly
602
+ ? "[LOCAL TOOL AVAILABILITY] This is a read-only turn; terminal commands are unavailable."
603
+ : !permission.commands
604
+ ? "[LOCAL TOOL AVAILABILITY] Plan permission mode is active; terminal commands are unavailable."
605
+ : commandTools
606
+ ? "[LOCAL TOOL AVAILABILITY] run_command is available. Manual/Accept Edits require command approval; Auto runs locally permitted commands without an individual prompt."
607
+ : !commandState.enabled
608
+ ? ctx.config.get("localCommandsEnabled") === false
609
+ ? "[LOCAL TOOL AVAILABILITY] Local commands were explicitly disabled with `/settings commands off`; the model has no run_command tool."
610
+ : "[LOCAL TOOL AVAILABILITY] Local commands are off. In Manual or Accept Edits, enable them with `/settings commands on`; selecting Auto opts in for the session."
611
+ : `[LOCAL TOOL AVAILABILITY] run_command is unavailable: ${commandState.blockedBy ?? "the interactive command tool is not available in this session"}. Do not claim that a command ran.`;
593
612
  let taskView;
594
613
  // What the final card needs that the workflow snapshot does not carry: why a
595
614
  // change stopped (from the coordinator's recorded result codes) and the last
@@ -664,7 +683,7 @@ turnOpts = {}) {
664
683
  approvedByPolicy: (plans) => {
665
684
  ui.stepEnd();
666
685
  taskView?.review(plans);
667
- ui.commit([...renderGroup(plans, false, 0, workspaceRoot()), " " + c.accent("✓ Approved by " + permissionModeLabel(getPermissionMode(ctx.config))) + c.dim(getPermissionMode(ctx.config) === "auto" ? " — test commands run too; writes/installs ask · /permissions to change" : " — commands still ask · /permissions to change"), ""]);
686
+ ui.commit([...renderGroup(plans, false, 0, workspaceRoot()), " " + c.accent("✓ Approved by " + permissionModeLabel(getPermissionMode(ctx.config))) + c.dim(getPermissionMode(ctx.config) === "auto" ? " — locally permitted commands run too; /settings commands off blocks them · /permissions to change" : " — commands still ask · /permissions to change"), ""]);
668
687
  workflow?.approval("approve");
669
688
  taskView?.decision(plans, "approve");
670
689
  },
@@ -699,7 +718,7 @@ turnOpts = {}) {
699
718
  ui: {
700
719
  review: (decision, reason, repository, operationId) => ui.borrow(async () => {
701
720
  ui.stepEnd();
702
- // Auto: a contained R0/R1 command is approved by the session's policy, and says so.
721
+ // Auto: locally admitted commands are approved by the session's policy, and say so.
703
722
  if (permission.approveCommandByPolicy(decision.tier)) {
704
723
  ui.commit([" " + c.ok("✓") + " " + c.dim("Auto: running ") + c.cmd(displayCommand(decision.program, decision.args)) + c.dim(" without asking (contained, " + decision.tier + ").")]);
705
724
  return "approve";
@@ -725,7 +744,7 @@ turnOpts = {}) {
725
744
  rememberCommandDetails(ctx, JSON.stringify([client.mutationRecoveryScope(), ctx.config.get("sessionId"), workspaceRoot()]), result.output);
726
745
  ui.commandEnded();
727
746
  ui.commit([...renderCommandSummary(decision, result, errorCode, detail), ...(result ? [" /details shows the full bounded command output."] : []), ""]);
728
- ui.status("thinking", "Working");
747
+ ui.status("thinking", "Thinking");
729
748
  },
730
749
  cancelTurn: abort
731
750
  }
@@ -764,7 +783,7 @@ turnOpts = {}) {
764
783
  const settled = client
765
784
  .chatStream({
766
785
  mode,
767
- message: turnOpts.sendAs ?? withProjectContext(ctx, message),
786
+ message: `${turnOpts.sendAs ?? withProjectContext(ctx, message)}\n\n${commandHint}`,
768
787
  session_id: sessionId,
769
788
  model: model || undefined,
770
789
  chat_type: ctx.chatType,
@@ -816,7 +835,7 @@ turnOpts = {}) {
816
835
  try {
817
836
  // One honest line instead of a scripted checklist: the turn is waiting on
818
837
  // the model until something real (a tool call, a delta) says otherwise.
819
- ui.status("thinking", webSearch === true ? "Searching the web" : ctx.highPower ? "Thinking (high power)" : workflow ? "Agent is working" : "Thinking");
838
+ ui.status("thinking", webSearch === true ? "Searching the web" : ctx.highPower ? "Thinking (high power)" : "Thinking");
820
839
  const outcome = await settled;
821
840
  ui.stepEnd();
822
841
  ui.stop(); // the live region is done; what remains is committed below