@carrieros/cli 0.3.0 → 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.
Files changed (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -0,0 +1,59 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { executionPlatform } from "./execution-platform.js";
4
+ /** Supported administrator-installed Docker CLI locations. No PATH or executable override. */
5
+ export function supportedDockerPaths(platform) {
6
+ if (platform === "darwin")
7
+ return ["/Applications/Docker.app/Contents/Resources/bin/docker", "/opt/homebrew/bin/docker", "/usr/local/bin/docker"];
8
+ if (platform === "linux")
9
+ return ["/usr/bin/docker", "/usr/local/bin/docker"];
10
+ return [];
11
+ }
12
+ export function supportedDockerTarget(platform, target) {
13
+ if (platform === "linux")
14
+ return ["/usr/bin/docker", "/usr/local/bin/docker"].includes(target);
15
+ if (platform !== "darwin")
16
+ return false;
17
+ return target === "/Applications/Docker.app/Contents/Resources/bin/docker" ||
18
+ /^\/(opt\/homebrew|usr\/local)\/Cellar\/docker\/[0-9][A-Za-z0-9._-]*\/bin\/docker$/.test(target);
19
+ }
20
+ /** Installation and local administrators are trusted, as for the CLI itself.
21
+ * This rejects project wrappers/scripts, arbitrary paths and unsafe writable binaries;
22
+ * it is not package-signature attestation against a compromised administrator.
23
+ */
24
+ export function installedDocker() {
25
+ const platform = executionPlatform();
26
+ for (const candidate of supportedDockerPaths(platform)) {
27
+ try {
28
+ const target = fs.realpathSync(candidate);
29
+ if (!supportedDockerTarget(platform, target))
30
+ continue;
31
+ const info = fs.statSync(target);
32
+ if (!info.isFile() || (info.mode & 0o022) || ![0, process.getuid?.()].includes(info.uid))
33
+ continue;
34
+ fs.accessSync(target, fs.constants.X_OK);
35
+ let directory = path.dirname(target);
36
+ while (directory !== path.dirname(directory)) {
37
+ // Package-manager directories may be writable by the administrator group.
38
+ if (fs.statSync(directory).mode & 0o002)
39
+ throw new Error("world writable installation");
40
+ directory = path.dirname(directory);
41
+ }
42
+ const fd = fs.openSync(target, "r");
43
+ const header = Buffer.alloc(4);
44
+ try {
45
+ if (fs.readSync(fd, header, 0, 4, 0) !== 4)
46
+ continue;
47
+ }
48
+ finally {
49
+ fs.closeSync(fd);
50
+ }
51
+ const magic = header.toString("hex");
52
+ if (platform === "linux" ? magic !== "7f454c46" : !["cffaedfe", "feedfacf", "cafebabe", "bebafeca", "cafebabf", "bfbafeca"].includes(magic))
53
+ continue;
54
+ return target;
55
+ }
56
+ catch { /* Try only the next supported installation, never PATH. */ }
57
+ }
58
+ throw Object.assign(new Error("Install the supported Docker CLI using Docker Desktop/Homebrew on macOS or the system Docker Engine package on Linux. Arbitrary runtime executables are not supported."), { code: "ISOLATION_UNAVAILABLE" });
59
+ }
@@ -0,0 +1,212 @@
1
+ import crypto from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { ConfigStore } from "./config.js";
6
+ import { activeRepository, resolveRepository } from "./workspace-registry.js";
7
+ /**
8
+ * Local freshness record for Task Context.
9
+ *
10
+ * The server keeps the durable task context (a projection over the recorded
11
+ * tool calls). What it cannot know is what happened to the user's files
12
+ * BETWEEN turns. This records, per conversation, the sha256 of each file a
13
+ * coding turn read or changed — taken from disk when the turn ends — and at
14
+ * the start of the next turn reports which of them are unchanged, changed or
15
+ * missing now.
16
+ *
17
+ * It is a hint, never authority. Nothing here lets a turn skip a read: the
18
+ * model must still read files in the new turn, and the CodingWorkflow and
19
+ * MutationCoordinator keep their own fresh-read and current-byte checks. No
20
+ * file content is stored, only paths and hashes.
21
+ *
22
+ * Scoped like the result outbox and mutation recovery: by the CLI owner scope
23
+ * (API origin + user + device session + session version), so another account
24
+ * or a new login on this machine never sees it.
25
+ */
26
+ export const TASK_FILE_LIMIT = 40;
27
+ const HASH_LIMIT_BYTES = 5 * 1024 * 1024;
28
+ const MUTATION_TOOLS = new Set(["create_file", "write_file", "edit_file", "delete_file", "revert_change"]);
29
+ function git(root, args) {
30
+ try {
31
+ return execFileSync("git", ["-C", root, ...args], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], windowsHide: true }).trim() || null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /** The repository's identity: its first commit survives renames and moves; the root path and branch are informative. */
38
+ export function repositoryIdentity(repo) {
39
+ const branch = git(repo.root, ["rev-parse", "--abbrev-ref", "HEAD"]);
40
+ const rootCommit = git(repo.root, ["rev-list", "--max-parents=0", "HEAD"])?.split("\n")[0] ?? null;
41
+ return { id: repo.id, name: repo.name, root: repo.root, branch: branch === "HEAD" ? null : branch, rootCommit };
42
+ }
43
+ const hash = (value) => crypto.createHash("sha256").update(value).digest("hex");
44
+ function ledgerFile(scope, conversationId) {
45
+ return path.join(ConfigStore.resolveDir(), "task-context", hash(scope), hash(conversationId) + ".json");
46
+ }
47
+ /** Realpath-contained file inside the repository root, or null. */
48
+ function contained(root, rel) {
49
+ if (!rel || path.isAbsolute(rel))
50
+ return null;
51
+ const realRoot = (() => { try {
52
+ return fs.realpathSync.native(root);
53
+ }
54
+ catch {
55
+ return null;
56
+ } })();
57
+ if (!realRoot)
58
+ return null;
59
+ const target = path.resolve(realRoot, rel);
60
+ if (target !== realRoot && !target.startsWith(realRoot + path.sep))
61
+ return null;
62
+ try {
63
+ const real = fs.realpathSync.native(target);
64
+ return real.startsWith(realRoot + path.sep) ? real : null;
65
+ }
66
+ catch {
67
+ return target; // missing now; still inside the root lexically
68
+ }
69
+ }
70
+ /** sha256 of the file's current bytes; null when missing, unreadable or too large to hash. */
71
+ function currentSha(root, rel) {
72
+ const file = contained(root, rel);
73
+ if (!file)
74
+ return null;
75
+ try {
76
+ const stat = fs.statSync(file);
77
+ if (!stat.isFile() || stat.size > HASH_LIMIT_BYTES)
78
+ return null;
79
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
80
+ }
81
+ catch (err) {
82
+ return err.code === "ENOENT" ? "missing" : null;
83
+ }
84
+ }
85
+ function readSavedFile(file) {
86
+ try {
87
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
88
+ if (data.version !== 1 || !Array.isArray(data.entries))
89
+ return { version: 1, entries: [] };
90
+ const entries = data.entries.filter((e) => e && typeof e.root === "string" && typeof e.rel === "string" && typeof e.repo === "string").slice(0, TASK_FILE_LIMIT);
91
+ const r = data.repository;
92
+ const repository = r && typeof r.id === "string" && typeof r.name === "string" && typeof r.root === "string" ? r : undefined;
93
+ return { version: 1, entries, ...(repository ? { repository } : {}) };
94
+ }
95
+ catch {
96
+ return { version: 1, entries: [] };
97
+ }
98
+ }
99
+ const readSaved = (file) => readSavedFile(file).entries;
100
+ function writeSaved(file, entries, repository) {
101
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
102
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
103
+ const fd = fs.openSync(tmp, "wx", 0o600);
104
+ try {
105
+ fs.writeFileSync(fd, JSON.stringify({ version: 1, entries, ...(repository ? { repository } : {}) }));
106
+ fs.fsyncSync(fd);
107
+ }
108
+ finally {
109
+ fs.closeSync(fd);
110
+ }
111
+ fs.renameSync(tmp, file);
112
+ }
113
+ /** What a coding turn touched, collected while it runs and saved when it ends. */
114
+ export class TaskFileLedger {
115
+ touched = new Map();
116
+ /** Record a successful read or change. Unknown repositories and unsafe paths are ignored. */
117
+ touch(toolName, args) {
118
+ if (toolName !== "read_file" && !MUTATION_TOOLS.has(toolName))
119
+ return;
120
+ const rawPath = typeof args?.path === "string" ? args.path : undefined;
121
+ if (!rawPath)
122
+ return;
123
+ let repo;
124
+ try {
125
+ repo = resolveRepository(args?.repository);
126
+ }
127
+ catch {
128
+ return;
129
+ }
130
+ const rel = path.normalize(rawPath).replace(/^(\.\/|\.\\)+/, "");
131
+ if (!contained(repo.root, rel))
132
+ return;
133
+ if (this.touched.size >= TASK_FILE_LIMIT * 2 && !this.touched.has(`${repo.id}\0${rel}`))
134
+ return;
135
+ this.touched.set(`${repo.id}\0${rel}`, { repo: repo.id, repoName: repo.name, root: repo.root, rel });
136
+ }
137
+ /** The coordinator's applied changes — created, modified or deleted files —
138
+ * never a proposal that was refused, rejected or not applied. */
139
+ touchApplied(applied) {
140
+ for (const a of applied)
141
+ this.touch(a.name, { path: a.rel, repository: a.repositoryName });
142
+ }
143
+ get size() {
144
+ return this.touched.size;
145
+ }
146
+ /**
147
+ * Save the turn's files with the hash they have NOW, newest first, merged
148
+ * with what earlier turns of this conversation recorded; bounded.
149
+ */
150
+ commit(scope, conversationId, now = Date.now()) {
151
+ if (!scope || !conversationId || !this.touched.size)
152
+ return;
153
+ const file = ledgerFile(scope, conversationId);
154
+ const fresh = [...this.touched.values()].map((t) => {
155
+ const sha = currentSha(t.root, t.rel);
156
+ return { repo: t.repo, root: t.root, rel: t.rel, sha: sha === "missing" ? null : sha, at: now };
157
+ });
158
+ const keys = new Set(fresh.map((e) => `${e.repo}\0${e.rel}`));
159
+ const merged = [...fresh, ...readSaved(file).filter((e) => !keys.has(`${e.repo}\0${e.rel}`))].slice(0, TASK_FILE_LIMIT);
160
+ // The repository the latest work happened in (the first touched file's).
161
+ const first = [...this.touched.values()][0];
162
+ const repository = first ? repositoryIdentity({ id: first.repo, name: first.repoName, root: first.root }) : undefined;
163
+ try {
164
+ writeSaved(file, merged, repository);
165
+ }
166
+ catch { /* best effort: freshness is a hint */ }
167
+ }
168
+ }
169
+ /**
170
+ * Which previously inspected files changed on disk since the conversation's
171
+ * last coding turn. Paths are repository-relative; a file in a repository other
172
+ * than the active one is prefixed with that repository's name.
173
+ */
174
+ export function repositoryState(scope, conversationId) {
175
+ if (!scope || !conversationId)
176
+ return [];
177
+ let active;
178
+ try {
179
+ active = activeRepository()?.id;
180
+ }
181
+ catch {
182
+ active = undefined;
183
+ }
184
+ return readSaved(ledgerFile(scope, conversationId)).map((e) => {
185
+ const now = currentSha(e.root, e.rel);
186
+ const status = now === "missing" ? "missing" : now !== null && e.sha !== null && now === e.sha ? "unchanged" : "changed";
187
+ const shown = e.repo === active ? e.rel : `${path.basename(e.root)}/${e.rel}`;
188
+ return { path: shown.split(path.sep).join("/").slice(0, 300), status };
189
+ });
190
+ }
191
+ /**
192
+ * Is this turn in the same repository the conversation's earlier coding work
193
+ * used? Same root commit (or, for a repository with no commits yet, the same
194
+ * root path) — true; a different one — false; nothing recorded — null. A
195
+ * different repository means the earlier context must not be treated as
196
+ * describing this code.
197
+ */
198
+ export function repositoryContext(scope, conversationId) {
199
+ let active;
200
+ try {
201
+ active = activeRepository();
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ if (!active)
207
+ return null;
208
+ const now = repositoryIdentity(active);
209
+ const saved = scope && conversationId ? readSavedFile(ledgerFile(scope, conversationId)).repository : undefined;
210
+ const same = !saved ? null : saved.rootCommit && now.rootCommit ? saved.rootCommit === now.rootCommit : saved.root === now.root;
211
+ return { name: now.name, branch: now.branch, same_repository: same };
212
+ }
@@ -0,0 +1,38 @@
1
+ const LIST = 6;
2
+ export function taskSnapshot(context) {
3
+ const t = context?.current;
4
+ if (!t)
5
+ return null;
6
+ const files = t.changes.files ?? { created: [], modified: [], deleted: [] };
7
+ const runs = t.validation.runs;
8
+ return {
9
+ title: t.title,
10
+ repository: t.repository,
11
+ status: t.workflow_state ?? t.verified_state,
12
+ verified: t.verified_state,
13
+ plan: t.plan.summary,
14
+ inspected: { files: t.investigation.files.slice(0, LIST), total: t.investigation.files.length + t.investigation.files_omitted },
15
+ investigation: {
16
+ searches: t.investigation.searches.length + t.investigation.searches_omitted,
17
+ symbols: (t.investigation.symbols_traced ?? []).slice(0, LIST),
18
+ relationships: (t.investigation.relationships ?? []).slice(0, LIST),
19
+ outlines: t.investigation.outlines ?? 0
20
+ },
21
+ rootCause: t.root_cause,
22
+ symptom: t.plan.investigation?.symptom ?? null,
23
+ changeLocation: t.plan.investigation?.change_location ?? null,
24
+ executionPath: (t.plan.investigation?.execution_path ?? []).slice(0, 8),
25
+ evidence: (t.plan.investigation?.evidence ?? []).slice(0, 4).map((e) => `${e.path ?? "?"}${e.lines ? `:${e.lines}` : ""}${e.note ? ` — ${e.note}` : ""}`),
26
+ ruledOut: (t.plan.investigation?.ruled_out ?? []).slice(0, 4).map((r) => `${r.path ?? "?"}${r.reason ? ` — ${r.reason}` : ""}`),
27
+ modified: files.modified.slice(0, LIST),
28
+ created: files.created.slice(0, LIST),
29
+ deleted: files.deleted.slice(0, LIST),
30
+ unresolved: [...new Set(t.changes.items.filter((c) => c.outcome === "unresolved").map((c) => c.path ?? "?"))].slice(0, LIST),
31
+ pendingOperations: t.pending_operations.slice(0, LIST),
32
+ corrections: t.corrections_total,
33
+ lastCorrection: t.corrections.at(-1)?.explanation ?? null,
34
+ tests: runs.slice(-LIST).map((r) => ({ command: r.command ?? "test", outcome: r.outcome })),
35
+ passed: runs.filter((r) => r.outcome === "passed").length,
36
+ failed: runs.filter((r) => r.outcome === "failed").length
37
+ };
38
+ }
@@ -0,0 +1,195 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { ConfigStore } from "./config.js";
5
+ import { isSealed, seal, sealingAvailable, sealingRequired, unseal } from "./secure-store.js";
6
+ const TTL = 16 * 60 * 1000; // Recovery never extends the server's deadline.
7
+ const MAX_ENTRIES = 100;
8
+ const MAX_BYTES = 2 * 1024 * 1024;
9
+ const hash = (s) => crypto.createHash("sha256").update(s).digest("hex");
10
+ export class ToolDeliveryError extends Error {
11
+ code = "TOOL_RESULT_DELIVERY_FAILED";
12
+ constructor(message = "Tool result delivery failed. Any saved result will be retried before the next chat; the tool will not be rerun.") { super(message); this.name = "ToolDeliveryError"; }
13
+ }
14
+ /** Only routing metadata, never credentials, goes into the directory name.
15
+ * JWT claims are NOT authorization: the server still enforces every binding. */
16
+ export function toolResultScope(apiUrl, token) {
17
+ let identity = hash(token); // legacy/opaque credentials: exact token only
18
+ try {
19
+ const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
20
+ if (claims.realm === 'carrier-cli' && claims.typ === 'cli_access' &&
21
+ ['sub', 'uid', 'sid'].every(k => typeof claims[k] === 'string' && claims[k].length > 0) &&
22
+ claims.sub === claims.uid && Number.isSafeInteger(claims.sv) && claims.sv >= 0 &&
23
+ claims.wsid == null && claims.pid == null && claims.developer_account_id == null) {
24
+ // Version the new realm without changing the legacy hash or moving files.
25
+ // Access-token renewal retains the session; a new login never inherits it.
26
+ identity = ['user-cli', 2, claims.uid, claims.sid, claims.sv];
27
+ }
28
+ else if (claims.realm !== 'carrier-cli' && claims.typ === 'cli_access' && ['sub', 'uid', 'sid'].every(k => typeof claims[k] === 'string') &&
29
+ ['wsid', 'pid'].every(k => typeof claims[k] === 'string' || claims[k] === null)) {
30
+ identity = [claims.sub, claims.uid, claims.sid, claims.wsid, claims.pid, claims.tv ?? 0];
31
+ }
32
+ }
33
+ catch { /* opaque credentials stay bound to their exact token */ }
34
+ return hash(JSON.stringify([new URL(apiUrl).origin, identity]));
35
+ }
36
+ /** Same canonical payload identity as the backend; transport timing is excluded. */
37
+ export function resultHash(payload) {
38
+ const canonical = (v) => Array.isArray(v) ? `[${v.map(canonical).join(",")}]`
39
+ : v && typeof v === "object" ? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
40
+ : JSON.stringify(v ?? null);
41
+ return hash(canonical(payload.ok ? { ok: true, result: payload.result } : { ok: false,
42
+ error: { code: payload.error.code.slice(0, 64), message: String(payload.error.message ?? "").slice(0, 500) } }));
43
+ }
44
+ /** Completed results only. Never stores executable work or starts an agent turn. */
45
+ export class ToolResultOutbox {
46
+ dir;
47
+ constructor(scope) {
48
+ this.dir = path.join(ConfigStore.resolveDir(), 'tool-result-outbox', scope);
49
+ }
50
+ file(id) { return path.join(this.dir, hash(id) + '.json'); }
51
+ read(file) {
52
+ try {
53
+ if (fs.statSync(file).size > MAX_BYTES * 2)
54
+ throw new Error();
55
+ const stored = fs.readFileSync(file, 'utf8');
56
+ const entry = JSON.parse(isSealed(stored) ? unseal(stored) : stored);
57
+ if (entry.version !== 1 || !Number.isFinite(entry.createdAt) || !entry.payload ||
58
+ typeof entry.payload.tool_call_id !== 'string' || typeof entry.payload.ok !== 'boolean' ||
59
+ this.file(entry.payload.tool_call_id) !== file)
60
+ throw new Error();
61
+ return entry;
62
+ }
63
+ catch {
64
+ throw new ToolDeliveryError('Saved tool result is unreadable. It was preserved; recovery cannot continue.');
65
+ }
66
+ }
67
+ put(payload, createdAt = Date.now()) {
68
+ try {
69
+ const serialized = JSON.stringify(payload);
70
+ if (Buffer.byteLength(serialized) > MAX_BYTES)
71
+ throw new ToolDeliveryError('Tool result exceeds the recovery storage limit. Nothing was submitted.');
72
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
73
+ const file = this.file(payload.tool_call_id);
74
+ // A completed payload may have been removed, but its durable identity
75
+ // remains authoritative. Validate it before publishing any new bytes.
76
+ if (fs.existsSync(file + '.state')) {
77
+ this.state(payload.tool_call_id); // validates the marker and existing payload
78
+ const marker = JSON.parse(fs.readFileSync(file + '.state', 'utf8'));
79
+ if (!marker.hash || marker.hash !== resultHash(payload)) {
80
+ throw new ToolDeliveryError('Saved delivery identity conflicts with this result. Original evidence was preserved.');
81
+ }
82
+ }
83
+ if (fs.existsSync(file)) {
84
+ if (JSON.stringify(this.read(file).payload) !== serialized)
85
+ throw new ToolDeliveryError('A different result is already saved for this tool call. The original was preserved.');
86
+ return;
87
+ }
88
+ if (fs.readdirSync(this.dir).filter(f => f.endsWith('.json')).length >= MAX_ENTRIES)
89
+ throw new ToolDeliveryError('Tool result recovery storage is full. Pending results were preserved.');
90
+ if (!Number.isFinite(createdAt) || createdAt > Date.now())
91
+ throw new ToolDeliveryError();
92
+ const entry = JSON.stringify({ version: 1, createdAt, payload });
93
+ if (sealingRequired() && !sealingAvailable())
94
+ throw new ToolDeliveryError('Secure tool result storage is unavailable. Nothing was submitted.');
95
+ const data = sealingAvailable() ? seal(entry) : entry;
96
+ const tmp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
97
+ try {
98
+ const fd = fs.openSync(tmp, 'wx', 0o600);
99
+ try {
100
+ fs.writeFileSync(fd, data);
101
+ fs.fsyncSync(fd);
102
+ }
103
+ finally {
104
+ fs.closeSync(fd);
105
+ }
106
+ // Link publishes without overwriting another process's immutable result.
107
+ try {
108
+ fs.linkSync(tmp, file);
109
+ }
110
+ catch (e) {
111
+ if (e.code !== 'EEXIST')
112
+ throw e;
113
+ if (JSON.stringify(this.read(file).payload) !== serialized)
114
+ throw new ToolDeliveryError('A different result is already saved for this tool call.');
115
+ }
116
+ }
117
+ finally {
118
+ try {
119
+ fs.unlinkSync(tmp);
120
+ }
121
+ catch { /* interrupted before creation */ }
122
+ }
123
+ }
124
+ catch (e) {
125
+ if (e instanceof ToolDeliveryError)
126
+ throw e;
127
+ throw new ToolDeliveryError('Could not safely save the tool result for recovery. Nothing was submitted.');
128
+ }
129
+ }
130
+ expired(id) { return Date.now() - this.read(this.file(id)).createdAt > TTL; }
131
+ state(id) {
132
+ const file = this.file(id) + '.state';
133
+ if (!fs.existsSync(file))
134
+ return 'pending';
135
+ try {
136
+ const stat = fs.lstatSync(file);
137
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096)
138
+ throw new Error();
139
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
140
+ if (value.id !== id || !['pending', 'submitting', 'acknowledged', 'rejected', 'expired', 'unresolved'].includes(value.state))
141
+ throw new Error();
142
+ if (value.hash && fs.existsSync(this.file(id)) && resultHash(this.read(this.file(id)).payload) !== value.hash)
143
+ throw new Error();
144
+ return value.state;
145
+ }
146
+ catch {
147
+ throw new ToolDeliveryError('Saved delivery state is unreadable; evidence was preserved.');
148
+ }
149
+ }
150
+ mark(id, state) {
151
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
152
+ const file = this.file(id) + '.state', tmp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
153
+ try {
154
+ const payloadHash = fs.existsSync(this.file(id)) ? resultHash(this.read(this.file(id)).payload) : null;
155
+ const fd = fs.openSync(tmp, 'wx', 0o600);
156
+ try {
157
+ fs.writeFileSync(fd, JSON.stringify({ id, state, hash: payloadHash }));
158
+ fs.fsyncSync(fd);
159
+ }
160
+ finally {
161
+ fs.closeSync(fd);
162
+ }
163
+ fs.renameSync(tmp, file);
164
+ }
165
+ finally {
166
+ try {
167
+ fs.unlinkSync(tmp);
168
+ }
169
+ catch { }
170
+ }
171
+ }
172
+ remove(id) { fs.rmSync(this.file(id), { force: true }); }
173
+ pending() {
174
+ if (!fs.existsSync(this.dir))
175
+ return { entries: [], expired: 0 };
176
+ const entries = [];
177
+ let expired = 0;
178
+ for (const name of fs.readdirSync(this.dir).filter(f => f.endsWith('.json'))) {
179
+ const entry = this.read(path.join(this.dir, name));
180
+ const state = this.state(entry.payload.tool_call_id);
181
+ if (['acknowledged', 'rejected', 'expired', 'unresolved'].includes(state))
182
+ continue;
183
+ if (Date.now() - entry.createdAt > TTL && state !== 'submitting') {
184
+ this.mark(entry.payload.tool_call_id, 'expired');
185
+ expired++;
186
+ }
187
+ else
188
+ entries.push(entry);
189
+ }
190
+ return { entries, expired };
191
+ }
192
+ }
193
+ export function terminalToolRejection(error) {
194
+ return [400, 403, 404, 409, 410, 413, 422].includes(error?.status ?? 0);
195
+ }
@@ -52,16 +52,21 @@ export function getCurrentVersion() {
52
52
  *
53
53
  * Lexical comparison gets 0.10.0 vs 0.9.0 wrong — the case that appears the
54
54
  * moment a project passes its ninth minor. Prereleases sort BELOW their release
55
- * (1.0.0-rc.1 < 1.0.0); identifiers compare as strings, which covers -rc.N and
56
- * -beta.N without taking on a semver dependency.
55
+ * (1.0.0-rc.1 < 1.0.0). Numeric prerelease identifiers compare numerically and
56
+ * sort below nonnumeric identifiers. Build metadata does not affect precedence.
57
57
  */
58
58
  export function compareVersions(a, b) {
59
59
  const parse = (v) => {
60
- const [core, ...rest] = String(v).trim().replace(/^v/, "").split("-");
61
- const nums = core.split(".").map((n) => Number.parseInt(n, 10) || 0);
62
- while (nums.length < 3)
63
- nums.push(0);
64
- return { nums, pre: rest.join("-") };
60
+ const normalized = String(v).trim().replace(/^v/, "");
61
+ if (!isVersionLike(normalized))
62
+ throw new Error(`Invalid version: ${v}`);
63
+ const version = normalized.split("+", 1)[0];
64
+ const dash = version.indexOf("-");
65
+ const core = dash === -1 ? version : version.slice(0, dash);
66
+ return {
67
+ nums: core.split(".").map((n) => BigInt(n)),
68
+ pre: dash === -1 ? [] : version.slice(dash + 1).split(".")
69
+ };
65
70
  };
66
71
  const x = parse(a);
67
72
  const y = parse(b);
@@ -69,17 +74,37 @@ export function compareVersions(a, b) {
69
74
  if (x.nums[i] !== y.nums[i])
70
75
  return x.nums[i] < y.nums[i] ? -1 : 1;
71
76
  }
72
- if (x.pre === y.pre)
77
+ if (!x.pre.length && !y.pre.length)
73
78
  return 0;
74
- if (!x.pre)
79
+ if (!x.pre.length)
75
80
  return 1;
76
- if (!y.pre)
81
+ if (!y.pre.length)
77
82
  return -1;
78
- return x.pre < y.pre ? -1 : 1;
83
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
84
+ const left = x.pre[i];
85
+ const right = y.pre[i];
86
+ if (left === undefined)
87
+ return -1;
88
+ if (right === undefined)
89
+ return 1;
90
+ if (left === right)
91
+ continue;
92
+ const leftNumeric = /^\d+$/.test(left);
93
+ const rightNumeric = /^\d+$/.test(right);
94
+ if (leftNumeric && rightNumeric)
95
+ return BigInt(left) < BigInt(right) ? -1 : 1;
96
+ if (leftNumeric !== rightNumeric)
97
+ return leftNumeric ? -1 : 1;
98
+ return left < right ? -1 : 1;
99
+ }
100
+ return 0;
79
101
  }
80
102
  /** Guards every version that reaches a comparison or a message. */
81
103
  export function isVersionLike(v) {
82
- return typeof v === "string" && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(v.trim());
104
+ if (typeof v !== "string")
105
+ return false;
106
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(v.trim());
107
+ return !!match && (!match[4] || match[4].split(".").every((id) => !/^\d+$/.test(id) || id === "0" || !id.startsWith("0")));
83
108
  }
84
109
  export function getLatestVersion() {
85
110
  let res;
@@ -1,3 +1,4 @@
1
+ import { isTrustedFolder } from "./folder-key.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { describeRepository, getCurrentDirectory, getWorkspace } from "./workspace.js";
@@ -254,9 +255,9 @@ export function repositoryForPath(absolutePath) {
254
255
  }
255
256
  /** Trust is per repository: registering a workspace grants nothing. */
256
257
  export function repositoryTrust(handle) {
257
- const folders = config?.get("trustedFolders") ?? [];
258
- const key = process.platform === "win32" ? path.resolve(handle.root).toLowerCase() : path.resolve(handle.root);
259
- return folders.some((f) => (process.platform === "win32" ? f.toLowerCase() : f) === key) ? "trusted" : "untrusted";
258
+ // The same canonical comparison as the trust prompt (ui/trust.ts), so a
259
+ // folder trusted under one spelling is the same folder here.
260
+ return isTrustedFolder(config?.get("trustedFolders") ?? [], handle.root) ? "trusted" : "untrusted";
260
261
  }
261
262
  /**
262
263
  * Resolve a repository that an operation may ACT on — a change or a command.
@@ -44,12 +44,19 @@ const MAX_MANIFEST_BYTES = 1024 * 1024;
44
44
  * ones — `status` rejects them — so the diff-driver keys are neutralized as
45
45
  * config overrides instead (see neutralizingOverrides).
46
46
  */
47
+ /**
48
+ * A hooks directory that cannot hold hooks. `NUL` is a device only on Windows;
49
+ * elsewhere it is an ordinary relative folder a repository can ship hooks in.
50
+ * Commands on macOS/Linux run git there or in the Linux container, so both use
51
+ * /dev/null.
52
+ */
53
+ export const GIT_NO_HOOKS_PATH = process.platform === "win32" ? "NUL" : "/dev/null";
47
54
  export const HARDENED_GIT_OPTIONS = [
48
55
  "--no-pager",
49
56
  "-c",
50
57
  "core.fsmonitor=false",
51
58
  "-c",
52
- "core.hooksPath=NUL",
59
+ `core.hooksPath=${GIT_NO_HOOKS_PATH}`,
53
60
  "-c",
54
61
  "diff.external="
55
62
  ];