@muse-code/sdk 1.4.15 → 1.4.23

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.
@@ -1,7 +1,7 @@
1
1
  /** Node stdio binding and type-state handshake for the MSP connection. */
2
2
  import { spawn } from "node:child_process";
3
3
  import { Connection, ProtocolError, requestWithFrame, submissionTail, } from "./connection.js";
4
- import { checkServedFingerprint } from "../fingerprint.js";
4
+ import { SchemaCompatibilityError, classifyServedSchema, isWellFormedEpoch } from "../fingerprint.js";
5
5
  const DEFAULT_STDERR_MAX_BYTES = 8 * 1024;
6
6
  const DEFAULT_STDERR_MAX_LINES = 100;
7
7
  /** SS2.1.2's default host drain timeout: the whole EOF sequence's budget. */
@@ -9,9 +9,17 @@ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;
9
9
  /**
10
10
  * SIGTERM → SIGKILL grace. Not a knob: by the time it runs the host has
11
11
  * already had its whole drain window, so this covers only a signal handler's
12
- * final flush. Codex's stdio launcher uses the same two seconds.
12
+ * final flush. Codex's stdio launcher uses the same two seconds. Also bounds
13
+ * how long a call failed by a host death waits for the exit (FR-97948-1).
14
+ * Exported from this module only, never the package barrel.
13
15
  */
14
- const SIGTERM_GRACE_MS = 2_000;
16
+ export const SIGTERM_GRACE_MS = 2_000;
17
+ /**
18
+ * How long the pipes may keep draining after the child's `exit` before the
19
+ * transport drops its own ends. A process the host started can hold the other
20
+ * ends for good, and Node fires `close` only once every holder lets go.
21
+ */
22
+ const POST_EXIT_DRAIN_MS = 1_000;
15
23
  /** Node's own `setTimeout` ceiling; past it a delay silently clamps to 1 ms. */
16
24
  const MAX_SHUTDOWN_TIMEOUT_MS = 2_147_483_647;
17
25
  const ownedTransport = Symbol("MuseServeChild.transport");
@@ -23,6 +31,16 @@ const adoptFlushSource = Symbol("ChildStdioTransport.adoptFlushSource");
23
31
  * (#49912) without a new public member on `MspHandshake`.
24
32
  */
25
33
  export const initializeAnswered = Symbol("MspHandshake.initializeAnswered");
34
+ /**
35
+ * Node's abort shape (`child_process.spawn({ signal })`): callers branch on
36
+ * `name`. Exported from this MODULE only (never the package barrel) so the
37
+ * facade raises the same error before host discovery.
38
+ */
39
+ export function abortError(reason) {
40
+ const error = new Error("The operation was aborted", { cause: reason });
41
+ error.name = "AbortError";
42
+ return error;
43
+ }
26
44
  function makeShutdownDeadline(budgetMs) {
27
45
  let timer;
28
46
  const expired = new Promise((resolve) => {
@@ -164,6 +182,13 @@ export class ChildStdioTransport {
164
182
  // behaved identically, and `#closing ??=` let whichever call won the race
165
183
  // discard the other's submission promise (PR #22819 round 4).
166
184
  #defaultFlushed;
185
+ // Set when the transport dropped its pipe ends after the post-exit drain,
186
+ // so the stdout iterator reads the resulting premature close as EOF.
187
+ #droppedPipes = false;
188
+ // Whether the owned group still had members when the pipes were dropped;
189
+ // only then may close() signal it, so a group already empty at the drop is
190
+ // never signalled (one that empties later and is reused is not covered).
191
+ #leftoverGroup = false;
167
192
  constructor(child, onStderr, shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS, ownsProcessGroup = false,
168
193
  /** Deterministic-test seam; production always uses `makeShutdownDeadline`. */
169
194
  deadlineFactory = makeShutdownDeadline) {
@@ -185,6 +210,14 @@ export class ChildStdioTransport {
185
210
  this.child.once("error", reject);
186
211
  this.child.once("close", (code, signal) => resolve({ code, signal }));
187
212
  });
213
+ this.child.once("exit", () => {
214
+ const drain = setTimeout(() => this.#dropPipes(), POST_EXIT_DRAIN_MS);
215
+ // Unref'd: a held pipe keeps the loop alive until the drain fires, and
216
+ // with nothing else waiting the embedder may exit without it.
217
+ drain.unref();
218
+ const clear = () => clearTimeout(drain);
219
+ void this.exited.then(clear, clear);
220
+ });
188
221
  // Mark handled at birth: a spawn failure (e.g. ENOENT) rejects `exited`
189
222
  // before anyone can await it, and the default unhandled-rejection policy
190
223
  // would kill the consumer. Later awaiters still receive the rejection.
@@ -264,11 +297,28 @@ export class ChildStdioTransport {
264
297
  * way to reach an exit, never a substitute for observing one.
265
298
  */
266
299
  async #awaitExitOrTerminate(deadline) {
267
- if (await this.#beforeDeadline(this.#settled(), deadline))
300
+ if (await this.#beforeDeadline(this.#settled(), deadline)) {
301
+ await this.#endLeftoverGroup();
268
302
  return;
303
+ }
269
304
  this.#signal("SIGTERM");
270
- if (await this.#settledWithin(SIGTERM_GRACE_MS))
271
- return;
305
+ // Deliberately ambient (NOT this.#makeShutdownDeadline): the SIGTERM grace
306
+ // window is outside the one shared shutdown budget the injected seam models.
307
+ const grace = makeShutdownDeadline(SIGTERM_GRACE_MS);
308
+ try {
309
+ if (await this.#beforeDeadline(this.#settled(), grace.expired)) {
310
+ // The drain can settle `exited` inside the grace while a group member
311
+ // that traps SIGTERM still runs: SIGKILL it when this same grace ends.
312
+ if (this.#leftoverGroup && this.#signalGroup(0)) {
313
+ await grace.expired;
314
+ this.#signalGroup("SIGKILL");
315
+ }
316
+ return;
317
+ }
318
+ }
319
+ finally {
320
+ grace.clear();
321
+ }
272
322
  // Past SIGTERM, drop our end of the pipe ourselves (PR #22819 round 3).
273
323
  // Nothing else does, so a write the host never drained keeps `stdin`
274
324
  // open — and the child's `close` event, which `exited` and the trailing
@@ -290,21 +340,36 @@ export class ChildStdioTransport {
290
340
  * an exited child — the ladder must never rethrow out of a stage.
291
341
  */
292
342
  #signal(signal) {
343
+ // A failed group signal falls through to the direct-child path, safe on
344
+ // every failure here.
345
+ if (this.#signalGroup(signal))
346
+ return;
347
+ this.child.kill(signal);
348
+ }
349
+ /** True only when the owned group existed and took the signal (`0` probes). */
350
+ #signalGroup(signal) {
293
351
  const pid = this.child.pid;
294
- if (this.#ownsProcessGroup && pid !== undefined) {
295
- try {
296
- process.kill(-pid, signal);
297
- return;
298
- }
299
- catch {
300
- // Fall through to the direct-child path, safe on every failure here.
301
- }
352
+ if (!this.#ownsProcessGroup || pid === undefined)
353
+ return false;
354
+ try {
355
+ process.kill(-pid, signal);
356
+ return true;
357
+ }
358
+ catch {
359
+ return false;
302
360
  }
303
- this.child.kill(signal);
304
361
  }
305
- /** True once `exited` settles either way — a rejection means no live child. */
306
- async #settledWithin(budgetMs) {
307
- return await this.#within(this.#settled(), budgetMs);
362
+ /**
363
+ * When the post-exit drain settled `exited` before the deadline, the ladder
364
+ * never ran, but what the host left in its own group must still end with it
365
+ * (FR-017b). A holder outside the group is left alone, and a group empty at
366
+ * the drop, or now (`ESRCH`), ends the stage at once.
367
+ */
368
+ async #endLeftoverGroup() {
369
+ if (!this.#leftoverGroup || !this.#signalGroup("SIGTERM"))
370
+ return;
371
+ await makeShutdownDeadline(SIGTERM_GRACE_MS).expired;
372
+ this.#signalGroup("SIGKILL");
308
373
  }
309
374
  /** True if `work` settles before the one shared shutdown deadline fires. */
310
375
  async #beforeDeadline(work, deadline) {
@@ -313,18 +378,6 @@ export class ChildStdioTransport {
313
378
  deadline.then(() => false),
314
379
  ]);
315
380
  }
316
- /** True if `work` settles inside `budgetMs`; false when the budget expires. */
317
- async #within(work, budgetMs) {
318
- // Deliberately ambient (NOT this.#makeShutdownDeadline): the SIGTERM grace
319
- // window is outside the one shared shutdown budget the injected seam models.
320
- const deadline = makeShutdownDeadline(budgetMs);
321
- try {
322
- return await this.#beforeDeadline(work, deadline.expired);
323
- }
324
- finally {
325
- deadline.clear();
326
- }
327
- }
328
381
  /**
329
382
  * `exited` REJECTS when the spawn itself failed (ENOENT). There is no
330
383
  * process to end and no exit to observe, so shutdown is complete; the
@@ -334,9 +387,27 @@ export class ChildStdioTransport {
334
387
  async #settled() {
335
388
  await this.exited.catch(() => { });
336
389
  }
390
+ /**
391
+ * Let go of our ends only: this sends no signal, but a holder's later writes
392
+ * fail (SIGPIPE/EPIPE) and its stdin reads EOF. `close` then fires, so
393
+ * `exited` reports the exit `exit` already saw.
394
+ */
395
+ #dropPipes() {
396
+ this.#droppedPipes = true;
397
+ this.#leftoverGroup = this.#signalGroup(0);
398
+ this.child.stdin.destroy();
399
+ this.child.stdout.destroy();
400
+ this.child.stderr.destroy();
401
+ }
337
402
  async *#stdoutChunks() {
338
- for await (const chunk of this.child.stdout)
339
- yield String(chunk);
403
+ try {
404
+ for await (const chunk of this.child.stdout)
405
+ yield String(chunk);
406
+ }
407
+ catch (error) {
408
+ if (!this.#droppedPipes)
409
+ throw error;
410
+ }
340
411
  }
341
412
  }
342
413
  /**
@@ -411,7 +482,13 @@ export class MspHandshake {
411
482
  #transport;
412
483
  #started = false;
413
484
  #answered = false;
485
+ #refuseDeclaredBreaking;
486
+ #signal;
487
+ #onAbort = () => void this.close().catch(() => undefined);
414
488
  constructor(options) {
489
+ // A handshake cancelled before it starts never starts a host to kill.
490
+ if (options.signal?.aborted)
491
+ throw abortError(options.signal.reason);
415
492
  this.child = MuseServeChild.spawn({
416
493
  museBin: options.command,
417
494
  ...(options.args === undefined ? {} : { args: options.args }),
@@ -421,6 +498,7 @@ export class MspHandshake {
421
498
  ...(options.shutdownTimeoutMs === undefined
422
499
  ? {}
423
500
  : { shutdownTimeoutMs: options.shutdownTimeoutMs }),
501
+ ...(options.spawnFn === undefined ? {} : { spawnFn: options.spawnFn }),
424
502
  });
425
503
  this.#transport = this.child[ownedTransport]();
426
504
  this.#connection = new Connection(this.#transport, options.connection);
@@ -429,6 +507,9 @@ export class MspHandshake {
429
507
  // this they ended the host's input while a just-accepted frame was still
430
508
  // queued on a microtask (PR #22819 round 4).
431
509
  this.#transport[adoptFlushSource](() => this.#connection[submissionTail]());
510
+ this.#refuseDeclaredBreaking = options.refuseDeclaredBreakingSchema === true;
511
+ this.#signal = options.signal;
512
+ this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
432
513
  }
433
514
  get exited() {
434
515
  return this.#transport.exited;
@@ -443,6 +524,7 @@ export class MspHandshake {
443
524
  this.#connection.onProtocolError(handler);
444
525
  }
445
526
  async close() {
527
+ this.#signal?.removeEventListener("abort", this.#onAbort);
446
528
  await this.#connection.close();
447
529
  return await this.#transport.exited;
448
530
  }
@@ -451,9 +533,31 @@ export class MspHandshake {
451
533
  return this.#answered;
452
534
  }
453
535
  async initialize(params) {
536
+ // Checked here, not in the try: a refused second call must leave the
537
+ // first call's abort listener in place.
454
538
  if (this.#started)
455
539
  throw new ProtocolError("initialize may be sent only once per connection");
456
540
  this.#started = true;
541
+ const signal = this.#signal;
542
+ try {
543
+ const spawned = await this.#initialize(params);
544
+ if (!signal?.aborted)
545
+ return spawned;
546
+ }
547
+ catch (error) {
548
+ if (!signal?.aborted)
549
+ throw error;
550
+ }
551
+ finally {
552
+ // Settled either way: a later abort must not close anything.
553
+ signal?.removeEventListener("abort", this.#onAbort);
554
+ }
555
+ // Aborted before the handshake completed: the abort listener already
556
+ // started the shutdown ladder; reject only once the host is gone.
557
+ await this.close().catch(() => undefined);
558
+ throw abortError(signal?.reason);
559
+ }
560
+ async #initialize(params) {
457
561
  const { result: raw, line } = await this.#connection[requestWithFrame]("initialize", params);
458
562
  this.#answered = true;
459
563
  const result = raw;
@@ -463,7 +567,31 @@ export class MspHandshake {
463
567
  // and the facade tells the two apart by it (#49912, #50588 review).
464
568
  throw new ProtocolError("initialize result has no schema fingerprint", line);
465
569
  }
466
- const fingerprintWarning = checkServedFingerprint(result.schema.fingerprint);
570
+ const rawEpoch = result.schema.compatibilityEpoch;
571
+ const wellFormed = isWellFormedEpoch(rawEpoch);
572
+ if (!wellFormed && this.#refuseDeclaredBreaking) {
573
+ // The member is an optional unsigned integer (FR-22936-2). With the
574
+ // refusal on, the tier it asks for cannot be read from this answer, so
575
+ // the arm fails closed like a result with no fingerprint (FR-22936-8).
576
+ throw new ProtocolError("initialize result has a schema compatibilityEpoch that is not a non-negative integer " +
577
+ "(FR-22936-8); the host is not a conforming MSP server: point `museBin` at a current " +
578
+ "`muse` build or reinstall it", line);
579
+ }
580
+ // With the refusal off a malformed member is read as absent (FR-22936-8):
581
+ // the published behaviour does not change until the owner enables the
582
+ // setting (ADR 22936 D3). The classifier applies that reading itself, so
583
+ // `classifyServedSchema(initializeResult.schema)` reports this same tier.
584
+ const fingerprintWarning = classifyServedSchema({
585
+ fingerprint: result.schema.fingerprint,
586
+ compatibilityEpoch: rawEpoch,
587
+ });
588
+ if (this.#refuseDeclaredBreaking && fingerprintWarning?.tier === "declaredBreaking") {
589
+ // ADR 22936 D3: refuse at connect. The host is closed first (stdin EOF,
590
+ // then the usual shutdown ladder) so a refusal orphans nothing, and
591
+ // `initialized` is never sent: the host saw a handshake that ended.
592
+ await this.close().catch(() => undefined);
593
+ throw new SchemaCompatibilityError(fingerprintWarning);
594
+ }
467
595
  this.#connection.notify("initialized");
468
596
  await this.#connection.flush();
469
597
  return new SpawnedMspConnection(this.#connection, this.#transport, this.child, result, fingerprintWarning);
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The types a typed `Connection` checks calls against (FR-100032-3).
3
+ *
4
+ * Every type here is computed from the generated stable method → type maps,
5
+ * so no params or result shape is restated by hand and none can drift from
6
+ * the schema. Internal: the package does not export these helpers.
7
+ */
8
+ import type { MspMethodMap, MspNotificationMap } from "../msp.js";
9
+ /** Every client-to-server method the stable map names. */
10
+ export type MethodName = keyof MspMethodMap & string;
11
+ /** A method's `params` type; `undefined` for a method that takes none. */
12
+ export type MethodParams<M extends MethodName> = MspMethodMap[M] extends {
13
+ params: infer P;
14
+ } ? P : never;
15
+ /** A method's `result` type. */
16
+ export type MethodResult<M extends MethodName> = MspMethodMap[M] extends {
17
+ result: infer R;
18
+ } ? R : never;
19
+ /**
20
+ * What a typed `request()`/`command()` resolves with: the method's result
21
+ * type, still open to members a newer host adds (the wire evolves
22
+ * additively), so it also stays assignable where `Record<string, unknown>`
23
+ * was expected before these types existed.
24
+ */
25
+ export type WireResult<M extends MethodName> = MethodResult<M> & Record<string, unknown>;
26
+ /**
27
+ * The params a caller passes to `command()`: the method's params without
28
+ * `commandId`, which the connection mints (INV-013).
29
+ */
30
+ export type CommandParams<M extends MethodName> = MethodParams<M> extends infer P ? (P extends object ? Omit<P, "commandId"> : Record<string, never>) : never;
31
+ /**
32
+ * The trailing `params` argument of a typed call: absent for a method that
33
+ * takes none, optional when every member is optional, required otherwise.
34
+ */
35
+ export type ParamsArgument<P> = [P] extends [undefined] ? [] : Record<string, never> extends P ? [params?: P] : [params: P];
36
+ /**
37
+ * Every notification the stable map names. The map also lists the two
38
+ * client-sent ones (`initialized`, `userInput/engaged`); a listener on either
39
+ * compiles but never runs, since the host does not send them.
40
+ */
41
+ export type NotificationName = keyof MspNotificationMap & string;
42
+ /** A notification's `params` type; `undefined` for one that carries none. */
43
+ export type NotificationParams<M extends NotificationName> = MspNotificationMap[M];
44
+ /**
45
+ * A method name the given names do NOT include. A listed method never
46
+ * matches, so the untyped fallback cannot accept a mistyped call to a typed
47
+ * method.
48
+ */
49
+ export type UnlistedMethod<Names extends string, M extends string> = M extends Names ? never : M;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The types a typed `Connection` checks calls against (FR-100032-3).
3
+ *
4
+ * Every type here is computed from the generated stable method → type maps,
5
+ * so no params or result shape is restated by hand and none can drift from
6
+ * the schema. Internal: the package does not export these helpers.
7
+ */
8
+ export {};
@@ -70,7 +70,7 @@ export declare class PermissionProfileNotApplied extends Error {
70
70
  constructor(requested: string, served: string | null, sessionId: string);
71
71
  }
72
72
  /** The developer-docs compatibility page the host-discovery error cites. */
73
- export declare const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/compatibility/";
73
+ export declare const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/latest/compatibility/";
74
74
  /**
75
75
  * No host binary was given and no executable `muse` is on `PATH` (FR-79107-1).
76
76
  * Raised by `MuseClient.spawn` before any process is started. The package does
@@ -80,13 +80,14 @@ export declare class MuseHostDiscoveryError extends Error {
80
80
  /** The spawn option that names an explicit host path. */
81
81
  readonly parameter = "museBin";
82
82
  /** The page listing the host versions this SDK supports. */
83
- readonly compatibilityUrl = "https://meta-models.github.io/muse-code-sdk/compatibility/";
83
+ readonly compatibilityUrl = "https://meta-models.github.io/muse-code-sdk/latest/compatibility/";
84
84
  constructor();
85
85
  }
86
86
  /**
87
- * `MuseClient.command` was asked to send a method whose state the facade owns
88
- * (FR-79107-2). Sending it raw would bypass that state, so it is refused
89
- * before anything is written; use the facade verb instead.
87
+ * `MuseClient.command` or `MuseClient.request` was asked to send a method
88
+ * whose state the facade owns (FR-79107-2). Sending it raw would bypass that
89
+ * state, so it is refused before anything is written; use the facade verb
90
+ * instead.
90
91
  */
91
92
  export declare class MuseFacadeOwnedMethodError extends Error {
92
93
  /** The refused wire method. */
@@ -75,7 +75,7 @@ export class PermissionProfileNotApplied extends Error {
75
75
  }
76
76
  }
77
77
  /** The developer-docs compatibility page the host-discovery error cites. */
78
- export const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/compatibility/";
78
+ export const COMPATIBILITY_PAGE_URL = "https://meta-models.github.io/muse-code-sdk/latest/compatibility/";
79
79
  /**
80
80
  * No host binary was given and no executable `muse` is on `PATH` (FR-79107-1).
81
81
  * Raised by `MuseClient.spawn` before any process is started. The package does
@@ -94,16 +94,17 @@ export class MuseHostDiscoveryError extends Error {
94
94
  }
95
95
  }
96
96
  /**
97
- * `MuseClient.command` was asked to send a method whose state the facade owns
98
- * (FR-79107-2). Sending it raw would bypass that state, so it is refused
99
- * before anything is written; use the facade verb instead.
97
+ * `MuseClient.command` or `MuseClient.request` was asked to send a method
98
+ * whose state the facade owns (FR-79107-2). Sending it raw would bypass that
99
+ * state, so it is refused before anything is written; use the facade verb
100
+ * instead.
100
101
  */
101
102
  export class MuseFacadeOwnedMethodError extends Error {
102
103
  /** The refused wire method. */
103
104
  method;
104
105
  constructor(method) {
105
- super(`${method} is sent by the facade itself and cannot go through MuseClient.command; ` +
106
- "use the facade verb that owns it");
106
+ super(`${method} is sent by the facade itself and cannot go through ` +
107
+ "MuseClient.command or MuseClient.request; use the facade verb that owns it");
107
108
  this.name = "MuseFacadeOwnedMethodError";
108
109
  this.method = method;
109
110
  }
@@ -302,7 +302,7 @@ export class ApprovalRouter {
302
302
  const ack = await connection.command("approval/decide", decideParams);
303
303
  // A `terminal: true` ack closed the WHOLE approval; remember it so the
304
304
  // trailing stale-frontier update #37538 permits cannot re-prompt.
305
- if (ack["terminal"] === true)
305
+ if (ack.terminal === true)
306
306
  this.#terminalApprovals.add(approvalId);
307
307
  }
308
308
  catch (error) {