@anureo/adapter-ahp 0.2.0 → 0.3.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/README.md +35 -29
- package/examples/reference.d.ts +12 -0
- package/examples/reference.js +242 -0
- package/package.json +15 -16
- package/src/index.d.ts +118 -0
- package/src/index.js +360 -0
- package/src/websocket.d.ts +23 -0
- package/src/websocket.js +126 -0
- package/src/wire.d.ts +119 -0
- package/src/wire.js +288 -0
- package/dist/index.d.ts +0 -31
- package/dist/index.js +0 -406
- package/dist/websocket.d.ts +0 -7
- package/dist/wire.d.ts +0 -35
- package/examples/reference.mjs +0 -171
package/dist/index.js
DELETED
|
@@ -1,406 +0,0 @@
|
|
|
1
|
-
// packages/ahp/src/index.ts
|
|
2
|
-
import { HarnessSdkError as HarnessSdkError3 } from "@anureo/sdk";
|
|
3
|
-
import { assertDefinition, assertEvent, assertResult, negotiateVersion, supportsExtension, publicValue } from "@anureo/protocol";
|
|
4
|
-
|
|
5
|
-
// packages/ahp/src/wire.ts
|
|
6
|
-
import { HarnessSdkError } from "@anureo/sdk";
|
|
7
|
-
import { spawnHarnessProcess } from "@anureo/sdk/process";
|
|
8
|
-
|
|
9
|
-
class AhpWire {
|
|
10
|
-
transport;
|
|
11
|
-
options;
|
|
12
|
-
nextId = 1;
|
|
13
|
-
pending = new Map;
|
|
14
|
-
closing = false;
|
|
15
|
-
tail = Promise.resolve();
|
|
16
|
-
backlog = 0;
|
|
17
|
-
loop;
|
|
18
|
-
onNotification;
|
|
19
|
-
onClose;
|
|
20
|
-
constructor(transport, options = {}) {
|
|
21
|
-
this.transport = transport;
|
|
22
|
-
this.options = options;
|
|
23
|
-
this.loop = this.read();
|
|
24
|
-
}
|
|
25
|
-
request(method, params) {
|
|
26
|
-
if (this.closing)
|
|
27
|
-
return Promise.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
28
|
-
if (this.pending.size >= (this.options.maxPending ?? 256))
|
|
29
|
-
return Promise.reject(new HarnessSdkError("BACKPRESSURE_EXCEEDED"));
|
|
30
|
-
const id = this.nextId++, message = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
31
|
-
if (new TextEncoder().encode(message).byteLength > (this.options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
32
|
-
return Promise.reject(new HarnessSdkError("FRAME_TOO_LARGE"));
|
|
33
|
-
return new Promise((resolve, reject) => {
|
|
34
|
-
const timer = setTimeout(() => {
|
|
35
|
-
this.pending.delete(id);
|
|
36
|
-
reject(new HarnessSdkError("RPC_TIMEOUT", "RPC_TIMEOUT", false, true, { method }));
|
|
37
|
-
}, this.options.timeoutMs ?? 30000);
|
|
38
|
-
this.pending.set(id, { resolve, reject, timer });
|
|
39
|
-
this.transport.send(message).catch(() => {
|
|
40
|
-
const p = this.pending.get(id);
|
|
41
|
-
if (p) {
|
|
42
|
-
clearTimeout(p.timer);
|
|
43
|
-
this.pending.delete(id);
|
|
44
|
-
p.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
45
|
-
}
|
|
46
|
-
});
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
notify(method, params) {
|
|
50
|
-
return this.transport.send(JSON.stringify({ jsonrpc: "2.0", method, ...params === undefined ? {} : { params } }));
|
|
51
|
-
}
|
|
52
|
-
async read() {
|
|
53
|
-
let failure = new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true);
|
|
54
|
-
try {
|
|
55
|
-
for await (const frame of this.transport.messages) {
|
|
56
|
-
if (this.closing)
|
|
57
|
-
break;
|
|
58
|
-
if (new TextEncoder().encode(frame).byteLength > (this.options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
59
|
-
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
60
|
-
let value;
|
|
61
|
-
try {
|
|
62
|
-
value = JSON.parse(frame);
|
|
63
|
-
} catch {
|
|
64
|
-
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
65
|
-
}
|
|
66
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
67
|
-
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
68
|
-
const message = value;
|
|
69
|
-
if (message.jsonrpc !== "2.0")
|
|
70
|
-
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
71
|
-
if (typeof message.method === "string") {
|
|
72
|
-
if (message.id !== undefined) {
|
|
73
|
-
await this.transport.send(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Method not found" } }));
|
|
74
|
-
continue;
|
|
75
|
-
}
|
|
76
|
-
if (++this.backlog > (this.options.maxNotifications ?? 2048))
|
|
77
|
-
throw new HarnessSdkError("BACKPRESSURE_EXCEEDED");
|
|
78
|
-
this.tail = this.tail.then(() => this.onNotification?.(message.method, message.params)).catch(async (cause) => {
|
|
79
|
-
await this.fail(cause);
|
|
80
|
-
}).finally(() => this.backlog--);
|
|
81
|
-
} else {
|
|
82
|
-
const pending = this.pending.get(message.id);
|
|
83
|
-
if (!pending)
|
|
84
|
-
continue;
|
|
85
|
-
clearTimeout(pending.timer);
|
|
86
|
-
this.pending.delete(message.id);
|
|
87
|
-
if (message.error && typeof message.error === "object") {
|
|
88
|
-
const error = message.error, data = error.data && typeof error.data === "object" ? error.data : {};
|
|
89
|
-
pending.reject(new HarnessSdkError(typeof data.code === "string" ? data.code : error.code === -32601 ? "CAPABILITY_UNSUPPORTED" : "AHP_RPC_ERROR", "AHP_RPC_ERROR", data.retryable === true, data.outcomeUnknown === true));
|
|
90
|
-
} else if (Object.hasOwn(message, "result"))
|
|
91
|
-
pending.resolve(message.result);
|
|
92
|
-
else
|
|
93
|
-
pending.reject(new HarnessSdkError("PROTOCOL_ERROR"));
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
} catch (cause) {
|
|
97
|
-
failure = cause;
|
|
98
|
-
}
|
|
99
|
-
if (!this.closing)
|
|
100
|
-
await this.fail(failure);
|
|
101
|
-
}
|
|
102
|
-
async fail(cause) {
|
|
103
|
-
if (this.closing)
|
|
104
|
-
return;
|
|
105
|
-
this.closing = true;
|
|
106
|
-
for (const pending of this.pending.values()) {
|
|
107
|
-
clearTimeout(pending.timer);
|
|
108
|
-
pending.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
109
|
-
}
|
|
110
|
-
this.pending.clear();
|
|
111
|
-
this.options.diagnostic?.(cause instanceof HarnessSdkError ? cause.code : "PROTOCOL_ERROR");
|
|
112
|
-
await this.onClose?.(cause);
|
|
113
|
-
await this.transport.close();
|
|
114
|
-
}
|
|
115
|
-
async close() {
|
|
116
|
-
if (!this.closing)
|
|
117
|
-
await this.fail(new HarnessSdkError("RUNTIME_DISPOSED"));
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
async function createStdioTransport(options) {
|
|
121
|
-
const process = await (options.processFactory ?? spawnHarnessProcess)(options);
|
|
122
|
-
const max = options.maxFrameBytes ?? 8 * 1024 * 1024;
|
|
123
|
-
(async () => {
|
|
124
|
-
for await (const _ of process.stderr) {}
|
|
125
|
-
})().catch(() => {});
|
|
126
|
-
async function* messages() {
|
|
127
|
-
const decoder = new TextDecoder;
|
|
128
|
-
let buffer = "";
|
|
129
|
-
for await (const chunk of process.stdout) {
|
|
130
|
-
buffer += decoder.decode(chunk, { stream: true });
|
|
131
|
-
for (;; ) {
|
|
132
|
-
const index = buffer.indexOf(`
|
|
133
|
-
`);
|
|
134
|
-
if (index < 0)
|
|
135
|
-
break;
|
|
136
|
-
const line = buffer.slice(0, index).replace(/\r$/, "");
|
|
137
|
-
buffer = buffer.slice(index + 1);
|
|
138
|
-
if (new TextEncoder().encode(line).byteLength > max)
|
|
139
|
-
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
140
|
-
if (line)
|
|
141
|
-
yield line;
|
|
142
|
-
}
|
|
143
|
-
if (new TextEncoder().encode(buffer).byteLength > max)
|
|
144
|
-
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
145
|
-
}
|
|
146
|
-
buffer += decoder.decode();
|
|
147
|
-
if (buffer.trim())
|
|
148
|
-
throw new HarnessSdkError("PROTOCOL_ERROR", "Unterminated AHP frame");
|
|
149
|
-
}
|
|
150
|
-
return { messages: messages(), send: (message) => process.write(message + `
|
|
151
|
-
`), close: () => process.dispose() };
|
|
152
|
-
}
|
|
153
|
-
// packages/ahp/src/websocket.ts
|
|
154
|
-
import { BoundedEventQueue, HarnessSdkError as HarnessSdkError2 } from "@anureo/sdk";
|
|
155
|
-
async function createWebSocketTransport(url, options = {}) {
|
|
156
|
-
const address = new URL(url);
|
|
157
|
-
if (!["ws:", "wss:"].includes(address.protocol) || address.username || address.password || address.search || address.hash || address.protocol === "ws:" && !["127.0.0.1", "localhost", "[::1]"].includes(address.hostname))
|
|
158
|
-
throw new HarnessSdkError2("INVALID_PARAMS", "Invalid AHP WebSocket address");
|
|
159
|
-
if (!options.factory && typeof WebSocket === "undefined")
|
|
160
|
-
throw new HarnessSdkError2("WEBSOCKET_FACTORY_REQUIRED");
|
|
161
|
-
const socket = options.factory ? options.factory(url) : new WebSocket(url);
|
|
162
|
-
const queue = new BoundedEventQueue({ maxFrameBytes: options.maxFrameBytes, maxBytes: options.maxBufferedBytes ?? 16 * 1024 * 1024, maxEvents: 2048 }, (v) => new TextEncoder().encode(v).byteLength);
|
|
163
|
-
let closed = false;
|
|
164
|
-
const fail = () => {
|
|
165
|
-
queue.end(new HarnessSdkError2("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
166
|
-
};
|
|
167
|
-
socket.addEventListener("message", (event) => {
|
|
168
|
-
try {
|
|
169
|
-
if (typeof event.data !== "string")
|
|
170
|
-
throw new HarnessSdkError2("PROTOCOL_ERROR");
|
|
171
|
-
queue.push(event.data);
|
|
172
|
-
} catch (cause) {
|
|
173
|
-
queue.end(cause);
|
|
174
|
-
socket.close();
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
socket.addEventListener("close", () => {
|
|
178
|
-
closed = true;
|
|
179
|
-
fail();
|
|
180
|
-
});
|
|
181
|
-
socket.addEventListener("error", fail);
|
|
182
|
-
await new Promise((resolve, reject) => {
|
|
183
|
-
const timeout = setTimeout(() => {
|
|
184
|
-
socket.close();
|
|
185
|
-
reject(new HarnessSdkError2("RPC_TIMEOUT"));
|
|
186
|
-
}, options.timeoutMs ?? 30000);
|
|
187
|
-
const finish = () => {
|
|
188
|
-
clearTimeout(timeout);
|
|
189
|
-
socket.removeEventListener("open", opened);
|
|
190
|
-
socket.removeEventListener("error", failed);
|
|
191
|
-
socket.removeEventListener("close", failed);
|
|
192
|
-
};
|
|
193
|
-
const opened = () => {
|
|
194
|
-
finish();
|
|
195
|
-
resolve();
|
|
196
|
-
}, failed = () => {
|
|
197
|
-
finish();
|
|
198
|
-
reject(new HarnessSdkError2("RPC_CONNECTION_FAILED"));
|
|
199
|
-
};
|
|
200
|
-
socket.addEventListener("open", opened);
|
|
201
|
-
socket.addEventListener("error", failed);
|
|
202
|
-
socket.addEventListener("close", failed);
|
|
203
|
-
if (socket.readyState === 1)
|
|
204
|
-
opened();
|
|
205
|
-
});
|
|
206
|
-
return { messages: queue, async send(message) {
|
|
207
|
-
if (closed || socket.readyState !== 1)
|
|
208
|
-
throw new HarnessSdkError2("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true);
|
|
209
|
-
if (socket.bufferedAmount > (options.maxBufferedBytes ?? 16 * 1024 * 1024))
|
|
210
|
-
throw new HarnessSdkError2("BACKPRESSURE_EXCEEDED");
|
|
211
|
-
socket.send(message);
|
|
212
|
-
}, async close() {
|
|
213
|
-
if (closed)
|
|
214
|
-
return;
|
|
215
|
-
closed = true;
|
|
216
|
-
socket.close();
|
|
217
|
-
queue.end();
|
|
218
|
-
} };
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// packages/ahp/src/index.ts
|
|
222
|
-
var METADATA_EXTENSION = { name: "x-anureo/session-metadata", version: "1" };
|
|
223
|
-
|
|
224
|
-
class AhpAdapter {
|
|
225
|
-
options;
|
|
226
|
-
wire;
|
|
227
|
-
initialized;
|
|
228
|
-
result;
|
|
229
|
-
sessions = new Map;
|
|
230
|
-
responding = new Map;
|
|
231
|
-
disposed = false;
|
|
232
|
-
constructor(options) {
|
|
233
|
-
this.options = options;
|
|
234
|
-
}
|
|
235
|
-
initialize(params) {
|
|
236
|
-
negotiateVersion(params.protocolVersions);
|
|
237
|
-
return this.initialized ??= (async () => {
|
|
238
|
-
let transport;
|
|
239
|
-
if (this.options.transport)
|
|
240
|
-
transport = typeof this.options.transport === "function" ? await this.options.transport() : this.options.transport;
|
|
241
|
-
else if (this.options.url) {
|
|
242
|
-
if (!this.options.connect)
|
|
243
|
-
throw new HarnessSdkError3("WEBSOCKET_FACTORY_REQUIRED");
|
|
244
|
-
transport = await this.options.connect(this.options.url);
|
|
245
|
-
} else {
|
|
246
|
-
if (!this.options.command)
|
|
247
|
-
throw new HarnessSdkError3("HARNESS_UNAVAILABLE");
|
|
248
|
-
transport = await createStdioTransport({ ...this.options, command: this.options.command });
|
|
249
|
-
}
|
|
250
|
-
const wire = this.wire = new AhpWire(transport, this.options);
|
|
251
|
-
wire.onNotification = (method, event) => this.notification(method, event);
|
|
252
|
-
wire.onClose = async (cause) => {
|
|
253
|
-
for (const session of this.sessions.values())
|
|
254
|
-
await session.sink.fail(cause);
|
|
255
|
-
for (const pending of this.responding.values())
|
|
256
|
-
pending.reject(cause);
|
|
257
|
-
this.responding.clear();
|
|
258
|
-
};
|
|
259
|
-
const clientCapabilities = { ...params.clientCapabilities, extensions: [...(params.clientCapabilities?.extensions ?? []).filter((e) => e.name !== METADATA_EXTENSION.name), METADATA_EXTENSION] };
|
|
260
|
-
const result = await wire.request("initialize", { ...params, clientCapabilities });
|
|
261
|
-
assertResult("initialize", result);
|
|
262
|
-
negotiateVersion([result.protocolVersion]);
|
|
263
|
-
this.result = result;
|
|
264
|
-
await wire.notify("initialized");
|
|
265
|
-
return result;
|
|
266
|
-
})();
|
|
267
|
-
}
|
|
268
|
-
async notification(method, value) {
|
|
269
|
-
const known = ["session/metadata", "session/state", "turn/started", "turn/completed", "item/started", "item/delta", "item/completed", "usage/updated", "interaction/requested", "interaction/resolved", "notice", "extension"];
|
|
270
|
-
if (!known.includes(method)) {
|
|
271
|
-
const raw = publicValue(JSON.parse(JSON.stringify(value ?? null)));
|
|
272
|
-
for (const session of this.sessions.values())
|
|
273
|
-
await session.sink.emit({ type: "notice", payload: { severity: "info", code: "UNKNOWN_NOTIFICATION", message: "Unknown AHP notification", raw } });
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
assertEvent(value);
|
|
277
|
-
if (value.type !== method)
|
|
278
|
-
throw new HarnessSdkError3("PROTOCOL_ERROR");
|
|
279
|
-
const session = this.sessions.get(value.sessionId);
|
|
280
|
-
if (!session)
|
|
281
|
-
throw new HarnessSdkError3("SOURCE_SESSION_MISMATCH");
|
|
282
|
-
const last = session.lastByStream.get(value.streamId) ?? 0;
|
|
283
|
-
if (value.seq <= last)
|
|
284
|
-
return;
|
|
285
|
-
if (session.streamId && session.streamId !== value.streamId)
|
|
286
|
-
throw new HarnessSdkError3("SOURCE_STREAM_UNAVAILABLE");
|
|
287
|
-
session.streamId = value.streamId;
|
|
288
|
-
if (value.seq !== last + 1) {
|
|
289
|
-
if (!this.result || !supportsExtension(this.result.capabilities, "x-anureo/event-replay", "1"))
|
|
290
|
-
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
291
|
-
const raw = await this.wire.request("x-anureo/events/read", { sessionId: value.sessionId, streamId: value.streamId, afterSeq: last, throughSeq: value.seq - 1 });
|
|
292
|
-
if (!raw || typeof raw !== "object" || !("events" in raw) || !Array.isArray(raw.events))
|
|
293
|
-
throw new HarnessSdkError3("SOURCE_STREAM_UNAVAILABLE");
|
|
294
|
-
for (const event of raw.events) {
|
|
295
|
-
assertEvent(event);
|
|
296
|
-
if (event.sessionId !== value.sessionId || event.streamId !== value.streamId || event.seq !== (session.lastByStream.get(value.streamId) ?? 0) + 1 || event.seq >= value.seq)
|
|
297
|
-
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
298
|
-
await this.deliver(session, event);
|
|
299
|
-
}
|
|
300
|
-
if ((session.lastByStream.get(value.streamId) ?? 0) + 1 !== value.seq)
|
|
301
|
-
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
302
|
-
}
|
|
303
|
-
await this.deliver(session, value);
|
|
304
|
-
}
|
|
305
|
-
async deliver(session, event) {
|
|
306
|
-
session.lastByStream.set(event.streamId, event.seq);
|
|
307
|
-
const scope = { turnId: event.turnId, itemId: event.itemId };
|
|
308
|
-
if (event.type === "session/metadata" || event.type === "extension" && event.payload.name === METADATA_EXTENSION.name) {
|
|
309
|
-
if (!this.result || !supportsExtension(this.result.capabilities, METADATA_EXTENSION.name, METADATA_EXTENSION.version))
|
|
310
|
-
throw new HarnessSdkError3("CAPABILITY_UNSUPPORTED");
|
|
311
|
-
if (event.type === "extension" && event.payload.version !== METADATA_EXTENSION.version)
|
|
312
|
-
throw new HarnessSdkError3("CAPABILITY_UNSUPPORTED");
|
|
313
|
-
const metadata = event.type === "session/metadata" ? event.payload : event.payload.data;
|
|
314
|
-
assertDefinition("SessionMetadata", metadata);
|
|
315
|
-
if (Object.hasOwn(metadata, "title"))
|
|
316
|
-
session.metadataObserved = true;
|
|
317
|
-
await session.sink.emit({ type: "session/metadata", payload: metadata });
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
if (event.type === "interaction/requested") {
|
|
321
|
-
const request = event.payload, key = `${event.sessionId}:${request.interactionId}`;
|
|
322
|
-
session.pending.add(request.interactionId);
|
|
323
|
-
session.sink.requestInteraction(request, async (response, reason) => {
|
|
324
|
-
let resolve, reject;
|
|
325
|
-
const confirmation = new Promise((yes, no) => {
|
|
326
|
-
resolve = yes;
|
|
327
|
-
reject = no;
|
|
328
|
-
});
|
|
329
|
-
this.responding.set(key, { resolve, reject });
|
|
330
|
-
try {
|
|
331
|
-
const method = response ? "interaction/respond" : "interaction/cancel";
|
|
332
|
-
const call = this.wire.request(method, { requestId: `ahp:${event.streamId}:${event.seq}`, sessionId: event.sessionId, interactionId: request.interactionId, ...response ? { response } : { reason } });
|
|
333
|
-
const result = await Promise.race([call, confirmation]);
|
|
334
|
-
assertResult(method, result);
|
|
335
|
-
if (result.outcome === "unknown")
|
|
336
|
-
throw new HarnessSdkError3("RESULT_UNKNOWN", "RESULT_UNKNOWN", false, true);
|
|
337
|
-
} finally {
|
|
338
|
-
this.responding.delete(key);
|
|
339
|
-
session.pending.delete(request.interactionId);
|
|
340
|
-
}
|
|
341
|
-
}).catch(() => {});
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
if (event.type === "interaction/resolved") {
|
|
345
|
-
const key = `${event.sessionId}:${event.payload.interactionId}`, responding = this.responding.get(key);
|
|
346
|
-
if (responding) {
|
|
347
|
-
responding.resolve(event.payload);
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
if (session.pending.has(event.payload.interactionId)) {
|
|
351
|
-
session.pending.delete(event.payload.interactionId);
|
|
352
|
-
await session.sink.resolveInteraction(event.payload);
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
if (event.type === "session/state" && event.payload.metadata && Object.hasOwn(event.payload.metadata, "title"))
|
|
358
|
-
session.metadataObserved = true;
|
|
359
|
-
await session.sink.emit({ type: event.type, payload: event.payload }, scope);
|
|
360
|
-
}
|
|
361
|
-
async openSession(params, sink) {
|
|
362
|
-
if (!this.wire || this.disposed)
|
|
363
|
-
throw new HarnessSdkError3("NOT_INITIALIZED");
|
|
364
|
-
if (this.sessions.has(params.binding.sessionId))
|
|
365
|
-
throw new HarnessSdkError3("SESSION_ALREADY_OPEN");
|
|
366
|
-
const record = { sink, lastByStream: new Map, pending: new Set };
|
|
367
|
-
this.sessions.set(params.binding.sessionId, record);
|
|
368
|
-
try {
|
|
369
|
-
const opened = await this.wire.request("session/open", params);
|
|
370
|
-
assertResult("session/open", opened);
|
|
371
|
-
if (opened.binding.sessionId !== params.binding.sessionId || opened.binding.adapterId !== params.binding.adapterId || opened.binding.runtimeConfigId !== params.binding.runtimeConfigId)
|
|
372
|
-
throw new HarnessSdkError3("SESSION_BINDING_MISMATCH");
|
|
373
|
-
record.streamId = opened.streamId;
|
|
374
|
-
if (!record.metadataObserved && opened.state?.metadata)
|
|
375
|
-
await sink.emit({ type: "session/metadata", payload: opened.state.metadata });
|
|
376
|
-
const adapter = this;
|
|
377
|
-
return { binding: opened.binding, capabilities: opened.capabilities, async execute(method, p) {
|
|
378
|
-
const result = await adapter.wire.request(method, p);
|
|
379
|
-
assertResult(method, result);
|
|
380
|
-
return result;
|
|
381
|
-
}, async dispose() {
|
|
382
|
-
adapter.sessions.delete(params.binding.sessionId);
|
|
383
|
-
} };
|
|
384
|
-
} catch (cause) {
|
|
385
|
-
this.sessions.delete(params.binding.sessionId);
|
|
386
|
-
throw cause;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
async dispose() {
|
|
390
|
-
if (this.disposed)
|
|
391
|
-
return;
|
|
392
|
-
this.disposed = true;
|
|
393
|
-
await this.wire?.close();
|
|
394
|
-
this.sessions.clear();
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
function createAhpAdapter(options) {
|
|
398
|
-
return new AhpAdapter(options);
|
|
399
|
-
}
|
|
400
|
-
export {
|
|
401
|
-
AhpAdapter,
|
|
402
|
-
AhpWire,
|
|
403
|
-
createAhpAdapter,
|
|
404
|
-
createStdioTransport,
|
|
405
|
-
createWebSocketTransport
|
|
406
|
-
};
|
package/dist/websocket.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { AhpTransport } from "./wire.js";
|
|
2
|
-
export declare function createWebSocketTransport(url: string, options?: {
|
|
3
|
-
factory?: (url: string) => WebSocket;
|
|
4
|
-
timeoutMs?: number;
|
|
5
|
-
maxFrameBytes?: number;
|
|
6
|
-
maxBufferedBytes?: number;
|
|
7
|
-
}): Promise<AhpTransport>;
|
package/dist/wire.d.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { type HarnessProcess, type HarnessProcessOptions } from "@anureo/sdk/process";
|
|
2
|
-
export interface AhpTransport {
|
|
3
|
-
messages: AsyncIterable<string>;
|
|
4
|
-
send: (message: string) => Promise<void>;
|
|
5
|
-
close: () => Promise<void>;
|
|
6
|
-
}
|
|
7
|
-
export interface WireOptions {
|
|
8
|
-
timeoutMs?: number;
|
|
9
|
-
maxFrameBytes?: number;
|
|
10
|
-
maxPending?: number;
|
|
11
|
-
maxNotifications?: number;
|
|
12
|
-
diagnostic?: (code: string) => void;
|
|
13
|
-
}
|
|
14
|
-
export declare class AhpWire {
|
|
15
|
-
private readonly transport;
|
|
16
|
-
private readonly options;
|
|
17
|
-
private nextId;
|
|
18
|
-
private readonly pending;
|
|
19
|
-
private closing;
|
|
20
|
-
private tail;
|
|
21
|
-
private backlog;
|
|
22
|
-
private readonly loop;
|
|
23
|
-
onNotification?: (method: string, params: unknown) => Promise<void> | void;
|
|
24
|
-
onClose?: (cause: unknown) => Promise<void> | void;
|
|
25
|
-
constructor(transport: AhpTransport, options?: WireOptions);
|
|
26
|
-
request(method: string, params: unknown): Promise<unknown>;
|
|
27
|
-
notify(method: string, params?: unknown): Promise<void>;
|
|
28
|
-
private read;
|
|
29
|
-
private fail;
|
|
30
|
-
close(): Promise<void>;
|
|
31
|
-
}
|
|
32
|
-
export declare function createStdioTransport(options: HarnessProcessOptions & {
|
|
33
|
-
processFactory?: (p: HarnessProcessOptions) => Promise<HarnessProcess>;
|
|
34
|
-
maxFrameBytes?: number;
|
|
35
|
-
}): Promise<AhpTransport>;
|
package/examples/reference.mjs
DELETED
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
|
-
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
-
|
|
4
|
-
// packages/ahp/examples/reference.ts
|
|
5
|
-
import { createInterface } from "node:readline";
|
|
6
|
-
import { createHarnessRuntime, HarnessSdkError } from "@anureo/sdk";
|
|
7
|
-
import { assertRequest, negotiateVersion, supportsExtension } from "@anureo/protocol";
|
|
8
|
-
var capabilities = { turn: { interrupt: true, inputModalities: ["text"] }, interactions: ["approval"], extensions: [{ name: "x-anureo/event-replay", version: "1" }, { name: "x-anureo/session-metadata", version: "1" }] };
|
|
9
|
-
|
|
10
|
-
class ReferenceAdapter {
|
|
11
|
-
metadataEnabled = false;
|
|
12
|
-
async initialize(p) {
|
|
13
|
-
negotiateVersion(p.protocolVersions);
|
|
14
|
-
this.metadataEnabled = supportsExtension(p.clientCapabilities ?? {}, "x-anureo/session-metadata", "1");
|
|
15
|
-
return { protocolVersion: 1, runtime: { name: "reference", version: "1.0.0", adapter: "reference/1" }, capabilities };
|
|
16
|
-
}
|
|
17
|
-
async openSession(p, sink) {
|
|
18
|
-
const binding = { ...p.binding, nativeRef: { provider: "reference", value: p.binding.sessionId } };
|
|
19
|
-
let active, closed = false;
|
|
20
|
-
const metadataEnabled = this.metadataEnabled;
|
|
21
|
-
return { binding, capabilities, async execute(method, params) {
|
|
22
|
-
if (method === "session/close")
|
|
23
|
-
return { closed: true };
|
|
24
|
-
if (method === "turn/interrupt") {
|
|
25
|
-
const turnId = params.turnId;
|
|
26
|
-
if (active === turnId) {
|
|
27
|
-
active = undefined;
|
|
28
|
-
await sink.emit({ type: "turn/completed", payload: { turnId, status: "interrupted" } });
|
|
29
|
-
}
|
|
30
|
-
return { accepted: true, turnId };
|
|
31
|
-
}
|
|
32
|
-
if (method !== "turn/start")
|
|
33
|
-
throw new HarnessSdkError("CAPABILITY_UNSUPPORTED");
|
|
34
|
-
const request = params;
|
|
35
|
-
active = request.turnId;
|
|
36
|
-
await sink.emit({ type: "turn/started", payload: { turnId: request.turnId, nativeTurnId: request.turnId } });
|
|
37
|
-
const text = request.input.filter((x) => x.type === "text").map((x) => x.text).join(`
|
|
38
|
-
`);
|
|
39
|
-
if (metadataEnabled && text.startsWith("/title "))
|
|
40
|
-
await sink.emit({ type: "session/metadata", payload: { title: text.slice(7) || null } });
|
|
41
|
-
if (text !== "/wait")
|
|
42
|
-
(async () => {
|
|
43
|
-
if (text === "/approval")
|
|
44
|
-
await sink.requestInteraction({ kind: "approval", interactionId: `approval:${request.turnId}`, turnId: request.turnId, options: [{ id: "allow", label: "Allow once", semantic: "allowOnce" }, { id: "deny", label: "Deny", semantic: "deny" }] }, async () => {});
|
|
45
|
-
if (closed || active !== request.turnId)
|
|
46
|
-
return;
|
|
47
|
-
const item = { id: "message", type: "agentMessage", text, phase: "final" };
|
|
48
|
-
await sink.emit({ type: "item/started", payload: { item: { ...item, text: "" } } }, { turnId: request.turnId });
|
|
49
|
-
await sink.emit({ type: "item/completed", payload: { item } }, { turnId: request.turnId });
|
|
50
|
-
active = undefined;
|
|
51
|
-
await sink.emit({ type: "turn/completed", payload: { turnId: request.turnId, status: "completed" } });
|
|
52
|
-
})().catch(async () => {
|
|
53
|
-
if (!closed && active === request.turnId) {
|
|
54
|
-
active = undefined;
|
|
55
|
-
await sink.emit({ type: "turn/completed", payload: { turnId: request.turnId, status: "interrupted" } });
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
return { turnId: request.turnId, accepted: true };
|
|
59
|
-
}, async dispose() {
|
|
60
|
-
closed = true;
|
|
61
|
-
active = undefined;
|
|
62
|
-
} };
|
|
63
|
-
}
|
|
64
|
-
async dispose() {}
|
|
65
|
-
}
|
|
66
|
-
function createReferenceHarness(send) {
|
|
67
|
-
const runtime = createHarnessRuntime(new ReferenceAdapter), sessions = new Map, logs = new Map;
|
|
68
|
-
const publish = async (event) => {
|
|
69
|
-
if (event.type === "session/metadata")
|
|
70
|
-
event = { ...event, type: "extension", payload: { name: "x-anureo/session-metadata", version: "1", data: event.payload } };
|
|
71
|
-
const log = logs.get(event.sessionId) ?? [];
|
|
72
|
-
log.push(event);
|
|
73
|
-
if (log.length > 2048)
|
|
74
|
-
log.shift();
|
|
75
|
-
logs.set(event.sessionId, log);
|
|
76
|
-
await send(JSON.stringify({ jsonrpc: "2.0", method: event.type, params: event }));
|
|
77
|
-
};
|
|
78
|
-
const invoke = async (method, params) => {
|
|
79
|
-
if (method === "initialize") {
|
|
80
|
-
assertRequest("initialize", params);
|
|
81
|
-
return runtime.initialize(params);
|
|
82
|
-
}
|
|
83
|
-
if (method === "session/open") {
|
|
84
|
-
assertRequest("session/open", params);
|
|
85
|
-
const session = await runtime.openSession(params);
|
|
86
|
-
sessions.set(session.binding.sessionId, session);
|
|
87
|
-
const reader = session.events()[Symbol.asyncIterator](), first = await reader.next();
|
|
88
|
-
if (first.done || first.value.type !== "session/state")
|
|
89
|
-
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
90
|
-
await publish(first.value);
|
|
91
|
-
(async () => {
|
|
92
|
-
for (;; ) {
|
|
93
|
-
const entry = await reader.next();
|
|
94
|
-
if (entry.done)
|
|
95
|
-
return;
|
|
96
|
-
await publish(entry.value);
|
|
97
|
-
}
|
|
98
|
-
})().catch(() => {});
|
|
99
|
-
return { binding: session.binding, streamId: first.value.streamId, state: first.value.payload, capabilities: session.capabilities };
|
|
100
|
-
}
|
|
101
|
-
if (!params || typeof params !== "object" || !("sessionId" in params) || typeof params.sessionId !== "string")
|
|
102
|
-
throw new HarnessSdkError("INVALID_PARAMS");
|
|
103
|
-
if (method === "x-anureo/events/read") {
|
|
104
|
-
const p = params, log = logs.get(p.sessionId) ?? [];
|
|
105
|
-
const events = log.filter((e) => e.streamId === p.streamId && e.seq > p.afterSeq && e.seq <= p.throughSeq);
|
|
106
|
-
if (events[0]?.seq !== p.afterSeq + 1 && p.afterSeq < p.throughSeq)
|
|
107
|
-
throw new HarnessSdkError("SOURCE_STREAM_UNAVAILABLE");
|
|
108
|
-
return { events };
|
|
109
|
-
}
|
|
110
|
-
const session = sessions.get(params.sessionId);
|
|
111
|
-
if (!session)
|
|
112
|
-
throw new HarnessSdkError("SESSION_NOT_FOUND");
|
|
113
|
-
switch (method) {
|
|
114
|
-
case "turn/start":
|
|
115
|
-
assertRequest(method, params);
|
|
116
|
-
return session.startTurn(params);
|
|
117
|
-
case "turn/interrupt":
|
|
118
|
-
assertRequest(method, params);
|
|
119
|
-
return session.interrupt(params);
|
|
120
|
-
case "interaction/respond":
|
|
121
|
-
assertRequest(method, params);
|
|
122
|
-
return session.respond(params);
|
|
123
|
-
case "interaction/cancel":
|
|
124
|
-
assertRequest(method, params);
|
|
125
|
-
return session.cancelInteraction(params);
|
|
126
|
-
case "session/close":
|
|
127
|
-
assertRequest(method, params);
|
|
128
|
-
await session.close();
|
|
129
|
-
sessions.delete(params.sessionId);
|
|
130
|
-
return { closed: true };
|
|
131
|
-
default:
|
|
132
|
-
throw new HarnessSdkError("CAPABILITY_UNSUPPORTED");
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
return { async receive(frame) {
|
|
136
|
-
let message;
|
|
137
|
-
try {
|
|
138
|
-
message = JSON.parse(frame);
|
|
139
|
-
} catch {
|
|
140
|
-
await send(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }));
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
if (message.method === "initialized" && message.id === undefined)
|
|
144
|
-
return;
|
|
145
|
-
if (message.jsonrpc !== "2.0" || typeof message.method !== "string" || message.id === undefined) {
|
|
146
|
-
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id ?? null, error: { code: -32600, message: "Invalid request" } }));
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
try {
|
|
150
|
-
const result = await invoke(message.method, message.params);
|
|
151
|
-
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
|
|
152
|
-
} catch (cause) {
|
|
153
|
-
const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "HARNESS_ERROR";
|
|
154
|
-
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32070, message: code, data: { code, retryable: false, outcomeUnknown: false } } }));
|
|
155
|
-
}
|
|
156
|
-
}, close: () => runtime.dispose() };
|
|
157
|
-
}
|
|
158
|
-
if (__require.main == __require.module) {
|
|
159
|
-
const harness = createReferenceHarness((message) => {
|
|
160
|
-
process.stdout.write(message + `
|
|
161
|
-
`);
|
|
162
|
-
});
|
|
163
|
-
const input = createInterface({ input: process.stdin });
|
|
164
|
-
for await (const line of input) {
|
|
165
|
-
harness.receive(line);
|
|
166
|
-
}
|
|
167
|
-
await harness.close();
|
|
168
|
-
}
|
|
169
|
-
export {
|
|
170
|
-
createReferenceHarness
|
|
171
|
-
};
|