@openartifactsai/harness-kit 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/src/harness.js ADDED
@@ -0,0 +1,678 @@
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 { LIBRARY_ROUTES, LEGACY_URL_SCHEME, OpenArtifactsError, TOOL_DEFINITIONS, artifactIdOf, artifactUrl, wakeSourceOf, } from '@openartifactsai/protocol';
10
+ import { HarnessClient, NO_REPLY } from "./client.js";
11
+ import { api, ensureDaemon, readDaemon, restartDaemon, stopDaemon } from "./daemon.js";
12
+ import { envValue } from "./legacy.js";
13
+ import { commands, keepSkillInstalled } from "./skill.js";
14
+ import { contextBlock, readContext } from "./context.js";
15
+ import { remoteGate, remotePolicyOf } from "./embed/remote.js";
16
+ import pkg from '../package.json' with { type: 'json' };
17
+ import { mcpLender } from "./mcp.js";
18
+ /** This kit's name and version, said in `hello` (`kit`). */
19
+ export const KIT = { name: '@openartifactsai/harness-kit', version: pkg.version ?? '0.0.0' };
20
+ /** The codes a `sample.create` refusal may carry; anything else a `run` throws answers `error`. */
21
+ export const SAMPLE_REFUSAL_CODES = Object.freeze(['rate_limited', 'unavailable', 'not_granted', 'session_expired', 'prompt_too_large']);
22
+ const ROUND_STOPS = ['end', 'length', 'tools', 'refusal'];
23
+ /** Default of {@link HarnessOptions.wakeTimeoutMs}: under the daemon's own 30 s wait for an answer. */
24
+ const WAKE_TIMEOUT_MS = 25_000;
25
+ const sessionParams = (session) => (typeof session === 'string' ? { session } : session);
26
+ /** A string that is an Open Artifacts link (or one as written before the rename, `open-artifact://`, still in transcripts). */
27
+ const isLink = (value) => typeof value === 'string' && (value.trim().startsWith('open-artifacts://') || value.trim().startsWith(LEGACY_URL_SCHEME));
28
+ /** Whether a tool call is about an Open Artifacts link (`url` or `type_url`), so a harness with its own tools can route it. */
29
+ export function ownsCall(args) {
30
+ return !!args && (isLink(args.url) || isLink(args.type_url));
31
+ }
32
+ /** The caps `hello` says: `options.caps`, plus what the callbacks and options imply. */
33
+ function capsOf(options) {
34
+ const caps = { ...options.caps };
35
+ if (options.agentName && !caps.agentName)
36
+ caps.agentName = options.agentName;
37
+ // Without a callback the adapter cannot answer the call, so it does not claim it.
38
+ if (options.wake)
39
+ caps.wake = caps.wake ?? {};
40
+ else
41
+ delete caps.wake;
42
+ if (options.open) {
43
+ if (caps.open === undefined || caps.open === true)
44
+ caps.open = options.embed ? { embed: options.embed.mode ?? 'frame', origins: [...options.embed.origins], remote: remotePolicyOf(options.embed.remote) } : true;
45
+ }
46
+ else
47
+ delete caps.open;
48
+ if (options.commands?.length && !caps.commands)
49
+ caps.commands = { names: [...options.commands] };
50
+ if (options.sample)
51
+ caps.sample = { ...options.sample.caps, ...(options.sample.caps.tiers ? { tiers: [...options.sample.caps.tiers] } : {}) };
52
+ else
53
+ delete caps.sample;
54
+ if (options.mcp)
55
+ caps.mcp = true;
56
+ else
57
+ delete caps.mcp;
58
+ // The models are those of a session `startSession` starts: without it, `sessionModels` declares nothing.
59
+ if (options.startSession)
60
+ caps.sessions = options.sessionModels ? { start: true, models: true } : { start: true };
61
+ else
62
+ delete caps.sessions;
63
+ return caps;
64
+ }
65
+ /** The profile `hello` reports, or `undefined` when there is nothing to say. */
66
+ function profileOf(options, caps) {
67
+ const { nudge: _nudge, ...given } = (options.profile ?? {});
68
+ const profile = {
69
+ ...given,
70
+ ...(options.agentName ? { agentName: options.agentName } : {}),
71
+ ...(options.commands?.length ? { commands: [...options.commands] } : {}),
72
+ ...(options.policy ? { policy: options.policy } : {}),
73
+ ...(options.rules ? { rules: options.rules } : {}),
74
+ ...(Object.keys(caps).length ? { caps } : {}),
75
+ };
76
+ return Object.keys(profile).length ? profile : undefined;
77
+ }
78
+ /** Runs `work`, or gives `fallback` when it takes longer than `ms`. */
79
+ function within(work, ms, fallback) {
80
+ return new Promise((resolveIt, rejectIt) => {
81
+ const timer = setTimeout(() => resolveIt(fallback()), ms);
82
+ timer.unref?.();
83
+ work.then((value) => {
84
+ clearTimeout(timer);
85
+ resolveIt(value);
86
+ }, (error) => {
87
+ clearTimeout(timer);
88
+ rejectIt(error);
89
+ });
90
+ });
91
+ }
92
+ /** `host.open`'s (or `view.open`'s) `remote`, reduced to its fields; `undefined` when there is none. */
93
+ function remotePageOf(remote) {
94
+ return remote && typeof remote.type === 'string' && Array.isArray(remote.origins) ? { type: remote.type, origins: remote.origins.filter((o) => typeof o === 'string') } : undefined;
95
+ }
96
+ /** What the `open` callback (and `view`) gets for a `host.open` (or `view.open`) answer. */
97
+ function openRequestOf(params, remote) {
98
+ return {
99
+ session: params.session ?? null,
100
+ url: params.url,
101
+ viewUrl: params.view_url,
102
+ embedUrl: params.embed_url || params.view_url,
103
+ ...(params.view ? { view: params.view } : {}),
104
+ ...(params.title !== undefined ? { title: params.title } : {}),
105
+ ...(remote?.origins.length ? { remote } : {}),
106
+ };
107
+ }
108
+ /** The wake to hand to the `wake` callback for one inbox message, or `null` when it is not a whole wake. */
109
+ function inboxWake(message, ref) {
110
+ if (message.kind !== 'wake' || typeof message.text !== 'string' || !message.text || !message.source || typeof message.source !== 'object')
111
+ return null;
112
+ return {
113
+ session: ref.session ?? null,
114
+ workspace: ref.workspace ?? null,
115
+ artifact: message.artifact ?? message.source.url ?? '',
116
+ artifactId: message.artifactId ?? message.source.artifactId ?? '',
117
+ text: message.text,
118
+ source: message.source,
119
+ };
120
+ }
121
+ /**
122
+ * Connects an agent app to the daemon. Resolves once the first connection attempt is over: when it failed (no daemon
123
+ * and `autoStart: false`, say), the harness keeps trying in the background and calls connect on demand.
124
+ *
125
+ * What `hello` says follows from the options: `caps.wake` when there is a `wake` callback, `caps.open` when there is
126
+ * an `open` callback (`{ embed, origins }` with `embed`), `caps.commands` from `commands`, `caps.agentName` from
127
+ * `agentName`, `caps.sample` from `sample`, `caps.mcp` from `mcp`, `caps.sessions.start` when there is a `startSession`
128
+ * callback (and `caps.sessions.models` when there is a `sessionModels` one too); `options.caps` adds the rest (`tools`, `library`, `wake.resume`, `wake.mode`). The profile carries
129
+ * `agentName`, `commands`, `policy`, `rules`, the caps and `options.profile`.
130
+ *
131
+ * `wake` answers how it handed the message over: `resumed` (started a turn), `delivered` (put it into the running
132
+ * turn), `drafted` (put it in the session's draft, for a harness whose `caps.wake.mode` is `draft`), `held` (left in
133
+ * the inbox: the app starts the session's turn itself, so the daemon does not nudge it; sent as `failed` to a daemon
134
+ * without the `wake.held` feature) or `failed` (the daemon keeps it for later). It may name the session that took it instead: `{ status, session }`. A callback that
135
+ * throws, or takes longer than `wakeTimeoutMs`, answers `failed`.
136
+ */
137
+ export async function createHarness(options) {
138
+ const log = options.log ?? (() => undefined);
139
+ const caps = capsOf(options);
140
+ // A remote type's page passes this gate before `open` sees it (the policy `hello` said; `ask` by default).
141
+ const remoteOk = remoteGate(typeof caps.open === 'object' && caps.open.remote ? caps.open.remote : remotePolicyOf(options.embed?.remote), options.allowRemote);
142
+ const profile = profileOf(options, caps);
143
+ const daemon = {
144
+ ...options.daemon,
145
+ ...(options.home ? { home: options.home } : {}),
146
+ };
147
+ // The harness's runtime is one candidate: the newest compatible runtime on this computer starts (`runtimes.ts`);
148
+ // `daemon.bin` and $OPEN_ARTIFACTS_DAEMON_BIN override the choice.
149
+ if (!daemon.bin && !daemon.own && options.runtime?.dir)
150
+ daemon.own = { dir: options.runtime.dir.replace(/[\\/]+$/, ''), version: options.runtime.version };
151
+ if (!daemon.version && options.runtime?.version)
152
+ daemon.version = options.runtime.version;
153
+ const listeners = {
154
+ artifact: new Set(),
155
+ event: new Set(),
156
+ state: new Set(),
157
+ shell: new Set(),
158
+ };
159
+ const emit = (kind, value) => {
160
+ for (const listener of listeners[kind]) {
161
+ try {
162
+ listener(value);
163
+ }
164
+ catch (error) {
165
+ log(`open-artifacts ${kind} listener: ${error?.message ?? error}`);
166
+ }
167
+ }
168
+ };
169
+ /**
170
+ * Inbox messages the `wake` callback did not take on a re-attach, when the daemon could not take them back
171
+ * (`inbox.return`): the session's next call or attach returns them.
172
+ */
173
+ const leftovers = new Map();
174
+ const sessionKey = (ref) => (ref.session ? `s:${ref.session}` : `w:${ref.workspace ?? ''}`);
175
+ const timeout = options.wakeTimeoutMs ?? WAKE_TIMEOUT_MS;
176
+ /** Asks the `wake` callback; never throws. */
177
+ const wake = async (params) => {
178
+ if (!options.wake)
179
+ return { status: 'failed' };
180
+ try {
181
+ // An older daemon's wake has no `reason` or `from`: they are read from its text, so the callback always has them.
182
+ const filled = { ...params, source: wakeSourceOf(params.source, params.text) };
183
+ const answer = await within(Promise.resolve(options.wake(filled)), timeout, () => {
184
+ log(`open-artifacts wake for ${params.session ?? params.workspace}: no answer in ${timeout} ms`);
185
+ return 'failed';
186
+ });
187
+ const result = typeof answer === 'string' ? { status: answer } : answer;
188
+ if (!result || typeof result.status !== 'string')
189
+ return { status: 'failed' };
190
+ // A daemon without `wake.held` would not know the answer: `failed` keeps the message in the inbox there too.
191
+ if (result.status === 'held' && !client.features.includes('wake.held'))
192
+ return { status: 'failed' };
193
+ return { status: result.status, ...(typeof result.session === 'string' && result.session ? { session: result.session } : {}) };
194
+ }
195
+ catch (error) {
196
+ log(`open-artifacts wake for ${params.session ?? params.workspace}: ${error?.message ?? error}`);
197
+ return { status: 'failed' };
198
+ }
199
+ };
200
+ /** Hands an attach's inbox to `wake`; returns what it did not take. */
201
+ const handOver = async (ref, inbox) => {
202
+ const left = [];
203
+ for (const message of inbox ?? []) {
204
+ const params = options.wake ? inboxWake(message, ref) : null;
205
+ const status = params ? (await wake(params)).status : 'failed';
206
+ // `held`: the app starts the session's turn itself, which takes the inbox; the message goes back there.
207
+ if (status === 'failed' || status === 'held')
208
+ left.push(message);
209
+ }
210
+ return left;
211
+ };
212
+ // ---- sample rounds ----
213
+ /** The rounds running now, by id: aborting one cancels it, and a cancelled one is never answered. */
214
+ const rounds = new Map();
215
+ /** Aborts round `id` (its signal's reason is the standard `AbortError`, as `fetch` and model SDKs expect). */
216
+ const cancelRound = (id, why) => {
217
+ const round = rounds.get(id);
218
+ if (!round || round.cancelled)
219
+ return;
220
+ round.cancelled = true;
221
+ log(`open-artifacts sample ${id}: ${why}`);
222
+ round.controller.abort();
223
+ };
224
+ const cancelAllRounds = (why) => {
225
+ for (const id of [...rounds.keys()])
226
+ cancelRound(id, why);
227
+ };
228
+ /** Answers `sample.create`: calls `run`, streams its text as `sample.delta`, maps what it throws. */
229
+ const sampleCreate = async (params) => {
230
+ const sample = options.sample;
231
+ const id = params?.id;
232
+ if (typeof id !== 'string' || !id)
233
+ throw new OpenArtifactsError('invalid_argument', 'sample.create: id is required.');
234
+ if (!Array.isArray(params.turns))
235
+ throw new OpenArtifactsError('invalid_argument', 'sample.create: turns is an array.');
236
+ if (rounds.has(id))
237
+ throw new OpenArtifactsError('invalid_argument', `sample.create: round ${id} is already running.`);
238
+ const round = { controller: new AbortController(), cancelled: false };
239
+ rounds.set(id, round);
240
+ let open = true;
241
+ const stream = sample.caps.stream === true;
242
+ const onText = (delta) => {
243
+ if (!stream || !open || round.cancelled || typeof delta !== 'string' || !delta)
244
+ return;
245
+ client.notify('sample.delta', { id, text: delta });
246
+ };
247
+ try {
248
+ const result = await sample.run(params, { onText, signal: round.controller.signal });
249
+ if (round.cancelled)
250
+ return NO_REPLY;
251
+ if (!result || typeof result.text !== 'string' || !ROUND_STOPS.includes(result.stop)) {
252
+ throw new OpenArtifactsError('error', 'sample.create: run resolved without { text, stop }.');
253
+ }
254
+ return {
255
+ text: result.text,
256
+ stop: result.stop,
257
+ ...(Array.isArray(result.toolCalls) && result.toolCalls.length ? { toolCalls: result.toolCalls } : {}),
258
+ ...(typeof result.model === 'string' && result.model ? { model: result.model } : {}),
259
+ ...(result.usage && typeof result.usage.input === 'number' && typeof result.usage.output === 'number' ? { usage: { input: result.usage.input, output: result.usage.output } } : {}),
260
+ };
261
+ }
262
+ catch (error) {
263
+ if (round.cancelled)
264
+ return NO_REPLY;
265
+ const code = error?.code;
266
+ const message = error?.message || String(error);
267
+ log(`open-artifacts sample ${id}: ${message}`);
268
+ if (typeof code === 'string' && SAMPLE_REFUSAL_CODES.includes(code))
269
+ throw new OpenArtifactsError(code, message);
270
+ throw new OpenArtifactsError('error', message);
271
+ }
272
+ finally {
273
+ open = false;
274
+ rounds.delete(id);
275
+ }
276
+ };
277
+ /** Answers `session.start`: asks the `startSession` callback; never throws. */
278
+ const startSession = async (params) => {
279
+ const artifact = params?.artifact;
280
+ try {
281
+ const picked = (value) => (typeof value === 'string' && value ? value : undefined);
282
+ const model = picked(params?.model);
283
+ // An effort is one of a model's: without a model there is none to pass on.
284
+ const effort = model ? picked(params?.effort) : undefined;
285
+ const answer = await options.startSession({ text: String(params?.text ?? ''), artifact, ...(model ? { model } : {}), ...(effort ? { effort } : {}) });
286
+ if (answer === false)
287
+ return { started: false };
288
+ const session = answer && typeof answer.session === 'string' && answer.session ? answer.session : undefined;
289
+ const workspace = answer && typeof answer.workspace === 'string' && answer.workspace ? answer.workspace : undefined;
290
+ return { started: true, ...(session ? { session } : {}), ...(workspace ? { workspace } : {}) };
291
+ }
292
+ catch (error) {
293
+ log(`open-artifacts session.start for ${artifact?.url ?? 'an artifact'}: ${error?.message ?? error}`);
294
+ return { started: false };
295
+ }
296
+ };
297
+ /** Answers `session.models`: asks the `sessionModels` callback; never throws (no models: the app's default). */
298
+ const sessionModels = async () => {
299
+ try {
300
+ const answer = await options.sessionModels();
301
+ return answer && typeof answer === 'object' && Array.isArray(answer.models) ? answer : { models: [] };
302
+ }
303
+ catch (error) {
304
+ log(`open-artifacts session.models: ${error?.message ?? error}`);
305
+ return { models: [] };
306
+ }
307
+ };
308
+ // ---- lent MCP servers ----
309
+ const lender = options.mcp ? mcpLender(options.mcp, log) : null;
310
+ // ---- artifacts ----
311
+ const known = new Map();
312
+ let since = Date.now();
313
+ const queued = new Map();
314
+ const chains = new Map();
315
+ const lookup = async (id) => {
316
+ const state = client.state ?? (await client.connect().then(() => client.state));
317
+ if (!state)
318
+ return null;
319
+ const record = await api(state, LIBRARY_ROUTES.artifact, undefined, { query: { id } }).catch(() => null);
320
+ return record && typeof record.id === 'string' && record.id === id ? record : null;
321
+ };
322
+ const toArtifact = (record) => {
323
+ const base = client.state?.url ?? '';
324
+ return {
325
+ url: record.url || artifactUrl(record.id),
326
+ id: record.id,
327
+ title: record.title,
328
+ type: record.type,
329
+ // The local Shell, also for a published artifact (its site's address is `publicUrl`).
330
+ viewUrl: base ? `${base}/a/${encodeURIComponent(record.id)}` : record.view_url || null,
331
+ publicUrl: record.remote?.url || null,
332
+ thumbnail: record.thumbnail ? `${base}/api/open-artifacts.${LIBRARY_ROUTES.thumbnail}?id=${encodeURIComponent(record.id)}&v=${encodeURIComponent(record.thumbnail)}` : null,
333
+ updatedAt: record.updatedAt,
334
+ };
335
+ };
336
+ const report = async (id) => {
337
+ const item = queued.get(id);
338
+ queued.delete(id);
339
+ if (!item)
340
+ return;
341
+ const extra = { ...(item.author ? { author: item.author } : {}), ...(item.paths.size ? { paths: [...item.paths] } : {}) };
342
+ if (item.removed) {
343
+ const last = known.get(id);
344
+ known.delete(id);
345
+ const artifact = last ? { ...last, viewUrl: null, publicUrl: null } : { url: artifactUrl(id), id, title: '', type: '', viewUrl: null, publicUrl: null, thumbnail: null, updatedAt: new Date().toISOString() };
346
+ emit('artifact', { session: null, workspace: null, artifact, change: 'removed', ...extra });
347
+ return;
348
+ }
349
+ const record = await lookup(id);
350
+ if (!record)
351
+ return;
352
+ const artifact = toArtifact(record);
353
+ // The first report of an artifact made since the kit started following is its creation.
354
+ const change = !known.has(id) && Date.parse(record.createdAt) >= since - 1000 ? 'created' : 'updated';
355
+ known.set(id, artifact);
356
+ const owner = record.owner && record.owner.harness === options.harness ? record.owner : null;
357
+ emit('artifact', { session: owner?.session ?? null, workspace: owner?.workspace ?? null, artifact, change, ...extra });
358
+ };
359
+ const onEvent = (event) => {
360
+ emit('event', event);
361
+ if (event.type !== 'artifacts/changed' || !listeners.artifact.size)
362
+ return;
363
+ const waiting = queued.get(event.id);
364
+ if (waiting) {
365
+ // Not looked up yet: one report covers both.
366
+ waiting.removed ||= !!event.removed;
367
+ if (event.author)
368
+ waiting.author = event.author;
369
+ for (const path of event.paths ?? [])
370
+ waiting.paths.add(path);
371
+ return;
372
+ }
373
+ queued.set(event.id, { removed: !!event.removed, ...(event.author ? { author: event.author } : {}), paths: new Set(event.paths ?? []) });
374
+ const next = (chains.get(event.id) ?? Promise.resolve()).then(() => report(event.id)).catch((error) => log(`open-artifacts artifact ${event.id}: ${error.message}`));
375
+ chains.set(event.id, next);
376
+ void next.finally(() => {
377
+ if (chains.get(event.id) === next)
378
+ chains.delete(event.id);
379
+ });
380
+ };
381
+ // ---- the connection ----
382
+ const client = new HarnessClient({
383
+ harness: options.harness,
384
+ caps,
385
+ hello: { kit: { ...KIT }, ...(profile ? { profile } : {}), ...(options.runtime ? { runtime: options.runtime } : {}) },
386
+ daemon,
387
+ ...(options.autoStart !== undefined ? { autoStart: options.autoStart } : {}),
388
+ reconnect: { minMs: options.reconnect?.minMs ?? 1000, maxMs: options.reconnect?.maxMs ?? 30_000 },
389
+ log,
390
+ onEvent,
391
+ onState: (state) => {
392
+ // A round's answer could only go to the connection it came on, which is gone: stop them all.
393
+ if (state !== 'connected')
394
+ cancelAllRounds('The connection to the daemon dropped.');
395
+ if (state !== 'connected')
396
+ lender?.cancelAll('The connection to the daemon dropped.');
397
+ emit('state', state);
398
+ },
399
+ onNotification: (method, params) => {
400
+ if (method === 'sample.cancel' && params && typeof params.id === 'string')
401
+ cancelRound(params.id, 'The daemon cancelled the round.');
402
+ if (method === 'mcp.cancel')
403
+ lender?.onCancel(params);
404
+ },
405
+ onReattach: async (params, result) => {
406
+ const left = await handOver(params, result.inbox);
407
+ if (!left.length)
408
+ return;
409
+ const who = params.session ?? params.workspace;
410
+ // Back to the daemon, which keeps them on disk for the session's next tool call, wait or attach.
411
+ if (client.features.includes('inbox.return')) {
412
+ try {
413
+ await client.request('inbox.return', { session: params.session ?? null, workspace: params.workspace ?? null, messages: left });
414
+ log(`open-artifacts: ${left.length} message(s) for ${who} were not taken; they wait in its inbox again`);
415
+ return;
416
+ }
417
+ catch (error) {
418
+ log(`open-artifacts inbox.return for ${who}: ${error?.message ?? error}`);
419
+ }
420
+ }
421
+ const key = sessionKey(params);
422
+ leftovers.set(key, [...(leftovers.get(key) ?? []), ...left]);
423
+ log(`open-artifacts: ${left.length} message(s) for ${who} were not taken; the session's next call or attach returns them`);
424
+ },
425
+ handlers: {
426
+ ...(options.wake ? { 'wake.deliver': (params) => wake(params) } : {}),
427
+ ...(options.sample ? { 'sample.create': sampleCreate } : {}),
428
+ ...(lender ? lender.handlers : {}),
429
+ ...(options.startSession ? { 'session.start': startSession } : {}),
430
+ ...(options.startSession && options.sessionModels ? { 'session.models': sessionModels } : {}),
431
+ 'shell.event': (params) => {
432
+ emit('shell', params);
433
+ return { ok: true };
434
+ },
435
+ ...(options.open
436
+ ? {
437
+ 'host.open': async (params) => {
438
+ const remote = remotePageOf(params.remote);
439
+ try {
440
+ if (!(await remoteOk(remote, params.title))) {
441
+ log(`open-artifacts open ${params.url}: a page from ${remote.origins.join(', ')} (another computer) was not allowed`);
442
+ return { opened: false };
443
+ }
444
+ }
445
+ catch {
446
+ return { opened: false };
447
+ }
448
+ const request = openRequestOf(params, remote);
449
+ try {
450
+ return { opened: (await options.open(request)) !== false };
451
+ }
452
+ catch (error) {
453
+ log(`open-artifacts open ${params.url}: ${error?.message ?? error}`);
454
+ return { opened: false };
455
+ }
456
+ },
457
+ }
458
+ : {}),
459
+ },
460
+ });
461
+ // Events are only asked for while someone listens.
462
+ await client.subscribe(false);
463
+ try {
464
+ await client.connect();
465
+ }
466
+ catch (error) {
467
+ log(`open-artifacts connect: ${error?.message ?? error}`);
468
+ client.reconnect();
469
+ }
470
+ /** A restart under way: a second call waits for the same one. */
471
+ let restarting = null;
472
+ /** Restart, stop and start run one after another. */
473
+ let lifecycle = Promise.resolve();
474
+ const inTurn = (run) => {
475
+ const next = lifecycle.then(run, run);
476
+ lifecycle = next.catch(() => undefined);
477
+ return next;
478
+ };
479
+ const homeOf = () => daemon.home ?? envValue(daemon.env, 'OPEN_ARTIFACTS_HOME') ?? undefined;
480
+ const withoutToken = ({ token: _token, ...state }) => state;
481
+ /** The other connections of a running daemon (`harnesses`), this harness's own left out; `null` when unreadable. */
482
+ const peersOf = async (state) => {
483
+ try {
484
+ const answer = await api(state, LIBRARY_ROUTES.harnesses, undefined, { signal: AbortSignal.timeout(3000) });
485
+ if (!Array.isArray(answer?.adapters))
486
+ return null;
487
+ const own = client.hello?.connection;
488
+ const titles = new Map((Array.isArray(answer.harnesses) ? answer.harnesses : []).map((h) => [h.name, h.title]));
489
+ return answer.adapters
490
+ .filter((a) => a && typeof a.id === 'string' && a.id !== own)
491
+ .map((a) => ({ connection: a.id, harness: a.harness, title: titles.get(a.harness) || a.harness, polling: a.polling === true, sessions: Array.isArray(a.sessions) ? a.sessions.length : 0 }));
492
+ }
493
+ catch (error) {
494
+ log(`open-artifacts harnesses: ${error?.message ?? error}`);
495
+ return null;
496
+ }
497
+ };
498
+ /** Connects if needed, then throws `unsupported` unless the daemon lists `feature`. */
499
+ const needs = async (feature, method) => {
500
+ if (!client.connected)
501
+ await client.connect();
502
+ if (!client.features.includes(feature)) {
503
+ throw new OpenArtifactsError('unsupported', `${method} needs feature ${feature}, which daemon ${client.hello?.daemon ?? '(unknown)'} does not list.`, { fix: 'Update the Open Artifacts runtime this computer runs.' });
504
+ }
505
+ };
506
+ const harness = {
507
+ client,
508
+ get connected() {
509
+ return client.connected;
510
+ },
511
+ get features() {
512
+ return client.features;
513
+ },
514
+ ready: () => {
515
+ client.resume();
516
+ return client.connect();
517
+ },
518
+ async attach(params) {
519
+ const result = await client.attach(params);
520
+ const key = sessionKey(params);
521
+ const earlier = leftovers.get(key) ?? [];
522
+ leftovers.delete(key);
523
+ return { key: result.key, inbox: [...earlier, ...(await handOver(params, result.inbox))] };
524
+ },
525
+ async status(session, status) {
526
+ await client.status({ ...sessionParams(session), status });
527
+ },
528
+ async detach(session) {
529
+ leftovers.delete(sessionKey(sessionParams(session)));
530
+ await client.detach(sessionParams(session));
531
+ },
532
+ async rename(session, title) {
533
+ await client.rename({ ...sessionParams(session), title });
534
+ },
535
+ async tools() {
536
+ if (client.connected) {
537
+ try {
538
+ return await client.tools();
539
+ }
540
+ catch (error) {
541
+ log(`open-artifacts tools.list: ${error?.message ?? error}`);
542
+ }
543
+ }
544
+ return TOOL_DEFINITIONS.map((tool) => ({ ...tool }));
545
+ },
546
+ async call(name, args, caller) {
547
+ // What an older daemon could not take back goes along, as the daemon adds what waited in the inbox.
548
+ const key = caller && (caller.session || caller.workspace) ? sessionKey(caller) : null;
549
+ const held = key ? leftovers.get(key) : undefined;
550
+ if (!key || !held?.length)
551
+ return client.callTool(name, args, caller);
552
+ leftovers.delete(key);
553
+ const texts = held.map((message) => message.text);
554
+ // A wait would only return what is there: these are.
555
+ if (name === 'ArtifactComments' && args.action === 'wait')
556
+ return { messages: texts };
557
+ let result;
558
+ try {
559
+ result = await client.callTool(name, args, caller);
560
+ }
561
+ catch (error) {
562
+ leftovers.set(key, [...held, ...(leftovers.get(key) ?? [])]);
563
+ throw error;
564
+ }
565
+ const more = Array.isArray(result.messages) ? result.messages : [];
566
+ return { ...result, messages: [...texts, ...more] };
567
+ },
568
+ wrote: (paths, caller) => client.request('agent.wrote', { paths, ...(caller ? { caller } : {}) }),
569
+ open: (url, opts) => client.request('artifact.open', { url, ...(opts ? { caller: opts } : {}) }),
570
+ owns: ownsCall,
571
+ async viewUrl(url) {
572
+ const id = artifactIdOf(url);
573
+ if (!id)
574
+ throw new OpenArtifactsError('invalid_argument', `Not an artifact: ${url}`);
575
+ const record = await lookup(id);
576
+ return record ? toArtifact(record).viewUrl : null;
577
+ },
578
+ async publicUrl(url) {
579
+ const id = artifactIdOf(url);
580
+ if (!id)
581
+ throw new OpenArtifactsError('invalid_argument', `Not an artifact: ${url}`);
582
+ const record = await lookup(id);
583
+ return record?.remote?.url || null;
584
+ },
585
+ embedOrigins: () => client.request('embed.origins', {}),
586
+ async view(url) {
587
+ await needs('view.open', 'view');
588
+ const params = await client.request('view.open', { url });
589
+ const remote = remotePageOf(params.remote);
590
+ if (remote && !(await remoteOk(remote, params.title).catch(() => false))) {
591
+ throw new OpenArtifactsError('not_granted', `The page of ${params.url} comes from ${remote.origins.join(', ')} (another computer), which this app does not let in.`);
592
+ }
593
+ return openRequestOf(params, remote);
594
+ },
595
+ async shellCommand(view, command) {
596
+ await client.request('shell.command', { view, command });
597
+ },
598
+ context: (url, opts) => readContext(client, url, opts),
599
+ contextBlock,
600
+ async saveThumbnail(url, jpeg) {
601
+ const id = artifactIdOf(url);
602
+ if (!id)
603
+ throw new OpenArtifactsError('invalid_argument', `Not an artifact: ${url}`);
604
+ const state = client.state ?? (await client.connect().then(() => client.state));
605
+ if (!state)
606
+ throw new OpenArtifactsError('no_daemon', 'Not connected to the daemon.');
607
+ const target = new URL(`/api/open-artifacts.${LIBRARY_ROUTES.thumbnail}`, state.url);
608
+ target.searchParams.set('id', id);
609
+ const response = await fetch(target, { method: 'POST', headers: { Authorization: `Bearer ${state.token}`, 'Content-Type': 'image/jpeg' }, body: new Blob([new Uint8Array(jpeg)]) });
610
+ if (!response.ok) {
611
+ const body = (await response.json().catch(() => ({})));
612
+ throw new OpenArtifactsError(body.code ?? 'error', body.message ?? `thumbnail: HTTP ${response.status}`);
613
+ }
614
+ },
615
+ on(kind, listener) {
616
+ const set = listeners[kind];
617
+ const wantsEvents = () => listeners.artifact.size + listeners.event.size > 0;
618
+ const before = wantsEvents();
619
+ set.add(listener);
620
+ if (!before && wantsEvents()) {
621
+ since = Date.now();
622
+ void client.subscribe(true).catch((error) => log(`open-artifacts subscribe: ${error.message}`));
623
+ }
624
+ return () => {
625
+ if (!set.delete(listener))
626
+ return;
627
+ if (kind !== 'state' && kind !== 'shell' && !wantsEvents())
628
+ void client.subscribe(false).catch(() => undefined);
629
+ };
630
+ },
631
+ async installSkill(opts) {
632
+ // With an `open` handler the app shows pages itself: the kit's own rendering says so, as the daemon's does.
633
+ const withOpens = options.open && opts.opens === undefined ? { ...opts, opens: 'host' } : opts;
634
+ return (await keepSkillInstalled(client, withOpens, (listener) => harness.on('state', listener), log)).result;
635
+ },
636
+ commands: (opts) => commands(client, opts),
637
+ runtime: {
638
+ async status() {
639
+ await needs('runtime.update', 'runtime.status');
640
+ return client.request('runtime.status', {});
641
+ },
642
+ async update(version) {
643
+ await needs('runtime.update', 'runtime.update');
644
+ return client.request('runtime.update', version ? { version } : {});
645
+ },
646
+ },
647
+ daemon: {
648
+ async restart() {
649
+ if (!restarting) {
650
+ restarting = inTurn(() => client.across(() => restartDaemon(daemon)))
651
+ .then(({ result }) => withoutToken(result.daemon))
652
+ .finally(() => (restarting = null));
653
+ }
654
+ return restarting;
655
+ },
656
+ stop: () => inTurn(async () => {
657
+ const running = await readDaemon(homeOf());
658
+ const others = running ? await peersOf(running) : null;
659
+ const stopped = await client.halt(() => stopDaemon({ home: homeOf(), ...(daemon.env ? { env: daemon.env } : {}) }));
660
+ return { stopped: stopped ? withoutToken(stopped) : null, others };
661
+ }),
662
+ start: () => inTurn(async () => {
663
+ if (client.connected && !client.stopped && client.state)
664
+ return withoutToken(client.state);
665
+ const { result } = await client.across(() => ensureDaemon(daemon));
666
+ return withoutToken(client.state ?? result);
667
+ }),
668
+ get stopped() {
669
+ return client.stopped;
670
+ },
671
+ },
672
+ close: () => {
673
+ cancelAllRounds('The harness was closed.');
674
+ client.close();
675
+ },
676
+ };
677
+ return harness;
678
+ }