@carrieros/cli-staging 0.0.0-stage → 0.4.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 (136) hide show
  1. package/README.md +6 -2
  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 +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -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,155 @@
1
+ import { select } from "@inquirer/prompts";
2
+ import { DEFAULT_API_URL } from "../services/config.js";
3
+ import { listCliProjects, listCliWorkspaces, setCliScope } from "../services/device-auth.js";
4
+ import { errorLine, heading, info, kv, line, success } from "../services/output.js";
5
+ import { withSpinner } from "../services/spinner.js";
6
+ import { screenActive } from "../ui/screen.js";
7
+ /**
8
+ * `cos workspace use [target]` / `cos project use [target]` — switch the active
9
+ * developer context. The chosen workspace + project are re-bound server-side
10
+ * (which rotates the session), so every subsequent request carries the new
11
+ * scope. `target` may be an id or a name; omit it for an interactive picker.
12
+ */
13
+ export function registerScope(program, ctx) {
14
+ const workspace = program.command("workspace").description("Advanced: manage API workspace scope (not local repositories)");
15
+ workspace
16
+ .command("list")
17
+ .description("List your workspaces")
18
+ .action(async () => {
19
+ const { apiUrl, provider } = auth(ctx);
20
+ const { workspaces } = await withSpinner("Loading workspaces…", () => listCliWorkspaces(apiUrl, provider));
21
+ printList("Workspaces", workspaces, activeWorkspaceId(ctx), (w) => `${w.name} ${dim(w.slug)}`);
22
+ });
23
+ workspace
24
+ .command("use [target]")
25
+ .description("Switch API workspace and automatically select its default project")
26
+ .action(async (target) => {
27
+ await useWorkspace(ctx, target);
28
+ });
29
+ const project = program.command("project").description("Advanced: manage API project scope (not local repositories)");
30
+ project
31
+ .command("list")
32
+ .description("List projects in the active workspace")
33
+ .action(async () => {
34
+ const { apiUrl, provider } = auth(ctx);
35
+ const wsId = requireActiveWorkspace(ctx);
36
+ const { projects } = await withSpinner("Loading projects…", () => listCliProjects(apiUrl, provider, wsId));
37
+ printList("Projects", projects, activeProjectId(ctx), (p) => `${p.name} ${dim(p.environment)}`);
38
+ });
39
+ project
40
+ .command("use [target]")
41
+ .description("Switch the active project within the current workspace")
42
+ .action(async (target) => {
43
+ await useProject(ctx, target);
44
+ });
45
+ }
46
+ // ── flows ─────────────────────────────────────────────────────────────────────
47
+ async function useWorkspace(ctx, target) {
48
+ const { apiUrl, provider } = auth(ctx);
49
+ const { workspaces } = await withSpinner("Loading workspaces…", () => listCliWorkspaces(apiUrl, provider));
50
+ const ws = await resolve(workspaces, target, "Select a workspace:", (w) => `${w.name} (${w.slug})`);
51
+ if (!ws)
52
+ return unresolved("workspace", workspaces, activeWorkspaceId(ctx), (w) => `${w.name} ${dim(w.slug)}`);
53
+ // A workspace switch needs a project in that workspace — pick its default, or
54
+ // use the server-provided default ordering without a second prompt.
55
+ const { projects } = await withSpinner("Loading projects…", () => listCliProjects(apiUrl, provider, ws.id));
56
+ if (projects.length === 0) {
57
+ errorLine(`Workspace "${ws.name}" has no projects. Create one in the dashboard first.`);
58
+ process.exitCode = 1;
59
+ return;
60
+ }
61
+ // The API lists the default project first. Keep a valid current selection
62
+ // when reselecting the same workspace; otherwise use that server ordering.
63
+ const proj = projects.find((p) => p.id === activeProjectId(ctx)) ?? projects[0];
64
+ await applyScope(ctx, apiUrl, provider, ws.id, proj.id);
65
+ }
66
+ async function useProject(ctx, target) {
67
+ const { apiUrl, provider } = auth(ctx);
68
+ const wsId = requireActiveWorkspace(ctx);
69
+ const { projects } = await withSpinner("Loading projects…", () => listCliProjects(apiUrl, provider, wsId));
70
+ const proj = await resolve(projects, target, "Select a project:", (p) => `${p.name} (${p.environment})`);
71
+ if (!proj)
72
+ return unresolved("project", projects, activeProjectId(ctx), (p) => `${p.name} ${dim(p.environment)}`);
73
+ await applyScope(ctx, apiUrl, provider, wsId, proj.id);
74
+ }
75
+ async function applyScope(ctx, apiUrl, provider, workspaceId, projectId) {
76
+ const tokens = await withSpinner("Switching context…", () => setCliScope(apiUrl, provider, workspaceId, projectId));
77
+ persist(ctx, tokens);
78
+ success("Context updated.");
79
+ line();
80
+ kv("Workspace", tokens.workspace?.name ?? "—");
81
+ kv("Project", tokens.project?.name ?? "—");
82
+ line();
83
+ }
84
+ // ── helpers ───────────────────────────────────────────────────────────────────
85
+ function auth(ctx) {
86
+ ctx.requireAuth();
87
+ return { apiUrl: ctx.config.get("apiUrl") ?? DEFAULT_API_URL, provider: ctx.authProvider() };
88
+ }
89
+ /** Resolve a target (id or name) or prompt interactively; returns undefined when
90
+ * no match and no picker is available (caller prints the list). */
91
+ async function resolve(items, target, message, labelFn) {
92
+ if (target) {
93
+ const q = target.trim().toLowerCase();
94
+ return items.find((i) => i.id.toLowerCase() === q || i.name.toLowerCase() === q);
95
+ }
96
+ // Interactive select only when we own a real TTY (not inside the shell's TUI).
97
+ if (!process.stdout.isTTY || screenActive())
98
+ return undefined;
99
+ if (items.length === 0)
100
+ return undefined;
101
+ if (items.length === 1)
102
+ return items[0];
103
+ const id = await select({
104
+ message,
105
+ choices: items.map((i) => ({ name: labelFn(i), value: i.id }))
106
+ });
107
+ return items.find((i) => i.id === id);
108
+ }
109
+ function unresolved(kind, items, activeId, labelFn) {
110
+ errorLine(`No matching ${kind}. Available ${kind}s:`);
111
+ printList(cap(kind) + "s", items, activeId, labelFn);
112
+ info(`Run \`cos ${kind} use <name-or-id>\` to switch.`);
113
+ process.exitCode = 1;
114
+ }
115
+ function persist(ctx, tokens) {
116
+ const current = ctx.config.get("auth");
117
+ if (current) {
118
+ ctx.config.update({
119
+ auth: {
120
+ ...current,
121
+ accessToken: tokens.access_token,
122
+ refreshToken: tokens.refresh_token,
123
+ workspace: tokens.workspace ?? current.workspace,
124
+ project: tokens.project ?? current.project
125
+ }
126
+ });
127
+ }
128
+ const user = ctx.config.get("scope")?.user ?? null;
129
+ ctx.config.set("scope", {
130
+ apiKey: null,
131
+ workspace: tokens.workspace ?? { id: "", name: "—", slug: "" },
132
+ project: tokens.project ?? { id: "", name: "—", projectId: "", environment: "" },
133
+ user
134
+ });
135
+ }
136
+ function printList(title, items, activeId, labelFn) {
137
+ heading(title);
138
+ for (const it of items) {
139
+ const marker = it.id === activeId ? "● " : " ";
140
+ line(` ${marker}${labelFn(it)}`);
141
+ }
142
+ line();
143
+ }
144
+ function requireActiveWorkspace(ctx) {
145
+ const wsId = activeWorkspaceId(ctx);
146
+ if (!wsId) {
147
+ errorLine("No active workspace. Run `cos workspace use` first.");
148
+ throw new Error("no active workspace");
149
+ }
150
+ return wsId;
151
+ }
152
+ const activeWorkspaceId = (ctx) => ctx.config.get("auth")?.workspace?.id;
153
+ const activeProjectId = (ctx) => ctx.config.get("auth")?.project?.id;
154
+ const dim = (s) => `· ${s}`;
155
+ const cap = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
@@ -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
+ }
@@ -0,0 +1,282 @@
1
+ import { ApiError } from "../services/api.js";
2
+ import { errorLine, info, line, success, timeAgo } from "../services/output.js";
3
+ import { showTaskContext } from "../shell/task-context-view.js";
4
+ import { clearActiveSession, listSessions, resolveSession, SessionRefError, setActiveSession } from "../services/session-resolver.js";
5
+ import { withSpinner } from "../services/spinner.js";
6
+ import { showHistory } from "./history.js";
7
+ import { c } from "../ui/colors.js";
8
+ import { pickFromList } from "../ui/select.js";
9
+ import { emptyState, icon, sectionHeader } from "../ui/ui.js";
10
+ /**
11
+ * Session management over GET /v1/conversations, GET|DELETE /v1/sessions/:id and
12
+ * POST /v1/sessions:
13
+ * cos sessions numbered list
14
+ * cos session <n|id> continue that conversation
15
+ * cos session use [n|id] same, kept for backward compatibility
16
+ * cos session delete <n|id> delete (asks first)
17
+ * cos new [title] start a fresh conversation
18
+ * cos clear forget the active session locally
19
+ *
20
+ * Numbers come from the last `cos sessions` listing and are resolved in exactly
21
+ * one place (services/session-resolver.ts); ids keep working everywhere.
22
+ */
23
+ export function registerSessions(program, ctx) {
24
+ program
25
+ .command("sessions")
26
+ .description("List conversations in the current project")
27
+ .option("-n, --limit <n>", "how many to show", "20")
28
+ .action(async (opts) => {
29
+ const client = ctx.requireAuth();
30
+ const { conversations, total } = await listSessions(ctx, client, {
31
+ limit: clampLimit(opts.limit)
32
+ });
33
+ renderSessionList(conversations, ctx.config.get("sessionId"), total);
34
+ });
35
+ const session = program.command("session").description("Inspect or switch the active session");
36
+ // `cos session 2` / `cos session <id>` — the shortest path, no sub-verb.
37
+ session
38
+ .argument("[ref]", "session number from `cos sessions`, or a session id")
39
+ .action(async (ref) => {
40
+ const client = ctx.requireAuth();
41
+ if (!ref) {
42
+ await pickSession(ctx, client);
43
+ return;
44
+ }
45
+ await switchTo(ctx, client, ref);
46
+ });
47
+ // Kept verbatim for backward compatibility with `cos session use <id>`.
48
+ session
49
+ .command("use")
50
+ .description("Switch the active session")
51
+ .argument("[ref]", "session number or id (prompts from the list if omitted)")
52
+ .action(async (ref) => {
53
+ const client = ctx.requireAuth();
54
+ if (!ref) {
55
+ await pickSession(ctx, client);
56
+ return;
57
+ }
58
+ await switchTo(ctx, client, ref);
59
+ });
60
+ session
61
+ .command("current")
62
+ .description("Show the active session")
63
+ .action(() => {
64
+ const sid = ctx.config.get("sessionId");
65
+ if (!sid) {
66
+ info("No active session (a new one starts on your next message).");
67
+ return;
68
+ }
69
+ const title = ctx.config.get("sessionTitle");
70
+ info(title ? `Current session: ${title} (${sid})` : `Current session: ${sid}`);
71
+ });
72
+ session
73
+ .command("delete")
74
+ .description("Delete a session")
75
+ .argument("<ref>", "session number from `cos sessions`, or a session id")
76
+ .action(async (ref) => {
77
+ const client = ctx.requireAuth();
78
+ await deleteSession(ctx, client, ref);
79
+ });
80
+ // Rename has no /v1 endpoint yet. Registered so the command reports the real
81
+ // reason rather than "unknown command", but deliberately NOT advertised in the
82
+ // palette — and it never invents a CLI-only title.
83
+ session
84
+ .command("rename")
85
+ .description("Rename a session (not yet supported by the API)")
86
+ .argument("[ref]", "session number or id")
87
+ .argument("[title...]", "new title")
88
+ .action(() => {
89
+ errorLine("Renaming isn't supported by the API yet.");
90
+ line(" " + c.dim("The /v1 surface has no update endpoint for a session."));
91
+ process.exitCode = 1;
92
+ });
93
+ program
94
+ .command("new")
95
+ .description("Start a new conversation")
96
+ .argument("[title...]", "optional title (Standard chat only)")
97
+ .action(async (titleParts) => {
98
+ const title = (titleParts ?? []).join(" ").trim();
99
+ await newSession(ctx, title);
100
+ });
101
+ program
102
+ .command("clear")
103
+ .description("Start a new session (forgets the active one locally)")
104
+ .action(() => {
105
+ clearActiveSession(ctx);
106
+ success("Cleared. Your next message starts a fresh session.");
107
+ });
108
+ }
109
+ // ── Shared operations (the shell routes straight to these) ───────────────────
110
+ /** Switch the active conversation by ordinal or id. */
111
+ export async function switchTo(ctx, client, ref) {
112
+ try {
113
+ const s = await withSpinner("Opening…", () => resolveSession(ctx, client, ref));
114
+ setActiveSession(ctx, s.session_id, s.title);
115
+ success(`Switched to “${s.title}”.`);
116
+ // Replay the conversation you just opened. Switching without it left you
117
+ // typing into a thread whose contents you could not see — the model has the
118
+ // full context, so the person should too. Reuses /history's renderer, so
119
+ // memory markers and clarification blocks render identically.
120
+ await showHistory(ctx, client, s.session_id);
121
+ // Earlier coding work in that conversation, as context only (shell/task-context-view.ts).
122
+ if (typeof client.mutationRecoveryScope === "function") {
123
+ await showTaskContext(client, s.session_id);
124
+ }
125
+ }
126
+ catch (err) {
127
+ reportRefError(err);
128
+ }
129
+ }
130
+ /** Arrow-key picker over the current conversations. */
131
+ export async function pickSession(ctx, client) {
132
+ const { conversations } = await listSessions(ctx, client, { limit: 25 });
133
+ if (conversations.length === 0) {
134
+ for (const l of emptyState("No conversations yet.", "Start chatting to create one."))
135
+ line(l);
136
+ return;
137
+ }
138
+ const activeId = ctx.config.get("sessionId");
139
+ // Numbers are padded and titles column-aligned so the picker reads like the
140
+ // printed list — the number shown here is the same one `/session <n>` takes,
141
+ // so switching between the two ways of choosing never means re-counting.
142
+ const nw = String(conversations.length).length;
143
+ const tw = Math.min(38, Math.max(...conversations.map((cv) => [...cv.title].length)));
144
+ const chosen = await pickFromList({
145
+ title: "Sessions",
146
+ description: "↑↓ to choose · Enter to continue that conversation · Esc to cancel",
147
+ initial: Math.max(0, conversations.findIndex((cv) => cv.session_id === activeId)),
148
+ choices: conversations.map((cv, i) => ({
149
+ value: cv.session_id,
150
+ label: `${String(i + 1).padStart(nw)} ${clipTitle(cv.title, tw)}`,
151
+ description: `${cv.message_count} msgs · ${timeAgo(cv.last_activity)}`,
152
+ current: cv.session_id === activeId
153
+ }))
154
+ });
155
+ if (chosen == null)
156
+ return; // Esc / Ctrl+C — leave the session unchanged
157
+ await switchTo(ctx, client, chosen);
158
+ }
159
+ /** Delete a conversation after an explicit confirmation. */
160
+ export async function deleteSession(ctx, client, ref) {
161
+ let target;
162
+ try {
163
+ target = await withSpinner("Loading…", () => resolveSession(ctx, client, ref));
164
+ }
165
+ catch (err) {
166
+ reportRefError(err);
167
+ return;
168
+ }
169
+ // Deletion is irreversible and there is no undo in a terminal, so name what
170
+ // will be lost. `initial: 0` = "Keep" so a non-TTY (piped/CI) run declines
171
+ // rather than silently deleting.
172
+ const answer = await pickFromList({
173
+ title: "Delete this conversation?",
174
+ description: `“${target.title}” — this cannot be undone.`,
175
+ initial: 0,
176
+ confirmOnNumber: true,
177
+ choices: [
178
+ { value: "no", label: "Keep it" },
179
+ { value: "yes", label: "Delete" }
180
+ ]
181
+ });
182
+ if (answer !== "yes") {
183
+ info("Left it alone.");
184
+ return;
185
+ }
186
+ try {
187
+ await withSpinner("Deleting…", () => client.deleteSession(target.session_id));
188
+ if (ctx.config.get("sessionId") === target.session_id)
189
+ clearActiveSession(ctx);
190
+ success(`Deleted “${target.title}”.`);
191
+ // The ordinals just shifted — refresh so the next number means what the user
192
+ // last saw, rather than pointing one place further down the list.
193
+ await listSessions(ctx, client, { spinner: false }).catch(() => undefined);
194
+ }
195
+ catch (err) {
196
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
197
+ process.exitCode = 1;
198
+ }
199
+ }
200
+ /**
201
+ * Start a fresh conversation.
202
+ *
203
+ * Without a title this just drops the local pointer — the next message creates
204
+ * the conversation with the CORRECT chat type (Carrier or Standard) through the
205
+ * normal chat flow. With a title we must call POST /v1/sessions, which hardcodes
206
+ * `type: "regular"`, so a titled new chat is Standard-only; in Carrier chat we
207
+ * say so instead of silently downgrading the conversation type.
208
+ */
209
+ export async function newSession(ctx, title) {
210
+ if (!title) {
211
+ clearActiveSession(ctx);
212
+ success("New conversation. Your next message starts it.");
213
+ return;
214
+ }
215
+ if (ctx.chatType === "carrier") {
216
+ errorLine("Titles are Standard chat only — the API creates titled sessions as Standard.");
217
+ line(" " + c.dim("Run /new without a title to start a Carrier chat, or /switch standard."));
218
+ return;
219
+ }
220
+ const client = ctx.requireAuth();
221
+ try {
222
+ const s = await withSpinner("Creating…", () => client.createSession(title));
223
+ setActiveSession(ctx, s.session_id, s.title);
224
+ success(`Started “${s.title}”.`);
225
+ }
226
+ catch (err) {
227
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
228
+ process.exitCode = 1;
229
+ }
230
+ }
231
+ /** Consistent, actionable output for a bad/stale reference. */
232
+ export function reportRefError(err) {
233
+ if (err instanceof SessionRefError) {
234
+ errorLine(err.message);
235
+ if (err.hint)
236
+ line(" " + c.dim(err.hint));
237
+ return;
238
+ }
239
+ errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
240
+ process.exitCode = 1;
241
+ }
242
+ /** Pad to `width`, or clip with an ellipsis when the title is longer. */
243
+ function clipTitle(title, width) {
244
+ const chars = [...title];
245
+ if (chars.length <= width)
246
+ return title.padEnd(width);
247
+ return chars.slice(0, width - 1).join("") + "…";
248
+ }
249
+ function clampLimit(raw) {
250
+ const n = parseInt(raw, 10);
251
+ if (Number.isNaN(n))
252
+ return 20;
253
+ return Math.min(Math.max(n, 1), 100);
254
+ }
255
+ /**
256
+ * The numbered listing. The number is the handle for every other command, so it
257
+ * leads the row; the id is dropped entirely — it was only ever there to be
258
+ * copied, which is what the numbers now replace.
259
+ */
260
+ export function renderSessionList(items, activeId, total) {
261
+ if (items.length === 0) {
262
+ for (const l of emptyState("No conversations yet.", "Type a message to start one, or run /new.")) {
263
+ line(l);
264
+ }
265
+ return;
266
+ }
267
+ line();
268
+ line(sectionHeader(`Sessions (${items.length} of ${total})`));
269
+ const w = Math.max(0, ...items.map((s) => [...s.title].length));
270
+ const nw = String(items.length).length;
271
+ items.forEach((s, i) => {
272
+ const active = s.session_id === activeId;
273
+ const num = c.dim(String(i + 1).padStart(nw));
274
+ const marker = active ? icon.active : " ";
275
+ const title = (active ? c.brand : c.value)(s.title.padEnd(w));
276
+ const meta = c.dim(`${s.message_count} msgs · ${timeAgo(s.last_activity)}`);
277
+ line(` ${num} ${marker} ${title} ${meta}`);
278
+ });
279
+ line();
280
+ line(" " + c.dim("Continue one with ") + c.cmd("/session <n>"));
281
+ line();
282
+ }