@muse-code/sdk 1.4.14 → 1.4.20

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.
@@ -19,6 +19,7 @@
19
19
  * composition every earlier arm builds — stays valid and refuses the submit
20
20
  * verbs loudly rather than dropping a caller's input on the floor.
21
21
  */
22
+ var _a;
22
23
  import { SessionFold } from "../fold/session-fold.js";
23
24
  import { PendingCommandSet } from "../pending/pending-command-set.js";
24
25
  import { ProtocolError } from "../connection/connection.js";
@@ -27,7 +28,8 @@ import { TurnSubmitter } from "./turn-submit.js";
27
28
  import { GapFiller } from "./gap-fill.js";
28
29
  import { isAbnormalHostDeath, isItemInProgress, MuseHostDiedError, survivesHostDeath, } from "./host-death.js";
29
30
  import { MuseForeignSessionError, MuseSessionDiscardedError } from "../errors.js";
30
- import { TurnHandle } from "./turn-handle.js";
31
+ import { PushStream, TurnHandle } from "./turn-handle.js";
32
+ import { runTurn } from "./run.js";
31
33
  /**
32
34
  * True when a routed `approval/request` carries every member the approval
33
35
  * router reads: its `approvalId`, the requirement's `approvalId` and
@@ -47,6 +49,8 @@ function isRecord(value) {
47
49
  }
48
50
  /** Bound to the generated vocabulary so a misspelling fails `tsc`. */
49
51
  const USER_MESSAGE = "userMessage";
52
+ const ACCEPTED = "accepted";
53
+ const QUEUED = "queued";
50
54
  /**
51
55
  * The shared already-settled `io` for an event that triggered no I/O.
52
56
  *
@@ -55,6 +59,24 @@ const USER_MESSAGE = "userMessage";
55
59
  * neither a pending command nor an approval.
56
60
  */
57
61
  const NO_IO = Promise.resolve([]);
62
+ /**
63
+ * Module-private friend seam (never on the package barrel, like
64
+ * `connection.ts`'s `submissionTail`): `MuseClient` marks each session it
65
+ * opens, because its inbound pump drops what `apply` returns. A reclaim the
66
+ * fold retires while this session's own `unqueue()` for that turn is in
67
+ * flight is then held for that call (FR-81734-1).
68
+ *
69
+ * @internal
70
+ */
71
+ export const pumpDropsApplyResults = Symbol("Session.pumpDropsApplyResults");
72
+ /**
73
+ * Module-private friend seam (never on the package barrel): `Session.run`'s
74
+ * abort takes a queued turn back under one `commandId` and sends that same
75
+ * reclaim again while the session runtime does not take it (ADR 77912 D1).
76
+ *
77
+ * @internal
78
+ */
79
+ export const resendableUnqueue = Symbol("Session.resendableUnqueue");
58
80
  /**
59
81
  * One conversation with the agent.
60
82
  *
@@ -76,7 +98,7 @@ export class Session {
76
98
  #approvals;
77
99
  /** The FR-020 splice-fill (`gap-fill.ts`). */
78
100
  #gaps;
79
- #fold = new SessionFold();
101
+ #fold;
80
102
  /**
81
103
  * Approvals the fold holds a durable terminal for. Read by a re-sent
82
104
  * `approval/request`, which skips the fold, so it authors nothing for an
@@ -99,9 +121,108 @@ export class Session {
99
121
  * durable `item/completed` always lands the item.
100
122
  */
101
123
  #unattributedDeltas = new Map();
124
+ /** The live `events()` streams, fed by every folded event. */
125
+ #eventStreams = new Set();
126
+ /** Set through {@link pumpDropsApplyResults} by `MuseClient`. */
127
+ #applyResultsDropped = false;
128
+ /** This session's own `unqueue()` calls awaiting their ack, counted per turn id. */
129
+ #unqueuesInFlight = new Map();
130
+ /**
131
+ * FR-81734-1: a reclaim the fold retired while its turn's own `unqueue()`
132
+ * was in flight on a session whose pump drops `apply`'s return. The call
133
+ * hands it out; it goes when the last in-flight call for the turn settles,
134
+ * so this holds at most one entry per in-flight call.
135
+ */
136
+ #heldReclaims = new Map();
137
+ /**
138
+ * The wire half of every turn handle's control verbs (FR-79106-1). Each
139
+ * refuses on a discarded or fold-only session before anything is sent;
140
+ * `steer` rides the SS4.13 submit path, and an accepted `unqueue` retires
141
+ * the queued entry at once (SS4.13 Reclaimed: "its own reclaim ack"); the
142
+ * later `turn/unqueued` then finds nothing left to retire. When
143
+ * `turn/unqueued` folds first under `MuseClient`, the fold's retirement is
144
+ * held for the call instead (FR-81734-1).
145
+ */
146
+ #turnControls = {
147
+ cancel: async (turnId) => (await this.#command("cancel", "turn/cancel", { turnId })),
148
+ interrupt: async (turnId, options) => (await this.#command("interrupt", "turn/interrupt", {
149
+ turnId,
150
+ ...(options.retract == null ? {} : { retract: options.retract }),
151
+ })),
152
+ steer: async (turnId, options) => {
153
+ this.#requireLiveConnection("steer");
154
+ return await this.#submit.steer(turnId, options, this.#lastFoldedItemId());
155
+ },
156
+ unqueue: async (turnId, commandId) => {
157
+ this.#unqueuesInFlight.set(turnId, (this.#unqueuesInFlight.get(turnId) ?? 0) + 1);
158
+ try {
159
+ const ack = (await this.#command("unqueue", "turn/unqueue", { turnId }, commandId));
160
+ const held = this.#heldReclaims.get(turnId);
161
+ if (held !== undefined) {
162
+ this.#heldReclaims.delete(turnId);
163
+ return { ack, retirement: held };
164
+ }
165
+ return { ack, retirement: ack.status === ACCEPTED ? this.#reclaimQueued(turnId) : undefined };
166
+ }
167
+ finally {
168
+ const left = (this.#unqueuesInFlight.get(turnId) ?? 1) - 1;
169
+ if (left > 0) {
170
+ this.#unqueuesInFlight.set(turnId, left);
171
+ }
172
+ else {
173
+ this.#unqueuesInFlight.delete(turnId);
174
+ this.#heldReclaims.delete(turnId);
175
+ }
176
+ }
177
+ },
178
+ };
179
+ /** @internal See {@link pumpDropsApplyResults}. */
180
+ [pumpDropsApplyResults]() {
181
+ this.#applyResultsDropped = true;
182
+ }
183
+ /** Yield one folded event to every live `events()` stream. */
184
+ #emit(frame, outcome) {
185
+ if (this.#eventStreams.size === 0)
186
+ return;
187
+ const fold = outcome.fold;
188
+ // The item as of THIS event: the store keeps one object per revision, so
189
+ // a later revision folding before the consumer reads cannot change it.
190
+ const item = fold.kind === "item" && fold.outcome.kind !== "ignoredStaleRevision"
191
+ ? this.#fold.items.get(fold.outcome.itemId)
192
+ : undefined;
193
+ const event = item === undefined ? { frame, outcome } : { frame, item, outcome };
194
+ for (const stream of this.#eventStreams)
195
+ stream.push(event);
196
+ }
197
+ /**
198
+ * Fold one frame an SS4.8 fill splices in, and yield it. Its retirements
199
+ * and I/O settle on the gap frame's `io`, so the event carries none.
200
+ */
201
+ #spliced(frame, into) {
202
+ const fold = this.#foldAndRoute(frame, into);
203
+ this.#emit(frame, { fold, io: NO_IO, retirements: [] });
204
+ }
205
+ /** @internal See {@link resendableUnqueue}: each call of the result sends the same reclaim. */
206
+ [resendableUnqueue](turnId) {
207
+ const commandId = this.#requireLiveConnection("unqueue").mintCommandId();
208
+ return () => this.#turnControls.unqueue(turnId, commandId);
209
+ }
210
+ /** Retire this session's acked-queued entry for `turnId`, if it holds one. */
211
+ #reclaimQueued(turnId) {
212
+ const entry = this.#pending
213
+ .list()
214
+ .find((held) => held.ack?.turnId === turnId && held.ack.disposition === QUEUED);
215
+ if (entry === undefined)
216
+ return undefined;
217
+ const retired = this.#pending.observedReclaim(entry.commandId);
218
+ if (retired !== undefined)
219
+ this.#submit.forgetRetired([retired]);
220
+ return retired;
221
+ }
102
222
  constructor(options) {
103
223
  this.sessionId = options.sessionId;
104
224
  this.#durability = options.durability;
225
+ this.#fold = new SessionFold(options.extensions);
105
226
  this.#discarded = options.discarded;
106
227
  this.opening = options.opening;
107
228
  this.#pending = new PendingCommandSet(options.discarded === undefined
@@ -110,7 +231,7 @@ export class Session {
110
231
  this.#submit = new TurnSubmitter(options.sessionId, options.connection, this.#pending);
111
232
  this.#approvals = new ApprovalRouter(options.sessionId, options.connection);
112
233
  this.#gaps = new GapFiller({
113
- apply: (frame, into) => this.#foldAndRoute(frame, into),
234
+ apply: (frame, into) => this.#spliced(frame, into),
114
235
  connection: options.connection,
115
236
  discarded: () => this.#discharge?.kind === "discharged",
116
237
  fold: this.#fold,
@@ -145,6 +266,45 @@ export class Session {
145
266
  return this.#turns.size;
146
267
  }
147
268
  apply(event) {
269
+ const outcome = this.#applyLive(event);
270
+ // A frame held for a fill is yielded when the fill splices it in.
271
+ if (outcome.fold.kind !== "bufferedDuringGap")
272
+ this.#emit(event, outcome);
273
+ return outcome;
274
+ }
275
+ /**
276
+ * Every event this session folds from now on, with what it changed
277
+ * (FR-97336-1). Live from the call, never replayed: read `fold`, then call
278
+ * this in the same tick, and nothing is missed, including the events
279
+ * folded while `startSession`/`resumeSession` was in flight. Each folded
280
+ * event is yielded once, in arrival order; the events a gap fill splices in
281
+ * are yielded when applied, in order. Buffered like `turn.items()`, so a slow
282
+ * reader never holds folding up.
283
+ *
284
+ * `break`, `return()` or `options.signal` ends it. It finishes the way a
285
+ * turn's `items()` does when the host dies: it ends after an ephemeral
286
+ * host's death, and rejects with `MuseHostDiedError` after a durable one's,
287
+ * once the events it already buffered are read.
288
+ */
289
+ events(options = {}) {
290
+ const stream = new PushStream(() => {
291
+ this.#eventStreams.delete(stream);
292
+ options.signal?.removeEventListener("abort", onAbort);
293
+ });
294
+ const onAbort = () => void stream.return();
295
+ if (options.signal?.aborted === true)
296
+ stream.end();
297
+ else if (this.#deathError !== undefined)
298
+ stream.fail(this.#deathError);
299
+ else if (this.#discharge?.kind === "discharged")
300
+ stream.end();
301
+ else {
302
+ this.#eventStreams.add(stream);
303
+ options.signal?.addEventListener("abort", onAbort, { once: true });
304
+ }
305
+ return stream;
306
+ }
307
+ #applyLive(event) {
148
308
  // Only enforce when the frame actually NAMES a session. `ViewEvent`'s
149
309
  // members all declare `sessionId`, but a newer host's unknown notification
150
310
  // reaches this method at runtime and SS1.5.4 says it is tolerated
@@ -214,7 +374,7 @@ export class Session {
214
374
  }
215
375
  return {
216
376
  fold: outcome,
217
- io: Session.#settleIo(sink.tasks),
377
+ io: _a.#settleIo(sink.tasks),
218
378
  retirements: sink.retirements,
219
379
  };
220
380
  }
@@ -289,8 +449,18 @@ export class Session {
289
449
  // later be retired `terminalUnknown` by a discharge, which would be a
290
450
  // fabricated annotation about a command whose fate is known.
291
451
  const reclaimed = this.#pending.observedReclaim(known.params.commandId);
292
- if (reclaimed !== undefined)
452
+ if (reclaimed === undefined)
453
+ break;
454
+ // FR-81734-1: under `MuseClient` this session's own in-flight unqueue
455
+ // for the turn is where it lands. Held INSTEAD of returned, so no
456
+ // outcome, live or spliced into a gap's `io`, carries it a second time.
457
+ if (this.#applyResultsDropped && this.#unqueuesInFlight.has(known.params.turnId)) {
458
+ this.#submit.forgetRetired([reclaimed]);
459
+ this.#heldReclaims.set(known.params.turnId, reclaimed);
460
+ }
461
+ else {
293
462
  retirements.push(reclaimed);
463
+ }
294
464
  break;
295
465
  }
296
466
  case "approval/requested":
@@ -327,6 +497,7 @@ export class Session {
327
497
  case "turn/retracted": // the turn still reaches its own terminal
328
498
  case "turn/retryScheduled": // non-terminal by contract (SS4.5.1)
329
499
  case "turn/modelRetryScheduled": // non-terminal by contract (SS4.5.1)
500
+ case "turn/modelAttemptStarted": // non-terminal by contract (SS4.5.1)
330
501
  case "turn/foregroundCompleted": // non-terminal by contract (SS4.5.12)
331
502
  case "approval/reviewing": // reviewer-held twin of approval/requested (tdd SS5.5.1): a notice, no decide is open
332
503
  case "approval/resolved":
@@ -416,7 +587,7 @@ export class Session {
416
587
  return this.#turns.get(turnId) ?? this.#mint(turnId);
417
588
  }
418
589
  #mint(turnId) {
419
- const fresh = new TurnHandle(turnId, () => this.#itemsOfTurn(turnId));
590
+ const fresh = new TurnHandle(turnId, () => this.#itemsOfTurn(turnId), this.#turnControls);
420
591
  this.#turns.set(turnId, fresh);
421
592
  return fresh;
422
593
  }
@@ -469,6 +640,9 @@ export class Session {
469
640
  this.#deathError = died;
470
641
  for (const handle of this.#turns.values())
471
642
  handle.fail(died);
643
+ for (const stream of this.#eventStreams)
644
+ stream.fail(died);
645
+ this.#eventStreams.clear();
472
646
  this.#discharge = { exit, kind: "durableDeath", profile };
473
647
  return this.#discharge;
474
648
  }
@@ -476,6 +650,9 @@ export class Session {
476
650
  const terminalUnknownItems = this.#fold.markEphemeralHostDeath(isItemInProgress);
477
651
  for (const handle of this.#turns.values())
478
652
  handle.settleTerminalUnknown();
653
+ for (const stream of this.#eventStreams)
654
+ stream.end();
655
+ this.#eventStreams.clear();
479
656
  // SS2.13.3b "do not attempt to reattach". `discardEphemeral` already wrote
480
657
  // the commandIds into the shared set (it holds it by reference); the
481
658
  // sessionId is this layer's to record, because the pending set does not
@@ -526,6 +703,16 @@ export class Session {
526
703
  const ack = await this.#submit.submit(options, this.#lastFoldedItemId());
527
704
  return this.#handle(ack.turnId);
528
705
  }
706
+ /**
707
+ * Run one turn to its end in a single call (FR-79108-1): submit `input`
708
+ * (a string is one text part), wait for the server to end the turn, and
709
+ * resolve its outcome, final answer text, items and usage. Pass
710
+ * `options.signal` to stop the turn; see {@link RunOptions}. Use
711
+ * `sendUserTurn` to stream items or deltas as they arrive.
712
+ */
713
+ run(input, options) {
714
+ return runTurn(this, input, options);
715
+ }
529
716
  // ---- FR-019 approval round trip (T031) ----------------------------------
530
717
  /** Answer approvals with `handler` (FR-019). See `ApprovalRouter`. */
531
718
  onApproval(handler) {
@@ -562,6 +749,184 @@ export class Session {
562
749
  }
563
750
  return ack;
564
751
  }
752
+ // ---- wire-present query and command facades -----------------------------
753
+ #requireLiveConnection(verb) {
754
+ if (this.#discharge?.kind === "discharged") {
755
+ throw new MuseSessionDiscardedError(`session ${this.sessionId} was discarded after an ephemeral host death; it cannot ${verb}`);
756
+ }
757
+ return this.#submit.requireConnection(verb);
758
+ }
759
+ // The four read-only lists (here and `MuseClient.listSessions`) ride
760
+ // `request()`, not `command()`: their wire params carry no `commandId`,
761
+ // and `command()` would retain one dedup entry per call for the whole
762
+ // connection lifetime — a polling caller would grow it without bound.
763
+ /** List this session's live background and foreground tasks (`task/list`). */
764
+ async listTasks() {
765
+ const ack = await this.#requireLiveConnection("listTasks").request("task/list", {
766
+ sessionId: this.sessionId,
767
+ });
768
+ return ack;
769
+ }
770
+ /** List this session's user-invocable skills (`skill/list`). */
771
+ async listSkills() {
772
+ const ack = await this.#requireLiveConnection("listSkills").request("skill/list", {
773
+ sessionId: this.sessionId,
774
+ });
775
+ return ack;
776
+ }
777
+ /** List this session's installed hook rows (`hook/list`). */
778
+ async listHooks() {
779
+ const ack = await this.#requireLiveConnection("listHooks").request("hook/list", {
780
+ sessionId: this.sessionId,
781
+ });
782
+ return ack;
783
+ }
784
+ /** Pause a live workflow run (`workflow/pause`). */
785
+ async pauseWorkflow(workflowRunId) {
786
+ const ack = await this.#requireLiveConnection("pauseWorkflow").command("workflow/pause", {
787
+ sessionId: this.sessionId,
788
+ workflowRunId,
789
+ });
790
+ return ack;
791
+ }
792
+ /** Resume a paused workflow run (`workflow/resume`). */
793
+ async resumeWorkflow(workflowRunId) {
794
+ const ack = await this.#requireLiveConnection("resumeWorkflow").command("workflow/resume", {
795
+ sessionId: this.sessionId,
796
+ workflowRunId,
797
+ });
798
+ return ack;
799
+ }
800
+ /** Request a recap of this session (`recap/request`); admission only. */
801
+ async requestRecap() {
802
+ const ack = await this.#requireLiveConnection("requestRecap").command("recap/request", {
803
+ sessionId: this.sessionId,
804
+ });
805
+ return ack;
806
+ }
807
+ /**
808
+ * Submit feedback about this session (`feedback/submit`). The host
809
+ * serves it only when the spawn requested the `feedback` capability
810
+ * (`requestedCapabilities: ["feedback"]`) and install policy allows
811
+ * it; without that grant the host refuses the call. Its wire params
812
+ * define no `commandId` (each call is one submit; the wire contract
813
+ * attaches no dedup), so it rides `request()` and mints none.
814
+ */
815
+ async submitFeedback(input) {
816
+ const ack = await this.#requireLiveConnection("submitFeedback").request("feedback/submit", {
817
+ ...input,
818
+ sessionId: this.sessionId,
819
+ });
820
+ return ack;
821
+ }
822
+ /**
823
+ * Open a side chat from this session (`session/sideChat`). Returns the wire
824
+ * result; opening a wired `Session` for the new side session is the
825
+ * caller's composition, as with a directly built `Session`.
826
+ */
827
+ async openSideChat() {
828
+ const ack = await this.#requireLiveConnection("openSideChat").command("session/sideChat", {
829
+ sessionId: this.sessionId,
830
+ });
831
+ return ack;
832
+ }
833
+ // ---- session control verbs (FR-79106-1) ---------------------------------
834
+ /** Send one session-scoped command; the connection mints its `commandId`. */
835
+ async #command(verb, method, params, commandId) {
836
+ return await this.#requireLiveConnection(verb).command(method, { ...params, sessionId: this.sessionId }, commandId === undefined ? undefined : { commandId });
837
+ }
838
+ /**
839
+ * Fork this session into a new one (`session/fork`). Returns the wire
840
+ * result for the new session; opening a wired `Session` for it stays the
841
+ * caller's composition, as with `openSideChat`.
842
+ */
843
+ async fork(options = {}) {
844
+ return (await this.#command("fork", "session/fork", { ...options }));
845
+ }
846
+ /** Compact this session's context (`session/compact`); admission only, or `noop`. */
847
+ async compact(options = {}) {
848
+ return (await this.#command("compact", "session/compact", { ...options }));
849
+ }
850
+ /** Select the model for later model calls (`session/setModel`). */
851
+ async setModel(model) {
852
+ return (await this.#command("setModel", "session/setModel", { model }));
853
+ }
854
+ /** Set this session's standing reasoning effort (`session/setReasoningEffort`). */
855
+ async setReasoningEffort(reasoningEffort) {
856
+ return (await this.#command("setReasoningEffort", "session/setReasoningEffort", {
857
+ reasoningEffort,
858
+ }));
859
+ }
860
+ /** Select one of the host's preconfigured approval modes (`session/setApprovalMode`). */
861
+ async setApprovalMode(mode) {
862
+ return (await this.#command("setApprovalMode", "session/setApprovalMode", {
863
+ mode,
864
+ }));
865
+ }
866
+ /** Set or change this session's stored name (`session/rename`). */
867
+ async rename(name) {
868
+ return (await this.#command("rename", "session/rename", { name }));
869
+ }
870
+ /**
871
+ * Release this session from the host (`session/leave`); `stop: true` also
872
+ * cancels unfinished work. Admission only: the host reports the release
873
+ * later as `session/leaveCompleted`.
874
+ */
875
+ async leave(options = {}) {
876
+ return (await this.#command("leave", "session/leave", { ...options }));
877
+ }
878
+ /** Queue a note into a running subagent (`subagent/sendMessage`). */
879
+ async sendSubagentMessage(subagentId, body) {
880
+ return await this.#subagent("sendSubagentMessage", "subagent/sendMessage", { body, subagentId });
881
+ }
882
+ /** Queue a follow-up task for a subagent (`subagent/followupTask`). */
883
+ async followupSubagentTask(subagentId, body) {
884
+ return await this.#subagent("followupSubagentTask", "subagent/followupTask", { body, subagentId });
885
+ }
886
+ /** Ask a subagent to yield at its next boundary (`subagent/interrupt`). */
887
+ async interruptSubagent(subagentId, options = {}) {
888
+ return await this.#subagent("interruptSubagent", "subagent/interrupt", { ...options, subagentId });
889
+ }
890
+ /** Stop a running subagent (`subagent/stop`). */
891
+ async stopSubagent(subagentId, options = {}) {
892
+ return await this.#subagent("stopSubagent", "subagent/stop", { ...options, subagentId });
893
+ }
894
+ /** Resume a paused or recoverable subagent (`subagent/resume`). */
895
+ async resumeSubagent(subagentId) {
896
+ return await this.#subagent("resumeSubagent", "subagent/resume", { subagentId });
897
+ }
898
+ /** Reopen a stopped or closed subagent (`subagent/reopen`). */
899
+ async reopenSubagent(subagentId) {
900
+ return await this.#subagent("reopenSubagent", "subagent/reopen", { subagentId });
901
+ }
902
+ /** Close a subagent as its owner (`subagent/close`). */
903
+ async closeSubagent(subagentId, options = {}) {
904
+ return await this.#subagent("closeSubagent", "subagent/close", { ...options, subagentId });
905
+ }
906
+ /** Consume a subagent's ready result (`subagent/readResult`). */
907
+ async readSubagentResult(subagentId) {
908
+ return await this.#subagent("readSubagentResult", "subagent/readResult", { subagentId });
909
+ }
910
+ async #subagent(verb, method, params) {
911
+ return (await this.#command(verb, method, params));
912
+ }
913
+ /** List this session's installed plugins (`plugin/list`); a query, like `listTasks`. */
914
+ async listPlugins() {
915
+ const ack = await this.#requireLiveConnection("listPlugins").request("plugin/list", {
916
+ sessionId: this.sessionId,
917
+ });
918
+ return ack;
919
+ }
920
+ /** Install one plugin from a marketplace or a host folder (`plugin/install`). */
921
+ async installPlugin(target) {
922
+ return (await this.#command("installPlugin", "plugin/install", { target }));
923
+ }
924
+ /** Turn one skill on or off in one scope (`skill/setActivation`). */
925
+ async setSkillActivation(options) {
926
+ return (await this.#command("setSkillActivation", "skill/setActivation", {
927
+ ...options,
928
+ }));
929
+ }
565
930
  // ---- consumer-driven SS4.13 retirement verbs ----------------------------
566
931
  /**
567
932
  * Stop the SS3.1.1 retry loop for one entry and take its input back
@@ -736,3 +1101,4 @@ export class Session {
736
1101
  this.#handle(held.turnId).pushDelta(params);
737
1102
  }
738
1103
  }
1104
+ _a = Session;
@@ -3,8 +3,10 @@
3
3
  * tasks.md T030).
4
4
  *
5
5
  * A handle owns two things: the SS3.1.4 turn-wait, and the async iterators
6
- * that ride the fold for this turn. It authors no wire traffic and holds no
7
- * durable state — `Session` feeds it folded events and it fans them out.
6
+ * that ride the fold for this turn. It holds no durable state — `Session`
7
+ * feeds it folded events and it fans them out. Its control verbs
8
+ * (`cancel`/`interrupt`/`steer`/`unqueue`, FR-79106-1) author wire traffic
9
+ * only through the `TurnControls` its `Session` hands it.
8
10
  *
9
11
  * INV-006 governs the wait: the SDK never locally times out, fails, or
10
12
  * completes a turn. Every settlement below traces to a server-authored fact,
@@ -13,7 +15,9 @@
13
15
  * client MUST ("stop waiting for a terminal") and which stays an annotation
14
16
  * rather than a synthesized event.
15
17
  */
16
- import type { Item, ItemDeltaParams, TurnCompletedParams, TurnUnqueuedParams } from "../msp.js";
18
+ import type { Item, ItemDeltaParams, TurnCancelResult, TurnCompletedParams, TurnInterruptParams, TurnInterruptResult, TurnSteerResult, TurnUnqueueResult, TurnUnqueuedParams } from "../msp.js";
19
+ import type { PendingRetirement } from "../pending/pending-command-set.js";
20
+ import type { SteerTurnOptions } from "./turn-submit.js";
17
21
  import type { DeepReadonly } from "../fold/session-fold.js";
18
22
  /**
19
23
  * What the iterators yield: the fold's stored item, sealed.
@@ -82,8 +86,59 @@ export type TurnOutcome = {
82
86
  * listening when the turn started is not looking at a launch failure.
83
87
  */
84
88
  export declare function isLaunchFailure(outcome: TurnOutcome): boolean;
89
+ /**
90
+ * A single-consumer push stream. Buffers when nobody is awaiting and hands the
91
+ * buffer over before reporting an end or a failure, so a consumer never loses
92
+ * events it was already owed.
93
+ */
94
+ export declare class PushStream<T> implements AsyncIterableIterator<T> {
95
+ #private;
96
+ /**
97
+ * `onFinished` deregisters this stream from its owner. Without it a consumer
98
+ * that `break`s out of a `for await` — or simply drops the iterator — stays
99
+ * in the fan-out set for the rest of the turn, so every later event is
100
+ * pushed into a stream nobody reads. A render loop that re-attaches per
101
+ * frame would grow one dead stream per frame.
102
+ */
103
+ constructor(onFinished: () => void);
104
+ push(value: T): void;
105
+ end(): void;
106
+ fail(error: unknown): void;
107
+ next(): Promise<IteratorResult<T>>;
108
+ /** `break`/`return` inside a `for await`: drop the backlog and finish. */
109
+ return(): Promise<IteratorResult<T>>;
110
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
111
+ }
85
112
  /** The turn's replayable backlog, supplied by `Session` from the fold. */
86
113
  export type ItemReplay = () => readonly FoldedItem[];
114
+ /** What `interrupt` forwards: the SS3.4 retract pairing. */
115
+ export type InterruptTurnOptions = Readonly<Pick<TurnInterruptParams, "retract">>;
116
+ /**
117
+ * What `unqueue` resolves to: the wire ack, and the SS4.13 retirement the
118
+ * accepted reclaim produced — the queued submit's input handed back to the
119
+ * composer. On a session `MuseClient` opened, `retirement` is set for this
120
+ * session's own accepted reclaim whatever order the ack and `turn/unqueued`
121
+ * arrive in. It is undefined when this session holds no queued entry for the
122
+ * turn (another client's submit, say). On a `Session` you feed through
123
+ * `apply` yourself, it is also undefined when `turn/unqueued` folded first:
124
+ * that `apply` returned the retirement, so restore the composer from
125
+ * whichever of the two returned it. Either way it is handed out once.
126
+ */
127
+ export interface TurnUnqueueOutcome<I> {
128
+ readonly ack: TurnUnqueueResult;
129
+ readonly retirement: PendingRetirement<I> | undefined;
130
+ }
131
+ /**
132
+ * The wire half of a handle's control verbs, supplied by its `Session`, which
133
+ * owns the connection, the discard latch and the SS4.13 pending set.
134
+ */
135
+ export interface TurnControls<I> {
136
+ cancel(turnId: string): Promise<TurnCancelResult>;
137
+ interrupt(turnId: string, options: InterruptTurnOptions): Promise<TurnInterruptResult>;
138
+ steer(turnId: string, options: SteerTurnOptions<I>): Promise<TurnSteerResult>;
139
+ /** `commandId` resends one reclaim under its first id; omitted, the connection mints one. */
140
+ unqueue(turnId: string, commandId?: string): Promise<TurnUnqueueOutcome<I>>;
141
+ }
87
142
  /**
88
143
  * A turn, as a CONSUMER sees it — the SS7.1 turn surface and nothing else.
89
144
  *
@@ -94,18 +149,41 @@ export type ItemReplay = () => readonly FoldedItem[];
94
149
  * is exactly what INV-006 forbids. They stay reachable only through
95
150
  * `Session.apply`, i.e. only from a server-authored event.
96
151
  */
97
- export interface Turn {
152
+ export interface Turn<I = unknown> {
98
153
  readonly turnId: string;
99
154
  /** Did THIS session observe a `turn/started`? Not a launch-failure marker. */
100
155
  readonly observedStart: boolean;
101
156
  readonly completed: Promise<TurnOutcome>;
102
157
  items(): AsyncIterableIterator<FoldedItem>;
103
158
  deltas(): AsyncIterableIterator<ItemDeltaParams>;
159
+ /**
160
+ * Cancel this turn on the normal command lane (`turn/cancel`, tdd SS3.5).
161
+ * Admission only: the turn is over when its `turn/completed` folds.
162
+ */
163
+ cancel(): Promise<TurnCancelResult>;
164
+ /**
165
+ * Stop this turn on the priority lane (`turn/interrupt`, tdd SS3.4), the
166
+ * user's stop gesture; `retract: true` also asks to retract the prompt.
167
+ * Admission only, like `cancel`.
168
+ */
169
+ interrupt(options?: InterruptTurnOptions): Promise<TurnInterruptResult>;
170
+ /**
171
+ * Add input to this turn while it runs (`turn/steer`, tdd SS3.3). The steer
172
+ * is a pending command (SS4.13) until its `userMessage` folds.
173
+ */
174
+ steer(options: SteerTurnOptions<I>): Promise<TurnSteerResult>;
175
+ /**
176
+ * Take this queued turn back before it launches (`turn/unqueue`, tdd SS3.6).
177
+ * An accepted ack means the turn never launches, so this session's queued
178
+ * entry retires at once (SS4.13 Reclaimed) and comes back as `retirement`;
179
+ * the turn itself settles `unqueued` when the server's `turn/unqueued` folds.
180
+ */
181
+ unqueue(): Promise<TurnUnqueueOutcome<I>>;
104
182
  }
105
- export declare class TurnHandle implements Turn {
183
+ export declare class TurnHandle<I = unknown> implements Turn<I> {
106
184
  #private;
107
185
  readonly turnId: string;
108
- constructor(turnId: string, replayItems: ItemReplay);
186
+ constructor(turnId: string, replayItems: ItemReplay, controls: TurnControls<I>);
109
187
  /** Settles on `turn/completed`, `turn/unqueued`, or the ephemeral discard. */
110
188
  get completed(): Promise<TurnOutcome>;
111
189
  /**
@@ -139,6 +217,10 @@ export declare class TurnHandle implements Turn {
139
217
  * state that INV-002's determinism would then have to defend.
140
218
  */
141
219
  deltas(): AsyncIterableIterator<ItemDeltaParams>;
220
+ cancel(): Promise<TurnCancelResult>;
221
+ interrupt(options?: InterruptTurnOptions): Promise<TurnInterruptResult>;
222
+ steer(options: SteerTurnOptions<I>): Promise<TurnSteerResult>;
223
+ unqueue(): Promise<TurnUnqueueOutcome<I>>;
142
224
  markStarted(): void;
143
225
  pushItem(item: FoldedItem): void;
144
226
  pushDelta(params: ItemDeltaParams): void;