@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.
- package/README.md +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +25 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +100 -0
- package/dist/commands/update.js +229 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +227 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +360 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +126 -0
- package/dist/services/api.js +439 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +383 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +371 -0
- package/dist/services/device-auth.js +286 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +15 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +113 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +311 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1619 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +389 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { folderKey } from "./folder-key.js";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ConfigStore } from "./config.js";
|
|
6
|
+
/**
|
|
7
|
+
* Checkpoints and the change journal for supervised file edits.
|
|
8
|
+
*
|
|
9
|
+
* Kept in the CLI's own app-data folder, per workspace — never inside the
|
|
10
|
+
* repository. A change can be undone whether or not the file was ever committed,
|
|
11
|
+
* nothing ends up in `git status`, and Git is not a dependency of the safety
|
|
12
|
+
* net. This is not a version-control system: it keeps enough to restore the
|
|
13
|
+
* last few approved changes, and prunes the rest.
|
|
14
|
+
*
|
|
15
|
+
* What a checkpoint holds is the ORIGINAL bytes of one file, plus whether it
|
|
16
|
+
* existed and its mode. That is the only file content the CLI ever retains, it
|
|
17
|
+
* stays on the machine, and credential files never get one because they are
|
|
18
|
+
* refused before a change is planned.
|
|
19
|
+
*/
|
|
20
|
+
/** Changes remembered per workspace; older checkpoints are deleted. */
|
|
21
|
+
const MAX_ENTRIES = 50;
|
|
22
|
+
export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
|
|
23
|
+
/**
|
|
24
|
+
* The identity of a repository's checkpoint store: a hash of its normalized
|
|
25
|
+
* root. Exported so a journal entry can record which store it was written to,
|
|
26
|
+
* and an undo can prove it is reading the right one.
|
|
27
|
+
*/
|
|
28
|
+
export function repositoryKey(root) {
|
|
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);
|
|
33
|
+
}
|
|
34
|
+
/** One directory per repository root, keyed by a hash of its normalized path. */
|
|
35
|
+
export function workspaceDir(root) {
|
|
36
|
+
const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
|
|
37
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
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
|
+
}
|
|
104
|
+
export function readJournal(root) {
|
|
105
|
+
try {
|
|
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;
|
|
116
|
+
}
|
|
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.");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function writeJournal(root, entries) {
|
|
124
|
+
durableWrite(journalFile(root), JSON.stringify(entries, null, 2));
|
|
125
|
+
}
|
|
126
|
+
export function newCheckpointId() {
|
|
127
|
+
return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
|
|
128
|
+
}
|
|
129
|
+
/** Save a file's original bytes before it is changed. */
|
|
130
|
+
export function saveCheckpoint(root, checkpointId, original) {
|
|
131
|
+
if (original === null)
|
|
132
|
+
return; // nothing existed — undo means delete
|
|
133
|
+
const file = path.join(workspaceDir(root), `${checkpointId}.before`);
|
|
134
|
+
durableWrite(file, original);
|
|
135
|
+
}
|
|
136
|
+
export function loadCheckpoint(root, checkpointId) {
|
|
137
|
+
try {
|
|
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);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
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
|
+
}
|
|
228
|
+
/** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
|
|
229
|
+
export function appendEntry(root, entry) {
|
|
230
|
+
const entries = [...readJournal(root), entry];
|
|
231
|
+
const dropped = entries.length > MAX_ENTRIES ? entries.splice(0, entries.length - MAX_ENTRIES) : [];
|
|
232
|
+
writeJournal(root, entries);
|
|
233
|
+
for (const d of dropped) {
|
|
234
|
+
try {
|
|
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 });
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
/* already gone */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
export function updateEntry(root, operationId, patch) {
|
|
248
|
+
const entries = readJournal(root);
|
|
249
|
+
const i = entries.findIndex((e) => e.operation_id === operationId);
|
|
250
|
+
if (i === -1)
|
|
251
|
+
return;
|
|
252
|
+
entries[i] = { ...entries[i], ...patch };
|
|
253
|
+
writeJournal(root, entries);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The change `/undo` (or `revert_change` without an id) should undo: the most
|
|
257
|
+
* recent applied change that has not already been undone. Reverts are skipped,
|
|
258
|
+
* so undoing twice walks back two changes rather than toggling one.
|
|
259
|
+
*/
|
|
260
|
+
export function latestRevertible(root, operationId, repositoryId) {
|
|
261
|
+
const key = repositoryKey(root);
|
|
262
|
+
// An entry has to belong to THIS repository's store. Entries written before
|
|
263
|
+
// repository identity existed carry neither field and are accepted on the
|
|
264
|
+
// strength of the directory they were found in; anything that names a
|
|
265
|
+
// different repository is refused rather than restored.
|
|
266
|
+
const mine = (e) => (e.repository_key === undefined || e.repository_key === key) &&
|
|
267
|
+
(repositoryId === undefined || e.repository_id === undefined || e.repository_id === repositoryId);
|
|
268
|
+
const entries = readJournal(root).filter(mine);
|
|
269
|
+
if (operationId) {
|
|
270
|
+
return entries.find((e) => e.operation_id === operationId && e.status === "EXECUTED" && !e.reverts) ?? null;
|
|
271
|
+
}
|
|
272
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
273
|
+
const e = entries[i];
|
|
274
|
+
if (e.status === "EXECUTED" && !e.reverts)
|
|
275
|
+
return e;
|
|
276
|
+
}
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
@@ -0,0 +1,356 @@
|
|
|
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";
|
|
5
|
+
import { workspaceRoot } from "./local-files.js";
|
|
6
|
+
import { MUTATION_TOOL_NAMES } from "./mutations.js";
|
|
7
|
+
import { inScreen } from "../ui/screen-prompt.js";
|
|
8
|
+
import { isTrusted } from "../ui/trust.js";
|
|
9
|
+
import { executionAdapter, executionPlatform } from "./execution-platform.js";
|
|
10
|
+
import { containerRuntime } from "./container-runner.js";
|
|
11
|
+
/**
|
|
12
|
+
* The CLI end of a delegated tool call: receive → execute locally → answer.
|
|
13
|
+
*
|
|
14
|
+
* There is no loop here and there must never be one. The server's agent loop
|
|
15
|
+
* decides what it needs; this runs exactly the call it was sent, through the
|
|
16
|
+
* same executor and the same containment checks as everything else local, and
|
|
17
|
+
* posts the outcome back. If this code ever starts deciding what to read next,
|
|
18
|
+
* it has become a second agent.
|
|
19
|
+
*/
|
|
20
|
+
/** Largest serialized result we will post — under the server's per-tool cap. */
|
|
21
|
+
const MAX_POST_BYTES = 380 * 1024;
|
|
22
|
+
/**
|
|
23
|
+
* Should this turn offer local tools at all?
|
|
24
|
+
*
|
|
25
|
+
* Only in a trusted workspace. Trust is the existing "may Carrier OS read this
|
|
26
|
+
* folder" consent, scoped to the workspace ROOT because that is what the tools
|
|
27
|
+
* reach. Asked for at startup in the shell; never prompted for mid-turn, where a
|
|
28
|
+
* dialog would fight the stream for the terminal. Non-interactive runs follow
|
|
29
|
+
* trust.ts's existing rule: there is nobody to ask, so the check does not apply.
|
|
30
|
+
*/
|
|
31
|
+
export function declaredClientTools(ctx) {
|
|
32
|
+
try {
|
|
33
|
+
const trusted = !process.stdin.isTTY || isTrusted(ctx.config, workspaceRoot());
|
|
34
|
+
return trusted ? [...LOCAL_TOOL_NAMES] : undefined;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined; // no usable workspace — plain chat, no local tools
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Should this turn offer file-changing tools?
|
|
42
|
+
*
|
|
43
|
+
* Folder trust is necessary but NOT sufficient: trust means "may read", and it
|
|
44
|
+
* is never taken as consent to write. What makes a change possible is a person
|
|
45
|
+
* approving that specific change, so these are offered only where one can be
|
|
46
|
+
* asked — the interactive shell's screen. Piped, scripted and `cos chat` runs
|
|
47
|
+
* never get them, and there is no flag to change that.
|
|
48
|
+
*/
|
|
49
|
+
export function declaredMutationTools(ctx) {
|
|
50
|
+
if (!inScreen())
|
|
51
|
+
return undefined;
|
|
52
|
+
try {
|
|
53
|
+
return isTrusted(ctx.config, workspaceRoot()) ? [...MUTATION_TOOL_NAMES] : undefined;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const isMutationName = (name) => MUTATION_TOOL_NAMES.includes(name);
|
|
60
|
+
/** Opt-in switch for local commands while their release blockers are open. */
|
|
61
|
+
export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
|
|
62
|
+
/**
|
|
63
|
+
* Should this turn offer run_command?
|
|
64
|
+
*
|
|
65
|
+
* Everything file changes require — the interactive screen and a trusted
|
|
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.
|
|
70
|
+
*/
|
|
71
|
+
export function declaredCommandTools(ctx, approverPresent = inScreen(), autoMode = false) {
|
|
72
|
+
const state = localCommandsState(ctx, approverPresent, autoMode);
|
|
73
|
+
return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether local commands are on, why, and what (if anything) stops them.
|
|
77
|
+
*
|
|
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.
|
|
83
|
+
*/
|
|
84
|
+
export function localCommandsState(ctx, approverPresent = inScreen(), autoMode = false) {
|
|
85
|
+
const fromEnv = process.env[COMMANDS_OPT_IN_ENV] === "1";
|
|
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;
|
|
92
|
+
let blockedBy = null;
|
|
93
|
+
if (enabled) {
|
|
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)
|
|
104
|
+
blockedBy = "only in the interactive shell";
|
|
105
|
+
else if (!blockedBy) {
|
|
106
|
+
try {
|
|
107
|
+
if (!isTrusted(ctx.config, workspaceRoot()))
|
|
108
|
+
blockedBy = "the active repository is not trusted";
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
blockedBy = "the active repository could not be checked";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { enabled, source, blockedBy };
|
|
116
|
+
}
|
|
117
|
+
/** A short, user-facing description of what is about to happen. */
|
|
118
|
+
export function toolActivityLabel(call) {
|
|
119
|
+
const a = (call.arguments ?? {});
|
|
120
|
+
const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
121
|
+
switch (call.name) {
|
|
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
|
+
}
|
|
127
|
+
case "search_files":
|
|
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"}`;
|
|
131
|
+
case "list_files":
|
|
132
|
+
return s(a.glob) ? `Finding ${s(a.glob)}` : `Listing ${s(a.path) ?? "project files"}`;
|
|
133
|
+
case "resolve_local_file":
|
|
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);
|
|
141
|
+
case "git_status":
|
|
142
|
+
return `Checking git status${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
|
|
143
|
+
case "git_diff":
|
|
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();
|
|
151
|
+
case "create_file":
|
|
152
|
+
return `Proposing to create ${s(a.path) ?? "a file"}`;
|
|
153
|
+
case "write_file":
|
|
154
|
+
case "edit_file":
|
|
155
|
+
return `Proposing a change to ${s(a.path) ?? "a file"}`;
|
|
156
|
+
case "delete_file":
|
|
157
|
+
return `Proposing to delete ${s(a.path) ?? "a file"}`;
|
|
158
|
+
case "revert_change":
|
|
159
|
+
return "Proposing to undo a change";
|
|
160
|
+
case "run_command": {
|
|
161
|
+
const list = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string").join(" ") : "";
|
|
162
|
+
return `Proposing to run ${s(a.program) ?? "a command"}${list ? " " + list : ""}`.slice(0, 120);
|
|
163
|
+
}
|
|
164
|
+
default:
|
|
165
|
+
return "Inspecting the project";
|
|
166
|
+
}
|
|
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
|
+
}
|
|
181
|
+
/** The codes the server documents for client tool failures. */
|
|
182
|
+
function publicCode(code) {
|
|
183
|
+
switch (code) {
|
|
184
|
+
case "NOT_FOUND":
|
|
185
|
+
return "FILE_NOT_FOUND";
|
|
186
|
+
case "UNKNOWN_TOOL":
|
|
187
|
+
return "UNKNOWN_CLIENT_TOOL";
|
|
188
|
+
case "INVALID_ARGUMENTS":
|
|
189
|
+
return "INVALID_TOOL_ARGUMENTS";
|
|
190
|
+
default:
|
|
191
|
+
return code;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** Keep a read result under the post cap by trimming content, and say so. */
|
|
195
|
+
function fitResult(result) {
|
|
196
|
+
let size = Buffer.byteLength(JSON.stringify(result), "utf8");
|
|
197
|
+
if (size <= MAX_POST_BYTES || typeof result.content !== "string")
|
|
198
|
+
return result;
|
|
199
|
+
let content = result.content;
|
|
200
|
+
while (size > MAX_POST_BYTES && content.length > 0) {
|
|
201
|
+
content = content.slice(0, Math.floor(content.length * 0.75));
|
|
202
|
+
const trimmed = { ...result, content, truncated: true };
|
|
203
|
+
delete trimmed.line_count;
|
|
204
|
+
size = Buffer.byteLength(JSON.stringify(trimmed), "utf8");
|
|
205
|
+
if (size <= MAX_POST_BYTES)
|
|
206
|
+
return trimmed;
|
|
207
|
+
}
|
|
208
|
+
return { ...result, content: "", truncated: true };
|
|
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
|
+
};
|
|
220
|
+
/**
|
|
221
|
+
* Post a result, retrying once on a transport failure: the server holds the
|
|
222
|
+
* call for its timeout, so a blip should not cost the turn. A 4xx is an
|
|
223
|
+
* answer, not a blip.
|
|
224
|
+
*/
|
|
225
|
+
export async function submitWithRetry(client, payload) {
|
|
226
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
227
|
+
try {
|
|
228
|
+
await client.submitToolResult(payload);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
const status = err.status ?? 0;
|
|
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
|
+
}
|
|
240
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Handle one `client_tool_call`. Never throws: every outcome, including a
|
|
246
|
+
* malformed request, becomes a result the server can hand back to the model.
|
|
247
|
+
*/
|
|
248
|
+
export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
249
|
+
const id = typeof call?.tool_call_id === "string" ? call.tool_call_id : "";
|
|
250
|
+
if (!id)
|
|
251
|
+
return; // nothing to correlate an answer with
|
|
252
|
+
const label = toolActivityLabel(call);
|
|
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
|
+
}
|
|
278
|
+
// A proposed command goes to the command coordinator — never anywhere else,
|
|
279
|
+
// and never at all unless this turn offered commands.
|
|
280
|
+
if (call.name === "run_command" || call.kind === "command") {
|
|
281
|
+
if (!ui.commands || call.name !== "run_command") {
|
|
282
|
+
await submitWithRetry(client, {
|
|
283
|
+
tool_call_id: id,
|
|
284
|
+
ok: false,
|
|
285
|
+
error: { code: "COMMAND_NOT_ENABLED", message: "Local commands are not enabled in this session. Nothing ran." },
|
|
286
|
+
duration_ms: 0
|
|
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." });
|
|
289
|
+
}
|
|
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
|
+
}
|
|
299
|
+
await ui.commands.handle(call);
|
|
300
|
+
}
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
// A proposed change goes to the reviewer — never to the read executor, and
|
|
304
|
+
// never anywhere at all unless this turn offered changes in the first place.
|
|
305
|
+
if (isMutationName(call.name) || call.kind === "mutation") {
|
|
306
|
+
if (!ui.mutations || !isMutationName(call.name)) {
|
|
307
|
+
await submitWithRetry(client, {
|
|
308
|
+
tool_call_id: id,
|
|
309
|
+
ok: false,
|
|
310
|
+
error: { code: "MUTATION_NOT_ENABLED", message: "File changes are not enabled in this session. Nothing was changed." },
|
|
311
|
+
duration_ms: 0
|
|
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." });
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
await ui.mutations.handle(call);
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
ui.onStart?.(label, call.name);
|
|
321
|
+
let payload;
|
|
322
|
+
const trusted = declaredClientTools(ctx) !== undefined;
|
|
323
|
+
if (!trusted) {
|
|
324
|
+
payload = {
|
|
325
|
+
tool_call_id: id,
|
|
326
|
+
ok: false,
|
|
327
|
+
error: { code: "TOOL_NOT_TRUSTED", message: "This folder has not been trusted for Carrier OS to read." }
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
else if (!call.arguments || typeof call.arguments !== "object" || Array.isArray(call.arguments)) {
|
|
331
|
+
payload = {
|
|
332
|
+
tool_call_id: id,
|
|
333
|
+
ok: false,
|
|
334
|
+
error: { code: "INVALID_TOOL_ARGUMENTS", message: "Tool arguments must be an object." }
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
// The executor re-validates everything — name, arguments, containment,
|
|
339
|
+
// ignore rules, size — regardless of what the server already checked.
|
|
340
|
+
const res = executeLocalTool({ id, name: call.name, arguments: call.arguments }, { readCache: ui.readCache });
|
|
341
|
+
payload = res.ok
|
|
342
|
+
? { tool_call_id: id, ok: true, result: fitResult(res.result) }
|
|
343
|
+
: {
|
|
344
|
+
tool_call_id: id,
|
|
345
|
+
ok: false,
|
|
346
|
+
error: { code: publicCode(res.error?.code ?? "TOOL_FAILED"), message: res.error?.message ?? "Tool failed." }
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
payload.duration_ms = Date.now() - started;
|
|
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);
|
|
355
|
+
ui.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
|
|
356
|
+
}
|