@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/bin/frame-host.d.ts +2 -0
  5. package/bin/frame-host.js +47 -0
  6. package/package.json +124 -4
  7. package/src/child.d.ts +37 -0
  8. package/src/child.js +64 -0
  9. package/src/connectors/connectors.d.ts +101 -0
  10. package/src/connectors/connectors.js +256 -0
  11. package/src/connectors/daemon-connectors.d.ts +34 -0
  12. package/src/connectors/daemon-connectors.js +73 -0
  13. package/src/connectors/index.d.ts +7 -0
  14. package/src/connectors/index.js +7 -0
  15. package/src/connectors/mcp-client.d.ts +157 -0
  16. package/src/connectors/mcp-client.js +483 -0
  17. package/src/daemon.d.ts +119 -0
  18. package/src/daemon.js +301 -0
  19. package/src/frame/access.d.ts +69 -0
  20. package/src/frame/access.js +168 -0
  21. package/src/frame/client/comments.css +1 -0
  22. package/src/frame/client/comments.js +58 -0
  23. package/src/frame/client/imports.d.ts +6 -0
  24. package/src/frame/client/imports.js +112 -0
  25. package/src/frame/client/mcp-shell.js +345 -0
  26. package/src/frame/client/mcp.js +253 -0
  27. package/src/frame/client/runtime.js +1363 -0
  28. package/src/frame/client/sample.js +762 -0
  29. package/src/frame/client/shell.css +51 -0
  30. package/src/frame/client/shell.html +29 -0
  31. package/src/frame/client/shell.js +1417 -0
  32. package/src/frame/comments.d.ts +102 -0
  33. package/src/frame/comments.js +379 -0
  34. package/src/frame/core.d.ts +313 -0
  35. package/src/frame/core.js +1757 -0
  36. package/src/frame/db.d.ts +162 -0
  37. package/src/frame/db.js +604 -0
  38. package/src/frame/declaration.d.ts +30 -0
  39. package/src/frame/declaration.js +60 -0
  40. package/src/frame/env.d.ts +262 -0
  41. package/src/frame/env.js +13 -0
  42. package/src/frame/files.d.ts +130 -0
  43. package/src/frame/files.js +472 -0
  44. package/src/frame/index.d.ts +35 -0
  45. package/src/frame/index.js +33 -0
  46. package/src/frame/local.d.ts +126 -0
  47. package/src/frame/local.js +612 -0
  48. package/src/frame/mcp-relay.d.ts +79 -0
  49. package/src/frame/mcp-relay.js +191 -0
  50. package/src/frame/page-api.d.ts +48 -0
  51. package/src/frame/page-api.js +1 -0
  52. package/src/frame/page-comments.d.ts +109 -0
  53. package/src/frame/page-comments.js +1 -0
  54. package/src/frame/page-db.d.ts +88 -0
  55. package/src/frame/page-db.js +1 -0
  56. package/src/frame/page-imports.d.ts +2 -0
  57. package/src/frame/page-imports.js +2 -0
  58. package/src/frame/page-services.d.ts +124 -0
  59. package/src/frame/page-services.js +1 -0
  60. package/src/frame/page-values.d.ts +90 -0
  61. package/src/frame/page-values.js +1 -0
  62. package/src/frame/sample-relay.d.ts +42 -0
  63. package/src/frame/sample-relay.js +186 -0
  64. package/src/frame/snapshot-action.d.ts +18 -0
  65. package/src/frame/snapshot-action.js +82 -0
  66. package/src/frame/wire.d.ts +198 -0
  67. package/src/frame/wire.js +21 -0
  68. package/src/index.d.ts +17 -0
  69. package/src/index.js +17 -0
  70. package/src/lan.d.ts +75 -0
  71. package/src/lan.js +200 -0
  72. package/src/legacy-env.d.ts +7 -0
  73. package/src/legacy-env.js +14 -0
  74. package/src/serve.d.ts +375 -0
  75. package/src/serve.js +811 -0
  76. package/src/snapshot.d.ts +41 -0
  77. package/src/snapshot.js +224 -0
  78. package/src/type-package.d.ts +48 -0
  79. package/src/type-package.js +114 -0
  80. package/src/ws.d.ts +50 -0
  81. package/src/ws.js +203 -0
  82. package/src/zip.d.ts +197 -0
  83. package/src/zip.js +662 -0
@@ -0,0 +1,604 @@
1
+ /**
2
+ * The db capability's local backend: documents are JSON files at
3
+ * `<root>/db/<collection>/<doc>.json`, a subcollection is a folder beside its
4
+ * document (`db/a/b.json` and `db/a/b/c/`). Paths follow the capability's
5
+ * grammar; queries (where / one orderBy / limit) run over one collection's
6
+ * files. Leases (`acquire`) live in memory.
7
+ *
8
+ * `readDb` / `writeDb` are the agent's view (`open-artifacts.db.read` / `open-artifacts.db.write`),
9
+ * in the shapes the CLI libraries answer.
10
+ */
11
+ import { createHash, randomBytes } from 'node:crypto';
12
+ import { EventEmitter } from 'node:events';
13
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
14
+ import { isAbsolute, join } from 'node:path';
15
+ import { FrameError, LINK_GUARD, writeAtomic } from "./files.js";
16
+ export const DB_DIR = 'db';
17
+ export const DOC_MAX_BYTES = 256 * 1024;
18
+ const DEPTH_MAX = 32;
19
+ const SEGMENT = /^[A-Za-z0-9_\-.~:@+]+$/;
20
+ const OPS = new Set(['==', '!=', '<', '<=', '>', '>=', 'in', 'not-in', 'array-contains']);
21
+ const SHA = /^[0-9a-f]{64}$/;
22
+ /** Largest page of an agent's read. */
23
+ export const READ_MAX = 1000;
24
+ export const dbError = (code, message, extra = {}) => new FrameError(code, message, code === 'invalid_argument' ? 400 : 409, extra);
25
+ /**
26
+ * A document's hash for `if_match`: the sha256 (lowercase hex) of its data as
27
+ * compact JSON, so reformatting a file by hand does not change it.
28
+ */
29
+ export function docSha256(data) {
30
+ return createHash('sha256').update(JSON.stringify(data)).digest('hex');
31
+ }
32
+ /** The fix for a `set` / `delete` over an existing document without `if_match`. */
33
+ export const IF_MATCH_FIX = 'Read the document with ArtifactData {action: "get"} and pass its sha256 as if_match, or pass "*" to replace it anyway.';
34
+ /** A new random document id (what `add()` names a document). */
35
+ export function newDocId() {
36
+ return randomBytes(10).toString('base64url').replace(/[^A-Za-z0-9]/g, 'x');
37
+ }
38
+ /** Splits and checks a db path. `kind`: 'doc', 'collection' or 'any' ('' is the root, allowed for 'any' only). */
39
+ export function splitPath(p, kind = 'any') {
40
+ if (typeof p !== 'string')
41
+ throw dbError('invalid_argument', 'A db path is a string.');
42
+ const trimmed = p.replace(/^\/+|\/+$/g, '');
43
+ if (trimmed === '') {
44
+ if (kind === 'any')
45
+ return [];
46
+ throw dbError('invalid_argument', 'An empty db path names no document or collection.');
47
+ }
48
+ if (Buffer.byteLength(trimmed) > 1000)
49
+ throw dbError('invalid_argument', 'A db path is at most 1000 bytes.');
50
+ const segs = trimmed.split('/');
51
+ if (segs.length > 16)
52
+ throw dbError('invalid_argument', 'A db path has at most 16 segments.');
53
+ for (const s of segs) {
54
+ if (!SEGMENT.test(s) || s === '.' || s === '..' || Buffer.byteLength(s) > 200)
55
+ throw dbError('invalid_argument', `Bad db path segment ${JSON.stringify(s)}.`);
56
+ }
57
+ if (kind === 'doc' && segs.length % 2 !== 0)
58
+ throw dbError('invalid_argument', `${trimmed} names a collection, not a document.`);
59
+ if (kind === 'collection' && segs.length % 2 !== 1)
60
+ throw dbError('invalid_argument', `${trimmed} names a document, not a collection.`);
61
+ return segs;
62
+ }
63
+ function isPlain(v) {
64
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
65
+ }
66
+ /** RFC 7386-style merge for `update`: objects merge, arrays and scalars replace, `{__delete__: true}` removes a key. */
67
+ export function mergePatch(target, patch) {
68
+ const out = isPlain(target) ? { ...target } : {};
69
+ for (const [k, v] of Object.entries(patch)) {
70
+ if (isPlain(v) && v.__delete__ === true && Object.keys(v).length === 1)
71
+ delete out[k];
72
+ else if (isPlain(v))
73
+ out[k] = mergePatch(out[k], v);
74
+ else
75
+ out[k] = v;
76
+ }
77
+ return out;
78
+ }
79
+ function hasDeleteMarker(v) {
80
+ if (Array.isArray(v))
81
+ return v.some(hasDeleteMarker);
82
+ if (!isPlain(v))
83
+ return false;
84
+ if (v.__delete__ === true)
85
+ return true;
86
+ return Object.values(v).some(hasDeleteMarker);
87
+ }
88
+ function depthOf(v, d = 0) {
89
+ if (d > DEPTH_MAX)
90
+ return d;
91
+ if (Array.isArray(v))
92
+ return Math.max(d, ...v.map((x) => depthOf(x, d + 1)));
93
+ if (isPlain(v))
94
+ return Math.max(d, ...Object.values(v).map((x) => depthOf(x, d + 1)));
95
+ return d;
96
+ }
97
+ function checkData(data) {
98
+ if (!isPlain(data))
99
+ throw dbError('invalid_argument', 'Document data is a JSON object.');
100
+ const text = JSON.stringify(data);
101
+ if (Buffer.byteLength(text) > DOC_MAX_BYTES)
102
+ throw dbError('too_large', `A document is at most ${DOC_MAX_BYTES} bytes.`);
103
+ if (depthOf(data) > DEPTH_MAX)
104
+ throw dbError('invalid_argument', `A document nests at most ${DEPTH_MAX} levels.`);
105
+ return text;
106
+ }
107
+ function fieldOf(data, field) {
108
+ if (field === '__name__' || field === 'id')
109
+ return undefined;
110
+ let v = data;
111
+ for (const k of String(field).split('.')) {
112
+ if (!isPlain(v))
113
+ return undefined;
114
+ v = v[k];
115
+ }
116
+ return v;
117
+ }
118
+ const typeRank = (v) => v === null ? 0 : typeof v === 'boolean' ? 1 : typeof v === 'number' ? 2 : typeof v === 'string' ? 3 : Array.isArray(v) ? 4 : 5;
119
+ function compare(a, b) {
120
+ const ra = typeRank(a);
121
+ const rb = typeRank(b);
122
+ if (ra !== rb)
123
+ return ra - rb;
124
+ if (ra === 2)
125
+ return a - b;
126
+ if (ra === 3)
127
+ return a < b ? -1 : a > b ? 1 : 0;
128
+ if (ra === 1)
129
+ return Number(a) - Number(b);
130
+ const sa = JSON.stringify(a);
131
+ const sb = JSON.stringify(b);
132
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
133
+ }
134
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
135
+ function matches(doc, w) {
136
+ const v = w.field === '__name__' || w.field === 'id' ? doc.id : fieldOf(doc.data, w.field);
137
+ switch (w.op) {
138
+ case '==':
139
+ return v !== undefined && same(v, w.value);
140
+ case '!=':
141
+ return v !== undefined && !same(v, w.value);
142
+ case '<':
143
+ case '<=':
144
+ case '>':
145
+ case '>=': {
146
+ if (v === undefined || typeRank(v) !== typeRank(w.value))
147
+ return false;
148
+ const c = compare(v, w.value);
149
+ return w.op === '<' ? c < 0 : w.op === '<=' ? c <= 0 : w.op === '>' ? c > 0 : c >= 0;
150
+ }
151
+ case 'in':
152
+ return v !== undefined && Array.isArray(w.value) && w.value.some((x) => same(x, v));
153
+ case 'not-in':
154
+ return v !== undefined && Array.isArray(w.value) && !w.value.some((x) => same(x, v));
155
+ case 'array-contains':
156
+ return Array.isArray(v) && v.some((x) => same(x, w.value));
157
+ default:
158
+ return false;
159
+ }
160
+ }
161
+ /** Checks a query spec from a page: `{where?: [{field, op, value}], orderBy?: {field, dir}, limit?}`. */
162
+ export function checkSpec(raw = {}) {
163
+ const spec = isPlain(raw) ? raw : {};
164
+ const where = (Array.isArray(spec.where) ? spec.where : []);
165
+ for (const w of where) {
166
+ if (typeof w?.field !== 'string' || !w.field)
167
+ throw dbError('invalid_argument', 'where() needs a field.');
168
+ if (!OPS.has(w.op))
169
+ throw dbError('invalid_argument', `where() does not know the operator ${w.op}.`);
170
+ if ((w.op === 'in' || w.op === 'not-in') && (!Array.isArray(w.value) || w.value.length > 30))
171
+ throw dbError('invalid_argument', `${w.op} takes an array of at most 30 values.`);
172
+ }
173
+ let orderBy = null;
174
+ if (spec.orderBy) {
175
+ const o = spec.orderBy;
176
+ if (typeof o.field !== 'string' || !o.field)
177
+ throw dbError('invalid_argument', 'orderBy() needs a field.');
178
+ orderBy = { field: o.field, dir: o.dir === 'desc' ? 'desc' : 'asc' };
179
+ }
180
+ let limit = null;
181
+ if (spec.limit !== undefined && spec.limit !== null) {
182
+ if (!Number.isInteger(spec.limit) || spec.limit < 1 || spec.limit > 1000)
183
+ throw dbError('invalid_argument', 'limit() takes 1 to 1000.');
184
+ limit = spec.limit;
185
+ }
186
+ return { where, orderBy, limit };
187
+ }
188
+ function pageOf(opts) {
189
+ let limit = null;
190
+ if (opts.limit !== undefined && opts.limit !== null) {
191
+ if (!Number.isInteger(opts.limit) || opts.limit < 1 || opts.limit > READ_MAX)
192
+ throw dbError('invalid_argument', `limit is 1 to ${READ_MAX}.`);
193
+ limit = opts.limit;
194
+ }
195
+ let offset = 0;
196
+ if (opts.cursor !== undefined && opts.cursor !== null && opts.cursor !== '') {
197
+ const n = typeof opts.cursor === 'string' && /^\d{1,9}$/.test(opts.cursor) ? Number(opts.cursor) : NaN;
198
+ if (!Number.isInteger(n))
199
+ throw dbError('invalid_argument', 'cursor is the next_cursor of an earlier read.');
200
+ offset = n;
201
+ }
202
+ return { limit, offset };
203
+ }
204
+ function paged(items, opts) {
205
+ const { limit, offset } = pageOf(opts);
206
+ const end = limit === null ? items.length : Math.min(items.length, offset + limit);
207
+ return { items: items.slice(offset, end), total: items.length, ...(end < items.length ? { next_cursor: String(end) } : {}) };
208
+ }
209
+ /** Sets a dot-path field of a copy of `data`. */
210
+ function withField(data, field, value) {
211
+ const keys = field.split('.');
212
+ const out = { ...data };
213
+ let at = out;
214
+ for (const k of keys.slice(0, -1)) {
215
+ const next = at[k];
216
+ if (!isPlain(next))
217
+ throw dbError('invalid_argument', `str_replace: ${field} is not a text field.`);
218
+ at[k] = { ...next };
219
+ at = at[k];
220
+ }
221
+ at[keys.at(-1)] = value;
222
+ return out;
223
+ }
224
+ function occurrences(text, part) {
225
+ let n = 0;
226
+ for (let i = text.indexOf(part); i !== -1; i = text.indexOf(part, i + part.length))
227
+ n++;
228
+ return n;
229
+ }
230
+ /** A store of one artifact's documents. Emits `change` with the doc paths a write touched. */
231
+ export class DbStore extends EventEmitter {
232
+ root;
233
+ dir;
234
+ leases = new Map();
235
+ guard;
236
+ imports;
237
+ /**
238
+ * `guard`: how it keeps inside the artifact folder (default {@link LINK_GUARD}: links followed). `imports`: where a
239
+ * write's `file_path` may be read from (it checks the path, or throws); none: anywhere.
240
+ */
241
+ constructor(root, options = {}) {
242
+ super();
243
+ this.root = root;
244
+ this.dir = join(root, DB_DIR);
245
+ this.guard = options.guard ?? LINK_GUARD;
246
+ this.imports = options.imports;
247
+ }
248
+ /** The bytes of a document's file as they are on disk (history and validation compare them); throws when it has none. */
249
+ readDocumentFile(p) {
250
+ return readFileSync(this.fileOf(splitPath(p, 'doc')), 'utf8');
251
+ }
252
+ /** A document's file; refused when a link (db/ itself, or a folder in it) leads it out of the artifact folder. */
253
+ fileOf(segs) {
254
+ const file = join(this.dir, ...segs.slice(0, -1), `${segs.at(-1)}.json`);
255
+ if (!this.guard.inside(this.root, file))
256
+ throw dbError('invalid_argument', `${segs.join('/')} leads out of the artifact folder (a link).`);
257
+ return file;
258
+ }
259
+ readDoc(p) {
260
+ const segs = splitPath(p, 'doc');
261
+ try {
262
+ const data = JSON.parse(readFileSync(this.fileOf(segs), 'utf8'));
263
+ return isPlain(data) ? data : null;
264
+ }
265
+ catch {
266
+ return null;
267
+ }
268
+ }
269
+ /** Documents of one collection, sorted by id. */
270
+ listCollection(p) {
271
+ const segs = splitPath(p, 'collection');
272
+ const dir = join(this.dir, ...segs);
273
+ if (!this.guard.inside(this.root, dir))
274
+ return [];
275
+ let names;
276
+ try {
277
+ names = readdirSync(dir, { withFileTypes: true });
278
+ }
279
+ catch {
280
+ return [];
281
+ }
282
+ const docs = [];
283
+ for (const e of names) {
284
+ if (!e.isFile() || e.name.startsWith('.') || !e.name.endsWith('.json'))
285
+ continue;
286
+ const id = e.name.slice(0, -5);
287
+ if (!SEGMENT.test(id))
288
+ continue;
289
+ try {
290
+ const data = JSON.parse(readFileSync(join(dir, e.name), 'utf8'));
291
+ if (isPlain(data))
292
+ docs.push({ id, data: data });
293
+ }
294
+ catch {
295
+ // half-written by hand: skipped until it parses
296
+ }
297
+ }
298
+ docs.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
299
+ return docs;
300
+ }
301
+ query(p, rawSpec) {
302
+ const spec = checkSpec(rawSpec);
303
+ let docs = this.listCollection(p).filter((d) => spec.where.every((w) => matches(d, w)));
304
+ if (spec.orderBy) {
305
+ const { field, dir } = spec.orderBy;
306
+ const key = (d) => (field === '__name__' || field === 'id' ? d.id : fieldOf(d.data, field));
307
+ docs = docs
308
+ .map((d, i) => ({ d, i, k: key(d) }))
309
+ .sort((a, b) => {
310
+ // Documents without the field sort last, either way.
311
+ if (a.k === undefined && b.k === undefined)
312
+ return a.i - b.i;
313
+ if (a.k === undefined)
314
+ return 1;
315
+ if (b.k === undefined)
316
+ return -1;
317
+ const c = compare(a.k, b.k) * (dir === 'desc' ? -1 : 1);
318
+ return c || a.i - b.i;
319
+ })
320
+ .map((x) => x.d);
321
+ }
322
+ if (spec.limit)
323
+ docs = docs.slice(0, spec.limit);
324
+ return docs;
325
+ }
326
+ set(p, data) {
327
+ const segs = splitPath(p, 'doc');
328
+ if (hasDeleteMarker(data))
329
+ throw dbError('invalid_argument', '{__delete__: true} is for update only.');
330
+ const text = checkData(data);
331
+ const file = this.fileOf(segs);
332
+ const created = !existsSync(file);
333
+ writeAtomic(file, `${text}\n`);
334
+ this.changed([segs.join('/')]);
335
+ return { bytes: Buffer.byteLength(text), created };
336
+ }
337
+ update(p, patch) {
338
+ const segs = splitPath(p, 'doc');
339
+ if (!isPlain(patch))
340
+ throw dbError('invalid_argument', 'update() takes an object.');
341
+ const have = this.readDoc(p);
342
+ if (!have)
343
+ throw dbError('invalid_argument', `update(): ${segs.join('/')} does not exist.`);
344
+ const text = checkData(mergePatch(have, patch));
345
+ writeAtomic(this.fileOf(segs), `${text}\n`);
346
+ this.changed([segs.join('/')]);
347
+ return { bytes: Buffer.byteLength(text) };
348
+ }
349
+ delete(p) {
350
+ const segs = splitPath(p, 'doc');
351
+ let existed = true;
352
+ try {
353
+ rmSync(this.fileOf(segs));
354
+ }
355
+ catch {
356
+ existed = false;
357
+ }
358
+ this.leases.delete(segs.join('/'));
359
+ if (existed)
360
+ this.changed([segs.join('/')]);
361
+ return { existed };
362
+ }
363
+ /** A new document in `collection`, under `id` (default: a new random one, {@link newDocId}). */
364
+ add(collection, data, id = newDocId()) {
365
+ const segs = splitPath(collection, 'collection');
366
+ const docPath = [...segs, id].join('/');
367
+ this.set(docPath, data);
368
+ return { id, path: docPath };
369
+ }
370
+ /** A lease on a document. */
371
+ acquire(p, opts = {}) {
372
+ const key = splitPath(p, 'doc').join('/');
373
+ const { holder, ttlMs = 30_000, data } = opts;
374
+ // 128 characters from a page; the frame core puts the viewer's id before them (up to 512 in all).
375
+ if (typeof holder !== 'string' || !holder || holder.length > 512)
376
+ throw dbError('invalid_argument', 'acquire() needs a holder.');
377
+ if (typeof ttlMs !== 'number' || !Number.isInteger(ttlMs) || ttlMs < 1000 || ttlMs > 600_000)
378
+ throw dbError('invalid_argument', 'acquire(): ttlMs is 1000 to 600000.');
379
+ const now = Date.now();
380
+ const have = this.leases.get(key);
381
+ if (have && have.expiresAt > now && have.holder !== holder)
382
+ return { acquired: false, holder: have.holder, expiresAt: have.expiresAt };
383
+ const lease = { holder, expiresAt: now + ttlMs, version: (have?.version ?? 0) + 1 };
384
+ this.leases.set(key, lease);
385
+ if (data !== undefined) {
386
+ if (this.readDoc(key))
387
+ this.update(key, data);
388
+ else
389
+ this.set(key, data);
390
+ }
391
+ return { acquired: true, version: lease.version, expiresAt: lease.expiresAt, holder };
392
+ }
393
+ release(p, holder) {
394
+ const key = splitPath(p, 'doc').join('/');
395
+ const have = this.leases.get(key);
396
+ const released = !!have && have.holder === holder;
397
+ if (released)
398
+ this.leases.delete(key);
399
+ return { released };
400
+ }
401
+ changed(paths) {
402
+ this.emit('change', paths);
403
+ }
404
+ // ---- the agent's view ---------------------------------------------------------------------------------------------
405
+ /** Every document file. */
406
+ listAll() {
407
+ const out = [];
408
+ const walk = (dir, segs) => {
409
+ let entries;
410
+ try {
411
+ entries = readdirSync(dir, { withFileTypes: true });
412
+ }
413
+ catch {
414
+ return;
415
+ }
416
+ for (const e of entries) {
417
+ if (e.name.startsWith('.'))
418
+ continue;
419
+ if (e.isDirectory() && SEGMENT.test(e.name))
420
+ walk(join(dir, e.name), [...segs, e.name]);
421
+ else if (e.isFile() && e.name.endsWith('.json')) {
422
+ const id = e.name.slice(0, -5);
423
+ const docSegs = [...segs, id];
424
+ if (docSegs.length % 2 !== 0 || !SEGMENT.test(id))
425
+ continue;
426
+ out.push({ path: docSegs.join('/'), bytes: statSync(join(dir, e.name)).size });
427
+ }
428
+ }
429
+ };
430
+ if (this.guard.inside(this.root, this.dir))
431
+ walk(this.dir, []);
432
+ return out.sort((a, b) => (a.path < b.path ? -1 : 1));
433
+ }
434
+ /**
435
+ * The agent's read (`open-artifacts.db.read`): the root lists every document path, a
436
+ * collection its documents (filtered by `query`), a document its data.
437
+ * Documents carry `sha256` for `if_match`; a page that stops early carries
438
+ * `next_cursor`.
439
+ */
440
+ readDb(p, opts = {}) {
441
+ const segs = splitPath(p ?? '', 'any');
442
+ if (segs.length === 0) {
443
+ const page = paged(this.listAll(), opts);
444
+ return { root: DB_DIR, documents: page.items, total: page.total, ...(page.next_cursor ? { next_cursor: page.next_cursor } : {}) };
445
+ }
446
+ const joined = segs.join('/');
447
+ if (segs.length % 2 === 1) {
448
+ const query = opts.query !== undefined && opts.query !== null;
449
+ const docs = query ? this.query(joined, opts.query) : this.listCollection(joined);
450
+ const page = paged(docs, opts);
451
+ return {
452
+ collection: joined,
453
+ ...(query ? { query: true } : {}),
454
+ docs: page.items.map((d) => ({ id: d.id, path: `${joined}/${d.id}`, sha256: docSha256(d.data), data: d.data })),
455
+ total: page.total,
456
+ ...(page.next_cursor ? { next_cursor: page.next_cursor } : {}),
457
+ };
458
+ }
459
+ if (opts.query !== undefined && opts.query !== null)
460
+ throw dbError('invalid_argument', `${joined} names a document; a query reads a collection.`);
461
+ const data = this.readDoc(joined);
462
+ return data ? { path: joined, exists: true, sha256: docSha256(data), data } : { path: joined, exists: false, sha256: null };
463
+ }
464
+ /**
465
+ * The agent's batch (`open-artifacts.db.write`): every write is checked before any is
466
+ * made. A write with `if_match` that no longer holds fails the whole batch
467
+ * with `conflict`, its `current` holding what each such document is now.
468
+ */
469
+ writeDb(writes, opts = {}) {
470
+ if (!Array.isArray(writes) || writes.length === 0)
471
+ throw dbError('invalid_argument', 'writes is a non-empty array.');
472
+ if (writes.length > 500)
473
+ throw dbError('invalid_argument', 'At most 500 writes at once.');
474
+ const seen = new Set();
475
+ const conflicts = {};
476
+ const unguarded = [];
477
+ const plan = writes.map((w) => {
478
+ const op = w?.op;
479
+ if (op !== 'set' && op !== 'update' && op !== 'delete' && op !== 'str_replace')
480
+ throw dbError('invalid_argument', `Unknown op ${String(op)}.`);
481
+ // A write names its document by `path`, or by `collection` + `doc_id` (the ArtifactData batch shape).
482
+ const named = w.path ?? (w.collection != null && w.doc_id != null ? `${w.collection}/${w.doc_id}` : '');
483
+ const p = splitPath(String(named), 'doc').join('/');
484
+ if (seen.has(p))
485
+ throw dbError('invalid_argument', `${p} appears twice in one batch.`);
486
+ seen.add(p);
487
+ const ifMatch = w.if_match;
488
+ if (ifMatch !== undefined && ifMatch !== null && ifMatch !== '*' && !(typeof ifMatch === 'string' && SHA.test(ifMatch))) {
489
+ throw dbError('invalid_argument', `${op} ${p}: if_match is a sha256 you read, null or "*".`);
490
+ }
491
+ const have = this.readDoc(p);
492
+ const haveSha = have ? docSha256(have) : null;
493
+ if (ifMatch !== undefined && ifMatch !== '*' && ifMatch !== haveSha) {
494
+ conflicts[p] = have ? { path: p, exists: true, sha256: haveSha, data: have } : { path: p, exists: false, sha256: null };
495
+ }
496
+ if (opts.requireIfMatch && (op === 'set' || op === 'delete') && have && ifMatch === undefined)
497
+ unguarded.push(`${op} ${p}`);
498
+ if (op === 'delete')
499
+ return { op, path: p, data: undefined };
500
+ if (op === 'str_replace') {
501
+ if (typeof w.field !== 'string' || !w.field)
502
+ throw dbError('invalid_argument', `str_replace ${p}: field (a dot path) is required.`);
503
+ if (typeof w.old !== 'string' || !w.old)
504
+ throw dbError('invalid_argument', `str_replace ${p}: old is a non-empty string.`);
505
+ if (typeof w.new !== 'string')
506
+ throw dbError('invalid_argument', `str_replace ${p}: new is a string.`);
507
+ if (!have)
508
+ throw dbError('invalid_argument', `str_replace: ${p} does not exist.`);
509
+ const text = fieldOf(have, w.field);
510
+ if (typeof text !== 'string')
511
+ throw dbError('invalid_argument', `str_replace ${p}: ${w.field} is not a text field.`);
512
+ const n = occurrences(text, w.old);
513
+ if (n === 0)
514
+ throw dbError('invalid_argument', `str_replace ${p}: old does not occur in ${w.field}.`, { fix: 'Read the document again and copy old exactly from it.' });
515
+ if (n > 1)
516
+ throw dbError('invalid_argument', `str_replace ${p}: old occurs ${n} times in ${w.field}.`, { fix: 'Make old longer so it occurs exactly once.' });
517
+ const data = withField(have, w.field, text.replace(w.old, () => w.new));
518
+ checkData(data);
519
+ return { op, path: p, data: data };
520
+ }
521
+ const hasData = w.data !== undefined;
522
+ const hasFile = typeof w.file_path === 'string' && w.file_path !== '';
523
+ if (hasData === hasFile)
524
+ throw dbError('invalid_argument', `${op} ${p}: give exactly one of data or file_path.`);
525
+ let data = w.data;
526
+ if (hasFile) {
527
+ if (!isAbsolute(w.file_path))
528
+ throw dbError('invalid_argument', 'file_path is an absolute path.');
529
+ let file;
530
+ try {
531
+ file = this.imports ? this.imports.resolve(w.file_path) : w.file_path;
532
+ }
533
+ catch {
534
+ throw dbError('not_granted', `${w.file_path} is outside the artifact's workspace.`);
535
+ }
536
+ try {
537
+ data = JSON.parse(readFileSync(file, 'utf8'));
538
+ }
539
+ catch (error) {
540
+ throw dbError('invalid_argument', `${w.file_path}: ${error?.message ?? error}`);
541
+ }
542
+ }
543
+ if (!isPlain(data))
544
+ throw dbError('invalid_argument', `${op} ${p}: the data is a JSON object.`);
545
+ if (op === 'set' && hasDeleteMarker(data))
546
+ throw dbError('invalid_argument', `set ${p}: {__delete__: true} is for update only.`);
547
+ checkData(op === 'update' ? mergePatch(have ?? {}, data) : data);
548
+ return { op, path: p, data };
549
+ });
550
+ const conflicted = Object.keys(conflicts);
551
+ if (conflicted.length) {
552
+ throw dbError('conflict', `${conflicted.length === 1 ? `${conflicted[0]} changed` : `${conflicted.length} documents changed`} since you read it: nothing was written.`, {
553
+ fix: 'Merge your change into the document in current, then write again with its sha256 as if_match.',
554
+ current: conflicts,
555
+ });
556
+ }
557
+ if (unguarded.length) {
558
+ throw dbError('invalid_argument', `${unguarded.join(', ')}: the document exists, so the write needs if_match. Nothing was written.`, {
559
+ fix: IF_MATCH_FIX,
560
+ need_if_match: unguarded.map((u) => u.slice(u.indexOf(' ') + 1)),
561
+ });
562
+ }
563
+ const out = [];
564
+ const shaOf = (path) => {
565
+ const data = this.readDoc(path);
566
+ return data ? docSha256(data) : null;
567
+ };
568
+ for (const w of plan) {
569
+ if (w.op === 'delete') {
570
+ const { existed } = this.delete(w.path);
571
+ out.push({ op: 'delete', path: w.path, sha256: null, ...(existed ? {} : { note: 'did not exist' }) });
572
+ }
573
+ else if (w.op === 'update' && this.readDoc(w.path)) {
574
+ const r = this.update(w.path, w.data);
575
+ out.push({ op: 'update', path: w.path, bytes: r.bytes, sha256: shaOf(w.path) });
576
+ }
577
+ else if (w.op === 'update') {
578
+ const r = this.set(w.path, mergePatch({}, w.data));
579
+ out.push({ op: 'update', path: w.path, bytes: r.bytes, sha256: shaOf(w.path), created: true, note: 'did not exist; created' });
580
+ }
581
+ else {
582
+ const r = this.set(w.path, w.data);
583
+ out.push({ op: w.op, path: w.path, bytes: r.bytes, sha256: shaOf(w.path), ...(r.created ? { created: true } : {}) });
584
+ }
585
+ }
586
+ return out;
587
+ }
588
+ }
589
+ /** Doc paths of the db files a watcher saw change (paths relative to the artifact folder). */
590
+ export function docPathsOf(relPaths) {
591
+ const out = [];
592
+ for (const rel of relPaths) {
593
+ const segs = rel.split(/[\\/]/);
594
+ if (segs[0] !== DB_DIR || segs.length < 2)
595
+ continue;
596
+ const last = segs.at(-1);
597
+ if (last.startsWith('.') || !last.endsWith('.json'))
598
+ continue;
599
+ const doc = [...segs.slice(1, -1), last.slice(0, -5)];
600
+ if (doc.length % 2 === 0)
601
+ out.push(doc.join('/'));
602
+ }
603
+ return out;
604
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The inline declaration of an original artifact type: a type's index.html
3
+ * carries, near the top of its first script, a block that starts with the
4
+ * line comment `// artifact.json` and declares
5
+ * `var key = "<type key>"; var capabilities = {...}; var monitoring = {...};`
6
+ * in some order (a type may leave capabilities out). Only that block is read:
7
+ * it ends at the next line comment (`declarationSource` in the protocol, which
8
+ * `open-artifacts types check` reads too). It is read as literal data
9
+ * (`parseLiteralDeclarations`), never run: nothing from a type folder is
10
+ * evaluated in Node, so an installed type's page is read the same way as a
11
+ * built-in one's.
12
+ */
13
+ import { type CapabilityDecl } from '@openartifactsai/protocol';
14
+ export { DECLARATION_LINE } from '@openartifactsai/protocol';
15
+ export type { CapabilityDecl } from '@openartifactsai/protocol';
16
+ export interface Declaration {
17
+ /** The type key, when the block names one. */
18
+ key: string | null;
19
+ /** cap → declared config. */
20
+ capabilities: Record<string, CapabilityDecl>;
21
+ monitoring: Record<string, unknown>;
22
+ }
23
+ /**
24
+ * The declaration in a type's index.html, or null when the page carries none. Only `var` bindings count (a `let` or
25
+ * `const` is not a global of the page, and `types check` flags it); the last initialized one of a name wins, as when the
26
+ * block runs. Throws when the block is not literal data.
27
+ */
28
+ export declare function parseDeclaration(html: string): Declaration | null;
29
+ /** The declaration of the type folder `dir` (its index.html), or null. */
30
+ export declare function readDeclaration(dir: string): Declaration | null;