@carrieros/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,145 @@
1
+ /** Thrown for every way a stream can end other than `complete`. */
2
+ export class StreamError extends Error {
3
+ code;
4
+ status;
5
+ constructor(code, message, status = 0) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ this.name = "StreamError";
10
+ }
11
+ }
12
+ /** Map the server's `complete` payload onto the synchronous endpoint's shape. */
13
+ export function completeToResult(d) {
14
+ return {
15
+ id: d.message_id ?? null,
16
+ response: typeof d.content === "string" ? d.content : "",
17
+ session_id: d.session_id,
18
+ tokens_used: Number(d.tokens_used ?? 0) || 0,
19
+ cost_usd: typeof d.cost_usd === "number" ? d.cost_usd : undefined,
20
+ credits_remaining: typeof d.credits_remaining === "number" ? d.credits_remaining : null,
21
+ credits_unlimited: typeof d.credits_unlimited === "boolean" ? d.credits_unlimited : null,
22
+ credits_spent: typeof d.credits_spent === "number" ? d.credits_spent : null,
23
+ sources: Array.isArray(d.sources) ? d.sources : [],
24
+ web_search_used: d.web_search_used === true,
25
+ high_power_used: d.high_power_used === true,
26
+ speed: d.speed === "fast" ? "fast" : d.speed === "standard" ? "standard" : undefined,
27
+ model: typeof d.model === "string" ? d.model : undefined
28
+ };
29
+ }
30
+ /**
31
+ * Consume an SSE body until `complete`, `error`, `interrupted` or the socket
32
+ * ends. Frames are `data: {"type":…,"data":…}` separated by a blank line;
33
+ * `: ping` comments and the `[DONE]` sentinel carry nothing.
34
+ */
35
+ export function consumeChatStream(body, handlers = {}, signal) {
36
+ return new Promise((resolve, reject) => {
37
+ let buffer = "";
38
+ let settled = false;
39
+ const finish = (fn) => {
40
+ if (settled)
41
+ return;
42
+ settled = true;
43
+ signal?.removeEventListener?.("abort", onAbort);
44
+ fn();
45
+ };
46
+ function onAbort() {
47
+ finish(() => reject(new StreamError("ABORTED", "Interrupted.")));
48
+ try {
49
+ body.destroy?.();
50
+ }
51
+ catch {
52
+ /* already closed */
53
+ }
54
+ }
55
+ if (signal?.aborted) {
56
+ onAbort();
57
+ return;
58
+ }
59
+ signal?.addEventListener?.("abort", onAbort, { once: true });
60
+ const dispatch = (type, data) => {
61
+ switch (type) {
62
+ case "message_created":
63
+ handlers.onMessageCreated?.(data);
64
+ return;
65
+ case "chunk":
66
+ if (typeof data.delta === "string" && data.delta)
67
+ handlers.onDelta?.(data.delta);
68
+ return;
69
+ case "status":
70
+ case "tool_status":
71
+ if (typeof data.message === "string")
72
+ handlers.onStatus?.(type, data.message);
73
+ return;
74
+ case "client_tool_call": {
75
+ if (!handlers.onClientToolCall)
76
+ return;
77
+ // Never let a tool handler's failure — or its duration — stall the
78
+ // parser: the server keeps streaming while it waits for the result.
79
+ void Promise.resolve()
80
+ .then(() => handlers.onClientToolCall(data))
81
+ .catch(() => undefined);
82
+ return;
83
+ }
84
+ case "complete":
85
+ finish(() => resolve(completeToResult(data)));
86
+ return;
87
+ case "interrupted":
88
+ finish(() => reject(signal?.aborted
89
+ ? new StreamError("ABORTED", "Interrupted.")
90
+ : new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
91
+ return;
92
+ case "error":
93
+ finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.")));
94
+ return;
95
+ default:
96
+ return; // generation_type and anything newer: nothing to do
97
+ }
98
+ };
99
+ const drain = () => {
100
+ buffer = buffer.replace(/\r\n/g, "\n");
101
+ let sep = buffer.indexOf("\n\n");
102
+ while (sep !== -1) {
103
+ const block = buffer.slice(0, sep);
104
+ buffer = buffer.slice(sep + 2);
105
+ const payload = block
106
+ .split("\n")
107
+ .filter((l) => l.startsWith("data:"))
108
+ .map((l) => l.slice(5).replace(/^ /, ""))
109
+ .join("\n");
110
+ if (payload && payload !== "[DONE]") {
111
+ try {
112
+ const frame = JSON.parse(payload);
113
+ if (frame?.type)
114
+ dispatch(frame.type, frame.data ?? {});
115
+ }
116
+ catch {
117
+ /* a malformed frame is skipped, never fatal */
118
+ }
119
+ }
120
+ if (settled)
121
+ return;
122
+ sep = buffer.indexOf("\n\n");
123
+ }
124
+ };
125
+ body.setEncoding?.("utf8");
126
+ body.on("data", (chunk) => {
127
+ if (settled)
128
+ return;
129
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
130
+ drain();
131
+ });
132
+ body.on("end", () => {
133
+ if (settled)
134
+ return;
135
+ buffer += "\n\n";
136
+ drain();
137
+ finish(() => reject(new StreamError("STREAM_ENDED", "The connection closed before the response finished.")));
138
+ });
139
+ body.on("error", () => {
140
+ finish(() => reject(signal?.aborted
141
+ ? new StreamError("ABORTED", "Interrupted.")
142
+ : new StreamError("NETWORK_ERROR", "The connection to the API dropped mid-response.")));
143
+ });
144
+ });
145
+ }
@@ -0,0 +1,116 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { ConfigStore } from "./config.js";
5
+ /**
6
+ * Checkpoints and the change journal for supervised file edits.
7
+ *
8
+ * Kept in the CLI's own app-data folder, per workspace — never inside the
9
+ * repository. A change can be undone whether or not the file was ever committed,
10
+ * nothing ends up in `git status`, and Git is not a dependency of the safety
11
+ * net. This is not a version-control system: it keeps enough to restore the
12
+ * last few approved changes, and prunes the rest.
13
+ *
14
+ * What a checkpoint holds is the ORIGINAL bytes of one file, plus whether it
15
+ * existed and its mode. That is the only file content the CLI ever retains, it
16
+ * stays on the machine, and credential files never get one because they are
17
+ * refused before a change is planned.
18
+ */
19
+ /** Changes remembered per workspace; older checkpoints are deleted. */
20
+ const MAX_ENTRIES = 50;
21
+ export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
22
+ /**
23
+ * The identity of a repository's checkpoint store: a hash of its normalized
24
+ * root. Exported so a journal entry can record which store it was written to,
25
+ * and an undo can prove it is reading the right one.
26
+ */
27
+ export function repositoryKey(root) {
28
+ const key = process.platform === "win32" ? path.resolve(root).toLowerCase() : path.resolve(root);
29
+ return sha256(key).slice(0, 16);
30
+ }
31
+ /** One directory per repository root, keyed by a hash of its normalized path. */
32
+ function workspaceDir(root) {
33
+ const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
34
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
35
+ return dir;
36
+ }
37
+ const journalFile = (root) => path.join(workspaceDir(root), "journal.json");
38
+ export function readJournal(root) {
39
+ try {
40
+ const parsed = JSON.parse(fs.readFileSync(journalFile(root), "utf8"));
41
+ return Array.isArray(parsed) ? parsed : [];
42
+ }
43
+ catch {
44
+ return [];
45
+ }
46
+ }
47
+ 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);
52
+ }
53
+ export function newCheckpointId() {
54
+ return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
55
+ }
56
+ /** Save a file's original bytes before it is changed. */
57
+ export function saveCheckpoint(root, checkpointId, original) {
58
+ if (original === null)
59
+ return; // nothing existed — undo means delete
60
+ const file = path.join(workspaceDir(root), `${checkpointId}.before`);
61
+ fs.writeFileSync(file, original, { mode: 0o600 });
62
+ }
63
+ export function loadCheckpoint(root, checkpointId) {
64
+ try {
65
+ return fs.readFileSync(path.join(workspaceDir(root), `${checkpointId}.before`));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ /** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
72
+ export function appendEntry(root, entry) {
73
+ const entries = [...readJournal(root), entry];
74
+ const dropped = entries.length > MAX_ENTRIES ? entries.splice(0, entries.length - MAX_ENTRIES) : [];
75
+ writeJournal(root, entries);
76
+ for (const d of dropped) {
77
+ try {
78
+ fs.unlinkSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`));
79
+ }
80
+ catch {
81
+ /* already gone */
82
+ }
83
+ }
84
+ }
85
+ export function updateEntry(root, operationId, patch) {
86
+ const entries = readJournal(root);
87
+ const i = entries.findIndex((e) => e.operation_id === operationId);
88
+ if (i === -1)
89
+ return;
90
+ entries[i] = { ...entries[i], ...patch };
91
+ writeJournal(root, entries);
92
+ }
93
+ /**
94
+ * The change `/undo` (or `revert_change` without an id) should undo: the most
95
+ * recent applied change that has not already been undone. Reverts are skipped,
96
+ * so undoing twice walks back two changes rather than toggling one.
97
+ */
98
+ export function latestRevertible(root, operationId, repositoryId) {
99
+ const key = repositoryKey(root);
100
+ // An entry has to belong to THIS repository's store. Entries written before
101
+ // repository identity existed carry neither field and are accepted on the
102
+ // strength of the directory they were found in; anything that names a
103
+ // different repository is refused rather than restored.
104
+ const mine = (e) => (e.repository_key === undefined || e.repository_key === key) &&
105
+ (repositoryId === undefined || e.repository_id === undefined || e.repository_id === repositoryId);
106
+ const entries = readJournal(root).filter(mine);
107
+ if (operationId) {
108
+ return entries.find((e) => e.operation_id === operationId && e.status === "EXECUTED" && !e.reverts) ?? null;
109
+ }
110
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
111
+ const e = entries[i];
112
+ if (e.status === "EXECUTED" && !e.reverts)
113
+ return e;
114
+ }
115
+ return null;
116
+ }
@@ -0,0 +1,260 @@
1
+ import { LOCAL_TOOL_NAMES, executeLocalTool } from "./local-tools.js";
2
+ import { workspaceRoot } from "./local-files.js";
3
+ import { MUTATION_TOOL_NAMES } from "./mutations.js";
4
+ import { inScreen } from "../ui/screen-prompt.js";
5
+ import { isTrusted } from "../ui/trust.js";
6
+ /**
7
+ * The CLI end of a delegated tool call: receive → execute locally → answer.
8
+ *
9
+ * There is no loop here and there must never be one. The server's agent loop
10
+ * decides what it needs; this runs exactly the call it was sent, through the
11
+ * same executor and the same containment checks as everything else local, and
12
+ * posts the outcome back. If this code ever starts deciding what to read next,
13
+ * it has become a second agent.
14
+ */
15
+ /** Largest serialized result we will post — under the server's per-tool cap. */
16
+ const MAX_POST_BYTES = 380 * 1024;
17
+ /**
18
+ * Should this turn offer local tools at all?
19
+ *
20
+ * Only in a trusted workspace. Trust is the existing "may Carrier OS read this
21
+ * folder" consent, scoped to the workspace ROOT because that is what the tools
22
+ * reach. Asked for at startup in the shell; never prompted for mid-turn, where a
23
+ * dialog would fight the stream for the terminal. Non-interactive runs follow
24
+ * trust.ts's existing rule: there is nobody to ask, so the check does not apply.
25
+ */
26
+ export function declaredClientTools(ctx) {
27
+ try {
28
+ const trusted = !process.stdin.isTTY || isTrusted(ctx.config, workspaceRoot());
29
+ return trusted ? [...LOCAL_TOOL_NAMES] : undefined;
30
+ }
31
+ catch {
32
+ return undefined; // no usable workspace — plain chat, no local tools
33
+ }
34
+ }
35
+ /**
36
+ * Should this turn offer file-changing tools?
37
+ *
38
+ * Folder trust is necessary but NOT sufficient: trust means "may read", and it
39
+ * is never taken as consent to write. What makes a change possible is a person
40
+ * approving that specific change, so these are offered only where one can be
41
+ * asked — the interactive shell's screen. Piped, scripted and `cos chat` runs
42
+ * never get them, and there is no flag to change that.
43
+ */
44
+ export function declaredMutationTools(ctx) {
45
+ if (!inScreen())
46
+ return undefined;
47
+ try {
48
+ return isTrusted(ctx.config, workspaceRoot()) ? [...MUTATION_TOOL_NAMES] : undefined;
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ const isMutationName = (name) => MUTATION_TOOL_NAMES.includes(name);
55
+ /** Opt-in switch for local commands while their release blockers are open. */
56
+ export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
57
+ /**
58
+ * Should this turn offer run_command?
59
+ *
60
+ * 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.
65
+ */
66
+ export function declaredCommandTools(ctx) {
67
+ const state = localCommandsState(ctx);
68
+ return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
69
+ }
70
+ /**
71
+ * Whether local commands are on, why, and what (if anything) stops them.
72
+ *
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
+ */
79
+ export function localCommandsState(ctx) {
80
+ 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;
84
+ let blockedBy = null;
85
+ if (enabled) {
86
+ if (process.platform !== "win32")
87
+ blockedBy = "commands need Windows process containment";
88
+ else if (!inScreen())
89
+ blockedBy = "only in the interactive shell";
90
+ else {
91
+ try {
92
+ if (!isTrusted(ctx.config, workspaceRoot()))
93
+ blockedBy = "the active repository is not trusted";
94
+ }
95
+ catch {
96
+ blockedBy = "the active repository could not be checked";
97
+ }
98
+ }
99
+ }
100
+ return { enabled, source, blockedBy };
101
+ }
102
+ /** A short, user-facing description of what is about to happen. */
103
+ export function toolActivityLabel(call) {
104
+ const a = (call.arguments ?? {});
105
+ const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
106
+ switch (call.name) {
107
+ case "read_file":
108
+ return `Reading ${s(a.path) ?? "a file"}`;
109
+ case "search_files":
110
+ return `Searching ${s(a.glob) ?? "the project"} for "${s(a.query) ?? ""}"`;
111
+ case "list_files":
112
+ return s(a.glob) ? `Finding ${s(a.glob)}` : `Listing ${s(a.path) ?? "project files"}`;
113
+ case "resolve_local_file":
114
+ return `Resolving ${s(a.reference) ?? "a file"}`;
115
+ case "git_status":
116
+ return `Checking git status${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
117
+ case "git_diff":
118
+ return `Reviewing changes${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
119
+ case "create_file":
120
+ return `Proposing to create ${s(a.path) ?? "a file"}`;
121
+ case "write_file":
122
+ case "edit_file":
123
+ return `Proposing a change to ${s(a.path) ?? "a file"}`;
124
+ case "delete_file":
125
+ return `Proposing to delete ${s(a.path) ?? "a file"}`;
126
+ case "revert_change":
127
+ return "Proposing to undo a change";
128
+ case "run_command": {
129
+ const list = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string").join(" ") : "";
130
+ return `Proposing to run ${s(a.program) ?? "a command"}${list ? " " + list : ""}`.slice(0, 120);
131
+ }
132
+ default:
133
+ return "Inspecting the project";
134
+ }
135
+ }
136
+ /** The codes the server documents for client tool failures. */
137
+ function publicCode(code) {
138
+ switch (code) {
139
+ case "NOT_FOUND":
140
+ return "FILE_NOT_FOUND";
141
+ case "UNKNOWN_TOOL":
142
+ return "UNKNOWN_CLIENT_TOOL";
143
+ case "INVALID_ARGUMENTS":
144
+ return "INVALID_TOOL_ARGUMENTS";
145
+ default:
146
+ return code;
147
+ }
148
+ }
149
+ /** Keep a read result under the post cap by trimming content, and say so. */
150
+ function fitResult(result) {
151
+ let size = Buffer.byteLength(JSON.stringify(result), "utf8");
152
+ if (size <= MAX_POST_BYTES || typeof result.content !== "string")
153
+ return result;
154
+ let content = result.content;
155
+ while (size > MAX_POST_BYTES && content.length > 0) {
156
+ content = content.slice(0, Math.floor(content.length * 0.75));
157
+ const trimmed = { ...result, content, truncated: true };
158
+ delete trimmed.line_count;
159
+ size = Buffer.byteLength(JSON.stringify(trimmed), "utf8");
160
+ if (size <= MAX_POST_BYTES)
161
+ return trimmed;
162
+ }
163
+ return { ...result, content: "", truncated: true };
164
+ }
165
+ /**
166
+ * Post a result, retrying once on a transport failure: the server holds the
167
+ * call for its timeout, so a blip should not cost the turn. A 4xx is an
168
+ * answer, not a blip.
169
+ */
170
+ export async function submitWithRetry(client, payload) {
171
+ for (let attempt = 0; attempt < 2; attempt += 1) {
172
+ try {
173
+ await client.submitToolResult(payload);
174
+ return;
175
+ }
176
+ catch (err) {
177
+ const status = err.status ?? 0;
178
+ if (status >= 400 && status < 500)
179
+ return;
180
+ if (attempt === 1)
181
+ return;
182
+ await new Promise((r) => setTimeout(r, 400));
183
+ }
184
+ }
185
+ }
186
+ /**
187
+ * Handle one `client_tool_call`. Never throws: every outcome, including a
188
+ * malformed request, becomes a result the server can hand back to the model.
189
+ */
190
+ export async function handleClientToolCall(ctx, client, call, ui = {}) {
191
+ const id = typeof call?.tool_call_id === "string" ? call.tool_call_id : "";
192
+ if (!id)
193
+ return; // nothing to correlate an answer with
194
+ const label = toolActivityLabel(call);
195
+ const started = Date.now();
196
+ // A proposed command goes to the command coordinator — never anywhere else,
197
+ // and never at all unless this turn offered commands.
198
+ if (call.name === "run_command" || call.kind === "command") {
199
+ if (!ui.commands || call.name !== "run_command") {
200
+ await submitWithRetry(client, {
201
+ tool_call_id: id,
202
+ ok: false,
203
+ error: { code: "COMMAND_NOT_ENABLED", message: "Local commands are not enabled in this session. Nothing ran." },
204
+ duration_ms: 0
205
+ });
206
+ }
207
+ else {
208
+ await ui.commands.handle(call);
209
+ }
210
+ return;
211
+ }
212
+ // A proposed change goes to the reviewer — never to the read executor, and
213
+ // never anywhere at all unless this turn offered changes in the first place.
214
+ if (isMutationName(call.name) || call.kind === "mutation") {
215
+ if (!ui.mutations || !isMutationName(call.name)) {
216
+ await submitWithRetry(client, {
217
+ tool_call_id: id,
218
+ ok: false,
219
+ error: { code: "MUTATION_NOT_ENABLED", message: "File changes are not enabled in this session. Nothing was changed." },
220
+ duration_ms: 0
221
+ });
222
+ }
223
+ else {
224
+ await ui.mutations.handle(call);
225
+ }
226
+ return;
227
+ }
228
+ ui.onStart?.(label, call.name);
229
+ let payload;
230
+ const trusted = declaredClientTools(ctx) !== undefined;
231
+ if (!trusted) {
232
+ payload = {
233
+ tool_call_id: id,
234
+ ok: false,
235
+ error: { code: "TOOL_NOT_TRUSTED", message: "This folder has not been trusted for Carrier OS to read." }
236
+ };
237
+ }
238
+ else if (!call.arguments || typeof call.arguments !== "object" || Array.isArray(call.arguments)) {
239
+ payload = {
240
+ tool_call_id: id,
241
+ ok: false,
242
+ error: { code: "INVALID_TOOL_ARGUMENTS", message: "Tool arguments must be an object." }
243
+ };
244
+ }
245
+ else {
246
+ // The executor re-validates everything — name, arguments, containment,
247
+ // ignore rules, size — regardless of what the server already checked.
248
+ const res = executeLocalTool({ id, name: call.name, arguments: call.arguments });
249
+ payload = res.ok
250
+ ? { tool_call_id: id, ok: true, result: fitResult(res.result) }
251
+ : {
252
+ tool_call_id: id,
253
+ ok: false,
254
+ error: { code: publicCode(res.error?.code ?? "TOOL_FAILED"), message: res.error?.message ?? "Tool failed." }
255
+ };
256
+ }
257
+ payload.duration_ms = Date.now() - started;
258
+ await submitWithRetry(client, payload);
259
+ ui.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
260
+ }