toolroll 0.9.116 → 0.9.118

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/CHANGELOG.md +46 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +93 -16
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +12 -2
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
@@ -0,0 +1,280 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { mintApiToken } from "./api-tokens.js";
3
+ import { html, htmlString, postForm, scriptElement } from "./html.js";
4
+ import { credentialProof, freshFacts, proveAccountNow } from "./scope.js";
5
+ import { KEY_FILL_SCRIPT } from "./server/mutation-key.js";
6
+ import { withFormToken } from "./server/request-context.js";
7
+ const PAIR_TTL_MS = 5 * 60_000;
8
+ const MAX_PENDING_PAIRS = 64;
9
+ const TOKEN_TTL_MS = 90 * 24 * 60 * 60_000;
10
+ const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
11
+ const PAIR_CODE_PATH = /^\/connect\/pair\/([A-Z2-9]{4}-[A-Z2-9]{4})$/;
12
+ const POLL_SECRET_RE = /^[a-f0-9]{64}$/;
13
+ const MAX_BODY_BYTES = 8 * 1024;
14
+ const FORBIDDEN_CLI_HEADERS = ["cookie", "origin", "referer", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest", "sec-fetch-user"];
15
+ function sendJson(response, status, body, extraHeaders = {}) {
16
+ const payload = JSON.stringify(body);
17
+ response.writeHead(status, {
18
+ "content-type": "application/json; charset=utf-8",
19
+ "cache-control": "no-store",
20
+ "content-length": String(Buffer.byteLength(payload)),
21
+ ...extraHeaders,
22
+ });
23
+ response.end(payload);
24
+ }
25
+ function sendHtml(response, status, markup, fillKey = false) {
26
+ const nonce = fillKey ? randomBytes(16).toString("base64") : null;
27
+ const raw = htmlString(markup);
28
+ const body = nonce === null ? raw : raw.replace(/<\/body><\/html>$/, `${htmlString(scriptElement(KEY_FILL_SCRIPT, { nonce }))}</body></html>`);
29
+ response.writeHead(status, {
30
+ "content-type": "text/html; charset=utf-8",
31
+ "cache-control": "no-store",
32
+ "x-content-type-options": "nosniff",
33
+ "x-frame-options": "DENY",
34
+ "referrer-policy": "no-referrer",
35
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline';${nonce === null ? "" : ` script-src 'nonce-${nonce}';`} form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
36
+ "content-length": String(Buffer.byteLength(body)),
37
+ });
38
+ response.end(body);
39
+ }
40
+ function hasBrowserHeaders(request) {
41
+ const keys = Object.keys(request.headers).map(k => k.toLowerCase());
42
+ return keys.some(k => FORBIDDEN_CLI_HEADERS.includes(k));
43
+ }
44
+ function generateUserCode() {
45
+ const bytes = randomBytes(8);
46
+ let raw = "";
47
+ for (let i = 0; i < 8; i += 1)
48
+ raw += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
49
+ return `${raw.slice(0, 4)}-${raw.slice(4, 8)}`;
50
+ }
51
+ function readRawBody(request, maxBytes = MAX_BODY_BYTES) {
52
+ return new Promise(resolve => {
53
+ const chunks = [];
54
+ let size = 0;
55
+ let over = false;
56
+ request.on("data", (chunk) => {
57
+ size += chunk.length;
58
+ if (size > maxBytes) {
59
+ over = true;
60
+ chunks.length = 0;
61
+ return;
62
+ }
63
+ chunks.push(chunk);
64
+ });
65
+ request.on("end", () => resolve(over ? null : Buffer.concat(chunks).toString("utf8")));
66
+ request.on("error", () => resolve(null));
67
+ });
68
+ }
69
+ function safeEqualHex(a, b) {
70
+ if (a.length !== b.length)
71
+ return false;
72
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
73
+ }
74
+ export function createDevicePairHandlers(options) {
75
+ const { store, clock, allowedHost, browserKeys, identify, freshFactsOf, admitSource } = options;
76
+ const entries = new Map();
77
+ const prune = (nowMs) => {
78
+ for (const [code, entry] of entries) {
79
+ if (entry.expiresAt <= nowMs) {
80
+ entry.token = null;
81
+ entries.delete(code);
82
+ }
83
+ }
84
+ };
85
+ async function start(request, response) {
86
+ if (request.method !== "POST")
87
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
88
+ if (hasBrowserHeaders(request))
89
+ return sendJson(response, 400, { ok: false, error: "browser_headers_forbidden" });
90
+ const budget = admitSource(request);
91
+ if (!budget.ok) {
92
+ const headers = {};
93
+ if (budget.status !== 503)
94
+ headers["retry-after"] = String(budget.retryAfter);
95
+ return sendJson(response, budget.status === 503 ? 503 : 429, { ok: false, error: "rate-limited", message: "Too many pairing attempts. Try again shortly." }, headers);
96
+ }
97
+ await readRawBody(request, 1024);
98
+ const nowMs = clock().getTime();
99
+ prune(nowMs);
100
+ if (entries.size >= MAX_PENDING_PAIRS) {
101
+ return sendJson(response, 429, { ok: false, error: "too_many_pending", message: "Too many pending terminal pairings. Try again shortly." });
102
+ }
103
+ let userCode = generateUserCode();
104
+ while (entries.has(userCode))
105
+ userCode = generateUserCode();
106
+ const pollSecret = randomBytes(32).toString("hex");
107
+ const expiresAt = nowMs + PAIR_TTL_MS;
108
+ entries.set(userCode, {
109
+ userCode,
110
+ pollSecret,
111
+ createdAt: nowMs,
112
+ expiresAt,
113
+ state: "pending",
114
+ account: null,
115
+ token: null,
116
+ });
117
+ return sendJson(response, 200, {
118
+ ok: true,
119
+ userCode,
120
+ pollSecret,
121
+ verificationPath: `/connect/pair/${userCode}`,
122
+ expiresAt: new Date(expiresAt).toISOString(),
123
+ });
124
+ }
125
+ async function poll(request, response) {
126
+ if (request.method !== "POST")
127
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
128
+ if (hasBrowserHeaders(request))
129
+ return sendJson(response, 400, { ok: false, error: "browser_headers_forbidden" });
130
+ const raw = await readRawBody(request, 2048);
131
+ if (raw === null)
132
+ return sendJson(response, 413, { ok: false, error: "too_large" });
133
+ let pollSecret = "";
134
+ try {
135
+ const parsed = JSON.parse(raw);
136
+ if (typeof parsed["pollSecret"] === "string")
137
+ pollSecret = parsed["pollSecret"];
138
+ }
139
+ catch {
140
+ return sendJson(response, 400, { ok: false, error: "bad_request" });
141
+ }
142
+ if (!POLL_SECRET_RE.test(pollSecret))
143
+ return sendJson(response, 400, { ok: false, error: "bad_request" });
144
+ const nowMs = clock().getTime();
145
+ prune(nowMs);
146
+ let matched = null;
147
+ for (const entry of entries.values()) {
148
+ if (safeEqualHex(entry.pollSecret, pollSecret))
149
+ matched = entry;
150
+ }
151
+ if (matched === null)
152
+ return sendJson(response, 404, { ok: false, status: "expired", message: "Pairing expired or unknown. Start again." });
153
+ if (matched.state === "pending")
154
+ return sendJson(response, 200, { ok: true, status: "pending" });
155
+ const account = matched.account;
156
+ const token = matched.token;
157
+ matched.token = null;
158
+ entries.delete(matched.userCode);
159
+ if (account === null || token === null) {
160
+ return sendJson(response, 404, { ok: false, status: "expired", message: "Pairing was already claimed." });
161
+ }
162
+ return sendJson(response, 200, { ok: true, status: "approved", account, token });
163
+ }
164
+ function renderPage(code, who, problem, done) {
165
+ const canAct = who.role === "approver";
166
+ return html `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Connect terminal — Toolroll</title>
167
+ <style>body{font-family:system-ui,-apple-system,sans-serif;background:#0c0e12;color:#f3f4f6;margin:0;padding:32px;display:flex;justify-content:center}main{max-width:440px;width:100%;background:#141821;border:1px solid #262c3a;border-radius:12px;padding:24px}h1{font-size:20px;margin:0 0 8px}.code{font-family:ui-monospace,monospace;font-size:28px;letter-spacing:3px;background:#0c0e12;border:1px solid #2e3648;border-radius:8px;padding:12px;text-align:center;margin:16px 0}label{display:block;font-size:13px;margin:12px 0 4px;color:#cbd5e1}input,select{width:100%;box-sizing:border-box;padding:8px 10px;border-radius:6px;border:1px solid #334155;background:#0c0e12;color:#f8fafc;font-size:14px}button{margin-top:16px;width:100%;padding:10px 14px;border-radius:8px;border:none;background:#38bdf8;color:#082f49;font-weight:600;font-size:14px;cursor:pointer}.err{background:#450a0a;border:1px solid #991b1b;color:#fecaca;padding:10px;border-radius:8px;font-size:13px;margin-bottom:12px}.ok{background:#052e16;border:1px solid #166534;color:#bbf7d0;padding:12px;border-radius:8px;font-size:14px}</style></head>
168
+ <body><main>
169
+ <h1>Connect a remote terminal</h1>
170
+ <p style="font-size:13px;color:#94a3b8;margin:0 0 8px">Signed in as <strong>${who.name}</strong>. Confirm the code shown in your terminal to mint a personal API token.</p>
171
+ <div class="code">${code}</div>
172
+ ${problem !== null ? html `<p class="err" role="alert">${problem}</p>` : ""}
173
+ ${done
174
+ ? html `<p class="ok">Terminal connected. You can close this tab and return to your terminal.</p>`
175
+ : withFormToken(who.session.csrf, () => postForm(`/connect/pair/${code}`, html `
176
+ <label for="access">Access level</label>
177
+ <select id="access" name="access">
178
+ <option value="read">Read only (recommended)</option>
179
+ ${canAct ? html `<option value="act">Read &amp; act (steer, revise, hand off, attach live terminals)</option>` : ""}
180
+ </select>
181
+ <label for="password">Confirm your Toolroll password</label>
182
+ <input id="password" name="password" type="password" autocomplete="current-password" required>
183
+ <button type="submit">Approve terminal connection</button>
184
+ `))}
185
+ </main></body></html>`;
186
+ }
187
+ function page(request, response, url) {
188
+ const match = PAIR_CODE_PATH.exec(url.pathname);
189
+ if (match === null)
190
+ return sendHtml(response, 404, html `<p>Unknown pairing code.</p>`);
191
+ const code = match[1];
192
+ const who = identify(request, false);
193
+ if (who === null || who.via !== "cookie") {
194
+ response.writeHead(303, { location: `/login?return=${encodeURIComponent(url.pathname)}`, "cache-control": "no-store" });
195
+ response.end();
196
+ return;
197
+ }
198
+ if (who.authority !== "full") {
199
+ return sendHtml(response, 403, html `<p>Set a password and sign in with a full browser session to connect remote terminals.</p>`);
200
+ }
201
+ const nowMs = clock().getTime();
202
+ prune(nowMs);
203
+ const entry = entries.get(code);
204
+ if (entry === undefined || entry.state !== "pending") {
205
+ return sendHtml(response, 404, html `<p>That terminal pairing code has expired or was already used. Run <code>toolroll connect --browser</code> again.</p>`);
206
+ }
207
+ return sendHtml(response, 200, renderPage(code, who, null, false), browserKeys.required());
208
+ }
209
+ async function confirm(request, response, url) {
210
+ if (request.method !== "POST")
211
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
212
+ const match = PAIR_CODE_PATH.exec(url.pathname);
213
+ if (match === null)
214
+ return sendHtml(response, 404, html `<p>Unknown pairing code.</p>`);
215
+ const code = match[1];
216
+ const who = identify(request, true);
217
+ if (who === null || who.via !== "cookie" || who.authority !== "full") {
218
+ return sendHtml(response, 403, html `<p>Sign in with a full browser session to approve a terminal connection.</p>`);
219
+ }
220
+ const origin = request.headers.origin;
221
+ const referer = request.headers.referer;
222
+ const named = typeof origin === "string" && origin !== "null" ? origin : typeof referer === "string" ? referer : null;
223
+ if (named === null || !allowedHost(named.replace(/^https?:\/\//, "").split("/")[0])) {
224
+ return sendHtml(response, 403, html `<p>Same-origin confirmation required.</p>`);
225
+ }
226
+ const raw = await readRawBody(request, MAX_BODY_BYTES);
227
+ if (raw === null)
228
+ return sendHtml(response, 413, html `<p>Request too large.</p>`);
229
+ const form = new URLSearchParams(raw);
230
+ if (form.get("csrf") !== who.session.csrf)
231
+ return sendHtml(response, 403, renderPage(code, who, "Invalid form token. Reload and try again.", false), browserKeys.required());
232
+ const keyErr = browserKeys.check(who, request, form);
233
+ if (keyErr !== null)
234
+ return sendHtml(response, keyErr.status, renderPage(code, who, keyErr.message, false), browserKeys.required());
235
+ const now = clock();
236
+ prune(now.getTime());
237
+ const entry = entries.get(code);
238
+ if (entry === undefined || entry.state !== "pending") {
239
+ return sendHtml(response, 404, html `<p>That terminal pairing code has expired or was already used.</p>`);
240
+ }
241
+ const password = form.get("password") ?? "";
242
+ const proved = freshFacts.run(freshFactsOf(request, who), () => proveAccountNow(store, who.name, password, { credential: true }));
243
+ if (!proved.ok || !credentialProof(proved.method)) {
244
+ return sendHtml(response, 403, renderPage(code, who, "Password did not match. Nothing was connected.", false), browserKeys.required());
245
+ }
246
+ const account = store.accountOf(who.name);
247
+ if (account === null || account.revokedAt !== null || account.generation !== who.session.generation) {
248
+ return sendHtml(response, 401, html `<p>Your session has ended.</p>`);
249
+ }
250
+ const requestedAccess = form.get("access") === "act" && account.role === "approver" ? "act" : "read";
251
+ const minted = mintApiToken();
252
+ store.createApiToken({
253
+ id: minted.id,
254
+ account: who.name,
255
+ name: `remote-tui-${code.toLowerCase()}`,
256
+ secretHash: minted.hash,
257
+ access: requestedAccess,
258
+ purpose: "api",
259
+ by: who.name,
260
+ projects: account.projects,
261
+ expiresAt: new Date(now.getTime() + TOKEN_TTL_MS).toISOString(),
262
+ }, now);
263
+ entry.state = "approved";
264
+ entry.account = who.name;
265
+ entry.token = minted.token;
266
+ store.recordAction({
267
+ at: now.toISOString(),
268
+ actor: who.name,
269
+ repo: null,
270
+ taskId: null,
271
+ runId: null,
272
+ action: "connect.pair.approved",
273
+ outcome: "recorded",
274
+ source: "sign-in",
275
+ detail: `paired remote terminal (${requestedAccess}, token ${minted.id})`,
276
+ });
277
+ return sendHtml(response, 200, renderPage(code, who, null, true));
278
+ }
279
+ return { start, poll, page, confirm };
280
+ }
@@ -0,0 +1,347 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { basename, extname, isAbsolute, join, relative } from "node:path";
4
+ import { assertManagedClonePath } from "./direct-chat-git.js";
5
+ export const MAX_ARTIFACT_BYTES = 10 * 1024 * 1024;
6
+ export const MAX_ARTIFACTS_PER_TURN = 20;
7
+ export const ALLOWED_IMAGE_MIMES = Object.freeze({
8
+ "image/png": ".png",
9
+ "image/jpeg": ".jpg",
10
+ "image/webp": ".webp",
11
+ "image/gif": ".gif",
12
+ });
13
+ export const ALLOWED_ATTACHMENT_TEXT_MIMES = Object.freeze({
14
+ "text/plain": ".txt",
15
+ "text/markdown": ".md",
16
+ "application/json": ".json",
17
+ });
18
+ const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
19
+ const SKIPPED_SCAN_DIRS = new Set([
20
+ ".git",
21
+ "node_modules",
22
+ ".toolroll-attachments",
23
+ ".next",
24
+ ".turbo",
25
+ ".venv",
26
+ "venv",
27
+ "dist",
28
+ "build",
29
+ "target",
30
+ ]);
31
+ export function detectSafeImageMime(bytes) {
32
+ if (bytes.length >= 8
33
+ && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
34
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
35
+ return "image/png";
36
+ }
37
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
38
+ return "image/jpeg";
39
+ }
40
+ if (bytes.length >= 6
41
+ && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38
42
+ && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
43
+ return "image/gif";
44
+ }
45
+ if (bytes.length >= 12
46
+ && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
47
+ && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
48
+ return "image/webp";
49
+ }
50
+ return null;
51
+ }
52
+ export function sanitizeArtifactFilename(raw, fallbackExt) {
53
+ const base = basename(raw.replace(/\\/g, "/"))
54
+ .replace(/[^A-Za-z0-9._-]/g, "_")
55
+ .replace(/^\.+/, "")
56
+ .slice(0, 96);
57
+ if (base === "")
58
+ return `artifact${fallbackExt}`;
59
+ return extname(base) === "" ? `${base}${fallbackExt}` : base;
60
+ }
61
+ function ensureAttachmentsExcludedFromGit(clonePath, gitDir) {
62
+ const targetGitDir = gitDir && existsSync(gitDir) ? gitDir : join(clonePath, ".git");
63
+ const excludePath = join(targetGitDir, "info", "exclude");
64
+ try {
65
+ mkdirSync(join(targetGitDir, "info"), { recursive: true });
66
+ const existing = existsSync(excludePath) ? readFileSync(excludePath, "utf8") : "";
67
+ if (!existing.split(/\r?\n/).includes(".toolroll-attachments/")) {
68
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
69
+ appendFileSync(excludePath, `${prefix}.toolroll-attachments/\n`, "utf8");
70
+ }
71
+ }
72
+ catch {
73
+ }
74
+ }
75
+ export function saveDirectChatArtifact(store, input) {
76
+ if (input.bytes.length === 0) {
77
+ return { ok: false, status: 400, error: "Empty artifact or attachment." };
78
+ }
79
+ if (input.bytes.length > MAX_ARTIFACT_BYTES) {
80
+ return { ok: false, status: 413, error: "Attachment exceeds the 10 MB limit." };
81
+ }
82
+ let resolvedMime = detectSafeImageMime(input.bytes);
83
+ if (resolvedMime === null && input.kind === "attachment") {
84
+ const requested = (input.mimeType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
85
+ if (requested in ALLOWED_ATTACHMENT_TEXT_MIMES) {
86
+ if (input.bytes.includes(0)) {
87
+ return { ok: false, status: 400, error: "Text attachments cannot contain binary NUL bytes." };
88
+ }
89
+ resolvedMime = requested;
90
+ }
91
+ }
92
+ if (resolvedMime === null) {
93
+ return { ok: false, status: 415, error: "Unsupported file type. Allowed: PNG, JPEG, WebP, GIF (and plain text, Markdown, JSON for attachments)." };
94
+ }
95
+ if (input.turnId !== null) {
96
+ const countRow = store.handle
97
+ .prepare("SELECT COUNT(*) AS n FROM direct_chat_artifact WHERE turn_id = ?")
98
+ .get(input.turnId);
99
+ if (Number(countRow?.["n"] ?? 0) >= MAX_ARTIFACTS_PER_TURN) {
100
+ return { ok: false, status: 429, error: "Artifact cap reached for this turn." };
101
+ }
102
+ }
103
+ const ext = resolvedMime in ALLOWED_IMAGE_MIMES
104
+ ? ALLOWED_IMAGE_MIMES[resolvedMime]
105
+ : ALLOWED_ATTACHMENT_TEXT_MIMES[resolvedMime];
106
+ const id = randomBytes(16).toString("hex");
107
+ const safeName = sanitizeArtifactFilename(input.filename, ext);
108
+ const sha256 = createHash("sha256").update(input.bytes).digest("hex");
109
+ const subdir = input.kind === "attachment" ? "attachments" : "artifacts";
110
+ const storageRel = join(subdir, input.threadId, `${id}${ext}`);
111
+ const storageAbs = join(input.stateRoot, "direct-chat", storageRel);
112
+ mkdirSync(join(input.stateRoot, "direct-chat", subdir, input.threadId), { recursive: true, mode: 0o700 });
113
+ writeFileSync(storageAbs, input.bytes, { mode: 0o600 });
114
+ let cloneRelativePath = null;
115
+ if (input.kind === "attachment" && input.clonePath) {
116
+ const managed = assertManagedClonePath(input.stateRoot, input.clonePath);
117
+ if (!managed.ok) {
118
+ return { ok: false, status: 409, error: managed.error };
119
+ }
120
+ ensureAttachmentsExcludedFromGit(managed.realClone, input.gitDir);
121
+ const attDir = join(managed.realClone, ".toolroll-attachments");
122
+ mkdirSync(attDir, { recursive: true, mode: 0o700 });
123
+ const cloneFilename = `${id.slice(0, 8)}-${safeName}`;
124
+ writeFileSync(join(attDir, cloneFilename), input.bytes, { mode: 0o600 });
125
+ cloneRelativePath = `.toolroll-attachments/${cloneFilename}`;
126
+ }
127
+ const createdAt = (input.now ?? new Date()).toISOString();
128
+ store.handle.prepare(`
129
+ INSERT INTO direct_chat_artifact (
130
+ id, thread_id, turn_id, kind, filename, mime_type, byte_size, sha256, storage_path, source_path, created_at
131
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
132
+ `).run(id, input.threadId, input.turnId, input.kind, safeName, resolvedMime, input.bytes.length, sha256, storageRel, input.sourcePath ?? cloneRelativePath, createdAt);
133
+ return {
134
+ ok: true,
135
+ cloneRelativePath,
136
+ artifact: {
137
+ id,
138
+ threadId: input.threadId,
139
+ turnId: input.turnId,
140
+ kind: input.kind,
141
+ filename: safeName,
142
+ mimeType: resolvedMime,
143
+ byteSize: input.bytes.length,
144
+ sha256,
145
+ storagePath: storageRel,
146
+ sourcePath: input.sourcePath ?? cloneRelativePath,
147
+ createdAt,
148
+ },
149
+ };
150
+ }
151
+ export function listArtifactsForThread(store, threadId) {
152
+ const rows = store.handle
153
+ .prepare("SELECT * FROM direct_chat_artifact WHERE thread_id = ? ORDER BY created_at ASC")
154
+ .all(threadId);
155
+ return rows.map(mapArtifactRow);
156
+ }
157
+ export function getDirectChatArtifact(store, stateRoot, threadId, artifactId) {
158
+ if (!/^[0-9a-f]{32}$/.test(threadId) || !/^[0-9a-f]{32}$/.test(artifactId))
159
+ return null;
160
+ const raw = store.handle
161
+ .prepare("SELECT * FROM direct_chat_artifact WHERE id = ? AND thread_id = ?")
162
+ .get(artifactId, threadId);
163
+ if (!raw)
164
+ return null;
165
+ const row = mapArtifactRow(raw);
166
+ const root = join(stateRoot, "direct-chat");
167
+ const abs = join(root, row.storagePath);
168
+ try {
169
+ const realRoot = realpathSync(root);
170
+ const realFile = realpathSync(abs);
171
+ const rel = relative(realRoot, realFile);
172
+ if (rel === ".." || rel.startsWith(`..${"/"}`) || isAbsolute(rel))
173
+ return null;
174
+ return { row, bytes: readFileSync(realFile) };
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ }
180
+ function mapArtifactRow(raw) {
181
+ return {
182
+ id: String(raw["id"]),
183
+ threadId: String(raw["thread_id"]),
184
+ turnId: typeof raw["turn_id"] === "string" ? raw["turn_id"] : null,
185
+ kind: raw["kind"] === "attachment" ? "attachment" : "output",
186
+ filename: String(raw["filename"]),
187
+ mimeType: String(raw["mime_type"]),
188
+ byteSize: Number(raw["byte_size"]),
189
+ sha256: String(raw["sha256"]),
190
+ storagePath: String(raw["storage_path"]),
191
+ sourcePath: typeof raw["source_path"] === "string" ? raw["source_path"] : null,
192
+ createdAt: String(raw["created_at"]),
193
+ };
194
+ }
195
+ export function snapshotWorkspaceImages(clonePath, maxFiles = 20_000) {
196
+ const snap = new Map();
197
+ if (!existsSync(clonePath))
198
+ return snap;
199
+ let rootReal;
200
+ try {
201
+ rootReal = realpathSync(clonePath);
202
+ }
203
+ catch {
204
+ return snap;
205
+ }
206
+ let visited = 0;
207
+ const stack = [rootReal];
208
+ while (stack.length > 0 && visited < maxFiles) {
209
+ const dir = stack.pop();
210
+ let entries;
211
+ try {
212
+ entries = readdirSync(dir);
213
+ }
214
+ catch {
215
+ continue;
216
+ }
217
+ for (const name of entries) {
218
+ visited += 1;
219
+ if (visited > maxFiles)
220
+ break;
221
+ if (SKIPPED_SCAN_DIRS.has(name))
222
+ continue;
223
+ const full = join(dir, name);
224
+ let st;
225
+ try {
226
+ st = lstatSync(full);
227
+ }
228
+ catch {
229
+ continue;
230
+ }
231
+ if (st.isSymbolicLink())
232
+ continue;
233
+ if (st.isDirectory()) {
234
+ stack.push(full);
235
+ }
236
+ else if (st.isFile() && IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) && st.size > 0 && st.size <= MAX_ARTIFACT_BYTES) {
237
+ const rel = relative(rootReal, full).replace(/\\/g, "/");
238
+ snap.set(rel, { size: st.size, mtimeMs: st.mtimeMs });
239
+ }
240
+ }
241
+ }
242
+ return snap;
243
+ }
244
+ export function captureNewWorkspaceArtifacts(store, input) {
245
+ const after = snapshotWorkspaceImages(input.clonePath);
246
+ const captured = [];
247
+ let rootReal;
248
+ try {
249
+ rootReal = realpathSync(input.clonePath);
250
+ }
251
+ catch {
252
+ return captured;
253
+ }
254
+ for (const [relPath, meta] of after) {
255
+ if (captured.length >= MAX_ARTIFACTS_PER_TURN)
256
+ break;
257
+ if (input.before !== undefined) {
258
+ const prev = input.before.get(relPath);
259
+ if (prev && prev.size === meta.size && prev.mtimeMs === meta.mtimeMs)
260
+ continue;
261
+ }
262
+ else if (input.sinceMs !== undefined) {
263
+ if (meta.mtimeMs < input.sinceMs)
264
+ continue;
265
+ }
266
+ else {
267
+ continue;
268
+ }
269
+ const full = join(rootReal, relPath);
270
+ try {
271
+ const st = lstatSync(full);
272
+ if (!st.isFile() || st.isSymbolicLink() || st.size > MAX_ARTIFACT_BYTES)
273
+ continue;
274
+ const bytes = readFileSync(full);
275
+ if (detectSafeImageMime(bytes) === null)
276
+ continue;
277
+ const saved = saveDirectChatArtifact(store, {
278
+ stateRoot: input.stateRoot,
279
+ threadId: input.threadId,
280
+ turnId: input.turnId,
281
+ kind: "output",
282
+ filename: basename(relPath),
283
+ bytes,
284
+ sourcePath: relPath,
285
+ now: input.now,
286
+ });
287
+ if (saved.ok)
288
+ captured.push(saved.artifact);
289
+ }
290
+ catch {
291
+ continue;
292
+ }
293
+ }
294
+ return captured;
295
+ }
296
+ export function extractBase64ImagesFromLine(line, _provider) {
297
+ const trimmed = line.trim();
298
+ if (trimmed === "" || !trimmed.includes("base64"))
299
+ return [];
300
+ let parsed;
301
+ try {
302
+ parsed = JSON.parse(trimmed);
303
+ }
304
+ catch {
305
+ return [];
306
+ }
307
+ const out = [];
308
+ const walk = (node, depth) => {
309
+ if (depth > 8 || out.length >= MAX_ARTIFACTS_PER_TURN || !node || typeof node !== "object")
310
+ return;
311
+ if (Array.isArray(node)) {
312
+ for (const item of node)
313
+ walk(item, depth + 1);
314
+ return;
315
+ }
316
+ const obj = node;
317
+ if (obj["type"] === "image" && obj["source"] && typeof obj["source"] === "object") {
318
+ const src = obj["source"];
319
+ if (src["type"] === "base64" && typeof src["data"] === "string" && src["data"].length > 16) {
320
+ try {
321
+ const bytes = Buffer.from(src["data"], "base64");
322
+ const mime = detectSafeImageMime(bytes);
323
+ if (mime !== null && bytes.length <= MAX_ARTIFACT_BYTES) {
324
+ const ext = ALLOWED_IMAGE_MIMES[mime];
325
+ out.push({ filename: `tool-capture-${out.length + 1}${ext}`, bytes });
326
+ }
327
+ }
328
+ catch {
329
+ }
330
+ }
331
+ return;
332
+ }
333
+ for (const val of Object.values(obj))
334
+ walk(val, depth + 1);
335
+ };
336
+ walk(parsed, 0);
337
+ return out;
338
+ }
339
+ export function imageContentHeaders(row) {
340
+ return {
341
+ "content-type": row.mimeType,
342
+ "content-disposition": `inline; filename="${row.filename.replace(/"/g, "")}"`,
343
+ "x-content-type-options": "nosniff",
344
+ "cache-control": "no-store",
345
+ "content-security-policy": "sandbox; default-src 'none'; img-src 'self'",
346
+ };
347
+ }