toolroll 0.9.129 → 0.9.130

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 (113) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/agent-fence.js +0 -2
  3. package/dist/agents-board.js +0 -3
  4. package/dist/assignment.js +4 -3
  5. package/dist/backup-ui.js +6 -3
  6. package/dist/bounded-spawn.js +0 -1
  7. package/dist/browser/manifest.json +57 -0
  8. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
  9. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz +0 -0
  10. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  11. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  12. package/dist/browser/{workspace.js → workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js} +25 -25
  13. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
  14. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
  15. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  16. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  17. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  18. package/dist/browser-shell.js +271 -25
  19. package/dist/canvas-freshness.js +122 -0
  20. package/dist/canvas-fs.js +273 -0
  21. package/dist/canvas-reads.js +747 -0
  22. package/dist/canvas-state-key.js +45 -0
  23. package/dist/canvas-state-worker.js +12 -0
  24. package/dist/central-recovery-stage.js +3 -3
  25. package/dist/chat-actions.js +26 -0
  26. package/dist/chat-channel.js +4 -3
  27. package/dist/chat-task-actions.js +1 -1
  28. package/dist/chat-warmth.js +0 -1
  29. package/dist/check-report.js +0 -6
  30. package/dist/commit-extract.js +79 -40
  31. package/dist/companion/access.js +1 -0
  32. package/dist/companion/actions.js +79 -16
  33. package/dist/companion/canvas.js +141 -0
  34. package/dist/companion/chat-origin.js +92 -0
  35. package/dist/companion/chat.js +571 -0
  36. package/dist/companion/daemon.js +46 -5
  37. package/dist/companion/finish.js +51 -0
  38. package/dist/companion/reads.js +5 -1
  39. package/dist/companion/schema.js +64 -0
  40. package/dist/companion/service.js +1 -0
  41. package/dist/companion/store.js +1 -0
  42. package/dist/companion/webauthn.js +11 -2
  43. package/dist/console-instance.js +0 -4
  44. package/dist/contracts/console-api.js +1 -1
  45. package/dist/converse.js +0 -1
  46. package/dist/coordinator.js +1 -1
  47. package/dist/desktop-config.js +156 -0
  48. package/dist/desktop-host.js +6 -152
  49. package/dist/desktop-update.js +1 -1
  50. package/dist/finished-task-sql.js +14 -0
  51. package/dist/flexible-answers.js +0 -1
  52. package/dist/github-read.js +41 -0
  53. package/dist/guides.js +4 -3
  54. package/dist/lead-doors.js +50 -3
  55. package/dist/lead-queue-runtime.js +11 -2
  56. package/dist/lead-queue.js +25 -0
  57. package/dist/live-backup-change.js +93 -0
  58. package/dist/live-backup.js +75 -31
  59. package/dist/live-bus.js +3 -2
  60. package/dist/live-records.js +0 -1
  61. package/dist/local-owner.js +0 -1
  62. package/dist/model-choices.js +0 -11
  63. package/dist/nightly-check.js +0 -3
  64. package/dist/nightly-github.js +1 -2
  65. package/dist/notification-retention.js +119 -0
  66. package/dist/observations.js +0 -1
  67. package/dist/operate.js +17 -4
  68. package/dist/pull-request-flow.js +56 -15
  69. package/dist/qr.js +0 -25
  70. package/dist/release-adapters.js +12 -42
  71. package/dist/release-auto.js +17 -13
  72. package/dist/release-card.js +0 -4
  73. package/dist/release-cli.js +37 -2
  74. package/dist/release.js +13 -2
  75. package/dist/restore-retirement.js +4 -1
  76. package/dist/result-review.js +0 -3
  77. package/dist/retention-ui.js +1 -1
  78. package/dist/retention.js +14 -21
  79. package/dist/review-context.js +0 -5
  80. package/dist/route-rules.js +1 -5
  81. package/dist/sandbox-runtime.js +0 -1
  82. package/dist/scope.js +1 -13
  83. package/dist/scout.js +0 -6
  84. package/dist/serve.js +31 -7
  85. package/dist/server/kit.js +1 -0
  86. package/dist/server/live.js +9 -2
  87. package/dist/server/pages.js +3 -2
  88. package/dist/server/phone-engine-api.js +22 -2
  89. package/dist/server/render-pages.js +1 -11
  90. package/dist/server/render-results.js +0 -1
  91. package/dist/server/render-tasks.js +0 -68
  92. package/dist/server/route-table.js +1 -1
  93. package/dist/server/settings-phone.js +32 -9
  94. package/dist/server/settings-scripts.js +1 -1
  95. package/dist/server/settings-section-table.js +0 -3
  96. package/dist/server/settings-sections.js +4 -2
  97. package/dist/server/settings.js +20 -5
  98. package/dist/server/terminals.js +2 -1
  99. package/dist/store.js +20 -5
  100. package/dist/structured-output.js +0 -1
  101. package/dist/style-asset.js +20 -7
  102. package/dist/tailnet.js +0 -3
  103. package/dist/task-control.js +5 -0
  104. package/dist/task-sizing.js +0 -1
  105. package/dist/toolroll-update-cli.js +19 -3
  106. package/dist/toolroll-update-ui.js +2 -2
  107. package/dist/toolroll-update.js +95 -15
  108. package/package.json +1 -1
  109. package/dist/companion/webauthn-test-support.js +0 -44
  110. package/dist/contracts/contract-test.js +0 -55
  111. package/dist/unfenced-test-support.js +0 -6
  112. /package/dist/browser/{terminal.js → terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js} +0 -0
  113. /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
@@ -0,0 +1,747 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+ import { execFile } from "node:child_process";
3
+ import { lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { withDirScope } from "./canvas-fs.js";
7
+ import { CanvasFreshness } from "./canvas-freshness.js";
8
+ export const CANVAS_IMAGE_BYTES = 20 * 1024 * 1024;
9
+ export const CANVAS_THUMB_BYTES = 256 * 1024;
10
+ export const CANVAS_THUMB_PIXELS = 720;
11
+ export const CANVAS_CHUNK_BYTES = 256 * 1024;
12
+ export const CANVAS_FRESHNESS_WAIT_MS = 1_500;
13
+ const MANIFEST_BYTES = 256 * 1024;
14
+ const INDEX_BYTES = 128 * 1024;
15
+ const REQUEST_BYTES = 64 * 1024;
16
+ const MAX_SURFACES = 8;
17
+ const MAX_APP_SCREENS = 60;
18
+ const MAX_WEB_SCREENS = 200;
19
+ const MAX_STATE_FOLDERS = 64;
20
+ const MAX_FILES_PER_FOLDER = 2_000;
21
+ const MAX_PINS = 200;
22
+ export const MAX_REQUEST_ENTRIES = 1_000;
23
+ const MAX_NEWEST_INDEXES = 16;
24
+ const MAX_REMEMBERED = 2_048;
25
+ const PINS_JSON_BUDGET = 700 * 1024;
26
+ const HASH_CHUNK = 1024 * 1024;
27
+ export class CanvasReadError extends Error {
28
+ code;
29
+ constructor(code, message) {
30
+ super(message);
31
+ this.code = code;
32
+ this.name = "CanvasReadError";
33
+ }
34
+ }
35
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
36
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;
37
+ export function imageMime(bytes) {
38
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_MAGIC))
39
+ return "image/png";
40
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
41
+ return "image/jpeg";
42
+ return null;
43
+ }
44
+ function pngSize(prefix) {
45
+ if (prefix.length < 24 || imageMime(prefix) !== "image/png" || prefix.toString("latin1", 12, 16) !== "IHDR")
46
+ return { width: null, height: null };
47
+ const width = prefix.readUInt32BE(16), height = prefix.readUInt32BE(20);
48
+ return width > 0 && height > 0 && width < 100_000 && height < 100_000 ? { width, height } : { width: null, height: null };
49
+ }
50
+ function readJson(scope, dir, name, cap) {
51
+ const file = scope.readFile(dir, name, cap);
52
+ if (file === null)
53
+ return undefined;
54
+ try {
55
+ return JSON.parse(file.bytes.toString("utf8"));
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
62
+ const str = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max ? value : null;
63
+ function line(text, max) {
64
+ const clean = text.replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ").replace(/\s+/g, " ").trim();
65
+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;
66
+ }
67
+ function paragraphs(text, max) {
68
+ const clean = text.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0009\u000b-\u001f\u007f\p{Cf}\u2028\u2029]/gu, "").trim();
69
+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;
70
+ }
71
+ function plainRelativePath(value) {
72
+ if (value === "" || value.length > 300 || value.startsWith("/") || value.startsWith("~") || value.startsWith(":") || /[\u0000-\u001f\u007f]/.test(value))
73
+ return false;
74
+ return !value.split("/").some(part => part === "" || part === "..");
75
+ }
76
+ const commitOf = (value) => typeof value === "string" && /^[0-9a-f]{7,40}$/.test(value) ? value : null;
77
+ const appearanceList = (value) => Array.isArray(value) && value.length > 0 && value.length <= 2 && value.every(one => one === "light" || one === "dark")
78
+ ? [...new Set(value)] : null;
79
+ function youiFolder(scope, repo, part) {
80
+ const root = scope.root(repo);
81
+ const youi = root === null ? null : scope.child(root, ".youi");
82
+ return youi === null ? null : scope.child(youi, part);
83
+ }
84
+ function readAppManifest(repo) {
85
+ const raw = withDirScope(scope => { const folder = youiFolder(scope, repo, "screens"); return folder === null ? null : record(readJson(scope, folder, "app.json", MANIFEST_BYTES)); });
86
+ if (raw === null || raw["schema"] !== "toolroll.app-screens/v1" || !Array.isArray(raw["surfaces"]))
87
+ return [];
88
+ const surfaces = [];
89
+ for (const one of raw["surfaces"].slice(0, MAX_SURFACES)) {
90
+ const surface = record(one);
91
+ const build = record(surface?.["build"]);
92
+ const id = str(surface?.["id"], 40), appearances = appearanceList(surface?.["appearances"]);
93
+ const paths = Array.isArray(surface?.["paths"]) ? surface["paths"] : [];
94
+ if (surface === null || id === null || !SLUG.test(id) || surface["kind"] !== "ios" || appearances === null || build === null
95
+ || typeof build["project"] !== "string" || !plainRelativePath(build["project"]) || paths.length === 0 || paths.length > 50
96
+ || !paths.every(path => typeof path === "string" && plainRelativePath(path)))
97
+ continue;
98
+ const seen = new Set();
99
+ const screens = [];
100
+ for (const each of Array.isArray(surface["screens"]) ? surface["screens"].slice(0, MAX_APP_SCREENS) : []) {
101
+ const screen = record(each);
102
+ const sid = str(screen?.["id"], 40), title = str(screen?.["title"], 80), view = str(screen?.["view"], 300);
103
+ const own = screen?.["appearances"] === undefined ? appearances : appearanceList(screen["appearances"]);
104
+ if (screen === null || sid === null || !SLUG.test(sid) || seen.has(sid) || title === null || view === null || !plainRelativePath(view) || own === null)
105
+ continue;
106
+ seen.add(sid);
107
+ screens.push({ id: sid, title: line(title, 80), view, appearances: own });
108
+ }
109
+ surfaces.push({ id, label: line(str(surface["label"], 80) ?? id, 80), device: line(str(surface["device"], 80) ?? "", 80), paths: paths, appearances, screens });
110
+ }
111
+ return surfaces;
112
+ }
113
+ function readWebRoutes(repo) {
114
+ const raw = withDirScope(scope => { const folder = youiFolder(scope, repo, "screens"); return folder === null ? null : record(readJson(scope, folder, "screens.json", MANIFEST_BYTES)); });
115
+ if (raw === null || !Array.isArray(raw["screens"]))
116
+ return null;
117
+ const seen = new Set();
118
+ const routes = [];
119
+ for (const one of raw["screens"].slice(0, MAX_WEB_SCREENS)) {
120
+ const entry = record(one);
121
+ const route = str(entry?.["route"], 300), path = str(entry?.["path"], 300);
122
+ if (route === null || path === null || seen.has(route))
123
+ continue;
124
+ seen.add(route);
125
+ routes.push({ route: line(route, 300), path: line(path, 300) });
126
+ }
127
+ return routes;
128
+ }
129
+ export function webSlug(route) {
130
+ const collapsed = [...route].map(ch => /[\p{L}\p{N}]/u.test(ch) ? ch : "-").join("").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
131
+ return collapsed === "" ? "home" : collapsed.toLowerCase();
132
+ }
133
+ export const canvasCacheRoot = (home) => join(home, ".cache", "toolroll", "canvas");
134
+ export const repoHash = (repo) => createHash("sha256").update(repo, "utf8").digest("hex").slice(0, 12);
135
+ function realOrNull(path) {
136
+ try {
137
+ return realpathSync(path);
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ }
143
+ function captureKey(capture) {
144
+ return createHash("sha256").update(`${capture.dirPath}\0${capture.file}\0${capture.size}\0${capture.mtimeMs}\0${capture.ino}`).digest("hex").slice(0, 24);
145
+ }
146
+ class CacheWalker {
147
+ scope;
148
+ rootPath;
149
+ hashes = [];
150
+ hashDirs = new Map();
151
+ current = null;
152
+ constructor(scope, home, repo) {
153
+ this.scope = scope;
154
+ this.rootPath = realOrNull(canvasCacheRoot(home));
155
+ const root = this.rootPath === null ? null : scope.root(this.rootPath);
156
+ if (root === null)
157
+ return;
158
+ const real = realOrNull(repo);
159
+ for (const hash of new Set([repoHash(repo), ...(real === null ? [] : [repoHash(real)])])) {
160
+ const dir = scope.child(root, hash);
161
+ if (dir === null)
162
+ continue;
163
+ this.hashes.push(hash);
164
+ this.hashDirs.set(hash, dir);
165
+ }
166
+ }
167
+ folder(loc) {
168
+ const base = this.hashDirs.get(loc.hash);
169
+ if (base === undefined)
170
+ return null;
171
+ if (loc.segments.length === 0)
172
+ return base;
173
+ const key = `${loc.hash}/${loc.segments.join("/")}`;
174
+ if (this.current?.key === key)
175
+ return this.current.chain.at(-1);
176
+ this.letGo();
177
+ const chain = [];
178
+ let at = base;
179
+ for (const name of loc.segments) {
180
+ at = this.scope.child(at, name);
181
+ if (at === null) {
182
+ for (const one of chain.reverse())
183
+ this.scope.release(one);
184
+ return null;
185
+ }
186
+ chain.push(at);
187
+ }
188
+ this.current = { key, chain };
189
+ return at;
190
+ }
191
+ letGo() {
192
+ if (this.current === null)
193
+ return;
194
+ for (const one of [...this.current.chain].reverse())
195
+ this.scope.release(one);
196
+ this.current = null;
197
+ }
198
+ dirPath(loc) {
199
+ return join(this.rootPath ?? "", loc.hash, ...loc.segments);
200
+ }
201
+ names(loc, max) {
202
+ const dir = this.folder(loc);
203
+ if (dir === null)
204
+ return [];
205
+ return this.scope.list(dir, max).map(name => ({ name, at: this.scope.peek(dir, name)?.mtimeMs ?? 0 }))
206
+ .sort((a, b) => b.at - a.at).map(one => one.name);
207
+ }
208
+ probe(loc, file) {
209
+ const dir = this.folder(loc);
210
+ const read = dir === null ? null : this.scope.readFile(dir, file, CANVAS_IMAGE_BYTES, 24);
211
+ const mime = read === null ? null : imageMime(read.bytes);
212
+ if (read === null || mime === null)
213
+ return null;
214
+ return { size: read.stats.size, mtimeMs: read.stats.mtimeMs, ino: read.stats.ino, mime, ...pngSize(read.bytes) };
215
+ }
216
+ json(loc, file, cap) {
217
+ const dir = this.folder(loc);
218
+ return dir === null ? undefined : readJson(this.scope, dir, file, cap);
219
+ }
220
+ open(capture) {
221
+ const dir = this.folder(capture.loc);
222
+ const file = dir === null ? null : this.scope.openFile(dir, capture.file, CANVAS_IMAGE_BYTES);
223
+ if (file === null)
224
+ return null;
225
+ if (file.stats.ino !== capture.ino || file.stats.size !== capture.size || file.stats.mtimeMs !== capture.mtimeMs) {
226
+ this.scope.releaseFile(file.fd);
227
+ return null;
228
+ }
229
+ return file;
230
+ }
231
+ capture(loc, file, variant, capturedAt, commit) {
232
+ const head = this.probe(loc, file);
233
+ if (head === null)
234
+ return null;
235
+ return { loc, dirPath: this.dirPath(loc), file, variant, capturedAt: capturedAt ?? new Date(head.mtimeMs).toISOString(), commit, ...head };
236
+ }
237
+ }
238
+ function readCaptureIndex(walker, loc, surface) {
239
+ const raw = record(walker.json(loc, "index.json", INDEX_BYTES));
240
+ const stateKey = str(raw?.["state_key"], 80), capturedAt = str(raw?.["captured_at"], 40);
241
+ if (raw === null || raw["schema"] !== "toolroll.app-captures/v1" || raw["surface"] !== surface || stateKey === null || capturedAt === null || !Array.isArray(raw["captures"]))
242
+ return null;
243
+ const captures = new Map();
244
+ for (const one of raw["captures"].slice(0, MAX_APP_SCREENS * 2)) {
245
+ const entry = record(one);
246
+ const screen = str(entry?.["screen"], 40), appearance = entry?.["appearance"];
247
+ if (entry === null || screen === null || !SLUG.test(screen) || (appearance !== "light" && appearance !== "dark"))
248
+ continue;
249
+ if (entry["file"] !== `${screen}-${appearance}.png`)
250
+ continue;
251
+ captures.set(`${screen}#${appearance}`, { file: entry["file"], commit: commitOf(entry["commit"]), capturedAt: str(entry["captured_at"], 40) ?? capturedAt });
252
+ }
253
+ return { loc, stateKey: line(stateKey, 80), device: str(raw["device"], 80) === null ? null : line(raw["device"], 80), commit: commitOf(raw["commit"]), capturedAt, captures };
254
+ }
255
+ function appIndexes(walker, surface, max) {
256
+ const found = [];
257
+ for (const hash of walker.hashes) {
258
+ for (const name of walker.names({ hash, segments: ["app", surface] }, MAX_FILES_PER_FOLDER).slice(0, max)) {
259
+ const index = readCaptureIndex(walker, { hash, segments: ["app", surface, name] }, surface);
260
+ if (index !== null)
261
+ found.push(index);
262
+ }
263
+ }
264
+ return found;
265
+ }
266
+ function latestAppIndex(walker, surface, stateKey) {
267
+ if (stateKey !== null && /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(stateKey)) {
268
+ for (const hash of walker.hashes) {
269
+ const index = readCaptureIndex(walker, { hash, segments: ["app", surface, stateKey] }, surface);
270
+ if (index !== null && index.stateKey === stateKey)
271
+ return index;
272
+ }
273
+ }
274
+ return appIndexes(walker, surface, MAX_NEWEST_INDEXES).reduce((best, one) => best === null || one.capturedAt > best.capturedAt ? one : best, null);
275
+ }
276
+ function webTiles(walker) {
277
+ const tiles = new Map();
278
+ for (const hash of walker.hashes) {
279
+ for (const folder of walker.names({ hash, segments: [] }, MAX_FILES_PER_FOLDER).slice(0, MAX_STATE_FOLDERS)) {
280
+ if (folder === "app" || folder === "checkpoints")
281
+ continue;
282
+ const loc = { hash, segments: [folder] };
283
+ for (const file of walker.names(loc, MAX_FILES_PER_FOLDER)) {
284
+ const match = /^([a-z0-9][a-z0-9-]{0,199})-(desktop|mobile)\.png$/.exec(file);
285
+ if (match === null)
286
+ continue;
287
+ const slot = `${match[1]}#${match[2]}`;
288
+ const list = tiles.get(slot) ?? [];
289
+ list.push({ loc, file, folder, variant: match[2] });
290
+ tiles.set(slot, list);
291
+ }
292
+ }
293
+ }
294
+ return tiles;
295
+ }
296
+ function webTile(walker, candidate) {
297
+ const capture = walker.capture(candidate.loc, candidate.file, candidate.variant, null, commitOf(candidate.folder));
298
+ return capture === null ? null : { ...capture, folder: candidate.folder };
299
+ }
300
+ function newestTile(walker, candidates) {
301
+ for (const candidate of candidates ?? []) {
302
+ const tile = webTile(walker, candidate);
303
+ if (tile !== null)
304
+ return tile;
305
+ }
306
+ return null;
307
+ }
308
+ let sharedFreshness = null;
309
+ const freshnessOf = (deps) => deps.freshness ?? (sharedFreshness ??= new CanvasFreshness());
310
+ const webPathspecs = (surfaces) => [".", ...surfaces.flatMap(one => one.paths).map(path => `:(exclude)${path}`)];
311
+ export const canvasProjectId = (repo, idKey) => `p${createHmac("sha256", idKey).update(repo, "utf8").digest("hex").slice(0, 16)}`;
312
+ const projectName = (repo) => repo.split(/[\\/]/).filter(one => one !== "").pop() ?? repo;
313
+ function inScope(scope) {
314
+ return [...new Set(scope.candidates())].filter(repo => scope.canSee(repo));
315
+ }
316
+ export function resolveCanvasProject(scope, id) {
317
+ if (typeof id !== "string" || !/^p[0-9a-f]{16}$/.test(id))
318
+ throw new CanvasReadError("invalid_params", "project is required");
319
+ const repo = inScope(scope).find(one => canvasProjectId(one, scope.idKey) === id);
320
+ if (repo === undefined || !scope.canSee(repo))
321
+ throw new CanvasReadError("not_found", "No such project.");
322
+ return repo;
323
+ }
324
+ const homeOf = (deps) => deps.home?.() ?? homedir();
325
+ export function canvasProjects(deps, scope) {
326
+ return inScope(scope).slice(0, 200).map(repo => ({
327
+ id: canvasProjectId(repo, scope.idKey), name: line(projectName(repo), 200),
328
+ hasCanvas: readAppManifest(repo).length > 0 || withDirScope(dirs => new CacheWalker(dirs, homeOf(deps), repo).hashes.length > 0),
329
+ })).sort((a, b) => Number(b.hasCanvas) - Number(a.hasCanvas) || a.name.localeCompare(b.name));
330
+ }
331
+ const listed = new Map();
332
+ function remember(repo, capture) {
333
+ const key = captureKey(capture);
334
+ listed.delete(key);
335
+ listed.set(key, { repo, capture });
336
+ while (listed.size > MAX_REMEMBERED)
337
+ listed.delete(listed.keys().next().value);
338
+ }
339
+ function locate(deps, scope, repo, keys, withPins) {
340
+ const captures = new Map();
341
+ const sections = [];
342
+ const surfaces = readAppManifest(repo);
343
+ const routesListed = readWebRoutes(repo);
344
+ const known = (answer) => answer?.known === true ? answer.key : null;
345
+ withDirScope(dirs => {
346
+ const walker = new CacheWalker(dirs, homeOf(deps), repo);
347
+ const webKey = known(keys?.web);
348
+ const tiles = webTiles(walker);
349
+ const routes = routesListed ?? [...new Set([...tiles.keys()].map(slot => slot.split("#")[0]))].sort().map(slug => ({ route: slug, path: "" }));
350
+ const webScreens = [];
351
+ let webAt = null;
352
+ for (const { route, path } of routes) {
353
+ const slug = webSlug(route);
354
+ const variants = [];
355
+ const current = [];
356
+ for (const viewport of ["desktop", "mobile"]) {
357
+ const tile = newestTile(walker, tiles.get(`${slug}#${viewport}`));
358
+ if (tile === null)
359
+ continue;
360
+ captures.set(`web:${slug}#${viewport}`, tile);
361
+ variants.push(variantOf(tile));
362
+ current.push(webKey === null ? null : tile.folder === webKey || tile.folder.startsWith(`${webKey}-o`));
363
+ if (webAt === null || tile.capturedAt > webAt)
364
+ webAt = tile.capturedAt;
365
+ }
366
+ webScreens.push({ id: `web:${slug}`, title: route, path: path === "" ? null : path, variants, stale: staleOf(current), pins: 0 });
367
+ }
368
+ if (webScreens.length > 0 && (routesListed !== null || tiles.size > 0)) {
369
+ sections.push({ id: "web", kind: "web", title: "Web", device: null, capturedAt: webAt, commit: null, stale: anyStale(webScreens), screens: webScreens.slice(0, MAX_WEB_SCREENS) });
370
+ }
371
+ for (const surface of surfaces) {
372
+ const key = known(keys?.surfaces.get(surface.id));
373
+ const index = latestAppIndex(walker, surface.id, key);
374
+ const stale = index === null || key === null ? null : index.stateKey !== key;
375
+ const screens = surface.screens.map(screen => {
376
+ const id = `app:${surface.id}/${screen.id}`;
377
+ const variants = [];
378
+ for (const appearance of screen.appearances) {
379
+ const entry = index?.captures.get(`${screen.id}#${appearance}`);
380
+ const capture = entry === undefined || index === null ? null : walker.capture(index.loc, entry.file, appearance, entry.capturedAt, entry.commit ?? index.commit);
381
+ if (capture === null)
382
+ continue;
383
+ captures.set(`${id}#${appearance}`, capture);
384
+ variants.push(variantOf(capture));
385
+ }
386
+ return { id, title: screen.title, path: screen.view, variants, stale: variants.length === 0 ? null : stale, pins: 0 };
387
+ });
388
+ sections.push({ id: surface.id, kind: "app", title: "App · iPhone", device: index?.device ?? (surface.device === "" ? null : surface.device),
389
+ capturedAt: index?.capturedAt ?? null, commit: index?.commit ?? null, stale, screens });
390
+ }
391
+ });
392
+ for (const capture of captures.values())
393
+ remember(repo, capture);
394
+ const listing = { project: { id: canvasProjectId(repo, scope.idKey), name: line(projectName(repo), 200), hasCanvas: sections.length > 0 || surfaces.length > 0 }, sections };
395
+ if (withPins) {
396
+ const counts = new Map();
397
+ for (const pin of readPins(deps, repo, listing).pins)
398
+ if (pin.screen !== null)
399
+ counts.set(pin.screen, (counts.get(pin.screen) ?? 0) + 1);
400
+ for (const section of sections)
401
+ for (const screen of section.screens)
402
+ screen.pins = counts.get(screen.id) ?? 0;
403
+ }
404
+ return { listing, captures, repo, surfaces };
405
+ }
406
+ function variantOf(capture) {
407
+ return { variant: capture.variant, key: captureKey(capture), capturedAt: capture.capturedAt, commit: capture.commit, bytes: capture.size,
408
+ width: capture.width, height: capture.height, mime: capture.mime };
409
+ }
410
+ const staleOf = (current) => current.length === 0 || current.some(one => one === null) ? null : !current.some(one => one === true);
411
+ const anyStale = (screens) => {
412
+ const known = screens.filter(one => one.variants.length > 0).map(one => one.stale);
413
+ return known.some(one => one === null) ? null : known.some(one => one === true);
414
+ };
415
+ export async function canvasList(deps, scope, projectId) {
416
+ const repo = resolveCanvasProject(scope, projectId);
417
+ const surfaces = readAppManifest(repo);
418
+ const hasCache = withDirScope(dirs => new CacheWalker(dirs, homeOf(deps), repo).hashes.length > 0);
419
+ const freshness = freshnessOf(deps), wait = deps.freshnessWaitMs ?? CANVAS_FRESHNESS_WAIT_MS;
420
+ const keys = { web: null, surfaces: new Map() };
421
+ if (hasCache) {
422
+ const [web, ...apps] = await Promise.all([freshness.get(repo, webPathspecs(surfaces), wait), ...surfaces.map(one => freshness.get(repo, one.paths, wait))]);
423
+ keys.web = web ?? null;
424
+ surfaces.forEach((one, index) => keys.surfaces.set(one.id, apps[index]));
425
+ }
426
+ if (!scope.canSee(repo))
427
+ throw new CanvasReadError("not_found", "No such project.");
428
+ return locate(deps, scope, repo, keys, true).listing;
429
+ }
430
+ const SCREEN_ID = /^(web:[a-z0-9][a-z0-9-]{0,199}|app:[a-z0-9][a-z0-9-]{0,39}\/[a-z0-9][a-z0-9-]{0,39})$/;
431
+ const VARIANTS = new Set(["light", "dark", "desktop", "mobile"]);
432
+ function checkImageParams(params) {
433
+ if (params.key !== undefined && (typeof params.key !== "string" || !/^[0-9a-f]{24}$/.test(params.key)))
434
+ throw new CanvasReadError("invalid_params", "key must be a capture key");
435
+ if (typeof params.screen !== "string" || !SCREEN_ID.test(params.screen))
436
+ throw new CanvasReadError("invalid_params", "screen is required");
437
+ if (typeof params.variant !== "string" || !VARIANTS.has(params.variant))
438
+ throw new CanvasReadError("invalid_params", "variant must be light, dark, desktop or mobile");
439
+ }
440
+ function capturedAs(capture) {
441
+ return capture.loc.segments[0] === "app" ? `app:${capture.loc.segments[1]}/${capture.file.replace(/-(light|dark)\.png$/, "")}#${capture.variant}`
442
+ : `web:${capture.file.replace(/-(desktop|mobile)\.png$/, "")}#${capture.variant}`;
443
+ }
444
+ function findCapture(deps, scope, params) {
445
+ checkImageParams(params);
446
+ const repo = resolveCanvasProject(scope, params.project);
447
+ const screen = params.screen, variant = params.variant;
448
+ if (typeof params.key === "string") {
449
+ const hit = listed.get(params.key);
450
+ if (hit !== undefined && hit.repo === repo && capturedAs(hit.capture) === `${screen}#${variant}`)
451
+ return { repo, capture: hit.capture };
452
+ }
453
+ const located = locate(deps, scope, repo, null, false);
454
+ let capture = located.captures.get(`${screen}#${variant}`);
455
+ if (typeof params.key === "string" && (capture === undefined || captureKey(capture) !== params.key)) {
456
+ const found = captureByKey(deps, located, screen, variant, params.key);
457
+ if (found === undefined)
458
+ throw new CanvasReadError("not_found", capture === undefined ? "That screen hasn't been captured." : "That capture changed. Open it again.");
459
+ capture = found;
460
+ remember(repo, found);
461
+ }
462
+ if (capture === undefined)
463
+ throw new CanvasReadError("not_found", "That screen hasn't been captured.");
464
+ return { repo, capture };
465
+ }
466
+ function captureByKey(deps, located, screen, variant, key) {
467
+ return withDirScope(dirs => {
468
+ const walker = new CacheWalker(dirs, homeOf(deps), located.repo);
469
+ const app = /^app:([a-z0-9-]+)\/([a-z0-9-]+)$/.exec(screen);
470
+ if (app !== null) {
471
+ if ((variant !== "light" && variant !== "dark") || !located.surfaces.some(one => one.id === app[1] && one.screens.some(s => s.id === app[2] && s.appearances.includes(variant))))
472
+ return undefined;
473
+ for (const index of appIndexes(walker, app[1], MAX_STATE_FOLDERS)) {
474
+ const entry = index.captures.get(`${app[2]}#${variant}`);
475
+ const capture = entry === undefined ? null : walker.capture(index.loc, entry.file, variant, entry.capturedAt, entry.commit ?? index.commit);
476
+ if (capture !== null && captureKey(capture) === key)
477
+ return capture;
478
+ }
479
+ return undefined;
480
+ }
481
+ if (variant !== "desktop" && variant !== "mobile")
482
+ return undefined;
483
+ for (const candidate of webTiles(walker).get(`${screen.slice(4)}#${variant}`) ?? []) {
484
+ const tile = webTile(walker, candidate);
485
+ if (tile !== null && captureKey(tile) === key)
486
+ return tile;
487
+ }
488
+ return undefined;
489
+ });
490
+ }
491
+ const digests = new Map();
492
+ function withCapture(deps, repo, capture, read) {
493
+ const gone = () => new CanvasReadError("not_found", "That capture changed. Open it again.");
494
+ return withDirScope(dirs => {
495
+ const walker = new CacheWalker(dirs, homeOf(deps), repo);
496
+ const file = walker.open(capture);
497
+ if (file === null)
498
+ throw gone();
499
+ const head = dirs.readAt(file, 0, Math.min(8, file.stats.size));
500
+ const mime = head === null ? null : imageMime(head);
501
+ if (mime === null)
502
+ throw gone();
503
+ const key = captureKey(capture);
504
+ let digest = digests.get(key);
505
+ if (digest === undefined) {
506
+ const hasher = createHash("sha256");
507
+ for (let at = 0; at < file.stats.size; at += HASH_CHUNK) {
508
+ const part = dirs.readAt(file, at, Math.min(HASH_CHUNK, file.stats.size - at));
509
+ if (part === null)
510
+ throw gone();
511
+ hasher.update(part);
512
+ }
513
+ digest = hasher.digest("hex");
514
+ digests.set(key, digest);
515
+ if (digests.size > MAX_REMEMBERED)
516
+ digests.delete(digests.keys().next().value);
517
+ }
518
+ return read(dirs, file, digest, mime);
519
+ });
520
+ }
521
+ export function canvasImagePiece(deps, scope, params) {
522
+ const start = params.offset === undefined ? 0 : params.offset;
523
+ const want = params.length === undefined ? CANVAS_CHUNK_BYTES : params.length;
524
+ if (typeof start !== "number" || !Number.isInteger(start) || start < 0)
525
+ throw new CanvasReadError("invalid_params", "offset must be a byte offset");
526
+ if (typeof want !== "number" || !Number.isInteger(want) || want < 1 || want > CANVAS_CHUNK_BYTES)
527
+ throw new CanvasReadError("invalid_params", `length must be 1 to ${CANVAS_CHUNK_BYTES}`);
528
+ const { repo, capture } = findCapture(deps, scope, params);
529
+ return withCapture(deps, repo, capture, (dirs, file, digest, mime) => {
530
+ const total = file.stats.size;
531
+ if (start > total)
532
+ throw new CanvasReadError("invalid_params", "offset is past the end");
533
+ const length = Math.min(want, total - start);
534
+ const data = length === 0 ? Buffer.alloc(0) : dirs.readAt(file, start, length);
535
+ if (data === null)
536
+ throw new CanvasReadError("not_found", "That capture changed. Open it again.");
537
+ return { key: captureKey(capture), digest, mime, offset: start, length, total, data };
538
+ });
539
+ }
540
+ export class ThumbnailPool {
541
+ maxRunning;
542
+ maxPending;
543
+ perOwner;
544
+ underway = new Map();
545
+ owners = new Map();
546
+ queue = [];
547
+ running = 0;
548
+ constructor(limits = {}) {
549
+ this.maxRunning = limits.maxRunning ?? 2;
550
+ this.maxPending = limits.maxPending ?? 4;
551
+ this.perOwner = limits.perOwner ?? 2;
552
+ }
553
+ get pending() { return this.underway.size; }
554
+ get active() { return this.running; }
555
+ run(owner, digest, make) {
556
+ const joined = this.underway.get(digest);
557
+ if (joined !== undefined)
558
+ return joined;
559
+ if (this.underway.size >= this.maxPending || (this.owners.get(owner) ?? 0) >= this.perOwner) {
560
+ return Promise.reject(new CanvasReadError("busy", "Your Mac is still making thumbnails. Try again in a moment."));
561
+ }
562
+ this.owners.set(owner, (this.owners.get(owner) ?? 0) + 1);
563
+ const work = new Promise((resolve, reject) => {
564
+ this.queue.push(() => {
565
+ this.running += 1;
566
+ Promise.resolve().then(make).then(resolve, reject).finally(() => {
567
+ this.running -= 1;
568
+ this.underway.delete(digest);
569
+ const left = (this.owners.get(owner) ?? 1) - 1;
570
+ if (left <= 0)
571
+ this.owners.delete(owner);
572
+ else
573
+ this.owners.set(owner, left);
574
+ this.pump();
575
+ });
576
+ });
577
+ });
578
+ this.underway.set(digest, work);
579
+ this.pump();
580
+ return work;
581
+ }
582
+ pump() {
583
+ while (this.running < this.maxRunning && this.queue.length > 0)
584
+ this.queue.shift()();
585
+ }
586
+ }
587
+ let sharedThumbnails = null;
588
+ const thumbCache = new Map();
589
+ export async function canvasScreenThumb(deps, scope, params) {
590
+ const { repo, capture } = findCapture(deps, scope, params);
591
+ const key = captureKey(capture);
592
+ const digest = withCapture(deps, repo, capture, (_dirs, _file, hashed) => hashed);
593
+ const cached = thumbCache.get(digest);
594
+ if (cached !== undefined)
595
+ return { key, digest, ...cached };
596
+ const pool = deps.thumbnails ?? (sharedThumbnails ??= new ThumbnailPool());
597
+ const made = await pool.run(deps.owner ?? "", digest, async () => {
598
+ const source = withCapture(deps, repo, capture, (dirs, file, hashed) => {
599
+ const bytes = dirs.readAt(file, 0, file.stats.size);
600
+ if (bytes === null || hashed !== digest)
601
+ throw new CanvasReadError("not_found", "That capture changed. Open it again.");
602
+ return bytes;
603
+ });
604
+ const out = await (deps.thumbnail ?? sipsThumbnail)(source);
605
+ if (out.bytes.length > CANVAS_THUMB_BYTES || imageMime(out.bytes) !== out.mime)
606
+ throw new CanvasReadError("unavailable", "The thumbnail couldn't be made.");
607
+ thumbCache.set(digest, out);
608
+ if (thumbCache.size > 64)
609
+ thumbCache.delete(thumbCache.keys().next().value);
610
+ return out;
611
+ });
612
+ return { key, digest, ...made };
613
+ }
614
+ export async function sipsThumbnail(image) {
615
+ const mime = imageMime(image);
616
+ if (mime === null)
617
+ throw new CanvasReadError("unavailable", "That capture isn't an image.");
618
+ let sips = false;
619
+ try {
620
+ sips = process.platform === "darwin" && lstatSync("/usr/bin/sips").isFile();
621
+ }
622
+ catch {
623
+ sips = false;
624
+ }
625
+ if (!sips) {
626
+ if (image.length <= CANVAS_THUMB_BYTES)
627
+ return { bytes: image, mime };
628
+ throw new CanvasReadError("unavailable", "Thumbnails are made on macOS.");
629
+ }
630
+ const dir = mkdtempSync(join(tmpdir(), "toolroll-canvas-thumb-"));
631
+ try {
632
+ const input = join(dir, mime === "image/png" ? "in.png" : "in.jpg");
633
+ writeFileSync(input, image, { mode: 0o600, flag: "wx" });
634
+ for (const [pixels, quality] of [[CANVAS_THUMB_PIXELS, 70], [Math.round(CANVAS_THUMB_PIXELS * 0.7), 55]]) {
635
+ const output = join(dir, `out-${pixels}.jpg`);
636
+ await new Promise((resolve, reject) => {
637
+ execFile("/usr/bin/sips", ["-s", "format", "jpeg", "-s", "formatOptions", String(quality), "-Z", String(pixels), input, "--out", output], { timeout: 15_000, killSignal: "SIGKILL", env: { PATH: "/usr/bin:/bin", LANG: "C" }, maxBuffer: 64 * 1024 }, error => error === null ? resolve() : reject(new CanvasReadError("unavailable", "The thumbnail couldn't be made.")));
638
+ });
639
+ const made = readOwnFile(output, 4 * CANVAS_THUMB_BYTES);
640
+ if (made !== null && imageMime(made) === "image/jpeg" && made.length <= CANVAS_THUMB_BYTES)
641
+ return { bytes: made, mime: "image/jpeg" };
642
+ }
643
+ throw new CanvasReadError("unavailable", "The thumbnail couldn't be made small enough.");
644
+ }
645
+ finally {
646
+ rmSync(dir, { recursive: true, force: true });
647
+ }
648
+ }
649
+ function readOwnFile(path, cap) {
650
+ try {
651
+ const stats = lstatSync(path);
652
+ if (!stats.isFile() || stats.nlink !== 1 || stats.size > cap)
653
+ return null;
654
+ return readFileSync(path);
655
+ }
656
+ catch {
657
+ return null;
658
+ }
659
+ }
660
+ const REQUEST_FILE = /^r-[0-9a-f]{10}\.json$/;
661
+ const fraction = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? Math.min(0.98, Math.max(0.02, value)) : fallback;
662
+ const TASK_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
663
+ function readPins(deps, repo, listing, screen) {
664
+ return withDirScope(dirs => {
665
+ const folder = youiFolder(dirs, repo, "requests");
666
+ if (folder === null)
667
+ return { pins: [], more: false };
668
+ const listedNames = dirs.listUpTo(folder, MAX_REQUEST_ENTRIES);
669
+ const names = listedNames.names.filter(name => REQUEST_FILE.test(name)).sort();
670
+ const webByPath = new Map();
671
+ const appScreens = new Set();
672
+ for (const section of listing.sections)
673
+ for (const one of section.screens) {
674
+ if (section.kind === "web" && one.path !== null)
675
+ webByPath.set(one.path, one.id);
676
+ if (section.kind === "web")
677
+ webByPath.set(one.title, one.id);
678
+ if (section.kind === "app")
679
+ appScreens.add(one.id);
680
+ }
681
+ const pins = [];
682
+ let more = listedNames.more || names.length > MAX_PINS, weight = 0;
683
+ for (const name of names.slice(0, MAX_PINS)) {
684
+ const id = name.slice(0, 12);
685
+ const raw = record(readJson(dirs, folder, name, REQUEST_BYTES));
686
+ const body = str(raw?.["body"], 8_000);
687
+ if (raw === null || raw["id"] !== id || body === null)
688
+ continue;
689
+ const kind = raw["kind"] === "comment" || raw["kind"] === "options" ? raw["kind"] : "change";
690
+ const target = record(raw["target"]), canvas = record(raw["canvas"]), author = record(raw["author"]);
691
+ const surface = str(canvas?.["surface"], 40);
692
+ const appearance = canvas?.["state"] === "light" || canvas?.["state"] === "dark" ? canvas["state"] : null;
693
+ const route = str(canvas?.["route"], 300) ?? str(target?.["route"], 300);
694
+ let on = null;
695
+ if (surface !== null && SLUG.test(surface) && route !== null && appScreens.has(route) && route.startsWith(`app:${surface}/`))
696
+ on = route;
697
+ else if (surface === null)
698
+ on = webByPath.get(str(target?.["route"], 300) ?? "") ?? webByPath.get(route ?? "") ?? null;
699
+ if (screen !== undefined && on !== screen)
700
+ continue;
701
+ const pin = {
702
+ id, screen: on, variant: appearance, kind, status: "open", body: paragraphs(body, 2_000),
703
+ author: line(str(author?.["name"], 100) ?? "you", 100) || "you",
704
+ element: target?.["scope"] === "element" && str(target["name"], 200) !== null ? line(target["name"], 200) : null,
705
+ x: fraction(canvas?.["xFrac"], 0.5), y: fraction(canvas?.["yFrac"], 0.35),
706
+ createdAt: str(raw["createdAt"], 40), task: null,
707
+ };
708
+ const filed = deps.filed?.(repo, id) ?? null;
709
+ const named = filed?.taskId ?? str(canvas?.["linkedTaskId"], 200) ?? taskFileTask(dirs, folder, id);
710
+ const task = named !== null && TASK_ID.test(named) ? deps.task?.(named) ?? null : null;
711
+ if (task !== null)
712
+ pin.task = { id: task.id, title: task.title === null ? null : line(task.title, 200), status: filed?.status ?? task.status };
713
+ const requestDone = raw["status"] === "addressed" || raw["status"] === "closed";
714
+ pin.status = requestDone || pin.task?.status === "done" ? "done" : pin.task !== null ? "filed" : "open";
715
+ weight += Buffer.byteLength(JSON.stringify(pin));
716
+ if (weight > PINS_JSON_BUDGET) {
717
+ more = true;
718
+ break;
719
+ }
720
+ pins.push(pin);
721
+ }
722
+ return { pins, more };
723
+ });
724
+ }
725
+ function taskFileTask(dirs, folder, id) {
726
+ const raw = record(readJson(dirs, folder, `${id}.task.json`, REQUEST_BYTES));
727
+ const task = raw?.["task"];
728
+ return str(record(task)?.["id"], 200) ?? str(task, 200);
729
+ }
730
+ export function canvasPins(deps, scope, params) {
731
+ if (params.screen !== undefined && params.screen !== null && (typeof params.screen !== "string" || !SCREEN_ID.test(params.screen))) {
732
+ throw new CanvasReadError("invalid_params", "screen must be a screen id");
733
+ }
734
+ const repo = resolveCanvasProject(scope, params.project);
735
+ const { listing } = locate(deps, scope, repo, null, false);
736
+ const result = { project: listing.project, ...readPins(deps, repo, listing, typeof params.screen === "string" ? params.screen : undefined) };
737
+ if (!scope.canSee(repo))
738
+ throw new CanvasReadError("not_found", "No such project.");
739
+ return result;
740
+ }
741
+ export function resetCanvasCachesForTest() {
742
+ listed.clear();
743
+ digests.clear();
744
+ thumbCache.clear();
745
+ sharedFreshness = null;
746
+ sharedThumbnails = null;
747
+ }