@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/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-artifacts <version>`) and its `etag`; it is written again only when the etag changes, and a file
7
+ * Open Artifacts 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 { OpenArtifactsError, SKILL_ARGUMENT_HINT, SKILL_COMMAND, SKILL_COMMAND_NAME, SKILL_GENERATED_BY, renderSkillBody, renderedSkillFile, skillDescription, skillFileKey, skillTypesSection, } from '@openartifactsai/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-artifacts',
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 OpenArtifactsError('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 OpenArtifactsError('conflict', `${file} was not written by Open Artifacts: 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-artifacts: ${again.file} rewritten for runtime ${again.version}`), (error) => log(`open-artifacts 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,44 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Duplex } from 'node:stream';
3
+ /** What a {@link WebSocketConnection} calls back. */
4
+ export interface WebSocketHandlers {
5
+ /** A complete text (or binary, decoded as UTF-8) message arrived. */
6
+ message?: (text: string) => void;
7
+ /** The connection closed, from either side. Called once. */
8
+ close?: () => void;
9
+ }
10
+ /** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
11
+ export declare function acceptKey(key: string): string;
12
+ /**
13
+ * Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
14
+ * subprotocol when the client asked for it; with a list, the first one the
15
+ * client asked for, in the list's order (an older name after the current one).
16
+ * Returns the connection, or `null` after refusing a request that is not a
17
+ * WebSocket handshake.
18
+ */
19
+ export declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, head: Buffer, protocol?: string | readonly string[]): WebSocketConnection | null;
20
+ /** One accepted WebSocket connection (server side: frames it sends are unmasked). */
21
+ export declare class WebSocketConnection {
22
+ /** The underlying socket. */
23
+ readonly socket: Duplex;
24
+ /** Set once the connection closed. */
25
+ closed: boolean;
26
+ /** Callbacks; assign them right after accepting. */
27
+ handlers: WebSocketHandlers;
28
+ private buffer;
29
+ private fragments;
30
+ private fragmentBytes;
31
+ private readonly pinger;
32
+ /** Wraps an upgraded socket; `head` is what the upgrade event already read. */
33
+ constructor(socket: Duplex, head?: Buffer);
34
+ /** Parses every complete frame in the buffer. */
35
+ private read;
36
+ /** Sends one unfragmented frame. */
37
+ private frame;
38
+ /** Sends a text message. */
39
+ sendText(text: string): void;
40
+ /** Sends a close frame with `code` and ends the connection. */
41
+ close(code?: number): void;
42
+ /** Ends the socket and calls the close handler once. */
43
+ private finish;
44
+ }
@@ -0,0 +1,204 @@
1
+ // A copy of packages/server-sdk/src/ws.ts (this package depends on @openartifactsai/protocol only); test/testing-ws.test.ts keeps the two identical.
2
+ /**
3
+ * A small WebSocket server side (RFC 6455) on Node built-ins only: text
4
+ * frames, ping/pong and close. Type servers use it for the event streams of
5
+ * mounted sites and for their own upgrades, and the daemon for the Harness API
6
+ * (`/__harness`).
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ /** The GUID RFC 6455 appends to the client key. */
10
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
11
+ /** Largest frame accepted, bytes. Bigger frames close the connection with 1009. */
12
+ const MAX_FRAME = 16 * 1024 * 1024;
13
+ /** Interval of keep-alive pings, ms. */
14
+ const PING_MS = 25_000;
15
+ /** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
16
+ export function acceptKey(key) {
17
+ return createHash('sha1').update(key + GUID).digest('base64');
18
+ }
19
+ /**
20
+ * Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
21
+ * subprotocol when the client asked for it; with a list, the first one the
22
+ * client asked for, in the list's order (an older name after the current one).
23
+ * Returns the connection, or `null` after refusing a request that is not a
24
+ * WebSocket handshake.
25
+ */
26
+ export function acceptWebSocket(request, socket, head, protocol) {
27
+ const key = request.headers['sec-websocket-key'];
28
+ if (typeof key !== 'string' || !key.trim() || String(request.headers.upgrade).toLowerCase() !== 'websocket') {
29
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
30
+ return null;
31
+ }
32
+ const asked = String(request.headers['sec-websocket-protocol'] ?? '')
33
+ .split(',')
34
+ .map((p) => p.trim())
35
+ .filter(Boolean);
36
+ const lines = ['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${acceptKey(key)}`];
37
+ const chosen = (typeof protocol === 'string' ? [protocol] : (protocol ?? [])).find((p) => asked.includes(p));
38
+ if (chosen)
39
+ lines.push(`Sec-WebSocket-Protocol: ${chosen}`);
40
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`);
41
+ return new WebSocketConnection(socket, head);
42
+ }
43
+ /** One accepted WebSocket connection (server side: frames it sends are unmasked). */
44
+ export class WebSocketConnection {
45
+ /** The underlying socket. */
46
+ socket;
47
+ /** Set once the connection closed. */
48
+ closed = false;
49
+ /** Callbacks; assign them right after accepting. */
50
+ handlers = {};
51
+ buffer;
52
+ fragments = [];
53
+ fragmentBytes = 0;
54
+ pinger;
55
+ /** Wraps an upgraded socket; `head` is what the upgrade event already read. */
56
+ constructor(socket, head) {
57
+ this.socket = socket;
58
+ this.buffer = head && head.length ? Buffer.from(head) : Buffer.alloc(0);
59
+ socket.setNoDelay?.(true);
60
+ socket.on('data', (chunk) => {
61
+ if (this.closed)
62
+ return;
63
+ this.buffer = Buffer.concat([this.buffer, chunk]);
64
+ this.read();
65
+ });
66
+ const end = () => this.finish();
67
+ socket.on('close', end);
68
+ socket.on('end', end);
69
+ socket.on('error', end);
70
+ if (this.buffer.length)
71
+ setImmediate(() => this.read());
72
+ this.pinger = setInterval(() => this.frame(0x9, Buffer.alloc(0)), PING_MS);
73
+ this.pinger.unref();
74
+ }
75
+ /** Parses every complete frame in the buffer. */
76
+ read() {
77
+ for (;;) {
78
+ if (this.closed)
79
+ return;
80
+ const b = this.buffer;
81
+ if (b.length < 2)
82
+ return;
83
+ const fin = (b[0] & 0x80) !== 0;
84
+ const op = b[0] & 0x0f;
85
+ const masked = (b[1] & 0x80) !== 0;
86
+ let len = b[1] & 0x7f;
87
+ let at = 2;
88
+ if (len === 126) {
89
+ if (b.length < 4)
90
+ return;
91
+ len = b.readUInt16BE(2);
92
+ at = 4;
93
+ }
94
+ else if (len === 127) {
95
+ if (b.length < 10)
96
+ return;
97
+ len = Number(b.readBigUInt64BE(2));
98
+ at = 10;
99
+ }
100
+ if (op >= 0x8 && (!fin || len > 125))
101
+ return this.close(1002);
102
+ if (len > MAX_FRAME)
103
+ return this.close(1009);
104
+ const maskAt = at;
105
+ if (masked)
106
+ at += 4;
107
+ if (b.length < at + len)
108
+ return;
109
+ let payload = b.subarray(at, at + len);
110
+ if (masked) {
111
+ const mask = b.subarray(maskAt, maskAt + 4);
112
+ payload = Buffer.from(payload);
113
+ for (let i = 0; i < payload.length; i++)
114
+ payload[i] = payload[i] ^ mask[i & 3];
115
+ }
116
+ this.buffer = b.subarray(at + len);
117
+ if (op === 0x8)
118
+ return this.close(1000);
119
+ if (op === 0x9) {
120
+ this.frame(0xa, payload);
121
+ continue;
122
+ }
123
+ if (op === 0xa)
124
+ continue;
125
+ if (op === 0x1 || op === 0x2 || op === 0x0) {
126
+ const continuing = this.fragments.length > 0;
127
+ if ((op === 0x0 && !continuing) || (op !== 0x0 && continuing))
128
+ return this.close(1002);
129
+ if (this.fragmentBytes + payload.length > MAX_FRAME)
130
+ return this.close(1009);
131
+ this.fragments.push(payload);
132
+ this.fragmentBytes += payload.length;
133
+ if (fin) {
134
+ const text = Buffer.concat(this.fragments).toString('utf8');
135
+ this.fragments = [];
136
+ this.fragmentBytes = 0;
137
+ try {
138
+ this.handlers.message?.(text);
139
+ }
140
+ catch {
141
+ // A handler's error is its own.
142
+ }
143
+ }
144
+ }
145
+ }
146
+ }
147
+ /** Sends one unfragmented frame. */
148
+ frame(op, payload) {
149
+ if (this.closed)
150
+ return;
151
+ const len = payload.length;
152
+ let header;
153
+ if (len < 126)
154
+ header = Buffer.from([0x80 | op, len]);
155
+ else if (len < 65536) {
156
+ header = Buffer.alloc(4);
157
+ header[0] = 0x80 | op;
158
+ header[1] = 126;
159
+ header.writeUInt16BE(len, 2);
160
+ }
161
+ else {
162
+ header = Buffer.alloc(10);
163
+ header[0] = 0x80 | op;
164
+ header[1] = 127;
165
+ header.writeBigUInt64BE(BigInt(len), 2);
166
+ }
167
+ try {
168
+ this.socket.write(Buffer.concat([header, payload]));
169
+ }
170
+ catch {
171
+ this.finish();
172
+ }
173
+ }
174
+ /** Sends a text message. */
175
+ sendText(text) {
176
+ this.frame(0x1, Buffer.from(text, 'utf8'));
177
+ }
178
+ /** Sends a close frame with `code` and ends the connection. */
179
+ close(code = 1000) {
180
+ if (this.closed)
181
+ return;
182
+ const payload = Buffer.alloc(2);
183
+ payload.writeUInt16BE(code, 0);
184
+ this.frame(0x8, payload);
185
+ this.finish();
186
+ }
187
+ /** Ends the socket and calls the close handler once. */
188
+ finish() {
189
+ if (this.closed)
190
+ return;
191
+ this.closed = true;
192
+ this.buffer = Buffer.alloc(0);
193
+ this.fragments = [];
194
+ this.fragmentBytes = 0;
195
+ clearInterval(this.pinger);
196
+ try {
197
+ this.socket.end();
198
+ }
199
+ catch {
200
+ // Already gone.
201
+ }
202
+ this.handlers.close?.();
203
+ }
204
+ }
@@ -0,0 +1,227 @@
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 { type ArtifactDetail, type AttachParams, type CommandEntry, type SkillParams, type SkillResult, type SkillTypeLine, type DaemonToAdapter, type EmbedOriginsResult, type HarnessEvent, type HarnessSampleCreateParams, type HarnessMcpCallToolParams, type PageMcpToolResult, type HarnessSampleCreateResult, type HarnessSampleDelta, type HostToShell, type ShellToHost, type ViewContextResult, type HelloParams, type HostOpenParams, type InboxMessage, type RuntimeStatus, type RuntimeUpdateResult, type SessionModelsResult, type SessionStartParams, type SessionStartResult, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverResult } from '@openartifactsai/protocol';
39
+ /** One call the fake daemon took from an adapter. */
40
+ export interface FakeCall {
41
+ method: string;
42
+ params: unknown;
43
+ /** The connection it came on (1 for the first, 2 after one reconnect, …). */
44
+ connection: number;
45
+ }
46
+ /** An error the adapter answered a call with: its message, and `error.data`'s `code` (`error` when it said none). */
47
+ export interface FakeCallError extends Error {
48
+ code: string;
49
+ /** The JSON-RPC `error.code`. */
50
+ rpcCode?: number;
51
+ data?: {
52
+ code?: string;
53
+ message?: string;
54
+ fix?: string;
55
+ };
56
+ }
57
+ /** One `sample.create` round the fake sent ({@link FakeDaemon.sample}). */
58
+ export interface FakeSampleRound {
59
+ /** The round's id (`sample.delta` and `sample.cancel` name it). */
60
+ readonly id: string;
61
+ /** The params sent. */
62
+ readonly params: HarnessSampleCreateParams;
63
+ /** The texts of the adapter's `sample.delta`s for this round, in order. */
64
+ readonly deltas: string[];
65
+ /**
66
+ * The adapter's answer. Rejects with a {@link FakeCallError} when it answered an error, and with code `cancelled` as
67
+ * soon as {@link cancel} is called (an answer that still arrives counts in {@link answers}, not here).
68
+ */
69
+ readonly result: Promise<HarnessSampleCreateResult>;
70
+ /** How many answers (result or error) the adapter sent for this round: 0 or 1, also after a cancel. */
71
+ readonly answers: number;
72
+ /** Sends `sample.cancel` for this round. */
73
+ cancel(): void;
74
+ }
75
+ /** One `mcp.callTool` the fake sent ({@link FakeDaemon.mcpCall}). */
76
+ export interface FakeMcpCall {
77
+ readonly params: HarnessMcpCallToolParams;
78
+ /** The adapter's answer; rejects with a {@link FakeCallError} on a refusal, and with code `cancelled` after {@link cancel}. */
79
+ readonly result: Promise<PageMcpToolResult>;
80
+ /** Sends `mcp.cancel` for this call. */
81
+ cancel(): void;
82
+ }
83
+ /** Options of {@link startFakeDaemon}. */
84
+ export interface FakeDaemonOptions {
85
+ /** The home to write `daemon.json` in (default: a new temporary folder, removed by `close`). */
86
+ home?: string;
87
+ /** The token adapters must say (default: random). */
88
+ token?: string;
89
+ /** The version `hello` answers (default `0.0.0-fake`). */
90
+ version?: string;
91
+ /** The protocol versions it speaks (default this kit's). */
92
+ protocols?: {
93
+ min: number;
94
+ max: number;
95
+ };
96
+ /** The features `hello` answers (default the real daemon's, `HARNESS_FEATURES`; `[]` plays an older daemon). */
97
+ features?: string[];
98
+ /** The installed types `skill.get` lists and `commands.list` gives an entry each (default one, `slides`). */
99
+ types?: SkillTypeLine[];
100
+ /** Answers `skill.get` (default: the protocol's template rendered for the adapter's caps and the params). */
101
+ onSkill?: (params: SkillParams) => SkillResult | Promise<SkillResult>;
102
+ /** Answers `commands.list` (default: `/<command> <type> ` per {@link FakeDaemonOptions.types}). */
103
+ onCommands?: (params: {
104
+ command?: string;
105
+ locale?: string;
106
+ }) => {
107
+ commands: CommandEntry[];
108
+ } | Promise<{
109
+ commands: CommandEntry[];
110
+ }>;
111
+ /** What `tools.list` answers (default the definitions this kit carries). */
112
+ tools?: ToolDefinition[];
113
+ /** Answers `tools.call` (default `{ content: [{ type: 'text', text: 'ok' }] }`). */
114
+ onToolCall?: (name: string, args: Record<string, unknown>) => ToolCallResult | Promise<ToolCallResult>;
115
+ /** Answers any method first; return `undefined` to leave it to the fake. Throw to answer an error. */
116
+ handle?: (method: string, params: unknown) => unknown;
117
+ /** What `embed.origins` answers (default the fake's own origin, as the daemon's). */
118
+ origins?: EmbedOriginsResult;
119
+ /**
120
+ * What `runtime.status` answers, over a default built from what adapters said in `hello`'s `runtime` (each a
121
+ * `registered` runtime; the running one is the fake's version). List `hello.runtime` / `runtime.update` in `features`
122
+ * to have adapters use it.
123
+ */
124
+ runtimeStatus?: Partial<RuntimeStatus>;
125
+ /** Answers `runtime.update` (default: nothing to update). */
126
+ onRuntimeUpdate?: (version: string | undefined) => RuntimeUpdateResult | Promise<RuntimeUpdateResult>;
127
+ }
128
+ /** A running fake daemon. */
129
+ export interface FakeDaemon {
130
+ /** Its address, `http://127.0.0.1:<port>`. */
131
+ readonly url: string;
132
+ /** The home its `daemon.json` is in. */
133
+ readonly home: string;
134
+ readonly token: string;
135
+ /** Every call adapters made, in order. */
136
+ readonly calls: FakeCall[];
137
+ /** The params of every `hello`. */
138
+ readonly hellos: HelloParams[];
139
+ /** The sessions attached now, by key (`<harness>:<session>`, else `<harness>:w:<workspace>`). */
140
+ readonly sessions: Map<string, AttachParams>;
141
+ /** Whether an adapter is connected and said hello. */
142
+ readonly connected: boolean;
143
+ /** Sends `wake.deliver` to the connected adapter; answers what it answered (`{ status }` objects included). */
144
+ wake(params: Partial<WakeDeliverParams> & {
145
+ text: string;
146
+ }): Promise<WakeDeliverResult>;
147
+ /** Sends `host.open` to the connected adapter. */
148
+ open(params: Partial<HostOpenParams> & {
149
+ url: string;
150
+ }): Promise<{
151
+ opened: boolean;
152
+ }>;
153
+ /**
154
+ * Sends `session.start` to the connected adapter, as the daemon does when the person picks the app for an artifact
155
+ * no session owns (missing params get defaults: artifact `a1`, a `slides` deck named `Untitled`, and a first message
156
+ * that names it). `model` and `effort` go as given, as what the person picked. Answers what the adapter answered:
157
+ * `{ started, session?, workspace? }`.
158
+ */
159
+ startSession(params?: {
160
+ text?: string;
161
+ artifact?: Partial<SessionStartParams['artifact']>;
162
+ model?: string;
163
+ effort?: string;
164
+ }): Promise<SessionStartResult>;
165
+ /**
166
+ * Sends `session.models` to the connected adapter, as the daemon does when the person is about to pick the app.
167
+ * Answers what the adapter answered, as it is: the daemon would drop what is malformed before showing it.
168
+ */
169
+ sessionModels(): Promise<SessionModelsResult>;
170
+ /**
171
+ * Sends `sample.create` to the connected adapter (missing params get defaults: a fresh `id`, artifact `a1`, an empty
172
+ * system prompt, one user turn, tier `default`, 16000 output tokens). `onDelta` sees each `sample.delta` text.
173
+ */
174
+ sample(params?: Partial<HarnessSampleCreateParams>, options?: {
175
+ onDelta?: (text: string) => void;
176
+ }): FakeSampleRound;
177
+ /** Every `sample.delta` adapters sent, in order (also those of rounds the fake does not know). */
178
+ readonly sampleDeltas: HarnessSampleDelta[];
179
+ /**
180
+ * Sends `mcp.callTool` to the connected adapter, as the daemon does for a page's allowed call of `host:<server>`
181
+ * (missing params get defaults: a fresh `id`, artifact `a1`, no arguments). List the servers with
182
+ * `request('mcp.listTools', {})`.
183
+ */
184
+ mcpCall(params: Partial<HarnessMcpCallToolParams> & {
185
+ server: string;
186
+ tool: string;
187
+ }): FakeMcpCall;
188
+ /** Sends any call to the connected adapter. */
189
+ request<M extends keyof DaemonToAdapter>(method: M, params: DaemonToAdapter[M]['params']): Promise<DaemonToAdapter[M]['result']>;
190
+ /** Sends an event to adapters that subscribed. */
191
+ emit(event: HarnessEvent): void;
192
+ /** Queues a message for a session; its next `session.attach` (or `inbox.take`) returns it. */
193
+ queueInbox(session: string, message: Partial<InboxMessage> & {
194
+ text: string;
195
+ }): void;
196
+ /** What `artifact?id=` answers for this id (missing fields get defaults). */
197
+ setArtifact(artifact: Partial<ArtifactDetail> & {
198
+ id: string;
199
+ }): ArtifactDetail;
200
+ /** `artifact?id=` answers `not_found` for this id again. */
201
+ removeArtifact(id: string): void;
202
+ /** Resolves with the next call of `method` (or a past one not waited for yet). */
203
+ waitFor(method: string, timeoutMs?: number): Promise<FakeCall>;
204
+ /** The `shell.command`s adapters sent, in order. */
205
+ readonly shellCommands: Array<{
206
+ view: string;
207
+ command: HostToShell;
208
+ }>;
209
+ /** The thumbnails saved, by artifact id (JPEG bytes). */
210
+ readonly thumbnails: Map<string, Uint8Array>;
211
+ /** What `view.context` answers for this artifact id (default `{ at: null, context: null, changed: false }`). */
212
+ setContext(id: string, context: Partial<ViewContextResult>): void;
213
+ /** Sends `shell.event` (what the Shell of top-level view `view` said) to the connected adapter. */
214
+ shellEvent(view: string, event: ShellToHost & {
215
+ artifact?: string;
216
+ }, session?: string | null): Promise<{
217
+ ok: true;
218
+ }>;
219
+ /** Tells subscribed adapters a runtime update exists (`runtime/update`; `installed`: already downloaded). */
220
+ runtimeUpdate(available: string, installed?: boolean): void;
221
+ /** Drops the connection, as a daemon that went away; the server keeps listening. */
222
+ drop(): void;
223
+ /** Stops the server (and removes the home it made). */
224
+ close(): Promise<void>;
225
+ }
226
+ /** Starts a fake daemon on `127.0.0.1` at an ephemeral port. */
227
+ export declare function startFakeDaemon(options?: FakeDaemonOptions): Promise<FakeDaemon>;