@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
|
@@ -36,20 +36,40 @@
|
|
|
36
36
|
* it is forwarded (or explicitly allow-listed as unforwardable).
|
|
37
37
|
*/
|
|
38
38
|
import { discoverMuseBin } from "../connection/discovery.js";
|
|
39
|
-
import { initializeAnswered, spawnMspConnection } from "../connection/spawn.js";
|
|
40
|
-
import {
|
|
39
|
+
import { abortError, initializeAnswered, SIGTERM_GRACE_MS, spawnMspConnection } from "../connection/spawn.js";
|
|
40
|
+
import { SchemaCompatibilityError } from "../fingerprint.js";
|
|
41
|
+
import { MuseFacadeOwnedMethodError, MuseSessionDiscardedError, PermissionProfileNotApplied, } from "../errors.js";
|
|
41
42
|
import { DiscardedSessions } from "./discarded.js";
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
43
|
+
import { fireExtensions } from "../fold/extension.js";
|
|
44
|
+
import { isAbnormalHostDeath, MuseHostDiedError, readSessionDurability } from "./host-death.js";
|
|
45
|
+
import { MspError, peerEndCause, ProtocolError } from "../connection/connection.js";
|
|
44
46
|
import { hostStartFailure } from "./host-start.js";
|
|
45
|
-
import { pumpDropsApplyResults, Session } from "./session.js";
|
|
47
|
+
import { endEventStreams, followsSubagents, forwardedConfig, forwardsEvents, grantedCapabilities, pumpDropsApplyResults, resumeResultOf, serverRequestFrame, Session, } from "./session.js";
|
|
48
|
+
/**
|
|
49
|
+
* Run a caller's observer so neither its throw nor an async observer's
|
|
50
|
+
* rejection escapes: in the read loop a throw ends the connection every session
|
|
51
|
+
* shares, and an unhandled rejection kills the embedder.
|
|
52
|
+
*/
|
|
53
|
+
function observe(call, onFailure) {
|
|
54
|
+
let result;
|
|
55
|
+
try {
|
|
56
|
+
result = call();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
onFailure(error);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (typeof result?.then === "function") {
|
|
63
|
+
result.then(undefined, onFailure);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
46
66
|
/**
|
|
47
67
|
* Every `StartParams` member `startSession` forwards. `config` is forwarded
|
|
48
68
|
* only behind the `sessionMcp` grant check (`#forwardConfig`),
|
|
49
|
-
* `previousSessionId`
|
|
50
|
-
* (the predecessor link
|
|
51
|
-
* the `switchPolicy` member), and `spawnedBy`
|
|
52
|
-
* expose a spawner yet.
|
|
69
|
+
* `previousSessionId` and `clear` are excluded because the facade starts root
|
|
70
|
+
* sessions (the predecessor link and the `/clear` marker belong to a client
|
|
71
|
+
* that switches sessions, as does the `switchPolicy` member), and `spawnedBy`
|
|
72
|
+
* because the facade does not expose a spawner yet.
|
|
53
73
|
*/
|
|
54
74
|
const START_FORWARDED = [
|
|
55
75
|
"approvalMode",
|
|
@@ -100,9 +120,25 @@ const FACADE_OWNED_METHODS = [
|
|
|
100
120
|
"view/subscribe",
|
|
101
121
|
"view/unsubscribe",
|
|
102
122
|
];
|
|
123
|
+
/**
|
|
124
|
+
* The stable facade-owned methods, and only those. The experimental host
|
|
125
|
+
* stop (`host/shutdown`) is the orderly stop `close()` owns too, and the
|
|
126
|
+
* Python twin refuses it, but this package names no experimental-only
|
|
127
|
+
* method: FR-97527-5's leak gate derives that set from the two schema
|
|
128
|
+
* bundles at check time, and a refusal list counts as naming (#99842). A
|
|
129
|
+
* caller that sends it raw owns the host exit that follows.
|
|
130
|
+
*/
|
|
103
131
|
const FACADE_OWNED = new Set(FACADE_OWNED_METHODS);
|
|
132
|
+
// Every facade-owned method is a stable method, so the untyped fallback
|
|
133
|
+
// (`UnlistedMethod<MethodName, M>`) refuses it too.
|
|
104
134
|
/** Every `SessionListParams` member `listSessions` forwards. */
|
|
105
135
|
const LIST_FORWARDED = ["cursor", "filter", "limit", "updatedAfter", "workspaceRoot"];
|
|
136
|
+
/** The turn a view frame belongs to: its own `turnId`, else its item's. */
|
|
137
|
+
function turnIdOf(frame) {
|
|
138
|
+
const params = frame.params;
|
|
139
|
+
const turnId = params?.turnId ?? params?.item?.turnId;
|
|
140
|
+
return typeof turnId === "string" ? turnId : undefined;
|
|
141
|
+
}
|
|
106
142
|
/**
|
|
107
143
|
* The caller's capability posture with `sessionMcp` added to its requests,
|
|
108
144
|
* each requested name once (ADR 32760 D3: the facade requests the grant its
|
|
@@ -141,8 +177,27 @@ export class MuseClient {
|
|
|
141
177
|
#connection;
|
|
142
178
|
#durability;
|
|
143
179
|
#discarded;
|
|
180
|
+
#extensions;
|
|
144
181
|
/** Sessions this client opened, so one death notification reaches them all. */
|
|
145
182
|
#sessions = new Set();
|
|
183
|
+
/** `onNotification` subscriptions, one entry each so a function added twice unsubscribes once per call. */
|
|
184
|
+
#listeners = new Set();
|
|
185
|
+
#notificationFailureHandlers = new Set();
|
|
186
|
+
#protocolErrorHandlers = new Set();
|
|
187
|
+
/**
|
|
188
|
+
* Set on the first `onProtocolError`, which then claims the connection's one
|
|
189
|
+
* handler: a client nobody observes leaves the caller's own handler alone.
|
|
190
|
+
*/
|
|
191
|
+
#protocolErrorsClaimed = false;
|
|
192
|
+
/**
|
|
193
|
+
* `#sessions` indexed by session id, so routing a frame is one lookup
|
|
194
|
+
* whatever the number of followed sub-agents (Constitution XIV).
|
|
195
|
+
*/
|
|
196
|
+
#sessionsById = new Map();
|
|
197
|
+
/** The internal sessions that fold a followed sub-agent's events (`events({ subagents: true })`). */
|
|
198
|
+
#followers = new WeakSet();
|
|
199
|
+
/** `session/resume` calls in flight, counted per session id, so a follow's unsubscribe never starves one. */
|
|
200
|
+
#resuming = new Map();
|
|
146
201
|
/**
|
|
147
202
|
* Frames naming a session this client has not registered YET, held only
|
|
148
203
|
* while a `session/start`/`session/resume` is in flight (#49790): the host
|
|
@@ -172,6 +227,7 @@ export class MuseClient {
|
|
|
172
227
|
// no current consumer spans two clients over one host lineage, so a
|
|
173
228
|
// sharing knob would be declared-ahead surface (Constitution XI).
|
|
174
229
|
this.#discarded = new DiscardedSessions();
|
|
230
|
+
this.#extensions = options.extensions ?? [];
|
|
175
231
|
this.#child = options.host?.child;
|
|
176
232
|
this.#initializeResult = options.host?.initializeResult;
|
|
177
233
|
// THE ONE INBOUND PUMP (FR-018/FR-019). `Session.apply` is the only event
|
|
@@ -179,9 +235,14 @@ export class MuseClient {
|
|
|
179
235
|
// consumer has no way to hear a single view frame: every turn wait hangs
|
|
180
236
|
// (SS3.1.4) and `onApproval` can never fire. `Connection.onNotification`
|
|
181
237
|
// holds ONE handler — this client claims it, which is part of what
|
|
182
|
-
// "MuseClient owns the connection" means; a
|
|
183
|
-
//
|
|
184
|
-
|
|
238
|
+
// "MuseClient owns the connection" means; a caller hears the feed through
|
|
239
|
+
// `onNotification`, after `#route` has handed each frame to its session
|
|
240
|
+
// (a frame held while that session's open is in flight is heard first).
|
|
241
|
+
this.#connection.onNotification((notification) => {
|
|
242
|
+
this.#route(notification);
|
|
243
|
+
for (const entry of [...this.#listeners])
|
|
244
|
+
this.#notify(entry.listener, notification);
|
|
245
|
+
});
|
|
185
246
|
// A question or approval still open at resume is re-sent as a
|
|
186
247
|
// `userInput/request` or `approval/request` server request (tdd SS5.6,
|
|
187
248
|
// SS5.10). Each is routed in arrival order and answered with the SS5.3.3
|
|
@@ -193,11 +254,11 @@ export class MuseClient {
|
|
|
193
254
|
// `-32601` a bare `Connection` answers.
|
|
194
255
|
this.#connection.onServerRequest(async (request) => {
|
|
195
256
|
if (request.method === "userInput/request") {
|
|
196
|
-
this.#route({ method: "userInput/requested", params: request.params });
|
|
257
|
+
this.#route(serverRequestFrame({ method: "userInput/requested", params: request.params }));
|
|
197
258
|
return {};
|
|
198
259
|
}
|
|
199
260
|
if (request.method === "approval/request") {
|
|
200
|
-
this.#route({ method: request.method, params: request.params });
|
|
261
|
+
this.#route(serverRequestFrame({ method: request.method, params: request.params }));
|
|
201
262
|
return {};
|
|
202
263
|
}
|
|
203
264
|
throw new MspError({
|
|
@@ -209,29 +270,39 @@ export class MuseClient {
|
|
|
209
270
|
// Registered at construction, not at the first session: an EOF can land
|
|
210
271
|
// before any session exists, and the flag has to be read at that moment.
|
|
211
272
|
void this.#connection.closed.then(() => this.#transportClosed());
|
|
273
|
+
// A call the connection fails because the host died says how it ended;
|
|
274
|
+
// read at the EOF, so a close() of ours leaves the bare error.
|
|
275
|
+
this.#connection[peerEndCause](() => this.#hostDeathCause());
|
|
212
276
|
}
|
|
213
277
|
/**
|
|
214
278
|
* Deliver one view notification to the session(s) it names.
|
|
215
279
|
*
|
|
216
|
-
* A frame naming NO session
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
280
|
+
* A frame naming NO session goes to the connection extensions (FR-97527-3:
|
|
281
|
+
* host-wide state names no session) rather than to every session:
|
|
282
|
+
* `Session.apply` already tolerates unknown methods, but only the
|
|
283
|
+
* frames that name a `sessionId` have a session owner to route to. A frame
|
|
284
|
+
* naming an UNKNOWN session is dropped for the same reason — routing it
|
|
285
|
+
* anywhere would trip the foreign-frame throw on a session it does not
|
|
286
|
+
* belong to — UNLESS an open is in flight, when it may be that open's own
|
|
287
|
+
* session named by the server before the awaiting promise has run (#49790):
|
|
288
|
+
* then it is held for `#openSession` to fold, or for `#open` to clear.
|
|
224
289
|
*/
|
|
225
290
|
#route(notification) {
|
|
226
291
|
const named = notification.params?.sessionId;
|
|
227
|
-
if (typeof named !== "string")
|
|
292
|
+
if (typeof named !== "string") {
|
|
293
|
+
// FR-97527-3: connection extensions share the fold's call-and-report
|
|
294
|
+
// loop, objects-only guard included.
|
|
295
|
+
fireExtensions(this.#extensions, notification.method, notification.params);
|
|
228
296
|
return;
|
|
297
|
+
}
|
|
229
298
|
let delivered = false;
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
299
|
+
// A copy: applying a frame can follow or stop a sub-agent, which edits the index.
|
|
300
|
+
for (const session of [...(this.#sessionsById.get(named) ?? [])]) {
|
|
301
|
+
session.apply(notification);
|
|
302
|
+
// A sub-agent follow's internal session never counts: a caller's open
|
|
303
|
+
// of that id must still hold the frames read with its reply.
|
|
304
|
+
if (!this.#followers.has(session))
|
|
233
305
|
delivered = true;
|
|
234
|
-
}
|
|
235
306
|
}
|
|
236
307
|
if (delivered || this.#opening === 0)
|
|
237
308
|
return;
|
|
@@ -241,6 +312,16 @@ export class MuseClient {
|
|
|
241
312
|
else
|
|
242
313
|
held.push(notification);
|
|
243
314
|
}
|
|
315
|
+
/** Call one listener, sending its throw or rejection to every `onNotificationError` handler. */
|
|
316
|
+
#notify(listener, notification) {
|
|
317
|
+
observe(() => listener(notification), (error) => {
|
|
318
|
+
// A failure observer failing too is swallowed: like
|
|
319
|
+
// `ApprovalRouter.#report`, there is no one left to tell.
|
|
320
|
+
for (const entry of [...this.#notificationFailureHandlers]) {
|
|
321
|
+
observe(() => entry.handler(error, notification), () => undefined);
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
}
|
|
244
325
|
/**
|
|
245
326
|
* Spawn an owned host, run the SS1.4 handshake, and hand back a client whose
|
|
246
327
|
* durability profile came from that handshake (FR-018).
|
|
@@ -253,6 +334,9 @@ export class MuseClient {
|
|
|
253
334
|
* Rejects with {@link MuseHostDiscoveryError} before starting anything when
|
|
254
335
|
* `museBin` is omitted and no executable `muse` is on `PATH`.
|
|
255
336
|
*
|
|
337
|
+
* Rejects with an `AbortError` (`cause`: `signal.reason`) when `signal`
|
|
338
|
+
* aborts before the handshake completes, once the host has exited.
|
|
339
|
+
*
|
|
256
340
|
* Rejects with {@link MuseHostStartError} when the host is lost before the
|
|
257
341
|
* handshake completes (the binary could not be spawned, or the process
|
|
258
342
|
* ended first — exit code or signal plus the bounded stderr tail;
|
|
@@ -260,9 +344,15 @@ export class MuseClient {
|
|
|
260
344
|
* that answers with a reply the SDK refuses keeps its own error: an
|
|
261
345
|
* `MspError` for an SS1.6 refusal, or a `ProtocolError` (with the whole
|
|
262
346
|
* refused frame on `line`) for a reply the SDK cannot use, such as one with
|
|
263
|
-
* no schema fingerprint.
|
|
347
|
+
* no schema fingerprint. With `refuseDeclaredBreakingSchema`, a host whose
|
|
348
|
+
* schema identity is a declared non-additive advance from this SDK's pin
|
|
349
|
+
* is refused with a `SchemaCompatibilityError` (ADR 22936 D3), the host
|
|
350
|
+
* closed.
|
|
264
351
|
*/
|
|
265
352
|
static async spawn(options) {
|
|
353
|
+
// A cancelled spawn does nothing at all, host discovery included (as Node).
|
|
354
|
+
if (options.signal?.aborted)
|
|
355
|
+
throw abortError(options.signal.reason);
|
|
266
356
|
// The process's own PATH, never `options.env`'s: the host is found the
|
|
267
357
|
// way the Rust and Python SDKs find it, whatever environment it gets.
|
|
268
358
|
const command = await discoverMuseBin(options.museBin, process.env["PATH"], process.platform);
|
|
@@ -275,6 +365,11 @@ export class MuseClient {
|
|
|
275
365
|
...(options.shutdownTimeoutMs === undefined
|
|
276
366
|
? {}
|
|
277
367
|
: { shutdownTimeoutMs: options.shutdownTimeoutMs }),
|
|
368
|
+
...(options.spawnFn === undefined ? {} : { spawnFn: options.spawnFn }),
|
|
369
|
+
...(options.refuseDeclaredBreakingSchema === undefined
|
|
370
|
+
? {}
|
|
371
|
+
: { refuseDeclaredBreakingSchema: options.refuseDeclaredBreakingSchema }),
|
|
372
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
278
373
|
});
|
|
279
374
|
let spawned;
|
|
280
375
|
try {
|
|
@@ -286,6 +381,10 @@ export class MuseClient {
|
|
|
286
381
|
catch (error) {
|
|
287
382
|
// A failed handshake must not leak the process it already spawned.
|
|
288
383
|
await handshake.close().catch(() => undefined);
|
|
384
|
+
// The caller's abort stays the caller's, never a lost host.
|
|
385
|
+
if (options.signal !== undefined && error instanceof Error && error.name === "AbortError") {
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
289
388
|
// A host that ANSWERED `initialize` is not a lost host, however it ends
|
|
290
389
|
// once we close it: its answer is the actionable error. "Answered" is
|
|
291
390
|
// evidence that a response frame came back — an SS1.6 `MspError`, or a
|
|
@@ -293,7 +392,12 @@ export class MuseClient {
|
|
|
293
392
|
// version-skewed reply) — never the error's class alone (#49912).
|
|
294
393
|
// Decided before the exit is read, so our own close ladder can never
|
|
295
394
|
// dress an answer up as a death.
|
|
296
|
-
|
|
395
|
+
// The SDK's own connect-time refusal of an answered identity (ADR 22936
|
|
396
|
+
// D3, `refuseDeclaredBreakingSchema`) is an answer too: the host served
|
|
397
|
+
// a usable result and the SDK declined it, so the refusal is the error.
|
|
398
|
+
const answered = error instanceof MspError ||
|
|
399
|
+
error instanceof SchemaCompatibilityError ||
|
|
400
|
+
(error instanceof ProtocolError && error.line !== undefined);
|
|
297
401
|
if (answered)
|
|
298
402
|
throw error;
|
|
299
403
|
// No refused frame: the host was lost — before answering, or after a
|
|
@@ -306,6 +410,7 @@ export class MuseClient {
|
|
|
306
410
|
}
|
|
307
411
|
return new MuseClient(spawned.connection, {
|
|
308
412
|
durability: readSessionDurability(spawned.initializeResult),
|
|
413
|
+
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
|
309
414
|
host: spawned,
|
|
310
415
|
});
|
|
311
416
|
}
|
|
@@ -332,6 +437,72 @@ export class MuseClient {
|
|
|
332
437
|
}
|
|
333
438
|
return this.#child.exit;
|
|
334
439
|
}
|
|
440
|
+
/**
|
|
441
|
+
* Settles when the connection closes for any reason: `close()`, the host
|
|
442
|
+
* hanging up, or a transport failure.
|
|
443
|
+
*/
|
|
444
|
+
get closed() {
|
|
445
|
+
return this.#connection.closed;
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Hear every server notification in wire order, including those naming no
|
|
449
|
+
* session (`usage/changed`, `account/loginCompleted`) or a session this
|
|
450
|
+
* client did not open. A frame naming a session this client has opened
|
|
451
|
+
* reaches the listener after that session has applied it: folded, or, while
|
|
452
|
+
* the session fills a gap, buffered and folded when the fill completes. One
|
|
453
|
+
* that arrives while its session's start/resume is still in flight reaches
|
|
454
|
+
* the listener first, and the session folds it before the verb returns.
|
|
455
|
+
* Returns the unsubscribe function.
|
|
456
|
+
*
|
|
457
|
+
* The frame is read-only: it is the one the session folds, which for a held
|
|
458
|
+
* or buffered frame happens after the listener runs. Like a `Connection`
|
|
459
|
+
* handler, the listener runs in the read loop, so it must not block. A throw, or an async listener's rejection, goes to every
|
|
460
|
+
* `onNotificationError` handler; the other listeners still hear the frame
|
|
461
|
+
* and the connection stays open.
|
|
462
|
+
*/
|
|
463
|
+
onNotification(listener) {
|
|
464
|
+
const entry = { listener };
|
|
465
|
+
this.#listeners.add(entry);
|
|
466
|
+
return () => {
|
|
467
|
+
this.#listeners.delete(entry);
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Hear what an `onNotification` listener threw or rejected with. With no
|
|
472
|
+
* handler the failure is dropped; either way the pump keeps running.
|
|
473
|
+
* Returns a function that removes this one subscription.
|
|
474
|
+
*/
|
|
475
|
+
onNotificationError(handler) {
|
|
476
|
+
const entry = { handler };
|
|
477
|
+
this.#notificationFailureHandlers.add(entry);
|
|
478
|
+
return () => {
|
|
479
|
+
this.#notificationFailureHandlers.delete(entry);
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Hear each framing or correlation violation the connection detects
|
|
484
|
+
* (`Connection.onProtocolError`). The handler's own throw or rejection is
|
|
485
|
+
* swallowed rather than ending the connection; it is already the observer
|
|
486
|
+
* of failures, so there is no one left to tell. The first call takes over
|
|
487
|
+
* `Connection.onProtocolError`, replacing a handler set there directly (and
|
|
488
|
+
* a later direct `connection.onProtocolError(...)` silences these
|
|
489
|
+
* subscribers). Returns a function that removes this one subscription.
|
|
490
|
+
*/
|
|
491
|
+
onProtocolError(handler) {
|
|
492
|
+
if (!this.#protocolErrorsClaimed) {
|
|
493
|
+
this.#protocolErrorsClaimed = true;
|
|
494
|
+
this.#connection.onProtocolError((error) => {
|
|
495
|
+
for (const entry of [...this.#protocolErrorHandlers]) {
|
|
496
|
+
observe(() => entry.handler(error), () => undefined);
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
const entry = { handler };
|
|
501
|
+
this.#protocolErrorHandlers.add(entry);
|
|
502
|
+
return () => {
|
|
503
|
+
this.#protocolErrorHandlers.delete(entry);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
335
506
|
/** The durability profile every session this client opens inherits. */
|
|
336
507
|
get durability() {
|
|
337
508
|
return this.#durability;
|
|
@@ -386,7 +557,9 @@ export class MuseClient {
|
|
|
386
557
|
* (no orphan keeps folding for an id the caller can never reach — the SDK
|
|
387
558
|
* has no set/close-by-id verb); the error's `sessionId` is the caller's
|
|
388
559
|
* handle to resume via `sessionId` or start again. A failed read-back
|
|
389
|
-
* propagates: the client still never proceeds on the default.
|
|
560
|
+
* propagates: the client still never proceeds on the default. The read-back
|
|
561
|
+
* rides `request()`: `SessionReadParams` define no `commandId`, so it mints
|
|
562
|
+
* none and is not retried as a command.
|
|
390
563
|
*/
|
|
391
564
|
async #proveSelection(session, requested) {
|
|
392
565
|
const opening = session.opening;
|
|
@@ -396,16 +569,16 @@ export class MuseClient {
|
|
|
396
569
|
if (started !== null) {
|
|
397
570
|
if (started === requested)
|
|
398
571
|
return session;
|
|
399
|
-
this.#
|
|
572
|
+
this.#untrack(session);
|
|
400
573
|
throw new PermissionProfileNotApplied(requested, started, session.sessionId);
|
|
401
574
|
}
|
|
402
|
-
const read = await this.#connection.
|
|
575
|
+
const read = await this.#connection.request("session/read", {
|
|
403
576
|
sessionId: session.sessionId,
|
|
404
577
|
});
|
|
405
578
|
const served = committedProfileId(read["session"]);
|
|
406
579
|
if (served === requested)
|
|
407
580
|
return session;
|
|
408
|
-
this.#
|
|
581
|
+
this.#untrack(session);
|
|
409
582
|
throw new PermissionProfileNotApplied(requested, served, session.sessionId);
|
|
410
583
|
}
|
|
411
584
|
/**
|
|
@@ -435,7 +608,7 @@ export class MuseClient {
|
|
|
435
608
|
if (options.config != null)
|
|
436
609
|
params.config = this.#forwardConfig("session/resume", options.config);
|
|
437
610
|
return this.#open("session/resume", params, (raw) => ({
|
|
438
|
-
result: raw,
|
|
611
|
+
result: resumeResultOf(raw),
|
|
439
612
|
verb: "session/resume",
|
|
440
613
|
}), { onApproval: options.onApproval, onApprovalError: options.onApprovalError });
|
|
441
614
|
}
|
|
@@ -445,17 +618,14 @@ export class MuseClient {
|
|
|
445
618
|
* (see `Session.listTasks`).
|
|
446
619
|
*/
|
|
447
620
|
async listSessions(options = {}) {
|
|
621
|
+
// One list drives both the exhaustiveness pin and the forwarding, so a
|
|
622
|
+
// regenerated member cannot compile yet be dropped on the wire (#76737).
|
|
448
623
|
const params = {};
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
params["limit"] = options.limit;
|
|
455
|
-
if (options.updatedAfter != null)
|
|
456
|
-
params["updatedAfter"] = options.updatedAfter;
|
|
457
|
-
if (options.workspaceRoot != null)
|
|
458
|
-
params["workspaceRoot"] = options.workspaceRoot;
|
|
624
|
+
for (const member of LIST_FORWARDED) {
|
|
625
|
+
const value = options[member];
|
|
626
|
+
if (value != null)
|
|
627
|
+
params[member] = value;
|
|
628
|
+
}
|
|
459
629
|
const ack = await this.#connection.request("session/list", params);
|
|
460
630
|
return ack;
|
|
461
631
|
}
|
|
@@ -479,29 +649,17 @@ export class MuseClient {
|
|
|
479
649
|
const ack = await this.#connection.request("usage/read");
|
|
480
650
|
return ack;
|
|
481
651
|
}
|
|
482
|
-
/**
|
|
483
|
-
* Send a wire method directly (FR-79107-2), typically one the facade does
|
|
484
|
-
* not wrap, through the
|
|
485
|
-
* same `Connection.command()` the verbs use: the connection mints the
|
|
486
|
-
* `commandId`, retries a nothing-admitted refusal under the same id, and
|
|
487
|
-
* checks the ack's echo. `options` are that seam's own.
|
|
488
|
-
*
|
|
489
|
-
* Refused before anything is written, with `MuseFacadeOwnedMethodError`:
|
|
490
|
-
* the methods whose state the facade owns (`FACADE_OWNED_METHODS`). Frames
|
|
491
|
-
* the command causes still reach your sessions through the client's one
|
|
492
|
-
* inbound pump; this sends and returns the ack, nothing more. Params and
|
|
493
|
-
* ack stay untyped objects: the generated types carry no method-to-params
|
|
494
|
-
* map, and restating one here would drift from the schema.
|
|
495
|
-
*
|
|
496
|
-
* Each call keeps one fixed-size fingerprint for the connection's lifetime
|
|
497
|
-
* (FR-45137-1), so prefer a facade verb for a query you poll.
|
|
498
|
-
*/
|
|
499
652
|
async command(method, params, options) {
|
|
500
653
|
// The type binds TypeScript callers; this binds plain-JS ones.
|
|
501
654
|
if (FACADE_OWNED.has(method))
|
|
502
655
|
throw new MuseFacadeOwnedMethodError(method);
|
|
503
656
|
return this.#connection.command(method, params, options);
|
|
504
657
|
}
|
|
658
|
+
async request(method, ...params) {
|
|
659
|
+
if (FACADE_OWNED.has(method))
|
|
660
|
+
throw new MuseFacadeOwnedMethodError(method);
|
|
661
|
+
return this.#connection.request(method, params[0]);
|
|
662
|
+
}
|
|
505
663
|
/**
|
|
506
664
|
* Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
|
|
507
665
|
* is not reported to your sessions as a host death.
|
|
@@ -519,15 +677,22 @@ export class MuseClient {
|
|
|
519
677
|
*/
|
|
520
678
|
async close() {
|
|
521
679
|
this.#closing = true;
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
session
|
|
680
|
+
try {
|
|
681
|
+
if (this.#child !== undefined) {
|
|
682
|
+
const exit = await this.#child.close();
|
|
683
|
+
if (isAbnormalHostDeath(exit)) {
|
|
684
|
+
for (const session of this.#sessions)
|
|
685
|
+
session.hostExited(exit);
|
|
686
|
+
}
|
|
687
|
+
return;
|
|
527
688
|
}
|
|
528
|
-
|
|
689
|
+
await this.#connection.close();
|
|
690
|
+
}
|
|
691
|
+
finally {
|
|
692
|
+
// An orderly exit reports no death, so nothing else ends the streams.
|
|
693
|
+
for (const session of this.#sessions)
|
|
694
|
+
session[endEventStreams]();
|
|
529
695
|
}
|
|
530
|
-
await this.#connection.close();
|
|
531
696
|
}
|
|
532
697
|
/**
|
|
533
698
|
* The window `#route` holds unknown-session frames for: from the request to
|
|
@@ -538,6 +703,9 @@ export class MuseClient {
|
|
|
538
703
|
*/
|
|
539
704
|
async #open(verb, params, opening, approvals = {}) {
|
|
540
705
|
this.#opening += 1;
|
|
706
|
+
const resumed = verb === "session/resume" ? params.sessionId : undefined;
|
|
707
|
+
if (resumed !== undefined)
|
|
708
|
+
this.#resuming.set(resumed, (this.#resuming.get(resumed) ?? 0) + 1);
|
|
541
709
|
try {
|
|
542
710
|
const opened = opening(await this.#connection.command(verb, params));
|
|
543
711
|
return this.#openSession(opened.result.session.sessionId, opened, approvals);
|
|
@@ -546,6 +714,13 @@ export class MuseClient {
|
|
|
546
714
|
this.#opening -= 1;
|
|
547
715
|
if (this.#opening === 0)
|
|
548
716
|
this.#held.clear();
|
|
717
|
+
if (resumed !== undefined) {
|
|
718
|
+
const left = (this.#resuming.get(resumed) ?? 1) - 1;
|
|
719
|
+
if (left > 0)
|
|
720
|
+
this.#resuming.set(resumed, left);
|
|
721
|
+
else
|
|
722
|
+
this.#resuming.delete(resumed);
|
|
723
|
+
}
|
|
549
724
|
}
|
|
550
725
|
}
|
|
551
726
|
#openSession(sessionId, opening, approvals) {
|
|
@@ -553,6 +728,7 @@ export class MuseClient {
|
|
|
553
728
|
connection: this.#connection,
|
|
554
729
|
discarded: this.#discarded,
|
|
555
730
|
durability: this.#durability,
|
|
731
|
+
extensions: this.#extensions,
|
|
556
732
|
opening,
|
|
557
733
|
sessionId,
|
|
558
734
|
});
|
|
@@ -562,9 +738,13 @@ export class MuseClient {
|
|
|
562
738
|
session.onApprovalError(approvals.onApprovalError);
|
|
563
739
|
if (approvals.onApproval !== undefined)
|
|
564
740
|
session.onApproval(approvals.onApproval);
|
|
741
|
+
// `reload()`'s config is checked against the same grants as the open verbs'.
|
|
742
|
+
if (this.#initializeResult !== undefined)
|
|
743
|
+
session[grantedCapabilities](this.#initializeResult.grantedCapabilities);
|
|
565
744
|
// `#route` drops what `apply` returns (FR-81734-1).
|
|
566
745
|
session[pumpDropsApplyResults]();
|
|
567
|
-
this.#
|
|
746
|
+
session[followsSubagents]((child, forward, onStopped) => this.#followSubagent(child, forward, onStopped));
|
|
747
|
+
this.#track(session);
|
|
568
748
|
// The frames that named this session while its verb was in flight fold
|
|
569
749
|
// NOW, in arrival order — synchronously, so nothing the pump routes next
|
|
570
750
|
// can overtake them.
|
|
@@ -576,6 +756,112 @@ export class MuseClient {
|
|
|
576
756
|
}
|
|
577
757
|
return session;
|
|
578
758
|
}
|
|
759
|
+
/**
|
|
760
|
+
* Follow a sub-agent's session for `events({ subagents: true })`:
|
|
761
|
+
* an internal session folds its events and hands each to `forward`, routed
|
|
762
|
+
* like any session's from the subscribe on. Its approvals are not its own:
|
|
763
|
+
* the host presents them on the parent (`subagentOrigin`) and takes the
|
|
764
|
+
* decision there, so this session answers none. Returns how to stop.
|
|
765
|
+
*/
|
|
766
|
+
#followSubagent(childSessionId, forward, onStopped) {
|
|
767
|
+
const child = new Session({
|
|
768
|
+
connection: this.#connection,
|
|
769
|
+
discarded: this.#discarded,
|
|
770
|
+
durability: this.#durability,
|
|
771
|
+
extensions: this.#extensions,
|
|
772
|
+
sessionId: childSessionId,
|
|
773
|
+
});
|
|
774
|
+
child[pumpDropsApplyResults]();
|
|
775
|
+
// Cleared first on stop: a gap fill still in flight on the child must not
|
|
776
|
+
// yield its frames after the follow ended.
|
|
777
|
+
let live = true;
|
|
778
|
+
let finishing = false;
|
|
779
|
+
// Turns this follow saw a frame of and the child fold has not ended: the
|
|
780
|
+
// subscribe replays nothing, so a turn already running when it landed has
|
|
781
|
+
// no turn/started here, and the fold's own activeTurnId cannot know it.
|
|
782
|
+
const runningTurns = new Set();
|
|
783
|
+
// An item/delta names no turn: a follow that joined mid-message sees only
|
|
784
|
+
// deltas until the message completes, so the child counts as busy until
|
|
785
|
+
// a turn ends.
|
|
786
|
+
let busy = false;
|
|
787
|
+
const running = () => busy || runningTurns.size > 0;
|
|
788
|
+
child[forwardsEvents]((event) => {
|
|
789
|
+
if (!live)
|
|
790
|
+
return;
|
|
791
|
+
forward(event);
|
|
792
|
+
const turnId = turnIdOf(event.frame);
|
|
793
|
+
if (turnId !== undefined) {
|
|
794
|
+
const state = child.fold.turn(turnId)?.state;
|
|
795
|
+
if (state === undefined || state === "running")
|
|
796
|
+
runningTurns.add(turnId);
|
|
797
|
+
else {
|
|
798
|
+
runningTurns.delete(turnId);
|
|
799
|
+
busy = false;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
else if (event.frame.method === "item/delta")
|
|
803
|
+
busy = true;
|
|
804
|
+
if (finishing && !running())
|
|
805
|
+
stop();
|
|
806
|
+
});
|
|
807
|
+
// The subscription is per connection: a second subscribe would replace one
|
|
808
|
+
// a session already routed here holds (or a resume in flight is taking)
|
|
809
|
+
// with an empty one at head, losing the frames queued for it. Ride it.
|
|
810
|
+
const held = this.#resuming.has(childSessionId) || this.#sessionsById.has(childSessionId);
|
|
811
|
+
this.#followers.add(child);
|
|
812
|
+
this.#track(child);
|
|
813
|
+
// Any refusal follows nothing and is not reported: usually a child that
|
|
814
|
+
// already finished, whose item/completed follows.
|
|
815
|
+
const subscribed = held
|
|
816
|
+
? Promise.resolve(true)
|
|
817
|
+
: this.#connection.request("view/subscribe", { sessionId: childSessionId }).then(() => true, () => {
|
|
818
|
+
this.#untrack(child);
|
|
819
|
+
return false;
|
|
820
|
+
});
|
|
821
|
+
const stop = () => {
|
|
822
|
+
if (!live)
|
|
823
|
+
return;
|
|
824
|
+
live = false;
|
|
825
|
+
this.#untrack(child);
|
|
826
|
+
onStopped();
|
|
827
|
+
void subscribed.then(async (accepted) => {
|
|
828
|
+
// Not while a session the caller opened routes that id, or a resume of
|
|
829
|
+
// it is in flight: the subscription is per connection, and dropping it
|
|
830
|
+
// would starve that session.
|
|
831
|
+
if (!accepted || this.#resuming.has(childSessionId) || this.#sessionsById.has(childSessionId))
|
|
832
|
+
return;
|
|
833
|
+
await this.#connection.request("view/unsubscribe", { sessionId: childSessionId }).catch(() => undefined);
|
|
834
|
+
});
|
|
835
|
+
};
|
|
836
|
+
return {
|
|
837
|
+
stop,
|
|
838
|
+
finish: () => {
|
|
839
|
+
if (running())
|
|
840
|
+
finishing = true;
|
|
841
|
+
else
|
|
842
|
+
stop();
|
|
843
|
+
},
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
/** Add a session to the routing set and its id index. */
|
|
847
|
+
#track(session) {
|
|
848
|
+
this.#sessions.add(session);
|
|
849
|
+
const held = this.#sessionsById.get(session.sessionId);
|
|
850
|
+
if (held === undefined)
|
|
851
|
+
this.#sessionsById.set(session.sessionId, new Set([session]));
|
|
852
|
+
else
|
|
853
|
+
held.add(session);
|
|
854
|
+
}
|
|
855
|
+
/** Remove a session from the routing set and its id index. */
|
|
856
|
+
#untrack(session) {
|
|
857
|
+
this.#sessions.delete(session);
|
|
858
|
+
const held = this.#sessionsById.get(session.sessionId);
|
|
859
|
+
if (held === undefined)
|
|
860
|
+
return;
|
|
861
|
+
held.delete(session);
|
|
862
|
+
if (held.size === 0)
|
|
863
|
+
this.#sessionsById.delete(session.sessionId);
|
|
864
|
+
}
|
|
579
865
|
/**
|
|
580
866
|
* The `config` to forward, or a typed refusal before anything is sent
|
|
581
867
|
* (FR-79107-3). Per-session MCP servers need the `sessionMcp` grant in the
|
|
@@ -584,11 +870,7 @@ export class MuseClient {
|
|
|
584
870
|
* it. A config naming no server needs no grant, as on the host (ADR 32760 D3).
|
|
585
871
|
*/
|
|
586
872
|
#forwardConfig(method, config) {
|
|
587
|
-
|
|
588
|
-
return config;
|
|
589
|
-
if (this.#initializeResult?.grantedCapabilities.includes("sessionMcp") === true)
|
|
590
|
-
return config;
|
|
591
|
-
throw new MuseCapabilityNotGrantedError("sessionMcp", method, "config.mcpServers needs the sessionMcp grant, which this connection's handshake does not hold (MuseClient.spawn requests it; a host withholds it when per-session MCP is turned off)");
|
|
873
|
+
return forwardedConfig(method, config, this.#initializeResult?.grantedCapabilities);
|
|
592
874
|
}
|
|
593
875
|
#assertReattachAllowed(sessionId) {
|
|
594
876
|
// Two facts, both recorded by an ephemeral discharge: THIS session was
|
|
@@ -604,6 +886,20 @@ export class MuseClient {
|
|
|
604
886
|
#survivesHostDeath() {
|
|
605
887
|
return this.#durability.kind === "durable";
|
|
606
888
|
}
|
|
889
|
+
/**
|
|
890
|
+
* Waits for the exit at most `SIGTERM_GRACE_MS`: a host that closed stdout
|
|
891
|
+
* but keeps running must not hold the failed calls past today's bare error.
|
|
892
|
+
*/
|
|
893
|
+
#hostDeathCause() {
|
|
894
|
+
if (this.#closing || this.#child === undefined)
|
|
895
|
+
return undefined;
|
|
896
|
+
const died = this.#child.exit.then((exit) => (isAbnormalHostDeath(exit) ? new MuseHostDiedError(exit) : undefined), () => undefined);
|
|
897
|
+
let timer;
|
|
898
|
+
const grace = new Promise((resolve) => {
|
|
899
|
+
timer = setTimeout(resolve, SIGTERM_GRACE_MS, undefined);
|
|
900
|
+
});
|
|
901
|
+
return Promise.race([died, grace]).finally(() => clearTimeout(timer));
|
|
902
|
+
}
|
|
607
903
|
/**
|
|
608
904
|
* The transport reached EOF. If this client did not cause it, that is
|
|
609
905
|
* SS2.13.3b's second death notification (T030 obligation b) and every session
|