@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.
@@ -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.js';
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[]>;
package/src/skill.js ADDED
@@ -0,0 +1,88 @@
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 { createHash } from 'node:crypto';
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
13
+ import { join, resolve } from 'node:path';
14
+ import { OpenArtifactError, SKILL_ARGUMENT_HINT, SKILL_COMMAND, SKILL_COMMAND_NAME, SKILL_GENERATED_BY, renderSkillBody, renderedSkillFile, skillDescription, skillFileKey, skillTypesSection, } from '@open-artifact/protocol';
15
+ import pkg from '../package.json' with { type: 'json' };
16
+ /** The skill rendered by the kit itself, for a daemon without `skill.get`: no installed types, no harness profile. */
17
+ export function localSkill(options) {
18
+ const name = options.command || SKILL_COMMAND;
19
+ const render = {
20
+ command: name,
21
+ ...(options.agentName ? { agentName: options.agentName } : {}),
22
+ ...(options.tools ? { tools: options.tools } : {}),
23
+ ...(options.toolNames ? { toolNames: options.toolNames } : {}),
24
+ ...(options.opens ? { opens: options.opens } : {}),
25
+ // The kit's skill is not in the daemon's skill folder, so the command line is the one on the PATH.
26
+ cli: 'open-artifact',
27
+ };
28
+ const body = `${renderSkillBody(render, options.form ?? 'full')}\n\n${skillTypesSection(null)}`;
29
+ const description = skillDescription(render);
30
+ const etag = createHash('sha256').update(JSON.stringify([name, description, SKILL_ARGUMENT_HINT, body, null])).digest('hex').slice(0, 16);
31
+ return { name, description, argumentHint: SKILL_ARGUMENT_HINT, body, version: pkg.version ?? '0.0.0', etag };
32
+ }
33
+ /**
34
+ * The skill for this harness without writing it anywhere, for a harness that hands skills to its agent itself: the
35
+ * daemon's rendering (`skill.get`) when connected to one that has it, else this kit's ({@link localSkill}).
36
+ */
37
+ export async function renderSkill(client, params) {
38
+ if (params.command !== undefined && !SKILL_COMMAND_NAME.test(params.command)) {
39
+ throw new OpenArtifactError('invalid_argument', 'command: lowercase letters, digits, - and _ (at most 32), without the slash.');
40
+ }
41
+ if (client?.connected && client.features.includes('skill.get'))
42
+ return { skill: await client.request('skill.get', params), source: 'daemon' };
43
+ return { skill: localSkill(params), source: 'kit' };
44
+ }
45
+ /** Writes the skill where the harness reads skills, when its etag changed. */
46
+ export async function installSkill(client, options) {
47
+ const { dir, force, ...params } = options;
48
+ const { skill, source } = await renderSkill(client, params);
49
+ const folder = join(resolve(dir), skill.name);
50
+ const file = join(folder, 'SKILL.md');
51
+ if (existsSync(file)) {
52
+ const text = readFileSync(file, 'utf8');
53
+ if (!force && !skillFileKey(text, SKILL_GENERATED_BY)) {
54
+ throw new OpenArtifactError('conflict', `${file} was not written by Open Artifact: it stays.`, { fix: 'Pass force: true to replace it, or another dir or command.' });
55
+ }
56
+ if (skillFileKey(text, 'etag') === skill.etag)
57
+ return { file, written: false, etag: skill.etag, version: skill.version, source };
58
+ }
59
+ mkdirSync(folder, { recursive: true });
60
+ writeFileSync(file, renderedSkillFile(skill));
61
+ return { file, written: true, etag: skill.etag, version: skill.version, source };
62
+ }
63
+ /**
64
+ * {@link installSkill} now, and again whenever the connection comes back to a runtime of another version (or to one
65
+ * that renders it, after the kit's own). `onState` registers a state listener and returns its remover. Returns the
66
+ * first result and a function that stops.
67
+ */
68
+ export async function keepSkillInstalled(client, options, onState, log = () => undefined) {
69
+ const result = await installSkill(client, options);
70
+ let last = `${result.source}:${client.hello?.daemon ?? ''}`;
71
+ const stop = onState((state) => {
72
+ if (state !== 'connected')
73
+ return;
74
+ const now = `${client.features.includes('skill.get') ? 'daemon' : 'kit'}:${client.hello?.daemon ?? ''}`;
75
+ if (now === last)
76
+ return;
77
+ last = now;
78
+ installSkill(client, options).then((again) => again.written && log(`open-artifact: ${again.file} rewritten for runtime ${again.version}`), (error) => log(`open-artifact skill: ${error.message}`));
79
+ });
80
+ return { result, stop };
81
+ }
82
+ /** The command menu: one entry per installed type (`[]` from a daemon without `commands.list`). */
83
+ export async function commands(client, options = {}) {
84
+ if (!client?.connected || !client.features.includes('commands.list'))
85
+ return [];
86
+ const answer = await client.request('commands.list', options);
87
+ return Array.isArray(answer?.commands) ? answer.commands : [];
88
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A small WebSocket server side (RFC 6455) on Node built-ins: text frames,
3
+ * ping / pong and close. The Harness API (`/__harness`) runs on it.
4
+ */
5
+ import type { IncomingMessage } from 'node:http';
6
+ import type { Duplex } from 'node:stream';
7
+ /** What a connection reports to its owner. */
8
+ export interface WebSocketHandlers {
9
+ message?: (text: string) => void;
10
+ close?: () => void;
11
+ }
12
+ /**
13
+ * Accepts an upgrade. Returns the connection, or `null` after refusing it.
14
+ * `protocol` is the subprotocol to answer with, when the client asked for it.
15
+ */
16
+ export declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, head: Buffer, protocol?: string): WebSocketConnection | null;
17
+ /** One accepted WebSocket. */
18
+ export declare class WebSocketConnection {
19
+ /** Set by the owner to receive messages and the close. */
20
+ handlers: WebSocketHandlers;
21
+ /** True once the socket is closing or closed. */
22
+ closed: boolean;
23
+ private readonly socket;
24
+ private buffer;
25
+ private fragments;
26
+ private readonly pinger;
27
+ constructor(socket: Duplex, head?: Buffer);
28
+ private read;
29
+ private frame;
30
+ /** Sends a text frame. */
31
+ sendText(text: string): void;
32
+ /** Sends a close frame and ends the socket. */
33
+ close(code?: number): void;
34
+ private finish;
35
+ }