@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,87 @@
1
+ /**
2
+ * Comment threads of a frame artifact, in the shared `comments.json` format
3
+ * (version 1) the other Open Artifact types write:
4
+ * `{version: 1, threads: [{id: 'c_…', anchor, label, detail?, location, status, agent?, createdAt, updatedAt,
5
+ * resolvedAt?, messages: [{id: 'm_…', author: {kind, name}, text, at, editedAt?}]}]}`.
6
+ *
7
+ * An original page anchors a comment with its own object; it is kept whole
8
+ * under `location.custom` and `anchor` is its stable JSON text, so the page
9
+ * gets back exactly what it gave. Writes take `comments.json.lock` (O_EXCL)
10
+ * and replace the file through a dot temp file; the file exists only once
11
+ * there is a thread.
12
+ */
13
+ export declare const COMMENTS_FILE = "comments.json";
14
+ export declare const TEXT_MAX = 10000;
15
+ export interface Author {
16
+ kind: 'user' | 'agent';
17
+ name: string;
18
+ }
19
+ export declare const AGENT_AUTHOR: Readonly<Author>;
20
+ export interface CommentMessage {
21
+ id: string;
22
+ author: Author;
23
+ text: string;
24
+ at: string;
25
+ editedAt?: string;
26
+ }
27
+ export interface ThreadAgentState {
28
+ status: 'pending' | 'delivered' | 'replied';
29
+ sentAt?: string;
30
+ deliveredAt?: string;
31
+ repliedAt?: string;
32
+ via?: string;
33
+ }
34
+ export interface Thread {
35
+ id: string;
36
+ anchor: string;
37
+ label: string;
38
+ detail?: string;
39
+ location: Record<string, unknown>;
40
+ status: 'open' | 'resolved';
41
+ agent?: ThreadAgentState;
42
+ createdAt: string;
43
+ updatedAt: string;
44
+ resolvedAt?: string;
45
+ messages: CommentMessage[];
46
+ }
47
+ interface CommentsDoc {
48
+ version: 1;
49
+ threads: Thread[];
50
+ }
51
+ export declare class CommentStore {
52
+ readonly root: string;
53
+ readonly file: string;
54
+ constructor(root: string);
55
+ load(): CommentsDoc;
56
+ threads({ all }?: {
57
+ all?: boolean;
58
+ }): Thread[];
59
+ openCount(): number;
60
+ find(doc: CommentsDoc, idOrPrefix: unknown): Thread;
61
+ /** Runs `fn(doc)` under the lock and writes the result back. */
62
+ mutate<T>(fn: (doc: CommentsDoc) => T): T;
63
+ create(input: {
64
+ anchor?: unknown;
65
+ label?: unknown;
66
+ detail?: unknown;
67
+ location?: unknown;
68
+ text: unknown;
69
+ author?: Author;
70
+ }): Thread;
71
+ addMessage(threadId: unknown, author: Author, text: unknown, { resolve }?: {
72
+ resolve?: boolean;
73
+ }): {
74
+ thread: Thread;
75
+ message: CommentMessage;
76
+ };
77
+ setResolved(threadId: unknown, resolved: boolean): Thread;
78
+ move(threadId: unknown, anchor: unknown, location?: unknown): Thread;
79
+ remove(threadId: unknown, messageId?: unknown): {
80
+ deleted: 'message' | 'thread';
81
+ };
82
+ markDelivered(threadId: unknown, via: string): Thread;
83
+ markSent(threadId: unknown): Thread;
84
+ }
85
+ /** What the agent reads of a thread. */
86
+ export declare function agentView(thread: Thread, n?: number): Record<string, unknown>;
87
+ export {};
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Comment threads of a frame artifact, in the shared `comments.json` format
3
+ * (version 1) the other Open Artifact types write:
4
+ * `{version: 1, threads: [{id: 'c_…', anchor, label, detail?, location, status, agent?, createdAt, updatedAt,
5
+ * resolvedAt?, messages: [{id: 'm_…', author: {kind, name}, text, at, editedAt?}]}]}`.
6
+ *
7
+ * An original page anchors a comment with its own object; it is kept whole
8
+ * under `location.custom` and `anchor` is its stable JSON text, so the page
9
+ * gets back exactly what it gave. Writes take `comments.json.lock` (O_EXCL)
10
+ * and replace the file through a dot temp file; the file exists only once
11
+ * there is a thread.
12
+ */
13
+ import { randomBytes } from 'node:crypto';
14
+ import { closeSync, existsSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { FrameError } from "./files.js";
17
+ export const COMMENTS_FILE = 'comments.json';
18
+ export const TEXT_MAX = 10_000;
19
+ const LOCK_STALE_MS = 10_000;
20
+ const LOCK_WAIT_MS = 5_000;
21
+ export const AGENT_AUTHOR = Object.freeze({ kind: 'agent', name: 'agent' });
22
+ const newId = (prefix) => `${prefix}${randomBytes(5).toString('hex')}`;
23
+ const now = () => new Date().toISOString();
24
+ export class CommentStore {
25
+ root;
26
+ file;
27
+ constructor(root) {
28
+ this.root = root;
29
+ this.file = join(root, COMMENTS_FILE);
30
+ }
31
+ load() {
32
+ try {
33
+ const doc = JSON.parse(readFileSync(this.file, 'utf8'));
34
+ if (doc && Array.isArray(doc.threads))
35
+ return { ...doc, version: 1, threads: doc.threads };
36
+ }
37
+ catch {
38
+ // none yet, or unreadable: an empty list
39
+ }
40
+ return { version: 1, threads: [] };
41
+ }
42
+ threads({ all = false } = {}) {
43
+ const list = this.load().threads.filter((t) => all || t.status !== 'resolved');
44
+ return list.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
45
+ }
46
+ openCount() {
47
+ return this.load().threads.filter((t) => t.status !== 'resolved').length;
48
+ }
49
+ find(doc, idOrPrefix) {
50
+ const id = String(idOrPrefix ?? '');
51
+ const exact = doc.threads.find((t) => t.id === id);
52
+ if (exact)
53
+ return exact;
54
+ if (id.length >= 3) {
55
+ const hits = doc.threads.filter((t) => t.id.startsWith(id));
56
+ if (hits.length === 1)
57
+ return hits[0];
58
+ if (hits.length > 1)
59
+ throw new FrameError('invalid_argument', `${id} matches ${hits.length} threads.`);
60
+ }
61
+ throw new FrameError('not_found', `No comment thread ${id}.`, 404);
62
+ }
63
+ /** Runs `fn(doc)` under the lock and writes the result back. */
64
+ mutate(fn) {
65
+ const lock = `${this.file}.lock`;
66
+ const started = Date.now();
67
+ let fd;
68
+ for (;;) {
69
+ try {
70
+ fd = openSync(lock, 'wx');
71
+ break;
72
+ }
73
+ catch (error) {
74
+ if (error.code !== 'EEXIST')
75
+ throw error;
76
+ try {
77
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
78
+ rmSync(lock, { force: true });
79
+ continue;
80
+ }
81
+ }
82
+ catch {
83
+ continue;
84
+ }
85
+ if (Date.now() - started > LOCK_WAIT_MS)
86
+ throw new FrameError('unavailable', 'comments.json is locked by another writer.', 409);
87
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
88
+ }
89
+ }
90
+ try {
91
+ const doc = this.load();
92
+ const out = fn(doc);
93
+ if (doc.threads.length || existsSync(this.file)) {
94
+ const tmp = join(this.root, `.${COMMENTS_FILE}.${randomBytes(4).toString('hex')}.tmp`);
95
+ writeFileSync(tmp, `${JSON.stringify({ version: 1, threads: doc.threads }, null, 2)}\n`);
96
+ renameSync(tmp, this.file);
97
+ }
98
+ return out;
99
+ }
100
+ finally {
101
+ closeSync(fd);
102
+ rmSync(lock, { force: true });
103
+ }
104
+ }
105
+ create(input) {
106
+ const body = checkText(input.text);
107
+ return this.mutate((doc) => {
108
+ const at = now();
109
+ const thread = {
110
+ id: newId('c_'),
111
+ anchor: typeof input.anchor === 'string' ? input.anchor : JSON.stringify(input.anchor ?? null),
112
+ label: typeof input.label === 'string' && input.label ? input.label.slice(0, 200) : 'the page',
113
+ ...(typeof input.detail === 'string' && input.detail ? { detail: input.detail.slice(0, 2000) } : {}),
114
+ location: isObject(input.location) ? input.location : {},
115
+ status: 'open',
116
+ createdAt: at,
117
+ updatedAt: at,
118
+ messages: [{ id: newId('m_'), author: input.author ?? { ...AGENT_AUTHOR }, text: body, at }],
119
+ };
120
+ doc.threads.push(thread);
121
+ return thread;
122
+ });
123
+ }
124
+ addMessage(threadId, author, text, { resolve = false } = {}) {
125
+ const body = checkText(text);
126
+ return this.mutate((doc) => {
127
+ const thread = this.find(doc, threadId);
128
+ const at = now();
129
+ const message = { id: newId('m_'), author, text: body, at };
130
+ thread.messages.push(message);
131
+ thread.updatedAt = at;
132
+ if (author.kind === 'agent') {
133
+ thread.agent = { ...(thread.agent ?? {}), status: 'replied', repliedAt: at };
134
+ if (resolve)
135
+ setStatus(thread, 'resolved', at);
136
+ }
137
+ else if (thread.status === 'resolved') {
138
+ setStatus(thread, 'open', at);
139
+ }
140
+ return { thread, message };
141
+ });
142
+ }
143
+ setResolved(threadId, resolved) {
144
+ return this.mutate((doc) => {
145
+ const thread = this.find(doc, threadId);
146
+ setStatus(thread, resolved ? 'resolved' : 'open', now());
147
+ return thread;
148
+ });
149
+ }
150
+ move(threadId, anchor, location) {
151
+ return this.mutate((doc) => {
152
+ const thread = this.find(doc, threadId);
153
+ thread.anchor = typeof anchor === 'string' ? anchor : JSON.stringify(anchor ?? null);
154
+ if (isObject(location))
155
+ thread.location = location;
156
+ thread.updatedAt = now();
157
+ return thread;
158
+ });
159
+ }
160
+ remove(threadId, messageId) {
161
+ return this.mutate((doc) => {
162
+ const thread = this.find(doc, threadId);
163
+ if (messageId) {
164
+ thread.messages = thread.messages.filter((m) => m.id !== messageId);
165
+ if (thread.messages.length) {
166
+ thread.updatedAt = now();
167
+ return { deleted: 'message' };
168
+ }
169
+ }
170
+ doc.threads = doc.threads.filter((t) => t !== thread);
171
+ return { deleted: 'thread' };
172
+ });
173
+ }
174
+ markDelivered(threadId, via) {
175
+ return this.mutate((doc) => {
176
+ const thread = this.find(doc, threadId);
177
+ const at = now();
178
+ thread.agent = { status: 'delivered', sentAt: thread.agent?.sentAt ?? at, deliveredAt: at, via };
179
+ return thread;
180
+ });
181
+ }
182
+ markSent(threadId) {
183
+ return this.mutate((doc) => {
184
+ const thread = this.find(doc, threadId);
185
+ thread.agent = { status: 'pending', sentAt: now() };
186
+ return thread;
187
+ });
188
+ }
189
+ }
190
+ function setStatus(thread, status, at) {
191
+ thread.status = status;
192
+ thread.updatedAt = at;
193
+ if (status === 'resolved')
194
+ thread.resolvedAt = at;
195
+ else
196
+ delete thread.resolvedAt;
197
+ }
198
+ function checkText(text) {
199
+ if (typeof text !== 'string' || !text.trim())
200
+ throw new FrameError('invalid_argument', 'A comment needs text.');
201
+ if (text.length > TEXT_MAX)
202
+ throw new FrameError('invalid_argument', `A comment is at most ${TEXT_MAX} characters.`);
203
+ return text;
204
+ }
205
+ function isObject(v) {
206
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
207
+ }
208
+ /** What the agent reads of a thread. */
209
+ export function agentView(thread, n) {
210
+ return {
211
+ id: thread.id,
212
+ ...(n !== undefined ? { n } : {}),
213
+ status: thread.status,
214
+ ...(typeof thread.location?.file === 'string' ? { file: thread.location.file } : {}),
215
+ where: thread.label,
216
+ ...(thread.detail ? { detail: thread.detail } : {}),
217
+ location: thread.location ?? {},
218
+ anchor: thread.label,
219
+ ...(thread.agent ? { agent: thread.agent } : {}),
220
+ messages: thread.messages.map((m) => ({
221
+ from: m.author?.kind ?? 'user',
222
+ name: m.author?.name ?? '',
223
+ text: m.text,
224
+ at: m.at,
225
+ ...(m.editedAt ? { editedAt: m.editedAt } : {}),
226
+ })),
227
+ };
228
+ }
@@ -0,0 +1,149 @@
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-artifact.db.read` / `open-artifact.db.write`),
9
+ * in the shapes the CLI libraries answer.
10
+ */
11
+ import { EventEmitter } from 'node:events';
12
+ import { FrameError } from './files.ts';
13
+ export declare const DB_DIR = "db";
14
+ export declare const DOC_MAX_BYTES: number;
15
+ /** Largest page of an agent's read. */
16
+ export declare const READ_MAX = 1000;
17
+ export type Json = null | boolean | number | string | Json[] | {
18
+ [key: string]: Json;
19
+ };
20
+ export type JsonObject = {
21
+ [key: string]: Json;
22
+ };
23
+ export declare const dbError: (code: string, message: string, extra?: Record<string, unknown>) => FrameError;
24
+ /**
25
+ * A document's hash for `if_match`: the sha256 (lowercase hex) of its data as
26
+ * compact JSON, so reformatting a file by hand does not change it.
27
+ */
28
+ export declare function docSha256(data: unknown): string;
29
+ /** The fix for a `set` / `delete` over an existing document without `if_match`. */
30
+ export declare const IF_MATCH_FIX = "Read the document with ArtifactData {action: \"get\"} and pass its sha256 as if_match, or pass \"*\" to replace it anyway.";
31
+ /** Splits and checks a db path. `kind`: 'doc', 'collection' or 'any' ('' is the root, allowed for 'any' only). */
32
+ export declare function splitPath(p: unknown, kind?: 'doc' | 'collection' | 'any'): string[];
33
+ /** RFC 7386-style merge for `update`: objects merge, arrays and scalars replace, `{__delete__: true}` removes a key. */
34
+ export declare function mergePatch(target: unknown, patch: Record<string, unknown>): JsonObject;
35
+ export interface Where {
36
+ field: string;
37
+ op: string;
38
+ value: unknown;
39
+ }
40
+ export interface QuerySpec {
41
+ where: Where[];
42
+ orderBy: {
43
+ field: string;
44
+ dir: 'asc' | 'desc';
45
+ } | null;
46
+ limit: number | null;
47
+ }
48
+ export interface Doc {
49
+ id: string;
50
+ data: JsonObject;
51
+ }
52
+ /** Checks a query spec from a page: `{where?: [{field, op, value}], orderBy?: {field, dir}, limit?}`. */
53
+ export declare function checkSpec(raw?: unknown): QuerySpec;
54
+ export interface Lease {
55
+ holder: string;
56
+ expiresAt: number;
57
+ version: number;
58
+ }
59
+ export interface DbWrite {
60
+ op: 'set' | 'update' | 'delete' | 'str_replace';
61
+ path?: string;
62
+ collection?: string;
63
+ doc_id?: string;
64
+ data?: unknown;
65
+ file_path?: string;
66
+ /** The sha256 the writer read: write only while the document still has it. `null`: only while it does not exist. `"*"`: whatever it is now. */
67
+ if_match?: string | null;
68
+ /** `str_replace`: the field (a dot path) holding the text. */
69
+ field?: string;
70
+ /** `str_replace`: the text to find; it must occur exactly once. */
71
+ old?: string;
72
+ /** `str_replace`: what replaces it. */
73
+ new?: string;
74
+ }
75
+ /** Options of {@link DbStore.readDb}. */
76
+ export interface ReadOptions {
77
+ /** A query over a collection: `{where?, orderBy?, limit?}` as pages give it. */
78
+ query?: unknown;
79
+ /** Page size (1 to 1000). Default: everything. */
80
+ limit?: unknown;
81
+ /** Where a page starts: the `next_cursor` of the page before. */
82
+ cursor?: unknown;
83
+ }
84
+ /** Options of {@link DbStore.writeDb}. */
85
+ export interface WriteOptions {
86
+ /** Refuse a `set` or `delete` over an existing document that has no `if_match`. */
87
+ requireIfMatch?: boolean;
88
+ }
89
+ /** A store of one artifact's documents. Emits `change` with the doc paths a write touched. */
90
+ export declare class DbStore extends EventEmitter {
91
+ readonly root: string;
92
+ readonly dir: string;
93
+ readonly leases: Map<string, Lease>;
94
+ constructor(root: string);
95
+ private fileOf;
96
+ readDoc(p: string): JsonObject | null;
97
+ /** Documents of one collection, sorted by id. */
98
+ listCollection(p: string): Doc[];
99
+ query(p: string, rawSpec?: unknown): Doc[];
100
+ set(p: string, data: unknown): {
101
+ bytes: number;
102
+ created: boolean;
103
+ };
104
+ update(p: string, patch: unknown): {
105
+ bytes: number;
106
+ };
107
+ delete(p: string): {
108
+ existed: boolean;
109
+ };
110
+ add(collection: string, data: unknown): {
111
+ id: string;
112
+ path: string;
113
+ };
114
+ /** A lease on a document. */
115
+ acquire(p: string, opts?: {
116
+ holder?: unknown;
117
+ ttlMs?: unknown;
118
+ data?: unknown;
119
+ }): {
120
+ acquired: boolean;
121
+ version?: number;
122
+ expiresAt?: number;
123
+ holder?: string;
124
+ };
125
+ release(p: string, holder: unknown): {
126
+ released: boolean;
127
+ };
128
+ changed(paths: string[]): void;
129
+ /** Every document file. */
130
+ listAll(): {
131
+ path: string;
132
+ bytes: number;
133
+ }[];
134
+ /**
135
+ * The agent's read (`open-artifact.db.read`): the root lists every document path, a
136
+ * collection its documents (filtered by `query`), a document its data.
137
+ * Documents carry `sha256` for `if_match`; a page that stops early carries
138
+ * `next_cursor`.
139
+ */
140
+ readDb(p?: unknown, opts?: ReadOptions): unknown;
141
+ /**
142
+ * The agent's batch (`open-artifact.db.write`): every write is checked before any is
143
+ * made. A write with `if_match` that no longer holds fails the whole batch
144
+ * with `conflict`, its `current` holding what each such document is now.
145
+ */
146
+ writeDb(writes: unknown, opts?: WriteOptions): Record<string, unknown>[];
147
+ }
148
+ /** Doc paths of the db files a watcher saw change (paths relative to the artifact folder). */
149
+ export declare function docPathsOf(relPaths: Iterable<string>): string[];