@carrieros/cli 0.3.0 → 0.4.1

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 (89) hide show
  1. package/README.md +89 -15
  2. package/dist/commands/chat.js +6 -6
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +34 -14
  5. package/dist/commands/logout.js +2 -0
  6. package/dist/commands/permissions.js +78 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +83 -10
  10. package/dist/commands/update.js +177 -51
  11. package/dist/commands/usage.js +10 -8
  12. package/dist/commands/version.js +1 -3
  13. package/dist/commands/whoami.js +12 -9
  14. package/dist/ide/editor-context.js +115 -12
  15. package/dist/ide/ide-session.js +288 -18
  16. package/dist/ide/tool-host.js +6 -6
  17. package/dist/main.js +10 -1
  18. package/dist/services/api.js +183 -15
  19. package/dist/services/auth-origin.js +20 -0
  20. package/dist/services/auto-update.js +221 -0
  21. package/dist/services/chat-stream.js +26 -3
  22. package/dist/services/checkpoints.js +176 -14
  23. package/dist/services/client-tools.js +123 -27
  24. package/dist/services/code-intel.js +243 -0
  25. package/dist/services/code-symbols.js +94 -0
  26. package/dist/services/coding-workflow.js +554 -0
  27. package/dist/services/command-coordinator.js +85 -12
  28. package/dist/services/command-policy.js +34 -4
  29. package/dist/services/config.js +96 -11
  30. package/dist/services/container-runner.js +254 -0
  31. package/dist/services/container-supervisor.js +38 -0
  32. package/dist/services/context.js +98 -25
  33. package/dist/services/device-auth.js +33 -6
  34. package/dist/services/execution-platform.js +30 -0
  35. package/dist/services/file-resolver.js +1 -1
  36. package/dist/services/folder-key.js +22 -0
  37. package/dist/services/git-tools.js +181 -0
  38. package/dist/services/helper-bin.js +56 -35
  39. package/dist/services/instruction-resolver.js +54 -0
  40. package/dist/services/job-helper.js +31 -10
  41. package/dist/services/local-files.js +148 -26
  42. package/dist/services/local-tools.js +540 -35
  43. package/dist/services/login-flow.js +44 -13
  44. package/dist/services/meta.js +27 -0
  45. package/dist/services/mutation-coordinator.js +186 -20
  46. package/dist/services/mutation-groups.js +309 -0
  47. package/dist/services/mutation-recovery.js +159 -0
  48. package/dist/services/mutations.js +264 -78
  49. package/dist/services/packaged-update.js +403 -0
  50. package/dist/services/packaged.js +15 -0
  51. package/dist/services/permission-mode.js +78 -0
  52. package/dist/services/process-runner.js +7 -1
  53. package/dist/services/project-context.js +4 -4
  54. package/dist/services/result-reconciliation.js +49 -0
  55. package/dist/services/secure-store.js +21 -1
  56. package/dist/services/session-resolver.js +7 -0
  57. package/dist/services/supported-runtime.js +59 -0
  58. package/dist/services/task-context.js +212 -0
  59. package/dist/services/task-snapshot.js +38 -0
  60. package/dist/services/tool-result-outbox.js +195 -0
  61. package/dist/services/update.js +457 -13
  62. package/dist/services/workspace-registry.js +4 -3
  63. package/dist/services/workspace.js +8 -1
  64. package/dist/shell/shell-chat.js +320 -34
  65. package/dist/shell/shell-commands.js +47 -5
  66. package/dist/shell/shell-prompt.js +21 -11
  67. package/dist/shell/shell-renderer.js +1 -1
  68. package/dist/shell/shell.js +107 -20
  69. package/dist/shell/task-context-view.js +40 -0
  70. package/dist/ui/agent-cards.js +111 -0
  71. package/dist/ui/agent-presentation.js +131 -0
  72. package/dist/ui/approval.js +46 -16
  73. package/dist/ui/banner.js +31 -87
  74. package/dist/ui/change-review.js +293 -46
  75. package/dist/ui/chat-renderer.js +6 -6
  76. package/dist/ui/colors.js +9 -9
  77. package/dist/ui/command-details.js +11 -0
  78. package/dist/ui/command-palette.js +27 -10
  79. package/dist/ui/command-registry.js +11 -4
  80. package/dist/ui/command-review.js +77 -28
  81. package/dist/ui/composer-layout.js +26 -20
  82. package/dist/ui/conversation.js +77 -25
  83. package/dist/ui/live.js +1 -1
  84. package/dist/ui/screen.js +19 -11
  85. package/dist/ui/select.js +6 -0
  86. package/dist/ui/task-context-card.js +99 -0
  87. package/dist/ui/trust.js +7 -12
  88. package/dist/ui/ui.js +23 -0
  89. package/package.json +9 -5
@@ -1,3 +1,4 @@
1
+ import { folderKey } from "./folder-key.js";
1
2
  import crypto from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
@@ -25,30 +26,102 @@ export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("h
25
26
  * and an undo can prove it is reading the right one.
26
27
  */
27
28
  export function repositoryKey(root) {
28
- const key = process.platform === "win32" ? path.resolve(root).toLowerCase() : path.resolve(root);
29
- return sha256(key).slice(0, 16);
29
+ // Canonical (real path, case-folded on Windows): a repository opened through a
30
+ // symlink must find the same evidence its changes wrote. Unchanged for any
31
+ // root whose resolved path is already its real path.
32
+ return sha256(folderKey(root)).slice(0, 16);
30
33
  }
31
34
  /** One directory per repository root, keyed by a hash of its normalized path. */
32
- function workspaceDir(root) {
35
+ export function workspaceDir(root) {
33
36
  const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
34
37
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
35
38
  return dir;
36
39
  }
37
40
  const journalFile = (root) => path.join(workspaceDir(root), "journal.json");
41
+ export class RecoveryStateError extends Error {
42
+ constructor(message = "Recovery state is unreadable or inconsistent. Existing evidence was preserved.") {
43
+ super(message);
44
+ this.name = "RecoveryStateError";
45
+ }
46
+ }
47
+ /** Waits between rename attempts while a Windows scanner or editor holds the target. */
48
+ export const RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80];
49
+ const LOCKED = new Set(["EPERM", "EBUSY", "EACCES"]);
50
+ /**
51
+ * renameSync that tolerates a transient Windows sharing lock (antivirus, the
52
+ * search indexer, an editor): EPERM/EBUSY/EACCES are retried a bounded number
53
+ * of times with a short backoff — on Windows only, where those codes mean a
54
+ * lock rather than a permission. Cancellation stops the retries. When they run
55
+ * out, the ORIGINAL error is thrown, so callers fail exactly as before.
56
+ */
57
+ export function renameWithRetry(from, to, opts = {}) {
58
+ const rename = opts.rename ?? fs.renameSync;
59
+ const wait = opts.wait ?? ((ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms));
60
+ const retries = (opts.platform ?? process.platform) === "win32" ? RENAME_RETRY_DELAYS_MS : [];
61
+ for (let attempt = 0;; attempt++) {
62
+ try {
63
+ rename(from, to);
64
+ return;
65
+ }
66
+ catch (err) {
67
+ const code = err.code ?? "";
68
+ if (!LOCKED.has(code) || attempt >= retries.length || opts.signal?.aborted)
69
+ throw err;
70
+ wait(retries[attempt]);
71
+ }
72
+ }
73
+ }
74
+ /** Atomic publication with file fsync; directory fsync where supported. */
75
+ export function durableWrite(file, data) {
76
+ const tmp = `${file}.${crypto.randomBytes(8).toString("hex")}.tmp`;
77
+ try {
78
+ const fd = fs.openSync(tmp, "wx", 0o600);
79
+ try {
80
+ fs.writeFileSync(fd, data);
81
+ fs.fsyncSync(fd);
82
+ }
83
+ finally {
84
+ fs.closeSync(fd);
85
+ }
86
+ renameWithRetry(tmp, file);
87
+ if (process.platform !== "win32") {
88
+ const dir = fs.openSync(path.dirname(file), "r");
89
+ try {
90
+ fs.fsyncSync(dir);
91
+ }
92
+ finally {
93
+ fs.closeSync(dir);
94
+ }
95
+ }
96
+ }
97
+ finally {
98
+ try {
99
+ fs.unlinkSync(tmp);
100
+ }
101
+ catch { /* absent after publication */ }
102
+ }
103
+ }
38
104
  export function readJournal(root) {
39
105
  try {
40
- const parsed = JSON.parse(fs.readFileSync(journalFile(root), "utf8"));
41
- return Array.isArray(parsed) ? parsed : [];
106
+ const file = journalFile(root);
107
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 2 * 1024 * 1024)
108
+ throw new RecoveryStateError();
109
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
110
+ if (!Array.isArray(parsed) || parsed.some(e => !e || typeof e.operation_id !== "string" ||
111
+ typeof e.path !== "string" || typeof e.checkpoint_id !== "string" ||
112
+ !["EXECUTED", "ROLLED_BACK", "FAILED"].includes(e.status)) ||
113
+ new Set(parsed.map(e => e.operation_id)).size !== parsed.length)
114
+ throw new RecoveryStateError();
115
+ return parsed;
42
116
  }
43
- catch {
44
- return [];
117
+ catch (err) {
118
+ if (err.code === "ENOENT")
119
+ return [];
120
+ throw new RecoveryStateError("Mutation journal is unreadable. It was preserved; history cannot be replaced or assumed empty.");
45
121
  }
46
122
  }
47
123
  function writeJournal(root, entries) {
48
- const file = journalFile(root);
49
- const tmp = `${file}.${process.pid}.tmp`;
50
- fs.writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 0o600 });
51
- fs.renameSync(tmp, file);
124
+ durableWrite(journalFile(root), JSON.stringify(entries, null, 2));
52
125
  }
53
126
  export function newCheckpointId() {
54
127
  return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
@@ -58,16 +131,100 @@ export function saveCheckpoint(root, checkpointId, original) {
58
131
  if (original === null)
59
132
  return; // nothing existed — undo means delete
60
133
  const file = path.join(workspaceDir(root), `${checkpointId}.before`);
61
- fs.writeFileSync(file, original, { mode: 0o600 });
134
+ durableWrite(file, original);
62
135
  }
63
136
  export function loadCheckpoint(root, checkpointId) {
64
137
  try {
65
- return fs.readFileSync(path.join(workspaceDir(root), `${checkpointId}.before`));
138
+ if (!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(checkpointId))
139
+ return null;
140
+ const file = path.join(workspaceDir(root), `${checkpointId}.before`);
141
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 1024 * 1024)
142
+ return null;
143
+ return fs.readFileSync(file);
66
144
  }
67
145
  catch {
68
146
  return null;
69
147
  }
70
148
  }
149
+ export function saveRecoveryReceipt(root, checkpointId, metadata) {
150
+ const file = path.join(workspaceDir(root), `${checkpointId}.recovery.json`);
151
+ if (fs.existsSync(file))
152
+ throw new RecoveryStateError();
153
+ durableWrite(file, JSON.stringify({ ...metadata, checkpoint_id: checkpointId, repository_key: repositoryKey(root) }));
154
+ }
155
+ export const MAX_RECOVERY_SCAN = 100;
156
+ export function recoveryReceipts(root) {
157
+ const receipts = [];
158
+ let problems = 0;
159
+ const dir = workspaceDir(root);
160
+ const names = [];
161
+ // Bound directory traversal, not only the number of parsed JSON records.
162
+ let visited = 0, bounded = false;
163
+ const directory = fs.opendirSync(dir);
164
+ try {
165
+ let entry;
166
+ while ((entry = directory.readSync()) !== null) {
167
+ if (++visited > MAX_RECOVERY_SCAN * 4) {
168
+ bounded = true;
169
+ break;
170
+ }
171
+ if (entry.name.endsWith(".recovery.json"))
172
+ names.push(entry.name);
173
+ }
174
+ }
175
+ finally {
176
+ directory.closeSync();
177
+ }
178
+ if (names.length > MAX_RECOVERY_SCAN)
179
+ bounded = true;
180
+ for (const name of names.slice(0, MAX_RECOVERY_SCAN)) {
181
+ try {
182
+ const file = path.join(dir, name);
183
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 64 * 1024)
184
+ throw new RecoveryStateError();
185
+ const r = JSON.parse(fs.readFileSync(file, "utf8"));
186
+ const hashValid = (exists, hash) => typeof exists === "boolean" &&
187
+ (exists ? typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash) : hash === null);
188
+ if ((r.group_id !== undefined && !/^grp_[a-f0-9]{32}$/.test(r.group_id)) ||
189
+ r.version !== 2 || r.approved !== true || r.repository_key !== repositoryKey(root) ||
190
+ typeof r.operation_id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(r.operation_id) || typeof r.repository_id !== "string" ||
191
+ typeof r.repository_name !== "string" || typeof r.path !== "string" ||
192
+ !/^cp_[a-z0-9]+_[a-f0-9]+$/.test(r.checkpoint_id) || name !== `${r.checkpoint_id}.recovery.json` ||
193
+ !["create_file", "write_file", "edit_file", "delete_file", "revert_change"].includes(r.action) ||
194
+ !["prepared", "applied", "verified", "rolled_back", "unresolved"].includes(r.phase) ||
195
+ !["none", "ready", "queued", "acknowledged", "rejected"].includes(r.delivery) ||
196
+ typeof r.journal_persisted !== "boolean" || !Number.isFinite(Date.parse(r.created_at)) ||
197
+ !hashValid(r.before_exists, r.before_sha) || !hashValid(r.after_exists, r.after_sha) ||
198
+ (r.scope !== undefined && !/^[a-f0-9]{64}$/.test(r.scope)) ||
199
+ (r.result && (r.result.tool_call_id !== r.operation_id || typeof r.result.ok !== "boolean")) ||
200
+ (r.delivery !== "none" && !r.result))
201
+ throw new RecoveryStateError();
202
+ receipts.push(r);
203
+ }
204
+ catch {
205
+ problems++;
206
+ } // No content, malformed paths or credentials in diagnostics.
207
+ }
208
+ const counts = new Map();
209
+ for (const r of receipts)
210
+ counts.set(r.operation_id, (counts.get(r.operation_id) ?? 0) + 1);
211
+ return { receipts: receipts.filter(r => {
212
+ if (counts.get(r.operation_id) > 1) {
213
+ problems++;
214
+ return false;
215
+ }
216
+ return true;
217
+ }), problems, bounded };
218
+ }
219
+ export function updateRecoveryReceipt(root, checkpointId, patch) {
220
+ const scan = recoveryReceipts(root);
221
+ const r = scan.receipts.find(e => e.checkpoint_id === checkpointId);
222
+ if (!r)
223
+ throw new RecoveryStateError();
224
+ if (r.result && patch.result && JSON.stringify(r.result) !== JSON.stringify(patch.result))
225
+ throw new RecoveryStateError();
226
+ durableWrite(path.join(workspaceDir(root), `${checkpointId}.recovery.json`), JSON.stringify({ ...r, ...patch }));
227
+ }
71
228
  /** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
72
229
  export function appendEntry(root, entry) {
73
230
  const entries = [...readJournal(root), entry];
@@ -75,7 +232,12 @@ export function appendEntry(root, entry) {
75
232
  writeJournal(root, entries);
76
233
  for (const d of dropped) {
77
234
  try {
78
- fs.unlinkSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`));
235
+ const receipt = recoveryReceipts(root).receipts.find(r => r.checkpoint_id === d.checkpoint_id);
236
+ if (!receipt || receipt.group_id || !receipt.journal_persisted || !["verified", "rolled_back"].includes(receipt.phase) ||
237
+ (receipt.scope && !["acknowledged", "rejected"].includes(receipt.delivery)))
238
+ continue;
239
+ fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`), { force: true });
240
+ fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.recovery.json`), { force: true });
79
241
  }
80
242
  catch {
81
243
  /* already gone */
@@ -1,8 +1,13 @@
1
1
  import { LOCAL_TOOL_NAMES, executeLocalTool } from "./local-tools.js";
2
+ import { activeRepository, resolveRepository } from "./workspace-registry.js";
3
+ import { ToolDeliveryError, terminalToolRejection } from "./tool-result-outbox.js";
4
+ import { errorLine } from "./output.js";
2
5
  import { workspaceRoot } from "./local-files.js";
3
6
  import { MUTATION_TOOL_NAMES } from "./mutations.js";
4
7
  import { inScreen } from "../ui/screen-prompt.js";
5
8
  import { isTrusted } from "../ui/trust.js";
9
+ import { executionAdapter, executionPlatform } from "./execution-platform.js";
10
+ import { containerRuntime } from "./container-runner.js";
6
11
  /**
7
12
  * The CLI end of a delegated tool call: receive → execute locally → answer.
8
13
  *
@@ -58,36 +63,46 @@ export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
58
63
  * Should this turn offer run_command?
59
64
  *
60
65
  * Everything file changes require — the interactive screen and a trusted
61
- * folder — plus containment this platform can provide (Windows Job Objects),
62
- * plus an explicit opt-in. Commands run project code with the user's
63
- * permissions, and the CLI's own credentials are still readable by that code,
64
- * so nothing offers them by default until that is resolved.
66
+ * folder — plus a configured platform containment adapter,
67
+ * plus an explicit opt-in. In Auto mode that opt-in is the mode selection
68
+ * itself; an explicit `/settings commands off` remains a hard stop. The Windows
69
+ * path still runs project code with the user's permissions.
65
70
  */
66
- export function declaredCommandTools(ctx) {
67
- const state = localCommandsState(ctx);
71
+ export function declaredCommandTools(ctx, approverPresent = inScreen(), autoMode = false) {
72
+ const state = localCommandsState(ctx, approverPresent, autoMode);
68
73
  return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
69
74
  }
70
75
  /**
71
76
  * Whether local commands are on, why, and what (if anything) stops them.
72
77
  *
73
- * ON means the user chose it: the persisted `/settings commands on`, or the
74
- * original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in, which keeps working so nobody
75
- * who relied on it has to migrate. Even when ON, the tool is only offered in
76
- * the interactive shell, on Windows (where containment exists), in a trusted
77
- * repository — the same conditions as before.
78
+ * ON means the user chose it: Auto mode, `/settings commands on`, or the
79
+ * original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in. An explicit persisted OFF is
80
+ * a hard stop. Even when ON, the tool is only offered in an interactive
81
+ * session, with platform containment and a trusted repository. Runtime health
82
+ * is checked again before execution.
78
83
  */
79
- export function localCommandsState(ctx) {
84
+ export function localCommandsState(ctx, approverPresent = inScreen(), autoMode = false) {
80
85
  const fromEnv = process.env[COMMANDS_OPT_IN_ENV] === "1";
81
- const fromSetting = ctx.config.get("localCommandsEnabled") === true;
82
- const enabled = fromEnv || fromSetting;
83
- const source = fromSetting ? "setting" : fromEnv ? "env" : null;
86
+ const localSetting = ctx.config.get("localCommandsEnabled");
87
+ const fromSetting = localSetting === true;
88
+ // Choosing Auto is itself an explicit command-execution opt-in. A persisted
89
+ // OFF is a deliberate kill switch and wins over Auto.
90
+ const enabled = localSetting !== false && (fromEnv || fromSetting || autoMode);
91
+ const source = !enabled ? null : fromSetting ? "setting" : fromEnv ? "env" : autoMode ? "auto" : null;
84
92
  let blockedBy = null;
85
93
  if (enabled) {
86
- if (process.platform !== "win32")
87
- blockedBy = "commands need Windows process containment";
88
- else if (!inScreen())
94
+ try {
95
+ if (executionAdapter(executionPlatform()) === "isolated-container")
96
+ containerRuntime();
97
+ }
98
+ catch (error) {
99
+ blockedBy = error.message;
100
+ }
101
+ // Someone must be present to approve each command: the interactive shell
102
+ // by default; the IDE passes whether a live panel can show the approval.
103
+ if (!blockedBy && !approverPresent)
89
104
  blockedBy = "only in the interactive shell";
90
- else {
105
+ else if (!blockedBy) {
91
106
  try {
92
107
  if (!isTrusted(ctx.config, workspaceRoot()))
93
108
  blockedBy = "the active repository is not trusted";
@@ -104,18 +119,35 @@ export function toolActivityLabel(call) {
104
119
  const a = (call.arguments ?? {});
105
120
  const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
106
121
  switch (call.name) {
107
- case "read_file":
108
- return `Reading ${s(a.path) ?? "a file"}`;
122
+ case "read_file": {
123
+ const from = typeof a.start_line === "number" ? a.start_line : undefined;
124
+ const to = typeof a.end_line === "number" ? a.end_line : undefined;
125
+ return `Reading ${s(a.path) ?? "a file"}${from || to ? ` lines ${from ?? 1}–${to ?? "…"}` : ""}`;
126
+ }
109
127
  case "search_files":
110
- return `Searching ${s(a.glob) ?? "the project"} for "${s(a.query) ?? ""}"`;
128
+ return `Searching ${s(a.path) ?? s(a.glob) ?? (s(a.type) ? `${s(a.type)} files` : "the project")} for ${a.regex === true ? "/" + (s(a.query) ?? "") + "/" : `"${s(a.query) ?? ""}"`}`.slice(0, 120);
129
+ case "find_files":
130
+ return `Finding ${s(a.pattern) ?? "files"}`;
111
131
  case "list_files":
112
132
  return s(a.glob) ? `Finding ${s(a.glob)}` : `Listing ${s(a.path) ?? "project files"}`;
113
133
  case "resolve_local_file":
114
134
  return `Resolving ${s(a.reference) ?? "a file"}`;
135
+ case "code_outline":
136
+ return `Outlining ${s(a.path) ?? "a file"}`;
137
+ case "find_symbol":
138
+ return `Finding the definition of ${s(a.name) ?? "a symbol"}`.slice(0, 120);
139
+ case "find_references":
140
+ return (s(a.name)?.startsWith("/") ? `Finding the route and callers of ${s(a.name)}` : `Finding usages of ${s(a.name) ?? "a symbol"}`).slice(0, 120);
115
141
  case "git_status":
116
142
  return `Checking git status${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
117
143
  case "git_diff":
118
144
  return `Reviewing changes${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
145
+ case "git_log":
146
+ return `Reading history${s(a.path) ? ` of ${s(a.path)}` : ""}`;
147
+ case "git_blame":
148
+ return `Reading blame for ${s(a.path) ?? "a file"}`;
149
+ case "git_show":
150
+ return `Reading commit ${s(a.revision) ?? ""}`.trim();
119
151
  case "create_file":
120
152
  return `Proposing to create ${s(a.path) ?? "a file"}`;
121
153
  case "write_file":
@@ -133,6 +165,19 @@ export function toolActivityLabel(call) {
133
165
  return "Inspecting the project";
134
166
  }
135
167
  }
168
+ function recordDeliveredRead(cache, call, payload) {
169
+ const r = payload.result;
170
+ if (!payload.ok || !r || r.truncated !== false || r.range === true || typeof r.content !== "string" || typeof r.sha256 !== "string")
171
+ return;
172
+ try {
173
+ const selector = call.arguments?.repository;
174
+ const repo = selector ? resolveRepository(selector) : activeRepository();
175
+ cache.record(repo.id, String(r.path), r.sha256, call.tool_call_id);
176
+ }
177
+ catch {
178
+ /* an unresolvable repository is simply not cached */
179
+ }
180
+ }
136
181
  /** The codes the server documents for client tool failures. */
137
182
  function publicCode(code) {
138
183
  switch (code) {
@@ -162,6 +207,16 @@ function fitResult(result) {
162
207
  }
163
208
  return { ...result, content: "", truncated: true };
164
209
  }
210
+ const commandText = (args) => {
211
+ const a = (args ?? {});
212
+ const program = typeof a.program === "string" ? a.program : "";
213
+ const rest = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string") : [];
214
+ return program ? [program, ...rest].join(" ").slice(0, 300) : undefined;
215
+ };
216
+ const pathOf = (args) => {
217
+ const p = args?.path;
218
+ return typeof p === "string" ? p.slice(0, 300) : undefined;
219
+ };
165
220
  /**
166
221
  * Post a result, retrying once on a transport failure: the server holds the
167
222
  * call for its timeout, so a blip should not cost the turn. A 4xx is an
@@ -175,10 +230,13 @@ export async function submitWithRetry(client, payload) {
175
230
  }
176
231
  catch (err) {
177
232
  const status = err.status ?? 0;
178
- if (status >= 400 && status < 500)
179
- return;
180
- if (attempt === 1)
181
- return;
233
+ if (terminalToolRejection(err) || (status >= 400 && status < 500 && status !== 408 && status !== 429) || attempt === 1) {
234
+ const failure = err instanceof ToolDeliveryError ? err : new ToolDeliveryError(terminalToolRejection(err)
235
+ ? "The server rejected the tool result. The tool was not rerun; the conversation may not reflect its outcome."
236
+ : undefined);
237
+ errorLine(failure.message);
238
+ throw failure;
239
+ }
182
240
  await new Promise((r) => setTimeout(r, 400));
183
241
  }
184
242
  }
@@ -193,6 +251,30 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
193
251
  return; // nothing to correlate an answer with
194
252
  const label = toolActivityLabel(call);
195
253
  const started = Date.now();
254
+ if (call.name === "coding_workflow") {
255
+ let payload;
256
+ try {
257
+ if (!ui.workflow || declaredClientTools(ctx) === undefined)
258
+ throw new Error("Coding workflow is not enabled in this trusted interactive session.");
259
+ payload = { tool_call_id: id, ok: true, result: await ui.workflow.control(call) };
260
+ }
261
+ catch (error) {
262
+ payload = { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } };
263
+ const action = call.arguments?.action;
264
+ ui.onRefused?.({ proposal: action === "plan" ? "plan" : "workflow", ...(typeof action === "string" ? { target: action } : {}),
265
+ code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
266
+ }
267
+ try {
268
+ await submitWithRetry(client, payload);
269
+ if (payload.ok)
270
+ ui.workflow?.confirmControl(id);
271
+ }
272
+ catch (error) {
273
+ ui.workflow?.interrupt();
274
+ throw error;
275
+ }
276
+ return;
277
+ }
196
278
  // A proposed command goes to the command coordinator — never anywhere else,
197
279
  // and never at all unless this turn offered commands.
198
280
  if (call.name === "run_command" || call.kind === "command") {
@@ -203,8 +285,17 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
203
285
  error: { code: "COMMAND_NOT_ENABLED", message: "Local commands are not enabled in this session. Nothing ran." },
204
286
  duration_ms: 0
205
287
  });
288
+ ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "COMMAND_NOT_ENABLED", reason: "Local commands are not enabled in this session. Nothing ran." });
206
289
  }
207
290
  else {
291
+ try {
292
+ ui.workflow?.beforeCommand(call);
293
+ }
294
+ catch (error) {
295
+ await submitWithRetry(client, { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } });
296
+ ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
297
+ return;
298
+ }
208
299
  await ui.commands.handle(call);
209
300
  }
210
301
  return;
@@ -219,6 +310,7 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
219
310
  error: { code: "MUTATION_NOT_ENABLED", message: "File changes are not enabled in this session. Nothing was changed." },
220
311
  duration_ms: 0
221
312
  });
313
+ ui.onRefused?.({ proposal: "change", target: pathOf(call.arguments), code: "MUTATION_NOT_ENABLED", reason: "File changes are not enabled in this session. Nothing was changed." });
222
314
  }
223
315
  else {
224
316
  await ui.mutations.handle(call);
@@ -245,7 +337,7 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
245
337
  else {
246
338
  // The executor re-validates everything — name, arguments, containment,
247
339
  // ignore rules, size — regardless of what the server already checked.
248
- const res = executeLocalTool({ id, name: call.name, arguments: call.arguments });
340
+ const res = executeLocalTool({ id, name: call.name, arguments: call.arguments }, { readCache: ui.readCache });
249
341
  payload = res.ok
250
342
  ? { tool_call_id: id, ok: true, result: fitResult(res.result) }
251
343
  : {
@@ -256,5 +348,9 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
256
348
  }
257
349
  payload.duration_ms = Date.now() - started;
258
350
  await submitWithRetry(client, payload);
351
+ // Only bytes that were actually posted, untrimmed, count as delivered.
352
+ if (ui.readCache && call.name === "read_file")
353
+ recordDeliveredRead(ui.readCache, call, payload);
354
+ ui.workflow?.observeRead(call, payload);
259
355
  ui.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
260
356
  }