@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.
- package/README.md +142 -57
- 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 +102 -13
- package/dist/commands/context.js +160 -0
- package/dist/commands/doctor.js +53 -8
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +3 -1
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +44 -41
- package/dist/commands/logout.js +13 -4
- 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/scope.js +152 -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/commands/whoami.js +2 -1
- 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 +30 -1
- package/dist/services/api.js +171 -13
- 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 +249 -22
- package/dist/services/context.js +307 -6
- package/dist/services/device-auth.js +261 -0
- 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 +120 -10
- 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 +13 -5
- 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/spinner.js +23 -1
- 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 +1115 -59
- package/dist/shell/shell-commands.js +220 -19
- package/dist/shell/shell-prompt.js +89 -37
- package/dist/shell/shell-renderer.js +19 -38
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +232 -44
- package/dist/types/index.js +3 -1
- package/dist/ui/approval.js +81 -0
- package/dist/ui/banner.js +55 -13
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +87 -0
- package/dist/ui/chat-renderer.js +223 -29
- package/dist/ui/color-picker.js +21 -0
- package/dist/ui/colors.js +9 -1
- package/dist/ui/command-filter.js +40 -5
- package/dist/ui/command-palette.js +122 -62
- package/dist/ui/command-registry.js +85 -11
- 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 +18 -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 +289 -0
- package/dist/ui/select.js +193 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +17 -0
- package/dist/ui/trust.js +93 -0
- package/dist/ui/ui.js +4 -1
- package/package.json +17 -6
- package/dist/ui/activity.js +0 -77
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { MAX_FILES_PER_APPROVAL, MAX_MUTATIONS_PER_TURN, MAX_REVIEW_LINES, MutationError, appliedResult, applyPlan, planMutation, reviewLineCount, rollbackApplied } from "./mutations.js";
|
|
2
|
+
import { inWorkspaceMode } from "./workspace-registry.js";
|
|
3
|
+
const VERB = {
|
|
4
|
+
create_file: "Created",
|
|
5
|
+
write_file: "Overwrote",
|
|
6
|
+
edit_file: "Edited",
|
|
7
|
+
delete_file: "Deleted",
|
|
8
|
+
revert_change: "Reverted"
|
|
9
|
+
};
|
|
10
|
+
export function createMutationCoordinator(opts) {
|
|
11
|
+
const windowMs = opts.windowMs ?? 150;
|
|
12
|
+
const { ui } = opts;
|
|
13
|
+
const queue = [];
|
|
14
|
+
const applied = [];
|
|
15
|
+
let received = 0;
|
|
16
|
+
let timer = null;
|
|
17
|
+
let chain = Promise.resolve();
|
|
18
|
+
let stopped = false;
|
|
19
|
+
const fail = (p, code, message) => opts.submit({
|
|
20
|
+
tool_call_id: p.call.tool_call_id,
|
|
21
|
+
ok: false,
|
|
22
|
+
error: { code, message },
|
|
23
|
+
duration_ms: Date.now() - p.started
|
|
24
|
+
});
|
|
25
|
+
const succeed = (p, change) => opts.submit({
|
|
26
|
+
tool_call_id: p.call.tool_call_id,
|
|
27
|
+
ok: true,
|
|
28
|
+
result: appliedResult(change),
|
|
29
|
+
duration_ms: Date.now() - p.started
|
|
30
|
+
});
|
|
31
|
+
async function review(batch) {
|
|
32
|
+
if (stopped) {
|
|
33
|
+
// A "no" ends proposals for the turn. The model asks the user what they
|
|
34
|
+
// want instead of offering variations until one is accepted.
|
|
35
|
+
await Promise.all(batch.map((p) => fail(p, "MUTATION_REJECTED", "The user already declined a change in this turn. Nothing was changed; ask the user how to proceed.")));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
// Plan everything first. A proposal that cannot be planned is answered
|
|
39
|
+
// straight away — nothing touched disk, so there is nothing to approve.
|
|
40
|
+
const ready = [];
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
for (const p of batch) {
|
|
43
|
+
try {
|
|
44
|
+
const plan = planMutation(p.call);
|
|
45
|
+
// Two repositories can hold the same relative path, so identity here is
|
|
46
|
+
// the repository AND the path.
|
|
47
|
+
const key = `${plan.repositoryId}:${plan.rel.toLowerCase()}`;
|
|
48
|
+
if (seen.has(key)) {
|
|
49
|
+
await fail(p, "CONFLICTING_CHANGE", `${plan.rel} is already changed by another proposal in this step. Propose one change per file.`);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (reviewLineCount(plan) > MAX_REVIEW_LINES) {
|
|
53
|
+
await fail(p, "DIFF_TOO_LARGE", `The change to ${plan.rel} is too large to review. Split it into smaller edits.`);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
seen.add(key);
|
|
57
|
+
ready.push({ p, plan });
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
const e = err instanceof MutationError ? err : new MutationError("TOOL_FAILED", err.message);
|
|
61
|
+
await fail(p, e.code, e.message);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (ready.length === 0)
|
|
65
|
+
return;
|
|
66
|
+
// One approval, one repository.
|
|
67
|
+
//
|
|
68
|
+
// A group is approved as a unit and applied all-or-nothing, and "all" has to
|
|
69
|
+
// mean something a person can hold in their head: these files, in this
|
|
70
|
+
// repository. A group spanning two repositories would ask for one yes
|
|
71
|
+
// covering two boundaries, and a rollback would have to reach across both.
|
|
72
|
+
// It is refused rather than split, because splitting it would decide on the
|
|
73
|
+
// user's behalf which half they meant.
|
|
74
|
+
const repositories = [...new Set(ready.map((r) => r.plan.repositoryId))];
|
|
75
|
+
if (repositories.length > 1) {
|
|
76
|
+
const names = [...new Set(ready.map((r) => r.plan.repositoryName))].join(", ");
|
|
77
|
+
ui.note([` ⊘ One change group cannot span ${names} — nothing was changed.`]);
|
|
78
|
+
await Promise.all(ready.map((r) => fail(r.p, "MULTI_REPOSITORY_MUTATION_NOT_ALLOWED", `A single change cannot span more than one repository (${names}). Nothing was changed. Propose the changes for each repository as a separate operation.`)));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const decision = await ui.review(ready.map((r) => r.plan));
|
|
82
|
+
if (decision !== "approve") {
|
|
83
|
+
const code = decision === "timeout" ? "APPROVAL_TIMEOUT" : "MUTATION_REJECTED";
|
|
84
|
+
const message = decision === "timeout"
|
|
85
|
+
? "No one approved the change in time. Nothing was changed."
|
|
86
|
+
: "The user rejected the change. Nothing was changed.";
|
|
87
|
+
ui.note([decision === "timeout" ? " ⊘ Approval timed out — nothing changed." : " ⊘ Rejected — nothing changed."]);
|
|
88
|
+
stopped = true;
|
|
89
|
+
await Promise.all(ready.map((r) => fail(r.p, code, message)));
|
|
90
|
+
if (decision === "cancel")
|
|
91
|
+
ui.cancelTurn();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
// Approved: apply in order, all or nothing.
|
|
95
|
+
const done = [];
|
|
96
|
+
for (let i = 0; i < ready.length; i += 1) {
|
|
97
|
+
const { p, plan } = ready[i];
|
|
98
|
+
try {
|
|
99
|
+
done.push({ p, change: applyPlan(plan) });
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
const e = err instanceof MutationError ? err : new MutationError("WRITE_FAILED", err.message);
|
|
103
|
+
for (const d of [...done].reverse())
|
|
104
|
+
rollbackApplied(d.change);
|
|
105
|
+
ui.note([` ✗ ${plan.rel}: ${e.message}`, ...(done.length ? [" ↺ Earlier changes in this group were rolled back."] : [])]);
|
|
106
|
+
await Promise.all([
|
|
107
|
+
...done.map((d) => fail(d.p, "ROLLED_BACK", `Rolled back because the change to ${plan.rel} failed.`)),
|
|
108
|
+
fail(p, e.code, e.message),
|
|
109
|
+
...ready.slice(i + 1).map((r) => fail(r.p, "NOT_APPLIED", `Not applied because the change to ${plan.rel} failed.`))
|
|
110
|
+
]);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
applied.push(...done.map((d) => d.change));
|
|
115
|
+
ui.note(done.map((d) => {
|
|
116
|
+
// Say WHICH repository once the workspace has more than one; in a single
|
|
117
|
+
// repository the name would be noise on every line.
|
|
118
|
+
const where = inWorkspaceMode() ? `${d.change.repositoryName}/` : "";
|
|
119
|
+
return ` ✓ ${VERB[d.change.name] ?? "Changed"} ${where}${d.change.rel} (+${d.change.added} −${d.change.removed})`;
|
|
120
|
+
}));
|
|
121
|
+
await Promise.all(done.map((d) => succeed(d.p, d.change)));
|
|
122
|
+
}
|
|
123
|
+
function flush() {
|
|
124
|
+
timer = null;
|
|
125
|
+
const batch = queue.splice(0, MAX_FILES_PER_APPROVAL);
|
|
126
|
+
if (queue.length)
|
|
127
|
+
timer = setTimeout(flush, 0);
|
|
128
|
+
chain = chain
|
|
129
|
+
.then(() => review(batch))
|
|
130
|
+
.catch(async () => {
|
|
131
|
+
// A failure here is a bug, not a decision — never leave a call unanswered.
|
|
132
|
+
await Promise.all(batch.map((p) => fail(p, "TOOL_FAILED", "The change could not be processed.").catch(() => undefined)));
|
|
133
|
+
})
|
|
134
|
+
.finally(() => batch.forEach((p) => p.done()));
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
applied,
|
|
138
|
+
handle(call) {
|
|
139
|
+
const started = Date.now();
|
|
140
|
+
received += 1;
|
|
141
|
+
if (received > MAX_MUTATIONS_PER_TURN) {
|
|
142
|
+
return opts
|
|
143
|
+
.submit({
|
|
144
|
+
tool_call_id: call.tool_call_id,
|
|
145
|
+
ok: false,
|
|
146
|
+
error: {
|
|
147
|
+
code: "MUTATION_LIMIT_REACHED",
|
|
148
|
+
message: `At most ${MAX_MUTATIONS_PER_TURN} file changes can be proposed in one turn.`
|
|
149
|
+
},
|
|
150
|
+
duration_ms: 0
|
|
151
|
+
})
|
|
152
|
+
.catch(() => undefined);
|
|
153
|
+
}
|
|
154
|
+
return new Promise((resolve) => {
|
|
155
|
+
queue.push({ call, started, done: resolve });
|
|
156
|
+
if (!timer)
|
|
157
|
+
timer = setTimeout(flush, windowMs);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
@@ -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
|
+
}
|