@muse-code/sdk 1.4.2 → 1.4.6

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.
@@ -42,6 +42,19 @@ export interface DuplexTransport {
42
42
  * public `child.close()` — gets the same step 0 (PR #22819 round 4).
43
43
  */
44
44
  export declare const submissionTail: unique symbol;
45
+ /**
46
+ * Module-private friend seam, like {@link submissionTail}: a request whose
47
+ * promise also yields the exact response frame it settled on, so a caller
48
+ * that refuses a successful result (the handshake's schema-fingerprint
49
+ * check) can put the whole refused frame on `ProtocolError.line`, the same
50
+ * value every other refusal carries (#50588 review).
51
+ */
52
+ export declare const requestWithFrame: unique symbol;
53
+ /** What {@link requestWithFrame} resolves with: the result and its wire line. */
54
+ export interface FramedResult {
55
+ readonly result: Record<string, unknown>;
56
+ readonly line: string;
57
+ }
45
58
  /**
46
59
  * Tuning knobs for a `Connection`. Every option is optional: the defaults
47
60
  * suit a spawned host, so most applications never pass this at all.
@@ -81,6 +94,12 @@ export declare class MspError extends Error {
81
94
  }
82
95
  /** A local framing/correlation violation, never a server-authored MSP error. */
83
96
  export declare class ProtocolError extends Error {
97
+ /**
98
+ * The inbound frame (wire line) the violation was detected on, when there
99
+ * is one — the whole line, e.g. the response a pending request refused;
100
+ * an oversized frame is cut to the frame limit. Absent for local state
101
+ * errors (closed connection, EOF) that no frame caused.
102
+ */
84
103
  readonly line: string | undefined;
85
104
  constructor(message: string, line?: string);
86
105
  }
@@ -104,6 +123,8 @@ export declare class Connection {
104
123
  /** See {@link submissionTail}. */
105
124
  [submissionTail](): Promise<void>;
106
125
  request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
126
+ /** See {@link requestWithFrame}. */
127
+ [requestWithFrame](method: string, params?: Record<string, unknown>): Promise<FramedResult>;
107
128
  /**
108
129
  * Take one id from THIS connection's single `commandId` minter (INV-013).
109
130
  *
@@ -8,6 +8,7 @@
8
8
  * stdout's encoding before implementing this interface — is one
9
9
  * well-behaved transport, not the general guarantee.
10
10
  */
11
+ import { createHash } from "node:crypto";
11
12
  const DEFAULT_FRAME_LIMIT_BYTES = 10_485_760;
12
13
  /**
13
14
  * Module-private friend seam (never on the package barrel, like spawn.ts's
@@ -16,6 +17,14 @@ const DEFAULT_FRAME_LIMIT_BYTES = 10_485_760;
16
17
  * public `child.close()` — gets the same step 0 (PR #22819 round 4).
17
18
  */
18
19
  export const submissionTail = Symbol("Connection.submissionTail");
20
+ /**
21
+ * Module-private friend seam, like {@link submissionTail}: a request whose
22
+ * promise also yields the exact response frame it settled on, so a caller
23
+ * that refuses a successful result (the handshake's schema-fingerprint
24
+ * check) can put the whole refused frame on `ProtocolError.line`, the same
25
+ * value every other refusal carries (#50588 review).
26
+ */
27
+ export const requestWithFrame = Symbol("Connection.requestWithFrame");
19
28
  /** The one typed error family consumers branch on (INV-012). */
20
29
  export class MspError extends Error {
21
30
  code;
@@ -33,6 +42,12 @@ export class MspError extends Error {
33
42
  }
34
43
  /** A local framing/correlation violation, never a server-authored MSP error. */
35
44
  export class ProtocolError extends Error {
45
+ /**
46
+ * The inbound frame (wire line) the violation was detected on, when there
47
+ * is one — the whole line, e.g. the response a pending request refused;
48
+ * an oversized frame is cut to the frame limit. Absent for local state
49
+ * errors (closed connection, EOF) that no frame caused.
50
+ */
36
51
  line;
37
52
  constructor(message, line) {
38
53
  super(message);
@@ -77,6 +92,13 @@ function canonical(value) {
77
92
  }
78
93
  return JSON.stringify(value);
79
94
  }
95
+ // FR-45137-1: the dedup guards compare fingerprints, so a remembered command
96
+ // costs 64 hex chars no matter how large its payload (or ack) was. The hash
97
+ // guards a correctness check, so it is SHA-256, not a faster non-crypto hash
98
+ // whose collision would silently accept a different payload.
99
+ function fingerprint(canonicalForm) {
100
+ return createHash("sha256").update(canonicalForm, "utf8").digest("hex");
101
+ }
80
102
  /** Create the SDK-owned UUIDv7 command-id source for a connection/client. */
81
103
  export function createUuidV7Mint() {
82
104
  let lastMs = -1;
@@ -177,6 +199,13 @@ export class Connection {
177
199
  return this.#submitTail;
178
200
  }
179
201
  request(method, params) {
202
+ return this.#request(method, params).then((framed) => framed.result);
203
+ }
204
+ /** See {@link requestWithFrame}. */
205
+ [requestWithFrame](method, params) {
206
+ return this.#request(method, params);
207
+ }
208
+ #request(method, params) {
180
209
  if (this.#finished)
181
210
  return Promise.reject(new ProtocolError("connection is closed"));
182
211
  const id = this.#mintRequestId();
@@ -193,7 +222,10 @@ export class Connection {
193
222
  ...(params === undefined ? {} : { params }),
194
223
  };
195
224
  return new Promise((resolve, reject) => {
196
- this.#pending.set(requestKey(id), { resolve, reject });
225
+ this.#pending.set(requestKey(id), {
226
+ resolve: (result, line) => resolve({ result, line }),
227
+ reject,
228
+ });
197
229
  void this.#write(request).catch((error) => {
198
230
  this.#pending.delete(requestKey(id));
199
231
  reject(error);
@@ -241,7 +273,7 @@ export class Connection {
241
273
  async command(method, params, options) {
242
274
  const commandId = options?.commandId ?? this.#mintCommandId();
243
275
  const commandParams = { ...params, commandId };
244
- const signature = canonical({ method, params: commandParams });
276
+ const signature = fingerprint(canonical({ method, params: commandParams }));
245
277
  const memory = this.#commands.get(commandId);
246
278
  if (memory !== undefined && memory.signature !== signature) {
247
279
  throw new ProtocolError(`commandId ${commandId} was reused with a different payload`);
@@ -261,10 +293,11 @@ export class Connection {
261
293
  if (ack["commandId"] !== undefined && ack["commandId"] !== commandId) {
262
294
  throw new ProtocolError(`${method} ack commandId ${String(ack["commandId"])} did not echo ${commandId}`);
263
295
  }
264
- if (remembered.ack !== undefined && canonical(remembered.ack) !== canonical(ack)) {
296
+ const ackFingerprint = fingerprint(canonical(ack));
297
+ if (remembered.ack !== undefined && remembered.ack !== ackFingerprint) {
265
298
  throw new ProtocolError(`${method} replay for commandId ${commandId} did not return a value-identical ack`);
266
299
  }
267
- remembered.ack = { ...ack };
300
+ remembered.ack = ackFingerprint;
268
301
  return ack;
269
302
  }
270
303
  catch (error) {
@@ -475,7 +508,7 @@ export class Connection {
475
508
  pending.reject(new ProtocolError("response result must be an object", line));
476
509
  return;
477
510
  }
478
- pending.resolve(result);
511
+ pending.resolve(result, line);
479
512
  return;
480
513
  }
481
514
  const error = frame["error"];
@@ -1,5 +1,6 @@
1
1
  /** Node stdio binding and type-state handshake for the MSP connection. */
2
- import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { spawn } from "node:child_process";
3
+ import type { ChildProcessWithoutNullStreams, SpawnOptionsWithoutStdio } from "node:child_process";
3
4
  import type { InitializeParams, InitializeResult } from "../msp.js";
4
5
  import { Connection } from "./connection.js";
5
6
  import type { ConnectionOptions, DuplexTransport, NotificationHandler, ProtocolErrorHandler, ServerRequestHandler } from "./connection.js";
@@ -73,9 +74,22 @@ export interface MuseServeChildOptions {
73
74
  * `0..2147483647`; anything else throws `RangeError` at spawn.
74
75
  */
75
76
  readonly shutdownTimeoutMs?: number;
77
+ /**
78
+ * Deterministic-test seam; production always uses `child_process.spawn`.
79
+ * A stub here observes the exact options the call site passes, so a
80
+ * `windowsHide` override at the call site fails the pin (FR-45141-1).
81
+ */
82
+ readonly spawnFn?: typeof spawn;
76
83
  }
77
84
  declare const ownedTransport: unique symbol;
78
85
  declare const adoptFlushSource: unique symbol;
86
+ /**
87
+ * Module friend seam: did `initialize` get a usable answer before the
88
+ * handshake failed? Exported from this MODULE only (never the package
89
+ * barrel) so the facade can word a host lost AFTER answering truthfully
90
+ * (#49912) without a new public member on `MspHandshake`.
91
+ */
92
+ export declare const initializeAnswered: unique symbol;
79
93
  /**
80
94
  * Shutdown deadline contract: `expired` resolves and never rejects; after
81
95
  * `clear()` it may remain pending forever.
@@ -122,6 +136,17 @@ export declare class ChildStdioTransport implements DuplexTransport {
122
136
  [adoptFlushSource](source: () => Promise<void>): void;
123
137
  close(flushed?: Promise<void>): Promise<void>;
124
138
  }
139
+ /**
140
+ * The exact options `MuseServeChild.spawn` hands to `child_process.spawn`,
141
+ * factored out so the spawn-options pin can assert on them without spawning.
142
+ * Exported from this MODULE only (never the package barrel) — the same
143
+ * module-only-test-seam precedent as `isBenignCloseRace`.
144
+ */
145
+ export declare function buildSpawnOptions(options: {
146
+ readonly cwd?: string;
147
+ readonly env?: NodeJS.ProcessEnv;
148
+ readonly detached: boolean;
149
+ }): SpawnOptionsWithoutStdio;
125
150
  /** One owned MSP host process with SS2.11 diagnostics and total exit mapping. */
126
151
  export declare class MuseServeChild {
127
152
  #private;
@@ -143,6 +168,8 @@ export declare class MspHandshake {
143
168
  onNotification(handler: NotificationHandler): void;
144
169
  onProtocolError(handler: ProtocolErrorHandler): void;
145
170
  close(): Promise<ProcessExit>;
171
+ /** See {@link initializeAnswered}. */
172
+ [initializeAnswered](): boolean;
146
173
  initialize(params: InitializeParams): Promise<SpawnedMspConnection>;
147
174
  }
148
175
  /** A fully initialized connection plus its owned process boundary. */
@@ -1,6 +1,6 @@
1
1
  /** Node stdio binding and type-state handshake for the MSP connection. */
2
2
  import { spawn } from "node:child_process";
3
- import { Connection, ProtocolError, submissionTail, } from "./connection.js";
3
+ import { Connection, ProtocolError, requestWithFrame, submissionTail, } from "./connection.js";
4
4
  import { checkServedFingerprint } from "../fingerprint.js";
5
5
  const DEFAULT_STDERR_MAX_BYTES = 8 * 1024;
6
6
  const DEFAULT_STDERR_MAX_LINES = 100;
@@ -16,6 +16,13 @@ const SIGTERM_GRACE_MS = 2_000;
16
16
  const MAX_SHUTDOWN_TIMEOUT_MS = 2_147_483_647;
17
17
  const ownedTransport = Symbol("MuseServeChild.transport");
18
18
  const adoptFlushSource = Symbol("ChildStdioTransport.adoptFlushSource");
19
+ /**
20
+ * Module friend seam: did `initialize` get a usable answer before the
21
+ * handshake failed? Exported from this MODULE only (never the package
22
+ * barrel) so the facade can word a host lost AFTER answering truthfully
23
+ * (#49912) without a new public member on `MspHandshake`.
24
+ */
25
+ export const initializeAnswered = Symbol("MspHandshake.initializeAnswered");
19
26
  function makeShutdownDeadline(budgetMs) {
20
27
  let timer;
21
28
  const expired = new Promise((resolve) => {
@@ -332,6 +339,23 @@ export class ChildStdioTransport {
332
339
  yield String(chunk);
333
340
  }
334
341
  }
342
+ /**
343
+ * The exact options `MuseServeChild.spawn` hands to `child_process.spawn`,
344
+ * factored out so the spawn-options pin can assert on them without spawning.
345
+ * Exported from this MODULE only (never the package barrel) — the same
346
+ * module-only-test-seam precedent as `isBenignCloseRace`.
347
+ */
348
+ export function buildSpawnOptions(options) {
349
+ return {
350
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
351
+ ...(options.env === undefined ? {} : { env: options.env }),
352
+ detached: options.detached,
353
+ // FR-45141-1: `muse serve` is never meant to be seen. Without this, a
354
+ // Windows host with no console of its own pops a console window for the
355
+ // life of the connection; the flag is a no-op on other platforms.
356
+ windowsHide: true,
357
+ };
358
+ }
335
359
  /** One owned MSP host process with SS2.11 diagnostics and total exit mapping. */
336
360
  export class MuseServeChild {
337
361
  #tail = new StderrTail();
@@ -360,12 +384,13 @@ export class MuseServeChild {
360
384
  // PID is a POSIX primitive, and pretending otherwise would fake
361
385
  // subtree containment there.
362
386
  const ownsProcessGroup = process.platform !== "win32";
363
- const spawnOptions = {
364
- ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
365
- ...(options.env === undefined ? {} : { env: options.env }),
387
+ const spawnOptions = buildSpawnOptions({
388
+ cwd: options.cwd,
389
+ env: options.env,
366
390
  detached: ownsProcessGroup,
367
- };
368
- return new MuseServeChild(spawn(options.museBin, [...(options.args ?? [])], spawnOptions), options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
391
+ });
392
+ const spawnChild = options.spawnFn ?? spawn;
393
+ return new MuseServeChild(spawnChild(options.museBin, [...(options.args ?? [])], spawnOptions), options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
369
394
  }
370
395
  get stderrTail() {
371
396
  return this.#tail.lines();
@@ -385,6 +410,7 @@ export class MspHandshake {
385
410
  child;
386
411
  #transport;
387
412
  #started = false;
413
+ #answered = false;
388
414
  constructor(options) {
389
415
  this.child = MuseServeChild.spawn({
390
416
  museBin: options.command,
@@ -420,14 +446,22 @@ export class MspHandshake {
420
446
  await this.#connection.close();
421
447
  return await this.#transport.exited;
422
448
  }
449
+ /** See {@link initializeAnswered}. */
450
+ [initializeAnswered]() {
451
+ return this.#answered;
452
+ }
423
453
  async initialize(params) {
424
454
  if (this.#started)
425
455
  throw new ProtocolError("initialize may be sent only once per connection");
426
456
  this.#started = true;
427
- const raw = await this.#connection.request("initialize", params);
457
+ const { result: raw, line } = await this.#connection[requestWithFrame]("initialize", params);
458
+ this.#answered = true;
428
459
  const result = raw;
429
460
  if (typeof result.schema?.fingerprint !== "string") {
430
- throw new ProtocolError("initialize result has no schema fingerprint");
461
+ // The whole refused frame rides on the error, as on every other
462
+ // refusal: a host that answered with an unusable result was not lost,
463
+ // and the facade tells the two apart by it (#49912, #50588 review).
464
+ throw new ProtocolError("initialize result has no schema fingerprint", line);
431
465
  }
432
466
  const fingerprintWarning = checkServedFingerprint(result.schema.fingerprint);
433
467
  this.#connection.notify("initialized");
@@ -52,3 +52,20 @@ export declare class MuseGapFillError extends Error {
52
52
  readonly next: string;
53
53
  constructor(reason: GapFillFailureReason, after: string, next: string, cause?: unknown);
54
54
  }
55
+ /**
56
+ * A required session-start permission-profile selection the client could not
57
+ * prove applied (TEST-42624-10, amendment 42624 § Compatibility): the start
58
+ * result carried no `permissionState`, and the `session/read` read-back
59
+ * served a different profile — or none at all. Never a silent default: the
60
+ * session stays open and the caller decides (set/retry or close) via
61
+ * `sessionId`, with no auto-close and no auto-set.
62
+ */
63
+ export declare class PermissionProfileNotApplied extends Error {
64
+ /** The profile id the caller required. */
65
+ readonly requested: string;
66
+ /** The committed profile id the read-back served, or null when unknown. */
67
+ readonly served: string | null;
68
+ /** The open session, so the caller can set, retry, or close it. */
69
+ readonly sessionId: string;
70
+ constructor(requested: string, served: string | null, sessionId: string);
71
+ }
@@ -49,3 +49,28 @@ export class MuseGapFillError extends Error {
49
49
  this.next = next;
50
50
  }
51
51
  }
52
+ /**
53
+ * A required session-start permission-profile selection the client could not
54
+ * prove applied (TEST-42624-10, amendment 42624 § Compatibility): the start
55
+ * result carried no `permissionState`, and the `session/read` read-back
56
+ * served a different profile — or none at all. Never a silent default: the
57
+ * session stays open and the caller decides (set/retry or close) via
58
+ * `sessionId`, with no auto-close and no auto-set.
59
+ */
60
+ export class PermissionProfileNotApplied extends Error {
61
+ /** The profile id the caller required. */
62
+ requested;
63
+ /** The committed profile id the read-back served, or null when unknown. */
64
+ served;
65
+ /** The open session, so the caller can set, retry, or close it. */
66
+ sessionId;
67
+ constructor(requested, served, sessionId) {
68
+ super(`required permissionProfile ${JSON.stringify(requested)} was not applied:` +
69
+ ` the committed selection is ${served === null ? "unknown" : JSON.stringify(served)}` +
70
+ ` (session ${sessionId})`);
71
+ this.name = "PermissionProfileNotApplied";
72
+ this.requested = requested;
73
+ this.served = served;
74
+ this.sessionId = sessionId;
75
+ }
76
+ }
@@ -80,6 +80,15 @@ export class ApprovalRouter {
80
80
  * with a frontier the host already closed, right before `approval/resolved`.
81
81
  */
82
82
  #terminalApprovals = new Set();
83
+ /**
84
+ * The most recently sent decide each approval has on the wire, settled when
85
+ * its ack lands or the decide fails. A trailing `stageResolved` update read
86
+ * in the SAME chunk as a `terminal: true` ack is routed before
87
+ * {@link #decide} resumes from that ack, so {@link updated} waits for it
88
+ * instead of re-asking. Scoped to the round trip: an open handler or a
89
+ * decide that never started blocks nobody.
90
+ */
91
+ #inFlight = new Map();
83
92
  constructor(sessionId, connection) {
84
93
  this.#sessionId = sessionId;
85
94
  this.#connection = connection;
@@ -171,8 +180,18 @@ export class ApprovalRouter {
171
180
  // parent's own approvals by contract (#36182 `skip_serializing_if`).
172
181
  if (params.subagentOrigin !== undefined)
173
182
  refreshed.subagentOrigin = params.subagentOrigin;
183
+ const acked = this.#inFlight.get(requested.approvalId);
184
+ if (acked !== undefined)
185
+ return this.#afterAck(acked, refreshed);
174
186
  return this.requested(refreshed);
175
187
  }
188
+ /** {@link updated}'s same-chunk arm: decide only once our own ack is in. */
189
+ async #afterAck(acked, refreshed) {
190
+ await acked;
191
+ if (this.#terminalApprovals.has(refreshed.approvalId))
192
+ return;
193
+ await this.requested(refreshed);
194
+ }
176
195
  static #stageKey(params) {
177
196
  const requirement = params.currentRequirementId;
178
197
  return `${params.approvalId} ${requirement.approvalId}:${String(requirement.sourceIndex)}`;
@@ -231,6 +250,14 @@ export class ApprovalRouter {
231
250
  // a plain-JS caller would be rejected by the host.
232
251
  if (decision.feedback != null)
233
252
  decideParams.feedback = decision.feedback;
253
+ // The wait covers only this round trip: an update for this approval read
254
+ // before the ack lands waits for it (see `#inFlight`).
255
+ const approvalId = params.approvalId;
256
+ let settle;
257
+ const acked = new Promise((resolve) => {
258
+ settle = resolve;
259
+ });
260
+ this.#inFlight.set(approvalId, acked);
234
261
  try {
235
262
  // No explicit `commandId`: unlike `sendUserTurn`, nothing here needs the
236
263
  // id before the ack, so `Connection.command()` mints and stamps it — and
@@ -239,10 +266,15 @@ export class ApprovalRouter {
239
266
  // A `terminal: true` ack closed the WHOLE approval; remember it so the
240
267
  // trailing stale-frontier update #37538 permits cannot re-prompt.
241
268
  if (ack["terminal"] === true)
242
- this.#terminalApprovals.add(params.approvalId);
269
+ this.#terminalApprovals.add(approvalId);
243
270
  }
244
271
  catch (error) {
245
- this.#report({ approvalId: params.approvalId, error, kind: "submitFailed" });
272
+ this.#report({ approvalId, error, kind: "submitFailed" });
273
+ }
274
+ finally {
275
+ settle();
276
+ if (this.#inFlight.get(approvalId) === acked)
277
+ this.#inFlight.delete(approvalId);
246
278
  }
247
279
  }
248
280
  #report(failure) {
@@ -46,7 +46,17 @@ import type { InitializeParams, InitializeResult, SessionResumeParams, SessionSt
46
46
  * `config` is excluded as well as `commandId` until the facade implements the
47
47
  * required `sessionMcp` grant check and forwarding.
48
48
  */
49
- export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "config">>;
49
+ export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "config"> & {
50
+ /**
51
+ * Require the `permissionProfile` selection (TEST-42624-10): when set,
52
+ * the client proves the committed selection equals the requested id —
53
+ * from the start result's `session.permissionState`, else a
54
+ * `session/read` read-back — and throws `PermissionProfileNotApplied`
55
+ * instead of proceeding on the host default. Client-local: never sent
56
+ * on the wire. Setting it without `permissionProfile` is a usage error.
57
+ */
58
+ requirePermissionProfile?: boolean;
59
+ }>;
50
60
  /** Caller-facing options for `session/resume` (tdd SS2.5.2). */
51
61
  export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId" | "config">>;
52
62
  /**
@@ -106,6 +116,15 @@ export declare class MuseClient {
106
116
  * reason this factory exists beside the bare constructor: SS2.13.1 makes the
107
117
  * absent/unrecognized distinction load-bearing, and a caller re-deriving it
108
118
  * by hand is a caller that can get it wrong.
119
+ *
120
+ * Rejects with {@link MuseHostStartError} when the host is lost before the
121
+ * handshake completes (the binary could not be spawned, or the process
122
+ * ended first — exit code or signal plus the bounded stderr tail;
123
+ * `answeredInitialize` says whether it died after a usable answer). A host
124
+ * that answers with a reply the SDK refuses keeps its own error: an
125
+ * `MspError` for an SS1.6 refusal, or a `ProtocolError` (with the whole
126
+ * refused frame on `line`) for a reply the SDK cannot use, such as one with
127
+ * no schema fingerprint.
109
128
  */
110
129
  static spawn(options: MuseClientSpawnOptions): Promise<MuseClient>;
111
130
  /**