@carrieros/cli 0.2.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 (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,92 @@
1
+ import { errorLine } from "../services/output.js";
2
+ import { activeRepository, isWildcardSelector, repositoryTrust, resolveRepository } from "../services/workspace-registry.js";
3
+ import { chatTurn } from "../shell/shell-chat.js";
4
+ import { buildFooter } from "../shell/shell-prompt.js";
5
+ /**
6
+ * `/review` — a read-only code review of one repository's uncommitted changes.
7
+ *
8
+ * This is a normal model turn, deliberately constrained: it is sent with the
9
+ * read tools only (read_file, search_files, git_status, git_diff) and NO
10
+ * mutation or command tools, so a review cannot change files or run commands
11
+ * however the model is prompted. It reuses the existing backend orchestration —
12
+ * there is no second agent loop — and the existing conversation renderer, so
13
+ * git activity and file reads appear as the same compact steps as any turn.
14
+ *
15
+ * "Review and fix" is not one step: this produces findings and stops. Fixing is
16
+ * a separate, explicit request that goes through the ordinary mutation flow
17
+ * (with its diffs and approvals). The two are never combined here.
18
+ */
19
+ export function registerReview(program, ctx) {
20
+ program
21
+ .command("review")
22
+ .argument("[repository]", "repository to review (defaults to the active one)")
23
+ .description("Review the uncommitted changes in a repository (read-only)")
24
+ .action(async (repository) => {
25
+ const client = ctx.requireAuth();
26
+ await runReview(ctx, client, repository);
27
+ });
28
+ }
29
+ /**
30
+ * Resolve the repository, refuse anything that is not exactly one trusted
31
+ * registered repository, and run the review turn. The active repository is
32
+ * never changed — a review of a sibling reads the sibling and leaves you where
33
+ * you were.
34
+ */
35
+ export async function runReview(ctx, client, repository, footer) {
36
+ if (isWildcardSelector(repository)) {
37
+ errorLine('Review is one repository at a time — "*" is not accepted. Name a repository, or omit it for the active one.');
38
+ return;
39
+ }
40
+ let handle;
41
+ try {
42
+ handle = repository ? resolveRepository(repository) : activeRepository();
43
+ }
44
+ catch (err) {
45
+ errorLine(err.message);
46
+ return;
47
+ }
48
+ if (repositoryTrust(handle) !== "trusted") {
49
+ errorLine(`${handle.name} is not a trusted repository, so it cannot be reviewed. Run /repo use ${handle.name} and confirm the trust prompt first.`);
50
+ return;
51
+ }
52
+ const display = repository
53
+ ? `Review the changes in ${handle.name}.`
54
+ : "Review the current changes.";
55
+ await chatTurn(ctx, client, display, {
56
+ footer: footer ?? (process.stdin.isTTY ? buildFooter(ctx) : undefined),
57
+ readOnly: true,
58
+ webSearch: false,
59
+ sendAs: reviewPrompt(handle.name)
60
+ });
61
+ }
62
+ /**
63
+ * The task framing sent to the model. It names the repository, drives the
64
+ * git_status → git_diff → read_file flow, fixes the output shape, and is
65
+ * explicit that this is read-only and one repository only. The read-only
66
+ * guarantee does not rest on this text — the turn declares no write tools — but
67
+ * saying so keeps the model from proposing changes it cannot make.
68
+ */
69
+ function reviewPrompt(repository) {
70
+ return [
71
+ `Review the uncommitted changes in the repository "${repository}". This is a READ-ONLY code review.`,
72
+ "",
73
+ "Do this:",
74
+ `1. Call git_status with repository: "${repository}". If the repository is clean (no staged, unstaged or untracked changes), say so in one line and stop — there is nothing to review.`,
75
+ `2. Otherwise call git_diff with repository: "${repository}" (scope "both" to see staged and unstaged together).`,
76
+ `3. Read only the changed files that need a closer look, and just enough surrounding context to judge a finding — use read_file with repository: "${repository}". Do not read the whole project.`,
77
+ "4. Analyse the changes for concrete problems: correctness bugs, regressions, broken edge cases, security issues, unsafe assumptions, missing error handling or validation, race conditions, resource leaks, incorrect API use, and material test-coverage gaps.",
78
+ "",
79
+ "Rules:",
80
+ "- Report only real issues you can point to in the diff or the files you read. A clean review is a valid result — do not invent findings.",
81
+ "- Do not invent line numbers. Cite a file and, where you can map it precisely, a line or range; if you cannot map it exactly, say which file and describe the location without a fabricated number.",
82
+ "- This is read-only. Do not propose or make any file change, and do not run any command. If asked to fix afterwards, the user will make that request separately.",
83
+ "- Review only this one repository.",
84
+ "",
85
+ "Output format:",
86
+ `Start with a one-line header naming the repository. Then, under a "### Findings" heading, one entry per finding as:`,
87
+ "**<Severity> — `<file>:<line or range>`** then a one-line title, then a short \"Why:\" explanation, then a \"Suggested fix:\" line.",
88
+ "Severity is one of critical, high, medium, low, info. Order findings most severe first.",
89
+ 'End with a "### Summary" section: the count by severity, and the line "No files were modified."',
90
+ 'If there are no findings, replace both sections with "### Review complete" and one line saying no concrete issues were found in the current changes.'
91
+ ].join("\n");
92
+ }
@@ -0,0 +1,92 @@
1
+ import { errorLine, line } from "../services/output.js";
2
+ import { searchFiles } from "../services/local-files.js";
3
+ import { discoverRootWithoutGit, getWorkspace } from "../services/workspace.js";
4
+ import { c } from "../ui/colors.js";
5
+ import { watchForInterrupt } from "../ui/interrupt.js";
6
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
7
+ import { sectionHeader } from "../ui/ui.js";
8
+ /**
9
+ * `cos search <query>` — plain text search across the local project.
10
+ *
11
+ * Local and literal. This is the Grep half of the CLI, not the semantic half:
12
+ * it looks for the characters you typed in the files on your disk, nothing is
13
+ * uploaded, and no embedding is involved. Semantic search over a project stays
14
+ * a backend capability reached through chat.
15
+ */
16
+ export function registerSearch(program, ctx) {
17
+ program
18
+ .command("search")
19
+ .argument("<query...>", "text to look for")
20
+ .option("-g, --glob <pattern>", "only search files matching a glob")
21
+ .option("-c, --case-sensitive", "match case exactly")
22
+ .option("-n, --limit <n>", "maximum matches to show", "50")
23
+ .description("Search the local project for text")
24
+ .action(async (queryParts, options) => {
25
+ await runSearch(ctx, queryParts.join(" "), {
26
+ glob: options.glob,
27
+ caseSensitive: Boolean(options.caseSensitive),
28
+ limit: Number.parseInt(options.limit, 10) || 50
29
+ });
30
+ });
31
+ }
32
+ export async function runSearch(ctx, query, opts = {}) {
33
+ if (!query.trim()) {
34
+ errorLine("Usage: /search <text>");
35
+ return;
36
+ }
37
+ // Reading the project is exactly what the folder-trust gate covers, and the
38
+ // scope that matters is the workspace ROOT — that is what the search walks,
39
+ // not just the directory you happen to be standing in.
40
+ if (!(await ensureWorkspaceTrust(ctx.config, discoverRootWithoutGit())))
41
+ return;
42
+ const ws = getWorkspace();
43
+ const label = ws.project.name;
44
+ // Ctrl+C during a long walk. watchForInterrupt is the existing mechanism and
45
+ // attaches only for the duration, so the composer keeps sole ownership of
46
+ // stdin either side of this.
47
+ const controller = new AbortController();
48
+ const stopWatching = watchForInterrupt(() => controller.abort());
49
+ line();
50
+ line(" " + c.dim(`Searching ${label}…`));
51
+ let result;
52
+ try {
53
+ result = searchFiles({
54
+ query,
55
+ glob: opts.glob,
56
+ caseSensitive: opts.caseSensitive,
57
+ limit: opts.limit ?? 50,
58
+ signal: controller.signal
59
+ });
60
+ }
61
+ finally {
62
+ stopWatching();
63
+ }
64
+ if (result.matches.length === 0) {
65
+ line();
66
+ line(" " + c.dim(result.aborted ? "Search cancelled." : "No matches found."));
67
+ line();
68
+ return;
69
+ }
70
+ const count = result.matches.length;
71
+ line();
72
+ line(sectionHeader(`${count} ${count === 1 ? "match" : "matches"} for "${query}"`));
73
+ const width = Math.max(40, (process.stdout.columns ?? 80) - 8);
74
+ for (const m of result.matches) {
75
+ line(" " + c.value(m.path) + c.dim(":") + c.accent(String(m.line)));
76
+ if (m.text)
77
+ line(" " + c.dim(clip(m.text, width)));
78
+ }
79
+ if (result.aborted) {
80
+ line();
81
+ line(" " + c.dim("Cancelled — showing what was found so far."));
82
+ }
83
+ else if (result.truncated) {
84
+ line();
85
+ line(" " + c.dim(`Stopped at ${count}. Narrow it with `) + c.cmd("--glob") + c.dim("."));
86
+ }
87
+ line();
88
+ }
89
+ /** Keep a matching line to one row. */
90
+ function clip(s, max) {
91
+ return [...s].length <= max ? s : [...s].slice(0, max - 1).join("") + "…";
92
+ }
@@ -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
+ }