@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,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
+ }
@@ -1,50 +1,223 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { ApiError } from "../services/api.js";
4
- import { errorLine, info, kv, line, success } from "../services/output.js";
3
+ import { attachedFilenames, ensureUploaded, uploadAndAttach, UploadError } from "../services/file-upload.js";
4
+ import { errorLine, info, line, success } from "../services/output.js";
5
5
  import { withSpinner } from "../services/spinner.js";
6
+ import { c } from "../ui/colors.js";
7
+ import { pickFromList } from "../ui/select.js";
8
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
9
+ /** Expand file args — literal paths pass through; `*`/`?` are globbed locally. */
10
+ function expandFiles(patterns) {
11
+ const out = [];
12
+ for (const p of patterns) {
13
+ const base = path.basename(p);
14
+ if (/[*?]/.test(base)) {
15
+ const dir = path.resolve(path.dirname(p));
16
+ const rx = new RegExp("^" +
17
+ base
18
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
19
+ .replace(/\*/g, ".*")
20
+ .replace(/\?/g, ".") +
21
+ "$", "i");
22
+ try {
23
+ for (const name of fs.readdirSync(dir)) {
24
+ const full = path.join(dir, name);
25
+ if (rx.test(name) && fs.statSync(full).isFile())
26
+ out.push(full);
27
+ }
28
+ }
29
+ catch {
30
+ /* directory missing */
31
+ }
32
+ }
33
+ else {
34
+ out.push(path.resolve(p));
35
+ }
36
+ }
37
+ return [...new Set(out)];
38
+ }
39
+ function reportError(err) {
40
+ errorLine(err instanceof UploadError ? err.message : err.message);
41
+ }
42
+ /** "Attached files (N)" list. */
43
+ function printAttachedList(ctx) {
44
+ const names = attachedFilenames(ctx);
45
+ if (names.length === 0)
46
+ return;
47
+ line();
48
+ line(" " + c.dim(`Attached files (${names.length})`));
49
+ for (const n of names)
50
+ line(" " + c.dim("• ") + c.value(n));
51
+ }
52
+ /** Next-command suggestions after a standalone upload. */
53
+ function printTry(multiple) {
54
+ line();
55
+ line(" " + c.dim("Try:"));
56
+ line(' ' + c.cmd('cos chat "Summarize this file"'));
57
+ if (multiple)
58
+ line(' ' + c.cmd('cos chat "Compare the attached files"'));
59
+ line(" " + c.cmd("cos") + c.dim(" (open interactive mode)"));
60
+ line();
61
+ }
62
+ /** Yes/No confirm (default Yes, 1→Yes / 2→No, Esc cancels → false). */
63
+ async function confirmAttach(question) {
64
+ const chosen = await pickFromList({
65
+ title: question,
66
+ choices: [
67
+ { value: "yes", label: "Yes" },
68
+ { value: "no", label: "No" }
69
+ ],
70
+ initial: 0,
71
+ confirmOnNumber: true
72
+ });
73
+ return chosen === "yes";
74
+ }
75
+ /** Standalone single-file flow: upload/find, then confirm attach (Case A/B/C). */
76
+ async function standaloneSingle(ctx, client, filePath, opts) {
77
+ const r = await ensureUploaded(ctx, client, filePath, {
78
+ onUploading: () => {
79
+ line();
80
+ line(" " + c.dim("Uploading…"));
81
+ },
82
+ onUploaded: (n) => success(`Uploaded ${n}`),
83
+ onProcessing: () => {
84
+ line();
85
+ line(" " + c.dim("Processing in background…"));
86
+ },
87
+ process: opts.process
88
+ });
89
+ // Case A — already uploaded AND attached.
90
+ if (r.status === "existing" && r.wasAttached) {
91
+ line();
92
+ success(`${r.filename} is already attached to this conversation.`);
93
+ line();
94
+ line(" " + c.dim("Ready to use."));
95
+ printAttachedList(ctx);
96
+ printTry(attachedFilenames(ctx).length > 1);
97
+ return;
98
+ }
99
+ // Case B — previously uploaded, not attached.
100
+ if (r.status === "existing" && !r.wasAttached) {
101
+ line();
102
+ success(`Found existing upload: ${r.filename}`);
103
+ line();
104
+ const yes = await confirmAttach("Attach it to this conversation?");
105
+ line();
106
+ if (yes) {
107
+ ctx.attachFile(r.fileId);
108
+ success(`Attached ${r.filename}`);
109
+ line();
110
+ line(" " + c.dim("Ready to chat about it."));
111
+ }
112
+ else {
113
+ info("Nothing changed.");
114
+ }
115
+ return;
116
+ }
117
+ // Case C — a brand-new upload (Uploading/Processing already printed).
118
+ line();
119
+ const yes = await confirmAttach("Attach this file to the current conversation?");
120
+ line();
121
+ if (yes) {
122
+ ctx.attachFile(r.fileId);
123
+ success(`Attached ${r.filename}`);
124
+ line();
125
+ line(" " + c.dim("Ready to chat about it."));
126
+ printTry(false);
127
+ }
128
+ else {
129
+ success("Upload complete.");
130
+ line();
131
+ line(" " + c.dim("The file is saved to your uploads. Attach it anytime with:"));
132
+ line(" " + c.cmd(`cos attach "${r.filename}"`));
133
+ line();
134
+ }
135
+ }
6
136
  /**
7
- * `cos upload <file>` — upload a file (POST /v1/files) and immediately
8
- * kick off indexing (POST /v1/files/:id/process). The file id is remembered
9
- * locally so `cos files` can list it and `chat` can reference it later.
137
+ * `cos upload <files...>` / `/upload` — upload one or more files and index each.
138
+ * Thin client: `ensureUploaded` does the /v1/files + /process calls; this owns the
139
+ * UX. It NEVER starts a chat or summarizes.
140
+ *
141
+ * • Inside the shell → upload + auto-attach + "Ready." (you're already chatting).
142
+ * • Standalone (single file) → upload, then confirm whether to attach.
143
+ * • Standalone (multiple) → upload + attach all, then show next steps.
10
144
  */
11
145
  export function registerUpload(program, ctx) {
12
146
  program
13
147
  .command("upload")
14
- .description("Upload a file and start processing it")
15
- .argument("<file>", "path to the file to upload")
148
+ .description("Upload one or more files and start processing them")
149
+ .argument("<files...>", "path(s) to upload — multiple files and * globs are supported")
16
150
  .option("--no-process", "upload only; skip the processing/indexing step")
17
- .action(async (file, opts) => {
151
+ .action(async (files, opts) => {
152
+ // Standalone runs reach the disk without having passed the shell's
153
+ // startup check, so gate them here too. In-shell is already trusted.
154
+ if (!ctx.inShell && !(await ensureWorkspaceTrust(ctx.config))) {
155
+ process.exitCode = 1;
156
+ return;
157
+ }
18
158
  const client = ctx.requireAuth();
19
- const filePath = path.resolve(file);
20
- if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
21
- errorLine(`No such file: ${filePath}`);
159
+ const paths = expandFiles(files);
160
+ if (paths.length === 0) {
161
+ errorLine("Couldn't find that file. Check the path and try again.");
22
162
  process.exitCode = 1;
23
163
  return;
24
164
  }
25
- try {
26
- const uploaded = await withSpinner(`Uploading ${path.basename(filePath)}…`, () => client.uploadFile(filePath));
27
- success("Uploaded.");
28
- kv("File id", uploaded.file_id);
29
- kv("Name", uploaded.filename);
30
- kv("Type", uploaded.file_type);
31
- kv("Size", `${(uploaded.file_size / 1024).toFixed(1)} KB`);
32
- ctx.config.addUpload({
33
- file_id: uploaded.file_id,
34
- filename: uploaded.filename,
35
- file_type: uploaded.file_type,
36
- uploaded_at: new Date().toISOString()
37
- });
38
- if (opts.process) {
39
- const processed = await withSpinner("Processing…", () => client.processFile(uploaded.file_id));
40
- kv("Status", processed.status);
41
- info("Processing runs in the background; the file is usable once indexed.");
165
+ // ── Interactive shell: upload + auto-attach, no prompts ──────────────────
166
+ if (ctx.inShell) {
167
+ let ok = 0;
168
+ for (const fp of paths) {
169
+ try {
170
+ const r = await withSpinner(`Uploading ${path.basename(fp)}…`, () => uploadAndAttach(ctx, client, fp, { process: opts.process }));
171
+ line();
172
+ if (r.status === "uploaded")
173
+ success(`Uploaded ${r.filename}`);
174
+ success(r.wasAttached ? `${r.filename} already attached` : `Attached ${r.filename}`);
175
+ ok += 1;
176
+ }
177
+ catch (err) {
178
+ reportError(err);
179
+ }
180
+ }
181
+ if (ok > 0) {
182
+ line();
183
+ info("Ready.");
184
+ line();
185
+ }
186
+ if (ok < paths.length)
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ // ── Standalone, single file: confirm attach (Case A/B/C) ─────────────────
191
+ if (paths.length === 1) {
192
+ try {
193
+ await standaloneSingle(ctx, client, paths[0], opts);
42
194
  }
195
+ catch (err) {
196
+ reportError(err);
197
+ process.exitCode = 1;
198
+ }
199
+ return;
200
+ }
201
+ // ── Standalone, multiple files: upload + attach all, then next steps ─────
202
+ let ok = 0;
203
+ for (const fp of paths) {
204
+ try {
205
+ const r = await withSpinner(`Uploading ${path.basename(fp)}…`, () => uploadAndAttach(ctx, client, fp, { process: opts.process }));
206
+ line();
207
+ success(r.status === "uploaded" ? `Uploaded ${r.filename}` : `${r.filename} (already uploaded)`);
208
+ ok += 1;
209
+ }
210
+ catch (err) {
211
+ reportError(err);
212
+ }
213
+ }
214
+ if (ok > 0) {
43
215
  line();
216
+ info(`Attached ${ok} file${ok > 1 ? "s" : ""} to this conversation.`);
217
+ printAttachedList(ctx);
218
+ printTry(ok > 1);
44
219
  }
45
- catch (err) {
46
- errorLine(err instanceof ApiError ? `${err.message} (${err.code})` : err.message);
220
+ if (ok < paths.length)
47
221
  process.exitCode = 1;
48
- }
49
222
  });
50
223
  }
@@ -1,9 +1,17 @@
1
- import chalk from "chalk";
2
- import { heading, kv, line } from "../services/output.js";
1
+ import { heading, line } from "../services/output.js";
3
2
  import { withSpinner } from "../services/spinner.js";
3
+ import { c } from "../ui/colors.js";
4
+ import { icon, sectionHeader, termWidth, visibleLen } from "../ui/ui.js";
4
5
  /**
5
- * `cos usage` — requests, tokens and estimated cost for the current
6
- * project, with today / this-month breakdowns, from GET /v1/usage.
6
+ * `cos usage` — requests, tokens and estimated cost for the current project,
7
+ * plus the credit balance that decides whether you can keep going, from
8
+ * GET /v1/usage.
9
+ *
10
+ * The two halves answer different questions and are deliberately separated:
11
+ * activity is scoped to THIS project's conversations, while credits are the
12
+ * account-wide wallet the web reads. Zero requests next to a spent wallet is a
13
+ * normal state, not a contradiction — the note under the table says so, because
14
+ * the two numbers sitting side by side otherwise read as a bug.
7
15
  */
8
16
  export function registerUsage(program, ctx) {
9
17
  program
@@ -13,19 +21,207 @@ export function registerUsage(program, ctx) {
13
21
  const client = ctx.requireAuth();
14
22
  const usage = await withSpinner("Loading usage…", () => client.usage());
15
23
  heading(`Usage · project ${usage.project_id}`);
16
- kv("Requests", String(usage.requests));
17
- kv("Successful", chalk.green(String(usage.successful_requests)));
18
- kv("Failed", usage.failed_requests > 0 ? chalk.red(String(usage.failed_requests)) : "0");
19
- kv("Tokens", usage.tokens_used.toLocaleString());
20
- kv("Est. cost", usage.estimated_cost);
21
- period("Today", usage.daily_usage);
22
- period("This month", usage.monthly_usage);
24
+ renderActivity(usage);
25
+ renderCredits(usage.credits);
23
26
  line();
24
27
  });
25
28
  }
26
- function period(label, p) {
27
- heading(label);
28
- kv("Requests", String(p.requests));
29
- kv("Tokens", p.tokens_used.toLocaleString());
30
- kv("Est. cost", p.estimated_cost);
29
+ /* ── Activity ─────────────────────────────────────────────────────────────── */
30
+ /**
31
+ * One table, three periods — not three stacked blocks repeating the same five
32
+ * labels. Today / month / all-time only mean anything next to each other.
33
+ */
34
+ export function renderActivity(u) {
35
+ const allTime = {
36
+ requests: u.requests,
37
+ successful_requests: u.successful_requests,
38
+ failed_requests: u.failed_requests,
39
+ input_tokens: 0,
40
+ output_tokens: 0,
41
+ tokens_used: u.tokens_used,
42
+ estimated_cost_usd: 0,
43
+ estimated_cost: u.estimated_cost
44
+ };
45
+ const periods = [
46
+ ["Today", u.daily_usage],
47
+ ["Month", u.monthly_usage],
48
+ ["All time", allTime]
49
+ ];
50
+ const cells = [
51
+ ["Requests", (p) => num(p.requests)],
52
+ ["Succeeded", (p) => tint(num(p.successful_requests), p.successful_requests > 0 ? c.ok : null)],
53
+ ["Failed", (p) => tint(num(p.failed_requests), p.failed_requests > 0 ? c.err : null)],
54
+ ["Tokens", (p) => num(p.tokens_used)],
55
+ ["Est. cost", (p) => p.estimated_cost]
56
+ ];
57
+ line();
58
+ line(sectionHeader("Activity"));
59
+ line();
60
+ for (const l of table(periods.map(([label]) => label), cells.map(([label, cell]) => [label, periods.map(([, p]) => cell(p))]))) {
61
+ line(l);
62
+ }
63
+ const a = u.activity;
64
+ if (a) {
65
+ // `Requests` counts every API call — a turn that used local tools also
66
+ // posts one result per tool, plus the lookups the shell does. Say what the
67
+ // turns actually were, so a 12-turn session does not read as 49 "requests".
68
+ line();
69
+ line(" " +
70
+ c.label("Turns".padEnd(11)) +
71
+ c.value(`${num(a.daily.turns)} today · ${num(a.monthly.turns)} this month · ${num(a.total.turns)} all time`));
72
+ line(" " +
73
+ c.dim(`Requests also include ${num(a.total.tool_results)} local tool results and ${num(a.total.other)} other API calls (history, models, auth).`));
74
+ }
75
+ line();
76
+ line(" " + c.dim("Conversations started through this project. Credits below are account-wide."));
77
+ }
78
+ /* ── Credits ──────────────────────────────────────────────────────────────── */
79
+ /**
80
+ * Credit balance and per-model pools. "Can I keep going?" is a billing
81
+ * question, and it is the one people actually run `/usage` to answer — so it
82
+ * gets the room the repeated request counts used to take.
83
+ *
84
+ * Silent when the API didn't send it (older build, or the billing lookup
85
+ * failed), rather than printing a zero balance that isn't true.
86
+ */
87
+ export function renderCredits(credits) {
88
+ if (!credits)
89
+ return;
90
+ // Unlimited: the balance cannot stop you, so it is not presented as one —
91
+ // no "overdrawn", no "out of credits" warning. The spend is still real and is
92
+ // shown in full, because hiding what an account costs is not the same thing
93
+ // as not alarming its owner.
94
+ const unlimited = credits.unlimited === true;
95
+ const empty = !unlimited && credits.remaining <= 0;
96
+ line();
97
+ line(sectionHeader("Credits"));
98
+ line();
99
+ if (unlimited) {
100
+ line(" " + c.label("Plan".padEnd(11)) + c.ok("Unlimited") + " " + c.dim("usage is recorded, never blocked"));
101
+ }
102
+ else {
103
+ // A negative balance is shown as it is, not clamped to zero — but
104
+ // "overdrawn" is what it means, and nobody should infer it from a minus sign.
105
+ line(" " +
106
+ c.label("Balance".padEnd(11)) +
107
+ (empty ? c.err(dec(credits.remaining)) : c.ok(dec(credits.remaining))) +
108
+ (credits.remaining < 0 ? " " + c.dim("overdrawn") : ""));
109
+ }
110
+ line(" " + c.label("Spent".padEnd(11)) + c.value(dec(credits.total_spent)) + " " + c.dim("all time"));
111
+ const month = credits.month_spent;
112
+ if (month) {
113
+ line(" " +
114
+ c.label("This month".padEnd(11)) +
115
+ c.value(dec(month.turns + month.background)) +
116
+ " " +
117
+ c.dim(`${dec(month.turns)} your turns · ${dec(month.background)} background context upkeep`));
118
+ }
119
+ if (empty) {
120
+ line();
121
+ line(" " + icon.warn + c.warn(" Out of credits — buy more or upgrade your plan to continue."));
122
+ }
123
+ // Per-model pools exist only on plans that define them; an empty list is a
124
+ // normal state, not a failure.
125
+ const pools = credits.models ?? [];
126
+ if (pools.length === 0)
127
+ return;
128
+ const spent = (p) => p.status === "exceeded" || p.remaining <= 0;
129
+ const available = pools.filter((p) => !spent(p)).sort((a, b) => b.remaining - a.remaining);
130
+ const exhausted = pools.filter(spent).sort((a, b) => a.model.localeCompare(b.model));
131
+ line();
132
+ line(sectionHeader(`Model credits (${available.length} of ${pools.length} available)`));
133
+ line();
134
+ // What you CAN use, with its balance, in as many columns as the terminal
135
+ // fits — this is the actionable half, so it keeps its numbers.
136
+ if (available.length > 0) {
137
+ for (const l of grid(available.map((p) => [p.model, dec(p.remaining)]))) {
138
+ line(l);
139
+ }
140
+ }
141
+ else {
142
+ line(" " + c.dim("No model has credit remaining."));
143
+ }
144
+ // What you can't is a single dim, wrapped list. Twenty rows of the word
145
+ // "exhausted" is the same information at twenty times the height.
146
+ if (exhausted.length > 0) {
147
+ line();
148
+ line(" " + c.err("✕") + c.dim(` ${exhausted.length} exhausted`));
149
+ for (const l of wrap(exhausted.map((p) => p.model).join(", "), Math.max(20, panelWidth() - 6))) {
150
+ line(" " + c.dim(l));
151
+ }
152
+ }
153
+ }
154
+ /* ── Layout helpers ───────────────────────────────────────────────────────── */
155
+ const num = (n) => n.toLocaleString("en-US");
156
+ const dec = (n) => n.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
157
+ const tint = (s, color) => (color ? color(s) : s);
158
+ /**
159
+ * A label column plus right-aligned value columns. Every width is measured on
160
+ * VISIBLE characters and padded before coloring, so ANSI codes can never throw
161
+ * the alignment off — the fixed-width `kv` this replaced collided with any
162
+ * label 14 characters or longer, which is most model ids.
163
+ */
164
+ function table(headers, rows) {
165
+ const labelW = Math.max(...rows.map(([label]) => visibleLen(label)));
166
+ const colW = headers.map((h, i) => Math.max(visibleLen(h), ...rows.map(([, cells]) => visibleLen(cells[i] ?? ""))));
167
+ const gap = " ";
168
+ const padLeft = (s, w) => " ".repeat(Math.max(0, w - visibleLen(s))) + s;
169
+ const out = [
170
+ " " + " ".repeat(labelW) + gap + headers.map((h, i) => c.dim(padLeft(h, colW[i]))).join(gap)
171
+ ];
172
+ for (const [label, cells] of rows) {
173
+ out.push(" " +
174
+ c.label(label.padEnd(labelW)) +
175
+ gap +
176
+ cells.map((cell, i) => padLeft(cell, colW[i])).join(gap));
177
+ }
178
+ return out;
179
+ }
180
+ /**
181
+ * Widest a block may grow, however wide the window is. Lists that run the full
182
+ * width of a maximised terminal are harder to read, not easier, and the rest of
183
+ * the CLI already keeps its section rules short.
184
+ */
185
+ const panelWidth = () => Math.min(termWidth(), 100);
186
+ /** `name value` pairs flowed into as many equal columns as the terminal fits. */
187
+ function grid(pairs, indent = " ") {
188
+ const nameW = Math.max(...pairs.map(([name]) => visibleLen(name)));
189
+ const valW = Math.max(...pairs.map(([, value]) => visibleLen(value)));
190
+ const cellW = nameW + 2 + valW;
191
+ const gap = 3;
192
+ const cols = Math.max(1, Math.floor((panelWidth() - indent.length + gap) / (cellW + gap)));
193
+ const rows = Math.ceil(pairs.length / cols);
194
+ const out = [];
195
+ for (let r = 0; r < rows; r++) {
196
+ const cells = [];
197
+ // Column-major, so reading down a column keeps the descending order.
198
+ for (let col = 0; col < cols; col++) {
199
+ const pair = pairs[col * rows + r];
200
+ if (!pair)
201
+ continue;
202
+ const [name, value] = pair;
203
+ cells.push(c.value(name.padEnd(nameW)) +
204
+ " " +
205
+ c.ok(" ".repeat(Math.max(0, valW - visibleLen(value))) + value));
206
+ }
207
+ out.push((indent + cells.join(" ".repeat(gap))).trimEnd());
208
+ }
209
+ return out;
210
+ }
211
+ /** Word-wrap plain text to `width` visible columns. */
212
+ function wrap(text, width) {
213
+ const out = [];
214
+ let cur = "";
215
+ for (const word of text.split(" ")) {
216
+ if (cur && cur.length + 1 + word.length > width) {
217
+ out.push(cur);
218
+ cur = word;
219
+ }
220
+ else {
221
+ cur = cur ? `${cur} ${word}` : word;
222
+ }
223
+ }
224
+ if (cur)
225
+ out.push(cur);
226
+ return out;
31
227
  }