@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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +64 -4
- package/src/broker.d.ts +93 -0
- package/src/broker.js +442 -0
- package/src/capabilities.d.ts +915 -0
- package/src/capabilities.js +77 -0
- package/src/client.d.ts +33 -0
- package/src/client.js +76 -0
- package/src/doc-api.d.ts +280 -0
- package/src/doc-api.js +35 -0
- package/src/http-api.d.ts +373 -0
- package/src/http-api.js +72 -0
- package/src/index.d.ts +24 -0
- package/src/index.js +24 -0
- package/src/legacy-storage.d.ts +1 -0
- package/src/legacy-storage.js +7 -0
- package/src/local-provider.d.ts +44 -0
- package/src/local-provider.js +491 -0
- package/src/roles.d.ts +41 -0
- package/src/roles.js +47 -0
- package/src/sample.d.ts +92 -0
- package/src/sample.js +570 -0
- package/src/sheet-api.d.ts +426 -0
- package/src/sheet-api.js +35 -0
- package/src/shell.d.ts +73 -0
- package/src/shell.js +197 -0
- package/src/untrusted.d.ts +24 -0
- package/src/untrusted.js +35 -0
package/src/broker.js
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of the Shell's capability broker.
|
|
3
|
+
*
|
|
4
|
+
* Inside the Open Artifacts Shell, `window.openartifacts` 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 `@openartifactsai/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, adoptLegacyEnvelope, withLegacyEnvelope, } from '@openartifactsai/protocol';
|
|
23
|
+
import { ArtifactError, MCP_CALL_TIMEOUT, validByteLimit, } from "./capabilities.js";
|
|
24
|
+
import { createLocalProvider } from "./local-provider.js";
|
|
25
|
+
import { SAMPLE_TRANSPORT_METHODS, createSampleFunction } from "./sample.js";
|
|
26
|
+
import { PendingCalls } from '@openartifactsai/protocol/pending';
|
|
27
|
+
import { SAMPLE_ACKED_WAIT_MS } from '@openartifactsai/protocol/sample';
|
|
28
|
+
import { shellOrigin } from "./shell.js";
|
|
29
|
+
/**
|
|
30
|
+
* The methods the broker carries, per capability. The Shell runs nothing
|
|
31
|
+
* else: a name outside this table is refused before it reaches a backend.
|
|
32
|
+
* Listener methods (`onChange`, `onStatus`, `onPeers`) are not calls; they
|
|
33
|
+
* listen to `cap_ev`.
|
|
34
|
+
*/
|
|
35
|
+
export const BROKERED_METHODS = {
|
|
36
|
+
artifact: ['title', 'list', 'readText', 'readBytes', 'publish'],
|
|
37
|
+
assets: ['upload'],
|
|
38
|
+
user: ['me'],
|
|
39
|
+
agent: ['send', 'status'],
|
|
40
|
+
room: ['self', 'presence', 'peers', 'participants', 'emit'],
|
|
41
|
+
downloads: ['save', 'check'],
|
|
42
|
+
db: ['get', 'list', 'listing', 'write'],
|
|
43
|
+
comments: ['list', 'create', 'reply', 'edit', 'react', 'setResolved', 'move', 'remove', 'sendToAgent'],
|
|
44
|
+
history: ['list', 'files', 'read', 'readBytes', 'diff', 'restore', 'dismissNotice', 'note'],
|
|
45
|
+
doc: ['session', 'read', 'call', 'history', 'version', 'restore', 'importFile', 'exportFile'],
|
|
46
|
+
mcp: ['callTool', 'listTools'],
|
|
47
|
+
sheet: ['read', 'send', 'widget', 'importFile'],
|
|
48
|
+
// The transport under the page's `sample` function (sample.ts): the function itself runs in the page.
|
|
49
|
+
sample: SAMPLE_TRANSPORT_METHODS,
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* The `cap_ev` event each listener method follows, per capability
|
|
53
|
+
* (`room.onPeers` → `peers`). The Shell subscribes to every listener method
|
|
54
|
+
* named here once per granted capability and forwards its events.
|
|
55
|
+
*/
|
|
56
|
+
export const BROKERED_EVENTS = {
|
|
57
|
+
artifact: { onChange: 'files' },
|
|
58
|
+
agent: { onStatus: 'status' },
|
|
59
|
+
room: { onPeers: 'peers', onMessage: 'message' },
|
|
60
|
+
db: { onChange: 'change' },
|
|
61
|
+
comments: { onChange: 'threads' },
|
|
62
|
+
history: { onChange: 'change' },
|
|
63
|
+
sheet: { onFrame: 'frame', onWalkthrough: 'walkthrough' },
|
|
64
|
+
doc: { onFrame: 'frame' },
|
|
65
|
+
sample: { onEvent: 'event' },
|
|
66
|
+
};
|
|
67
|
+
const CALL_TIMEOUT = { downloads: 150_000, assets: 272_000, user: 20_000 };
|
|
68
|
+
const DEFAULT_CALL_TIMEOUT = 130_000;
|
|
69
|
+
/** After `cap_ack` (a consent prompt, a queue): the long deadline. */
|
|
70
|
+
const ACKED_TIMEOUT = 900_000;
|
|
71
|
+
/** How long `sample.request()` waits for the person to answer the Shell's dialog before it reads the state instead. */
|
|
72
|
+
const SAMPLE_REQUEST_TIMEOUT = 900_000;
|
|
73
|
+
/** Capabilities whose calls resolve `null` instead of rejecting when cut or timed out. */
|
|
74
|
+
const RESOLVES_NULL = new Set(['user']);
|
|
75
|
+
/** Rebuilds the error a Shell sent. */
|
|
76
|
+
function toArtifactError(error) {
|
|
77
|
+
const code = (error?.code ?? 'unavailable');
|
|
78
|
+
const retryable = error?.retryable === true;
|
|
79
|
+
return new ArtifactError(code, error?.message ?? 'The Shell refused the call.', error?.paths, retryable);
|
|
80
|
+
}
|
|
81
|
+
/** A per-load prefix plus a counter, like the frame runtime's call ids. */
|
|
82
|
+
function idMaker() {
|
|
83
|
+
const prefix = Math.random().toString(36).slice(2, 10);
|
|
84
|
+
let seq = 0;
|
|
85
|
+
return () => `${prefix}${(++seq).toString(36)}`;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* A provider that brokers every capability through the Shell, falling back
|
|
89
|
+
* to `options.fallback` when the Shell never grants.
|
|
90
|
+
*/
|
|
91
|
+
export function createShellProvider(options = {}) {
|
|
92
|
+
const origin = options.origin ?? shellOrigin();
|
|
93
|
+
const fallback = options.fallback ?? createLocalProvider();
|
|
94
|
+
if (!origin || typeof window === 'undefined')
|
|
95
|
+
return fallback;
|
|
96
|
+
const target = options.target ?? window.parent;
|
|
97
|
+
const base = new URL(options.base ?? './', location.href).toString();
|
|
98
|
+
const wantTimeoutMs = options.wantTimeoutMs ?? 1500;
|
|
99
|
+
const nextId = idMaker();
|
|
100
|
+
/** `true` once a grant arrived, `false` once the first want timed out. */
|
|
101
|
+
let brokered = null;
|
|
102
|
+
let gen = 0;
|
|
103
|
+
const pending = new PendingCalls();
|
|
104
|
+
const grants = new Map();
|
|
105
|
+
const listeners = new Map();
|
|
106
|
+
const post = (message, gesture = false) => {
|
|
107
|
+
// `includeUserActivation` lets the Shell see a click behind the call
|
|
108
|
+
// (Chromium); other browsers ignore the option.
|
|
109
|
+
// Both envelope keys: a Shell from before the rename reads `openArtifact`.
|
|
110
|
+
target.postMessage(withLegacyEnvelope(message), gesture ? { targetOrigin: origin, includeUserActivation: true } : { targetOrigin: origin });
|
|
111
|
+
};
|
|
112
|
+
/** Ends a call that will get no answer. */
|
|
113
|
+
const cut = (id, cap, message) => {
|
|
114
|
+
if (RESOLVES_NULL.has(cap))
|
|
115
|
+
pending.resolve(id, null);
|
|
116
|
+
else
|
|
117
|
+
pending.reject(id, new ArtifactError('unavailable', message));
|
|
118
|
+
};
|
|
119
|
+
/** `sample.request()` asks waiting on the Shell's `sample_permission_r`, by id. */
|
|
120
|
+
const permissionAsks = new Map();
|
|
121
|
+
/**
|
|
122
|
+
* The person is asked with the consent dialog a call would open, without a model call: the Shell's
|
|
123
|
+
* `sample_permission` (`op: 'request'`), as a page's `permissions.request("sample")` is. `null`: it cannot ask.
|
|
124
|
+
*/
|
|
125
|
+
const askSamplePermission = () => new Promise((resolve) => {
|
|
126
|
+
const id = nextId();
|
|
127
|
+
const timer = setTimeout(() => done(null), SAMPLE_REQUEST_TIMEOUT);
|
|
128
|
+
const done = (state) => {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
permissionAsks.delete(id);
|
|
131
|
+
resolve(state === 'granted' || state === 'denied' ? state : state === 'prompt' ? 'none' : null);
|
|
132
|
+
};
|
|
133
|
+
permissionAsks.set(id, done);
|
|
134
|
+
const message = { openArtifacts: 'sample_permission', id, op: 'request' };
|
|
135
|
+
target.postMessage(withLegacyEnvelope(message), { targetOrigin: origin, includeUserActivation: true });
|
|
136
|
+
});
|
|
137
|
+
const onMessage = (event) => {
|
|
138
|
+
if (event.source !== target || event.origin !== origin)
|
|
139
|
+
return;
|
|
140
|
+
const data = adoptLegacyEnvelope(event.data);
|
|
141
|
+
const answer = data;
|
|
142
|
+
if (answer?.openArtifacts === 'sample_permission_r' && typeof answer.id === 'string') {
|
|
143
|
+
const state = answer.state;
|
|
144
|
+
permissionAsks.get(answer.id)?.(state === 'granted' || state === 'prompt' || state === 'denied' ? state : null);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!data || typeof data !== 'object' || typeof data.openArtifacts !== 'string' || !data.openArtifacts.startsWith('cap_'))
|
|
148
|
+
return;
|
|
149
|
+
switch (data.openArtifacts) {
|
|
150
|
+
case 'cap_grant': {
|
|
151
|
+
brokered = true;
|
|
152
|
+
if (typeof data.gen === 'number' && Number.isInteger(data.gen) && data.gen >= 0)
|
|
153
|
+
gen = data.gen;
|
|
154
|
+
const waiting = grants.get(data.cap);
|
|
155
|
+
grants.delete(data.cap);
|
|
156
|
+
for (const done of waiting ?? [])
|
|
157
|
+
done(data);
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
case 'cap_r': {
|
|
161
|
+
if (!pending.has(data.id))
|
|
162
|
+
return;
|
|
163
|
+
if (data.error)
|
|
164
|
+
pending.reject(data.id, toArtifactError(data.error));
|
|
165
|
+
else
|
|
166
|
+
pending.resolve(data.id, data.result);
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case 'cap_ack': {
|
|
170
|
+
// Consent or slow work: the call gets the long deadline.
|
|
171
|
+
pending.extend(data.id, ACKED_TIMEOUT);
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
case 'cap_ev':
|
|
175
|
+
for (const listener of listeners.get(`${data.cap}:${data.event}`) ?? []) {
|
|
176
|
+
try {
|
|
177
|
+
listener(data.data);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
queueMicrotask(() => {
|
|
181
|
+
throw error;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
break;
|
|
186
|
+
case 'cap_rewired': {
|
|
187
|
+
// As the frame runtime's modules do: a new generation cuts every call sent
|
|
188
|
+
// under another one, and `caps` (when given) lists what the broker
|
|
189
|
+
// still serves, so calls to anything else are cut too.
|
|
190
|
+
if (typeof data.gen !== 'number' || !Number.isInteger(data.gen) || data.gen < 0)
|
|
191
|
+
return;
|
|
192
|
+
const caps = Array.isArray(data.caps) ? new Set(data.caps) : null;
|
|
193
|
+
for (const [id, meta] of pending.entries()) {
|
|
194
|
+
if (meta && (meta.gen !== data.gen || (caps && !caps.has(meta.cap))))
|
|
195
|
+
cut(id, meta.cap, REWIRED_MESSAGE);
|
|
196
|
+
}
|
|
197
|
+
gen = data.gen;
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
default:
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
window.addEventListener('message', onMessage);
|
|
205
|
+
const want = (cap) => new Promise((resolve) => {
|
|
206
|
+
const timer = setTimeout(() => {
|
|
207
|
+
const waiting = grants.get(cap);
|
|
208
|
+
if (!waiting?.includes(done))
|
|
209
|
+
return;
|
|
210
|
+
waiting.splice(waiting.indexOf(done), 1);
|
|
211
|
+
if (!waiting.length)
|
|
212
|
+
grants.delete(cap);
|
|
213
|
+
if (brokered === null)
|
|
214
|
+
brokered = false;
|
|
215
|
+
resolve(null);
|
|
216
|
+
}, wantTimeoutMs);
|
|
217
|
+
const done = (grant) => {
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
resolve(grant);
|
|
220
|
+
};
|
|
221
|
+
const list = grants.get(cap) ?? [];
|
|
222
|
+
list.push(done);
|
|
223
|
+
grants.set(cap, list);
|
|
224
|
+
post({ openArtifacts: 'cap_want', cap, protocol: CAP_PROTOCOL, base });
|
|
225
|
+
});
|
|
226
|
+
const call = (cap, method, args, gesture = false, timeoutMs, signal) => {
|
|
227
|
+
const id = nextId();
|
|
228
|
+
const deadline = timeoutMs ?? CALL_TIMEOUT[cap] ?? DEFAULT_CALL_TIMEOUT;
|
|
229
|
+
const answer = pending.wait(id, {
|
|
230
|
+
meta: { cap, gen },
|
|
231
|
+
// A deadline that is not a positive, finite number cuts the call at once, as a timer of that length would.
|
|
232
|
+
timeoutMs: deadline > 0 && Number.isFinite(deadline) ? deadline : 1,
|
|
233
|
+
onTimeout: () => cut(id, cap, 'The Shell did not answer in time.'),
|
|
234
|
+
// A signal cannot cross postMessage: the call is dropped here and its answer ignored.
|
|
235
|
+
...(signal ? { signal } : {}),
|
|
236
|
+
});
|
|
237
|
+
// A call aborted already is not sent.
|
|
238
|
+
if (!pending.has(id))
|
|
239
|
+
return answer;
|
|
240
|
+
try {
|
|
241
|
+
post({ openArtifacts: 'cap', id, cap, method, args, gen }, gesture);
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
// Arguments the structured clone refuses: the call fails with that error.
|
|
245
|
+
pending.reject(id, error);
|
|
246
|
+
}
|
|
247
|
+
return answer;
|
|
248
|
+
};
|
|
249
|
+
const listen = (cap, event, listener) => {
|
|
250
|
+
const key = `${cap}:${event}`;
|
|
251
|
+
const set = listeners.get(key) ?? new Set();
|
|
252
|
+
set.add(listener);
|
|
253
|
+
listeners.set(key, set);
|
|
254
|
+
return () => void set.delete(listener);
|
|
255
|
+
};
|
|
256
|
+
/** Builds the page's namespace for a granted capability. */
|
|
257
|
+
const build = (cap, config) => {
|
|
258
|
+
const c = (method, args = [], gesture = false) => call(cap, method, args, gesture);
|
|
259
|
+
switch (cap) {
|
|
260
|
+
case 'artifact': {
|
|
261
|
+
const ns = {
|
|
262
|
+
id: String(config.id ?? ''),
|
|
263
|
+
title: () => c('title'),
|
|
264
|
+
list: () => c('list'),
|
|
265
|
+
readText: (path) => c('readText', [path]),
|
|
266
|
+
readBytes: (path) => c('readBytes', [path]),
|
|
267
|
+
publish: (batch) => c('publish', [batch]),
|
|
268
|
+
onChange: (listener) => listen('artifact', BROKERED_EVENTS.artifact.onChange, listener),
|
|
269
|
+
};
|
|
270
|
+
return ns;
|
|
271
|
+
}
|
|
272
|
+
case 'assets': {
|
|
273
|
+
const ns = { upload: (data, opts) => c('upload', opts ? [data, opts] : [data]), ...(validByteLimit(config.maxBytes) ? { maxBytes: config.maxBytes } : {}) };
|
|
274
|
+
return ns;
|
|
275
|
+
}
|
|
276
|
+
case 'user': {
|
|
277
|
+
// Answered from the grant, like the frame runtime's `user.config`.
|
|
278
|
+
const viewer = config.me;
|
|
279
|
+
const ns = { me: () => (viewer ? Promise.resolve({ ...viewer }) : c('me')) };
|
|
280
|
+
return ns;
|
|
281
|
+
}
|
|
282
|
+
case 'agent': {
|
|
283
|
+
const ns = {
|
|
284
|
+
send: (request, opts) => c('send', opts ? [request, opts] : [request], true),
|
|
285
|
+
status: () => c('status'),
|
|
286
|
+
onStatus: (listener) => listen('agent', BROKERED_EVENTS.agent.onStatus, listener),
|
|
287
|
+
};
|
|
288
|
+
return ns;
|
|
289
|
+
}
|
|
290
|
+
case 'room': {
|
|
291
|
+
let self = null;
|
|
292
|
+
const ns = {
|
|
293
|
+
self: () => {
|
|
294
|
+
if (!self) {
|
|
295
|
+
const request = c('self');
|
|
296
|
+
self = request;
|
|
297
|
+
void request.catch(() => {
|
|
298
|
+
if (self === request)
|
|
299
|
+
self = null;
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
return self;
|
|
303
|
+
},
|
|
304
|
+
presence: (patch) => c('presence', [patch]),
|
|
305
|
+
peers: () => c('peers'),
|
|
306
|
+
participants: () => c('participants'),
|
|
307
|
+
onPeers: (listener) => listen('room', BROKERED_EVENTS.room.onPeers, listener),
|
|
308
|
+
emit: (topic, data) => c('emit', [topic, data]),
|
|
309
|
+
onMessage: (listener) => listen('room', BROKERED_EVENTS.room.onMessage, listener),
|
|
310
|
+
};
|
|
311
|
+
return ns;
|
|
312
|
+
}
|
|
313
|
+
case 'db': {
|
|
314
|
+
const ns = {
|
|
315
|
+
get: (path) => c('get', [path]),
|
|
316
|
+
list: (collection) => c('list', [collection]),
|
|
317
|
+
listing: (collection) => c('listing', [collection]),
|
|
318
|
+
write: (writes) => c('write', [writes]),
|
|
319
|
+
onChange: (listener) => listen('db', BROKERED_EVENTS.db.onChange, listener),
|
|
320
|
+
};
|
|
321
|
+
return ns;
|
|
322
|
+
}
|
|
323
|
+
case 'comments': {
|
|
324
|
+
const ns = {
|
|
325
|
+
list: () => c('list'),
|
|
326
|
+
create: (input) => c('create', [input]),
|
|
327
|
+
reply: (threadId, text, options) => c('reply', options ? [threadId, text, options] : [threadId, text]),
|
|
328
|
+
edit: (threadId, messageId, text, options) => c('edit', options ? [threadId, messageId, text, options] : [threadId, messageId, text]),
|
|
329
|
+
react: (threadId, messageId, emoji, on) => c('react', [threadId, messageId, emoji, on]),
|
|
330
|
+
setResolved: (threadId, resolved) => c('setResolved', [threadId, resolved]),
|
|
331
|
+
move: (threadId, anchor, location, options) => c('move', options?.from !== undefined ? [threadId, anchor, location, { from: options.from }] : location ? [threadId, anchor, location] : [threadId, anchor]),
|
|
332
|
+
remove: (threadId, messageId) => c('remove', messageId ? [threadId, messageId] : [threadId]),
|
|
333
|
+
// A host hears only threads people send: one the page would send unasked is not handed over there. The
|
|
334
|
+
// person's words and selection go along (the type server checks the words against the thread).
|
|
335
|
+
sendToAgent: (threadId, options) => {
|
|
336
|
+
if (options?.unasked)
|
|
337
|
+
return Promise.reject(new Error('This host takes only threads that ask the agent.'));
|
|
338
|
+
const parts = { ...(options?.userText ? { userText: options.userText } : {}), ...(options?.selectionSnapshot ? { selectionSnapshot: options.selectionSnapshot } : {}) };
|
|
339
|
+
return c('sendToAgent', Object.keys(parts).length ? [threadId, parts] : [threadId], true);
|
|
340
|
+
},
|
|
341
|
+
onChange: (listener) => listen('comments', BROKERED_EVENTS.comments.onChange, listener),
|
|
342
|
+
};
|
|
343
|
+
return ns;
|
|
344
|
+
}
|
|
345
|
+
case 'sheet': {
|
|
346
|
+
const ns = {
|
|
347
|
+
read: (request) => c('read', [request]),
|
|
348
|
+
send: (request) => c('send', [request]),
|
|
349
|
+
widget: (request) => c('widget', [request]),
|
|
350
|
+
importFile: (file, name) => c('importFile', [file, name], true),
|
|
351
|
+
onFrame: (listener) => listen('sheet', BROKERED_EVENTS.sheet.onFrame, listener),
|
|
352
|
+
onWalkthrough: (listener) => listen('sheet', BROKERED_EVENTS.sheet.onWalkthrough, listener),
|
|
353
|
+
};
|
|
354
|
+
return ns;
|
|
355
|
+
}
|
|
356
|
+
case 'history': {
|
|
357
|
+
const ns = {
|
|
358
|
+
list: () => c('list'),
|
|
359
|
+
files: (n) => c('files', [n]),
|
|
360
|
+
read: (n, path) => c('read', [n, path]),
|
|
361
|
+
readBytes: (n, path) => c('readBytes', [n, path]),
|
|
362
|
+
diff: (n, path) => c('diff', [n, path]),
|
|
363
|
+
restore: (n, paths) => c('restore', paths ? [n, paths] : [n]),
|
|
364
|
+
dismissNotice: (id) => c('dismissNotice', [id]),
|
|
365
|
+
note: (n, text) => c('note', [n, text]),
|
|
366
|
+
onChange: (listener) => listen('history', BROKERED_EVENTS.history.onChange, listener),
|
|
367
|
+
};
|
|
368
|
+
return ns;
|
|
369
|
+
}
|
|
370
|
+
case 'doc': {
|
|
371
|
+
const ns = {
|
|
372
|
+
session: () => c('session'),
|
|
373
|
+
read: (tab) => c('read', [tab]),
|
|
374
|
+
call: (request) => c('call', [request]),
|
|
375
|
+
history: (tab) => c('history', [tab]),
|
|
376
|
+
version: (tab, rev) => c('version', [tab, rev]),
|
|
377
|
+
restore: (request) => c('restore', [request]),
|
|
378
|
+
importFile: (name, bytes, tabName) => c('importFile', tabName === undefined ? [name, bytes] : [name, bytes, tabName], true),
|
|
379
|
+
exportFile: (query) => c('exportFile', [query], true),
|
|
380
|
+
onFrame: (listener) => listen('doc', BROKERED_EVENTS.doc.onFrame, listener),
|
|
381
|
+
};
|
|
382
|
+
return ns;
|
|
383
|
+
}
|
|
384
|
+
case 'downloads': {
|
|
385
|
+
// The Shell says when its host saves in this browser (a cloud host): the page then sends every role's files.
|
|
386
|
+
const ns = { save: (file) => c('save', [file], true), ...(config.browser === true ? { browser: true, check: () => c('check') } : {}) };
|
|
387
|
+
return ns;
|
|
388
|
+
}
|
|
389
|
+
case 'mcp': {
|
|
390
|
+
const ns = {
|
|
391
|
+
callTool: (server, tool, args, opts) => {
|
|
392
|
+
const timeoutMs = opts?.timeoutMs;
|
|
393
|
+
const wire = timeoutMs === undefined ? [server, tool, args] : [server, tool, args, { timeoutMs }];
|
|
394
|
+
// The page waits a little longer than the host does, so the host's own timeout error arrives.
|
|
395
|
+
const budget = Math.min(timeoutMs ?? MCP_CALL_TIMEOUT.defaultMs, MCP_CALL_TIMEOUT.maxMs) + 15_000;
|
|
396
|
+
return call('mcp', 'callTool', wire, false, budget, opts?.signal);
|
|
397
|
+
},
|
|
398
|
+
listTools: (server) => c('listTools', server === undefined ? [] : [server]),
|
|
399
|
+
};
|
|
400
|
+
return ns;
|
|
401
|
+
}
|
|
402
|
+
case 'sample': {
|
|
403
|
+
// The Shell runs the HTTP transport; the checks, the tools and the timers stay here, in the page.
|
|
404
|
+
const transport = {
|
|
405
|
+
start: (id, input, modelTier, options) =>
|
|
406
|
+
// No `cap_ack` comes (a consent dialog may be up): the page's own timers end a call that hangs.
|
|
407
|
+
call('sample', 'start', [id, input, modelTier, options], true, SAMPLE_ACKED_WAIT_MS + 60_000).catch((error) => ({ t: 'error', code: 'upstream_error', message: error instanceof Error ? error.message : String(error) })),
|
|
408
|
+
toolResults: (id, results) => c('toolResults', [id, results]),
|
|
409
|
+
cancel: (id) => c('cancel', [id]),
|
|
410
|
+
readLimits: () => c('readLimits'),
|
|
411
|
+
readState: () => c('readState'),
|
|
412
|
+
onEvent: (listener) => listen('sample', BROKERED_EVENTS.sample.onEvent, listener),
|
|
413
|
+
};
|
|
414
|
+
return createSampleFunction(transport, { ask: askSamplePermission });
|
|
415
|
+
}
|
|
416
|
+
default:
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
return {
|
|
421
|
+
async get(name) {
|
|
422
|
+
if (!CAP_NAME.test(name) || !(name in BROKERED_METHODS))
|
|
423
|
+
return null;
|
|
424
|
+
if (brokered === false)
|
|
425
|
+
return fallback.get(name);
|
|
426
|
+
const grant = await want(name);
|
|
427
|
+
if (!grant)
|
|
428
|
+
return brokered ? null : fallback.get(name);
|
|
429
|
+
if (!grant.ok)
|
|
430
|
+
return null;
|
|
431
|
+
return build(name, grant.config ?? {});
|
|
432
|
+
},
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* The provider a page should use: brokered through the Shell when it is in
|
|
437
|
+
* one, otherwise the local type server.
|
|
438
|
+
*/
|
|
439
|
+
export function createPageProvider(options = {}) {
|
|
440
|
+
const fallback = createLocalProvider(options);
|
|
441
|
+
return shellOrigin() ? createShellProvider({ ...options, fallback }) : fallback;
|
|
442
|
+
}
|