@muse-code/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +270 -0
  3. package/dist/src/connection/connection.d.ts +128 -0
  4. package/dist/src/connection/connection.js +548 -0
  5. package/dist/src/connection/spawn.d.ts +161 -0
  6. package/dist/src/connection/spawn.js +462 -0
  7. package/dist/src/errors.d.ts +54 -0
  8. package/dist/src/errors.js +51 -0
  9. package/dist/src/facade/approval.d.ts +76 -0
  10. package/dist/src/facade/approval.js +165 -0
  11. package/dist/src/facade/client.d.ts +153 -0
  12. package/dist/src/facade/client.js +300 -0
  13. package/dist/src/facade/discarded.d.ts +36 -0
  14. package/dist/src/facade/discarded.js +36 -0
  15. package/dist/src/facade/gap-fill.d.ts +80 -0
  16. package/dist/src/facade/gap-fill.js +375 -0
  17. package/dist/src/facade/host-death.d.ts +139 -0
  18. package/dist/src/facade/host-death.js +96 -0
  19. package/dist/src/facade/session.d.ts +309 -0
  20. package/dist/src/facade/session.js +639 -0
  21. package/dist/src/facade/turn-handle.d.ts +156 -0
  22. package/dist/src/facade/turn-handle.js +271 -0
  23. package/dist/src/facade/turn-submit.d.ts +72 -0
  24. package/dist/src/facade/turn-submit.js +168 -0
  25. package/dist/src/fingerprint.d.ts +37 -0
  26. package/dist/src/fingerprint.js +54 -0
  27. package/dist/src/fold/item-store.d.ts +110 -0
  28. package/dist/src/fold/item-store.js +169 -0
  29. package/dist/src/fold/session-fold.d.ts +455 -0
  30. package/dist/src/fold/session-fold.js +399 -0
  31. package/dist/src/fold/state-store.d.ts +68 -0
  32. package/dist/src/fold/state-store.js +89 -0
  33. package/dist/src/index.d.ts +56 -0
  34. package/dist/src/index.js +52 -0
  35. package/dist/src/pending/pending-command-set.d.ts +361 -0
  36. package/dist/src/pending/pending-command-set.js +468 -0
  37. package/package.json +39 -0
@@ -0,0 +1,300 @@
1
+ /**
2
+ * `MuseClient` — the SS7.1 facade's session-opening half (FR-018, T030).
3
+ *
4
+ * It turns the two v1 session verbs into correctly-shaped `session/start` /
5
+ * `session/resume` params and hands back a WIRED `Session`. It frames nothing
6
+ * and mints nothing: `Connection.command()` stamps the `commandId` from the
7
+ * single injected mint, so INV-013's single-minter property is preserved by
8
+ * DELEGATION rather than re-implemented here.
9
+ *
10
+ * IT OWNS TWO FACTS NO OTHER LAYER HOLDS, and that is why obligations (b) and
11
+ * (c) of T030 live here rather than on `Session`:
12
+ *
13
+ * - WHETHER A CLOSE WAS OURS. `Connection` is duplex-generic; a transport
14
+ * cannot tell a peer's hang-up from its own shutdown. SS2.13.3b counts
15
+ * "process exit **or transport EOF**" as a death, so somebody has to know
16
+ * the difference, and only the layer that owns `close()` does.
17
+ * - WHAT AN EARLIER DEATH DISCARDED. `DiscardedSessions` is client-scoped, so
18
+ * a `commandId` refusal and a withheld reattach survive the `Session` object
19
+ * that died — which is exactly what "do not replay the SESSION's commandIds"
20
+ * requires of a client that then opens a new session.
21
+ *
22
+ * OPTIONAL MEANS OMITTED, NEVER `null` (tdd SS1.2). Every member this module
23
+ * can leave unset is optional-non-nullable in the generated params, so an
24
+ * unset member is dropped from the frame rather than nulled. The guards below
25
+ * are LOOSE (`!= null`) on purpose: the types only bind strict TypeScript
26
+ * consumers, and a plain-JS caller reaching the built `dist` can pass an
27
+ * explicit `null` that a `!== undefined` guard would forward verbatim. `false
28
+ * != null` is true, so `excludeItems: false` still serializes.
29
+ *
30
+ * The params and the caller options are both COMPOSED from the generated
31
+ * types rather than restated (INV-001: narrow and compose, never restate).
32
+ * Composition alone does NOT stop drift, though: the guard chains below are
33
+ * hand-listed, so a regenerated member would be settable by a caller and then
34
+ * silently dropped on the way to the wire. The `AssertNever` pins next to each
35
+ * chain close that gap — add a member upstream and the BUILD fails here until
36
+ * it is forwarded (or explicitly allow-listed as unforwardable).
37
+ */
38
+ import { spawnMspConnection } from "../connection/spawn.js";
39
+ import { MuseSessionDiscardedError } from "../errors.js";
40
+ import { DiscardedSessions } from "./discarded.js";
41
+ import { isAbnormalHostDeath, readSessionDurability } from "./host-death.js";
42
+ import { Session } from "./session.js";
43
+ /**
44
+ * Every `StartParams` member `startSession` forwards. `config` is allow-listed
45
+ * as intentionally unforwardable: [`SessionConfig`] declares no members yet.
46
+ */
47
+ const START_FORWARDED = [
48
+ "approvalMode",
49
+ "providerId",
50
+ "sessionId",
51
+ "workspaceRoot",
52
+ "modelId",
53
+ ];
54
+ /** Every `ResumeParams` member `resumeSession` forwards. */
55
+ const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history"];
56
+ /**
57
+ * Your entry point to the SDK.
58
+ *
59
+ * Spawn a host with `MuseClient.spawn`, then open conversations with
60
+ * `startSession` or `resumeSession`. The client owns the connection: it
61
+ * routes every server event to the session it belongs to and reports a host
62
+ * death to all of them. Call `close` to shut the host down cleanly.
63
+ */
64
+ export class MuseClient {
65
+ #connection;
66
+ #durability;
67
+ #discarded;
68
+ /** Sessions this client opened, so one death notification reaches them all. */
69
+ #sessions = new Set();
70
+ /** The spawned host, when `spawn` built this client. */
71
+ #child;
72
+ #initializeResult;
73
+ /**
74
+ * Set by `close()` BEFORE the connection is torn down.
75
+ *
76
+ * This flag is the entire discriminator for obligation (b): the same
77
+ * transport EOF is an orderly SS2.1.2 shutdown when we caused it and an
78
+ * abnormal death when we did not, and nothing below this layer can tell.
79
+ */
80
+ #closing = false;
81
+ /** Latched by an abnormal EOF, so a later `resumeSession` can be withheld. */
82
+ #hostDied = false;
83
+ constructor(connection, options) {
84
+ this.#connection = connection;
85
+ this.#durability = options.durability;
86
+ // Client-owned, never injected: SS2.13.3b is a one-client obligation and
87
+ // no current consumer spans two clients over one host lineage, so a
88
+ // sharing knob would be declared-ahead surface (Constitution XI).
89
+ this.#discarded = new DiscardedSessions();
90
+ this.#child = options.host?.child;
91
+ this.#initializeResult = options.host?.initializeResult;
92
+ // THE ONE INBOUND PUMP (FR-018/FR-019). `Session.apply` is the only event
93
+ // entry point and `#connection` is private, so without this a spawn-built
94
+ // consumer has no way to hear a single view frame: every turn wait hangs
95
+ // (SS3.1.4) and `onApproval` can never fire. `Connection.onNotification`
96
+ // holds ONE handler — this client claims it, which is part of what
97
+ // "MuseClient owns the connection" means; a consumer that needs the raw
98
+ // feed builds around a bare `Connection` and `Session` instead.
99
+ this.#connection.onNotification((notification) => this.#route(notification));
100
+ // Registered at construction, not at the first session: an EOF can land
101
+ // before any session exists, and the flag has to be read at that moment.
102
+ void this.#connection.closed.then(() => this.#transportClosed());
103
+ }
104
+ /**
105
+ * Deliver one view notification to the session(s) it names.
106
+ *
107
+ * A frame naming NO session is dropped here rather than fed to every
108
+ * session: `Session.apply` already tolerates unknown methods, but only the
109
+ * frames that name a `sessionId` have an owner to route to. A frame naming
110
+ * an UNKNOWN session is dropped for the same reason — routing it anywhere
111
+ * would trip the foreign-frame throw on a session it does not belong to.
112
+ */
113
+ #route(notification) {
114
+ const named = notification.params?.sessionId;
115
+ if (typeof named !== "string")
116
+ return;
117
+ for (const session of this.#sessions) {
118
+ if (session.sessionId === named)
119
+ session.apply(notification);
120
+ }
121
+ }
122
+ /**
123
+ * Spawn an owned host, run the SS1.4 handshake, and hand back a client whose
124
+ * durability profile came from that handshake (FR-018).
125
+ *
126
+ * The profile is READ rather than asked of the caller, which is the whole
127
+ * reason this factory exists beside the bare constructor: SS2.13.1 makes the
128
+ * absent/unrecognized distinction load-bearing, and a caller re-deriving it
129
+ * by hand is a caller that can get it wrong.
130
+ */
131
+ static async spawn(options) {
132
+ const handshake = spawnMspConnection({
133
+ command: options.museBin,
134
+ ...(options.args === undefined ? {} : { args: options.args }),
135
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
136
+ ...(options.env === undefined ? {} : { env: options.env }),
137
+ ...(options.onStderr === undefined ? {} : { onStderr: options.onStderr }),
138
+ ...(options.shutdownTimeoutMs === undefined
139
+ ? {}
140
+ : { shutdownTimeoutMs: options.shutdownTimeoutMs }),
141
+ });
142
+ let spawned;
143
+ try {
144
+ spawned = await handshake.initialize({
145
+ clientInfo: options.clientInfo,
146
+ ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }),
147
+ });
148
+ }
149
+ catch (error) {
150
+ // A failed handshake must not leak the process it already spawned.
151
+ await handshake.close().catch(() => undefined);
152
+ throw error;
153
+ }
154
+ return new MuseClient(spawned.connection, {
155
+ durability: readSessionDurability(spawned.initializeResult),
156
+ host: spawned,
157
+ });
158
+ }
159
+ /**
160
+ * The handshake result, when this client was built by `spawn`.
161
+ *
162
+ * A plain `Error`, not a typed one: reading this off a client that was not
163
+ * built by `spawn` is API misuse, not a protocol STATE an embedder branches
164
+ * on — a typed class here would send the SS2.13.3b recovery path chasing a
165
+ * host death that never happened.
166
+ */
167
+ get initializeResult() {
168
+ if (this.#initializeResult === undefined) {
169
+ throw new Error("initializeResult is only available on a client built by MuseClient.spawn");
170
+ }
171
+ return this.#initializeResult;
172
+ }
173
+ /** The host's SS2.11 exit row, when this client was built by `spawn`. */
174
+ get exit() {
175
+ if (this.#child === undefined) {
176
+ // Plain `Error` for the same reason as `initializeResult`: API misuse,
177
+ // not a protocol state.
178
+ throw new Error("exit is only available on a client built by MuseClient.spawn");
179
+ }
180
+ return this.#child.exit;
181
+ }
182
+ /** The durability profile every session this client opens inherits. */
183
+ get durability() {
184
+ return this.#durability;
185
+ }
186
+ /** Open a new root session (tdd SS2.5.1). */
187
+ async startSession(options = {}) {
188
+ const params = {};
189
+ if (options.approvalMode != null)
190
+ params.approvalMode = options.approvalMode;
191
+ if (options.providerId != null)
192
+ params.providerId = options.providerId;
193
+ if (options.sessionId != null)
194
+ params.sessionId = options.sessionId;
195
+ if (options.workspaceRoot != null)
196
+ params.workspaceRoot = options.workspaceRoot;
197
+ if (options.modelId != null)
198
+ params.modelId = options.modelId;
199
+ const raw = await this.#connection.command("session/start", params);
200
+ const result = raw;
201
+ // Keyed by the id the SERVER named, never the one the caller asked for:
202
+ // `sessionId` is a REQUEST on start, and a session keyed by a hopeful id
203
+ // would reject every one of its own events as foreign.
204
+ return this.#openSession(result.session.sessionId, {
205
+ result,
206
+ verb: "session/start",
207
+ });
208
+ }
209
+ /**
210
+ * Load an existing session and subscribe this connection to its view
211
+ * (tdd SS2.5.2).
212
+ *
213
+ * WITHHELD after an ephemeral host death (SS2.13.3b clause 2, "do not attempt
214
+ * to reattach"), and refused on THIS side of the transport: a reattach
215
+ * attempt that reaches the wire has already violated the clause, whatever the
216
+ * server answers.
217
+ */
218
+ async resumeSession(options) {
219
+ this.#assertReattachAllowed(options.sessionId);
220
+ const params = { sessionId: options.sessionId };
221
+ if (options.cursor != null)
222
+ params.cursor = options.cursor;
223
+ if (options.excludeItems != null)
224
+ params.excludeItems = options.excludeItems;
225
+ if (options.history != null)
226
+ params.history = options.history;
227
+ const raw = await this.#connection.command("session/resume", params);
228
+ const result = raw;
229
+ return this.#openSession(result.session.sessionId, {
230
+ result,
231
+ verb: "session/resume",
232
+ });
233
+ }
234
+ /**
235
+ * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
236
+ * is not reported to your sessions as a host death.
237
+ *
238
+ * The EOF this close produces is NOT a death, which is what `#closing`
239
+ * records.
240
+ *
241
+ * `#closing` covers only the EOF; it must not swallow the EXIT ROW. When the
242
+ * host ignores stdin EOF, `#child.close()` escalates to SIGTERM/SIGKILL and
243
+ * the exit classifies as a crash — an abnormal death under SS2.13.3b no
244
+ * matter who started the close, and one no transport event will ever report
245
+ * here because `#closing` already claimed the EOF. So the classification the
246
+ * close itself returns is forwarded to every session: `hostExited` answers
247
+ * `notADeath` for `cleanShutdown`, keeping the orderly arm inert.
248
+ */
249
+ async close() {
250
+ this.#closing = true;
251
+ if (this.#child !== undefined) {
252
+ const exit = await this.#child.close();
253
+ if (isAbnormalHostDeath(exit)) {
254
+ for (const session of this.#sessions)
255
+ session.hostExited(exit);
256
+ }
257
+ return;
258
+ }
259
+ await this.#connection.close();
260
+ }
261
+ #openSession(sessionId, opening) {
262
+ const session = new Session({
263
+ connection: this.#connection,
264
+ discarded: this.#discarded,
265
+ durability: this.#durability,
266
+ opening,
267
+ sessionId,
268
+ });
269
+ this.#sessions.add(session);
270
+ return session;
271
+ }
272
+ #assertReattachAllowed(sessionId) {
273
+ // Two facts, both recorded by an ephemeral discharge: THIS session was
274
+ // discarded, or this client's own ephemeral host died (in which case there
275
+ // is nothing on the other end to reattach TO, whatever id is asked for).
276
+ if (this.#discarded.sessionIds.has(sessionId)) {
277
+ throw new MuseSessionDiscardedError(`session ${sessionId} was discarded after an ephemeral host death; it cannot be resumed`);
278
+ }
279
+ if (this.#hostDied && !this.#survivesHostDeath()) {
280
+ throw new MuseSessionDiscardedError("this client's ephemeral host died; SS2.13.3b forbids reattaching to it");
281
+ }
282
+ }
283
+ #survivesHostDeath() {
284
+ return this.#durability.kind === "durable";
285
+ }
286
+ /**
287
+ * The transport reached EOF. If this client did not cause it, that is
288
+ * SS2.13.3b's second death notification (T030 obligation b) and every session
289
+ * this client opened discharges through the SAME `Session.hostExited` path
290
+ * the process exit uses — including its latch, so whichever notification
291
+ * arrives second replays the first one's report instead of a half delta.
292
+ */
293
+ #transportClosed() {
294
+ if (this.#closing)
295
+ return;
296
+ this.#hostDied = true;
297
+ for (const session of this.#sessions)
298
+ session.hostExited({ kind: "transportEof" });
299
+ }
300
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What an ephemeral host death discarded, remembered ACROSS the sessions one
3
+ * client opened (spec 14990 T030 obligation (c); tdd SS2.13.3b).
4
+ *
5
+ * SS2.13.3b's five-clause MUST includes "do not attempt to reattach" and "do
6
+ * not replay the session's `commandId`s". Both are statements about what the
7
+ * CLIENT does next, and "next" outlives the session object that died:
8
+ *
9
+ * - `PendingCommandSet` already refuses a replay of an id IT discarded, but
10
+ * its memory is per-instance, so a FRESH `Session` — the natural thing to
11
+ * build after a host dies — knew nothing and would replay those ids at the
12
+ * new host. That is the exactly-once violation the clause exists to prevent,
13
+ * and it is why T030b's own arm could only name the gap;
14
+ * - nothing at all held the discarded `sessionId`, so `resumeSession` had no
15
+ * fact to withhold on.
16
+ *
17
+ * This is client state, never a wire shape and never durable (INV-007): it
18
+ * lives exactly as long as the `MuseClient` that owns it. It is deliberately
19
+ * NOT a module-global — two clients in one process are two independent trust
20
+ * boundaries, and a process-wide set would let one client's dead host silence
21
+ * another's live one.
22
+ */
23
+ /**
24
+ * The two sets, exposed directly rather than behind add/has pairs.
25
+ *
26
+ * `PendingCommandSet` takes the `commandIds` set BY REFERENCE and writes to it
27
+ * from `discardEphemeral()`, so a wrapper would have to re-expose a mutable
28
+ * seam anyway; a `Set<string>` is the honest shape for one, and it is already
29
+ * the shape that class used internally.
30
+ */
31
+ export declare class DiscardedSessions {
32
+ /** `commandId`s an ephemeral discharge retired. Never replayed again. */
33
+ readonly commandIds: Set<string>;
34
+ /** `sessionId`s whose ephemeral host died. Never reattached. */
35
+ readonly sessionIds: Set<string>;
36
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What an ephemeral host death discarded, remembered ACROSS the sessions one
3
+ * client opened (spec 14990 T030 obligation (c); tdd SS2.13.3b).
4
+ *
5
+ * SS2.13.3b's five-clause MUST includes "do not attempt to reattach" and "do
6
+ * not replay the session's `commandId`s". Both are statements about what the
7
+ * CLIENT does next, and "next" outlives the session object that died:
8
+ *
9
+ * - `PendingCommandSet` already refuses a replay of an id IT discarded, but
10
+ * its memory is per-instance, so a FRESH `Session` — the natural thing to
11
+ * build after a host dies — knew nothing and would replay those ids at the
12
+ * new host. That is the exactly-once violation the clause exists to prevent,
13
+ * and it is why T030b's own arm could only name the gap;
14
+ * - nothing at all held the discarded `sessionId`, so `resumeSession` had no
15
+ * fact to withhold on.
16
+ *
17
+ * This is client state, never a wire shape and never durable (INV-007): it
18
+ * lives exactly as long as the `MuseClient` that owns it. It is deliberately
19
+ * NOT a module-global — two clients in one process are two independent trust
20
+ * boundaries, and a process-wide set would let one client's dead host silence
21
+ * another's live one.
22
+ */
23
+ /**
24
+ * The two sets, exposed directly rather than behind add/has pairs.
25
+ *
26
+ * `PendingCommandSet` takes the `commandIds` set BY REFERENCE and writes to it
27
+ * from `discardEphemeral()`, so a wrapper would have to re-expose a mutable
28
+ * seam anyway; a `Set<string>` is the honest shape for one, and it is already
29
+ * the shape that class used internally.
30
+ */
31
+ export class DiscardedSessions {
32
+ /** `commandId`s an ephemeral discharge retired. Never replayed again. */
33
+ commandIds = new Set();
34
+ /** `sessionId`s whose ephemeral host died. Never reattached. */
35
+ sessionIds = new Set();
36
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * SS4.8 gap recovery by splice-fill (spec 14990 FR-020 / T032, tdd SS4.8).
3
+ *
4
+ * Split out of `session.ts` for the same reason `approval.ts` and
5
+ * `turn-submit.ts` were: this is a delivery-plane concern with its own buffer,
6
+ * page walk, and failure vocabulary, and `Session` was already the package's
7
+ * largest module.
8
+ *
9
+ * THE RECIPE, verbatim from tdd SS4.8 and unchanged here: buffer live events
10
+ * at cursors at or after `next` as they arrive; page forward from `after` with
11
+ * `view/page` until the walk reaches `next`; discard the paged events the
12
+ * buffer already holds; splice the buffer after the paged prefix. D-030's
13
+ * second sanctioned path (drop state and re-anchor at the latest compaction
14
+ * snapshot) is NOT built here — it is the #208 lane's spec work, and building
15
+ * both would be a second concrete path for one current use.
16
+ *
17
+ * CURSORS STAY OPAQUE (tdd SS4.1). Nothing below orders two cursors: "at or
18
+ * after `next`" is delivery ORDER, not a comparison — every live frame that
19
+ * arrives after the gap marker is, by the server's own delivery contract, at
20
+ * or after `next`. The walk stops on cursor EQUALITY with the target or on the
21
+ * server's own end-of-view, and the overlap is discarded by set membership.
22
+ */
23
+ import { MuseGapFillError } from "../errors.js";
24
+ import type { Connection } from "../connection/connection.js";
25
+ import type { SessionFold } from "../fold/session-fold.js";
26
+ import type { PendingRetirement } from "../pending/pending-command-set.js";
27
+ /** One wire frame, exactly as `Session.apply`'s wide overload accepts it. */
28
+ export interface WireFrame {
29
+ readonly method: string;
30
+ readonly params?: unknown;
31
+ }
32
+ /**
33
+ * Where a drained frame's side effects go. The filler re-feeds frames through
34
+ * `Session`'s own fold-and-route path, so the retirements and the client→server
35
+ * I/O they trigger belong to `Session`, not here.
36
+ */
37
+ export interface DrainSink<I> {
38
+ readonly retirements: PendingRetirement<I>[];
39
+ readonly tasks: Promise<readonly PendingRetirement<I>[]>[];
40
+ }
41
+ export interface GapFillerOptions<I> {
42
+ readonly sessionId: string;
43
+ /** Absent on a fold-only `Session`: there is nothing to page through. */
44
+ readonly connection: Connection | undefined;
45
+ readonly fold: SessionFold;
46
+ /** Fold and route ONE frame, collecting what it produced. */
47
+ readonly apply: (frame: WireFrame, into: DrainSink<I>) => void;
48
+ /** SS2.13.3b: a discharged session folds nothing, fill or no fill. */
49
+ readonly discarded: () => boolean;
50
+ }
51
+ /** Reported, never thrown — see {@link MuseGapFillError}. */
52
+ export type GapFillFailureHandler = (failure: MuseGapFillError) => void;
53
+ export declare class GapFiller<I> {
54
+ #private;
55
+ constructor(options: GapFillerOptions<I>);
56
+ /** While true, every live frame but the gap marker itself is held. */
57
+ get filling(): boolean;
58
+ /**
59
+ * Was this frame already applied from a page, as part of the overlap the
60
+ * splice discards? Consuming: a twin is refused exactly once.
61
+ *
62
+ * Returns the matched CURSOR rather than a boolean so the caller can report
63
+ * which event it refused without re-reading (and re-defaulting) a field this
64
+ * method already proved is there.
65
+ */
66
+ claimServedTwin(frame: WireFrame): string | undefined;
67
+ /** Observe fills that did not complete. See {@link MuseGapFillError}. */
68
+ onError(handler: GapFillFailureHandler): void;
69
+ /** Hold one live frame until the paged prefix is in. */
70
+ hold(frame: WireFrame): void;
71
+ /**
72
+ * Recover the fold's outstanding hole.
73
+ *
74
+ * Called on every `view/gap`, including one that lands mid-fill: the running
75
+ * walk reads its target from `fold.pendingGap` on each pass, so a coalesced
76
+ * hole extends the walk in flight rather than starting a second one racing
77
+ * it for the same cursor stream.
78
+ */
79
+ start(): Promise<readonly PendingRetirement<I>[]>;
80
+ }