@open-artifact/runtime 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,194 @@
1
+ /**
2
+ * The HTTP contract between an editor page and its local type server.
3
+ *
4
+ * Every route is relative to the artifact's page base (for example
5
+ * `http://127.0.0.1:4720/design/<token>/`). Both the browser provider
6
+ * ({@link ./local-provider.ts}) and the Node server (`@open-artifact/type-server`)
7
+ * import these names and shapes, so the two sides cannot drift apart.
8
+ */
9
+ import type { AgentDelivery, AgentRequest, AgentSendResult, AgentStatus, ArtifactErrorCode, CommentCreate, CommentThread, ConflictPath, DbChangeEvent, DbDocument, DbWrite, FileListing, FilesChangedEvent, HistoryChangeEvent, HistoryFileDiff, HistoryListing, HistoryRestoreResult, JsonRecord, JsonValue, Peer, PublishBatch, PublishResult, RoomMessage, Viewer } from './capabilities.ts';
10
+ /** Route paths, relative to the page base. */
11
+ export declare const API: {
12
+ readonly session: "_api/session";
13
+ readonly files: "_api/files";
14
+ readonly file: "_api/file";
15
+ readonly publish: "_api/publish";
16
+ readonly assets: "_api/assets";
17
+ readonly events: "_api/events";
18
+ readonly agentSend: "_api/agent/send";
19
+ readonly presence: "_api/presence";
20
+ readonly peers: "_api/peers";
21
+ readonly downloads: "_api/downloads";
22
+ readonly roomEmit: "_api/room/emit";
23
+ readonly dbGet: "_api/db/get";
24
+ readonly dbList: "_api/db/list";
25
+ readonly dbWrite: "_api/db/write";
26
+ readonly comments: "_api/comments";
27
+ readonly commentsCreate: "_api/comments/create";
28
+ readonly commentsReply: "_api/comments/reply";
29
+ readonly commentsResolve: "_api/comments/resolve";
30
+ readonly commentsMove: "_api/comments/move";
31
+ readonly commentsRemove: "_api/comments/remove";
32
+ readonly commentsSend: "_api/comments/send";
33
+ readonly history: "_api/history";
34
+ readonly historyFiles: "_api/history/files";
35
+ readonly historyFile: "_api/history/file";
36
+ readonly historyDiff: "_api/history/diff";
37
+ readonly historyRestore: "_api/history/restore";
38
+ readonly historyDismiss: "_api/history/dismiss";
39
+ };
40
+ /** Root-relative prefix every upload is served under. */
41
+ export declare const BLOB_PREFIX = "/_blob/";
42
+ /** `GET _api/session` */
43
+ export interface SessionResponse {
44
+ artifact: {
45
+ id: string;
46
+ title: string;
47
+ type: string;
48
+ };
49
+ viewer: Viewer;
50
+ agent: AgentStatus;
51
+ /** Stores the type keeps beside its files; absent ones are not offered (`db` / `comments` resolve `null`). */
52
+ stores?: {
53
+ db?: boolean;
54
+ comments?: boolean;
55
+ history?: boolean;
56
+ };
57
+ }
58
+ /** `GET _api/files` */
59
+ export interface FilesResponse {
60
+ files: FileListing;
61
+ }
62
+ /** Header carrying the SHA-256 of a file returned by `GET _api/file`. */
63
+ export declare const SHA_HEADER = "x-open-artifact-sha256";
64
+ /** `POST _api/publish` request body. */
65
+ export interface PublishRequest {
66
+ files: PublishBatch;
67
+ /** The publishing page's client id, so its own change events are not echoed back. */
68
+ client: string;
69
+ }
70
+ /** `POST _api/publish` 200 body. */
71
+ export type PublishResponse = PublishResult;
72
+ /** Body of every non-2xx JSON answer. */
73
+ export interface ErrorResponse {
74
+ code: ArtifactErrorCode;
75
+ message: string;
76
+ paths?: ConflictPath[];
77
+ }
78
+ /** `POST _api/agent/send` request body. */
79
+ export interface AgentSendRequest {
80
+ request: AgentRequest;
81
+ deliver: AgentDelivery;
82
+ }
83
+ /** `POST _api/agent/send` 200 body. */
84
+ export type AgentSendResponse = AgentSendResult;
85
+ /** `POST _api/presence` request body. */
86
+ export interface PresenceRequest {
87
+ client: string;
88
+ patch: Record<string, unknown>;
89
+ }
90
+ /** `GET _api/peers` */
91
+ export interface PeersResponse {
92
+ peers: Peer[];
93
+ }
94
+ /** `POST _api/room/emit` request body. Relayed to every other client as a `room` event. */
95
+ export interface RoomEmitRequest {
96
+ client: string;
97
+ topic: string;
98
+ data: JsonValue;
99
+ }
100
+ /** `GET _api/db/get?path=` 200 body. */
101
+ export interface DbGetResponse {
102
+ data: JsonRecord | null;
103
+ }
104
+ /** `GET _api/db/list?collection=` 200 body. */
105
+ export interface DbListResponse {
106
+ documents: DbDocument[];
107
+ }
108
+ /** `POST _api/db/write` request body. */
109
+ export interface DbWriteRequest {
110
+ writes: DbWrite[];
111
+ /** The writing page's client id, so the change is not echoed back to it. */
112
+ client: string;
113
+ }
114
+ /** `GET _api/comments` 200 body, and the body of `POST _api/comments/remove`. */
115
+ export interface CommentsResponse {
116
+ threads: CommentThread[];
117
+ }
118
+ /** `POST _api/comments/create` request body. */
119
+ export interface CommentCreateRequest {
120
+ input: CommentCreate;
121
+ }
122
+ /** `POST _api/comments/reply` request body. */
123
+ export interface CommentReplyRequest {
124
+ threadId: string;
125
+ text: string;
126
+ }
127
+ /** `POST _api/comments/resolve` request body. */
128
+ export interface CommentResolveRequest {
129
+ threadId: string;
130
+ resolved: boolean;
131
+ }
132
+ /** `POST _api/comments/move` request body. */
133
+ export interface CommentMoveRequest {
134
+ threadId: string;
135
+ anchor: string;
136
+ location?: JsonRecord;
137
+ }
138
+ /** `POST _api/comments/remove` request body. */
139
+ export interface CommentRemoveRequest {
140
+ threadId: string;
141
+ messageId?: string;
142
+ }
143
+ /** `POST _api/comments/send` request body. */
144
+ export interface CommentSendRequest {
145
+ threadId: string;
146
+ }
147
+ /** 200 body of the comment routes that change one thread. */
148
+ export interface CommentThreadResponse {
149
+ thread: CommentThread;
150
+ }
151
+ /** `GET _api/history` 200 body (versions newest first). */
152
+ export type HistoryResponse = HistoryListing;
153
+ /** `GET _api/history/files?n=` 200 body. */
154
+ export interface HistoryFilesResponse {
155
+ files: FileListing;
156
+ }
157
+ /**
158
+ * `GET _api/history/file?n=&path=` answers the raw bytes (with
159
+ * {@link SHA_HEADER}); `GET _api/history/diff?n=&path=` a
160
+ * {@link HistoryDiffResponse}.
161
+ */
162
+ export type HistoryDiffResponse = HistoryFileDiff;
163
+ /** `POST _api/history/restore` request body. */
164
+ export interface HistoryRestoreRequest {
165
+ n: number;
166
+ /** Only these paths (default: every path). */
167
+ paths?: string[];
168
+ /** The restoring page's client id (it hears of the restore like every other page). */
169
+ client?: string;
170
+ }
171
+ /** `POST _api/history/restore` 200 body. */
172
+ export type HistoryRestoreResponse = HistoryRestoreResult;
173
+ /** `POST _api/history/dismiss` request body. */
174
+ export interface HistoryDismissRequest {
175
+ id: string;
176
+ }
177
+ /** Server-sent events on `GET _api/events?client=<id>`, by event name. */
178
+ export interface ServerEvents {
179
+ /** Files changed by someone other than the subscribing client. */
180
+ files: FilesChangedEvent;
181
+ /** Agent availability changed. */
182
+ agent: AgentStatus;
183
+ /** The set of present peers changed. */
184
+ peers: Peer[];
185
+ /** Documents changed by someone other than the subscribing client (db-backed types). */
186
+ db: DbChangeEvent;
187
+ /** The full comment thread list, after any change (types with comments). */
188
+ comments: CommentThread[];
189
+ /** An ephemeral message from another client. */
190
+ room: RoomMessage;
191
+ /** A version was recorded (or grew). */
192
+ history: HistoryChangeEvent;
193
+ }
194
+ export type ServerEventName = keyof ServerEvents;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The HTTP contract between an editor page and its local type server.
3
+ *
4
+ * Every route is relative to the artifact's page base (for example
5
+ * `http://127.0.0.1:4720/design/<token>/`). Both the browser provider
6
+ * ({@link ./local-provider.ts}) and the Node server (`@open-artifact/type-server`)
7
+ * import these names and shapes, so the two sides cannot drift apart.
8
+ */
9
+ /** Route paths, relative to the page base. */
10
+ export const API = {
11
+ session: '_api/session',
12
+ files: '_api/files',
13
+ file: '_api/file',
14
+ publish: '_api/publish',
15
+ assets: '_api/assets',
16
+ events: '_api/events',
17
+ agentSend: '_api/agent/send',
18
+ presence: '_api/presence',
19
+ peers: '_api/peers',
20
+ downloads: '_api/downloads',
21
+ roomEmit: '_api/room/emit',
22
+ dbGet: '_api/db/get',
23
+ dbList: '_api/db/list',
24
+ dbWrite: '_api/db/write',
25
+ comments: '_api/comments',
26
+ commentsCreate: '_api/comments/create',
27
+ commentsReply: '_api/comments/reply',
28
+ commentsResolve: '_api/comments/resolve',
29
+ commentsMove: '_api/comments/move',
30
+ commentsRemove: '_api/comments/remove',
31
+ commentsSend: '_api/comments/send',
32
+ history: '_api/history',
33
+ historyFiles: '_api/history/files',
34
+ historyFile: '_api/history/file',
35
+ historyDiff: '_api/history/diff',
36
+ historyRestore: '_api/history/restore',
37
+ historyDismiss: '_api/history/dismiss',
38
+ };
39
+ /** Root-relative prefix every upload is served under. */
40
+ export const BLOB_PREFIX = '/_blob/';
41
+ /** Header carrying the SHA-256 of a file returned by `GET _api/file`. */
42
+ export const SHA_HEADER = 'x-open-artifact-sha256';
package/src/index.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@open-artifact/runtime`: the `window.openartifact` page runtime.
3
+ *
4
+ * - `capabilities.ts`: the capability contracts (types and errors).
5
+ * - `client.ts`: installs `window.openartifact` over a provider.
6
+ * - `local-provider.ts`: the provider backed by the local type server.
7
+ * - `broker.ts`: the provider that brokers calls through the Shell (and `createPageProvider`).
8
+ * - `http-api.ts`: the HTTP contract shared with `@open-artifact/type-server`.
9
+ * - `shell.ts`: the page side of the Open Artifact Shell protocol.
10
+ * - `untrusted.ts`: fencing untrusted text before it reaches a model.
11
+ */
12
+ export * from './capabilities.ts';
13
+ export * from './client.ts';
14
+ export * from './local-provider.ts';
15
+ export * from './broker.ts';
16
+ export * from './http-api.ts';
17
+ export * from './shell.ts';
18
+ export * from './untrusted.ts';
package/src/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@open-artifact/runtime`: the `window.openartifact` page runtime.
3
+ *
4
+ * - `capabilities.ts`: the capability contracts (types and errors).
5
+ * - `client.ts`: installs `window.openartifact` over a provider.
6
+ * - `local-provider.ts`: the provider backed by the local type server.
7
+ * - `broker.ts`: the provider that brokers calls through the Shell (and `createPageProvider`).
8
+ * - `http-api.ts`: the HTTP contract shared with `@open-artifact/type-server`.
9
+ * - `shell.ts`: the page side of the Open Artifact Shell protocol.
10
+ * - `untrusted.ts`: fencing untrusted text before it reaches a model.
11
+ */
12
+ export * from "./capabilities.js";
13
+ export * from "./client.js";
14
+ export * from "./local-provider.js";
15
+ export * from "./broker.js";
16
+ export * from "./http-api.js";
17
+ export * from "./shell.js";
18
+ export * from "./untrusted.js";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A capability provider backed by the local type server's HTTP API.
3
+ *
4
+ * This is what makes an editor page work when it is served by
5
+ * `@open-artifact/type-server`: every capability call becomes a `fetch`
6
+ * against the page base, and pushed changes arrive over one EventSource.
7
+ */
8
+ import type { CapabilityProvider } from './client.ts';
9
+ /**
10
+ * Why the page's access changed: `removed` (the server now refuses this
11
+ * viewer: a share link was turned off or reset, the guest was removed, or
12
+ * sharing stopped) or `changed` (the viewer is someone else now, or has
13
+ * another role).
14
+ */
15
+ export type AccessChange = 'removed' | 'changed';
16
+ /** Options of {@link createLocalProvider}. */
17
+ export interface LocalProviderOptions {
18
+ /** The page base URL; defaults to the directory of `location.href`. */
19
+ base?: string;
20
+ /**
21
+ * Called once when the event stream was cut and the server no longer lets
22
+ * this viewer in as before (instead of reconnecting forever). Default:
23
+ * reload the page, so it opens with the new role, or the server's
24
+ * "No access" page.
25
+ */
26
+ onAccessChange?: (change: AccessChange) => void;
27
+ }
28
+ /**
29
+ * What a session answer means for a page that started as `was`: `null` when
30
+ * nothing changed, else how its access changed. `status` is the HTTP status
31
+ * of `_api/session`.
32
+ */
33
+ export declare function accessChangeOf(was: {
34
+ id: string;
35
+ role: string;
36
+ }, status: number, now?: {
37
+ id?: unknown;
38
+ role?: unknown;
39
+ } | null): AccessChange | null;
40
+ /**
41
+ * Creates the provider. Capabilities are built lazily on first `use()` and the
42
+ * session (`GET _api/session`) is fetched once and shared.
43
+ */
44
+ export declare function createLocalProvider(options?: LocalProviderOptions): CapabilityProvider;
@@ -0,0 +1,360 @@
1
+ /**
2
+ * A capability provider backed by the local type server's HTTP API.
3
+ *
4
+ * This is what makes an editor page work when it is served by
5
+ * `@open-artifact/type-server`: every capability call becomes a `fetch`
6
+ * against the page base, and pushed changes arrive over one EventSource.
7
+ */
8
+ import { ArtifactError, canEdit, } from "./capabilities.js";
9
+ import { API, } from "./http-api.js";
10
+ /**
11
+ * What a session answer means for a page that started as `was`: `null` when
12
+ * nothing changed, else how its access changed. `status` is the HTTP status
13
+ * of `_api/session`.
14
+ */
15
+ export function accessChangeOf(was, status, now) {
16
+ if (status === 401 || status === 403)
17
+ return 'removed';
18
+ if (status < 200 || status >= 300 || !now)
19
+ return null;
20
+ return now.id === was.id && now.role === was.role ? null : 'changed';
21
+ }
22
+ /** Turns a non-2xx response into an {@link ArtifactError}. */
23
+ async function toError(response) {
24
+ let body = {};
25
+ try {
26
+ body = (await response.json());
27
+ }
28
+ catch {
29
+ /* not JSON: fall through to a status-based code */
30
+ }
31
+ const fallback = response.status === 409 ? 'conflict' : response.status === 403 ? 'not_writer' : response.status === 404 ? 'not_found' : 'unavailable';
32
+ return new ArtifactError(body.code ?? fallback, body.message ?? `HTTP ${response.status}`, body.paths);
33
+ }
34
+ /** A random id for this page load, used to suppress echoes of our own writes. */
35
+ function makeClientId() {
36
+ const bytes = new Uint8Array(8);
37
+ crypto.getRandomValues(bytes);
38
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
39
+ }
40
+ /**
41
+ * Creates the provider. Capabilities are built lazily on first `use()` and the
42
+ * session (`GET _api/session`) is fetched once and shared.
43
+ */
44
+ export function createLocalProvider(options = {}) {
45
+ const base = new URL(options.base ?? './', location.href);
46
+ const client = makeClientId();
47
+ const url = (path, query) => {
48
+ const target = new URL(path, base);
49
+ for (const [key, value] of Object.entries(query ?? {}))
50
+ target.searchParams.set(key, value);
51
+ return target.toString();
52
+ };
53
+ const json = async (path, init, query) => {
54
+ let response;
55
+ try {
56
+ response = await fetch(url(path, query), init);
57
+ }
58
+ catch (error) {
59
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
60
+ }
61
+ if (!response.ok)
62
+ throw await toError(response);
63
+ return (await response.json());
64
+ };
65
+ /** POSTs a JSON body and reads the JSON answer. */
66
+ const post = (path, body) => json(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
67
+ const listeners = new Map();
68
+ const dispatch = (name, payload) => {
69
+ for (const fn of listeners.get(name) ?? [])
70
+ fn(payload);
71
+ };
72
+ const subscribe = (name, listener) => {
73
+ let set = listeners.get(name);
74
+ if (!set) {
75
+ set = new Set();
76
+ listeners.set(name, set);
77
+ fallback?.addEventListener(name, fromSource);
78
+ }
79
+ set.add(listener);
80
+ connect();
81
+ return () => set.delete(listener);
82
+ };
83
+ // The stream is a WebSocket: browsers open at most six HTTP connections to
84
+ // one host, for all tabs together, and an EventSource held open by every
85
+ // page would use them up once six pages are open. WebSockets do not count
86
+ // against that limit. When no WebSocket ever opens (a proxy that does not
87
+ // pass upgrades), the same events come as server-sent events instead.
88
+ let socket = null;
89
+ let opened = false;
90
+ let fallback = null;
91
+ let retry = null;
92
+ const fromSource = (event) => {
93
+ dispatch(event.type, JSON.parse(event.data));
94
+ };
95
+ const useEventSource = () => {
96
+ const source = new EventSource(url(API.events, { client }));
97
+ fallback = source;
98
+ for (const name of listeners.keys())
99
+ source.addEventListener(name, fromSource);
100
+ // An EventSource retries by itself, but gives up (CLOSED) on a refusal.
101
+ source.onerror = () => {
102
+ void checkAccess().then((ended) => {
103
+ if (ended || source.readyState !== EventSource.CLOSED || fallback !== source)
104
+ return;
105
+ fallback = null;
106
+ retry = setTimeout(() => {
107
+ retry = null;
108
+ connect();
109
+ }, 2000);
110
+ });
111
+ };
112
+ };
113
+ /*
114
+ * A guest who lost access has their stream cut, and every reconnect is
115
+ * refused (a WebSocket never says it was a 403). So when the stream drops,
116
+ * ask the session first: refused, or answered for someone else, ends the
117
+ * page's connection instead of retrying forever.
118
+ */
119
+ let accessEnded = false;
120
+ let checking = false;
121
+ const endAccess = (change) => {
122
+ if (accessEnded)
123
+ return;
124
+ accessEnded = true;
125
+ if (retry)
126
+ clearTimeout(retry);
127
+ retry = null;
128
+ fallback?.close();
129
+ fallback = null;
130
+ socket?.close();
131
+ socket = null;
132
+ if (options.onAccessChange)
133
+ options.onAccessChange(change);
134
+ else
135
+ location.reload();
136
+ };
137
+ /** Resolves true when access ended (the stream must not reconnect). */
138
+ const checkAccess = async () => {
139
+ if (accessEnded)
140
+ return true;
141
+ if (!session || checking)
142
+ return false;
143
+ checking = true;
144
+ try {
145
+ const was = (await session.catch(() => null))?.viewer;
146
+ if (!was)
147
+ return false;
148
+ let response;
149
+ try {
150
+ response = await fetch(url(API.session), { cache: 'no-store' });
151
+ }
152
+ catch {
153
+ return false; // the server is down: keep reconnecting
154
+ }
155
+ const now = response.ok ? (await response.json().catch(() => null))?.viewer : null;
156
+ const change = accessChangeOf(was, response.status, now);
157
+ if (change)
158
+ endAccess(change);
159
+ return change !== null;
160
+ }
161
+ finally {
162
+ checking = false;
163
+ }
164
+ };
165
+ function connect() {
166
+ if (socket || fallback || retry || accessEnded)
167
+ return;
168
+ if (typeof WebSocket === 'undefined')
169
+ return useEventSource();
170
+ const target = new URL(url(API.events, { client }));
171
+ target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
172
+ const ws = new WebSocket(target);
173
+ socket = ws;
174
+ ws.onopen = () => {
175
+ opened = true;
176
+ };
177
+ ws.onmessage = (event) => {
178
+ let message;
179
+ try {
180
+ message = JSON.parse(String(event.data));
181
+ }
182
+ catch {
183
+ return;
184
+ }
185
+ if (message.event)
186
+ dispatch(message.event, message.data);
187
+ };
188
+ ws.onclose = () => {
189
+ if (socket === ws)
190
+ socket = null;
191
+ if (accessEnded)
192
+ return;
193
+ if (!opened)
194
+ return useEventSource();
195
+ // Reconnect as an EventSource would, unless access ended.
196
+ void checkAccess().then((ended) => {
197
+ if (ended || socket || fallback || retry)
198
+ return;
199
+ retry = setTimeout(() => {
200
+ retry = null;
201
+ connect();
202
+ }, 2000);
203
+ });
204
+ };
205
+ }
206
+ let session = null;
207
+ const getSession = () => (session ??= json(API.session));
208
+ const builders = {
209
+ async artifact() {
210
+ const { artifact } = await getSession();
211
+ const capability = {
212
+ id: artifact.id,
213
+ title: async () => (await json(API.session)).artifact.title,
214
+ list: async () => (await json(API.files)).files,
215
+ readText: async (path) => new TextDecoder().decode(await readBytes(path)),
216
+ readBytes: (path) => readBytes(path),
217
+ publish: async (files) => {
218
+ const body = { files, client };
219
+ return json(API.publish, {
220
+ method: 'POST',
221
+ headers: { 'content-type': 'application/json' },
222
+ body: JSON.stringify(body),
223
+ });
224
+ },
225
+ onChange: (listener) => subscribe('files', listener),
226
+ };
227
+ return capability;
228
+ },
229
+ async assets() {
230
+ const { viewer } = await getSession();
231
+ if (!canEdit(viewer.role))
232
+ return null;
233
+ const capability = {
234
+ upload: async (data, opts) => json(API.assets, { method: 'POST', headers: { 'content-type': data.type || 'application/octet-stream' }, body: data }, opts?.name ? { name: opts.name } : undefined),
235
+ };
236
+ return capability;
237
+ },
238
+ async user() {
239
+ const { viewer } = await getSession();
240
+ const capability = { me: async () => viewer };
241
+ return capability;
242
+ },
243
+ async agent() {
244
+ const capability = {
245
+ send: async (request, opts) => {
246
+ const body = { request, deliver: opts?.deliver ?? 'send' };
247
+ return json(API.agentSend, {
248
+ method: 'POST',
249
+ headers: { 'content-type': 'application/json' },
250
+ body: JSON.stringify(body),
251
+ });
252
+ },
253
+ status: async () => (await json(API.session)).agent,
254
+ onStatus: (listener) => subscribe('agent', listener),
255
+ };
256
+ return capability;
257
+ },
258
+ async room() {
259
+ const capability = {
260
+ self: async () => client,
261
+ presence: async (patch) => {
262
+ const body = { client, patch };
263
+ await json(API.presence, {
264
+ method: 'POST',
265
+ headers: { 'content-type': 'application/json' },
266
+ body: JSON.stringify(body),
267
+ });
268
+ },
269
+ peers: async () => (await json(API.peers)).peers,
270
+ onPeers: (listener) => subscribe('peers', listener),
271
+ emit: async (topic, data) => {
272
+ const body = { client, topic, data };
273
+ await post(API.roomEmit, body);
274
+ },
275
+ onMessage: (listener) => subscribe('room', listener),
276
+ };
277
+ return capability;
278
+ },
279
+ async db() {
280
+ const { stores } = await getSession();
281
+ if (!stores?.db)
282
+ return null;
283
+ const capability = {
284
+ get: async (path) => (await json(API.dbGet, { cache: 'no-store' }, { path })).data,
285
+ list: async (collection) => (await json(API.dbList, { cache: 'no-store' }, { collection })).documents,
286
+ write: async (writes) => {
287
+ const body = { writes, client };
288
+ await post(API.dbWrite, body);
289
+ },
290
+ onChange: (listener) => subscribe('db', listener),
291
+ };
292
+ return capability;
293
+ },
294
+ async comments() {
295
+ const { stores } = await getSession();
296
+ if (!stores?.comments)
297
+ return null;
298
+ const thread = async (path, body) => (await post(path, body)).thread;
299
+ const capability = {
300
+ list: async () => (await json(API.comments, { cache: 'no-store' })).threads,
301
+ create: (input) => thread(API.commentsCreate, { input }),
302
+ reply: (threadId, text) => thread(API.commentsReply, { threadId, text }),
303
+ setResolved: (threadId, resolved) => thread(API.commentsResolve, { threadId, resolved }),
304
+ move: (threadId, anchor, location) => thread(API.commentsMove, { threadId, anchor, ...(location ? { location } : {}) }),
305
+ remove: async (threadId, messageId) => {
306
+ await post(API.commentsRemove, { threadId, ...(messageId ? { messageId } : {}) });
307
+ },
308
+ sendToAgent: (threadId) => thread(API.commentsSend, { threadId }),
309
+ onChange: (listener) => subscribe('comments', listener),
310
+ };
311
+ return capability;
312
+ },
313
+ async history() {
314
+ const { stores } = await getSession();
315
+ if (!stores?.history)
316
+ return null;
317
+ const at = (n, path) => ({ n: String(n), ...(path === undefined ? {} : { path }) });
318
+ const capability = {
319
+ list: () => json(API.history, { cache: 'no-store' }),
320
+ files: async (n) => (await json(API.historyFiles, { cache: 'no-store' }, at(n))).files,
321
+ read: async (n, path) => new TextDecoder().decode(await fetchBytes(API.historyFile, at(n, path))),
322
+ readBytes: (n, path) => fetchBytes(API.historyFile, at(n, path)),
323
+ diff: (n, path) => json(API.historyDiff, { cache: 'no-store' }, at(n, path)),
324
+ restore: (n, paths) => post(API.historyRestore, { n, ...(paths ? { paths } : {}), client }),
325
+ dismissNotice: async (id) => {
326
+ await post(API.historyDismiss, { id });
327
+ },
328
+ onChange: (listener) => subscribe('history', listener),
329
+ };
330
+ return capability;
331
+ },
332
+ async downloads() {
333
+ const capability = {
334
+ save: async ({ name, data }) => json(API.downloads, { method: 'POST', headers: { 'content-type': data.type || 'application/octet-stream' }, body: data }, { name }),
335
+ };
336
+ return capability;
337
+ },
338
+ };
339
+ function readBytes(path) {
340
+ return fetchBytes(API.file, { path });
341
+ }
342
+ async function fetchBytes(route, query) {
343
+ let response;
344
+ try {
345
+ response = await fetch(url(route, query), { cache: 'no-store' });
346
+ }
347
+ catch (error) {
348
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
349
+ }
350
+ if (!response.ok)
351
+ throw await toError(response);
352
+ return new Uint8Array(await response.arrayBuffer());
353
+ }
354
+ return {
355
+ get(name) {
356
+ const build = builders[name];
357
+ return build ? build() : null;
358
+ },
359
+ };
360
+ }