@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
@@ -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
+ }
@@ -0,0 +1,200 @@
1
+ import { PolicyError, evaluateCommand } from "./command-policy.js";
2
+ import { JobHelperError } from "./job-helper.js";
3
+ import { RunnerError, runProcess } from "./process-runner.js";
4
+ import { Redactor, projectEnvSecrets } from "./redaction.js";
5
+ import { neutralizingOverrides } from "./workspace.js";
6
+ import { RepositoryError, activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
7
+ /**
8
+ * One turn's proposed local commands: check → ask → run → answer.
9
+ *
10
+ * Order is the whole point. The policy decides first, so a refused command
11
+ * never reaches the prompt. The person at the keyboard decides second, on
12
+ * exactly what will run — resolved script text included. Only then does the
13
+ * contained runner start anything. Commands run one at a time.
14
+ *
15
+ * Like the change reviewer, this is not an agent: it never proposes, retries or
16
+ * re-runs anything, and a "no" ends command proposals for the rest of the turn.
17
+ */
18
+ /** Largest serialized result posted — under the server's 64 KB cap. */
19
+ const MAX_RESULT_BYTES = 62 * 1024;
20
+ /** Keep the posted result under the cap by trimming the middle of the output. */
21
+ export function fitCommandResult(result) {
22
+ let out = result;
23
+ let size = Buffer.byteLength(JSON.stringify(out), "utf8");
24
+ while (size > MAX_RESULT_BYTES && typeof out.output === "string" && out.output.length > 0) {
25
+ const text = out.output;
26
+ const keep = Math.floor(text.length * 0.8);
27
+ const head = text.slice(0, Math.floor(keep * 0.25));
28
+ const tail = text.slice(text.length - Math.floor(keep * 0.75));
29
+ out = { ...out, output: `${head}\n… [output trimmed to fit] …\n${tail}`, truncated: true };
30
+ size = Buffer.byteLength(JSON.stringify(out), "utf8");
31
+ }
32
+ return out;
33
+ }
34
+ /**
35
+ * The repository a command runs in.
36
+ *
37
+ * Omitted means the active repository. A name may be any registered, TRUSTED
38
+ * repository — the user reads that name on the approval card before anything
39
+ * starts, and the active repository does not move. A wildcard, an unknown name
40
+ * or an untrusted one is an error the model sees.
41
+ *
42
+ * The returned root is what the policy, the cwd and the runner all use, so the
43
+ * package.json a script is read from is the SELECTED repository's, never the
44
+ * active one's.
45
+ */
46
+ function commandRepository(selector, fallbackRoot) {
47
+ if (selector === undefined || selector === null || selector === "") {
48
+ return repositoryForRoot(fallbackRoot) ?? activeRepository();
49
+ }
50
+ if (isWildcardSelector(selector)) {
51
+ throw new RunnerError("REPOSITORY_WILDCARD_NOT_ALLOWED", 'A command must name one repository; "*" is not accepted.');
52
+ }
53
+ return resolveOperableRepository(selector);
54
+ }
55
+ /** The registered repository a root belongs to, for the result and the audit. */
56
+ function repositoryForRoot(root) {
57
+ const norm = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
58
+ return listRepositories().find((r) => norm(r.root) === norm(root));
59
+ }
60
+ function errorCodeOf(err) {
61
+ if (err instanceof PolicyError || err instanceof RunnerError || err instanceof JobHelperError || err instanceof RepositoryError) {
62
+ return { code: err.code, message: err.message };
63
+ }
64
+ return { code: "START_FAILED", message: err?.message ?? "The command could not be run." };
65
+ }
66
+ export function createCommandCoordinator(opts) {
67
+ const { ui } = opts;
68
+ let chain = Promise.resolve();
69
+ let declined = false;
70
+ const fail = (call, started, code, message) => opts.submit({ tool_call_id: call.tool_call_id, ok: false, error: { code, message }, duration_ms: Date.now() - started });
71
+ async function process(call) {
72
+ const started = Date.now();
73
+ const args = (call.arguments ?? {});
74
+ const reason = typeof args.reason === "string" ? args.reason.slice(0, 300) : "";
75
+ if (declined) {
76
+ await fail(call, started, "COMMAND_REJECTED", "The user already declined a command in this turn. Nothing ran; ask how to proceed.");
77
+ return;
78
+ }
79
+ if (opts.signal.aborted) {
80
+ await fail(call, started, "COMMAND_CANCELLED", "The turn was stopped. Nothing ran.");
81
+ return;
82
+ }
83
+ // 1. Which repository, then policy — both before anyone is asked. A command
84
+ // runs in ONE repository: the active one, or one explicitly named as long as
85
+ // it IS the active one. Naming another is refused, never redirected.
86
+ let root = opts.root;
87
+ let repository = repositoryForRoot(opts.root);
88
+ try {
89
+ repository = commandRepository(args.repository, opts.root);
90
+ root = repository.root;
91
+ }
92
+ catch (err) {
93
+ const e = errorCodeOf(err);
94
+ ui.finished({ decision: null, errorCode: e.code, message: e.message });
95
+ await fail(call, started, e.code, e.message);
96
+ return;
97
+ }
98
+ let decision;
99
+ try {
100
+ const { reason: _r, repository: _repo, ...proposal } = args;
101
+ decision = evaluateCommand(proposal, root);
102
+ }
103
+ catch (err) {
104
+ const e = errorCodeOf(err);
105
+ ui.finished({ decision: null, errorCode: e.code, message: e.message });
106
+ await fail(call, started, e.code, e.message);
107
+ return;
108
+ }
109
+ // Git reads file content through repository-configured programs; neutralize
110
+ // them for this call exactly as repository detection does.
111
+ if (decision.program === "git") {
112
+ const overrides = neutralizingOverrides(root);
113
+ if (!overrides) {
114
+ const message = "The repository's Git configuration could not be read safely, so the command was not run.";
115
+ ui.finished({ decision, errorCode: "COMMAND_DENIED", message });
116
+ await fail(call, started, "COMMAND_DENIED", message);
117
+ return;
118
+ }
119
+ const sub = decision.effectiveArgs.indexOf(decision.args[0]);
120
+ decision = { ...decision, effectiveArgs: [...decision.effectiveArgs.slice(0, sub), ...overrides, ...decision.effectiveArgs.slice(sub)] };
121
+ }
122
+ // 2. Approval, then 3. run — both while holding the terminal.
123
+ await opts.withTerminal(async () => {
124
+ const answer = await ui.review(decision, reason, repository?.name);
125
+ if (answer !== "approve") {
126
+ declined = true;
127
+ const code = answer === "timeout" ? "APPROVAL_TIMEOUT" : answer === "cancel" ? "COMMAND_CANCELLED" : "COMMAND_REJECTED";
128
+ const message = answer === "timeout"
129
+ ? "No one approved the command in time. Nothing ran."
130
+ : answer === "cancel"
131
+ ? "The user stopped the turn. Nothing ran."
132
+ : "The user rejected the command. Nothing ran.";
133
+ ui.finished({ decision, errorCode: code, message });
134
+ await fail(call, started, code, message);
135
+ if (answer === "cancel")
136
+ ui.cancelTurn();
137
+ return;
138
+ }
139
+ let result;
140
+ try {
141
+ const redactor = new Redactor([...projectEnvSecrets(root), ...(opts.cliSecrets ?? [])]);
142
+ result = await runProcess({
143
+ program: decision.program,
144
+ args: decision.effectiveArgs,
145
+ cwd: decision.cwdAbsolute,
146
+ root,
147
+ timeoutMs: decision.timeoutMs,
148
+ signal: opts.signal,
149
+ redactor,
150
+ onStart: () => ui.started(decision),
151
+ onOutput: (stream, text) => ui.output(stream, text)
152
+ });
153
+ }
154
+ catch (err) {
155
+ const e = errorCodeOf(err);
156
+ ui.finished({ decision, errorCode: e.code, message: e.message });
157
+ await fail(call, started, e.code, e.message);
158
+ return;
159
+ }
160
+ ui.finished({ decision, result });
161
+ const payload = fitCommandResult({
162
+ // Reported from the RESOLVED handle, so the audit records which
163
+ // repository was selected rather than inferring one from a path.
164
+ repository: repository?.name,
165
+ repository_id: repository?.id,
166
+ program: decision.program,
167
+ args: decision.args,
168
+ cwd: decision.cwdRelative,
169
+ risk_tier: decision.tier,
170
+ network_label: decision.network,
171
+ exit_code: result.exit_code,
172
+ signal: result.signal,
173
+ timed_out: result.timed_out,
174
+ cancelled: result.cancelled,
175
+ tree_killed: result.tree_killed,
176
+ started_at: result.started_at,
177
+ ended_at: result.ended_at,
178
+ duration_ms: result.duration_ms,
179
+ stdout_bytes: result.stdout_bytes,
180
+ stderr_bytes: result.stderr_bytes,
181
+ truncated: result.truncated,
182
+ redaction_count: result.redaction_count,
183
+ dropped_environment_names: result.dropped_environment_names,
184
+ ...(decision.script ? { script: { name: decision.script.name, text: decision.script.text.slice(0, 500) } } : {}),
185
+ output: result.output
186
+ });
187
+ await opts.submit({ tool_call_id: call.tool_call_id, ok: true, result: payload, duration_ms: Date.now() - started });
188
+ });
189
+ }
190
+ return {
191
+ handle(call) {
192
+ const next = chain.then(() => process(call)).catch(async (err) => {
193
+ // A bug here must still answer the call, never leave the turn waiting.
194
+ await fail(call, Date.now(), "START_FAILED", err?.message ?? "The command could not be processed.").catch(() => undefined);
195
+ });
196
+ chain = next;
197
+ return next;
198
+ }
199
+ };
200
+ }