@openartifactsai/harness-kit 0.0.0-stage → 0.23.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +210 -2
- package/package.json +52 -4
- package/src/client.d.ts +160 -0
- package/src/client.js +409 -0
- package/src/context.d.ts +31 -0
- package/src/context.js +61 -0
- package/src/daemon.d.ts +177 -0
- package/src/daemon.js +293 -0
- package/src/embed/index.d.ts +230 -0
- package/src/embed/index.js +376 -0
- package/src/embed/remote.d.ts +39 -0
- package/src/embed/remote.js +51 -0
- package/src/harness.d.ts +383 -0
- package/src/harness.js +678 -0
- package/src/index.d.ts +28 -0
- package/src/index.js +20 -0
- package/src/legacy.d.ts +106 -0
- package/src/legacy.js +278 -0
- package/src/mcp.d.ts +39 -0
- package/src/mcp.js +85 -0
- package/src/runtimes.d.ts +174 -0
- package/src/runtimes.js +398 -0
- package/src/skill.d.ts +58 -0
- package/src/skill.js +88 -0
- package/src/testing-ws.d.ts +44 -0
- package/src/testing-ws.js +204 -0
- package/src/testing.d.ts +227 -0
- package/src/testing.js +564 -0
package/src/testing.js
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A fake daemon for testing an adapter (`@openartifactsai/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`, `inbox.return` (back in front of the session's queue), `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}), `view.open` (an artifact of {@link FakeDaemon.setArtifact}, by
|
|
22
|
+
* `open-artifacts://artifact/<id>` or the fake's own `/a/<id>`; any other address is `invalid_argument`; an adapter with
|
|
23
|
+
* `caps.open.embed: 'view'` gets a ticket that `shell.command` then takes), `runtime.status`, `runtime.update`; any other method is `methodNotFound` unless `handle` answers it. The Library API answers
|
|
24
|
+
* `GET artifact?id=` from {@link FakeDaemon.setArtifact}, `POST artifacts.thumbnail?id=` (kept in
|
|
25
|
+
* {@link FakeDaemon.thumbnails}), and health. {@link FakeDaemon.open} with `view` set plays a top-level view; then
|
|
26
|
+
* {@link FakeDaemon.shellEvent} sends the adapter what its Shell said. {@link FakeDaemon.startSession} sends
|
|
27
|
+
* `session.start`, as the daemon does when the person picks the app for an artifact no session owns, and
|
|
28
|
+
* {@link FakeDaemon.sessionModels} sends `session.models` (the answer as the adapter gave it: the fake does not cut it down as the daemon does). `Harness.daemon.restart()` is refused against a
|
|
29
|
+
* fake (`invalid_argument`): its `daemon.json` names this very process.
|
|
30
|
+
*
|
|
31
|
+
* {@link FakeDaemon.sample} plays the daemon's side of a page's model round: it sends `sample.create`, collects the
|
|
32
|
+
* adapter's `sample.delta` notifications for it, and `cancel()` sends `sample.cancel`:
|
|
33
|
+
*
|
|
34
|
+
* const round = fake.sample({ turns: [{ role: 'user', content: 'Hi' }] });
|
|
35
|
+
* const result = await round.result; // what the adapter's `sample.run` resolved with
|
|
36
|
+
* round.deltas; // the `sample.delta` texts, in order
|
|
37
|
+
*/
|
|
38
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
39
|
+
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
40
|
+
import { createServer } from 'node:http';
|
|
41
|
+
import { tmpdir } from 'node:os';
|
|
42
|
+
import { join } from 'node:path';
|
|
43
|
+
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 '@openartifactsai/protocol';
|
|
44
|
+
import { acceptWebSocket } from "./testing-ws.js";
|
|
45
|
+
/** Starts a fake daemon on `127.0.0.1` at an ephemeral port. */
|
|
46
|
+
export async function startFakeDaemon(options = {}) {
|
|
47
|
+
const madeHome = !options.home;
|
|
48
|
+
const home = options.home ?? mkdtempSync(join(tmpdir(), 'oa-fake-daemon-'));
|
|
49
|
+
const token = options.token ?? randomBytes(16).toString('hex');
|
|
50
|
+
const version = options.version ?? '0.0.0-fake';
|
|
51
|
+
const speaks = options.protocols ?? { min: PROTOCOL_MIN, max: PROTOCOL_MAX };
|
|
52
|
+
const calls = [];
|
|
53
|
+
const hellos = [];
|
|
54
|
+
const sessions = new Map();
|
|
55
|
+
const inboxes = new Map();
|
|
56
|
+
const artifacts = new Map();
|
|
57
|
+
const contexts = new Map();
|
|
58
|
+
const views = new Set();
|
|
59
|
+
const shellCommands = [];
|
|
60
|
+
const thumbnails = new Map();
|
|
61
|
+
const waiters = [];
|
|
62
|
+
const taken = new Map();
|
|
63
|
+
let connections = 0;
|
|
64
|
+
let socket = null;
|
|
65
|
+
let harness = '';
|
|
66
|
+
let said = false;
|
|
67
|
+
let subscribed = false;
|
|
68
|
+
let nextId = 1;
|
|
69
|
+
const pending = new Map();
|
|
70
|
+
const sampleDeltas = [];
|
|
71
|
+
/** Rounds by their round id: who wants their deltas, and how many answers came. */
|
|
72
|
+
const sampleRounds = new Map();
|
|
73
|
+
/** JSON-RPC ids of `sample.create` calls → their round id, kept after a cancel so a late answer is counted. */
|
|
74
|
+
const sampleCalls = new Map();
|
|
75
|
+
let nextRound = 1;
|
|
76
|
+
const keyOf = (params) => params.session ? `${harness}:${params.session}` : `${harness}:w:${params.workspace ?? ''}`;
|
|
77
|
+
const record = (call) => {
|
|
78
|
+
calls.push(call);
|
|
79
|
+
for (const waiter of [...waiters]) {
|
|
80
|
+
if (waiter.method !== call.method)
|
|
81
|
+
continue;
|
|
82
|
+
waiters.splice(waiters.indexOf(waiter), 1);
|
|
83
|
+
taken.set(call.method, calls.filter((c) => c.method === call.method).length);
|
|
84
|
+
waiter.done(call);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
/** Throws a JSON-RPC error with the daemon's number for `code` (`rpcErrorCode`) and `data: { code, message }`. */
|
|
88
|
+
const fail = (code, message) => {
|
|
89
|
+
throw Object.assign(new Error(message), { rpc: { code: rpcErrorCode(code), message, data: { code, message } } });
|
|
90
|
+
};
|
|
91
|
+
const types = options.types ?? [{ id: 'slides', title: 'Slides', description: 'A slide deck.' }];
|
|
92
|
+
/** The command the adapter's skill answers to: asked for, else the first of its caps, else `open-artifacts`. */
|
|
93
|
+
const commandOf = (asked) => (typeof asked === 'string' && asked ? asked : hellos.at(-1)?.caps?.commands?.names?.[0] ?? SKILL_COMMAND);
|
|
94
|
+
/** `skill.get` as the daemon renders it (`harness-skill.ts`), from the adapter's caps and the params alone. */
|
|
95
|
+
const skillOf = (params) => {
|
|
96
|
+
const caps = hellos.at(-1)?.caps ?? {};
|
|
97
|
+
const form = params.form ?? 'full';
|
|
98
|
+
if (form !== 'full' && form !== 'entry')
|
|
99
|
+
fail('invalid_argument', 'form: "entry" or "full".');
|
|
100
|
+
const agentName = params.agentName ?? caps.agentName;
|
|
101
|
+
const tools = params.tools ?? caps.tools;
|
|
102
|
+
const opens = params.opens ?? (caps.open ? 'host' : undefined);
|
|
103
|
+
const o = {
|
|
104
|
+
command: commandOf(params.command),
|
|
105
|
+
...(agentName ? { agentName } : {}),
|
|
106
|
+
...(tools ? { tools } : {}),
|
|
107
|
+
...(params.toolNames ? { toolNames: params.toolNames } : {}),
|
|
108
|
+
...(opens ? { opens } : {}),
|
|
109
|
+
};
|
|
110
|
+
const body = `${renderSkillBody(o, form)}\n\n${skillTypesSection(types)}`;
|
|
111
|
+
const description = skillDescription(o);
|
|
112
|
+
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) };
|
|
113
|
+
};
|
|
114
|
+
const commandsOf = (params) => {
|
|
115
|
+
const command = commandOf(params.command);
|
|
116
|
+
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 ?? '' })) };
|
|
117
|
+
};
|
|
118
|
+
const answer = async (method, params) => {
|
|
119
|
+
const own = options.handle?.(method, params);
|
|
120
|
+
if (own !== undefined)
|
|
121
|
+
return await own;
|
|
122
|
+
if (method !== 'hello' && !said)
|
|
123
|
+
fail('not_granted', 'Say hello first.');
|
|
124
|
+
switch (method) {
|
|
125
|
+
case 'hello': {
|
|
126
|
+
const hello = params;
|
|
127
|
+
if (hello.token !== token)
|
|
128
|
+
fail('not_granted', 'Wrong token.');
|
|
129
|
+
const asked = hello.protocols ?? { min: 1, max: 1 };
|
|
130
|
+
const lo = Math.max(asked.min, speaks.min);
|
|
131
|
+
const hi = Math.min(asked.max, speaks.max);
|
|
132
|
+
if (lo > hi)
|
|
133
|
+
fail('unsupported_protocol', 'No common protocol version.');
|
|
134
|
+
hellos.push(hello);
|
|
135
|
+
harness = hello.harness;
|
|
136
|
+
said = true;
|
|
137
|
+
return { protocol: hi, daemon: version, connection: `c${connections}`, features: [...(options.features ?? HARNESS_FEATURES)] };
|
|
138
|
+
}
|
|
139
|
+
case 'session.attach': {
|
|
140
|
+
const attach = params;
|
|
141
|
+
const key = keyOf(attach);
|
|
142
|
+
sessions.set(key, attach);
|
|
143
|
+
const inbox = inboxes.get(attach.session ?? '') ?? [];
|
|
144
|
+
inboxes.delete(attach.session ?? '');
|
|
145
|
+
return { key, inbox };
|
|
146
|
+
}
|
|
147
|
+
case 'session.status':
|
|
148
|
+
case 'session.rename':
|
|
149
|
+
return { ok: true };
|
|
150
|
+
case 'session.detach':
|
|
151
|
+
sessions.delete(keyOf(params));
|
|
152
|
+
return { ok: true };
|
|
153
|
+
case 'tools.list':
|
|
154
|
+
return { tools: options.tools ?? TOOL_DEFINITIONS };
|
|
155
|
+
case 'tools.call': {
|
|
156
|
+
const { name, arguments: args } = params;
|
|
157
|
+
return options.onToolCall ? await options.onToolCall(name, args ?? {}) : { content: [{ type: 'text', text: 'ok' }] };
|
|
158
|
+
}
|
|
159
|
+
case 'agent.wrote':
|
|
160
|
+
return { ok: true };
|
|
161
|
+
case 'artifact.open': {
|
|
162
|
+
const id = String(params.url ?? '').replace(/^open-artifacts:\/\/artifact\//, '');
|
|
163
|
+
return { opened: false, view_url: `${server.url}/a/${id}` };
|
|
164
|
+
}
|
|
165
|
+
case 'inbox.take': {
|
|
166
|
+
const session = String(params.session ?? '');
|
|
167
|
+
const messages = inboxes.get(session) ?? [];
|
|
168
|
+
inboxes.delete(session);
|
|
169
|
+
return { messages };
|
|
170
|
+
}
|
|
171
|
+
case 'inbox.return': {
|
|
172
|
+
// Back in front of what came since, as the real daemon does.
|
|
173
|
+
const session = String(params.session ?? '');
|
|
174
|
+
const back = params.messages ?? [];
|
|
175
|
+
inboxes.set(session, [...back, ...(inboxes.get(session) ?? [])]);
|
|
176
|
+
return { ok: true, returned: back.length };
|
|
177
|
+
}
|
|
178
|
+
case 'subscribe':
|
|
179
|
+
subscribed = !!params.on;
|
|
180
|
+
return { ok: true };
|
|
181
|
+
case 'embed.origins':
|
|
182
|
+
return options.origins ?? { origins: [server.url], entries: [{ origin: server.url, kind: 'daemon', remote: false }] };
|
|
183
|
+
case 'shell.command': {
|
|
184
|
+
const { view, command } = params;
|
|
185
|
+
if (!view || !views.has(view))
|
|
186
|
+
fail('not_found', 'No such view.');
|
|
187
|
+
shellCommands.push({ view: view, command: command });
|
|
188
|
+
return { ok: true };
|
|
189
|
+
}
|
|
190
|
+
case 'skill.get':
|
|
191
|
+
return options.onSkill ? await options.onSkill(params) : skillOf(params);
|
|
192
|
+
case 'commands.list':
|
|
193
|
+
return options.onCommands ? await options.onCommands(params) : commandsOf(params);
|
|
194
|
+
case 'view.context': {
|
|
195
|
+
const id = String(params.url ?? '').replace(/^open-artifacts:\/\/artifact\//, '');
|
|
196
|
+
return contexts.get(id) ?? { at: null, context: null, changed: false };
|
|
197
|
+
}
|
|
198
|
+
case 'view.open': {
|
|
199
|
+
const url = String(params.url ?? '');
|
|
200
|
+
const match = /^open-artifacts:\/\/artifact\/([^/?#]+)$/.exec(url) ?? new RegExp(`^${server.url.replace(/[.]/g, '\\.')}/a/([^/?#]+)/?(?:[?#].*)?$`).exec(url);
|
|
201
|
+
if (!match)
|
|
202
|
+
return fail('invalid_argument', "url: one of this daemon's artifacts (open-artifacts://artifact/<id> or its /a/<id> address).");
|
|
203
|
+
const found = artifacts.get(match[1]);
|
|
204
|
+
if (!found)
|
|
205
|
+
return fail('not_found', `No artifact ${match[1]}.`);
|
|
206
|
+
const viewUrl = `${server.url}/a/${found.id}`;
|
|
207
|
+
const open = hellos.at(-1)?.caps?.open;
|
|
208
|
+
if (!open || typeof open !== 'object' || open.embed !== 'view')
|
|
209
|
+
return { url: found.url, view_url: found.view_url, title: found.title, embed_url: viewUrl };
|
|
210
|
+
const view = randomBytes(12).toString('hex');
|
|
211
|
+
views.add(view);
|
|
212
|
+
return { url: found.url, view_url: found.view_url, title: found.title, view, embed_url: `${viewUrl}?oa_view=${view}` };
|
|
213
|
+
}
|
|
214
|
+
case 'runtime.status': {
|
|
215
|
+
const runtimes = hellos
|
|
216
|
+
.filter((h) => h.runtime?.dir && h.runtime.version)
|
|
217
|
+
.map((h) => ({ source: 'registered', dir: h.runtime.dir, version: h.runtime.version, protocols: h.protocols ?? { min: 1, max: 1 }, harness: h.harness }));
|
|
218
|
+
const status = {
|
|
219
|
+
running: version,
|
|
220
|
+
selected: runtimes[0] ?? null,
|
|
221
|
+
runtimes,
|
|
222
|
+
missing: [],
|
|
223
|
+
policy: { update: 'prompt', source: 'default' },
|
|
224
|
+
pin: null,
|
|
225
|
+
registry: 'https://registry.npmjs.org/',
|
|
226
|
+
check: null,
|
|
227
|
+
pending: null,
|
|
228
|
+
};
|
|
229
|
+
return { ...status, ...options.runtimeStatus };
|
|
230
|
+
}
|
|
231
|
+
case 'runtime.update': {
|
|
232
|
+
const asked = params.version;
|
|
233
|
+
const want = typeof asked === 'string' ? asked : undefined;
|
|
234
|
+
return options.onRuntimeUpdate ? await options.onRuntimeUpdate(want) : { installed: null, pending: false, message: 'Nothing to update (fake daemon).' };
|
|
235
|
+
}
|
|
236
|
+
default:
|
|
237
|
+
return fail('method_not_found', `No method ${method}.`);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
const onMessage = async (connection, id, text) => {
|
|
241
|
+
let message;
|
|
242
|
+
try {
|
|
243
|
+
message = JSON.parse(text);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (!message.method) {
|
|
249
|
+
const round = sampleCalls.get(String(message.id));
|
|
250
|
+
if (round !== undefined) {
|
|
251
|
+
const known = sampleRounds.get(round);
|
|
252
|
+
if (known)
|
|
253
|
+
known.answers++;
|
|
254
|
+
}
|
|
255
|
+
const waiting = pending.get(String(message.id));
|
|
256
|
+
if (!waiting)
|
|
257
|
+
return;
|
|
258
|
+
pending.delete(String(message.id));
|
|
259
|
+
if (message.error) {
|
|
260
|
+
const data = message.error.data;
|
|
261
|
+
waiting.reject(Object.assign(new Error(message.error.message), { code: data?.code ?? 'error', rpcCode: message.error.code, ...(data ? { data } : {}) }));
|
|
262
|
+
}
|
|
263
|
+
else
|
|
264
|
+
waiting.resolve(message.result);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
record({ method: message.method, params: message.params ?? {}, connection: id });
|
|
268
|
+
if (message.method === 'sample.delta' && message.id === undefined) {
|
|
269
|
+
const delta = message.params;
|
|
270
|
+
if (typeof delta?.id === 'string' && typeof delta.text === 'string') {
|
|
271
|
+
sampleDeltas.push({ id: delta.id, text: delta.text });
|
|
272
|
+
const round = sampleRounds.get(delta.id);
|
|
273
|
+
if (round) {
|
|
274
|
+
round.deltas.push(delta.text);
|
|
275
|
+
round.onDelta?.(delta.text);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
const result = await answer(message.method, message.params ?? {});
|
|
282
|
+
if (message.id !== undefined)
|
|
283
|
+
connection.sendText(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: result ?? null }));
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
const rpc = error.rpc ?? { code: rpcErrorCode('error'), message: error?.message ?? String(error) };
|
|
287
|
+
if (message.id !== undefined)
|
|
288
|
+
connection.sendText(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: rpc }));
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
const sendJson = (res, status, body) => {
|
|
292
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
293
|
+
res.end(JSON.stringify(body));
|
|
294
|
+
};
|
|
295
|
+
const http = createServer((req, res) => {
|
|
296
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
297
|
+
if (req.method === 'POST' && url.pathname === `/api/open-artifacts.${LIBRARY_ROUTES.thumbnail}` && req.headers.authorization === `Bearer ${token}`) {
|
|
298
|
+
const chunks = [];
|
|
299
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
300
|
+
req.on('end', () => {
|
|
301
|
+
thumbnails.set(url.searchParams.get('id') ?? '', new Uint8Array(Buffer.concat(chunks)));
|
|
302
|
+
sendJson(res, 200, { thumbnail: 'fake' });
|
|
303
|
+
});
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
req.resume();
|
|
307
|
+
if (url.pathname === '/__open-artifacts/health')
|
|
308
|
+
return sendJson(res, 200, { openArtifacts: 1, version, pid: process.pid });
|
|
309
|
+
if (req.headers.authorization !== `Bearer ${token}`)
|
|
310
|
+
return sendJson(res, 401, { code: 'not_granted', message: 'Token required.' });
|
|
311
|
+
if (url.pathname === `/api/open-artifacts.${LIBRARY_ROUTES.harnesses}`) {
|
|
312
|
+
// The one adapter it serves (a new connection replaces the old one), as the daemon lists connections.
|
|
313
|
+
const adapters = socket && said && harness ? [{ id: `c${connections}`, harness, caps: hellos.at(-1)?.caps ?? {}, sessions: [...sessions.keys()], polling: false }] : [];
|
|
314
|
+
return sendJson(res, 200, { harnesses: adapters.map((a) => ({ name: a.harness, title: a.harness, agentName: a.harness, connected: true, sessions: [] })), adapters, sessions: [] });
|
|
315
|
+
}
|
|
316
|
+
if (url.pathname === `/api/open-artifacts.${LIBRARY_ROUTES.artifact}`) {
|
|
317
|
+
const found = artifacts.get(url.searchParams.get('id') ?? '');
|
|
318
|
+
return found ? sendJson(res, 200, found) : sendJson(res, 404, { code: 'not_found', message: 'No such artifact.' });
|
|
319
|
+
}
|
|
320
|
+
return sendJson(res, 404, { code: 'not_found', message: `Not served by the fake daemon: ${url.pathname}` });
|
|
321
|
+
});
|
|
322
|
+
http.on('upgrade', (req, sock, head) => {
|
|
323
|
+
if (new URL(req.url ?? '/', 'http://127.0.0.1').pathname !== HARNESS_PATH) {
|
|
324
|
+
sock.end('HTTP/1.1 404 Not Found\r\n\r\n');
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const connection = acceptWebSocket(req, sock, head, HARNESS_SUBPROTOCOL);
|
|
328
|
+
if (!connection)
|
|
329
|
+
return;
|
|
330
|
+
// One adapter at a time: a new connection replaces the old one.
|
|
331
|
+
socket?.close();
|
|
332
|
+
const id = ++connections;
|
|
333
|
+
socket = connection;
|
|
334
|
+
said = false;
|
|
335
|
+
subscribed = false;
|
|
336
|
+
connection.handlers = {
|
|
337
|
+
message: (text) => void onMessage(connection, id, text),
|
|
338
|
+
close: () => {
|
|
339
|
+
if (socket !== connection)
|
|
340
|
+
return;
|
|
341
|
+
socket = null;
|
|
342
|
+
said = false;
|
|
343
|
+
for (const waiting of pending.values())
|
|
344
|
+
waiting.reject(new Error('The adapter went away.'));
|
|
345
|
+
pending.clear();
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
});
|
|
349
|
+
await new Promise((done) => http.listen(0, '127.0.0.1', done));
|
|
350
|
+
const server = { url: `http://127.0.0.1:${http.address().port}` };
|
|
351
|
+
mkdirSync(home, { recursive: true });
|
|
352
|
+
writeFileSync(join(home, 'daemon.json'), JSON.stringify({ url: server.url, port: Number(server.url.split(':')[2]), pid: process.pid, token, version }));
|
|
353
|
+
/** Sends a call; `onId` learns its JSON-RPC id before it goes out. */
|
|
354
|
+
const send = (method, params, onId) => new Promise((resolveCall, rejectCall) => {
|
|
355
|
+
if (!socket || !said) {
|
|
356
|
+
rejectCall(Object.assign(new Error('No adapter is connected.'), { code: 'disconnected' }));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
const id = `d${nextId++}`;
|
|
360
|
+
onId?.(id);
|
|
361
|
+
pending.set(id, { resolve: resolveCall, reject: rejectCall });
|
|
362
|
+
socket.sendText(JSON.stringify({ jsonrpc: '2.0', id, method, params }));
|
|
363
|
+
});
|
|
364
|
+
const request = (method, params) => send(method, params);
|
|
365
|
+
const sample = (given = {}, opts = {}) => {
|
|
366
|
+
const params = {
|
|
367
|
+
id: given.id ?? `r${nextRound++}`,
|
|
368
|
+
artifactId: 'a1',
|
|
369
|
+
artifact: 'Untitled',
|
|
370
|
+
system: '',
|
|
371
|
+
turns: [{ role: 'user', content: 'Hello' }],
|
|
372
|
+
tier: 'default',
|
|
373
|
+
maxOutputTokens: 16_000,
|
|
374
|
+
...given,
|
|
375
|
+
};
|
|
376
|
+
const state = { deltas: [], answers: 0, ...(opts.onDelta ? { onDelta: opts.onDelta } : {}) };
|
|
377
|
+
sampleRounds.set(params.id, state);
|
|
378
|
+
let rpcId = '';
|
|
379
|
+
let cancelled = null;
|
|
380
|
+
const stopped = new Promise((_, reject) => (cancelled = reject));
|
|
381
|
+
stopped.catch(() => undefined);
|
|
382
|
+
const answered = send('sample.create', params, (id) => {
|
|
383
|
+
rpcId = id;
|
|
384
|
+
sampleCalls.set(id, params.id);
|
|
385
|
+
});
|
|
386
|
+
const result = Promise.race([answered, stopped]);
|
|
387
|
+
result.catch(() => undefined);
|
|
388
|
+
return {
|
|
389
|
+
id: params.id,
|
|
390
|
+
params,
|
|
391
|
+
deltas: state.deltas,
|
|
392
|
+
result,
|
|
393
|
+
get answers() {
|
|
394
|
+
return state.answers;
|
|
395
|
+
},
|
|
396
|
+
cancel() {
|
|
397
|
+
// The call stays known (its id), so an answer that still comes is counted, not lost.
|
|
398
|
+
pending.delete(rpcId);
|
|
399
|
+
if (socket && said)
|
|
400
|
+
socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'sample.cancel', params: { id: params.id } }));
|
|
401
|
+
cancelled?.(Object.assign(new Error(`Round ${params.id} was cancelled.`), { code: 'cancelled' }));
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
};
|
|
405
|
+
const mcpCall = (given) => {
|
|
406
|
+
const params = { id: given.id ?? `m${nextRound++}`, artifactId: 'a1', arguments: {}, ...given };
|
|
407
|
+
let rpcId = '';
|
|
408
|
+
let cancelled = null;
|
|
409
|
+
const stopped = new Promise((_, reject) => (cancelled = reject));
|
|
410
|
+
stopped.catch(() => undefined);
|
|
411
|
+
const result = Promise.race([send('mcp.callTool', params, (id) => (rpcId = id)), stopped]);
|
|
412
|
+
result.catch(() => undefined);
|
|
413
|
+
return {
|
|
414
|
+
params,
|
|
415
|
+
result,
|
|
416
|
+
cancel() {
|
|
417
|
+
pending.delete(rpcId);
|
|
418
|
+
if (socket && said)
|
|
419
|
+
socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'mcp.cancel', params: { id: params.id } }));
|
|
420
|
+
cancelled?.(Object.assign(new Error(`Call ${params.id} was cancelled.`), { code: 'cancelled' }));
|
|
421
|
+
},
|
|
422
|
+
};
|
|
423
|
+
};
|
|
424
|
+
return {
|
|
425
|
+
url: server.url,
|
|
426
|
+
home,
|
|
427
|
+
token,
|
|
428
|
+
calls,
|
|
429
|
+
hellos,
|
|
430
|
+
sessions,
|
|
431
|
+
get connected() {
|
|
432
|
+
return !!socket && said;
|
|
433
|
+
},
|
|
434
|
+
async wake(params) {
|
|
435
|
+
const artifact = params.artifact ?? artifactUrl(params.artifactId ?? 'a1');
|
|
436
|
+
const full = {
|
|
437
|
+
session: params.session ?? null,
|
|
438
|
+
workspace: params.workspace ?? null,
|
|
439
|
+
artifact,
|
|
440
|
+
artifactId: params.artifactId ?? artifact.replace(/^open-artifacts:\/\/artifact\//, ''),
|
|
441
|
+
text: params.text,
|
|
442
|
+
source: params.source ?? {
|
|
443
|
+
kind: WAKE_SOURCE_KIND,
|
|
444
|
+
artifactId: params.artifactId ?? artifact.replace(/^open-artifacts:\/\/artifact\//, ''),
|
|
445
|
+
url: artifact,
|
|
446
|
+
title: 'Untitled',
|
|
447
|
+
root: '',
|
|
448
|
+
viewUrl: `${server.url}/a/${params.artifactId ?? ''}`,
|
|
449
|
+
threads: [],
|
|
450
|
+
requests: [],
|
|
451
|
+
summary: params.text.slice(0, 120),
|
|
452
|
+
reason: 'comment',
|
|
453
|
+
from: { kind: 'owner' },
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
const result = (await request('wake.deliver', full));
|
|
457
|
+
return typeof result === 'string' ? { status: result } : result;
|
|
458
|
+
},
|
|
459
|
+
open(params) {
|
|
460
|
+
const id = params.url.replace(/^open-artifacts:\/\/artifact\//, '');
|
|
461
|
+
if (params.view)
|
|
462
|
+
views.add(params.view);
|
|
463
|
+
return request('host.open', { ...params, session: params.session ?? null, view_url: params.view_url ?? `${server.url}/a/${id}` });
|
|
464
|
+
},
|
|
465
|
+
startSession(params = {}) {
|
|
466
|
+
const id = params.artifact?.id ?? 'a1';
|
|
467
|
+
const url = params.artifact?.url ?? artifactUrl(id);
|
|
468
|
+
const artifact = { id, url, title: 'Untitled', type: 'slides', root: join(home, 'artifacts', id), ...params.artifact };
|
|
469
|
+
return request('session.start', { text: params.text ?? `Take over artifact ${url}.`, artifact, ...(params.model !== undefined ? { model: params.model } : {}), ...(params.effort !== undefined ? { effort: params.effort } : {}) });
|
|
470
|
+
},
|
|
471
|
+
sessionModels() {
|
|
472
|
+
return request('session.models', {});
|
|
473
|
+
},
|
|
474
|
+
request,
|
|
475
|
+
sample,
|
|
476
|
+
sampleDeltas,
|
|
477
|
+
mcpCall,
|
|
478
|
+
emit(event) {
|
|
479
|
+
if (socket && said && subscribed)
|
|
480
|
+
socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: event }));
|
|
481
|
+
},
|
|
482
|
+
queueInbox(session, message) {
|
|
483
|
+
const list = inboxes.get(session) ?? [];
|
|
484
|
+
list.push({ kind: 'wake', at: new Date().toISOString(), ...message });
|
|
485
|
+
inboxes.set(session, list);
|
|
486
|
+
},
|
|
487
|
+
setArtifact(artifact) {
|
|
488
|
+
const now = new Date().toISOString();
|
|
489
|
+
const detail = {
|
|
490
|
+
url: artifactUrl(artifact.id),
|
|
491
|
+
title: 'Untitled',
|
|
492
|
+
type: 'slides',
|
|
493
|
+
typeTitle: 'Slides',
|
|
494
|
+
typeMissing: false,
|
|
495
|
+
root: join(home, 'artifacts', artifact.id),
|
|
496
|
+
view_url: `${server.url}/a/${artifact.id}`,
|
|
497
|
+
page_url: `${server.url}/a/${artifact.id}/page`,
|
|
498
|
+
owner: null,
|
|
499
|
+
pinned: false,
|
|
500
|
+
createdAt: now,
|
|
501
|
+
updatedAt: now,
|
|
502
|
+
openedAt: null,
|
|
503
|
+
contentAt: null,
|
|
504
|
+
thumbnail: null,
|
|
505
|
+
shared: false,
|
|
506
|
+
open: false,
|
|
507
|
+
bytes: 0,
|
|
508
|
+
...artifact,
|
|
509
|
+
};
|
|
510
|
+
artifacts.set(artifact.id, detail);
|
|
511
|
+
return detail;
|
|
512
|
+
},
|
|
513
|
+
removeArtifact(id) {
|
|
514
|
+
artifacts.delete(id);
|
|
515
|
+
},
|
|
516
|
+
shellCommands,
|
|
517
|
+
thumbnails,
|
|
518
|
+
setContext(id, context) {
|
|
519
|
+
contexts.set(id, { at: null, context: null, changed: false, ...context });
|
|
520
|
+
},
|
|
521
|
+
shellEvent(view, event, session = null) {
|
|
522
|
+
const params = { view, session, event };
|
|
523
|
+
return request('shell.event', params);
|
|
524
|
+
},
|
|
525
|
+
waitFor(method, timeoutMs = 5000) {
|
|
526
|
+
const seen = taken.get(method) ?? 0;
|
|
527
|
+
const past = calls.filter((c) => c.method === method);
|
|
528
|
+
if (past.length > seen) {
|
|
529
|
+
taken.set(method, seen + 1);
|
|
530
|
+
return Promise.resolve(past[seen]);
|
|
531
|
+
}
|
|
532
|
+
return new Promise((resolveWait, rejectWait) => {
|
|
533
|
+
const timer = setTimeout(() => {
|
|
534
|
+
waiters.splice(waiters.indexOf(waiter), 1);
|
|
535
|
+
rejectWait(new Error(`No ${method} call within ${timeoutMs} ms.`));
|
|
536
|
+
}, timeoutMs);
|
|
537
|
+
const waiter = {
|
|
538
|
+
method,
|
|
539
|
+
seen,
|
|
540
|
+
done: (call) => {
|
|
541
|
+
clearTimeout(timer);
|
|
542
|
+
resolveWait(call);
|
|
543
|
+
},
|
|
544
|
+
};
|
|
545
|
+
waiters.push(waiter);
|
|
546
|
+
});
|
|
547
|
+
},
|
|
548
|
+
runtimeUpdate(available, installed = false) {
|
|
549
|
+
if (socket && said && subscribed)
|
|
550
|
+
socket.sendText(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'runtime/update', current: version, available, installed } }));
|
|
551
|
+
},
|
|
552
|
+
drop() {
|
|
553
|
+
socket?.close(1012);
|
|
554
|
+
},
|
|
555
|
+
async close() {
|
|
556
|
+
socket?.close(1001);
|
|
557
|
+
const closed = new Promise((done) => http.close(() => done()));
|
|
558
|
+
http.closeAllConnections?.();
|
|
559
|
+
await closed;
|
|
560
|
+
if (madeHome)
|
|
561
|
+
rmSync(home, { recursive: true, force: true });
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
}
|