@muse-code/sdk 0.1.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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +270 -0
  3. package/dist/src/connection/connection.d.ts +128 -0
  4. package/dist/src/connection/connection.js +548 -0
  5. package/dist/src/connection/spawn.d.ts +161 -0
  6. package/dist/src/connection/spawn.js +462 -0
  7. package/dist/src/errors.d.ts +54 -0
  8. package/dist/src/errors.js +51 -0
  9. package/dist/src/facade/approval.d.ts +76 -0
  10. package/dist/src/facade/approval.js +165 -0
  11. package/dist/src/facade/client.d.ts +153 -0
  12. package/dist/src/facade/client.js +300 -0
  13. package/dist/src/facade/discarded.d.ts +36 -0
  14. package/dist/src/facade/discarded.js +36 -0
  15. package/dist/src/facade/gap-fill.d.ts +80 -0
  16. package/dist/src/facade/gap-fill.js +375 -0
  17. package/dist/src/facade/host-death.d.ts +139 -0
  18. package/dist/src/facade/host-death.js +96 -0
  19. package/dist/src/facade/session.d.ts +309 -0
  20. package/dist/src/facade/session.js +639 -0
  21. package/dist/src/facade/turn-handle.d.ts +156 -0
  22. package/dist/src/facade/turn-handle.js +271 -0
  23. package/dist/src/facade/turn-submit.d.ts +72 -0
  24. package/dist/src/facade/turn-submit.js +168 -0
  25. package/dist/src/fingerprint.d.ts +37 -0
  26. package/dist/src/fingerprint.js +54 -0
  27. package/dist/src/fold/item-store.d.ts +110 -0
  28. package/dist/src/fold/item-store.js +169 -0
  29. package/dist/src/fold/session-fold.d.ts +455 -0
  30. package/dist/src/fold/session-fold.js +399 -0
  31. package/dist/src/fold/state-store.d.ts +68 -0
  32. package/dist/src/fold/state-store.js +89 -0
  33. package/dist/src/index.d.ts +56 -0
  34. package/dist/src/index.js +52 -0
  35. package/dist/src/pending/pending-command-set.d.ts +361 -0
  36. package/dist/src/pending/pending-command-set.js +468 -0
  37. package/package.json +39 -0
@@ -0,0 +1,548 @@
1
+ /**
2
+ * Duplex-agnostic MSP NDJSON connection (spec 14990 FR-012/014/015/016).
3
+ *
4
+ * The transport supplies decoded UTF-8 chunks. Chunks may be empty and may
5
+ * split anywhere — including mid surrogate pair: the byte accounting below
6
+ * reconciles split pairs (FR-012(a)), so transports need not align chunks
7
+ * to character boundaries. The Node child-process binding — which sets
8
+ * stdout's encoding before implementing this interface — is one
9
+ * well-behaved transport, not the general guarantee.
10
+ */
11
+ const DEFAULT_FRAME_LIMIT_BYTES = 10_485_760;
12
+ /**
13
+ * Module-private friend seam (never on the package barrel, like spawn.ts's
14
+ * `ownedTransport`): the submission tail a process-owning transport adopts as
15
+ * its DEFAULT `flushed`, so a close routed around this class — e.g. the
16
+ * public `child.close()` — gets the same step 0 (PR #22819 round 4).
17
+ */
18
+ export const submissionTail = Symbol("Connection.submissionTail");
19
+ /** The one typed error family consumers branch on (INV-012). */
20
+ export class MspError extends Error {
21
+ code;
22
+ kind;
23
+ data;
24
+ retryable;
25
+ constructor(error) {
26
+ super(error.message);
27
+ this.name = "MspError";
28
+ this.code = error.code;
29
+ this.kind = error.data?.kind ?? "unknown";
30
+ this.data = error.data === undefined ? {} : { ...error.data };
31
+ this.retryable = error.data?.retryable;
32
+ }
33
+ }
34
+ /** A local framing/correlation violation, never a server-authored MSP error. */
35
+ export class ProtocolError extends Error {
36
+ line;
37
+ constructor(message, line) {
38
+ super(message);
39
+ this.name = "ProtocolError";
40
+ this.line = line;
41
+ }
42
+ }
43
+ function requestKey(id) {
44
+ return `${typeof id === "number" ? "number" : "string"}:${String(id)}`;
45
+ }
46
+ function utf8ByteLength(text) {
47
+ let bytes = 0;
48
+ for (const scalar of text) {
49
+ const point = scalar.codePointAt(0);
50
+ bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
51
+ }
52
+ return bytes;
53
+ }
54
+ /** FM-007: error evidence is bounded in UTF-8 BYTES, never code units. */
55
+ function truncateToUtf8Bytes(text, limitBytes) {
56
+ let bytes = 0;
57
+ let end = 0;
58
+ for (const scalar of text) {
59
+ const point = scalar.codePointAt(0);
60
+ const width = point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
61
+ if (bytes + width > limitBytes)
62
+ break;
63
+ bytes += width;
64
+ end += scalar.length;
65
+ }
66
+ return text.slice(0, end);
67
+ }
68
+ function canonical(value) {
69
+ if (Array.isArray(value))
70
+ return `[${value.map(canonical).join(",")}]`;
71
+ if (value !== null && typeof value === "object") {
72
+ const object = value;
73
+ return `{${Object.keys(object)
74
+ .sort()
75
+ .map((key) => `${JSON.stringify(key)}:${canonical(object[key])}`)
76
+ .join(",")}}`;
77
+ }
78
+ return JSON.stringify(value);
79
+ }
80
+ /** Create the SDK-owned UUIDv7 command-id source for a connection/client. */
81
+ export function createUuidV7Mint() {
82
+ let lastMs = -1;
83
+ let sequence = 0;
84
+ return () => {
85
+ let now = Date.now();
86
+ if (now <= lastMs) {
87
+ now = lastMs;
88
+ sequence += 1;
89
+ if (sequence > 0x0fff) {
90
+ now += 1;
91
+ sequence = 0;
92
+ }
93
+ }
94
+ else {
95
+ sequence = 0;
96
+ }
97
+ lastMs = now;
98
+ const bytes = new Uint8Array(16);
99
+ globalThis.crypto.getRandomValues(bytes);
100
+ let timestamp = now;
101
+ for (let index = 5; index >= 0; index -= 1) {
102
+ bytes[index] = timestamp & 0xff;
103
+ timestamp = Math.floor(timestamp / 256);
104
+ }
105
+ bytes[6] = 0x70 | ((sequence >> 8) & 0x0f);
106
+ bytes[7] = sequence & 0xff;
107
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
108
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
109
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
110
+ };
111
+ }
112
+ async function defaultRetryDelay(attempt) {
113
+ const ceilingMs = Math.min(2_000, 50 * 2 ** Math.max(0, attempt - 1));
114
+ const delayMs = Math.floor(Math.random() * (ceilingMs + 1));
115
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
116
+ }
117
+ function isObject(value) {
118
+ return value !== null && typeof value === "object" && !Array.isArray(value);
119
+ }
120
+ /**
121
+ * One MSP connection over newline-delimited JSON.
122
+ *
123
+ * The connection sends your requests and commands, correlates their
124
+ * responses, enforces the frame-size limit, and hands inbound notifications
125
+ * and server requests to the handlers you register. It is transport-agnostic:
126
+ * pair it with any `DuplexTransport`. Most applications never build one
127
+ * directly — `MuseClient.spawn` or `spawnMspConnection` does it for you;
128
+ * reach for a bare `Connection` when you need the raw notification feed or
129
+ * your own transport.
130
+ */
131
+ export class Connection {
132
+ #transport;
133
+ #frameLimitBytes;
134
+ #mintCommandId;
135
+ #mintRequestId;
136
+ #pending = new Map();
137
+ #commands = new Map();
138
+ #nextRequestId = 1;
139
+ #serverRequestHandler;
140
+ #notificationHandler;
141
+ #protocolErrorHandler;
142
+ #writeTail = Promise.resolve();
143
+ // Settles when every accepted frame has been HANDED to the transport, as
144
+ // opposed to #writeTail, which settles when the peer has taken it.
145
+ #submitTail = Promise.resolve();
146
+ #writeFailure;
147
+ #buffer = "";
148
+ #bufferBytes = 0; // FR-012: incremental accounting — never a full-buffer rescan per chunk
149
+ // FR-012: the last UTF-16 unit of #buffer (-1 when empty), maintained from each
150
+ // fresh chunk so the surrogate-pair reconciliation below never READS #buffer on
151
+ // the hot no-newline path — reading it (charCodeAt/indexOf/regex) flattens the
152
+ // V8 rope and copies the whole buffer per chunk, the O(bytes^2) this FR bans.
153
+ #bufferTailCode = -1;
154
+ #droppingOversized = false;
155
+ #finished = false;
156
+ #closedPromise;
157
+ #resolveClosed;
158
+ constructor(transport, options) {
159
+ this.#transport = transport;
160
+ this.#frameLimitBytes = options?.frameLimitBytes ?? DEFAULT_FRAME_LIMIT_BYTES;
161
+ this.#mintCommandId = options?.mintCommandId ?? createUuidV7Mint();
162
+ this.#mintRequestId = options?.mintRequestId ?? (() => {
163
+ const id = this.#nextRequestId;
164
+ this.#nextRequestId += 1;
165
+ return id;
166
+ });
167
+ this.#closedPromise = new Promise((resolve) => {
168
+ this.#resolveClosed = resolve;
169
+ });
170
+ void this.#readLoop();
171
+ }
172
+ get closed() {
173
+ return this.#closedPromise;
174
+ }
175
+ /** See {@link submissionTail}. */
176
+ [submissionTail]() {
177
+ return this.#submitTail;
178
+ }
179
+ request(method, params) {
180
+ if (this.#finished)
181
+ return Promise.reject(new ProtocolError("connection is closed"));
182
+ const id = this.#mintRequestId();
183
+ if (typeof id !== "string" && (typeof id !== "number" || !Number.isInteger(id))) {
184
+ return Promise.reject(new ProtocolError("request id must be a string or integer"));
185
+ }
186
+ if (this.#pending.has(requestKey(id))) {
187
+ return Promise.reject(new ProtocolError(`request id ${String(id)} is already in flight`));
188
+ }
189
+ const request = {
190
+ jsonrpc: "2.0",
191
+ id,
192
+ method,
193
+ ...(params === undefined ? {} : { params }),
194
+ };
195
+ return new Promise((resolve, reject) => {
196
+ this.#pending.set(requestKey(id), { resolve, reject });
197
+ void this.#write(request).catch((error) => {
198
+ this.#pending.delete(requestKey(id));
199
+ reject(error);
200
+ });
201
+ });
202
+ }
203
+ /**
204
+ * Take one id from THIS connection's single `commandId` minter (INV-013).
205
+ *
206
+ * Exposed for the callers that need the id BEFORE the ack: `sendUserTurn`
207
+ * records its optimistic SS4.13 entry under it, and an entry created only on
208
+ * the ack is invisible for exactly the window it exists to cover. The
209
+ * alternative was a facade-side mint, which is the second minter INV-013
210
+ * forbids — delegating here keeps the single-minter property intact and
211
+ * preserves the injected `mintCommandId` seam for deterministic transcripts.
212
+ *
213
+ * Pair it with `command(..., { commandId })`, which reuses the id instead of
214
+ * minting a second one.
215
+ */
216
+ mintCommandId() {
217
+ return this.#mintCommandId();
218
+ }
219
+ notify(method, params) {
220
+ const notification = {
221
+ jsonrpc: "2.0",
222
+ method,
223
+ ...(params === undefined ? {} : { params }),
224
+ };
225
+ void this.#write(notification).catch((error) => this.#finish(error));
226
+ }
227
+ onServerRequest(handler) {
228
+ this.#serverRequestHandler = handler;
229
+ }
230
+ onNotification(handler) {
231
+ this.#notificationHandler = handler;
232
+ }
233
+ onProtocolError(handler) {
234
+ this.#protocolErrorHandler = handler;
235
+ }
236
+ async flush() {
237
+ await this.#writeTail;
238
+ if (this.#writeFailure !== undefined)
239
+ throw this.#writeFailure;
240
+ }
241
+ async command(method, params, options) {
242
+ const commandId = options?.commandId ?? this.#mintCommandId();
243
+ const commandParams = { ...params, commandId };
244
+ const signature = canonical({ method, params: commandParams });
245
+ const memory = this.#commands.get(commandId);
246
+ if (memory !== undefined && memory.signature !== signature) {
247
+ throw new ProtocolError(`commandId ${commandId} was reused with a different payload`);
248
+ }
249
+ const remembered = memory ?? { signature };
250
+ this.#commands.set(commandId, remembered);
251
+ const maxAttempts = Math.max(1, options?.maxAttempts ?? 3);
252
+ const retryDelay = options?.retryDelay ?? defaultRetryDelay;
253
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
254
+ try {
255
+ const ack = await this.request(method, commandParams);
256
+ // session/start's and session/resume's result schemas omit the
257
+ // redundant commandId echo (the two omitting families recorded in
258
+ // specs/14990-muse-sdk/contracts/sdk-surface.md; approval/decide
259
+ // DOES echo it). When a result carries it, preserve the strict echo
260
+ // check (TEST-018).
261
+ if (ack["commandId"] !== undefined && ack["commandId"] !== commandId) {
262
+ throw new ProtocolError(`${method} ack commandId ${String(ack["commandId"])} did not echo ${commandId}`);
263
+ }
264
+ if (remembered.ack !== undefined && canonical(remembered.ack) !== canonical(ack)) {
265
+ throw new ProtocolError(`${method} replay for commandId ${commandId} did not return a value-identical ack`);
266
+ }
267
+ remembered.ack = { ...ack };
268
+ return ack;
269
+ }
270
+ catch (error) {
271
+ const retryableNothingAdmitted = error instanceof MspError &&
272
+ ((error.code === -32001 && error.kind === "overloaded") ||
273
+ (error.code === -32031 && error.kind === "backpressured"));
274
+ if (!retryableNothingAdmitted || attempt === maxAttempts)
275
+ throw error;
276
+ await retryDelay(attempt, error);
277
+ }
278
+ }
279
+ throw new ProtocolError("unreachable command retry state");
280
+ }
281
+ async close() {
282
+ // COMPLETION must not gate teardown — that is the #15943 hang, since a
283
+ // peer that stopped reading never completes a write. SUBMISSION must,
284
+ // though: `#write` hands the frame to the transport on a later
285
+ // microtask, so ending the peer's input synchronously here dropped a
286
+ // just-accepted `notify()` and rejected close() with a raw
287
+ // ERR_STREAM_WRITE_AFTER_END on a HEALTHY peer (PR #22819 round 3).
288
+ // The submission promise goes TO the transport, which waits for it
289
+ // inside its own shutdown budget, so this class still knows nothing
290
+ // about processes, signals, or timeouts.
291
+ //
292
+ // The guarantee is SCOPED to transports that implement close() (PR
293
+ // #22819 round 4). A close-less transport has no budget to bound the
294
+ // wait with, and submission of frame N+1 only happens once frame N
295
+ // COMPLETES — exactly what a wedged peer withholds — so awaiting it here
296
+ // would hang teardown outright, where previously `#finish` at least
297
+ // rejected in-flight requests and settled `closed`. Finishing
298
+ // immediately is the honest behaviour for a transport that never told us
299
+ // how long it may take.
300
+ const tail = this.#writeTail;
301
+ if (this.#transport.close !== undefined) {
302
+ await this.#transport.close(this.#submitTail);
303
+ // Bounded by the transport's own shutdown: the peer is gone by now, so
304
+ // a pending write has errored and the tail records `#writeFailure`.
305
+ await tail;
306
+ }
307
+ else {
308
+ // Nothing here may wait on the peer: a stuck write's tail would never
309
+ // settle either. `#finish` has already rejected every in-flight
310
+ // request and settled `closed`; `flush()` still surfaces a later
311
+ // write failure.
312
+ this.#finish(new ProtocolError("connection closed"));
313
+ }
314
+ await this.#closedPromise;
315
+ }
316
+ async #write(frame) {
317
+ if (this.#finished)
318
+ throw new ProtocolError("connection is closed");
319
+ const line = `${JSON.stringify(frame)}\n`;
320
+ let markSubmitted;
321
+ const submitted = new Promise((resolve) => {
322
+ markSubmitted = resolve;
323
+ });
324
+ this.#submitTail = this.#submitTail.then(() => submitted);
325
+ const write = this.#writeTail.then(async () => {
326
+ try {
327
+ if (this.#finished)
328
+ throw new ProtocolError("connection is closed");
329
+ // Invoking write() IS submission: the transport's synchronous prefix
330
+ // has reached the underlying stream by the time the call returns.
331
+ const inFlight = this.#transport.write(line);
332
+ markSubmitted();
333
+ await inFlight;
334
+ }
335
+ catch (error) {
336
+ // A frame that can never be submitted must not wedge close() either.
337
+ markSubmitted();
338
+ throw error;
339
+ }
340
+ });
341
+ this.#writeTail = write.catch((error) => {
342
+ this.#writeFailure = error;
343
+ this.#finish(error);
344
+ });
345
+ await write;
346
+ }
347
+ async #readLoop() {
348
+ try {
349
+ for await (const chunk of this.#transport.incoming)
350
+ this.#ingest(chunk);
351
+ if (!this.#droppingOversized && this.#buffer.length > 0) {
352
+ this.#protocolError(new ProtocolError("inbound frame ended without a newline", this.#buffer));
353
+ }
354
+ this.#finish(new ProtocolError("connection reached EOF"));
355
+ }
356
+ catch (error) {
357
+ this.#finish(error);
358
+ }
359
+ }
360
+ #ingest(chunk) {
361
+ let remaining = chunk;
362
+ if (this.#droppingOversized) {
363
+ const newline = remaining.indexOf("\n");
364
+ if (newline < 0)
365
+ return;
366
+ this.#droppingOversized = false;
367
+ remaining = remaining.slice(newline + 1);
368
+ }
369
+ // FR-012: a chunk boundary can split a surrogate pair; the lone halves
370
+ // counted 3+3 UTF-8 bytes as they arrived, but the joined pair counts 4 at
371
+ // line-extract. Reconcile the +2 residue now, or legal frames accumulate
372
+ // drift until one false-trips the frame limit.
373
+ if (remaining.length === 0)
374
+ return;
375
+ const chunkHead = remaining.charCodeAt(0);
376
+ if (this.#bufferTailCode >= 0xd800 &&
377
+ this.#bufferTailCode <= 0xdbff &&
378
+ chunkHead >= 0xdc00 &&
379
+ chunkHead <= 0xdfff) {
380
+ this.#bufferBytes -= 2;
381
+ }
382
+ this.#buffer += remaining;
383
+ this.#bufferBytes += utf8ByteLength(remaining);
384
+ this.#bufferTailCode = remaining.charCodeAt(remaining.length - 1);
385
+ // FR-012: the retained buffer is newline-free on entry (the drain below runs
386
+ // to exhaustion), so only the fresh chunk can carry a newline. Gating the
387
+ // drain here keeps ingest O(bytes) instead of rescanning the whole buffer
388
+ // from offset 0 on every newline-less chunk (O(bytes^2)).
389
+ if (remaining.includes("\n")) {
390
+ while (true) {
391
+ const newline = this.#buffer.indexOf("\n");
392
+ if (newline < 0)
393
+ break;
394
+ const line = this.#buffer.slice(0, newline);
395
+ this.#buffer = this.#buffer.slice(newline + 1);
396
+ this.#bufferBytes -= utf8ByteLength(line) + 1;
397
+ this.#line(line);
398
+ }
399
+ // No post-drain tail refresh needed: the retained buffer's last unit IS
400
+ // the chunk's last unit (already recorded above) — or the chunk ended in
401
+ // "\n", which can never pass the high-surrogate check that is this
402
+ // field's only reader. Pinned by TEST-017's interleaved-chunk arm.
403
+ }
404
+ if (this.#bufferBytes > this.#frameLimitBytes) {
405
+ this.#protocolError(new ProtocolError(`inbound frame exceeds ${this.#frameLimitBytes} bytes`, truncateToUtf8Bytes(this.#buffer, this.#frameLimitBytes)));
406
+ this.#buffer = "";
407
+ this.#bufferBytes = 0;
408
+ this.#bufferTailCode = -1;
409
+ this.#droppingOversized = true;
410
+ }
411
+ }
412
+ #line(raw) {
413
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
414
+ if (line.trim().length === 0)
415
+ return;
416
+ if (utf8ByteLength(line) > this.#frameLimitBytes) {
417
+ this.#protocolError(new ProtocolError(`inbound frame exceeds ${this.#frameLimitBytes} bytes`, truncateToUtf8Bytes(line, this.#frameLimitBytes)));
418
+ return;
419
+ }
420
+ let parsed;
421
+ try {
422
+ parsed = JSON.parse(line);
423
+ }
424
+ catch {
425
+ this.#protocolError(new ProtocolError("inbound frame is not valid JSON", line));
426
+ return;
427
+ }
428
+ if (!isObject(parsed) || parsed["jsonrpc"] !== "2.0") {
429
+ this.#protocolError(new ProtocolError("inbound frame is not a JSON-RPC 2.0 object", line));
430
+ return;
431
+ }
432
+ const method = parsed["method"];
433
+ const id = parsed["id"];
434
+ if (typeof method === "string") {
435
+ if (typeof id === "string" || typeof id === "number") {
436
+ if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) {
437
+ this.#protocolError(new ProtocolError("server request id must be a positive integer", line));
438
+ return;
439
+ }
440
+ void this.#serverRequest(parsed).catch((error) => {
441
+ this.#finish(error);
442
+ });
443
+ return;
444
+ }
445
+ this.#notificationHandler?.(parsed);
446
+ return;
447
+ }
448
+ if (typeof id !== "string" && typeof id !== "number") {
449
+ this.#protocolError(new ProtocolError("response has no usable id", line));
450
+ return;
451
+ }
452
+ this.#response(parsed, id, line);
453
+ }
454
+ #response(frame, id, line) {
455
+ const pending = this.#pending.get(requestKey(id));
456
+ if (pending === undefined) {
457
+ this.#protocolError(new ProtocolError(`response for unknown request id ${String(id)}`, line));
458
+ return;
459
+ }
460
+ const hasResult = Object.hasOwn(frame, "result");
461
+ const hasError = Object.hasOwn(frame, "error");
462
+ if (hasResult === hasError) {
463
+ // FR-014: the MATCHED caller must settle — with no local timeout
464
+ // (INV-006) an unrejected caller would hang until EOF.
465
+ const violation = new ProtocolError("response must carry exactly one of result or error", line);
466
+ this.#pending.delete(requestKey(id));
467
+ pending.reject(violation);
468
+ this.#protocolError(violation);
469
+ return;
470
+ }
471
+ this.#pending.delete(requestKey(id));
472
+ if (hasResult) {
473
+ const result = frame["result"];
474
+ if (!isObject(result)) {
475
+ pending.reject(new ProtocolError("response result must be an object", line));
476
+ return;
477
+ }
478
+ pending.resolve(result);
479
+ return;
480
+ }
481
+ const error = frame["error"];
482
+ if (!isObject(error) ||
483
+ typeof error["code"] !== "number" ||
484
+ !Number.isInteger(error["code"]) ||
485
+ typeof error["message"] !== "string") {
486
+ pending.reject(new ProtocolError("error response has an invalid error object", line));
487
+ return;
488
+ }
489
+ const data = error["data"];
490
+ if (!isObject(data) || typeof data["kind"] !== "string") {
491
+ pending.reject(new ProtocolError("MSP error response has no data.kind", line));
492
+ return;
493
+ }
494
+ pending.reject(new MspError({
495
+ code: error["code"],
496
+ message: error["message"],
497
+ data: data,
498
+ }));
499
+ }
500
+ async #serverRequest(request) {
501
+ const id = request.id;
502
+ try {
503
+ if (this.#serverRequestHandler === undefined) {
504
+ throw new MspError({
505
+ code: -32601,
506
+ message: `method not found: ${request.method}`,
507
+ data: { kind: "methodNotFound", retryable: false },
508
+ });
509
+ }
510
+ const result = await this.#serverRequestHandler(request);
511
+ // FM-009: a failed reply write finishes the connection; it must not
512
+ // escape this fire-and-forget task as an unhandled rejection.
513
+ await this.#write({ jsonrpc: "2.0", id, result }).catch((writeError) => this.#finish(writeError));
514
+ }
515
+ catch (error) {
516
+ const typed = error instanceof MspError
517
+ ? error
518
+ : new MspError({
519
+ code: -32603,
520
+ message: error instanceof Error ? error.message : "server request handler failed",
521
+ data: { kind: "internal" },
522
+ });
523
+ await this.#write({
524
+ jsonrpc: "2.0",
525
+ id,
526
+ error: {
527
+ code: typed.code,
528
+ message: typed.message,
529
+ data: typed.data,
530
+ },
531
+ }).catch((writeError) => this.#finish(writeError)); // FM-009
532
+ }
533
+ }
534
+ #protocolError(error) {
535
+ this.#protocolErrorHandler?.(error);
536
+ }
537
+ #finish(reason) {
538
+ if (this.#finished)
539
+ return;
540
+ this.#finished = true;
541
+ const error = reason instanceof Error ? reason : new ProtocolError(String(reason));
542
+ for (const pending of this.#pending.values())
543
+ pending.reject(error);
544
+ this.#pending.clear();
545
+ this.#resolveClosed?.();
546
+ this.#resolveClosed = undefined;
547
+ }
548
+ }