@open-artifact/server-sdk 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1075 @@
1
+ /**
2
+ * frame-host: serves an original artifact type (a folder whose index.html
3
+ * declares itself in an inline `// artifact.json` block) so its page runs as
4
+ * it would in its first home.
5
+ *
6
+ * Three windows take part:
7
+ *
8
+ * the outer Shell (the daemon's /a/<id>)
9
+ * └─ embeds ─▶ the inner shell (this server, /f/<token>/, Site.page)
10
+ * └─ embeds ─▶ the original page on its own origin
11
+ * (http://<id>.frame.localhost:<port>/_f/<ver>/, Site.content)
12
+ *
13
+ * The page gets `window.openArtifact` from the Frame Runtime this server injects
14
+ * first in its <head> (client/runtime.ts). Every capability call is a
15
+ * `__frame_cap` postMessage to the inner shell (client/shell.ts), which
16
+ * carries it here over HTTP and pushes events (db changes, room, file and
17
+ * comment changes, rewiring) back from one event stream.
18
+ *
19
+ * Backends live in the artifact folder: db/ (db.ts), comments.json
20
+ * (comments.ts), the files the page publishes and _blobs/ (files.ts). An
21
+ * agent's edits land on disk; a watcher sends them to open pages.
22
+ */
23
+ import { createHash, randomBytes } from 'node:crypto';
24
+ import { createReadStream, existsSync, readFileSync, readdirSync, statSync, watch } from 'node:fs';
25
+ import { ServerResponse } from 'node:http';
26
+ import * as nodeModule from 'node:module';
27
+ import { userInfo } from 'node:os';
28
+ import { dirname, join, resolve, sep } from 'node:path';
29
+ import { fileURLToPath } from 'node:url';
30
+ import { AGENT_AUTHOR, COMMENTS_FILE, CommentStore, agentView } from "./comments.js";
31
+ import { DbStore, docPathsOf } from "./db.js";
32
+ import { readDeclaration } from "./declaration.js";
33
+ import { BlobStore, FileStore, FrameError, cleanPath, contentTypeOf, reservedPath, typePath } from "./files.js";
34
+ import { STALE_GEN_MESSAGE, UNDECLARED_MESSAGE, } from "./wire.js";
35
+ export { parseDeclaration, readDeclaration, DECLARATION_LINE } from "./declaration.js";
36
+ export { FrameError } from "./files.js";
37
+ /** The Frame Runtime contract reported to pages. */
38
+ export const CONTRACT = '0.2.92';
39
+ /**
40
+ * Where the browser scripts and the shell page are: `$OPEN_ARTIFACT_FRAME_CLIENT_DIR`,
41
+ * else `client/` beside this module (src/frame/client from source, or
42
+ * dist/daemon/frame-host/client beside the bundle).
43
+ */
44
+ export const CLIENT_DIR = process.env.OPEN_ARTIFACT_FRAME_CLIENT_DIR || join(dirname(fileURLToPath(import.meta.url)), 'client');
45
+ /** Capabilities with a local backend; a declared one is granted. `artifact` (self) and `permissions` always are. */
46
+ const BACKED = new Set(['db', 'artifact', 'assets', 'downloads', 'comments', 'user', 'room', 'permissions']);
47
+ /** Declared capabilities that answer, but only with an error code: nothing here can serve them. */
48
+ const STUBBED = { mcp: 'server_not_connected', sample: 'tools_unavailable', tts: 'capability_disabled', paste: 'capability_disabled' };
49
+ /** Caps whose stale-generation reply is `unavailable`; `user` answers null; others use the fallback error code. */
50
+ const STALE_UNAVAILABLE = new Set(['db', 'downloads', 'files', 'paste', 'reads']);
51
+ const BODY_MAX = 64 * 1024 * 1024;
52
+ const UPLOAD_MAX = 21 * 1024 * 1024;
53
+ const WATCH_DEBOUNCE_MS = 300;
54
+ const PALETTE = ['#785ee8', '#dc3c3d', '#019c7f', '#fbb315', '#ce447d', '#10a122', '#257de0'];
55
+ const ROOM_LIMITS = { maxBytes: 4096, presenceHz: 30, keepaliveMs: 20_000, silenceMs: 150_000, maxPeers: 256, maxRooms: 0 };
56
+ function colorOf(id) {
57
+ let h = 0;
58
+ for (let i = 0; i < id.length; i++)
59
+ h = (Math.imul(h, 31) + id.charCodeAt(i)) | 0;
60
+ return PALETTE[Math.abs(h) % PALETTE.length] ?? '#c7c9d1';
61
+ }
62
+ function localUser() {
63
+ let name = 'You';
64
+ try {
65
+ name = userInfo().username || name;
66
+ }
67
+ catch {
68
+ // no passwd entry
69
+ }
70
+ return { id: 'local', name, avatarUrl: null, color: colorOf('local'), email: null, isOwner: true, canEdit: true };
71
+ }
72
+ function typeConfig(typeDir) {
73
+ try {
74
+ return JSON.parse(readFileSync(join(typeDir, 'artifact-type.json'), 'utf8'));
75
+ }
76
+ catch {
77
+ return {};
78
+ }
79
+ }
80
+ /** A fingerprint of what the type serves: index.html and artifact-type/ (names, sizes, times). */
81
+ function typeFingerprint(typeDir) {
82
+ const hash = createHash('sha256');
83
+ try {
84
+ hash.update(readFileSync(join(typeDir, 'index.html')));
85
+ }
86
+ catch {
87
+ hash.update('-');
88
+ }
89
+ const walk = (dir, rel, depth) => {
90
+ if (depth > 8)
91
+ return;
92
+ let entries;
93
+ try {
94
+ entries = readdirSync(dir, { withFileTypes: true });
95
+ }
96
+ catch {
97
+ return;
98
+ }
99
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
100
+ if (e.name.startsWith('.'))
101
+ continue;
102
+ const path = join(dir, e.name);
103
+ if (e.isDirectory())
104
+ walk(path, `${rel}/${e.name}`, depth + 1);
105
+ else if (e.isFile()) {
106
+ try {
107
+ const st = statSync(path);
108
+ hash.update(`\n${rel}/${e.name}\0${st.size}\0${st.mtimeMs}`);
109
+ }
110
+ catch {
111
+ // gone
112
+ }
113
+ }
114
+ }
115
+ };
116
+ walk(join(typeDir, 'artifact-type'), 'artifact-type', 0);
117
+ return hash.digest('hex').slice(0, 16);
118
+ }
119
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
120
+ /** Mounts one artifact folder. Throws when the type folder carries no declaration or the server has no content hosts. */
121
+ export async function mountFrameSite(root, ctx) {
122
+ const typeDir = resolve(ctx.typeDir ?? process.env.OPEN_ARTIFACT_TYPE_DIR ?? process.cwd());
123
+ const declaration = readDeclaration(typeDir);
124
+ if (!declaration)
125
+ throw new FrameError('not_frame_type', `${typeDir}/index.html has no // artifact.json declaration.`, 500);
126
+ if (!ctx.contentOrigin)
127
+ throw new FrameError('no_content_origin', 'frame-host needs serve({contentHosts: true}) and an art_ artifact id.', 500);
128
+ return new FrameSite(resolve(root), typeDir, declaration, ctx);
129
+ }
130
+ /** One open artifact of an original type. */
131
+ export class FrameSite {
132
+ root;
133
+ typeDir;
134
+ id;
135
+ page;
136
+ contentOrigin;
137
+ shellOrigin;
138
+ db;
139
+ comments;
140
+ files;
141
+ blobs;
142
+ /** The broker generation: bumped when the type or the files change under an open page. */
143
+ brokerGen = 1;
144
+ declaration;
145
+ title;
146
+ ver;
147
+ grants = [];
148
+ stubs = {};
149
+ me;
150
+ ctx;
151
+ shellOrigins;
152
+ config;
153
+ flagKeys = [];
154
+ typeVer;
155
+ clients = new Map();
156
+ touchTimer = null;
157
+ touchPaths = new Set();
158
+ presenceCache = null;
159
+ watchers = [];
160
+ watchTimer = null;
161
+ typeTimer = null;
162
+ pending = new Set();
163
+ constructor(root, typeDir, declaration, ctx) {
164
+ this.root = root;
165
+ this.typeDir = typeDir;
166
+ this.declaration = declaration;
167
+ this.ctx = ctx;
168
+ this.id = ctx.id;
169
+ this.title = ctx.title ?? '';
170
+ this.page = `/f/${randomBytes(18).toString('base64url')}/`;
171
+ this.contentOrigin = ctx.contentOrigin;
172
+ const port = new URL(this.contentOrigin).port;
173
+ this.shellOrigin = `http://127.0.0.1:${port}`;
174
+ this.shellOrigins = new Set([this.shellOrigin, `http://localhost:${port}`]);
175
+ this.db = new DbStore(root);
176
+ this.comments = new CommentStore(root);
177
+ this.files = new FileStore(root);
178
+ this.blobs = new BlobStore(root);
179
+ this.ver = this.files.manifest().ver;
180
+ this.config = typeConfig(typeDir);
181
+ this.me = localUser();
182
+ this.typeVer = typeFingerprint(typeDir);
183
+ this.applyDeclaration(declaration);
184
+ this.db.on('change', (paths) => this.broadcast({ t: 'db', paths }));
185
+ this.watch();
186
+ }
187
+ applyDeclaration(declaration) {
188
+ this.declaration = declaration;
189
+ const caps = declaration.capabilities ?? {};
190
+ this.grants = [...new Set([...Object.keys(caps).filter((c) => BACKED.has(c)), 'artifact', 'permissions'])];
191
+ this.stubs = Object.fromEntries(Object.keys(caps).flatMap((c) => (STUBBED[c] ? [[c, STUBBED[c]]] : [])));
192
+ const flags = caps.flags;
193
+ this.flagKeys = isObject(flags) && Array.isArray(flags.keys) ? flags.keys.filter((k) => typeof k === 'string') : [];
194
+ }
195
+ log(line) {
196
+ this.ctx.log?.(line);
197
+ }
198
+ close() {
199
+ if (this.watchTimer)
200
+ clearTimeout(this.watchTimer);
201
+ if (this.typeTimer)
202
+ clearTimeout(this.typeTimer);
203
+ if (this.touchTimer)
204
+ clearTimeout(this.touchTimer);
205
+ for (const w of this.watchers) {
206
+ try {
207
+ w.close();
208
+ }
209
+ catch {
210
+ // already closed
211
+ }
212
+ }
213
+ this.watchers = [];
214
+ for (const c of this.clients.values())
215
+ c.end();
216
+ this.clients.clear();
217
+ }
218
+ hasBlob(id) {
219
+ return !!this.blobs.meta(id);
220
+ }
221
+ // ---- watching the folders ----------------------------------------------------------------------------------------
222
+ watch() {
223
+ try {
224
+ const w = watch(this.root, { recursive: true }, (_event, name) => {
225
+ if (!name)
226
+ return;
227
+ const rel = String(name).split(sep).join('/');
228
+ if (rel.split('/').some((s) => s.startsWith('.')) || rel.startsWith('_blobs/') || rel.startsWith('history/'))
229
+ return;
230
+ this.pending.add(rel);
231
+ if (this.watchTimer)
232
+ clearTimeout(this.watchTimer);
233
+ this.watchTimer = setTimeout(() => this.flushWatch(), WATCH_DEBOUNCE_MS);
234
+ });
235
+ w.on('error', () => { });
236
+ this.watchers.push(w);
237
+ }
238
+ catch (error) {
239
+ this.log(`watch: ${error?.message ?? error}`);
240
+ }
241
+ // The type folder: a new index.html or artifact-type/ under an open page rewires its broker.
242
+ try {
243
+ const w = watch(this.typeDir, { recursive: true }, (_event, name) => {
244
+ if (name && String(name).split(sep).some((s) => s.startsWith('.')))
245
+ return;
246
+ if (this.typeTimer)
247
+ clearTimeout(this.typeTimer);
248
+ this.typeTimer = setTimeout(() => this.typeChanged(), WATCH_DEBOUNCE_MS);
249
+ });
250
+ w.on('error', () => { });
251
+ this.watchers.push(w);
252
+ }
253
+ catch (error) {
254
+ this.log(`watch type: ${error?.message ?? error}`);
255
+ }
256
+ }
257
+ /** Re-reads the type; when what it serves changed, rewires. */
258
+ typeChanged() {
259
+ const next = typeFingerprint(this.typeDir);
260
+ if (next === this.typeVer)
261
+ return false;
262
+ this.typeVer = next;
263
+ let declaration = null;
264
+ try {
265
+ declaration = readDeclaration(this.typeDir);
266
+ }
267
+ catch (error) {
268
+ this.log(`type: ${error?.message ?? error}`);
269
+ }
270
+ if (declaration)
271
+ this.applyDeclaration(declaration);
272
+ this.rewire('type');
273
+ return true;
274
+ }
275
+ /** A new broker generation: calls stamped with the old one are not run, open shells cut theirs and reload. */
276
+ rewire(reason) {
277
+ this.brokerGen += 1;
278
+ this.broadcast({ t: 'rewired', brokerGen: this.brokerGen, caps: this.grants, reason });
279
+ }
280
+ /** Applies what the folder watcher gathered (exposed for tests: watchers are slow to settle). */
281
+ flushWatch() {
282
+ const rels = [...this.pending];
283
+ this.pending.clear();
284
+ const docs = docPathsOf(rels);
285
+ if (docs.length || rels.some((r) => r === 'db' || r.startsWith('db/')))
286
+ this.broadcast({ t: 'db', paths: docs });
287
+ if (rels.includes(COMMENTS_FILE))
288
+ this.commentsChanged();
289
+ if (rels.some((r) => r !== COMMENTS_FILE && !r.startsWith('db/') && r !== 'db'))
290
+ this.filesChanged(rels.filter((r) => !reservedPath(r)));
291
+ }
292
+ /** Files changed on disk, not by this page's own publish: a new manifest rewires and reloads open pages. */
293
+ filesChanged(paths = []) {
294
+ const m = this.files.manifest();
295
+ if (m.ver === this.ver)
296
+ return false;
297
+ this.ver = m.ver;
298
+ this.rewire('files');
299
+ this.broadcast({ t: 'files', ver: m.ver, paths });
300
+ return true;
301
+ }
302
+ broadcast(event) {
303
+ for (const c of this.clients.values())
304
+ c.send(event);
305
+ }
306
+ /** A write from the page: the daemon records it (best effort, gathered). */
307
+ touched(paths) {
308
+ for (const p of paths)
309
+ this.touchPaths.add(p);
310
+ if (this.touchTimer)
311
+ return;
312
+ this.touchTimer = setTimeout(() => {
313
+ this.touchTimer = null;
314
+ const list = [...this.touchPaths].slice(0, 100);
315
+ this.touchPaths.clear();
316
+ const daemon = this.ctx.daemon;
317
+ if (daemon?.available)
318
+ daemon.touch(this.id, { author: 'owner', paths: list }).catch(() => { });
319
+ }, 1000);
320
+ this.touchTimer.unref?.();
321
+ }
322
+ // ---- requests on the inner shell's origin (under Site.page) ------------------------------------------------------
323
+ async handle(req, res) {
324
+ const url = new URL(req.url ?? '/', 'http://local');
325
+ const p = url.pathname;
326
+ if (!(res instanceof ServerResponse)) {
327
+ if (p === '/api/frame/events' && this.ctx.local(req))
328
+ return this.events(req, res, url);
329
+ res.writeHead(404);
330
+ res.end();
331
+ return;
332
+ }
333
+ const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(p);
334
+ if (blob)
335
+ return this.sendBlob(req, res, blob[1]);
336
+ if (!this.ctx.local(req))
337
+ return deny(req, res, 403, 'Frame pages open on this computer only.');
338
+ if (p === '/' || p === '/index.html')
339
+ return this.sendClientFile(req, res, 'shell.html');
340
+ if (p === '/shell.js' || p === '/shell.css' || p === '/comments.js' || p === '/comments.css')
341
+ return this.sendClientFile(req, res, p.slice(1));
342
+ if (!p.startsWith('/api/frame/'))
343
+ return deny(req, res, 404, 'Not found');
344
+ if (!this.sameOrigin(req))
345
+ return deny(req, res, 403, 'Not from this page.');
346
+ const name = p.slice('/api/frame/'.length);
347
+ try {
348
+ if (name === 'events' && req.method === 'GET')
349
+ return this.events(req, res, url);
350
+ if (name === 'session' && req.method === 'GET')
351
+ return json(res, 200, this.session());
352
+ if (req.method !== 'POST')
353
+ return deny(req, res, 405, 'Method not allowed');
354
+ if (name === 'upload') {
355
+ const stale = this.gate('assets', numberOrUndefined(url.searchParams.get('gen')));
356
+ if (stale)
357
+ return json(res, 200, stale);
358
+ const data = await readBody(req, UPLOAD_MAX);
359
+ const out = this.blobs.upload(data, url.searchParams.get('type') ?? req.headers['content-type']);
360
+ this.touched(['_blobs']);
361
+ return json(res, 200, { result: out });
362
+ }
363
+ if (!String(req.headers['content-type'] ?? '').startsWith('application/json'))
364
+ return deny(req, res, 415, 'JSON only.');
365
+ const body = JSON.parse((await readBody(req, BODY_MAX)).toString('utf8') || '{}');
366
+ if (name === 'cap')
367
+ return json(res, 200, await this.call(body));
368
+ if (name === 'title')
369
+ return json(res, 200, await this.proposeTitle(body));
370
+ if (name === 'agent')
371
+ return json(res, 200, await this.askAgent(body));
372
+ if (name === 'activity')
373
+ return json(res, 200, await this.activity());
374
+ return deny(req, res, 404, 'Not found');
375
+ }
376
+ catch (error) {
377
+ if (!res.headersSent)
378
+ return json(res, error?.status ?? 500, { error: errorOf(error) });
379
+ res.destroy();
380
+ }
381
+ }
382
+ /** The inner shell's own requests: from its origin, never from a page elsewhere. */
383
+ sameOrigin(req) {
384
+ const origin = req.headers.origin;
385
+ if (origin !== undefined)
386
+ return this.shellOrigins.has(origin);
387
+ const site = req.headers['sec-fetch-site'];
388
+ return site === undefined || site === 'same-origin' || site === 'none';
389
+ }
390
+ /** Per-capability config, as `__frame_init.capabilities[cap].config` or a grant carries it. */
391
+ configs() {
392
+ const out = {};
393
+ for (const cap of this.grants) {
394
+ if (cap === 'artifact')
395
+ out[cap] = { id: this.id, key: this.declaration.key, publish: true };
396
+ else if (cap === 'user') {
397
+ // for the owner (see runtime.ts).
398
+ out[cap] = { id: this.me.id, color: this.me.color, owner: true, canEdit: true, profile: true, email: false };
399
+ }
400
+ else if (cap === 'room')
401
+ out[cap] = { limits: ROOM_LIMITS };
402
+ else
403
+ out[cap] = {};
404
+ }
405
+ return out;
406
+ }
407
+ session() {
408
+ const flags = {};
409
+ const openArtifact = isObject(this.config.openArtifact) ? this.config.openArtifact : {};
410
+ const configured = (isObject(openArtifact.flags) ? openArtifact.flags : isObject(this.config.flags) ? this.config.flags : {});
411
+ for (const k of this.flagKeys)
412
+ flags[k] = configured[k] === true;
413
+ return {
414
+ id: this.id,
415
+ title: this.title,
416
+ key: this.declaration.key,
417
+ ver: this.ver,
418
+ contract: CONTRACT,
419
+ contentOrigin: this.contentOrigin,
420
+ shellOrigin: this.shellOrigin,
421
+ brokerGen: this.brokerGen,
422
+ grants: this.grants,
423
+ stubs: this.stubs,
424
+ configs: this.configs(),
425
+ capabilities: this.declaration.capabilities,
426
+ flags,
427
+ readyTimeoutS: Number(this.declaration.monitoring?.readyTimeoutS) || 60,
428
+ me: this.me,
429
+ comments: { available: this.grants.includes('comments'), count: this.comments.openCount() },
430
+ agent: { available: !!this.ctx.daemon?.available, name: this.ctx.agentName ?? null },
431
+ };
432
+ }
433
+ /** The event stream of one inner shell: JSON objects, over a `baoyu-sse` WebSocket or as SSE. */
434
+ events(req, res, url) {
435
+ const client = String(url.searchParams.get('c') ?? '');
436
+ if (!/^[A-Za-z0-9_-]{8,64}$/.test(client)) {
437
+ res.writeHead(400);
438
+ res.end();
439
+ return;
440
+ }
441
+ const sse = res instanceof ServerResponse;
442
+ if (sse)
443
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
444
+ else
445
+ res.writeHead(200);
446
+ const send = (obj) => {
447
+ try {
448
+ res.write(sse ? `data: ${JSON.stringify(obj)}\n\n` : JSON.stringify(obj));
449
+ }
450
+ catch {
451
+ // closing
452
+ }
453
+ };
454
+ this.clients.get(client)?.end();
455
+ const entry = { send, presence: {}, end: () => res.end() };
456
+ this.clients.set(client, entry);
457
+ const ping = sse ? setInterval(() => res.write(': ping\n\n'), 25_000) : null;
458
+ req.on('close', () => {
459
+ if (ping)
460
+ clearInterval(ping);
461
+ if (this.clients.get(client) === entry) {
462
+ this.clients.delete(client);
463
+ this.broadcast({ t: 'peers', peers: this.peers() });
464
+ }
465
+ });
466
+ send({ t: 'hello', ver: this.ver, brokerGen: this.brokerGen, peers: this.peers(), count: this.comments.openCount() });
467
+ this.broadcast({ t: 'peers', peers: this.peers() });
468
+ }
469
+ peers() {
470
+ return [...this.clients.entries()].map(([peer, c]) => ({ peer, by: this.me.id, name: this.me.name, presence: c.presence, kind: 'user' }));
471
+ }
472
+ // ---- capabilities ------------------------------------------------------------------------------------------------
473
+ gate(cap, gen) {
474
+ if (gen !== undefined && gen !== this.brokerGen) {
475
+ if (cap === 'user')
476
+ return { result: null };
477
+ const code = STALE_UNAVAILABLE.has(cap) ? 'unavailable' : 'upstream_error';
478
+ return { error: { code, message: STALE_GEN_MESSAGE, ...(cap === 'mcp' ? { retryable: true } : {}) } };
479
+ }
480
+ return null;
481
+ }
482
+ /** `POST /api/frame/cap`: one call, answered as `{result}` or `{error}`. */
483
+ async call(body) {
484
+ const cap = String(body.cap ?? '') === 'self' ? 'artifact' : String(body.cap ?? '');
485
+ const method = String(body.method ?? '');
486
+ const gen = typeof body.brokerGen === 'number' ? body.brokerGen : undefined;
487
+ const stale = this.gate(cap, gen);
488
+ if (stale)
489
+ return stale;
490
+ const args = Array.isArray(body.args) ? body.args : [body.args];
491
+ try {
492
+ return { result: await this.capability(cap, method, isObject(args[0]) ? args[0] : {}, String(body.client ?? '')) };
493
+ }
494
+ catch (error) {
495
+ this.log(`${cap}.${method}: ${error?.code ?? 'error'} ${error?.message ?? error}`);
496
+ return { error: errorOf(error) };
497
+ }
498
+ }
499
+ author() {
500
+ return { kind: 'user', name: this.me.name, principal: this.me.id };
501
+ }
502
+ async capability(cap, method, a, client) {
503
+ if (this.stubs[cap])
504
+ throw new FrameError(this.stubs[cap], `${cap} is not available on this computer.`);
505
+ if (!this.grants.includes(cap))
506
+ throw new FrameError('not_granted', `${cap}: ${UNDECLARED_MESSAGE}`);
507
+ const path = () => String(a.path ?? '');
508
+ switch (`${cap}.${method}`) {
509
+ case 'db.get': {
510
+ const data = this.db.readDoc(path());
511
+ return data ? { exists: true, data } : { exists: false };
512
+ }
513
+ case 'db.set':
514
+ this.db.set(path(), a.data);
515
+ this.touched([`db/${path()}`]);
516
+ return {};
517
+ case 'db.update':
518
+ this.db.update(path(), a.data);
519
+ this.touched([`db/${path()}`]);
520
+ return {};
521
+ case 'db.delete':
522
+ this.db.delete(path());
523
+ this.touched([`db/${path()}`]);
524
+ return {};
525
+ case 'db.add': {
526
+ const out = this.db.add(path(), a.data);
527
+ this.touched([`db/${out.path}`]);
528
+ return out;
529
+ }
530
+ case 'db.query':
531
+ return { docs: this.db.query(path(), a.spec ?? {}) };
532
+ case 'db.acquire':
533
+ return this.db.acquire(path(), isObject(a.options) ? a.options : {});
534
+ case 'db.release':
535
+ return this.db.release(path(), a.holder);
536
+ case 'artifact.publish':
537
+ if (typeof a.html === 'string')
538
+ throw new FrameError('read_only_path', "index.html belongs to this artifact's type; publish files instead.", 403);
539
+ return this.publish(isObject(a.files) ? a.files : {}, client);
540
+ case 'artifact.sync':
541
+ return { version: this.ver, files: this.files.manifest().files };
542
+ case 'artifact.metadata': {
543
+ const refs = Array.isArray(a.refs) ? a.refs : [];
544
+ const out = {};
545
+ for (const ref of refs.slice(0, 100)) {
546
+ if (ref === this.id || ref === 'self')
547
+ out[String(ref)] = { id: this.id, title: this.title, type: this.declaration.key };
548
+ }
549
+ return out;
550
+ }
551
+ case 'artifact.search':
552
+ return { results: [] };
553
+ case 'artifact.edit':
554
+ throw new FrameError('capability_disabled', 'edit() is for live documents; publish the files instead.');
555
+ case 'assets.list':
556
+ return this.blobs.list();
557
+ case 'assets.delete': {
558
+ const out = this.blobs.delete(a.ref);
559
+ if (out.deleted)
560
+ this.touched(['_blobs']);
561
+ return out;
562
+ }
563
+ case 'user.me':
564
+ case 'user.profile':
565
+ return { id: this.me.id, name: this.me.name, avatarUrl: this.me.avatarUrl, color: this.me.color };
566
+ case 'user.email':
567
+ return null;
568
+ case 'user.profiles': {
569
+ const ids = Array.isArray(a.ids) ? a.ids : [];
570
+ return Object.fromEntries(ids
571
+ .filter((i) => i === this.me.id)
572
+ .map((i) => [i, { id: i, name: this.me.name, avatarUrl: null, color: this.me.color, email: null, isMe: true, guest: false, roles: null }]));
573
+ }
574
+ case 'user.access': {
575
+ const ids = Array.isArray(a.ids) ? a.ids : [];
576
+ return Object.fromEntries(ids.map((i) => [String(i), i === this.me.id ? 'owner' : null]));
577
+ }
578
+ case 'user.search':
579
+ return [];
580
+ case 'comments.list':
581
+ return { threads: this.comments.threads({ all: a.all !== false }).map(pageThread) };
582
+ case 'comments.create': {
583
+ const thread = this.comments.create({
584
+ anchor: a.anchor,
585
+ label: a.label,
586
+ detail: a.detail,
587
+ location: { custom: a.anchor ?? null, ...(typeof a.file === 'string' ? { file: a.file } : {}) },
588
+ text: a.text,
589
+ author: this.author(),
590
+ });
591
+ this.commentsChanged();
592
+ return { threadId: thread.id, commentId: thread.messages[0].id, thread: pageThread(thread) };
593
+ }
594
+ case 'comments.reply': {
595
+ const { thread, message } = this.comments.addMessage(a.threadId, this.author(), a.text);
596
+ this.commentsChanged();
597
+ return { threadId: thread.id, commentId: message.id, thread: pageThread(thread) };
598
+ }
599
+ case 'comments.resolve': {
600
+ const thread = this.comments.setResolved(a.threadId, a.resolved !== false);
601
+ this.commentsChanged();
602
+ return { thread: pageThread(thread) };
603
+ }
604
+ case 'comments.move': {
605
+ const have = this.comments.load().threads.find((t) => t.id === a.threadId);
606
+ const thread = this.comments.move(a.threadId, a.anchor, { ...(have?.location ?? {}), custom: a.anchor ?? null });
607
+ this.commentsChanged();
608
+ return { thread: pageThread(thread) };
609
+ }
610
+ case 'comments.delete': {
611
+ const out = this.comments.remove(a.threadId, a.commentId);
612
+ this.commentsChanged();
613
+ return out;
614
+ }
615
+ case 'comments.sendToAgent':
616
+ return this.sendToAgent(a);
617
+ case 'comments.canSendToAgent':
618
+ return this.canSendToAgent();
619
+ case 'room.emit':
620
+ if (JSON.stringify(a.data ?? null).length > ROOM_LIMITS.maxBytes)
621
+ throw new FrameError('too_large', `A room message is at most ${ROOM_LIMITS.maxBytes} bytes.`);
622
+ this.broadcast({ t: 'room', topic: String(a.topic ?? ''), data: a.data ?? null, from: client, by: this.me.id });
623
+ return {};
624
+ case 'room.presence': {
625
+ const c = this.clients.get(client);
626
+ if (c)
627
+ c.presence = { ...c.presence, ...(isObject(a.patch) ? a.patch : {}) };
628
+ this.broadcast({ t: 'peers', peers: this.peers() });
629
+ return {};
630
+ }
631
+ case 'room.peers':
632
+ return this.peers();
633
+ case 'room.sendToAgentSession': {
634
+ const text = typeof a.data === 'string' ? a.data : JSON.stringify(a.data ?? null);
635
+ if (Buffer.byteLength(text) > ROOM_LIMITS.maxBytes)
636
+ throw new FrameError('too_large', `sendToAgentSession() takes at most ${ROOM_LIMITS.maxBytes} bytes.`);
637
+ const out = await this.ctx.agentHook.request({ label: this.declaration.key ?? 'page', text });
638
+ return { to: out?.via ?? 'agent' };
639
+ }
640
+ case 'room.canSendToAgentSession':
641
+ return (await this.canSendToAgent()) === 'available';
642
+ default:
643
+ throw new FrameError('invalid_request', `${cap}.${method} is not supported here.`);
644
+ }
645
+ }
646
+ /** The page's publish: its wire form (`{text}` | `{b64}` | null | `{delete:true}`, each with an optional ifMatch). */
647
+ publish(files, client) {
648
+ const plan = {};
649
+ for (const [p, raw] of Object.entries(files)) {
650
+ const spec = isObject(raw) ? raw : null;
651
+ const guard = spec && 'ifMatch' in spec ? { ifMatch: spec.ifMatch } : {};
652
+ if (raw === null || spec?.delete === true) {
653
+ plan[p] = { delete: true, ...guard };
654
+ continue;
655
+ }
656
+ let data;
657
+ if (typeof spec?.b64 === 'string')
658
+ data = Buffer.from(spec.b64, 'base64');
659
+ else if (typeof spec?.text === 'string')
660
+ data = Buffer.from(spec.text, 'utf8');
661
+ else
662
+ throw new FrameError('invalid_content', `${p}: no content.`);
663
+ plan[p] = { data, ...(typeof spec.contentType === 'string' ? { contentType: spec.contentType } : {}), ...guard };
664
+ }
665
+ const out = this.files.publish(plan);
666
+ if (out.version !== this.ver) {
667
+ // The page's own write: no rewiring (its calls stay valid); other shells reload.
668
+ this.ver = out.version;
669
+ this.broadcast({ t: 'files', ver: out.version, paths: out.changed.map((c) => c.path), from: client });
670
+ }
671
+ if (out.changed.length)
672
+ this.touched(out.changed.map((c) => c.path));
673
+ return out;
674
+ }
675
+ commentsChanged() {
676
+ this.broadcast({ t: 'comments', count: this.comments.openCount() });
677
+ }
678
+ async presence() {
679
+ const daemon = this.ctx.daemon;
680
+ if (!daemon?.available)
681
+ return null;
682
+ if (this.presenceCache && Date.now() - this.presenceCache.at < 3000)
683
+ return this.presenceCache.value;
684
+ let value = null;
685
+ try {
686
+ value = await daemon.presence(this.id);
687
+ }
688
+ catch {
689
+ value = null;
690
+ }
691
+ this.presenceCache = { at: Date.now(), value };
692
+ return value;
693
+ }
694
+ async canSendToAgent() {
695
+ if (!this.ctx.daemon?.available)
696
+ return 'off';
697
+ const p = await this.presence();
698
+ if (!p)
699
+ return 'no_session';
700
+ return p.canSend === false ? 'no_session' : 'available';
701
+ }
702
+ async sendToAgent(a) {
703
+ let threadId = typeof a.threadId === 'string' ? a.threadId : '';
704
+ if (!threadId) {
705
+ threadId = this.comments.create({ anchor: a.anchor, label: a.label, detail: a.detail, location: { custom: a.anchor ?? null }, text: a.text, author: this.author() }).id;
706
+ }
707
+ else if (typeof a.text === 'string' && a.text.trim()) {
708
+ this.comments.addMessage(threadId, this.author(), a.text);
709
+ }
710
+ this.comments.markSent(threadId);
711
+ this.commentsChanged();
712
+ const thread = this.comments.load().threads.find((t) => t.id === threadId);
713
+ let out;
714
+ try {
715
+ out = await this.ctx.agentHook.thread(agentView(thread));
716
+ }
717
+ catch (error) {
718
+ throw new FrameError('agent_unavailable', error?.message ?? 'The agent could not be reached.', 409);
719
+ }
720
+ const marked = this.comments.markDelivered(threadId, out?.via === 'wait' ? 'wait' : 'hook');
721
+ this.commentsChanged();
722
+ return { threadId, status: out?.status ?? 'delivered', thread: pageThread(marked) };
723
+ }
724
+ async proposeTitle({ title, ifUnnamed }) {
725
+ if (typeof title !== 'string' || !title.trim())
726
+ return { applied: false };
727
+ const clean = title.trim().slice(0, 200);
728
+ if (ifUnnamed && this.title && !/^untitled\b/i.test(this.title))
729
+ return { applied: false };
730
+ const daemon = this.ctx.daemon;
731
+ if (!daemon?.available)
732
+ return { applied: false };
733
+ try {
734
+ await daemon.touch(this.id, { author: 'owner', paths: [], title: clean });
735
+ this.title = clean;
736
+ return { applied: true, title: clean };
737
+ }
738
+ catch {
739
+ return { applied: false };
740
+ }
741
+ }
742
+ async askAgent({ text }) {
743
+ const out = await this.ctx.agentHook.request({ label: this.declaration.key ?? 'page', text: String(text ?? '').slice(0, 20_000) });
744
+ return { status: out?.status ?? 'delivered', via: out?.via ?? null };
745
+ }
746
+ async activity() {
747
+ const p = await this.presence();
748
+ return { working: !!p?.busy, available: !!p };
749
+ }
750
+ // ---- the page's own origin (Site.content) ------------------------------------------------------------------------
751
+ async content(req, res) {
752
+ if (req.method !== 'GET' && req.method !== 'HEAD')
753
+ return deny(req, res, 405, 'Method not allowed');
754
+ res.on('finish', () => {
755
+ if (res.statusCode >= 400 && !String(req.url).endsWith('/_files.json'))
756
+ this.log(`content ${req.method} ${req.url} → ${res.statusCode}`);
757
+ });
758
+ const url = new URL(req.url ?? '/', 'http://local');
759
+ const p = url.pathname;
760
+ if (p === '/' || p === '/index.html') {
761
+ res.writeHead(302, { Location: `/_f/${this.ver}/${url.search}`, 'Cache-Control': 'no-store' }).end();
762
+ return;
763
+ }
764
+ if (p === '/_runtime/open-artifact-frame.js')
765
+ return this.sendScript(req, res, 'runtime');
766
+ const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(p);
767
+ if (blob)
768
+ return this.sendBlob(req, res, blob[1]);
769
+ const m = /^\/_f\/([A-Za-z0-9_-]{1,128})\/(.*)$/.exec(p);
770
+ if (!m)
771
+ return deny(req, res, 404, 'Not found');
772
+ let rel;
773
+ try {
774
+ rel = decodeURIComponent(m[2]);
775
+ }
776
+ catch {
777
+ return deny(req, res, 400, 'Bad path');
778
+ }
779
+ if (rel === '' || rel === 'index.html')
780
+ return this.sendIndex(req, res);
781
+ if (rel === '_files.json') {
782
+ const manifest = this.files.manifest();
783
+ // An artifact with no files yet has no listing: the original pages read that 404 as "start empty".
784
+ if (Object.keys(manifest.files).length === 0)
785
+ return json(res, 404, { code: 'empty', message: 'No files yet.' }, req.method === 'HEAD');
786
+ return json(res, 200, { ver: manifest.ver, files: manifest.files }, req.method === 'HEAD');
787
+ }
788
+ const clean = cleanPath(rel);
789
+ if (!clean || clean.split('/').some((s) => s.startsWith('.')))
790
+ return deny(req, res, 404, 'Not found');
791
+ if (clean.startsWith('artifact-type/')) {
792
+ const file = join(this.typeDir, clean);
793
+ if (!file.startsWith(join(this.typeDir, 'artifact-type') + sep))
794
+ return deny(req, res, 404, 'Not found');
795
+ return this.sendFile(req, res, file, contentTypeOf(file), true);
796
+ }
797
+ if (typePath(clean))
798
+ return deny(req, res, 404, 'Not found');
799
+ const file = this.files.resolve(clean);
800
+ if (!file)
801
+ return deny(req, res, 404, 'Not found');
802
+ return this.sendFile(req, res, file, contentTypeOf(file));
803
+ }
804
+ contentUpgrade(_req, socket) {
805
+ socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
806
+ }
807
+ /** The type's index.html with the Frame Runtime first in its <head>. */
808
+ sendIndex(req, res) {
809
+ let html;
810
+ try {
811
+ html = readFileSync(join(this.typeDir, 'index.html'), 'utf8');
812
+ }
813
+ catch {
814
+ return deny(req, res, 500, 'The type has no index.html.');
815
+ }
816
+ const boot = {
817
+ shellOrigin: this.shellOrigin,
818
+ id: this.id,
819
+ key: this.declaration.key,
820
+ grants: this.grants,
821
+ stubs: Object.keys(this.stubs),
822
+ contract: CONTRACT,
823
+ ...(process.env.OPEN_ARTIFACT_FRAME_DEBUG ? { debug: true } : {}),
824
+ };
825
+ const safe = (v) => JSON.stringify(v).replace(/[<\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
826
+ const inject = `<script>window.__FRAME_PREAMBLE=${safe({ origins: [this.shellOrigin] })};window.__OPEN_ARTIFACT_FRAME=${safe(boot)};</script>` +
827
+ `<script src="/_runtime/open-artifact-frame.js"></script>`;
828
+ const head = /<head\b[^>]*>/i.exec(html);
829
+ const out = head ? html.slice(0, head.index + head[0].length) + inject + html.slice(head.index + head[0].length) : inject + html;
830
+ const body = Buffer.from(out, 'utf8');
831
+ res.writeHead(200, {
832
+ 'Content-Type': 'text/html; charset=utf-8',
833
+ 'Content-Length': body.length,
834
+ 'Cache-Control': 'no-store',
835
+ // Every ancestor counts: the inner shell and the Open Artifact Shell around it, both on this computer.
836
+ 'Content-Security-Policy': 'frame-ancestors http://127.0.0.1:* http://localhost:*',
837
+ 'X-Content-Type-Options': 'nosniff',
838
+ 'Referrer-Policy': 'no-referrer',
839
+ });
840
+ res.end(req.method === 'HEAD' ? undefined : body);
841
+ }
842
+ sendClientFile(req, res, name) {
843
+ if (name === 'shell.js')
844
+ return this.sendScript(req, res, 'shell');
845
+ if (name === 'comments.js' || name === 'comments.css') {
846
+ return this.sendFile(req, res, builtClientFile(name), name.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8');
847
+ }
848
+ const port = new URL(this.shellOrigin).port;
849
+ if (name === 'shell.html') {
850
+ return this.sendFile(req, res, join(CLIENT_DIR, name), 'text/html; charset=utf-8', false, {
851
+ 'Content-Security-Policy': [
852
+ "default-src 'none'",
853
+ "script-src 'self'",
854
+ "style-src 'self' 'unsafe-inline'",
855
+ "img-src 'self' data: blob:",
856
+ // The comment views' font (Inter) is inlined as data: URLs in comments.css.
857
+ "font-src 'self' data:",
858
+ `connect-src 'self' ws://127.0.0.1:${port} ws://localhost:${port}`,
859
+ // CSP host sources cannot spell an id with '_', so: any artifact origin on this server's port.
860
+ `frame-src http://*.frame.localhost:${port}`,
861
+ "base-uri 'none'",
862
+ "form-action 'none'",
863
+ ].join('; '),
864
+ 'Referrer-Policy': 'origin',
865
+ });
866
+ }
867
+ return this.sendFile(req, res, join(CLIENT_DIR, name), 'text/css; charset=utf-8');
868
+ }
869
+ /** A browser script: the built `<name>.js`, or, from source, `<name>.ts` with its types stripped. */
870
+ sendScript(req, res, name) {
871
+ const built = join(CLIENT_DIR, `${name}.js`);
872
+ try {
873
+ if (statSync(built).isFile())
874
+ return this.sendFile(req, res, built, 'text/javascript; charset=utf-8');
875
+ }
876
+ catch {
877
+ // not built: from source
878
+ }
879
+ let code;
880
+ try {
881
+ code = scriptFromSource(join(CLIENT_DIR, `${name}.ts`));
882
+ }
883
+ catch (error) {
884
+ this.log(`client ${name}: ${error?.message ?? error}`);
885
+ return deny(req, res, 500, `The frame ${name} script is missing.`);
886
+ }
887
+ const body = Buffer.from(code, 'utf8');
888
+ res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Content-Length': body.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
889
+ res.end(req.method === 'HEAD' ? undefined : body);
890
+ }
891
+ sendBlob(req, res, id) {
892
+ const meta = this.blobs.meta(id);
893
+ if (!meta)
894
+ return deny(req, res, 404, 'Not found');
895
+ const extra = meta.contentType === 'image/svg+xml' ? { 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox" } : {};
896
+ return this.sendFile(req, res, join(this.blobs.dir, id), meta.contentType, true, { ...extra, 'Cache-Control': 'public, max-age=31536000, immutable' });
897
+ }
898
+ sendFile(req, res, file, type, cacheable = false, extra = {}) {
899
+ let st;
900
+ try {
901
+ st = statSync(file);
902
+ if (!st.isFile())
903
+ throw new Error('not a file');
904
+ }
905
+ catch {
906
+ return deny(req, res, 404, 'Not found');
907
+ }
908
+ const etag = `W/"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
909
+ const headers = {
910
+ 'Content-Type': type,
911
+ 'Cache-Control': cacheable ? 'no-cache' : 'no-store',
912
+ ETag: etag,
913
+ 'X-Content-Type-Options': 'nosniff',
914
+ ...extra,
915
+ };
916
+ if (req.headers['if-none-match'] === etag) {
917
+ res.writeHead(304, headers).end();
918
+ return;
919
+ }
920
+ res.writeHead(200, { ...headers, 'Content-Length': st.size });
921
+ if (req.method === 'HEAD')
922
+ return void res.end();
923
+ createReadStream(file)
924
+ .on('error', () => res.destroy())
925
+ .pipe(res);
926
+ }
927
+ }
928
+ // ---- helpers -----------------------------------------------------------------------------------------------------------
929
+ const stripped = new Map();
930
+ /**
931
+ * A client file only a build makes (the comment views, comments.js and
932
+ * comments.css): beside the bundle, or, from source, in the repository's
933
+ * built frame-host client folder.
934
+ */
935
+ function builtClientFile(name) {
936
+ const here = join(CLIENT_DIR, name);
937
+ if (existsSync(here))
938
+ return here;
939
+ return join(CLIENT_DIR, '..', '..', '..', '..', '..', 'dist', 'daemon', 'frame-host', 'client', name);
940
+ }
941
+ /** A client .ts as a browser script: types stripped by Node (no bundling: the client files import types only). */
942
+ function scriptFromSource(file) {
943
+ const st = statSync(file);
944
+ const have = stripped.get(file);
945
+ if (have && have.mtimeMs === st.mtimeMs)
946
+ return have.code;
947
+ const strip = nodeModule.stripTypeScriptTypes;
948
+ if (typeof strip !== 'function')
949
+ throw new Error('this Node cannot strip TypeScript; build the client scripts (node scripts/build.mjs --only frame).');
950
+ const code = strip(readFileSync(file, 'utf8'), { mode: 'strip' });
951
+ stripped.set(file, { mtimeMs: st.mtimeMs, code });
952
+ return code;
953
+ }
954
+ const numberOrUndefined = (v) => (v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
955
+ /** A thread as a page sees it. */
956
+ function pageThread(t) {
957
+ let anchor = t.location?.custom;
958
+ if (anchor === undefined) {
959
+ try {
960
+ anchor = JSON.parse(t.anchor);
961
+ }
962
+ catch {
963
+ anchor = t.anchor;
964
+ }
965
+ }
966
+ return {
967
+ id: t.id,
968
+ anchor,
969
+ label: t.label,
970
+ resolved: t.status === 'resolved',
971
+ status: t.status,
972
+ agent: t.agent ?? null,
973
+ createdAt: t.createdAt,
974
+ updatedAt: t.updatedAt,
975
+ messages: t.messages.map((m) => ({ id: m.id, author: m.author, text: m.text, at: m.at })),
976
+ };
977
+ }
978
+ function errorOf(error) {
979
+ const e = error;
980
+ return { code: typeof e?.code === 'string' ? e.code : 'upstream_error', message: e?.message ?? String(error), ...(e?.extra ?? {}) };
981
+ }
982
+ function json(res, status, body, headOnly = false) {
983
+ const text = Buffer.from(JSON.stringify(body));
984
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': text.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
985
+ res.end(headOnly ? undefined : text);
986
+ }
987
+ function deny(req, res, status, message) {
988
+ req.resume?.();
989
+ res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
990
+ res.end(message);
991
+ }
992
+ function readBody(req, limit) {
993
+ return new Promise((resolvePromise, reject) => {
994
+ const chunks = [];
995
+ let size = 0;
996
+ req.on('data', (c) => {
997
+ size += c.length;
998
+ if (size > limit) {
999
+ reject(new FrameError('too_large', `The request is over ${limit} bytes.`, 413));
1000
+ req.destroy();
1001
+ return;
1002
+ }
1003
+ chunks.push(c);
1004
+ });
1005
+ req.on('end', () => resolvePromise(Buffer.concat(chunks)));
1006
+ req.on('error', reject);
1007
+ });
1008
+ }
1009
+ // ---- the agent's actions -------------------------------------------------------------------------------------------
1010
+ function frameOf(artifact) {
1011
+ const site = artifact.site;
1012
+ if (!(site instanceof FrameSite))
1013
+ throw new FrameError('not_found', `${artifact.id} is not open here.`, 404);
1014
+ return site;
1015
+ }
1016
+ /**
1017
+ * The type's actions (`/__open-artifact/actions/<name>`): `info` for Artifact `call`,
1018
+ * and the hidden `open-artifact.db.*` and `open-artifact.comments.*` that ArtifactData and
1019
+ * ArtifactComments use, in the shapes `libraryActions` answers.
1020
+ */
1021
+ export const frameActions = {
1022
+ info: {
1023
+ title: 'What the artifact holds',
1024
+ run: (artifact) => {
1025
+ const site = frameOf(artifact);
1026
+ const manifest = site.files.manifest();
1027
+ return {
1028
+ info: {
1029
+ type: site.declaration.key,
1030
+ contract: CONTRACT,
1031
+ capabilities: site.grants,
1032
+ ver: manifest.ver,
1033
+ brokerGen: site.brokerGen,
1034
+ files: Object.entries(manifest.files).map(([p, f]) => ({ path: p, size: f.size })),
1035
+ db: site.db.listAll().length,
1036
+ assets: site.blobs.list().usage,
1037
+ comments: { open: site.comments.openCount() },
1038
+ },
1039
+ };
1040
+ },
1041
+ },
1042
+ 'open-artifact.db.read': { hidden: true, run: (artifact, a) => frameOf(artifact).db.readDb(a.path || undefined, { query: a.query, limit: a.limit, cursor: a.cursor }) },
1043
+ 'open-artifact.db.write': {
1044
+ hidden: true,
1045
+ run: (artifact, a) => ({ writes: frameOf(artifact).db.writeDb(Array.isArray(a.writes) ? a.writes : [], { requireIfMatch: a.require_if_match === true }) }),
1046
+ },
1047
+ 'open-artifact.comments.read': {
1048
+ hidden: true,
1049
+ run: (artifact, a) => ({
1050
+ threads: frameOf(artifact)
1051
+ .comments.threads({ all: !!a.all })
1052
+ .map((t, i) => agentView(t, i + 1)),
1053
+ // A thread without `agent` was not sent to the agent: the daemon keeps the agent's replies off it.
1054
+ sent_tracked: true,
1055
+ }),
1056
+ },
1057
+ 'open-artifact.comments.reply': {
1058
+ hidden: true,
1059
+ run: (artifact, a) => {
1060
+ const site = frameOf(artifact);
1061
+ const { thread } = site.comments.addMessage(a.thread_id, { ...AGENT_AUTHOR }, a.text, { resolve: !!a.resolve });
1062
+ site.commentsChanged();
1063
+ return { thread: agentView(thread) };
1064
+ },
1065
+ },
1066
+ 'open-artifact.comments.resolve': {
1067
+ hidden: true,
1068
+ run: (artifact, a) => {
1069
+ const site = frameOf(artifact);
1070
+ const thread = site.comments.setResolved(a.thread_id, !a.reopen);
1071
+ site.commentsChanged();
1072
+ return { thread: agentView(thread) };
1073
+ },
1074
+ },
1075
+ };