@muse-code/sdk 0.1.0

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +270 -0
  3. package/dist/src/connection/connection.d.ts +128 -0
  4. package/dist/src/connection/connection.js +548 -0
  5. package/dist/src/connection/spawn.d.ts +161 -0
  6. package/dist/src/connection/spawn.js +462 -0
  7. package/dist/src/errors.d.ts +54 -0
  8. package/dist/src/errors.js +51 -0
  9. package/dist/src/facade/approval.d.ts +76 -0
  10. package/dist/src/facade/approval.js +165 -0
  11. package/dist/src/facade/client.d.ts +153 -0
  12. package/dist/src/facade/client.js +300 -0
  13. package/dist/src/facade/discarded.d.ts +36 -0
  14. package/dist/src/facade/discarded.js +36 -0
  15. package/dist/src/facade/gap-fill.d.ts +80 -0
  16. package/dist/src/facade/gap-fill.js +375 -0
  17. package/dist/src/facade/host-death.d.ts +139 -0
  18. package/dist/src/facade/host-death.js +96 -0
  19. package/dist/src/facade/session.d.ts +309 -0
  20. package/dist/src/facade/session.js +639 -0
  21. package/dist/src/facade/turn-handle.d.ts +156 -0
  22. package/dist/src/facade/turn-handle.js +271 -0
  23. package/dist/src/facade/turn-submit.d.ts +72 -0
  24. package/dist/src/facade/turn-submit.js +168 -0
  25. package/dist/src/fingerprint.d.ts +37 -0
  26. package/dist/src/fingerprint.js +54 -0
  27. package/dist/src/fold/item-store.d.ts +110 -0
  28. package/dist/src/fold/item-store.js +169 -0
  29. package/dist/src/fold/session-fold.d.ts +455 -0
  30. package/dist/src/fold/session-fold.js +399 -0
  31. package/dist/src/fold/state-store.d.ts +68 -0
  32. package/dist/src/fold/state-store.js +89 -0
  33. package/dist/src/index.d.ts +56 -0
  34. package/dist/src/index.js +52 -0
  35. package/dist/src/pending/pending-command-set.d.ts +361 -0
  36. package/dist/src/pending/pending-command-set.js +468 -0
  37. package/package.json +39 -0
@@ -0,0 +1,639 @@
1
+ /**
2
+ * `Session` — the SS7.1 facade's composition of the transport-less core
3
+ * (spec 14990 FR-018 / T030, FM-002 / T030b).
4
+ *
5
+ * It owns a `SessionFold` and a `PendingCommandSet`, routes folded view events
6
+ * to per-turn handles, and discharges the ephemeral host-death obligation.
7
+ * Like everything else in this SDK it holds no durable state (spec Lifecycle &
8
+ * Composition): every fact it reports came from a server event or from the two
9
+ * stores it composes.
10
+ *
11
+ * The SS4.8 splice-fill (FR-020, T032) is here too, in `gap-fill.ts`: this
12
+ * layer owns it because the recipe needs client→server I/O (`view/page`) and
13
+ * because the buffer it splices is the same routing path the iterators read.
14
+ *
15
+ * Everything else FR-018/FR-019 name IS here as of #23980: `sendUserTurn` over
16
+ * the enrolled `turn/start` row, `onApproval`'s idempotent `approval/decide`
17
+ * submission, and the SS4.13 retirement drivers that need client->server I/O.
18
+ * The connection is an OPTIONAL seam: a fold-only `Session` — the transport-less
19
+ * composition every earlier arm builds — stays valid and refuses the submit
20
+ * verbs loudly rather than dropping a caller's input on the floor.
21
+ */
22
+ import { SessionFold } from "../fold/session-fold.js";
23
+ import { PendingCommandSet } from "../pending/pending-command-set.js";
24
+ import { ApprovalRouter } from "./approval.js";
25
+ import { TurnSubmitter } from "./turn-submit.js";
26
+ import { GapFiller } from "./gap-fill.js";
27
+ import { isAbnormalHostDeath, isItemInProgress, MuseHostDiedError, survivesHostDeath, } from "./host-death.js";
28
+ import { MuseForeignSessionError } from "../errors.js";
29
+ import { TurnHandle } from "./turn-handle.js";
30
+ /** Bound to the generated vocabulary so a misspelling fails `tsc`. */
31
+ const USER_MESSAGE = "userMessage";
32
+ /**
33
+ * The shared already-settled `io` for an event that triggered no I/O.
34
+ *
35
+ * A fresh `Promise.resolve([])` per `apply` would allocate on the hot
36
+ * notification path for the overwhelming majority of frames, which carry
37
+ * neither a pending command nor an approval.
38
+ */
39
+ const NO_IO = Promise.resolve([]);
40
+ /**
41
+ * One conversation with the agent.
42
+ *
43
+ * A session folds every server event into readable state — items, turns,
44
+ * session facts, pending approvals — and submits your side of the exchange.
45
+ * Get one from `MuseClient.startSession` or `resumeSession`, then
46
+ * `sendUserTurn` to talk, `turn` to follow a turn's items to its outcome,
47
+ * and `onApproval` to answer permission requests.
48
+ */
49
+ export class Session {
50
+ sessionId;
51
+ /** See {@link SessionOpening}. Absent when the caller built this directly. */
52
+ opening;
53
+ #pending;
54
+ #discarded;
55
+ /** `turn/start` submission and same-`commandId` replay (`turn-submit.ts`). */
56
+ #submit;
57
+ /** The FR-019 round trip (`approval.ts`). */
58
+ #approvals;
59
+ /** The FR-020 splice-fill (`gap-fill.ts`). */
60
+ #gaps;
61
+ #fold = new SessionFold();
62
+ #durability;
63
+ /** The first discharge, replayed verbatim on every later call. */
64
+ #discharge;
65
+ /** Set on a durable abnormal death, so late handles inherit the rejection. */
66
+ #deathError;
67
+ #turns = new Map();
68
+ /**
69
+ * `item/delta` frames whose item the fold does not hold yet. The store
70
+ * already buffers the delta TEXT against the item's arrival (SS4.7.3, spec
71
+ * Edge Cases); a delta's TURN is equally unknowable until then, so the
72
+ * frames wait here and are attributed when the item lands. Dropping them
73
+ * instead would put a silent hole in the very iterators FR-020 forbids one
74
+ * in. Bounded by the same fact that bounds the store's own buffer: the
75
+ * durable `item/completed` always lands the item.
76
+ */
77
+ #unattributedDeltas = new Map();
78
+ constructor(options) {
79
+ this.sessionId = options.sessionId;
80
+ this.#durability = options.durability;
81
+ this.#discarded = options.discarded;
82
+ this.opening = options.opening;
83
+ this.#pending = new PendingCommandSet(options.discarded === undefined
84
+ ? undefined
85
+ : { discardedCommandIds: options.discarded.commandIds });
86
+ this.#submit = new TurnSubmitter(options.sessionId, options.connection, this.#pending);
87
+ this.#approvals = new ApprovalRouter(options.sessionId, options.connection);
88
+ this.#gaps = new GapFiller({
89
+ apply: (frame, into) => this.#foldAndRoute(frame, into),
90
+ connection: options.connection,
91
+ discarded: () => this.#discharge?.kind === "discharged",
92
+ fold: this.#fold,
93
+ sessionId: options.sessionId,
94
+ });
95
+ }
96
+ get durability() {
97
+ return this.#durability;
98
+ }
99
+ /** Read-only; events enter through `apply` so turn routing cannot be skipped. */
100
+ get fold() {
101
+ return this.#fold;
102
+ }
103
+ /** The SS4.13 set, minus the three mutators `Session` drives itself. */
104
+ get pending() {
105
+ return this.#pending;
106
+ }
107
+ /**
108
+ * How many turns this session has minted a handle for.
109
+ *
110
+ * Distinct from `fold.turns()`, which counts turns the WIRE named: a handle
111
+ * is also minted by `turn()` and by item routing, so this is the number that
112
+ * reveals a phantom turn minted from a bad key (a `userShell` item's null
113
+ * `turnId`, say). Read-only and observation-only.
114
+ *
115
+ * @internal Test observability, stripped from the published declarations
116
+ * (`stripInternal`). `Session` is barrel-exported, so without this the getter
117
+ * would be frozen API the moment #211 adopts the package — the same call
118
+ * `liveStreamCount` got by staying off the public `Turn` (Constitution XI).
119
+ */
120
+ get knownTurnCount() {
121
+ return this.#turns.size;
122
+ }
123
+ apply(event) {
124
+ // Only enforce when the frame actually NAMES a session. `ViewEvent`'s
125
+ // members all declare `sessionId`, but a newer host's unknown notification
126
+ // reaches this method at runtime and SS1.5.4 says it is tolerated
127
+ // losslessly — an unconditional read threw `MuseForeignSessionError`
128
+ // ("belongs to session undefined") on it, or a raw `TypeError` when the
129
+ // frame carried no `params` at all.
130
+ const named = event.params?.sessionId;
131
+ if (typeof named === "string" && named !== this.sessionId) {
132
+ throw new MuseForeignSessionError(`event ${event.method} belongs to session ${named}, not ${this.sessionId}`);
133
+ }
134
+ // AFTER the foreign check, deliberately. A frame naming a DIFFERENT session
135
+ // is an embedder routing bug, never this session's trailing drain frame, so
136
+ // the pump-safety rationale below does not cover it — refusing it here
137
+ // would relabel a routing bug as our own drain refusal and hide it exactly
138
+ // when a multiplexed embedder needs to see it.
139
+ //
140
+ // REFUSED, not thrown. A discarded session must still not fold — ItemStore's
141
+ // own guard covers only ITEM events, so a post-discharge `turn/completed`
142
+ // once settled a fresh turn "completed" on a session the client was told to
143
+ // discard. But throwing killed the consumer's pump on a single trailing
144
+ // drain frame, the exact failure this method already refuses for missing
145
+ // params and unknown methods. SS2.13.3b requires that nothing fold; it does
146
+ // not require an exception.
147
+ if (this.#discharge?.kind === "discharged") {
148
+ return { fold: { kind: "refusedSessionDiscarded" }, io: NO_IO, retirements: [] };
149
+ }
150
+ // An SS4.8 fill is in flight, so the live tail waits for the paged prefix
151
+ // (tdd SS4.8's "buffer live events … splice the buffer after the paged
152
+ // prefix"). Folding it now would run the fold backwards when the older
153
+ // paged events land, and would hand the iterators the tail before the
154
+ // hole they follow. The MARKER itself is exempt: a second overflow has to
155
+ // reach the fold to extend the outstanding hole, or the walk stops short
156
+ // of it and reports current with a hole still open.
157
+ if (this.#gaps.filling && event.method !== "view/gap") {
158
+ this.#gaps.hold(event);
159
+ return {
160
+ fold: { kind: "bufferedDuringGap", method: event.method },
161
+ io: NO_IO,
162
+ retirements: [],
163
+ };
164
+ }
165
+ // The overlap's late half: a frame a completed fill already applied from a
166
+ // page, whose live twin the wire delivered afterwards. Reached only when NO
167
+ // fill is running — during one the buffer takes the frame first, and the
168
+ // drain refuses it there against both its own paged cursors and the
169
+ // persistent set.
170
+ const twin = this.#gaps.claimServedTwin(event);
171
+ if (twin !== undefined) {
172
+ return {
173
+ fold: { kind: "ignoredGapOverlap", method: event.method, viewCursor: twin },
174
+ io: NO_IO,
175
+ retirements: [],
176
+ };
177
+ }
178
+ const sink = { retirements: [], tasks: [] };
179
+ const outcome = this.#foldAndRoute(event, sink);
180
+ // FR-020: recover before this fold may call itself current again. Started
181
+ // HERE rather than inside the routing switch because it is the one arm
182
+ // that authors client→server I/O off a notification, and `io` is the
183
+ // channel that carries it.
184
+ if (outcome.kind === "deliveryGap")
185
+ sink.tasks.push(this.#gaps.start());
186
+ return {
187
+ fold: outcome,
188
+ io: Session.#settleIo(sink.tasks),
189
+ retirements: sink.retirements,
190
+ };
191
+ }
192
+ /** Observe SS4.8 fills that did not complete. See `MuseGapFillError`. */
193
+ onGapError(handler) {
194
+ this.#gaps.onError(handler);
195
+ }
196
+ /**
197
+ * Fold one frame and fan it out to the turn handles that want it.
198
+ *
199
+ * The shared path: `apply` uses it for a live frame, and `GapFiller` uses it
200
+ * to re-feed the paged prefix and the buffered tail. One path is what makes
201
+ * a spliced frame indistinguishable from a live one to everything
202
+ * downstream — the fold, the iterators, and the SS4.13 retirements.
203
+ */
204
+ #foldAndRoute(event, sink) {
205
+ const retirements = [];
206
+ const tasks = sink.tasks;
207
+ const outcome = this.#fold.apply(event);
208
+ // The fold drops a frame with no `params` as `ignoredMissingParams`
209
+ // (SS1.5.4: drop, never throw). The switch below reads `event.params` on
210
+ // the turn and delta arms, so without this early return a single
211
+ // `{method:"turn/completed"}` frame throws a raw TypeError out of the ONLY
212
+ // event entry point and kills the consumer's notification pump.
213
+ if (outcome.kind === "ignoredMissingParams")
214
+ return outcome;
215
+ const known = event;
216
+ switch (known.method) {
217
+ case "item/started":
218
+ case "item/updated":
219
+ case "item/completed":
220
+ // A stale re-emission changed nothing (INV-003), so it yields nothing.
221
+ if (outcome.kind === "item" && outcome.outcome.kind !== "ignoredStaleRevision") {
222
+ this.#itemFolded(known.params.item, retirements);
223
+ }
224
+ break;
225
+ case "item/delta":
226
+ this.#deltaFolded(known.params);
227
+ break;
228
+ case "turn/started":
229
+ this.#handle(known.params.turnId).markStarted();
230
+ this.#queueMoved(known.params.turnId, tasks);
231
+ break;
232
+ case "turn/completed":
233
+ this.#handle(known.params.turnId).settleCompleted(known.params);
234
+ this.#queueMoved(known.params.turnId, tasks);
235
+ break;
236
+ case "turn/unqueued": {
237
+ this.#handle(known.params.turnId).settleUnqueued(known.params);
238
+ // SS4.13 "Reclaimed": the reclaim this client just observed retires
239
+ // the entry NOW, with its input restored to the composer. Leaving it
240
+ // in the set is the durable-looking echo SS4.13 forbids — and it would
241
+ // later be retired `terminalUnknown` by a discharge, which would be a
242
+ // fabricated annotation about a command whose fate is known.
243
+ const reclaimed = this.#pending.observedReclaim(known.params.commandId);
244
+ if (reclaimed !== undefined)
245
+ retirements.push(reclaimed);
246
+ break;
247
+ }
248
+ case "approval/requested":
249
+ // FR-019's outbound half. Gated on the fold's own verdict: a request
250
+ // the fold IGNORED (a redelivery for an approval already durably
251
+ // resolved) must author no decision — no second resolution is coming,
252
+ // so a decide against it can only bounce.
253
+ if (outcome.kind === "approvalPending")
254
+ this.#approvalRequested(known.params, tasks);
255
+ break;
256
+ // Folded, deliberately NOT routed to a turn handle. Listed rather than
257
+ // defaulted so this switch is exhaustive over `ViewEvent`: the fold's
258
+ // `AssertNever` forces each new #206 view notification into that union,
259
+ // and a `default` arm here would swallow the addition silently.
260
+ //
261
+ // `view/gap` is here because it routes to no turn: it names a hole in
262
+ // DELIVERY, so what it moves is the fold's currency, and the recovery
263
+ // it triggers is started by `apply` off the `deliveryGap` verdict rather
264
+ // than from this switch (FR-020 / T032).
265
+ case "view/gap":
266
+ case "turn/retracted": // the turn still reaches its own terminal
267
+ case "turn/retryScheduled": // non-terminal by contract (SS4.5.1)
268
+ // An UPDATE refreshes a pending approval; it never opens one, and it
269
+ // carries none of the request-shape members (`itemId`, `turnId`,
270
+ // `toolName`) an `ApprovalHandler` is typed on. SS5.6.3: a re-issued
271
+ // REQUEST embodies the refresh, and that is the frame that drives the
272
+ // handler — so calling it from here would either lie about the request
273
+ // or need a second, thinner handler type for one wire event.
274
+ case "approval/updated":
275
+ case "approval/resolved":
276
+ case "userInput/requested":
277
+ case "userInput/settled":
278
+ case "session/modelChanged":
279
+ case "session/goalChanged":
280
+ case "session/todoListChanged":
281
+ case "session/branchChanged":
282
+ case "session/tokenUsage":
283
+ case "session/contextUsage":
284
+ case "session/approvalModeChanged":
285
+ break;
286
+ default: {
287
+ // Compile-time exhaustiveness. Runtime tolerance of a newer host's
288
+ // unknown method is unaffected — `SessionFold.apply` already returns
289
+ // `ignoredUnrecognizedMethod` for one (SS1.5.4).
290
+ const unrouted = known;
291
+ void unrouted;
292
+ break;
293
+ }
294
+ }
295
+ // The retired entries are gone from the pending set, so their replay
296
+ // memory goes with them — `TurnSubmitter.#memory`'s contract is "pruned on
297
+ // retirement, so it tracks the pending set". This covers the two
298
+ // retirements `apply` produces synchronously (the materialized userMessage
299
+ // and the `turn/unqueued` reclaim); the consumer-driven retirement verbs
300
+ // (`stopRetrying`, `replayAnswered`) prune through their own `Session`
301
+ // wrappers.
302
+ if (retirements.length > 0) {
303
+ this.#submit.forgetRetired(retirements);
304
+ sink.retirements.push(...retirements);
305
+ }
306
+ return outcome;
307
+ }
308
+ /** Flatten the event's I/O tasks, or hand back the shared empty. */
309
+ static #settleIo(tasks) {
310
+ if (tasks.length === 0)
311
+ return NO_IO;
312
+ return Promise.all(tasks).then((batches) => batches.flat());
313
+ }
314
+ /**
315
+ * The handle for a turn, created on first mention from either side. A turn
316
+ * the fold has already settled returns its settled handle, so a wait
317
+ * registered late resolves instead of hanging on an event that has passed.
318
+ */
319
+ turn(turnId) {
320
+ const held = this.#turns.get(turnId);
321
+ if (held !== undefined)
322
+ return held;
323
+ const fresh = this.#mint(turnId);
324
+ // A CONSUMER asking about a turn this session has no news of, after the
325
+ // host died, must not hang: no answer is coming on this connection. That
326
+ // is the SS3.1.4 trap SS2.13.3b's "stop waiting for a terminal" forbids.
327
+ // Server-minted handles deliberately skip this — see `#handle`.
328
+ if (this.#discharge?.kind === "discharged")
329
+ fresh.settleTerminalUnknown();
330
+ else if (this.#deathError !== undefined)
331
+ fresh.fail(this.#deathError);
332
+ return fresh;
333
+ }
334
+ /**
335
+ * A handle minted because a SERVER FRAME named this turn. Never pre-failed,
336
+ * and that is what makes the post-death behaviour ORDER-INDEPENDENT.
337
+ *
338
+ * A durable death does not stop the fold (FM-001), so frames can still
339
+ * arrive for a turn with no handle yet. Pre-failing here made the outcome
340
+ * depend on which frame arrived first: terminal-first settled, started-first
341
+ * pre-failed the handle and first-settlement-wins then dropped the real
342
+ * terminal one frame later — the same server fact, two different answers.
343
+ * That asymmetry is measured against synthetic frames; which order a real
344
+ * host emits after a crash is NOT something this lane has observed, and the
345
+ * rule does not depend on it. A frame arriving IS the connection still speaking,
346
+ * so a handle it mints is not a waiter with no answer coming; `turn()` keeps
347
+ * the latch for the case that genuinely is.
348
+ */
349
+ #handle(turnId) {
350
+ return this.#turns.get(turnId) ?? this.#mint(turnId);
351
+ }
352
+ #mint(turnId) {
353
+ const fresh = new TurnHandle(turnId, () => this.#itemsOfTurn(turnId));
354
+ this.#turns.set(turnId, fresh);
355
+ return fresh;
356
+ }
357
+ /**
358
+ * A host process exited. Classify it, and discharge SS2.13.3b if the profile
359
+ * demands it (tasks.md T030b, FM-002).
360
+ *
361
+ * REPORT EVERY NOTIFICATION OF THE DEATH — the exit promise AND transport
362
+ * EOF. A repeat report of an already-latched death is not a no-op: it marks
363
+ * END OF DRAIN and settles waits the drain minted after the first report.
364
+ * A consumer that dedupes exit notifications and reports the death once
365
+ * leaves those waits pending forever (FM-001).
366
+ *
367
+ * Three outcomes, and the middle one is the one an implementation drops:
368
+ * - an ORDERLY exit (SS2.11 row 0) is not a death: nothing is discharged
369
+ * and the session stays usable;
370
+ * - a DURABLE session's abnormal death reconciles on resume (FM-001), so
371
+ * the stores are left exactly as observed and only the waiters are told;
372
+ * - an EPHEMERAL — or unrecognized (SS2.13.1) — session's abnormal death
373
+ * discharges the obligation in full.
374
+ */
375
+ hostExited(exit) {
376
+ // A second notification of the SAME death (a client can learn of it from
377
+ // both the exit promise and a transport EOF) must report the same thing.
378
+ // The primitives are only side-effect-idempotent: `discardEphemeral`
379
+ // drains the set, so its RETURN is a one-shot delta and a client reading
380
+ // the later notification would silently lose the retired inputs.
381
+ if (this.#discharge !== undefined) {
382
+ // END-OF-DRAIN SWEEP. A durable death does not stop the fold (FM-001),
383
+ // so between the first notification and this one the drain can mint
384
+ // handles from `turn/started` frames whose terminals never arrive.
385
+ // Those are left pending by `#handle` on purpose — a delivered terminal
386
+ // must be able to win — but a SECOND notification means the drain is
387
+ // over and nothing more is coming, so anything still unsettled would
388
+ // hang forever: the SS3.1.4 trap INV-014 forbids.
389
+ //
390
+ // Safe precisely because `fail()`/`settleTerminalUnknown()` no-op on an
391
+ // already-settled handle: a terminal the drain DID deliver keeps its
392
+ // win, so this cannot undo the order-independence it sits beside.
393
+ this.#sweepUnsettledAfterDrain();
394
+ return this.#discharge;
395
+ }
396
+ const profile = this.#durability;
397
+ if (!isAbnormalHostDeath(exit))
398
+ return { exit, kind: "notADeath", profile };
399
+ if (survivesHostDeath(profile)) {
400
+ // FM-001: the stores are left exactly as observed — the terminals arrive
401
+ // on resume — so only the waiters are told.
402
+ const died = new MuseHostDiedError(exit);
403
+ this.#deathError = died;
404
+ for (const handle of this.#turns.values())
405
+ handle.fail(died);
406
+ this.#discharge = { exit, kind: "durableDeath", profile };
407
+ return this.#discharge;
408
+ }
409
+ const retiredCommands = this.#pending.discardEphemeral();
410
+ const terminalUnknownItems = this.#fold.markEphemeralHostDeath(isItemInProgress);
411
+ for (const handle of this.#turns.values())
412
+ handle.settleTerminalUnknown();
413
+ // SS2.13.3b "do not attempt to reattach". `discardEphemeral` already wrote
414
+ // the commandIds into the shared set (it holds it by reference); the
415
+ // sessionId is this layer's to record, because the pending set does not
416
+ // know one. `MuseClient.resumeSession` is the reader.
417
+ this.#discarded?.sessionIds.add(this.sessionId);
418
+ this.#submit.forgetRetired(retiredCommands);
419
+ this.#discharge = {
420
+ exit,
421
+ kind: "discharged",
422
+ profile,
423
+ retiredCommands,
424
+ terminalUnknownItems,
425
+ };
426
+ return this.#discharge;
427
+ }
428
+ /**
429
+ * Settle everything the drain left open. DURABLE ONLY, and `#deathError` is
430
+ * set iff a durable death latched, so the condition is the discriminator.
431
+ *
432
+ * There is deliberately no ephemeral arm: after a discharge the first
433
+ * notification settled every held handle, `apply()` refuses before a frame
434
+ * can mint one, and `turn()` settles a fresh mint on the spot — so no
435
+ * unsettled handle can exist for it to reach. An arm for that state would be
436
+ * untestable defense for something no producer reaches (Constitution XI) and
437
+ * a mutant that survives by construction.
438
+ */
439
+ #sweepUnsettledAfterDrain() {
440
+ if (this.#deathError === undefined)
441
+ return;
442
+ for (const handle of this.#turns.values())
443
+ handle.fail(this.#deathError);
444
+ }
445
+ // ---- FR-018 submit verb (T030 obligation a) -----------------------------
446
+ /**
447
+ * Submit a user turn (tdd SS3.2) and hand back THIS session's handle for the
448
+ * turn the ack named.
449
+ *
450
+ * The returned handle is the one `apply` already routes events to — not a
451
+ * second one minted beside it, which would compare equal on every field and
452
+ * then never receive an item, a delta, or a terminal.
453
+ *
454
+ * The wire shaping, the optimistic SS4.13 entry, and the settle-on-rejection
455
+ * rule all live in `TurnSubmitter`; what is decided HERE is the one thing that
456
+ * needs the fold: the entry's insertion point, which is the last item this
457
+ * session holds at submission time.
458
+ */
459
+ async sendUserTurn(options) {
460
+ const ack = await this.#submit.submit(options, this.#lastFoldedItemId());
461
+ return this.#handle(ack.turnId);
462
+ }
463
+ // ---- FR-019 approval round trip (T031) ----------------------------------
464
+ /** Answer approvals with `handler` (FR-019). See `ApprovalRouter`. */
465
+ onApproval(handler) {
466
+ this.#approvals.onApproval(handler);
467
+ }
468
+ /** Observe round trips that did not complete. See `ApprovalFailure`. */
469
+ onApprovalError(handler) {
470
+ this.#approvals.onApprovalError(handler);
471
+ }
472
+ // ---- consumer-driven SS4.13 retirement verbs ----------------------------
473
+ /**
474
+ * Stop the SS3.1.1 retry loop for one entry and take its input back
475
+ * (SS4.13 "Abandoned").
476
+ *
477
+ * A `Session` method rather than a `pending` view member: the retirement
478
+ * must also prune the submitter's replay memory, or the abandoned command's
479
+ * `turn/start` params live for the session's lifetime — unbounded over the
480
+ * sanctioned submit-then-abandon flow.
481
+ */
482
+ stopRetrying(commandId) {
483
+ const retired = this.#pending.stopRetrying(commandId);
484
+ if (retired !== undefined)
485
+ this.#submit.forgetRetired([retired]);
486
+ return retired;
487
+ }
488
+ /**
489
+ * Feed a consumer-driven replay's answer through the live SS4.13 settlement
490
+ * rules. Wrapped for the same replay-memory bookkeeping as `stopRetrying`;
491
+ * `"held"` means the answer settled nothing and the entry stays.
492
+ */
493
+ replayAnswered(commandId, answer) {
494
+ const settled = this.#pending.replayAnswered(commandId, answer);
495
+ if (settled !== "held")
496
+ this.#submit.forgetRetired([settled]);
497
+ return settled;
498
+ }
499
+ // ---- SS4.13 drivers that need client->server I/O (T030 obligation d) ----
500
+ /**
501
+ * Resolve a snapshot join by performing the I/O its plan demands (SS4.13,
502
+ * SS4.9): same-`commandId` resubmits FIRST, then the replays, then the
503
+ * reclaimed-signature verdict.
504
+ *
505
+ * The order is normative, not incidental: SS4.13 requires an unacked entry be
506
+ * resubmitted "before any retire-to-composer", because a join miss does not
507
+ * prove the intake was never written.
508
+ *
509
+ * `PendingCommandSet.joinSnapshot` stays available on `pending` for a
510
+ * fold-only consumer that performs its own I/O; this verb is for the wired
511
+ * case and therefore requires a connection even when the plan turns out empty.
512
+ */
513
+ async resolveSnapshotJoin(facts) {
514
+ this.#submit.requireConnection("resolveSnapshotJoin");
515
+ const plan = this.#pending.joinSnapshot(facts);
516
+ const out = [...plan.retirements];
517
+ for (const commandId of plan.mustResubmit)
518
+ await this.#submit.driveReplay(commandId, out);
519
+ const queuedCommandIds = facts.queuedTurns.map((queued) => queued.commandId);
520
+ for (const commandId of plan.mustReplay) {
521
+ const answer = await this.#submit.replay(commandId);
522
+ if (answer === undefined)
523
+ continue;
524
+ // The snapshot is what makes the reclaimed signature decidable, so this
525
+ // path uses `resolveReplayAtJoin` rather than the live `replayAnswered`.
526
+ const settled = this.#pending.resolveReplayAtJoin(commandId, answer, queuedCommandIds);
527
+ if (settled !== "held")
528
+ out.push(settled);
529
+ }
530
+ this.#submit.forgetRetired(out);
531
+ return out;
532
+ }
533
+ /**
534
+ * Resolve a reconnect with NO snapshot (`history.mode: "none"`, the default
535
+ * cursor-resume path). Reconnect itself is the trigger: replay each acked
536
+ * entry once, resubmit each unacked entry's SAME `commandId` once.
537
+ */
538
+ async resolveReconnect() {
539
+ this.#submit.requireConnection("resolveReconnect");
540
+ const plan = this.#pending.reconnectedWithoutSnapshot();
541
+ const out = [];
542
+ for (const commandId of plan.mustResubmit)
543
+ await this.#submit.driveReplay(commandId, out);
544
+ for (const commandId of plan.mustReplay)
545
+ await this.#submit.driveReplay(commandId, out);
546
+ this.#submit.forgetRetired(out);
547
+ return out;
548
+ }
549
+ // ---- event-driven I/O ---------------------------------------------------
550
+ #lastFoldedItemId() {
551
+ const items = this.#fold.items.list();
552
+ return items.length === 0 ? null : (items[items.length - 1]?.itemId ?? null);
553
+ }
554
+ /**
555
+ * SS4.13 "Queue movement": a `turn/started` or `turn/completed` for a turn
556
+ * that is not an entry's own decides that entry's fate at a launch boundary,
557
+ * and SS4.3 carries no view event for a command-intake settlement — so the
558
+ * only way to learn it is to replay.
559
+ */
560
+ #queueMoved(turnId, tasks) {
561
+ if (!this.#submit.wired)
562
+ return;
563
+ const commandIds = this.#pending.observedQueueMovement(turnId);
564
+ if (commandIds.length === 0)
565
+ return;
566
+ tasks.push(this.#driveQueueReplays(commandIds));
567
+ }
568
+ async #driveQueueReplays(commandIds) {
569
+ const out = [];
570
+ for (const commandId of commandIds) {
571
+ try {
572
+ await this.#submit.driveReplay(commandId, out);
573
+ }
574
+ catch {
575
+ // Swallowed on purpose, and narrowly: `replay` already converts a
576
+ // server-authored MSP error into an answer, so reaching here means the
577
+ // TRANSPORT failed. That proves nothing about the intake, so the entry
578
+ // holds — and the authoritative report is the host-death notification
579
+ // already on its way. Rethrowing would reject an `io` most consumers
580
+ // never await, i.e. crash the embedder for a fact it is about to be
581
+ // told properly.
582
+ }
583
+ }
584
+ this.#submit.forgetRetired(out);
585
+ return out;
586
+ }
587
+ #approvalRequested(params, tasks) {
588
+ const decided = this.#approvals.requested(params);
589
+ // An approval decision retires no pending command — it is not an SS4.13
590
+ // entry — but it still has to be awaitable through the same `io`, or a
591
+ // consumer has no barrier for the round trip it just triggered.
592
+ if (decided !== undefined)
593
+ tasks.push(decided.then(() => []));
594
+ }
595
+ #itemsOfTurn(turnId) {
596
+ return this.#fold.items.list().filter((item) => item.turnId === turnId);
597
+ }
598
+ #itemFolded(item, retirements) {
599
+ // SS4.13 "Materialized": the `commandId`-bearing `userMessage` landed, so
600
+ // the optimistic entry is replaced by the real item at the item's own
601
+ // position. `itemId` is the ITEM's id — item ids and command ids are
602
+ // separate namespaces on the wire.
603
+ if (item.kind === USER_MESSAGE && item.commandId !== undefined) {
604
+ const materialized = this.#pending.observedUserMessage(item.commandId, item.itemId);
605
+ if (materialized !== undefined)
606
+ retirements.push(materialized);
607
+ }
608
+ // `!= null`, not `!== undefined`: `userShell` items carry `turnId: null`
609
+ // on the wire (spec Edge Cases; tdd SS4.5.6 example) while the generated
610
+ // type says `turnId?: string`, so tsc cannot catch this one. A `!==
611
+ // undefined` guard let null through and minted a phantom turn keyed
612
+ // `null`, attributing the userShell item and its deltas to it.
613
+ const turnId = item.turnId ?? undefined;
614
+ if (turnId != null)
615
+ this.#handle(turnId).pushItem(item);
616
+ const buffered = this.#unattributedDeltas.get(item.itemId);
617
+ if (buffered === undefined)
618
+ return;
619
+ this.#unattributedDeltas.delete(item.itemId);
620
+ if (turnId == null)
621
+ return; // `userShell` is not turn-scoped
622
+ const handle = this.#handle(turnId);
623
+ for (const params of buffered)
624
+ handle.pushDelta(params);
625
+ }
626
+ #deltaFolded(params) {
627
+ const held = this.#fold.items.get(params.itemId);
628
+ if (held === undefined) {
629
+ const buffered = this.#unattributedDeltas.get(params.itemId);
630
+ if (buffered === undefined)
631
+ this.#unattributedDeltas.set(params.itemId, [params]);
632
+ else
633
+ buffered.push(params);
634
+ return;
635
+ }
636
+ if (held.turnId != null)
637
+ this.#handle(held.turnId).pushDelta(params);
638
+ }
639
+ }