@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,227 @@
1
+ import { heading, line } from "../services/output.js";
2
+ import { withSpinner } from "../services/spinner.js";
3
+ import { c } from "../ui/colors.js";
4
+ import { formatCredits, icon, sectionHeader, termWidth, visibleLen } from "../ui/ui.js";
5
+ /**
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.
15
+ */
16
+ export function registerUsage(program, ctx) {
17
+ program
18
+ .command("usage")
19
+ .description("Show requests, tokens and estimated cost for this project")
20
+ .action(async () => {
21
+ const client = ctx.requireAuth();
22
+ const usage = await withSpinner("Loading usage…", () => client.usage());
23
+ heading(usage.project_id ? `Usage · project ${usage.project_id}` : "CLI usage");
24
+ renderActivity(usage);
25
+ renderCredits(usage.credits);
26
+ line();
27
+ });
28
+ }
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. An unlimited plan is never blocked by a pool, so "25 exhausted" would be false.
125
+ const pools = credits.models ?? [];
126
+ if (pools.length === 0 || unlimited)
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 = formatCredits;
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;
227
+ }
@@ -0,0 +1,26 @@
1
+ import chalk from "chalk";
2
+ import { cliVersion } from "../services/meta.js";
3
+ import { kv, line } from "../services/output.js";
4
+ /**
5
+ * `cos version` — CLI version (from package.json) + best-effort live API
6
+ * version. It deliberately omits the configured API URL. Prints:
7
+ * Carrier OS CLI 0.1.0
8
+ * API Version v1
9
+ */
10
+ export function registerVersion(program, ctx) {
11
+ program
12
+ .command("version")
13
+ .description("Print the CLI and API versions")
14
+ .action(async () => {
15
+ line();
16
+ line(` ${chalk.bold.white("Carrier OS CLI")} ${cliVersion()}`);
17
+ try {
18
+ const health = await ctx.client().health();
19
+ kv("API Version", health.version);
20
+ }
21
+ catch {
22
+ kv("API Version", chalk.dim("unreachable"));
23
+ }
24
+ line();
25
+ });
26
+ }
@@ -0,0 +1,44 @@
1
+ import { ApiError } from "../services/api.js";
2
+ import { heading, kv, line, warn } from "../services/output.js";
3
+ import { withSpinner } from "../services/spinner.js";
4
+ /**
5
+ * `cos whoami` — show the signed-in account. Re-verifies
6
+ * against the API for freshness, falling back to the cached scope if offline.
7
+ */
8
+ export function registerWhoami(program, ctx) {
9
+ program
10
+ .command("whoami")
11
+ .description("Show your signed-in account")
12
+ .option("--details", "include advanced API workspace, project and environment details")
13
+ .action(async (options) => {
14
+ const client = ctx.requireAuth();
15
+ try {
16
+ const scope = await withSpinner("Checking…", () => client.verify());
17
+ ctx.config.set("scope", scope);
18
+ render(scope, false, options.details);
19
+ }
20
+ catch (err) {
21
+ const cached = ctx.config.get("scope");
22
+ if (cached) {
23
+ warn(`Could not reach the API (${err instanceof ApiError ? err.code : "error"}); showing cached details.`);
24
+ render(cached, true, options.details);
25
+ }
26
+ else {
27
+ throw err;
28
+ }
29
+ }
30
+ });
31
+ }
32
+ function render(scope, cached, details = false) {
33
+ heading(cached ? "Account (cached)" : "Account");
34
+ if (details) {
35
+ kv("API workspace", `${scope.workspace?.name ?? "Not required"} (${scope.workspace?.slug ?? "user session"})`);
36
+ kv("API project", scope.project?.name ?? "Not required");
37
+ kv("Project environment", scope.project?.environment ?? "Not applicable");
38
+ }
39
+ // apiKey is null for a device-flow (browser) session.
40
+ kv("Signed in via", scope.apiKey ? `API key · ${scope.apiKey.name}` : "Browser session");
41
+ if (scope.user)
42
+ kv("Account", scope.user.email);
43
+ line();
44
+ }
@@ -0,0 +1,275 @@
1
+ import path from "node:path";
2
+ import { looksBinary } from "../services/local-files.js";
3
+ import { executeLocalTool } from "../services/local-tools.js";
4
+ import { repositoryForPath } from "../services/workspace-registry.js";
5
+ /** Bounds — editor context is a hint, never a payload. */
6
+ const MAX_SELECTION_BYTES = 32 * 1024;
7
+ const MAX_OPEN_FILES = 100;
8
+ const MAX_DIAGNOSTICS = 100;
9
+ const posix = (p) => p.split(path.sep).join("/");
10
+ /** { repository, path } for an absolute file, or null when outside every repo. */
11
+ function locate(absPath, resolve) {
12
+ const repo = resolve(absPath);
13
+ if (!repo)
14
+ return null;
15
+ const rel = posix(path.relative(repo.root, path.resolve(absPath)));
16
+ if (!rel || rel.startsWith(".."))
17
+ return null;
18
+ return { repository: repo.name, path: rel };
19
+ }
20
+ /**
21
+ * Answer one editor-context tool from a snapshot. Never throws; an unknown tool
22
+ * or an out-of-workspace file comes back as a clean, model-readable result.
23
+ */
24
+ export function executeIdeContextTool(name, args, state, resolve) {
25
+ switch (name) {
26
+ case "get_active_file": {
27
+ const a = state.activeFile;
28
+ if (!a)
29
+ return ok({ active: false });
30
+ const at = locate(a.absPath, resolve);
31
+ if (!at)
32
+ return ok({ active: false, reason: "The focused file is outside the workspace's repositories." });
33
+ return ok({
34
+ active: true,
35
+ repository: at.repository,
36
+ path: at.path,
37
+ language: a.languageId ?? null,
38
+ cursor: a.cursorLine ? { line: a.cursorLine, column: a.cursorColumn ?? 1 } : null,
39
+ visible_range: a.visibleRange ? { start_line: a.visibleRange.startLine, end_line: a.visibleRange.endLine } : null,
40
+ // Unsaved edits mean read_file (disk) and the editor differ.
41
+ dirty: a.dirty === true,
42
+ version: Number.isInteger(a.version) ? a.version : null
43
+ });
44
+ }
45
+ case "get_selection": {
46
+ const a = state.activeFile;
47
+ if (!a?.selection || !a.selection.text)
48
+ return ok({ selected: false });
49
+ // Editor metadata/resolvers cannot grant content access. Use the actual
50
+ // registry and the SAME read_file executor as CLI reads: trust, canonical
51
+ // containment, ignore/sensitive rules, binary detection and bounded I/O.
52
+ // Its file content is discarded; only the approved editor selection leaves
53
+ // this process (including unsaved edits to an existing allowed file).
54
+ const repo = repositoryForPath(a.absPath);
55
+ if (!repo)
56
+ return selectionDenied("OUTSIDE_WORKSPACE");
57
+ const checked = executeLocalTool({
58
+ id: "ide-selection-check",
59
+ name: "read_file",
60
+ arguments: { repository: repo.name, path: a.absPath }
61
+ });
62
+ if (!checked.ok)
63
+ return selectionDenied(checked.error?.code ?? "SELECTION_DENIED");
64
+ const checkedFile = checked.result;
65
+ // A small selection must not circumvent the underlying file's read cap.
66
+ if (checkedFile.truncated)
67
+ return selectionDenied("FILE_TOO_LARGE");
68
+ if (Buffer.byteLength(a.selection.text, "utf8") > MAX_SELECTION_BYTES) {
69
+ return selectionDenied("SELECTION_TOO_LARGE");
70
+ }
71
+ if (looksBinary(Buffer.from(a.selection.text, "utf8")))
72
+ return selectionDenied("BINARY_FILE");
73
+ return ok({
74
+ selected: true,
75
+ repository: repo.name,
76
+ path: checkedFile.path,
77
+ language: a.languageId ?? null,
78
+ start_line: a.selection.startLine,
79
+ end_line: a.selection.endLine,
80
+ ...(a.selection.startColumn ? { start_column: a.selection.startColumn, end_column: a.selection.endColumn ?? null } : {}),
81
+ version: Number.isInteger(a.version) ? a.version : null,
82
+ text: a.selection.text,
83
+ truncated: false
84
+ });
85
+ }
86
+ case "get_open_files": {
87
+ const seen = new Set();
88
+ const files = [];
89
+ const meta = new Map((state.openDocuments ?? []).map((d) => [path.resolve(d.absPath), d]));
90
+ let outside = 0;
91
+ for (const abs of (state.openFiles ?? []).slice(0, MAX_OPEN_FILES * 2)) {
92
+ const at = locate(abs, resolve);
93
+ if (!at) {
94
+ outside += 1;
95
+ continue;
96
+ }
97
+ const key = `${at.repository}:${at.path}`;
98
+ if (seen.has(key))
99
+ continue;
100
+ seen.add(key);
101
+ const d = meta.get(path.resolve(abs));
102
+ if (files.length < MAX_OPEN_FILES) {
103
+ files.push({ ...at, ...(d ? { language: d.languageId, dirty: d.dirty === true, active: d.active === true, ...(Number.isInteger(d.version) ? { version: d.version } : {}) } : {}) });
104
+ }
105
+ }
106
+ return ok({ files, outside_workspace: outside, truncated: files.length >= MAX_OPEN_FILES });
107
+ }
108
+ case "get_workspace_folders": {
109
+ const repos = (state.repositories ?? []).map((r) => ({ repository: r.name, active: r.active === true }));
110
+ return ok({ repositories: repos, active: repos.find((r) => r.active)?.repository ?? null });
111
+ }
112
+ case "get_diagnostics": {
113
+ // A named file, or the active one.
114
+ let absPath;
115
+ const wanted = typeof args.path === "string" ? args.path.trim() : "";
116
+ const wantedRepo = typeof args.repository === "string" ? args.repository.trim() : "";
117
+ if (wanted) {
118
+ // Resolve the requested project-relative path within the named/active repo.
119
+ const repoRoot = (state.repositories ?? []).find((r) => !wantedRepo || r.name === wantedRepo)?.root;
120
+ if (repoRoot)
121
+ absPath = path.resolve(repoRoot, wanted);
122
+ }
123
+ else {
124
+ absPath = state.activeFile?.absPath;
125
+ }
126
+ if (!absPath)
127
+ return ok({ diagnostics: [], reason: "No file to report diagnostics for." });
128
+ const at = locate(absPath, resolve);
129
+ if (!at)
130
+ return ok({ diagnostics: [], reason: "That file is outside the workspace's repositories." });
131
+ const entry = (state.diagnostics ?? []).find((d) => path.resolve(d.absPath) === path.resolve(absPath));
132
+ const items = (entry?.items ?? []).slice(0, MAX_DIAGNOSTICS).map((d) => ({
133
+ line: d.line,
134
+ column: d.column ?? null,
135
+ severity: d.severity,
136
+ message: clampBytes(d.message, 2000).text,
137
+ source: d.source ?? null,
138
+ code: d.code ?? null
139
+ }));
140
+ return ok({
141
+ repository: at.repository,
142
+ path: at.path,
143
+ diagnostics: items,
144
+ truncated: (entry?.items?.length ?? 0) > items.length
145
+ });
146
+ }
147
+ default:
148
+ return { ok: false, error: { code: "UNKNOWN_TOOL", message: `No IDE context tool named "${name}".` } };
149
+ }
150
+ }
151
+ /** The IDE editor-context tool names this module answers. */
152
+ export const IDE_CONTEXT_TOOL_NAMES = [
153
+ "get_active_file",
154
+ "get_selection",
155
+ "get_open_files",
156
+ "get_workspace_folders",
157
+ "get_diagnostics"
158
+ ];
159
+ export function isIdeContextTool(name) {
160
+ return IDE_CONTEXT_TOOL_NAMES.includes(name);
161
+ }
162
+ /**
163
+ * A small, bounded hint the host prepends to the user's message so the model
164
+ * knows what "this file"/"this section" refers to WITHOUT having to call
165
+ * get_active_file first. It is not a replacement for those tools — the model may
166
+ * still call them for more (the selected text, diagnostics, other open files).
167
+ *
168
+ * What it carries is deliberately minimal and safe:
169
+ * • the active file's repository and repo-relative path (identity, mapped the
170
+ * same way the tools map it — never an absolute path or a filesystem root);
171
+ * • the selected LINE RANGE only, when a selection exists — never the selected
172
+ * text or any file contents.
173
+ *
174
+ * Returns null when there is no active file inside a workspace repository, so
175
+ * the caller sends the plain message unchanged. The block is clearly labelled as
176
+ * editor-provided, so the model never mistakes it for the user's own words.
177
+ */
178
+ export function ideContextHint(state, resolve) {
179
+ const a = state.activeFile;
180
+ if (!a)
181
+ return null;
182
+ const at = locate(a.absPath, resolve);
183
+ if (!at)
184
+ return null;
185
+ const lines = [
186
+ "[IDE CONTEXT] (provided by the editor, not written by the user)",
187
+ `Repository: ${at.repository}`,
188
+ `File: ${at.path}`
189
+ ];
190
+ if (a.languageId)
191
+ lines.push(`Language: ${a.languageId}`);
192
+ if (a.cursorLine)
193
+ lines.push(`Cursor: line ${a.cursorLine}, column ${a.cursorColumn ?? 1}`);
194
+ if (a.visibleRange)
195
+ lines.push(`Visible lines: ${a.visibleRange.startLine}-${a.visibleRange.endLine}`);
196
+ if (a.dirty)
197
+ lines.push(`Unsaved edits in the editor${Number.isInteger(a.version) ? ` (version ${a.version})` : ""}: the file on disk differs; read_file returns the saved bytes.`);
198
+ const sel = a.selection;
199
+ if (sel && sel.text && Number.isFinite(sel.startLine) && Number.isFinite(sel.endLine)) {
200
+ lines.push(`Selection: lines ${sel.startLine}-${sel.endLine}`);
201
+ }
202
+ // Other open tabs: identity only. The agent reads any of them with read_file.
203
+ const others = [];
204
+ const seen = new Set([`${at.repository}:${at.path}`]);
205
+ const meta = new Map((state.openDocuments ?? []).map((d) => [path.resolve(d.absPath), d]));
206
+ for (const abs of state.openFiles ?? []) {
207
+ const o = locate(abs, resolve);
208
+ if (!o || seen.has(`${o.repository}:${o.path}`))
209
+ continue;
210
+ seen.add(`${o.repository}:${o.path}`);
211
+ others.push(`${o.repository === at.repository ? o.path : `${o.repository}:${o.path}`}${meta.get(path.resolve(abs))?.dirty ? " (unsaved edits)" : ""}`);
212
+ }
213
+ if (others.length)
214
+ lines.push(`Other open files: ${others.slice(0, MAX_HINT_OPEN_FILES).join(", ")}${others.length > MAX_HINT_OPEN_FILES ? ` (+${others.length - MAX_HINT_OPEN_FILES} more)` : ""}`);
215
+ return lines.join("\n");
216
+ }
217
+ const MAX_HINT_OPEN_FILES = 10;
218
+ const MAX_ATTACHMENTS = 20;
219
+ const MAX_ATTACHED_DIAGNOSTICS = 30;
220
+ /** The attached context as one bounded, clearly labelled block, or null when none. */
221
+ export function attachmentsHint(attachments) {
222
+ if (!attachments.length)
223
+ return null;
224
+ const where = (a) => `${a.repository}:${a.path}`;
225
+ const out = ["[ATTACHED CONTEXT] (chosen by the user in the editor; read files with read_file before relying on them)"];
226
+ for (const a of attachments.slice(0, MAX_ATTACHMENTS)) {
227
+ switch (a.kind) {
228
+ case "file":
229
+ out.push(`- File: ${where(a)}`);
230
+ break;
231
+ case "folder":
232
+ out.push(`- Folder: ${where(a)}/`);
233
+ break;
234
+ case "open_files":
235
+ out.push(`- Open files: ${a.files.map((f) => `${where(f)}${f.dirty ? " (unsaved edits)" : ""}`).join(", ") || "none"}`);
236
+ break;
237
+ case "diagnostics": {
238
+ out.push(`- Diagnostics for ${where(a)}: ${a.items.length ? "" : "none reported"}`);
239
+ for (const d of a.items.slice(0, MAX_ATTACHED_DIAGNOSTICS)) {
240
+ out.push(` - line ${d.line}${d.column ? `:${d.column}` : ""} ${d.severity}${d.source ? ` [${d.source}${d.code ? ` ${d.code}` : ""}]` : ""}: ${d.message.split("\n")[0].slice(0, 300)}`);
241
+ }
242
+ if (a.truncated || a.items.length > MAX_ATTACHED_DIAGNOSTICS)
243
+ out.push(" - … more not shown");
244
+ break;
245
+ }
246
+ case "selection": {
247
+ const cols = a.startColumn ? ` (columns ${a.startColumn}-${a.endColumn ?? "?"})` : "";
248
+ out.push(`- Selection: ${where(a)} lines ${a.startLine}-${a.endLine}${cols}`);
249
+ if (a.stale)
250
+ out.push(" The file changed since this was selected; read the lines again with read_file.");
251
+ else if (a.text)
252
+ out.push(` Selected text (editor buffer${a.language ? `, ${a.language}` : ""}):`, " ```", ...a.text.split("\n").map((l) => ` ${l}`), " ```");
253
+ break;
254
+ }
255
+ }
256
+ }
257
+ if (attachments.length > MAX_ATTACHMENTS)
258
+ out.push(`- … ${attachments.length - MAX_ATTACHMENTS} more attachments not included`);
259
+ return out.join("\n");
260
+ }
261
+ function ok(result) {
262
+ return { ok: true, result };
263
+ }
264
+ /** Do not echo editor text or absolute paths in a denial sent to the backend. */
265
+ function selectionDenied(code) {
266
+ return { ok: false, error: { code, message: "Selection content is unavailable under the local file-access policy." } };
267
+ }
268
+ function clampBytes(text, max) {
269
+ if (Buffer.byteLength(text, "utf8") <= max)
270
+ return { text, truncated: false };
271
+ let out = text;
272
+ while (Buffer.byteLength(out, "utf8") > max)
273
+ out = out.slice(0, Math.floor(out.length * 0.9));
274
+ return { text: out + "\n… [truncated]", truncated: true };
275
+ }