@open-artifact/runtime 0.0.0-stage → 0.2.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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +48 -4
- package/src/broker.d.ts +83 -0
- package/src/broker.js +352 -0
- package/src/capabilities.d.ts +629 -0
- package/src/capabilities.js +73 -0
- package/src/client.d.ts +29 -0
- package/src/client.js +64 -0
- package/src/http-api.d.ts +216 -0
- package/src/http-api.js +44 -0
- package/src/index.d.ts +18 -0
- package/src/index.js +18 -0
- package/src/local-provider.d.ts +44 -0
- package/src/local-provider.js +388 -0
- package/src/shell.d.ts +46 -0
- package/src/shell.js +113 -0
- package/src/untrusted.d.ts +24 -0
- package/src/untrusted.js +35 -0
package/src/broker.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of the Shell's capability broker.
|
|
3
|
+
*
|
|
4
|
+
* Inside the Open Artifact Shell, `window.openartifact` does not call its
|
|
5
|
+
* backend itself: every call goes to the Shell by `postMessage`, the Shell
|
|
6
|
+
* runs it and answers, and it lets
|
|
7
|
+
* the Shell see and mediate what a page does: an agent turn needs a click,
|
|
8
|
+
* one event connection serves the page, and a page whose broker was
|
|
9
|
+
* rewired learns which calls may not have run.
|
|
10
|
+
*
|
|
11
|
+
* The messages are `cap_*` in `@open-artifact/protocol`'s `shell.ts`:
|
|
12
|
+
*
|
|
13
|
+
* page → Shell cap_want {cap, protocol, base} once per capability
|
|
14
|
+
* Shell → page cap_grant {cap, ok, gen, config?}
|
|
15
|
+
* page → Shell cap {id, cap, method, args, gen} every call
|
|
16
|
+
* Shell → page cap_r {id, result | error} · cap_ack {id} · cap_ev {cap, event, data} · cap_rewired {gen, caps?}
|
|
17
|
+
*
|
|
18
|
+
* A Shell that does not answer the first `cap_want` (an older daemon, or a
|
|
19
|
+
* page framed by something else under the Shell's frame name) leaves the
|
|
20
|
+
* page on its fallback provider, the local type server.
|
|
21
|
+
*/
|
|
22
|
+
import { CAP_NAME, CAP_PROTOCOL, REWIRED_MESSAGE, } from '@open-artifact/protocol';
|
|
23
|
+
import { ArtifactError, MCP_CALL_TIMEOUT, } from "./capabilities.js";
|
|
24
|
+
import { createLocalProvider } from "./local-provider.js";
|
|
25
|
+
import { shellOrigin } from "./shell.js";
|
|
26
|
+
/**
|
|
27
|
+
* The methods the broker carries, per capability. The Shell runs nothing
|
|
28
|
+
* else: a name outside this table is refused before it reaches a backend.
|
|
29
|
+
* Listener methods (`onChange`, `onStatus`, `onPeers`) are not calls; they
|
|
30
|
+
* listen to `cap_ev`.
|
|
31
|
+
*/
|
|
32
|
+
export const BROKERED_METHODS = {
|
|
33
|
+
artifact: ['title', 'list', 'readText', 'readBytes', 'publish'],
|
|
34
|
+
assets: ['upload'],
|
|
35
|
+
user: ['me'],
|
|
36
|
+
agent: ['send', 'status'],
|
|
37
|
+
room: ['self', 'presence', 'peers', 'emit'],
|
|
38
|
+
downloads: ['save'],
|
|
39
|
+
db: ['get', 'list', 'write'],
|
|
40
|
+
comments: ['list', 'create', 'reply', 'setResolved', 'move', 'remove', 'sendToAgent'],
|
|
41
|
+
history: ['list', 'files', 'read', 'readBytes', 'diff', 'restore', 'dismissNotice'],
|
|
42
|
+
mcp: ['callTool', 'listTools'],
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* The `cap_ev` event each listener method follows, per capability
|
|
46
|
+
* (`room.onPeers` → `peers`). The Shell subscribes to every listener method
|
|
47
|
+
* named here once per granted capability and forwards its events.
|
|
48
|
+
*/
|
|
49
|
+
export const BROKERED_EVENTS = {
|
|
50
|
+
artifact: { onChange: 'files' },
|
|
51
|
+
agent: { onStatus: 'status' },
|
|
52
|
+
room: { onPeers: 'peers', onMessage: 'message' },
|
|
53
|
+
db: { onChange: 'change' },
|
|
54
|
+
comments: { onChange: 'threads' },
|
|
55
|
+
history: { onChange: 'change' },
|
|
56
|
+
};
|
|
57
|
+
const CALL_TIMEOUT = { downloads: 150_000, assets: 272_000, user: 20_000 };
|
|
58
|
+
const DEFAULT_CALL_TIMEOUT = 130_000;
|
|
59
|
+
/** After `cap_ack` (a consent prompt, a queue): the long deadline. */
|
|
60
|
+
const ACKED_TIMEOUT = 900_000;
|
|
61
|
+
/** Capabilities whose calls resolve `null` instead of rejecting when cut or timed out. */
|
|
62
|
+
const RESOLVES_NULL = new Set(['user']);
|
|
63
|
+
/** Rebuilds the error a Shell sent. */
|
|
64
|
+
function toArtifactError(error) {
|
|
65
|
+
const code = (error?.code ?? 'unavailable');
|
|
66
|
+
const retryable = error?.retryable === true;
|
|
67
|
+
return new ArtifactError(code, error?.message ?? 'The Shell refused the call.', error?.paths, retryable);
|
|
68
|
+
}
|
|
69
|
+
/** A per-load prefix plus a counter, like the frame runtime's call ids. */
|
|
70
|
+
function idMaker() {
|
|
71
|
+
const prefix = Math.random().toString(36).slice(2, 10);
|
|
72
|
+
let seq = 0;
|
|
73
|
+
return () => `${prefix}${(++seq).toString(36)}`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A provider that brokers every capability through the Shell, falling back
|
|
77
|
+
* to `options.fallback` when the Shell never grants.
|
|
78
|
+
*/
|
|
79
|
+
export function createShellProvider(options = {}) {
|
|
80
|
+
const origin = options.origin ?? shellOrigin();
|
|
81
|
+
const fallback = options.fallback ?? createLocalProvider();
|
|
82
|
+
if (!origin || typeof window === 'undefined')
|
|
83
|
+
return fallback;
|
|
84
|
+
const target = options.target ?? window.parent;
|
|
85
|
+
const base = new URL(options.base ?? './', location.href).toString();
|
|
86
|
+
const wantTimeoutMs = options.wantTimeoutMs ?? 1500;
|
|
87
|
+
const nextId = idMaker();
|
|
88
|
+
/** `true` once a grant arrived, `false` once the first want timed out. */
|
|
89
|
+
let brokered = null;
|
|
90
|
+
let gen = 0;
|
|
91
|
+
const pending = new Map();
|
|
92
|
+
const grants = new Map();
|
|
93
|
+
const listeners = new Map();
|
|
94
|
+
const post = (message, gesture = false) => {
|
|
95
|
+
// `includeUserActivation` lets the Shell see a click behind the call
|
|
96
|
+
// (Chromium); other browsers ignore the option.
|
|
97
|
+
target.postMessage(message, gesture ? { targetOrigin: origin, includeUserActivation: true } : { targetOrigin: origin });
|
|
98
|
+
};
|
|
99
|
+
/** Ends a call that will get no answer. */
|
|
100
|
+
const cut = (id, entry, message) => {
|
|
101
|
+
pending.delete(id);
|
|
102
|
+
if (entry.timer)
|
|
103
|
+
clearTimeout(entry.timer);
|
|
104
|
+
if (RESOLVES_NULL.has(entry.cap))
|
|
105
|
+
entry.resolve(null);
|
|
106
|
+
else
|
|
107
|
+
entry.reject(new ArtifactError('unavailable', message));
|
|
108
|
+
};
|
|
109
|
+
const armTimer = (id, entry, ms) => {
|
|
110
|
+
if (entry.timer)
|
|
111
|
+
clearTimeout(entry.timer);
|
|
112
|
+
entry.timer = setTimeout(() => {
|
|
113
|
+
if (pending.get(id) === entry)
|
|
114
|
+
cut(id, entry, 'The Shell did not answer in time.');
|
|
115
|
+
}, ms);
|
|
116
|
+
};
|
|
117
|
+
const onMessage = (event) => {
|
|
118
|
+
if (event.source !== target || event.origin !== origin)
|
|
119
|
+
return;
|
|
120
|
+
const data = event.data;
|
|
121
|
+
if (!data || typeof data !== 'object' || typeof data.openArtifact !== 'string' || !data.openArtifact.startsWith('cap_'))
|
|
122
|
+
return;
|
|
123
|
+
switch (data.openArtifact) {
|
|
124
|
+
case 'cap_grant': {
|
|
125
|
+
brokered = true;
|
|
126
|
+
if (typeof data.gen === 'number' && Number.isInteger(data.gen) && data.gen >= 0)
|
|
127
|
+
gen = data.gen;
|
|
128
|
+
const waiting = grants.get(data.cap);
|
|
129
|
+
grants.delete(data.cap);
|
|
130
|
+
for (const done of waiting ?? [])
|
|
131
|
+
done(data);
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
case 'cap_r': {
|
|
135
|
+
const entry = pending.get(data.id);
|
|
136
|
+
if (!entry)
|
|
137
|
+
return;
|
|
138
|
+
pending.delete(data.id);
|
|
139
|
+
if (entry.timer)
|
|
140
|
+
clearTimeout(entry.timer);
|
|
141
|
+
if (data.error)
|
|
142
|
+
entry.reject(toArtifactError(data.error));
|
|
143
|
+
else
|
|
144
|
+
entry.resolve(data.result);
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
case 'cap_ack': {
|
|
148
|
+
// Consent or slow work: the call gets the long deadline.
|
|
149
|
+
const entry = pending.get(data.id);
|
|
150
|
+
if (entry)
|
|
151
|
+
armTimer(data.id, entry, ACKED_TIMEOUT);
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
case 'cap_ev':
|
|
155
|
+
for (const listener of listeners.get(`${data.cap}:${data.event}`) ?? []) {
|
|
156
|
+
try {
|
|
157
|
+
listener(data.data);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
queueMicrotask(() => {
|
|
161
|
+
throw error;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
break;
|
|
166
|
+
case 'cap_rewired': {
|
|
167
|
+
// As the frame runtime's modules do: a new generation cuts every call sent
|
|
168
|
+
// under another one, and `caps` (when given) lists what the broker
|
|
169
|
+
// still serves, so calls to anything else are cut too.
|
|
170
|
+
if (typeof data.gen !== 'number' || !Number.isInteger(data.gen) || data.gen < 0)
|
|
171
|
+
return;
|
|
172
|
+
const caps = Array.isArray(data.caps) ? new Set(data.caps) : null;
|
|
173
|
+
for (const [id, entry] of [...pending]) {
|
|
174
|
+
if (entry.gen !== data.gen || (caps && !caps.has(entry.cap)))
|
|
175
|
+
cut(id, entry, REWIRED_MESSAGE);
|
|
176
|
+
}
|
|
177
|
+
gen = data.gen;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
default:
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
window.addEventListener('message', onMessage);
|
|
185
|
+
const want = (cap) => new Promise((resolve) => {
|
|
186
|
+
const list = grants.get(cap) ?? [];
|
|
187
|
+
list.push(resolve);
|
|
188
|
+
grants.set(cap, list);
|
|
189
|
+
post({ openArtifact: 'cap_want', cap, protocol: CAP_PROTOCOL, base });
|
|
190
|
+
setTimeout(() => {
|
|
191
|
+
const waiting = grants.get(cap);
|
|
192
|
+
if (!waiting?.includes(resolve))
|
|
193
|
+
return;
|
|
194
|
+
waiting.splice(waiting.indexOf(resolve), 1);
|
|
195
|
+
if (brokered === null)
|
|
196
|
+
brokered = false;
|
|
197
|
+
resolve(null);
|
|
198
|
+
}, wantTimeoutMs);
|
|
199
|
+
});
|
|
200
|
+
const call = (cap, method, args, gesture = false, timeoutMs, signal) => new Promise((resolve, reject) => {
|
|
201
|
+
const id = nextId();
|
|
202
|
+
const entry = { cap, gen, resolve, reject, timer: null };
|
|
203
|
+
pending.set(id, entry);
|
|
204
|
+
armTimer(id, entry, timeoutMs ?? CALL_TIMEOUT[cap] ?? DEFAULT_CALL_TIMEOUT);
|
|
205
|
+
if (signal) {
|
|
206
|
+
// A signal cannot cross postMessage: the call is dropped here and its answer ignored.
|
|
207
|
+
const abort = () => {
|
|
208
|
+
if (pending.get(id) !== entry)
|
|
209
|
+
return;
|
|
210
|
+
pending.delete(id);
|
|
211
|
+
if (entry.timer)
|
|
212
|
+
clearTimeout(entry.timer);
|
|
213
|
+
reject(signal.reason);
|
|
214
|
+
};
|
|
215
|
+
if (signal.aborted)
|
|
216
|
+
return abort();
|
|
217
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
218
|
+
}
|
|
219
|
+
post({ openArtifact: 'cap', id, cap, method, args, gen }, gesture);
|
|
220
|
+
});
|
|
221
|
+
const listen = (cap, event, listener) => {
|
|
222
|
+
const key = `${cap}:${event}`;
|
|
223
|
+
const set = listeners.get(key) ?? new Set();
|
|
224
|
+
set.add(listener);
|
|
225
|
+
listeners.set(key, set);
|
|
226
|
+
return () => void set.delete(listener);
|
|
227
|
+
};
|
|
228
|
+
/** Builds the page's namespace for a granted capability. */
|
|
229
|
+
const build = (cap, config) => {
|
|
230
|
+
const c = (method, args = [], gesture = false) => call(cap, method, args, gesture);
|
|
231
|
+
switch (cap) {
|
|
232
|
+
case 'artifact': {
|
|
233
|
+
const ns = {
|
|
234
|
+
id: String(config.id ?? ''),
|
|
235
|
+
title: () => c('title'),
|
|
236
|
+
list: () => c('list'),
|
|
237
|
+
readText: (path) => c('readText', [path]),
|
|
238
|
+
readBytes: (path) => c('readBytes', [path]),
|
|
239
|
+
publish: (batch) => c('publish', [batch]),
|
|
240
|
+
onChange: (listener) => listen('artifact', BROKERED_EVENTS.artifact.onChange, listener),
|
|
241
|
+
};
|
|
242
|
+
return ns;
|
|
243
|
+
}
|
|
244
|
+
case 'assets': {
|
|
245
|
+
const ns = { upload: (data, opts) => c('upload', opts ? [data, opts] : [data]) };
|
|
246
|
+
return ns;
|
|
247
|
+
}
|
|
248
|
+
case 'user': {
|
|
249
|
+
// Answered from the grant, like the frame runtime's `user.config`.
|
|
250
|
+
const viewer = config.me;
|
|
251
|
+
const ns = { me: () => (viewer ? Promise.resolve({ ...viewer }) : c('me')) };
|
|
252
|
+
return ns;
|
|
253
|
+
}
|
|
254
|
+
case 'agent': {
|
|
255
|
+
const ns = {
|
|
256
|
+
send: (request, opts) => c('send', opts ? [request, opts] : [request], true),
|
|
257
|
+
status: () => c('status'),
|
|
258
|
+
onStatus: (listener) => listen('agent', BROKERED_EVENTS.agent.onStatus, listener),
|
|
259
|
+
};
|
|
260
|
+
return ns;
|
|
261
|
+
}
|
|
262
|
+
case 'room': {
|
|
263
|
+
let self = null;
|
|
264
|
+
const ns = {
|
|
265
|
+
self: () => (self ??= c('self')),
|
|
266
|
+
presence: (patch) => c('presence', [patch]),
|
|
267
|
+
peers: () => c('peers'),
|
|
268
|
+
onPeers: (listener) => listen('room', BROKERED_EVENTS.room.onPeers, listener),
|
|
269
|
+
emit: (topic, data) => c('emit', [topic, data]),
|
|
270
|
+
onMessage: (listener) => listen('room', BROKERED_EVENTS.room.onMessage, listener),
|
|
271
|
+
};
|
|
272
|
+
return ns;
|
|
273
|
+
}
|
|
274
|
+
case 'db': {
|
|
275
|
+
const ns = {
|
|
276
|
+
get: (path) => c('get', [path]),
|
|
277
|
+
list: (collection) => c('list', [collection]),
|
|
278
|
+
write: (writes) => c('write', [writes]),
|
|
279
|
+
onChange: (listener) => listen('db', BROKERED_EVENTS.db.onChange, listener),
|
|
280
|
+
};
|
|
281
|
+
return ns;
|
|
282
|
+
}
|
|
283
|
+
case 'comments': {
|
|
284
|
+
const ns = {
|
|
285
|
+
list: () => c('list'),
|
|
286
|
+
create: (input) => c('create', [input]),
|
|
287
|
+
reply: (threadId, text) => c('reply', [threadId, text]),
|
|
288
|
+
setResolved: (threadId, resolved) => c('setResolved', [threadId, resolved]),
|
|
289
|
+
move: (threadId, anchor, location) => c('move', location ? [threadId, anchor, location] : [threadId, anchor]),
|
|
290
|
+
remove: (threadId, messageId) => c('remove', messageId ? [threadId, messageId] : [threadId]),
|
|
291
|
+
sendToAgent: (threadId) => c('sendToAgent', [threadId], true),
|
|
292
|
+
onChange: (listener) => listen('comments', BROKERED_EVENTS.comments.onChange, listener),
|
|
293
|
+
};
|
|
294
|
+
return ns;
|
|
295
|
+
}
|
|
296
|
+
case 'history': {
|
|
297
|
+
const ns = {
|
|
298
|
+
list: () => c('list'),
|
|
299
|
+
files: (n) => c('files', [n]),
|
|
300
|
+
read: (n, path) => c('read', [n, path]),
|
|
301
|
+
readBytes: (n, path) => c('readBytes', [n, path]),
|
|
302
|
+
diff: (n, path) => c('diff', [n, path]),
|
|
303
|
+
restore: (n, paths) => c('restore', paths ? [n, paths] : [n]),
|
|
304
|
+
dismissNotice: (id) => c('dismissNotice', [id]),
|
|
305
|
+
onChange: (listener) => listen('history', BROKERED_EVENTS.history.onChange, listener),
|
|
306
|
+
};
|
|
307
|
+
return ns;
|
|
308
|
+
}
|
|
309
|
+
case 'downloads': {
|
|
310
|
+
const ns = { save: (file) => c('save', [file], true) };
|
|
311
|
+
return ns;
|
|
312
|
+
}
|
|
313
|
+
case 'mcp': {
|
|
314
|
+
const ns = {
|
|
315
|
+
callTool: (server, tool, args, opts) => {
|
|
316
|
+
const timeoutMs = opts?.timeoutMs;
|
|
317
|
+
const wire = timeoutMs === undefined ? [server, tool, args] : [server, tool, args, { timeoutMs }];
|
|
318
|
+
// The page waits a little longer than the host does, so the host's own timeout error arrives.
|
|
319
|
+
const budget = Math.min(timeoutMs ?? MCP_CALL_TIMEOUT.defaultMs, MCP_CALL_TIMEOUT.maxMs) + 15_000;
|
|
320
|
+
return call('mcp', 'callTool', wire, false, budget, opts?.signal);
|
|
321
|
+
},
|
|
322
|
+
listTools: (server) => c('listTools', server === undefined ? [] : [server]),
|
|
323
|
+
};
|
|
324
|
+
return ns;
|
|
325
|
+
}
|
|
326
|
+
default:
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
return {
|
|
331
|
+
async get(name) {
|
|
332
|
+
if (!CAP_NAME.test(name) || !(name in BROKERED_METHODS))
|
|
333
|
+
return null;
|
|
334
|
+
if (brokered === false)
|
|
335
|
+
return fallback.get(name);
|
|
336
|
+
const grant = await want(name);
|
|
337
|
+
if (!grant)
|
|
338
|
+
return brokered ? null : fallback.get(name);
|
|
339
|
+
if (!grant.ok)
|
|
340
|
+
return null;
|
|
341
|
+
return build(name, grant.config ?? {});
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The provider a page should use: brokered through the Shell when it is in
|
|
347
|
+
* one, otherwise the local type server.
|
|
348
|
+
*/
|
|
349
|
+
export function createPageProvider(options = {}) {
|
|
350
|
+
const fallback = createLocalProvider(options);
|
|
351
|
+
return shellOrigin() ? createShellProvider({ ...options, fallback }) : fallback;
|
|
352
|
+
}
|