@muse-code/sdk 0.1.0 → 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,270 +1,88 @@
1
1
  # `@muse-code/sdk`
2
2
 
3
- The MSP TypeScript facade (tdd SS7.1). Owning spec: `specs/14990-muse-sdk/`.
3
+ The TypeScript SDK for Muse Code: a typed Node client for driving a Muse Code
4
+ agent over the Muse Session Protocol (MSP).
4
5
 
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.
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.
9
14
 
10
- **Nothing is published to npm** before 1.0 (tdd D-013).
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.
11
18
 
12
- ## The loop
19
+ ## Install
13
20
 
14
21
  ```sh
15
- cd projects/tbh
16
- npm ci # installs the pinned workspace devDependencies from the lockfile
17
- npm run check # tsc --strict over both packages
18
- npm test # build + node:test; TEST-009 builds/runs the Rust serve-fixture
22
+ npm install @muse-code/sdk
23
+ npm install -D @types/node # required for TypeScript consumers
19
24
  ```
20
25
 
21
- CI runs exactly this in the non-required, path-filtered `tbh-muse-sdk-ts`
22
- workflow.
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.
23
30
 
24
- ## Consuming this package (#211 and #210)
31
+ You also need the Muse Code CLI: a `muse` binary on `PATH`, or an explicit
32
+ path passed at spawn time.
25
33
 
26
- Both in-repo consumers import from the package barrel; nothing reaches into
27
- `src/` paths, and nothing re-derives a rule the core already holds.
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.
28
41
 
29
- **Fold a canned or live event stream.** `Session` composes the two stores, the
30
- SS4.13 pending set, and the per-turn handles. Feed it `ViewEvent`s — a wire
31
- notification's `method` paired with its generated params object — and read the
32
- fold:
33
-
34
- ```ts
35
- import { readSessionDurability, Session } from "@muse-code/sdk";
36
-
37
- const session = new Session({
38
- sessionId,
39
- durability: readSessionDurability(initializeResult), // never defaulted; see below
40
- });
41
-
42
- const turn = session.turn(turnId); // a handle, before or after its events
43
-
44
- // Events enter HERE and only here — `session.fold` is read-only, so turn
45
- // routing cannot be bypassed. Nothing below settles until they arrive.
46
- for (const event of viewEvents) session.apply(event); // {method, params} per notification
47
-
48
- for await (const item of turn.items()) render(item);
49
- const outcome = await turn.completed; // settles on EVERY no-run exit (INV-014)
50
- ```
51
-
52
- `turn.completed` resolves `{kind: "completed"}`, `{kind: "unqueued"}` for a
53
- reclaimed queued submit, or `{kind: "terminalUnknown"}` after an ephemeral host
54
- death. For the launch-failure exit (`"deferred_start_failed"`) branch on the
55
- wire marker via `isLaunchFailure(outcome)` — `terminal: "failed"` plus
56
- `error.kind: "launchError"`. Do **not** read `observedStart: false` as that
57
- marker: it is a session-local observation and is also false for a legitimate
58
- terminal-first fold (a single-shot turn, a gap fill, or a consumer that
59
- attached mid-stream).
60
-
61
- The two async iterators end when the turn settles and never on a local
62
- timeout. `items()` replays what the fold already holds for the turn before its
63
- live tail. **`deltas()` is live-only** — nothing is replayed to a
64
- late-attached iterator, because the store keeps accumulated field text
65
- (`fold.items.accumulated(itemId)`) rather than the delta event sequence.
66
-
67
- **A dropped delivery is a pause, not a hole.** When a slow subscription
68
- overflows, the host sends `view/gap` and the SDK recovers by the SS4.8
69
- splice-fill without the consumer doing anything: `session.fold.current` goes
70
- false, the live tail is held, `view/page` walks `(after, next)`, and the paged
71
- prefix then the held tail reach the iterators in cursor order. Deltas lost in
72
- the hole stay lost by design (the fill lands final item states, not the delta
73
- sequence). A fill that cannot complete is reported — never swallowed:
74
-
75
- ```ts
76
- session.onGapError((failure) => {
77
- // MuseGapFillError: `reason` ("noConnection" | "pageFailed" | "pageStalled")
78
- // plus the hole's own opaque `after`/`next`.
79
- report(failure);
80
- // `session.fold.current` stays false and `session.fold.pendingGap` still
81
- // names the hole; recovering from there (a resume, or D-030's re-anchor) is
82
- // the consumer's call.
83
- });
84
- ```
85
-
86
- **Open sessions and submit through the facade.** `MuseClient.spawn` owns the
87
- host, runs the SS1.4 handshake, and reads `sessionDurability` off it, so a
88
- consumer never re-derives the SS2.13.1 profile by hand:
42
+ ## Use
89
43
 
90
44
  ```ts
91
45
  import { MuseClient } from "@muse-code/sdk";
92
46
 
93
47
  const client = await MuseClient.spawn({
94
48
  museBin: "muse",
95
- args: ["serve"], // spawn passes args through verbatim; a bare `muse` is the TUI
96
- clientInfo: { name: "dm", version: "1.0.0" },
49
+ args: ["serve"],
50
+ clientInfo: { name: "my-app", version: "1.0.0" },
97
51
  });
98
52
 
99
- const session = await client.startSession({ workspaceRoot });
100
- // or: await client.resumeSession({ sessionId, cursor })
101
- session.opening; // the typed wire result, by verb
53
+ const session = await client.startSession({ workspaceRoot: process.cwd() });
102
54
 
103
- const turn = await session.sendUserTurn({ input: [{ type: "text", text }] });
104
- 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);
105
59
  await turn.completed;
106
60
 
107
- session.onApproval(async (request) => ({ choiceId: request.availableChoices[0].choiceId }));
108
- session.onApprovalError((failure) => report(failure));
109
-
110
- await client.close(); // orderly SS2.1.2 shutdown; NOT a death
61
+ await client.close();
111
62
  ```
112
63
 
113
- The returned `Turn` IS the handle this session routes events to — not a copy —
114
- and the submit is visible as an optimistic SS4.13 pending entry from the moment
115
- it is sent, before the ack. Approval choices are **server-minted only** (D-006):
116
- a `choiceId` the request never offered is refused before the frame is built and
117
- reported to `onApprovalError`. Registering no handler at all is the supported
118
- posture, not a degraded one (D-008): the client runs under the server's own
119
- default-deny and this SDK parks nothing.
120
-
121
- `session.apply(...)` returns `io` alongside `retirements` — a promise for the
122
- client→server I/O that event triggered (an SS4.13 replay, an approval decision).
123
- Awaiting it is optional and always safe; it never rejects.
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.
124
67
 
125
- **Discharge the host-death obligation.** Read the profile from the handshake
126
- once, then hand every death notification to the session. SS2.13.3b names TWO —
127
- the process exit AND transport EOF — and `MuseClient` reports the EOF half
128
- 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:
129
71
 
130
72
  ```ts
131
- const discharge = session.hostExited(await child.exit);
132
- // or, from MuseClient's own wiring: session.hostExited({ kind: "transportEof" })
133
- ```
134
-
135
- Exit 0 is not a death and discharges nothing. A **durable** session's abnormal
136
- death also discharges nothing — its terminals arrive on resume (FM-001) — and
137
- only rejects the live turn-waits with the classification. An **ephemeral** one
138
- marks every still-`inProgress` item terminal-unknown, retires every pending
139
- command, refuses further events, and permanently refuses `commandId` replay
140
- (tdd SS2.13.3b) — across every session the same client opens, and it withholds
141
- `resumeSession` for the discharged session rather than reattaching. An **unrecognized** `sessionDurability` is treated exactly
142
- like ephemeral: SS2.13.1 forbids inferring a durability guarantee from a value
143
- this SDK predates, and the absent-means-durable rule keys on the member being
144
- *missing*, not on its value being unfamiliar.
145
-
146
- **Report defects here, not in the adapter.** A fold rule the core gets wrong
147
- is a #14990 bug; a fixture the fold cannot consume is a #210 fixture request.
148
- Neither is ever patched locally in `@muse-code/acp` (spec Sibling lanes).
149
-
150
- ## What is here (slices 1 and 2, and slice 3 in full)
151
-
152
- - `src/fingerprint.ts` — the schema staleness anchor. `EXPECTED_SCHEMA_
153
- FINGERPRINT` is test-bound to `schema/msp/stable/manifest.json`, so a schema
154
- advance that forgets the SDK reds this lane. **A red fingerprint means
155
- "re-pin after a schema advance", not "the SDK is broken"** — the failure
156
- message says so.
157
- - `src/fold/item-store.ts` — the item half of the SS4 fold: upsert-by-revision
158
- (replace iff strictly higher) and per-field delta accumulation whose
159
- concatenation equals the final committed value.
160
- - `src/fold/state-store.ts` — the session-state half: replace-wholesale,
161
- cursor-ordered, latest-wins; an explicit `null` clears and is a fact.
162
- - `src/pending/pending-command-set.ts` — the complete SS4.13 `PendingCommand`
163
- fold (decision record D-032): deterministic anchoring, the four retirement
164
- arms, nothing-admitted holds, queue-movement re-verification, the five
165
- snapshot-join arms with `queuedTurns` reordering, the no-snapshot reconnect
166
- rules, and the ephemeral-profile discard obligation.
167
- - `src/connection/connection.ts` — the transport-less NDJSON connection:
168
- awaited serialized writes, bounded inbound framing, request correlation,
169
- typed `data.kind` errors, server-request routing, and the UUIDv7
170
- `commandId` retry/value-identical-ack contract. A process binding supplies
171
- the duplex transport.
172
- - `src/connection/spawn.ts` — the owned Node stdio process binding. Before
173
- handshake it exposes no send method; `initialize` sends the SS1.4 sequence
174
- exactly once and returns the ready connection, negotiated capabilities,
175
- fingerprint warning (when any), stderr-forwarding seam, and the bounded
176
- close path. `MuseServeChild` captures a bounded 8 KiB / 100-line stderr
177
- tail from birth, maps every process exit through the SS2.11 table, and
178
- exposes the same owned child on the handshake and initialized connection.
179
- `close()` is the only termination surface and it is bounded: stdin EOF
180
- first so the host can drain (SS2.1.2), then `SIGTERM` and one `SIGKILL`
181
- escalation once `shutdownTimeoutMs` (default 30 s) has passed, and it
182
- resolves on the exit actually observed — so a wedged host is the crash row
183
- carrying the delivered signal, never a synthesized clean shutdown. It ends
184
- once the child's stdio closes; on POSIX the SDK spawns the host as the
185
- leader of an SDK-owned process group and the TERM/KILL stages signal that
186
- group ([#22777](https://github.com/mslsrc/tbh/issues/22777)), so a
187
- grandchild that inherited the host's stdout is ended with the host and
188
- cannot stall the close. On Windows the ladder still signals only the
189
- child — no subtree containment is claimed there (spec FR-017b).
190
- - `src/fold/session-fold.ts` — the two stores bound to the generated view
191
- types, plus the turn lifecycle and the approval/user-input view events as
192
- fold inputs. A compile-time assertion fails if a later #206 enrollment adds
193
- a view notification the fold would silently ignore.
194
- - `src/facade/session.ts` — `Session`: the fold, the pending set, per-turn
195
- event routing, and the SS2.13.3b host-death discharge.
196
- - `src/facade/gap-fill.ts` — the SS4.8 splice-fill: the live-frame buffer, the
197
- `view/page` walk bounded by progress rather than by an attempt cap, and the
198
- cursor-equality overlap discard. Only the splice-fill path is built; D-030's
199
- re-anchor alternative is the #208 lane's spec work.
200
- - `src/facade/turn-handle.ts` — `TurnHandle`: the SS3.1.4 turn-wait and the
201
- fold-backed `items()`/`deltas()` iterators.
202
- - `src/facade/host-death.ts` — reading `sessionDurability` off the handshake
203
- (SS2.13.1) and classifying an exit as abnormal (SS2.11).
204
- - `test/helpers/tolerance-corpus-runner.ts` — #210's workspace-only TEST-008
205
- runner. It discovers the three `sdk-tolerance` manifests, feeds item events
206
- through `ItemStore<Item>`, and preserves every notification for lossless
207
- tolerance assertions. It does not duplicate #14990 T019's `SessionFold`.
208
-
209
- ## `qa/` — the `--area sdk` black-box QA driver
210
-
211
- `qa/` is **not part of the shipped facade**. It is a QA driver (issue #22764,
212
- spec 14990 Scenario 6) that plays an external integrator: it reaches
213
- `@muse-code/sdk` only through `src/index.ts`, spawns the real `tbh serve` binary
214
- over MSP stdio, and tees every wire byte so each finding can be stated as
215
- "public API said X, wire said Y". A finding without both halves is refused at
216
- construction, and the driver never files anything — the auto-qa procedure
217
- (`specs/2159-auto-qa-skill`, `--area sdk`) does that.
218
-
219
- ```sh
220
- cd projects/tbh
221
- CARGO_TARGET_DIR=$(scripts/probe-env.sh --print) cargo build -p tbh-cli --bin tbh
222
- export MUSE_QA_SDK_BIN=$CARGO_TARGET_DIR/debug/tbh
223
- 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
+ }));
224
76
  ```
225
77
 
226
- Without `MUSE_QA_SDK_BIN` (or a `tbh` in `target/debug`) the driver exits 2 and
227
- runs nothing: it never substitutes a fixture host, because a green pass against
228
- a canned transcript would prove nothing about the product. For the same reason
229
- its real-binary contract arm reports a loud non-pass rather than a silent skip —
230
- building `tbh` is a multi-minute Rust build that does not belong in this Node
231
- lane, so CI runs the rest and the QA procedure, which always has a binary,
232
- carries that coverage.
233
-
234
- Every finding also carries a **facade-vs-binary** component decided by replaying
235
- the captured host frames into a fresh SDK with no binary present. `facade` is a
236
- bug in this package; `binary` is a bug in `tbh`.
237
-
238
- ## What is not here yet, and what it waits on
239
-
240
- No gap below waits on a wire shape any more — #24021 enrolled the last one,
241
- `view/gap` — and the facade itself is complete: `MuseClient.spawn`, the two
242
- session verbs returning a `Session`, `sendUserTurn`, and
243
- `session.onApproval`'s idempotent `approval/decide` landed with #23980 against
244
- the #22946 command-plane enrollment, and the SS4.8 in-iterator splice-fill
245
- landed with T032 against the #24021 one. The condition
246
- and the command that re-derives what remains live once, in
247
- `specs/14990-muse-sdk/tasks.md` under "The slice-3 blocker" — INV-001 holds
248
- with no exception, so a shape the generated layer lacks is a #206 enrollment
249
- request, never a local interface.
250
-
251
- | Missing | Waits on |
252
- | --- | --- |
253
- | 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. |
254
- | 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. |
255
- | 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. |
256
-
257
- ## 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.
258
81
 
259
- The concrete item/event payload types are generated, not written here
260
- (INV-001). The stores were built while the session-view plane was still being
261
- enrolled, so they state only the *algebraic precondition* each rule needs —
262
- an item has an identity and a revision — and take the payload as a type
263
- parameter. #14953 landed 2026-08-13, and `SessionFold` now binds those
264
- parameters to `@muse-code/msp`'s types with no change to the fold logic and no
265
- protocol shape ever restated locally.
82
+ ## Documentation
266
83
 
267
- The same discipline is why `ItemStore.markEphemeralHostDeath` asks its caller
268
- for an `isInProgress` probe instead of reading `item.status` itself: the store
269
- stays wire-shape-blind, and `src/facade/host-death.ts` supplies the probe
270
- 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>
@@ -8,7 +8,7 @@
8
8
  * stdout's encoding before implementing this interface — is one
9
9
  * well-behaved transport, not the general guarantee.
10
10
  */
11
- import type { ErrorKind, ErrorObject, Notification, Request, RequestId } from "@muse-code/msp";
11
+ import type { ErrorKind, ErrorObject, Notification, Request, RequestId } from "../msp.js";
12
12
  /**
13
13
  * The two-way text stream a `Connection` speaks MSP over.
14
14
  *
@@ -1,6 +1,6 @@
1
1
  /** Node stdio binding and type-state handshake for the MSP connection. */
2
2
  import type { ChildProcessWithoutNullStreams } from "node:child_process";
3
- import type { InitializeParams, InitializeResult } from "@muse-code/msp";
3
+ import type { InitializeParams, InitializeResult } from "../msp.js";
4
4
  import { Connection } from "./connection.js";
5
5
  import type { ConnectionOptions, DuplexTransport, NotificationHandler, ProtocolErrorHandler, ServerRequestHandler } from "./connection.js";
6
6
  import type { FingerprintWarning } from "../fingerprint.js";
@@ -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 "@muse-code/msp";
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" });
@@ -39,17 +39,16 @@ 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
41
  import { Session } from "./session.js";
42
- import type { InitializeParams, InitializeResult, SessionResumeParams, SessionStartParams } from "@muse-code/msp";
42
+ import type { InitializeParams, InitializeResult, SessionResumeParams, SessionStartParams } from "../msp.js";
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.
@@ -12,7 +12,7 @@
12
12
  * The stores stay wire-shape-blind (INV-001): the `Item` probe lives here,
13
13
  * where it is checked against the GENERATED type.
14
14
  */
15
- import type { InitializeResult, Item } from "@muse-code/msp";
15
+ import type { InitializeResult, Item } from "../msp.js";
16
16
  import type { ExitClassification } from "../connection/spawn.js";
17
17
  import type { TerminalUnknownItemAnnotation } from "../fold/item-store.js";
18
18
  import type { PendingRetirement } from "../pending/pending-command-set.js";
@@ -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 "@muse-code/msp";
33
+ import type { SessionResumeResult, SessionStartResult } from "../msp.js";
34
34
  /**
35
35
  * Which verb opened this session, and what it answered.
36
36
  *