@muse-code/sdk 1.4.20 → 1.4.24

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 CHANGED
@@ -54,7 +54,7 @@ import { MuseClient } from "@muse-code/sdk";
54
54
 
55
55
  const client = await MuseClient.spawn({
56
56
  args: ["serve"],
57
- clientInfo: { name: "my-app", version: "1.0.0" },
57
+ clientInfo: { name: "my_app", version: "1.0.0" },
58
58
  });
59
59
 
60
60
  const session = await client.startSession({ workspaceRoot: process.cwd() });
@@ -65,6 +65,10 @@ console.log(result.finalText);
65
65
  await client.close();
66
66
  ```
67
67
 
68
+ `clientInfo.name` must be a machine identifier: lowercase letters, digits and
69
+ `_` only (`[a-z0-9_]+`), at most 64 characters. The host refuses any other
70
+ name at `initialize`. `workspaceRoot` must be an absolute path.
71
+
68
72
  `session.run` sends one turn and resolves when the turn has ended, with the
69
73
  outcome, the final answer text, the turn's items, and its token usage. A turn
70
74
  that failed or was cancelled still resolves; read `result.outcome` to tell.
@@ -77,7 +81,9 @@ To stop it, pass an `AbortSignal`, for example
77
81
  `session.run(prompt, { signal: AbortSignal.timeout(60_000) })`. A turn still
78
82
  waiting in the queue is taken back, and a running turn is cancelled. `run`
79
83
  then waits for the turn to end and rejects with the signal's reason. An
80
- already-aborted signal sends nothing.
84
+ already-aborted signal sends nothing. The signal can stop a turn only after
85
+ the host has answered its `turn/start`: if the host stalls before it answers,
86
+ `run` keeps waiting until it does, timeout signal or not.
81
87
 
82
88
  To follow a turn as it runs, send it yourself and read its items:
83
89
 
@@ -138,12 +144,35 @@ for await (const { frame, outcome, item } of session.events()) {
138
144
 
139
145
  Each event arrives once, in order, including events the SDK fetches to fill a
140
146
  gap in delivery. `break` (or an `AbortSignal` passed as
141
- `session.events({ signal })`) stops listening. The stream ends when an
142
- ephemeral host dies and rejects with `MuseHostDiedError` when a durable one
143
- does, as `turn.items()` does. Reading it changes nothing else:
147
+ `session.events({ signal })`) stops listening. The stream ends when the
148
+ client closes or an ephemeral host dies, and rejects with `MuseHostDiedError`
149
+ when a durable host dies, as `turn.items()` does. Reading it changes nothing else:
144
150
  `turn.unqueue()` still returns the queued input it takes back, and that input
145
151
  is not repeated on an event.
146
152
 
153
+ To also watch what each sub-agent does, step by step, pass
154
+ `session.events({ subagents: true })`. Each sub-agent's events arrive in the
155
+ same stream, in order with the session's own, with `subagent` set to the
156
+ sub-agent they belong to (`itemId`, `subagentId`, `childSessionId`); their
157
+ `frame`, `outcome` and `item` are the sub-agent's own:
158
+
159
+ ```ts
160
+ for await (const event of session.events({ subagents: true })) {
161
+ if (event.subagent !== undefined) renderStep(event.subagent.subagentId, event.item);
162
+ else render(event.frame.method, event.outcome.fold, event.item);
163
+ }
164
+ ```
165
+
166
+ The SDK subscribes to each running sub-agent while such a stream is open, and
167
+ unsubscribes when the sub-agent finishes or no stream needs it. A sub-agent
168
+ already running when the stream opens streams from then on. Approval requests
169
+ from a sub-agent still arrive once, on the session, through `onApproval`.
170
+ Known limitation: if the host refuses the subscription to a sub-agent
171
+ (usually because it already finished, sometimes because it runs on another
172
+ host), its steps do not arrive and no reason is given; its start and result
173
+ still arrive on the session. A sub-agent resumed after it finished a turn is
174
+ not subscribed again, so the steps of that later run do not arrive either.
175
+
147
176
  To answer a question the agent asks, read it from
148
177
  `session.fold.pendingUserInputs()` and answer it with `session.answerUserInput`,
149
178
  one answer per question: `selectedLabel` for a single-select question,
@@ -168,6 +197,26 @@ The session itself can `fork`, `compact`, `rename`, and `leave`, and switch its
168
197
  model, reasoning effort, or approval mode (`setModel`, `setReasoningEffort`,
169
198
  `setApprovalMode`); `client.listModels()` lists the models it accepts.
170
199
 
200
+ To send a wire method the facade does not wrap, use `client.command` (a
201
+ command: the client mints its `commandId`) or `client.request` (a query).
202
+ Params and result are typed from the generated method map; a method the map
203
+ does not list is still sent, untyped:
204
+
205
+ ```ts
206
+ const ack = await client.command("task/stop", { sessionId, taskId });
207
+ const { models } = await client.request("model/list");
208
+ ```
209
+
210
+ For a raw connection (`const { connection } = await spawnMspConnection({ ... }).initialize({ ... })`),
211
+ `request` and `command` are typed the same way, and `addNotificationListener` gives one
212
+ notification method's typed params:
213
+
214
+ ```ts
215
+ connection.addNotificationListener("turn/completed", (params) => {
216
+ console.log(params.turnId, params.terminal);
217
+ });
218
+ ```
219
+
171
220
  Status: developer preview. The facade — spawn, session open/resume, turns,
172
221
  approvals, questions, and recovery after dropped deliveries — is complete and covered by
173
222
  the conformance suites in the source repository.
@@ -9,6 +9,7 @@
9
9
  * well-behaved transport, not the general guarantee.
10
10
  */
11
11
  import type { ErrorKind, ErrorObject, Notification, Request, RequestId } from "../msp.js";
12
+ import type { CommandParams, MethodName, MethodParams, NotificationName, NotificationParams, ParamsArgument, UnlistedMethod, WireResult } from "./surface.js";
12
13
  /**
13
14
  * The two-way text stream a `Connection` speaks MSP over.
14
15
  *
@@ -90,7 +91,16 @@ export interface CommandOptions {
90
91
  export type ServerRequestHandler = (request: Request) => Promise<Record<string, unknown>>;
91
92
  /** Receives every server notification, in arrival order. */
92
93
  export type NotificationHandler = (notification: Notification) => void;
93
- /** Receives each framing or correlation violation the connection detects on its inbound stream. */
94
+ /**
95
+ * Receives one notification method's typed `params`, plus the whole frame
96
+ * (for `emittedAtMs`). Registered with `Connection.addNotificationListener`.
97
+ */
98
+ export type NotificationListener<M extends NotificationName> = (params: NotificationParams<M>, notification: Notification) => void;
99
+ /**
100
+ * Receives each framing or correlation violation the connection detects on
101
+ * its inbound stream, and each exception a notification listener throws
102
+ * (that error rides on `cause`).
103
+ */
94
104
  export type ProtocolErrorHandler = (error: ProtocolError) => void;
95
105
  /** The one typed error family consumers branch on (INV-012). */
96
106
  export declare class MspError extends Error {
@@ -101,11 +111,12 @@ export declare class MspError extends Error {
101
111
  constructor(error: ErrorObject);
102
112
  }
103
113
  /**
104
- * A local framing/correlation violation, never a server-authored MSP error.
105
- * When a call fails because a host `MuseClient.spawn` started died, the error
106
- * it rejects with (usually this class; the transport's own error when a write
107
- * failed) has a `MuseHostDiedError` `cause` saying how the host ended, so
108
- * check `cause` alone.
114
+ * A local framing/correlation violation, or an exception a notification
115
+ * listener threw (the listener's error on `cause`); never a server-authored
116
+ * MSP error. When a call fails because a host `MuseClient.spawn` started
117
+ * died, the error it rejects with (usually this class; the transport's own
118
+ * error when a write failed) has a `MuseHostDiedError` `cause` saying how the
119
+ * host ended, so check `cause` alone.
109
120
  */
110
121
  export declare class ProtocolError extends Error {
111
122
  /**
@@ -115,7 +126,9 @@ export declare class ProtocolError extends Error {
115
126
  * errors (closed connection, EOF) that no frame caused.
116
127
  */
117
128
  readonly line: string | undefined;
118
- constructor(message: string, line?: string);
129
+ constructor(message: string, line?: string, options?: {
130
+ cause?: unknown;
131
+ });
119
132
  }
120
133
  /** Create the SDK-owned UUIDv7 command-id source for a connection/client. */
121
134
  export declare function createUuidV7Mint(): () => string;
@@ -137,6 +150,26 @@ export declare class Connection {
137
150
  get closed(): Promise<void>;
138
151
  /** See {@link submissionTail}. */
139
152
  [submissionTail](): Promise<void>;
153
+ /**
154
+ * Send one request and resolve with its result. A stable method is typed
155
+ * from the generated method map; any other method name stays sendable
156
+ * untyped, for an experimental method or a host newer than these types.
157
+ */
158
+ request<M extends MethodName>(method: M, ...params: ParamsArgument<MethodParams<M>>): Promise<WireResult<M>>;
159
+ request<M extends string>(method: UnlistedMethod<MethodName, M>, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
160
+ /**
161
+ * @deprecated Loosely typed params for a listed method: pass the method's
162
+ * generated params type. This overload goes away in a later release
163
+ * (ADR 25304 D3's deprecation path).
164
+ */
165
+ request(method: MethodName, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
166
+ /**
167
+ * @deprecated A generic `M extends string` method, or a union mixing listed
168
+ * and unlisted names, cannot be checked; it compiles untyped for one
169
+ * release and goes away with the loose overload above (ADR 25304 D3's
170
+ * deprecation path). Widen the name to `string` (`method as string`) to
171
+ * keep sending it untyped.
172
+ */
140
173
  request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
141
174
  /** See {@link peerEndCause}. */
142
175
  [peerEndCause](read: () => Promise<unknown> | undefined): void;
@@ -159,8 +192,35 @@ export declare class Connection {
159
192
  notify(method: string, params?: Record<string, unknown>): void;
160
193
  onServerRequest(handler: ServerRequestHandler): void;
161
194
  onNotification(handler: NotificationHandler): void;
195
+ /**
196
+ * Add a listener for one notification method, typed from the generated
197
+ * notification map. Listeners run after the `onNotification` handler, in
198
+ * the order added. A listener that throws (or rejects) is reported to
199
+ * `onProtocolError`, or as a process warning when no handler is set; the
200
+ * connection, the other listeners and pending calls go on. Returns a
201
+ * function that removes this listener.
202
+ */
203
+ addNotificationListener<M extends NotificationName>(method: M, listener: NotificationListener<M>): () => void;
162
204
  onProtocolError(handler: ProtocolErrorHandler): void;
163
205
  flush(): Promise<void>;
206
+ /**
207
+ * Send one command (SS3.1.1): mint its `commandId`, retry a
208
+ * nothing-admitted refusal under the same id, and check the ack. Typed like
209
+ * `request`, with `commandId` left out of the params.
210
+ */
211
+ command<M extends MethodName>(method: M, params: CommandParams<M>, options?: CommandOptions): Promise<WireResult<M>>;
212
+ command<M extends string>(method: UnlistedMethod<MethodName, M>, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
213
+ /**
214
+ * @deprecated Loosely typed params for a listed method: pass the method's
215
+ * generated params type. This overload goes away in a later release
216
+ * (ADR 25304 D3's deprecation path).
217
+ */
218
+ command(method: MethodName, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
219
+ /**
220
+ * @deprecated A generic or mixed-union method name cannot be checked; it
221
+ * compiles untyped for one release, as on `request`. Widen the name to
222
+ * `string` (`method as string`) to keep sending it untyped.
223
+ */
164
224
  command(method: string, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
165
225
  close(): Promise<void>;
166
226
  }
@@ -49,11 +49,12 @@ export class MspError extends Error {
49
49
  }
50
50
  }
51
51
  /**
52
- * A local framing/correlation violation, never a server-authored MSP error.
53
- * When a call fails because a host `MuseClient.spawn` started died, the error
54
- * it rejects with (usually this class; the transport's own error when a write
55
- * failed) has a `MuseHostDiedError` `cause` saying how the host ended, so
56
- * check `cause` alone.
52
+ * A local framing/correlation violation, or an exception a notification
53
+ * listener threw (the listener's error on `cause`); never a server-authored
54
+ * MSP error. When a call fails because a host `MuseClient.spawn` started
55
+ * died, the error it rejects with (usually this class; the transport's own
56
+ * error when a write failed) has a `MuseHostDiedError` `cause` saying how the
57
+ * host ended, so check `cause` alone.
57
58
  */
58
59
  export class ProtocolError extends Error {
59
60
  /**
@@ -63,12 +64,21 @@ export class ProtocolError extends Error {
63
64
  * errors (closed connection, EOF) that no frame caused.
64
65
  */
65
66
  line;
66
- constructor(message, line) {
67
- super(message);
67
+ constructor(message, line, options) {
68
+ super(message, options);
68
69
  this.name = "ProtocolError";
69
70
  this.line = line;
70
71
  }
71
72
  }
73
+ /** A thrown value's text, even for one whose `toString` is missing or throws. */
74
+ function describeThrown(error) {
75
+ try {
76
+ return String(error);
77
+ }
78
+ catch {
79
+ return Object.prototype.toString.call(error);
80
+ }
81
+ }
72
82
  function requestKey(id) {
73
83
  return `${typeof id === "number" ? "number" : "string"}:${String(id)}`;
74
84
  }
@@ -176,6 +186,7 @@ export class Connection {
176
186
  #nextRequestId = 1;
177
187
  #serverRequestHandler;
178
188
  #notificationHandler;
189
+ #notificationListeners = new Map();
179
190
  #protocolErrorHandler;
180
191
  #peerEndCause;
181
192
  #endCause;
@@ -216,8 +227,8 @@ export class Connection {
216
227
  [submissionTail]() {
217
228
  return this.#submitTail;
218
229
  }
219
- request(method, params) {
220
- return this.#request(method, params).then((framed) => framed.result);
230
+ request(method, ...params) {
231
+ return this.#request(method, params[0]).then((framed) => framed.result);
221
232
  }
222
233
  /** See {@link peerEndCause}. */
223
234
  [peerEndCause](read) {
@@ -288,6 +299,26 @@ export class Connection {
288
299
  onNotification(handler) {
289
300
  this.#notificationHandler = handler;
290
301
  }
302
+ /**
303
+ * Add a listener for one notification method, typed from the generated
304
+ * notification map. Listeners run after the `onNotification` handler, in
305
+ * the order added. A listener that throws (or rejects) is reported to
306
+ * `onProtocolError`, or as a process warning when no handler is set; the
307
+ * connection, the other listeners and pending calls go on. Returns a
308
+ * function that removes this listener.
309
+ */
310
+ addNotificationListener(method, listener) {
311
+ const untyped = (params, notification) => listener(params, notification);
312
+ let listeners = this.#notificationListeners.get(method);
313
+ if (listeners === undefined) {
314
+ listeners = new Set();
315
+ this.#notificationListeners.set(method, listeners);
316
+ }
317
+ listeners.add(untyped);
318
+ return () => {
319
+ listeners.delete(untyped);
320
+ };
321
+ }
291
322
  onProtocolError(handler) {
292
323
  this.#protocolErrorHandler = handler;
293
324
  }
@@ -310,7 +341,7 @@ export class Connection {
310
341
  const retryDelay = options?.retryDelay ?? defaultRetryDelay;
311
342
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
312
343
  try {
313
- const ack = await this.request(method, commandParams);
344
+ const ack = await this.#request(method, commandParams).then((framed) => framed.result);
314
345
  // session/start's and session/resume's result schemas omit the
315
346
  // redundant commandId echo (the two omitting families recorded in
316
347
  // specs/14990-muse-sdk/contracts/sdk-surface.md; approval/decide
@@ -504,7 +535,33 @@ export class Connection {
504
535
  });
505
536
  return;
506
537
  }
507
- this.#notificationHandler?.(parsed);
538
+ const notification = parsed;
539
+ this.#notificationHandler?.(notification);
540
+ // A copy, so a listener added during dispatch waits for the next frame.
541
+ for (const listener of [...(this.#notificationListeners.get(method) ?? [])]) {
542
+ // One consumer's bug refuses only its own listener (Constitution
543
+ // XIII): the connection, its other listeners and pending calls go on.
544
+ const report = (error) => {
545
+ const failure = new ProtocolError(`listener for ${method} threw: ${describeThrown(error)}`, line, {
546
+ cause: error,
547
+ });
548
+ // With no handler a listener bug would vanish; a warning keeps it visible.
549
+ if (this.#protocolErrorHandler === undefined)
550
+ process.emitWarning(failure);
551
+ else
552
+ this.#protocolErrorHandler(failure);
553
+ };
554
+ try {
555
+ const result = listener(notification.params, notification);
556
+ // Any thenable, so a promise from another realm (a `vm` context) is caught too.
557
+ if (typeof result?.then === "function") {
558
+ Promise.resolve(result).catch(report);
559
+ }
560
+ }
561
+ catch (error) {
562
+ report(error);
563
+ }
564
+ }
508
565
  return;
509
566
  }
510
567
  if (typeof id !== "string" && typeof id !== "number") {
@@ -22,6 +22,26 @@ export interface SpawnMspConnectionOptions {
22
22
  readonly shutdownTimeoutMs?: number;
23
23
  /** See {@link MuseServeChildOptions.spawnFn}. */
24
24
  readonly spawnFn?: MuseServeChildOptions["spawnFn"];
25
+ /**
26
+ * ADR 22936 D3, default off: refuse at connect when the host's stable
27
+ * fingerprint differs AND its `schema.compatibilityEpoch` differs from the
28
+ * epoch this SDK was built against (a declared non-additive advance). The
29
+ * refusal is a `SchemaCompatibilityError` naming both bundles; the SDK
30
+ * closes the host it spawned first and never sends `initialized`. Off, the
31
+ * same mismatch is a `fingerprintWarning` with `tier: "declaredBreaking"`
32
+ * and the connection proceeds as before. Equal or absent epochs (the
33
+ * additive tier) are never refused, whatever this setting.
34
+ */
35
+ readonly refuseDeclaredBreakingSchema?: boolean;
36
+ /**
37
+ * Cancels the handshake. Aborting before `initialize` resolves closes the
38
+ * host through the usual shutdown ladder, then rejects with an `AbortError`
39
+ * whose `cause` is `signal.reason`; an already-aborted signal throws that
40
+ * error here, before anything is spawned. Aborting later does nothing. The
41
+ * rejection waits for the host to exit: a host that ignores stdin EOF takes
42
+ * up to `shutdownTimeoutMs` plus the 2 s SIGTERM grace.
43
+ */
44
+ readonly signal?: AbortSignal;
25
45
  }
26
46
  /**
27
47
  * How the host process ended: its exit code, or the signal that ended it.
@@ -110,6 +130,12 @@ declare const adoptFlushSource: unique symbol;
110
130
  * (#49912) without a new public member on `MspHandshake`.
111
131
  */
112
132
  export declare const initializeAnswered: unique symbol;
133
+ /**
134
+ * Node's abort shape (`child_process.spawn({ signal })`): callers branch on
135
+ * `name`. Exported from this MODULE only (never the package barrel) so the
136
+ * facade raises the same error before host discovery.
137
+ */
138
+ export declare function abortError(reason: unknown): Error;
113
139
  /**
114
140
  * Shutdown deadline contract: `expired` resolves and never rejects; after
115
141
  * `clear()` it may remain pending forever.