@carrieros/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +102 -13
  7. package/dist/commands/context.js +160 -0
  8. package/dist/commands/doctor.js +53 -8
  9. package/dist/commands/files.js +84 -23
  10. package/dist/commands/help.js +3 -1
  11. package/dist/commands/history.js +88 -23
  12. package/dist/commands/login.js +44 -41
  13. package/dist/commands/logout.js +13 -4
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +39 -3
  16. package/dist/commands/modes.js +4 -1
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +152 -0
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +219 -65
  24. package/dist/commands/settings.js +87 -0
  25. package/dist/commands/update.js +159 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +212 -16
  28. package/dist/commands/whoami.js +2 -1
  29. package/dist/ide/editor-context.js +172 -0
  30. package/dist/ide/ide-session.js +94 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +30 -1
  33. package/dist/services/api.js +171 -13
  34. package/dist/services/chat-stream.js +145 -0
  35. package/dist/services/checkpoints.js +116 -0
  36. package/dist/services/client-tools.js +260 -0
  37. package/dist/services/command-coordinator.js +200 -0
  38. package/dist/services/command-policy.js +404 -0
  39. package/dist/services/config.js +249 -22
  40. package/dist/services/context.js +307 -6
  41. package/dist/services/device-auth.js +261 -0
  42. package/dist/services/diff.js +196 -0
  43. package/dist/services/env-policy.js +108 -0
  44. package/dist/services/file-detect.js +104 -0
  45. package/dist/services/file-resolver.js +199 -0
  46. package/dist/services/file-upload.js +126 -0
  47. package/dist/services/git-tools.js +248 -0
  48. package/dist/services/glob-match.js +164 -0
  49. package/dist/services/helper-bin.js +64 -0
  50. package/dist/services/ignore-rules.js +189 -0
  51. package/dist/services/job-helper.js +307 -0
  52. package/dist/services/local-files.js +517 -0
  53. package/dist/services/local-tools.js +432 -0
  54. package/dist/services/login-flow.js +120 -10
  55. package/dist/services/meta.js +3 -1
  56. package/dist/services/mutation-coordinator.js +161 -0
  57. package/dist/services/mutations.js +493 -0
  58. package/dist/services/open-url.js +68 -0
  59. package/dist/services/output.js +13 -5
  60. package/dist/services/packaged.js +24 -0
  61. package/dist/services/process-runner.js +406 -0
  62. package/dist/services/project-context.js +298 -0
  63. package/dist/services/redaction.js +201 -0
  64. package/dist/services/secure-store.js +197 -0
  65. package/dist/services/session-resolver.js +108 -0
  66. package/dist/services/sia.js +51 -0
  67. package/dist/services/spinner.js +23 -1
  68. package/dist/services/update.js +286 -0
  69. package/dist/services/workspace-registry.js +309 -0
  70. package/dist/services/workspace.js +573 -0
  71. package/dist/shell/shell-chat.js +1115 -59
  72. package/dist/shell/shell-commands.js +220 -19
  73. package/dist/shell/shell-prompt.js +89 -37
  74. package/dist/shell/shell-renderer.js +19 -38
  75. package/dist/shell/shell-router.js +19 -3
  76. package/dist/shell/shell.js +232 -44
  77. package/dist/types/index.js +3 -1
  78. package/dist/ui/approval.js +81 -0
  79. package/dist/ui/banner.js +55 -13
  80. package/dist/ui/btw-overlay.js +230 -0
  81. package/dist/ui/change-review.js +87 -0
  82. package/dist/ui/chat-renderer.js +223 -29
  83. package/dist/ui/color-picker.js +21 -0
  84. package/dist/ui/colors.js +9 -1
  85. package/dist/ui/command-filter.js +40 -5
  86. package/dist/ui/command-palette.js +122 -62
  87. package/dist/ui/command-registry.js +85 -11
  88. package/dist/ui/command-review.js +138 -0
  89. package/dist/ui/composer-layout.js +41 -0
  90. package/dist/ui/conversation.js +398 -0
  91. package/dist/ui/interrupt.js +35 -0
  92. package/dist/ui/live.js +18 -1
  93. package/dist/ui/markdown.js +63 -9
  94. package/dist/ui/message.js +14 -31
  95. package/dist/ui/screen-prompt.js +181 -0
  96. package/dist/ui/screen.js +289 -0
  97. package/dist/ui/select.js +193 -29
  98. package/dist/ui/sia-qa.js +213 -0
  99. package/dist/ui/text-prompt.js +74 -0
  100. package/dist/ui/theme.js +17 -0
  101. package/dist/ui/trust.js +93 -0
  102. package/dist/ui/ui.js +4 -1
  103. package/package.json +17 -6
  104. package/dist/ui/activity.js +0 -77
@@ -1,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
  }
@@ -33,7 +33,8 @@ function render(scope, cached) {
33
33
  kv("Workspace", `${scope.workspace.name} (${scope.workspace.slug})`);
34
34
  kv("Project", scope.project.name);
35
35
  kv("Environment", scope.project.environment);
36
- kv("Key", `${scope.apiKey.name} · ${scope.apiKey.type}`);
36
+ // apiKey is null for a device-flow (browser) session.
37
+ kv("Signed in via", scope.apiKey ? `API key · ${scope.apiKey.name}` : "Browser session");
37
38
  if (scope.user)
38
39
  kv("Account", scope.user.email);
39
40
  line();
@@ -0,0 +1,172 @@
1
+ import path from "node:path";
2
+ /** Bounds — editor context is a hint, never a payload. */
3
+ const MAX_SELECTION_BYTES = 32 * 1024;
4
+ const MAX_OPEN_FILES = 100;
5
+ const MAX_DIAGNOSTICS = 100;
6
+ const posix = (p) => p.split(path.sep).join("/");
7
+ /** { repository, path } for an absolute file, or null when outside every repo. */
8
+ function locate(absPath, resolve) {
9
+ const repo = resolve(absPath);
10
+ if (!repo)
11
+ return null;
12
+ const rel = posix(path.relative(repo.root, path.resolve(absPath)));
13
+ if (!rel || rel.startsWith(".."))
14
+ return null;
15
+ return { repository: repo.name, path: rel };
16
+ }
17
+ /**
18
+ * Answer one editor-context tool from a snapshot. Never throws; an unknown tool
19
+ * or an out-of-workspace file comes back as a clean, model-readable result.
20
+ */
21
+ export function executeIdeContextTool(name, args, state, resolve) {
22
+ switch (name) {
23
+ case "get_active_file": {
24
+ const a = state.activeFile;
25
+ if (!a)
26
+ return ok({ active: false });
27
+ const at = locate(a.absPath, resolve);
28
+ if (!at)
29
+ return ok({ active: false, reason: "The focused file is outside the workspace's repositories." });
30
+ return ok({
31
+ active: true,
32
+ repository: at.repository,
33
+ path: at.path,
34
+ language: a.languageId ?? null,
35
+ cursor: a.cursorLine ? { line: a.cursorLine, column: a.cursorColumn ?? 1 } : null
36
+ });
37
+ }
38
+ case "get_selection": {
39
+ const a = state.activeFile;
40
+ if (!a?.selection || !a.selection.text)
41
+ return ok({ selected: false });
42
+ const at = locate(a.absPath, resolve);
43
+ if (!at)
44
+ return ok({ selected: false, reason: "The selection is in a file outside the workspace." });
45
+ const text = clampBytes(a.selection.text, MAX_SELECTION_BYTES);
46
+ return ok({
47
+ selected: true,
48
+ repository: at.repository,
49
+ path: at.path,
50
+ language: a.languageId ?? null,
51
+ start_line: a.selection.startLine,
52
+ end_line: a.selection.endLine,
53
+ text: text.text,
54
+ truncated: text.truncated
55
+ });
56
+ }
57
+ case "get_open_files": {
58
+ const seen = new Set();
59
+ const files = [];
60
+ let outside = 0;
61
+ for (const abs of (state.openFiles ?? []).slice(0, MAX_OPEN_FILES * 2)) {
62
+ const at = locate(abs, resolve);
63
+ if (!at) {
64
+ outside += 1;
65
+ continue;
66
+ }
67
+ const key = `${at.repository}:${at.path}`;
68
+ if (seen.has(key))
69
+ continue;
70
+ seen.add(key);
71
+ if (files.length < MAX_OPEN_FILES)
72
+ files.push(at);
73
+ }
74
+ return ok({ files, outside_workspace: outside, truncated: files.length >= MAX_OPEN_FILES });
75
+ }
76
+ case "get_workspace_folders": {
77
+ const repos = (state.repositories ?? []).map((r) => ({ repository: r.name, active: r.active === true }));
78
+ return ok({ repositories: repos, active: repos.find((r) => r.active)?.repository ?? null });
79
+ }
80
+ case "get_diagnostics": {
81
+ // A named file, or the active one.
82
+ let absPath;
83
+ const wanted = typeof args.path === "string" ? args.path.trim() : "";
84
+ const wantedRepo = typeof args.repository === "string" ? args.repository.trim() : "";
85
+ if (wanted) {
86
+ // Resolve the requested project-relative path within the named/active repo.
87
+ const repoRoot = (state.repositories ?? []).find((r) => !wantedRepo || r.name === wantedRepo)?.root;
88
+ if (repoRoot)
89
+ absPath = path.resolve(repoRoot, wanted);
90
+ }
91
+ else {
92
+ absPath = state.activeFile?.absPath;
93
+ }
94
+ if (!absPath)
95
+ return ok({ diagnostics: [], reason: "No file to report diagnostics for." });
96
+ const at = locate(absPath, resolve);
97
+ if (!at)
98
+ return ok({ diagnostics: [], reason: "That file is outside the workspace's repositories." });
99
+ const entry = (state.diagnostics ?? []).find((d) => path.resolve(d.absPath) === path.resolve(absPath));
100
+ const items = (entry?.items ?? []).slice(0, MAX_DIAGNOSTICS).map((d) => ({
101
+ line: d.line,
102
+ severity: d.severity,
103
+ message: clampBytes(d.message, 2000).text,
104
+ source: d.source ?? null
105
+ }));
106
+ return ok({
107
+ repository: at.repository,
108
+ path: at.path,
109
+ diagnostics: items,
110
+ truncated: (entry?.items?.length ?? 0) > items.length
111
+ });
112
+ }
113
+ default:
114
+ return { ok: false, error: { code: "UNKNOWN_TOOL", message: `No IDE context tool named "${name}".` } };
115
+ }
116
+ }
117
+ /** The IDE editor-context tool names this module answers. */
118
+ export const IDE_CONTEXT_TOOL_NAMES = [
119
+ "get_active_file",
120
+ "get_selection",
121
+ "get_open_files",
122
+ "get_workspace_folders",
123
+ "get_diagnostics"
124
+ ];
125
+ export function isIdeContextTool(name) {
126
+ return IDE_CONTEXT_TOOL_NAMES.includes(name);
127
+ }
128
+ /**
129
+ * A small, bounded hint the host prepends to the user's message so the model
130
+ * knows what "this file"/"this section" refers to WITHOUT having to call
131
+ * get_active_file first. It is not a replacement for those tools — the model may
132
+ * still call them for more (the selected text, diagnostics, other open files).
133
+ *
134
+ * What it carries is deliberately minimal and safe:
135
+ * • the active file's repository and repo-relative path (identity, mapped the
136
+ * same way the tools map it — never an absolute path or a filesystem root);
137
+ * • the selected LINE RANGE only, when a selection exists — never the selected
138
+ * text or any file contents.
139
+ *
140
+ * Returns null when there is no active file inside a workspace repository, so
141
+ * the caller sends the plain message unchanged. The block is clearly labelled as
142
+ * editor-provided, so the model never mistakes it for the user's own words.
143
+ */
144
+ export function ideContextHint(state, resolve) {
145
+ const a = state.activeFile;
146
+ if (!a)
147
+ return null;
148
+ const at = locate(a.absPath, resolve);
149
+ if (!at)
150
+ return null;
151
+ const lines = [
152
+ "[IDE CONTEXT] (provided by the editor, not written by the user)",
153
+ `Repository: ${at.repository}`,
154
+ `File: ${at.path}`
155
+ ];
156
+ const sel = a.selection;
157
+ if (sel && sel.text && Number.isFinite(sel.startLine) && Number.isFinite(sel.endLine)) {
158
+ lines.push(`Selection: lines ${sel.startLine}-${sel.endLine}`);
159
+ }
160
+ return lines.join("\n");
161
+ }
162
+ function ok(result) {
163
+ return { ok: true, result };
164
+ }
165
+ function clampBytes(text, max) {
166
+ if (Buffer.byteLength(text, "utf8") <= max)
167
+ return { text, truncated: false };
168
+ let out = text;
169
+ while (Buffer.byteLength(out, "utf8") > max)
170
+ out = out.slice(0, Math.floor(out.length * 0.9));
171
+ return { text: out + "\n… [truncated]", truncated: true };
172
+ }