@carrieros/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  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 +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -1,16 +1,23 @@
1
1
  import { ApiError } from "../services/api.js";
2
2
  import { errorLine, info, line, success, timeAgo } from "../services/output.js";
3
+ import { clearActiveSession, listSessions, resolveSession, SessionRefError, setActiveSession } from "../services/session-resolver.js";
3
4
  import { withSpinner } from "../services/spinner.js";
5
+ import { showHistory } from "./history.js";
4
6
  import { c } from "../ui/colors.js";
5
7
  import { pickFromList } from "../ui/select.js";
6
8
  import { emptyState, icon, sectionHeader } from "../ui/ui.js";
7
9
  /**
8
- * Session management, all backed by GET /v1/conversations, GET /v1/sessions/:id
9
- * and DELETE /v1/sessions/:id:
10
- * cos sessions list conversations
11
- * cos session use [id] switch active session (prompts if no id)
12
- * cos session delete <id> delete a session
13
- * cos clear start a new session (drops the local pointer)
10
+ * Session management over GET /v1/conversations, GET|DELETE /v1/sessions/:id and
11
+ * POST /v1/sessions:
12
+ * cos sessions numbered list
13
+ * cos session <n|id> continue that conversation
14
+ * cos session use [n|id] same, kept for backward compatibility
15
+ * cos session delete <n|id> delete (asks first)
16
+ * cos new [title] start a fresh conversation
17
+ * cos clear forget the active session locally
18
+ *
19
+ * Numbers come from the last `cos sessions` listing and are resolved in exactly
20
+ * one place (services/session-resolver.ts); ids keep working everywhere.
14
21
  */
15
22
  export function registerSessions(program, ctx) {
16
23
  program
@@ -19,105 +26,252 @@ export function registerSessions(program, ctx) {
19
26
  .option("-n, --limit <n>", "how many to show", "20")
20
27
  .action(async (opts) => {
21
28
  const client = ctx.requireAuth();
22
- const limit = clampLimit(opts.limit);
23
- const { conversations, pagination } = await withSpinner("Loading sessions…", () => client.conversations({ limit }));
24
- renderList(conversations, ctx.config.get("sessionId"), pagination.total);
29
+ const { conversations, total } = await listSessions(ctx, client, {
30
+ limit: clampLimit(opts.limit)
31
+ });
32
+ renderSessionList(conversations, ctx.config.get("sessionId"), total);
25
33
  });
26
34
  const session = program.command("session").description("Inspect or switch the active session");
35
+ // `cos session 2` / `cos session <id>` — the shortest path, no sub-verb.
36
+ session
37
+ .argument("[ref]", "session number from `cos sessions`, or a session id")
38
+ .action(async (ref) => {
39
+ const client = ctx.requireAuth();
40
+ if (!ref) {
41
+ await pickSession(ctx, client);
42
+ return;
43
+ }
44
+ await switchTo(ctx, client, ref);
45
+ });
46
+ // Kept verbatim for backward compatibility with `cos session use <id>`.
27
47
  session
28
48
  .command("use")
29
49
  .description("Switch the active session")
30
- .argument("[id]", "session id (prompts from the list if omitted)")
31
- .action(async (id) => {
50
+ .argument("[ref]", "session number or id (prompts from the list if omitted)")
51
+ .action(async (ref) => {
32
52
  const client = ctx.requireAuth();
33
- let target = id;
34
- if (!target) {
35
- const { conversations } = await withSpinner("Loading sessions…", () => client.conversations({ limit: 25 }));
36
- if (conversations.length === 0) {
37
- for (const l of emptyState("No conversations yet.", "Start chatting to create one.")) {
38
- line(l);
39
- }
40
- return;
41
- }
42
- const activeId = ctx.config.get("sessionId");
43
- const chosen = await pickFromList({
44
- title: "Select a session",
45
- description: "Switch the active conversation.",
46
- initial: Math.max(0, conversations.findIndex((cv) => cv.session_id === activeId)),
47
- choices: conversations.map((cv) => ({
48
- value: cv.session_id,
49
- label: cv.title,
50
- description: `${cv.message_count} msgs · ${timeAgo(cv.last_activity)}`,
51
- current: cv.session_id === activeId
52
- }))
53
- });
54
- if (chosen == null)
55
- return; // Esc / Ctrl+C — leave the session unchanged
56
- target = chosen;
57
- }
58
- try {
59
- const info_ = await withSpinner("Opening…", () => client.session(target));
60
- ctx.config.set("sessionId", info_.session_id);
61
- success(`Switched to “${info_.title}”.`);
62
- }
63
- catch (err) {
64
- errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
65
- process.exitCode = 1;
53
+ if (!ref) {
54
+ await pickSession(ctx, client);
55
+ return;
66
56
  }
57
+ await switchTo(ctx, client, ref);
67
58
  });
68
59
  session
69
60
  .command("current")
70
- .description("Show the active session id")
61
+ .description("Show the active session")
71
62
  .action(() => {
72
63
  const sid = ctx.config.get("sessionId");
73
- info(sid ? `Current session: ${sid}` : "No active session (a new one starts on your next message).");
64
+ if (!sid) {
65
+ info("No active session (a new one starts on your next message).");
66
+ return;
67
+ }
68
+ const title = ctx.config.get("sessionTitle");
69
+ info(title ? `Current session: ${title} (${sid})` : `Current session: ${sid}`);
74
70
  });
75
71
  session
76
72
  .command("delete")
77
73
  .description("Delete a session")
78
- .argument("<id>", "session id")
79
- .action(async (id) => {
74
+ .argument("<ref>", "session number from `cos sessions`, or a session id")
75
+ .action(async (ref) => {
80
76
  const client = ctx.requireAuth();
81
- try {
82
- await withSpinner("Deleting…", () => client.deleteSession(id));
83
- if (ctx.config.get("sessionId") === id)
84
- ctx.config.set("sessionId", undefined);
85
- success("Session deleted.");
86
- }
87
- catch (err) {
88
- errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
89
- process.exitCode = 1;
90
- }
77
+ await deleteSession(ctx, client, ref);
78
+ });
79
+ // Rename has no /v1 endpoint yet. Registered so the command reports the real
80
+ // reason rather than "unknown command", but deliberately NOT advertised in the
81
+ // palette — and it never invents a CLI-only title.
82
+ session
83
+ .command("rename")
84
+ .description("Rename a session (not yet supported by the API)")
85
+ .argument("[ref]", "session number or id")
86
+ .argument("[title...]", "new title")
87
+ .action(() => {
88
+ errorLine("Renaming isn't supported by the API yet.");
89
+ line(" " + c.dim("The /v1 surface has no update endpoint for a session."));
90
+ process.exitCode = 1;
91
+ });
92
+ program
93
+ .command("new")
94
+ .description("Start a new conversation")
95
+ .argument("[title...]", "optional title (Standard chat only)")
96
+ .action(async (titleParts) => {
97
+ const title = (titleParts ?? []).join(" ").trim();
98
+ await newSession(ctx, title);
91
99
  });
92
100
  program
93
101
  .command("clear")
94
102
  .description("Start a new session (forgets the active one locally)")
95
103
  .action(() => {
96
- ctx.config.set("sessionId", undefined);
104
+ clearActiveSession(ctx);
97
105
  success("Cleared. Your next message starts a fresh session.");
98
106
  });
99
107
  }
108
+ // ── Shared operations (the shell routes straight to these) ───────────────────
109
+ /** Switch the active conversation by ordinal or id. */
110
+ export async function switchTo(ctx, client, ref) {
111
+ try {
112
+ const s = await withSpinner("Opening…", () => resolveSession(ctx, client, ref));
113
+ setActiveSession(ctx, s.session_id, s.title);
114
+ success(`Switched to “${s.title}”.`);
115
+ // Replay the conversation you just opened. Switching without it left you
116
+ // typing into a thread whose contents you could not see — the model has the
117
+ // full context, so the person should too. Reuses /history's renderer, so
118
+ // memory markers and clarification blocks render identically.
119
+ await showHistory(ctx, client, s.session_id);
120
+ }
121
+ catch (err) {
122
+ reportRefError(err);
123
+ }
124
+ }
125
+ /** Arrow-key picker over the current conversations. */
126
+ export async function pickSession(ctx, client) {
127
+ const { conversations } = await listSessions(ctx, client, { limit: 25 });
128
+ if (conversations.length === 0) {
129
+ for (const l of emptyState("No conversations yet.", "Start chatting to create one."))
130
+ line(l);
131
+ return;
132
+ }
133
+ const activeId = ctx.config.get("sessionId");
134
+ // Numbers are padded and titles column-aligned so the picker reads like the
135
+ // printed list — the number shown here is the same one `/session <n>` takes,
136
+ // so switching between the two ways of choosing never means re-counting.
137
+ const nw = String(conversations.length).length;
138
+ const tw = Math.min(38, Math.max(...conversations.map((cv) => [...cv.title].length)));
139
+ const chosen = await pickFromList({
140
+ title: "Sessions",
141
+ description: "↑↓ to choose · Enter to continue that conversation · Esc to cancel",
142
+ initial: Math.max(0, conversations.findIndex((cv) => cv.session_id === activeId)),
143
+ choices: conversations.map((cv, i) => ({
144
+ value: cv.session_id,
145
+ label: `${String(i + 1).padStart(nw)} ${clipTitle(cv.title, tw)}`,
146
+ description: `${cv.message_count} msgs · ${timeAgo(cv.last_activity)}`,
147
+ current: cv.session_id === activeId
148
+ }))
149
+ });
150
+ if (chosen == null)
151
+ return; // Esc / Ctrl+C — leave the session unchanged
152
+ await switchTo(ctx, client, chosen);
153
+ }
154
+ /** Delete a conversation after an explicit confirmation. */
155
+ export async function deleteSession(ctx, client, ref) {
156
+ let target;
157
+ try {
158
+ target = await withSpinner("Loading…", () => resolveSession(ctx, client, ref));
159
+ }
160
+ catch (err) {
161
+ reportRefError(err);
162
+ return;
163
+ }
164
+ // Deletion is irreversible and there is no undo in a terminal, so name what
165
+ // will be lost. `initial: 0` = "Keep" so a non-TTY (piped/CI) run declines
166
+ // rather than silently deleting.
167
+ const answer = await pickFromList({
168
+ title: "Delete this conversation?",
169
+ description: `“${target.title}” — this cannot be undone.`,
170
+ initial: 0,
171
+ confirmOnNumber: true,
172
+ choices: [
173
+ { value: "no", label: "Keep it" },
174
+ { value: "yes", label: "Delete" }
175
+ ]
176
+ });
177
+ if (answer !== "yes") {
178
+ info("Left it alone.");
179
+ return;
180
+ }
181
+ try {
182
+ await withSpinner("Deleting…", () => client.deleteSession(target.session_id));
183
+ if (ctx.config.get("sessionId") === target.session_id)
184
+ clearActiveSession(ctx);
185
+ success(`Deleted “${target.title}”.`);
186
+ // The ordinals just shifted — refresh so the next number means what the user
187
+ // last saw, rather than pointing one place further down the list.
188
+ await listSessions(ctx, client, { spinner: false }).catch(() => undefined);
189
+ }
190
+ catch (err) {
191
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
192
+ process.exitCode = 1;
193
+ }
194
+ }
195
+ /**
196
+ * Start a fresh conversation.
197
+ *
198
+ * Without a title this just drops the local pointer — the next message creates
199
+ * the conversation with the CORRECT chat type (Carrier or Standard) through the
200
+ * normal chat flow. With a title we must call POST /v1/sessions, which hardcodes
201
+ * `type: "regular"`, so a titled new chat is Standard-only; in Carrier chat we
202
+ * say so instead of silently downgrading the conversation type.
203
+ */
204
+ export async function newSession(ctx, title) {
205
+ if (!title) {
206
+ clearActiveSession(ctx);
207
+ success("New conversation. Your next message starts it.");
208
+ return;
209
+ }
210
+ if (ctx.chatType === "carrier") {
211
+ errorLine("Titles are Standard chat only — the API creates titled sessions as Standard.");
212
+ line(" " + c.dim("Run /new without a title to start a Carrier chat, or /switch standard."));
213
+ return;
214
+ }
215
+ const client = ctx.requireAuth();
216
+ try {
217
+ const s = await withSpinner("Creating…", () => client.createSession(title));
218
+ setActiveSession(ctx, s.session_id, s.title);
219
+ success(`Started “${s.title}”.`);
220
+ }
221
+ catch (err) {
222
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
223
+ process.exitCode = 1;
224
+ }
225
+ }
226
+ /** Consistent, actionable output for a bad/stale reference. */
227
+ export function reportRefError(err) {
228
+ if (err instanceof SessionRefError) {
229
+ errorLine(err.message);
230
+ if (err.hint)
231
+ line(" " + c.dim(err.hint));
232
+ return;
233
+ }
234
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
235
+ process.exitCode = 1;
236
+ }
237
+ /** Pad to `width`, or clip with an ellipsis when the title is longer. */
238
+ function clipTitle(title, width) {
239
+ const chars = [...title];
240
+ if (chars.length <= width)
241
+ return title.padEnd(width);
242
+ return chars.slice(0, width - 1).join("") + "…";
243
+ }
100
244
  function clampLimit(raw) {
101
245
  const n = parseInt(raw, 10);
102
246
  if (Number.isNaN(n))
103
247
  return 20;
104
248
  return Math.min(Math.max(n, 1), 100);
105
249
  }
106
- function renderList(items, activeId, total) {
250
+ /**
251
+ * The numbered listing. The number is the handle for every other command, so it
252
+ * leads the row; the id is dropped entirely — it was only ever there to be
253
+ * copied, which is what the numbers now replace.
254
+ */
255
+ export function renderSessionList(items, activeId, total) {
107
256
  if (items.length === 0) {
108
- for (const l of emptyState("No conversations yet.", "Start chatting to create one."))
257
+ for (const l of emptyState("No conversations yet.", "Type a message to start one, or run /new.")) {
109
258
  line(l);
259
+ }
110
260
  return;
111
261
  }
112
262
  line();
113
263
  line(sectionHeader(`Sessions (${items.length} of ${total})`));
114
264
  const w = Math.max(0, ...items.map((s) => [...s.title].length));
115
- for (const s of items) {
265
+ const nw = String(items.length).length;
266
+ items.forEach((s, i) => {
116
267
  const active = s.session_id === activeId;
268
+ const num = c.dim(String(i + 1).padStart(nw));
117
269
  const marker = active ? icon.active : " ";
118
270
  const title = (active ? c.brand : c.value)(s.title.padEnd(w));
119
- const meta = c.dim(`${s.message_count} msgs · ${timeAgo(s.last_activity)} · ${s.session_id.slice(0, 8)}`);
120
- line(` ${marker} ${title} ${meta}`);
121
- }
271
+ const meta = c.dim(`${s.message_count} msgs · ${timeAgo(s.last_activity)}`);
272
+ line(` ${num} ${marker} ${title} ${meta}`);
273
+ });
274
+ line();
275
+ line(" " + c.dim("Continue one with ") + c.cmd("/session <n>"));
122
276
  line();
123
277
  }
@@ -0,0 +1,87 @@
1
+ import { COMMANDS_OPT_IN_ENV, localCommandsState } from "../services/client-tools.js";
2
+ import { errorLine, line } from "../services/output.js";
3
+ import { c } from "../ui/colors.js";
4
+ import { sectionHeader } from "../ui/ui.js";
5
+ /**
6
+ * `cos settings` — the CLI's persisted behaviour settings, in one place.
7
+ *
8
+ * /settings show them
9
+ * /settings commands on|off allow or stop local commands (run_command)
10
+ *
11
+ * Most settings already have their own toggle (/fast, /hipwr, /sia, /websearch)
12
+ * and keep it; this command lists them together and owns the one setting that
13
+ * had no home: whether the model may propose running commands at all.
14
+ */
15
+ export function registerSettings(program, ctx) {
16
+ program
17
+ .command("settings")
18
+ .argument("[setting]", 'the setting to change, e.g. "commands"')
19
+ .argument("[value]", "on or off")
20
+ .description("Show or change CLI settings (e.g. settings commands on)")
21
+ .action((setting, value) => {
22
+ runSettings(ctx, [setting, value].filter(Boolean).join(" "));
23
+ });
24
+ }
25
+ const ON = new Set(["on", "yes", "true", "enable", "enabled"]);
26
+ const OFF = new Set(["off", "no", "false", "disable", "disabled"]);
27
+ export function runSettings(ctx, argStr) {
28
+ const [name = "", value = ""] = argStr.trim().toLowerCase().split(/\s+/);
29
+ if (!name)
30
+ return showSettings(ctx);
31
+ if (name !== "commands" && name !== "local-commands") {
32
+ errorLine(`Unknown setting "${name}". Try: /settings commands on|off`);
33
+ return;
34
+ }
35
+ if (!ON.has(value) && !OFF.has(value)) {
36
+ errorLine("Use /settings commands on or /settings commands off.");
37
+ return;
38
+ }
39
+ const enable = ON.has(value);
40
+ ctx.config.set("localCommandsEnabled", enable);
41
+ line();
42
+ if (enable) {
43
+ line(" " + c.ok("✓") + " " + c.value("Local commands enabled."));
44
+ // Said plainly at the moment it is switched on: what a command can do.
45
+ for (const l of LOCAL_COMMANDS_NOTICE)
46
+ line(" " + c.dim(l));
47
+ }
48
+ else {
49
+ line(" " + c.ok("✓") + " " + c.value("Local commands disabled.") + " " + c.dim("The model can still read, search and propose file changes."));
50
+ }
51
+ line();
52
+ }
53
+ /**
54
+ * What enabling local commands means, in the user's terms. Shown when it is
55
+ * switched on — not buried in documentation — because it is the one decision
56
+ * here that lets project code run.
57
+ */
58
+ export const LOCAL_COMMANDS_NOTICE = [
59
+ "The model may now PROPOSE commands such as npm test or git status.",
60
+ "Every command still needs your approval, only runs in a trusted repository,",
61
+ "and is limited to an allowlist (no shells, no network tools, no git writes).",
62
+ "Approved project code runs as your Windows account: it can read what you can",
63
+ "read, and may open other applications through Windows file associations.",
64
+ "Turn it off again with /settings commands off."
65
+ ];
66
+ function showSettings(ctx) {
67
+ const state = localCommandsState(ctx);
68
+ const row = (label, value, note = "") => line(" " + c.label(label.padEnd(16)) + value + (note ? " " + c.dim(note) : ""));
69
+ line();
70
+ line(sectionHeader("Settings"));
71
+ line();
72
+ row("Local commands", state.enabled ? c.ok("enabled") : c.dim("disabled"), state.source === "env"
73
+ ? `via ${COMMANDS_OPT_IN_ENV}=1`
74
+ : state.enabled
75
+ ? "/settings commands off to stop"
76
+ : "/settings commands on to allow");
77
+ if (state.enabled && state.blockedBy)
78
+ row("", c.warn("not active"), state.blockedBy);
79
+ row("Mode", c.value(ctx.mode));
80
+ row("Model", c.value(ctx.config.get("model") || "mode default"));
81
+ row("Fast", ctx.fast ? c.ok("on") : c.dim("off"), "/fast");
82
+ row("High Power", ctx.highPower ? c.ok("on") : c.dim("off"), "/hipwr");
83
+ row("Clarification", c.value(ctx.siaMode), "/sia");
84
+ const web = ctx.webSearch;
85
+ row("Web search", web === undefined ? c.dim("workspace default") : web ? c.ok("on") : c.dim("off"), "/websearch");
86
+ line();
87
+ }
@@ -0,0 +1,159 @@
1
+ import { line } from "../services/output.js";
2
+ import { withSpinner } from "../services/spinner.js";
3
+ import { isPackaged, PACKAGED_DOWNLOAD_URL } from "../services/packaged.js";
4
+ import { checkForUpdate, installLatest, isLinkedInstallation, PACKAGE_NAME, verifyInstallation } from "../services/update.js";
5
+ import { c } from "../ui/colors.js";
6
+ import { pickFromList } from "../ui/select.js";
7
+ /**
8
+ * `/update` and `cos update` — check for, and install, a newer CLI.
9
+ *
10
+ * Bare `/update` NEVER mutates the installation; `/update install` is the only
11
+ * path that changes anything, and only after an explicit confirmation. The
12
+ * process is never restarted: npm swaps files under a running Node, and
13
+ * re-execing through the shim while the old process still holds handles is how
14
+ * partial installs happen. The user is told to restart instead.
15
+ *
16
+ * This file owns every message. services/update.ts owns the logic, so the shell
17
+ * command and the standalone command cannot drift apart.
18
+ */
19
+ const MANUAL = "npm install -g " + PACKAGE_NAME + "@latest";
20
+ function heading() {
21
+ line();
22
+ line(" " + c.title("Carrier OS CLI"));
23
+ line();
24
+ }
25
+ function versions(current, latest) {
26
+ line(" " + c.dim("Current version: ") + c.value(current));
27
+ line(" " + c.dim("Latest version: ") + c.value(latest));
28
+ line();
29
+ }
30
+ function renderTerminalState(state) {
31
+ if (state.kind === "current") {
32
+ line();
33
+ line(" " + c.ok("✓") + " " + c.value("Carrier OS CLI is already up to date (v" + state.current + ")"));
34
+ line();
35
+ return;
36
+ }
37
+ if (state.kind === "ahead") {
38
+ heading();
39
+ versions(state.current, state.latest);
40
+ line(" " + c.ok("✓") + " " + c.value("You are running a newer version than npm's latest."));
41
+ line(" " + c.dim("Nothing to do — this will not downgrade."));
42
+ line();
43
+ return;
44
+ }
45
+ if (state.kind === "no-npm") {
46
+ heading();
47
+ line(" " + c.err("✗") + " " + c.value("Unable to check for updates."));
48
+ line();
49
+ line(" " + c.dim("npm was not found on this system."));
50
+ line(" " + c.dim("Update manually with:"));
51
+ line(" " + c.cmd(MANUAL));
52
+ line();
53
+ return;
54
+ }
55
+ // unreachable
56
+ heading();
57
+ line(" " + c.err("✗") + " " + c.value("Could not check for the latest version."));
58
+ line();
59
+ line(" " + c.dim("Your current version: ") + c.value(state.current));
60
+ line(" " + c.dim(state.detail));
61
+ line();
62
+ }
63
+ /**
64
+ * `/update` and `cos update` — the entire user-facing surface.
65
+ *
66
+ * One command: check, and if something newer exists, offer to install it. The
67
+ * check/install split exists only as functions in services/update.ts — exposing
68
+ * it as subcommands would make the user choose between two things that are
69
+ * really one intention.
70
+ *
71
+ * Nothing is installed without an explicit Yes, and the process is never
72
+ * restarted: npm swaps files under a running Node, and re-execing through the
73
+ * shim while the old process still holds handles is how partial installs occur.
74
+ */
75
+ export async function runUpdate() {
76
+ // The packaged executable has no npm to update through. Point at the download
77
+ // rather than running an npm command that cannot exist in that environment.
78
+ if (isPackaged()) {
79
+ line();
80
+ line(" " + c.dim("You're running the packaged Carrier OS CLI."));
81
+ line(" " + c.dim("Download the latest build from ") + c.value(PACKAGED_DOWNLOAD_URL) + c.dim("."));
82
+ line();
83
+ return;
84
+ }
85
+ const state = await withSpinner(c.dim("Checking for updates…"), async () => checkForUpdate());
86
+ // Up to date, ahead of the registry, npm missing, or unreachable — each says
87
+ // everything it needs to, including how to update by hand.
88
+ if (state.kind !== "available") {
89
+ renderTerminalState(state);
90
+ return;
91
+ }
92
+ // MANDATORY GUARD, before anything can write. `npm i -g` against a linked
93
+ // install replaces the symlink, silently detaching a developer's checkout.
94
+ if (isLinkedInstallation()) {
95
+ heading();
96
+ versions(state.current, state.latest);
97
+ line(" " + c.warn("⚠") + " " + c.value("Running from a linked development checkout."));
98
+ line();
99
+ line(" " + c.dim("Automatic update is disabled here — it would replace the link."));
100
+ line(" " + c.dim("Install a published version from npm before using /update."));
101
+ line();
102
+ return;
103
+ }
104
+ heading();
105
+ versions(state.current, state.latest);
106
+ line(" " + c.value("A new version is available."));
107
+ line();
108
+ const answer = await pickFromList({
109
+ title: "Update now?",
110
+ description: "Runs " + MANUAL,
111
+ choices: [
112
+ { value: "yes", label: "Yes", description: "Install v" + state.latest + " now" },
113
+ { value: "no", label: "No", description: "Stay on v" + state.current }
114
+ ],
115
+ initial: 0,
116
+ confirmOnNumber: true
117
+ });
118
+ // Esc resolves null — a dismissed prompt must never install anything.
119
+ if (answer !== "yes") {
120
+ line(" " + c.dim("Update cancelled."));
121
+ line();
122
+ return;
123
+ }
124
+ const result = await withSpinner(c.dim("Updating Carrier OS CLI…"), async () => installLatest());
125
+ if (!result.ok) {
126
+ line();
127
+ line(" " + c.err("✗") + " " + c.value("Update failed."));
128
+ line();
129
+ line(" " + c.dim("Carrier OS CLI remains at v") + c.value(state.current) + c.dim("."));
130
+ if (result.permission) {
131
+ line(" " + c.dim("This looks like a permissions problem — try an elevated terminal,"));
132
+ line(" " + c.dim("or run: ") + c.cmd(MANUAL));
133
+ }
134
+ if (result.detail) {
135
+ line();
136
+ for (const l of result.detail.split("\n").slice(0, 6))
137
+ line(" " + c.dim(l));
138
+ }
139
+ line();
140
+ return;
141
+ }
142
+ // Trust the disk, not this process: our own package.json was read at startup
143
+ // and the old modules stay loaded, so cliVersion() cannot see the swap.
144
+ const installed = verifyInstallation() ?? state.latest;
145
+ line();
146
+ line(" " + c.ok("✓") + " " + c.value("Carrier OS CLI updated successfully."));
147
+ line(" " + c.dim(state.current) + c.dim(" → ") + c.value(installed));
148
+ line();
149
+ line(" " + c.dim("Restart Carrier OS CLI to use the new version."));
150
+ line();
151
+ }
152
+ export function registerUpdate(program, _ctx) {
153
+ program
154
+ .command("update")
155
+ .description("Check for and install the latest Carrier OS CLI version")
156
+ .action(async () => {
157
+ await runUpdate();
158
+ });
159
+ }