@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.
- package/README.md +78 -2
- package/dist/src/connection/connection.d.ts +83 -6
- package/dist/src/connection/connection.js +113 -14
- package/dist/src/connection/spawn.d.ts +50 -4
- package/dist/src/connection/spawn.js +161 -33
- package/dist/src/connection/surface.d.ts +49 -0
- package/dist/src/connection/surface.js +8 -0
- package/dist/src/errors.d.ts +6 -5
- package/dist/src/errors.js +7 -6
- package/dist/src/facade/approval.js +1 -1
- package/dist/src/facade/client.d.ts +158 -17
- package/dist/src/facade/client.js +370 -74
- package/dist/src/facade/gap-fill.d.ts +2 -0
- package/dist/src/facade/gap-fill.js +11 -2
- package/dist/src/facade/host-death.d.ts +5 -1
- package/dist/src/facade/host-death.js +5 -1
- package/dist/src/facade/session.d.ts +133 -5
- package/dist/src/facade/session.js +419 -13
- package/dist/src/facade/turn-handle.d.ts +23 -0
- package/dist/src/facade/turn-handle.js +1 -1
- package/dist/src/fingerprint.d.ts +79 -4
- package/dist/src/fingerprint.js +110 -11
- package/dist/src/fingerprint.stamped.d.ts +2 -1
- package/dist/src/fingerprint.stamped.js +2 -1
- package/dist/src/fold/extension.d.ts +39 -0
- package/dist/src/fold/extension.js +49 -0
- package/dist/src/fold/session-fold.d.ts +11 -0
- package/dist/src/fold/session-fold.js +13 -0
- package/dist/src/index.d.ts +6 -5
- package/dist/src/index.js +1 -1
- package/dist/src/msp.d.ts +319 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,6 +14,11 @@ agent over the Muse Session Protocol (MSP).
|
|
|
14
14
|
- A client-side fold keeps a live, typed view of the session — items, session
|
|
15
15
|
state, pending commands — with gap recovery after dropped deliveries and
|
|
16
16
|
safe same-command retry that can never double-submit.
|
|
17
|
+
- Observe the connection itself: `client.onNotification` hears every
|
|
18
|
+
notification the host sends (including ones that name no session, such as
|
|
19
|
+
`usage/changed`), `onProtocolError` hears messages the SDK rejects as
|
|
20
|
+
malformed, and `client.closed` resolves when the connection closes. Each
|
|
21
|
+
`on*` call returns its own unsubscribe function.
|
|
17
22
|
|
|
18
23
|
**Zero runtime dependencies**: pure TypeScript over the Node standard
|
|
19
24
|
library. The MSP wire declarations are bundled into the package, so nothing
|
|
@@ -49,7 +54,7 @@ import { MuseClient } from "@muse-code/sdk";
|
|
|
49
54
|
|
|
50
55
|
const client = await MuseClient.spawn({
|
|
51
56
|
args: ["serve"],
|
|
52
|
-
clientInfo: { name: "
|
|
57
|
+
clientInfo: { name: "my_app", version: "1.0.0" },
|
|
53
58
|
});
|
|
54
59
|
|
|
55
60
|
const session = await client.startSession({ workspaceRoot: process.cwd() });
|
|
@@ -60,6 +65,10 @@ console.log(result.finalText);
|
|
|
60
65
|
await client.close();
|
|
61
66
|
```
|
|
62
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
|
+
|
|
63
72
|
`session.run` sends one turn and resolves when the turn has ended, with the
|
|
64
73
|
outcome, the final answer text, the turn's items, and its token usage. A turn
|
|
65
74
|
that failed or was cancelled still resolves; read `result.outcome` to tell.
|
|
@@ -72,7 +81,9 @@ To stop it, pass an `AbortSignal`, for example
|
|
|
72
81
|
`session.run(prompt, { signal: AbortSignal.timeout(60_000) })`. A turn still
|
|
73
82
|
waiting in the queue is taken back, and a running turn is cancelled. `run`
|
|
74
83
|
then waits for the turn to end and rejects with the signal's reason. An
|
|
75
|
-
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.
|
|
76
87
|
|
|
77
88
|
To follow a turn as it runs, send it yourself and read its items:
|
|
78
89
|
|
|
@@ -117,6 +128,51 @@ the resume reply can happen before `resumeSession` returns, so
|
|
|
117
128
|
that throws, picks a choice that was not offered, or adds feedback to a choice
|
|
118
129
|
that takes none (which is then answered with the reject choice).
|
|
119
130
|
|
|
131
|
+
To render incrementally, read `session.events()`: every event the session
|
|
132
|
+
folds from then on, with what it changed. Read the current state first, then
|
|
133
|
+
subscribe in the same tick, and nothing is missed, including the events that
|
|
134
|
+
arrived before `startSession` or `resumeSession` returned:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
const session = await client.startSession();
|
|
138
|
+
renderAll(session.fold); // the state so far
|
|
139
|
+
for await (const { frame, outcome, item } of session.events()) {
|
|
140
|
+
// `item` is the item as of this event; `session.fold` may already be ahead.
|
|
141
|
+
render(frame.method, outcome.fold, item);
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Each event arrives once, in order, including events the SDK fetches to fill a
|
|
146
|
+
gap in delivery. `break` (or an `AbortSignal` passed as
|
|
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:
|
|
150
|
+
`turn.unqueue()` still returns the queued input it takes back, and that input
|
|
151
|
+
is not repeated on an event.
|
|
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
|
+
|
|
120
176
|
To answer a question the agent asks, read it from
|
|
121
177
|
`session.fold.pendingUserInputs()` and answer it with `session.answerUserInput`,
|
|
122
178
|
one answer per question: `selectedLabel` for a single-select question,
|
|
@@ -141,6 +197,26 @@ The session itself can `fork`, `compact`, `rename`, and `leave`, and switch its
|
|
|
141
197
|
model, reasoning effort, or approval mode (`setModel`, `setReasoningEffort`,
|
|
142
198
|
`setApprovalMode`); `client.listModels()` lists the models it accepts.
|
|
143
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
|
+
|
|
144
220
|
Status: developer preview. The facade — spawn, session open/resume, turns,
|
|
145
221
|
approvals, questions, and recovery after dropped deliveries — is complete and covered by
|
|
146
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
|
*
|
|
@@ -50,6 +51,14 @@ export declare const submissionTail: unique symbol;
|
|
|
50
51
|
* value every other refusal carries (#50588 review).
|
|
51
52
|
*/
|
|
52
53
|
export declare const requestWithFrame: unique symbol;
|
|
54
|
+
/**
|
|
55
|
+
* Module-private friend seam, like {@link submissionTail}: the owner of the
|
|
56
|
+
* peer process says, once when the connection finishes, why the peer is gone.
|
|
57
|
+
* A promise it returns settles (never rejects) with the `cause` given to
|
|
58
|
+
* every call the connection then fails; `undefined` keeps the bare error and
|
|
59
|
+
* its timing.
|
|
60
|
+
*/
|
|
61
|
+
export declare const peerEndCause: unique symbol;
|
|
53
62
|
/** What {@link requestWithFrame} resolves with: the result and its wire line. */
|
|
54
63
|
export interface FramedResult {
|
|
55
64
|
readonly result: Record<string, unknown>;
|
|
@@ -82,7 +91,16 @@ export interface CommandOptions {
|
|
|
82
91
|
export type ServerRequestHandler = (request: Request) => Promise<Record<string, unknown>>;
|
|
83
92
|
/** Receives every server notification, in arrival order. */
|
|
84
93
|
export type NotificationHandler = (notification: Notification) => void;
|
|
85
|
-
/**
|
|
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
|
+
*/
|
|
86
104
|
export type ProtocolErrorHandler = (error: ProtocolError) => void;
|
|
87
105
|
/** The one typed error family consumers branch on (INV-012). */
|
|
88
106
|
export declare class MspError extends Error {
|
|
@@ -92,7 +110,14 @@ export declare class MspError extends Error {
|
|
|
92
110
|
readonly retryable: boolean | undefined;
|
|
93
111
|
constructor(error: ErrorObject);
|
|
94
112
|
}
|
|
95
|
-
/**
|
|
113
|
+
/**
|
|
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.
|
|
120
|
+
*/
|
|
96
121
|
export declare class ProtocolError extends Error {
|
|
97
122
|
/**
|
|
98
123
|
* The inbound frame (wire line) the violation was detected on, when there
|
|
@@ -101,7 +126,9 @@ export declare class ProtocolError extends Error {
|
|
|
101
126
|
* errors (closed connection, EOF) that no frame caused.
|
|
102
127
|
*/
|
|
103
128
|
readonly line: string | undefined;
|
|
104
|
-
constructor(message: string, line?: string
|
|
129
|
+
constructor(message: string, line?: string, options?: {
|
|
130
|
+
cause?: unknown;
|
|
131
|
+
});
|
|
105
132
|
}
|
|
106
133
|
/** Create the SDK-owned UUIDv7 command-id source for a connection/client. */
|
|
107
134
|
export declare function createUuidV7Mint(): () => string;
|
|
@@ -112,9 +139,10 @@ export declare function createUuidV7Mint(): () => string;
|
|
|
112
139
|
* responses, enforces the frame-size limit, and hands inbound notifications
|
|
113
140
|
* and server requests to the handlers you register. It is transport-agnostic:
|
|
114
141
|
* pair it with any `DuplexTransport`. Most applications never build one
|
|
115
|
-
* directly — `MuseClient.spawn` or `spawnMspConnection` does it for you
|
|
116
|
-
*
|
|
117
|
-
* your own transport
|
|
142
|
+
* directly — `MuseClient.spawn` or `spawnMspConnection` does it for you, and
|
|
143
|
+
* `MuseClient.onNotification` hears the notification feed. Reach for a bare
|
|
144
|
+
* `Connection` only for your own transport or to handle frames before session
|
|
145
|
+
* routing.
|
|
118
146
|
*/
|
|
119
147
|
export declare class Connection {
|
|
120
148
|
#private;
|
|
@@ -122,7 +150,29 @@ export declare class Connection {
|
|
|
122
150
|
get closed(): Promise<void>;
|
|
123
151
|
/** See {@link submissionTail}. */
|
|
124
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
|
+
*/
|
|
125
173
|
request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
174
|
+
/** See {@link peerEndCause}. */
|
|
175
|
+
[peerEndCause](read: () => Promise<unknown> | undefined): void;
|
|
126
176
|
/** See {@link requestWithFrame}. */
|
|
127
177
|
[requestWithFrame](method: string, params?: Record<string, unknown>): Promise<FramedResult>;
|
|
128
178
|
/**
|
|
@@ -142,8 +192,35 @@ export declare class Connection {
|
|
|
142
192
|
notify(method: string, params?: Record<string, unknown>): void;
|
|
143
193
|
onServerRequest(handler: ServerRequestHandler): void;
|
|
144
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;
|
|
145
204
|
onProtocolError(handler: ProtocolErrorHandler): void;
|
|
146
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
|
+
*/
|
|
147
224
|
command(method: string, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
|
|
148
225
|
close(): Promise<void>;
|
|
149
226
|
}
|
|
@@ -25,6 +25,14 @@ export const submissionTail = Symbol("Connection.submissionTail");
|
|
|
25
25
|
* value every other refusal carries (#50588 review).
|
|
26
26
|
*/
|
|
27
27
|
export const requestWithFrame = Symbol("Connection.requestWithFrame");
|
|
28
|
+
/**
|
|
29
|
+
* Module-private friend seam, like {@link submissionTail}: the owner of the
|
|
30
|
+
* peer process says, once when the connection finishes, why the peer is gone.
|
|
31
|
+
* A promise it returns settles (never rejects) with the `cause` given to
|
|
32
|
+
* every call the connection then fails; `undefined` keeps the bare error and
|
|
33
|
+
* its timing.
|
|
34
|
+
*/
|
|
35
|
+
export const peerEndCause = Symbol("Connection.peerEndCause");
|
|
28
36
|
/** The one typed error family consumers branch on (INV-012). */
|
|
29
37
|
export class MspError extends Error {
|
|
30
38
|
code;
|
|
@@ -40,7 +48,14 @@ export class MspError extends Error {
|
|
|
40
48
|
this.retryable = error.data?.retryable;
|
|
41
49
|
}
|
|
42
50
|
}
|
|
43
|
-
/**
|
|
51
|
+
/**
|
|
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.
|
|
58
|
+
*/
|
|
44
59
|
export class ProtocolError extends Error {
|
|
45
60
|
/**
|
|
46
61
|
* The inbound frame (wire line) the violation was detected on, when there
|
|
@@ -49,12 +64,21 @@ export class ProtocolError extends Error {
|
|
|
49
64
|
* errors (closed connection, EOF) that no frame caused.
|
|
50
65
|
*/
|
|
51
66
|
line;
|
|
52
|
-
constructor(message, line) {
|
|
53
|
-
super(message);
|
|
67
|
+
constructor(message, line, options) {
|
|
68
|
+
super(message, options);
|
|
54
69
|
this.name = "ProtocolError";
|
|
55
70
|
this.line = line;
|
|
56
71
|
}
|
|
57
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
|
+
}
|
|
58
82
|
function requestKey(id) {
|
|
59
83
|
return `${typeof id === "number" ? "number" : "string"}:${String(id)}`;
|
|
60
84
|
}
|
|
@@ -147,9 +171,10 @@ function isObject(value) {
|
|
|
147
171
|
* responses, enforces the frame-size limit, and hands inbound notifications
|
|
148
172
|
* and server requests to the handlers you register. It is transport-agnostic:
|
|
149
173
|
* pair it with any `DuplexTransport`. Most applications never build one
|
|
150
|
-
* directly — `MuseClient.spawn` or `spawnMspConnection` does it for you
|
|
151
|
-
*
|
|
152
|
-
* your own transport
|
|
174
|
+
* directly — `MuseClient.spawn` or `spawnMspConnection` does it for you, and
|
|
175
|
+
* `MuseClient.onNotification` hears the notification feed. Reach for a bare
|
|
176
|
+
* `Connection` only for your own transport or to handle frames before session
|
|
177
|
+
* routing.
|
|
153
178
|
*/
|
|
154
179
|
export class Connection {
|
|
155
180
|
#transport;
|
|
@@ -161,7 +186,10 @@ export class Connection {
|
|
|
161
186
|
#nextRequestId = 1;
|
|
162
187
|
#serverRequestHandler;
|
|
163
188
|
#notificationHandler;
|
|
189
|
+
#notificationListeners = new Map();
|
|
164
190
|
#protocolErrorHandler;
|
|
191
|
+
#peerEndCause;
|
|
192
|
+
#endCause;
|
|
165
193
|
#writeTail = Promise.resolve();
|
|
166
194
|
// Settles when every accepted frame has been HANDED to the transport, as
|
|
167
195
|
// opposed to #writeTail, which settles when the peer has taken it.
|
|
@@ -199,16 +227,24 @@ export class Connection {
|
|
|
199
227
|
[submissionTail]() {
|
|
200
228
|
return this.#submitTail;
|
|
201
229
|
}
|
|
202
|
-
request(method, params) {
|
|
203
|
-
return this.#request(method, params).then((framed) => framed.result);
|
|
230
|
+
request(method, ...params) {
|
|
231
|
+
return this.#request(method, params[0]).then((framed) => framed.result);
|
|
232
|
+
}
|
|
233
|
+
/** See {@link peerEndCause}. */
|
|
234
|
+
[peerEndCause](read) {
|
|
235
|
+
this.#peerEndCause = read;
|
|
236
|
+
// The host can die between the handshake and this registration.
|
|
237
|
+
if (this.#finished && this.#endCause === undefined)
|
|
238
|
+
this.#endCause = read();
|
|
204
239
|
}
|
|
205
240
|
/** See {@link requestWithFrame}. */
|
|
206
241
|
[requestWithFrame](method, params) {
|
|
207
242
|
return this.#request(method, params);
|
|
208
243
|
}
|
|
209
244
|
#request(method, params) {
|
|
210
|
-
if (this.#finished)
|
|
211
|
-
return Promise
|
|
245
|
+
if (this.#finished) {
|
|
246
|
+
return new Promise((_, reject) => this.#rejectWithEndCause(reject, new ProtocolError("connection is closed")));
|
|
247
|
+
}
|
|
212
248
|
const id = this.#mintRequestId();
|
|
213
249
|
if (typeof id !== "string" && (typeof id !== "number" || !Number.isInteger(id))) {
|
|
214
250
|
return Promise.reject(new ProtocolError("request id must be a string or integer"));
|
|
@@ -229,7 +265,7 @@ export class Connection {
|
|
|
229
265
|
});
|
|
230
266
|
void this.#write(request).catch((error) => {
|
|
231
267
|
this.#pending.delete(requestKey(id));
|
|
232
|
-
reject
|
|
268
|
+
this.#rejectWithEndCause(reject, error);
|
|
233
269
|
});
|
|
234
270
|
});
|
|
235
271
|
}
|
|
@@ -263,6 +299,26 @@ export class Connection {
|
|
|
263
299
|
onNotification(handler) {
|
|
264
300
|
this.#notificationHandler = handler;
|
|
265
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
|
+
}
|
|
266
322
|
onProtocolError(handler) {
|
|
267
323
|
this.#protocolErrorHandler = handler;
|
|
268
324
|
}
|
|
@@ -285,7 +341,7 @@ export class Connection {
|
|
|
285
341
|
const retryDelay = options?.retryDelay ?? defaultRetryDelay;
|
|
286
342
|
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
287
343
|
try {
|
|
288
|
-
const ack = await this
|
|
344
|
+
const ack = await this.#request(method, commandParams).then((framed) => framed.result);
|
|
289
345
|
// session/start's and session/resume's result schemas omit the
|
|
290
346
|
// redundant commandId echo (the two omitting families recorded in
|
|
291
347
|
// specs/14990-muse-sdk/contracts/sdk-surface.md; approval/decide
|
|
@@ -302,7 +358,10 @@ export class Connection {
|
|
|
302
358
|
return ack;
|
|
303
359
|
}
|
|
304
360
|
catch (error) {
|
|
361
|
+
// A present data.retryable overrides the code's table default, so an
|
|
362
|
+
// explicit false stops the retry; absent keeps it.
|
|
305
363
|
const retryableNothingAdmitted = error instanceof MspError &&
|
|
364
|
+
error.retryable !== false &&
|
|
306
365
|
((error.code === -32001 && error.kind === "overloaded") ||
|
|
307
366
|
(error.code === -32031 && error.kind === "backpressured"));
|
|
308
367
|
if (!retryableNothingAdmitted || attempt === maxAttempts)
|
|
@@ -476,7 +535,33 @@ export class Connection {
|
|
|
476
535
|
});
|
|
477
536
|
return;
|
|
478
537
|
}
|
|
479
|
-
|
|
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
|
+
}
|
|
480
565
|
return;
|
|
481
566
|
}
|
|
482
567
|
if (typeof id !== "string" && typeof id !== "number") {
|
|
@@ -565,6 +650,19 @@ export class Connection {
|
|
|
565
650
|
}).catch((writeError) => this.#finish(writeError)); // FM-009
|
|
566
651
|
}
|
|
567
652
|
}
|
|
653
|
+
/** Reject with `error`, first giving it the peer's end cause when the owner reported one. */
|
|
654
|
+
#rejectWithEndCause(reject, error) {
|
|
655
|
+
const endCause = this.#endCause;
|
|
656
|
+
if (endCause === undefined || !(error instanceof Error) || error.cause !== undefined) {
|
|
657
|
+
reject(error);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
void endCause.then((cause) => {
|
|
661
|
+
if (cause !== undefined)
|
|
662
|
+
error.cause = cause;
|
|
663
|
+
reject(error);
|
|
664
|
+
});
|
|
665
|
+
}
|
|
568
666
|
#protocolError(error) {
|
|
569
667
|
this.#protocolErrorHandler?.(error);
|
|
570
668
|
}
|
|
@@ -573,8 +671,9 @@ export class Connection {
|
|
|
573
671
|
return;
|
|
574
672
|
this.#finished = true;
|
|
575
673
|
const error = reason instanceof Error ? reason : new ProtocolError(String(reason));
|
|
674
|
+
this.#endCause = this.#peerEndCause?.();
|
|
576
675
|
for (const pending of this.#pending.values())
|
|
577
|
-
pending.reject
|
|
676
|
+
this.#rejectWithEndCause(pending.reject, error);
|
|
578
677
|
this.#pending.clear();
|
|
579
678
|
this.#resolveClosed?.();
|
|
580
679
|
this.#resolveClosed = undefined;
|
|
@@ -8,7 +8,7 @@ import type { FingerprintWarning } from "../fingerprint.js";
|
|
|
8
8
|
/**
|
|
9
9
|
* What `spawnMspConnection` needs to launch a host: the command to run, plus
|
|
10
10
|
* optional arguments, working directory, environment, connection tuning, a
|
|
11
|
-
* stderr tap,
|
|
11
|
+
* stderr tap, the shutdown drain budget, and a replacement for the spawn call.
|
|
12
12
|
*/
|
|
13
13
|
export interface SpawnMspConnectionOptions {
|
|
14
14
|
readonly command: string;
|
|
@@ -20,6 +20,28 @@ export interface SpawnMspConnectionOptions {
|
|
|
20
20
|
readonly onStderr?: (chunk: string) => void;
|
|
21
21
|
/** See {@link MuseServeChildOptions.shutdownTimeoutMs}. */
|
|
22
22
|
readonly shutdownTimeoutMs?: number;
|
|
23
|
+
/** See {@link MuseServeChildOptions.spawnFn}. */
|
|
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;
|
|
23
45
|
}
|
|
24
46
|
/**
|
|
25
47
|
* How the host process ended: its exit code, or the signal that ended it.
|
|
@@ -75,12 +97,30 @@ export interface MuseServeChildOptions {
|
|
|
75
97
|
*/
|
|
76
98
|
readonly shutdownTimeoutMs?: number;
|
|
77
99
|
/**
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* `windowsHide` override at the call site fails the
|
|
100
|
+
* Replaces `child_process.spawn`, e.g. with an in-memory fake host. It is
|
|
101
|
+
* called once as `spawnFn(museBin, args, options)` with the exact options
|
|
102
|
+
* production passes, so a `windowsHide` override at the call site fails the
|
|
103
|
+
* pin (FR-45141-1).
|
|
104
|
+
*
|
|
105
|
+
* The returned child must provide what the SDK reads from a real one:
|
|
106
|
+
* `stdout` and `stderr` as readable streams, one MSP frame per `stdout`
|
|
107
|
+
* line; `stdin` as a writable stream, which the SDK ends to start shutdown;
|
|
108
|
+
* a `close` event with `(code, signal)` once the host has exited, or an
|
|
109
|
+
* `error` event if it never started; and `kill(signal)`, called with
|
|
110
|
+
* SIGTERM then SIGKILL when the host outlives the drain window. Leave `pid`
|
|
111
|
+
* undefined on an in-memory fake: on POSIX a set `pid` is signalled as a
|
|
112
|
+
* process group (`-pid`), which would reach a real one.
|
|
81
113
|
*/
|
|
82
114
|
readonly spawnFn?: typeof spawn;
|
|
83
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* SIGTERM → SIGKILL grace. Not a knob: by the time it runs the host has
|
|
118
|
+
* already had its whole drain window, so this covers only a signal handler's
|
|
119
|
+
* final flush. Codex's stdio launcher uses the same two seconds. Also bounds
|
|
120
|
+
* how long a call failed by a host death waits for the exit (FR-97948-1).
|
|
121
|
+
* Exported from this module only, never the package barrel.
|
|
122
|
+
*/
|
|
123
|
+
export declare const SIGTERM_GRACE_MS = 2000;
|
|
84
124
|
declare const ownedTransport: unique symbol;
|
|
85
125
|
declare const adoptFlushSource: unique symbol;
|
|
86
126
|
/**
|
|
@@ -90,6 +130,12 @@ declare const adoptFlushSource: unique symbol;
|
|
|
90
130
|
* (#49912) without a new public member on `MspHandshake`.
|
|
91
131
|
*/
|
|
92
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;
|
|
93
139
|
/**
|
|
94
140
|
* Shutdown deadline contract: `expired` resolves and never rejects; after
|
|
95
141
|
* `clear()` it may remain pending forever.
|