@openartifactsai/runtime 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.
@@ -0,0 +1,491 @@
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
+ * `@openartifactsai/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, validByteLimit, } from "./capabilities.js";
9
+ import { createHttpSampleTransport, createSampleFunction, withTransport } from "./sample.js";
10
+ import { API, } from "./http-api.js";
11
+ import { SHEET_API, SHEET_EVENT, SHEET_WALKTHROUGH_EVENT } from "./sheet-api.js";
12
+ import { DOC_API, } from "./doc-api.js";
13
+ /**
14
+ * What a session answer means for a page that started as `was`: `null` when
15
+ * nothing changed, else how its access changed. `status` is the HTTP status
16
+ * of `_api/session`.
17
+ */
18
+ export function accessChangeOf(was, status, now) {
19
+ if (status === 401 || status === 403)
20
+ return 'removed';
21
+ if (status < 200 || status >= 300 || !now)
22
+ return null;
23
+ return now.id === was.id && now.role === was.role ? null : 'changed';
24
+ }
25
+ /** Turns a non-2xx response into an {@link ArtifactError}. */
26
+ async function toError(response) {
27
+ let body = {};
28
+ try {
29
+ body = (await response.json());
30
+ }
31
+ catch {
32
+ /* not JSON: fall through to a status-based code */
33
+ }
34
+ const fallback = response.status === 409 ? 'conflict' : response.status === 403 ? 'not_writer' : response.status === 404 ? 'not_found' : 'unavailable';
35
+ return new ArtifactError(body.code ?? fallback, body.message ?? `HTTP ${response.status}`, body.paths, body.retryable === true);
36
+ }
37
+ /** A random id for this page load, used to suppress echoes of our own writes. */
38
+ function makeClientId() {
39
+ const bytes = new Uint8Array(8);
40
+ crypto.getRandomValues(bytes);
41
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
42
+ }
43
+ /**
44
+ * Creates the provider. Capabilities are built lazily on first `use()` and the
45
+ * session (`GET _api/session`) is fetched once and shared.
46
+ */
47
+ export function createLocalProvider(options = {}) {
48
+ const base = new URL(options.base ?? './', location.href);
49
+ const client = makeClientId();
50
+ const url = (path, query) => {
51
+ const target = new URL(path, base);
52
+ for (const [key, value] of Object.entries(query ?? {}))
53
+ target.searchParams.set(key, value);
54
+ return target.toString();
55
+ };
56
+ const json = async (path, init, query) => {
57
+ let response;
58
+ try {
59
+ response = await fetch(url(path, query), init);
60
+ }
61
+ catch (error) {
62
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
63
+ }
64
+ if (!response.ok)
65
+ throw await toError(response);
66
+ return (await response.json());
67
+ };
68
+ /** POSTs a JSON body and reads the JSON answer. */
69
+ const post = (path, body) => json(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
70
+ const listeners = new Map();
71
+ const dispatch = (name, payload) => {
72
+ for (const fn of listeners.get(name) ?? [])
73
+ fn(payload);
74
+ };
75
+ const subscribe = (name, listener) => {
76
+ let set = listeners.get(name);
77
+ if (!set) {
78
+ set = new Set();
79
+ listeners.set(name, set);
80
+ fallback?.addEventListener(name, fromSource);
81
+ }
82
+ set.add(listener);
83
+ connect();
84
+ return () => set.delete(listener);
85
+ };
86
+ // The stream is a WebSocket: browsers open at most six HTTP connections to
87
+ // one host, for all tabs together, and an EventSource held open by every
88
+ // page would use them up once six pages are open. WebSockets do not count
89
+ // against that limit. When no WebSocket ever opens (a proxy that does not
90
+ // pass upgrades), the same events come as server-sent events instead.
91
+ let socket = null;
92
+ let opened = false;
93
+ /*
94
+ * Changes made while the stream was down are not sent again. When it opens
95
+ * after it had been open, file listeners hear an empty `resync` event and
96
+ * compare the listing with what they hold.
97
+ */
98
+ let streamed = false;
99
+ const streamOpened = () => {
100
+ if (streamed)
101
+ dispatch('files', { changes: {}, resync: true });
102
+ streamed = true;
103
+ };
104
+ let fallback = null;
105
+ let retry = null;
106
+ const fromSource = (event) => {
107
+ dispatch(event.type, JSON.parse(event.data));
108
+ };
109
+ const useEventSource = () => {
110
+ const source = new EventSource(url(API.events, { client }));
111
+ fallback = source;
112
+ for (const name of listeners.keys())
113
+ source.addEventListener(name, fromSource);
114
+ // Also on each reconnect the EventSource makes by itself.
115
+ source.onopen = streamOpened;
116
+ // An EventSource retries by itself, but gives up (CLOSED) on a refusal.
117
+ source.onerror = () => {
118
+ void checkAccess().then((ended) => {
119
+ if (ended || source.readyState !== EventSource.CLOSED || fallback !== source)
120
+ return;
121
+ fallback = null;
122
+ retry = setTimeout(() => {
123
+ retry = null;
124
+ connect();
125
+ }, 2000);
126
+ });
127
+ };
128
+ };
129
+ /*
130
+ * A guest who lost access has their stream cut, and every reconnect is
131
+ * refused (a WebSocket never says it was a 403). So when the stream drops,
132
+ * ask the session first: refused, or answered for someone else, ends the
133
+ * page's connection instead of retrying forever.
134
+ */
135
+ let accessEnded = false;
136
+ let checking = false;
137
+ const endAccess = (change) => {
138
+ if (accessEnded)
139
+ return;
140
+ accessEnded = true;
141
+ if (retry)
142
+ clearTimeout(retry);
143
+ retry = null;
144
+ fallback?.close();
145
+ fallback = null;
146
+ socket?.close();
147
+ socket = null;
148
+ if (options.onAccessChange)
149
+ options.onAccessChange(change);
150
+ else
151
+ location.reload();
152
+ };
153
+ /** Resolves true when access ended (the stream must not reconnect). */
154
+ const checkAccess = async () => {
155
+ if (accessEnded)
156
+ return true;
157
+ if (!session || checking)
158
+ return false;
159
+ checking = true;
160
+ try {
161
+ const was = (await session.catch(() => null))?.viewer;
162
+ if (!was)
163
+ return false;
164
+ let response;
165
+ try {
166
+ response = await fetch(url(API.session), { cache: 'no-store' });
167
+ }
168
+ catch {
169
+ return false; // the server is down: keep reconnecting
170
+ }
171
+ const now = response.ok ? (await response.json().catch(() => null))?.viewer : null;
172
+ const change = accessChangeOf(was, response.status, now);
173
+ if (change)
174
+ endAccess(change);
175
+ return change !== null;
176
+ }
177
+ finally {
178
+ checking = false;
179
+ }
180
+ };
181
+ function connect() {
182
+ if (socket || fallback || retry || accessEnded)
183
+ return;
184
+ if (typeof WebSocket === 'undefined')
185
+ return useEventSource();
186
+ const target = new URL(url(API.events, { client }));
187
+ target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
188
+ const ws = new WebSocket(target);
189
+ socket = ws;
190
+ ws.onopen = () => {
191
+ opened = true;
192
+ streamOpened();
193
+ };
194
+ ws.onmessage = (event) => {
195
+ let message;
196
+ try {
197
+ message = JSON.parse(String(event.data));
198
+ }
199
+ catch {
200
+ return;
201
+ }
202
+ if (message.event)
203
+ dispatch(message.event, message.data);
204
+ };
205
+ ws.onclose = () => {
206
+ if (socket === ws)
207
+ socket = null;
208
+ if (accessEnded)
209
+ return;
210
+ if (!opened)
211
+ return useEventSource();
212
+ // Reconnect as an EventSource would, unless access ended.
213
+ void checkAccess().then((ended) => {
214
+ if (ended || socket || fallback || retry)
215
+ return;
216
+ retry = setTimeout(() => {
217
+ retry = null;
218
+ connect();
219
+ }, 2000);
220
+ });
221
+ };
222
+ }
223
+ let session = null;
224
+ const getSession = () => (session ??= json(API.session));
225
+ const builders = {
226
+ async artifact() {
227
+ const { artifact, stores } = await getSession();
228
+ const capability = {
229
+ id: artifact.id,
230
+ ...(stores?.systemCopy ? {
231
+ systemCopy: (namespace, action) => json(API.systemCopy, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ namespace, action }) }),
232
+ } : {}),
233
+ title: async () => (await json(API.session)).artifact.title,
234
+ list: async () => (await json(API.files)).files,
235
+ readText: async (path) => new TextDecoder().decode(await readBytes(path)),
236
+ readBytes: (path) => readBytes(path),
237
+ publish: async (files) => {
238
+ const body = { files, client };
239
+ return json(API.publish, {
240
+ method: 'POST',
241
+ headers: { 'content-type': 'application/json' },
242
+ body: JSON.stringify(body),
243
+ });
244
+ },
245
+ onChange: (listener) => subscribe('files', listener),
246
+ };
247
+ return capability;
248
+ },
249
+ async assets() {
250
+ const { viewer, uploadMaxBytes } = await getSession();
251
+ if (!canEdit(viewer.role))
252
+ return null;
253
+ const capability = {
254
+ 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),
255
+ ...(validByteLimit(uploadMaxBytes) ? { maxBytes: uploadMaxBytes } : {}),
256
+ };
257
+ return capability;
258
+ },
259
+ async user() {
260
+ const { viewer } = await getSession();
261
+ const capability = { me: async () => viewer };
262
+ return capability;
263
+ },
264
+ async agent() {
265
+ const capability = {
266
+ send: async (request, opts) => {
267
+ const body = { request, deliver: opts?.deliver ?? 'send' };
268
+ return json(API.agentSend, {
269
+ method: 'POST',
270
+ headers: { 'content-type': 'application/json' },
271
+ body: JSON.stringify(body),
272
+ });
273
+ },
274
+ status: async () => (await json(API.session)).agent,
275
+ onStatus: (listener) => subscribe('agent', listener),
276
+ };
277
+ return capability;
278
+ },
279
+ async room() {
280
+ const capability = {
281
+ self: async () => client,
282
+ presence: async (patch) => {
283
+ const body = { client, patch };
284
+ await json(API.presence, {
285
+ method: 'POST',
286
+ headers: { 'content-type': 'application/json' },
287
+ body: JSON.stringify(body),
288
+ });
289
+ },
290
+ peers: async () => (await json(API.peers)).peers,
291
+ participants: async () => (await json(API.participants)).participants,
292
+ onPeers: (listener) => subscribe('peers', listener),
293
+ emit: async (topic, data) => {
294
+ const body = { client, topic, data };
295
+ await post(API.roomEmit, body);
296
+ },
297
+ onMessage: (listener) => subscribe('room', listener),
298
+ };
299
+ return capability;
300
+ },
301
+ async db() {
302
+ const { stores } = await getSession();
303
+ if (!stores?.db)
304
+ return null;
305
+ const capability = {
306
+ get: async (path) => (await json(API.dbGet, { cache: 'no-store' }, { path })).data,
307
+ list: async (collection) => (await json(API.dbList, { cache: 'no-store' }, { collection })).documents,
308
+ listing: async (collection) => {
309
+ const { documents, epoch, seq } = await json(API.dbList, { cache: 'no-store' }, { collection });
310
+ return typeof epoch === 'string' && typeof seq === 'number' ? { documents, epoch, seq } : { documents };
311
+ },
312
+ write: async (writes) => {
313
+ const body = { writes, client };
314
+ const { epoch, seq, documents } = await post(API.dbWrite, body);
315
+ return typeof epoch === 'string' && typeof seq === 'number' && documents !== undefined ? { epoch, seq, documents } : undefined;
316
+ },
317
+ onChange: (listener) => subscribe('db', listener),
318
+ };
319
+ return capability;
320
+ },
321
+ async comments() {
322
+ const { stores } = await getSession();
323
+ if (!stores?.comments)
324
+ return null;
325
+ const thread = async (path, body) => (await post(path, body)).thread;
326
+ const capability = {
327
+ list: async () => (await json(API.comments, { cache: 'no-store' })).threads,
328
+ create: (input) => thread(API.commentsCreate, { input }),
329
+ reply: (threadId, text, options) => thread(API.commentsReply, { threadId, text, ...(options?.to?.length ? { to: options.to } : {}), ...(options?.assignee !== undefined ? { assignee: options.assignee } : {}) }),
330
+ edit: (threadId, messageId, text, options) => thread(API.commentsEdit, { threadId, messageId, text, ...(options?.to ? { to: options.to } : {}) }),
331
+ react: (threadId, messageId, emoji, on) => thread(API.commentsReact, { threadId, messageId, emoji, on }),
332
+ setResolved: (threadId, resolved) => thread(API.commentsResolve, { threadId, resolved }),
333
+ move: (threadId, anchor, location, options) => thread(API.commentsMove, { threadId, anchor, ...(location ? { location } : {}), ...(typeof options?.from === 'string' ? { from: options.from } : {}) }),
334
+ remove: async (threadId, messageId) => {
335
+ await post(API.commentsRemove, { threadId, ...(messageId ? { messageId } : {}) });
336
+ },
337
+ sendToAgent: (threadId, options) => thread(API.commentsSend, {
338
+ threadId,
339
+ ...(options?.unasked
340
+ ? { unasked: true }
341
+ : { ...(options?.userText ? { userText: options.userText } : {}), ...(options?.selectionSnapshot ? { selectionSnapshot: options.selectionSnapshot } : {}) }),
342
+ }),
343
+ onChange: (listener) => subscribe('comments', listener),
344
+ };
345
+ return capability;
346
+ },
347
+ async doc() {
348
+ const { stores } = await getSession();
349
+ if (!stores?.doc)
350
+ return null;
351
+ const capability = {
352
+ session: () => post(DOC_API.session, { client }),
353
+ read: (tab) => post(DOC_API.read, { tab }),
354
+ call: (request) => post(DOC_API.call, { ...request, client }),
355
+ history: (tab) => post(DOC_API.history, { tab }),
356
+ version: (tab, rev) => post(DOC_API.version, { tab, rev }),
357
+ restore: (request) => post(DOC_API.restore, request),
358
+ importFile: (name, bytes, tabName) => json(DOC_API.importFile, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: bytes }, { name, ...(tabName ? { tabName } : {}) }),
359
+ exportFile: async (query) => {
360
+ let response;
361
+ try {
362
+ response = await fetch(url(DOC_API.exportFile, { format: query.format, ...(query.tab ? { tab: query.tab } : {}), ...(query.paper ? { paper: query.paper } : {}) }), { cache: 'no-store' });
363
+ }
364
+ catch (error) {
365
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
366
+ }
367
+ if (!response.ok)
368
+ throw await toError(response);
369
+ const disposition = response.headers.get('content-disposition') ?? '';
370
+ const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(disposition)?.[1] ?? '') || `doc.${query.format === 'markdown' ? 'md' : query.format}`;
371
+ let notes = [];
372
+ try {
373
+ notes = JSON.parse(decodeURIComponent(response.headers.get('x-doc-export-notes') ?? '%5B%5D'));
374
+ }
375
+ catch {
376
+ /* no notes */
377
+ }
378
+ return { name, mime: response.headers.get('content-type') ?? 'application/octet-stream', bytes: new Uint8Array(await response.arrayBuffer()), notes };
379
+ },
380
+ onFrame: (listener) => subscribe('doc', listener),
381
+ };
382
+ return capability;
383
+ },
384
+ async history() {
385
+ const { stores } = await getSession();
386
+ if (!stores?.history)
387
+ return null;
388
+ const at = (n, path) => ({ n: String(n), ...(path === undefined ? {} : { path }) });
389
+ const capability = {
390
+ list: () => json(API.history, { cache: 'no-store' }),
391
+ files: async (n) => (await json(API.historyFiles, { cache: 'no-store' }, at(n))).files,
392
+ read: async (n, path) => new TextDecoder().decode(await fetchBytes(API.historyFile, at(n, path))),
393
+ readBytes: (n, path) => fetchBytes(API.historyFile, at(n, path)),
394
+ diff: (n, path) => json(API.historyDiff, { cache: 'no-store' }, at(n, path)),
395
+ restore: (n, paths) => post(API.historyRestore, { n, ...(paths ? { paths } : {}), client }),
396
+ dismissNotice: async (id) => {
397
+ await post(API.historyDismiss, { id });
398
+ },
399
+ note: async (n, text) => {
400
+ await post(API.historyNote, { n, note: text });
401
+ },
402
+ onChange: (listener) => subscribe('history', listener),
403
+ };
404
+ return capability;
405
+ },
406
+ async mcp() {
407
+ const { viewer } = await getSession();
408
+ if (viewer.role !== 'owner')
409
+ return null;
410
+ const capability = {
411
+ callTool: async (server, tool, args, opts) => {
412
+ const signal = opts?.signal;
413
+ signal?.throwIfAborted();
414
+ const body = { server, tool, args, ...(opts?.timeoutMs === undefined ? {} : { timeoutMs: opts.timeoutMs }) };
415
+ try {
416
+ return await json(API.mcpCall, {
417
+ method: 'POST',
418
+ headers: { 'content-type': 'application/json' },
419
+ body: JSON.stringify(body),
420
+ ...(signal ? { signal } : {}),
421
+ });
422
+ }
423
+ catch (error) {
424
+ // Closing the request cancels the call on the server too.
425
+ if (signal?.aborted)
426
+ throw signal.reason;
427
+ throw error;
428
+ }
429
+ },
430
+ listTools: (server) => json(API.mcpTools, { cache: 'no-store' }, server === undefined ? undefined : { server }),
431
+ };
432
+ return capability;
433
+ },
434
+ async sheet() {
435
+ const { stores } = await getSession();
436
+ if (!stores?.sheet)
437
+ return null;
438
+ // Sends go one at a time, each once the one before it is answered: the server takes them, and the page hears
439
+ // their answers, in the order the page made them, though each request is a fetch of its own.
440
+ let sending = Promise.resolve();
441
+ const capability = {
442
+ read: (request) => post(SHEET_API.read, request),
443
+ send: (request) => {
444
+ const answer = sending.then(() => post(SHEET_API.send, request));
445
+ sending = answer.catch(() => undefined);
446
+ return answer;
447
+ },
448
+ widget: (request) => post(SHEET_API.widget, request),
449
+ importFile: (file, name) => json(SHEET_API.importFile, { method: 'POST', headers: { 'content-type': file.type || 'application/octet-stream' }, body: file }, { name }),
450
+ onFrame: (listener) => subscribe(SHEET_EVENT, listener),
451
+ onWalkthrough: (listener) => subscribe(SHEET_WALKTHROUGH_EVENT, listener),
452
+ };
453
+ return capability;
454
+ },
455
+ async sample() {
456
+ const { stores } = await getSession();
457
+ // An older type server does not say it serves `sample`: the capability is not there.
458
+ if (!stores?.sample)
459
+ return null;
460
+ const transport = createHttpSampleTransport({ url, client, routes: API });
461
+ return withTransport(createSampleFunction(transport), transport);
462
+ },
463
+ async downloads() {
464
+ const capability = {
465
+ save: async ({ name, data }) => json(API.downloads, { method: 'POST', headers: { 'content-type': data.type || 'application/octet-stream' }, body: data }, { name }),
466
+ };
467
+ return capability;
468
+ },
469
+ };
470
+ function readBytes(path) {
471
+ return fetchBytes(API.file, { path });
472
+ }
473
+ async function fetchBytes(route, query) {
474
+ let response;
475
+ try {
476
+ response = await fetch(url(route, query), { cache: 'no-store' });
477
+ }
478
+ catch (error) {
479
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
480
+ }
481
+ if (!response.ok)
482
+ throw await toError(response);
483
+ return new Uint8Array(await response.arrayBuffer());
484
+ }
485
+ return {
486
+ get(name) {
487
+ const build = builders[name];
488
+ return build ? build() : null;
489
+ },
490
+ };
491
+ }
package/src/roles.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What each role may do on an artifact's page routes.
3
+ *
4
+ * The local type server (`@openartifactsai/type-server`'s `sharing.ts`) and a
5
+ * cloud host both decide with this table, so a role means the same thing
6
+ * wherever the page is served. Reads (`GET`) are everyone's; the table is
7
+ * about write calls.
8
+ *
9
+ * Pure: no Node or DOM APIs.
10
+ */
11
+ import type { Role } from './capabilities.js';
12
+ /** Page routes a commenter may write: the comment threads (not sending them to the agent). */
13
+ export declare const COMMENT_WRITES: ReadonlySet<string>;
14
+ /** Page routes that change the artifact. */
15
+ export declare const EDIT_WRITES: ReadonlySet<string>;
16
+ /** Page routes that answer with a POST: everyone's, as reads are (a Sheet's widget refuses a write by role itself). */
17
+ export declare const POSTED_READS: ReadonlySet<string>;
18
+ /** Page routes that act on this computer or reach the agent (or the person's model sources): the owner's alone. */
19
+ export declare const OWNER_WRITES: ReadonlySet<string>;
20
+ /** What a type lets roles do beyond the table above. */
21
+ export interface RoleOptions {
22
+ /**
23
+ * A commenter may write some store documents of their own (the type's `commenterWrites`): the store's write route
24
+ * lets them through, and the store checks each path.
25
+ */
26
+ commenterWrites?: boolean;
27
+ /**
28
+ * An editor may send to the owner's agent ({@link ASK_AGENT_ROUTES}): a hosted artifact whose owner lets editors
29
+ * ask. Never a commenter or a viewer. Off by default, and never set on this computer.
30
+ */
31
+ editorsAskAgent?: boolean;
32
+ }
33
+ /**
34
+ * The owner's routes that send to their agent (or, for a dashboard's live-data refresh, to their linked computer): an
35
+ * editor's too when {@link RoleOptions.editorsAskAgent}.
36
+ */
37
+ export declare const ASK_AGENT_ROUTES: ReadonlySet<string>;
38
+ /** Whether the role may make a write call to a page route (reads are everyone's). */
39
+ export declare function roleMay(role: Role, route: string, options?: RoleOptions): boolean;
40
+ /** Whether a page route is the owner's alone, whatever the other roles are (for the message that refuses it). */
41
+ export declare function isOwnerOnlyRoute(route: string): boolean;
package/src/roles.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What each role may do on an artifact's page routes.
3
+ *
4
+ * The local type server (`@openartifactsai/type-server`'s `sharing.ts`) and a
5
+ * cloud host both decide with this table, so a role means the same thing
6
+ * wherever the page is served. Reads (`GET`) are everyone's; the table is
7
+ * about write calls.
8
+ *
9
+ * Pure: no Node or DOM APIs.
10
+ */
11
+ import { DOC_API } from "./doc-api.js";
12
+ import { API } from "./http-api.js";
13
+ import { SHEET_API } from "./sheet-api.js";
14
+ /** Page routes a commenter may write: the comment threads (not sending them to the agent). */
15
+ export const COMMENT_WRITES = new Set([API.commentsCreate, API.commentsReply, API.commentsEdit, API.commentsReact, API.commentsResolve, API.commentsMove]);
16
+ /** Page routes that change the artifact. */
17
+ export const EDIT_WRITES = new Set([API.publish, API.assets, API.dbWrite, API.commentsRemove, API.roomEmit, API.historyRestore, API.historyDismiss, API.historyNote, DOC_API.restore, DOC_API.importFile, SHEET_API.send]);
18
+ /** Page routes that answer with a POST: everyone's, as reads are (a Sheet's widget refuses a write by role itself). */
19
+ export const POSTED_READS = new Set([API.dataShared, SHEET_API.read, SHEET_API.widget, DOC_API.session, DOC_API.read, DOC_API.history, DOC_API.version, DOC_API.call]);
20
+ /** Page routes that act on this computer or reach the agent (or the person's model sources): the owner's alone. */
21
+ export const OWNER_WRITES = new Set([API.agentSend, API.commentsSend, API.downloads, API.mcpCall, API.dataRefresh, API.dataShare, SHEET_API.importFile, API.sample, API.sampleTool]);
22
+ /**
23
+ * The owner's routes that send to their agent (or, for a dashboard's live-data refresh, to their linked computer): an
24
+ * editor's too when {@link RoleOptions.editorsAskAgent}.
25
+ */
26
+ export const ASK_AGENT_ROUTES = new Set([API.agentSend, API.commentsSend, API.dataRefresh]);
27
+ /** Whether the role may make a write call to a page route (reads are everyone's). */
28
+ export function roleMay(role, route, options = {}) {
29
+ if (role === 'owner')
30
+ return true;
31
+ if (route === API.presence || POSTED_READS.has(route))
32
+ return true;
33
+ if (OWNER_WRITES.has(route))
34
+ return role === 'editor' && options.editorsAskAgent === true && ASK_AGENT_ROUTES.has(route);
35
+ if (COMMENT_WRITES.has(route))
36
+ return role !== 'viewer';
37
+ if (route === API.dbWrite && role === 'commenter' && options.commenterWrites === true)
38
+ return true;
39
+ if (EDIT_WRITES.has(route))
40
+ return role === 'editor';
41
+ // A route this list does not know: the owner's, to be safe.
42
+ return false;
43
+ }
44
+ /** Whether a page route is the owner's alone, whatever the other roles are (for the message that refuses it). */
45
+ export function isOwnerOnlyRoute(route) {
46
+ return OWNER_WRITES.has(route);
47
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The editor runtime's `sample` capability: a built-in editor asks the person's model for text, as a page does with
3
+ * `openArtifacts.use("sample")`. The function a page gets and the one an editor gets behave alike (the shapes and the
4
+ * checks are `@openartifactsai/protocol/sample`'s): `sample(input, options)`, `sample.json(...)`, `sample.limits()`, and
5
+ * one plain `{code, message, text?}` object for every failure.
6
+ *
7
+ * Underneath, a call travels by a {@link SampleTransport}: straight to the type server (`_api/sample`, an NDJSON
8
+ * stream), or, inside the Shell, through its broker, which runs the same HTTP transport on the page's behalf. The
9
+ * transport resolves each call with its last event (`done` or `error`) instead of rejecting, so a code, and the text a
10
+ * failure keeps, cross the broker unchanged; the events before it (`wait`, `delta`, `tool`) come through `onEvent`.
11
+ *
12
+ * Editors send no images: a call that passes some is refused `images_unavailable`.
13
+ */
14
+ import type { SampleError, SampleErrorCode, SampleFunction, SampleInput, SampleLimits, SampleModelTier, SampleStreamEvent, SampleToolResult, SampleWireOptions } from '@openartifactsai/protocol/sample';
15
+ /** Whether the person's grants already cover this artifact's calls: `granted`, `denied`, or `none` (a call would ask). */
16
+ export type SampleGrantState = 'granted' | 'denied' | 'none';
17
+ /**
18
+ * The `sample` capability of an editor: the page-facing function (see `SampleFunction` in
19
+ * `@openartifactsai/protocol/sample`), plus `state()`, which tells without asking whether a call would open a consent
20
+ * dialog (so an editor asks in the background only once the person allowed it), and `request()`, which asks.
21
+ */
22
+ export interface SampleCapability extends SampleFunction {
23
+ state(): Promise<SampleGrantState>;
24
+ /**
25
+ * Asks the person, without a model call, in the consent dialog a call would open, and resolves what they answered
26
+ * (`none` when they closed it). Only for something the person just did: in a Shell that cannot ask (an older one,
27
+ * or none), the same as {@link state}.
28
+ */
29
+ request(): Promise<SampleGrantState>;
30
+ }
31
+ /** The last event of a call. */
32
+ export type SampleEndEvent = Extract<SampleStreamEvent, {
33
+ t: 'done';
34
+ }> | Extract<SampleStreamEvent, {
35
+ t: 'error';
36
+ }>;
37
+ /** An event of a call before its last one. */
38
+ export type SampleProgressEvent = Exclude<SampleStreamEvent, SampleEndEvent>;
39
+ /**
40
+ * How calls travel. Every method is one the Shell's broker carries (`BROKERED_METHODS.sample`), and `onEvent` the
41
+ * listener it forwards; none of them rejects with a sample failure: `start` resolves with the call's last event.
42
+ */
43
+ export interface SampleTransport {
44
+ /** Starts call `call` (an id the caller made): resolves with its `done` or `error` event, never rejects. */
45
+ start(call: string, input: SampleInput, modelTier: SampleModelTier, options: SampleWireOptions): Promise<SampleEndEvent>;
46
+ /** Hands back one round's results of call `call`: whether they were taken. */
47
+ toolResults(call: string, results: SampleToolResult[]): Promise<boolean>;
48
+ /** Stops call `call` (its `start` then resolves `cancelled`). */
49
+ cancel(call: string): Promise<void>;
50
+ readLimits(): Promise<SampleLimits | {
51
+ error: SampleError;
52
+ }>;
53
+ readState(): Promise<SampleGrantState>;
54
+ /** Every call's events before its last one, with the call they are about. */
55
+ onEvent(listener: (message: {
56
+ call: string;
57
+ event: SampleProgressEvent;
58
+ }) => void): () => void;
59
+ }
60
+ /** The transport methods, by the names the broker carries. */
61
+ export declare const SAMPLE_TRANSPORT_METHODS: readonly ["start", "toolResults", "cancel", "readLimits", "readState"];
62
+ /** The one failure shape: a plain object. */
63
+ export declare function sampleFailure(code: SampleErrorCode, message: string, text?: string): SampleError;
64
+ /** Options of {@link createSampleFunction} (for tests). */
65
+ export interface SampleFunctionOptions {
66
+ /** How long the host may take between two signs of life, ms. Default `SAMPLE_REPLY_BUDGET_MS`. */
67
+ budgetMs?: number;
68
+ /** After a `wait` event (a consent dialog is up, or the call waits its turn), ms. Default `SAMPLE_ACKED_WAIT_MS`. */
69
+ waitMs?: number;
70
+ /** Asks the person without a model call (the Shell's dialog); `null`: it cannot ask. Absent: `request()` is `state()`. */
71
+ ask?: () => Promise<SampleGrantState | null>;
72
+ }
73
+ /** The editor's `sample` capability over `transport`. */
74
+ export declare function createSampleFunction(transport: SampleTransport, settings?: SampleFunctionOptions): SampleCapability;
75
+ /** `sample` with its transport's methods on it (not enumerable), as the Shell's broker calls them. */
76
+ export declare function withTransport(sample: SampleCapability, transport: SampleTransport): SampleCapability;
77
+ /** Options of {@link createHttpSampleTransport}. */
78
+ export interface HttpSampleTransportOptions {
79
+ /** The absolute address of a page route, with its query. */
80
+ url(path: string, query?: Record<string, string>): string;
81
+ /** The page's client id: one view, which a decline holds for. */
82
+ client: string;
83
+ /** The routes (`API.sample` and the others of `http-api.ts`). */
84
+ routes: {
85
+ sample: string;
86
+ sampleTool: string;
87
+ sampleLimits: string;
88
+ sampleState: string;
89
+ };
90
+ }
91
+ /** The transport straight to the type server: `POST _api/sample` streams the call's events. */
92
+ export declare function createHttpSampleTransport(options: HttpSampleTransportOptions): SampleTransport;