@carrieros/cli-staging 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -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
+ }