@muse-code/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +270 -0
- package/dist/src/connection/connection.d.ts +128 -0
- package/dist/src/connection/connection.js +548 -0
- package/dist/src/connection/spawn.d.ts +161 -0
- package/dist/src/connection/spawn.js +462 -0
- package/dist/src/errors.d.ts +54 -0
- package/dist/src/errors.js +51 -0
- package/dist/src/facade/approval.d.ts +76 -0
- package/dist/src/facade/approval.js +165 -0
- package/dist/src/facade/client.d.ts +153 -0
- package/dist/src/facade/client.js +300 -0
- package/dist/src/facade/discarded.d.ts +36 -0
- package/dist/src/facade/discarded.js +36 -0
- package/dist/src/facade/gap-fill.d.ts +80 -0
- package/dist/src/facade/gap-fill.js +375 -0
- package/dist/src/facade/host-death.d.ts +139 -0
- package/dist/src/facade/host-death.js +96 -0
- package/dist/src/facade/session.d.ts +309 -0
- package/dist/src/facade/session.js +639 -0
- package/dist/src/facade/turn-handle.d.ts +156 -0
- package/dist/src/facade/turn-handle.js +271 -0
- package/dist/src/facade/turn-submit.d.ts +72 -0
- package/dist/src/facade/turn-submit.js +168 -0
- package/dist/src/fingerprint.d.ts +37 -0
- package/dist/src/fingerprint.js +54 -0
- package/dist/src/fold/item-store.d.ts +110 -0
- package/dist/src/fold/item-store.js +169 -0
- package/dist/src/fold/session-fold.d.ts +455 -0
- package/dist/src/fold/session-fold.js +399 -0
- package/dist/src/fold/state-store.d.ts +68 -0
- package/dist/src/fold/state-store.js +89 -0
- package/dist/src/index.d.ts +56 -0
- package/dist/src/index.js +52 -0
- package/dist/src/pending/pending-command-set.d.ts +361 -0
- package/dist/src/pending/pending-command-set.js +468 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
# `@muse-code/sdk`
|
|
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.
|
|
9
|
+
|
|
10
|
+
**Nothing is published to npm** before 1.0 (tdd D-013).
|
|
11
|
+
|
|
12
|
+
## The loop
|
|
13
|
+
|
|
14
|
+
```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
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
CI runs exactly this in the non-required, path-filtered `tbh-muse-sdk-ts`
|
|
22
|
+
workflow.
|
|
23
|
+
|
|
24
|
+
## Consuming this package (#211 and #210)
|
|
25
|
+
|
|
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.
|
|
28
|
+
|
|
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:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { MuseClient } from "@muse-code/sdk";
|
|
92
|
+
|
|
93
|
+
const client = await MuseClient.spawn({
|
|
94
|
+
museBin: "muse",
|
|
95
|
+
args: ["serve"], // spawn passes args through verbatim; a bare `muse` is the TUI
|
|
96
|
+
clientInfo: { name: "dm", version: "1.0.0" },
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const session = await client.startSession({ workspaceRoot });
|
|
100
|
+
// or: await client.resumeSession({ sessionId, cursor })
|
|
101
|
+
session.opening; // the typed wire result, by verb
|
|
102
|
+
|
|
103
|
+
const turn = await session.sendUserTurn({ input: [{ type: "text", text }] });
|
|
104
|
+
for await (const item of turn.items()) render(item);
|
|
105
|
+
await turn.completed;
|
|
106
|
+
|
|
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
|
|
111
|
+
```
|
|
112
|
+
|
|
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.
|
|
124
|
+
|
|
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:
|
|
129
|
+
|
|
130
|
+
```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
|
|
224
|
+
```
|
|
225
|
+
|
|
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
|
|
258
|
+
|
|
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.
|
|
266
|
+
|
|
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`.
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Duplex-agnostic MSP NDJSON connection (spec 14990 FR-012/014/015/016).
|
|
3
|
+
*
|
|
4
|
+
* The transport supplies decoded UTF-8 chunks. Chunks may be empty and may
|
|
5
|
+
* split anywhere — including mid surrogate pair: the byte accounting below
|
|
6
|
+
* reconciles split pairs (FR-012(a)), so transports need not align chunks
|
|
7
|
+
* to character boundaries. The Node child-process binding — which sets
|
|
8
|
+
* stdout's encoding before implementing this interface — is one
|
|
9
|
+
* well-behaved transport, not the general guarantee.
|
|
10
|
+
*/
|
|
11
|
+
import type { ErrorKind, ErrorObject, Notification, Request, RequestId } from "@muse-code/msp";
|
|
12
|
+
/**
|
|
13
|
+
* The two-way text stream a `Connection` speaks MSP over.
|
|
14
|
+
*
|
|
15
|
+
* Implement it to run the protocol over any duplex channel: yield decoded
|
|
16
|
+
* UTF-8 chunks on `incoming` and accept outgoing frames through `write`.
|
|
17
|
+
* Chunks may be empty and may split anywhere — even mid surrogate pair — the
|
|
18
|
+
* connection reassembles them. If your transport decodes bytes itself, use a
|
|
19
|
+
* streaming decoder: a multi-byte character split across two byte chunks and
|
|
20
|
+
* decoded separately becomes a replacement character before the connection
|
|
21
|
+
* ever sees it. The SDK's spawned child-process stdio binding sets the stream
|
|
22
|
+
* encoding, so it is safe, and is one ready-made implementation.
|
|
23
|
+
*/
|
|
24
|
+
export interface DuplexTransport {
|
|
25
|
+
readonly incoming: AsyncIterable<string>;
|
|
26
|
+
write(chunk: string): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* `flushed` settles once every frame the connection had accepted when
|
|
29
|
+
* `close()` was called has been HANDED to `write()` — submission, not
|
|
30
|
+
* completion. A process-owning transport waits for it inside its own
|
|
31
|
+
* shutdown budget before ending the peer's input, so a frame still queued
|
|
32
|
+
* on a microtask is not dropped; it is never GATED by it, because
|
|
33
|
+
* completion is exactly what a wedged peer withholds. Optional and
|
|
34
|
+
* additive: a transport that ignores it behaves as before.
|
|
35
|
+
*/
|
|
36
|
+
close?(flushed?: Promise<void>): void | Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Module-private friend seam (never on the package barrel, like spawn.ts's
|
|
40
|
+
* `ownedTransport`): the submission tail a process-owning transport adopts as
|
|
41
|
+
* its DEFAULT `flushed`, so a close routed around this class — e.g. the
|
|
42
|
+
* public `child.close()` — gets the same step 0 (PR #22819 round 4).
|
|
43
|
+
*/
|
|
44
|
+
export declare const submissionTail: unique symbol;
|
|
45
|
+
/**
|
|
46
|
+
* Tuning knobs for a `Connection`. Every option is optional: the defaults
|
|
47
|
+
* suit a spawned host, so most applications never pass this at all.
|
|
48
|
+
*/
|
|
49
|
+
export interface ConnectionOptions {
|
|
50
|
+
readonly frameLimitBytes?: number;
|
|
51
|
+
readonly mintCommandId?: () => string;
|
|
52
|
+
/** Injectable for deterministic transcript clients; values must be unique in flight. */
|
|
53
|
+
readonly mintRequestId?: () => RequestId;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Per-command overrides for `Connection.command`: pin a command id so a
|
|
57
|
+
* reconnect can replay the same logical command, cap the attempt count, or
|
|
58
|
+
* supply your own retry delay.
|
|
59
|
+
*/
|
|
60
|
+
export interface CommandOptions {
|
|
61
|
+
/** Reuse this id for a reconnect/replay of the same logical command. */
|
|
62
|
+
readonly commandId?: string;
|
|
63
|
+
/** Total attempts, including the first. */
|
|
64
|
+
readonly maxAttempts?: number;
|
|
65
|
+
/** Injectable so deterministic tests do not sleep. */
|
|
66
|
+
readonly retryDelay?: (attempt: number, error: MspError) => Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
/** Handles one server-initiated request and resolves with the result to send back. */
|
|
69
|
+
export type ServerRequestHandler = (request: Request) => Promise<Record<string, unknown>>;
|
|
70
|
+
/** Receives every server notification, in arrival order. */
|
|
71
|
+
export type NotificationHandler = (notification: Notification) => void;
|
|
72
|
+
/** Receives each framing or correlation violation the connection detects on its inbound stream. */
|
|
73
|
+
export type ProtocolErrorHandler = (error: ProtocolError) => void;
|
|
74
|
+
/** The one typed error family consumers branch on (INV-012). */
|
|
75
|
+
export declare class MspError extends Error {
|
|
76
|
+
readonly code: number;
|
|
77
|
+
readonly kind: ErrorKind;
|
|
78
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
79
|
+
readonly retryable: boolean | undefined;
|
|
80
|
+
constructor(error: ErrorObject);
|
|
81
|
+
}
|
|
82
|
+
/** A local framing/correlation violation, never a server-authored MSP error. */
|
|
83
|
+
export declare class ProtocolError extends Error {
|
|
84
|
+
readonly line: string | undefined;
|
|
85
|
+
constructor(message: string, line?: string);
|
|
86
|
+
}
|
|
87
|
+
/** Create the SDK-owned UUIDv7 command-id source for a connection/client. */
|
|
88
|
+
export declare function createUuidV7Mint(): () => string;
|
|
89
|
+
/**
|
|
90
|
+
* One MSP connection over newline-delimited JSON.
|
|
91
|
+
*
|
|
92
|
+
* The connection sends your requests and commands, correlates their
|
|
93
|
+
* responses, enforces the frame-size limit, and hands inbound notifications
|
|
94
|
+
* and server requests to the handlers you register. It is transport-agnostic:
|
|
95
|
+
* pair it with any `DuplexTransport`. Most applications never build one
|
|
96
|
+
* directly — `MuseClient.spawn` or `spawnMspConnection` does it for you;
|
|
97
|
+
* reach for a bare `Connection` when you need the raw notification feed or
|
|
98
|
+
* your own transport.
|
|
99
|
+
*/
|
|
100
|
+
export declare class Connection {
|
|
101
|
+
#private;
|
|
102
|
+
constructor(transport: DuplexTransport, options?: ConnectionOptions);
|
|
103
|
+
get closed(): Promise<void>;
|
|
104
|
+
/** See {@link submissionTail}. */
|
|
105
|
+
[submissionTail](): Promise<void>;
|
|
106
|
+
request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
107
|
+
/**
|
|
108
|
+
* Take one id from THIS connection's single `commandId` minter (INV-013).
|
|
109
|
+
*
|
|
110
|
+
* Exposed for the callers that need the id BEFORE the ack: `sendUserTurn`
|
|
111
|
+
* records its optimistic SS4.13 entry under it, and an entry created only on
|
|
112
|
+
* the ack is invisible for exactly the window it exists to cover. The
|
|
113
|
+
* alternative was a facade-side mint, which is the second minter INV-013
|
|
114
|
+
* forbids — delegating here keeps the single-minter property intact and
|
|
115
|
+
* preserves the injected `mintCommandId` seam for deterministic transcripts.
|
|
116
|
+
*
|
|
117
|
+
* Pair it with `command(..., { commandId })`, which reuses the id instead of
|
|
118
|
+
* minting a second one.
|
|
119
|
+
*/
|
|
120
|
+
mintCommandId(): string;
|
|
121
|
+
notify(method: string, params?: Record<string, unknown>): void;
|
|
122
|
+
onServerRequest(handler: ServerRequestHandler): void;
|
|
123
|
+
onNotification(handler: NotificationHandler): void;
|
|
124
|
+
onProtocolError(handler: ProtocolErrorHandler): void;
|
|
125
|
+
flush(): Promise<void>;
|
|
126
|
+
command(method: string, params: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>;
|
|
127
|
+
close(): Promise<void>;
|
|
128
|
+
}
|