@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.
- package/README.md +142 -57
- package/dist/commands/attach.js +45 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +80 -14
- package/dist/commands/context.js +160 -0
- package/dist/commands/doctor.js +46 -1
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +1 -0
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +31 -7
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +39 -3
- package/dist/commands/modes.js +4 -1
- 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/search.js +92 -0
- package/dist/commands/sessions.js +219 -65
- package/dist/commands/settings.js +87 -0
- package/dist/commands/update.js +159 -0
- package/dist/commands/upload.js +204 -31
- package/dist/commands/usage.js +212 -16
- package/dist/ide/editor-context.js +172 -0
- package/dist/ide/ide-session.js +94 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +26 -1
- package/dist/services/api.js +140 -6
- package/dist/services/chat-stream.js +145 -0
- package/dist/services/checkpoints.js +116 -0
- package/dist/services/client-tools.js +260 -0
- package/dist/services/command-coordinator.js +200 -0
- package/dist/services/command-policy.js +404 -0
- package/dist/services/config.js +247 -22
- package/dist/services/context.js +265 -20
- package/dist/services/device-auth.js +42 -30
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -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/git-tools.js +248 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +64 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/job-helper.js +307 -0
- package/dist/services/local-files.js +517 -0
- package/dist/services/local-tools.js +432 -0
- package/dist/services/login-flow.js +15 -8
- package/dist/services/meta.js +3 -1
- package/dist/services/mutation-coordinator.js +161 -0
- package/dist/services/mutations.js +493 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +5 -2
- package/dist/services/packaged.js +24 -0
- package/dist/services/process-runner.js +406 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/secure-store.js +197 -0
- package/dist/services/session-resolver.js +108 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/update.js +286 -0
- package/dist/services/workspace-registry.js +309 -0
- package/dist/services/workspace.js +573 -0
- package/dist/shell/shell-chat.js +1028 -57
- package/dist/shell/shell-commands.js +200 -11
- package/dist/shell/shell-prompt.js +81 -8
- package/dist/shell/shell-renderer.js +7 -19
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +185 -17
- package/dist/types/index.js +3 -1
- package/dist/ui/approval.js +81 -0
- package/dist/ui/banner.js +39 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +87 -0
- package/dist/ui/chat-renderer.js +206 -13
- package/dist/ui/colors.js +4 -0
- package/dist/ui/command-filter.js +26 -5
- package/dist/ui/command-palette.js +17 -4
- package/dist/ui/command-registry.js +84 -9
- package/dist/ui/command-review.js +138 -0
- package/dist/ui/composer-layout.js +41 -0
- package/dist/ui/conversation.js +398 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +3 -1
- package/dist/ui/markdown.js +63 -9
- package/dist/ui/message.js +14 -31
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +1 -1
- package/dist/ui/select.js +185 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/trust.js +93 -0
- package/dist/ui/ui.js +4 -1
- package/package.json +13 -2
- package/dist/ui/activity.js +0 -77
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { appendEntry, latestRevertible, repositoryKey, loadCheckpoint, newCheckpointId, saveCheckpoint, sha256, updateEntry } from "./checkpoints.js";
|
|
5
|
+
import { diffLines, formatUnified } from "./diff.js";
|
|
6
|
+
import { LocalFileError, isInside, isPathIgnored, resolveInside } from "./local-files.js";
|
|
7
|
+
import { isSensitiveName } from "./local-tools.js";
|
|
8
|
+
import { activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
|
|
9
|
+
/**
|
|
10
|
+
* Supervised file changes: plan, show, approve, apply, undo.
|
|
11
|
+
*
|
|
12
|
+
* This module never decides that a change is wanted. It turns a proposal into a
|
|
13
|
+
* PLAN — validated, diffed, touching nothing on disk — and applies a plan only
|
|
14
|
+
* when the caller has an explicit approval for that exact plan. Between the two
|
|
15
|
+
* the file is read again, and if it changed at all the apply refuses: the user
|
|
16
|
+
* approved a diff against a specific file, not whatever is there now.
|
|
17
|
+
*
|
|
18
|
+
* Every boundary the read tools enforce applies here too, and more strictly:
|
|
19
|
+
* the workspace root, realpath containment for the file AND every existing
|
|
20
|
+
* parent directory, ignored paths (which include .git and node_modules), and
|
|
21
|
+
* credential-shaped files, which are refused outright rather than confirmed.
|
|
22
|
+
*/
|
|
23
|
+
export const MUTATION_TOOL_NAMES = ["create_file", "write_file", "edit_file", "delete_file", "revert_change"];
|
|
24
|
+
/** Largest content a create/write may carry, and largest file an edit reads. */
|
|
25
|
+
export const MAX_WRITE_BYTES = 512 * 1024;
|
|
26
|
+
export const MAX_EDIT_SOURCE_BYTES = 1024 * 1024;
|
|
27
|
+
/** Most files in one approval, and in one turn. Intentionally small. */
|
|
28
|
+
export const MAX_FILES_PER_APPROVAL = 5;
|
|
29
|
+
export const MAX_MUTATIONS_PER_TURN = 8;
|
|
30
|
+
/** A diff longer than this cannot be reviewed on a terminal and is refused. */
|
|
31
|
+
export const MAX_REVIEW_LINES = 800;
|
|
32
|
+
/** Unanswered approvals close as rejected — inside the server's 5 minute hold. */
|
|
33
|
+
export const APPROVAL_TIMEOUT_MS = 4 * 60 * 1000;
|
|
34
|
+
/**
|
|
35
|
+
* Names refused for changes beyond the read tools' credential list: anything
|
|
36
|
+
* called "secrets", git credential stores, and SSH material by directory.
|
|
37
|
+
*/
|
|
38
|
+
const EXTRA_PROTECTED = [/^secrets?(\..+)?$/i, /^\.git-credentials$/i, /^\.htpasswd$/i, /^authorized_keys$/i, /^known_hosts$/i];
|
|
39
|
+
export class MutationError extends Error {
|
|
40
|
+
code;
|
|
41
|
+
constructor(code, message) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.name = "MutationError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
48
|
+
const posix = (p) => p.split(path.sep).join("/");
|
|
49
|
+
/** Text with a NUL byte in its first 8 KB is not something we edit as text. */
|
|
50
|
+
function isBinary(buf) {
|
|
51
|
+
const end = Math.min(buf.length, 8192);
|
|
52
|
+
for (let i = 0; i < end; i += 1)
|
|
53
|
+
if (buf[i] === 0)
|
|
54
|
+
return true;
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Resolve a proposed path and prove it may be changed.
|
|
59
|
+
*
|
|
60
|
+
* For a file that does not exist yet, realpath cannot run on it, so containment
|
|
61
|
+
* is proven on the deepest ancestor that DOES exist — otherwise a junction
|
|
62
|
+
* directory inside the project would let a "new file" land outside it.
|
|
63
|
+
*/
|
|
64
|
+
function resolveTarget(input, root) {
|
|
65
|
+
const raw = str(input)?.trim();
|
|
66
|
+
if (!raw)
|
|
67
|
+
throw new MutationError("INVALID_TOOL_ARGUMENTS", '"path" is required.');
|
|
68
|
+
if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) {
|
|
69
|
+
throw new MutationError("OUTSIDE_WORKSPACE", "Paths must be relative to the project root.");
|
|
70
|
+
}
|
|
71
|
+
if (raw.split(/[\\/]+/).includes("..")) {
|
|
72
|
+
throw new MutationError("OUTSIDE_WORKSPACE", "Paths must stay inside the project.");
|
|
73
|
+
}
|
|
74
|
+
let abs;
|
|
75
|
+
try {
|
|
76
|
+
abs = resolveInside(raw, root);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
if (err instanceof LocalFileError)
|
|
80
|
+
throw new MutationError(err.code, err.message);
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
let probe = path.dirname(abs);
|
|
84
|
+
while (!fs.existsSync(probe) && isInside(root, path.dirname(probe)) && path.dirname(probe) !== probe) {
|
|
85
|
+
probe = path.dirname(probe);
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
if (!isInside(root, fs.realpathSync.native(probe))) {
|
|
89
|
+
throw new MutationError("OUTSIDE_WORKSPACE", `${raw} is inside a link that leaves the project.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
if (err instanceof MutationError)
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
const rel = posix(path.relative(root, abs));
|
|
97
|
+
if (!rel || rel.startsWith(".."))
|
|
98
|
+
throw new MutationError("OUTSIDE_WORKSPACE", "Paths must stay inside the project.");
|
|
99
|
+
if (isPathIgnored(rel, root)) {
|
|
100
|
+
throw new MutationError("IGNORED_PATH", `${rel} is excluded by the project's ignore rules and will not be changed.`);
|
|
101
|
+
}
|
|
102
|
+
const base = path.basename(abs);
|
|
103
|
+
if (isSensitiveName(base) || EXTRA_PROTECTED.some((re) => re.test(base)) || rel.split("/").includes(".ssh")) {
|
|
104
|
+
throw new MutationError("SENSITIVE_FILE", `${rel} looks like a credentials file. Carrier OS will not change it.`);
|
|
105
|
+
}
|
|
106
|
+
return { abs, rel };
|
|
107
|
+
}
|
|
108
|
+
function readExisting(abs, rel) {
|
|
109
|
+
let st;
|
|
110
|
+
try {
|
|
111
|
+
st = fs.statSync(abs);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
throw new MutationError("FILE_NOT_FOUND", `${rel} does not exist.`);
|
|
115
|
+
}
|
|
116
|
+
if (!st.isFile())
|
|
117
|
+
throw new MutationError("NOT_A_FILE", `${rel} is not a file.`);
|
|
118
|
+
if (st.size > MAX_EDIT_SOURCE_BYTES) {
|
|
119
|
+
throw new MutationError("FILE_TOO_LARGE", `${rel} is larger than ${MAX_EDIT_SOURCE_BYTES} bytes.`);
|
|
120
|
+
}
|
|
121
|
+
const buf = fs.readFileSync(abs);
|
|
122
|
+
if (isBinary(buf))
|
|
123
|
+
throw new MutationError("BINARY_FILE", `${rel} is not a text file.`);
|
|
124
|
+
return { buf, mode: st.mode };
|
|
125
|
+
}
|
|
126
|
+
function checkWriteSize(content) {
|
|
127
|
+
if (Buffer.byteLength(content, "utf8") > MAX_WRITE_BYTES) {
|
|
128
|
+
throw new MutationError("FILE_TOO_LARGE", `The new content exceeds ${MAX_WRITE_BYTES} bytes.`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function countOccurrences(haystack, needle) {
|
|
132
|
+
let count = 0;
|
|
133
|
+
let from = 0;
|
|
134
|
+
for (;;) {
|
|
135
|
+
const i = haystack.indexOf(needle, from);
|
|
136
|
+
if (i === -1)
|
|
137
|
+
return count;
|
|
138
|
+
count += 1;
|
|
139
|
+
from = i + needle.length;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Apply an edit's replacement deterministically, or refuse.
|
|
144
|
+
*
|
|
145
|
+
* Exact match only — no fuzzy matching, no whitespace normalisation beyond one
|
|
146
|
+
* well-defined case: a Windows file with CRLF line endings, where a model that
|
|
147
|
+
* read the file copies `old_string` with LF. That is retried ONCE with CRLF
|
|
148
|
+
* applied to both strings, and still has to match exactly and uniquely.
|
|
149
|
+
*/
|
|
150
|
+
function applyEdit(original, oldStr, newStr, replaceAll, rel) {
|
|
151
|
+
const attempt = (o, n) => {
|
|
152
|
+
const count = countOccurrences(original, o);
|
|
153
|
+
if (count === 0)
|
|
154
|
+
return null;
|
|
155
|
+
if (count > 1 && !replaceAll) {
|
|
156
|
+
throw new MutationError("EDIT_AMBIGUOUS", `old_string occurs ${count} times in ${rel}. Include more surrounding lines so it matches exactly once.`);
|
|
157
|
+
}
|
|
158
|
+
return replaceAll ? original.split(o).join(n) : original.replace(o, () => n);
|
|
159
|
+
};
|
|
160
|
+
const direct = attempt(oldStr, newStr);
|
|
161
|
+
if (direct !== null)
|
|
162
|
+
return direct;
|
|
163
|
+
if (original.includes("\r\n") && !oldStr.includes("\r\n")) {
|
|
164
|
+
const crlf = (s) => s.replace(/\r?\n/g, "\r\n");
|
|
165
|
+
const converted = attempt(crlf(oldStr), crlf(newStr));
|
|
166
|
+
if (converted !== null)
|
|
167
|
+
return converted;
|
|
168
|
+
}
|
|
169
|
+
throw new MutationError("EDIT_TARGET_NOT_FOUND", `old_string was not found in ${rel}. Read the file again and copy the text exactly.`);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The repository a change will touch.
|
|
173
|
+
*
|
|
174
|
+
* Omitted means the ACTIVE repository — the behaviour every earlier call
|
|
175
|
+
* depends on. A named repository may be any registered, TRUSTED one, whether or
|
|
176
|
+
* not it is active: the user still reads that name on the approval card and
|
|
177
|
+
* still says yes to that specific change, and the active repository is left
|
|
178
|
+
* exactly where it was. What is never accepted is a wildcard, an unknown name,
|
|
179
|
+
* anything path-shaped, or a repository the user has not trusted.
|
|
180
|
+
*/
|
|
181
|
+
function repositoryForChange(selector) {
|
|
182
|
+
if (selector === undefined || selector === null || selector === "")
|
|
183
|
+
return activeRepository();
|
|
184
|
+
if (isWildcardSelector(selector)) {
|
|
185
|
+
throw new MutationError("REPOSITORY_WILDCARD_NOT_ALLOWED", 'A change must name one repository; "*" is not accepted.');
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
return resolveOperableRepository(selector);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
throw new MutationError(err.code ?? "INVALID_REPOSITORY", err.message);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function finishPlan(p) {
|
|
195
|
+
const before = p.beforeBuf?.toString("utf8") ?? "";
|
|
196
|
+
const after = p.afterBuf?.toString("utf8") ?? "";
|
|
197
|
+
const diff = diffLines(before, after);
|
|
198
|
+
return {
|
|
199
|
+
...p,
|
|
200
|
+
beforeSha: p.beforeBuf ? sha256(p.beforeBuf) : null,
|
|
201
|
+
afterSha: p.afterBuf ? sha256(p.afterBuf) : null,
|
|
202
|
+
diff,
|
|
203
|
+
unified: formatUnified(p.rel, diff, { oldExists: p.beforeExists, newExists: p.afterExists })
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Turn one proposal into a reviewable plan. Reads, never writes. Throws a
|
|
208
|
+
* MutationError with a code the model can act on for anything it refuses.
|
|
209
|
+
*/
|
|
210
|
+
export function planMutation(call) {
|
|
211
|
+
const name = call.name;
|
|
212
|
+
if (!MUTATION_TOOL_NAMES.includes(name)) {
|
|
213
|
+
throw new MutationError("UNKNOWN_CLIENT_TOOL", `No local tool named "${call.name}".`);
|
|
214
|
+
}
|
|
215
|
+
const args = (call.arguments ?? {});
|
|
216
|
+
const reason = str(args.reason)?.trim() || "No reason given.";
|
|
217
|
+
// One change, one repository — resolved BEFORE any path is touched, so the
|
|
218
|
+
// root every containment check runs against is a registry handle's root and
|
|
219
|
+
// never something derived from the path itself.
|
|
220
|
+
const repo = repositoryForChange(args.repository);
|
|
221
|
+
const root = repo.root;
|
|
222
|
+
const operationId = call.tool_call_id;
|
|
223
|
+
if (name === "revert_change") {
|
|
224
|
+
// Scoped to this repository's own journal: an operation id belonging to a
|
|
225
|
+
// different repository is simply not found here, which is the behaviour we
|
|
226
|
+
// want — a change is undone where it was made, or not at all.
|
|
227
|
+
const target = latestRevertible(root, str(args.operation_id), repo.id);
|
|
228
|
+
if (!target) {
|
|
229
|
+
throw new MutationError("NOTHING_TO_REVERT", str(args.operation_id)
|
|
230
|
+
? `No applied change with that id in ${repo.name}. A change is undone in the repository it was made in.`
|
|
231
|
+
: `There is no applied change to undo in ${repo.name}.`);
|
|
232
|
+
}
|
|
233
|
+
const { abs, rel } = resolveTarget(target.path, root);
|
|
234
|
+
// Undo restores what was there BEFORE the change — but only if the file is
|
|
235
|
+
// still exactly what the change left. Anything else would clobber later work.
|
|
236
|
+
const nowExists = fs.existsSync(abs);
|
|
237
|
+
const nowBuf = nowExists ? fs.readFileSync(abs) : null;
|
|
238
|
+
const nowSha = nowBuf ? sha256(nowBuf) : null;
|
|
239
|
+
if (nowExists !== target.after_exists || nowSha !== target.after_sha) {
|
|
240
|
+
throw new MutationError("STALE_FILE", `${rel} has changed since that change was applied, so it will not be reverted.`);
|
|
241
|
+
}
|
|
242
|
+
let restored = null;
|
|
243
|
+
if (target.before_exists) {
|
|
244
|
+
restored = loadCheckpoint(root, target.checkpoint_id);
|
|
245
|
+
if (!restored)
|
|
246
|
+
throw new MutationError("CHECKPOINT_MISSING", `The checkpoint for ${rel} is no longer available.`);
|
|
247
|
+
}
|
|
248
|
+
return finishPlan({
|
|
249
|
+
operationId,
|
|
250
|
+
repositoryId: repo.id,
|
|
251
|
+
repositoryName: repo.name,
|
|
252
|
+
repositoryRoot: root,
|
|
253
|
+
name,
|
|
254
|
+
rel,
|
|
255
|
+
abs,
|
|
256
|
+
reason,
|
|
257
|
+
beforeExists: nowExists,
|
|
258
|
+
beforeBuf: nowBuf,
|
|
259
|
+
afterExists: target.before_exists,
|
|
260
|
+
afterBuf: restored,
|
|
261
|
+
reverts: target.operation_id,
|
|
262
|
+
revertEntry: target,
|
|
263
|
+
beforeMode: target.mode
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
const { abs, rel } = resolveTarget(args.path, root);
|
|
267
|
+
const exists = fs.existsSync(abs);
|
|
268
|
+
switch (name) {
|
|
269
|
+
case "create_file": {
|
|
270
|
+
const content = str(args.content);
|
|
271
|
+
if (content === undefined)
|
|
272
|
+
throw new MutationError("INVALID_TOOL_ARGUMENTS", '"content" must be a string.');
|
|
273
|
+
if (exists)
|
|
274
|
+
throw new MutationError("FILE_EXISTS", `${rel} already exists. Use edit_file or write_file to change it.`);
|
|
275
|
+
checkWriteSize(content);
|
|
276
|
+
return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: false, beforeBuf: null, afterExists: true, afterBuf: Buffer.from(content, "utf8") });
|
|
277
|
+
}
|
|
278
|
+
case "write_file": {
|
|
279
|
+
const content = str(args.content);
|
|
280
|
+
if (content === undefined)
|
|
281
|
+
throw new MutationError("INVALID_TOOL_ARGUMENTS", '"content" must be a string.');
|
|
282
|
+
if (!exists)
|
|
283
|
+
throw new MutationError("FILE_NOT_FOUND", `${rel} does not exist. Use create_file for a new file.`);
|
|
284
|
+
checkWriteSize(content);
|
|
285
|
+
const { buf, mode } = readExisting(abs, rel);
|
|
286
|
+
return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: true, afterBuf: Buffer.from(content, "utf8") });
|
|
287
|
+
}
|
|
288
|
+
case "edit_file": {
|
|
289
|
+
const oldStr = str(args.old_string);
|
|
290
|
+
const newStr = str(args.new_string);
|
|
291
|
+
if (!oldStr || newStr === undefined) {
|
|
292
|
+
throw new MutationError("INVALID_TOOL_ARGUMENTS", '"old_string" and "new_string" are required.');
|
|
293
|
+
}
|
|
294
|
+
const { buf, mode } = readExisting(abs, rel);
|
|
295
|
+
const updated = applyEdit(buf.toString("utf8"), oldStr, newStr, args.replace_all === true, rel);
|
|
296
|
+
checkWriteSize(updated);
|
|
297
|
+
return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: true, afterBuf: Buffer.from(updated, "utf8") });
|
|
298
|
+
}
|
|
299
|
+
case "delete_file": {
|
|
300
|
+
const { buf, mode } = readExisting(abs, rel);
|
|
301
|
+
return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: false, afterBuf: null });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
throw new MutationError("UNKNOWN_CLIENT_TOOL", `No local tool named "${call.name}".`);
|
|
305
|
+
}
|
|
306
|
+
/** Write bytes via a temp file in the same directory, then rename over the target. */
|
|
307
|
+
function atomicWrite(abs, buf, mode) {
|
|
308
|
+
const dir = path.dirname(abs);
|
|
309
|
+
const tmp = path.join(dir, `.${path.basename(abs)}.cos-${crypto.randomBytes(4).toString("hex")}.tmp`);
|
|
310
|
+
fs.writeFileSync(tmp, buf, mode ? { mode: mode & 0o777 } : undefined);
|
|
311
|
+
try {
|
|
312
|
+
fs.renameSync(tmp, abs);
|
|
313
|
+
}
|
|
314
|
+
catch (err) {
|
|
315
|
+
try {
|
|
316
|
+
fs.unlinkSync(tmp);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
/* ignore */
|
|
320
|
+
}
|
|
321
|
+
throw err;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Apply an APPROVED plan. Re-reads the file first and refuses if anything
|
|
326
|
+
* changed since the plan was made; checkpoints the original; writes atomically;
|
|
327
|
+
* verifies the result. On a failure after the write began, the original is put
|
|
328
|
+
* back before the error propagates.
|
|
329
|
+
*/
|
|
330
|
+
export function applyPlan(plan) {
|
|
331
|
+
const root = plan.repositoryRoot;
|
|
332
|
+
// Re-validate the path: the workspace or a link could have changed while the
|
|
333
|
+
// user was reading the diff.
|
|
334
|
+
resolveTarget(plan.rel, root);
|
|
335
|
+
const nowExists = fs.existsSync(plan.abs);
|
|
336
|
+
const nowSha = nowExists ? sha256(fs.readFileSync(plan.abs)) : null;
|
|
337
|
+
if (nowExists !== plan.beforeExists || nowSha !== plan.beforeSha) {
|
|
338
|
+
throw new MutationError("STALE_FILE", `${plan.rel} changed after the proposal was made. Nothing was written.`);
|
|
339
|
+
}
|
|
340
|
+
const checkpointId = newCheckpointId();
|
|
341
|
+
try {
|
|
342
|
+
saveCheckpoint(root, checkpointId, plan.beforeBuf);
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
throw new MutationError("CHECKPOINT_FAILED", `Could not save a checkpoint for ${plan.rel}. Nothing was written.`);
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
if (plan.afterExists && plan.afterBuf) {
|
|
349
|
+
if (!plan.beforeExists) {
|
|
350
|
+
fs.mkdirSync(path.dirname(plan.abs), { recursive: true });
|
|
351
|
+
// mkdir may have created directories; the file's final location must
|
|
352
|
+
// still be inside the project.
|
|
353
|
+
if (!isInside(root, fs.realpathSync.native(path.dirname(plan.abs)))) {
|
|
354
|
+
throw new MutationError("OUTSIDE_WORKSPACE", `${plan.rel} resolved outside the project.`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
atomicWrite(plan.abs, plan.afterBuf, plan.beforeMode);
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
fs.unlinkSync(plan.abs);
|
|
361
|
+
}
|
|
362
|
+
const verifySha = fs.existsSync(plan.abs) ? sha256(fs.readFileSync(plan.abs)) : null;
|
|
363
|
+
if (verifySha !== plan.afterSha) {
|
|
364
|
+
throw new MutationError("WRITE_FAILED", `${plan.rel} did not end up with the approved content.`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
catch (err) {
|
|
368
|
+
restoreOriginal(plan.abs, plan.beforeExists, plan.beforeBuf, plan.beforeMode);
|
|
369
|
+
if (err instanceof MutationError)
|
|
370
|
+
throw err;
|
|
371
|
+
throw new MutationError("WRITE_FAILED", `Could not write ${plan.rel}: ${err.message}`);
|
|
372
|
+
}
|
|
373
|
+
const applied = {
|
|
374
|
+
operationId: plan.operationId,
|
|
375
|
+
repositoryId: plan.repositoryId,
|
|
376
|
+
repositoryName: plan.repositoryName,
|
|
377
|
+
checkpointId,
|
|
378
|
+
name: plan.name,
|
|
379
|
+
rel: plan.rel,
|
|
380
|
+
beforeExists: plan.beforeExists,
|
|
381
|
+
afterExists: plan.afterExists,
|
|
382
|
+
beforeSha: plan.beforeSha,
|
|
383
|
+
afterSha: plan.afterSha,
|
|
384
|
+
beforeBytes: plan.beforeBuf?.length ?? 0,
|
|
385
|
+
afterBytes: plan.afterBuf?.length ?? 0,
|
|
386
|
+
added: plan.diff.added,
|
|
387
|
+
removed: plan.diff.removed,
|
|
388
|
+
...(plan.reverts ? { reverts: plan.reverts } : {})
|
|
389
|
+
};
|
|
390
|
+
appendEntry(root, {
|
|
391
|
+
operation_id: plan.operationId,
|
|
392
|
+
repository_id: plan.repositoryId,
|
|
393
|
+
repository_name: plan.repositoryName,
|
|
394
|
+
repository_key: repositoryKey(root),
|
|
395
|
+
checkpoint_id: checkpointId,
|
|
396
|
+
action: plan.name,
|
|
397
|
+
path: plan.rel,
|
|
398
|
+
reason: plan.reason.slice(0, 300),
|
|
399
|
+
created_at: new Date().toISOString(),
|
|
400
|
+
status: "EXECUTED",
|
|
401
|
+
before_exists: plan.beforeExists,
|
|
402
|
+
after_exists: plan.afterExists,
|
|
403
|
+
before_sha: plan.beforeSha,
|
|
404
|
+
after_sha: plan.afterSha,
|
|
405
|
+
before_bytes: applied.beforeBytes,
|
|
406
|
+
after_bytes: applied.afterBytes,
|
|
407
|
+
added: plan.diff.added,
|
|
408
|
+
removed: plan.diff.removed,
|
|
409
|
+
mode: plan.beforeMode,
|
|
410
|
+
...(plan.reverts ? { reverts: plan.reverts } : {})
|
|
411
|
+
});
|
|
412
|
+
if (plan.reverts) {
|
|
413
|
+
updateEntry(root, plan.reverts, {
|
|
414
|
+
status: "ROLLED_BACK",
|
|
415
|
+
reverted_by: plan.operationId,
|
|
416
|
+
rolled_back_at: new Date().toISOString()
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
return applied;
|
|
420
|
+
}
|
|
421
|
+
function restoreOriginal(abs, existed, buf, mode) {
|
|
422
|
+
try {
|
|
423
|
+
if (existed && buf)
|
|
424
|
+
atomicWrite(abs, buf, mode);
|
|
425
|
+
else if (!existed && fs.existsSync(abs))
|
|
426
|
+
fs.unlinkSync(abs);
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
/* best effort — the checkpoint still holds the original */
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Undo a change applied earlier in the SAME approval group, used when a later
|
|
434
|
+
* change in the group fails. Only restores if the file is still exactly what
|
|
435
|
+
* this change wrote.
|
|
436
|
+
*/
|
|
437
|
+
export function rollbackApplied(applied) {
|
|
438
|
+
const root = repositoryRootById(applied.repositoryId);
|
|
439
|
+
// The repository is no longer registered: there is no root we can honestly
|
|
440
|
+
// restore into, and guessing one would write another repository's file.
|
|
441
|
+
if (!root)
|
|
442
|
+
return false;
|
|
443
|
+
const abs = path.join(root, applied.rel);
|
|
444
|
+
const nowExists = fs.existsSync(abs);
|
|
445
|
+
const nowSha = nowExists ? sha256(fs.readFileSync(abs)) : null;
|
|
446
|
+
if (nowExists !== applied.afterExists || nowSha !== applied.afterSha)
|
|
447
|
+
return false;
|
|
448
|
+
const original = applied.beforeExists ? loadCheckpoint(root, applied.checkpointId) : null;
|
|
449
|
+
if (applied.beforeExists && !original)
|
|
450
|
+
return false;
|
|
451
|
+
restoreOriginal(abs, applied.beforeExists, original);
|
|
452
|
+
updateEntry(root, applied.operationId, { status: "ROLLED_BACK", rolled_back_at: new Date().toISOString() });
|
|
453
|
+
if (applied.reverts) {
|
|
454
|
+
// Rolling back a revert puts the reverted change back in force.
|
|
455
|
+
updateEntry(root, applied.reverts, { status: "EXECUTED", reverted_by: undefined, rolled_back_at: undefined });
|
|
456
|
+
}
|
|
457
|
+
return true;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* The root of the repository an earlier change belonged to, or null.
|
|
461
|
+
*
|
|
462
|
+
* Null rather than a fallback on purpose: a checkpoint whose repository has
|
|
463
|
+
* left the registry must fail safely. Falling back to "wherever we are now"
|
|
464
|
+
* would restore one repository's bytes into another.
|
|
465
|
+
*/
|
|
466
|
+
function repositoryRootById(id) {
|
|
467
|
+
return listRepositories().find((r) => r.id === id)?.root ?? null;
|
|
468
|
+
}
|
|
469
|
+
/** Metadata posted back to the server for an applied change — never content. */
|
|
470
|
+
export function appliedResult(a) {
|
|
471
|
+
return {
|
|
472
|
+
operation_id: a.operationId,
|
|
473
|
+
repository: a.repositoryName,
|
|
474
|
+
repository_id: a.repositoryId,
|
|
475
|
+
status: "EXECUTED",
|
|
476
|
+
action: a.name,
|
|
477
|
+
path: a.rel,
|
|
478
|
+
checkpoint_id: a.checkpointId,
|
|
479
|
+
before_exists: a.beforeExists,
|
|
480
|
+
after_exists: a.afterExists,
|
|
481
|
+
bytes_before: a.beforeBytes,
|
|
482
|
+
bytes_after: a.afterBytes,
|
|
483
|
+
sha_before: a.beforeSha,
|
|
484
|
+
sha_after: a.afterSha,
|
|
485
|
+
lines_added: a.added,
|
|
486
|
+
lines_removed: a.removed,
|
|
487
|
+
...(a.reverts ? { reverted_operation_id: a.reverts } : {})
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/** Diff lines a plan asks a person to read. */
|
|
491
|
+
export function reviewLineCount(plan) {
|
|
492
|
+
return plan.diff.hunks.reduce((n, h) => n + h.lines.length + 1, 0);
|
|
493
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Hand a URL to the OS default browser.
|
|
5
|
+
*
|
|
6
|
+
* Detached + ignored stdio so the browser never becomes a child whose output
|
|
7
|
+
* bleeds into the transcript or whose lifetime is tied to the shell.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Only http(s) may reach the OS opener. A `file:` or `javascript:` URL must not
|
|
11
|
+
* launch anything just because it arrived in an API response. Callers check this
|
|
12
|
+
* BEFORE announcing the open, so a refusal never reads as a half-done action.
|
|
13
|
+
*
|
|
14
|
+
* @returns the normalized URL, or an error message explaining the refusal.
|
|
15
|
+
*/
|
|
16
|
+
export function checkUrl(url) {
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = new URL(url);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return { ok: false, reason: `Not a valid URL: ${url}` };
|
|
23
|
+
}
|
|
24
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
25
|
+
return { ok: false, reason: `Refusing to open a ${parsed.protocol} URL.` };
|
|
26
|
+
}
|
|
27
|
+
return { ok: true, url: parsed.toString() };
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The program and argv that open `url`, without any shell.
|
|
31
|
+
*
|
|
32
|
+
* Windows used to go through `cmd /c start "" <url>`. cmd.exe parses its whole
|
|
33
|
+
* command line, and `&`, `|` and `^` are legal in a URL query — so a link like
|
|
34
|
+
* `https://example.com/?a=1&calc` from a search result ran `calc`. rundll32
|
|
35
|
+
* hands the URL to the shell's protocol handler as data; nothing parses it as a
|
|
36
|
+
* command. It is named by absolute path under SystemRoot so that no PATH entry
|
|
37
|
+
* or folder can substitute a different `rundll32`.
|
|
38
|
+
*
|
|
39
|
+
* Takes an ALREADY-CHECKED url: callers go through checkUrl first, which only
|
|
40
|
+
* lets http(s) through and percent-encodes spaces and quotes.
|
|
41
|
+
*/
|
|
42
|
+
export function browserLaunchCommand(url, platform = process.platform) {
|
|
43
|
+
if (platform === "win32") {
|
|
44
|
+
const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
45
|
+
return {
|
|
46
|
+
program: path.win32.join(systemRoot, "System32", "rundll32.exe"),
|
|
47
|
+
args: ["url.dll,FileProtocolHandler", url]
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (platform === "darwin")
|
|
51
|
+
return { program: "open", args: [url] };
|
|
52
|
+
return { program: "xdg-open", args: [url] };
|
|
53
|
+
}
|
|
54
|
+
/** Launch detached with no shell and no stdio. Exported for the regression test. */
|
|
55
|
+
export function spawnOpener(program, args) {
|
|
56
|
+
const child = spawn(program, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
|
|
57
|
+
child.on("error", () => {
|
|
58
|
+
/* No browser / headless box — the caller already printed the URL. */
|
|
59
|
+
});
|
|
60
|
+
child.unref();
|
|
61
|
+
}
|
|
62
|
+
export function openUrl(url) {
|
|
63
|
+
const checked = checkUrl(url);
|
|
64
|
+
if (!checked.ok)
|
|
65
|
+
throw new Error(checked.reason);
|
|
66
|
+
const { program, args } = browserLaunchCommand(checked.url);
|
|
67
|
+
spawnOpener(program, args);
|
|
68
|
+
}
|
package/dist/services/output.js
CHANGED
|
@@ -23,12 +23,15 @@ export const errorLine = (msg) => line(`${icon.err} ${msg}`);
|
|
|
23
23
|
export const heading = (text) => line("\n" + c.title(text));
|
|
24
24
|
/** Left-aligned label + value, dim label. Used across whoami / usage / doctor. */
|
|
25
25
|
export function kv(label, value, width = 14) {
|
|
26
|
-
|
|
26
|
+
// A label wider than the column keeps its own separator — without this an
|
|
27
|
+
// over-long label runs straight into its value with no space between them.
|
|
28
|
+
const pad = label.length >= width ? label + " " : label.padEnd(width);
|
|
29
|
+
line(` ${c.label(pad)}${value}`);
|
|
27
30
|
}
|
|
28
31
|
/** The focused-chat header (used by `cos chat`). */
|
|
29
32
|
export function printBanner(_scope, mode, modelLabel) {
|
|
30
33
|
line();
|
|
31
|
-
line(c.
|
|
34
|
+
line(c.brandFixed.bold(" Carrier OS CLI"));
|
|
32
35
|
line(c.dim(" Ready."));
|
|
33
36
|
line();
|
|
34
37
|
kv("Mode", capitalize(mode));
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Am I running as the packaged Windows executable, or from a Node/npm checkout?
|
|
3
|
+
*
|
|
4
|
+
* A Single Executable Application reports this through `node:sea`. Several
|
|
5
|
+
* behaviours differ between the two: a packaged build has no npm to self-update
|
|
6
|
+
* through, no package.json on disk to read a version from, and ships its native
|
|
7
|
+
* helpers prebuilt beside the .exe. Each of those checks this rather than
|
|
8
|
+
* guessing from paths.
|
|
9
|
+
*/
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
export function isPackaged() {
|
|
12
|
+
try {
|
|
13
|
+
// `node:sea` is a Node 20+ builtin; resolving it against the executable
|
|
14
|
+
// path works in both the ESM dev build and the bundled CJS executable.
|
|
15
|
+
const require = createRequire(process.execPath);
|
|
16
|
+
const sea = require("node:sea");
|
|
17
|
+
return typeof sea?.isSea === "function" ? sea.isSea() : false;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Where to point someone at a new packaged build (no npm involved). */
|
|
24
|
+
export const PACKAGED_DOWNLOAD_URL = "https://carrieros.ai/cli";
|