@open-artifact/harness-kit 0.0.0-stage → 0.14.1
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 +102 -2
- package/package.json +48 -4
- package/src/client.d.ts +110 -0
- package/src/client.js +272 -0
- package/src/context.d.ts +31 -0
- package/src/context.js +61 -0
- package/src/daemon.d.ts +139 -0
- package/src/daemon.js +219 -0
- package/src/embed/index.d.ts +183 -0
- package/src/embed/index.js +343 -0
- package/src/embed/remote.d.ts +39 -0
- package/src/embed/remote.js +51 -0
- package/src/harness.d.ts +237 -0
- package/src/harness.js +426 -0
- package/src/index.d.ts +18 -0
- package/src/index.js +17 -0
- package/src/runtimes.d.ts +138 -0
- package/src/runtimes.js +357 -0
- package/src/skill.d.ts +58 -0
- package/src/skill.js +88 -0
- package/src/testing-ws.d.ts +35 -0
- package/src/testing-ws.js +173 -0
- package/src/testing.d.ts +143 -0
- package/src/testing.js +424 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@open-artifact/harness-kit/embed`: browser code that puts an artifact's Shell page, or the library's home page,
|
|
3
|
+
* into an agent app's own UI. No Node imports: it runs in the app's renderer (a web page, an Electron or Tauri view).
|
|
4
|
+
*
|
|
5
|
+
* Two ways to show an artifact:
|
|
6
|
+
*
|
|
7
|
+
* - **Frame**: the host's page holds an `<iframe>` of the Shell (`viewUrl`). The Shell says `shell_hello` to its parent;
|
|
8
|
+
* this module answers `host_hello` to the Shell's origin only, and takes messages only from that iframe's window and
|
|
9
|
+
* the Shell's origin (the origin of the address it was given: loopback or not, `http` or `https`). The host's origin
|
|
10
|
+
* must be one its adapter declared (`caps.open.origins` in `hello`), or the Shell sends it no prompt or comment text,
|
|
11
|
+
* links, saved files or destinations.
|
|
12
|
+
*
|
|
13
|
+
* const view = embedArtifact(iframe, { url: viewUrl, agentName: 'My Agent', onNewSession: ({ prompt }) => … });
|
|
14
|
+
*
|
|
15
|
+
* - **Top-level view**: the host opens `host.open`'s `embed_url` in a view of its own (a tab, a webview, a window) with
|
|
16
|
+
* no parent frame; the Shell talks to the daemon, the daemon to the adapter (`shell.event` / `shell.command`). The
|
|
17
|
+
* host passes a transport that carries those both ways (in an Electron app, IPC to the process that holds the
|
|
18
|
+
* Harness connection):
|
|
19
|
+
*
|
|
20
|
+
* const view = embedArtifact({ send: (command) => harness.shellCommand(viewId, command), onEvent: (listener) => … }, { url: embedUrl, … });
|
|
21
|
+
*
|
|
22
|
+
* What the Shell sends is data about what the person did: prompts and comments are their words for the agent, never
|
|
23
|
+
* instructions to the host.
|
|
24
|
+
*
|
|
25
|
+
* Thumbnails: give `capture` (returns a JPEG of the view, as the host's own view can take one) and `saveThumbnail`
|
|
26
|
+
* (stores it, e.g. through the adapter's `Harness.saveThumbnail`; a browser page should not hold the daemon token).
|
|
27
|
+
* The kit captures {@link THUMBNAIL_DELAY_MS} after the Shell is ready, then after a place change at most once every
|
|
28
|
+
* {@link THUMBNAIL_INTERVAL_MS}.
|
|
29
|
+
*/
|
|
30
|
+
import { HOST_PROTOCOL, MAX_HOST_DESTINATIONS, shellToHostOf, } from '@open-artifact/protocol';
|
|
31
|
+
/** How long after the Shell is ready the first thumbnail is captured. */
|
|
32
|
+
export const THUMBNAIL_DELAY_MS = 2000;
|
|
33
|
+
/** The least time between two thumbnails of one view. */
|
|
34
|
+
export const THUMBNAIL_INTERVAL_MS = 60_000;
|
|
35
|
+
const isFrame = (target) => !('send' in target && typeof target.send === 'function');
|
|
36
|
+
function originOf(url) {
|
|
37
|
+
if (!url)
|
|
38
|
+
return null;
|
|
39
|
+
try {
|
|
40
|
+
const origin = new URL(url).origin;
|
|
41
|
+
return origin && origin !== 'null' ? origin : null;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** The address without the view ticket (`oa_view`) and with `hash` as its fragment. */
|
|
48
|
+
function addressOf(url, hash) {
|
|
49
|
+
if (!url)
|
|
50
|
+
return null;
|
|
51
|
+
try {
|
|
52
|
+
const address = new URL(url);
|
|
53
|
+
address.searchParams.delete('oa_view');
|
|
54
|
+
if (hash)
|
|
55
|
+
address.hash = hash.startsWith('#') ? hash : `#${hash}`;
|
|
56
|
+
return address.href;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function jpegOf(value) {
|
|
63
|
+
if (!value)
|
|
64
|
+
return null;
|
|
65
|
+
const bytes = value instanceof Uint8Array ? value : value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(await value.arrayBuffer());
|
|
66
|
+
return bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8 ? bytes : null;
|
|
67
|
+
}
|
|
68
|
+
function defaultWindow() {
|
|
69
|
+
return globalThis.window ?? null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Shows an artifact's Shell in the host's UI: `target` is the `<iframe>` (frame mode) or a transport to a top-level
|
|
73
|
+
* view (see the module's notes). Answers the Shell's hello and turns its messages into the callbacks.
|
|
74
|
+
*/
|
|
75
|
+
export function embedArtifact(target, options = {}) {
|
|
76
|
+
const win = options.window ?? defaultWindow();
|
|
77
|
+
const frame = isFrame(target) ? target : null;
|
|
78
|
+
const transport = frame ? null : target;
|
|
79
|
+
if (frame && options.url && frame.src !== options.url)
|
|
80
|
+
frame.src = options.url;
|
|
81
|
+
const shellUrl = options.url ?? frame?.src;
|
|
82
|
+
const shellOrigin = frame ? originOf(shellUrl) : null;
|
|
83
|
+
if (frame && !shellOrigin)
|
|
84
|
+
throw new Error('embedArtifact: the Shell address (options.url or the iframe src) is not an http(s) address.');
|
|
85
|
+
if (frame && !win)
|
|
86
|
+
throw new Error('embedArtifact: no window to listen on.');
|
|
87
|
+
let theme = options.theme;
|
|
88
|
+
let info = null;
|
|
89
|
+
let place = null;
|
|
90
|
+
let helloed = false;
|
|
91
|
+
let stopped = false;
|
|
92
|
+
let resolveReady;
|
|
93
|
+
const ready = new Promise((resolve) => (resolveReady = resolve));
|
|
94
|
+
let thumbTimer = null;
|
|
95
|
+
let lastThumb = 0;
|
|
96
|
+
const report = (error) => {
|
|
97
|
+
try {
|
|
98
|
+
options.onError?.(error);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// The host's own error handler failed: nothing more to do.
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
const safely = (run) => {
|
|
105
|
+
try {
|
|
106
|
+
run();
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
report(error);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const send = (message) => {
|
|
113
|
+
if (stopped)
|
|
114
|
+
return;
|
|
115
|
+
if (frame)
|
|
116
|
+
frame.contentWindow?.postMessage(message, shellOrigin);
|
|
117
|
+
else
|
|
118
|
+
void Promise.resolve(transport.send(message)).catch(report);
|
|
119
|
+
};
|
|
120
|
+
const hello = () => {
|
|
121
|
+
const caps = {};
|
|
122
|
+
if (options.onOpenSession || options.onNewSession)
|
|
123
|
+
caps.sessions = true;
|
|
124
|
+
if (options.toolbar)
|
|
125
|
+
caps.toolbar = true;
|
|
126
|
+
return {
|
|
127
|
+
openArtifact: 'host_hello',
|
|
128
|
+
caps,
|
|
129
|
+
protocol: HOST_PROTOCOL,
|
|
130
|
+
...(options.agentName ? { agentName: options.agentName } : {}),
|
|
131
|
+
...(options.harness ? { harness: options.harness } : {}),
|
|
132
|
+
...(theme ? { theme } : {}),
|
|
133
|
+
...(options.destinations?.length ? { destinations: options.destinations.slice(0, MAX_HOST_DESTINATIONS).map((d) => ({ id: d.id, label: d.label })) } : {}),
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
const thumbnail = () => {
|
|
137
|
+
thumbTimer = null;
|
|
138
|
+
if (stopped || !info || !options.capture || !options.saveThumbnail)
|
|
139
|
+
return;
|
|
140
|
+
lastThumb = Date.now();
|
|
141
|
+
const artifact = info.artifact;
|
|
142
|
+
void (async () => {
|
|
143
|
+
const jpeg = await jpegOf(await options.capture());
|
|
144
|
+
if (jpeg && !stopped)
|
|
145
|
+
await options.saveThumbnail(jpeg, artifact);
|
|
146
|
+
})().catch(report);
|
|
147
|
+
};
|
|
148
|
+
const scheduleThumbnail = (first) => {
|
|
149
|
+
if (stopped || thumbTimer || !options.capture || !options.saveThumbnail)
|
|
150
|
+
return;
|
|
151
|
+
const wait = first ? THUMBNAIL_DELAY_MS : Math.max(THUMBNAIL_DELAY_MS, lastThumb + THUMBNAIL_INTERVAL_MS - Date.now());
|
|
152
|
+
thumbTimer = setTimeout(thumbnail, wait);
|
|
153
|
+
};
|
|
154
|
+
const onShellMessage = (raw) => {
|
|
155
|
+
const message = shellToHostOf(raw);
|
|
156
|
+
if (!message || stopped)
|
|
157
|
+
return;
|
|
158
|
+
switch (message.openArtifact) {
|
|
159
|
+
case 'shell_hello':
|
|
160
|
+
info = { artifact: message.artifact, id: message.id, title: message.title, type: message.type, version: message.version, protocol: message.protocol };
|
|
161
|
+
helloed = true;
|
|
162
|
+
send(hello());
|
|
163
|
+
break;
|
|
164
|
+
case 'shell_ready': {
|
|
165
|
+
// A top-level view's hello may have come before the host listened: what `shell_ready` says is enough.
|
|
166
|
+
info ??= { artifact: message.artifact, id: message.artifact.replace(/^open-artifact:\/\/artifact\//, ''), title: '', type: '', version: '', protocol: HOST_PROTOCOL };
|
|
167
|
+
const ready = info;
|
|
168
|
+
safely(() => options.onReady?.(ready));
|
|
169
|
+
resolveReady(ready);
|
|
170
|
+
if (!lastThumb)
|
|
171
|
+
scheduleThumbnail(true);
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
case 'place':
|
|
175
|
+
place = message.hash;
|
|
176
|
+
safely(() => options.onPlace?.({ artifact: message.artifact, hash: message.hash }));
|
|
177
|
+
if (lastThumb)
|
|
178
|
+
scheduleThumbnail(false);
|
|
179
|
+
break;
|
|
180
|
+
case 'new_session':
|
|
181
|
+
safely(() => options.onNewSession?.({ prompt: message.prompt, artifact: message.artifact }));
|
|
182
|
+
break;
|
|
183
|
+
case 'open_session':
|
|
184
|
+
safely(() => options.onOpenSession?.({ session: message.session, harness: message.harness, artifact: info?.artifact ?? null }));
|
|
185
|
+
break;
|
|
186
|
+
case 'comment_summon':
|
|
187
|
+
safely(() => options.onCommentSent?.({ text: message.text }));
|
|
188
|
+
break;
|
|
189
|
+
case 'close':
|
|
190
|
+
safely(() => options.onClose?.());
|
|
191
|
+
break;
|
|
192
|
+
case 'open_external':
|
|
193
|
+
safely(() => {
|
|
194
|
+
if (options.onOpenExternal)
|
|
195
|
+
options.onOpenExternal(message.url);
|
|
196
|
+
else
|
|
197
|
+
win?.open?.(message.url, '_blank', 'noopener');
|
|
198
|
+
});
|
|
199
|
+
break;
|
|
200
|
+
case 'saved_file':
|
|
201
|
+
safely(() => options.onSavedFile?.(message.path));
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const onWindowMessage = (event) => {
|
|
206
|
+
// Only the Shell's own window, from the Shell's origin.
|
|
207
|
+
if (!frame || event.source !== frame.contentWindow || event.origin !== shellOrigin)
|
|
208
|
+
return;
|
|
209
|
+
onShellMessage(event.data);
|
|
210
|
+
};
|
|
211
|
+
let stopTransport = null;
|
|
212
|
+
if (frame)
|
|
213
|
+
win.addEventListener('message', onWindowMessage);
|
|
214
|
+
else {
|
|
215
|
+
stopTransport = transport.onEvent(onShellMessage);
|
|
216
|
+
// A top-level view's Shell may have said hello before the host listened: answer now; it takes the latest.
|
|
217
|
+
send(hello());
|
|
218
|
+
helloed = true;
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
get artifact() {
|
|
222
|
+
return info?.artifact ?? null;
|
|
223
|
+
},
|
|
224
|
+
get place() {
|
|
225
|
+
return place;
|
|
226
|
+
},
|
|
227
|
+
ready,
|
|
228
|
+
goto(hash) {
|
|
229
|
+
if (typeof hash === 'string' && hash)
|
|
230
|
+
send({ openArtifact: 'goto', hash });
|
|
231
|
+
},
|
|
232
|
+
setTheme(next) {
|
|
233
|
+
theme = next;
|
|
234
|
+
if (helloed)
|
|
235
|
+
send(hello());
|
|
236
|
+
},
|
|
237
|
+
url: () => addressOf(shellUrl, place),
|
|
238
|
+
destroy() {
|
|
239
|
+
if (stopped)
|
|
240
|
+
return;
|
|
241
|
+
stopped = true;
|
|
242
|
+
if (thumbTimer)
|
|
243
|
+
clearTimeout(thumbTimer);
|
|
244
|
+
if (frame)
|
|
245
|
+
win?.removeEventListener('message', onWindowMessage);
|
|
246
|
+
stopTransport?.();
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
const text = (value, max) => (typeof value === 'string' ? value.slice(0, max) : '');
|
|
251
|
+
/** Shows the library's home page in an `<iframe>`, listing the host's own artifacts, and turns its messages into callbacks. */
|
|
252
|
+
export function embedLibrary(iframe, options = {}) {
|
|
253
|
+
const win = options.window ?? defaultWindow();
|
|
254
|
+
if (!win)
|
|
255
|
+
throw new Error('embedLibrary: no window to listen on.');
|
|
256
|
+
if (options.url && iframe.src !== options.url)
|
|
257
|
+
iframe.src = options.url;
|
|
258
|
+
const origin = originOf(options.url ?? iframe.src);
|
|
259
|
+
if (!origin)
|
|
260
|
+
throw new Error('embedLibrary: the home page address (options.url or the iframe src) is not an http(s) address.');
|
|
261
|
+
let theme = options.theme;
|
|
262
|
+
let helloed = false;
|
|
263
|
+
let stopped = false;
|
|
264
|
+
const hello = () => {
|
|
265
|
+
const caps = {};
|
|
266
|
+
if (options.onOpenSession || options.onNewSession)
|
|
267
|
+
caps.sessions = true;
|
|
268
|
+
if (options.onOpenArtifact)
|
|
269
|
+
caps.artifacts = true;
|
|
270
|
+
const library = {};
|
|
271
|
+
if (options.harness)
|
|
272
|
+
library.harness = options.harness;
|
|
273
|
+
if (options.workspace)
|
|
274
|
+
library.workspace = options.workspace;
|
|
275
|
+
return {
|
|
276
|
+
openArtifact: 'host_hello',
|
|
277
|
+
caps,
|
|
278
|
+
protocol: HOST_PROTOCOL,
|
|
279
|
+
...(options.harness ? { harness: options.harness } : {}),
|
|
280
|
+
...(options.agentName ? { agentName: options.agentName } : {}),
|
|
281
|
+
...(theme ? { theme } : {}),
|
|
282
|
+
...(library.harness || library.workspace ? { library } : {}),
|
|
283
|
+
};
|
|
284
|
+
};
|
|
285
|
+
const send = (message) => {
|
|
286
|
+
if (!stopped)
|
|
287
|
+
iframe.contentWindow?.postMessage(message, origin);
|
|
288
|
+
};
|
|
289
|
+
const safely = (run) => {
|
|
290
|
+
try {
|
|
291
|
+
run();
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
try {
|
|
295
|
+
options.onError?.(error);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
// Nothing more to do.
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const onMessage = (event) => {
|
|
303
|
+
if (stopped || event.source !== iframe.contentWindow || event.origin !== origin)
|
|
304
|
+
return;
|
|
305
|
+
const data = event.data;
|
|
306
|
+
if (!data || typeof data !== 'object')
|
|
307
|
+
return;
|
|
308
|
+
switch (data.openArtifact) {
|
|
309
|
+
case 'home_hello':
|
|
310
|
+
helloed = true;
|
|
311
|
+
send(hello());
|
|
312
|
+
break;
|
|
313
|
+
case 'home_ready':
|
|
314
|
+
safely(() => options.onReady?.());
|
|
315
|
+
break;
|
|
316
|
+
case 'open_artifact': {
|
|
317
|
+
const artifact = { url: text(data.url, 200), id: text(data.id, 100), title: text(data.title, 500), type: text(data.type, 100) };
|
|
318
|
+
if (artifact.url)
|
|
319
|
+
safely(() => options.onOpenArtifact?.(artifact));
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
case 'open_session':
|
|
323
|
+
safely(() => options.onOpenSession?.({ session: typeof data.session === 'string' ? data.session.slice(0, 200) : null, harness: text(data.harness, 64) }));
|
|
324
|
+
break;
|
|
325
|
+
case 'new_session':
|
|
326
|
+
safely(() => options.onNewSession?.({ prompt: text(data.prompt, 8000), artifact: text(data.artifact, 200) }));
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
win.addEventListener('message', onMessage);
|
|
331
|
+
return {
|
|
332
|
+
setTheme(next) {
|
|
333
|
+
theme = next;
|
|
334
|
+
if (helloed)
|
|
335
|
+
send(hello());
|
|
336
|
+
},
|
|
337
|
+
destroy() {
|
|
338
|
+
stopped = true;
|
|
339
|
+
win.removeEventListener('message', onMessage);
|
|
340
|
+
},
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
export { remoteGate, remotePolicyOf } from "./remote.js";
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a host shows a page that comes from another computer: a remote type's page (`host.open`'s `remote`).
|
|
3
|
+
*
|
|
4
|
+
* The host picks a policy (`HarnessOptions.embed.remote`, said in `hello` as `caps.open.remote`):
|
|
5
|
+
*
|
|
6
|
+
* - `allow`: show it, as any other page.
|
|
7
|
+
* - `ask` (the default): ask the person through the host's `allowRemote({ origin, type, title })`. A yes is kept per
|
|
8
|
+
* origin for the life of the process; a no (or a question that throws) is not, so the next open asks again. With no
|
|
9
|
+
* `allowRemote`, the answer is no.
|
|
10
|
+
* - `deny`: never show it; the daemon is told the page was not opened.
|
|
11
|
+
*
|
|
12
|
+
* No Node imports: an app may also run this in its renderer.
|
|
13
|
+
*/
|
|
14
|
+
import type { RemotePagePolicy } from '@open-artifact/protocol';
|
|
15
|
+
export type { RemotePagePolicy };
|
|
16
|
+
/** What `allowRemote` is asked: may a page from `origin` (of type `type`) be shown? */
|
|
17
|
+
export interface RemotePageRequest {
|
|
18
|
+
/** The other computer's origin, e.g. `https://types.example.com`. */
|
|
19
|
+
origin: string;
|
|
20
|
+
/** The type id. */
|
|
21
|
+
type: string;
|
|
22
|
+
/** The artifact's title, when the daemon said it. */
|
|
23
|
+
title?: string;
|
|
24
|
+
}
|
|
25
|
+
/** The host's answer: `true` shows the page. */
|
|
26
|
+
export type AllowRemote = (request: RemotePageRequest) => boolean | Promise<boolean>;
|
|
27
|
+
/** The remote part of a `host.open`: the type and the origins its page comes from. */
|
|
28
|
+
export interface RemotePage {
|
|
29
|
+
type: string;
|
|
30
|
+
origins: string[];
|
|
31
|
+
}
|
|
32
|
+
/** The policy a host's option names, or the default (`ask`) for anything else. */
|
|
33
|
+
export declare function remotePolicyOf(value: unknown): RemotePagePolicy;
|
|
34
|
+
/**
|
|
35
|
+
* A gate for remote pages under one policy: `(remote, title) → shown?`. A page with no `remote` (a type on this
|
|
36
|
+
* computer) always passes. Under `ask`, a yes is kept per origin for the gate's life; a no, or a question that
|
|
37
|
+
* throws, is not kept: the person is asked again the next time.
|
|
38
|
+
*/
|
|
39
|
+
export declare function remoteGate(policy?: RemotePagePolicy, allowRemote?: AllowRemote): (remote: RemotePage | null | undefined, title?: string) => Promise<boolean>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a host shows a page that comes from another computer: a remote type's page (`host.open`'s `remote`).
|
|
3
|
+
*
|
|
4
|
+
* The host picks a policy (`HarnessOptions.embed.remote`, said in `hello` as `caps.open.remote`):
|
|
5
|
+
*
|
|
6
|
+
* - `allow`: show it, as any other page.
|
|
7
|
+
* - `ask` (the default): ask the person through the host's `allowRemote({ origin, type, title })`. A yes is kept per
|
|
8
|
+
* origin for the life of the process; a no (or a question that throws) is not, so the next open asks again. With no
|
|
9
|
+
* `allowRemote`, the answer is no.
|
|
10
|
+
* - `deny`: never show it; the daemon is told the page was not opened.
|
|
11
|
+
*
|
|
12
|
+
* No Node imports: an app may also run this in its renderer.
|
|
13
|
+
*/
|
|
14
|
+
/** The policy a host's option names, or the default (`ask`) for anything else. */
|
|
15
|
+
export function remotePolicyOf(value) {
|
|
16
|
+
return value === 'allow' || value === 'deny' || value === 'ask' ? value : 'ask';
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A gate for remote pages under one policy: `(remote, title) → shown?`. A page with no `remote` (a type on this
|
|
20
|
+
* computer) always passes. Under `ask`, a yes is kept per origin for the gate's life; a no, or a question that
|
|
21
|
+
* throws, is not kept: the person is asked again the next time.
|
|
22
|
+
*/
|
|
23
|
+
export function remoteGate(policy = 'ask', allowRemote) {
|
|
24
|
+
const answers = new Map();
|
|
25
|
+
const ask = (origin, type, title) => {
|
|
26
|
+
let answer = answers.get(origin);
|
|
27
|
+
if (!answer) {
|
|
28
|
+
answer = (async () => (await allowRemote({ origin, type, ...(title !== undefined ? { title } : {}) })) === true)();
|
|
29
|
+
// Shared while the question is open (two opens at once ask once); only a yes stays after it.
|
|
30
|
+
answers.set(origin, answer);
|
|
31
|
+
answer.then((yes) => {
|
|
32
|
+
if (!yes)
|
|
33
|
+
answers.delete(origin);
|
|
34
|
+
}, () => answers.delete(origin));
|
|
35
|
+
}
|
|
36
|
+
return answer.catch(() => false);
|
|
37
|
+
};
|
|
38
|
+
return async (remote, title) => {
|
|
39
|
+
if (!remote || !Array.isArray(remote.origins) || !remote.origins.length)
|
|
40
|
+
return true;
|
|
41
|
+
if (policy === 'allow')
|
|
42
|
+
return true;
|
|
43
|
+
if (policy === 'deny' || !allowRemote)
|
|
44
|
+
return false;
|
|
45
|
+
for (const origin of remote.origins) {
|
|
46
|
+
if (!(await ask(origin, remote.type, title)))
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
};
|
|
51
|
+
}
|
package/src/harness.d.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createHarness`: everything an agent app's adapter does with the daemon, behind one object.
|
|
3
|
+
*
|
|
4
|
+
* It finds or starts the daemon, connects, and keeps the connection: a dropped one comes back with backoff, attaches
|
|
5
|
+
* every session again and hands what waited in their inboxes to the `wake` callback. The app answers two callbacks,
|
|
6
|
+
* `wake` (give a message to a session) and `open` (show a page in its own UI), and calls the rest: sessions, tools,
|
|
7
|
+
* files its agent wrote, and the artifacts its sessions make.
|
|
8
|
+
*/
|
|
9
|
+
import { type AdapterCaps, type AttachParams, type CommandEntry, type EmbedOriginsResult, type HarnessEvent, type HostToShell, type ShellEventParams, type HarnessPolicy, type HarnessProfile, type HarnessRuntime, type HelloResult, type InboxMessage, type RuntimeStatus, type RuntimeUpdateResult, type SessionParams, type SessionStatus, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverResult, type WakeDeliverStatus } from '@open-artifact/protocol';
|
|
10
|
+
import { HarnessClient, type HarnessConnectionState } from './client.js';
|
|
11
|
+
import { type EnsureDaemonOptions } from './daemon.js';
|
|
12
|
+
import { type InstallSkillOptions, type InstallSkillResult } from './skill.js';
|
|
13
|
+
import { type ArtifactContext } from './context.js';
|
|
14
|
+
import { type AllowRemote, type RemotePage, type RemotePagePolicy } from './embed/remote.js';
|
|
15
|
+
/** This kit's name and version, said in `hello` (`kit`). */
|
|
16
|
+
export declare const KIT: {
|
|
17
|
+
readonly name: "@open-artifact/harness-kit";
|
|
18
|
+
readonly version: string;
|
|
19
|
+
};
|
|
20
|
+
/** What the `wake` callback answers: a status, or a status with the session that took the message instead. */
|
|
21
|
+
export type WakeAnswer = WakeDeliverStatus | WakeDeliverResult;
|
|
22
|
+
/** What the `open` callback gets: show this artifact for this session. */
|
|
23
|
+
export interface OpenRequest {
|
|
24
|
+
/** The session that asked, or `null` when no session did. */
|
|
25
|
+
session: string | null;
|
|
26
|
+
/** `open-artifact://artifact/<id>`. */
|
|
27
|
+
url: string;
|
|
28
|
+
/** The Shell page. */
|
|
29
|
+
viewUrl: string;
|
|
30
|
+
/** What a top-level view loads: `viewUrl` with a view ticket when the daemon gave one, else `viewUrl`. */
|
|
31
|
+
embedUrl: string;
|
|
32
|
+
/** The view ticket, when the daemon gave one. */
|
|
33
|
+
view?: string;
|
|
34
|
+
title?: string;
|
|
35
|
+
/**
|
|
36
|
+
* The artifact's type is on another computer: its page comes from these origins. Present only once the host's
|
|
37
|
+
* `embed.remote` policy let it through (`allow`, or `ask` answered yes); the host lets these origins in to show it.
|
|
38
|
+
*/
|
|
39
|
+
remote?: RemotePage;
|
|
40
|
+
}
|
|
41
|
+
/** An artifact as `on('artifact')` reports it. */
|
|
42
|
+
export interface HarnessArtifact {
|
|
43
|
+
/** `open-artifact://artifact/<id>`: what to store in messages and cards (it does not change with the daemon's port). */
|
|
44
|
+
url: string;
|
|
45
|
+
id: string;
|
|
46
|
+
title: string;
|
|
47
|
+
/** The type id. */
|
|
48
|
+
type: string;
|
|
49
|
+
/** The local Shell page (also when it is published: the person's own copy); `null` once removed. */
|
|
50
|
+
viewUrl: string | null;
|
|
51
|
+
/** Its address on the site it is published to, or `null` when it is not published. */
|
|
52
|
+
publicUrl?: string | null;
|
|
53
|
+
/** The Library API address of its thumbnail, when one was captured. */
|
|
54
|
+
thumbnail: string | null;
|
|
55
|
+
updatedAt: string;
|
|
56
|
+
}
|
|
57
|
+
/** What changed about an artifact. */
|
|
58
|
+
export type ArtifactChange = 'created' | 'updated' | 'removed';
|
|
59
|
+
/** An `on('artifact')` report. */
|
|
60
|
+
export interface ArtifactReport {
|
|
61
|
+
/** The session of this harness that owns the artifact, or `null` when it is not one of this harness's sessions. */
|
|
62
|
+
session: string | null;
|
|
63
|
+
/** That session's workspace, when known. */
|
|
64
|
+
workspace: string | null;
|
|
65
|
+
artifact: HarnessArtifact;
|
|
66
|
+
change: ArtifactChange;
|
|
67
|
+
/** Who changed it, as the daemon said (`agent`, or the person's page). */
|
|
68
|
+
author?: string;
|
|
69
|
+
/** The files that changed, when the daemon said. */
|
|
70
|
+
paths?: string[];
|
|
71
|
+
}
|
|
72
|
+
/** Options of {@link createHarness}. */
|
|
73
|
+
export interface HarnessOptions {
|
|
74
|
+
/** The harness name (`^[a-z0-9][a-z0-9._-]{0,40}$`). */
|
|
75
|
+
harness: string;
|
|
76
|
+
/** What the harness calls its agent. */
|
|
77
|
+
agentName?: string;
|
|
78
|
+
/** The harness's command names, e.g. `['artifact']`. */
|
|
79
|
+
commands?: string[];
|
|
80
|
+
/** Capabilities beyond what the callbacks and options imply (see {@link createHarness}). */
|
|
81
|
+
caps?: AdapterCaps;
|
|
82
|
+
/** The harness's rules that are data (the daemon writes its instructions by them, or refuses calls). */
|
|
83
|
+
policy?: HarnessPolicy;
|
|
84
|
+
/** The harness's rules that are only text. */
|
|
85
|
+
rules?: string;
|
|
86
|
+
/** More of the harness's profile, reported in `hello` (`nudge` is never sent). */
|
|
87
|
+
profile?: Omit<Partial<HarnessProfile>, 'nudge' | 'name' | 'source'>;
|
|
88
|
+
/** The runtime the harness carries (`@open-artifact/cli`): it starts the daemon when none runs. */
|
|
89
|
+
runtime?: HarnessRuntime;
|
|
90
|
+
/**
|
|
91
|
+
* How the harness embeds pages, when it shows them itself (`open`). `remote` is what it does with a remote type's
|
|
92
|
+
* page (one on another computer): `allow` shows it, `deny` answers not-opened without calling `open`, `ask` (the
|
|
93
|
+
* default) asks `allowRemote`, keeping a yes per origin for the life of the process and asking again after a no.
|
|
94
|
+
*/
|
|
95
|
+
embed?: {
|
|
96
|
+
origins: string[];
|
|
97
|
+
mode?: 'frame' | 'view';
|
|
98
|
+
remote?: RemotePagePolicy;
|
|
99
|
+
};
|
|
100
|
+
/** Asked under `embed.remote: 'ask'` before a remote type's page is shown; without it the answer is no. */
|
|
101
|
+
allowRemote?: AllowRemote;
|
|
102
|
+
/** An Open Artifact home of the harness's own: its own daemon and library, apart from the other apps'. */
|
|
103
|
+
home?: string;
|
|
104
|
+
/** Start the daemon when none runs (default `true`). */
|
|
105
|
+
autoStart?: boolean;
|
|
106
|
+
/** More options for starting the daemon (`env`, `bin`, `timeoutMs`, and `spawn` for a host that starts the process itself). */
|
|
107
|
+
daemon?: EnsureDaemonOptions;
|
|
108
|
+
/** Gives a message to a session (`wake.deliver`); see {@link createHarness}. */
|
|
109
|
+
wake?: (params: WakeDeliverParams) => WakeAnswer | Promise<WakeAnswer>;
|
|
110
|
+
/** Shows a page in the harness's own UI (`host.open`). `false`: it was not shown. */
|
|
111
|
+
open?: (request: OpenRequest) => boolean | void | Promise<boolean | void>;
|
|
112
|
+
/** How long `wake` may take before the daemon is told it failed (and keeps the message), ms. Default 25 s. */
|
|
113
|
+
wakeTimeoutMs?: number;
|
|
114
|
+
/** Reconnect delays, ms: from `minMs` (default 1 s) doubling to `maxMs` (default 30 s). */
|
|
115
|
+
reconnect?: {
|
|
116
|
+
minMs?: number;
|
|
117
|
+
maxMs?: number;
|
|
118
|
+
};
|
|
119
|
+
/** Diagnostic log. */
|
|
120
|
+
log?: (line: string) => void;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The runtime calls (feature `runtime.update`): what runtimes this computer has and which starts, and the host's yes
|
|
124
|
+
* to an update. Both connect first, and throw `unsupported` when the daemon does not list the feature.
|
|
125
|
+
*/
|
|
126
|
+
export interface HarnessRuntimeCalls {
|
|
127
|
+
/** `runtime.status`: the runtimes here, the update policy, the last check and a waiting switch. */
|
|
128
|
+
status(): Promise<RuntimeStatus>;
|
|
129
|
+
/**
|
|
130
|
+
* `runtime.update`: downloads the newest compatible runtime (or `version`) into the shared folder; the daemon
|
|
131
|
+
* switches once idle. Refused (`not_granted`) when updates are off for the whole computer.
|
|
132
|
+
*/
|
|
133
|
+
update(version?: string): Promise<RuntimeUpdateResult>;
|
|
134
|
+
}
|
|
135
|
+
/** The connection to the daemon, as {@link createHarness} returns it. */
|
|
136
|
+
export interface Harness {
|
|
137
|
+
/** The underlying connection, for calls the kit does not wrap (`client.request(method, params)`). */
|
|
138
|
+
readonly client: HarnessClient;
|
|
139
|
+
/** Whether the connection is up. */
|
|
140
|
+
readonly connected: boolean;
|
|
141
|
+
/** The daemon's features (see `HarnessFeature`); empty while not connected. */
|
|
142
|
+
readonly features: readonly string[];
|
|
143
|
+
/** Connects now if it is not connected (starting the daemon unless `autoStart` is false). */
|
|
144
|
+
ready(): Promise<HelloResult>;
|
|
145
|
+
/**
|
|
146
|
+
* Attaches a session; a reconnect attaches it again. What waited in its inbox goes to the `wake` callback; the
|
|
147
|
+
* answer's `inbox` holds what the callback did not take (all of it without a callback).
|
|
148
|
+
*/
|
|
149
|
+
attach(params: AttachParams): Promise<{
|
|
150
|
+
key: string;
|
|
151
|
+
inbox: InboxMessage[];
|
|
152
|
+
}>;
|
|
153
|
+
/** The session's agent is `running` or `idle` now. */
|
|
154
|
+
status(session: string | SessionParams, status: SessionStatus): Promise<void>;
|
|
155
|
+
/** Detaches a session. */
|
|
156
|
+
detach(session: string | SessionParams): Promise<void>;
|
|
157
|
+
/** Renames a session. */
|
|
158
|
+
rename(session: string | SessionParams, title: string): Promise<void>;
|
|
159
|
+
/** The tool definitions: the daemon's when connected, else the ones this kit carries. */
|
|
160
|
+
tools(): Promise<ToolDefinition[]>;
|
|
161
|
+
/** Calls a tool for a session. */
|
|
162
|
+
call(name: string, args: Record<string, unknown>, caller?: SessionParams): Promise<ToolCallResult>;
|
|
163
|
+
/** The agent wrote these files (absolute paths) with its own tools. */
|
|
164
|
+
wrote(paths: string[], caller?: SessionParams): Promise<{
|
|
165
|
+
ok: true;
|
|
166
|
+
artifacts?: string[];
|
|
167
|
+
}>;
|
|
168
|
+
/** Shows an artifact for a session (through `open`, when the harness shows pages). */
|
|
169
|
+
open(url: string, options?: SessionParams): Promise<{
|
|
170
|
+
opened: boolean;
|
|
171
|
+
view_url?: string;
|
|
172
|
+
}>;
|
|
173
|
+
/** Whether a tool call is about an Open Artifact link (`url` or `type_url` is `open-artifact://…`). */
|
|
174
|
+
owns(args: Record<string, unknown> | null | undefined): boolean;
|
|
175
|
+
/**
|
|
176
|
+
* The artifact's local Shell page (stable while the daemon keeps its port; also for a published artifact), or `null`
|
|
177
|
+
* when the daemon does not know it. The published address is {@link Harness.publicUrl}.
|
|
178
|
+
*/
|
|
179
|
+
viewUrl(url: string): Promise<string | null>;
|
|
180
|
+
/** The artifact's address on the site it is published to, or `null` (not published, or unknown). */
|
|
181
|
+
publicUrl(url: string): Promise<string | null>;
|
|
182
|
+
/** The origins a host must let in to show pages (feature `embed.origins`); `on('event')` gets `embed/origins` changes. */
|
|
183
|
+
embedOrigins(): Promise<EmbedOriginsResult>;
|
|
184
|
+
/** Sends a host message to the Shell of a top-level view this harness opened (feature `shell.command`). */
|
|
185
|
+
shellCommand(view: string, command: HostToShell): Promise<void>;
|
|
186
|
+
/**
|
|
187
|
+
* What the person selected on the artifact's page, read as its owner session (feature `view.context`); turn it into
|
|
188
|
+
* prompt text with {@link Harness.contextBlock}. `on('event')` gets `view/context` when it changes (best effort).
|
|
189
|
+
*/
|
|
190
|
+
context(url: string, options?: {
|
|
191
|
+
session?: string | null;
|
|
192
|
+
workspace?: string | null;
|
|
193
|
+
}): Promise<ArtifactContext>;
|
|
194
|
+
/** The prompt block of a context (see `contextBlock`): `''` when there is nothing to say. */
|
|
195
|
+
contextBlock(context: ArtifactContext | null | undefined): string;
|
|
196
|
+
/** Saves a captured thumbnail (JPEG bytes) for the artifact, for libraries and cards. */
|
|
197
|
+
saveThumbnail(url: string, jpeg: Uint8Array): Promise<void>;
|
|
198
|
+
/** What the Shell of a top-level view this harness opened says (`shell.event`). Returns a function that stops. */
|
|
199
|
+
on(event: 'shell', listener: (event: ShellEventParams) => void): () => void;
|
|
200
|
+
/** Reports artifacts created, changed or removed. Returns a function that stops. */
|
|
201
|
+
on(event: 'artifact', listener: (report: ArtifactReport) => void): () => void;
|
|
202
|
+
/** Every event the daemon sends. Returns a function that stops. */
|
|
203
|
+
on(event: 'event', listener: (event: HarnessEvent) => void): () => void;
|
|
204
|
+
/** The connection went up or down. Returns a function that stops. */
|
|
205
|
+
on(event: 'state', listener: (state: HarnessConnectionState) => void): () => void;
|
|
206
|
+
/**
|
|
207
|
+
* Writes the skill for this harness into `<dir>/<command>/SKILL.md` (rendered by the daemon, `skill.get`, else by
|
|
208
|
+
* this kit), only when it changed; again after a reconnect to another runtime.
|
|
209
|
+
*/
|
|
210
|
+
installSkill(options: InstallSkillOptions): Promise<InstallSkillResult>;
|
|
211
|
+
/** One command per installed type, for the harness's command menu (`commands.list`; `[]` without it). */
|
|
212
|
+
commands(options?: {
|
|
213
|
+
command?: string;
|
|
214
|
+
locale?: string;
|
|
215
|
+
}): Promise<CommandEntry[]>;
|
|
216
|
+
/** The runtime's status and updates (feature `runtime.update`); `on('event')` gets `runtime/update` when one exists. */
|
|
217
|
+
readonly runtime: HarnessRuntimeCalls;
|
|
218
|
+
/** Closes the connection for good. */
|
|
219
|
+
close(): void;
|
|
220
|
+
}
|
|
221
|
+
/** Whether a tool call is about an Open Artifact link (`url` or `type_url`), so a harness with its own tools can route it. */
|
|
222
|
+
export declare function ownsCall(args: Record<string, unknown> | null | undefined): boolean;
|
|
223
|
+
/**
|
|
224
|
+
* Connects an agent app to the daemon. Resolves once the first connection attempt is over: when it failed (no daemon
|
|
225
|
+
* and `autoStart: false`, say), the harness keeps trying in the background and calls connect on demand.
|
|
226
|
+
*
|
|
227
|
+
* What `hello` says follows from the options: `caps.wake` when there is a `wake` callback, `caps.open` when there is
|
|
228
|
+
* an `open` callback (`{ embed, origins }` with `embed`), `caps.commands` from `commands`, `caps.agentName` from
|
|
229
|
+
* `agentName`; `options.caps` adds the rest (`tools`, `library`, `wake.resume`, `wake.mode`). The profile carries
|
|
230
|
+
* `agentName`, `commands`, `policy`, `rules`, the caps and `options.profile`.
|
|
231
|
+
*
|
|
232
|
+
* `wake` answers how it handed the message over: `resumed` (started a turn), `delivered` (put it into the running
|
|
233
|
+
* turn), `drafted` (put it in the session's draft, for a harness whose `caps.wake.mode` is `draft`) or `failed` (the
|
|
234
|
+
* daemon keeps it for later). It may name the session that took it instead: `{ status, session }`. A callback that
|
|
235
|
+
* throws, or takes longer than `wakeTimeoutMs`, answers `failed`.
|
|
236
|
+
*/
|
|
237
|
+
export declare function createHarness(options: HarnessOptions): Promise<Harness>;
|