@open-artifact/harness-kit 0.0.0-stage → 0.14.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/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 DaemonStartPlan, type EnsureDaemonOptions } from './daemon.ts';
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.ts';
13
+ export { HarnessClient, type HarnessClientOptions, type HarnessConnectionState, type HelloExtras } from './client.ts';
14
+ export { KIT, createHarness, ownsCall, type ArtifactChange, type ArtifactReport, type Harness, type HarnessArtifact, type HarnessOptions, type HarnessRuntimeCalls, type OpenRequest, type WakeAnswer, } from './harness.ts';
15
+ export type { RuntimeStatus, RuntimeUpdateResult } from '@open-artifact/protocol';
16
+ export { remoteGate, remotePolicyOf, type AllowRemote, type RemotePage, type RemotePagePolicy, type RemotePageRequest } from './embed/remote.ts';
17
+ export { CONTEXT_HEADER, MAX_CONTEXT_CHARS, contextBlock, readContext, type ArtifactContext } from './context.ts';
18
+ export { commands, installSkill, keepSkillInstalled, localSkill, renderSkill, type InstallSkillOptions, type InstallSkillResult } from './skill.ts';
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 {};
@@ -0,0 +1,357 @@
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 { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
18
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
19
+ /** The entry of a runtime folder, relative to it. */
20
+ export const RUNTIME_ENTRY = join('scripts', 'open-artifact.mjs');
21
+ /** The protocol range of a runtime that does not say (every runtime before protocol 2). */
22
+ export const LEGACY_PROTOCOLS = Object.freeze({ min: 1, max: 1 });
23
+ /** `x.y.z[-pre][+build]`, with a leading `v` or `=` allowed; `null` when it is not one. */
24
+ export function parseVersion(version) {
25
+ if (typeof version !== 'string')
26
+ return null;
27
+ const match = /^[v=\s]*(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(version);
28
+ if (!match)
29
+ return null;
30
+ return { n: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] ? match[4].split('.') : [] };
31
+ }
32
+ function comparePre(a, b) {
33
+ if (!a.length || !b.length)
34
+ return a.length === b.length ? 0 : a.length ? -1 : 1;
35
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
36
+ const x = a[i];
37
+ const y = b[i];
38
+ if (x === undefined)
39
+ return -1;
40
+ if (y === undefined)
41
+ return 1;
42
+ const nx = /^\d+$/.test(x);
43
+ const ny = /^\d+$/.test(y);
44
+ if (nx && ny && Number(x) !== Number(y))
45
+ return Number(x) < Number(y) ? -1 : 1;
46
+ if (nx !== ny)
47
+ return nx ? -1 : 1;
48
+ if (x !== y)
49
+ return x < y ? -1 : 1;
50
+ }
51
+ return 0;
52
+ }
53
+ /** Semver order: negative when `a` is older than `b`. A version that does not parse is older than any that does. */
54
+ export function compareVersions(a, b) {
55
+ const x = parseVersion(a);
56
+ const y = parseVersion(b);
57
+ if (!x || !y)
58
+ return x ? 1 : y ? -1 : 0;
59
+ for (let i = 0; i < 3; i++)
60
+ if (x.n[i] !== y.n[i])
61
+ return x.n[i] < y.n[i] ? -1 : 1;
62
+ return comparePre(x.pre, y.pre);
63
+ }
64
+ /** Whether a version is a pre-release (`0.14.0-beta.1`). */
65
+ export function isPrerelease(version) {
66
+ return !!parseVersion(version)?.pre.length;
67
+ }
68
+ const tuple = (n) => ({ n: [n[0] ?? 0, n[1] ?? 0, n[2] ?? 0], pre: [] });
69
+ /** One range token (`^0.13.1`, `0.13.x`, `>=1.2`, `*`) as comparators; throws on what it does not know. */
70
+ function comparatorsOf(token) {
71
+ const match = /^(\^|~|>=|<=|>|<|=)?\s*v?(\*|x|X|\d+)(?:\.(\*|x|X|\d+))?(?:\.(\*|x|X|\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(token);
72
+ if (!match)
73
+ throw new Error(`not a version range: ${token}`);
74
+ const op = match[1] ?? '';
75
+ const parts = [match[2], match[3], match[4]];
76
+ const wild = (p) => p === undefined || /^[*xX]$/.test(p);
77
+ const fixed = [];
78
+ for (const part of parts) {
79
+ if (wild(part))
80
+ break;
81
+ fixed.push(Number(part));
82
+ }
83
+ const pre = match[5] ? match[5].split('.') : [];
84
+ if (fixed.length === 0)
85
+ return op === '<' || op === '>' ? [{ op: '<', v: tuple([0, 0, 0]) }] : [];
86
+ const low = { ...tuple(fixed), pre: fixed.length === 3 ? pre : [] };
87
+ // The first version past the partial one: 1.2 → 1.3.0, 1 → 2.0.0.
88
+ const next = (n) => tuple(n.length === 1 ? [n[0] + 1, 0, 0] : n.length === 2 ? [n[0], n[1] + 1, 0] : [n[0], n[1], n[2] + 1]);
89
+ switch (op) {
90
+ case '^': {
91
+ const [a = 0, b = 0, c = 0] = fixed;
92
+ const upper = a > 0 || fixed.length === 1 ? tuple([a + 1, 0, 0]) : b > 0 || fixed.length === 2 ? tuple([0, b + 1, 0]) : tuple([0, 0, c + 1]);
93
+ return [{ op: '>=', v: low }, { op: '<', v: upper }];
94
+ }
95
+ case '~':
96
+ return [{ op: '>=', v: low }, { op: '<', v: next(fixed.length === 3 ? fixed.slice(0, 2) : fixed) }];
97
+ case '>=':
98
+ return [{ op: '>=', v: low }];
99
+ case '<':
100
+ return [{ op: '<', v: low }];
101
+ case '>':
102
+ return fixed.length === 3 ? [{ op: '>', v: low }] : [{ op: '>=', v: next(fixed) }];
103
+ case '<=':
104
+ return fixed.length === 3 ? [{ op: '<=', v: low }] : [{ op: '<', v: next(fixed) }];
105
+ default:
106
+ return fixed.length === 3 ? [{ op: '=', v: low }] : [{ op: '>=', v: low }, { op: '<', v: next(fixed) }];
107
+ }
108
+ }
109
+ const cmp = (a, b) => {
110
+ for (let i = 0; i < 3; i++)
111
+ if (a.n[i] !== b.n[i])
112
+ return a.n[i] < b.n[i] ? -1 : 1;
113
+ return comparePre(a.pre, b.pre);
114
+ };
115
+ /** A range in npm's notation, as sets of comparators (`||` between sets). Throws when it is not one this reader knows. */
116
+ export function parseRange(range) {
117
+ const text = range.trim();
118
+ if (!text)
119
+ throw new Error('an empty range');
120
+ return text.split('||').map((set) => {
121
+ const hyphen = /^\s*(\S+)\s+-\s+(\S+)\s*$/.exec(set);
122
+ if (hyphen)
123
+ return [...comparatorsOf(`>=${hyphen[1]}`), ...comparatorsOf(`<=${hyphen[2]}`)];
124
+ const tokens = set.trim().replace(/(\^|~|>=|<=|>|<|=)\s+/g, '$1').split(/\s+/).filter(Boolean);
125
+ if (!tokens.length)
126
+ throw new Error(`an empty part in ${range}`);
127
+ return tokens.flatMap(comparatorsOf);
128
+ });
129
+ }
130
+ /** Whether `range` is a range this reader knows. */
131
+ export function validRange(range) {
132
+ try {
133
+ parseRange(range);
134
+ return true;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ }
140
+ /**
141
+ * 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`,
142
+ * `a || b`, `*`). A pre-release is only in a range that names that same version exactly. A range that does not
143
+ * parse matches nothing.
144
+ */
145
+ export function satisfies(version, range) {
146
+ const v = parseVersion(version);
147
+ if (!v)
148
+ return false;
149
+ let sets;
150
+ try {
151
+ sets = parseRange(range);
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ return sets.some((set) => {
157
+ if (v.pre.length && !set.some((c) => c.op === '=' && cmp(c.v, v) === 0))
158
+ return false;
159
+ return set.every((c) => {
160
+ const order = cmp(v, c.v);
161
+ return c.op === '=' ? order === 0 : c.op === '>=' ? order >= 0 : c.op === '>' ? order > 0 : c.op === '<' ? order < 0 : order <= 0;
162
+ });
163
+ });
164
+ }
165
+ /** Whether two protocol ranges share a version. */
166
+ export function rangesMeet(a, b) {
167
+ return Math.max(a.min, b.min) <= Math.min(a.max, b.max);
168
+ }
169
+ /** A `{min, max}` of whole numbers, else `null`. */
170
+ export function protocolRangeOf(value) {
171
+ const range = value;
172
+ if (!range || typeof range !== 'object' || !Number.isInteger(range.min) || !Number.isInteger(range.max) || range.min < 1 || range.max < range.min)
173
+ return null;
174
+ return { min: range.min, max: range.max };
175
+ }
176
+ // ---- folders ------------------------------------------------------------------------------------------------------
177
+ const readJsonFile = (file) => {
178
+ try {
179
+ return JSON.parse(readFileSync(file, 'utf8'));
180
+ }
181
+ catch {
182
+ return null;
183
+ }
184
+ };
185
+ /**
186
+ * What a runtime folder says about itself: its entry, version and protocols (`package.json`, then
187
+ * `vendor/runtime.json`). `null` when it is not a runtime folder (no entry).
188
+ */
189
+ export function runtimeInfo(dir) {
190
+ const bin = join(dir, RUNTIME_ENTRY);
191
+ if (!existsSync(bin))
192
+ return null;
193
+ const pkg = readJsonFile(join(dir, 'package.json'));
194
+ const own = readJsonFile(join(dir, 'vendor', 'runtime.json'));
195
+ const version = [pkg?.version, own?.version].find((v) => typeof v === 'string' && !!parseVersion(v)) ?? null;
196
+ return { bin, version, protocols: protocolRangeOf(pkg?.openArtifact?.protocols) ?? protocolRangeOf(own?.protocols) };
197
+ }
198
+ /** `<home>/runtimes.json`. */
199
+ export const runtimesFileOf = (home) => join(home, 'runtimes.json');
200
+ /** `<home>/runtime`: the shared runtimes, one folder per version. */
201
+ export const sharedRuntimesOf = (home) => join(home, 'runtime');
202
+ /** `runtimes.json` of a home (an empty one when it is missing or broken). */
203
+ export function readRuntimesFile(home) {
204
+ const raw = readJsonFile(runtimesFileOf(home));
205
+ const runtimes = Array.isArray(raw?.runtimes)
206
+ ? raw.runtimes.filter((r) => !!r && typeof r.dir === 'string' && isAbsolute(r.dir) && typeof r.version === 'string')
207
+ : [];
208
+ const adapters = {};
209
+ for (const [name, entry] of Object.entries(raw?.adapters ?? {})) {
210
+ const protocols = protocolRangeOf(entry?.protocols);
211
+ if (protocols)
212
+ adapters[name] = { protocols, seenAt: String(entry.seenAt ?? '') };
213
+ }
214
+ return { runtimes, adapters };
215
+ }
216
+ /** The person's pin (`settings.json` `runtime.pin`), or `null`. */
217
+ export function readRuntimePin(home) {
218
+ const settings = readJsonFile(join(home, 'settings.json'));
219
+ const pin = settings?.runtime?.pin;
220
+ return typeof pin === 'string' && pin.trim() && validRange(pin) ? pin.trim() : null;
221
+ }
222
+ /** The versions installed in the shared folder, newest first (folders named by a version, with an entry). */
223
+ export function sharedRuntimes(home) {
224
+ const root = sharedRuntimesOf(home);
225
+ let names;
226
+ try {
227
+ names = readdirSync(root);
228
+ }
229
+ catch {
230
+ return [];
231
+ }
232
+ const found = [];
233
+ for (const name of names) {
234
+ if (name.startsWith('.') || !parseVersion(name))
235
+ continue;
236
+ const dir = join(root, name);
237
+ const info = runtimeInfo(dir);
238
+ // A folder whose package says another version is not what its name claims.
239
+ if (!info || (info.version && info.version !== name))
240
+ continue;
241
+ found.push({ source: 'shared', dir, bin: info.bin, version: name, protocols: info.protocols ?? LEGACY_PROTOCOLS });
242
+ }
243
+ return found.sort((a, b) => compareVersions(b.version, a.version));
244
+ }
245
+ /** The caller's own runtime as a candidate, when it names a folder or an entry that is there. */
246
+ export function ownCandidate(own) {
247
+ if (!own?.version)
248
+ return null;
249
+ if (own.dir) {
250
+ const info = runtimeInfo(own.dir);
251
+ const bin = own.bin ?? info?.bin;
252
+ if (!bin || !existsSync(bin))
253
+ return null;
254
+ return { source: 'own', dir: resolve(own.dir), bin, version: own.version, protocols: own.protocols ?? info?.protocols ?? LEGACY_PROTOCOLS };
255
+ }
256
+ if (!own.bin || !existsSync(own.bin))
257
+ return null;
258
+ return { source: 'own', dir: null, bin: own.bin, version: own.version, protocols: own.protocols ?? LEGACY_PROTOCOLS };
259
+ }
260
+ /**
261
+ * Every runtime that could start the daemon for this home: the caller's own, the registered ones whose folder is
262
+ * still a runtime of the recorded version, and the shared ones.
263
+ */
264
+ export function runtimeCandidates(home, own) {
265
+ const out = [];
266
+ const mine = ownCandidate(own);
267
+ if (mine)
268
+ out.push(mine);
269
+ for (const record of readRuntimesFile(home).runtimes) {
270
+ const info = runtimeInfo(record.dir);
271
+ if (!info || !parseVersion(record.version) || (info.version && info.version !== record.version))
272
+ continue;
273
+ out.push({ source: 'registered', dir: record.dir, bin: info.bin, version: record.version, protocols: info.protocols ?? LEGACY_PROTOCOLS, ...(record.harness ? { harness: record.harness } : {}) });
274
+ }
275
+ out.push(...sharedRuntimes(home));
276
+ return out;
277
+ }
278
+ /** The registered runtimes whose folder is gone or is no longer that runtime. */
279
+ export function missingRuntimes(home) {
280
+ return readRuntimesFile(home).runtimes.filter((record) => {
281
+ const info = runtimeInfo(record.dir);
282
+ return !info || (!!info.version && info.version !== record.version);
283
+ });
284
+ }
285
+ const SOURCE_RANK = { own: 0, shared: 1, registered: 2 };
286
+ /** Whether this process's Node meets a runtime folder's `engines.node` (the caller's own runs already; no range: yes). */
287
+ function runsOnThisNode(c) {
288
+ if (c.source === 'own' || !c.dir)
289
+ return true;
290
+ const node = readJsonFile(join(c.dir, 'package.json'))?.engines?.node;
291
+ return typeof node !== 'string' || !validRange(node) || satisfies(process.versions.node, node);
292
+ }
293
+ /**
294
+ * The candidates that may start a daemon for a caller speaking `protocols`, best first: those within `pin` (when any
295
+ * is), each highest version first; on a tie the caller's own, then the shared copy. Empty when none speaks the
296
+ * caller's protocols. A runtime folder whose `package.json` `engines.node` this process's Node does not meet is left
297
+ * out: the daemon runs with this process's executable (in a single executable, the Node inside it).
298
+ */
299
+ export function rankRuntimes(candidates, options) {
300
+ const usable = candidates.filter((c) => !!parseVersion(c.version) && rangesMeet(c.protocols, options.protocols) && runsOnThisNode(c));
301
+ const pinned = options.pin ? usable.filter((c) => satisfies(c.version, options.pin)) : usable;
302
+ const pool = pinned.length ? pinned : usable;
303
+ const seen = new Set();
304
+ return [...pool]
305
+ .sort((a, b) => compareVersions(b.version, a.version) || SOURCE_RANK[a.source] - SOURCE_RANK[b.source])
306
+ .filter((c) => {
307
+ const key = realOrResolved(c.bin);
308
+ if (seen.has(key))
309
+ return false;
310
+ seen.add(key);
311
+ return true;
312
+ });
313
+ }
314
+ /** The runtime to start (see {@link rankRuntimes}), or `null`. */
315
+ export function selectRuntime(candidates, options) {
316
+ return rankRuntimes(candidates, options)[0] ?? null;
317
+ }
318
+ /** A path with links resolved, or resolved as it is when it is not there. */
319
+ export function realOrResolved(path) {
320
+ try {
321
+ return realpathSync(path);
322
+ }
323
+ catch {
324
+ return resolve(path);
325
+ }
326
+ }
327
+ /** Whether `path` is `dir` or inside it. */
328
+ export function within(dir, path) {
329
+ const rel = relative(realOrResolved(dir), realOrResolved(path));
330
+ return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel) && !rel.startsWith(`..${sep}`));
331
+ }
332
+ /** Whether `dir` is a folder. */
333
+ export function isFolder(dir) {
334
+ try {
335
+ return statSync(dir).isDirectory();
336
+ }
337
+ catch {
338
+ return false;
339
+ }
340
+ }
341
+ /**
342
+ * The variables a launcher sets to point the daemon at its own folder's pieces. When another runtime starts, the ones
343
+ * that point into a runtime folder other than the one starting are dropped, so its daemon serves its own Shell and types.
344
+ */
345
+ export const RUNTIME_VARIABLES = ['OPEN_ARTIFACT_DAEMON_BIN', 'OPEN_ARTIFACT_SHELL_DIR', 'OPEN_ARTIFACT_HOME_DIR', 'OPEN_ARTIFACT_BUILTIN_TYPES', 'OPEN_ARTIFACT_HARNESS_PROFILES'];
346
+ /** `env` for starting `chosen`: without the entry override, nor the variables that point into another runtime's folder. */
347
+ export function runtimeEnv(env, chosen, others) {
348
+ const out = { ...env };
349
+ delete out.OPEN_ARTIFACT_DAEMON_BIN;
350
+ const foreign = others.map((c) => c.dir ?? null).filter((dir) => !!dir && (!chosen.dir || realOrResolved(dir) !== realOrResolved(chosen.dir)));
351
+ for (const name of RUNTIME_VARIABLES) {
352
+ const value = out[name];
353
+ if (value && foreign.some((dir) => within(dir, value)))
354
+ delete out[name];
355
+ }
356
+ return out;
357
+ }
package/src/skill.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The skill a harness installs for its agent, and its command menu.
3
+ *
4
+ * `installSkill` writes `<dir>/<command>/SKILL.md`: the daemon's rendering for this harness (`skill.get`) when it has
5
+ * the feature, else the template this kit carries (without the installed types). The file says which runtime wrote it
6
+ * (`generated-by: open-artifact <version>`) and its `etag`; it is written again only when the etag changes, and a file
7
+ * Open Artifact did not write stays unless `force`. {@link keepSkillInstalled} runs it again after a reconnect to
8
+ * another runtime. `commands` lists one command per installed type (`commands.list`): their starting prompts go into
9
+ * the person's input box, never sent by themselves.
10
+ */
11
+ import { type CommandEntry, type SkillParams, type SkillResult } from '@open-artifact/protocol';
12
+ import type { HarnessClient, HarnessConnectionState } from './client.ts';
13
+ /** What {@link installSkill} takes. */
14
+ export interface InstallSkillOptions extends Omit<SkillParams, 'command'> {
15
+ /** The folder the harness reads skills from (the skill goes in `<dir>/<command>/`). */
16
+ dir: string;
17
+ /** The command, without the slash (default `open-artifact`). */
18
+ command?: string;
19
+ /** Replace a SKILL.md there that Open Artifact did not write. */
20
+ force?: boolean;
21
+ }
22
+ /** What {@link installSkill} did. */
23
+ export interface InstallSkillResult {
24
+ file: string;
25
+ /** false: the file there already had this etag. */
26
+ written: boolean;
27
+ etag: string;
28
+ /** The runtime that rendered it (the kit's own version when rendered here). */
29
+ version: string;
30
+ /** `daemon`: `skill.get`; `kit`: the template this kit carries (the daemon is not there or lacks the feature). */
31
+ source: 'daemon' | 'kit';
32
+ }
33
+ /** The skill rendered by the kit itself, for a daemon without `skill.get`: no installed types, no harness profile. */
34
+ export declare function localSkill(options: Omit<InstallSkillOptions, 'dir' | 'force'>): SkillResult;
35
+ /**
36
+ * The skill for this harness without writing it anywhere, for a harness that hands skills to its agent itself: the
37
+ * daemon's rendering (`skill.get`) when connected to one that has it, else this kit's ({@link localSkill}).
38
+ */
39
+ export declare function renderSkill(client: HarnessClient | null, params: Omit<InstallSkillOptions, 'dir' | 'force'>): Promise<{
40
+ skill: SkillResult;
41
+ source: InstallSkillResult['source'];
42
+ }>;
43
+ /** Writes the skill where the harness reads skills, when its etag changed. */
44
+ export declare function installSkill(client: HarnessClient | null, options: InstallSkillOptions): Promise<InstallSkillResult>;
45
+ /**
46
+ * {@link installSkill} now, and again whenever the connection comes back to a runtime of another version (or to one
47
+ * that renders it, after the kit's own). `onState` registers a state listener and returns its remover. Returns the
48
+ * first result and a function that stops.
49
+ */
50
+ export declare function keepSkillInstalled(client: HarnessClient, options: InstallSkillOptions, onState: (listener: (state: HarnessConnectionState) => void) => () => void, log?: (line: string) => void): Promise<{
51
+ result: InstallSkillResult;
52
+ stop: () => void;
53
+ }>;
54
+ /** The command menu: one entry per installed type (`[]` from a daemon without `commands.list`). */
55
+ export declare function commands(client: HarnessClient | null, options?: {
56
+ command?: string;
57
+ locale?: string;
58
+ }): Promise<CommandEntry[]>;