@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/src/harness.js ADDED
@@ -0,0 +1,426 @@
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, OpenArtifactError, TOOL_DEFINITIONS, artifactIdOf, artifactUrl, wakeSourceOf, } from '@open-artifact/protocol';
10
+ import { HarnessClient } from "./client.js";
11
+ import { api } from "./daemon.js";
12
+ import { commands, keepSkillInstalled } from "./skill.js";
13
+ import { contextBlock, readContext } from "./context.js";
14
+ import { remoteGate, remotePolicyOf } from "./embed/remote.js";
15
+ import pkg from '../package.json' with { type: 'json' };
16
+ /** This kit's name and version, said in `hello` (`kit`). */
17
+ export const KIT = { name: '@open-artifact/harness-kit', version: pkg.version ?? '0.0.0' };
18
+ /** Default of {@link HarnessOptions.wakeTimeoutMs}: under the daemon's own 30 s wait for an answer. */
19
+ const WAKE_TIMEOUT_MS = 25_000;
20
+ const sessionParams = (session) => (typeof session === 'string' ? { session } : session);
21
+ /** A string that is an Open Artifact link. */
22
+ const isLink = (value) => typeof value === 'string' && value.trim().startsWith('open-artifact://');
23
+ /** Whether a tool call is about an Open Artifact link (`url` or `type_url`), so a harness with its own tools can route it. */
24
+ export function ownsCall(args) {
25
+ return !!args && (isLink(args.url) || isLink(args.type_url));
26
+ }
27
+ /** The caps `hello` says: `options.caps`, plus what the callbacks and options imply. */
28
+ function capsOf(options) {
29
+ const caps = { ...options.caps };
30
+ if (options.agentName && !caps.agentName)
31
+ caps.agentName = options.agentName;
32
+ // Without a callback the adapter cannot answer the call, so it does not claim it.
33
+ if (options.wake)
34
+ caps.wake = caps.wake ?? {};
35
+ else
36
+ delete caps.wake;
37
+ if (options.open) {
38
+ if (caps.open === undefined || caps.open === true)
39
+ caps.open = options.embed ? { embed: options.embed.mode ?? 'frame', origins: [...options.embed.origins], remote: remotePolicyOf(options.embed.remote) } : true;
40
+ }
41
+ else
42
+ delete caps.open;
43
+ if (options.commands?.length && !caps.commands)
44
+ caps.commands = { names: [...options.commands] };
45
+ return caps;
46
+ }
47
+ /** The profile `hello` reports, or `undefined` when there is nothing to say. */
48
+ function profileOf(options, caps) {
49
+ const { nudge: _nudge, ...given } = (options.profile ?? {});
50
+ const profile = {
51
+ ...given,
52
+ ...(options.agentName ? { agentName: options.agentName } : {}),
53
+ ...(options.commands?.length ? { commands: [...options.commands] } : {}),
54
+ ...(options.policy ? { policy: options.policy } : {}),
55
+ ...(options.rules ? { rules: options.rules } : {}),
56
+ ...(Object.keys(caps).length ? { caps } : {}),
57
+ };
58
+ return Object.keys(profile).length ? profile : undefined;
59
+ }
60
+ /** Runs `work`, or gives `fallback` when it takes longer than `ms`. */
61
+ function within(work, ms, fallback) {
62
+ return new Promise((resolveIt, rejectIt) => {
63
+ const timer = setTimeout(() => resolveIt(fallback()), ms);
64
+ timer.unref?.();
65
+ work.then((value) => {
66
+ clearTimeout(timer);
67
+ resolveIt(value);
68
+ }, (error) => {
69
+ clearTimeout(timer);
70
+ rejectIt(error);
71
+ });
72
+ });
73
+ }
74
+ /** The wake to hand to the `wake` callback for one inbox message, or `null` when it is not a whole wake. */
75
+ function inboxWake(message, ref) {
76
+ if (message.kind !== 'wake' || typeof message.text !== 'string' || !message.text || !message.source || typeof message.source !== 'object')
77
+ return null;
78
+ return {
79
+ session: ref.session ?? null,
80
+ workspace: ref.workspace ?? null,
81
+ artifact: message.artifact ?? message.source.url ?? '',
82
+ artifactId: message.artifactId ?? message.source.artifactId ?? '',
83
+ text: message.text,
84
+ source: message.source,
85
+ };
86
+ }
87
+ /**
88
+ * Connects an agent app to the daemon. Resolves once the first connection attempt is over: when it failed (no daemon
89
+ * and `autoStart: false`, say), the harness keeps trying in the background and calls connect on demand.
90
+ *
91
+ * What `hello` says follows from the options: `caps.wake` when there is a `wake` callback, `caps.open` when there is
92
+ * an `open` callback (`{ embed, origins }` with `embed`), `caps.commands` from `commands`, `caps.agentName` from
93
+ * `agentName`; `options.caps` adds the rest (`tools`, `library`, `wake.resume`, `wake.mode`). The profile carries
94
+ * `agentName`, `commands`, `policy`, `rules`, the caps and `options.profile`.
95
+ *
96
+ * `wake` answers how it handed the message over: `resumed` (started a turn), `delivered` (put it into the running
97
+ * turn), `drafted` (put it in the session's draft, for a harness whose `caps.wake.mode` is `draft`) or `failed` (the
98
+ * daemon keeps it for later). It may name the session that took it instead: `{ status, session }`. A callback that
99
+ * throws, or takes longer than `wakeTimeoutMs`, answers `failed`.
100
+ */
101
+ export async function createHarness(options) {
102
+ const log = options.log ?? (() => undefined);
103
+ const caps = capsOf(options);
104
+ // A remote type's page passes this gate before `open` sees it (the policy `hello` said; `ask` by default).
105
+ const remoteOk = remoteGate(typeof caps.open === 'object' && caps.open.remote ? caps.open.remote : remotePolicyOf(options.embed?.remote), options.allowRemote);
106
+ const profile = profileOf(options, caps);
107
+ const daemon = {
108
+ ...options.daemon,
109
+ ...(options.home ? { home: options.home } : {}),
110
+ };
111
+ // The harness's runtime is one candidate: the newest compatible runtime on this computer starts (`runtimes.ts`);
112
+ // `daemon.bin` and $OPEN_ARTIFACT_DAEMON_BIN override the choice.
113
+ if (!daemon.bin && !daemon.own && options.runtime?.dir)
114
+ daemon.own = { dir: options.runtime.dir.replace(/[\\/]+$/, ''), version: options.runtime.version };
115
+ if (!daemon.version && options.runtime?.version)
116
+ daemon.version = options.runtime.version;
117
+ const listeners = {
118
+ artifact: new Set(),
119
+ event: new Set(),
120
+ state: new Set(),
121
+ shell: new Set(),
122
+ };
123
+ const emit = (kind, value) => {
124
+ for (const listener of listeners[kind]) {
125
+ try {
126
+ listener(value);
127
+ }
128
+ catch (error) {
129
+ log(`open-artifact ${kind} listener: ${error?.message ?? error}`);
130
+ }
131
+ }
132
+ };
133
+ /** Inbox messages the `wake` callback did not take on a re-attach, handed back by the session's next attach. */
134
+ const leftovers = new Map();
135
+ const sessionKey = (ref) => (ref.session ? `s:${ref.session}` : `w:${ref.workspace ?? ''}`);
136
+ const timeout = options.wakeTimeoutMs ?? WAKE_TIMEOUT_MS;
137
+ /** Asks the `wake` callback; never throws. */
138
+ const wake = async (params) => {
139
+ if (!options.wake)
140
+ return { status: 'failed' };
141
+ try {
142
+ // An older daemon's wake has no `reason` or `from`: they are read from its text, so the callback always has them.
143
+ const filled = { ...params, source: wakeSourceOf(params.source, params.text) };
144
+ const answer = await within(Promise.resolve(options.wake(filled)), timeout, () => {
145
+ log(`open-artifact wake for ${params.session ?? params.workspace}: no answer in ${timeout} ms`);
146
+ return 'failed';
147
+ });
148
+ const result = typeof answer === 'string' ? { status: answer } : answer;
149
+ if (!result || typeof result.status !== 'string')
150
+ return { status: 'failed' };
151
+ return { status: result.status, ...(typeof result.session === 'string' && result.session ? { session: result.session } : {}) };
152
+ }
153
+ catch (error) {
154
+ log(`open-artifact wake for ${params.session ?? params.workspace}: ${error?.message ?? error}`);
155
+ return { status: 'failed' };
156
+ }
157
+ };
158
+ /** Hands an attach's inbox to `wake`; returns what it did not take. */
159
+ const handOver = async (ref, inbox) => {
160
+ const left = [];
161
+ for (const message of inbox ?? []) {
162
+ const params = options.wake ? inboxWake(message, ref) : null;
163
+ if (!params || (await wake(params)).status === 'failed')
164
+ left.push(message);
165
+ }
166
+ return left;
167
+ };
168
+ // ---- artifacts ----
169
+ const known = new Map();
170
+ let since = Date.now();
171
+ const queued = new Map();
172
+ const chains = new Map();
173
+ const lookup = async (id) => {
174
+ const state = client.state ?? (await client.connect().then(() => client.state));
175
+ if (!state)
176
+ return null;
177
+ const record = await api(state, LIBRARY_ROUTES.artifact, undefined, { query: { id } }).catch(() => null);
178
+ return record && typeof record.id === 'string' && record.id === id ? record : null;
179
+ };
180
+ const toArtifact = (record) => {
181
+ const base = client.state?.url ?? '';
182
+ return {
183
+ url: record.url || artifactUrl(record.id),
184
+ id: record.id,
185
+ title: record.title,
186
+ type: record.type,
187
+ // The local Shell, also for a published artifact (its site's address is `publicUrl`).
188
+ viewUrl: base ? `${base}/a/${encodeURIComponent(record.id)}` : record.view_url || null,
189
+ publicUrl: record.remote?.url || null,
190
+ thumbnail: record.thumbnail ? `${base}/api/open-artifact.${LIBRARY_ROUTES.thumbnail}?id=${encodeURIComponent(record.id)}&v=${encodeURIComponent(record.thumbnail)}` : null,
191
+ updatedAt: record.updatedAt,
192
+ };
193
+ };
194
+ const report = async (id) => {
195
+ const item = queued.get(id);
196
+ queued.delete(id);
197
+ if (!item)
198
+ return;
199
+ const extra = { ...(item.author ? { author: item.author } : {}), ...(item.paths.size ? { paths: [...item.paths] } : {}) };
200
+ if (item.removed) {
201
+ const last = known.get(id);
202
+ known.delete(id);
203
+ const artifact = last ? { ...last, viewUrl: null, publicUrl: null } : { url: artifactUrl(id), id, title: '', type: '', viewUrl: null, publicUrl: null, thumbnail: null, updatedAt: new Date().toISOString() };
204
+ emit('artifact', { session: null, workspace: null, artifact, change: 'removed', ...extra });
205
+ return;
206
+ }
207
+ const record = await lookup(id);
208
+ if (!record)
209
+ return;
210
+ const artifact = toArtifact(record);
211
+ // The first report of an artifact made since the kit started following is its creation.
212
+ const change = !known.has(id) && Date.parse(record.createdAt) >= since - 1000 ? 'created' : 'updated';
213
+ known.set(id, artifact);
214
+ const owner = record.owner && record.owner.harness === options.harness ? record.owner : null;
215
+ emit('artifact', { session: owner?.session ?? null, workspace: owner?.workspace ?? null, artifact, change, ...extra });
216
+ };
217
+ const onEvent = (event) => {
218
+ emit('event', event);
219
+ if (event.type !== 'artifacts/changed' || !listeners.artifact.size)
220
+ return;
221
+ const waiting = queued.get(event.id);
222
+ if (waiting) {
223
+ // Not looked up yet: one report covers both.
224
+ waiting.removed ||= !!event.removed;
225
+ if (event.author)
226
+ waiting.author = event.author;
227
+ for (const path of event.paths ?? [])
228
+ waiting.paths.add(path);
229
+ return;
230
+ }
231
+ queued.set(event.id, { removed: !!event.removed, ...(event.author ? { author: event.author } : {}), paths: new Set(event.paths ?? []) });
232
+ const next = (chains.get(event.id) ?? Promise.resolve()).then(() => report(event.id)).catch((error) => log(`open-artifact artifact ${event.id}: ${error.message}`));
233
+ chains.set(event.id, next);
234
+ void next.finally(() => {
235
+ if (chains.get(event.id) === next)
236
+ chains.delete(event.id);
237
+ });
238
+ };
239
+ // ---- the connection ----
240
+ const client = new HarnessClient({
241
+ harness: options.harness,
242
+ caps,
243
+ hello: { kit: { ...KIT }, ...(profile ? { profile } : {}), ...(options.runtime ? { runtime: options.runtime } : {}) },
244
+ daemon,
245
+ ...(options.autoStart !== undefined ? { autoStart: options.autoStart } : {}),
246
+ reconnect: { minMs: options.reconnect?.minMs ?? 1000, maxMs: options.reconnect?.maxMs ?? 30_000 },
247
+ log,
248
+ onEvent,
249
+ onState: (state) => emit('state', state),
250
+ onReattach: async (params, result) => {
251
+ const left = await handOver(params, result.inbox);
252
+ if (left.length) {
253
+ const key = sessionKey(params);
254
+ leftovers.set(key, [...(leftovers.get(key) ?? []), ...left]);
255
+ log(`open-artifact: ${left.length} message(s) for ${params.session ?? params.workspace} were not taken; the next attach returns them`);
256
+ }
257
+ },
258
+ handlers: {
259
+ ...(options.wake ? { 'wake.deliver': (params) => wake(params) } : {}),
260
+ 'shell.event': (params) => {
261
+ emit('shell', params);
262
+ return { ok: true };
263
+ },
264
+ ...(options.open
265
+ ? {
266
+ 'host.open': async (params) => {
267
+ const remote = params.remote && typeof params.remote.type === 'string' && Array.isArray(params.remote.origins) ? { type: params.remote.type, origins: params.remote.origins.filter((o) => typeof o === 'string') } : undefined;
268
+ try {
269
+ if (!(await remoteOk(remote, params.title))) {
270
+ log(`open-artifact open ${params.url}: a page from ${remote.origins.join(', ')} (another computer) was not allowed`);
271
+ return { opened: false };
272
+ }
273
+ }
274
+ catch {
275
+ return { opened: false };
276
+ }
277
+ const request = {
278
+ session: params.session ?? null,
279
+ url: params.url,
280
+ viewUrl: params.view_url,
281
+ embedUrl: params.embed_url || params.view_url,
282
+ ...(params.view ? { view: params.view } : {}),
283
+ ...(params.title !== undefined ? { title: params.title } : {}),
284
+ ...(remote?.origins.length ? { remote } : {}),
285
+ };
286
+ try {
287
+ return { opened: (await options.open(request)) !== false };
288
+ }
289
+ catch (error) {
290
+ log(`open-artifact open ${params.url}: ${error?.message ?? error}`);
291
+ return { opened: false };
292
+ }
293
+ },
294
+ }
295
+ : {}),
296
+ },
297
+ });
298
+ // Events are only asked for while someone listens.
299
+ await client.subscribe(false);
300
+ try {
301
+ await client.connect();
302
+ }
303
+ catch (error) {
304
+ log(`open-artifact connect: ${error?.message ?? error}`);
305
+ client.reconnect();
306
+ }
307
+ /** Connects if needed, then throws `unsupported` unless the daemon lists `feature`. */
308
+ const needs = async (feature, method) => {
309
+ if (!client.connected)
310
+ await client.connect();
311
+ if (!client.features.includes(feature)) {
312
+ throw new OpenArtifactError('unsupported', `${method} needs feature ${feature}, which daemon ${client.hello?.daemon ?? '(unknown)'} does not list.`, { fix: 'Update the Open Artifact runtime this computer runs.' });
313
+ }
314
+ };
315
+ const harness = {
316
+ client,
317
+ get connected() {
318
+ return client.connected;
319
+ },
320
+ get features() {
321
+ return client.features;
322
+ },
323
+ ready: () => client.connect(),
324
+ async attach(params) {
325
+ const result = await client.attach(params);
326
+ const key = sessionKey(params);
327
+ const earlier = leftovers.get(key) ?? [];
328
+ leftovers.delete(key);
329
+ return { key: result.key, inbox: [...earlier, ...(await handOver(params, result.inbox))] };
330
+ },
331
+ async status(session, status) {
332
+ await client.status({ ...sessionParams(session), status });
333
+ },
334
+ async detach(session) {
335
+ leftovers.delete(sessionKey(sessionParams(session)));
336
+ await client.detach(sessionParams(session));
337
+ },
338
+ async rename(session, title) {
339
+ await client.rename({ ...sessionParams(session), title });
340
+ },
341
+ async tools() {
342
+ if (client.connected) {
343
+ try {
344
+ return await client.tools();
345
+ }
346
+ catch (error) {
347
+ log(`open-artifact tools.list: ${error?.message ?? error}`);
348
+ }
349
+ }
350
+ return TOOL_DEFINITIONS.map((tool) => ({ ...tool }));
351
+ },
352
+ call: (name, args, caller) => client.callTool(name, args, caller),
353
+ wrote: (paths, caller) => client.request('agent.wrote', { paths, ...(caller ? { caller } : {}) }),
354
+ open: (url, opts) => client.request('artifact.open', { url, ...(opts ? { caller: opts } : {}) }),
355
+ owns: ownsCall,
356
+ async viewUrl(url) {
357
+ const id = artifactIdOf(url);
358
+ if (!id)
359
+ throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
360
+ const record = await lookup(id);
361
+ return record ? toArtifact(record).viewUrl : null;
362
+ },
363
+ async publicUrl(url) {
364
+ const id = artifactIdOf(url);
365
+ if (!id)
366
+ throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
367
+ const record = await lookup(id);
368
+ return record?.remote?.url || null;
369
+ },
370
+ embedOrigins: () => client.request('embed.origins', {}),
371
+ async shellCommand(view, command) {
372
+ await client.request('shell.command', { view, command });
373
+ },
374
+ context: (url, opts) => readContext(client, url, opts),
375
+ contextBlock,
376
+ async saveThumbnail(url, jpeg) {
377
+ const id = artifactIdOf(url);
378
+ if (!id)
379
+ throw new OpenArtifactError('invalid_argument', `Not an artifact: ${url}`);
380
+ const state = client.state ?? (await client.connect().then(() => client.state));
381
+ if (!state)
382
+ throw new OpenArtifactError('no_daemon', 'Not connected to the daemon.');
383
+ const target = new URL(`/api/open-artifact.${LIBRARY_ROUTES.thumbnail}`, state.url);
384
+ target.searchParams.set('id', id);
385
+ const response = await fetch(target, { method: 'POST', headers: { Authorization: `Bearer ${state.token}`, 'Content-Type': 'image/jpeg' }, body: new Blob([new Uint8Array(jpeg)]) });
386
+ if (!response.ok) {
387
+ const body = (await response.json().catch(() => ({})));
388
+ throw new OpenArtifactError(body.code ?? 'error', body.message ?? `thumbnail: HTTP ${response.status}`);
389
+ }
390
+ },
391
+ on(kind, listener) {
392
+ const set = listeners[kind];
393
+ const wantsEvents = () => listeners.artifact.size + listeners.event.size > 0;
394
+ const before = wantsEvents();
395
+ set.add(listener);
396
+ if (!before && wantsEvents()) {
397
+ since = Date.now();
398
+ void client.subscribe(true).catch((error) => log(`open-artifact subscribe: ${error.message}`));
399
+ }
400
+ return () => {
401
+ if (!set.delete(listener))
402
+ return;
403
+ if (kind !== 'state' && kind !== 'shell' && !wantsEvents())
404
+ void client.subscribe(false).catch(() => undefined);
405
+ };
406
+ },
407
+ async installSkill(opts) {
408
+ // With an `open` handler the app shows pages itself: the kit's own rendering says so, as the daemon's does.
409
+ const withOpens = options.open && opts.opens === undefined ? { ...opts, opens: 'host' } : opts;
410
+ return (await keepSkillInstalled(client, withOpens, (listener) => harness.on('state', listener), log)).result;
411
+ },
412
+ commands: (opts) => commands(client, opts),
413
+ runtime: {
414
+ async status() {
415
+ await needs('runtime.update', 'runtime.status');
416
+ return client.request('runtime.status', {});
417
+ },
418
+ async update(version) {
419
+ await needs('runtime.update', 'runtime.update');
420
+ return client.request('runtime.update', version ? { version } : {});
421
+ },
422
+ },
423
+ close: () => client.close(),
424
+ };
425
+ return harness;
426
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@open-artifact/harness-kit`: how an agent app connects to Open Artifact.
3
+ *
4
+ * `createHarness` is the whole adapter for most apps: it finds or starts the daemon, keeps the Harness API
5
+ * connection, hands messages to sessions and pages to the app's UI. `HarnessClient` is the connection under it, for an
6
+ * app that wants the calls themselves; `ensureDaemon`, `readDaemon` and `api` find the daemon and call its Library API.
7
+ *
8
+ * Entry points: `.` (this file), `./testing` (a fake daemon for an adapter's tests) and `./embed` (browser code that
9
+ * puts a Shell page or the home page into the app's own UI: `embedArtifact`, `embedLibrary`).
10
+ */
11
+ export { api, daemonStartPlan, defaultDaemonBin, ensureDaemon, isOlderVersion, openArtifactHome, readDaemon, startDaemonProcess, type ApiOptions, type DaemonExitSource, type DaemonSpawn, type DaemonStart, type DaemonStartPlan, type EnsureDaemonOptions } from './daemon.js';
12
+ export { LEGACY_PROTOCOLS, RUNTIME_ENTRY, compareVersions, isPrerelease, missingRuntimes, parseVersion, protocolRangeOf, rangesMeet, rankRuntimes, readRuntimePin, readRuntimesFile, runtimeCandidates, runtimeEnv, runtimeInfo, runtimesFileOf, satisfies, selectRuntime, sharedRuntimes, sharedRuntimesOf, validRange, type OwnRuntime, type RuntimeCandidate, type RuntimeRecord, type RuntimesFile, } from './runtimes.js';
13
+ export { HarnessClient, type HarnessClientOptions, type HarnessConnectionState, type HelloExtras } from './client.js';
14
+ export { KIT, createHarness, ownsCall, type ArtifactChange, type ArtifactReport, type Harness, type HarnessArtifact, type HarnessOptions, type HarnessRuntimeCalls, type OpenRequest, type WakeAnswer, } from './harness.js';
15
+ export type { RuntimeStatus, RuntimeUpdateResult } from '@open-artifact/protocol';
16
+ export { remoteGate, remotePolicyOf, type AllowRemote, type RemotePage, type RemotePagePolicy, type RemotePageRequest } from './embed/remote.js';
17
+ export { CONTEXT_HEADER, MAX_CONTEXT_CHARS, contextBlock, readContext, type ArtifactContext } from './context.js';
18
+ export { commands, installSkill, keepSkillInstalled, localSkill, renderSkill, type InstallSkillOptions, type InstallSkillResult } from './skill.js';
package/src/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@open-artifact/harness-kit`: how an agent app connects to Open Artifact.
3
+ *
4
+ * `createHarness` is the whole adapter for most apps: it finds or starts the daemon, keeps the Harness API
5
+ * connection, hands messages to sessions and pages to the app's UI. `HarnessClient` is the connection under it, for an
6
+ * app that wants the calls themselves; `ensureDaemon`, `readDaemon` and `api` find the daemon and call its Library API.
7
+ *
8
+ * Entry points: `.` (this file), `./testing` (a fake daemon for an adapter's tests) and `./embed` (browser code that
9
+ * puts a Shell page or the home page into the app's own UI: `embedArtifact`, `embedLibrary`).
10
+ */
11
+ export { api, daemonStartPlan, defaultDaemonBin, ensureDaemon, isOlderVersion, openArtifactHome, readDaemon, startDaemonProcess } from "./daemon.js";
12
+ export { LEGACY_PROTOCOLS, RUNTIME_ENTRY, compareVersions, isPrerelease, missingRuntimes, parseVersion, protocolRangeOf, rangesMeet, rankRuntimes, readRuntimePin, readRuntimesFile, runtimeCandidates, runtimeEnv, runtimeInfo, runtimesFileOf, satisfies, selectRuntime, sharedRuntimes, sharedRuntimesOf, validRange, } from "./runtimes.js";
13
+ export { HarnessClient } from "./client.js";
14
+ export { KIT, createHarness, ownsCall, } from "./harness.js";
15
+ export { remoteGate, remotePolicyOf } from "./embed/remote.js";
16
+ export { CONTEXT_HEADER, MAX_CONTEXT_CHARS, contextBlock, readContext } from "./context.js";
17
+ export { commands, installSkill, keepSkillInstalled, localSkill, renderSkill } from "./skill.js";
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Which Open Artifact runtime starts the daemon (design 10.1).
3
+ *
4
+ * A runtime is a folder with the content of `@open-artifact/cli`: `scripts/open-artifact.mjs` (the entry), `vendor/`,
5
+ * and a `package.json` (the npm package) or `vendor/runtime.json` (a skill folder) that says its version and the
6
+ * Harness API versions it speaks (`openArtifact.protocols`, `protocols`; left out: protocol 1). Three places hold them:
7
+ *
8
+ * - the caller's own (the folder a host carries, or the command line's own build);
9
+ * - the ones adapters registered in `hello` (`runtime: { dir, version }`), kept by the daemon in
10
+ * `<OPEN_ARTIFACT_HOME>/runtimes.json`; a folder that is gone (its host was uninstalled) is skipped;
11
+ * - the shared folder `<OPEN_ARTIFACT_HOME>/runtime/<version>/`, where `open-artifact runtime update` installs and
12
+ * where the daemon copies the newest runtime a host brought, so uninstalling that host does not take it away.
13
+ *
14
+ * The one that starts is the highest version whose protocols meet the caller's, within the person's pin
15
+ * (`settings.json` `runtime.pin`) when any candidate is; ties go to the caller's own. Everything here reads files only.
16
+ */
17
+ import type { ProtocolRange, RuntimeSource } from '@open-artifact/protocol';
18
+ /** The entry of a runtime folder, relative to it. */
19
+ export declare const RUNTIME_ENTRY: string;
20
+ /** The protocol range of a runtime that does not say (every runtime before protocol 2). */
21
+ export declare const LEGACY_PROTOCOLS: ProtocolRange;
22
+ /** One runtime `runtimes.json` records. */
23
+ export interface RuntimeRecord {
24
+ dir: string;
25
+ version: string;
26
+ /** The update policy the adapter that registered it asked for. */
27
+ update?: 'auto' | 'prompt' | 'bundled';
28
+ /** The harness that registered it (`daemon`: the daemon's own folder). */
29
+ harness?: string;
30
+ /** When it was last registered (ISO). */
31
+ seenAt?: string;
32
+ }
33
+ /** What `runtimes.json` holds. */
34
+ export interface RuntimesFile {
35
+ runtimes: RuntimeRecord[];
36
+ /** The protocol range each harness's adapter last said in `hello`, so an update stays compatible with all of them. */
37
+ adapters?: Record<string, {
38
+ protocols: ProtocolRange;
39
+ seenAt: string;
40
+ }>;
41
+ }
42
+ /** A runtime that could start the daemon. */
43
+ export interface RuntimeCandidate extends RuntimeSource {
44
+ /** The file to run with Node (`<dir>/scripts/open-artifact.mjs`, or the caller's own entry). */
45
+ bin: string;
46
+ }
47
+ /** The caller's own runtime: a folder, or an entry file (a source checkout). */
48
+ export interface OwnRuntime {
49
+ dir?: string;
50
+ bin?: string;
51
+ version: string;
52
+ protocols?: ProtocolRange;
53
+ }
54
+ interface Parsed {
55
+ n: [number, number, number];
56
+ pre: string[];
57
+ }
58
+ /** `x.y.z[-pre][+build]`, with a leading `v` or `=` allowed; `null` when it is not one. */
59
+ export declare function parseVersion(version: unknown): Parsed | null;
60
+ /** Semver order: negative when `a` is older than `b`. A version that does not parse is older than any that does. */
61
+ export declare function compareVersions(a: string, b: string): number;
62
+ /** Whether a version is a pre-release (`0.14.0-beta.1`). */
63
+ export declare function isPrerelease(version: string): boolean;
64
+ type Comparator = {
65
+ op: '>=' | '>' | '<' | '<=' | '=';
66
+ v: Parsed;
67
+ };
68
+ /** A range in npm's notation, as sets of comparators (`||` between sets). Throws when it is not one this reader knows. */
69
+ export declare function parseRange(range: string): Comparator[][];
70
+ /** Whether `range` is a range this reader knows. */
71
+ export declare function validRange(range: string): boolean;
72
+ /**
73
+ * Whether `version` is in `range` (npm notation: `0.13.x`, `^0.13.1`, `~0.13.0`, `>=0.13 <0.15`, `1.2.3 - 1.4`,
74
+ * `a || b`, `*`). A pre-release is only in a range that names that same version exactly. A range that does not
75
+ * parse matches nothing.
76
+ */
77
+ export declare function satisfies(version: string, range: string): boolean;
78
+ /** Whether two protocol ranges share a version. */
79
+ export declare function rangesMeet(a: ProtocolRange, b: ProtocolRange): boolean;
80
+ /** A `{min, max}` of whole numbers, else `null`. */
81
+ export declare function protocolRangeOf(value: unknown): ProtocolRange | null;
82
+ /**
83
+ * What a runtime folder says about itself: its entry, version and protocols (`package.json`, then
84
+ * `vendor/runtime.json`). `null` when it is not a runtime folder (no entry).
85
+ */
86
+ export declare function runtimeInfo(dir: string): {
87
+ bin: string;
88
+ version: string | null;
89
+ protocols: ProtocolRange | null;
90
+ } | null;
91
+ /** `<home>/runtimes.json`. */
92
+ export declare const runtimesFileOf: (home: string) => string;
93
+ /** `<home>/runtime`: the shared runtimes, one folder per version. */
94
+ export declare const sharedRuntimesOf: (home: string) => string;
95
+ /** `runtimes.json` of a home (an empty one when it is missing or broken). */
96
+ export declare function readRuntimesFile(home: string): RuntimesFile;
97
+ /** The person's pin (`settings.json` `runtime.pin`), or `null`. */
98
+ export declare function readRuntimePin(home: string): string | null;
99
+ /** The versions installed in the shared folder, newest first (folders named by a version, with an entry). */
100
+ export declare function sharedRuntimes(home: string): RuntimeCandidate[];
101
+ /** The caller's own runtime as a candidate, when it names a folder or an entry that is there. */
102
+ export declare function ownCandidate(own: OwnRuntime | undefined): RuntimeCandidate | null;
103
+ /**
104
+ * Every runtime that could start the daemon for this home: the caller's own, the registered ones whose folder is
105
+ * still a runtime of the recorded version, and the shared ones.
106
+ */
107
+ export declare function runtimeCandidates(home: string, own?: OwnRuntime): RuntimeCandidate[];
108
+ /** The registered runtimes whose folder is gone or is no longer that runtime. */
109
+ export declare function missingRuntimes(home: string): RuntimeRecord[];
110
+ /**
111
+ * The candidates that may start a daemon for a caller speaking `protocols`, best first: those within `pin` (when any
112
+ * is), each highest version first; on a tie the caller's own, then the shared copy. Empty when none speaks the
113
+ * caller's protocols. A runtime folder whose `package.json` `engines.node` this process's Node does not meet is left
114
+ * out: the daemon runs with this process's executable (in a single executable, the Node inside it).
115
+ */
116
+ export declare function rankRuntimes(candidates: readonly RuntimeCandidate[], options: {
117
+ protocols: ProtocolRange;
118
+ pin?: string | null;
119
+ }): RuntimeCandidate[];
120
+ /** The runtime to start (see {@link rankRuntimes}), or `null`. */
121
+ export declare function selectRuntime(candidates: readonly RuntimeCandidate[], options: {
122
+ protocols: ProtocolRange;
123
+ pin?: string | null;
124
+ }): RuntimeCandidate | null;
125
+ /** A path with links resolved, or resolved as it is when it is not there. */
126
+ export declare function realOrResolved(path: string): string;
127
+ /** Whether `path` is `dir` or inside it. */
128
+ export declare function within(dir: string, path: string): boolean;
129
+ /** Whether `dir` is a folder. */
130
+ export declare function isFolder(dir: string): boolean;
131
+ /**
132
+ * The variables a launcher sets to point the daemon at its own folder's pieces. When another runtime starts, the ones
133
+ * that point into a runtime folder other than the one starting are dropped, so its daemon serves its own Shell and types.
134
+ */
135
+ export declare const RUNTIME_VARIABLES: readonly ["OPEN_ARTIFACT_DAEMON_BIN", "OPEN_ARTIFACT_SHELL_DIR", "OPEN_ARTIFACT_HOME_DIR", "OPEN_ARTIFACT_BUILTIN_TYPES", "OPEN_ARTIFACT_HARNESS_PROFILES"];
136
+ /** `env` for starting `chosen`: without the entry override, nor the variables that point into another runtime's folder. */
137
+ export declare function runtimeEnv(env: NodeJS.ProcessEnv, chosen: RuntimeCandidate, others: readonly RuntimeCandidate[]): NodeJS.ProcessEnv;
138
+ export {};