@muse-code/sdk 0.1.1 → 1.3.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.
package/README.md CHANGED
@@ -1,285 +1,88 @@
1
1
  # `@muse-code/sdk`
2
2
 
3
- The MSP TypeScript facade (tdd SS7.1). Owning spec: `specs/14990-muse-sdk/`.
4
-
5
- **Zero runtime dependencies** (INV-009): pure TypeScript over `@muse-code/msp` plus
6
- the Node standard library. A proposed runtime dependency is an owner
7
- escalation under the #211 O-3 precedent — official protocol-owner SDKs,
8
- pinned exact, supply-chain reviewed — not a local decision.
3
+ The TypeScript SDK for Muse Code: a typed Node client for driving a Muse Code
4
+ agent over the Muse Session Protocol (MSP).
5
+
6
+ - Spawn a `muse serve` host, open and resume sessions, and send turns.
7
+ - Stream a turn's items and text deltas as async iterators; await the turn's
8
+ server-authored outcome.
9
+ - Answer tool-approval requests with a handler you register — or register
10
+ none and run under the server's own default-deny.
11
+ - A client-side fold keeps a live, typed view of the session — items, session
12
+ state, pending commands — with gap recovery after dropped deliveries and
13
+ safe same-command retry that can never double-submit.
14
+
15
+ **Zero runtime dependencies**: pure TypeScript over the Node standard
16
+ library. The MSP wire declarations are bundled into the package, so nothing
17
+ else is needed to typecheck against it.
9
18
 
10
19
  ## Install
11
20
 
12
21
  ```sh
13
22
  npm install @muse-code/sdk
14
- npm install -D @types/node # required: the declarations reference Node's stdlib
15
- ```
16
-
17
- Node 20 or newer. `@types/node` is a peer of your own toolchain rather than a
18
- dependency of this package, so a TypeScript consumer installs it explicitly —
19
- without it the declarations that name `ChildProcess`, `Readable` and friends do
20
- not resolve. The MSP wire declarations are **bundled into the tarball**, so
21
- nothing else is needed to typecheck against the published package.
22
-
23
- **This is a 0.x release and it is experimental.** There is no stability promise
24
- before 1.0: any release may change or remove API you are using. Pin an exact
25
- version, and read the changelog before moving off it.
26
-
27
- ## The loop
28
-
29
- ```sh
30
- cd projects/tbh
31
- npm ci # installs the pinned workspace devDependencies from the lockfile
32
- npm run check # tsc --strict over both packages
33
- npm test # build + node:test; TEST-009 builds/runs the Rust serve-fixture
34
- ```
35
-
36
- CI runs exactly this in the non-required, path-filtered `tbh-muse-sdk-ts`
37
- workflow.
38
-
39
- ## Consuming this package (#211 and #210)
40
-
41
- Both in-repo consumers import from the package barrel; nothing reaches into
42
- `src/` paths, and nothing re-derives a rule the core already holds.
43
-
44
- **Fold a canned or live event stream.** `Session` composes the two stores, the
45
- SS4.13 pending set, and the per-turn handles. Feed it `ViewEvent`s — a wire
46
- notification's `method` paired with its generated params object — and read the
47
- fold:
48
-
49
- ```ts
50
- import { readSessionDurability, Session } from "@muse-code/sdk";
51
-
52
- const session = new Session({
53
- sessionId,
54
- durability: readSessionDurability(initializeResult), // never defaulted; see below
55
- });
56
-
57
- const turn = session.turn(turnId); // a handle, before or after its events
58
-
59
- // Events enter HERE and only here — `session.fold` is read-only, so turn
60
- // routing cannot be bypassed. Nothing below settles until they arrive.
61
- for (const event of viewEvents) session.apply(event); // {method, params} per notification
62
-
63
- for await (const item of turn.items()) render(item);
64
- const outcome = await turn.completed; // settles on EVERY no-run exit (INV-014)
23
+ npm install -D @types/node # required for TypeScript consumers
65
24
  ```
66
25
 
67
- `turn.completed` resolves `{kind: "completed"}`, `{kind: "unqueued"}` for a
68
- reclaimed queued submit, or `{kind: "terminalUnknown"}` after an ephemeral host
69
- death. For the launch-failure exit (`"deferred_start_failed"`) branch on the
70
- wire marker via `isLaunchFailure(outcome)` — `terminal: "failed"` plus
71
- `error.kind: "launchError"`. Do **not** read `observedStart: false` as that
72
- marker: it is a session-local observation and is also false for a legitimate
73
- terminal-first fold (a single-shot turn, a gap fill, or a consumer that
74
- attached mid-stream).
75
-
76
- The two async iterators end when the turn settles and never on a local
77
- timeout. `items()` replays what the fold already holds for the turn before its
78
- live tail. **`deltas()` is live-only** — nothing is replayed to a
79
- late-attached iterator, because the store keeps accumulated field text
80
- (`fold.items.accumulated(itemId)`) rather than the delta event sequence.
26
+ Node 20 or newer. `@types/node` is declared as an **optional peer
27
+ dependency**: a JavaScript consumer needs nothing, while a TypeScript
28
+ consumer installs it explicitly — without it the declarations that name
29
+ `ChildProcess`, `Readable` and friends do not resolve.
81
30
 
82
- **A dropped delivery is a pause, not a hole.** When a slow subscription
83
- overflows, the host sends `view/gap` and the SDK recovers by the SS4.8
84
- splice-fill without the consumer doing anything: `session.fold.current` goes
85
- false, the live tail is held, `view/page` walks `(after, next)`, and the paged
86
- prefix then the held tail reach the iterators in cursor order. Deltas lost in
87
- the hole stay lost by design (the fill lands final item states, not the delta
88
- sequence). A fill that cannot complete is reported — never swallowed:
31
+ You also need the Muse Code CLI: a `muse` binary on `PATH`, or an explicit
32
+ path passed at spawn time.
89
33
 
90
- ```ts
91
- session.onGapError((failure) => {
92
- // MuseGapFillError: `reason` ("noConnection" | "pageFailed" | "pageStalled")
93
- // plus the hole's own opaque `after`/`next`.
94
- report(failure);
95
- // `session.fold.current` stays false and `session.fold.pendingGap` still
96
- // names the hole; recovering from there (a resume, or D-030's re-anchor) is
97
- // the consumer's call.
98
- });
99
- ```
34
+ **This package versions in lockstep with Muse Code**: the SDK version is the
35
+ Muse Code release it ships with — `@muse-code/sdk X.Y.Z` pairs with Muse Code
36
+ `X.Y.Z`. The stable MSP surface follows the product's compatibility posture:
37
+ evolution is additive, and a breaking change follows a documented deprecation
38
+ and changelog path. Surfaces marked experimental (`x-msp-openness`)
39
+ may change or be removed with a changelog entry and no deprecation window. Pin an
40
+ exact version, and read the changelog before moving off it.
100
41
 
101
- **Open sessions and submit through the facade.** `MuseClient.spawn` owns the
102
- host, runs the SS1.4 handshake, and reads `sessionDurability` off it, so a
103
- consumer never re-derives the SS2.13.1 profile by hand:
42
+ ## Use
104
43
 
105
44
  ```ts
106
45
  import { MuseClient } from "@muse-code/sdk";
107
46
 
108
47
  const client = await MuseClient.spawn({
109
48
  museBin: "muse",
110
- args: ["serve"], // spawn passes args through verbatim; a bare `muse` is the TUI
111
- clientInfo: { name: "dm", version: "1.0.0" },
49
+ args: ["serve"],
50
+ clientInfo: { name: "my-app", version: "1.0.0" },
112
51
  });
113
52
 
114
- const session = await client.startSession({ workspaceRoot });
115
- // or: await client.resumeSession({ sessionId, cursor })
116
- session.opening; // the typed wire result, by verb
53
+ const session = await client.startSession({ workspaceRoot: process.cwd() });
117
54
 
118
- const turn = await session.sendUserTurn({ input: [{ type: "text", text }] });
119
- for await (const item of turn.items()) render(item);
55
+ const turn = await session.sendUserTurn({
56
+ input: [{ type: "text", text: "Summarize this repository." }],
57
+ });
58
+ for await (const item of turn.items()) console.log(item);
120
59
  await turn.completed;
121
60
 
122
- session.onApproval(async (request) => ({ choiceId: request.availableChoices[0].choiceId }));
123
- session.onApprovalError((failure) => report(failure));
124
-
125
- await client.close(); // orderly SS2.1.2 shutdown; NOT a death
61
+ await client.close();
126
62
  ```
127
63
 
128
- The returned `Turn` IS the handle this session routes events to — not a copy —
129
- and the submit is visible as an optimistic SS4.13 pending entry from the moment
130
- it is sent, before the ack. Approval choices are **server-minted only** (D-006):
131
- a `choiceId` the request never offered is refused before the frame is built and
132
- reported to `onApprovalError`. Registering no handler at all is the supported
133
- posture, not a degraded one (D-008): the client runs under the server's own
134
- default-deny and this SDK parks nothing.
64
+ `turn.items()` replays what the session already holds before its live tail;
65
+ `turn.deltas()` is live-only. `turn.completed` settles on every exit, so an
66
+ awaited turn can never hang on a session that ended without an answer.
135
67
 
136
- `session.apply(...)` returns `io` alongside `retirements` — a promise for the
137
- client→server I/O that event triggered (an SS4.13 replay, an approval decision).
138
- Awaiting it is optional and always safe; it never rejects.
139
-
140
- **Discharge the host-death obligation.** Read the profile from the handshake
141
- once, then hand every death notification to the session. SS2.13.3b names TWO —
142
- the process exit AND transport EOF — and `MuseClient` reports the EOF half
143
- itself, because it is the only layer that knows whether the close was its own:
68
+ To approve tool use programmatically, register a handler on the session;
69
+ approval choices are server-minted, and a decision the request never offered
70
+ is refused and reported rather than sent:
144
71
 
145
72
  ```ts
146
- const discharge = session.hostExited(await child.exit);
147
- // or, from MuseClient's own wiring: session.hostExited({ kind: "transportEof" })
148
- ```
149
-
150
- Exit 0 is not a death and discharges nothing. A **durable** session's abnormal
151
- death also discharges nothing — its terminals arrive on resume (FM-001) — and
152
- only rejects the live turn-waits with the classification. An **ephemeral** one
153
- marks every still-`inProgress` item terminal-unknown, retires every pending
154
- command, refuses further events, and permanently refuses `commandId` replay
155
- (tdd SS2.13.3b) — across every session the same client opens, and it withholds
156
- `resumeSession` for the discharged session rather than reattaching. An **unrecognized** `sessionDurability` is treated exactly
157
- like ephemeral: SS2.13.1 forbids inferring a durability guarantee from a value
158
- this SDK predates, and the absent-means-durable rule keys on the member being
159
- *missing*, not on its value being unfamiliar.
160
-
161
- **Report defects here, not in the adapter.** A fold rule the core gets wrong
162
- is a #14990 bug; a fixture the fold cannot consume is a #210 fixture request.
163
- Neither is ever patched locally in `@muse-code/acp` (spec Sibling lanes).
164
-
165
- ## What is here (slices 1 and 2, and slice 3 in full)
166
-
167
- - `src/fingerprint.ts` — the schema staleness anchor. `EXPECTED_SCHEMA_
168
- FINGERPRINT` is test-bound to `schema/msp/stable/manifest.json`, so a schema
169
- advance that forgets the SDK reds this lane. **A red fingerprint means
170
- "re-pin after a schema advance", not "the SDK is broken"** — the failure
171
- message says so.
172
- - `src/fold/item-store.ts` — the item half of the SS4 fold: upsert-by-revision
173
- (replace iff strictly higher) and per-field delta accumulation whose
174
- concatenation equals the final committed value.
175
- - `src/fold/state-store.ts` — the session-state half: replace-wholesale,
176
- cursor-ordered, latest-wins; an explicit `null` clears and is a fact.
177
- - `src/pending/pending-command-set.ts` — the complete SS4.13 `PendingCommand`
178
- fold (decision record D-032): deterministic anchoring, the four retirement
179
- arms, nothing-admitted holds, queue-movement re-verification, the five
180
- snapshot-join arms with `queuedTurns` reordering, the no-snapshot reconnect
181
- rules, and the ephemeral-profile discard obligation.
182
- - `src/connection/connection.ts` — the transport-less NDJSON connection:
183
- awaited serialized writes, bounded inbound framing, request correlation,
184
- typed `data.kind` errors, server-request routing, and the UUIDv7
185
- `commandId` retry/value-identical-ack contract. A process binding supplies
186
- the duplex transport.
187
- - `src/connection/spawn.ts` — the owned Node stdio process binding. Before
188
- handshake it exposes no send method; `initialize` sends the SS1.4 sequence
189
- exactly once and returns the ready connection, negotiated capabilities,
190
- fingerprint warning (when any), stderr-forwarding seam, and the bounded
191
- close path. `MuseServeChild` captures a bounded 8 KiB / 100-line stderr
192
- tail from birth, maps every process exit through the SS2.11 table, and
193
- exposes the same owned child on the handshake and initialized connection.
194
- `close()` is the only termination surface and it is bounded: stdin EOF
195
- first so the host can drain (SS2.1.2), then `SIGTERM` and one `SIGKILL`
196
- escalation once `shutdownTimeoutMs` (default 30 s) has passed, and it
197
- resolves on the exit actually observed — so a wedged host is the crash row
198
- carrying the delivered signal, never a synthesized clean shutdown. It ends
199
- once the child's stdio closes; on POSIX the SDK spawns the host as the
200
- leader of an SDK-owned process group and the TERM/KILL stages signal that
201
- group ([#22777](https://github.com/mslsrc/tbh/issues/22777)), so a
202
- grandchild that inherited the host's stdout is ended with the host and
203
- cannot stall the close. On Windows the ladder still signals only the
204
- child — no subtree containment is claimed there (spec FR-017b).
205
- - `src/fold/session-fold.ts` — the two stores bound to the generated view
206
- types, plus the turn lifecycle and the approval/user-input view events as
207
- fold inputs. A compile-time assertion fails if a later #206 enrollment adds
208
- a view notification the fold would silently ignore.
209
- - `src/facade/session.ts` — `Session`: the fold, the pending set, per-turn
210
- event routing, and the SS2.13.3b host-death discharge.
211
- - `src/facade/gap-fill.ts` — the SS4.8 splice-fill: the live-frame buffer, the
212
- `view/page` walk bounded by progress rather than by an attempt cap, and the
213
- cursor-equality overlap discard. Only the splice-fill path is built; D-030's
214
- re-anchor alternative is the #208 lane's spec work.
215
- - `src/facade/turn-handle.ts` — `TurnHandle`: the SS3.1.4 turn-wait and the
216
- fold-backed `items()`/`deltas()` iterators.
217
- - `src/facade/host-death.ts` — reading `sessionDurability` off the handshake
218
- (SS2.13.1) and classifying an exit as abnormal (SS2.11).
219
- - `test/helpers/tolerance-corpus-runner.ts` — #210's workspace-only TEST-008
220
- runner. It discovers the three `sdk-tolerance` manifests, feeds item events
221
- through `ItemStore<Item>`, and preserves every notification for lossless
222
- tolerance assertions. It does not duplicate #14990 T019's `SessionFold`.
223
-
224
- ## `qa/` — the `--area sdk` black-box QA driver
225
-
226
- `qa/` is **not part of the shipped facade**. It is a QA driver (issue #22764,
227
- spec 14990 Scenario 6) that plays an external integrator: it reaches
228
- `@muse-code/sdk` only through `src/index.ts`, spawns the real `tbh serve` binary
229
- over MSP stdio, and tees every wire byte so each finding can be stated as
230
- "public API said X, wire said Y". A finding without both halves is refused at
231
- construction, and the driver never files anything — the auto-qa procedure
232
- (`specs/2159-auto-qa-skill`, `--area sdk`) does that.
233
-
234
- ```sh
235
- cd projects/tbh
236
- CARGO_TARGET_DIR=$(scripts/probe-env.sh --print) cargo build -p tbh-cli --bin tbh
237
- export MUSE_QA_SDK_BIN=$CARGO_TARGET_DIR/debug/tbh
238
- npm run qa:sdk -- --json /tmp/sdk-qa.json --markdown /tmp/sdk-qa.md
73
+ session.onApproval(async (request) => ({
74
+ choiceId: request.availableChoices[0].choiceId,
75
+ }));
239
76
  ```
240
77
 
241
- Without `MUSE_QA_SDK_BIN` (or a `tbh` in `target/debug`) the driver exits 2 and
242
- runs nothing: it never substitutes a fixture host, because a green pass against
243
- a canned transcript would prove nothing about the product. For the same reason
244
- its real-binary contract arm reports a loud non-pass rather than a silent skip —
245
- building `tbh` is a multi-minute Rust build that does not belong in this Node
246
- lane, so CI runs the rest and the QA procedure, which always has a binary,
247
- carries that coverage.
248
-
249
- Every finding also carries a **facade-vs-binary** component decided by replaying
250
- the captured host frames into a fresh SDK with no binary present. `facade` is a
251
- bug in this package; `binary` is a bug in `tbh`.
252
-
253
- ## What is not here yet, and what it waits on
254
-
255
- No gap below waits on a wire shape any more — #24021 enrolled the last one,
256
- `view/gap` — and the facade itself is complete: `MuseClient.spawn`, the two
257
- session verbs returning a `Session`, `sendUserTurn`, and
258
- `session.onApproval`'s idempotent `approval/decide` landed with #23980 against
259
- the #22946 command-plane enrollment, and the SS4.8 in-iterator splice-fill
260
- landed with T032 against the #24021 one. The condition
261
- and the command that re-derives what remains live once, in
262
- `specs/14990-muse-sdk/tasks.md` under "The slice-3 blocker" — INV-001 holds
263
- with no exception, so a shape the generated layer lacks is a #206 enrollment
264
- request, never a local interface.
265
-
266
- | Missing | Waits on |
267
- | --- | --- |
268
- | Snapshot ingestion + splice against a real `Snapshot` (FR-008, TEST-006) | Nothing shape-side: the object is the generated `ViewSnapshot` (#22946) and A-5's two one-family fixtures are in `schema/msp/transcripts/`. Sequenced behind spec 210 T061's host-generated corpus regeneration ([#18953](https://github.com/mslsrc/tbh/issues/18953)), which flips those fixtures' provenance. The store-level seed+splice algebra IS covered. |
269
- | Corpus replay + checkpoint equality (TEST-001/007) | Its own PR (plan slice 1c): the golden transcripts LANDED with [#14951](https://github.com/par-msl/tbh/pull/14951) (merged 2026-08-13) and sit in `schema/msp/transcripts/`. Same T061 sequencing as the row above. |
270
- | D-030's re-anchor recovery (drop folded state, re-anchor at the latest compaction snapshot) | The owning [#208](https://github.com/mslsrc/tbh/issues/208) lane's spec work: when each path is sane, and how a re-anchor interacts with buffered live events, is theirs to state (tdd SS4.8). This package builds the OTHER sanctioned path, splice-fill, which is complete (T032/FR-020) — the server requires neither and holds no partial-fill state. |
271
-
272
- ## Why the stores are generic
78
+ Status: developer preview. The facade — spawn, session open/resume, turns,
79
+ approvals, and recovery after dropped deliveries — is complete and covered by
80
+ the conformance suites in the source repository.
273
81
 
274
- The concrete item/event payload types are generated, not written here
275
- (INV-001). The stores were built while the session-view plane was still being
276
- enrolled, so they state only the *algebraic precondition* each rule needs —
277
- an item has an identity and a revision — and take the payload as a type
278
- parameter. #14953 landed 2026-08-13, and `SessionFold` now binds those
279
- parameters to `@muse-code/msp`'s types with no change to the fold logic and no
280
- protocol shape ever restated locally.
82
+ ## Documentation
281
83
 
282
- The same discipline is why `ItemStore.markEphemeralHostDeath` asks its caller
283
- for an `isInProgress` probe instead of reading `item.status` itself: the store
284
- stays wire-shape-blind, and `src/facade/host-death.ts` supplies the probe
285
- where `tsc` checks the field and its value against the generated `Item`.
84
+ - Guides, cookbook recipes, and the protocol reference:
85
+ <https://meta-models.github.io/muse-code-sdk/>
86
+ - TypeScript API reference:
87
+ <https://meta-models.github.io/muse-code-sdk/next/generated/sdk/>
88
+ - Source and issues: <https://github.com/meta-models/muse-code-sdk>
@@ -13,7 +13,8 @@
13
13
  * would be a #206 enrollment request (INV-001), never a local interface.
14
14
  */
15
15
  import type { Connection } from "../connection/connection.js";
16
- import type { ApprovalDecideParams, ApprovalRequestParams } from "../msp.js";
16
+ import type { DeepReadonly } from "../fold/session-fold.js";
17
+ import type { ApprovalDecideParams, ApprovalRequestParams, ApprovalUpdatedParams } from "../msp.js";
17
18
  /**
18
19
  * What an approval handler answers with: a choice the SERVER offered, and
19
20
  * optional feedback. Composed from the generated decide params, so "the client
@@ -73,4 +74,23 @@ export declare class ApprovalRouter {
73
74
  * parks nothing — no queued decision, no synthesized denial, no local hold.
74
75
  */
75
76
  requested(params: ApprovalRequestParams): Promise<void> | undefined;
77
+ /**
78
+ * An `approval/updated` folded onto a STILL-PENDING approval (#36949).
79
+ *
80
+ * A multi-stage approval advances `currentRequirementId` through this frame
81
+ * 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.
86
+ *
87
+ * The update alone carries none of the request-shape members the handler is
88
+ * typed on, but the fold retains the original request and every identity
89
+ * member is stable across the stages of ONE approval, so the merged request
90
+ * below is honest (`REFRESH_FROM_*` above pins the split). Feeding it
91
+ * through {@link requested} reuses the per-stage latch, so an update whose
92
+ * requirement was already decided — and any later re-issued request for the
93
+ * stage this update decided — authors nothing.
94
+ */
95
+ updated(requested: DeepReadonly<ApprovalRequestParams>, params: ApprovalUpdatedParams): Promise<void> | undefined;
76
96
  }
@@ -25,6 +25,35 @@ const DECIDE_FORWARDED = [
25
25
  "sessionId",
26
26
  "feedback",
27
27
  ];
28
+ /**
29
+ * The #36949 refreshed-request merge, hand-listed by SOURCE. Stage-scoped
30
+ * members come from the `approval/updated` frame in hand; identity members
31
+ * come from the fold's retained request (stable across the stages of one
32
+ * approval). The `AssertNever` makes a regenerated member — REQUIRED or
33
+ * OPTIONAL — a build error until someone says which side of the merge it
34
+ * comes from: an optional addition (e.g. `subagentOrigin`, #36182) would
35
+ * otherwise just vanish from the refreshed request, `tsc`-green.
36
+ */
37
+ const REFRESH_FROM_UPDATE = [
38
+ "availableChoices",
39
+ "currentRequirementId",
40
+ "sessionId",
41
+ "sourceRange",
42
+ "subagentOrigin",
43
+ "subject",
44
+ "viewCursor",
45
+ ];
46
+ const REFRESH_FROM_REQUEST = [
47
+ "approvalId",
48
+ "itemId",
49
+ "judgeEscalated",
50
+ "protectedWrite",
51
+ "rawArgs",
52
+ "taskId",
53
+ "toolCallId",
54
+ "toolName",
55
+ "turnId",
56
+ ];
28
57
  export class ApprovalRouter {
29
58
  #sessionId;
30
59
  #connection;
@@ -42,6 +71,15 @@ export class ApprovalRouter {
42
71
  * per stage" holds absolutely.
43
72
  */
44
73
  #decidedStages = new Set();
74
+ /**
75
+ * Approvals whose `approval/decide` ACK came back `terminal: true`: the host
76
+ * closed the whole approval on that decision (a rule that also satisfied the
77
+ * remaining stages), so no later stage can need this consumer. Kept beside
78
+ * the stage latch because the runtime records only the RESOLVED stage
79
+ * (#37538), letting the view fold emit one trailing `stageResolved` update
80
+ * with a frontier the host already closed, right before `approval/resolved`.
81
+ */
82
+ #terminalApprovals = new Set();
45
83
  constructor(sessionId, connection) {
46
84
  this.#sessionId = sessionId;
47
85
  this.#connection = connection;
@@ -81,6 +119,60 @@ export class ApprovalRouter {
81
119
  this.#decidedStages.add(stage);
82
120
  return this.#decide(params, handler);
83
121
  }
122
+ /**
123
+ * An `approval/updated` folded onto a STILL-PENDING approval (#36949).
124
+ *
125
+ * A multi-stage approval advances `currentRequirementId` through this frame
126
+ * ALONE on the notification plane — the SS5.6 item-3 re-issue on stage
127
+ * advance is the protected `approval/request` SERVER-REQUEST dual, which is
128
+ * not enrolled here (SHAPE NOTE above) — so waiting for a re-issued
129
+ * `approval/requested` notification leaves the new stage undecided and the
130
+ * turn pending forever.
131
+ *
132
+ * The update alone carries none of the request-shape members the handler is
133
+ * typed on, but the fold retains the original request and every identity
134
+ * member is stable across the stages of ONE approval, so the merged request
135
+ * below is honest (`REFRESH_FROM_*` above pins the split). Feeding it
136
+ * through {@link requested} reuses the per-stage latch, so an update whose
137
+ * requirement was already decided — and any later re-issued request for the
138
+ * stage this update decided — authors nothing.
139
+ */
140
+ updated(requested, params) {
141
+ // `alreadyTerminal` says the host holds a durable terminal whose resolve
142
+ // frame has not landed yet; a decision against it can only bounce -32051,
143
+ // so asking the consumer for one would be a pointless question.
144
+ if (params.change.kind === "alreadyTerminal")
145
+ return undefined;
146
+ // Same fact, learned from OUR OWN decide ack: `terminal: true` means the
147
+ // host closed the whole approval on that decision, and the one trailing
148
+ // `stageResolved` update the fold can still emit (#37538) names a frontier
149
+ // that no longer exists — re-asking would prompt the consumer for a stage
150
+ // the host already closed, and the decide could only bounce -32051.
151
+ if (this.#terminalApprovals.has(requested.approvalId))
152
+ return undefined;
153
+ const refreshed = {
154
+ approvalId: requested.approvalId,
155
+ availableChoices: params.availableChoices,
156
+ currentRequirementId: params.currentRequirementId,
157
+ itemId: requested.itemId,
158
+ judgeEscalated: requested.judgeEscalated,
159
+ protectedWrite: requested.protectedWrite,
160
+ rawArgs: requested.rawArgs,
161
+ sessionId: params.sessionId,
162
+ sourceRange: params.sourceRange,
163
+ subject: params.subject,
164
+ taskId: requested.taskId,
165
+ toolCallId: requested.toolCallId,
166
+ toolName: requested.toolName,
167
+ turnId: requested.turnId,
168
+ viewCursor: params.viewCursor,
169
+ };
170
+ // Omitted rather than nulled, like `feedback` above: absent on the
171
+ // parent's own approvals by contract (#36182 `skip_serializing_if`).
172
+ if (params.subagentOrigin !== undefined)
173
+ refreshed.subagentOrigin = params.subagentOrigin;
174
+ return this.requested(refreshed);
175
+ }
84
176
  static #stageKey(params) {
85
177
  const requirement = params.currentRequirementId;
86
178
  return `${params.approvalId} ${requirement.approvalId}:${String(requirement.sourceIndex)}`;
@@ -143,7 +235,11 @@ export class ApprovalRouter {
143
235
  // No explicit `commandId`: unlike `sendUserTurn`, nothing here needs the
144
236
  // id before the ack, so `Connection.command()` mints and stamps it — and
145
237
  // its own SS3.1.1 retry then reuses that id for free.
146
- await connection.command("approval/decide", decideParams);
238
+ const ack = await connection.command("approval/decide", decideParams);
239
+ // A `terminal: true` ack closed the WHOLE approval; remember it so the
240
+ // trailing stale-frontier update #37538 permits cannot re-prompt.
241
+ if (ack["terminal"] === true)
242
+ this.#terminalApprovals.add(params.approvalId);
147
243
  }
148
244
  catch (error) {
149
245
  this.#report({ approvalId: params.approvalId, error, kind: "submitFailed" });
@@ -43,13 +43,12 @@ import type { InitializeParams, InitializeResult, SessionResumeParams, SessionSt
43
43
  /**
44
44
  * Caller-facing options for `session/start` (tdd SS2.5.1).
45
45
  *
46
- * `config` is excluded as well as `commandId`: [`SessionConfig`] declares no
47
- * members and is reserved for a future Configuration section, so there is
48
- * nothing a caller could put in it today.
46
+ * `config` is excluded as well as `commandId` until the facade implements the
47
+ * required `sessionMcp` grant check and forwarding.
49
48
  */
50
49
  export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "config">>;
51
50
  /** Caller-facing options for `session/resume` (tdd SS2.5.2). */
52
- export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId">>;
51
+ export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId" | "config">>;
53
52
  /**
54
53
  * Options for building a `MuseClient` around a connection you already own.
55
54
  * `MuseClient.spawn` fills these in for you; supply them yourself only when
@@ -41,8 +41,9 @@ import { DiscardedSessions } from "./discarded.js";
41
41
  import { isAbnormalHostDeath, readSessionDurability } from "./host-death.js";
42
42
  import { Session } from "./session.js";
43
43
  /**
44
- * Every `StartParams` member `startSession` forwards. `config` is allow-listed
45
- * as intentionally unforwardable: [`SessionConfig`] declares no members yet.
44
+ * Every `StartParams` member `startSession` forwards. `config` is temporarily
45
+ * excluded until the facade can pair forwarding with the required
46
+ * `sessionMcp` grant check.
46
47
  */
47
48
  const START_FORWARDED = [
48
49
  "approvalMode",
@@ -51,7 +52,10 @@ const START_FORWARDED = [
51
52
  "workspaceRoot",
52
53
  "modelId",
53
54
  ];
54
- /** Every `ResumeParams` member `resumeSession` forwards. */
55
+ /**
56
+ * Every `ResumeParams` member `resumeSession` forwards. `config` has the same
57
+ * temporary capability-check boundary as the start facade above.
58
+ */
55
59
  const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history"];
56
60
  /**
57
61
  * Your entry point to the SDK.
@@ -253,6 +253,18 @@ export class Session {
253
253
  if (outcome.kind === "approvalPending")
254
254
  this.#approvalRequested(known.params, tasks);
255
255
  break;
256
+ case "approval/updated":
257
+ // FR-019's outbound half too (#36949): a stage advance is delivered by
258
+ // this frame alone on the notification plane, so it must drive the
259
+ // handler — the why and the request merge live on
260
+ // `ApprovalRouter.updated`. The same fold verdict gates it: an update
261
+ // the fold IGNORED (unknown or already-resolved approval) authors
262
+ // nothing, and the verdict itself carries the retained request the
263
+ // merge needs.
264
+ if (outcome.kind === "approvalPending") {
265
+ this.#approvalUpdated(outcome.requested, known.params, tasks);
266
+ }
267
+ break;
256
268
  // Folded, deliberately NOT routed to a turn handle. Listed rather than
257
269
  // defaulted so this switch is exhaustive over `ViewEvent`: the fold's
258
270
  // `AssertNever` forces each new #206 view notification into that union,
@@ -265,23 +277,19 @@ export class Session {
265
277
  case "view/gap":
266
278
  case "turn/retracted": // the turn still reaches its own terminal
267
279
  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
280
  case "approval/resolved":
276
281
  case "userInput/requested":
277
282
  case "userInput/settled":
278
283
  case "session/modelChanged":
284
+ case "session/reasoningEffortChanged":
279
285
  case "session/goalChanged":
280
286
  case "session/todoListChanged":
281
287
  case "session/branchChanged":
282
288
  case "session/tokenUsage":
283
289
  case "session/contextUsage":
284
290
  case "session/approvalModeChanged":
291
+ case "session/modelRouteUnserved":
292
+ case "session/nameChanged":
285
293
  break;
286
294
  default: {
287
295
  // Compile-time exhaustiveness. Runtime tolerance of a newer host's
@@ -592,6 +600,13 @@ export class Session {
592
600
  if (decided !== undefined)
593
601
  tasks.push(decided.then(() => []));
594
602
  }
603
+ /** The #36949 stage-advance re-route; the merge lives on `ApprovalRouter.updated`. */
604
+ #approvalUpdated(requested, params, tasks) {
605
+ const decided = this.#approvals.updated(requested, params);
606
+ // Awaitable through `io`, same as `#approvalRequested` above.
607
+ if (decided !== undefined)
608
+ tasks.push(decided.then(() => []));
609
+ }
595
610
  #itemsOfTurn(turnId) {
596
611
  return this.#fold.items.list().filter((item) => item.turnId === turnId);
597
612
  }
@@ -606,11 +621,10 @@ export class Session {
606
621
  retirements.push(materialized);
607
622
  }
608
623
  // `!= 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;
624
+ // on the wire (spec Edge Cases; tdd SS4.5.6 example). A `!== undefined`
625
+ // guard let null through and minted a phantom turn keyed `null`,
626
+ // attributing the userShell item and its deltas to it (#23557).
627
+ const turnId = item.turnId;
614
628
  if (turnId != null)
615
629
  this.#handle(turnId).pushItem(item);
616
630
  const buffered = this.#unattributedDeltas.get(item.itemId);
@@ -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:03312c213efd14277a0e0a102f70adeae497a469ca4edf7242f479953ed758b7";
16
+ export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7469c9e352e67def4a59df7e439984d7194fa351e1c8b7abb34060fd977ced81";
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:03312c213efd14277a0e0a102f70adeae497a469ca4edf7242f479953ed758b7";
16
+ export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7469c9e352e67def4a59df7e439984d7194fa351e1c8b7abb34060fd977ced81";
17
17
  /**
18
18
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
19
  *