@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,173 @@
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 { createHash } from 'node:crypto';
6
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
7
+ const MAX_FRAME = 16 * 1024 * 1024;
8
+ const PING_MS = 25_000;
9
+ /**
10
+ * Accepts an upgrade. Returns the connection, or `null` after refusing it.
11
+ * `protocol` is the subprotocol to answer with, when the client asked for it.
12
+ */
13
+ export function acceptWebSocket(request, socket, head, protocol) {
14
+ const key = request.headers['sec-websocket-key'];
15
+ if (typeof key !== 'string' || String(request.headers.upgrade).toLowerCase() !== 'websocket') {
16
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
17
+ return null;
18
+ }
19
+ const accept = createHash('sha1').update(key + GUID).digest('base64');
20
+ const asked = String(request.headers['sec-websocket-protocol'] ?? '')
21
+ .split(',')
22
+ .map((p) => p.trim())
23
+ .filter(Boolean);
24
+ const lines = ['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${accept}`];
25
+ if (protocol && asked.includes(protocol))
26
+ lines.push(`Sec-WebSocket-Protocol: ${protocol}`);
27
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`);
28
+ return new WebSocketConnection(socket, head);
29
+ }
30
+ /** One accepted WebSocket. */
31
+ export class WebSocketConnection {
32
+ /** Set by the owner to receive messages and the close. */
33
+ handlers = {};
34
+ /** True once the socket is closing or closed. */
35
+ closed = false;
36
+ socket;
37
+ buffer;
38
+ fragments = [];
39
+ pinger;
40
+ constructor(socket, head) {
41
+ this.socket = socket;
42
+ this.buffer = head?.length ? Buffer.from(head) : Buffer.alloc(0);
43
+ socket.setNoDelay?.(true);
44
+ socket.on('data', (chunk) => {
45
+ this.buffer = Buffer.concat([this.buffer, chunk]);
46
+ this.read();
47
+ });
48
+ const end = () => this.finish();
49
+ socket.on('close', end);
50
+ socket.on('end', end);
51
+ socket.on('error', end);
52
+ if (this.buffer.length)
53
+ setImmediate(() => this.read());
54
+ this.pinger = setInterval(() => this.frame(0x9, Buffer.alloc(0)), PING_MS);
55
+ this.pinger.unref?.();
56
+ }
57
+ read() {
58
+ for (;;) {
59
+ const b = this.buffer;
60
+ if (b.length < 2)
61
+ return;
62
+ const fin = (b[0] & 0x80) !== 0;
63
+ const op = b[0] & 0x0f;
64
+ const masked = (b[1] & 0x80) !== 0;
65
+ let length = b[1] & 0x7f;
66
+ let at = 2;
67
+ if (length === 126) {
68
+ if (b.length < 4)
69
+ return;
70
+ length = b.readUInt16BE(2);
71
+ at = 4;
72
+ }
73
+ else if (length === 127) {
74
+ if (b.length < 10)
75
+ return;
76
+ length = Number(b.readBigUInt64BE(2));
77
+ at = 10;
78
+ }
79
+ if (length > MAX_FRAME) {
80
+ this.close(1009);
81
+ return;
82
+ }
83
+ const maskAt = at;
84
+ if (masked)
85
+ at += 4;
86
+ if (b.length < at + length)
87
+ return;
88
+ let payload = b.subarray(at, at + length);
89
+ if (masked) {
90
+ const mask = b.subarray(maskAt, maskAt + 4);
91
+ payload = Buffer.from(payload);
92
+ for (let i = 0; i < payload.length; i++)
93
+ payload[i] = payload[i] ^ mask[i & 3];
94
+ }
95
+ this.buffer = b.subarray(at + length);
96
+ if (op === 0x8) {
97
+ this.close(1000);
98
+ return;
99
+ }
100
+ if (op === 0x9) {
101
+ this.frame(0xa, payload);
102
+ continue;
103
+ }
104
+ if (op === 0xa)
105
+ continue;
106
+ if (op === 0x1 || op === 0x2 || op === 0x0) {
107
+ this.fragments.push(payload);
108
+ if (fin) {
109
+ const text = Buffer.concat(this.fragments).toString('utf8');
110
+ this.fragments = [];
111
+ try {
112
+ this.handlers.message?.(text);
113
+ }
114
+ catch {
115
+ /* a handler's error is its own */
116
+ }
117
+ }
118
+ }
119
+ }
120
+ }
121
+ frame(op, payload) {
122
+ if (this.closed)
123
+ return;
124
+ const length = payload.length;
125
+ let header;
126
+ if (length < 126)
127
+ header = Buffer.from([0x80 | op, length]);
128
+ else if (length < 65536) {
129
+ header = Buffer.alloc(4);
130
+ header[0] = 0x80 | op;
131
+ header[1] = 126;
132
+ header.writeUInt16BE(length, 2);
133
+ }
134
+ else {
135
+ header = Buffer.alloc(10);
136
+ header[0] = 0x80 | op;
137
+ header[1] = 127;
138
+ header.writeBigUInt64BE(BigInt(length), 2);
139
+ }
140
+ try {
141
+ this.socket.write(Buffer.concat([header, payload]));
142
+ }
143
+ catch {
144
+ this.finish();
145
+ }
146
+ }
147
+ /** Sends a text frame. */
148
+ sendText(text) {
149
+ this.frame(0x1, Buffer.from(text, 'utf8'));
150
+ }
151
+ /** Sends a close frame and ends the socket. */
152
+ close(code = 1000) {
153
+ if (this.closed)
154
+ return;
155
+ const payload = Buffer.alloc(2);
156
+ payload.writeUInt16BE(code, 0);
157
+ this.frame(0x8, payload);
158
+ this.finish();
159
+ }
160
+ finish() {
161
+ if (this.closed)
162
+ return;
163
+ this.closed = true;
164
+ clearInterval(this.pinger);
165
+ try {
166
+ this.socket.end();
167
+ }
168
+ catch {
169
+ /* gone */
170
+ }
171
+ this.handlers.close?.();
172
+ }
173
+ }
@@ -0,0 +1,143 @@
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 { type ArtifactDetail, type AttachParams, type CommandEntry, type SkillParams, type SkillResult, type SkillTypeLine, type DaemonToAdapter, type EmbedOriginsResult, type HarnessEvent, type HostToShell, type ShellToHost, type ViewContextResult, type HelloParams, type HostOpenParams, type InboxMessage, type RuntimeStatus, type RuntimeUpdateResult, type ToolCallResult, type ToolDefinition, type WakeDeliverParams, type WakeDeliverResult } from '@open-artifact/protocol';
27
+ /** One call the fake daemon took from an adapter. */
28
+ export interface FakeCall {
29
+ method: string;
30
+ params: unknown;
31
+ /** The connection it came on (1 for the first, 2 after one reconnect, …). */
32
+ connection: number;
33
+ }
34
+ /** Options of {@link startFakeDaemon}. */
35
+ export interface FakeDaemonOptions {
36
+ /** The home to write `daemon.json` in (default: a new temporary folder, removed by `close`). */
37
+ home?: string;
38
+ /** The token adapters must say (default: random). */
39
+ token?: string;
40
+ /** The version `hello` answers (default `0.0.0-fake`). */
41
+ version?: string;
42
+ /** The protocol versions it speaks (default this kit's). */
43
+ protocols?: {
44
+ min: number;
45
+ max: number;
46
+ };
47
+ /** The features `hello` answers (default the real daemon's, `HARNESS_FEATURES`; `[]` plays an older daemon). */
48
+ features?: string[];
49
+ /** The installed types `skill.get` lists and `commands.list` gives an entry each (default one, `slides`). */
50
+ types?: SkillTypeLine[];
51
+ /** Answers `skill.get` (default: the protocol's template rendered for the adapter's caps and the params). */
52
+ onSkill?: (params: SkillParams) => SkillResult | Promise<SkillResult>;
53
+ /** Answers `commands.list` (default: `/<command> <type> ` per {@link FakeDaemonOptions.types}). */
54
+ onCommands?: (params: {
55
+ command?: string;
56
+ locale?: string;
57
+ }) => {
58
+ commands: CommandEntry[];
59
+ } | Promise<{
60
+ commands: CommandEntry[];
61
+ }>;
62
+ /** What `tools.list` answers (default the definitions this kit carries). */
63
+ tools?: ToolDefinition[];
64
+ /** Answers `tools.call` (default `{ content: [{ type: 'text', text: 'ok' }] }`). */
65
+ onToolCall?: (name: string, args: Record<string, unknown>) => ToolCallResult | Promise<ToolCallResult>;
66
+ /** Answers any method first; return `undefined` to leave it to the fake. Throw to answer an error. */
67
+ handle?: (method: string, params: unknown) => unknown;
68
+ /** What `embed.origins` answers (default the fake's own origin, as the daemon's). */
69
+ origins?: EmbedOriginsResult;
70
+ /**
71
+ * What `runtime.status` answers, over a default built from what adapters said in `hello`'s `runtime` (each a
72
+ * `registered` runtime; the running one is the fake's version). List `hello.runtime` / `runtime.update` in `features`
73
+ * to have adapters use it.
74
+ */
75
+ runtimeStatus?: Partial<RuntimeStatus>;
76
+ /** Answers `runtime.update` (default: nothing to update). */
77
+ onRuntimeUpdate?: (version: string | undefined) => RuntimeUpdateResult | Promise<RuntimeUpdateResult>;
78
+ }
79
+ /** A running fake daemon. */
80
+ export interface FakeDaemon {
81
+ /** Its address, `http://127.0.0.1:<port>`. */
82
+ readonly url: string;
83
+ /** The home its `daemon.json` is in. */
84
+ readonly home: string;
85
+ readonly token: string;
86
+ /** Every call adapters made, in order. */
87
+ readonly calls: FakeCall[];
88
+ /** The params of every `hello`. */
89
+ readonly hellos: HelloParams[];
90
+ /** The sessions attached now, by key (`<harness>:<session>`, else `<harness>:w:<workspace>`). */
91
+ readonly sessions: Map<string, AttachParams>;
92
+ /** Whether an adapter is connected and said hello. */
93
+ readonly connected: boolean;
94
+ /** Sends `wake.deliver` to the connected adapter; answers what it answered (`{ status }` objects included). */
95
+ wake(params: Partial<WakeDeliverParams> & {
96
+ text: string;
97
+ }): Promise<WakeDeliverResult>;
98
+ /** Sends `host.open` to the connected adapter. */
99
+ open(params: Partial<HostOpenParams> & {
100
+ url: string;
101
+ }): Promise<{
102
+ opened: boolean;
103
+ }>;
104
+ /** Sends any call to the connected adapter. */
105
+ request<M extends keyof DaemonToAdapter>(method: M, params: DaemonToAdapter[M]['params']): Promise<DaemonToAdapter[M]['result']>;
106
+ /** Sends an event to adapters that subscribed. */
107
+ emit(event: HarnessEvent): void;
108
+ /** Queues a message for a session; its next `session.attach` (or `inbox.take`) returns it. */
109
+ queueInbox(session: string, message: Partial<InboxMessage> & {
110
+ text: string;
111
+ }): void;
112
+ /** What `artifact?id=` answers for this id (missing fields get defaults). */
113
+ setArtifact(artifact: Partial<ArtifactDetail> & {
114
+ id: string;
115
+ }): ArtifactDetail;
116
+ /** `artifact?id=` answers `not_found` for this id again. */
117
+ removeArtifact(id: string): void;
118
+ /** Resolves with the next call of `method` (or a past one not waited for yet). */
119
+ waitFor(method: string, timeoutMs?: number): Promise<FakeCall>;
120
+ /** The `shell.command`s adapters sent, in order. */
121
+ readonly shellCommands: Array<{
122
+ view: string;
123
+ command: HostToShell;
124
+ }>;
125
+ /** The thumbnails saved, by artifact id (JPEG bytes). */
126
+ readonly thumbnails: Map<string, Uint8Array>;
127
+ /** What `view.context` answers for this artifact id (default `{ at: null, context: null, changed: false }`). */
128
+ setContext(id: string, context: Partial<ViewContextResult>): void;
129
+ /** Sends `shell.event` (what the Shell of top-level view `view` said) to the connected adapter. */
130
+ shellEvent(view: string, event: ShellToHost & {
131
+ artifact?: string;
132
+ }, session?: string | null): Promise<{
133
+ ok: true;
134
+ }>;
135
+ /** Tells subscribed adapters a runtime update exists (`runtime/update`; `installed`: already downloaded). */
136
+ runtimeUpdate(available: string, installed?: boolean): void;
137
+ /** Drops the connection, as a daemon that went away; the server keeps listening. */
138
+ drop(): void;
139
+ /** Stops the server (and removes the home it made). */
140
+ close(): Promise<void>;
141
+ }
142
+ /** Starts a fake daemon on `127.0.0.1` at an ephemeral port. */
143
+ export declare function startFakeDaemon(options?: FakeDaemonOptions): Promise<FakeDaemon>;