@muse-code/sdk 1.4.10 → 1.4.12

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 CHANGED
@@ -8,6 +8,9 @@ agent over the Muse Session Protocol (MSP).
8
8
  server-authored outcome.
9
9
  - Answer tool-approval requests with a handler you register — or register
10
10
  none and run under the server's own default-deny.
11
+ - Answer the agent's questions: list them with
12
+ `session.fold.pendingUserInputs()` and answer with
13
+ `session.answerUserInput`.
11
14
  - A client-side fold keeps a live, typed view of the session — items, session
12
15
  state, pending commands — with gap recovery after dropped deliveries and
13
16
  safe same-command retry that can never double-submit.
@@ -75,8 +78,43 @@ session.onApproval(async (request) => ({
75
78
  }));
76
79
  ```
77
80
 
81
+ An approval still pending when you resume a session arrives right after the
82
+ resume reply, so pass the handler to `resumeSession` itself:
83
+
84
+ ```ts
85
+ const session = await client.resumeSession({
86
+ sessionId,
87
+ onApproval: async (request) => ({
88
+ choiceId: request.availableChoices[0].choiceId,
89
+ }),
90
+ onApprovalError: (failure) => console.error(failure.kind, failure.approvalId),
91
+ });
92
+ ```
93
+
94
+ Pass `onApprovalError` there too: a failure for an approval that arrived with
95
+ the resume reply can happen before `resumeSession` returns, so
96
+ `session.onApprovalError` would be too late to hear it. That covers a handler
97
+ that throws, picks a choice that was not offered, or adds feedback to a choice
98
+ that takes none (which is then answered with the reject choice).
99
+
100
+ To answer a question the agent asks, read it from
101
+ `session.fold.pendingUserInputs()` and answer it with `session.answerUserInput`,
102
+ one answer per question: `selectedLabel` for a single-select question,
103
+ `selectedLabels` for a multiple-select one, or `freeText`. The question leaves
104
+ the list when the server settles it:
105
+
106
+ ```ts
107
+ const [prompt] = session.fold.pendingUserInputs();
108
+ const [question] = prompt?.questions ?? [];
109
+ if (prompt !== undefined && question !== undefined) {
110
+ await session.answerUserInput(prompt.userInputId, [
111
+ { questionId: question.id, selectedLabel: "Yes" },
112
+ ]);
113
+ }
114
+ ```
115
+
78
116
  Status: developer preview. The facade — spawn, session open/resume, turns,
79
- approvals, and recovery after dropped deliveries — is complete and covered by
117
+ approvals, questions, and recovery after dropped deliveries — is complete and covered by
80
118
  the conformance suites in the source repository.
81
119
 
82
120
  ## Documentation
@@ -1,16 +1,18 @@
1
1
  /**
2
- * The FR-019 approval round trip: inbound `approval/requested` → the consumer's
3
- * handler → outbound `approval/decide` (spec 14990 T031, tdd SS5.4).
2
+ * The FR-019 approval round trip: inbound `approval/requested` or
3
+ * `approval/request` → the consumer's handler → outbound `approval/decide`
4
+ * (spec 14990 T031, FR-53910-1, tdd SS5.4).
4
5
  *
5
6
  * Split out of `session.ts` rather than added to it: the router owns a handler,
6
7
  * a per-stage latch, and a decision-shaping guard chain that have nothing to do
7
8
  * with folding a view, and `Session` was already the package's largest module.
8
9
  *
9
- * SHAPE NOTE, established from the bundle rather than assumed. `approval/request`
10
- * as a SERVER REQUEST is not enrolled — the schema carries `approval/requested`
11
- * as a NOTIFICATION only — so the round trip is notification-in /
12
- * command-out, which is exactly the pair FR-019 names. The server-request form
13
- * would be a #206 enrollment request (INV-001), never a local interface.
10
+ * Two frames carry a request in: the `approval/requested` notification and the
11
+ * enrolled `approval/request` server request (`RequestReceipt`), which the host
12
+ * sends beside it and re-sends after a resume (tdd SS5.6). A client-owned
13
+ * connection routes both here (ADR 42116 D18), and the per-stage latch decides
14
+ * each stage once, whichever arrives first. The decision goes out as the
15
+ * `approval/decide` command FR-019 names.
14
16
  */
15
17
  import type { Connection } from "../connection/connection.js";
16
18
  import type { DeepReadonly } from "../fold/session-fold.js";
@@ -32,15 +34,31 @@ export type ApprovalHandler = (request: ApprovalRequestParams) => ApprovalDecisi
32
34
  *
33
35
  * REPORTED, not thrown: the trip is driven from a notification, so a throw
34
36
  * would escape into the consumer's pump with nothing to catch it — the same
35
- * hazard `Session.apply` already refuses a malformed frame for. Each arm names
36
- * a DIFFERENT owner (the consumer's handler, the consumer's choice, the host),
37
- * because the repair differs.
37
+ * hazard `Session.apply` already refuses a malformed frame for. Each kind names
38
+ * whose repair it is (the consumer's handler; the consumer's choice, for
39
+ * `unofferedChoice` and `feedbackNotAccepted`; the host), because the repair
40
+ * differs.
38
41
  */
39
42
  export type ApprovalFailure = {
40
43
  readonly kind: "unofferedChoice";
41
44
  readonly approvalId: string;
42
45
  readonly choiceId: string;
43
46
  readonly availableChoiceIds: readonly string[];
47
+ }
48
+ /**
49
+ * The handler attached `feedback` to a choice whose `acceptsFeedback` is not
50
+ * true. The host would refuse that decision, so it is not sent; the offered
51
+ * reject (the `denied` choice, else the `abort` one) is sent next, so the
52
+ * approval closes. With neither offered, nothing is sent and the approval
53
+ * stays open; a failure to send the reject is reported as `submitFailed`.
54
+ * Next time, answer without feedback, or pick one of `feedbackChoiceIds`, the
55
+ * offered choices that accept it.
56
+ */
57
+ | {
58
+ readonly kind: "feedbackNotAccepted";
59
+ readonly approvalId: string;
60
+ readonly choiceId: string;
61
+ readonly feedbackChoiceIds: readonly string[];
44
62
  } | {
45
63
  readonly kind: "handlerThrew";
46
64
  readonly approvalId: string;
@@ -66,8 +84,9 @@ export declare class ApprovalRouter {
66
84
  /** Observe round trips that did not complete. See {@link ApprovalFailure}. */
67
85
  onApprovalError(handler: ApprovalFailureHandler): void;
68
86
  /**
69
- * An `approval/requested` folded. Returns the decision round trip to await,
70
- * or `undefined` when this client authors nothing for it.
87
+ * An `approval/requested` the fold kept pending, or a routed `approval/request`
88
+ * (FR-53910-1). Returns the decision round trip to await, or `undefined` when
89
+ * this client authors nothing for it.
71
90
  *
72
91
  * No handler at all is the supported default posture, NOT a degraded one
73
92
  * (D-008): the client runs under the server's own default-deny, and this SDK
@@ -79,10 +98,11 @@ export declare class ApprovalRouter {
79
98
  *
80
99
  * A multi-stage approval advances `currentRequirementId` through this frame
81
100
  * ALONE on the notification plane — the SS5.6 item-3 re-issue on stage
82
- * advance is the protected `approval/request` SERVER-REQUEST dual, which is
83
- * not enrolled here (SHAPE NOTE above) — so waiting for a re-issued
84
- * `approval/requested` notification leaves the new stage undecided and the
85
- * turn pending forever.
101
+ * advance is the `approval/request` server request, which reaches this
102
+ * router only through `Session.apply` (a `MuseClient`-owned connection
103
+ * delivers it; a bare `Connection` answers it `-32601`) — so waiting for a
104
+ * re-issued `approval/requested` notification leaves the new stage undecided
105
+ * and the turn pending forever.
86
106
  *
87
107
  * The update alone carries none of the request-shape members the handler is
88
108
  * typed on, but the fold retains the original request and every identity
@@ -1,16 +1,18 @@
1
1
  /**
2
- * The FR-019 approval round trip: inbound `approval/requested` → the consumer's
3
- * handler → outbound `approval/decide` (spec 14990 T031, tdd SS5.4).
2
+ * The FR-019 approval round trip: inbound `approval/requested` or
3
+ * `approval/request` → the consumer's handler → outbound `approval/decide`
4
+ * (spec 14990 T031, FR-53910-1, tdd SS5.4).
4
5
  *
5
6
  * Split out of `session.ts` rather than added to it: the router owns a handler,
6
7
  * a per-stage latch, and a decision-shaping guard chain that have nothing to do
7
8
  * with folding a view, and `Session` was already the package's largest module.
8
9
  *
9
- * SHAPE NOTE, established from the bundle rather than assumed. `approval/request`
10
- * as a SERVER REQUEST is not enrolled — the schema carries `approval/requested`
11
- * as a NOTIFICATION only — so the round trip is notification-in /
12
- * command-out, which is exactly the pair FR-019 names. The server-request form
13
- * would be a #206 enrollment request (INV-001), never a local interface.
10
+ * Two frames carry a request in: the `approval/requested` notification and the
11
+ * enrolled `approval/request` server request (`RequestReceipt`), which the host
12
+ * sends beside it and re-sends after a resume (tdd SS5.6). A client-owned
13
+ * connection routes both here (ADR 42116 D18), and the per-stage latch decides
14
+ * each stage once, whichever arrives first. The decision goes out as the
15
+ * `approval/decide` command FR-019 names.
14
16
  */
15
17
  /**
16
18
  * Every `DecideParams` member the guard chain below forwards. Composition alone
@@ -45,6 +47,7 @@ const REFRESH_FROM_UPDATE = [
45
47
  ];
46
48
  const REFRESH_FROM_REQUEST = [
47
49
  "approvalId",
50
+ "cuaCardFacts",
48
51
  "itemId",
49
52
  "judgeEscalated",
50
53
  "protectedWrite",
@@ -108,8 +111,9 @@ export class ApprovalRouter {
108
111
  this.#onFailure = handler;
109
112
  }
110
113
  /**
111
- * An `approval/requested` folded. Returns the decision round trip to await,
112
- * or `undefined` when this client authors nothing for it.
114
+ * An `approval/requested` the fold kept pending, or a routed `approval/request`
115
+ * (FR-53910-1). Returns the decision round trip to await, or `undefined` when
116
+ * this client authors nothing for it.
113
117
  *
114
118
  * No handler at all is the supported default posture, NOT a degraded one
115
119
  * (D-008): the client runs under the server's own default-deny, and this SDK
@@ -133,10 +137,11 @@ export class ApprovalRouter {
133
137
  *
134
138
  * A multi-stage approval advances `currentRequirementId` through this frame
135
139
  * ALONE on the notification plane — the SS5.6 item-3 re-issue on stage
136
- * advance is the protected `approval/request` SERVER-REQUEST dual, which is
137
- * not enrolled here (SHAPE NOTE above) — so waiting for a re-issued
138
- * `approval/requested` notification leaves the new stage undecided and the
139
- * turn pending forever.
140
+ * advance is the `approval/request` server request, which reaches this
141
+ * router only through `Session.apply` (a `MuseClient`-owned connection
142
+ * delivers it; a bare `Connection` answers it `-32601`) — so waiting for a
143
+ * re-issued `approval/requested` notification leaves the new stage undecided
144
+ * and the turn pending forever.
140
145
  *
141
146
  * The update alone carries none of the request-shape members the handler is
142
147
  * typed on, but the fold retains the original request and every identity
@@ -180,6 +185,11 @@ export class ApprovalRouter {
180
185
  // parent's own approvals by contract (#36182 `skip_serializing_if`).
181
186
  if (params.subagentOrigin !== undefined)
182
187
  refreshed.subagentOrigin = params.subagentOrigin;
188
+ // A Computer Use card's facts belong to the call, so they stay with the
189
+ // retained request across stages; omitted when absent.
190
+ if (requested.cuaCardFacts !== undefined) {
191
+ refreshed.cuaCardFacts = requested.cuaCardFacts;
192
+ }
183
193
  const acked = this.#inFlight.get(requested.approvalId);
184
194
  if (acked !== undefined)
185
195
  return this.#afterAck(acked, refreshed);
@@ -223,7 +233,8 @@ export class ApprovalRouter {
223
233
  return;
224
234
  }
225
235
  const availableChoiceIds = params.availableChoices.map((choice) => choice.choiceId);
226
- if (!availableChoiceIds.includes(decision.choiceId)) {
236
+ const chosen = params.availableChoices.find((choice) => choice.choiceId === decision.choiceId);
237
+ if (chosen === undefined) {
227
238
  // D-006 select-never-create, enforced on THIS side of the transport. An
228
239
  // invented choice bounces -32052 a round trip later, by which time the
229
240
  // stage may have advanced — so the diagnosis a consumer would actually
@@ -237,6 +248,26 @@ export class ApprovalRouter {
237
248
  });
238
249
  return;
239
250
  }
251
+ if (decision.feedback != null && chosen.acceptsFeedback !== true) {
252
+ // The host refuses feedback on any other choice (-32052) and keeps its
253
+ // approval open, so refuse it here and answer with the offered reject
254
+ // instead, the choice the Rust SDK sends too: the approval closes and
255
+ // the host's turn goes on. With neither a `denied` nor an `abort`
256
+ // choice, nothing is sent.
257
+ this.#report({
258
+ approvalId: params.approvalId,
259
+ choiceId: decision.choiceId,
260
+ feedbackChoiceIds: params.availableChoices
261
+ .filter((choice) => choice.acceptsFeedback === true)
262
+ .map((choice) => choice.choiceId),
263
+ kind: "feedbackNotAccepted",
264
+ });
265
+ const reject = params.availableChoices.find((choice) => choice.decision === "denied") ??
266
+ params.availableChoices.find((choice) => choice.decision === "abort");
267
+ if (reject === undefined)
268
+ return;
269
+ decision = { choiceId: reject.choiceId };
270
+ }
240
271
  const decideParams = {
241
272
  approvalId: params.approvalId,
242
273
  choiceId: decision.choiceId,
@@ -38,6 +38,7 @@
38
38
  import type { Connection } from "../connection/connection.js";
39
39
  import type { ExitClassification, SpawnedMspConnection } from "../connection/spawn.js";
40
40
  import type { SessionDurabilityProfile } from "./host-death.js";
41
+ import type { ApprovalFailureHandler, ApprovalHandler } from "./approval.js";
41
42
  import { Session } from "./session.js";
42
43
  import type { InitializeParams, InitializeResult, SessionResumeParams, SessionStartParams } from "../msp.js";
43
44
  /**
@@ -58,7 +59,22 @@ export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId"
58
59
  requirePermissionProfile?: boolean;
59
60
  }>;
60
61
  /** Caller-facing options for `session/resume` (tdd SS2.5.2). */
61
- export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId" | "config">>;
62
+ export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId" | "config"> & {
63
+ /**
64
+ * Answers this session's approvals from its first frame, so an approval
65
+ * the host re-sends right after the resume reply reaches it. The same
66
+ * contract as `session.onApproval`, installed before the frames that
67
+ * arrived with the reply are applied.
68
+ */
69
+ onApproval?: ApprovalHandler;
70
+ /**
71
+ * Hears this session's approval failures from its first frame, as
72
+ * `session.onApprovalError` does later. A failure for an approval that
73
+ * arrived with the resume reply can happen before `resumeSession` returns,
74
+ * so only this option is sure to hear it.
75
+ */
76
+ onApprovalError?: ApprovalFailureHandler;
77
+ }>;
62
78
  /**
63
79
  * Options for building a `MuseClient` around a connection you already own.
64
80
  * `MuseClient.spawn` fills these in for you; supply them yourself only when
@@ -55,12 +55,13 @@ const START_FORWARDED = [
55
55
  "workspaceRoots",
56
56
  "modelId",
57
57
  "permissionProfile",
58
+ "recoveryMode",
58
59
  ];
59
60
  /**
60
61
  * Every `ResumeParams` member `resumeSession` forwards. `config` has the same
61
62
  * temporary capability-check boundary as the start facade above.
62
63
  */
63
- const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history", "permissionProfile"];
64
+ const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history", "permissionProfile", "recoveryMode"];
64
65
  /**
65
66
  * The committed profile id a session snapshot claims, or null when the
66
67
  * snapshot is silent (the stable bundle strips the member; absent and null
@@ -130,6 +131,30 @@ export class MuseClient {
130
131
  // "MuseClient owns the connection" means; a consumer that needs the raw
131
132
  // feed builds around a bare `Connection` and `Session` instead.
132
133
  this.#connection.onNotification((notification) => this.#route(notification));
134
+ // A question or approval still open at resume is re-sent as a
135
+ // `userInput/request` or `approval/request` server request (tdd SS5.6,
136
+ // SS5.10). Each is routed in arrival order and answered with the SS5.3.3
137
+ // receipt `{}`: a question as the `userInput/requested` twin it shares
138
+ // params with, so its session lists it, and an approval as itself, which
139
+ // the session routes to its approval handler. The receipt does not wait on
140
+ // `#route` finding the session: a request read during an open is held
141
+ // before that session exists. Every other server-request method keeps the
142
+ // `-32601` a bare `Connection` answers.
143
+ this.#connection.onServerRequest(async (request) => {
144
+ if (request.method === "userInput/request") {
145
+ this.#route({ method: "userInput/requested", params: request.params });
146
+ return {};
147
+ }
148
+ if (request.method === "approval/request") {
149
+ this.#route({ method: request.method, params: request.params });
150
+ return {};
151
+ }
152
+ throw new MspError({
153
+ code: -32601,
154
+ message: `method not found: ${request.method}`,
155
+ data: { kind: "methodNotFound", retryable: false },
156
+ });
157
+ });
133
158
  // Registered at construction, not at the first session: an EOF can land
134
159
  // before any session exists, and the flag has to be read at that moment.
135
160
  void this.#connection.closed.then(() => this.#transportClosed());
@@ -269,6 +294,8 @@ export class MuseClient {
269
294
  params.workspaceRoots = options.workspaceRoots;
270
295
  if (options.modelId != null)
271
296
  params.modelId = options.modelId;
297
+ if (options.recoveryMode != null)
298
+ params.recoveryMode = options.recoveryMode;
272
299
  // The initial permission-profile selection, forwarded verbatim like the
273
300
  // other start members (undefined stays omitted).
274
301
  if (options.permissionProfile != null)
@@ -340,12 +367,14 @@ export class MuseClient {
340
367
  params.excludeItems = options.excludeItems;
341
368
  if (options.history != null)
342
369
  params.history = options.history;
370
+ if (options.recoveryMode != null)
371
+ params.recoveryMode = options.recoveryMode;
343
372
  if (options.permissionProfile != null)
344
373
  params.permissionProfile = options.permissionProfile;
345
374
  return this.#open("session/resume", params, (raw) => ({
346
375
  result: raw,
347
376
  verb: "session/resume",
348
- }));
377
+ }), { onApproval: options.onApproval, onApprovalError: options.onApprovalError });
349
378
  }
350
379
  /**
351
380
  * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
@@ -381,11 +410,11 @@ export class MuseClient {
381
410
  * named no session this client opened is held no longer than the open it
382
411
  * rode in with (#49790).
383
412
  */
384
- async #open(verb, params, opening) {
413
+ async #open(verb, params, opening, approvals = {}) {
385
414
  this.#opening += 1;
386
415
  try {
387
416
  const opened = opening(await this.#connection.command(verb, params));
388
- return this.#openSession(opened.result.session.sessionId, opened);
417
+ return this.#openSession(opened.result.session.sessionId, opened, approvals);
389
418
  }
390
419
  finally {
391
420
  this.#opening -= 1;
@@ -393,7 +422,7 @@ export class MuseClient {
393
422
  this.#held.clear();
394
423
  }
395
424
  }
396
- #openSession(sessionId, opening) {
425
+ #openSession(sessionId, opening, approvals) {
397
426
  const session = new Session({
398
427
  connection: this.#connection,
399
428
  discarded: this.#discarded,
@@ -401,6 +430,12 @@ export class MuseClient {
401
430
  opening,
402
431
  sessionId,
403
432
  });
433
+ // Before the held frames below: an approval re-sent with the resume reply
434
+ // must find the handler, and its failure the observer.
435
+ if (approvals.onApprovalError !== undefined)
436
+ session.onApprovalError(approvals.onApprovalError);
437
+ if (approvals.onApproval !== undefined)
438
+ session.onApproval(approvals.onApproval);
404
439
  this.#sessions.add(session);
405
440
  // The frames that named this session while its verb was in flight fold
406
441
  // NOW, in arrival order — synchronously, so nothing the pump routes next
@@ -114,8 +114,9 @@ export class GapFiller {
114
114
  */
115
115
  start() {
116
116
  const gap = this.#options.fold.pendingGap;
117
- // Only reachable if a caller invokes this with nothing outstanding; the
118
- // one production caller folds the marker first, which always sets it.
117
+ // Only reachable if a caller invokes this with nothing outstanding:
118
+ // `Session.apply` folds the marker first (which sets it, or a stale repeat
119
+ // finds it already set), and `#run` checks it before it restarts itself.
119
120
  if (gap === undefined)
120
121
  return NO_RETIREMENTS;
121
122
  if (this.#filling)
@@ -357,6 +358,10 @@ export class GapFiller {
357
358
  return Promise.all(sink.tasks).then((batches) => [...sink.retirements, ...batches.flat()]);
358
359
  }
359
360
  static #viewCursorOf(frame) {
361
+ // A routed `approval/request` carries its notification's cursor but is not
362
+ // that event: matching it would spend the twin's overlap slot.
363
+ if (frame.method === "approval/request")
364
+ return undefined;
360
365
  const cursor = frame.params?.viewCursor;
361
366
  return typeof cursor === "string" ? cursor : undefined;
362
367
  }
@@ -30,7 +30,7 @@ import type { GapFillFailureHandler } from "./gap-fill.js";
30
30
  import type { DiscardedSessions } from "./discarded.js";
31
31
  import type { HostDeathDischarge, HostDeathNotification, SessionDurabilityProfile } from "./host-death.js";
32
32
  import type { Turn } from "./turn-handle.js";
33
- import type { SessionResumeResult, SessionStartResult } from "../msp.js";
33
+ import type { SessionResumeResult, SessionStartResult, UserInputAnswer, UserInputAnswerResult } from "../msp.js";
34
34
  /**
35
35
  * Which verb opened this session, and what it answered.
36
36
  *
@@ -165,7 +165,10 @@ export interface SessionGapOverlap {
165
165
  * A SECOND `view/gap` that lands while a fill is running rides the same
166
166
  * channel for the same reason: it extends the running walk instead of starting
167
167
  * its own, so its apply reports `deliveryGap` with an already-settled empty
168
- * `io`, and the work it caused settles on the FIRST gap frame's.
168
+ * `io`, and the work it caused settles on the FIRST gap frame's. A repeat of a
169
+ * `next` already named while the hole is open folds as `ignoredStaleFrame` and
170
+ * extends nothing; after a failed fill it still restarts that fill, and the
171
+ * restarted walk's work settles on this frame's `io`.
169
172
  */
170
173
  export interface SessionApplyOutcome<I> {
171
174
  readonly fold: FoldOutcome | SessionApplyRefusal | SessionGapBuffered | SessionGapOverlap;
@@ -270,6 +273,13 @@ export declare class Session<I = unknown> {
270
273
  onApproval(handler: ApprovalHandler): void;
271
274
  /** Observe round trips that did not complete. See `ApprovalFailure`. */
272
275
  onApprovalError(handler: ApprovalFailureHandler): void;
276
+ /**
277
+ * Answer a question this session lists in `fold.pendingUserInputs()` (tdd
278
+ * SS5.10.2): sends `userInput/answer` with one answer per question and
279
+ * resolves with the host's admission. The question leaves the pending list
280
+ * only when the server's `userInput/settled` arrives.
281
+ */
282
+ answerUserInput(userInputId: string, answers: readonly UserInputAnswer[]): Promise<UserInputAnswerResult>;
273
283
  /**
274
284
  * Stop the SS3.1.1 retry loop for one entry and take its input back
275
285
  * (SS4.13 "Abandoned").
@@ -21,12 +21,30 @@
21
21
  */
22
22
  import { SessionFold } from "../fold/session-fold.js";
23
23
  import { PendingCommandSet } from "../pending/pending-command-set.js";
24
+ import { ProtocolError } from "../connection/connection.js";
24
25
  import { ApprovalRouter } from "./approval.js";
25
26
  import { TurnSubmitter } from "./turn-submit.js";
26
27
  import { GapFiller } from "./gap-fill.js";
27
28
  import { isAbnormalHostDeath, isItemInProgress, MuseHostDiedError, survivesHostDeath, } from "./host-death.js";
28
- import { MuseForeignSessionError } from "../errors.js";
29
+ import { MuseForeignSessionError, MuseSessionDiscardedError } from "../errors.js";
29
30
  import { TurnHandle } from "./turn-handle.js";
31
+ /**
32
+ * True when a routed `approval/request` carries every member the approval
33
+ * router reads: its `approvalId`, the requirement's `approvalId` and
34
+ * `sourceIndex`, and each offered choice's `choiceId`.
35
+ */
36
+ function isRoutableApprovalRequest(params) {
37
+ const { approvalId, currentRequirementId, availableChoices } = params;
38
+ return (typeof approvalId === "string" &&
39
+ isRecord(currentRequirementId) &&
40
+ typeof currentRequirementId["approvalId"] === "string" &&
41
+ Number.isInteger(currentRequirementId["sourceIndex"]) &&
42
+ Array.isArray(availableChoices) &&
43
+ availableChoices.every((choice) => isRecord(choice) && typeof choice["choiceId"] === "string"));
44
+ }
45
+ function isRecord(value) {
46
+ return value !== null && typeof value === "object" && !Array.isArray(value);
47
+ }
30
48
  /** Bound to the generated vocabulary so a misspelling fails `tsc`. */
31
49
  const USER_MESSAGE = "userMessage";
32
50
  /**
@@ -59,6 +77,12 @@ export class Session {
59
77
  /** The FR-020 splice-fill (`gap-fill.ts`). */
60
78
  #gaps;
61
79
  #fold = new SessionFold();
80
+ /**
81
+ * Approvals the fold holds a durable terminal for. Read by a re-sent
82
+ * `approval/request`, which skips the fold, so it authors nothing for an
83
+ * approval already resolved; mirrors the fold's own record, keyed for O(1).
84
+ */
85
+ #resolvedApprovalIds = new Set();
62
86
  #durability;
63
87
  /** The first discharge, replayed verbatim on every later call. */
64
88
  #discharge;
@@ -181,8 +205,13 @@ export class Session {
181
205
  // HERE rather than inside the routing switch because it is the one arm
182
206
  // that authors client→server I/O off a notification, and `io` is the
183
207
  // channel that carries it.
184
- if (outcome.kind === "deliveryGap")
208
+ // A stale repeat of an earlier gap still restarts a failed fill, as every
209
+ // folded `view/gap` (a `deliveryGap` or a stale repeat) reaches `start()`
210
+ // (a no-op while a fill runs).
211
+ if (outcome.kind === "deliveryGap" ||
212
+ (outcome.kind === "ignoredStaleFrame" && outcome.method === "view/gap")) {
185
213
  sink.tasks.push(this.#gaps.start());
214
+ }
186
215
  return {
187
216
  fold: outcome,
188
217
  io: Session.#settleIo(sink.tasks),
@@ -204,7 +233,26 @@ export class Session {
204
233
  #foldAndRoute(event, sink) {
205
234
  const retirements = [];
206
235
  const tasks = sink.tasks;
236
+ // A re-sent `approval/request` server request skips the fold, which lists
237
+ // only the `approval/requested` notification, and reaches approval routing
238
+ // like that notification: the per-stage latch decides each stage once, and
239
+ // an approval already resolved authors nothing.
240
+ // A request missing the members the router reads is dropped, never thrown
241
+ // on (SS1.5.4), whichever path applies it: a held frame replayed inside
242
+ // `resumeSession` included. A routed or dropped request reports
243
+ // `ignoredUnrecognizedMethod`, a sanctioned interim like `session/started`'s
244
+ // (#62835 owns a dedicated outcome); one with no params object falls through
245
+ // to the fold's `ignoredMissingParams`, like every other frame.
246
+ if (event.method === "approval/request" && isRecord(event.params)) {
247
+ const params = event.params;
248
+ if (isRoutableApprovalRequest(params) && !this.#resolvedApprovalIds.has(params.approvalId)) {
249
+ this.#approvalRequested(params, tasks);
250
+ }
251
+ return { kind: "ignoredUnrecognizedMethod", method: event.method };
252
+ }
207
253
  const outcome = this.#fold.apply(event);
254
+ if (outcome.kind === "approvalResolved")
255
+ this.#resolvedApprovalIds.add(outcome.approvalId);
208
256
  // The fold drops a frame with no `params` as `ignoredMissingParams`
209
257
  // (SS1.5.4: drop, never throw). The switch below reads `event.params` on
210
258
  // the turn and delta arms, so without this early return a single
@@ -272,8 +320,9 @@ export class Session {
272
320
  //
273
321
  // `view/gap` is here because it routes to no turn: it names a hole in
274
322
  // DELIVERY, so what it moves is the fold's currency, and the recovery
275
- // it triggers is started by `apply` off the `deliveryGap` verdict rather
276
- // than from this switch (FR-020 / T032).
323
+ // it triggers is started by `apply` off the `deliveryGap` verdict, or off
324
+ // a stale `view/gap`'s `ignoredStaleFrame`, rather than from this switch
325
+ // (FR-020 / T032).
277
326
  case "view/gap":
278
327
  case "turn/retracted": // the turn still reaches its own terminal
279
328
  case "turn/retryScheduled": // non-terminal by contract (SS4.5.1)
@@ -293,6 +342,12 @@ export class Session {
293
342
  case "session/approvalModeChanged":
294
343
  case "session/modelRouteUnserved":
295
344
  case "session/nameChanged":
345
+ // The monitor-inbox trio (SS4.5.18): consumer-folded notices, never
346
+ // turn-handle traffic — the fold surfaces their facts on the
347
+ // `monitorInbox` outcome and seeds no store.
348
+ case "monitor/inboxItemAdmitted":
349
+ case "monitor/inboxItemDrained":
350
+ case "monitor/inboxItemVoided":
296
351
  break;
297
352
  default: {
298
353
  // Compile-time exhaustiveness. Runtime tolerance of a newer host's
@@ -480,6 +535,33 @@ export class Session {
480
535
  onApprovalError(handler) {
481
536
  this.#approvals.onApprovalError(handler);
482
537
  }
538
+ // ---- user-input answers (ADR 42116 D18) ----------------------------------
539
+ /**
540
+ * Answer a question this session lists in `fold.pendingUserInputs()` (tdd
541
+ * SS5.10.2): sends `userInput/answer` with one answer per question and
542
+ * resolves with the host's admission. The question leaves the pending list
543
+ * only when the server's `userInput/settled` arrives.
544
+ */
545
+ async answerUserInput(userInputId, answers) {
546
+ // Refused before anything is sent, as `sendUserTurn` is: SS2.13.3b
547
+ // forbids reattaching a discarded session.
548
+ if (this.#discharge?.kind === "discharged") {
549
+ throw new MuseSessionDiscardedError(`session ${this.sessionId} was discarded after an ephemeral host death; it cannot answer a question`);
550
+ }
551
+ const connection = this.#submit.requireConnection("answerUserInput");
552
+ // No explicit `commandId`: `Connection.command()` mints and stamps it, and
553
+ // refuses an ack that echoes a different one. An ack with none is refused
554
+ // here, with one naming another question.
555
+ const ack = await connection.command("userInput/answer", {
556
+ sessionId: this.sessionId,
557
+ userInputId,
558
+ answers: [...answers],
559
+ });
560
+ if (typeof ack["commandId"] !== "string" || ack["userInputId"] !== userInputId) {
561
+ throw new ProtocolError(`userInput/answer acknowledged command ${String(ack["commandId"])} for question ${String(ack["userInputId"])}, expected question ${userInputId}`);
562
+ }
563
+ return ack;
564
+ }
483
565
  // ---- consumer-driven SS4.13 retirement verbs ----------------------------
484
566
  /**
485
567
  * Stop the SS3.1.1 retry loop for one entry and take its input back
@@ -13,7 +13,7 @@
13
13
  * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
14
  * working against a newer host.
15
15
  */
16
- export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:5d3b43e5ccdb7dc4f5a32c380f5f2cde0f10e3059b93610afb2e73f73b1d914c";
16
+ export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:cfdb6d2525601b9bac76584ccb0610ab3a5539b5e4f51141f079b99b39fcb4e0";
17
17
  /**
18
18
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
19
  *
@@ -13,7 +13,7 @@
13
13
  * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
14
  * working against a newer host.
15
15
  */
16
- export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:5d3b43e5ccdb7dc4f5a32c380f5f2cde0f10e3059b93610afb2e73f73b1d914c";
16
+ export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:cfdb6d2525601b9bac76584ccb0610ab3a5539b5e4f51141f079b99b39fcb4e0";
17
17
  /**
18
18
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
19
  *