@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/testing.js ADDED
@@ -0,0 +1,424 @@
1
+ /**
2
+ * A fake daemon for testing an adapter (`@open-artifact/harness-kit/testing`): it speaks the Harness API over a real
3
+ * WebSocket on an ephemeral port, in this process, with no dependencies. It writes `daemon.json` in a home of its own,
4
+ * so `createHarness({ harness, home: fake.home, autoStart: false })` finds it as it finds the real daemon.
5
+ *
6
+ * const fake = await startFakeDaemon();
7
+ * const harness = await createHarness({ harness: 'my-app', home: fake.home, autoStart: false, wake: … });
8
+ * await harness.attach({ session: 's1', workspace: '/w' });
9
+ * assert.equal((await fake.wake({ session: 's1', … })).status, 'resumed'); // the adapter's `wake` answered
10
+ * fake.setArtifact({ id: 'a1', title: 'Deck', … });
11
+ * fake.emit({ type: 'artifacts/changed', id: 'a1' }); // `on('artifact')` reports it
12
+ * fake.drop(); // the adapter reconnects and attaches again
13
+ * await fake.close();
14
+ *
15
+ * What it answers: `hello` (negotiating `protocols`; `features` as the real daemon lists them, `HARNESS_FEATURES`),
16
+ * `skill.get` (the protocol's skill template, rendered for the adapter's caps), `commands.list` (one entry per
17
+ * {@link FakeDaemonOptions.types}), `session.attach` (with what {@link FakeDaemon.queueInbox} queued),
18
+ * `session.status`, `session.detach`, `session.rename`, `tools.list`, `tools.call`, `agent.wrote`, `artifact.open`,
19
+ * `inbox.take`, `subscribe`, `embed.origins` ({@link FakeDaemonOptions.origins}), `shell.command` (kept in
20
+ * {@link FakeDaemon.shellCommands}; a view this fake did not open is `not_found`), `view.context` (from
21
+ * {@link FakeDaemon.setContext}), `runtime.status`, `runtime.update`; any other method is `methodNotFound` unless `handle` answers it. The Library API answers
22
+ * `GET artifact?id=` from {@link FakeDaemon.setArtifact}, `POST artifacts.thumbnail?id=` (kept in
23
+ * {@link FakeDaemon.thumbnails}), and health. {@link FakeDaemon.open} with `view` set plays a top-level view; then
24
+ * {@link FakeDaemon.shellEvent} sends the adapter what its Shell said.
25
+ */
26
+ import { createHash, randomBytes } from 'node:crypto';
27
+ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
28
+ import { createServer } from 'node:http';
29
+ import { tmpdir } from 'node:os';
30
+ import { join } from 'node:path';
31
+ import { HARNESS_FEATURES, HARNESS_PATH, HARNESS_SUBPROTOCOL, LIBRARY_ROUTES, PROTOCOL_MAX, PROTOCOL_MIN, SKILL_ARGUMENT_HINT, SKILL_COMMAND, TOOL_DEFINITIONS, WAKE_SOURCE_KIND, artifactUrl, renderSkillBody, rpcErrorCode, skillDescription, skillTypesSection, } from '@open-artifact/protocol';
32
+ import { acceptWebSocket } from "./testing-ws.js";
33
+ /** Starts a fake daemon on `127.0.0.1` at an ephemeral port. */
34
+ export async function startFakeDaemon(options = {}) {
35
+ const madeHome = !options.home;
36
+ const home = options.home ?? mkdtempSync(join(tmpdir(), 'oa-fake-daemon-'));
37
+ const token = options.token ?? randomBytes(16).toString('hex');
38
+ const version = options.version ?? '0.0.0-fake';
39
+ const speaks = options.protocols ?? { min: PROTOCOL_MIN, max: PROTOCOL_MAX };
40
+ const calls = [];
41
+ const hellos = [];
42
+ const sessions = new Map();
43
+ const inboxes = new Map();
44
+ const artifacts = new Map();
45
+ const contexts = new Map();
46
+ const views = new Set();
47
+ const shellCommands = [];
48
+ const thumbnails = new Map();
49
+ const waiters = [];
50
+ const taken = new Map();
51
+ let connections = 0;
52
+ let socket = null;
53
+ let harness = '';
54
+ let said = false;
55
+ let subscribed = false;
56
+ let nextId = 1;
57
+ const pending = new Map();
58
+ const keyOf = (params) => params.session ? `${harness}:${params.session}` : `${harness}:w:${params.workspace ?? ''}`;
59
+ const record = (call) => {
60
+ calls.push(call);
61
+ for (const waiter of [...waiters]) {
62
+ if (waiter.method !== call.method)
63
+ continue;
64
+ waiters.splice(waiters.indexOf(waiter), 1);
65
+ taken.set(call.method, calls.filter((c) => c.method === call.method).length);
66
+ waiter.done(call);
67
+ }
68
+ };
69
+ /** Throws a JSON-RPC error with the daemon's number for `code` (`rpcErrorCode`) and `data: { code, message }`. */
70
+ const fail = (code, message) => {
71
+ throw Object.assign(new Error(message), { rpc: { code: rpcErrorCode(code), message, data: { code, message } } });
72
+ };
73
+ const types = options.types ?? [{ id: 'slides', title: 'Slides', description: 'A slide deck.' }];
74
+ /** The command the adapter's skill answers to: asked for, else the first of its caps, else `open-artifact`. */
75
+ const commandOf = (asked) => (typeof asked === 'string' && asked ? asked : hellos.at(-1)?.caps?.commands?.names?.[0] ?? SKILL_COMMAND);
76
+ /** `skill.get` as the daemon renders it (`harness-skill.ts`), from the adapter's caps and the params alone. */
77
+ const skillOf = (params) => {
78
+ const caps = hellos.at(-1)?.caps ?? {};
79
+ const form = params.form ?? 'full';
80
+ if (form !== 'full' && form !== 'entry')
81
+ fail('invalid_argument', 'form: "entry" or "full".');
82
+ const agentName = params.agentName ?? caps.agentName;
83
+ const tools = params.tools ?? caps.tools;
84
+ const opens = params.opens ?? (caps.open ? 'host' : undefined);
85
+ const o = {
86
+ command: commandOf(params.command),
87
+ ...(agentName ? { agentName } : {}),
88
+ ...(tools ? { tools } : {}),
89
+ ...(params.toolNames ? { toolNames: params.toolNames } : {}),
90
+ ...(opens ? { opens } : {}),
91
+ };
92
+ const body = `${renderSkillBody(o, form)}\n\n${skillTypesSection(types)}`;
93
+ const description = skillDescription(o);
94
+ return { name: o.command, description, argumentHint: SKILL_ARGUMENT_HINT, body, version, etag: createHash('sha256').update(JSON.stringify([o.command, description, body])).digest('hex').slice(0, 16) };
95
+ };
96
+ const commandsOf = (params) => {
97
+ const command = commandOf(params.command);
98
+ return { commands: [...types].sort((a, b) => a.id.localeCompare(b.id)).map((t) => ({ text: `/${command} ${t.id} `, type: t.id, title: t.title, description: t.description ?? '' })) };
99
+ };
100
+ const answer = async (method, params) => {
101
+ const own = options.handle?.(method, params);
102
+ if (own !== undefined)
103
+ return await own;
104
+ if (method !== 'hello' && !said)
105
+ fail('not_granted', 'Say hello first.');
106
+ switch (method) {
107
+ case 'hello': {
108
+ const hello = params;
109
+ if (hello.token !== token)
110
+ fail('not_granted', 'Wrong token.');
111
+ const asked = hello.protocols ?? { min: 1, max: 1 };
112
+ const lo = Math.max(asked.min, speaks.min);
113
+ const hi = Math.min(asked.max, speaks.max);
114
+ if (lo > hi)
115
+ fail('unsupported_protocol', 'No common protocol version.');
116
+ hellos.push(hello);
117
+ harness = hello.harness;
118
+ said = true;
119
+ return { protocol: hi, daemon: version, connection: `c${connections}`, features: [...(options.features ?? HARNESS_FEATURES)] };
120
+ }
121
+ case 'session.attach': {
122
+ const attach = params;
123
+ const key = keyOf(attach);
124
+ sessions.set(key, attach);
125
+ const inbox = inboxes.get(attach.session ?? '') ?? [];
126
+ inboxes.delete(attach.session ?? '');
127
+ return { key, inbox };
128
+ }
129
+ case 'session.status':
130
+ case 'session.rename':
131
+ return { ok: true };
132
+ case 'session.detach':
133
+ sessions.delete(keyOf(params));
134
+ return { ok: true };
135
+ case 'tools.list':
136
+ return { tools: options.tools ?? TOOL_DEFINITIONS };
137
+ case 'tools.call': {
138
+ const { name, arguments: args } = params;
139
+ return options.onToolCall ? await options.onToolCall(name, args ?? {}) : { content: [{ type: 'text', text: 'ok' }] };
140
+ }
141
+ case 'agent.wrote':
142
+ return { ok: true };
143
+ case 'artifact.open': {
144
+ const id = String(params.url ?? '').replace(/^open-artifact:\/\/artifact\//, '');
145
+ return { opened: false, view_url: `${server.url}/a/${id}` };
146
+ }
147
+ case 'inbox.take': {
148
+ const session = String(params.session ?? '');
149
+ const messages = inboxes.get(session) ?? [];
150
+ inboxes.delete(session);
151
+ return { messages };
152
+ }
153
+ case 'subscribe':
154
+ subscribed = !!params.on;
155
+ return { ok: true };
156
+ case 'embed.origins':
157
+ return options.origins ?? { origins: [server.url], entries: [{ origin: server.url, kind: 'daemon', remote: false }] };
158
+ case 'shell.command': {
159
+ const { view, command } = params;
160
+ if (!view || !views.has(view))
161
+ fail('not_found', 'No such view.');
162
+ shellCommands.push({ view: view, command: command });
163
+ return { ok: true };
164
+ }
165
+ case 'skill.get':
166
+ return options.onSkill ? await options.onSkill(params) : skillOf(params);
167
+ case 'commands.list':
168
+ return options.onCommands ? await options.onCommands(params) : commandsOf(params);
169
+ case 'view.context': {
170
+ const id = String(params.url ?? '').replace(/^open-artifact:\/\/artifact\//, '');
171
+ return contexts.get(id) ?? { at: null, context: null, changed: false };
172
+ }
173
+ case 'runtime.status': {
174
+ const runtimes = hellos
175
+ .filter((h) => h.runtime?.dir && h.runtime.version)
176
+ .map((h) => ({ source: 'registered', dir: h.runtime.dir, version: h.runtime.version, protocols: h.protocols ?? { min: 1, max: 1 }, harness: h.harness }));
177
+ const status = {
178
+ running: version,
179
+ selected: runtimes[0] ?? null,
180
+ runtimes,
181
+ missing: [],
182
+ policy: { update: 'prompt', source: 'default' },
183
+ pin: null,
184
+ registry: 'https://registry.npmjs.org/',
185
+ check: null,
186
+ pending: null,
187
+ };
188
+ return { ...status, ...options.runtimeStatus };
189
+ }
190
+ case 'runtime.update': {
191
+ const asked = params.version;
192
+ const want = typeof asked === 'string' ? asked : undefined;
193
+ return options.onRuntimeUpdate ? await options.onRuntimeUpdate(want) : { installed: null, pending: false, message: 'Nothing to update (fake daemon).' };
194
+ }
195
+ default:
196
+ return fail('method_not_found', `No method ${method}.`);
197
+ }
198
+ };
199
+ const onMessage = async (connection, id, text) => {
200
+ let message;
201
+ try {
202
+ message = JSON.parse(text);
203
+ }
204
+ catch {
205
+ return;
206
+ }
207
+ if (!message.method) {
208
+ const waiting = pending.get(String(message.id));
209
+ if (!waiting)
210
+ return;
211
+ pending.delete(String(message.id));
212
+ if (message.error)
213
+ waiting.reject(new Error(message.error.message));
214
+ else
215
+ waiting.resolve(message.result);
216
+ return;
217
+ }
218
+ record({ method: message.method, params: message.params ?? {}, connection: id });
219
+ try {
220
+ const result = await answer(message.method, message.params ?? {});
221
+ if (message.id !== undefined)
222
+ connection.sendText(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: result ?? null }));
223
+ }
224
+ catch (error) {
225
+ const rpc = error.rpc ?? { code: rpcErrorCode('error'), message: error?.message ?? String(error) };
226
+ if (message.id !== undefined)
227
+ connection.sendText(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: rpc }));
228
+ }
229
+ };
230
+ const sendJson = (res, status, body) => {
231
+ res.writeHead(status, { 'Content-Type': 'application/json' });
232
+ res.end(JSON.stringify(body));
233
+ };
234
+ const http = createServer((req, res) => {
235
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
236
+ if (req.method === 'POST' && url.pathname === `/api/open-artifact.${LIBRARY_ROUTES.thumbnail}` && req.headers.authorization === `Bearer ${token}`) {
237
+ const chunks = [];
238
+ req.on('data', (chunk) => chunks.push(chunk));
239
+ req.on('end', () => {
240
+ thumbnails.set(url.searchParams.get('id') ?? '', new Uint8Array(Buffer.concat(chunks)));
241
+ sendJson(res, 200, { thumbnail: 'fake' });
242
+ });
243
+ return;
244
+ }
245
+ req.resume();
246
+ if (url.pathname === '/__open-artifact/health')
247
+ return sendJson(res, 200, { openArtifact: 1, version, pid: process.pid });
248
+ if (req.headers.authorization !== `Bearer ${token}`)
249
+ return sendJson(res, 401, { code: 'not_granted', message: 'Token required.' });
250
+ if (url.pathname === `/api/open-artifact.${LIBRARY_ROUTES.artifact}`) {
251
+ const found = artifacts.get(url.searchParams.get('id') ?? '');
252
+ return found ? sendJson(res, 200, found) : sendJson(res, 404, { code: 'not_found', message: 'No such artifact.' });
253
+ }
254
+ return sendJson(res, 404, { code: 'not_found', message: `Not served by the fake daemon: ${url.pathname}` });
255
+ });
256
+ http.on('upgrade', (req, sock, head) => {
257
+ if (new URL(req.url ?? '/', 'http://127.0.0.1').pathname !== HARNESS_PATH) {
258
+ sock.end('HTTP/1.1 404 Not Found\r\n\r\n');
259
+ return;
260
+ }
261
+ const connection = acceptWebSocket(req, sock, head, HARNESS_SUBPROTOCOL);
262
+ if (!connection)
263
+ return;
264
+ // One adapter at a time: a new connection replaces the old one.
265
+ socket?.close();
266
+ const id = ++connections;
267
+ socket = connection;
268
+ said = false;
269
+ subscribed = false;
270
+ connection.handlers = {
271
+ message: (text) => void onMessage(connection, id, text),
272
+ close: () => {
273
+ if (socket !== connection)
274
+ return;
275
+ socket = null;
276
+ said = false;
277
+ for (const waiting of pending.values())
278
+ waiting.reject(new Error('The adapter went away.'));
279
+ pending.clear();
280
+ },
281
+ };
282
+ });
283
+ await new Promise((done) => http.listen(0, '127.0.0.1', done));
284
+ const server = { url: `http://127.0.0.1:${http.address().port}` };
285
+ mkdirSync(home, { recursive: true });
286
+ writeFileSync(join(home, 'daemon.json'), JSON.stringify({ url: server.url, port: Number(server.url.split(':')[2]), pid: process.pid, token, version }));
287
+ const request = (method, params) => new Promise((resolveCall, rejectCall) => {
288
+ if (!socket || !said) {
289
+ rejectCall(new Error('No adapter is connected.'));
290
+ return;
291
+ }
292
+ const id = `d${nextId++}`;
293
+ pending.set(id, { resolve: resolveCall, reject: rejectCall });
294
+ socket.sendText(JSON.stringify({ jsonrpc: '2.0', id, method, params }));
295
+ });
296
+ return {
297
+ url: server.url,
298
+ home,
299
+ token,
300
+ calls,
301
+ hellos,
302
+ sessions,
303
+ get connected() {
304
+ return !!socket && said;
305
+ },
306
+ async wake(params) {
307
+ const artifact = params.artifact ?? artifactUrl(params.artifactId ?? 'a1');
308
+ const full = {
309
+ session: params.session ?? null,
310
+ workspace: params.workspace ?? null,
311
+ artifact,
312
+ artifactId: params.artifactId ?? artifact.replace(/^open-artifact:\/\/artifact\//, ''),
313
+ text: params.text,
314
+ source: params.source ?? {
315
+ kind: WAKE_SOURCE_KIND,
316
+ artifactId: params.artifactId ?? artifact.replace(/^open-artifact:\/\/artifact\//, ''),
317
+ url: artifact,
318
+ title: 'Untitled',
319
+ root: '',
320
+ viewUrl: `${server.url}/a/${params.artifactId ?? ''}`,
321
+ threads: [],
322
+ requests: [],
323
+ summary: params.text.slice(0, 120),
324
+ reason: 'comment',
325
+ from: { kind: 'owner' },
326
+ },
327
+ };
328
+ const result = (await request('wake.deliver', full));
329
+ return typeof result === 'string' ? { status: result } : result;
330
+ },
331
+ open(params) {
332
+ const id = params.url.replace(/^open-artifact:\/\/artifact\//, '');
333
+ if (params.view)
334
+ views.add(params.view);
335
+ return request('host.open', { ...params, session: params.session ?? null, view_url: params.view_url ?? `${server.url}/a/${id}` });
336
+ },
337
+ request,
338
+ emit(event) {
339
+ if (socket && said && subscribed)
340
+ socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: event }));
341
+ },
342
+ queueInbox(session, message) {
343
+ const list = inboxes.get(session) ?? [];
344
+ list.push({ kind: 'wake', at: new Date().toISOString(), ...message });
345
+ inboxes.set(session, list);
346
+ },
347
+ setArtifact(artifact) {
348
+ const now = new Date().toISOString();
349
+ const detail = {
350
+ url: artifactUrl(artifact.id),
351
+ title: 'Untitled',
352
+ type: 'slides',
353
+ typeTitle: 'Slides',
354
+ typeMissing: false,
355
+ root: join(home, 'artifacts', artifact.id),
356
+ view_url: `${server.url}/a/${artifact.id}`,
357
+ page_url: `${server.url}/a/${artifact.id}/page`,
358
+ owner: null,
359
+ pinned: false,
360
+ createdAt: now,
361
+ updatedAt: now,
362
+ openedAt: null,
363
+ contentAt: null,
364
+ thumbnail: null,
365
+ shared: false,
366
+ open: false,
367
+ bytes: 0,
368
+ ...artifact,
369
+ };
370
+ artifacts.set(artifact.id, detail);
371
+ return detail;
372
+ },
373
+ removeArtifact(id) {
374
+ artifacts.delete(id);
375
+ },
376
+ shellCommands,
377
+ thumbnails,
378
+ setContext(id, context) {
379
+ contexts.set(id, { at: null, context: null, changed: false, ...context });
380
+ },
381
+ shellEvent(view, event, session = null) {
382
+ const params = { view, session, event };
383
+ return request('shell.event', params);
384
+ },
385
+ waitFor(method, timeoutMs = 5000) {
386
+ const seen = taken.get(method) ?? 0;
387
+ const past = calls.filter((c) => c.method === method);
388
+ if (past.length > seen) {
389
+ taken.set(method, seen + 1);
390
+ return Promise.resolve(past[seen]);
391
+ }
392
+ return new Promise((resolveWait, rejectWait) => {
393
+ const timer = setTimeout(() => {
394
+ waiters.splice(waiters.indexOf(waiter), 1);
395
+ rejectWait(new Error(`No ${method} call within ${timeoutMs} ms.`));
396
+ }, timeoutMs);
397
+ const waiter = {
398
+ method,
399
+ seen,
400
+ done: (call) => {
401
+ clearTimeout(timer);
402
+ resolveWait(call);
403
+ },
404
+ };
405
+ waiters.push(waiter);
406
+ });
407
+ },
408
+ runtimeUpdate(available, installed = false) {
409
+ if (socket && said && subscribed)
410
+ socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'runtime/update', current: version, available, installed } }));
411
+ },
412
+ drop() {
413
+ socket?.close(1012);
414
+ },
415
+ async close() {
416
+ socket?.close(1001);
417
+ const closed = new Promise((done) => http.close(() => done()));
418
+ http.closeAllConnections?.();
419
+ await closed;
420
+ if (madeHome)
421
+ rmSync(home, { recursive: true, force: true });
422
+ },
423
+ };
424
+ }