@muse-code/sdk 1.4.20 → 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 +54 -5
- package/dist/src/connection/connection.d.ts +67 -7
- package/dist/src/connection/connection.js +68 -11
- package/dist/src/connection/spawn.d.ts +26 -0
- package/dist/src/connection/spawn.js +156 -31
- package/dist/src/connection/surface.d.ts +49 -0
- package/dist/src/connection/surface.js +8 -0
- package/dist/src/facade/approval.js +1 -1
- package/dist/src/facade/client.d.ts +70 -17
- package/dist/src/facade/client.js +198 -62
- package/dist/src/facade/gap-fill.d.ts +2 -0
- package/dist/src/facade/gap-fill.js +11 -2
- package/dist/src/facade/session.d.ts +77 -3
- package/dist/src/facade/session.js +344 -16
- 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/index.d.ts +4 -4
- package/dist/src/index.js +1 -1
- package/dist/src/msp.d.ts +278 -2
- package/package.json +1 -1
|
@@ -36,14 +36,15 @@
|
|
|
36
36
|
* it is forwarded (or explicitly allow-listed as unforwardable).
|
|
37
37
|
*/
|
|
38
38
|
import { discoverMuseBin } from "../connection/discovery.js";
|
|
39
|
-
import { initializeAnswered, SIGTERM_GRACE_MS, 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
43
|
import { fireExtensions } from "../fold/extension.js";
|
|
43
44
|
import { isAbnormalHostDeath, MuseHostDiedError, readSessionDurability } from "./host-death.js";
|
|
44
45
|
import { MspError, peerEndCause, ProtocolError } from "../connection/connection.js";
|
|
45
46
|
import { hostStartFailure } from "./host-start.js";
|
|
46
|
-
import { pumpDropsApplyResults, Session } from "./session.js";
|
|
47
|
+
import { endEventStreams, followsSubagents, forwardedConfig, forwardsEvents, grantedCapabilities, pumpDropsApplyResults, resumeResultOf, serverRequestFrame, Session, } from "./session.js";
|
|
47
48
|
/**
|
|
48
49
|
* Run a caller's observer so neither its throw nor an async observer's
|
|
49
50
|
* rejection escapes: in the read loop a throw ends the connection every session
|
|
@@ -128,8 +129,16 @@ const FACADE_OWNED_METHODS = [
|
|
|
128
129
|
* caller that sends it raw owns the host exit that follows.
|
|
129
130
|
*/
|
|
130
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.
|
|
131
134
|
/** Every `SessionListParams` member `listSessions` forwards. */
|
|
132
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
|
+
}
|
|
133
142
|
/**
|
|
134
143
|
* The caller's capability posture with `sessionMcp` added to its requests,
|
|
135
144
|
* each requested name once (ADR 32760 D3: the facade requests the grant its
|
|
@@ -180,6 +189,15 @@ export class MuseClient {
|
|
|
180
189
|
* handler: a client nobody observes leaves the caller's own handler alone.
|
|
181
190
|
*/
|
|
182
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();
|
|
183
201
|
/**
|
|
184
202
|
* Frames naming a session this client has not registered YET, held only
|
|
185
203
|
* while a `session/start`/`session/resume` is in flight (#49790): the host
|
|
@@ -236,11 +254,11 @@ export class MuseClient {
|
|
|
236
254
|
// `-32601` a bare `Connection` answers.
|
|
237
255
|
this.#connection.onServerRequest(async (request) => {
|
|
238
256
|
if (request.method === "userInput/request") {
|
|
239
|
-
this.#route({ method: "userInput/requested", params: request.params });
|
|
257
|
+
this.#route(serverRequestFrame({ method: "userInput/requested", params: request.params }));
|
|
240
258
|
return {};
|
|
241
259
|
}
|
|
242
260
|
if (request.method === "approval/request") {
|
|
243
|
-
this.#route({ method: request.method, params: request.params });
|
|
261
|
+
this.#route(serverRequestFrame({ method: request.method, params: request.params }));
|
|
244
262
|
return {};
|
|
245
263
|
}
|
|
246
264
|
throw new MspError({
|
|
@@ -278,11 +296,13 @@ export class MuseClient {
|
|
|
278
296
|
return;
|
|
279
297
|
}
|
|
280
298
|
let delivered = false;
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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))
|
|
284
305
|
delivered = true;
|
|
285
|
-
}
|
|
286
306
|
}
|
|
287
307
|
if (delivered || this.#opening === 0)
|
|
288
308
|
return;
|
|
@@ -314,6 +334,9 @@ export class MuseClient {
|
|
|
314
334
|
* Rejects with {@link MuseHostDiscoveryError} before starting anything when
|
|
315
335
|
* `museBin` is omitted and no executable `muse` is on `PATH`.
|
|
316
336
|
*
|
|
337
|
+
* Rejects with an `AbortError` (`cause`: `signal.reason`) when `signal`
|
|
338
|
+
* aborts before the handshake completes, once the host has exited.
|
|
339
|
+
*
|
|
317
340
|
* Rejects with {@link MuseHostStartError} when the host is lost before the
|
|
318
341
|
* handshake completes (the binary could not be spawned, or the process
|
|
319
342
|
* ended first — exit code or signal plus the bounded stderr tail;
|
|
@@ -321,9 +344,15 @@ export class MuseClient {
|
|
|
321
344
|
* that answers with a reply the SDK refuses keeps its own error: an
|
|
322
345
|
* `MspError` for an SS1.6 refusal, or a `ProtocolError` (with the whole
|
|
323
346
|
* refused frame on `line`) for a reply the SDK cannot use, such as one with
|
|
324
|
-
* 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.
|
|
325
351
|
*/
|
|
326
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);
|
|
327
356
|
// The process's own PATH, never `options.env`'s: the host is found the
|
|
328
357
|
// way the Rust and Python SDKs find it, whatever environment it gets.
|
|
329
358
|
const command = await discoverMuseBin(options.museBin, process.env["PATH"], process.platform);
|
|
@@ -337,6 +366,10 @@ export class MuseClient {
|
|
|
337
366
|
? {}
|
|
338
367
|
: { shutdownTimeoutMs: options.shutdownTimeoutMs }),
|
|
339
368
|
...(options.spawnFn === undefined ? {} : { spawnFn: options.spawnFn }),
|
|
369
|
+
...(options.refuseDeclaredBreakingSchema === undefined
|
|
370
|
+
? {}
|
|
371
|
+
: { refuseDeclaredBreakingSchema: options.refuseDeclaredBreakingSchema }),
|
|
372
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
340
373
|
});
|
|
341
374
|
let spawned;
|
|
342
375
|
try {
|
|
@@ -348,6 +381,10 @@ export class MuseClient {
|
|
|
348
381
|
catch (error) {
|
|
349
382
|
// A failed handshake must not leak the process it already spawned.
|
|
350
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
|
+
}
|
|
351
388
|
// A host that ANSWERED `initialize` is not a lost host, however it ends
|
|
352
389
|
// once we close it: its answer is the actionable error. "Answered" is
|
|
353
390
|
// evidence that a response frame came back — an SS1.6 `MspError`, or a
|
|
@@ -355,7 +392,12 @@ export class MuseClient {
|
|
|
355
392
|
// version-skewed reply) — never the error's class alone (#49912).
|
|
356
393
|
// Decided before the exit is read, so our own close ladder can never
|
|
357
394
|
// dress an answer up as a death.
|
|
358
|
-
|
|
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);
|
|
359
401
|
if (answered)
|
|
360
402
|
throw error;
|
|
361
403
|
// No refused frame: the host was lost — before answering, or after a
|
|
@@ -515,7 +557,9 @@ export class MuseClient {
|
|
|
515
557
|
* (no orphan keeps folding for an id the caller can never reach — the SDK
|
|
516
558
|
* has no set/close-by-id verb); the error's `sessionId` is the caller's
|
|
517
559
|
* handle to resume via `sessionId` or start again. A failed read-back
|
|
518
|
-
* 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.
|
|
519
563
|
*/
|
|
520
564
|
async #proveSelection(session, requested) {
|
|
521
565
|
const opening = session.opening;
|
|
@@ -525,16 +569,16 @@ export class MuseClient {
|
|
|
525
569
|
if (started !== null) {
|
|
526
570
|
if (started === requested)
|
|
527
571
|
return session;
|
|
528
|
-
this.#
|
|
572
|
+
this.#untrack(session);
|
|
529
573
|
throw new PermissionProfileNotApplied(requested, started, session.sessionId);
|
|
530
574
|
}
|
|
531
|
-
const read = await this.#connection.
|
|
575
|
+
const read = await this.#connection.request("session/read", {
|
|
532
576
|
sessionId: session.sessionId,
|
|
533
577
|
});
|
|
534
578
|
const served = committedProfileId(read["session"]);
|
|
535
579
|
if (served === requested)
|
|
536
580
|
return session;
|
|
537
|
-
this.#
|
|
581
|
+
this.#untrack(session);
|
|
538
582
|
throw new PermissionProfileNotApplied(requested, served, session.sessionId);
|
|
539
583
|
}
|
|
540
584
|
/**
|
|
@@ -564,7 +608,7 @@ export class MuseClient {
|
|
|
564
608
|
if (options.config != null)
|
|
565
609
|
params.config = this.#forwardConfig("session/resume", options.config);
|
|
566
610
|
return this.#open("session/resume", params, (raw) => ({
|
|
567
|
-
result: raw,
|
|
611
|
+
result: resumeResultOf(raw),
|
|
568
612
|
verb: "session/resume",
|
|
569
613
|
}), { onApproval: options.onApproval, onApprovalError: options.onApprovalError });
|
|
570
614
|
}
|
|
@@ -605,47 +649,16 @@ export class MuseClient {
|
|
|
605
649
|
const ack = await this.#connection.request("usage/read");
|
|
606
650
|
return ack;
|
|
607
651
|
}
|
|
608
|
-
/**
|
|
609
|
-
* Send a wire method directly (FR-79107-2), typically one the facade does
|
|
610
|
-
* not wrap, experimental ones included, through the
|
|
611
|
-
* same `Connection.command()` the verbs use: the connection mints the
|
|
612
|
-
* `commandId`, retries a nothing-admitted refusal under the same id, and
|
|
613
|
-
* checks the ack's echo. `options` are that seam's own. An experimental
|
|
614
|
-
* method needs a client spawned with `capabilities: { experimentalApi: true }`
|
|
615
|
-
* (otherwise the host refuses it with an `MspError` of kind
|
|
616
|
-
* `experimentalRequired`, code -32601) and may change without notice.
|
|
617
|
-
*
|
|
618
|
-
* Refused before anything is written, with `MuseFacadeOwnedMethodError`:
|
|
619
|
-
* the methods whose state the facade owns (`FACADE_OWNED_METHODS`); the
|
|
620
|
-
* experimental host stop is not among them (this package names no
|
|
621
|
-
* experimental-only method), so sent raw it is the caller's own, and the
|
|
622
|
-
* exit it causes reaches your sessions as a host death; `close()` is the
|
|
623
|
-
* orderly stop. Frames
|
|
624
|
-
* the command causes still reach your sessions through the client's one
|
|
625
|
-
* inbound pump; this sends and returns the ack, nothing more. Params and
|
|
626
|
-
* ack stay untyped objects: the generated types carry no method-to-params
|
|
627
|
-
* map, and restating one here would drift from the schema.
|
|
628
|
-
*
|
|
629
|
-
* Each call keeps one fixed-size fingerprint for the connection's lifetime
|
|
630
|
-
* (FR-45137-1), so prefer `request` for a query you poll.
|
|
631
|
-
*/
|
|
632
652
|
async command(method, params, options) {
|
|
633
653
|
// The type binds TypeScript callers; this binds plain-JS ones.
|
|
634
654
|
if (FACADE_OWNED.has(method))
|
|
635
655
|
throw new MuseFacadeOwnedMethodError(method);
|
|
636
656
|
return this.#connection.command(method, params, options);
|
|
637
657
|
}
|
|
638
|
-
|
|
639
|
-
* Send a wire request directly (FR-79107-2), typically a query the facade
|
|
640
|
-
* does not wrap, experimental ones included, through `Connection.request()`:
|
|
641
|
-
* no `commandId`, no retry, and omitted `params` stay off the frame.
|
|
642
|
-
* Refuses the same facade-owned methods as `command`, the same way, and
|
|
643
|
-
* needs the same `experimentalApi` opt-in for an experimental method.
|
|
644
|
-
*/
|
|
645
|
-
async request(method, params) {
|
|
658
|
+
async request(method, ...params) {
|
|
646
659
|
if (FACADE_OWNED.has(method))
|
|
647
660
|
throw new MuseFacadeOwnedMethodError(method);
|
|
648
|
-
return this.#connection.request(method, params);
|
|
661
|
+
return this.#connection.request(method, params[0]);
|
|
649
662
|
}
|
|
650
663
|
/**
|
|
651
664
|
* Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
|
|
@@ -664,15 +677,22 @@ export class MuseClient {
|
|
|
664
677
|
*/
|
|
665
678
|
async close() {
|
|
666
679
|
this.#closing = true;
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
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;
|
|
672
688
|
}
|
|
673
|
-
|
|
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]();
|
|
674
695
|
}
|
|
675
|
-
await this.#connection.close();
|
|
676
696
|
}
|
|
677
697
|
/**
|
|
678
698
|
* The window `#route` holds unknown-session frames for: from the request to
|
|
@@ -683,6 +703,9 @@ export class MuseClient {
|
|
|
683
703
|
*/
|
|
684
704
|
async #open(verb, params, opening, approvals = {}) {
|
|
685
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);
|
|
686
709
|
try {
|
|
687
710
|
const opened = opening(await this.#connection.command(verb, params));
|
|
688
711
|
return this.#openSession(opened.result.session.sessionId, opened, approvals);
|
|
@@ -691,6 +714,13 @@ export class MuseClient {
|
|
|
691
714
|
this.#opening -= 1;
|
|
692
715
|
if (this.#opening === 0)
|
|
693
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
|
+
}
|
|
694
724
|
}
|
|
695
725
|
}
|
|
696
726
|
#openSession(sessionId, opening, approvals) {
|
|
@@ -708,9 +738,13 @@ export class MuseClient {
|
|
|
708
738
|
session.onApprovalError(approvals.onApprovalError);
|
|
709
739
|
if (approvals.onApproval !== undefined)
|
|
710
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);
|
|
711
744
|
// `#route` drops what `apply` returns (FR-81734-1).
|
|
712
745
|
session[pumpDropsApplyResults]();
|
|
713
|
-
this.#
|
|
746
|
+
session[followsSubagents]((child, forward, onStopped) => this.#followSubagent(child, forward, onStopped));
|
|
747
|
+
this.#track(session);
|
|
714
748
|
// The frames that named this session while its verb was in flight fold
|
|
715
749
|
// NOW, in arrival order — synchronously, so nothing the pump routes next
|
|
716
750
|
// can overtake them.
|
|
@@ -722,6 +756,112 @@ export class MuseClient {
|
|
|
722
756
|
}
|
|
723
757
|
return session;
|
|
724
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
|
+
}
|
|
725
865
|
/**
|
|
726
866
|
* The `config` to forward, or a typed refusal before anything is sent
|
|
727
867
|
* (FR-79107-3). Per-session MCP servers need the `sessionMcp` grant in the
|
|
@@ -730,11 +870,7 @@ export class MuseClient {
|
|
|
730
870
|
* it. A config naming no server needs no grant, as on the host (ADR 32760 D3).
|
|
731
871
|
*/
|
|
732
872
|
#forwardConfig(method, config) {
|
|
733
|
-
|
|
734
|
-
return config;
|
|
735
|
-
if (this.#initializeResult?.grantedCapabilities.includes("sessionMcp") === true)
|
|
736
|
-
return config;
|
|
737
|
-
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);
|
|
738
874
|
}
|
|
739
875
|
#assertReattachAllowed(sessionId) {
|
|
740
876
|
// Two facts, both recorded by an ephemeral discharge: THIS session was
|
|
@@ -68,6 +68,8 @@ export declare class GapFiller<I> {
|
|
|
68
68
|
onError(handler: GapFillFailureHandler): void;
|
|
69
69
|
/** Hold one live frame until the paged prefix is in. */
|
|
70
70
|
hold(frame: WireFrame): void;
|
|
71
|
+
/** The cursors of the live frames held for the running fill, in arrival order. */
|
|
72
|
+
heldCursors(): string[];
|
|
71
73
|
/**
|
|
72
74
|
* Recover the fold's outstanding hole.
|
|
73
75
|
*
|
|
@@ -104,6 +104,16 @@ export class GapFiller {
|
|
|
104
104
|
hold(frame) {
|
|
105
105
|
this.#buffer.push(frame);
|
|
106
106
|
}
|
|
107
|
+
/** The cursors of the live frames held for the running fill, in arrival order. */
|
|
108
|
+
heldCursors() {
|
|
109
|
+
const cursors = [];
|
|
110
|
+
for (const frame of this.#buffer) {
|
|
111
|
+
const cursor = _a.#viewCursorOf(frame);
|
|
112
|
+
if (cursor !== undefined)
|
|
113
|
+
cursors.push(cursor);
|
|
114
|
+
}
|
|
115
|
+
return cursors;
|
|
116
|
+
}
|
|
107
117
|
/**
|
|
108
118
|
* Recover the fold's outstanding hole.
|
|
109
119
|
*
|
|
@@ -280,8 +290,7 @@ export class GapFiller {
|
|
|
280
290
|
limit: PAGE_LIMIT,
|
|
281
291
|
sessionId: this.#options.sessionId,
|
|
282
292
|
};
|
|
283
|
-
|
|
284
|
-
return raw;
|
|
293
|
+
return await connection.request("view/page", params);
|
|
285
294
|
}
|
|
286
295
|
/**
|
|
287
296
|
* A page that serves another session's events aborts the fill.
|
|
@@ -32,7 +32,7 @@ import type { DiscardedSessions } from "./discarded.js";
|
|
|
32
32
|
import type { HostDeathDischarge, HostDeathNotification, SessionDurabilityProfile } from "./host-death.js";
|
|
33
33
|
import type { FoldedItem, Turn } from "./turn-handle.js";
|
|
34
34
|
import type { RunOptions, RunResult } from "./run.js";
|
|
35
|
-
import type { ApprovalMode, CommandAcceptedResult, FeedbackSubmitParams, FeedbackSubmitResult, HookListResult, ModelSelection, PluginInstallResult, PluginInstallTarget, PluginListResult, ReasoningEffort, RecapRequestResult, SessionCompactParams, SessionCompactResult, SessionForkParams, SessionForkResult, SessionLeaveParams, SessionLeaveResult, SessionRenameResult, SessionResumeResult, SessionSetApprovalModeResult, SessionSetModelResult, SessionSetReasoningEffortResult, SessionSideChatResult, SessionStartResult, SkillListResult, SkillSetActivationParams, SkillSetActivationResult, SubagentOwnerReasonParams, TaskListResult, TurnInputPart, UserInputAnswer, UserInputAnswerResult, WorkflowControlResult, WorkflowResumeResult } from "../msp.js";
|
|
35
|
+
import type { ApprovalMode, CommandAcceptedResult, FeedbackSubmitParams, FeedbackSubmitResult, HookListResult, ModelSelection, PluginInstallResult, PluginInstallTarget, PluginListResult, ReasoningEffort, RecapRequestResult, SessionCompactParams, SessionCompactResult, SessionForkParams, SessionForkResult, SessionLeaveParams, SessionLeaveResult, SessionRenameResult, SessionResumeResult, SessionSetApprovalModeResult, SessionSetModelResult, SessionSetReasoningEffortResult, SessionSideChatResult, SessionStartResult, SkillListResult, SkillSetActivationParams, SkillSetActivationResult, SessionResumeParams, SubagentOwnerReasonParams, TaskListResult, TurnInputPart, UserInputAnswer, UserInputAnswerResult, WorkflowControlResult, WorkflowResumeResult } from "../msp.js";
|
|
36
36
|
/**
|
|
37
37
|
* Which verb opened this session, and what it answered.
|
|
38
38
|
*
|
|
@@ -51,6 +51,13 @@ export type SessionOpening = {
|
|
|
51
51
|
};
|
|
52
52
|
/** The optional reason `interruptSubagent`/`stopSubagent`/`closeSubagent` record. */
|
|
53
53
|
export type SubagentReasonOptions = Readonly<Pick<SubagentOwnerReasonParams, "reason">>;
|
|
54
|
+
/**
|
|
55
|
+
* Options for `reload()`. `config` is forwarded on the `session/resume` it
|
|
56
|
+
* sends, behind the same `sessionMcp` grant check as `resumeSession`'s
|
|
57
|
+
* (FR-79107-3). Explicit: after an idle unload the caller supplies its
|
|
58
|
+
* additions again (ADR 32760), and the opening's config is never re-sent for it.
|
|
59
|
+
*/
|
|
60
|
+
export type ReloadOptions = Readonly<Pick<SessionResumeParams, "config">>;
|
|
54
61
|
/**
|
|
55
62
|
* Options for constructing a `Session` directly. Sessions opened through
|
|
56
63
|
* `MuseClient` are configured for you; build one yourself when you manage
|
|
@@ -154,6 +161,17 @@ export interface SessionGapOverlap {
|
|
|
154
161
|
readonly method: string;
|
|
155
162
|
readonly viewCursor: string;
|
|
156
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* A frame `reload()`'s replay repeats (#97920): its cursor already reached
|
|
166
|
+
* this session during the reload, from the replay or the live stream. Refused
|
|
167
|
+
* by cursor equality, because folding it again would append an `item/delta`
|
|
168
|
+
* twice.
|
|
169
|
+
*/
|
|
170
|
+
export interface SessionReplayDuplicate {
|
|
171
|
+
readonly kind: "ignoredReplayDuplicate";
|
|
172
|
+
readonly method: string;
|
|
173
|
+
readonly viewCursor: string;
|
|
174
|
+
}
|
|
157
175
|
/**
|
|
158
176
|
* What one `Session.apply` did: the fold's own outcome, plus any SS4.13
|
|
159
177
|
* pending-command retirements the event triggered.
|
|
@@ -181,7 +199,7 @@ export interface SessionGapOverlap {
|
|
|
181
199
|
* restarted walk's work settles on this frame's `io`.
|
|
182
200
|
*/
|
|
183
201
|
export interface SessionApplyOutcome<I> {
|
|
184
|
-
readonly fold: FoldOutcome | SessionApplyRefusal | SessionGapBuffered | SessionGapOverlap;
|
|
202
|
+
readonly fold: FoldOutcome | SessionApplyRefusal | SessionGapBuffered | SessionGapOverlap | SessionReplayDuplicate;
|
|
185
203
|
readonly retirements: readonly PendingRetirement<I>[];
|
|
186
204
|
/**
|
|
187
205
|
* The client->server I/O this event triggered, settled — the SS4.13 replays
|
|
@@ -227,11 +245,37 @@ export interface SessionEvent<I = unknown> {
|
|
|
227
245
|
readonly outcome: SessionApplyOutcome<I>;
|
|
228
246
|
/** For an item event that changed the item: the item as it stood after this event. */
|
|
229
247
|
readonly item?: FoldedItem;
|
|
248
|
+
/**
|
|
249
|
+
* Set on a sub-agent's event, yielded by `events({ subagents: true })`: the
|
|
250
|
+
* sub-agent it belongs to. Its `frame`, `outcome` and `item` are the
|
|
251
|
+
* sub-agent's own.
|
|
252
|
+
*/
|
|
253
|
+
readonly subagent?: SessionEventSubagent;
|
|
254
|
+
}
|
|
255
|
+
/** The sub-agent a `SessionEvent` belongs to. */
|
|
256
|
+
export interface SessionEventSubagent {
|
|
257
|
+
/** The parent session's `subagent` item for it. */
|
|
258
|
+
readonly itemId: string;
|
|
259
|
+
/** The sub-agent's durable id, which the `subagent/*` control verbs take. */
|
|
260
|
+
readonly subagentId: string;
|
|
261
|
+
/** The sub-agent's own session, which the event came from. */
|
|
262
|
+
readonly childSessionId: string;
|
|
230
263
|
}
|
|
231
264
|
/** Options for `Session.events()`. */
|
|
232
265
|
export interface SessionEventsOptions {
|
|
233
266
|
/** Aborting it ends the stream, as `return()` does. */
|
|
234
267
|
readonly signal?: AbortSignal;
|
|
268
|
+
/**
|
|
269
|
+
* Also yield each running sub-agent's events, tagged with `subagent`, in
|
|
270
|
+
* arrival order with this session's own. The client follows each
|
|
271
|
+
* sub-agent's session while such a stream is open. Needs a session
|
|
272
|
+
* `MuseClient` opened. Known limitation: if the host refuses the
|
|
273
|
+
* subscription to a sub-agent (usually because it already finished), its
|
|
274
|
+
* steps do not arrive and no reason is given; its start and result still
|
|
275
|
+
* arrive on the session. A sub-agent resumed after it finished a turn is
|
|
276
|
+
* not subscribed again.
|
|
277
|
+
*/
|
|
278
|
+
readonly subagents?: boolean;
|
|
235
279
|
}
|
|
236
280
|
/**
|
|
237
281
|
* One conversation with the agent.
|
|
@@ -277,12 +321,42 @@ export declare class Session<I = unknown> {
|
|
|
277
321
|
* are yielded when applied, in order. Buffered like `turn.items()`, so a slow
|
|
278
322
|
* reader never holds folding up.
|
|
279
323
|
*
|
|
280
|
-
*
|
|
324
|
+
* With `{ subagents: true }` on a session `MuseClient` did not open it
|
|
325
|
+
* throws a plain `Error`.
|
|
326
|
+
*
|
|
327
|
+
* `break`, `return()` or `options.signal` ends it, and so does an orderly
|
|
328
|
+
* `MuseClient.close()` (a stream created afterwards ends at once). It finishes the way a
|
|
281
329
|
* turn's `items()` does when the host dies: it ends after an ephemeral
|
|
282
330
|
* host's death, and rejects with `MuseHostDiedError` after a durable one's,
|
|
283
331
|
* once the events it already buffered are read.
|
|
284
332
|
*/
|
|
285
333
|
events(options?: SessionEventsOptions): AsyncIterableIterator<SessionEvent<I>>;
|
|
334
|
+
/**
|
|
335
|
+
* Catch this session up in place (#97920): send `session/resume` with the
|
|
336
|
+
* cursor of the last view notification it folded, so the host loads the
|
|
337
|
+
* session if it was unloaded, re-attaches this connection, and streams the
|
|
338
|
+
* suffix after that cursor into THIS session. Its fold, handlers and
|
|
339
|
+
* pending turns stay; a frame the suffix repeats is dropped
|
|
340
|
+
* (`ignoredReplayDuplicate`). Resolves to the resume result once the host
|
|
341
|
+
* replies. Concurrent calls share one resume; a call with `config` while
|
|
342
|
+
* one is in flight is refused (plain `Error`) rather than dropped. `opening`
|
|
343
|
+
* still holds the original open's result. See {@link ReloadOptions}.
|
|
344
|
+
*
|
|
345
|
+
* The fold is caught up only when `result.history.noneReason` is
|
|
346
|
+
* `"cursorSuffix"`. Any other reply (a snapshot for a cursor older than the
|
|
347
|
+
* host keeps, a history budget) means the host served history instead of
|
|
348
|
+
* the missed events, and what streams after it folds over that gap; later
|
|
349
|
+
* reloads then refuse (plain `Error`) before sending: `resumeSession` it
|
|
350
|
+
* instead, for a new `Session` with a fresh fold.
|
|
351
|
+
*
|
|
352
|
+
* Use it before the next command on a session the host may have unloaded
|
|
353
|
+
* (`session/closed`). Refused before anything is sent when the session has
|
|
354
|
+
* folded no cursor yet (plain `Error`): a resume without one would not
|
|
355
|
+
* catch the fold up. A discarded session refuses as every verb does. A
|
|
356
|
+
* refused or failed reload leaves the fold, the other verbs and later
|
|
357
|
+
* reloads usable, except after a reply that was not a cursor suffix (above).
|
|
358
|
+
*/
|
|
359
|
+
reload(options?: ReloadOptions): Promise<SessionResumeResult>;
|
|
286
360
|
/** Observe SS4.8 fills that did not complete. See `MuseGapFillError`. */
|
|
287
361
|
onGapError(handler: GapFillFailureHandler): void;
|
|
288
362
|
/**
|